Beispiel #1
0
//  ========== DtCameraGetPosition ==========
//
//  SYNOPSIS
//	Return the camera position.
//
int DtCameraGetPosition( int cameraID,
						 float* xTran,
						 float* yTran,
						 float* zTran )
{
    // Check for error.
    //
	if( (cameraID < 0) || (cameraID >= local->camera_ct ) )
	{
		*xTran = 0.0;
		*yTran = 0.0;
		*zTran = 0.0;
		return( 0 );
	}

	MStatus stat = MS::kSuccess;

    MFnDagNode fnDagNode( local->cameras[cameraID].transformNode, &stat );
    MDagPath aPath;
    stat = fnDagNode.getPath( aPath );
	
    // Get the global transformation matrix of the camera node.
    //
    MMatrix globalMatrix = aPath.inclusiveMatrix();

	MFnCamera fnCamera( local->cameras[cameraID].cameraShapeNode, &stat );

	MPoint eyePt;
    double eyePos[4]; 

	if( MS::kSuccess == stat )
	{
	    eyePt = fnCamera.eyePoint( MSpace::kObject, &stat );

		if( DtExt_Debug() & DEBUG_CAMERA )
		{
			cerr << "eye point is at " 
				 << eyePt.x << " " << eyePt.y << " " << eyePt.z << endl;
		}

	    eyePt *= globalMatrix;
	    eyePt.get( eyePos );

	}
	else
	{
		DtExt_Err( "Error in getting the camera function set\n" );
	}

    // Return values:
    //
	*xTran = eyePos[0];
	*yTran = eyePos[1];
	*zTran = eyePos[2];

	return( 1 );
}  // DtCameraGetPosition //
Beispiel #2
0
/*****************************************************
**
**   Painter   ---   getTextExtent
**
******************************************************/
MPoint Painter::getTextExtent( const MString &f )
{
	double x = 0, y = 0;
	MPoint p;

	for( list<MToken>::const_iterator iter = f.tokens.begin(); iter != f.tokens.end(); iter++ )
	{
		p = getTextExtent( *iter );
		x += p.real();
		y = Max( y, p.imag());
	}
	return MPoint( x, y );
}
/*****************************************************
**
**   BasicVedicChart   ---   drawTextItemLine
**
******************************************************/
void BasicVedicChart::drawTextItemLine( MRect rect, const wxString &s, const int &align, const FIELD_PART &part )
{
	setDefaultTextColor( part );
	MPoint p = painter->getTextExtent( s );

	if ( align & Align::Right ) rect.x = rect.x + rect.width - p.real();
	else if ( align & Align::HCenter ) rect.x = rect.x + .5 * ( rect.width - p.real() );

	//painter->drawRectangle( rect );

	// TODO

	painter->drawTextFormatted( rect, s, Align::Left + Align::Top );
}
Beispiel #4
0
//  ========== DtCameraGetInterest ==========
//
//  SYNOPSIS
//  Return the camera position.
//
int DtCameraGetInterest(int cameraID,float* xTran,float* yTran,float* zTran)
{
	// check for error
	//

	if ( (cameraID < 0) || (cameraID >= local->camera_ct) )
	{
		*xTran = 0.0;
		*yTran = 0.0;
		*zTran = 0.0;
		return(0);
	}
 
	// return values
	//
	
    MStatus stat = MS::kSuccess;

    MFnDagNode fnDagNode( local->cameras[cameraID].transformNode, &stat );
    MDagPath aPath;
    stat = fnDagNode.getPath( aPath );

    // Get the global transformation matrix of the camera node.
    //
    MMatrix globalMatrix = aPath.inclusiveMatrix();

    MFnCamera fnCamera( local->cameras[cameraID].cameraShapeNode, &stat );

    // Center of interest point: view node point.
    //
    MPoint coiPoint = fnCamera.centerOfInterestPoint( MSpace::kObject, &stat );
    double coiPos[4]; 
    if( DtExt_Debug() & DEBUG_CAMERA )
    {
        coiPoint.get( coiPos );
        cerr << "local center of interest( view point position ) is " <<
            coiPos[0] << " " << coiPos[1] << " " << coiPos[2] << " "  
             << coiPos[3] << endl;
    }        
    coiPoint *= globalMatrix;
    coiPoint.get( coiPos );

	*xTran = coiPos[0];
	*yTran = coiPos[1];
	*zTran = coiPos[2];
 
	return(1);

}  // DtCameraGetInterest //
Beispiel #5
0
void ItemIterator::publishOnMouseMotion(int mouse_x, int mouse_y)
{
    Point mousePt (mouse_x, mouse_y);
    MPoint relpt (0, 0);
    for(;next();)
    {
        if(item()->contains(&mousePt))
        {
            relpt.setPoint(mouse_x - item()->getX(), mouse_y - item()->getY());
            item()->setMouseOver(true);
            item()->onMouseMotion(&relpt);
        }
        else
        {
            item()->setMouseOver(false);
        }
    }
}
Beispiel #6
0
/*****************************************************
**
**   DcPainter   ---   drawRotatedText
**
******************************************************/
void DcPainter::drawRotatedText( wxString s, const double &x, const double &y, const double &alfa )
{
	MPoint p = getTextExtent( s );
	/*
	const double a = 2;
	printf( "DcPainter::drawRotatedText angle is %f extent %f %f\n", alfa, p.real(), p.imag());
	dc->DrawRectangle( x - .5 * p.real(), y - .5 * p.imag(), p.real(), p.imag());
	dc->DrawRectangle( x - a, y - a, 2 * a, 2 * a );
	*/

	const double w = .5 * p.real();
	const double h = .5 * p.imag();

	const double px = x - w * cos( alfa * DEG2RAD ) -  h * sin( alfa * DEG2RAD );
	const double py = y + w * sin( alfa * DEG2RAD ) - h * cos( alfa * DEG2RAD );

	//dc->DrawRectangle( px - a, py - a, 2 * a, 2 * a );
	dc->DrawRotatedText( s, px, py, alfa );
}
	// used when ray does not intersect object
	// to account for perspective, all edges are flattened onto 
	// a plane defined by the raySource and rayDirection
	double gpuCacheIsectUtil::getEdgeSnapPointOnTriangle(const MPoint& raySource, const MVector& rayDirection, const MPoint& vert1, const MPoint& vert2, const MPoint& vert3, MPoint& snapPoint){
		MPointArray verts;
		verts.insert(vert1,0);
		verts.insert(vert2,1);
		verts.insert(vert3,2);

		int edgeIndices[3][2]={{0,1},{1,2},{2,0}};

		double minDistTri = std::numeric_limits<double>::max();

		for(int edge=0; edge<3;edge++){
			MPoint vertex1Org = verts[edgeIndices[edge][0]];
			MPoint vertex2Org = verts[edgeIndices[edge][1]];

			double coef_plane = rayDirection * raySource;
			double d = coef_plane - rayDirection * vertex1Org;
			MPoint vertex1 = vertex1Org + rayDirection * d;
			d = coef_plane - rayDirection * vertex2Org;
			MPoint vertex2 = vertex2Org + rayDirection * d;

			MVector edgeDir = vertex2 - vertex1;
			
			if (edgeDir.length()<0.0000001){
				double dist = vertex1.distanceTo(raySource);
				if (dist < minDistTri) {
					minDistTri = dist;
					snapPoint = vertex1Org;
				}
			} else {
				MPoint edgePt;
				// Compute the closest point from the edge to cursor Ray.
				double percent = gpuCacheIsectUtil::getClosestPointOnLine(raySource, vertex1, vertex2, edgePt);
				double dist = edgePt.distanceTo(raySource);                                                            
				if (dist < minDistTri) {
					minDistTri = dist;
					snapPoint =  (vertex1Org + percent * (vertex2Org - vertex1Org));
				}
			}
		}

		return minDistTri;
	}
