Esempio n. 1
0
void MyPrimitive::GenerateTube(float a_fOuterRadius, float a_fInnerRadius, float a_fHeight, int a_nSubdivisions, vector3 a_v3Color)
{
	if (a_nSubdivisions < 3)
		a_nSubdivisions = 3;
	if (a_nSubdivisions > 360)
		a_nSubdivisions = 360;

	Release();
	Init();

	for (int i = 0; i < a_nSubdivisions; i++)
	{
		float ang = (2 * PI) / a_nSubdivisions;

		vector3 point0(a_fOuterRadius*cos((i + 1)*ang), a_fHeight, a_fOuterRadius*sin((i + 1)*ang)); //1
		vector3 point1(a_fOuterRadius*cos(i*ang), 0, a_fOuterRadius*sin(i*ang)); //2
		vector3 point2(a_fOuterRadius*cos(i*ang), a_fHeight, a_fOuterRadius*sin(i*ang)); //0
		vector3 point3(a_fOuterRadius*cos((i + 1)*ang), 0, a_fOuterRadius*sin((i + 1)*ang)); //3

		vector3 point4(a_fInnerRadius*cos((i + 1)*ang), a_fHeight, a_fInnerRadius*sin((i + 1)*ang)); //1
		vector3 point5(a_fInnerRadius*cos(i*ang), 0, a_fInnerRadius*sin(i*ang)); //2
		vector3 point6(a_fInnerRadius*cos(i*ang), a_fHeight, a_fInnerRadius*sin(i*ang)); //0
		vector3 point7(a_fInnerRadius*cos((i + 1)*ang), 0, a_fInnerRadius*sin((i + 1)*ang)); //3

		AddQuad(point4, point0, point6, point2); //Top
		AddQuad(point0, point3, point2, point1); //Outer
		AddQuad(point7, point5, point3, point1); //Bottom
		AddQuad(point5, point7, point6,point4 ); // Inner
		
	}

	//Your code ends here
	CompileObject(a_v3Color);
}
void MyPrimitive::GenerateTorus(float a_fOuterRadius, float a_fInnerRadius, int a_nSubdivisionsA, int a_nSubdivisionsB, vector3 a_v3Color)
{
	if (a_fOuterRadius <= a_fInnerRadius + 0.1f)
		return;

	if (a_nSubdivisionsA < 3)
		a_nSubdivisionsA = 3;
	if (a_nSubdivisionsA > 25)
		a_nSubdivisionsA = 25;

	if (a_nSubdivisionsB < 3)
		a_nSubdivisionsB = 3;
	if (a_nSubdivisionsB > 25)
		a_nSubdivisionsB = 25;

	Release();
	Init();

	//Your code starts here
	float fValue = 0.5f;
	//3--2
	//|  |
	//0--1
	vector3 point0(-fValue, -fValue, fValue); //0
	vector3 point1(fValue, -fValue, fValue); //1
	vector3 point2(fValue, fValue, fValue); //2
	vector3 point3(-fValue, fValue, fValue); //3

	AddQuad(point0, point1, point3, point2);

	//Your code ends here
	CompileObject(a_v3Color);
}
// track object
void ObjectTrackingClass::track(cv::Mat& image, // output image
                                cv::Mat& image1, // previous frame
                                cv::Mat& image2, // next frame
                                std::vector<cv::Point2f>& points1, // previous points 
                                std::vector<cv::Point2f>& points2, // next points
                                std::vector<uchar>& status, // status array
                                std::vector<float>& err) // error array
{
    // tracking code
    cv::calcOpticalFlowPyrLK(image1,
                             image2,
                             points1,
                             points2,
                             status,
                             err,
                             winSize,
                             maxLevel,
                             termcrit,
                             flags,
                             minEigThreshold);
    
    // work out maximum X,Y keypoint values in the next_points keypoint vector
    cv::Point2f min(FLT_MAX, FLT_MAX);
    cv::Point2f max(FLT_MIN, FLT_MIN);
    
    // refactor the points array to remove points lost due to tracking error
    size_t i, k;
    for( i = k = 0; i < points2.size(); i++ )
    {
        if( !status[i] )
            continue;
        
        points2[k++] = points2[i];
        
        // find keypoints at the extremes
        min.x = Min(min.x, points2[i].x);
        min.y = Min(min.y, points2[i].y);
        max.x = Max(max.x, points2[i].x);
        max.y = Max(max.y, points2[i].y);
        
        // draw points
        cv::circle( image, points2[i], 3, cv::Scalar(0,255,0), -1, 8);
    }
    points2.resize(k);
    
    // Draw lines between the extreme points (square)
    cv::Point2f point0(min.x, min.y);
    cv::Point2f point1(max.x, min.y);
    cv::Point2f point2(max.x, max.y);
    cv::Point2f point3(min.x, max.y);
    cv::line( image, point0, point1, cv::Scalar( 0, 255, 0 ), 4 );
    cv::line( image, point1, point2, cv::Scalar( 0, 255, 0 ), 4 );
    cv::line( image, point2, point3, cv::Scalar( 0, 255, 0 ), 4 );
    cv::line( image, point3, point0, cv::Scalar( 0, 255, 0 ), 4 );
}
Esempio n. 4
0
int main(int argc, char **argv) {
  std::cout
      << "¸.·´¯`·.¸¸.·´ BioFractalTree Version 0 Revision 1 `·.¸¸.·´¯`·.¸\n";

  // set up a bcurve for testing early curve / surface viz algs
  vector<double> coords0 = { 0.0, 0.0, 0.0 };
  vector<double> coords1 = { 0.0, 0.3, 0.3 };
  vector<double> coords2 = { 0.3, 0.0, 0.6 };
  vector<double> coords3 = { 0.0, 0.0, 1.0 };

  std::unique_ptr<point> point0(new point(coords0, 0));
  std::unique_ptr<point> point1(new point(coords1, 1));
  std::unique_ptr<point> point2(new point(coords2, 2));
  std::unique_ptr<point> point3(new point(coords3, 3));

  vector<point> curve0 = { *point0, *point1, *point2, *point3 };
  std::unique_ptr<bcurve> thisCurve(new bcurve(curve0, 20));

  // we set up a static Bernstein basis set for a given resolution
  std::unique_ptr<bBasis> bBasis_20(new bBasis(20));
  // this sets up a 4x21 vector of vector<double>
  // 19 internal points plus the two endpoints

  // we can return / output the basis set
  vector<vector<double> > returnBasis;
  bBasis_20->getBasis(returnBasis);
  //    std::cout << "Basis Set Output: \n";
  //    std::cout << "  size : " << returnBasis.at(0).size();
  for (int j = 0; j < 4; j++) {
    //        std::cout << "\n  b[" << j << "] : ";
    for (int i = 0; i < returnBasis.at(j).size(); i++) {
      //    std::cout << returnBasis.at(j).at(i) << " ";
    }
  }
  //    std::cout << "\n";

  // now we can try getting some points on the bcurve
  vector<point> returnPoints;
  thisCurve->getPointsOnCurve(returnPoints, returnBasis, 4);
  // only returnPoints gets modified by the above function
  // it returns 21 points along the curve, including endpoints
  std::cout << "points on curve : \n";
  for (int i = 0; i < returnPoints.size(); i++) {
    vector<double> tempCoord;
    returnPoints.at(i).getCoord(tempCoord);
    for (int j = 0; j < 3; j++) {
      std::cout << tempCoord.at(j) << " ";
    }
    std::cout << "\n";
  }

  return 0;
}
void MyPrimitive::GenerateCube(float a_mSize, vector3 a_vColor)
{
	//If the size is less than this make it this large
	if (a_mSize < 0.01f)
		a_mSize = 0.01f;

	//Clean up Memory
	Release();
	Init();

	float fValue = 0.5f * a_mSize;
	//3--2
	//|  |
	//0--1
	vector3 point0(-fValue, -fValue, fValue); //0
	vector3 point1(fValue, -fValue, fValue); //1
	vector3 point2(fValue, fValue, fValue); //2
	vector3 point3(-fValue, fValue, fValue); //3

	//7--6
	//|  |
	//4--5
	vector3 point4(-fValue, -fValue, -fValue); //4
	vector3 point5(fValue, -fValue, -fValue); //5
	vector3 point6(fValue, fValue, -fValue); //6
	vector3 point7(-fValue, fValue, -fValue); //7

	//F
	AddQuad(point0, point1, point3, point2);

	//B
	AddQuad(point5, point4, point6, point7);

	//L
	AddQuad(point4, point0, point7, point3);

	//R
	AddQuad(point1, point5, point2, point6);

	//U
	AddQuad(point3, point2, point7, point6);

	//D
	AddQuad(point4, point5, point0, point1);

	//Compile the object in this color and assign it this name
	CompileObject(a_vColor);
}
Esempio n. 6
0
  bool BSPTree::intersect(Ray &ray, const ISectTri &isecttri, double t_max) const 
  {
    tri_calls++;

    // This is the Möller-Trumbore method
    Vec3d direction(ray.direction);
    Vec3d edge0(isecttri.edge0);
    Vec3d edge1(isecttri.edge1);

    // Ray-triangle intersection
    Vec3d p = cross(direction, edge1);
    double a = dot(edge0, p);
    if(a > -d_eps && a < d_eps)
      return false;

    // Just delay these 
    Vec3d origin(ray.origin);
    Vec3d point0(isecttri.point0);    
    double f = 1.0/a;
    Vec3d s = origin - point0;
    double u = f*dot(s, p);
    if(u < 0.0 || u > 1.0)
      return false;

    Vec3d q = cross(s, edge0);
    double v = f*dot(direction, q);  
    if(v < 0.0 || u + v > 1.0)
      return false;

    double t = f*dot(edge1, q);
    if(t < f_eps || t*t < 1.0e-9)
      return false;
    if(t > t_max)
      return false;
    if(t > ray.dist)
      return false;
  
    ray.dist = t;
    ray.u = u;
    ray.v = v;
    ray.hit_object = (TriMesh*)isecttri.mesh_id;
    ray.hit_face_id = isecttri.tri_id;
    ray.has_hit=true;
    return true; 
  }
