Exemplo n.º 1
0
	MStatus StrandLengthCount::doIt(const MArgList & args) {
		std::list<MObject> targets;
		MStatus status = ArgList_GetModelObjects(args, syntax(), "-b", targets);
		if (status != MStatus::kNotFound && status != MStatus::kSuccess) {
			HMEVALUATE_RETURN_DESCRIPTION("ArgList_GetModelObjects", status);
		}

		clearResult();
		if (!targets.empty()) {
			for (std::list<MObject>::const_iterator it(targets.begin()); it != targets.end(); ++it) {
				Model::Base base(*it);
				Model::Strand strand(base);
				HPRINT("Calling with base: %s", base.getDagPath(status).fullPathName().asChar());
				appendToResult(int(m_operation.length(strand)));
			}
		} else {
			MObjectArray objects;
			HMEVALUATE_RETURN(status = Model::Base::AllSelected(objects), status);

			for (unsigned int i = 0; i < objects.length(); ++i) {
				Model::Base base(objects[i]);
				Model::Strand strand(base);
				HPRINT("Calling with base: %s", base.getDagPath(status).fullPathName().asChar());
				appendToResult(int(m_operation.length(strand)));
			}
		}

		return MStatus::kSuccess;
	}
Exemplo n.º 2
0
//======================================================================
//
// Do the command in query mode. It only does one thing, print the Stream,
// Channel, Associations, and Structure formats available.
//
MStatus exportMetadataCmd::doQuery()
{
	assert( fSerializer );
	MStatus status = MS::kSuccess;

	std::set<const adsk::Data::StreamSerializer*>::iterator sFmtIt;
	for( sFmtIt = adsk::Data::StreamSerializer::allFormats().begin();
		 sFmtIt != adsk::Data::StreamSerializer::allFormats().end(); sFmtIt++ )
	{
		const adsk::Data::StreamSerializer* fmt = *sFmtIt;
		MString fmtMsg( MStringResource::getString(kExportMetadataFormatType, status) );
		MString fmtType( "Stream" );
		MString fmtName( fmt->formatType() );
		MString msg;
		msg.format( fmtMsg, fmtType, fmtName );
		appendToResult( msg );
	}

	std::set<const adsk::Data::ChannelSerializer*>::iterator cFmtIt;
	for( cFmtIt = adsk::Data::ChannelSerializer::allFormats().begin();
		 cFmtIt != adsk::Data::ChannelSerializer::allFormats().end(); cFmtIt++ )
	{
		const adsk::Data::ChannelSerializer* fmt = *cFmtIt;
		MString fmtMsg( MStringResource::getString(kExportMetadataFormatType, status) );
		MString fmtType( "Channel" );
		MString fmtName( fmt->formatType() );
		MString msg;
		msg.format( fmtMsg, fmtType, fmtName );
		appendToResult( msg );
	}

	std::set<const adsk::Data::AssociationsSerializer*>::iterator aFmtIt;
	for( aFmtIt = adsk::Data::AssociationsSerializer::allFormats().begin();
		 aFmtIt != adsk::Data::AssociationsSerializer::allFormats().end(); aFmtIt++ )
	{
		const adsk::Data::AssociationsSerializer* fmt = *aFmtIt;
		MString fmtMsg( MStringResource::getString(kExportMetadataFormatType, status) );
		MString fmtType( "Associations" );
		MString fmtName( fmt->formatType() );
		MString msg;
		msg.format( fmtMsg, fmtType, fmtName );
		appendToResult( msg );
	}

	std::set<const adsk::Data::StructureSerializer*>::iterator fmtIt;
	for( fmtIt = adsk::Data::StructureSerializer::allFormats().begin();
		 fmtIt != adsk::Data::StructureSerializer::allFormats().end(); fmtIt++ )
	{
		const adsk::Data::StructureSerializer* fmt = *fmtIt;
		MString fmtMsg( MStringResource::getString(kExportMetadataFormatType, status) );
		MString fmtType( "Structure" );
		MString fmtName( fmt->formatType() );
		MString msg;
		msg.format( fmtMsg, fmtType, fmtName );
		appendToResult( msg );
	}

	return status;
}
Exemplo n.º 3
0
MStatus cvPos::redoIt()
{
    clearResult();
    appendToResult( point.x );
    appendToResult( point.y );
    appendToResult( point.z );

    return MS::kSuccess;
}
Exemplo n.º 4
0
MStatus iffPixel::redoIt()
{
    clearResult();
	if (useDepth) {
		appendToResult (d);
	} else {
		appendToResult( r );
		appendToResult( g );
		appendToResult( b );
		appendToResult( a );
	}

    return MS::kSuccess;
}
Exemplo n.º 5
0
bool ValueParser::parse() {
	_failed = false;
	_result.reserve(_end - _begin);
	for (; _ch != _end; ++_ch) {
		if (*_ch == '{') {
			appendToResult(_ch);

			++_ch;
			if (!readTag()) {
				return false;
			}

			_result.append(_currentTagReplacer);

			_begin = _ch + 1;
			_currentTag = QLatin1String("");
		}
	}
	appendToResult(_end);
	return true;
}
Exemplo n.º 6
0
void peltOverlap::numOverlapUVFaces(const MString& shadingGroup, MStringArray& flattenFaces)
//
// Description
//     Return overlapping faces in pairs for given a shading group and its associated faces.
//
{
    MFloatArray  face1Orig, face1Vec, face2Orig, face2Vec, center, radius;
    // Loop through face i
    unsigned int numOverlap = 0;
    createBoundingCircle(flattenFaces, center, radius);
    for(unsigned int i = 0; i < flattenFaces.length() && numOverlap < fNthPairs; i++) {
        if(!createRayGivenFace(flattenFaces[i], face1Orig, face1Vec)) continue;
        const float cui  = center[2*i];
        const float cvi  = center[2*i+1];
        const float ri  = radius[i];
        // Exclude the degenerate face
        // if(area(face1Orig) < 0.000001) continue;
        // Loop through face j where j != i
        for(unsigned int j = i+1; j < flattenFaces.length() && numOverlap < fNthPairs; j++) {
            const float &cuj = center[2*j];
            const float &cvj = center[2*j+1];
            const float &rj  = radius[j];
            float du = cuj - cui;
            float dv = cvj - cvi;
            float dsqr = du*du + dv*dv;
            // Quick rejection if bounding circles don't overlap
            if (dsqr >= (ri+rj)*(ri+rj)) continue;

            if(!createRayGivenFace(flattenFaces[j], face2Orig, face2Vec)) continue;
            // Exclude the degenerate face
            // if(area(face2Orig) < 0.000001) continue;
            if (checkCrossingEdges(face1Orig, face1Vec, face2Orig, face2Vec)) {
                numOverlap++;
                appendToResult(flattenFaces[i]);
                appendToResult(flattenFaces[j]);
                continue;
            }
        }
    }
}
Exemplo n.º 7
0
void skinClusterWeights::doItQuery()
{
    MStatus status;
    unsigned int i, j;

    MDoubleArray weights;
    // To allow "skinClusterWeights -q" to return empty double array
    setResult(weights);
    MSelectionList selList;
    for (i = 0; i < geometryArray.length(); i++) {
	MDagPath dagPath;
	MObject  component;
	  
	selList.clear();
	selList.add(geometryArray[i]);
	MStatus status = selList.getDagPath(0, dagPath, component);
	if (status != MS::kSuccess) {
	    continue;
	}
	if (component.isNull()) dagPath.extendToShape();
	  
	MObject skinCluster = findSkinCluster(dagPath);
	if (!isSkinClusterIncluded(skinCluster)) {
	    continue;
	}  

	MFnSkinCluster skinClusterFn(skinCluster, &status);
	if (status != MS::kSuccess) {
	    continue; 
	}

	MIntArray influenceIndexArray;
	populateInfluenceIndexArray(skinClusterFn, influenceIndexArray);
	  
	weights.clear();
	skinClusterFn.getWeights(dagPath, component, influenceIndexArray, weights);

	if (weights.length() > 0) {
	    for (j = 0; j < weights.length(); j++) {
		appendToResult(weights[j]);
	    }
	}
    }
}
Exemplo n.º 8
0
MStatus	liqGetAttr::doIt( const MArgList& args )
{
	CM_TRACE_FUNC("liqGetAttr::doIt(args)");

	MStatus					status;
	unsigned				i;
	MString					nodeName, attrName;
	MSelectionList				nodeList;

	for ( i = 0; i < args.length(); i++ ) 
  {
		if ( MString( "-debug" ) == args.asString( i, &status) ) 
    {
		} 
    else if ( MString( "-node" ) == args.asString( i, &status) ) 
    {
			i++;
			nodeName = args.asString( i, &status ) ;
		} 
    else if ( MString( "-attr" ) == args.asString( i, &status) ) 
    {
			i++;
			attrName = args.asString( i, &status );
		}
	}
	nodeList.add( nodeName );
	MObject depNodeObj;
	nodeList.getDependNode(0, depNodeObj);
	MFnDependencyNode depNode( depNodeObj );
	MPlug attrPlug = depNode.findPlug( attrName );
	MObject plugObj;
	attrPlug.getValue( plugObj );
	if( plugObj.apiType() == MFn::kDoubleArrayData ) 
  {
	  MFnDoubleArrayData fnDoubleArrayData( plugObj );
	  const MDoubleArray& doubleArrayData( fnDoubleArrayData.array( &status ) );
	  for ( i = 0; i < doubleArrayData.length(); i++ ) 
		  appendToResult( doubleArrayData[i] );
	}
	return MS::kSuccess;
};
Exemplo n.º 9
0
MStatus blindComplexDataCmd::redoIt()
{
	MStatus     stat;				// Status code
	MObject 	dependNode;		// Selected dependency node

	// Iterate over all selected dependency nodes
	//
	for ( ; !iter->isDone(); iter->next() ) 
	{
		// Get the selected dependency node and create
		// a function set for it
		//
		if ( MS::kSuccess != iter->getDependNode( dependNode ) ) {
			cerr << "Error getting the dependency node" << endl;
			continue;
		}
		
		MFnDependencyNode fnDN( dependNode, &stat );
		if ( MS::kSuccess != stat ) {
			cerr << "Error creating MFnDependencyNode" << endl;
			continue;
		}

		// Create a new attribute for our blind data
		//
		// cout << "Creating attr..." << endl;
		
		MFnTypedAttribute fnAttr;
		const MString fullName( "blindComplexData" );
		const MString briefName( "BCD" );
		MObject newAttr = fnAttr.create( fullName, briefName,
										 blindComplexData::id );

		// Now add the new attribute to the current dependency node
		//
		// cout << "Adding attr..." << endl;
		fnDN.addAttribute( newAttr, MFnDependencyNode::kLocalDynamicAttr );
		
		//
		// now we will demonstrate setting the value by using a plug.
		MPlug plug( dependNode, newAttr );  

		//
		// create an instance of the blind data with an initial array size of
		// 5.
		blindComplexData * newData = new blindComplexData( 5 );

		//
		// initialized 
		// cout << "setting data values..." << endl;
		unsigned int i;
		for ( i= 0; i < newData->length(); i++ ) {
			(*newData)[i]._intData = 10 + i;
			(*newData)[i]._doubleData = 20.02 + i;
		}

		// 
		// setting the value for the plug.
		stat = plug.setValue( newData );

		//
		// The following code demonstrates the retrieving of data from the 
		// plug.
		MObject sData;
		stat = plug.getValue( sData );

		if ( stat != MS::kSuccess ) {
			cerr << "error getting value off plug" << endl;
			continue;
		}

		// 
		// Convert the data from an MObject back to a pointer to MPxData, then
		// cast it back to a pointer to blindComplexData.
		MFnPluginData pdFn( sData ); 
		blindComplexData* data =
							( blindComplexData* ) pdFn.constData( &stat );
		//
		// read the data, and set the result to the values set.
		
		clearResult();

		if ( NULL != data ) {
			// cout << "retrieving data values..." << endl;
			for ( i = 0; i < data->length(); i++ ) {
				// cout << "rec #" << i << ": " << (*data)[i]._intData << ", "; 
				// cout << (*data)[i]._doubleData << endl;
				appendToResult((double) ((*data)[i]._intData));
				appendToResult((*data)[i]._doubleData);
			}
		} else {
			// cout << "Null data" << endl;
		}

	}
	return MS::kSuccess;
}
Exemplo n.º 10
0
MStatus tm_randPoint::doIt( const MArgList& args )
{
	MStatus stat = MS::kSuccess;
	double amp = 1.0;
	double amp_x = 1.0;
	double amp_y = 1.0;
	double amp_z = 1.0;
	unsigned int seed = 0;
	bool useAxisAmp = false;
	bool exactObject = false;
	unsigned int num_meshes;
	MString objMString;
	helpMode = false;

	MArgDatabase argData( syntax(), args);
	if(argData.isFlagSet( help_Flag))
	{
		helpMode = true;
		appendToResult( "\n// tm_polygon randPoint usage:\n");
		appendToResult( "//    Command operates with specified object with \"-obj\" flag,\n");
		appendToResult( "//       if this flag is not set, command use selected poly objects or poly vertices.\n");
		appendToResult( "//    Synopsis: tm_polygon [flags].\n");
		appendToResult( "//    Type \"help tm_randPoint\" to query flags.\n");
		return MS::kSuccess;
	}
	if(argData.isFlagSet( amp_Flag))
		argData.getFlagArgument( amp_Flag, 0, amp);
	if(argData.isFlagSet( ampX_Flag))
	{
		argData.getFlagArgument( ampX_Flag, 0, amp_x);
		useAxisAmp = true;
	}
	if(argData.isFlagSet( ampY_Flag))
	{
		argData.getFlagArgument( ampY_Flag, 0, amp_y);
		useAxisAmp = true;
	}
	if(argData.isFlagSet( ampZ_Flag))
	{
		argData.getFlagArgument( ampZ_Flag, 0, amp_z);
		useAxisAmp = true;
	}
	if(argData.isFlagSet( seed_Flag))
		argData.getFlagArgument( seed_Flag, 0, seed);
	if(argData.isFlagSet( obj_Flag))
	{
		exactObject = true;
		argData.getFlagArgument( obj_Flag, 0, objMString);
	}

   double randMax = (double)RAND_MAX;
   double halfRandMax = 0.5 * randMax;


	unsigned i;
    if( exactObject)
	{
		selVtxMode = false;
		MSelectionList m_selList;
		MDagPath m_dagPath;
		stat = m_selList.add( objMString);
		if (!stat){stat.perror("###1 invalid obect path string");return stat;}
		stat = m_selList.getDagPath( 0, m_dagPath);
		if (!stat){stat.perror("###2 invalid obect path string");return stat;}
		stat = res_MDagPathArray.append( m_dagPath);
		if (!stat){stat.perror("###3 invalid obect path string");return stat;}
	}
	else
	{
		MSelectionList curSel;
		MGlobal::getActiveSelectionList( curSel);
		unsigned int numSelected = curSel.length();
		MItSelectionList iter( curSel, MFn::kMeshVertComponent);
		if (iter.isDone())
		{
			selVtxMode = false;
			MItDag::TraversalType traversalType = MItDag::kBreadthFirst;
			MFn::Type filter = MFn::kMesh;
			MItDag mit_dag( traversalType, filter, &stat);
			for( i = 0; i < numSelected; i++ )
			{
				MDagPath sel_dagPath;
				curSel.getDagPath( i, sel_dagPath);
				stat = mit_dag.reset( sel_dagPath,  traversalType, filter);
				if ( !stat) { stat.perror("MItDag constructor");return stat;}
				for ( ; !mit_dag.isDone(); mit_dag.next() )
				{
					MDagPath m_dagPath;
					stat = mit_dag.getPath(m_dagPath);
					if ( !stat ) { stat.perror("MItDag::getPath error"); continue;}
					stat = res_MDagPathArray.append( m_dagPath);
					if ( !stat ) { stat.perror("MDagPathArray.append error"); continue;}
				}
			}
		}
		else
		{
			newPointsArrays = new MPointArray[1];
			oldPointsArrays = new MPointArray[1];
			selVtxMode = true;
			MObject component;
			MDagPath selVtx_dagPath;
			for ( ; !iter.isDone(); iter.next() )
			{
				iter.getDagPath(selVtx_dagPath, component);
				MItMeshVertex vertexIter( selVtx_dagPath, component );
				for ( ; !vertexIter.isDone(); vertexIter.next() )
				{
					MPoint oldPoint = vertexIter.position(MSpace::kObject );
					MPoint newPoint;
					newPoint.x = oldPoint.x + ((halfRandMax - (double)rand()) / randMax) * amp * amp_x;
					newPoint.y = oldPoint.y + ((halfRandMax - (double)rand()) / randMax) * amp * amp_y;
					newPoint.z = oldPoint.z + ((halfRandMax - (double)rand()) / randMax) * amp * amp_z;
					oldPointsArrays[0].append( oldPoint);
					newPointsArrays[0].append( newPoint);
				}
			}
		}
	}

	if(!selVtxMode)
	{
		num_meshes = res_MDagPathArray.length();
		newPointsArrays = new MPointArray[num_meshes];
		oldPointsArrays = new MPointArray[num_meshes];
		for( i = 0; i < num_meshes; i++ )
		{
			MDagPath dagPath = res_MDagPathArray[i];
			MObject node;

			node = dagPath.node();
			MFnDependencyNode fnNode( node );
			
			MStatus polyStatus;
			MFnMesh fnMesh( node, &polyStatus );

			if( polyStatus == MS::kSuccess )
			{
				MStatus status;
				status = fnMesh.getPoints( oldPointsArrays[i]);
				if (!status){status.perror("### error getting mesh points");return stat;}
				unsigned int numVertices = oldPointsArrays[i].length();
				newPointsArrays[i].setLength(numVertices);
				oldPointsArrays[i].setLength(numVertices);
				if(seed != 0) srand(seed);
				if(useAxisAmp)
				{
					for( unsigned int v = 0; v < numVertices; v++)
					{
						newPointsArrays[i][v].x = oldPointsArrays[i][v].x + ((halfRandMax - (double)rand()) / randMax) * amp * amp_x;
						newPointsArrays[i][v].y = oldPointsArrays[i][v].y + ((halfRandMax - (double)rand()) / randMax) * amp * amp_y;
						newPointsArrays[i][v].z = oldPointsArrays[i][v].z + ((halfRandMax - (double)rand()) / randMax) * amp * amp_z;
					}
				}
				else
				{
					for( unsigned int v = 0; v < numVertices; v++)
					{
						newPointsArrays[i][v].x = oldPointsArrays[i][v].x + ((halfRandMax - (double)rand()) / randMax) * amp;
						newPointsArrays[i][v].y = oldPointsArrays[i][v].y + ((halfRandMax - (double)rand()) / randMax) * amp;
						newPointsArrays[i][v].z = oldPointsArrays[i][v].z + ((halfRandMax - (double)rand()) / randMax) * amp;
					}
				}
			}
			else stat = MS::kFailure;
		}
	}
	return redoIt();
}
Exemplo n.º 11
0
MStatus VDBQueryCmd::doIt(const MArgList& args)
{
    MStatus status = MS::kSuccess;
    MArgDatabase arg_data(syntax(), args);

    // always open new files to simplify code, it's cheap anyhow
    std::vector<std::string> vdb_paths;

    if (arg_data.isFlagSet(node_short_flag))
    {
        MSelectionList slist;
        arg_data.getFlagArgument(node_short_flag, 0, slist);

        MObject node;
        slist.getDependNode(0, node);
        MFnDependencyNode dnode(node, &status);

        if (!status)
            return status;

        if (dnode.typeName() != VDBVisualizerShape::typeName)
        {
            MGlobal::displayError("[openvdb] Wrong node was passed to the command : " + dnode.name());
            return MS::kFailure;
        }

        if (arg_data.isFlagSet(current_frame_short_flag))
            vdb_paths.push_back(MPlug(node, VDBVisualizerShape::s_out_vdb_path).asString().asChar());
        else
        {
            build_file_list(MPlug(node, VDBVisualizerShape::s_vdb_path).asString().asChar(),
                            MPlug(node, VDBVisualizerShape::s_cache_playback_start).asInt(),
                            MPlug(node, VDBVisualizerShape::s_cache_playback_end).asInt(),
                            vdb_paths);
        }
    }
    else if (arg_data.isFlagSet(file_short_flag))
    {
        MString vdb_path;
        arg_data.getFlagArgument(file_short_flag, 0, vdb_path);
        if (arg_data.isFlagSet(current_frame_short_flag))
        {
            const int current_frame = static_cast<int>(MAnimControl::currentTime().as(MTime::uiUnit()));
            build_file_list(vdb_path.asChar(), current_frame, current_frame, vdb_paths);
        }
        else
        {
            int start_frame = 0;
            int end_frame = 0;
            if (arg_data.isFlagSet(start_frame_short_flag))
                arg_data.getFlagArgument(start_frame_short_flag, 0, start_frame);
            else
                start_frame = static_cast<int>(MAnimControl::animationStartTime().as(MTime::uiUnit()));

            if (arg_data.isFlagSet(end_frame_short_flag))
                arg_data.getFlagArgument(end_frame_short_flag, 0, end_frame);
            else
                end_frame = static_cast<int>(MAnimControl::animationEndTime().as(MTime::uiUnit()));

            build_file_list(vdb_path.asChar(), start_frame, end_frame, vdb_paths);
        }
    }
    else
    {
        MGlobal::displayError("[openvdb] No cache was passed to the command, use the -file(f) or the -node(n) flags");
        return MS::kFailure;
    }

    if (vdb_paths.size() == 0)
    {
        MGlobal::displayError("[openvdb] No paths are passed to the command.");
        return MS::kFailure;
    }

    std::vector<openvdb::io::File*> vdb_files;
    vdb_files.reserve(vdb_paths.size());

    MString query_type = "";
    if (arg_data.isFlagSet(query_short_flag))
        arg_data.getFlagArgument(query_short_flag, 0, query_type);
    else
    {
        MGlobal::displayError("[openvdb] No query is specified.");
        return MS::kFailure;
    }

    auto get_array_from_flag = [&](const char* flag_name, std::vector<std::string>& out_values) {
        if (arg_data.isFlagSet(flag_name))
        {
            MString flag_data;
            arg_data.getFlagArgument(flag_name, 0, flag_data);
            MStringArray flags;
            if (flag_data.index(','))
                flag_data.split(',', flags);
            else if (flag_data.index(';'))
                flag_data.split(';', flags);
            else if (flag_data.index(':'))
                flag_data.split(':', flags);
            else if (flag_data.index(' '))
                flag_data.split(' ', flags);
            else
                flags.append(flag_data);

            const unsigned int flag_count = flags.length();
            out_values.reserve(flag_count);
            for (unsigned int f = 0; f < flag_count; ++f)
                out_values.push_back(flags[f].asChar());
        }
    };

    std::vector<std::string> queries;
    get_array_from_flag(query_short_flag, queries);

    if (queries.size() == 0)
    {
        MGlobal::displayError("[openvdb] No queries are specified!");
        return MS::kFailure;
    }

    for (auto vdb_path : vdb_paths)
    {
        openvdb::io::File* vdb_file = new openvdb::io::File(vdb_path);
        vdb_file->open(false);
        if (vdb_file->isOpen())
            vdb_files.push_back(vdb_file);
        else
            delete vdb_file;
    }

    if (vdb_files.size() == 0)
    {
        MGlobal::displayError("[openvdb] No vdb files can be opened.");
        return MS::kFailure;
    }

    std::vector<std::string> grid_names;
    get_array_from_flag(grid_short_flag, grid_names);

    std::vector<std::string> grid_types;
    get_array_from_flag(grid_type_short_flag, grid_types);

    const bool all_grids = grid_names.size() == 0 && grid_types.size() == 0;

    auto grid_required = [&](openvdb::GridBase::ConstPtr grid) -> bool {
        if (all_grids)
            return true;
        else
        {
            return std::find(grid_names.begin(), grid_names.end(), grid->getName()) != grid_names.end() ||
                   std::find(grid_types.begin(), grid_types.end(), grid->valueType()) != grid_types.end();
        }
    };

    for (auto query : queries)
    {
        if (query == query_type_bbox)
        {
            MBoundingBox bbox;
            for (auto vdb_file : vdb_files)
            {
                openvdb::GridPtrVecPtr grids = vdb_file->readAllGridMetadata();
                for (openvdb::GridPtrVec::const_iterator it = grids->begin(); it != grids->end(); ++it)
                {
                    if (openvdb::GridBase::ConstPtr grid = *it)
                    {
                        if (grid_required(grid))
                            read_transformed_bounding_box(grid, bbox);
                    }
                }
            }
            const MPoint min = bbox.min();
            const MPoint max = bbox.max();
            appendToResult(min.x);
            appendToResult(min.y);
            appendToResult(min.z);
            appendToResult(max.x);
            appendToResult(max.y);
            appendToResult(max.z);
        }
        else if (query == query_type_min_max)
        {
            std::vector<double> mins;
            std::vector<double> maxs;
            for (auto vdb_file : vdb_files)
            {
                openvdb::GridPtrVecPtr grids = vdb_file->readAllGridMetadata();
                for (openvdb::GridPtrVec::const_iterator it = grids->begin(); it != grids->end(); ++it)
                {
                    if (openvdb::GridBase::ConstPtr grid = *it)
                    {
                        if (grid_required(grid))
                        {
                            // TODO: check for the minimum and maximum metadata
                            if (grid->valueType() == "float")
                            {
                                if (mins.size() < 1)
                                    mins.resize(1, std::numeric_limits<double>::max());
                                if (maxs.size() < 1)
                                    maxs.resize(1, std::numeric_limits<double>::min());

                                openvdb::FloatGrid::ConstPtr grid_data = openvdb::gridConstPtrCast<openvdb::FloatGrid>(vdb_file->readGrid(grid->getName()));

                                for (auto iter = grid_data->beginValueOn(); iter; ++iter)
                                {
                                    const double value = static_cast<double>(iter.getValue());
                                    mins[0] = std::min(mins[0], value);
                                    maxs[0] = std::max(maxs[0], value);
                                }
                            }
                            else if (grid->valueType() == "vec3s")
                            {
                                if (mins.size() < 3)
                                    mins.resize(3, std::numeric_limits<double>::max());
                                if (maxs.size() < 3)
                                    maxs.resize(3, std::numeric_limits<double>::min());

                                openvdb::Vec3SGrid::ConstPtr grid_data = openvdb::gridConstPtrCast<openvdb::Vec3SGrid>(vdb_file->readGrid(grid->getName()));

                                for (auto iter = grid_data->beginValueOn(); iter; ++iter)
                                {
                                    const openvdb::Vec3d value = iter.getValue();
                                    mins[0] = std::min(mins[0], value.x());
                                    mins[1] = std::min(mins[1], value.y());
                                    mins[2] = std::min(mins[2], value.z());

                                    maxs[0] = std::max(maxs[0], value.x());
                                    maxs[1] = std::max(maxs[1], value.y());
                                    maxs[2] = std::max(maxs[2], value.z());
                                }
                            }
                        }
                    }
                }
            }
            for (auto mn : mins)
                appendToResult(mn);
            for (auto mx : maxs)
                appendToResult(mx);
        }
    }

    for (auto vdb_file : vdb_files)
        delete vdb_file;

    return status;
}
Exemplo n.º 12
0
MStatus usdImport::doIt(const MArgList & args)
{

    MStatus status;

    MArgDatabase argData(syntax(), args, &status);

    // Check that all flags were valid
    if (status != MS::kSuccess) {
        MGlobal::displayError("Invalid parameters detected.  Exiting.");
        return status;
    }

    JobImportArgs jobArgs;
    //bool verbose = argData.isFlagSet("verbose");
    
    std::string mFileName;
    if (argData.isFlagSet("file"))
    {
        // Get the value
        MString tmpVal;
        argData.getFlagArgument("file", 0, tmpVal);

        // resolve the path into an absolute path
        MFileObject absoluteFile;
        absoluteFile.setRawFullName(tmpVal);
        absoluteFile.setRawFullName( absoluteFile.resolvedFullName() ); // Make sure an absolute path

        if (!absoluteFile.exists()) {
            MGlobal::displayError("File does not exist.  Exiting.");
            return MS::kFailure;
        }

        // Set the fileName
        mFileName = absoluteFile.resolvedFullName().asChar();
        MGlobal::displayInfo(MString("Importing ") + MString(mFileName.c_str()));
    }
    
    if (mFileName.empty()) {
        MString error = "Non empty file specified. Skipping...";
        MGlobal::displayError(error);
        return MS::kFailure;
    }

    if (argData.isFlagSet("shadingMode")) {
        MString stringVal;
        argData.getFlagArgument("shadingMode", 0, stringVal);
        TfToken shadingMode(stringVal.asChar());

        if (shadingMode.IsEmpty()) {
            jobArgs.shadingMode = PxrUsdMayaShadingModeTokens->displayColor;
        }
        else {
            if (PxrUsdMayaShadingModeRegistry::GetInstance().GetExporter(shadingMode)) {
                jobArgs.shadingMode = shadingMode;
            }
            else {
                MGlobal::displayError(TfStringPrintf("No shadingMode '%s' found.  Setting shadingMode='none'", 
                            shadingMode.GetText()).c_str());
                jobArgs.shadingMode = PxrUsdMayaShadingModeTokens->none;
            }
        }
    }

    if (argData.isFlagSet("readAnimData"))
    {   
        bool tmpBool = false;
        argData.getFlagArgument("readAnimData", 0, tmpBool);
        jobArgs.readAnimData = tmpBool;
    }

    // Specify usd PrimPath.  Default will be "/<useFileBasename>"
    std::string mPrimPath;
    if (argData.isFlagSet("primPath"))
    {
        // Get the value
        MString tmpVal;
        argData.getFlagArgument("primPath", 0, tmpVal);
        mPrimPath = tmpVal.asChar();
    }

    // Add variant (variantSet, variant).  Multi-use
    std::map<std::string,std::string> mVariants;
    for (unsigned int i=0; i < argData.numberOfFlagUses("variant"); ++i)
    {
        MArgList tmpArgList;
        status = argData.getFlagArgumentList("variant", i, tmpArgList);
        // Get the value
        MString tmpKey = tmpArgList.asString(0, &status);
        MString tmpVal = tmpArgList.asString(1, &status);
        mVariants.insert( std::pair<std::string, std::string>(tmpKey.asChar(), tmpVal.asChar()) );
    }

    if (argData.isFlagSet("assemblyRep"))
    {
        // Get the value
        MString stringVal;
        argData.getFlagArgument("assemblyRep", 0, stringVal);
        std::string assemblyRep = stringVal.asChar();
        if (not assemblyRep.empty()) {
            jobArgs.assemblyRep = TfToken(assemblyRep);
        }
    }

    // Create the command
    if (mUsdReadJob) {
        delete mUsdReadJob;
    }


    // pass in assemblyTypeName and proxyShapeTypeName
    mUsdReadJob = new usdReadJob(mFileName, mPrimPath, mVariants, jobArgs,
            _assemblyTypeName, _proxyShapeTypeName);


    // Add optional command params
    if (argData.isFlagSet("parent"))
    {
        // Get the value
        MString tmpVal;
        argData.getFlagArgument("parent", 0, tmpVal);

        if (tmpVal.length()) {
            MSelectionList selList;
            selList.add(tmpVal);
            MDagPath dagPath;
            status = selList.getDagPath(0, dagPath);
            if (status != MS::kSuccess) {
                std::string errorStr = TfStringPrintf(
                        "Invalid path \"%s\"for -parent.",
                        tmpVal.asChar());
                MGlobal::displayError(MString(errorStr.c_str()));
                return MS::kFailure;
            }
            mUsdReadJob->setMayaRootDagPath( dagPath );
        }
    }

    // Execute the command
    std::vector<MDagPath> addedDagPaths;
    bool success = mUsdReadJob->doIt(&addedDagPaths);
    if (success) {
        TF_FOR_ALL(iter, addedDagPaths) {
            appendToResult(iter->fullPathName());
        }
    }