Beispiel #8
0
/*****************************************************
**
**   PdfPainter   ---   drawRotatedText
**
******************************************************/
void PdfPainter::drawRotatedText( wxString s, const double &x, const double &y, const double &alfa )
{
	MPoint p = getTextExtent( s );

	const double w = .5 * p.real();
	const double h = .5 * p.imag();

	// in pdf mode the anchor is located at the left sid of the text. y value is in the middle
	const double px = x - w * cos( alfa * DEG2RAD ) +  h * sin( alfa * DEG2RAD );
	const double py = y + w * sin( alfa * DEG2RAD ) + h * cos( alfa * DEG2RAD );

	/*
	const int rw = 1;
	setDefaultPen();
	//drawRectangle( x - rw, y - rw, 2 * rw, 2 * rw );
	drawRectangle( px - rw, py - rw, 2 * rw, 2 * rw );
	*/

	pdf->RotatedText( px, py, s, alfa );
}
Beispiel #9
0
/*****************************************************
**
**   PdfPainter   ---  drawTextFormatted
**
******************************************************/
void PdfPainter::drawTextFormatted( const MRect &r, const wxString &t, const int& align )
{
	double oldx = pdf->GetX();
	double oldy = pdf->GetY();
	double x1 = r.x;
	double y1 = r.y;

	MPoint p = getTextExtent( t );

	if ( align & Align::Top )
	{
		y1 = r.y + p.imag();
	}
	else if ( align & Align::Bottom )
	{
		// add a certain part of p.imag, otherwise text will be too deep e.g. in SBC
		y1 = r.y + r.height - .2 * p.imag();
	}
	else if ( align & Align::VCenter )
	{
		y1 = r.y + .5 * ( r.height + p.imag() );
	}
	if ( align & Align::HCenter )
	{
		x1 = r.x + .5 * ( r.width - p.real() );
	}
	else if ( align & Align::Right )
	{
		x1 = r.x + r.width - p.real();
	}
	pdf->Text( x1, y1, t );
	//drawEllipse( x1, y1, 2, 2 );
	pdf->SetXY( oldx, oldy );
}
void SurfaceAttach::surfaceLengthsV(const MFnNurbsSurface &fnSurface, const double parmU) {
    MPoint pointA;
    fnSurface.getPointAtParam(parmU, 0.0, pointA, MSpace::Space::kWorld);

    this->length = 0.0;
    MPoint pointB;

    double *s = &this->sampler[0];
    double *d = &this->distances[0];

    for (size_t i=0; i < this->sampleCount; i++){
        fnSurface.getPointAtParam(parmU, *s++, pointB, MSpace::Space::kWorld);

        // Add the measured distanced to 'length' and set the measured length in 'distances'
        this->length += pointA.distanceTo(pointB);
        *d++ = this->length;

        pointA.x = pointB.x;
        pointA.y = pointB.y;
        pointA.z = pointB.z;
    }
}
Beispiel #11
0
// which one is the closest point(in points array) to pt
int TestDeformer::getClosestPt(const MPoint &pt, const MPointArray &points)
{
    int ptIndex=0;
	float currentDistance = 9e99;
	float furthestDistanceSoFar = 9e99;

	for(int i = 0; i < points.length(); ++i)
    {
        currentDistance = pt.distanceTo( points[i] );
        if(currentDistance < furthestDistanceSoFar )
        {
            ptIndex = i;
            furthestDistanceSoFar = currentDistance;
        }
    }

	return ptIndex;
}
Beispiel #12
0
void NewMapState::onResize(int m_width, int m_height)
{

    MPoint curpt;

    curpt.setPoint(5, 50);

    lblSizes.setPoint(&curpt);

    curpt.setY(curpt.getY() + lblSizes.getHeight() + 5);

    listSizes.setPoint(&curpt);

    curpt.setY(curpt.getY() + listSizes.getHeight() + 5);

    btnCreate.setPoint(&curpt);

    curpt.setPoint(5, m_height - BTN_HEIGHT - 5);

    btnBack.setPoint(&curpt);
}
Beispiel #13
0
  int composeFun
      (Word* args, Word& result, int message, Word& local, Supplier s)
  {

      // storage for the result
      result = qp->ResultStorage(s);
      
      // the moving point
      MPoint* movingPoint = static_cast<MPoint*>(args[0].addr);
      
      // the sT object
      typename T::this_type* raster =
          static_cast<typename T::this_type*>(args[1].addr);

      // The result of the compose
      typename T::moving_type* pResult =
            static_cast<typename T::moving_type*>(result.addr);


      if (!movingPoint->IsDefined() || !raster->isDefined()) {
        pResult->SetDefined(false);
        return 0;
      }

      pResult->Clear();
      pResult->StartBulkLoad();

      // get the number of components
      int num = movingPoint->GetNoComponents();

      UPoint unit(0);
      grid2 grid = raster->getGrid();
      grid2::index_type cell1;
      grid2::index_type cell2;

      for (int i = 0; i < num; i++)
      {
          movingPoint->Get(i, unit);
          
          // get the coordinates
          double xStart = unit.p0.GetX();
          double yStart = unit.p0.GetY();
          double xEnd = unit.p1.GetX();
          double yEnd = unit.p1.GetY();

          cell1 = grid.getIndex(xStart,yStart);
          cell2 = grid.getIndex(xEnd, yEnd);

          if(cell1==cell2){ // only a constant unit in result
            typename T::cell_type v = raster->atlocation(xStart,yStart);  
            if(!raster->isUndefined(v)){  
                typename T::wrapper_type v1(true,v);
                pResult->MergeAdd(typename T::unit_type(
                                   unit.timeInterval,v1,v1));
            }
          } else {
            DateTime t1 = unit.timeInterval.start;
            DateTime t2 = unit.timeInterval.end;
            DateTime dur = t2 - t1;
            CellIterator it(grid,xStart,yStart,xEnd,yEnd);
            double dx = xEnd - xStart;
            double dy = yEnd - yStart; 
            while(it.hasNext()){
               pair<double,double> p = it.next();
               DateTime s = t1 + (dur*p.first);
               DateTime e = t1 + (dur*p.second);
               if(e>s){
                  Interval<Instant> iv(s,e,true,false);
                  double delta  =(p.first + p.second) / 2.0;
                  double x = xStart + delta*dx;
                  double y = yStart + delta*dy;
                  typename T::cell_type v = raster->atlocation(x,y);  
                  if(!raster->isUndefined(v)){  
                     typename T::wrapper_type v1(true,v);
                     pResult->MergeAdd(typename T::unit_type(iv,v1,v1));
                  }
               } else {
                  assert(e==s);
               } 
            }  
          }
      }
       
      pResult->EndBulkLoad();

    return 0;
  }
