Пример #1
0
SpriteSheet& SpriteSheet::add_frame(const std::vector<sf::Vector2f>& points){

  auto width = vector_length(points[0] - points[1]);
  auto height = vector_length(points[0] - points[2]);
  
  FrameInfo frame = {
    {
      sf::Vector2f(0, 0),
      sf::Vector2f(0, height),
      sf::Vector2f(width, height),
      sf::Vector2f(width, 0),
    },
    {
      points[0],
      points[1],
      points[2],
      points[3],
    },
    {0, 0, width, height }
  };
  
  m_frames.push_back(frame);

  return *this;
}
Пример #2
0
static void scalar_op(Array arr, double s, char op, Array ans)
/* Elementwise scalar operations */
{
    int i;

    assert (test_array_conform(arr, ans));

    switch (op) {
	case '*':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr)[i] * s;
	    break;
	case '+':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr)[i] + s;
	    break;
	case '/':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr)[i] / s;
	    break;
	case '-':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr)[i] - s;
	    break;
	default:
	    printf("Unknown op in array_op");
    }
}
Пример #3
0
static void __bounding_get_effective_position(const Bounding *b, Vector *result)
{
    assert(b && "Bad bounding pointer.");
    assert(b->origin && b->previous_origin && b->orientation && b->direction && "Bad bounding data.");
    assert(result && "Bad result pointer.");

    Vector p = *b->origin,
           t,
           side;
    if (!vector_eq(b->orientation, b->direction))
    {
        vector_vector_mul(b->orientation, b->direction, &side);
    }
    else
    {
        vector_get_orthogonal(b->direction, &side);
    }
    VECTOR_NORMALIZE(&side);

    double sx, sy, sz;
    vector_scale(b->direction, b->offset.x, &t);
    sx = vector_length(&t);
    vector_scale(&side, b->offset.y, &t);
    sy = vector_length(&t);
    vector_scale(b->orientation, b->offset.z, &t);
    sz = vector_length(&t);

    p.x += sx;
    p.y += sy;
    p.z += sz;

    *result = p;
}
Пример #4
0
static void array_op(Array arr1, Array arr2, char op, Array ans)
/* Element-wise array operations */
{
    int i;

    assert (test_array_conform(arr1, arr2));
    assert (test_array_conform(arr2, ans));

    switch (op) {
	case '*':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr1)[i] * VECTOR(arr2)[i];
	    break;
	case '+':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr1)[i] + VECTOR(arr2)[i];
	    break;
	case '/':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr1)[i] / VECTOR(arr2)[i];
	    break;
	case '-':
	    for (i = 0; i < vector_length(ans); i++)
		VECTOR(ans)[i] = VECTOR(arr1)[i] - VECTOR(arr2)[i];
	    break;
	default:
	    printf("Unknown op in array_op");
    }
}
Пример #5
0
/* FIXME: incompatible with current design of soft-method-calling */
VALUE
thread_schedule()
{
	int i;
	VALUE th;

	/* don't increment round-robin count if in critical section */
	if ( TEST(thr_crit) || (vector_length(thr_stk) <= 1) )
	{
		if (!THREAD(cur_thr)->alive_p)
			thread_deadlock();
		return cur_thr;
	}

	/* find the highest priority thread; lowest round-robin count otherwise */
	for (i = 0; i < vector_length(thr_stk); i++)
	{
		th = (VALUE)vector_aref(thr_stk, i);
		if ( (THREAD(th)->prio > THREAD(cur_thr)->prio) ||
		     (!(THREAD(th)->prio < THREAD(cur_thr)->prio) && (THREAD(th)->cnt < THREAD(cur_thr)->cnt)) )
		{
			if (THREAD(th)->alive_p)
				cur_thr = (VALUE)vector_aref(thr_stk, i);
			else
				THREAD(th)->cnt++;
		}
	}

	THREAD(cur_thr)->cnt++;
	return cur_thr;
}
Пример #6
0
void constr_scale(float A[3], float B[3], float C[3], float D[3],
	     float fixed_point[3], 
	     int g)
      /*  scales group by |AB|/|CD| */
{
  double lAB,lCD,s;
  float AB[3], CD[3];
  vector_sub(B, A, AB);
  vector_sub(D, C, CD);
  lAB=vector_length(AB);
  lCD=vector_length(CD);
  if(lCD==0) 
    {
      printf("scaling refused: |CD| = 0 !!!\n");
      return;
    }
  s=lAB/lCD;
  
  if(s== 1.0)
    {
      printf("scaling by 1 does not change anything !!!\n");
      return;
    }

  backup();
  group_scale(g, s, s, s, fixed_point, group, vertex, vertex_used);
}
Пример #7
0
static double dice_coefficient(const double *vec1, const double *vec2,
                               size_t veclen, bool normalize)
{
    if (!vec1 && !vec2)
        return 1.0 ;
    else if (!vec1 || !vec2)
        return (veclen == 0) ? 1.0 : 0.0 ;// no overlap, but same if zero-length
    double prod(0.0) ;
    double sum(0.0) ;
    if (normalize)
    {
        double length1 = vector_length(vec1,veclen) ;
        double length2 = vector_length(vec2,veclen) ;
        // prevent division by zero -- if ||vector|| is zero, all elements are
        //   zero, so it doesn't matter what we divide by; pick 1.0
        if (length1 == 0) length1 = 1.0 ;
        if (length2 == 0) length2 = 1.0 ;
        for (size_t i = 0 ; i < veclen ; i++)
        {
            double v1 = vec1[i] / length1 ;
            double v2 = vec2[i] / length2 ;
            prod += (v1 * v2) ;
            sum += (v1 + v2) ;
        }
    }
    else
    {
        for (size_t i = 0 ; i < veclen ; i++)
        {
            prod += (vec1[i] * vec2[i]) ;
            sum += (vec1[i] + vec2[i]) ;
        }
    }
    return (sum > 0.0) ? (2.0 * prod / sum) : 0.0 ;
}
Пример #8
0
static double manhattan_distance(const double *vec1, const double *vec2,
                                 size_t veclen, bool normalize)
{
    double distance = 0.0 ;
    if (normalize)
    {
        double length1 = vector_length(vec1,veclen) ;
        double length2 = vector_length(vec2,veclen) ;
        // prevent division by zero -- if ||vector|| is zero, all elements are
        //   zero, so it doesn't matter what we divide by; pick 1.0
        if (length1 == 0) length1 = 1.0 ;
        if (length2 == 0) length2 = 1.0 ;
        for (size_t i = 0 ; i < veclen ; i++)
        {
            distance += fabs((vec1[i] / length1) - (vec2[i] / length2)) ;
        }
    }
    else
    {
        for (size_t i = 0 ; i < veclen ; i++)
        {
            distance += fabs(vec1[i] - vec2[i]) ;
        }
    }
    return distance ;
}
Пример #9
0
static double circle_product(const double *vec1, const double *vec2,
                             size_t veclen, bool normalize)
{
    if (!vec1 || !vec2)
        return 0.0 ;
    double sum(0.0) ;
    if (normalize)
    {
        double length1 = vector_length(vec1,veclen) ;
        double length2 = vector_length(vec2,veclen) ;
        // prevent division by zero -- if ||vector|| is zero, all elements are
        //   zero, so it doesn't matter what we divide by; pick 1.0
        if (length1 == 0) length1 = 1.0 ;
        if (length2 == 0) length2 = 1.0 ;
        for (size_t i = 0 ; i < veclen ; i++)
        {
            double v1 = vec1[i] / length1 ;
            double v2 = vec2[i] / length2 ;
            sum += minimum(v1,v2) ;
        }
    }
    else
    {
        for (size_t i = 0 ; i < veclen ; i++)
        {
            double v1 = vec1[i] ;
            double v2 = vec2[i] ;
            sum += minimum(v1,v2) ;
        }
    }
    return sum ;
}
Пример #10
0
TEST_F(Vector2Test, orthonormal_basis_creates_perpendicular_vectors_of_length_1)
{
    if (random_vector != random_vector2) {
        generate_orthonormal_basis(random_vector, random_vector2);
        EXPECT_NEAR(0.0, dot_product(random_vector, random_vector2), PRECISION);
        EXPECT_NEAR(1.0, vector_length(random_vector), PRECISION);
        EXPECT_NEAR(1.0, vector_length(random_vector2), PRECISION);
    }
}
Пример #11
0
void main( int argc, char **argv)
{
   double state_vect2[6], jd = atof( argv[3]);
   const int home_planet = atoi( argv[1]), planet_no = atoi( argv[2]);
   double dist = 0., pvsun[6];
   int i, pass, center = 12;
   void *p;
   char *filename;

   if( argc > 4)
      center = atoi( argv[4]);
   printf( "Year approx %.3lf\n", 2000. + (jd - 2451545.) / 365.25);
   filename = "d:\\guide_b\\jpl_eph\\sub_de.406";
   p = jpl_init_ephemeris( filename, NULL, NULL);
   if( !p)
      {
      printf( "JPL data not loaded\n");
      exit( -1);
      }
   jpl_pleph( p, jd, center, home_planet, state_vect2, 1);
   printf( "Observer state vector:\n");
   show_state_vector( state_vect2);
// for( i = 0; i < 3; i++)
//    pvsun[i] = jpl_get_pvsun( p)[i];
   for( pass = 0; pass < 4; pass++)
      {
      double state_vect[6], ang;
      char buff[30];

      jpl_pleph( p, jd - dist * AU_IN_KM / (SPEED_OF_LIGHT * 86400.),
                     center, planet_no, state_vect, 1);
      if( pass == 3)
         {
         for( i = 0; i < 3; i++)
            pvsun[i] = state_vect[i] + jpl_get_pvsun( p)[i];
//          pvsun[i] += state_vect[i];
         printf( "%.11lf %.11lf %.11lf\n", pvsun[0], pvsun[1], pvsun[2]);
         printf( "Dist to sun: %.11lf\n", vector_length( pvsun));
         }
      for( i = 0; i < 6; i++)
         state_vect[i] -= state_vect2[i];
      dist = vector_length( state_vect);
      show_state_vector( state_vect);

      ang = atan2( state_vect[1], state_vect[0]) * 12. / PI;
      format_base_sixty( buff, ang + 12.);
      buff[15] = '\0';
      printf( "%s   ", buff + 1);      /* skip leading '+' */

      ang = -asin( state_vect[2] / dist) * 180. / PI;
      format_base_sixty( buff, ang);
      buff[14] = '\0';
      printf( "%s   %.11lf (%.3lf km)\n", buff, dist, dist * AU_IN_KM);
      }
   jpl_close_ephemeris( p);
}
Пример #12
0
inline boolformula_t *cdnfformula_to_boolformula (conjunction * f) {
    boolformula_t* ret=boolformula_conjunction_new(vector_length(f)), *temp;
    uscalar_t i;
    for (i = 0; i < vector_length (f); i++) {
        temp=dnf_to_boolformula(vector_get(f,i));
        boolformula_set(ret, i, temp);
        boolformula_free(temp);
    }
    return ret;
}
Пример #13
0
void SCANLINE::Compute_Poly_Normal()
{
    vector< vector<float> > temp_vertex_normal(world_vertex.size(),vector<float>(3));

    vector <float> temp_I_light(3);//light intensity
    I_light = temp_I_light;
    I_light[0] = 1.0;//R
    I_light[1] = 0.64;//G
    I_light[2] = 0;//B

    vector <float> poly_vector_1(3);
    vector <float> poly_vector_2(3);
    vector <float> poly_normal(3);
    vector <float> temp_H(3);
    //calculus H
    vector_summation(temp_H, vec_light,vec_view);
    for (int j=0; j<3 ;j++ )
        H_specular.push_back(temp_H[j]/vector_length(temp_H));
    ///---Intensity ambient----Ka*I
    for (int j=0; j<3 ;j++ )
        Intensity_ambient.push_back(K_ambient*I_light[j]);
    for(int i=0; i<(int)Poly.size(); i++)
    {//compute polygon normal
        vector_subtraction(poly_vector_1,
                           world_vertex[Poly[i][2]-1],
                           world_vertex[Poly[i][1]-1]);
        vector_subtraction(poly_vector_2,
                           world_vertex[Poly[i][2]-1],
                           world_vertex[Poly[i][3]-1]);
        //compute 2 vector on one polygon
        cross_product3D(poly_normal, poly_vector_1, poly_vector_2);
        //calculus cross product

        for(int j=1; j<(int)Poly[i][0]+1 ;j++)
        {//add normal of neibor polygon to vertex
            for (int p=0; p<3 ;p++ )
                temp_vertex_normal[Poly[i][j]-1][p] += poly_normal[p];
        }

    }
    for(int i=0; i<(int)temp_vertex_normal.size() ;i++ )
    {
        float temp_length = vector_length(temp_vertex_normal[i]);
        for (int j=0; j<3 ;j++ )
        {   //normalize the normal on vertex
            temp_vertex_normal[i][j] = temp_vertex_normal[i][j] / temp_length;

        }
    }
    vertex_normal = temp_vertex_normal;
    //vertex normals as average of surrounding neibor polygon's normal


}
Пример #14
0
inline boolformula_t* monomial_to_boolformula (monomial *m)
{
    boolformula_t* ret=boolformula_conjunction_new(vector_length(m)),*temp;

    uscalar_t i;
    for (i = 0; i < vector_length (m); i++) {
        temp=boolformula_literal_new((lit)vector_get(m,i));
        boolformula_set(ret, i, temp);
        boolformula_free(temp);
    }
    return ret;
}
Пример #15
0
void constr_scale_in_direction(float A[3], float B[3], float C[3], float D[3],
			  float E[3], float F[3], float fixed_point[3], 
			  int g)
      /*  scales group by |AB|/|CD| in direction EF */
{
  double lAB,lCD,s;
  float AB[3], CD[3], EF[3], v[3], tmp[3];
  double sp;
  int i;

  if(vector_eq(E,F))
    {
      printf("scaling in direction EF refused: EF = 0 !!!\n");
      return;
    }

  vector_sub(B, A, AB);
  vector_sub(D, C, CD);
  vector_sub(F, E, EF);
  vector_normalize(EF);

  lAB=vector_length(AB);
  lCD=vector_length(CD);
  if(lCD==0) 
    {
      printf("scaling refused: |CD| = 0 !!!\n");
      return;
    }
  s=lAB/lCD;

  if(s== 1.0)
    {
      printf("scaling by 1 does not change anything !!!\n");
      return;
    }

  backup();  
  for(i=0; i<VERTEX_MAX; i++)
    if(vertex_used[i] && group[i]==g)
      {
	vector_sub(vertex[i], fixed_point, v);
	sp=scalar_product(EF,v);
	vectorcpy(tmp, EF);
	vector_scale((s-1)*sp, tmp);
	vector_add(v,tmp, v);
	vector_add(v, fixed_point, vertex[i]);
      }

}
Пример #16
0
static void cdnfformula_monomial_to_string (monomial *m)
{
    if (vector_length (m) == 0) {
        fprintf (stderr, "( T )");
    } else {
        uscalar_t i;
        fprintf (stderr, "( ");
        for (i = vector_length (m) - 1; i > 0; i--) {
            fprintf (stderr, "%ld & ", (lit) vector_get (m, i));
        }
        assert (i == 0);
        fprintf (stderr, "%ld ", (lit) vector_get (m, i));
        fprintf (stderr, " )");
    }
}
Пример #17
0
void cdnfformula_print (conjunction *f)
{
    if (vector_length (f) == 0) {
        fprintf (stderr, "{ T }");
    } else {
        uscalar_t i;
        fprintf (stderr, "{ ");
        for (i = vector_length (f) - 1; i > 0; i--) {
            cdnfformula_disjunction_to_string (vector_get (f, i));
            fprintf (stderr, " & ");
        }
        assert (i == 0);
        cdnfformula_disjunction_to_string (vector_get (f, i));
        fprintf (stderr, " }\n");
    }
}
Пример #18
0
static void cdnfformula_disjunction_to_string (disjunction *f)
{
    if (vector_length (f) == 0) {
        fprintf (stderr, "[ F ]");
    } else {
        uscalar_t i;
        fprintf (stderr, "[ ");
        for (i = vector_length (f) - 1; i > 0; i--) {
            cdnfformula_monomial_to_string (vector_get (f, i));
            fprintf (stderr, " | ");
        }
        assert (i == 0);
        cdnfformula_monomial_to_string (vector_get (f, i));
        fprintf (stderr, " ]");
    }
}
Пример #19
0
static PyObject *
nblist_pair_distances(PyObject *self, PyObject *args)
{
  PyNonbondedListObject *nblist = (PyNonbondedListObject *)self;
  struct nblist_iterator iterator;
  PyArrayObject *array;
  vector3 dv;
  double *d;
  int i;
#if defined(NUMPY)
  npy_intp n;
#else
  int n;
#endif
  if (!PyArg_ParseTuple(args, ""))
    return NULL;
  n = nblist_length(nblist);
#if defined(NUMPY)
  array = (PyArrayObject *)PyArray_SimpleNew(1, &n, PyArray_DOUBLE);
#else
  array = (PyArrayObject *)PyArray_FromDims(1, &n, PyArray_DOUBLE);
#endif
  if (array == NULL)
    return NULL;
  d = (double *)array->data;
  iterator.state = nblist_start;
  i = 0;
  while (nblist_iterate(nblist, &iterator)) {
    nblist->universe_spec->distance_function(dv, nblist->lastx[iterator.a1],
	nblist->lastx[iterator.a2], nblist->universe_spec->geometry_data);
    d[i++] = vector_length(dv);
  }
  return (PyObject *)array;
}
Пример #20
0
// return true if motion detected.
bool motion_detector::new_data(vector v)
{
	if (avg_count <= 0)
	{
		accumulated = v;
		avg_count = 1;

		return false;
	}

	// t = accumulated/avg_count - v
	vector t = accumulated;
	vector_divide(&t, avg_count);
	vector_sub(&t, &v);
	
	if (vector_length(&t) > threshold)
	{
		accumulated = v;
		avg_count = 1;

		return true;
	}

	vector_add(&accumulated, &v);
	avg_count++;

	return false;
}
Пример #21
0
Файл: json.c Проект: mlmhl/cWeb
static int marshal_array(json_node *n, buffer *buf) {
	int retCode;
	if (n->arr == NULL) {
		if ((retCode = buffer_append(buf, "null", 4)) > 0) {
			return retCode;
		}
	}
	else {
		if ((retCode = buffer_append(buf, "[", 1)) > 0) {
			return retCode;
		}
		size_t len = vector_length(n->arr);

		for (int i = 0; i < len; ++i) {
			void *p = NULL;
			if ((retCode = v_get_ptr(n->arr, i, &p)) > 0) {
				return retCode;
			}
			
			if ((retCode = marshal_recursive((json_node*)p, buf)) > 0) {
				return retCode;
			}
			if (i < len - 1 && (retCode = buffer_append(buf, ",", 1)) > 0) {
				return retCode;
			}
		}
		if ((retCode = buffer_append(buf, "]", 1)) > 0) {
			return retCode;
		}
	}
	return 0;
}
Пример #22
0
void op_ls(const char **params, int nparams) {
  assert(nparams > 0);
  inode_t *ino = vfs_open(params[0], &dummy_access);

  assert(ino && "File not found!");
  vector_t files = vfs_readdir(ino);

  for (unsigned i = 0; i < vector_length(&files); ++i) {
    dirent_t *dent = vector_get(&files, i);
    const char *c;
    switch (dent->ino->type) {
    case it_file: c = "FILE"; break;
    case it_dir: c = "DIR"; break;
    case it_chardev: c = "CDEV"; break;
    case it_blockdev: c = "BDEV"; break;
    case it_fifo: c = "FIFO"; break;
    case it_socket: c = "SOCK"; break;
    default: assert(0);
    }
    kprintf("[[%s]] %s : nlink %d mode %x ctime %d mtime %d atime %d uid %d gid %d size %d\n",
            c,
            dent->name,
            dent->ino->nlink, dent->ino->mode,
            dent->ino->ctime, dent->ino->mtime, dent->ino->atime,
            dent->ino->uid, dent->ino->gid, dent->ino->size);
  }
}
Пример #23
0
int main(int argc, char *argv[]) {
	vector a;
	
	vector_init(&a, 0);

	// test for ptr operations
	int n = 5;
	for (int i = 0; i < n; ++i) {
		char *str = malloc(2);
		v_push_ptr(&a, itoa(i, str, 10));
	}
	vector_print(&a);
	
	for (int i = 0; i < n / 2; ++i) {
		void *p = NULL;
		v_get_ptr(&a, i, &p);
		void *q  =NULL;
		v_get_ptr(&a, n - i - 1, &q);
		v_set_ptr(&a, i, q);
		v_set_ptr(&a, n - i - 1, p);
	}
	vector_print(&a);

	while (vector_length(&a) > 0) {
		v_pop_ptr(&a, NULL);
	}

	return 0;
}
Пример #24
0
/**
 * sphere_intersect - Check ray intersection with a sphere object.
 * @sphere: Pointer to sphere object
 * @ray:    Pointer to normalized ray object
 *
 * This function will test if a ray, @ray, will intersect a sphere, @sphere.
 * Imaging a ray R with origin at E and direction V intersecting a sphere with
 * center O and radius r. The intersection point will be detnoted P. A triangle
 * E-O-A, where A is a right angle can be drawn. The E-O side has length c, E-A
 * has length v and O-A has length b. See figure 1.
 *
 *                       ...---o O                               ...---o O
 *              c  ...---      |                        r  ...---      |
 *           ...---            | b                   ...---            | b
 *     ...---                  |               ...---                  |
 *  E o------------------------o A          P o------------------------o A
 *                 v                                       d
 *  fig 1.                                  fig 2.
 *
 * The v side will then have the same direction as V and i.e. will represent a
 * bit of the ray R.
 * Pythagorean theorem gives:
 *    v² + b² = c²   (1)
 *
 * A triangle P-O-A, where A is a right angle can be drawn. The P-O side has
 * length r (the sphere radius; remember point P is the sphere intersection
 * point), P-A has length d and O-A has length b (same side as previous drawn
 * triangle). See figure 2.
 *
 * Pythagorean theorem gives:
 *    d² + b² = r²   (2)
 *
 * (1) and (2) gives:
 *    (1): b² = c² - v²
 *    (2): d² = r² - b²
 *     =>  d² = r² - (c² - v²)   (3)
 *
 * For a vector a and a vector b, the dot product
 *    a * b = |a| |b| cos(p)
 * where |a| and |b| denote the the length of a and b, and p is the angle
 * between them. If both a and b have length one (i.e. they are unit vectors),
 * their dot product simply gives the cosine of the angle between them. If only
 * b is a unit vector, then the dot product a * b gives |a| cos(p), i.e. the
 * orthogonal projection of the vector a onto the vector b, with a minus sign
 * if the direction is opposite. This is called the scalar projection of a onto
 * b. For an intuitive understanding of this formula, recall from trigonometry
 * that
 *    cos(p) = a * b / |a|
 * where b is the unit vector
 *
 * If V is normalized (a unit vector), v is equal to the dot product of E-O
 * and V, i.e.
 *    v = E-O * V
 *
 * To determine whether an intersection occurs, we compute the value of d. That
 * is, if r² - (c² - v²) in (3) is less than 0, d can't be computed and the ray
 * does not intersect the sphere. If a intersection occurs, the distance from E
 * to the intersection point P is v - d.
 *
 * Returns:
 * Distance from @ray origin to the @sphere intersection point or 0 if no
 * intersection was found.
 */
