/* @param d direction of ray * @param w basic vectors */ static void rayConstruction(point3 d, const point3 u, const point3 v, const point3 w, unsigned int i, unsigned int j, const viewpoint *view, unsigned int width, unsigned int height) { double xmin = -0.0175; double ymin = -0.0175; double xmax = 0.0175; double ymax = 0.0175; double focal = 0.05; point3 u_tmp, v_tmp, w_tmp, s; double w_s = focal; double u_s = xmin + ((xmax - xmin) * (float) i / (width - 1)); double v_s = ymax + ((ymin - ymax) * (float) j / (height - 1)); /* s = e + u_s * u + v_s * v + w_s * w */ multiply_vector(u, u_s, u_tmp); multiply_vector(v, v_s, v_tmp); multiply_vector(w, w_s, w_tmp); add_vector(view->vrp, u_tmp, s); add_vector(s, v_tmp, s); add_vector(s, w_tmp, s); /* p(t) = e + td = e + t(s - e) */ subtract_vector(s, view->vrp, d); normalize(d); }
static void localColor(color local_color, const color light_color, double diffuse, double specular, const object_fill *fill) { color ambi = { 0.1, 0.1, 0.1 }; color diff, spec, lightCo, surface; /* Local Color = ambient * surface + * light * ( kd * surface * diffuse + ks * specular) */ COPY_COLOR(diff, fill->fill_color); multiply_vector(diff, fill->Kd, diff); multiply_vector(diff, diffuse, diff); COPY_COLOR(lightCo, light_color); multiply_vectors(diff, lightCo, diff); COPY_COLOR(spec, light_color); multiply_vector(spec, fill->Ks, spec); multiply_vector(spec, specular, spec); COPY_COLOR(surface, fill->fill_color); multiply_vectors(ambi,surface, ambi); add_vector(diff, ambi, diff); add_vector(diff, spec, diff); add_vector(local_color, diff, local_color); }
static void solve_master(t_map *map) { map->solutions = new_vector(sizeof(t_vector *)); map->working_list = new_vector(sizeof(char *)); while (42) { map->len = map->list->len; map->working_list->len = 0; map->solution = new_vector(sizeof(char *)); solve(map, map->start, 1); if (map->solution->len == 0) { free_vector(map->solution); break ; } remove_used(map); add_vector(map->solution, map->end); add_vector(map->solution, NULL); add_vector(map->solutions, map->solution); } if (map->solutions->len || map->direct) tell_solutions(map); else write(1, "Error\n", 6); }
void rbm::cd_single_data(float * features_idx, float ** weights, float * hidden_bias, float * visible_bias, float ** delta_weights, float * delta_hidden_bias, float * delta_visible_bias, int K){ float * v = new float[num_visible_units]; float * h = new float[num_hidden_units]; float * p_h = new float[num_hidden_units]; float * p_v = new float[num_visible_units]; float * p_0 = new float[num_hidden_units]; float * wvc = new float[num_hidden_units]; float * whb = new float[num_visible_units]; copy_vec(v, features_idx, num_visible_units); // compute wv0 multiply_matrix_vector(weights, v, wvc, num_hidden_units, num_visible_units); // compute wvc0 add_vector(wvc, hidden_bias, num_hidden_units); // compute p_0 compute_probability_hidden_given_visible(wvc, p_0, num_hidden_units); // do K-step gibbs sampling for (int i=0; i<K; i++){ // compute wv multiply_matrix_vector(weights, v, wvc, num_hidden_units, num_visible_units); // compute wvc add_vector(wvc, hidden_bias, num_hidden_units); compute_probability_hidden_given_visible(wvc, p_h, num_hidden_units); sample_vector(h, p_h, num_hidden_units); // compute wh multiply_matrix_vector_column_wise(weights, h, whb, num_hidden_units, num_visible_units); // compute whb add_vector(whb, visible_bias, num_visible_units); compute_probability_visible_given_hidden(whb, p_v, num_visible_units); sample_vector(v, p_v, num_visible_units); } update_weights_gradient(delta_weights, features_idx, v, p_0, p_h, num_hidden_units, num_visible_units); update_visible_bias_gradient(delta_visible_bias, features_idx, v, num_visible_units); update_hidden_bias_gradient(delta_hidden_bias, p_0, p_h, num_hidden_units); delete[] v; delete[] h; delete[] p_h; delete[] p_v; delete[] p_0; delete[] wvc; delete[] whb; }
void draw_vector_balls(SDL_Renderer* r, SDL_Texture* t, struct vector3d ball[], int size, int width, int height) { SDL_Rect dest; dest.w = 20; dest.h = 20; int i; for (i = 0; i < size; i++) { struct vector3d z_translate = {0,0,2}; struct vector3d screen_translate = {width / 2 , height / 2, 0}; struct vector3d world = {ball[i].x, ball[i].y, ball[i].z}; add_vector(&world, &z_translate); multiply_vector(&world, 100); add_vector(&world, &screen_translate); float inv = 400 - world.z; float interp = inv / 342; dest.w = 30 * interp; dest.h = 30 * interp; /* if (i == 0) { dest.w = 30; dest.h = 30; printf("z = %.1f\n", world.z); } else { dest.w = 20; dest.h = 20; } */ dest.x = world.x; dest.y = world.y; SDL_RenderCopy(r, t, NULL, &dest); //draw screen pixel_buffer } }
void spacing_simulator_step(spacing_simulator *ss) { linked_list* vertices = ss->vg->vertices; linked_list* edges = ss->vg->edges; for(node* i = vertices->first; i != NULL;i = i->next){ visual_vertex* v1 = (visual_vertex*)i->element; v1->sim_data.speed = subtract_vector(make_vector_2d(400, 300), v1->position); v1->sim_data.speed = multiply_vector(normalize(v1->sim_data.speed), ss->origin_point_force); //debug_vector2d(v1->position, "POSITION"); //debug_vector2d(v1->sim_data.speed, "SPEED"); //debug("VVVVVVVVVV\n"); } for(node* i = vertices->first; i != NULL;i = i->next){ visual_vertex* v1 = (visual_vertex*)i->element; for(node* j = i->next;j != NULL;j = j->next){ visual_vertex* v2 = (visual_vertex*)j->element; vector_2d speed1 = subtract_vector(v1->position, v2->position); vector_2d speed2 = subtract_vector(v2->position, v1->position); float distance = calculate_distance(v1->position, v2->position); float force_factor = 100-distance; force_factor = (force_factor > 0 ? force_factor : 0)*2; speed1 = normalize(speed1); speed2 = normalize(speed2); speed1 = multiply_vector(speed1, force_factor); speed2 = multiply_vector(speed2, force_factor); v1->sim_data.speed = add_vector(v1->sim_data.speed, speed1); v2->sim_data.speed = add_vector(v2->sim_data.speed, speed2); //debug_vector2d(speed1, "SPEED1"); //debug_vector2d(speed2, "SPEED2"); } } for(node* i = edges->first;i != NULL;i = i->next){ visual_edge* e = (visual_edge*)i->element; vector_2d pos1 = e->v1->position; vector_2d pos2 = e->v2->position; float distance = calculate_distance(pos1, pos2); vector_2d direction1 = normalize(subtract_vector(pos2, pos1)); vector_2d direction2 = normalize(subtract_vector(pos1, pos2)); vector_2d speed1 = multiply_vector(direction1, distance*distance/500); vector_2d speed2 = multiply_vector(direction2, distance*distance/500); e->v1->sim_data.speed = add_vector(e->v1->sim_data.speed, speed1); e->v2->sim_data.speed = add_vector(e->v2->sim_data.speed, speed2); } for(node* i = vertices->first; i != NULL;i = i->next){ visual_vertex* v1 = (visual_vertex*)i->element; v1->sim_data.speed = multiply_vector(v1->sim_data.speed, ss->friction_factor); v1->position = add_vector(v1->position, v1->sim_data.speed); } }
/* @param t t distance * @return 1 means hit, otherwise 0 */ static int raySphereIntersection(const point3 ray_e, const point3 ray_d, const sphere *sph, intersection *ip, double *t1) { point3 l; subtract_vector(sph->center, ray_e, l); double s = dot_product(l, ray_d); double l2 = dot_product(l, l); double r2 = sph->radius * sph->radius; if (s < 0 && l2 > r2) return 0; float m2 = l2 - s * s; if (m2 > r2) return 0; float q = sqrt(r2 - m2); *t1 = (l2 > r2) ? (s - q) : (s + q); /* p = e + t1 * d */ multiply_vector(ray_d, *t1, ip->point); add_vector(ray_e, ip->point, ip->point); subtract_vector(ip->point, sph->center, ip->normal); normalize(ip->normal); if (dot_product(ip->normal, ray_d) > 0.0) multiply_vector(ip->normal, -1, ip->normal); return 1; }
void solve_parallel(matrix *a, double *x, double *b, int nproc, int steps) { double w = 1.0; double *it_vec = get_iterative_vector(a, w, b); matrix upper = get_iterative_upper_matrix(a, w); matrix lower = get_iterative_lower_matrix(a, w); double *z = malloc(a->n*sizeof(*z)); for (int i = 1; i < nproc; i++) send_matrix(upper, i); for (int s = 0; s < steps; s++) { for (int i = 1; i < nproc; i++) send_values(x, a->n, i); range r = compute_range(a->n, nproc, 0); mul_matrix_row(&upper, x, z, r.begin, r.end); for (int i = 1; i < nproc; i++) wait_for_results(z, a->n, nproc, i); add_vector(z, it_vec, a->n); forward_subst(&lower, x, z); } terminate_children(nproc); }
int add_clone(GapIO *io, char *CN, char *CV) { int err; int clone; int freerec; GClones c; /* find vector record */ c.vector = find_vector(io,CV); if (!c.vector) c.vector = add_vector(io,CV,1); /* allocate clone name */ c.name = allocate(io,GT_Text); err = TextWrite(io,c.name,CN,strlen(CN)); /* find new clone number */ clone = ++io->db.Nclones; ArrayRef(io->clones,clone-1); /* add clone to list */ arr(GCardinal,io->clones,clone-1) = freerec = allocate(io,GT_Clones); err = GT_Write(io,freerec,&c,sizeof(c),GT_Clones); /* write array */ err = ArrayDelay(io, io->db.clones, io->db.Nclones, io->clones); /* write db */ DBDelayWrite(io); return clone; }
BigInt BigInt::operator+(BigInt b) { BigInt a = *this; match_size_of_digits(a, b); extend(a, 1); extend(b, 1); add_vector(a.value_, b.value_); if (a.negative_ == b.negative_) { if (a.negative_) a.value_.pop_back(); } else { if (a.value_.back() >= 5) // not sure if this should be > or >= a.negative_ = true; else a.negative_ = false; a.value_.pop_back(); } clean_leading_digits(a); return a; }
void PTree::add_vectors(const LinAlg::System& las) { for(size_t i = 0; i < las.n_vectors(); ++i) { const LinAlg::ConstVector cv(i, las); add_vector(cv); } }
/* create_formation_enemies() * Fills a newly created formation with actual enemies */ void create_formation_enemies( game_state_t* GS, formation_t* formation, int top_tier, int amount ) { int i, new_tier; formation_t* f = formation; // Create enemies to fill the formation for( i = 0 ; i < amount ; i++ ) { // Adjust tier according to rank, decreasing with rank new_tier = max( TIER_1, top_tier - (f->ranks[i].coordinate.y - 1) ); //((i+1)/2) ) f->ranks[i].occupied_by = add_enemy( GS, new_tier, add_vector( f->position, f->ranks[i].position ), f->velocity, f ) ; } }
int main() { int a[3][3] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}}, i, row_sum = 0, sum = 0, pd[2]; // create a pipe if(pipe(pd) == -1) { error_exit("pipe() failed"); } // N = 3 for(i = 0; i < 3; ++i) { if(fork() == 0) { row_sum = add_vector(a[i]); if(write(pd[1], &row_sum, sizeof(int)) == -1) { error_exit("write() failed"); } return; } } for(i = 0; i < 3; ++i) { if(read(pd[0], &row_sum, sizeof(int)) == -1) { error_exit("read() failed"); } sum += row_sum; } printf("Sum of the array = %d\n", sum); return 0; }
void ContinuationSystem::init_data () { // Add a vector which stores the tangent "du/ds" to the system and save its pointer. du_ds = &(add_vector("du_ds")); // Add a vector which stores the tangent "du/ds" to the system and save its pointer. previous_du_ds = &(add_vector("previous_du_ds")); // Add a vector to keep track of the previous nonlinear solution // at the old value of lambda. previous_u = &(add_vector("previous_u")); // Add a vector to keep track of the temporary solution "y" of Ay=G_{\lambda}. y = &(add_vector("y")); // Add a vector to keep track of the "old value" of "y" which is the solution of Ay=G_{\lambda}. y_old = &(add_vector("y_old")); // Add a vector to keep track of the temporary solution "z" of Az=-G. z = &(add_vector("z")); // Add a vector to keep track of the Newton update during the constrained PDE solves. delta_u = &(add_vector("delta_u")); // Call the Parent's initialization routine. Parent::init_data(); }
DefaultLayout() { add_base(get_structlayout<CPipeDataSBase>()); add_simple(_T("a1"),&CPipeDataS::m_a1); add_simple(_T("a2"),&CPipeDataS::m_a2); add_simple(_T("b"),&CPipeDataS::m_b); add_simple(_T("String"),&CPipeDataS::m_str); add_vector(_T("Vec"),&CPipeDataS::m_vec,get_primitivelayout<long>()); add_struct(_T("Struct"),&CPipeDataS::m_struct,get_structlayout<CPipeDataSBase>()); }
void get_reflected_ray(t_ray* ray, t_object* obj, t_ray* new_ray) { new_ray->distance = 20000; mult_vector(&ray->dest, &new_ray->origin, ray->distance); add_vector(&new_ray->origin, &ray->origin, &new_ray->origin); get_normal(obj, &new_ray->origin, &new_ray->dest); mult_vector(&new_ray->dest, &new_ray->dest, dot_vector(&ray->dest, &new_ray->dest)); mult_vector(&new_ray->dest, &new_ray->dest, 2); sub_vector(&ray->dest, &new_ray->dest, &new_ray->dest); }
void BigInt::complement(std::vector<int> &val) { for (int i = 0; i < val.size(); ++i) { val[i] = 9 - val[i]; } std::vector<int> one; one.push_back(1); while( one.size() != val.size()) one.push_back(0); add_vector(val, one); }
void dnn::forward_activation(int index_lower_layer, float ** local_weights, float * local_bias, float * visible, float * hidden) { int num_units_hidden=num_units_ineach_layer[index_lower_layer+1]; int num_units_visible=num_units_ineach_layer[index_lower_layer]; matrix_vector_multiply(local_weights, visible, hidden, num_units_hidden, num_units_visible); add_vector(hidden, local_bias, num_units_hidden); if(index_lower_layer<num_layers-2) activate_logistic(hidden, num_units_hidden); else if(index_lower_layer==num_layers-2) log2ori(hidden,num_units_hidden ); }
void solve(matrix *a, double *x, double *b) { double w = 1.0; int steps = 1000; double *it_vec = get_iterative_vector(a, w, b); matrix upper = get_iterative_upper_matrix(a, w); matrix lower = get_iterative_lower_matrix(a, w); double *z = malloc(a->n*sizeof(*z)); for (int i = 0; i < steps; i++) { mul_matrix_row(&upper, x, z, 0, a->n); add_vector(z, it_vec, a->n); forward_subst(&lower, x, z); } }
static void remove_used(t_map *map) { size_t i; void *tmp; tmp = map->working_list; map->working_list = map->list; map->list = tmp; map->list->len = 0; i = 0; while (i < map->working_list->len) { tmp = get_vector(*(map->working_list), i); if (!in_vector(*(map->solution), tmp)) add_vector(map->list, tmp); ++i; } }
/* @param t distance */ static intersection ray_hit_object(const point3 e, const point3 d, double t0, double t1, const rectangular_node rectangulars, rectangular_node *hit_rectangular, const sphere_node spheres, sphere_node *hit_sphere) { /* set these to not hit */ *hit_rectangular = NULL; *hit_sphere = NULL; point3 biased_e; multiply_vector(d, t0, biased_e); add_vector(biased_e, e, biased_e); double nearest = t1; intersection result, tmpresult; for (rectangular_node rec = rectangulars; rec; rec = rec->next) { if (rayRectangularIntersection(biased_e, d, &(rec->element), &tmpresult, &t1) && (t1 < nearest)) { /* hit is closest so far */ *hit_rectangular = rec; nearest = t1; result = tmpresult; } } /* check the spheres */ for (sphere_node sphere = spheres; sphere; sphere = sphere->next) { if (raySphereIntersection(biased_e, d, &(sphere->element), &tmpresult, &t1) && (t1 < nearest)) { *hit_sphere = sphere; *hit_rectangular = NULL; nearest = t1; result = tmpresult; } } return result; }
void init_refraction(t_ray** rays, t_vector* normal, t_object* obj, t_vector* tmp) { (*rays[1]).distance = 20000; mult_vector(&(*rays[0]).dest, &(*rays[1]).origin, (*rays[0]).distance); add_vector(&(*rays[1]).origin, &(*rays[0]).origin, &(*rays[1]).origin); get_normal(obj, &(*rays[1]).origin, normal, rays[0]); sub_vector(NULL, &(*rays[0]).dest, tmp); if ((*rays[0]).in_obj == 0) { if (obj->obj_type != E_PLANE) (*rays[1]).in_obj = 1; else (*rays[1]).in_obj = 0; (*rays[1]).refract = obj->material.refract; } else { sub_vector(NULL, normal, normal); (*rays[1]).in_obj = 0; (*rays[1]).refract = 1.0; } }
// Adds two vectors elementwise and returns a new vector. double *add_vector_func(Vector *A, Vector *B) { Vector *C = make_vector(A->len); add_vector(A, B, C); }
// forward activation void rbm::forward_activation(float ** weights, float * hidden_bias, float * visible, float * hidden){ multiply_matrix_vector(weights, visible, hidden, num_hidden_units, num_visible_units); add_vector(hidden, hidden_bias, num_hidden_units); activate_logistic(hidden, num_hidden_units); }
// Gradient ascent update for the hidden bias void rbm::update_hidden_bias(float * hidden_bias, float * delta_hidden_bias, float learning_rate, int n, float size_mBatch){ multiply_constant_vector(delta_hidden_bias, learning_rate, n); add_vector(hidden_bias,delta_hidden_bias,n); }
// Gradient ascent update for the visible bias void rbm::update_visible_bias(float * visible_bias, float * delta_visible_bias, float learning_rate, int m, float size_mBatch){ multiply_constant_vector(delta_visible_bias,learning_rate,m); add_vector(visible_bias, delta_visible_bias,m); }
/* * Calculate the value Ki. * */ vect_list * kicalc(vect_list * pin, vect * dimensions){ vect_list * ki = NULL; vect_list * ki_start = NULL; vect * curr; vect * temp2; vect * temp = NULL; //char isfirst = 0; temp = (vect*)malloc(sizeof(vect)); //printf("kicalc"); if(temp == NULL){ printf("/nnot enough memory error."); } while(pin != NULL){ //printf("while"); temp->x = (pin->vector_element->x+dimensions->x); temp->y = (pin->vector_element->y+dimensions->y); temp->z = (pin->vector_element->z+dimensions->z);//indefInt(x+a,y+b,z+c) curr = indefintegral(temp); temp->x = (pin->vector_element->x-dimensions->x); temp->y = (pin->vector_element->y+dimensions->y);// - indefInt(x-a,y+b,z+c) temp->z = (pin->vector_element->z+dimensions->z); temp2 = indefintegral(temp); free(temp); temp = temp2; curr->x = curr->x - temp->x; curr->y = curr->y - temp->y; curr->z = curr->z - temp->z; temp->x = (pin->vector_element->x+dimensions->x); temp->y = (pin->vector_element->y-dimensions->y);// - indefInt(x+a,y-b,z+c) temp->z = (pin->vector_element->z+dimensions->z); temp2 = indefintegral(temp); free(temp); temp = temp2; curr->x = curr->x - temp->x; curr->y = curr->y - temp->y; curr->z = curr->z - temp->z; temp->x = (pin->vector_element->x-dimensions->x); temp->y = (pin->vector_element->y-dimensions->y);// + indefInt(x+a,y+b,z-c) temp->z = (pin->vector_element->z+dimensions->z); temp2 = indefintegral(temp); free(temp); temp = temp2; //printf("mid"); curr->x = curr->x + temp->x; curr->y = curr->y + temp->y; curr->z = curr->z + temp->z; temp->x = (pin->vector_element->x+dimensions->x); temp->y = (pin->vector_element->y+dimensions->y);// - indefInt(x+a,y+b,z-c) temp->z = (pin->vector_element->z-dimensions->z); temp2 = indefintegral(temp); free(temp); temp = temp2; curr->x = curr->x - temp->x; curr->y = curr->y - temp->y; curr->z = curr->z - temp->z; temp->x = (pin->vector_element->x-dimensions->x); temp->y = (pin->vector_element->y+dimensions->y);// + indefInt(x-a,y+b,z-c) temp->z = (pin->vector_element->z-dimensions->z); temp2 = indefintegral(temp); free(temp); temp = temp2; curr->x = curr->x + temp->x; curr->y = curr->y + temp->y; curr->z = curr->z + temp->z; temp->x = (pin->vector_element->x+dimensions->x); temp->y = (pin->vector_element->y-dimensions->y);// + indefInt(x+a,y-b,z-c) temp->z = (pin->vector_element->z-dimensions->z); temp2 = indefintegral(temp); free(temp); temp = temp2; curr->x = curr->x + temp->x; curr->y = curr->y + temp->y; curr->z = curr->z + temp->z; temp->x = (pin->vector_element->x-dimensions->x); temp->y = (pin->vector_element->y-dimensions->y);// - indefInt(x-a,y-b,z-c) temp->z = (pin->vector_element->z-dimensions->z); temp2 = indefintegral(temp); free(temp); temp = temp2; curr->x = curr->x - temp->x; curr->y = curr->y - temp->y; curr->z = curr->z - temp->z; //ki->next = NULL; //ki->vector_element = curr; //ki = ki->next; add_vector(&ki_start,&ki,curr); pin = pin->next; } free(temp); return ki_start; }
/* % Essentially, what we have to do for segments with arbitrary direction is % the following. First, we have to rotate the coordinate system such that % the segment is pointing along the x direction in the new (primed) % coordinate system. Then we compute the contribution to the field, which, % because it's a vector, we have to rotate back into the original % coordinate system. calc_position {x,y,z} coordinates for the magnetic field to be calculated. current density {pos: x,y,z; coordinates for the current field. curr:x,y,z} vector values for the current at specified coordinates. dimensions {x,y,z} (Width, heigth, length) of current segments. */ position_vector * calculateBfield(vect_list* calc_position, position_vector * current_density, vect_list * dimensions){ position_vector * b_start = NULL; position_vector * b = NULL; //in this case current_density is used as the magnetic field density. position_vector * b_temp; vect_list * calc_position_start = calc_position; vect_list * vp_start = NULL; vect_list * vp = NULL; vect_list * ki; vect_list * kistart; double yoverx, zoverr, a1, a2, a3; vect * tempv0; vect * tempv; halfofvect(&dimensions);//take half of dimensions to move to the edges of the segments //Initialize B field to zero, should be same length as current_density. printf("\nStarting calculation process."); printf("\nInitializing B field to zero"); while(calc_position != NULL){ b_temp = (position_vector*)malloc(sizeof(position_vector)); b_temp->current_density = (vect*)malloc(sizeof(vect)); b_temp->position = (vect*)malloc(sizeof(vect)); if(b_temp == NULL){ printf("out of memory error"); } else{ if(b_temp->current_density == NULL || b_temp->position == NULL){ printf("out of memory error"); } } b_temp->current_density->x = 0.00; b_temp->current_density->y = 0.00; b_temp->current_density->z = 0.00; b_temp->position->x = calc_position->vector_element->x; b_temp->position->y = calc_position->vector_element->y; b_temp->position->z = calc_position->vector_element->z; b_temp->next = NULL; add_position_vector_pointer(&b_start,&b,b_temp); printf("\nadded\n"); /*if(b_start == NULL){ b = b_temp; b_start = b; } else{ b->next = b_temp; b = b->next; }*/ calc_position = calc_position->next; printf(".\n"); } b = b_start; calc_position = calc_position_start; printf(" ... Done\nCalculating Magnetic field:"); while(current_density != NULL){ /* printf("start whileloop"); scanf("%d",&inp);*/ //printf("\nassign values to temporary variables."); tempv0 = (vect *)malloc(sizeof(vect)); /*printf("malloced tempv0"); scanf("%d",&inp);*/ //obtain spherical coordinates for current segment current value. //vect * spheric = cartesianToSpherical(current_density->current_density); //obtain yoverx and zoverr for usage for determining primed positions. also state values a1 a2 and a3 for use. zoverr = current_density->current_density->z/sqrt((current_density->current_density->x)*(current_density->current_density->x) + (current_density->current_density->y)*(current_density->current_density->y) + (current_density->current_density->z)*(current_density->current_density->z)); a3 = (yoverx/sqrt(yoverx*yoverx+1)); if(current_density->current_density->x != 0){ yoverx = current_density->current_density->y/current_density->current_density->x; a1 = 1/sqrt(yoverx*yoverx+1); a2 = (sqrt(1-zoverr*zoverr)); } else{ a1 = 0; a2 = 1; yoverx = 0; if((current_density->current_density->x == 0) && (current_density->current_density->y == 0) && (current_density->current_density->z == 0)){ zoverr = 0; a3 = 1; } } //printf(".\n"); //printf("calculate offsets for rotation matrix"); tempv0->x = (a1)*(a2)*current_density->position->x - ((a3)*a2*current_density->position->y) - ((zoverr)*current_density->position->z);//obtain offset to subtract from calculated value. tempv0->y = -(a3)*current_density->position->x + (a1)*current_density->position->y; tempv0->z = (a1)*(zoverr)*current_density->position->x + (a3)*(zoverr)*current_density->position->y + (a2)*current_density->position->z; //printf(".\n"); //printf("Multiply with rotation matrix"); while(calc_position != NULL){ //multiply R with VP and subtract V0 tempv = (vect *)malloc(sizeof(vect)); tempv->x = (a1)*(a2)*calc_position->vector_element->x - ((a3)*a2*calc_position->vector_element->y) - ((zoverr)*calc_position->vector_element->z) - tempv0->x; tempv->y = -(a3)*calc_position->vector_element->x + (a1)*calc_position->vector_element->y - tempv0->y; tempv->z = (a1)*(zoverr)*calc_position->vector_element->x + (a3)*(zoverr)*calc_position->vector_element->y + (a2)*calc_position->vector_element->z - tempv0->z; add_vector(&vp_start,&vp,tempv); calc_position = calc_position->next; } calc_position = calc_position_start; /*printf("malloced vp_start"); scanf("%d",&inp);*/ free(tempv0); /*printf("freed tempv0"); scanf("%d",&inp);*/ //printf(".\n"); //printf("calculate the integral values"); ki = kicalc(vp_start,dimensions->vector_element); //calculate Ki /* printf("malloced kistart"); scanf("%d",&inp);*/ //printf(".\n"); kistart = ki; //printf("free vp vector list"); free_vect_list(&vp_start); /* printf("freed vpstart"); scanf("%d",&inp);*/ vp_start = NULL; //printf(".\n"); //printf("Times ki matrix with inverting R matrix"); while(ki != NULL){ //times Ki with inverting R matrix to rotate to original coordinates ki->vector_element->x = a1*a2*ki->vector_element->x - a3*ki->vector_element->y + a1*a2*ki->vector_element->z; ki->vector_element->y = - a3*a2*ki->vector_element->x + a1*ki->vector_element->y + a3*a2*ki->vector_element->z; ki->vector_element->z = - a2*ki->vector_element->x + a2*ki->vector_element->z; ki = ki->next; } //printf(".\n"); ki = kistart; // % Cross the result with the original current density to give the field // % contribution: //printf("Cross result with curent density"); while(ki != NULL){ b->current_density->x = b->current_density->x + (current_density->current_density->y*ki->vector_element->z - ki->vector_element->y*current_density->current_density->z); b->current_density->y = b->current_density->y + (-current_density->current_density->x*ki->vector_element->z + ki->vector_element->x*current_density->current_density->z); b->current_density->z = b->current_density->z + (current_density->current_density->x*ki->vector_element->y - ki->vector_element->x*current_density->current_density->y); ki = ki->next; b = b->next; } ki = kistart; //printf(".\n"); //printf("free vect list KI"); free_vect_list(&kistart); kistart = NULL; /*printf("freed kistart"); scanf("%d",&inp);*/ //printf(".\n"); b = b_start; current_density = current_density->next; dimensions = dimensions->next; } position_vector_divten(&b_start); return b_start; }
/* @return 1 means hit, otherwise 0; */ static int rayRectangularIntersection(const point3 ray_e, const point3 ray_d, rectangular *rec, intersection *ip, double *t1) { point3 e01, e03, p; subtract_vector(rec->vertices[1], rec->vertices[0], e01); subtract_vector(rec->vertices[3], rec->vertices[0], e03); cross_product(ray_d, e03, p); double det = dot_product(e01, p); /* Reject rays orthagonal to the normal vector. * I.e. rays parallell to the plane. */ if (det < 1e-4) return 0; double inv_det = 1.0 / det; point3 s; subtract_vector(ray_e, rec->vertices[0], s); double alpha = inv_det * dot_product(s, p); if ((alpha > 1.0) || (alpha < 0.0)) return 0; point3 q; cross_product(s, e01, q); double beta = inv_det * dot_product(ray_d, q); if ((beta > 1.0) || (beta < 0.0)) return 0; *t1 = inv_det * dot_product(e03, q); if (alpha + beta > 1.0f) { /* for the second triangle */ point3 e23, e21; subtract_vector(rec->vertices[3], rec->vertices[2], e23); subtract_vector(rec->vertices[1], rec->vertices[2], e21); cross_product(ray_d, e21, p); det = dot_product(e23, p); if (det < 1e-4) return 0; inv_det = 1.0 / det; subtract_vector(ray_e, rec->vertices[2], s); alpha = inv_det * dot_product(s, p); if (alpha < 0.0) return 0; cross_product(s, e23, q); beta = inv_det * dot_product(ray_d, q); if ((beta < 0.0) || (beta + alpha > 1.0)) return 0; *t1 = inv_det * dot_product(e21, q); } if (*t1 < 1e-4) return 0; COPY_POINT3(ip->normal, rec->normal); if (dot_product(ip->normal, ray_d)>0.0) multiply_vector(ip->normal, -1, ip->normal); multiply_vector(ray_d, *t1, ip->point); add_vector(ray_e, ip->point, ip->point); return 1; }
static unsigned int ray_color(const point3 e, double t, const point3 d, idx_stack *stk, const rectangular_node rectangulars, const sphere_node spheres, const light_node lights, color object_color, int bounces_left) { rectangular_node hit_rec = NULL, light_hit_rec = NULL; sphere_node hit_sphere = NULL, light_hit_sphere = NULL; double diffuse, specular; point3 l, _l, r, rr; object_fill fill; color reflection_part; color refraction_part; /* might be a reflection ray, so check how many times we've bounced */ if (bounces_left == 0) { SET_COLOR(object_color, 0.0, 0.0, 0.0); return 0; } /* check for intersection with a sphere or a rectangular */ intersection ip= ray_hit_object(e, d, t, MAX_DISTANCE, rectangulars, &hit_rec, spheres, &hit_sphere); if (!hit_rec && !hit_sphere) return 0; /* pick the fill of the object that was hit */ fill = hit_rec ? hit_rec->element.rectangular_fill : hit_sphere->element.sphere_fill; void *hit_obj = hit_rec ? (void *) hit_rec : (void *) hit_sphere; /* assume it is a shadow */ SET_COLOR(object_color, 0.0, 0.0, 0.0); for (light_node light = lights; light; light = light->next) { /* calculate the intersection vector pointing at the light */ subtract_vector(ip.point, light->element.position, l); multiply_vector(l, -1, _l); normalize(_l); /* check for intersection with an object. use ignore_me * because we don't care about this normal */ ray_hit_object(ip.point, _l, MIN_DISTANCE, length(l), rectangulars, &light_hit_rec, spheres, &light_hit_sphere); /* the light was not block by itself(lit object) */ if (light_hit_rec || light_hit_sphere) continue; compute_specular_diffuse(&diffuse, &specular, d, l, ip.normal, fill.phong_power); localColor(object_color, light->element.light_color, diffuse, specular, &fill); } reflection(r, d, ip.normal); double idx = idx_stack_top(stk).idx, idx_pass = fill.index_of_refraction; if (idx_stack_top(stk).obj == hit_obj) { idx_stack_pop(stk); idx_pass = idx_stack_top(stk).idx; } else { idx_stack_element e = { .obj = hit_obj, .idx = fill.index_of_refraction }; idx_stack_push(stk, e); } refraction(rr, d, ip.normal, idx, idx_pass); double R = (fill.T > 0.1) ? fresnel(d, rr, ip.normal, idx, idx_pass) : 1.0; /* totalColor = localColor + mix((1-fill.Kd) * fill.R * reflection, T * refraction, R) */ if (fill.R > 0) { /* if we hit something, add the color */ int old_top = stk->top; if (ray_color(ip.point, MIN_DISTANCE, r, stk, rectangulars, spheres, lights, reflection_part, bounces_left - 1)) { multiply_vector(reflection_part, R * (1.0 - fill.Kd) * fill.R, reflection_part); add_vector(object_color, reflection_part, object_color); } stk->top = old_top; } /* calculate refraction ray */ if ((length(rr) > 0.0) && (fill.T > 0.0) && (fill.index_of_refraction > 0.0)) { normalize(rr); if (ray_color(ip.point, MIN_DISTANCE, rr, stk,rectangulars, spheres, lights, refraction_part, bounces_left - 1)) { multiply_vector(refraction_part, (1 - R) * fill.T, refraction_part); add_vector(object_color, refraction_part, object_color); } } protect_color_overflow(object_color); return 1; } /* @param background_color this is not ambient light */ void raytracing(void* args) { arg *data = (arg*) args; point3 u, v, w, d; color object_color = { 0.0, 0.0, 0.0 }; const viewpoint *view = (*data).View; color back = { 0.0 , 0.1 , 0.1 }; uint8_t *pixels = data->pixels; int start_j,end_j; /* Separate to count the pixels */ if(pthread_equal(pthread_self(),THREAD[0])) { start_j = 0; end_j = 128; } else if(pthread_equal(pthread_self(),THREAD[1])) { start_j = 128; end_j = 256; } else if(pthread_equal(pthread_self(),THREAD[2])) { start_j = 256; end_j = 384; } else if(pthread_equal(pthread_self(),THREAD[3])) { start_j = 384; end_j = 512; } /* calculate u, v, w */ calculateBasisVectors(u, v, w, view); idx_stack stk; int factor = sqrt(SAMPLES); #pragma omp parallel for num_threads(64) \ private(stk), private(d), \ private(object_color) for (int j = start_j ; j < end_j; j++) { for (int i = 0 ; i < (*data).row; i++) { double r = 0, g = 0, b = 0; /* MSAA */ for (int s = 0; s < SAMPLES; s++) { idx_stack_init(&stk); rayConstruction(d, u, v, w, i * factor + s / factor, j * factor + s % factor, view, (*data).row * factor, (*data).col * factor); if (ray_color(view->vrp, 0.0, d, &stk,(*data).rectangulars, (*data).spheres, (*data).lights, object_color, MAX_REFLECTION_BOUNCES)) { r += object_color[0]; g += object_color[1]; b += object_color[2]; } else { r += back[0]; g += back[1]; b += back[2]; } pixels[((i + (j * (*data).row)) * 3) + 0] = r * 255 / SAMPLES; pixels[((i + (j * (*data).row)) * 3) + 1] = g * 255 / SAMPLES; pixels[((i + (j * (*data).row)) * 3) + 2] = b * 255 / SAMPLES; } } } }