Beispiel #14
0
MStatus	grabUVContext::doDrag ( MEvent & event, MHWRender::MUIDrawManager& drawMgr, const MHWRender::MFrameContext& context)
{
	if (event.mouseButton() != MEvent::kLeftMouse || 
		!event.isModifierNone() )
		return MS::kFailure;

	MPxTexContext::doDrag(event, drawMgr, context);

	short x, y;
	event.getPosition( x, y );
	fLastScreenPoint = fCurrentScreenPoint;
	fCurrentScreenPoint = MPoint( x, y );

	double xView, yView;
	portToView(x, y, xView, yView);	// pos at viewrect coordinate

	fLastPoint = fCurrentPoint;
	fCurrentPoint = MPoint( xView, yView, 0.0 );

	if( fDragMode == kBrushSize )
	{
		double dis = fCurrentScreenPoint.distanceTo( fLastScreenPoint );
		if ( fCurrentScreenPoint[0] > fLastScreenPoint[0] )
			setSize( size() + float(dis) );
		else
			setSize( std::max( size() - float(dis), 0.01f ) );
	}
	else
	{
		fBrushCenterScreenPoint = MPoint( x, y );

		MFloatArray uUVsExported;
		MFloatArray vUVsExported;

		const MVector vec = fCurrentPoint - fLastPoint;

		if (!fCommand)
		{
			fCommand = (UVUpdateCommand *)(newToolCommand());
		}
		if (fCommand)
		{
			MFnMesh mesh(fDagPath);
			MString currentUVSetName;
			mesh.getCurrentUVSetName(currentUVSetName);

			int nbUVs = mesh.numUVs(currentUVSetName);
			MDoubleArray pinData;
			MUintArray uvPinIds;
			MDoubleArray fullPinData;
			mesh.getPinUVs(uvPinIds, pinData, &currentUVSetName);
			int len = pinData.length();

			fullPinData.setLength(nbUVs);
			for (unsigned int i = 0; i < nbUVs; i++) {
				fullPinData[i] = 0.0;
			}
			while( len-- > 0 ) {
				fullPinData[uvPinIds[len]] = pinData[len];
			}

			MFloatArray uValues;
			MFloatArray vValues;
			float pinWeight = 0;
			for (unsigned int i = 0; i < fCollectedUVs.length(); ++i)
			{
				float u, v;
				MStatus bGetUV = mesh.getUV(fCollectedUVs[i], u, v, &currentUVSetName);
				if (bGetUV == MS::kSuccess)
				{
					pinWeight = fullPinData[fCollectedUVs[i]];
					u += (float)vec[0]*(1-pinWeight);
					v += (float)vec[1]*(1-pinWeight);
					uValues.append( u );
					vValues.append( v ); 
				}
			}
			fCommand->setUVs( mesh.object(), fCollectedUVs, uValues, vValues, &currentUVSetName );
		}
	}
	return MS::kSuccess;
}
Beispiel #15
0
MStatus CrawlSurface(const MPoint& startPoint, const MIntArray& vertexIndices, MPointArray& points, double maxDistance,
                     std::vector<std::set<int> >& adjacency, std::map<int, double>& distances) {
  MStatus status;
  distances[NORMALIZATION_INDEX] = 0.0; // -1 will represent our hit point.
  double minStartDistance = 999999.0;
  unsigned int minStartIndex = 0;

  // Instead of a recursive function, which can get pretty slow, we'll use a queue to keep
  // track of where we are going and where we are coming from.
  std::queue<CrawlData> verticesToVisit;
  // Add the initial crawl paths to the queue.
  for (unsigned int i = 0; i < vertexIndices.length(); ++i) {
    double distance = startPoint.distanceTo(points[vertexIndices[i]]);
    // Only crawl to the starting vertices if they are within the radius.
    if (distance <= maxDistance) {
      CrawlData root = {startPoint, distance, vertexIndices[i]};
      verticesToVisit.push(root);
    }
    // Track the minimum start distance in case we need to add the closest vertex below.
    // The minimum must be greater than 0 to make sure we do not use the vertex that is the
    // same as the startPoint which would create an invalid up vector.
    if (distance < minStartDistance && distance > 0.000001) {
      minStartDistance = distance;
      minStartIndex = vertexIndices[i];
    }
  }
  // If we didn't even reach a vertex in the hit face, or the startPoint is equal to a vertex
  // on the face, add the closest vertex so we can calculate a proper up vector
  if (verticesToVisit.size() <= 1) {
    CrawlData root = {startPoint, maxDistance - 0.001, (int)minStartIndex};
    verticesToVisit.push(root);
    distances[minStartIndex] = maxDistance - 0.001;
  }
  while (verticesToVisit.size()) {
    CrawlData next = verticesToVisit.front();
    verticesToVisit.pop();

    // Extract the data out of the crawl struct
    int idx = next.nextVertex;
    MPoint& pt = points[idx];
    MPoint sourcePoint = next.sourcePosition;
    double currentCrawlDistance = next.crawlDistance;

    currentCrawlDistance += sourcePoint.distanceTo(pt);
    if (currentCrawlDistance >= maxDistance) {
      // If this vertex is outside the radius, no need to crawl anymore from that vertex.
      continue;
    }
    double& savedDistance = distances[idx];
    if (currentCrawlDistance <= savedDistance || savedDistance == 0.0) {
      // If this current crawl distance is less then the distance we have saved for this
      // vertex, use this new crawl distance instead.
      savedDistance = currentCrawlDistance;
    } else {
      // A smaller distance is already stored so we don't want to crawl
      // from this vertex any further.
      continue;
    }
    // Crawl the adjacent vertices
    std::set<int>::iterator iter;
    for (iter = adjacency[idx].begin(); iter != adjacency[idx].end(); ++iter) {
      CrawlData data = {pt, currentCrawlDistance, *iter};
      verticesToVisit.push(data);
    }
  }
  assert(distances.size() > 0);
  
  return MS::kSuccess;
}
Beispiel #16
0
//
//      Deform computation
//
MStatus jhMeshBlur::deform( MDataBlock& block,MItGeometry& iter,const MMatrix& m,unsigned int multiIndex)
{
    MStatus returnStatus;

    // Envelope
    float envData = block.inputValue(envelope, &returnStatus).asFloat();
	CHECK_MSTATUS(returnStatus);

    if(envData == 0)
		return MS::kFailure;

    /*
     VARIABLES
     */
    //float factor = block.inputValue(aShapeFactor, &returnStatus).asFloat();
    float fStrength = block.inputValue(aStrength, &returnStatus).asFloat();
	CHECK_MSTATUS(returnStatus);
	
	if (fStrength == 0)
		return MS::kFailure;
	
    float fThreshold = block.inputValue(aTreshhold, &returnStatus).asFloat();
	CHECK_MSTATUS(returnStatus);
    float fW = 0.0f; // weight
    float fDistance;
    fStrength *= envData;

    double dKracht = block.inputValue(aInterpPower, &returnStatus).asDouble();
	CHECK_MSTATUS(returnStatus);
    double dDotProduct;  // Dotproduct of the point

    bool bTweakblur = block.inputValue(aTweakBlur, &returnStatus).asBool();
	CHECK_MSTATUS(returnStatus);
	
    bool bQuad = block.inputValue(aQuadInterp, &returnStatus).asBool();
	CHECK_MSTATUS(returnStatus);
	
	MTime inTime = block.inputValue(aTime).asTime();
    int nTijd = (int)inTime.as(MTime::kFilm);


    MFloatVectorArray currentNormals;   // normals of mesh
    MFnPointArrayData fnPoints;         // help converting to MPointArrays
    MFloatVector dirVector;             // direction vector of the point
    MFloatVector normal;                // normal of the point
    MPointArray savedPoints;            // save all point before edited
    MMatrix matInv = m.inverse();       // inversed matrix
    MPoint ptA;                         // current point (iter mesh)
    MPoint ptB;                         // previous point (iter mesh)
    MPoint ptC;                         // mesh before previous point (iter mesh)

    // get node, use node to get inputGeom, use inputGeom to get mesh data, use mesh data to get normal data
    MFnDependencyNode nodeFn(this->thisMObject());

    MPlug inGeomPlug(nodeFn.findPlug(this->inputGeom,true));
    MObject inputObject(inGeomPlug.asMObject());
    MFnMesh inMesh(inputObject);

    inMesh.getVertexNormals(true, currentNormals);

    // get the previous mesh data
    MPlug oldMeshPlug = nodeFn.findPlug(MString("oldMesh"));
    MPlug oldMeshPositionsAPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 0);
    MPlug oldMeshPositionsBPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 1);
    MPlug oldMeshPositionsCPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 2); // cache for tweak mode
    MPlug oldMeshPositionsDPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 3); // cache for tweak mode

    // convert to MPointArrays
    MObject objOldMeshA;
    MObject objOldMeshB;
    MObject objOldMeshC; // cache
    MObject objOldMeshD; // cache

    oldMeshPositionsAPlug.getValue(objOldMeshA);
    oldMeshPositionsBPlug.getValue(objOldMeshB);
    oldMeshPositionsCPlug.getValue(objOldMeshC); // cache
    oldMeshPositionsDPlug.getValue(objOldMeshD); // cache

    fnPoints.setObject(objOldMeshA);
    MPointArray oldMeshPositionsA = fnPoints.array();
    
    fnPoints.setObject(objOldMeshB);
    MPointArray oldMeshPositionsB = fnPoints.array();
    
    fnPoints.setObject(objOldMeshC);
    MPointArray oldMeshPositionsC = fnPoints.array(); // cache
    
    fnPoints.setObject(objOldMeshD);
    MPointArray oldMeshPositionsD = fnPoints.array(); // cache

    
    
    // If mesh position variables are empty,fill them with default values
    if(oldMeshPositionsA.length() == 0 || nTijd <= 1){
        iter.allPositions(oldMeshPositionsA);

        for(int i=0; i < oldMeshPositionsA.length(); i++)
        {
            // convert to world
            oldMeshPositionsA[i] = oldMeshPositionsA[i] * m;
        }
		
        oldMeshPositionsB.copy(oldMeshPositionsA);
        oldMeshPositionsC.copy(oldMeshPositionsA); // cache
        oldMeshPositionsD.copy(oldMeshPositionsA); // cache
    }
	
	// get back old date again
	if (bTweakblur == true) { // restore cache
		oldMeshPositionsA.copy(oldMeshPositionsC);
		oldMeshPositionsB.copy(oldMeshPositionsD);
	}
    
    
    iter.allPositions(savedPoints);
    for(int i=0; i < savedPoints.length(); i++)
    {
        // convert points to world points
        savedPoints[i] = savedPoints[i] * m;
    }

    // Actual Iteration through points
    for (; !iter.isDone(); iter.next()){
        // get current position
        ptA = iter.position();
        // get old positions
        ptB = oldMeshPositionsA[iter.index()] * matInv;
        ptC = oldMeshPositionsB[iter.index()] * matInv;

        fDistance = ptA.distanceTo(ptB);
        fW = weightValue(block,multiIndex,iter.index());


        if (fDistance * (fStrength*fW) < fThreshold && fThreshold > 0){
            iter.setPosition(ptA);
        } else {
            // aim/direction vector to calculate strength
            dirVector = (ptA - ptB); // (per punt)
            dirVector.normalize();

            normal = currentNormals[iter.index()];

            dDotProduct = normal.x * dirVector.x + normal.y * dirVector.y + normal.z * dirVector.z;

            
            if(bQuad == true){
                MVector vecA(((ptB - ptC) + (ptA - ptB)) / 2);
                vecA.normalize();

                MPoint hiddenPt(ptB + (vecA * fDistance) * dKracht);
                ptA = quadInterpBetween(ptB, hiddenPt, ptA, (1 - fStrength * fW) + (linearInterp(dDotProduct, -1, 1) * (fStrength * fW) ) );
            } else {
                MPoint halfway = (ptA - ptB) * 0.5;
                MPoint offset = halfway * dDotProduct * (fStrength*fW);
                ptA = ptA - ((halfway * (fStrength*fW)) - offset); // + (offset * strength);
            }
            // set new value

            iter.setPosition(ptA);
        }
    }
    if(bTweakblur == false){
        oldMeshPositionsD.copy(oldMeshPositionsB);
        oldMeshPositionsC.copy(oldMeshPositionsA);
        oldMeshPositionsB.copy(oldMeshPositionsA);
        oldMeshPositionsA.copy(savedPoints);

        // Save back to plugs
        objOldMeshA = fnPoints.create(oldMeshPositionsA);
        objOldMeshB = fnPoints.create(oldMeshPositionsB);
        objOldMeshC = fnPoints.create(oldMeshPositionsC);
        objOldMeshD = fnPoints.create(oldMeshPositionsD);
		
        oldMeshPositionsAPlug.setValue(objOldMeshA);
        oldMeshPositionsBPlug.setValue(objOldMeshB);
        oldMeshPositionsCPlug.setValue(objOldMeshC);
        oldMeshPositionsDPlug.setValue(objOldMeshD);
    }
    
    return returnStatus;
}
Beispiel #17
0
bool apiSimpleShapeUI::selectVertices( MSelectInfo &selectInfo,
							 MSelectionList &selectionList,
							 MPointArray &worldSpaceSelectPts ) const