void MyPrimitive::GenerateCube(float a_fSize, vector3 a_v3Color)
{
	if (a_fSize < 0.01f)
		a_fSize = 0.01f;

	Release();
	Init();

	float fValue = 0.5f * a_fSize;
	//3--2
	//|  |
	//0--1
	vector3 point0(-fValue, -fValue, fValue); //0
	vector3 point1(fValue, -fValue, fValue); //1
	vector3 point2(fValue, fValue, fValue); //2
	vector3 point3(-fValue, fValue, fValue); //3

	vector3 point4(-fValue, -fValue, -fValue); //4
	vector3 point5(fValue, -fValue, -fValue); //5
	vector3 point6(fValue, fValue, -fValue); //6
	vector3 point7(-fValue, fValue, -fValue); //7

											  //F
	AddQuad(point0, point1, point3, point2);

	//B
	AddQuad(point5, point4, point6, point7);

	//L
	AddQuad(point4, point0, point7, point3);

	//R
	AddQuad(point1, point5, point2, point6);

	//U
	AddQuad(point3, point2, point7, point6);

	//D
	AddQuad(point4, point5, point0, point1);

	CompileObject(a_v3Color);
}
Esempio n. 8
0
void MyPrimitive::GenerateCylinder(float a_fRadius, float a_fHeight, int a_nSubdivisions, vector3 a_v3Color)
{
	if (a_nSubdivisions < 3)
		a_nSubdivisions = 3;
	if (a_nSubdivisions > 360)
		a_nSubdivisions = 360;

	Release();
	Init();

	//Your code starts here
	float fValue = 0.5f;
	//3--2
	//|  |
	//0--1
	//vector3 point0(-fValue, -fValue, fValue); //0
	//vector3 point1(fValue, -fValue, fValue); //1
	//vector3 point2(fValue, fValue, fValue); //2
	//vector3 point3(-fValue, fValue, fValue); //3
	//
	//AddQuad(point0, point1, point3, point2);
		vector3 point0(0, 0, 0); 
		vector3 point1(0, a_fHeight, 0); 
	for (int i = 0; i < a_nSubdivisions; i++)
	{
		float ang = (2 * PI) / a_nSubdivisions;

		
		vector3 point2(a_fRadius*cos(i*ang), 0, a_fRadius*sin(i*ang)); //0
		vector3 point3(a_fRadius*cos((i + 1)*ang), 0, a_fRadius*sin((i + 1)*ang)); //3


		vector3 point4(a_fRadius*cos(i*ang), a_fHeight, a_fRadius*sin(i*ang)); //0
		vector3 point5(a_fRadius*cos((i + 1)*ang), a_fHeight, a_fRadius*sin((i + 1)*ang)); //3

		AddQuad(point1, point3, point2, point4);
		AddQuad(point1, point4, point5, point3);
	}
	//Your code ends here
	CompileObject(a_v3Color);
}
Esempio n. 9
0
void MyPrimitive::GenerateSphere(float a_fRadius, int a_nSubdivisions, vector3 a_v3Color)
{
	//Sets minimum and maximum of subdivisions
	if (a_nSubdivisions < 1)
	{
		GenerateCube(a_fRadius * 2, a_v3Color);
		return;
	}
	if (a_nSubdivisions > 6)
		a_nSubdivisions = 6;

	Release();
	Init();

	//Your code starts here
	float a_fHeight;
	vector3 point0(0, 0, 0);
	vector3 point1(0, a_fHeight, 0);
	for (int i = 0; i < a_nSubdivisions; i++)
	{
		float ang = (2 * PI) / a_nSubdivisions;


		vector3 point2(a_fRadius*cos(i*ang), 0, a_fRadius*sin(i*ang)); //0
		vector3 point3(a_fRadius*cos((i + 1)*ang), 0, a_fRadius*sin((i + 1)*ang)); //3


		vector3 point4(a_fRadius*cos(i*ang), a_fHeight, a_fRadius*sin(i*ang)); //0
		vector3 point5(a_fRadius*cos((i + 1)*ang), a_fHeight, a_fRadius*sin((i + 1)*ang)); //3

		AddQuad(point1, point3, point2, point4);
		AddQuad(point1, point4, point5, point3);
	}



	//Your code ends here
	CompileObject(a_v3Color);
}
Esempio n. 10
0
BOOL ray_pyramid(const LLVector3 &ray_point, const LLVector3 &ray_direction,
                 const LLVector3 &p_center, const LLVector3 &p_scale, const LLQuaternion &p_rotation,
                 LLVector3 &intersection, LLVector3 &intersection_normal)
{
    // center of mass of pyramid is located 1/4 its height from the base
    F32 x = 0.5f * p_scale.mV[VX];
    F32 y = 0.5f * p_scale.mV[VY];
    F32 z = 0.25f * p_scale.mV[VZ];

    LLVector3 point0(0.0f, 0.0f,  p_scale.mV[VZ] - z);
    LLVector3 point1( x,  y, -z);
    LLVector3 point2(-x,  y, -z);
    LLVector3 point3(-x, -y, -z);
    LLVector3 point4( x, -y, -z);

    // transform these points into absolute frame
    point0 = (point0 * p_rotation) + p_center;
    point1 = (point1 * p_rotation) + p_center;
    point2 = (point2 * p_rotation) + p_center;
    point3 = (point3 * p_rotation) + p_center;
    point4 = (point4 * p_rotation) + p_center;

    // test ray intersection for each face
    BOOL b_hit = FALSE;
    LLVector3 face_intersection, face_normal;
    F32 distance_squared = 1.0e12f;
    F32 temp;

    // face 0
    if (ray_direction * ( (point1 - point4) % (point0 - point4)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point4, point1, point0, intersection, intersection_normal))
    {
        distance_squared = (ray_point - intersection).magVecSquared();
        b_hit = TRUE;
    }

    // face 1
    if (ray_direction * ( (point2 - point1) % (point0 - point1)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point1, point2, point0, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 2
    if (ray_direction * ( (point3 - point2) % (point0 - point2)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point2, point3, point0, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 3
    if (ray_direction * ( (point4 - point3) % (point0 - point3)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point3, point4, point0, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 4
    if (ray_direction * ( (point3 - point4) % (point2 - point4)) < 0.0f  &&
            ray_quadrangle(ray_point, ray_direction, point4, point3, point2, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    return b_hit;
}
Esempio n. 11
0
BOOL ray_tetrahedron(const LLVector3 &ray_point, const LLVector3 &ray_direction,
                     const LLVector3 &t_center, const LLVector3 &t_scale, const LLQuaternion &t_rotation,
                     LLVector3 &intersection, LLVector3 &intersection_normal)
{
    F32 a = 0.5f * F_SQRT3;				// height of unit triangle
    F32 b = 1.0f / F_SQRT3;				// distance of center of unit triangle to each point
    F32 c = F_SQRT2 / F_SQRT3;			// height of unit tetrahedron
    F32 d = 0.5f * F_SQRT3 / F_SQRT2;	// distance of center of tetrahedron to each point

    // if we want the tetrahedron to have unit height (c = 1.0) then we need to divide
    // each constant by hieght of a unit tetrahedron
    F32 oo_c = 1.0f / c;
    a = a * oo_c;
    b = b * oo_c;
    c = 1.0f;
    d = d * oo_c;
    F32 e = 0.5f * oo_c;

    LLVector3 point0(			   0.0f,					0.0f,  t_scale.mV[VZ] * d);
    LLVector3 point1(t_scale.mV[VX] * b,					0.0f,  t_scale.mV[VZ] * (d-c));
    LLVector3 point2(t_scale.mV[VX] * (b-a),  e * t_scale.mV[VY],  t_scale.mV[VZ] * (d-c));
    LLVector3 point3(t_scale.mV[VX] * (b-a), -e * t_scale.mV[VY],  t_scale.mV[VZ] * (d-c));

    // transform these points into absolute frame
    point0 = (point0 * t_rotation) + t_center;
    point1 = (point1 * t_rotation) + t_center;
    point2 = (point2 * t_rotation) + t_center;
    point3 = (point3 * t_rotation) + t_center;

    // test ray intersection for each face
    BOOL b_hit = FALSE;
    LLVector3 face_intersection, face_normal;
    F32 distance_squared = 1.0e12f;
    F32 temp;

    // face 0
    if (ray_direction * ( (point2 - point1) % (point0 - point1)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point1, point2, point0, intersection, intersection_normal))
    {
        distance_squared = (ray_point - intersection).magVecSquared();
        b_hit = TRUE;
    }

    // face 1
    if (ray_direction * ( (point3 - point2) % (point0 - point2)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point2, point3, point0, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 2
    if (ray_direction * ( (point1 - point3) % (point0 - point3)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point3, point1, point0, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 3
    if (ray_direction * ( (point2 - point3) % (point1 - point3)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point3, point2, point1, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    return b_hit;
}
Esempio n. 12
0
BOOL ray_prism(const LLVector3 &ray_point, const LLVector3 &ray_direction,
               const LLVector3 &prism_center, const LLVector3 &prism_scale, const LLQuaternion &prism_rotation,
               LLVector3 &intersection, LLVector3 &intersection_normal)
{
    //      (0)              Z
    //      /| \             .
    //    (1)|  \           /|\  _.Y
    //     | \   \           |   /|
    //     | |\   \          |  /
    //     | | \(0)\         | /
    //     | |  \   \        |/
    //     | |   \   \      (*)----> X
    //     |(3)---\---(2)
    //     |/      \  /
    //    (4)-------(5)

    // need to calculate the points of the prism so we can run ray tests with each face
    F32 x = prism_scale.mV[VX];
    F32 y = prism_scale.mV[VY];
    F32 z = prism_scale.mV[VZ];

    F32 tx = x * 2.0f / 3.0f;
    F32 ty = y * 0.5f;
    F32 tz = z * 2.0f / 3.0f;

    LLVector3 point0(tx-x,  ty, tz);
    LLVector3 point1(tx-x, -ty, tz);
    LLVector3 point2(tx,    ty, tz-z);
    LLVector3 point3(tx-x,  ty, tz-z);
    LLVector3 point4(tx-x, -ty, tz-z);
    LLVector3 point5(tx,   -ty, tz-z);

    // transform these points into absolute frame
    point0 = (point0 * prism_rotation) + prism_center;
    point1 = (point1 * prism_rotation) + prism_center;
    point2 = (point2 * prism_rotation) + prism_center;
    point3 = (point3 * prism_rotation) + prism_center;
    point4 = (point4 * prism_rotation) + prism_center;
    point5 = (point5 * prism_rotation) + prism_center;

    // test ray intersection for each face
    BOOL b_hit = FALSE;
    LLVector3 face_intersection, face_normal;
    F32 distance_squared = 0.0f;
    F32 temp;

    // face 0
    if (ray_direction * ( (point0 - point2) % (point5 - point2)) < 0.0f  &&
            ray_quadrangle(ray_point, ray_direction, point5, point2, point0, intersection, intersection_normal))
    {
        distance_squared = (ray_point - intersection).magVecSquared();
        b_hit = TRUE;
    }

    // face 1
    if (ray_direction * ( (point0 - point3) % (point2 - point3)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point2, point3, point0, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 2
    if (ray_direction * ( (point1 - point4) % (point3 - point4)) < 0.0f  &&
            ray_quadrangle(ray_point, ray_direction, point3, point4, point1, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 3
    if (ray_direction * ( (point5 - point4) % (point1 - point4)) < 0.0f  &&
            ray_triangle(ray_point, ray_direction, point1, point4, point5, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    // face 4
    if (ray_direction * ( (point4 - point5) % (point2 - point5)) < 0.0f  &&
            ray_quadrangle(ray_point, ray_direction, point2, point5, point4, face_intersection, face_normal))
    {
        if (TRUE == b_hit)
        {
            temp = (ray_point - face_intersection).magVecSquared();
            if (temp < distance_squared)
            {
                distance_squared = temp;
                intersection = face_intersection;
                intersection_normal = face_normal;
            }
        }
        else
        {
            distance_squared = (ray_point - face_intersection).magVecSquared();
            intersection = face_intersection;
            intersection_normal = face_normal;
            b_hit = TRUE;
        }
    }

    return b_hit;
}
void ShapeParabolicRectangle::generatePrimitives(SoAction *action)
{
    SoPrimitiveVertex   pv;
    SoState  *state = action->getState();

    SbBool useTexFunc = ( SoTextureCoordinateElement::getType(state) ==
                          SoTextureCoordinateElement::FUNCTION );

    const SoTextureCoordinateElement* tce = 0;
    if ( useTexFunc ) tce = SoTextureCoordinateElement::getInstance(state);


    SbVec3f  point;
 	const int rows = 12; // Number of points per row
    const int columns = 12; // Number of points per column
    const int totalPoints = (rows)*(columns); // Total points in the grid

    float vertex[totalPoints][6];

    int h = 0;
    double ui = 0;
	double vj = 0;

    for (int i = 0; i < rows; ++i )
    {
    	ui =( 1.0 /(double)(rows-1) ) * i;

    	for ( int j = 0 ; j < columns ; ++j )
    	{
    		vj = ( 1.0 /(double)(columns-1) ) * j;

    		Point3D point = GetPoint3D(ui, vj);
    		NormalVector normal;
    		if( activeSide.getValue() == 0 )	normal = -GetNormal(ui, vj);
    		else	normal = GetNormal(ui, vj);

    		vertex[h][0] = point.x;
    		vertex[h][1] = point.y;
    		vertex[h][2] = point.z;
    		vertex[h][3] = normal.x;
    		vertex[h][4] = normal.y;
    		vertex[h][5] = normal.z;

    		pv.setPoint( vertex[h][0], vertex[h][1], vertex[h][2] );
    		h++; //Increase h to the next point.

    	}
    }

    float u = 1;
    float v = 1;
    beginShape(action, QUADS );
	for( int irow = 0; irow < (rows-1); ++irow )
	{
		for( int icolumn = 0; icolumn < (columns-1); ++icolumn )
		{
			int index0 = irow*columns + icolumn;
			SbVec3f  point0( vertex[index0][0], vertex[index0][1],  vertex[index0][2] );
			SbVec3f normal0(vertex[index0][3], vertex[index0][4], vertex[index0][5] );
			SbVec4f texCoord0 = useTexFunc ? tce->get(point0, normal0): SbVec4f( u,v, 0.0, 1.0 );
			pv.setPoint(point0);
			pv.setNormal(normal0);
			pv.setTextureCoords(texCoord0);
			shapeVertex(&pv);

			int index1 = index0 + 1;
			SbVec3f  point1( vertex[index1][0], vertex[index1][1],  vertex[index1][2] );
			SbVec3f normal1(vertex[index1][3], vertex[index1][4], vertex[index1][5] );
			SbVec4f texCoord1 = useTexFunc ? tce->get(point1, normal1): SbVec4f( u,v, 0.0, 1.0 );
			pv.setPoint(point1);
			pv.setNormal(normal1);
			pv.setTextureCoords(texCoord1);
			shapeVertex(&pv);

			int index3 = index0 + columns;
			int index2 = index3 + 1;

			SbVec3f  point2( vertex[index2][0], vertex[index2][1],  vertex[index2][2] );
			SbVec3f normal2(vertex[index2][3], vertex[index2][4], vertex[index2][5] );
			SbVec4f texCoord2 = useTexFunc ? tce->get(point2, normal2): SbVec4f( u,v, 0.0, 1.0 );
			pv.setPoint(point2);
			pv.setNormal(normal2);
			pv.setTextureCoords(texCoord2);
			shapeVertex(&pv);

			SbVec3f  point3( vertex[index3][0], vertex[index3][1],  vertex[index3][2] );
			SbVec3f normal3(vertex[index3][3], vertex[index3][4], vertex[index3][5] );
			SbVec4f texCoord3 = useTexFunc ? tce->get(point3, normal3): SbVec4f( u,v, 0.0, 1.0 );
			pv.setPoint(point3);
			pv.setNormal(normal3);
			pv.setTextureCoords(texCoord3);
			shapeVertex(&pv);

		}
	}

	endShape();

}
Esempio n. 14
0
	bool PlaypenApp::appFrameStarted(opal::real dt)
	{
		// Do per-frame application-specific things here.

		// Update the grasping spring line.
		if (mPhysicalCamera->isGrasping())
		{
			Ogre::Entity* pickingSphere = 
				mSceneMgr->getEntity("pickingSphere");
			if (!pickingSphere->isVisible())
			{
				pickingSphere->setVisible(true);
			}

			Ogre::Entity* springLine = 
				mSceneMgr->getEntity("springLine");
			if (!springLine->isVisible())
			{
				springLine->setVisible(true);
			}

			opal::Point3r desiredPos = 
				mPhysicalCamera->getGraspGlobalPos();
			Ogre::Vector3 point0(desiredPos[0], desiredPos[1], desiredPos[2]);

			opal::Point3r attachPos = mPhysicalCamera->getAttachGlobalPos();
			Ogre::Vector3 point1(attachPos[0], attachPos[1], attachPos[2]);

			pickingSphere->getParentSceneNode()->setPosition(point1);

			Ogre::Vector3 lineVec = point0 - point1;
			if (!lineVec.isZeroLength())
			{
				Ogre::SceneNode* springLineNode = 
					springLine->getParentSceneNode();
				springLineNode->setPosition(0.5 * (point0 + point1));
				
				springLineNode->setDirection(lineVec, Ogre::Node::TS_WORLD);
				springLineNode->setScale(0.1, 0.1, lineVec.length());
			}
			else
			{
				springLine->setVisible(false);
			}
		}
		else
		{
			Ogre::Entity* pickingSphere = 
				mSceneMgr->getEntity("pickingSphere");
			if (pickingSphere->isVisible())
			{
				pickingSphere->setVisible(false);
			}

			Ogre::Entity* springLine = 
				mSceneMgr->getEntity("springLine");
			if (springLine->isVisible())
			{
				springLine->setVisible(false);
			}
		}

		// Return true to continue looping.
		return true;
	}
Esempio n. 15
0
TEST(intersection, triangle_tetrahedron) {
    TIntersectionType it;
    double area;

    // create tetrahedron
    TPoint point0(0.00, 0.00, 0.00);
    TPoint point1(3.00, 0.00, 0.00);
    TPoint point2(0.00, 3.00, 0.00);
    TPoint point3(0.00, 0.00, 3.00);
    TTetrahedron tetrahedron(point0, point1, point2, point3);

    // triangle is in tetrahedron
    TPoint pointA(0.50, 0.50, 0.50);
    TPoint pointB(0.50, 1.50, 0.50);
    TPoint pointC(1.50, 0.50, 0.50);
    TTriangle triangle(pointA, pointB, pointC);

    xprintf(Msg, "Test - triangle is in tetrahedron\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.5);

    // triangle is greater than tetrahedron, intersection is triangle
    pointA.SetCoord(-3.0, 2.0, 2.0);
    pointB.SetCoord(2.0, -3.0, 2.0);
    pointC.SetCoord(2.0, 2.0, 2.0);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - triangle is greater than tetrahedron, intersection is triangle\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.5);

    // intersection is tetragon
    pointA.SetCoord(-0.50, 0.50, 1.00);
    pointB.SetCoord(2.00, 0.50, 1.00);
    pointC.SetCoord(2.00, 3.00, 1.00);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is tetragon\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.875);

    // intersection is pentagon
    pointA.SetCoord(-1.0, 2.00, 1.00);
    pointB.SetCoord(1.50, 2.00, 1.00);
    pointC.SetCoord(1.50,-0.5 , 1.00);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is pentagon\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 0.5+0.5+0.5*3.0/4.0);

    // intersection is hexagon (plane parallel to x-y)
    pointA.SetCoord(2.00, 2.00, 0.50);
    pointB.SetCoord(2.00, -1.00, 0.50);
    pointC.SetCoord(-1.00, 2.00, 0.50);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is hexagon (plane parallel to x-y)\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 2.375);

    // intersection is hexagon
    pointA.SetCoord(0.25, 2.00, 1.00);
    pointB.SetCoord(2.25, 1.00, -1.00);
    pointC.SetCoord(0.25, -1.00, 3.00);
    triangle.SetPoints(pointA, pointB, pointC);

    xprintf(Msg, "Test - intersection is hexagon\n");
    GetIntersection(triangle, tetrahedron, it, area);
    EXPECT_FLOAT_EQ(area, 3.477919);
}
Esempio n. 16
0
int main()
{
  /*
   Geom::Point3d a(1, 2, 3);
   Geom::Point3d b(4, 5, 6);
   
   Geom::Vector3d product = a.cross(b);
   
   std::cout << "Cross Product: " << product.to_string() << std::endl;
   
   std::cout << "Dot Product: " << a.dot(b) << std::endl;
   
   std::cout << "A: " << a.to_string() << std::endl;
   std::cout << "Magnitude of A: " << a.magnitude() << std::endl;
   
   a.unitize();
   std::cout << "A: " << a.to_string() << std::endl;
   std::cout << "Magnitude of A: " << a.magnitude() << std::endl;
   
   Mesh::Surface* surf = new Mesh::Surface();
   
   std::cout << "Total Nodes: " << surf->total_nodes() << std::endl;
   surf->create_node(a);
   std::cout << "Total Nodes: " << surf->total_nodes() << std::endl;
   */
  
  if(true) {
    std::cout << "====================== SQUARE ======================" << std::endl;
    
    Geom::Point3d point0(0.0, 0.0, 0.0);
    Geom::Point3d point1(1.0, 0.0, 0.0);
    Geom::Point3d point2(1.0, 1.0, 0.0);
    Geom::Point3d point3(0.0, 1.0, 0.0);
    
    Mesh::Surface* square = new Mesh::Surface();
    Mesh::Node* node0 = square->create_node(point0);
    Mesh::Node* node1 = square->create_node(point1);
    Mesh::Node* node2 = square->create_node(point2);
    Mesh::Node* node3 = square->create_node(point3);
    
    square->create_face(node0, node1, node2);
    square->create_face(node0, node2, node3);
    
    square->rebuild_mesh_connectivity();
    
    std::cout << "Mesh has " << square->total_nodes() << " nodes." << std::endl;
    std::cout << "Mesh has " << square->total_edges() << " edges." << std::endl;
    std::cout << "Mesh has " << square->total_faces() << " faces." << std::endl;
    
    std::cout << "Mesh has " << square->total_main_edges() << " main edges." << std::endl;
    std::cout << "Mesh has " << square->total_border_edges() << " border edges." << std::endl;
    std::cout << "Mesh has " << square->get_boundary_loops().size() << " border loops." << std::endl;
  }
  
  if(true) {
    std::cout << "====================== TETRAHEDRON ======================" << std::endl;
    Mesh::Surface* tetrahedron = new Mesh::Surface();
    
    Geom::Point3d point0(0.0, 0.0, 0.0);
    Geom::Point3d point1(1.0, 0.0, 0.0);
    Geom::Point3d point2(0.0, 1.0, 0.0);
    Geom::Point3d point3(0.0, 0.0, 1.0);
    
    Mesh::Node* node0 = tetrahedron->create_node(point0);
    Mesh::Node* node1 = tetrahedron->create_node(point1);
    Mesh::Node* node2 = tetrahedron->create_node(point2);
    Mesh::Node* node3 = tetrahedron->create_node(point3);
    
    tetrahedron->create_face(node0, node2, node1);
    tetrahedron->create_face(node3, node1, node2);
    tetrahedron->create_face(node1, node3, node0);
    tetrahedron->create_face(node3, node2, node0);
    
    tetrahedron->rebuild_mesh_connectivity();
    
    std::cout << "Mesh has " << tetrahedron->total_nodes() << " nodes." << std::endl;
    std::cout << "Mesh has " << tetrahedron->total_edges() << " edges." << std::endl;
    std::cout << "Mesh has " << tetrahedron->total_faces() << " faces." << std::endl;
    
    std::cout << "Mesh has " << tetrahedron->total_main_edges() << " main edges." << std::endl;
    std::cout << "Mesh has " << tetrahedron->total_border_edges() << " border edges." << std::endl;
    std::cout << "Mesh has " << tetrahedron->get_boundary_loops().size() << " border loops." << std::endl;
  }
  
  return 0;
}
Esempio n. 17
0
CRhinoCommand::result CGenPianoVis::RunCommand( const CRhinoCommandContext& context )
{

  Cscript1PlugIn& plugin = script1PlugIn();

  if( !plugin.IsDlgVisible() )
  {
    return CRhinoCommand::nothing;
  }


  /*GET THE LAYER NAME*/
  CRhinoGetString gs;
  gs.SetCommandPrompt( L"NAME OF LAYER WHICH CONTAINS VISIONAL PLANE : " );
  gs.GetString();
  if( gs.CommandResult() != CRhinoCommand::success )
  {
	  return gs.CommandResult();
  }
  /*VALIDATE THE STRING*/
  ON_wString layer_name = gs.String();
  layer_name.TrimLeftAndRight();
  if( layer_name.IsEmpty() )
  {
	  return CRhinoCommand::cancel;
  }
    
  /*GET A REFERENCE TO THE LAYER TABLE*/
  CRhinoLayerTable& layer_table = context.m_doc.m_layer_table;
 
  /*FIND THE LAYER*/ 
  int layer_index = layer_table.FindLayer(layer_name );
  if( layer_index < 0 )
  {
    RhinoApp().Print( L"LAYER \"%s\" DOES NOT EXIST.\n", layer_name );
	
  }
  else
  {
	  ON_Layer currentLayer;
	  int numLayers = layer_table.LayerCount();
	  layer_table.SetCurrentLayerIndex(layer_index);
	  for(int i = 0; i < numLayers; i++)
	  {
		  if(i != layer_index)
		  {
			  currentLayer = layer_table[i];
			  currentLayer.SetVisible(false);
			  layer_table.ModifyLayer(currentLayer, i);
		  }
	  }
	  context.m_doc.Redraw();
	  const CRhinoLayer& layer = context.m_doc.m_layer_table[layer_index];
	  ON_SimpleArray<CRhinoObject*> obj_list;

	 
	  
      int object_count = context.m_doc.LookupObject( layer, obj_list );
      if( object_count > 0 )
      {
		 /********************************************************************/
		 //CRhinoObject* obj = obj_list[0];
		 //if( obj && obj->IsSelectable() )
		 //{
			// obj->Select(true);
			// obj->Highlight(true);
			// m_doc.Redraw();
		 //}
		 /********************************************************************/
		 //aniello gegin
		 // Disable redrawing
		 //CRhinoView::EnableDrawing( FALSE ); meglio tenerlo disabilitato altrimenti la schermata non si aggiorna.
 
         // Get the next runtime object serial number before scripting
		 unsigned int first_sn = CRhinoObject::NextRuntimeObjectSerialNumber();
	     //aniello end
	     /////////////////////
		  
		 CRhinoGetObject gc;
		 gc.SetCommandPrompt( L"SELECT LINE TO EXTEND" );
         gc.SetGeometryFilter( CRhinoGetObject::curve_object );
         gc.GetObjects( 1, 1 );
		 if(gc.CommandResult() == CRhinoCommand::success )
		 {
			const CRhinoObjRef& objref = gc.Object(0);
            const ON_Curve* pC = ON_Curve::Cast( objref.Geometry() );
			ON_Curve* crv0 = pC->DuplicateCurve();
			
			bool rc0 = RhinoExtendCurve(crv0, CRhinoExtend::Line, 1, 5);
			bool rc1 = RhinoExtendCurve(crv0, CRhinoExtend::Line, 0, 15);
			context.m_doc.ReplaceObject(objref, *crv0 );
            context.m_doc.Redraw();

			///// begin prova memorizzazione id o name linea pv
		////ON_UUID uuid1 = gc->Attributes().m_uuid;
		////	ON_UUID uuid1 = objref.ObjectUuid();
		//	//ON_UuidToString( uuid1, cvrPrima );
		//	 const CRhinoObject* obj5 = objref.Object();
  //          ON_UUID uuid1 = obj5->Attributes().m_uuid;

		//	pvcurva =  uuid1;
		//	ON_3dmObjectAttributes obj_attribs = obj5->Attributes();
		//	CRhinoGetString gs;
  //gs.SetCommandPrompt( L"New object name" );
  //gs.SetDefaultString( obj_attribs.m_name );
  //gs.AcceptNothing( TRUE );
  //gs.GetString();
  //if( gs.CommandResult() != CRhinoCommand::success )
  //  return gs.CommandResult();
 
  //// Get the string entered by the user
  //ON_wString obj_name = gs.String();
  //obj_name.TrimLeftAndRight();
 
  //// Is name the same?
  //if( obj_name.Compare(obj_attribs.m_name) == 0 )
  //  return CRhinoCommand::nothing;

		//	//ON_wString obj_name = (L"stringanome");
		//	obj_attribs.m_name = obj_name;
		//	context.m_doc.ModifyObjectAttributes( objref, obj_attribs );

///// end prova memorizzazione id o name linea pv



			
			ON_3dPoint p0 = crv0->PointAtStart();
            ON_3dPoint p1 = crv0->PointAtEnd();
 
			CRhinoGetNumber gn;
			//double default_value = 30;
			gn.SetCommandPrompt( L"ENTER ANTERIOR ANGLE FOR EXTENSION in grad: " );
			gn.SetCommandPromptDefault(L"30");
			gn.SetDefaultNumber(30);
			//gn.AcceptNothing(true);
			gn.GetNumber();
			double alphaAngle = gn.Number();
			
			

			gn.SetCommandPrompt( L"ENTER ANTERIOR LENGTH FOR EXTENSION in mm: " );
			gn.SetCommandPromptDefault(L"80");
			gn.SetDefaultNumber(80);
			gn.GetNumber();
			double antLen = gn.Number();

			gn.SetCommandPrompt( L"ENTER ANTERIOR FILLET RADIUS in mm: " );
			gn.SetCommandPromptDefault(L"6");
			gn.SetDefaultNumber(6);
			gn.GetNumber();
			double antRad = gn.Number();

			gn.SetCommandPrompt( L"ENTER POSTERIOR ANGLE FOR EXTENSION default <ALPHA + 10°= 40°> : " );
			gn.SetCommandPromptDefault(L"40");
			gn.SetDefaultNumber(40);
			gn.GetNumber();
			double betaAngle = gn.Number();

			gn.SetCommandPrompt( L"ENTER POSTERIOR LENGTH FOR EXTENSION in mm: " );
			gn.SetCommandPromptDefault(L"80");
			gn.SetDefaultNumber(80);
			gn.GetNumber();
			double posLen = gn.Number();

			gn.SetCommandPrompt( L"ENTER POSTERIOR FILLET RADIUS in mm: " );
			gn.SetCommandPromptDefault(L"13");
			gn.SetDefaultNumber(13);
			gn.GetNumber();
			double posRad = gn.Number();

		
			ON_3dPoint pointStart;
            ON_3dPoint pointEnd;
		 
			//// Fillet radius
			//double radius = 1.0;
		 
			// Do the fillet calculation
			double t0 = 0.0, t1 = 0.0;
 
			ON_Plane plane;
			plane.plane_equation.y = 1.0;

			pointStart = crv0->PointAtStart();
			
			pointEnd   = crv0->PointAtEnd();

			ON_3dPoint point0((pointStart.x - posLen*cos(betaAngle*acos(-1.0)/180.0)), 0.0, (pointStart.z + posLen*sin(betaAngle*acos(-1.0)/180.0)));
			ON_3dPoint point1((pointEnd.x + antLen*cos(alphaAngle*acos(-1.0)/180.0)), 0.0, (pointEnd.z - antLen*sin(alphaAngle*acos(-1.0)/180.0)));

			/**********************************/
			/*CREATE THE LINE CURVES TO FILLET*/ 
			/**********************************/
			ON_LineCurve curve0( pointStart, point0 ); //LINEA A SINISTRA IN FRONT VIEW
			ON_LineCurve curve1( point1, pointEnd );   //LINEA A DESTRA IN FRONT VIEW 

			
			/***************************************************/
			/*FILLET AT THE END/START POINTS OF THE LINE CURVES*/ 
			/***************************************************/
			double curve0_t = crv0->Domain().Max();
			double curve1_t = curve1.Domain().Min();
			ON_3dPoint PuntoAltezzaTacco = curve1.m_line.to;
			AltezzaTacco = PuntoAltezzaTacco;
			
			
			
			if( RhinoGetFilletPoints(curve1,  *crv0, antRad, curve1_t, curve0_t, t1, t0, plane) )
			{
				/*******************************/
				/*TRIM BACK THE TWO LINE CURVES*/ 
				/*******************************/
				ON_Interval domain1( curve1.Domain().Min(), t1 );
				curve1.Trim( domain1 );
		 
				ON_Interval domain0( crv0->Domain().Min(), t0 );
				crv0->Trim( domain0 );

		        /**************************/
				/*COMPUTE THE FILLET CURVE*/ 
				/**************************/
				ON_3dVector radial0 = curve1.PointAt(t1) - plane.Origin();
				radial0.Unitize();
		 
				ON_3dVector radial1 = crv0->PointAt(t0) - plane.Origin();
				radial1.Unitize();
		 
				double angle = acos( radial0 * radial1 );
				ON_Plane fillet_plane( plane.Origin(), radial0, radial1 );
				ON_Arc fillet( fillet_plane, plane.Origin(), antRad, angle );
		 
				/******************/
				/*ADD THE GEOMETRY*/
				/******************/
				context.m_doc.AddCurveObject( curve1 );
				context.m_doc.ReplaceObject(objref, *crv0 );
				context.m_doc.AddCurveObject( fillet );
				context.m_doc.Redraw();
			}
			

			t0 = 0.0, t1 = 0.0;
			/*FILLET AT THE START POINTS OF THE LINE CURVES*/
			curve0_t = crv0->Domain().Min();
			curve1_t = curve0.Domain().Min();

			if( RhinoGetFilletPoints(curve0, *crv0, posRad, curve1_t, curve0_t, t1, t0, plane) )
			{
				// Trim back the two line curves
				ON_Interval domain0( t1, curve0.Domain().Max() );
				curve0.Trim( domain0 );
		 
				ON_Interval domain1( t0, crv0->Domain().Max() );
				crv0->Trim( domain1 );
				

				/*COMPUTE THE FILLET CURVE*/ 
				ON_3dVector radial0 = curve0.PointAt(t1) - plane.Origin();
				radial0.Unitize();
		 
				ON_3dVector radial1 = crv0->PointAt(t0) - plane.Origin();
				radial1.Unitize();
		 
				double angle = acos( radial0 * radial1 );
				ON_Plane fillet_plane( plane.Origin(), radial0, radial1 );
				ON_Arc fillet( fillet_plane, plane.Origin(), posRad, angle );
		 
				/*ADD THE GEOMETRY*/ 
				context.m_doc.AddCurveObject( curve0 );
				context.m_doc.ReplaceObject(objref, *crv0 );
				context.m_doc.AddCurveObject( fillet );
				context.m_doc.Redraw();
			}
			/******************/
			/*CLEAN UP OR LEAK*/ 
			/******************/
			delete crv0;
			crv0 = 0;

			
			// code temp
// aniello begin
// Get the next runtime object serial number after scripting
  unsigned int next_sn = CRhinoObject::NextRuntimeObjectSerialNumber();

 
  // Enable redrawing
  //CRhinoView::EnableDrawing( TRUE );
 
  // if the two are the same, then nothing happened
 /* if( first_sn == next_sn )
    //return CRhinoCommand::nothing;
	return;
*/ //commento questo per far compilare :-)
 
  // The the pointers of all of the objects that were added during scripting
  ON_SimpleArray<const CRhinoObject*> objects;
  for( unsigned int sn = first_sn; sn < next_sn; sn++ )
  {
    const CRhinoObject* obj = context.m_doc.LookupObjectByRuntimeSerialNumber( sn );
    if( obj && !obj->IsDeleted() )
      objects.Append( obj );
  }
 
  /*
  // Sort and cull the list, as there may be duplicates
  if( objects.Count() > 1 )
  {
    objects.HeapSort( CompareObjectPtr );
    const CRhinoObject* last_obj = objects[objects.Count()-1];
    for( int i = objects.Count()-2; i >= 0; i-- )
    {
      const CRhinoObject* prev_obj = objects[i];
     if( last_obj == prev_obj )
        objects.Remove(i);
      else
        last_obj = prev_obj;
    }
  }
	*/
  // Do something with the list...
  for( int i = 0; i < objects.Count(); i++ )
  {
    const CRhinoObject* obj = objects[i];
    if( obj->IsSelectable(true) )
      obj->Select( true );
  }
//aniello end
			//end code temp

  			/*********************/
			/*JOIN LINES TOGETHER*/
			/*********************/
			ON_SimpleArray<const ON_Curve*> lines;
			ON_SimpleArray<CRhinoObject*> objectsLine;
			ON_SimpleArray<ON_Curve*> output;
			double tolerance = context.m_doc.AbsoluteTolerance();
			int LinesCount = context.m_doc.LookupObject( layer, objectsLine);

			if( LinesCount > 0 )
			{
				for(int i = 0; i < LinesCount; i++)
				{
					const CRhinoCurveObject* curve_obj = CRhinoCurveObject::Cast( objectsLine[i] );
					if( curve_obj )
					{
						lines.Append(curve_obj->Curve());
					}
				}
			}
		    if( RhinoMergeCurves(lines, output, tolerance) )
		    {
				for(int i = 0; i < output.Count(); i++ )
				{
					CRhinoCurveObject* crv = new CRhinoCurveObject;
					crv->SetCurve( output[i] );
					if( context.m_doc.AddObject(crv) )
					{
						crv->Select();
					}
					else
					{
						delete crv;
					}
				}
		    }
			/************************/
			/*DELETE CHILDREN CURVES*/
			/************************/
			for(int i = 0; i < LinesCount; i++ )
			{
				context.m_doc.DeleteObject(objectsLine[i]);
			}
			context.m_doc.Redraw();

			/*************************/
			/*END JOIN LINES TOGETHER*/
			/*************************/
	     }
	  }/*CHIUSURA IF( OBJECT_COUNT > 0 )*/
  }/*CHIUSURA ELSE*/

  return CRhinoCommand::success;
}
RTC::ReturnCode_t CollisionDetector::onExecute(RTC::UniqueId ec_id)
{
    static int loop = 0;
    loop++;
    if (m_qRefIn.isNew()) {
	m_qRefIn.read();

        TimedPosture tp;
        tp.time = 0;

	assert(m_qRef.data.length() == m_robot->numJoints());
        if ( m_use_viewer ) {
          for (int i=0; i<m_glbody->numLinks(); i++){
            ((GLlink *)m_glbody->link(i))->highlight(false);
          }
        }
        //set robot model's angle for collision check(two types)
        //  1. current safe angle .. check based on qRef
        //  2. recovery or collision angle .. check based on q'(m_recover_jointdata)
        if (m_safe_posture && m_recover_time == 0) {           // 1. current safe angle
          for ( int i = 0; i < m_robot->numJoints(); i++ ){
	    m_robot->joint(i)->q = m_qRef.data[i];
          }
        }else{   // recovery or collision angle
          for ( int i = 0; i < m_robot->numJoints(); i++ ){
	    m_robot->joint(i)->q = m_recover_jointdata[i];
          }
        }
        //collision check process in case of angle set above
	m_robot->calcForwardKinematics();
        m_safe_posture = true;
	coil::TimeValue tm1 = coil::gettimeofday();
        std::map<std::string, VclipLinkPairPtr>::iterator it = m_pair.begin();
	for (unsigned int i = 0; it != m_pair.end(); i++, it++){
	    VclipLinkPairPtr p = it->second;
            hrp::Vector3 point0(0,0,0), point1(0,0,0);
	    double d = p->computeDistance(point0.data(), point1.data());
            tp.lines.push_back(std::make_pair(point0, point1));
	    if ( d <= p->getTolerance() ) {
		m_safe_posture = false;
		hrp::JointPathPtr jointPath = m_robot->getJointPath(p->link(0),p->link(1));
		std::cerr << i << "/" << m_pair.size() << " pair: " << p->link(0)->name << "/" << p->link(1)->name << "(" << jointPath->numJoints() << "), distance = " << d << std::endl;
              if ( m_use_viewer ) {
                ((GLlink *)p->link(0))->highlight(true);
                ((GLlink *)p->link(1))->highlight(true);
              }
	    }
	}
        //     mode : m_safe_posture : recover_time  : set as q
        // safe     :           true :            0  : qRef
        // collison :          false :         >  0  : q( do nothing)
        // recover  :           true :         >  0  : q'
        //std::cerr << "m_recover_time: " << m_recover_time << std::endl;
        coil::TimeValue tm2 = coil::gettimeofday();
        if (m_safe_posture && m_recover_time == 0){ // safe mode
          //std::cerr << "safe-------------- " << std::endl;
          for ( int i = 0; i < m_q.data.length(); i++ ) {
            m_q.data[i] = m_qRef.data[i];
          }
        } else {
          if(m_safe_posture){  //recover
            //std::cerr << "recover-------------- " << std::endl;
            for ( int i = 0; i < m_q.data.length(); i++ ) {
              m_q.data[i] = m_recover_jointdata[i];
            }
            m_recover_time = m_recover_time - i_dt;
          }else{ //collision
            //std::cerr << "collision-------------- " << std::endl;
            //do nothing (stay previous m_q)
            m_recover_time = default_recover_time;      // m_recover_time should be set based on difference between qRef and q
            m_interpolator->set(m_q.data.get_buffer()); //Set initial angle
          }
          //calc q'
#if 0
          //linear interpolation (dangerous)
          for ( int i = 0; i < m_q.data.length(); i++ ) {
            m_recover_jointdata[i] = m_q.data[i] + (m_qRef.data[i] - m_q.data[i]) / m_recover_time;
          }
#else
          //minjerk interpolation
          m_interpolator->setGoal(m_qRef.data.get_buffer(), m_recover_time);
          m_interpolator->get(m_recover_jointdata);
#endif
        }
        if ( DEBUGP ) {
          std::cerr << "check collisions for for " << m_pair.size() << " pairs in " << (tm2.sec()-tm1.sec())*1000+(tm2.usec()-tm1.usec())/1000.0 
                    << " [msec], safe = " << m_safe_posture << ", time = " << m_recover_time << " " << m_q.data[0] << " " << m_q.data[1] 
                    << " " << m_q.data[2] << " " << m_q.data[3] << " " << m_q.data[4] << " " << m_q.data[5] << " " << m_q.data[6] << std::endl;
        }
        //
        m_qOut.write();

        tp.posture.resize(m_qRef.data.length());
        for (size_t i=0; i<tp.posture.size(); i++) tp.posture[i] = m_q.data[i];
        m_log.add(tp);
    }
    if ( m_use_viewer ) m_window.oneStep();
    return RTC::RTC_OK;
}
Esempio n. 19
0
CRhinoCommand::result CGenCylinder::RunCommand( const CRhinoCommandContext& context )
{

	Cscript1PlugIn& plugin = script1PlugIn();
	if( !plugin.IsDlgVisible() )
	{
		return CRhinoCommand::nothing;
	}

	/*****************************************/
	/*CHECKING IF THERE IS ALREADY A CYLINDER*/
	/*****************************************/
	const CRhinoLayer& layer = context.m_doc.m_layer_table.CurrentLayer();
	ON_SimpleArray<CRhinoObject*> objects;
	int object_count = context.m_doc.LookupObject( layer, objects );
	const CRhinoBrepObject* brep_obj;
	const CRhinoCurveObject* curve_obj;
	const CRhinoSurfaceObject* surface_obj;
	int surf_count=0;
	if( object_count > 0 )
	{
		int brep_obj_count = 0;
		int polycurve_count = 0;
		const CRhinoObject* object = 0;
		for(int i = 0; i < object_count; i++ )
		{
			object = objects[ i ];
			/************************************/
			/*TRY CASTING AS A RHINO BREP OBJECT*/ 
			/************************************/
			brep_obj = CRhinoBrepObject::Cast( object );
			if( brep_obj && object->IsSolid())
			{
				brep_obj_count++;
			}
			/*******************************/
			/*TRY CASTING AS A CURVE OBJECT*/ 
			/*******************************/
			curve_obj = CRhinoCurveObject::Cast( object );
			if( curve_obj )
			{
				polycurve_count++;
			}
			//surface_obj = CRhinoSurfaceObject::Cast( object );
		 //   if( surface_obj )
		 //   {
			//surf_count++;
		 //   }
		}
		if( brep_obj_count == 0)
		{
			ON_3dPoint center_point( 0.0, 0.0, 0.0 );
			double radius = 63.5;
			int __count = plugin.m_dialog->m_comboAltTacco.GetCount();

			int nIndex = plugin.m_dialog->m_comboAltTacco.GetCurSel();
			CString strCBText;
			plugin.m_dialog->m_comboAltTacco.GetLBText( nIndex, strCBText);
			int height = _wtoi(strCBText);


			ON_3dPoint height_point( 0.0, 0.0, height);
			ON_3dVector zaxis = height_point - center_point;
			ON_Plane planeCir( center_point, zaxis );

			/*ADD CIRCLE FOR CYLINDER'S BASE*/
			ON_Circle circle( planeCir, radius );

			/*ADD CYLINDER*/
			ON_Cylinder cylinder( circle, zaxis.Length() );
			ON_Brep* brep = ON_BrepCylinder( cylinder, TRUE, TRUE );
			unsigned int first_SN;
			unsigned int next_SN;
			if( brep )
			{
				first_SN = CRhinoObject::NextRuntimeObjectSerialNumber();
				/********************/
				/*TRANSLATE CYLINDER*/
				/********************/
				int nIndex1 = plugin.m_dialog->AltezzaFondelloControllo.GetCurSel();
				CString strCBText1;
				plugin.m_dialog->AltezzaFondelloControllo.GetLBText( nIndex1, strCBText1);
				int altfondello = _wtoi(strCBText1);
				ON_wString obj_nameCyl = L"CILINDRO";
								
				
				brep->Translate(ON_3dVector( 0.0, 0.0, -altfondello));
				CRhinoBrepObject* cylinder_object = new CRhinoBrepObject();
				cylinder_object->SetBrep( brep );
				if( context.m_doc.AddObject(cylinder_object) )
				{
					context.m_doc.Redraw();
					next_SN = CRhinoObject::NextRuntimeObjectSerialNumber();
					if( first_SN == next_SN )
					{
						return CRhinoCommand::nothing;
					}
					else
					{
						SetNametoObject(context.m_doc,first_SN,obj_nameCyl,true);			  
					}
				}
				else
				{
					delete cylinder_object;
				}

				/*********************************************/
				/*               DA SISTEMARE                */
				/*********************************************/
				
				CRhinoSnapContext snap;
				bool dec1 = snap.SnapToPoint(ON_3dPoint(63.5, 0.0, (height - altfondello)));
				bool dec2 = snap.SnapToPoint(ON_3dPoint(63.5, 0.0, -altfondello));
				bool dec3 = snap.SnapToPoint(ON_3dPoint(63.5, 0.0, 0.0));
				if(dec1 && dec2)
				{
					CRhinoLinearDimension* dim_obj = new CRhinoLinearDimension();
					ON_Plane plane( ON_zx_plane );
					plane.SetOrigin( ON_3dPoint(63.5, 0.0, 0.0) );
					dim_obj->SetPlane( plane );
					ON_3dPoint pt_1(63.5, 0.0, (height - altfondello));
					ON_3dPoint pt_2(63.5, 0.0, -altfondello);

					double u, v;
					plane.ClosestPointTo( pt_1, &u, &v );
					dim_obj->SetPoint( 0, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 1, ON_2dPoint(u, (v + height/2)) );


					plane.ClosestPointTo( pt_2, &u, &v );
					dim_obj->SetPoint( 2, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 3, ON_2dPoint(u, (v + height/2)) );

					dim_obj->UpdateText();
					 
					if( context.m_doc.AddObject(dim_obj) )
					{
						context.m_doc.Redraw();
					}		
					else
					{
						delete dim_obj;
					}
				}
				/*********************************************/
				/*               DA SISTEMARE                */
				/*********************************************/
				if(dec2 && dec3)
				{
					CRhinoLinearDimension* dim_obj = new CRhinoLinearDimension();
					ON_Plane plane( ON_zx_plane );
					plane.SetOrigin( ON_3dPoint(63.5, 0.0, 0.0) );
					dim_obj->SetPlane( plane );
					ON_3dPoint pt_1(63.5, 0.0, 0.0);
					ON_3dPoint pt_2(63.5, 0.0, -altfondello);

					double u, v;
					plane.ClosestPointTo( pt_1, &u, &v );
					dim_obj->SetPoint( 0, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 1, ON_2dPoint(u, (v + height/2)) );


					plane.ClosestPointTo( pt_2, &u, &v );
					dim_obj->SetPoint( 2, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 3, ON_2dPoint(u, (v + height/2)) );

					dim_obj->UpdateText();
					 
					if( context.m_doc.AddObject(dim_obj) )
					{
						context.m_doc.Redraw();
					}		
					else
					{
						delete dim_obj;
					}
				}
				/*********************************************/
				/*               DA SISTEMARE  By Nello              */
				/*********************************************/
				
				ON_3dPoint provapunto2 = AltezzaTacco;
				ON_3dPoint provapunto(59.5,0,provapunto2.z);
				provapunto.z-=0.7;
				ON_3dPoint pt_1(59.5, 0.0, (height - altfondello));
				CRhinoLinearDimension* dim_obj = new CRhinoLinearDimension();
					ON_Plane plane( ON_zx_plane );
					plane.SetOrigin(pt_1);
					dim_obj->SetPlane( plane );
					//ON_3dPoint pt_1(63.5, 0.0, 0.0);
					ON_3dPoint pt_2 = provapunto;

					double u, v;
					plane.ClosestPointTo( pt_1, &u, &v );
					dim_obj->SetPoint( 0, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 1, ON_2dPoint(u, (v + height/2)) );


					plane.ClosestPointTo( pt_2, &u, &v );
					dim_obj->SetPoint( 2, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 3, ON_2dPoint(u, (v + height/2)) );

					dim_obj->UpdateText();
					 
					if( context.m_doc.AddObject(dim_obj) )
					{
						context.m_doc.Redraw();
					}		
					else
					{
						delete dim_obj;
					}
				
					/*INIZIO FUNZIONE CONTROLLO*/
			
					if ( (height - altfondello)>=provapunto.z+10){
						::RhinoApp().Print( L"Funzione controllo altezza OK");
					}
					else{
						::RhinoApp().Print( L"Funzione controllo altezza NOK: CONTROLLARE!! Il valore della testa e' minore del valore minimo di 10 mm. Occorre diminuire l'altezza del fondello o aumentare l'altezza dello stampo.");
					}


				/*********************************************/
				/*           CREATE FONDELLO PLANE           */
				/*********************************************/

				ON_3dPoint point0((63.5 + 20.0),0.0, 0.0);
				ON_3dPoint point1(-(63.5 + 20.0),0.0, 0.0);
				ON_LineCurve curve0( point0, point1 );

				context.m_doc.AddCurveObject(curve0);
				context.m_doc.Redraw();


				/******************************************************/
				/*****************************/
				/*USER GIVES NAME TO SURFACES*/ 
				/*****************************/
				unsigned int first_sn;
				unsigned int next_sn;
				ON_wString obj_name;
				object_count = context.m_doc.LookupObject( layer, objects );
				for(int i = 0; i < object_count; i++ )
				{
					object = objects[ i ];
					first_sn = CRhinoObject::NextRuntimeObjectSerialNumber();

					/*******************************/
					/*TRY CASTING AS A CURVE OBJECT*/ 
					/*******************************/
					curve_obj = CRhinoCurveObject::Cast( object );
					if( curve_obj )
					{
						const ON_Geometry* geo = curve_obj->Geometry();
						const ON_Curve* curve00 = ON_Curve::Cast(geo); 
						ON_3dPoint point  = curve00->PointAt(0.0);
						ON_3dPoint point_ = curve00->PointAt(1.0);
						if((point.z + point_.z)/2 > 0.0)
						{
							obj_name = L"SURFPV";
						}
						else
						{
							obj_name = L"SURFFO";
						}
						ON_3dPoint point0(point.x, (point.y + 70.0), point.z);
						ON_3dPoint point1(point.x, (point.y - 70.0), point.z);
						ON_LineCurve* curve = new ON_LineCurve();
						curve->SetStartPoint(point0);
						curve->SetEndPoint(point1);
						ON_SumSurface sumSurf0;
						sumSurf0.Create(*curve, *curve00);

						if( context.m_doc.AddSurfaceObject(sumSurf0) )
						{

							context.m_doc.Redraw();
							next_sn = CRhinoObject::NextRuntimeObjectSerialNumber();
							if( first_sn == next_sn )
							{
								return CRhinoCommand::nothing;
							}
							else
							{
								SetNametoObject(context.m_doc,first_sn,obj_name,true);			  
							}
						}

					}
				}/*CLOSED FOR*/

				//int R = 0;
				//object_count = context.m_doc.LookupObject( layer, objects );
				//for(int i = 0; i < object_count; i++)
				//{
				//	object = objects[ i ];
				//	const CRhinoCurveObject* surface_obj = CRhinoCurveObject::Cast(object);
				//	if(surface_obj)
				//	{
				//		R++;
				//	}
				//}

				 // // Get the string entered by the user
				 // ON_wString obj_name = gs.String();
				 // obj_name.TrimLeftAndRight();
				 //
				 // // Is name the same?
				 // if( obj_name.Compare(obj_attribs.m_name) == 0 )
					//return CRhinoCommand::nothing;
				 //
				 // // Modify the attributes of the object
				 // obj_attribs.m_name = obj_name;
				 // context.m_doc.ModifyObjectAttributes( objref, obj_attribs );
				 // if(selectobjectbyuuid_s(context.m_doc,obj_Surf[j],false))
				 // {
					//int R = 0;
				 // }



			  
			  ON_wString obj_Surf[2];
			  ON_wString name;
              obj_Surf[0] = L"SURFPV";
			  obj_Surf[1] = L"SURFFO";
			  object_count = context.m_doc.LookupObject( layer, objects );
			  int R = 0;
			  /************************/
			  /*TRY SPLITTING THE BREP*/
			  /************************/
			  for(int j = 0; j < 2; j++)
			  {
				  for(int i = 0; i < object_count; i++)
				  {
					  object = objects[ i ];

					  /*MAKE COPY OF OBJECT ATTRIBUTES. THIS OBJECTS*/ 
					  /*HOLDS AN OBJECT'S USER-DEFINED NAME.*/ 
					  ON_3dmObjectAttributes obj_attribs = object->Attributes();
			
					  name = object->Attributes().m_name;

					  surface_obj = CRhinoSurfaceObject::Cast( object );
					  if( surface_obj && !surface_obj->IsSolid())
					  {
						  ON_wString obj_SurfLoc = obj_Surf[j];

						  /*IS THE CUTTING SURFACE?*/
						  if( obj_SurfLoc.Compare(name) == 0 )
						  {							
							R++;
						  }
					  }/*CHIUSURA IF SUPERFICIE*/
				  } 
				 

				 // /************************/
				 // /*PICK THE BREP TO SPLIT*/ 
				 // /************************/
				 // CRhinoGetObject go;
				 // go.SetCommandPrompt( L"SELECT SOLID TO SPLIT" );
				 // go.SetGeometryFilter( CRhinoGetObject::polysrf_object  );//CRhinoGetObject::surface_object | CRhinoGetObject::polysrf_object 
				 // go.GetObjects( 1, 1 );
				 // if( go.CommandResult() != success )
				 // {
					//return go.CommandResult();
				 // }
				 // else
				 // {
					//	RhinoMessageBox(L"CYLINDER IS SELECTED", PlugIn()->PlugInName(), MB_OK | MB_ICONEXCLAMATION );
				 // }
				 //
				 // const CRhinoObjRef& split_ref = go.Object(0);
				 //
				 // const CRhinoObject* split_object = split_ref.Object();
				 // if( !split_object )
				 // {
					//return failure;
				 // }
				 //
				 // const ON_Brep* split = split_ref.Brep();
				 // if( !split )
				 // {
					//return failure;
				 // }

				 // ON_SimpleArray<ON_Brep*> pieces;
				 // double tol = context.m_doc.AbsoluteTolerance();
			 
				 // /***********************/
				 // /*PICK THE CUTTING BREP*/
				 // /***********************/
				 // go.SetCommandPrompt( L"SELECT CUTTING SURFACE OR POLYSUFACE" );
				 // go.SetGeometryFilter( CRhinoGetObject::surface_object | CRhinoGetObject::polysrf_object  ); 
				 // go.EnablePreSelect( FALSE );
				 // go.EnableDeselectAllBeforePostSelect( FALSE );
				 // go.GetObjects( 1, 2 );
				 // if( go.CommandResult() != success )
				 // {
					//return go.CommandResult();
				 // }

				 // const ON_Brep* cutter = go.Object(0).Brep();
				 // if( !cutter )
				 // {
					//return failure;
				 // }
				 //

				 // if( !RhinoBrepSplit(*split, *cutter, tol, pieces) )
				 // {
					//RhinoApp().Print( L"UNABLE TO SPLIT BREP.\n" );
				 // }
				 //
				 // int i, count = pieces.Count();
				 // if( count == 0 | count == 1 )
				 // {
					//if( count == 1 )
					//{
					//  delete pieces[0];
					//}
					//return nothing;
				 // }
				 //
				 // CRhinoObjectAttributes attrib = split_object->Attributes();
				 // attrib.m_uuid = ON_nil_uuid; 
				 //
				 // const CRhinoObjectVisualAnalysisMode* vam_list = split_object->m_analysis_mode_list;
				 //
				 // for( i = 0; i < count; i++ )
				 // {
					//CRhinoBrepObject* brep_object = new CRhinoBrepObject( attrib );
					//if( brep_object )
					//{
					//  brep_object->SetBrep( pieces[i] );
					//  if( context.m_doc.AddObject(brep_object) )
					//  {
					//	RhinoCopyAnalysisModes( vam_list, brep_object );

					//  }
					//  else
					//  {
					//	delete brep_object;
					//  }
					//}
				 // }
				 //
				 // context.m_doc.DeleteObject( split_ref ); 
				 // context.m_doc.Redraw();
			  }



		    /*CREATE A NEW LAYER*/
			  ON_Layer layer;
			  int layer_index = 0;
			  ON_Color color = ON_Color(0, 0, 0);
			  ON_wString layer_name_FONDELLO = L"FONDELLO";
			  layer.SetLayerName( layer_name_FONDELLO );
			  layer.SetPlotColor(color.Green());

			/*ADD THE LAYER TO THE LAYER TABLE*/ 
			  layer_index = context.m_doc.m_layer_table.AddLayer( layer );

			  ON_wString layer_name_MATRICE  = L"MATRICE";
			  layer.SetLayerName( layer_name_MATRICE );
			  layer.SetColor(color.Red());

			/*ADD THE LAYER TO THE LAYER TABLE*/ 
			  layer_index = context.m_doc.m_layer_table.AddLayer( layer );


			  ON_wString layer_name_FISSO    = L"FISSO";
			  layer.SetLayerName( layer_name_FISSO );
			  layer.SetColor(color.Blue());

			/*ADD THE LAYER TO THE LAYER TABLE*/ 
			  layer_index = context.m_doc.m_layer_table.AddLayer( layer );
	  
			  context.m_doc.Redraw();
			/*********************************************************/
			}
		}/*CLOSED IF OVER CHECKING BREP COUNT OBJECT*/
		else
		{
			RhinoMessageBox(L"THERE IS ALREADY A CYLINDER OBJECT", PlugIn()->PlugInName(), MB_OK | MB_ICONEXCLAMATION );
		}
	}
	/**********************************************************************/



  return CRhinoCommand::success;
}
Esempio n. 20
0
	bool PlaypenApp::appFrameStarted(opal::real dt)
	{
		// Do per-frame application-specific things here.

		// Handle speech input.
		bool keepLooping = true;
		bool makeObject = false;
		std::string material;
		ObjectType type;
		std::string outputString;
		while (voce::getRecognizerQueueSize() > 0)
		{
			std::string s = voce::popRecognizedString();

			//// Check if the string contains 'quit'.
			//if (std::string::npos != s.rfind("quit"))
			//{
			//	keepLooping = false;
			//}

			// Check if we should reset.
			if (std::string::npos != s.rfind("reset"))
			{
				// Make sure the PhysicalCamera isn't grabbing anything.
				mPhysicalCamera->release();
				destroyAllPhysicalEntities();
				setupInitialPhysicalEntities();
				voce::synthesize("reset");
				return true;
			}

			// Check for material color.
			if (std::string::npos != s.rfind("yellow"))
			{
				outputString += "yellow";
				material = "Plastic/Yellow";
			}
			else if (std::string::npos != s.rfind("red"))
			{
				outputString += "red";
				material = "Plastic/Red";
			}
			else if (std::string::npos != s.rfind("blue"))
			{
				outputString += "blue";
				material = "Plastic/Blue";
			}
			else if (std::string::npos != s.rfind("green"))
			{
				outputString += "green";
				material = "Plastic/Green";
			}
			else if (std::string::npos != s.rfind("purple"))
			{
				outputString += "purple";
				material = "Plastic/Purple";
			}
			else if (std::string::npos != s.rfind("orange"))
			{
				outputString += "orange";
				material = "Plastic/Orange";
			}
			else
			{
				// Default to dark gray.
				material = "Plastic/DarkGray";
			}

			// Check for object type.
			if (std::string::npos != s.rfind("box"))
			{
				outputString += " box";
				type = OBJECT_TYPE_BOX;
				makeObject = true;
			}
			else if (std::string::npos != s.rfind("sphere"))
			{
				outputString += " sphere";
				type = OBJECT_TYPE_SPHERE;
				makeObject = true;
			}
			else if (std::string::npos != s.rfind("wall"))
			{
				outputString += " wall";
				type = OBJECT_TYPE_WALL;
				makeObject = true;
			}
			else if (std::string::npos != s.rfind("tower"))
			{
				outputString += " tower";
				type = OBJECT_TYPE_TOWER;
				makeObject = true;
			}
			else if (std::string::npos != s.rfind("character"))
			{
				outputString += " character";
				type = OBJECT_TYPE_RAGDOLL;
				makeObject = true;
			}

			if (makeObject)
			{
				voce::synthesize(outputString);
				createObject(material, type);
			}
		}

		// Update the grasping spring line.
		if (mPhysicalCamera->isGrasping())
		{
			Ogre::Entity* pickingSphere = 
				mSceneMgr->getEntity("pickingSphere");
			if (!pickingSphere->isVisible())
			{
				pickingSphere->setVisible(true);
			}

			Ogre::Entity* springLine = 
				mSceneMgr->getEntity("springLine");
			if (!springLine->isVisible())
			{
				springLine->setVisible(true);
			}

			opal::Point3r desiredPos = 
				mPhysicalCamera->getGraspGlobalPos();
			Ogre::Vector3 point0(desiredPos[0], desiredPos[1], desiredPos[2]);

			opal::Point3r attachPos = mPhysicalCamera->getAttachGlobalPos();
			Ogre::Vector3 point1(attachPos[0], attachPos[1], attachPos[2]);

			pickingSphere->getParentSceneNode()->setPosition(point1);

			Ogre::Vector3 lineVec = point0 - point1;
			if (!lineVec.isZeroLength())
			{
				Ogre::SceneNode* springLineNode = 
					springLine->getParentSceneNode();
				springLineNode->setPosition(0.5 * (point0 + point1));
				
				springLineNode->setDirection(lineVec);
				springLineNode->setScale(0.1, 0.1, lineVec.length());
			}
			else
			{
				springLine->setVisible(false);
			}
		}
		else
		{
			Ogre::Entity* pickingSphere = 
				mSceneMgr->getEntity("pickingSphere");
			if (pickingSphere->isVisible())
			{
				pickingSphere->setVisible(false);
			}

			Ogre::Entity* springLine = 
				mSceneMgr->getEntity("springLine");
			if (springLine->isVisible())
			{
				springLine->setVisible(false);
			}
		}

		// Return true to continue looping.
		return keepLooping;
	}
Esempio n. 21
0
GLuint Model_PLY::LoadFlat(GLchar* filename)
{
	char* pch = strstr(filename, ".ply");

	if (pch != nullptr)
	{
		// Open file and read it.
		FILE* file;
		fopen_s(&file, filename, "rb");

		fseek(file, 0, SEEK_END);
		long fileSize = ftell(file); //ftell is get the current position of pointer.

		try
		{
			vertexBuffer = (float*)malloc(fileSize);
		}
		catch (char*) // but why should be char* here?
		{
			return -1;
		}

		if (vertexBuffer == nullptr)
		{
			return -1;
		}

		fseek(file, 0, SEEK_SET);

		faceTriangles = (float*)malloc(fileSize * sizeof(float));
		verticesNormals = (float*)malloc(fileSize * sizeof(float));

		if (file != nullptr)
		{
			int i = 0;
			int temp = 0;
			int normalIndex = 0;
			int triangleIndex = 0;
			char buffer[1000]; // every time gets 1000 buffer.

			fgets(buffer, 300, file); //ply

			// READ HEADER
			//-------------------

			// Find number of vertexes
			// e.g. element vertex 12
			while (strncmp("element vertex", buffer, strlen("element vertex")) != 0)
			{
				fgets(buffer, 300, file);
			}
			strcpy_s(buffer, sizeof(buffer) - strlen("element vertex"), buffer + strlen("element vertex")); //erase "element vertex" header.
			sscanf_s(buffer, "%i", &this->numConnectedPoints); //read integer value for num of points.
			std::cout << "Number of connected point is : " << numConnectedPoints << std::endl;

			// find number of faces
			// e.g. element face 10
			fseek(file, 0, SEEK_SET);
			while (strncmp("element face", buffer, strlen("element face")) != 0)
			{
				fgets(buffer, 300, file);
			}
			strcpy_s(buffer, sizeof(buffer) - strlen("element face"), buffer + strlen("element face")); //erase "element face" header.
			sscanf_s(buffer, "%i", &this->numFaces); //read integer value for num of faces.
			std::cout << "Number of faces is : " << numFaces << std::endl;

			// go to end_header
			while (strncmp(("end_header"), buffer, strlen("end_header")) != 0)
			{
				fgets(buffer, 300, file);
			}


			// Read vertexes
			i = 0;
			for (GLuint iter = 0; iter < this->numConnectedPoints; ++iter)
			{
				fgets(buffer, 300, file);

				sscanf_s(buffer, "%f %f %f", &vertexBuffer[i], &vertexBuffer[i + 1], &vertexBuffer[i + 2]);
				i += 3;
			}

			// Read faces
			i = 0;
			for (GLuint iter = 0; iter < this->numFaces; ++iter)
			{
				fgets(buffer, 300, file);

				if ('3' == buffer[0])
				{
					int vert0 = 0, vert1 = 0, vert2 = 0;
					buffer[0] = ' ';
					sscanf_s(buffer, "%i%i%i", &vert0, &vert1, &vert2);




					// set values to faceTriangles.
 					faceTriangles[triangleIndex] = vertexBuffer[3 * vert0];
 					faceTriangles[triangleIndex + 1] = vertexBuffer[3 * vert0 + 1];
					faceTriangles[triangleIndex + 2] = vertexBuffer[3 * vert0 + 2];
 					faceTriangles[triangleIndex + 3] = vertexBuffer[3 * vert1];
					faceTriangles[triangleIndex + 4] = vertexBuffer[3 * vert1 + 1];
					faceTriangles[triangleIndex + 5] = vertexBuffer[3 * vert1 + 2];
 					faceTriangles[triangleIndex + 6] = vertexBuffer[3 * vert2];
					faceTriangles[triangleIndex + 7] = vertexBuffer[3 * vert2 + 1];
					faceTriangles[triangleIndex + 8] = vertexBuffer[3 * vert2 + 2];
 
 					// going to calculate verticesNormals.
					vec3 point0(vertexBuffer[3 * vert0], vertexBuffer[3 * vert0 + 1], vertexBuffer[3 * vert0 + 2]);
					vec3 point1(vertexBuffer[3 * vert1], vertexBuffer[3 * vert1 + 1], vertexBuffer[3 * vert1 + 2]);
					vec3 point2(vertexBuffer[3 * vert2], vertexBuffer[3 * vert2 + 1], vertexBuffer[3 * vert2 + 2]);
 
 					vec3 norm(0.0f);
 					this->calculateNormal(point0, point1, point2, norm);

 					for (int offset = 0; offset < 9; ++offset)
 					{
						verticesNormals[normalIndex + offset] = norm[offset % 3]; //set normal for each point.
 					}
 
 					normalIndex += 9; //set offset to next triangle. 

					triangleIndex += 9; //set offset to next triangle.
					numConnectedTriangles += 3; // three points per triangle
				}
				i += 3;
			}

			fclose(file);

		}
		else
		{
			std::cerr << "Error : Can not open file." << std::endl;
		}
	}
	else
	{
		std::cerr << "Error : File do not have a \".ply\" extension." << std::endl;
	}
	return 0;
}