Beispiel #1
0
ObjAxis3ImpGL::ObjAxis3ImpGL(Point3f origin, float size, bool bShow)
{
	m_origin = origin;
	m_axisX.reset(ObjFactoryImpGL::GetInstance()->CreateLine(origin, origin.AddX(size), 0xAAff0000));
	m_axisY.reset(ObjFactoryImpGL::GetInstance()->CreateLine(origin, origin.AddY(size), 0xAA00ff00));
	m_axisZ.reset(ObjFactoryImpGL::GetInstance()->CreateLine(origin, origin.AddZ(size), 0xAAffff00));
}
Beispiel #2
0
  /// Return false if the particle is dead
  bool advance(float dt)
  {
    if (curtime >= t0 + maxlife)
			return false;

    // gravity
	vit.z() -= gravity * dt;

	// update
	pos += vit * dt;

	// collision
	if (pos.z() < 0)
	{
		float dv = vit.z();

		pos.z() = 0;
		if (dv < 0)
		{
			vit.z() = -0.8f * vit.z();
			last_col = curtime; //-d;
		}
	}

	// color
	float c = curtime - last_col;

	if (c > 1)
		c = 1;

	color.x() = 1 - c;
	return true;
  }
Beispiel #3
0
void Polygon::rotate(const Point3f& p1, const Point3f& p2, float a) {
    Point3f u = p2 - p1;
    u /= u.length();
    float cosa = cos(a / 180 * PI);
    float sina = sin(a / 180 * PI);
    float onec = 1 - cosa;
    Matrix rot(3, 3);
    rot[0][0] = u.x * u.x * onec + cosa;
    rot[0][1] = u.x * u.y * onec - u.z * sina;
    rot[0][2] = u.x * u.z * onec + u.y * sina;
    rot[1][0] = u.y * u.x * onec + u.z * sina;
    rot[1][1] = u.y * u.y * onec + cosa;
    rot[1][2] = u.z * u.y * onec + u.x * sina;
    rot[2][0] = u.x * u.z * onec + u.y * sina;
    rot[2][1] = u.y * u.z * onec - u.x * sina;
    rot[2][2] = u.z * u.z * onec + cosa;
    for (int i = 0; i < _vertices.size(); i++) {
        Point3f p = _vertices[i] - p1;
        Matrix v(3, 1);
        v[0][0] = p.x; v[1][0] = p.y; v[2][0] = p.z;
        Matrix r = rot * v;
        p.x = r[0][0]; p.y = r[1][0]; p.z = r[2][0];
        _vertices[i] = p + p1;
    }
}
void GlobalFun::find_original_neighbors(CGrid::iterator starta, CGrid::iterator enda, 
	CGrid::iterator startb, CGrid::iterator endb, double radius)
{	

	double radius2 = radius*radius;
	double iradius16 = -4/radius2;
	const double PI = 3.1415926;

	for(CGrid::iterator dest = starta; dest != enda; dest++) 
	{
		CVertex &v = *(*dest);

		Point3f &p = v.P();
		for(CGrid::iterator origin = startb; origin != endb; origin++)
		{
			CVertex &t = *(*origin);

			Point3f &q = t.P();
			Point3f diff = p-q;

			double dist2 = diff.SquaredNorm();

			if(dist2 < radius2) 
			{                          
				v.original_neighbors.push_back((*origin)->m_index);
			}
		}
	}
}
std::vector<float> CalBarycentric(const std::vector<Point2f> &points, Point2f tf)
{
	Point3f p1 = Point3f(points[0].x, points[0].y, 0.0f);
	Point3f p2 = Point3f(points[1].x, points[1].y, 0.0f);
	Point3f p3 = Point3f(points[2].x, points[2].y, 0.0f);

	Point3f f(tf.x, tf.y, 0.0f);
	Point3f f1 = p1 - f;
	Point3f f2 = p2 - f;
	Point3f f3 = p3 - f;

	Point3f va = (p1 - p2).cross(p1 - p3);
	Point3f va1 = f2.cross(f3);
	Point3f va2 = f3.cross(f1);
	Point3f va3 = f1.cross(f2);

	float a = CalLength(va);
	float a1 = CalLength(va1) / a * sign(va.dot(va1));
	float a2 = CalLength(va2) / a * sign(va.dot(va2));
	float a3 = CalLength(va3) / a * sign(va.dot(va3));

	std::vector<float> w;
	w.push_back(a1);
	w.push_back(a2);
	w.push_back(a3);
	return w;
}
void WLOP::computeRepulsionTerm(CMesh* samples)
{
	double repulsion_power = para->getDouble("Repulsion Power");
	bool need_density = para->getBool("Need Compute Density");
	double radius = para->getDouble("CGrid Radius"); 

	double radius2 = radius * radius;
	double iradius16 = -para->getDouble("H Gaussian Para")/radius2;

	cout << endl<< endl<< "Sample Neighbor Size:" << samples->vert[0].neighbors.size() << endl<< endl;
	for(int i = 0; i < samples->vert.size(); i++)
	{
		CVertex& v = samples->vert[i];
		for (int j = 0; j < v.neighbors.size(); j++)
		{
			CVertex& t = samples->vert[v.neighbors[j]];
			Point3f diff = v.P() - t.P();

			double dist2  = diff.SquaredNorm();
			double len = sqrt(dist2);
			if(len <= 0.001 * radius) len = radius*0.001;

			double w = exp(dist2*iradius16);
			double rep = w * pow(1.0 / len, repulsion_power);

			if (need_density)
			{
				rep *= samples_density[t.m_index];
			}

			repulsion[i] += diff * rep;  
			repulsion_weight_sum[i] += rep;
		}
	}
}
Beispiel #7
0
static void ioMB_exportSkeleton(const BrfSkeleton &s){
  for (int i=0; i<(int)s.bone.size(); i++) {
    const BrfBone &bone(s.bone[i]);

    fprintf(f,"createNode joint -n \"%s\" ",substitute(bone.name,'.','_'));
    if (bone.attach!=-1)
    fprintf(f,"-p \"%s\" ",substitute(s.bone[bone.attach].name,'.','_'));
    fprintf(f,";\n");

    float *abc;
    abc = matrix2euler(s.getRotationMatrix( i ).transpose() );
    Point3f t = bone.t;
    if (bone.attach==-1) { float tmp=t[1]; t[1]=t[2]; t[2]=tmp;}
    t.X()*=-1;
    t.Y()*=-1;
    t*=SCALE;

    fprintf(f,
      "\taddAttr -ci true -sn \"liw\" -ln \"lockInfluenceWeights\" -bt \"lock\" -min 0 -max 1 -at \"bool\";\n"
      "\tsetAttr \".uoc\" yes;\n"
      "\tsetAttr \".t\" -type \"double3\" %f %f %f ;\n"
      "\tsetAttr \".r\" -type \"double3\" %f %f %f ;\n"
      "\tsetAttr \".mnrl\" -type \"double3\" -360 -360 -360 ;\n"
      "\tsetAttr \".mxrl\" -type \"double3\" 360 360 360 ;\n",
      -t[0],t[2],-t[1],
      abc[0]*180/M_PI,abc[1]*180/M_PI,abc[2]*180/M_PI
    );

    //qDebug()<< "[" << i << "]: abc" << abc[0]*180/M_PI << abc[1]*180/M_PI <<abc[2]*180/M_PI <<"\n";
  }
}
Beispiel #8
0
	WavefrontOBJ(const PropertyList &propList) {
		typedef boost::unordered_map<OBJVertex, uint32_t, OBJVertexHash> VertexMap;

		/* Process the OBJ-file line by line */	
		QString filename = propList.getString("filename");
		QFile input(filename);
		if (!input.open(QIODevice::ReadOnly | QIODevice::Text))
			throw NoriException(QString("Cannot open \"%1\"").arg(filename));

		Transform trafo = propList.getTransform("toWorld", Transform());

		cout << "Loading \"" << qPrintable(filename) << "\" .." << endl;
		m_name = filename;

		QTextStream stream(&input);
		QTextStream line;
		QString temp, prefix;

		std::vector<Point3f>   positions;
		std::vector<Point2f>   texcoords;
		std::vector<Normal3f>  normals;
		std::vector<uint32_t>  indices;
		std::vector<OBJVertex> vertices;
		VertexMap vertexMap;

		while (!(temp = stream.readLine()).isNull()) {
			line.setString(&temp);

			line >> prefix;
			if (prefix == "v") {
				Point3f p;
				line >> p.x() >> p.y() >> p.z();
				p = trafo * p;
				positions.push_back(p);
			} else if (prefix == "vt") {
Beispiel #9
0
	/**
	 * \brief Evaluate sigma_t(p), where 'p' is given in local coordinates
	 *
	 * You may assume that the maximum value returned by this function is
	 * equal to 'm_densityMultiplier'
	 */
	float lookupSigmaT(const Point3f &_p) const {
		Point3f p  = _p.cwiseProduct(m_resolution.cast<float>()),
				pf = Point3f(std::floor(p.x()), std::floor(p.y()), std::floor(p.z()));
		Point3i p0 = pf.cast<int>();

		if ((p0.array() < 0).any() || (p0.array() >= m_resolution.array() - 1).any())
			return 0.0f;

		size_t row    = m_resolution.x(),
		       slab   = row * m_resolution.y(),
		       offset = p0.z()*slab + p0.y()*row + p0.x();

		const float
			d000 = m_data[offset],
			d001 = m_data[offset + 1],
			d010 = m_data[offset + row],
			d011 = m_data[offset + row + 1],
			d100 = m_data[offset + slab],
			d101 = m_data[offset + slab + 1],
			d110 = m_data[offset + slab + row],
			d111 = m_data[offset + slab + row + 1];

		Vector3f w1 = p-pf, w0 = (1 - w1.array()).matrix();

		/* Trilinearly interpolate */
		return (((d000 * w0.x() + d001 * w1.x()) * w0.y() +
		         (d010 * w0.x() + d011 * w1.x()) * w1.y()) * w0.z() +
		        ((d100 * w0.x() + d101 * w1.x()) * w0.y() +
		         (d110 * w0.x() + d111 * w1.x()) * w1.y()) * w1.z()) * m_densityMultiplier;
	}
Beispiel #10
0
void GetRandPlane(Box3f &bb, Plane3f &plane)
{
    Point3f planeCenter = bb.Center();
    Point3f planeDir = Point3f(-0.5f+float(rand())/RAND_MAX,-0.5f+float(rand())/RAND_MAX,-0.5f+float(rand())/RAND_MAX);
    planeDir.Normalize();

    plane.Init(planeCenter+planeDir*0.3f*bb.Diag()*float(rand())/RAND_MAX,planeDir);
}
vector<Point2f> findCorner(const Mat& img, int idx)
{
	stringstream ss;
	ss << idx;
	string iname = ss.str();

	Mat img_gray, d_edges;
	Mat line1 = img.clone(), line2 = img.clone(), line3 = img.clone();
	Size imgSize = img.size();
	cvtColor(img, img_gray, CV_BGR2GRAY);
	//GaussianBlur(img_gray, img_gray, Size(3, 3), 0, 0);
	// edges detector
	Canny(img_gray, d_edges, 50, 300);
	imwrite("imgEdge" + iname + ".jpg", d_edges);

	vector<Vec2f> lines;
	// hough lines detector
	HoughLines(d_edges, lines, 1, CV_PI/180, 50);
	line1 = drawHoughLines(lines, img);
	imwrite("imgSlines" + iname + ".jpg", line1);

	VHLINE vh;
	vector<Vec2f> vlines, hlines;
	vh = divideVHLines(lines);
	
	// sort two directional lines
	sort(vh.vlines.begin(), vh.vlines.end(), sortVLines);
	sort(vh.hlines.begin(), vh.hlines.end(), sortHLines);

	// get unique lines
	vlines = groupLines(vh.vlines, imgSize, 15.0);
	hlines = groupLines(vh.hlines, imgSize, 15.0);

	line2 = drawHoughLines(vlines, img);
	line3 = drawHoughLines(hlines, line2);
	imwrite("imglines" + iname + ".jpg", line3);

	vector<Point2f> corners;

	// get two orthogonal lines' intersection as corners
	for(size_t i = 0; i < hlines.size(); i++)
	{
		Point3d hline = getHoughHC(hlines[i]);
		for(size_t j = 0; j < vlines.size(); j++)
		{
			Point3f vline = getHoughHC(vlines[j]);
			Point3f corner = vline.cross(hline);
			normHC(corner);
			corners.push_back(Point2d(corner.x, corner.y));
		}
	}

	// refine corners
	cornerSubPix(img_gray, corners, Size(15,15), Size(-1,-1),
		TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 0.01));

	return corners;
}
void GraphicsPainter::drawSphere(const Point3f &center, float radius)
{
    glPushMatrix();
    glTranslated(center.x(), center.y(), center.z());

    drawSphere(radius);

    glPopMatrix();
}
Beispiel #13
0
// kernal that produce ray direction texture
void PhotonMapperGPU::EyeKernel()
{
#ifndef STUB_PHOTONMAPPERGPU
	// figure out necessary eye vectors
	Vector3f nn, vv, uu;
//	nn.set(eyePos.x - look.x, eyePos.y - look.y, eyePos.z - look.z); // make n
//	uu.set(up.cross(nn)); // make u = up X n
//	nn.normalize(); uu.normalize(); // make them unit length
//	vv.set(nn.cross(uu));  // make v =  n X u
 

    nn = m_pCamera->N();
    vv = m_pCamera->V();
    uu = m_pCamera->U();
    Point3f eyePos = m_pCamera->GetEye();
	// firgure out world width and height
    float sH = m_pCamera->GetNearClipPlane() * tan( m_pCamera->GetViewAngle() * (3.1415/360));
    float sW = sH * m_pCamera->GetAspect();

//	cout << eyePos.x << " " << eyePos.y << " " << eyePos.z << endl;

//	cout << sH << " " << sW << endl;

    CShader& ray = m_ShaderManager->GetShader(RAY);

    CGparameter& n = ray.GetNamedParameter("IN2.n");
	cgGLSetParameter3f(n, nn.X(), nn.Y(), nn.Z());

    CGparameter& v = ray.GetNamedParameter("IN2.v");
	cgGLSetParameter3f(v, vv.X(), vv.Y(), vv.Z());

    CGparameter& u = ray.GetNamedParameter("IN2.u");
	cgGLSetParameter3f(u, uu.X(), uu.Y(), uu.Z());

    CGparameter& view = ray.GetNamedParameter("IN2.view");
	cgGLSetParameter2f(view, m_pixelCols, m_pixelRows);

    CGparameter& world = ray.GetNamedParameter("IN2.world");
	cgGLSetParameter2f(world, sW, sH);
    
    CGparameter& nearDist = ray.GetNamedParameter("IN2.nearDist");
    cgGLSetParameter1f(nearDist, m_pCamera->GetNearClipPlane());

    CGparameter& eye = ray.GetNamedParameter("eyePos");
	cgGLSetParameter3f(eye, eyePos.X(), eyePos.Y(), eyePos.Z());
	
	ray.Bind();
    ray.Enable();

	Workspace();
	
    ray.Disable();
#endif // STUB_PHOTONMAPPERGPU
}
Beispiel #14
0
Point3f RandomUnitVec(){
  Point3f k;
  do {
    k=Point3f(
     (random(200)-100)*0.01,
     (random(200)-100)*0.01,
     (random(200)-100)*0.01
    );
  } while (k.SquaredNorm()>1.0);

  return k.Normalize();
}
/// Multiplies \p point by the inverse of the transform.
Point3f GraphicsTransform::inverseMultiplyPoint(const Point3f &point) const
{
    Eigen::Matrix<float, 4, 1> vector4;
    vector4[0] = point.x();
    vector4[1] = point.y();
    vector4[2] = point.z();
    vector4[3] = 1;

    vector4 = m_matrix->inverse() * vector4;

    return Point3f(vector4[0], vector4[1], vector4[2]);
}
Beispiel #16
0
//
//	Check if the given vertex is visible on the current user view
//			This method is used for rendering vertices labels, and
//			rendering edges/faces
//	Returns: true if visible
bool edit_topo::isVertexVisible(Point3f v)
{
	float   pix;
	double tx,ty,tz;

	gluProject(v.X(),v.Y(),v.Z(), mvmatrix,projmatrix,viewport, &tx,&ty,&tz);
	glReadPixels(tx,ty,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&pix);

	float ff = fabs(tz - pix);

	return ((ff < 0.003));
}
void WLOP::computeAverageTerm(CMesh* samples, CMesh* original)
{
	double average_power = para->getDouble("Average Power");
	bool need_density = para->getBool("Need Compute Density");
	double radius = para->getDouble("CGrid Radius"); 

	double radius2 = radius * radius;
	double iradius16 = -para->getDouble("H Gaussian Para")/radius2;

	cout << "Original Size:" << samples->vert[0].original_neighbors.size() << endl;
	for(int i = 0; i < samples->vert.size(); i++)
	{
		CVertex& v = samples->vert[i];

		for (int j = 0; j < v.original_neighbors.size(); j++)
		{
			CVertex& t = original->vert[v.original_neighbors[j]];
			
			Point3f diff = v.P() - t.P();
			double dist2  = diff.SquaredNorm();

			double w = 1;
			if (para->getBool("Run Anisotropic LOP"))
			{
				double len = sqrt(dist2);
				if(len <= 0.001 * radius) len = radius*0.001;
				double hn = diff * v.N();
				double phi = exp(hn * hn * iradius16);
				w = phi / pow(len, 2 - average_power);
			}
			else if (average_power < 2)
			{
				double len = sqrt(dist2);
				if(len <= 0.001 * radius) len = radius*0.001;
				w = exp(dist2 * iradius16) / pow(len, 2 - average_power);
			}
			else
			{
				w = exp(dist2 * iradius16);
			}

			if (need_density)
			{
				w *= original_density[t.m_index];
			}

			average[i] += t.P() * w;  
			average_weight_sum[i] += w;  

		}
	}
}
Beispiel #18
0
//---------------------------------------------------------
void FSMAIControl::UpdatePerceptions(float dt)
{
    if(m_willCollide)
        m_safetyRadius = 30.0f;
    else
        m_safetyRadius = 15.0f;

    //store closest asteroid and powerup
    m_nearestAsteroid = Game.GetClosestGameObj(m_ship,GameObj::OBJ_ASTEROID);
    m_nearestPowerup  = Game.GetClosestGameObj(m_ship,GameObj::OBJ_POWERUP);

    //asteroid collision determination
    m_willCollide = false;
    if(m_nearestAsteroid)
    {
        float speed = m_ship->m_velocity.Length();
        m_nearestAsteroidDist = m_nearestAsteroid->m_position.Distance(m_ship->m_position);
        Point3f normDelta = m_nearestAsteroid->m_position - m_ship->m_position;
        normDelta.Normalize();
        float astSpeed = m_nearestAsteroid->m_velocity.Length();
        float shpSpeedAdj = DOT(m_ship->UnitVectorVelocity(),normDelta)*speed;
        float astSpeedAdj = DOT(m_nearestAsteroid->UnitVectorVelocity(),-normDelta)*astSpeed;
        speed = shpSpeedAdj+astSpeedAdj;

//        if(speed > astSpeed)
//            dotVel  = DOT(m_ship->UnitVectorVelocity(),normDelta);
//        else
//        {
//            speed = astSpeed;
//            dotVel = DOT(m_nearestAsteroid->UnitVectorVelocity(),-normDelta);
//        }
        float spdAdj = LERP(speed/m_maxSpeed,0.0f,90.0f);
        float adjSafetyRadius = m_safetyRadius+spdAdj+m_nearestAsteroid->m_size;

        //if you're too close, and I'm heading somewhat towards you,
        //flag a collision
        if(m_nearestAsteroidDist <= adjSafetyRadius && speed > 0)
            m_willCollide = true;
    }

    //powerup near determination
    m_powerupNear = false;
    if(m_nearestPowerup)
    {
        m_nearestPowerupDist = m_nearestPowerup->m_position.Distance(m_ship->m_position);
        if(m_nearestPowerupDist <= POWERUP_SCAN_DIST)
        {
            m_powerupNear     = true;
        }
    }

}
Beispiel #19
0
float GetVelocity(CMeshO::CoordType o_p,CMeshO::CoordType n_p,CMeshO::FacePointer f,CMeshO::CoordType g,float m,float v){
    Point3f n=f->N();
    float b=n[0]*g[0]+n[1]*g[1]+n[2]*g[2];
    float distance=Distance(o_p,n_p);
    Point3f force;
    force[0]=g[0]-b*n[0];
    force[1]=g[1]-b*n[1];
    force[2]=g[2]-b*n[2];
    if(force.Norm()==0) return 0;
    float acceleration=(force/m).Norm();
    float n_v=math::Sqrt(pow(v,2)+(2*acceleration*distance));
    return n_v;
}
Beispiel #20
0
// Algorithm:
// plane equation: P*N + c = 0
// we find point rays in 3D from image points and camera parameters
// then we fit c by minimizing average L2 distance between rotated and translated object points
// and points found by crossing point rays with plane. We use the fact that center of mass
// of object points and fitted points should coincide.
void findPlanarObjectPose(const vector<Point3f>& _object_points, const Mat& image_points, const Point3f& normal,
                const Mat& intrinsic_matrix, const Mat& distortion_coeffs, double& alpha, double& C, vector<Point3f>& object_points_crf)
{
    vector<Point2f> _rays;
    undistortPoints(image_points, _rays, intrinsic_matrix, distortion_coeffs);

    // filter out rays that are parallel to the plane
    vector<Point3f> rays;
    vector<Point3f> object_points;
    for(size_t i = 0; i < _rays.size(); i++)
    {
        Point3f ray(_rays[i].x, _rays[i].y, 1.0f);
        double proj = ray.dot(normal);
        if(fabs(proj) > std::numeric_limits<double>::epsilon())
        {
            rays.push_back(ray*(1.0/ray.dot(normal)));
            object_points.push_back(_object_points[i]);
        }
    }

    Point3f pc = massCenter(rays);
    Point3f p0c = massCenter(object_points);
    
    vector<Point3f> drays;
    drays.resize(rays.size());
    for(size_t i = 0; i < rays.size(); i++)
    {
        drays[i] = rays[i] - pc;
        object_points[i] -= p0c;
    }

    double s1 = 0.0, s2 = 0.0, s3 = 0.0;
    for(size_t i = 0; i < rays.size(); i++)
    {
        Point3f vprod = crossProduct(drays[i], object_points[i]);
        s1 += vprod.dot(normal);
        s2 += drays[i].dot(object_points[i]);
        s3 += drays[i].dot(drays[i]);
    }
    
    alpha = atan2(s1, s2);
    C = (s2*cos(alpha) + s1*sin(alpha))/s3;
    
//    printf("alpha = %f, C = %f\n", alpha, C);
    
    object_points_crf.resize(rays.size());
    for(size_t i = 0; i < rays.size(); i++)
    {
        object_points_crf[i] = rays[i]*C;
    }
}
static
void computeCorrespsFiltered(const Mat& K, const Mat& K_inv, const Mat& Rt,
                            const Mat& depth0, const Mat& validMask0,
                            const Mat& depth1, const Mat& selectMask1, float maxDepthDiff,
                            Mat& corresps,
                            const Mat& normals0, const Mat& transformedNormals1,
                            const Mat& image0, const Mat& image1)
{
    const double maxNormalsDiff = 30; // in degrees
    const double maxColorDiff = 50;
    const double maxNormalAngleDev = 75; // in degrees

    computeCorresps(K, K_inv, Rt, depth0, validMask0, depth1, selectMask1,
                    maxDepthDiff, corresps);

    const Point3f Oz_inv(0,0,-1); // TODO replace by vector to camera position?
    for(int v0 = 0; v0 < corresps.rows; v0++)
    {
        for(int u0 = 0; u0 < corresps.cols; u0++)
        {
            int c = corresps.at<int>(v0, u0);
            if(c != -1)
            {
                Point3f curNormal = normals0.at<Point3f>(v0,u0);
                curNormal *= 1./cv::norm(curNormal);
                if(std::abs(curNormal.ddot(Oz_inv)) < std::cos(maxNormalAngleDev / 180 * CV_PI))
                {
                    corresps.at<int>(v0, u0) = -1;
                    continue;
                }

                int u1, v1;
                get2shorts(c, u1, v1);

                Point3f transfPrevNormal = transformedNormals1.at<Point3f>(v1,u1);
                transfPrevNormal *= 1./cv::norm(transfPrevNormal);
                if(std::abs(curNormal.ddot(transfPrevNormal)) < std::cos(maxNormalsDiff / 180 * CV_PI))
                {
                    corresps.at<int>(v0, u0) = -1;
                    continue;
                }

                if(std::abs(image0.at<uchar>(v0,u0) - image1.at<uchar>(v1,u1)) > maxColorDiff)
                {
                    corresps.at<int>(v0, u0) = -1;
                    continue;
                }
            }
        }
    }
}
Beispiel #22
0
int main( int argc, char **argv )
{
  if(argc<2)
  {
    printf("Usage trimesh_base <meshfilename.ply>\n");
    return -1;
  }

  MyMesh m,em,cm,full;

  if(tri::io::ImporterPLY<MyMesh>::Open(m,argv[1])!=0)
  {
    printf("Error reading file  %s\n",argv[1]);
    exit(0);
  }

  tri::UpdateFlags<MyMesh>::FaceBorderFromFF(m);
  tri::UpdateNormals<MyMesh>::PerVertexNormalized(m);
  tri::UpdateBounding<MyMesh>::Box(m);

  printf("Input mesh  vn:%i fn:%i\n",m.vn,m.fn);
  printf( "Mesh has %i vert and %i faces\n", m.vn, m.fn );
  srand(time(0));
  Plane3f slicingPlane;
  Point3f planeCenter = m.bbox.Center();

  for(int i=0;i<10;++i)
  {
    cm.Clear();
    em.Clear();
    Point3f planeDir = Point3f(-0.5f+float(rand())/RAND_MAX,-0.5f+float(rand())/RAND_MAX,-0.5f+float(rand())/RAND_MAX);
    planeDir.Normalize();
    printf("slicing dir %5.2f %5.2f %5.2f\n",planeDir[0],planeDir[1],planeDir[2]);

    slicingPlane.Init(planeCenter+planeDir*0.3f*m.bbox.Diag()*float(rand())/RAND_MAX,planeDir);

    vcg::IntersectionPlaneMesh<MyMesh, MyMesh, float>(m, slicingPlane, em );
    tri::Clean<MyMesh>::RemoveDuplicateVertex(em);
    vcg::tri::CapEdgeMesh(em,cm);

    printf("  edge mesh vn %5i en %5i fn %5i\n",em.vn,em.en,em.fn);
    printf("sliced mesh vn %5i en %5i fn %5i\n",cm.vn,cm.en,cm.fn);

    tri::Append<MyMesh,MyMesh>::Mesh(full,cm);
  }

  tri::io::ExporterPLY<MyMesh>::Save(full,"out.ply",false);

  return 0;
}
Beispiel #23
0
static Point3f findRayIntersection(Point3f k1, Point3f b1, Point3f k2, Point3f b2)
{    
    float a[4], b[2], x[2];
    a[0] = k1.dot(k1);
    a[1] = a[2] = -k1.dot(k2);
    a[3] = k2.dot(k2);
    b[0] = k1.dot(b2 - b1);
    b[1] = k2.dot(b1 - b2);
    Mat_<float> A(2, 2, a), B(2, 1, b), X(2, 1, x);
    solve(A, B, X);
    
    float s1 = X.at<float>(0, 0);
    float s2 = X.at<float>(1, 0);
    return (k1*s1 + b1 + k2*s2 + b2)*0.5f;
};
Beispiel #24
0
CMeshO::CoordType getVelocityComponent(float v,CMeshO::FacePointer f,CMeshO::CoordType g){
    CMeshO::CoordType cV;
    Point3f n= f->N();
    float a=n[0]*g[0]+n[1]*g[1]+n[2]*g[2];
    Point3f d;
    d[0]=g[0]-a*n[0];
    d[1]=g[1]-a*n[1];
    d[2]=g[2]-a*n[2];
    cV=d/d.Norm();
    cV.Normalize();
    cV[0]=v*d[0];
    cV[1]=v*d[1];
    cV[2]=v*d[2];
    return cV;
}
Beispiel #25
0
//
//	Get visible vertex nearest to mouse position (from a given vertices list)
//	Returns: true if visible
bool edit_topo::getVisibleVertexNearestToMouse(QList<Vtx> list, Vtx &out)
{
	bool found = false;
	double minDist = 100000;
	int minIdx = -1;
	Point3f t;

	QList<Vtx> visib;

	for(int i=0; i<list.count(); i++)
		if(isVertexVisible(list.at(i).V))
			visib.push_back(list.at(i));

	QPoint mPos = QPoint(mousePos.x(), mouseRealY);
	for(int i=0; i<visib.count(); i++)
	{
		Point3f p = visib.at(i).V;
		double tx,ty,tz;
		gluProject(p.X(),p.Y(),p.Z(), mvmatrix,projmatrix,viewport, &tx,&ty,&tz);

		QPoint qp = QPoint(tx, ty);

		// faster distance
		//double dx = fabs((double)(qp.x() - mPos.x()));
		//double dy = fabs((double)(qp.y() - mPos.y()));
		//double dist = (dy > dx) ? 0.41*dx+0.941246*dy : 0.41*dy+0.941246*dx;

		double dist = sqrt((double)(math::Sqr(qp.x() - mPos.x()) + math::Sqr(qp.y() - mPos.y())));
			
		if(dist<minDist)
		{
			minDist = dist;
			minIdx = i;
			found = true;						
		}
	}

	if(found)
	{
		for(int j=0; j<list.count(); j++)
			if(list.at(j).vName==visib.at(minIdx).vName)
			{
				out = list.at(j);
				return true;
			}
	}
	return false;
}
Beispiel #26
0
/// Returns the depth of point in the scene.
float GraphicsView::depth(const Point3f &point) const
{
    Eigen::Matrix<float, 4, 1> viewPoint;
    viewPoint[0] = point.x();
    viewPoint[1] = point.y();
    viewPoint[2] = point.z();
    viewPoint[3] = 1;

    GraphicsTransform transform = projectionTransform() * modelViewTransform();
    viewPoint = transform.multiply(viewPoint);
    viewPoint *= 1.0 / viewPoint[3];

    float winZ = (viewPoint[2] + 1) / 2;

    return winZ;
}
Beispiel #27
0
void SPHSystem::computeForce()
{
	int i, j, s, numNei;
	float dij;
	float term1, term2;
	Point3f vij;
	Point3f pf, vf, tf, gf, cf;

	//#pragma omp parallel for private( j, nId, numNei, d, term1, term2, dv, pf, vf, tf, gf )
	for(i=0; i<p.size(); ++i) {
		pf.Set(0,0,0);
		vf.Set(0,0,0);
		tf.Set(0,0,0);
		numNei = p[i]->pq.getSize();

		
		for(s=1; s<=numNei; ++s) {
			j = p[i]->pq.queue[s];
			if(i==j) continue;
			term1 = p[i]->p/(p[i]->d*p[i]->d);
			term2 = p[j]->p/(p[j]->d*p[j]->d);
			vij = *p[i]-*p[j];
			dij = vij.Length();
			// pressure force
			pf += (term1+term2)*p[j]->m*k->pw1(dij)*vij;
			// viscosity force
			vf += p[j]->m*k->vw2(dij)*(p[j]->v-p[i]->v);
			// surface tension			
		}

		
		pf = -p[i]->d*pf;
		vf = (X/p[i]->d)*vf;
		gf = p[i]->d*Point3f(0.0f, -GR, 0.0f);
		
		if(p[i]->n.Length() < ( SIM_DIM==2 ? 0.6f : 3.0f) )		// for 2d < 0.6 ,   3d < 3.0
			tf.Zero();
		else
			tf = -p[i]->lapc*p[i]->n.GetNormalized();
		
		p[i]->tf = tf;
		p[i]->pf = pf;

		p[i]->vf = vf;
		p[i]->a = (pf+vf+gf+tf)/p[i]->d;
	}
}
Beispiel #28
0
void SPHSystem::computeDensityPressure()
{
	int i, j, s, numNei;
	float lapc, c, d;
	float w;
	float vj;       // volumn
	float lenij;    // length (i,j)
	Point3f n;
	Point3f vecij;  // vector (i,j)
	
	for(i=0; i<p.size(); ++i) {
		p[i]->vol = p[i]->m/p[i]->d;
	}

	#pragma omp parallel for private(s, j, numNei, lapc, c, d, w, vj, lenij, n, vecij )
	for(i=0; i<p.size(); ++i) {
		lapc = 0;
		c = 0;
		d = 0;
		n.Zero();
		numNei = p[i]->pq.getSize();
		for(s=1; s<=numNei; ++s) {
			j = p[i]->pq.queue[s];
			vj = p[j]->vol;
			vecij = *p[i]-*p[j];
			lenij = vecij.Length();
			w = k->w(lenij);
			
			c += p[j]->c*p[j]->m*(vj)*w;
			n += p[j]->m*(vj)*k->w1(lenij)*(vecij);
			lapc += p[j]->m*(vj)*k->w2(lenij);
			
			d += p[j]->m*w;
		}
		p[i]->lapc = lapc;										// laplacian of c
		p[i]->c = c;											// color field
		p[i]->n = n;											// inward surface normal
		
		p[i]->d = d;											// density
		p[i]->p = (K*RHO/7.0f)*(pow((d/RHO),7.0f)-1);           // pressure (Tait Equation, http://graphics.stanford.edu/~wicke/eg09-tutorial/coursenotes.pdf)
		if(p[i]->p < 0)											// correct pressure if p<0
			p[i]->p *= Z;										// reduce it to a tiny number (~=0)
			
	}

}
Beispiel #29
0
    Spectrum PerspectiveSensor::sampleRay(Ray3f& ray, const Point2f& samplePosition, const Point2f& apertureSample) const
    {
        Point3f nearPoint = m_sampleToCamera * Point3f(
            samplePosition.x() * m_invImageSize.x(),
            samplePosition.y() * m_invImageSize.y(), 0.f);

        Vector3f dir = nearPoint.normalized();
        float invZ = 1.f / dir.z();

        ray.o = m_cameraToWorld * Point3f(0.f, 0.f, 0.f);
        ray.d = m_cameraToWorld * dir;
        ray.minT = m_nearClip * invZ;
        ray.maxT = m_farClip * invZ;
        ray.update();

        return Spectrum(1.f);
    }
void GraphicsPainter::drawCylinder(const Point3f &a, const Point3f &b, float radius)
{
    glPushMatrix();

    glTranslatef(a.x(), a.y(), a.z());

    Vector3f vector = (a - b).normalized();
    Vector3f axis = vector.cross(-Vector3f::UnitZ()).normalized();
    float angle = chemkit::geometry::angle(vector.cast<Real>(), -Vector3f::UnitZ().cast<Real>());
    glRotatef(-angle, axis.x(), axis.y(), axis.z());

    float length = chemkit::geometry::distance(a.cast<Real>(), b.cast<Real>());

    drawCylinder(radius, length);

    glPopMatrix();
}