//
// Description:
//
//     Vertex selection.
//
// Arguments:
//
//     selectInfo           - the selection state information
//     selectionList        - the list of selected items to add to
//     worldSpaceSelectPts  -
//
{
	bool selected = false;
	M3dView view = selectInfo.view();

	MPoint 		xformedPoint;
	MPoint 		currentPoint;
	MPoint 		selectionPoint;
	double		z,previousZ = 0.0;
 	int			closestPointVertexIndex = -1;

	const MDagPath & path = selectInfo.multiPath();

	// Create a component that will store the selected vertices
	//
	MFnSingleIndexedComponent fnComponent;
	MObject surfaceComponent = fnComponent.create( MFn::kMeshVertComponent );
	int vertexIndex;

	// if the user did a single mouse click and we find > 1 selection
	// we will use the alignmentMatrix to find out which is the closest
	//
	MMatrix	alignmentMatrix;
	MPoint singlePoint; 
	bool singleSelection = selectInfo.singleSelection();
	if( singleSelection ) {
		alignmentMatrix = selectInfo.getAlignmentMatrix();
	}

	// Get the geometry information
	//
	apiSimpleShape* shape = (apiSimpleShape*) surfaceShape();
	MVectorArray* geomPtr = shape->getControlPoints();
	MVectorArray& geom = *geomPtr;


	// Loop through all vertices of the mesh and
	// see if they lie withing the selection area
	//
	int numVertices = geom.length();
	for ( vertexIndex=0; vertexIndex<numVertices; vertexIndex++ )
	{
		const MVector& point = geom[ vertexIndex ];

		// Sets OpenGL's render mode to select and stores
		// selected items in a pick buffer
		//
		view.beginSelect();

		glBegin( GL_POINTS );
		glVertex3f( (float)point[0], 
					(float)point[1], 
					(float)point[2] );
		glEnd();

		if ( view.endSelect() > 0 )	// Hit count > 0
		{
			selected = true;

			if ( singleSelection ) {
				xformedPoint = currentPoint;
				xformedPoint.homogenize();
				xformedPoint*= alignmentMatrix;
				z = xformedPoint.z;
				if ( closestPointVertexIndex < 0 || z > previousZ ) {
					closestPointVertexIndex = vertexIndex;
					singlePoint = currentPoint;
					previousZ = z;
				}
			} else {
				// multiple selection, store all elements
				//
				fnComponent.addElement( vertexIndex );
			}
		}
	}

	// If single selection, insert the closest point into the array
	//
	if ( selected && selectInfo.singleSelection() ) {
		fnComponent.addElement(closestPointVertexIndex);

		// need to get world space position for this vertex
		//
		selectionPoint = singlePoint;
		selectionPoint *= path.inclusiveMatrix();
	}

	// Add the selected component to the selection list
	//
	if ( selected ) {
		MSelectionList selectionItem;
		selectionItem.add( path, surfaceComponent );

		MSelectionMask mask( MSelectionMask::kSelectComponentsMask );
		selectInfo.addSelection(
			selectionItem, selectionPoint,
			selectionList, worldSpaceSelectPts,
			mask, true );
	}

	return selected;
}
Beispiel #18
0
//  ========== DtCameraGetUpPosition ==========
//
//  SYNOPSIS
//  Return the camera Up position.
//
int DtCameraGetUpPosition( int cameraID,
                         float* xTran,
                         float* yTran,
                         float* zTran )
{                        
    // Check for error.  
    //
    if( (cameraID < 0) || (cameraID >= local->camera_ct ) )
    {
        *xTran = 0.0;
        *yTran = 0.0;
        *zTran = 0.0;
        return( 0 );
    }   
    
    MStatus stat = MS::kSuccess;
    
    MFnDagNode fnDagNode( local->cameras[cameraID].transformNode, &stat );
    MDagPath aPath;
    stat = fnDagNode.getPath( aPath );
    
    // Get the global transformation matrix of the camera node.
    //
    MMatrix globalMatrix = aPath.inclusiveMatrix();
    
    MFnCamera fnCamera( local->cameras[cameraID].cameraShapeNode, &stat );
    
    MPoint eyePt;
    double eyePos[4];
    double upPos[4];
    
    if( MS::kSuccess == stat )
    {
        eyePt = fnCamera.eyePoint( MSpace::kObject, &stat );
        
        eyePt *= globalMatrix;
        eyePt.get( eyePos );

	    MVector upVec = fnCamera.upDirection( MSpace::kObject, &stat );
		upVec *= globalMatrix;
		
	    if( DtExt_Debug() & DEBUG_CAMERA )
	    {
	        double up[3];
	        upVec.get( up );
	        cerr << "local up vector is " << up[0] << " " 
										<< up[1] << " " << up[2] << endl; 
    	}

    	MPoint upPoint = eyePt + upVec;
    	upPoint.get( upPos );
    	if( DtExt_Debug() & DEBUG_CAMERA )
    	{
    	    cerr << "global up point position is " 
						<< upPos[0] << " " << upPos[1]
            			<< " " << upPos[2] << " " << upPos[3] << endl;
    	}        
    	
    }   
    else
    {
        DtExt_Err( "Error in getting the camera function set\n" );
    }   

    *xTran = upPos[0];
    *yTran = upPos[1];
    *zTran = upPos[2];

	return(1);

}
Beispiel #19
0
bool
PxrUsdMayaWriteUtil::SetUsdAttr(
        const MPlug& attrPlug,
        const UsdAttribute& usdAttr,
        const UsdTimeCode& usdTime,
        const bool translateMayaDoubleToUsdSinglePrecision)
{
    if (!usdAttr || attrPlug.isNull()) {
        return false;
    }

    bool isAnimated = attrPlug.isDestination();
    if (usdTime.IsDefault() == isAnimated) {
        return true;
    }

    // We perform a similar set of type-infererence acrobatics here as we do up
    // above in GetUsdTypeName(). See the comments there for more detail on a
    // few type-related oddities.

    MObject attrObj(attrPlug.attribute());

    if (attrObj.hasFn(MFn::kEnumAttribute)) {
        MFnEnumAttribute enumAttrFn(attrObj);
        const short enumIndex = attrPlug.asShort();
        const TfToken enumToken(enumAttrFn.fieldName(enumIndex).asChar());
        return usdAttr.Set(enumToken, usdTime);
    }

    MFnNumericData::Type numericDataType;
    MFnData::Type typedDataType;
    MFnUnitAttribute::Type unitDataType;

    _GetMayaAttributeNumericTypedAndUnitDataTypes(attrPlug,
                                                  numericDataType,
                                                  typedDataType,
                                                  unitDataType);

    if (attrObj.hasFn(MFn::kMatrixAttribute)) {
        typedDataType = MFnData::kMatrix;
    }

    switch (typedDataType) {
        case MFnData::kString: {
            MFnStringData stringDataFn(attrPlug.asMObject());
            const std::string usdVal(stringDataFn.string().asChar());
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kMatrix: {
            MFnMatrixData matrixDataFn(attrPlug.asMObject());
            const GfMatrix4d usdVal(matrixDataFn.matrix().matrix);
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kStringArray: {
            MFnStringArrayData stringArrayDataFn(attrPlug.asMObject());
            VtStringArray usdVal(stringArrayDataFn.length());
            for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) {
                usdVal[i] = std::string(stringArrayDataFn[i].asChar());
            }
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kDoubleArray: {
            MFnDoubleArrayData doubleArrayDataFn(attrPlug.asMObject());
            if (translateMayaDoubleToUsdSinglePrecision) {
                VtFloatArray usdVal(doubleArrayDataFn.length());
                for (unsigned int i = 0; i < doubleArrayDataFn.length(); ++i) {
                    usdVal[i] = (float)doubleArrayDataFn[i];
                }
                return usdAttr.Set(usdVal, usdTime);
            } else {
                VtDoubleArray usdVal(doubleArrayDataFn.length());
                for (unsigned int i = 0; i < doubleArrayDataFn.length(); ++i) {
                    usdVal[i] = doubleArrayDataFn[i];
                }
                return usdAttr.Set(usdVal, usdTime);
            }
            break;
        }
        case MFnData::kFloatArray: {
            MFnFloatArrayData floatArrayDataFn(attrPlug.asMObject());
            VtFloatArray usdVal(floatArrayDataFn.length());
            for (unsigned int i = 0; i < floatArrayDataFn.length(); ++i) {
                usdVal[i] = floatArrayDataFn[i];
            }
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kIntArray: {
            MFnIntArrayData intArrayDataFn(attrPlug.asMObject());
            VtIntArray usdVal(intArrayDataFn.length());
            for (unsigned int i = 0; i < intArrayDataFn.length(); ++i) {
                usdVal[i] = intArrayDataFn[i];
            }
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnData::kPointArray: {
            MFnPointArrayData pointArrayDataFn(attrPlug.asMObject());
            if (translateMayaDoubleToUsdSinglePrecision) {
                VtVec3fArray usdVal(pointArrayDataFn.length());
                for (unsigned int i = 0; i < pointArrayDataFn.length(); ++i) {
                    MPoint tmpMayaVal = pointArrayDataFn[i];
                    if (tmpMayaVal.w != 0) {
                        tmpMayaVal.cartesianize();
                    }
                    usdVal[i] = GfVec3f((float)tmpMayaVal[0],
                                        (float)tmpMayaVal[1],
                                        (float)tmpMayaVal[2]);
                }
                return usdAttr.Set(usdVal, usdTime);
            } else {
                VtVec3dArray usdVal(pointArrayDataFn.length());
                for (unsigned int i = 0; i < pointArrayDataFn.length(); ++i) {
                    MPoint tmpMayaVal = pointArrayDataFn[i];
                    if (tmpMayaVal.w != 0) {
                        tmpMayaVal.cartesianize();
                    }
                    usdVal[i] = GfVec3d(tmpMayaVal[0],
                                        tmpMayaVal[1],
                                        tmpMayaVal[2]);
                }
                return usdAttr.Set(usdVal, usdTime);
            }
            break;
        }
        case MFnData::kVectorArray: {
            MFnVectorArrayData vectorArrayDataFn(attrPlug.asMObject());
            if (translateMayaDoubleToUsdSinglePrecision) {
                VtVec3fArray usdVal(vectorArrayDataFn.length());
                for (unsigned int i = 0; i < vectorArrayDataFn.length(); ++i) {
                    MVector tmpMayaVal = vectorArrayDataFn[i];
                    usdVal[i] = GfVec3f((float)tmpMayaVal[0],
                                        (float)tmpMayaVal[1],
                                        (float)tmpMayaVal[2]);
                }
                return usdAttr.Set(usdVal, usdTime);
            } else {
                VtVec3dArray usdVal(vectorArrayDataFn.length());
                for (unsigned int i = 0; i < vectorArrayDataFn.length(); ++i) {
                    MVector tmpMayaVal = vectorArrayDataFn[i];
                    usdVal[i] = GfVec3d(tmpMayaVal[0],
                                        tmpMayaVal[1],
                                        tmpMayaVal[2]);
                }
                return usdAttr.Set(usdVal, usdTime);
            }
            break;
        }
        default:
            break;
    }

    switch (numericDataType) {
        case MFnNumericData::kBoolean: {
            const bool usdVal(attrPlug.asBool());
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnNumericData::kByte:
        case MFnNumericData::kChar: {
            const int usdVal(attrPlug.asChar());
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnNumericData::kShort: {
            const int usdVal(attrPlug.asShort());
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnNumericData::kInt: {
            const int usdVal(attrPlug.asInt());
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnNumericData::k2Short: {
            short tmp1, tmp2;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2);
            return usdAttr.Set(GfVec2i(tmp1, tmp2), usdTime);
            break;
        }
        case MFnNumericData::k2Int: {
            int tmp1, tmp2;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2);
            return usdAttr.Set(GfVec2i(tmp1, tmp2), usdTime);
            break;
        }
        case MFnNumericData::k3Short: {
            short tmp1, tmp2, tmp3;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2, tmp3);
            return usdAttr.Set(GfVec3i(tmp1, tmp2, tmp3), usdTime);
            break;
        }
        case MFnNumericData::k3Int: {
            int tmp1, tmp2, tmp3;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2, tmp3);
            return usdAttr.Set(GfVec3i(tmp1, tmp2, tmp3), usdTime);
            break;
        }
        case MFnNumericData::kFloat: {
            const float usdVal(attrPlug.asFloat());
            return usdAttr.Set(usdVal, usdTime);
            break;
        }
        case MFnNumericData::k2Float: {
            float tmp1, tmp2;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2);
            return usdAttr.Set(GfVec2f(tmp1, tmp2), usdTime);
            break;
        }
        case MFnNumericData::k3Float: {
            float tmp1, tmp2, tmp3;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2, tmp3);
            return _SetVec(usdAttr, GfVec3f(tmp1, tmp2, tmp3), usdTime);
            break;
        }
        case MFnNumericData::kDouble: {
            const double usdVal(attrPlug.asDouble());
            if (translateMayaDoubleToUsdSinglePrecision) {
                return usdAttr.Set((float)usdVal, usdTime);
            } else {
                return usdAttr.Set(usdVal, usdTime);
            }
            break;
        }
        case MFnNumericData::k2Double: {
            double tmp1, tmp2;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2);
            if (translateMayaDoubleToUsdSinglePrecision) {
                return usdAttr.Set(GfVec2f((float)tmp1, (float)tmp2), usdTime);
            } else {
                return usdAttr.Set(GfVec2d(tmp1, tmp2), usdTime);
            }
            break;
        }
        case MFnNumericData::k3Double: {
            double tmp1, tmp2, tmp3;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2, tmp3);
            if (translateMayaDoubleToUsdSinglePrecision) {
                return _SetVec(usdAttr,
                               GfVec3f((float)tmp1,
                                       (float)tmp2,
                                       (float)tmp3),
                               usdTime);
            } else {
                return _SetVec(usdAttr, GfVec3d(tmp1, tmp2, tmp3), usdTime);
            }
            break;
        }
        case MFnNumericData::k4Double: {
            double tmp1, tmp2, tmp3, tmp4;
            MFnNumericData numericDataFn(attrPlug.asMObject());
            numericDataFn.getData(tmp1, tmp2, tmp3, tmp4);
            if (translateMayaDoubleToUsdSinglePrecision) {
                return _SetVec(usdAttr,
                               GfVec4f((float)tmp1,
                                       (float)tmp2,
                                       (float)tmp3,
                                       (float)tmp4),
                               usdTime);
            } else {
                return _SetVec(usdAttr,
                               GfVec4d(tmp1, tmp2, tmp3, tmp4),
                               usdTime);
            }
            break;
        }
        default:
            break;
    }

    switch (unitDataType) {
        case MFnUnitAttribute::kAngle:
        case MFnUnitAttribute::kDistance:
            if (translateMayaDoubleToUsdSinglePrecision) {
                const float usdVal(attrPlug.asFloat());
                return usdAttr.Set(usdVal, usdTime);
            } else {
                const double usdVal(attrPlug.asDouble());
                return usdAttr.Set(usdVal, usdTime);
            }
            break;
        default:
            break;
    }

    return false;
}
Beispiel #20
0
	void swap(MPoint & x,MPoint &y)
	{
		std::cout<<"enter std  template special function \n";
		x.swap(y);	//自定义函数
	}