float sphere_intersect (sphere_t* sphere, ray_t* ray)
{
   vector_t oe;   /* O-E vector in fig 1. */
   float    c;    /* Length of O-E vector, i.e. c in fig 1. */
   float    v;    /* Length of E-A vector, i.e. v in fig 1. */
   float    d2;   /* Computed d² value from formula (3). */

   /* Get the direction from the ray origin to the sphere center (O-E) */
   vector_sub (&oe, &sphere->center, &ray->origin);

   /* Get the length from the ray origin to the sphere center (c) */
   c = vector_length (&oe);

   /* Get the orthogonal projection of O-E vector onto the V vector,
    * i.e. the length of v. */
   v = vector_dot (&oe, &ray->dir);

   /* If the length of v is less than zero then the ray is going the opposite
    * direction and will therefore not intersect the sphere */
   if (v < 0 )
      return 0.0;

   /* Use formula (3) to check for sphere intersection */
   d2 = (sphere->radius * sphere->radius) - (c * c) + (v * v);

   /* If d2 is less than zero then d can not be computed, i.e. the ray does
    * not intersect the sphere */
   if (d2 < 0)
      return 0.0;

   /* The ray hit the sphere, return the distance from the ray origin to
    * the intersection point (P) */
   return v - sqrt(d2);
}
Пример #25
0
float CalcBestSine(float *points, int count, float X[4])
{
    float J[count][3];
    float R[count];

    int i;
    for(i = 0; i<count; i++) {
        
        /*
          y = a*sin(b*x+c) + d
        */
        float x = i, y = points[i];

        float inner = x/X[1] + X[2];
        J[i][0] = -sin(inner);
        J[i][1] = 2*x*X[0]*cos(inner)/(X[1]*X[1]);
        J[i][2] = -X[0]*cos(inner);

        R[i] = X[0]*sin(inner) - y;
   }

    if(ApplyLeastSquares(X, J, R, 3, count))
        return 0;
    
    return vector_length(R, count) / count;
}
Пример #26
0
float CalcBestLine(float *points, int count, float X[2])
{
    float J[count][2];
    float R[count];

    X[0] = X[1] = 0; /* initial conditions */
    int i;
    for(i = 0; i<count; i++) {
        /*
        a*x + b - y = 0
        dy/da = -x
        dy/db = -1
        */
        float x = i, y = points[i];

        J[i][0] = -x;
        J[i][1] = -1;

        R[i] = X[0]*x + X[1] - y;
   }

    if(ApplyLeastSquares(X, J, R, 2, count))
        return 0;

    return vector_length(R, count) / count;
}
Пример #27
0
bool line_segments_intersect(vector_float2 p1, vector_float2 p2, vector_float2 q1, vector_float2 q2)
{
    vector_float2 r = {p2.x - p1.x, p2.y - p1.y};
    vector_float2 s = {q2.x - q1.x, q2.y - q1.y};
    vector_float2 q_minus_p = {q1.x - p1.x, q1.y - p1.y};
    float r_cross_s = vector_cross(r, s).z;
    float q_minus_p_cross_r = vector_cross(q_minus_p, r).z;
    float q_minus_p_cross_s = vector_cross(q_minus_p, s).z;

    if (q_minus_p_cross_r == 0 && r_cross_s == 0) {
        // The lines are colinear
        float magnitude_r = vector_length(r);
        float s_dot_r = vector_dot(s, r);
        float t0 = vector_dot(q_minus_p, r) / magnitude_r;
        float t1 = t0 + s_dot_r / magnitude_r;

        return ((t0 >= 0 && t0 <= 1) || (t1 >= 0 && t1 <= 1));
    } else if (r_cross_s == 0 && q_minus_p_cross_r != 0) {
        // The lines are parallel and non-intersecting
        return false;
    } else if (r_cross_s != 0) {
        float t = q_minus_p_cross_s / r_cross_s;
        float u = q_minus_p_cross_r / r_cross_s;

        // Normally you'd want to test for 0 <= t <= 1 && 0 <= u <= 1, but
        // that would mean that two lines that share the same endpoint are
        // marked as intersecting, which isn't what we want for our use case.
        return t > 0 && t < 1 && u > 0 && u < 1;
    }

    return false;
}
Пример #28
0
void SCANLINE::Compute_pixel_intensity()
{
    vector <float> Intensity_diffuse(3);
    vector <float> Intensity_specular(3);

    for (int i = 0; i< Ymax ; i++ )
    	for (int j = 0; j< Xmax ; j++ )
    	{
    	    vector<float> pixel_normal(real_pixel[i][j].begin()+2,real_pixel[i][j].end());
    	    float temp_length = vector_length(pixel_normal);
            for (int p=0; p<3 ;p++ )
            {   //normalize the pixel normal
                pixel_normal[p] = pixel_normal[p] / temp_length;

            }
    	    float cos_diffuse = dot_product3D(pixel_normal,vec_light);
            float cos_specular = pow(dot_product3D(pixel_normal,H_specular),8);
            for (int p = 0; p< 3 ; p++ )
            {
                ///----------Intensity diffuse----Kd*I*(NL)
                Intensity_diffuse[p] = K_diffuse*I_light[p]*cos_diffuse;
                ///----------Intensity specular----Ks*I*(NH)^n
                Intensity_specular[p] = K_specular*I_light[p]*cos_specular;

                //---------------sum of all intensity--
                //replace normal value to RGB value in real_pixel
                real_pixel[i][j][p+2]= Intensity_diffuse[p] +
                    Intensity_specular[p] + Intensity_ambient[p];
            }

    	}
}
Пример #29
0
/* calculate best fit for a sphere
   (x-a)^2 + (y-b)^2 + (z-c)^2 = r^2
*/
static float CalcBestFitSphere(float (*points)[3], int count, float X[4])
{
    float J[count][4];
    float R[count];

    int i;
    for(i = 0; i<count; i++) {
        float d[3];
        vector_sub(d, points[i], X, 3);

        J[i][0] = -2*d[0];
        J[i][1] = -2*d[1];
        J[i][2] = -2*d[2];
        J[i][3] = -2*X[3];

        R[i] = X[3]*X[3] - magnitude2(d);
   }

    if(ApplyLeastSquares(X, J, R, 4, count))
        return 0;
    
    if(X[3] < 0 || isnan(X[0]))
        return 0;
    
    return vector_length(R, count) / count;
}
Пример #30
0
bool vector_equals(const Vector *one, const Vector *two, vector_comparitor comparitor)
{
    if(NULL == one || NULL == two || NULL == comparitor)
    {
        errno = EINVAL;
        return false;
    }

    if(one == two)
    {
        return true;
    }
    if(0 == one->length && 0 == two->length)
    {
        return true;
    }
    if(one->length != two->length)
    {
        return false;
    }
    for(size_t i = 0; i < vector_length(one); i++)
    {
        if(!comparitor(one->items[i], two->items[i]))
        {
            return false;
        }
    }
    return true;
}