Beispiel #21
0
/*****************************************************
**
**   Painter   ---   drawSingleMStringLine
**
******************************************************/
void Painter::drawSingleMStringLine( const MRect &r, MString &f, const int& align )
{
	assert( f.formattedLines.size() == 0 );
	wxString s;
	MPoint p;
	Lang lang( writercfg );
	wxFont oldFont = getCurrentFont();
	const int drawalign = Align::Left + Align::VCenter;
	SheetFormatter formatter( writercfg );

	if ( ! f.isEmpty() && ( f.size.real() == 0 ||  f.size.imag() == 0 ))
	{
		printf( "WARN: size not set\n" );
		f.size = getTextExtent( f );
	}

	//printf( "PAINT -- --- - - - - x %f y %f w %f h %f SIZE x %f y %f\n", r.x, r.y, r.width, r.height, size.real(), size.imag() );
	//printf( " ----- %s\n", str2char( formatter.fragment2PlainText( f )));

	double x0 = r.x;
	double y0 = r.y;

	if ( align & Align::HCenter )
	{
		x0 += .5 * ( r.width - f.size.real());
	}
	else if ( align & Align::Right )
	{
		x0 = x0 + r.width - f.size.real();
	}

	// offset for subscriptum and superscriptum
	const double yoffset = .5 * f.size.imag();

	double yy = y0; // + .5 * ( r.height - size.imag());
	for( list<MToken>::const_iterator iter = f.tokens.begin(); iter != f.tokens.end(); iter++ )
	{
		switch ( iter->fontFormat )
		{
			case TTFF_SUBSCRPTUM:
				yy = y0 + yoffset;
			break;
			case TTFF_SUPERSCRPTUM:
				yy = y0 - yoffset;
			break;
			case TTFF_NORMAL:
			default:
				yy = y0;
			break;
		}

		setFont( oldFont );

		wxChar symbol = 0;
		SymbolProvider sp( writercfg );
		switch ( iter->entity )
		{
			case TTSE_PLANET:
				if ( writercfg->planetSymbols ) symbol = sp.getPlanetCode( (ObjectId)iter->entityId );
				if ( ! symbol || symbol == SYMBOL_CODE_ERROR )
					s = formatter.getObjectNamePlain( (ObjectId)iter->entityId, iter->textFormat, iter->vedic );
			break;
			case TTSE_SIGN:
				if ( writercfg->signSymbols ) symbol = sp.getSignCode( (Rasi)iter->entityId );
				if ( ! symbol ) s = lang.getSignName( (Rasi)iter->entityId, iter->textFormat ); //, writercfg->vedicSignNames );
			break;
			case TTSE_ASPECT:
				symbol = SymbolProvider().getAspectCode( (ASPECT_TYPE)iter->entityId );
				if ( ! symbol ) s = AspectExpert::getAspectShortDescription( (int)iter->entityId );
			break;
			case TTSE_DIRECTION:
				symbol = sp.getRetroCode( (MOVING_DIRECTION)iter->entityId );
				if ( ! symbol ) s = wxT( "R" );
			break;
			default:
				symbol = 0;
				s = iter->text;
			break;
		}
		if ( symbol && symbol != SYMBOL_CODE_ERROR )
		{
			const int pointSize = oldFont.GetPointSize();
			setFont( *FontProvider::get()->getFontBySize( FONT_GRAPHIC_SYMBOLS, pointSize ));
			drawTextFormatted( MRect( x0, yy, r.width, r.height ), symbol, drawalign );
			p = getTextExtent( symbol );
		}
		else
		{
			drawTextFormatted( MRect( x0, yy, r.width, r.height ), s, drawalign );
			p = getTextExtent( s );
		}

		x0 += p.real();
	}
}
Beispiel #22
0
/*****************************************************
**
**   Painter   ---   drawLine
**
******************************************************/
void Painter::drawLine( const MPoint &p1, const MPoint &p2 )
{
	drawLine( p1.real(), p1.imag(), p2.real(), p2.imag() );
}
	bool gpuCacheIsectUtil::getClosestPointOnTri(const MPoint &toThisPoint, const MPoint &pt1, const MPoint &pt2, const MPoint &pt3, MPoint &theClosestPoint, double &currDist) 
	{
		double		sum, a, b, c, len, dist;
		MMatrix mat;
		mat.setToIdentity();
		mat[2][0] = mat[2][1] = mat[2][2] = 1.;

		MVector v = toThisPoint - pt1;
		MVector v12 = pt2 - pt1;
		MVector v13 = pt3 - pt1;
		MVector norm = v12 ^ v13;
		len = norm * norm;
		if (len < 1.175494351e-38F) return false;
		len = ( norm * v ) / len;

		MPoint pnt = toThisPoint - len * norm;

		// Do a quick test first
		if (pnt.distanceTo(toThisPoint) >= currDist)
			return false;

		int i, j;				// Find best plane to project to
		if (fabs(norm[0]) > fabs(norm[1]))
		{
			if (fabs(norm[0]) > fabs(norm[2]))
			{
				i = 1; j = 2;
			}
			else
			{
				i = 0; j = 1;
			}
		}
		else
		{
			if (fabs(norm[1]) > fabs(norm[2]))
			{
				i = 0; j = 2;
				// i = 2; j = 0;
			}
			else
			{
				i = 0; j = 1;
			}
		}

		mat[0][0] = pt1[i]; mat[0][1] = pt2[i]; mat[0][2] = pt3[i]; 
		mat[1][0] = pt1[j]; mat[1][1] = pt2[j]; mat[1][2] = pt3[j]; 

		MMatrix	matInv = mat.inverse();
		MPoint abc(pnt[i], pnt[j], 1, 0);

		abc = matInv * abc;
		// Now abc is the barycentric coordinates of pnt
		// clip to inside triangle

		if (abc[0]<0) { // a < 0
			if (abc[1]<0) { // b < 0
				a = b = 0;
				c = 1;
			} else if (abc[2]<0) { // c < 0
				a = c = 0;
				b = 1;
			} else {
				a = 0;
				// c = BP dot BC / BC square;
				MVector v23 = pt3 - pt2; // BC
				MVector vp =  toThisPoint - pt2;  // BP

				c = ( vp * v23 ) / ( v23[0]*v23[0] + v23[1]*v23[1] + v23[2]*v23[2] );
				if (c<0) c = 0; else if (c>1) c = 1;
				b = 1 - c;
			}
		} else if (abc[1]<0) { // b < 0
			if (abc[2]<0) { // c < 0
				b = c = 0;
				a = 1;
				//} else if (abc[0]<0) { // a < 0
				//	b = a = 0;	// commented-code for optimization
				//	c = 1;		// leaving it in for readability (cyclic variations)
			} else {
				b = 0;
				// a = CP dot CA / CA square;
				MVector v31 = pt1 - pt3; // CA
				MVector vp =  toThisPoint - pt3;  // CP

				a = ( vp * v31 ) / ( v31[0]*v31[0] + v31[1]*v31[1] +v31[2]*v31[2] );
				if (a<0) a = 0; else if (a>1) a = 1;
				c = 1 - a;
			} 
		} else if (abc[2]<0) { // c < 0
			//if (abc[1]<0) { // b < 0
			//	c = b = 0;
			//	a = 1;
			//} else if (abc[0]<0) { // a < 0
			//	c = a = 0;
			//	b = 1;	// commented-code for optimization
			//} else {	// leaving it in for readability (cyclic variations)
			c = 0;
			// b = AP dot AB / AB square;
			//DIFF(v23, pt3, pt2); // AB
			MVector vp =  toThisPoint - pt1;  // AP

			b = ( vp * v12 ) / ( v12[0]*v12[0] + v12[1]*v12[1] + v12[2]*v12[2] );
			if (b<0) b = 0; else if (b>1) b = 1;
			a = 1 - b;
			//}
		} else {
			if (abc[0]>0) a = abc[0]; else a = 0;
			if (abc[1]>0) b = abc[1]; else b = 0;
			if (abc[2]>0) c = abc[2]; else c = 0;
		}
		sum = a+b+c;
		a /= sum ; b /= sum ; c /= sum ; 
		pnt = a * pt1 + b * pt2 + c * pt3;
		dist = pnt.distanceTo(toThisPoint);
		if ( dist < currDist)
		{			
			// Now it's really closer, keep it
			currDist = dist;
			theClosestPoint = pnt;
			return true;
		}
		return false;
	}
	// used when ray does not intersect object
	// to account for perspective, all edges are flattened onto 
	// a plane defined by the raySource and rayDirection
	double gpuCacheIsectUtil::getEdgeSnapPointOnBox(const MPoint& raySource, const MVector& rayDirection, const MBoundingBox& bbox, MPoint& snapPoint){
		//if ray intersects bbox
		MPoint boxIntersectionPt;
		if(firstRayIntersection(bbox.min(), bbox.max(), raySource, rayDirection, NULL, &boxIntersectionPt))
		{
			//	ray intersects bounding box, so snapPoint is
			//	closest hit on the outside of the box
			//  and distance to box is 0 (for snapping purposes)
			snapPoint = boxIntersectionPt;
			return 0.0;
		}

		MPointArray verts;
		MPoint vmin = bbox.min();
		MPoint vmax = bbox.max();

		verts.insert(vmin,0);
		verts.insert(MPoint(vmax[0],vmin[1],vmin[2]),1);
		verts.insert(MPoint(vmax[0],vmax[1],vmin[2]),2);
		verts.insert(MPoint(vmin[0],vmax[1],vmin[2]),3);
		verts.insert(MPoint(vmin[0],vmin[1],vmax[2]),4);
		verts.insert(MPoint(vmax[0],vmin[1],vmax[2]),5);
		verts.insert(vmax,6);
		verts.insert(MPoint(vmin[0],vmax[1],vmax[2]),7);

		int edgeIndices[12][2]={{0,1},{1,2},{2,3},{3,0},{4,5},{5,6},{6,7},{7,4},{0,4},{1,5},{3,7},{2,6}};

		double minDistRect = std::numeric_limits<double>::max();
		
		for(int edge=0; edge<12;edge++){
			MPoint vertex1Org = verts[edgeIndices[edge][0]];
			MPoint vertex2Org = verts[edgeIndices[edge][1]];
			
			double coef_plane = rayDirection * raySource;
			double d = coef_plane - rayDirection * vertex1Org;
			MPoint vertex1 = vertex1Org + rayDirection * d;
			d = coef_plane - rayDirection * vertex2Org;
			MPoint vertex2 = vertex2Org + rayDirection * d;

			MVector edgeDir = vertex2 - vertex1;

			if (edgeDir.length()<0.0000001){
				double dist = vertex1.distanceTo(raySource);
				if (dist < minDistRect) {
					minDistRect = dist;
					snapPoint = vertex1Org;
				}
			} else {
				MPoint edgePt;
				// Compute the closest point from the edge to cursor Ray.
				double percent = gpuCacheIsectUtil::getClosestPointOnLine(raySource, vertex1, vertex2, edgePt);
				double dist = edgePt.distanceTo(raySource);
				if (dist < minDistRect) {
					minDistRect = dist;
					snapPoint =  (vertex1Org + percent * (vertex2Org - vertex1Org));
				}
			}
		}
		
		return minDistRect;
	}
MStatus clusterWeightFunctionCmd::performWeighting(MFnWeightGeometryFilter &cluster,
										   MDagPath &dagPath,
										   MObject &component)
{
	MStatus status;
	MItGeometry geomIter(dagPath, component, &status);
	MObject comp;
	MObjectArray compArray;
	MDoubleArray weightArray;
	double weight = 0.0;

	if (MS::kSuccess == status) {
		for (; !geomIter.isDone(); geomIter.next()) {
			comp = geomIter.component();

			MPoint pnt = geomIter.position(MSpace::kWorld, &status);

			if (MS::kSuccess != status) {
				return MS::kFailure;
			}

			if (kSine == fEffectType) {
				weight = sin(pnt.x)*sin(pnt.z);
			}
			else if (kSineDistance == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = sin(distance);
			}
			else if (kSineDistance2 == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = sin(distance*distance);
			}
			else if (kDistanceSineDistance == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = distance*sin(distance);
			}
			else if (kInverseDistanceSineDistance == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = sin(distance)/(distance+1);
			}
			else if (kDistance == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = distance;
			}
			else if (kDistance2 == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = distance*distance;
			}
			else if (kDistance3 == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = distance*distance*distance;
			}
			else if (kDistance4 == fEffectType) {
				double distance = pnt.distanceTo(MPoint::origin);
				weight = distance*distance*distance*distance;
			}
			else if (kInverseDistance == fEffectType) {
				double dist = pnt.distanceTo(MPoint::origin) + 1;
				weight = 1/(dist);
			}
			else if (kInverseDistance2 == fEffectType) {
				double dist = pnt.distanceTo(MPoint::origin) + 1;
				weight = 1/(dist*dist);
			}
			else if (kInverseDistance3 == fEffectType) {
				double dist = pnt.distanceTo(MPoint::origin) + 1;
				weight = 1/(dist*dist*dist);
			}
			else if (kInverseDistance4 == fEffectType) {
				double dist = pnt.distanceTo(MPoint::origin) + 1;
				weight = 1/(dist*dist*dist*dist);
			}

			compArray.append(comp);
			weightArray.append(weight);
		}

		unsigned length = compArray.length();
		for (unsigned i = 0; i < length; i++) {
			cluster.setWeight(dagPath, compArray[i], (float) weightArray[i]);
		}

		return MS::kSuccess;
	} else
		return MS::kFailure;
}
Beispiel #26
0
void highOrderTools::computeStraightSidedPositions()
{
  _clean();
  // compute straigh sided positions that are actually X,Y,Z positions
  // that are NOT always on curves and surfaces

  // points classified on model vertices shall not move !
  for(GModel::viter it = _gm->firstVertex(); it != _gm->lastVertex(); ++it){
    if ((*it)->points.size()){
      MPoint *p = (*it)->points[0];
      MVertex *v = p->getVertex(0);
      _straightSidedLocation [v] = SVector3((*it)->x(),(*it)->y(),(*it)->z());
      _targetLocation [v] = SVector3((*it)->x(),(*it)->y(),(*it)->z());
    }
  }

  //  printf("coucou2\n");
  // compute stright sided positions of vertices that are classified on model edges
  for(GModel::eiter it = _gm->firstEdge(); it != _gm->lastEdge(); ++it){
    for (unsigned int i=0;i<(*it)->lines.size();i++){
      MLine *l = (*it)->lines[i];
      int N = l->getNumVertices()-2;
      SVector3 p0((*it)->lines[i]->getVertex(0)->x(),
          (*it)->lines[i]->getVertex(0)->y(),
          (*it)->lines[i]->getVertex(0)->z());
      SVector3 p1((*it)->lines[i]->getVertex(1)->x(),
          (*it)->lines[i]->getVertex(1)->y(),
          (*it)->lines[i]->getVertex(1)->z());

      for (int j=1;j<=N;j++){
        const double xi = (double)(j)/(N+1);
        //	printf("xi = %g\n",xi);
        const SVector3 straightSidedPoint   = p0 *(1.-xi) + p1*xi;
        MVertex *v = (*it)->lines[i]->getVertex(j+1);
        if (_straightSidedLocation.find(v) == _straightSidedLocation.end()){
          _straightSidedLocation   [v] = straightSidedPoint;
          _targetLocation[v] = SVector3(v->x(),v->y(),v->z());
        }
      }
    }
  }

  //  printf("coucou3\n");
  // compute stright sided positions of vertices that are classified on model faces
  for(GModel::fiter it = _gm->firstFace(); it != _gm->lastFace(); ++it){
    for (unsigned int i=0;i<(*it)->mesh_vertices.size();i++){
      MVertex *v = (*it)->mesh_vertices[i];
      _targetLocation[v] = SVector3(v->x(),v->y(),v->z());
    }

    for (unsigned int i=0;i<(*it)->triangles.size();i++){
      MTriangle *t = (*it)->triangles[i];
      MFace face = t->getFace(0);
      const nodalBasis* fs = t->getFunctionSpace();
      for (int j=0;j<t->getNumVertices();j++){
        if (t->getVertex(j)->onWhat() == *it){
          const double t1 = fs->points(j, 0);
          const double t2 = fs->points(j, 1);
          SPoint3 pc = face.interpolate(t1, t2);
          _straightSidedLocation [t->getVertex(j)] =
            SVector3(pc.x(),pc.y(),pc.z());
        }
      }
    }
    for (unsigned int i=0;i<(*it)->quadrangles.size();i++){
      //      printf("coucou quad %d\n",i);
      MQuadrangle *q = (*it)->quadrangles[i];
      MFace face = q->getFace(0);
      const nodalBasis* fs = q->getFunctionSpace();
      for (int j=0;j<q->getNumVertices();j++){
        if (q->getVertex(j)->onWhat() == *it){
          const double t1 = fs->points(j, 0);
          const double t2 = fs->points(j, 1);
          SPoint3 pc = face.interpolate(t1, t2);
          _straightSidedLocation [q->getVertex(j)] =
            SVector3(pc.x(),pc.y(),pc.z());
        }
      }
    }
  }

  for(GModel::riter it = _gm->firstRegion(); it != _gm->lastRegion(); ++it){
    for (unsigned int i=0;i<(*it)->mesh_vertices.size();i++){
      MVertex *v = (*it)->mesh_vertices[i];
      _targetLocation[v] = SVector3(v->x(),v->y(),v->z());
    }
    for (unsigned int i=0;i<(*it)->tetrahedra.size();i++){
      _dim = 3;
      MTetrahedron *t = (*it)->tetrahedra[i];
      MTetrahedron t_1 ((*it)->tetrahedra[i]->getVertex(0),
          (*it)->tetrahedra[i]->getVertex(1),
          (*it)->tetrahedra[i]->getVertex(2),
          (*it)->tetrahedra[i]->getVertex(3));
      const nodalBasis* fs = t->getFunctionSpace();
      for (int j=0;j<t->getNumVertices();j++){
        if (t->getVertex(j)->onWhat() == *it){
          double t1 = fs->points(j, 0);
          double t2 = fs->points(j, 1);
          double t3 = fs->points(j, 2);
          SPoint3 pc; t_1.pnt(t1, t2, t3,pc);
          _straightSidedLocation [t->getVertex(j)] =
            SVector3(pc.x(),pc.y(),pc.z());
        }
      }
    }
    for (unsigned int i=0;i<(*it)->hexahedra.size();i++){
      _dim = 3;
      MHexahedron *h = (*it)->hexahedra[i];
      MHexahedron h_1 ((*it)->hexahedra[i]->getVertex(0),
          (*it)->hexahedra[i]->getVertex(1),
          (*it)->hexahedra[i]->getVertex(2),
          (*it)->hexahedra[i]->getVertex(3),
          (*it)->hexahedra[i]->getVertex(4),
          (*it)->hexahedra[i]->getVertex(5),
          (*it)->hexahedra[i]->getVertex(6),
          (*it)->hexahedra[i]->getVertex(7));
      const nodalBasis* fs = h->getFunctionSpace();
      for (int j=0;j<h->getNumVertices();j++){
        if (h->getVertex(j)->onWhat() == *it){
          double t1 = fs->points(j, 0);
          double t2 = fs->points(j, 1);
          double t3 = fs->points(j, 2);
          SPoint3 pc; h_1.pnt(t1, t2, t3,pc);
          _straightSidedLocation [h->getVertex(j)] =
            SVector3(pc.x(),pc.y(),pc.z());
        }
      }
    }
  }

  Msg::Info("highOrderTools has been set up : %d nodes are considered",
            _straightSidedLocation.size());
}
Beispiel #27
0
/*****************************************************
**
**   BasicVedicChart   ---   getFieldForScreenPos
**
******************************************************/
uint BasicVedicChart::getFieldForScreenPos( const MPoint &p )
{
	//printf( "BasicVedicChart::getFieldForScreenPos %f %f count %d\n", p.real(), p.imag(), field_count );
	for( uint i = 0; i < field_count && i < fields.size(); i++ )
	{
		//printf( "BasicVedicChart::getFieldForScreenPos %f %f RECT %s\n", p.x, p.y, str2char( fields[i].rect.toString()) );
		if ( pointInRect( p, fields[i].rect ))
		{
			const double x = ( p.real() - fields[i].rect.x ) / fields[i].rect.width;
			const double y = ( p.imag() - fields[i].rect.y ) / fields[i].rect.height;

			switch( fields[i].fieldtype )
			{
				case FIELD_TYPE_FULL: // all fields in south indian chart, sbc, fixed rasis in east indian chart
					return i;
				break;

				case FIELD_TYPE_NE: // east: taurus and sag
					if ( x >= y ) return i;
				break;

				case FIELD_TYPE_SW: // east: gemini and scorpio
					if ( x <= y ) return i;
				break;

				case FIELD_TYPE_NW: // east: leo and pisces
					if ( 1 - x >= y ) return i;
				break;

				case FIELD_TYPE_SE: // east: virgo and aquarius
					if ( 1 - x <= y ) return i;
				break;

				case FIELD_TYPE_N: // north: houses 2 and 12
					if ( fabs( x - .5 ) <= .5 * ( 1 - y )) return i;
				break;

				case FIELD_TYPE_W: // north: houses 3 and 5
					if ( fabs( y - .5 ) <= .5 * ( 1 - x )) return i;
				break;

				case FIELD_TYPE_S: // north: houses 6 and 8
					if ( fabs( x - .5 ) <= .5 * y ) return i;
				break;

				case FIELD_TYPE_E: // north: houses 9 and 11
					if ( fabs( y - .5 ) <= .5 * x ) return i;
				break;

				case FIELD_TYPE_DIAMOND:// north: houses 1: 4: 7: 10
					if ( .5 - fabs( x - .5 ) >= fabs( y - .5 )) return i;
				break;

				default:
					printf( "BasicVedicChart::getFieldForScreenPos WARN: invalid field type %d at postion %u\n", fields[i].fieldtype, i );
				break;
			}
		}
	}
	//return UINT_FOR_NOT_FOUND;
	return UINT_FOR_OUTSIDE;
}