コード例 #1
0
ファイル: System.cpp プロジェクト: cout/biophys
void
System::
init_particles()
{
  init_particles(
      sodium_,
      params_.initial_sodium_in,
      params_.initial_sodium_out,
      params_.sodium_mass);

  init_particles(
      potassium_,
      params_.initial_potassium_in,
      params_.initial_potassium_out,
      params_.potassium_mass);
}
コード例 #2
0
ファイル: game.c プロジェクト: noox/Raketka
//inicializacni funkce pri zacatku hry
void init_game() {
	//pocatecni pozice, rychlost a hp raketky
	posx=0;
	posy=-300;
	speedx=speedy=0;
	hp=1;

	//hrac muze hned strilet
	reload=0;
	
	//promenne pro zachovani hlavnich statistik hry
	level=0;
	plevel=0;
	score=0;

	//na zacatku hrac zije
	playerdead=0; 
	
	//cas od smrti hrace nakonci
	deathtimer=0;
	
	//trvani bonusu
	shieldtimer=0;
	canontimer=0;
	
	init_stars();
	init_bullets();
	init_enemies();
	init_particles();
	init_bonuses();
}
コード例 #3
0
ファイル: problem.c プロジェクト: Allanis/CosmicDust
void problem_init(int argc, char* argv[]) {
  // Setup constants.
  OMEGA = 1.0;
  // Setup particle structures.
  boxsize_x = 10;
  boxsize_y = 1;
  boxsize_z = 1;
  init_particles(50);
  dt = 1e-3;
  // Initial conditions.
  for(int i = 0; i < N; i++) {
    particles[i].x  = ((double)rand() / (double)RAND_MAX-0.5) * boxsize_x;
    particles[i].y  = ((double)rand() / (double)RAND_MAX-0.5) * boxsize_y;
    particles[i].z  = 0.1 * ((double)rand() / (double)RAND_MAX-0.5) * boxsize_z;
    particles[i].vx = 0;
    particles[i].vy = -1.5 * particles[i].x * OMEGA;
    particles[i].vz = 0;
    particles[i].ax = 0;
    particles[i].ay = 0;
    particles[i].az = 0;
    particles[i].m  = 0.0001;
    particles[i].r  = 0.05;
  }
  // Don't use ghost boxes in x and y.
  nghostx = 0;
  nghosty = 0;
  nghostz = 0;
}
コード例 #4
0
ファイル: problem.c プロジェクト: Allanis/CosmicDust
void problem_init(int argc, char* argv[]) {
  // Setup constants.
  dt = 1e-1;
  boxsize_x = 3;
  boxsize_y = 3;
  boxsize_z = 3;
  // Setup particle structures.
  init_particles(1);
  // Initial conditions.
  particles[0].x  = 1;
  particles[0].y  = 0;
  particles[0].z  = 0;
  particles[0].vx = 0;
  particles[0].vy = 1;
  particles[0].vz = 0;
  particles[0].ax = 0;
  particles[0].ay = 0;
  particles[0].az = 0;
  particles[0].m  = 0;

  // Do not use any ghost boxes.
  nghostx = 0;
  nghosty = 0;
  nghostz = 0;
}
コード例 #5
0
ファイル: misha_serial2.cpp プロジェクト: CuppoJava/CS267-HW2
int main( int argc, char **argv )
{    
    if( find_option( argc, argv, "-h" ) >= 0 )
    {
        printf( "Options:\n" );
        printf( "-h to see this help\n" );
        printf( "-n <int> to set the number of particles\n" );
        printf( "-o <filename> to specify the output file name\n" );
        return 0;
    }
    
    int n = read_int( argc, argv, "-n", 1000 );

    char *savename = read_string( argc, argv, "-o", NULL );
    
    FILE *fsave = savename ? fopen( savename, "w" ) : NULL;
    particle_t *particles = (particle_t*) malloc( n * sizeof(particle_t) );
    set_size( n );
    init_particles( n, particles );
    
    //
    //  simulate a number of time steps
    //
    double simulation_time = read_timer( );
    run_simulation(particles, n, fsave);
    simulation_time = read_timer( ) - simulation_time;
    
    printf( "n = %d, simulation time = %g seconds\n", n, simulation_time );
    
    free( particles );
    if( fsave )
        fclose( fsave );
    
    return 0;
}
コード例 #6
0
ファイル: sph.c プロジェクト: runiteking1/sph
int main(int argc, char** argv)
{
    sim_param_t params;
    if (get_params(argc, argv, &params) != 0)
        exit(-1);
    sim_state_t* state = init_particles(&params);
    FILE* fp    = fopen(params.fname, "w");
    int nframes = params.nframes;
    int npframe = params.npframe;
    float dt    = params.dt;
    int n       = state->n;

    double t_start = omp_get_wtime();
    //write_header(fp, n);
    write_header(fp, n, nframes, params.h);
    write_frame_data(fp, n, state, NULL);
    compute_accel(state, &params);
    leapfrog_start(state, dt);
    check_state(state);
    for (int frame = 1; frame < nframes; ++frame) {
        for (int i = 0; i < npframe; ++i) {
            compute_accel(state, &params);
            leapfrog_step(state, dt);
            check_state(state);
        }
        printf("Frame: %d of %d - %2.1f%%\n",frame, nframes, 
               100*(float)frame/nframes);
        write_frame_data(fp, n, state, NULL);
    }
    double t_end = omp_get_wtime();
    printf("Ran in %g seconds\n", t_end-t_start);

    fclose(fp);
    free_state(state);
}
コード例 #7
0
ファイル: sph_simulation.cpp プロジェクト: OlivierLi/libclsph
void sph_simulation::simulate(int frame_count) {
  if (frame_count == 0) {
    frame_count = (int)ceil(parameters.simulation_time * parameters.target_fps);
  }

  cl_int cl_error;

  std::vector<cl::Device> device_array;
  check_cl_error(init_cl_single_device(&context_, device_array, "", "", true));

  queue_ = cl::CommandQueue(context_, device_array[0], 0, &cl_error);
  check_cl_error(cl_error);

  running_device = &device_array[0];

  std::string source = readKernelFile(BUFFER_KERNEL_FILE_NAME);
  cl::Program program;
  check_cl_error(make_program(&program, context_, device_array, source, true,
                              "-I ./kernels/ -I ./common/"));

  kernel_density_pressure_ = make_kernel(program, "density_pressure");
  kernel_advection_collision_ = make_kernel(program, "advection_collision");
  kernel_forces_ = make_kernel(program, "forces");
  kernel_locate_in_grid_ = make_kernel(program, "locate_in_grid");
  kernel_sort_count_ = make_kernel(program, "sort_count");
  kernel_sort_ = make_kernel(program, "sort");

  front_buffer_ =
      cl::Buffer(context_, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
                 sizeof(particle) * parameters.particles_count);
  back_buffer_ = cl::Buffer(context_, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
                            sizeof(particle) * parameters.particles_count);
  sort_count_buffer_ =
      cl::Buffer(context_, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
                 sizeof(unsigned int) * kSortThreadCount * kBucketCount);

  particle* particles = new particle[parameters.particles_count];
  init_particles(particles, parameters);

  for (int i = 0; i < frame_count; ++i) {
    if (pre_frame) {
      pre_frame(particles, parameters, true);
    }

    for (int j = 0; (float)j < (1.f / parameters.simulation_scale); ++j) {
      if (pre_frame) pre_frame(particles, parameters, false);

      simulate_single_frame(particles, particles);

      if (post_frame) post_frame(particles, parameters, false);
    }

    if (post_frame) {
      post_frame(particles, parameters, true);
    }
  }
  delete[] particles;
}
コード例 #8
0
ファイル: serial.cpp プロジェクト: Darkmush/ppsProjVT12
//
//  benchmarking program
//
int main( int argc, char **argv )
{    
    if( find_option( argc, argv, "-h" ) >= 0 )
    {
        printf( "Options:\n" );
        printf( "-h to see this help\n" );
        printf( "-n <int> to set the number of particles\n" );
        printf( "-o <filename> to specify the output file name\n" );
        return 0;
    }
    
    int n = read_int( argc, argv, "-n", 1000 );

    char *savename = read_string( argc, argv, "-o", NULL );
    
    FILE *fsave = savename ? fopen( savename, "w" ) : NULL;
    particle_t *particles = (particle_t*) malloc( n * sizeof(particle_t) );
    set_size( n );
    init_particles( n, particles );
    
    //
    //  simulate a number of time steps
    //
    double simulation_time = read_timer( );
    for( int step = 0; step < NSTEPS; step++ )
    {
        //
        //  compute forces
        //
        for( int i = 0; i < n; i++ )
        {
            particles[i].ax = particles[i].ay = 0;
            for (int j = 0; j < n; j++ )
                apply_force( particles[i], particles[j] );
        }
        
        //
        //  move particles
        //
        for( int i = 0; i < n; i++ ) 
            move( particles[i] );
        
        //
        //  save if necessary
        //
        if( fsave && (step%SAVEFREQ) == 0 )
            save( fsave, n, particles );
    }
    simulation_time = read_timer( ) - simulation_time;
    
    printf( "n = %d, simulation time = %g seconds\n", n, simulation_time );
    
    free( particles );
    if( fsave )
        fclose( fsave );
    
    return 0;
}
コード例 #9
0
ファイル: System.cpp プロジェクト: cout/biophys
void
System::
reset()
{
  now_ = 0;
  init_cell();
  init_outer_limit();
  init_particles();
}
コード例 #10
0
int main(int argc,char **argv)
{
  srandom(123456789);
  init_particles();
  InitGL(argc, argv);
  InitCL(); 
  glutDisplayFunc(mydisplayfunc);
  glutKeyboardFunc(getout);
  glutMainLoop();
}
コード例 #11
0
void init_pfsys(pfsys_t* pfsys, int particle_num, int dat_num, void (*init_particles)(pfsys_t* pfsys), float (*likelyhood_func)(float* pdat, float* mdat), void (*predict_func)(float* pdat))
{
    int i;

    pfsys->pnum = particle_num;
    pfsys->dnum = dat_num;
    pfsys->likelyhood_func = likelyhood_func;
    pfsys->predict_func = predict_func;
    for (i = 0; i < pfsys->pnum; i++)
        pfsys->weight[i] = NOT_MEASURED_WEIGHT;

    init_particles(pfsys);
}
コード例 #12
0
ファイル: init.c プロジェクト: cthielen/epiar-historical
int init_subsystems(void) {

  init_hud();
  init_flares();
  init_starfield();
  init_fire();
  init_particles();
  init_chunks();
  init_video_new_game();
  reset_update();
  reset_plugins();
  init_asteroids();

  return (0);
}
コード例 #13
0
ファイル: providence.c プロジェクト: MaddTheSane/xscreensaver
static void pinit(providencestruct *mp) 
{
  glClearDepth(1.0);

  mp->currenttime = 0.0;
  init_particles(mp);
  make_brick(mp);
  build_eye(mp);

  /* build pyramid list */
  mp->pyramidlist = glGenLists(1);
  glNewList(mp->pyramidlist, GL_COMPILE);
  draw_seal(mp);
  glEndList();
}
コード例 #14
0
void
globalpos_ackerman_initialize_from_xsens(carmen_fused_odometry_state_vector initial_state, double timestamp)
{
	carmen_point_t mean;

	mean.x = initial_state.pose.position.x;
	mean.y = initial_state.pose.position.y;
	mean.theta = initial_state.pose.orientation.yaw;// - 0.35;

	carmen_point_t std;
	std.x = fused_odometry_parameters->xsens_gps_x_std_error;
	std.y = fused_odometry_parameters->xsens_gps_y_std_error;
	std.theta = fused_odometry_parameters->xsens_yaw_std_error;

	carmen_localize_ackerman_initialize_gaussian_time_command(mean, std, timestamp);

	init_particles(initial_state, fused_odometry_parameters);
}
コード例 #15
0
ファイル: problem.c プロジェクト: Allanis/CosmicDust
void problem_init(int argc, char* argv[]) {
  // Setup constants.
  dt = 1e-3;
  tmax = 10000;
  boxsize_x = 3;
  boxsize_y = 3;
  boxsize_z = 3;
  coefficient_of_restitution = 1; // Elastic collisions.
  // Setup particle structures.
  init_particles(2);
  // Initial conditions.
  particles[0].x  = 1;
  particles[0].y  = 1;
  particles[0].z  = 0;
  particles[0].vx = 0;
  particles[0].vy = 0;
  particles[0].vz = 0;
  particles[0].ax = 0;
  particles[0].ay = 0;
  particles[0].az = 0;
  particles[0].m  = 1;
  particles[0].r  = 0.1;
  particles[1].x  = -1;
  particles[1].y  = -1;
  particles[1].z  = 0;
  particles[1].vx = 0;
  particles[1].vy = 0;
  particles[1].vz = 0;
  particles[1].ax = 0;
  particles[1].ay = 0;
  particles[1].az = 0;
  particles[1].m  = 1;
  particles[1].r  = 0.1;

  // Don't use ghost boxes.
  nghostx = 0;
  nghosty = 0;
  nghostz = 0;

  printf("init done\n");  
}
コード例 #16
0
ファイル: providence.c プロジェクト: RazZziel/pongclock
static void pinit(providencestruct *mp) 
{
  glClearDepth(1.0);
  glClearColor(0.0, 0.0, 0.0, 1.0);
  
  /* setup twoside lighting */
  glLightfv(GL_LIGHT0, GL_AMBIENT, ambient2);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
  glLightfv(GL_LIGHT0, GL_POSITION, mp->position0);

  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
  glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);

  mp->currenttime = 0.0;
  init_particles(mp);
  make_brick(mp);
  build_eye(mp);

  glEnable(GL_NORMALIZE);
  glFrontFace(GL_CCW);
/*   glDisable(GL_CULL_FACE); */
  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glShadeModel(GL_SMOOTH);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  /* build pyramid list */
  mp->pyramidlist = glGenLists(1);
  glNewList(mp->pyramidlist, GL_COMPILE);
  draw_seal(mp);
  glEndList();
}
コード例 #17
0
void handle_init() {
  uint32_t seed = 4;
  tinymt32_init(&rndstate, seed);

  window = window_create();
  window_set_fullscreen(window, true);
  window_stack_push(window, true /* Animated */);
  window_set_background_color(window, GColorBlack);

  // resource_init_current_app(&APP_RESOURCES);

  // Init the layer for the minute display
  // layer_init(&layer, window.layer.frame);
  // layer.update_proc = &layer_update_callback;
  // layer_add_child(&window.layer, &layer);

  init_particles();

  // setup debugging text layer
  GRect window_bounds = layer_get_bounds(window_get_root_layer(window));
  text_header_layer = text_layer_create(window_bounds);
  text_layer_set_text_color(text_header_layer, GColorWhite);
  text_layer_set_background_color(text_header_layer, GColorClear);
  text_layer_set_font(text_header_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14));
  layer_add_child(window_get_root_layer(window), text_layer_get_layer(text_header_layer));
 
  particle_layer = layer_create(window_bounds);
  layer_set_update_proc(particle_layer, update_particles_layer);
  layer_add_child(window_get_root_layer(window), particle_layer);

  app_timer_register(50, handle_animation_timer, NULL);
  app_timer_register(random_in_range(5000, 15000), handle_swarm_timer, NULL);

  tick_timer_service_subscribe(MINUTE_UNIT, handle_tick);
  accel_tap_service_subscribe(handle_tap);
}
コード例 #18
0
int main( int argc, char **argv ) {
    num_particles = read_int( argc, argv, "-n", 1000 );
    char *savename = read_string( argc, argv, "-o", NULL );
    MPI_Init( &argc, &argv );
    MPI_Comm_size( MPI_COMM_WORLD, &num_procs );
    MPI_Comm_rank( MPI_COMM_WORLD, &rank );
    fsave = savename && rank == 0 ? fopen( savename, "w" ) : NULL;
    particles = (particle_t*) malloc( num_particles * sizeof(particle_t) );
    MPI_Type_contiguous( 7, MPI_DOUBLE, &PARTICLE );
    MPI_Type_commit( &PARTICLE );
    set_size( num_particles );

    init_vars();
    init_partitions();

    if( rank == 0 ) {
        init_particles( num_particles, particles );
    }
    MPI_Bcast(particles, num_particles, PARTICLE, 0, MPI_COMM_WORLD);
    partition_particles();
    init_grid();

    double simulation_time = read_timer();

    for( int step = 0; step < NSTEPS; step++ ) {
        if (rank == 0) {
            right_fringe();
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_my_particles + recvd_right_count;
            memcpy(my_particles + num_my_particles, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
        } else if (rank == (num_procs-1)) {
            left_fringe();
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            num_augmented_particles = num_my_particles + recvd_left_count;
            memcpy(my_particles + num_my_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
        } else {
            left_fringe();
            right_fringe();
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_my_particles + recvd_left_count + recvd_right_count;
            memcpy(my_particles + num_my_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
            memcpy(my_particles + num_my_particles + recvd_left_count, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
        }

        populate_grid();
        time_step();

        num_sending_left = 0;
        num_sending_right = 0;
        int num_remaining_particles = 0;
        for ( int i = 0; i < num_my_particles; i++ ) {
            if (rank != 0 && my_particles[i].x <= partition_offsets[rank]) {
                left_sending_buffer[num_sending_left++] = my_particles[i];
            } else if (rank != (num_procs-1) && my_particles[i].x > partition_offsets[rank+1]) {
                right_sending_buffer[num_sending_right++] = my_particles[i];
            } else {
                remaining_particles[num_remaining_particles++] = my_particles[i];
            }
        }
        if (rank == 0) {
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_remaining_particles + recvd_right_count;
            memcpy(my_particles, remaining_particles, num_remaining_particles * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
            num_my_particles = num_augmented_particles;
        } else if (rank == (num_procs-1)) {
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            num_augmented_particles = num_remaining_particles + recvd_left_count;
            memcpy(my_particles, remaining_particles, num_remaining_particles * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
            num_my_particles = num_augmented_particles;
        } else {
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_remaining_particles + recvd_left_count + recvd_right_count;
            memcpy(my_particles, remaining_particles, num_remaining_particles * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles + recvd_left_count, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
            num_my_particles = num_augmented_particles;
        }
    }

    simulation_time = read_timer() - simulation_time;
    if( rank == 0 ) {
        printf( "num_particles = %d, num_procs = %d, simulation time = %g s\n", num_particles, num_procs, simulation_time );
    }

    if (savename) {
        if (rank == 0) {
            final_partition_sizes = (int*) malloc( num_procs * sizeof(int) );
        }
        MPI_Gather(&num_my_particles, 1, MPI_INT, final_partition_sizes, 1, MPI_INT, 0, MPI_COMM_WORLD);
        if (rank == 0) {
            final_partition_offsets = (int*) malloc( num_procs * sizeof(int) );
            final_partition_offsets[0] = 0;
            for (int i = 1; i < num_procs; i++) {
                final_partition_offsets[i] = final_partition_offsets[i-1] + final_partition_sizes[i-1];
            }
        }
        MPI_Gatherv(my_particles, num_my_particles, PARTICLE, particles, final_partition_sizes, final_partition_offsets, PARTICLE, 0, MPI_COMM_WORLD);
        if (rank == 0) {
            save( fsave, num_particles, particles );
            free(final_partition_sizes);
            free(final_partition_offsets);
        }
    }

    free( partition_offsets );
    free( partition_sizes );
    free( my_particles ); // same as my_particles
    free(remaining_particles);
    free( left_sending_buffer );
    free( right_sending_buffer );
    free( left_receiving_buffer );
    free( right_receiving_buffer );
    if( fsave ) fclose( fsave );
    MPI_Finalize();
    return 0;
}
コード例 #19
0
//
//  benchmarking program
//
int main( int argc, char **argv )
{   
    int navg,nabsavg=0,numthreads; 
    double dmin, absmin=1.0,davg,absavg=0.0;
    
    if( find_option( argc, argv, "-h" ) >= 0 )
    {
        printf( "Options:\n" );
        printf( "-h to see this help\n" );
        printf( "-n <int> to set number of particles\n" );
        printf( "-o <filename> to specify the output file name\n" );
        printf( "-s <filename> to specify a summary file name\n" ); 
        printf( "-no turns off all correctness checks and particle output\n");   
        return 0;
    }

    int n = read_int( argc, argv, "-n", 1000 );
    char *savename = read_string( argc, argv, "-o", NULL );
    char *sumname = read_string( argc, argv, "-s", NULL );

    FILE *fsave = savename ? fopen( savename, "w" ) : NULL;
    FILE *fsum = sumname ? fopen ( sumname, "a" ) : NULL;      

    particle_t *particles = (particle_t*) malloc( n * sizeof(particle_t) );
    set_size( n );
    init_particles( n, particles );

    //
    //  simulate a number of time steps
    //
    double simulation_time = read_timer( );

    #pragma omp parallel private(dmin) 
    {
        numthreads = omp_get_num_threads();
        for( int step = 0; step < NSTEPS; step++ )
        {
            navg = 0;
            davg = 0.0;
            dmin = 1.0;
            //
            //  compute all forces
            //
            #pragma omp for reduction (+:navg) reduction(+:davg)
            for( int i = 0; i < n; i++ )
            {
                particles[i].ax = particles[i].ay = 0;
                for (int j = 0; j < n; j++ )
                    apply_force( particles[i], particles[j],&dmin,&davg,&navg);
            }
            
            
            //
            //  move particles
            //
            #pragma omp for
            for( int i = 0; i < n; i++ ) 
                move( particles[i] );
      
            if( find_option( argc, argv, "-no" ) == -1 ) 
            {
              //
              //  compute statistical data
              //
              #pragma omp master
              if (navg) { 
                absavg += davg/navg;
                nabsavg++;
              }

              #pragma omp critical
          if (dmin < absmin) absmin = dmin; 
            
              //
              //  save if necessary
              //
              #pragma omp master
              if( fsave && (step%SAVEFREQ) == 0 )
                  save( fsave, n, particles );
            }
        }
    }
    simulation_time = read_timer( ) - simulation_time;
    
    printf( "n = %d,threads = %d, simulation time = %g seconds", n,numthreads, simulation_time);

    if( find_option( argc, argv, "-no" ) == -1 )
    {
      if (nabsavg) absavg /= nabsavg;
    // 
    //  -The minimum distance absmin between 2 particles during the run of the simulation
    //  -A Correct simulation will have particles stay at greater than 0.4 (of cutoff) with typical values between .7-.8
    //  -A simulation where particles don't interact correctly will be less than 0.4 (of cutoff) with typical values between .01-.05
    //
    //  -The average distance absavg is ~.95 when most particles are interacting correctly and ~.66 when no particles are interacting
    //
    printf( ", absmin = %lf, absavg = %lf", absmin, absavg);
    if (absmin < 0.4) printf ("\nThe minimum distance is below 0.4 meaning that some particle is not interacting");
    if (absavg < 0.8) printf ("\nThe average distance is below 0.8 meaning that most particles are not interacting");
    }
    printf("\n");
    
    //
    // Printing summary data
    //
    if( fsum)
        fprintf(fsum,"%d %d %g\n",n,numthreads,simulation_time);

    //
    // Clearing space
    //
    if( fsum )
        fclose( fsum );

    free( particles );
    if( fsave )
        fclose( fsave );
    
    return 0;
}
コード例 #20
0
ファイル: main.c プロジェクト: imclab/Open-World-Domination
int main(){
	BOOL done = FALSE;
	MSG msg;
	IDirect3DDevice9 *device = NULL;
	IDirect3DSurface9 *main_rendertarget = NULL;
	D3DFORMAT format;
	
	float old_time = 0;

	/* render-to-texture-stuff */
	IDirect3DTexture9 *rtt_texture;
	IDirect3DSurface9 *rtt_surface;
	IDirect3DTexture9 *rtt_32_texture;
	IDirect3DSurface9 *rtt_32_surface;

	/* textures used from mainloop */
	int white, black;
	int odd_is_back_again[4];
	int at_the_gathering_2003[4];
	int o_d_d_in_your_face[4];
	int world_domination[4];
	int back_once_again[3];
	int were_back;
	int cred[4];
	int mad_props[4];
	int not_eph[4];
	int piss_the_fuck_off[11];
	int hardcore;

	int refmap, refmap2;
	int eatyrcode;
	int code_0, code_1;
	int overlaytest;
	int circle_particle;

	/* special-textures */
	int rtt_texture_id;
	int rtt_32_texture_id;
	int video_texture_id;
	int dilldall,dilldall2;
	int metaball_text;

	/* videos */
	video *vid;

	/* 3d-scenes */
	scene *fysikkfjall;
	scene *startblob;
	scene *inni_abstrakt;
	scene *korridor;
	scene *skjerm_rom;
	scene *bare_paa_lissom;

	format = D3DFMT_X8R8G8B8;
	device = d3dwin_open(TITLE, WIDTH, HEIGHT, format, FULLSCREEN);
	if(!device){
		format = D3DFMT_A8R8G8B8;
		device = d3dwin_open(TITLE, WIDTH, HEIGHT, format, FULLSCREEN);
		if(!device){
			format = D3DFMT_X1R5G5B5;
			device = d3dwin_open(TITLE, WIDTH, HEIGHT, format, FULLSCREEN);
			if(!device){
				format = D3DFMT_R5G6B5;
				device = d3dwin_open(TITLE, WIDTH, HEIGHT, format, FULLSCREEN);
				if(!device) error("failed to initialize Direct3D9");
			}
		}
	}

#ifdef BIGSCREEN
	set_gamma(device,1.05f);
#endif

	if (!BASS_Init(1, 44100, BASS_DEVICE_LATENCY, win, NULL)) error("failed to initialize BASS");
	fp = file_open("worlddomination.ogg");
	if (!fp) error("music-file not found");
	music_file = BASS_StreamCreateFile(1, fp->data, 0, fp->size, 0);

	/*** music ***/
//	if(!pest_open(win)) error("failed to initialize DirectSond");
//	if(!pest_load("worlddomination.ogg",0)) error("failed to load music-file");


	/*** subsystems ***/
	init_tunnel();
	video_init();
	if(!init_particles(device)) error("failed to initialize");
	if(!init_overlays(device)) error("f**k a duck");
	if(!init_marching_cubes(device)) error("screw a kangaroo");

	make_random_particles(particles, PARTICLES, vector_make(0,-180,0), 500);
	make_random_particles(particles2, PARTICLES2, vector_make(0,-180,0), 500);
	make_random_particles(particles3, PARTICLES3, vector_make(0,0,0), 800);

	/*** rendertextures ***/
	if (IDirect3DDevice9_CreateTexture(device, 512, 256, 0,D3DUSAGE_RENDERTARGET, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &rtt_texture, NULL)!=D3D_OK) error("failed to create rendertarget-texture");
	if (IDirect3DTexture9_GetSurfaceLevel(rtt_texture,0,&rtt_surface)!=D3D_OK) error("could not get kvasi-backbuffer-surface");
	if ((rtt_texture_id=texture_insert(device, "rendertexture.jpg", rtt_texture))==-1) error("fakk off!");

	if(IDirect3DDevice9_CreateTexture(device,16,16,0,D3DUSAGE_RENDERTARGET|D3DUSAGE_AUTOGENMIPMAP,D3DFMT_X8R8G8B8,D3DPOOL_DEFAULT, &rtt_32_texture, NULL)!=D3D_OK) error("failed to create rendertarget-texture");
	if(IDirect3DTexture9_GetSurfaceLevel(rtt_32_texture,0,&rtt_32_surface)!=D3D_OK) error("could not get kvasi-backbuffer-surface");
	if((rtt_32_texture_id=texture_insert(device, "rendertexture2.jpg", rtt_32_texture))==-1) error("fakk off!");


	/*** textures ***/
	/* solid colors for fades etc */
	if((white=texture_load(device,"white.png",FALSE))==-1) error("shjit!");
	if((black=texture_load(device,"black.png",FALSE))==-1) error("shjit!");

	/* textoverlays */
	if((odd_is_back_again[0]=texture_load(device,"odd_is_back_again_0.png",FALSE))==-1) error("failed to load image");
	if((odd_is_back_again[1]=texture_load(device,"odd_is_back_again_1.png",FALSE))==-1) error("failed to load image");
	if((odd_is_back_again[2]=texture_load(device,"odd_is_back_again_2.png",FALSE))==-1) error("failed to load image");
	if((odd_is_back_again[3]=texture_load(device,"odd_is_back_again_3.png",FALSE))==-1) error("failed to load image");
	if((at_the_gathering_2003[0]=texture_load(device,"at_the_gathering_2003_0.png",FALSE))==-1) error("failed to load image");
	if((at_the_gathering_2003[1]=texture_load(device,"at_the_gathering_2003_1.png",FALSE))==-1) error("failed to load image");
	if((at_the_gathering_2003[2]=texture_load(device,"at_the_gathering_2003_2.png",FALSE))==-1) error("failed to load image");
	if((at_the_gathering_2003[3]=texture_load(device,"at_the_gathering_2003_3.png",FALSE))==-1) error("failed to load image");
	if((back_once_again[0]=texture_load(device,"back_once_again_0.png",TRUE))==-1) error("failed to load image");
	if((back_once_again[1]=texture_load(device,"back_once_again_1.png",TRUE))==-1) error("failed to load image");
	if((back_once_again[2]=texture_load(device,"back_once_again_2.png",TRUE))==-1) error("failed to load image");
	if((o_d_d_in_your_face[0]=texture_load(device,"o_d_d_in_your_face_0.png",TRUE))==-1) error("failed to load image");
	if((o_d_d_in_your_face[1]=texture_load(device,"o_d_d_in_your_face_1.png",TRUE))==-1) error("failed to load image");
	if((o_d_d_in_your_face[2]=texture_load(device,"o_d_d_in_your_face_2.png",TRUE))==-1) error("failed to load image");
	if((o_d_d_in_your_face[3]=texture_load(device,"o_d_d_in_your_face_3.png",TRUE))==-1) error("failed to load image");
	if((world_domination[0]=texture_load(device,"world_domination_0.png",TRUE))==-1) error("failed to load image");
	if((world_domination[1]=texture_load(device,"world_domination_1.png",TRUE))==-1) error("failed to load image");
	if((world_domination[2]=texture_load(device,"world_domination_2.png",TRUE))==-1) error("failed to load image");
	if((world_domination[3]=texture_load(device,"world_domination_3.png",TRUE))==-1) error("failed to load image");
	if((were_back=texture_load(device,"were_back.png",TRUE))==-1) error("failed to load image");

	if((cred[0]=texture_load(device,"cred_0.png",TRUE))==-1) error("failed to load image");
	if((cred[1]=texture_load(device,"cred_1.png",TRUE))==-1) error("failed to load image");
	if((cred[2]=texture_load(device,"cred_2.png",TRUE))==-1) error("failed to load image");
	if((cred[3]=texture_load(device,"cred_3.png",TRUE))==-1) error("failed to load image");
	if((mad_props[0]=texture_load(device,"mad_props_0.png",TRUE))==-1) error("failed to load image");
	if((mad_props[1]=texture_load(device,"mad_props_1.png",TRUE))==-1) error("failed to load image");
	if((mad_props[2]=texture_load(device,"mad_props_2.png",TRUE))==-1) error("failed to load image");
	if((mad_props[3]=texture_load(device,"mad_props_3.png",TRUE))==-1) error("failed to load image");
	if((not_eph[0]=texture_load(device,"not_eph_0.png",TRUE))==-1) error("failed to load image");
	if((not_eph[1]=texture_load(device,"not_eph_1.png",TRUE))==-1) error("failed to load image");
	if((not_eph[2]=texture_load(device,"not_eph_2.png",TRUE))==-1) error("failed to load image");
	if((not_eph[3]=texture_load(device,"not_eph_3.png",TRUE))==-1) error("failed to load image");

	if((piss_the_fuck_off[0]=texture_load(device,"piss_the_fuck_off_0.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[1]=texture_load(device,"piss_the_fuck_off_1.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[2]=texture_load(device,"piss_the_fuck_off_2.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[3]=texture_load(device,"piss_the_fuck_off_3.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[4]=texture_load(device,"piss_the_fuck_off_4.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[5]=texture_load(device,"piss_the_fuck_off_5.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[6]=texture_load(device,"piss_the_fuck_off_6.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[7]=texture_load(device,"piss_the_fuck_off_7.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[8]=texture_load(device,"piss_the_fuck_off_8.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[9]=texture_load(device,"piss_the_fuck_off_9.png",TRUE))==-1) error("failed to load image");
	if((piss_the_fuck_off[10]=texture_load(device,"piss_the_fuck_off_10.png",TRUE))==-1) error("failed to load image");
	if((hardcore=texture_load(device,"hardcore.png",TRUE))==-1) error("failed to load image");

	/* other textures */
	if((circle_particle=texture_load(device,"circle_particle.jpg",FALSE))==-1) error("shjit!");
	if((refmap=texture_load(device,"fysikkfjall/refmap.jpg",FALSE))==-1) error("shjit!");
	if((refmap2=texture_load(device,"refmap2.jpg",FALSE))==-1) error("shjit!");
	if((eatyrcode=texture_load(device,"eatyrcode.jpg",FULLSCREEN_HACK))==-1) error("shjit!");
	if((code_0=texture_load(device,"code-0.jpg",FALSE))==-1) error("shjit!");
	if((code_1=texture_load(device,"code-1.jpg",FALSE))==-1) error("shjit!");
	if((overlaytest=texture_load(device,"overlaytest.jpg",FALSE))==-1) error("shjit!");

	if((dilldall=texture_load(device,"dilldall.png",FALSE))==-1) error("shjit!");
	if((dilldall2=texture_load(device,"dilldall2.png",FALSE))==-1) error("shjit!");

	if((metaball_text=texture_load(device,"metaballs.png",TRUE))==-1) error("shjit!");

	/*** video ***/
	if(!(vid=video_load(device,"test.kpg"))) error("fæck!");
	video_texture_id = texture_insert(device, "skjerm_rom/skjerm_tom.tga", vid->texture);


	/*** misc stuff ***/
	/* main rendertarget */
	IDirect3DDevice9_GetRenderTarget(device,0,&main_rendertarget);

	/* default state */
	IDirect3DDevice9_CreateStateBlock(device, D3DSBT_ALL, &default_state);
	init_defaultstate(device);
	IDirect3DStateBlock9_Capture(default_state);


	/*** 3d scenes ***/
	if(!(fysikkfjall=load_scene(device,"fysikkfjall/fysikkfjall.krs"))) error("failed to load 3d scene");
	if(!(startblob=load_scene(device,"startblob/startblob.krs"))) error("failed to load 3d scene");
	if(!(inni_abstrakt=load_scene(device,"inni_abstrakt/inni_abstrakt.krs"))) error("failed to load 3d scene");
	if(!(korridor=load_scene(device,"korridor/korridor.krs"))) error("failed to load 3d scene");
	if(!(skjerm_rom=load_scene(device,"skjerm_rom/skjerm_rom.krs"))) error("failed to load 3d scene");
	if(!(bare_paa_lissom=load_scene(device,"bare_paa_lissom/bare_paa_lissom.krs"))) error("failed to load 3d scene");

//	pest_play();
	BASS_Start();
	BASS_StreamPlay(music_file, 1, 0);
	do{
		grid g;
		int i;
		matrix m, temp, temp_matrix;
		matrix marching_cubes_matrix;

		long long bytes_played = BASS_ChannelGetPosition(music_file);
		float time =  bytes_played * (1.0 / (44100 * 2 * 2));
//		float time = pest_get_pos()+0.05f;
		float delta_time = time-old_time;

		int beat = (int)(time*((float)BPM/60.f));

		if(time_index<(sizeof(timetable)/4)){
			while(timetable[time_index]<time) time_index++;
		}

#ifdef _DEBUG
		printf("time: %2.2f, delta_time: %2.2f, time_index: %i, beat: %i                    \r",time,delta_time,time_index,beat);
#endif

		IDirect3DDevice9_SetRenderTarget(device,0,main_rendertarget);
		IDirect3DStateBlock9_Apply(default_state);
		IDirect3DDevice9_Clear(device, 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, 0, 1.0f, 0);
//		IDirect3DDevice9_Clear(device, 0, NULL, D3DCLEAR_ZBUFFER, 0, 1.0f, 0);
		IDirect3DDevice9_BeginScene(device);
#if 1
		if(time_index<40){
			if(time_index>0&&time_index<5){
				draw_overlay(device,odd_is_back_again[time_index-1],0,0,1,FALSE);
			}else if(time_index>4&&time_index<19){
				float itime = time*10;
				grid_flat(g,0,0);
				for(i=0;i<7;i++){
					int scale = (time_index&1);
					grid_wave(g,(float)sin(itime-i+sin(i-itime))*0.3f*scale,(float)cos(itime*0.69f+i*0.733f)*0.3f*scale,7,(float)sin(itime+i*0.1f)*0.5f*scale);
				}
				draw_grid(device, g, odd_is_back_again[3], FALSE);
			}else if(time_index>=19){
				float itime = (time-timetable[18])*0.5f;
				grid_flat(g,0,0);
				for(i=0;i<7;i++){
					grid_wave(g,(float)sin(time-i+sin(i-time))*0.3f,(float)cos(time*0.69f+i*0.733f)*0.3f,7, itime*itime);
				}
				draw_grid(device, g, odd_is_back_again[3], FALSE);
			}
			if(time_index>20&&time_index<25){
				draw_overlay(device,at_the_gathering_2003[(time_index-21)%4],0,0,1,TRUE);
			}else if(time_index>=25&&time_index<38){
				float itime = time*10;
				grid_flat(g,0,0);
				for(i=0;i<10;i++){
					int scale = (time_index&1);
					grid_wave(g,(float)sin(itime-i+sin(i-itime))*0.3f*scale,(float)cos(itime*0.69f+i*0.733f)*0.3f*scale,7,(float)sin(itime+i*0.1f)*0.5f*scale);
				}
				draw_grid(device,g,at_the_gathering_2003[3],TRUE);
			}else if(time_index>=38){
				float itime = (time-timetable[37])*0.5f;
				grid_flat(g,0,0);
				for(i=0;i<10;i++){
					grid_wave(g,(float)sin(time-i+sin(i-time))*0.3f,(float)cos(time*0.69f+i*0.733f)*0.3f,7, itime*itime);
				}
				draw_grid(device,g,at_the_gathering_2003[3],TRUE);
			}
		}else if(time_index<52){
			animate_scene(inni_abstrakt,(time-timetable[39]));
			draw_scene(device,inni_abstrakt,0,TRUE);

			flash(device,white,time,timetable[39],1);

			if(time_index<43){
				draw_overlay(device, back_once_again[(time_index-40)%3],0,0,1,FALSE);
			}else if(time_index<47){
				draw_overlay(device, o_d_d_in_your_face[(time_index-43)%4],0,0,1,FALSE);
			}else if(time_index<51){
				draw_overlay(device, world_domination[(time_index-47)%4],0,0,1,FALSE);
			}else{
				draw_overlay(device, were_back,0,0,(time-timetable[51]),FALSE);
			}

			draw_overlay(device,dilldall,sin(sin(time)*0.07f+(((beat+1)/2)*0.8f)),sin(time*0.03337f+(((beat+1)/2)*0.14f)),0.5f,TRUE);
			draw_overlay(device,dilldall2,sin(sin(time*0.1f)*0.07f+time*0.1f+(((beat+1)/2)*0.8f)),sin(time*0.01337f+(((beat+1)/2)*0.14f)),0.5f,TRUE);

		}else if(time_index<69){

			animate_scene(startblob,(time-timetable[39]-0.27f+((beat+1)&2))*0.74948f);

			startblob->cameras[0].fog = TRUE;
			startblob->cameras[0].fog_start = 100.f;
			startblob->cameras[0].fog_end = 700.f;

			if(time_index>=53 && time_index<66 && time_index&1 ){
				float f = fade(timetable[time_index-1],1.7f,time,0.5f,0);
				f *= f;
				f *= 2;

				if(f>0.f)
				IDirect3DDevice9_SetRenderTarget(device,0,rtt_surface);

				draw_scene(device,startblob,0,TRUE);
				draw_particles(device, particles3, PARTICLES3, code_0);

				if(f>0.f){
					IDirect3DDevice9_SetRenderTarget(device,0,main_rendertarget);
					draw_radialblur(device,0,0,f,0,rtt_texture_id, FALSE);
				}
				if(time_index<61) draw_overlay(device,cred[((time_index/2)-2)%4],0,0,f*3,FALSE);
			}else{
				draw_scene(device,startblob,0,TRUE);
				draw_particles(device, particles3, PARTICLES3, circle_particle);			
			}
			if(time_index>=54&& !(time_index&1)){

				float f = fade(timetable[time_index-1],1.8f,time,1.f,0)*0.8f;
				IDirect3DDevice9_SetRenderTarget(device,0,rtt_32_surface);
				draw_scene(device,startblob,0,TRUE);
				draw_particles(device, particles3, PARTICLES3, code_0);

				IDirect3DDevice9_SetRenderTarget(device,0,main_rendertarget);
				IDirect3DDevice9_SetSamplerState(device, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
				draw_overlay(device,rtt_32_texture_id,0,0,f,TRUE);
				draw_overlay(device,rtt_32_texture_id,0,0,f,TRUE);
				IDirect3DDevice9_SetSamplerState(device, 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
			}

			flash(device,were_back,time,timetable[51],2);
			flash(device,white,time,timetable[51],1);
		}else if(time_index<79){

			for(i=0;i<BALLS;i++){
				balls[i].pos.x = (float)sin(time+i-sin((float)i*0.1212111f))*0.35f;
				balls[i].pos.y = (float)cos(time-(float)i*0.29342111f)*0.35f;
				balls[i].pos.z = (float)sin(time*0.31121f+sin(i-time))*0.35f;
				balls[i].r = 0.15f + (float)sin(time+i)*0.01f;
				balls[i].pos = vector_normalize(balls[i].pos);
				balls[i].pos = vector_scale(balls[i].pos, (float)(cos(i*0.11131f-time*0.55311f)+sin(time+(float)sin(time-i+time*0.3f)))*0.2f );
			}

			animate_scene(korridor,(time-timetable[68])*0.65f );
			draw_scene(device,korridor,(beat/4)&1,TRUE);

			memcpy(temp,korridor->objects[korridor->object_count-1]->mat,sizeof(matrix));
			matrix_scale(marching_cubes_matrix,vector_make(120,120,120));
			matrix_multiply(marching_cubes_matrix,temp,marching_cubes_matrix);
	
			matrix_rotate(temp,vector_make(time,-time,time*0.5f+sin(time)));
			matrix_multiply(marching_cubes_matrix,marching_cubes_matrix,temp);

			IDirect3DDevice9_SetTransform( device, D3DTS_WORLD, (D3DMATRIX*)&marching_cubes_matrix );

			fill_metafield_blur(balls, BALLS,0.98f);
			march_my_cubes_opt(balls, BALLS, 0.9f);

			IDirect3DDevice9_SetRenderState(device, D3DRS_CULLMODE, D3DCULL_NONE);

			set_texture(device,0,refmap2);
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR );
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLOROP, D3DTOP_ADD);
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG2, D3DTA_CURRENT);

			draw_marched_cubes(device);

			flash(device,white,time,timetable[68],1);

			if(time_index>69&&time_index<74){
				draw_overlay(device,mad_props[(time_index+2)%4],0,0,1,FALSE);
			}else if(time_index>73&&time_index<77){
				draw_overlay(device,not_eph[(time_index+2)%4],0,0,1,FALSE);
			}else if(time_index==77){
				float f = fade(timetable[76],2.5f,time,1,0);
				draw_overlay(device,not_eph[3],0,0,f,FALSE);
			}
		}
		if(time_index>77&&time_index<92){
			float f = fade(timetable[77],timetable[78]-timetable[77],time,0,1);
			draw_overlay(device,eatyrcode,0,0,f,FALSE);

			if(time>109.5f){
				IDirect3DStateBlock9_Apply(default_state);
				animate_particles(particles, PARTICLES, delta_time*30);
				animate_particles(particles2, PARTICLES2, delta_time*28);

				draw_particles(device, particles, PARTICLES, code_0);
				draw_particles(device, particles2, PARTICLES2, code_1);
			}
			if(time_index>79&&time_index<90){
				draw_overlay(device,piss_the_fuck_off[(time_index-80)%11],0,0,1,FALSE);
			}else if(time_index==90){
				float f = fade(timetable[89],2,time,1,0);
				draw_overlay(device,piss_the_fuck_off[10],0,0,f,FALSE);
			}
			if(time_index==91){
				float f = fade(timetable[90],2,time,1,0);
				draw_overlay(device,hardcore,0,0,f,FALSE);
			}
		}else if(time_index>91 && time_index<97){
			animate_scene(skjerm_rom,time);
			video_update(vid, time);
			draw_scene(device,skjerm_rom,((beat/4)&1),TRUE);

			draw_overlay(device,dilldall,sin(sin(time)*0.07f+(((beat+1)/2)*0.8f)),sin(time*0.03337f+(((beat+1)/2)*0.14f)),0.5f,TRUE);
			draw_overlay(device,dilldall2,sin(sin(time*0.1f)*0.07f+time*0.1f+(((beat+1)/2)*0.8f)),sin(time*0.01337f+(((beat+1)/2)*0.14f)),0.5f,TRUE);
			if(time_index>92)
				draw_overlay(device, world_domination[(time_index-93)%4],0,0,1,FALSE);

		}else if(time_index>96&&time_index<104){
			grid_zero(g);

			matrix_translate(m, vector_make(cos(time)*1.5f, sin(time)*1.5f,time*10));
			matrix_rotate(temp_matrix, vector_make(sin(time*0.8111f)*0.2f,sin(time*1.2f)*0.2f,time));
			matrix_multiply(m,m,temp_matrix);

			render_tunnel(g,m);

			matrix_rotate(temp_matrix, vector_make(0,M_PI,0));
			matrix_multiply(m,m,temp_matrix);
			render_tunnel(g,m);
			matrix_rotate(temp_matrix, vector_make(M_PI,0,0));
			matrix_multiply(m,m,temp_matrix);
			render_tunnel(g,m);

			grid_add_noice(g,sin(time)*0.1f);

			draw_grid(device, g, circle_particle, FALSE);

			if(time_index>97&&time_index<102){
				float f = 1;
				if(time_index==101) f = fade(timetable[100],3,time,1,0);
				draw_overlay(device, o_d_d_in_your_face[(time_index-42)%4],0,0,f,FALSE);
			}
		}
		if(time_index>101 && time_index<104){
			float f = fade(timetable[101],8,time,0,1);
			float f2 = fade(timetable[101],4,time,0,1);

			draw_overlay(device,black,0,0,f2,FALSE);

			IDirect3DDevice9_SetRenderTarget(device,0,rtt_surface);
			IDirect3DDevice9_Clear(device, 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0, 1.0f, 0);

			IDirect3DStateBlock9_Apply(default_state);

			animate_scene(bare_paa_lissom,time-timetable[101]);
			draw_scene(device,bare_paa_lissom,0,TRUE);

			time *=0.5f;

			for(i=0;i<BALLS2;i++){
				balls2[i].pos.x = (float)sin(time+i-sin((float)i*0.1212111f))*0.35f;
				balls2[i].pos.y = (float)cos(time-(float)i*0.29342111f)*0.35f;
				balls2[i].pos.z = (float)sin(time*0.31121f+sin(i-time))*0.35f;
				balls2[i].r = 0.15f + (float)sin(time+i)*0.01f;
				balls2[i].pos = vector_normalize(balls2[i].pos);
				balls2[i].pos = vector_scale(balls2[i].pos, (float)(cos(i*0.11131f-time*0.55311f)+sin(time+(float)sin(time-i+time*0.3f)))*0.2f );
			}

			memcpy(temp,bare_paa_lissom->objects[bare_paa_lissom->object_count-1]->mat,sizeof(matrix));
			matrix_scale(marching_cubes_matrix,vector_make(120,120,120));
			matrix_multiply(marching_cubes_matrix,temp,marching_cubes_matrix);

			IDirect3DDevice9_SetTransform( device, D3DTS_WORLD, (D3DMATRIX*)&marching_cubes_matrix );
			fill_metafield(balls2, BALLS2);
			march_my_cubes_opt(balls2, BALLS2, 0.9f);

			IDirect3DDevice9_SetRenderState(device, D3DRS_CULLMODE, D3DCULL_NONE);

			set_texture(device,0,refmap);
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR );
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLOROP, D3DTOP_ADD);
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
			IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG2, D3DTA_CURRENT);

			draw_marched_cubes(device);

			IDirect3DDevice9_SetRenderTarget(device,0,main_rendertarget);
			draw_overlay(device,rtt_texture_id,0,0,f,TRUE);

			if(time_index==103){
				float f;
				time *= 2;
				f = fade(timetable[time_index-1],3,time,1,0);
				draw_overlay(device,metaball_text,0,0,f,FALSE);

				flash(device,white,time,timetable[time_index-1],1);
			}
		}
		if(time_index==104){
			float f = fade(timetable[103],timetable[104]-timetable[103],time,0,1);

			animate_scene(korridor,180-(time-timetable[time_index-1])*0.8f );
			draw_scene(device,korridor,(beat/4)&1,TRUE);
			draw_overlay(device,black,0,0,f,FALSE);
		}
		if(time_index==105){
			float f = fade(timetable[104],timetable[105]-timetable[104],time,0,1);
			float t = (time-timetable[time_index-1])*0.6f+2.2f;
			animate_scene(fysikkfjall,t);
			draw_scene(device,fysikkfjall,0,TRUE);
			draw_overlay(device,black,0,0,f,FALSE);
		}
#endif
/*
*/
/*
		draw_overlay(device, were_back, (1+sin(time))*0.5f, TRUE);
*/
//		animate_scene(risterom,time);
//		draw_scene(device,risterom,0,TRUE);

#if 0 //helvete_har_frosset
		draw_overlay(device, eatyrcode, 1,FALSE);

		IDirect3DStateBlock9_Apply(default_state);

		animate_particles(particles, PARTICLES, delta_time*30);
		animate_particles(particles2, PARTICLES2, delta_time*28);

		draw_particles(device, particles, PARTICLES, code_0);
		draw_particles(device, particles2, PARTICLES2, code_1);
#endif

#ifdef pikk

//				IDirect3DDevice9_SetRenderTarget(device,0,rtt_surface);
				IDirect3DDevice9_Clear(device, 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0, 1.0f, 0);

				draw_overlay(device, eatyrcode, TRUE);

				animate_scene(startblob,(time-timetable[39]-0.27f)*0.7453f);
				draw_scene(device,startblob,0,FALSE);
				draw_particles(device, particles, PARTICLES, code_0);
				draw_particles(device, particles2, PARTICLES2, code_1);
//				IDirect3DDevice9_SetRenderTarget(device,0,main_rendertarget);
/*
				draw_radialblur(device,
					(float)sin(time)*0.2f,
					(float)sin(-time*0.331f)*0.13f,
					(float)(2+(float)sin(time*0.5f))*0.2f,
					0,//sin(time)*0.25f,
					rtt_texture_id, TRUE);

				animate_scene(fysikkfjall,time);
				draw_scene(device,fysikkfjall,0,FALSE);
*/
//				draw_overlay(device, rtt_texture_id, TRUE);
#endif

//		draw_overlay(device, eatyrcode, FALSE);

//		video_update(vid, time);
#if 0
//		IDirect3DDevice9_SetRenderTarget(device,0,rtt_surface);

		animate_scene(testscene,time);

//		morph_object(testscene->objects[0], time );
		draw_scene(device,testscene,0,TRUE);
//		draw_particles(device, particles, PARTICLES, particle);

//		IDirect3DDevice9_SetRenderTarget(device,0,main_rendertarget);
#endif
#if 0
		time *=0.5f;

		for(i=0;i<BALLS2;i++){
			balls2[i].pos.x = (float)sin(time+i-sin((float)i*0.1212111f))*0.35f;
			balls2[i].pos.y = (float)cos(time-(float)i*0.29342111f)*0.35f;
			balls2[i].pos.z = (float)sin(time*0.31121f+sin(i-time))*0.35f;
			balls2[i].r = 0.15f + (float)sin(time+i)*0.01f;
			balls2[i].pos = vector_normalize(balls2[i].pos);
			balls2[i].pos = vector_scale(balls2[i].pos, (float)(cos(i*0.11131f-time*0.55311f)+sin(time+(float)sin(time-i+time*0.3f)))*0.2f );
//			balls2[i].pos.x *= 2.8f;
		}

		matrix_translate(temp,vector_make(0,0,87));
		matrix_scale(marching_cubes_matrix,vector_make(50,50,50));
		matrix_multiply(marching_cubes_matrix,temp,marching_cubes_matrix);

		IDirect3DDevice9_SetTransform( device, D3DTS_WORLD, (D3DMATRIX*)&marching_cubes_matrix );
		fill_metafield(balls2, BALLS2);
//		fill_metafield_blur(balls, BALLS,0.98f);
		march_my_cubes_opt(balls2, BALLS2, 0.9f);
//		march_my_cubes(0.9f);

		IDirect3DDevice9_SetRenderState(device, D3DRS_CULLMODE, D3DCULL_CW);

		set_texture(device,0,refmap);
		IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR );
		IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLOROP, D3DTOP_ADD);
		IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
		IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG2, D3DTA_CURRENT);

		draw_marched_cubes(device);
#endif

#if 0
//		time *= 0.5f;
		grid_zero(g);
//		for(i=0;i<10;i++)
//			grid_wave(g,sin(time-i+sin(i-time))*0.3f,cos(time*0.69f+i*0.733f)*0.3f,7,sin(time+i*0.1f)*0.5f);

		matrix_translate(m, vector_make(cos(time)*1.5f, sin(time)*1.5f,time*10));
		matrix_rotate(temp_matrix, vector_make(sin(time*0.8111f)*0.2f,sin(time*1.2f)*0.2f,time));
		matrix_multiply(m,m,temp_matrix);

//		empty_grid( grid );
		render_tunnel(g,m);

		matrix_rotate(temp_matrix, vector_make(0,M_PI,0));
		matrix_multiply(m,m,temp_matrix);
		render_tunnel(g,m);
		matrix_rotate(temp_matrix, vector_make(M_PI,0,0));
		matrix_multiply(m,m,temp_matrix);
		render_tunnel(g,m);
//		tyfuus_expand_grid( screen, grid, texture );

		grid_add_noice(g,sin(time)*0.1f);

		draw_grid(device, g, circle_particle, FALSE);
#endif
//		IDirect3DDevice9_SetRenderTarget(device,0,main_rendertarget);

//		video_update(vid,time);
/*
		draw_radialblur(device,
			(float)sin(time)*0.2f,
			(float)sin(-time*0.331f)*0.13f,
			(float)(1+(float)sin(time*0.5f))*0.2f,
			0,//sin(time)*0.25f,
			rtt_texture_id, FALSE);
*/
//		IDirect3DStateBlock9_Apply(default_state);

//		draw_overlay(device,rtt_texture_id,FALSE);
//		draw_overlay(device,fullscreen,FALSE);

//		draw_radialblur(device,0,sin(time*0.2f)*2.f, rtt_texture_id);

//		IDirect3DDevice9_StretchRect(device,main_rendertarget,NULL,rtt_surface,NULL,D3DTEXF_NONE);
//		IDirect3DBaseTexture9_GenerateMipSubLevels(rtt_texture);

		IDirect3DDevice9_EndScene(device);
		if(IDirect3DDevice9_Present(device, NULL, NULL, NULL, NULL)==D3DERR_DEVICELOST)
			error("fakkin lost device. keep your hands off alt-tab, looser.");

		old_time = time;

		while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)){ 
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if (msg.message == WM_QUIT ||
			    msg.message == WM_KEYDOWN && LOWORD(msg.wParam) == VK_ESCAPE)
				done = TRUE;
		}
	}while(!done);

	deinit_marching_cubes();
	deinit_overlays();
	deinit_particles();

	free_scene(fysikkfjall);
	free_scene(startblob);
	free_scene(inni_abstrakt);
	free_scene(korridor);
	free_scene(skjerm_rom);
	free_scene(bare_paa_lissom);

	free_materials();
	free_textures();
	free_video(vid);

	rtt_surface->lpVtbl->Release(rtt_surface);
	rtt_32_surface->lpVtbl->Release(rtt_32_surface);

	main_rendertarget->lpVtbl->Release(main_rendertarget);
	IDirect3DStateBlock9_Release(default_state);


	d3dwin_close();

	if (music_file) BASS_StreamFree( music_file );
	if (fp) file_close( fp );
	BASS_Free();

//	pest_close();

	return 0;
}
コード例 #21
0
//
//  benchmarking program
//
int main( int argc, char **argv )
{    
    int navg, nabsavg=0;
    double dmin, absmin=1.0,davg,absavg=0.0;
    double rdavg,rdmin;
    int rnavg; 
 
    //
    //  process command line parameters
    //
    if( find_option( argc, argv, "-h" ) >= 0 )
    {
        printf( "Options:\n" );
        printf( "-h to see this help\n" );
        printf( "-n <int> to set the number of particles\n" );
        printf( "-o <filename> to specify the output file name\n" );
        printf( "-s <filename> to specify a summary file name\n" );
        printf( "-no turns off all correctness checks and particle output\n");
        return 0;
    }
    
    int n = read_int( argc, argv, "-n", 1000 );
    char *savename = read_string( argc, argv, "-o", NULL );
    char *sumname = read_string( argc, argv, "-s", NULL );
    
    //
    //  set up MPI
    //
    int n_proc, rank;
    MPI_Init( &argc, &argv );
    MPI_Comm_size( MPI_COMM_WORLD, &n_proc );
    MPI_Comm_rank( MPI_COMM_WORLD, &rank );
    
    //
    //  allocate generic resources
    //
    FILE *fsave = savename && rank == 0 ? fopen( savename, "w" ) : NULL;
    FILE *fsum = sumname && rank == 0 ? fopen ( sumname, "a" ) : NULL;


    particle_t *particles = (particle_t*) malloc( n * sizeof(particle_t) );
    
    MPI_Datatype PARTICLE;
    MPI_Type_contiguous( 6, MPI_DOUBLE, &PARTICLE );
    MPI_Type_commit( &PARTICLE );
    
    //
    //  set up the data partitioning across processors
    //
    int particle_per_proc = (n + n_proc - 1) / n_proc;
    int *partition_offsets = (int*) malloc( (n_proc+1) * sizeof(int) );
    for( int i = 0; i < n_proc+1; i++ )
        partition_offsets[i] = min( i * particle_per_proc, n );
    
    int *partition_sizes = (int*) malloc( n_proc * sizeof(int) );
    for( int i = 0; i < n_proc; i++ )
        partition_sizes[i] = partition_offsets[i+1] - partition_offsets[i];
    
    //
    //  allocate storage for local partition
    //
    int nlocal = partition_sizes[rank];
    particle_t *local = (particle_t*) malloc( nlocal * sizeof(particle_t) );
    
    //
    //  initialize and distribute the particles (that's fine to leave it unoptimized)
    //
    set_size( n );
    if( rank == 0 )
        init_particles( n, particles );
    MPI_Scatterv( particles, partition_sizes, partition_offsets, PARTICLE, local, nlocal, PARTICLE, 0, MPI_COMM_WORLD );
    
    //
    //  simulate a number of time steps
    //
    double simulation_time = read_timer( );
    for( int step = 0; step < NSTEPS; step++ )
    {
        navg = 0;
        dmin = 1.0;
        davg = 0.0;
        // 
        //  collect all global data locally (not good idea to do)
        //
        MPI_Allgatherv( local, nlocal, PARTICLE, particles, partition_sizes, partition_offsets, PARTICLE, MPI_COMM_WORLD );
        
        //
        //  save current step if necessary (slightly different semantics than in other codes)
        //
        if( find_option( argc, argv, "-no" ) == -1 )
          if( fsave && (step%SAVEFREQ) == 0 )
            save( fsave, n, particles );
        
        //
        //  compute all forces
        //
        for( int i = 0; i < nlocal; i++ )
        {
            local[i].ax = local[i].ay = 0;
            for (int j = 0; j < n; j++ )
                apply_force( local[i], particles[j], &dmin, &davg, &navg );
        }
     
        if( find_option( argc, argv, "-no" ) == -1 )
        {
          
          MPI_Reduce(&davg,&rdavg,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
          MPI_Reduce(&navg,&rnavg,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
          MPI_Reduce(&dmin,&rdmin,1,MPI_DOUBLE,MPI_MIN,0,MPI_COMM_WORLD);

 
          if (rank == 0){
            //
            // Computing statistical data
            //
            if (rnavg) {
              absavg +=  rdavg/rnavg;
              nabsavg++;
            }
            if (rdmin < absmin) absmin = rdmin;
          }
        }

        //
        //  move particles
        //
        for( int i = 0; i < nlocal; i++ )
            move( local[i] );
    }
    simulation_time = read_timer( ) - simulation_time;
  
    if (rank == 0) {  
      printf( "n = %d, simulation time = %g seconds", n, simulation_time);

      if( find_option( argc, argv, "-no" ) == -1 )
      {
        if (nabsavg) absavg /= nabsavg;
      // 
      //  -the minimum distance absmin between 2 particles during the run of the simulation
      //  -A Correct simulation will have particles stay at greater than 0.4 (of cutoff) with typical values between .7-.8
      //  -A simulation were particles don't interact correctly will be less than 0.4 (of cutoff) with typical values between .01-.05
      //
      //  -The average distance absavg is ~.95 when most particles are interacting correctly and ~.66 when no particles are interacting
      //
      printf( ", absmin = %lf, absavg = %lf", absmin, absavg);
      if (absmin < 0.4) printf ("\nThe minimum distance is below 0.4 meaning that some particle is not interacting");
      if (absavg < 0.8) printf ("\nThe average distance is below 0.8 meaning that most particles are not interacting");
      }
      printf("\n");     
        
      //  
      // Printing summary data
      //  
      if( fsum)
        fprintf(fsum,"%d %d %g\n",n,n_proc,simulation_time);
    }
  
    //
    //  release resources
    //
    if ( fsum )
        fclose( fsum );
    free( partition_offsets );
    free( partition_sizes );
    free( local );
    free( particles );
    if( fsave )
        fclose( fsave );
    
    MPI_Finalize( );
    
    return 0;
}
コード例 #22
0
ファイル: nbody.c プロジェクト: skattoju/nbody
void init_particles(particle* system){

/*
* particles will be placed randomly 4 quadrants of 3d space
* q1: x>0, y>0
* q2: x<0, y>0
* q3: x<0, y<0
* q4: x>0, y<0
*
*/

 int i = 0;
 srand(time(NULL));

 // q1 x>0, y>0
 for(; i < NO_OF_PARTICLES/4; i++){
   system[i].position = (__vector float){rand()%INIT_BOUNDING_BOX,
rand()%INIT_BOUNDING_BOX,
(rand()%INIT_BOUNDING_BOX*2)-INIT_BOUNDING_BOX, 0};
   system[i].velocity = VECZERO;
   system[i].acceleration = VECZERO;
 }

 // q2 x<0, y>0
 for(; i < NO_OF_PARTICLES/2; i++){
   system[i].position = (__vector float){-rand()%INIT_BOUNDING_BOX,
rand()%INIT_BOUNDING_BOX,
(rand()%INIT_BOUNDING_BOX*2)-INIT_BOUNDING_BOX, 0};
   system[i].velocity = VECZERO;
   system[i].acceleration = VECZERO;
 }

 // q3 x<0, y<0
 for(; i < 3*NO_OF_PARTICLES/4; i++){

   system[i].position = (__vector float){-rand()%INIT_BOUNDING_BOX,
-rand()%INIT_BOUNDING_BOX,
(rand()%INIT_BOUNDING_BOX*2)-INIT_BOUNDING_BOX, 0};
   system[i].velocity = VECZERO;
   system[i].acceleration = VECZERO;
 }

 // q4 x>0, y<0
 for(; i < NO_OF_PARTICLES; i++){

   system[i].position = (__vector float){rand()%INIT_BOUNDING_BOX,
-rand()%INIT_BOUNDING_BOX,
(rand()%INIT_BOUNDING_BOX*2)-INIT_BOUNDING_BOX, 0};
   system[i].velocity = VECZERO;
   system[i].acceleration = VECZERO;

 }


}

void compute_interaction(particle* i , particle* j){

 __vector float radius, radius_sqr, s_vector, displ, accel, distSqr,
distSixth, invDistCube;

 /*compute acceleration of particle i*/
 radius = vec_sub(j->position,i->position);
 radius_sqr = vec_madd(radius,radius, VECZERO);
 distSqr = vec_add(vec_splat(radius_sqr,0),vec_splat(radius_sqr,1));
 distSqr = vec_add(vec_splat(radius_sqr,2),distSqr);
 distSqr = vec_add(EPS2_VECTOR,distSqr);
 distSixth = vec_madd(distSqr,distSqr,VECZERO);
 distSixth = vec_madd(distSixth,distSqr,VEC3ZERO);
 invDistCube = vec_rsqrte(distSixth);
 s_vector = vec_madd(MASS_VECTOR,invDistCube,VECZERO);
 i->acceleration = vec_madd(radius,s_vector,i->acceleration);

 /*compute new position & velocity of particle i*/
 displ = vec_madd(i->velocity,TIME_STEP_VECTOR,i->position);
 accel = vec_madd(VECHALF,i->acceleration, VECZERO);
 i->position = vec_madd(accel,TIME_SQUARED, displ);
 i->velocity = vec_madd(i->acceleration,TIME_STEP_VECTOR, i->velocity);

}


void update_particles(particle* system){

 int i, j;

 //Thread 1 ?
 for(i = 0;i<NO_OF_PARTICLES/4;i++){
   for(j = 0;j<NO_OF_PARTICLES;j++){
     compute_interaction(&system[i],&system[j]);
   }
 }

 //Thread 2 ?
 for(i = NO_OF_PARTICLES/4;i<NO_OF_PARTICLES/2;i++){
   for(j = 0;j<NO_OF_PARTICLES;j++){
     compute_interaction(&system[i],&system[j]);
   }
 }

 //Thread 3 ?
 for(i = NO_OF_PARTICLES/2;i<3*NO_OF_PARTICLES/4;i++){
   for(j = 0;j<NO_OF_PARTICLES;j++){
     compute_interaction(&system[i],&system[j]);
   }
 }

 //Thread 4 ?
 for(i = 3*NO_OF_PARTICLES/4;i<NO_OF_PARTICLES;i++){
   for(j = 0;j<NO_OF_PARTICLES;j++){
     compute_interaction(&system[i],&system[j]);
   }
 }

}

__vector int get_quadrant_count(particle* system){
 
  __vector int quad_count = VECINTZERO;
  __vector int quad_mask = VECINTZERO;
 int i;
 for(i = 0; i < NO_OF_PARTICLES ; i++){

         __vector int top2 = (__vector int){1,1,0,0};
         __vector int bottom2 = (__vector int){0,0,1,1};
         __vector int left2 = (__vector int){0,1,0,1};
         __vector int right2 = (__vector int){1,0,1,0};
	 __vector int mask1, mask2;
   
         __vector float vx = vec_splat(system[i].position,0);
         __vector float vy = vec_splat(system[i].position,1);
	 
	 mask1 = vec_sel(right2, left2, vec_cmpgt(vx,VECZERO));
	 mask2 = vec_sel(top2, bottom2, vec_cmpgt(vy,VECZERO));
         quad_mask = vec_and(mask1,mask2);
	 quad_count = vec_add(quad_count,quad_mask);
	 
 }
 return quad_count;
}

void render(particle* system){

 int i = 0;
 for(; i < NO_OF_PARTICLES; i++){

   float *pos = (float*) &system[i].position;
   float *vel = (float*) &system[i].velocity;
   float *acc = (float*) &system[i].acceleration;

   printf("position : %f %f %f ", pos[0], pos[1], pos[2]);
   printf("velocity : %f %f %f ", vel[0], vel[1], vel[2]);
   printf("acceleration : %f %f %f \n", acc[0], acc[1], acc[2]);

 }
}

int main ()
{

 /* create particle system --> array of particles */
 particle particle_system[NO_OF_PARTICLES] __attribute__((aligned(64)));
 
 /* vector that tracks the no. of particles in each quadrant */
 __vector int quad_count;
 int * qc;
 
 /* place particles in 4 quadrants */
 init_particles(particle_system);

 /* run simulation */
 float simulationTime = 0.0;
 int iterations = COMPUTE_ITERATIONS;
 printf("----------------------------------------------");
 printf("----------------------------------------------\n");
 printf("Running Simulation with %d particles & %d iterations with %f seconds time steps\n",
	NO_OF_PARTICLES, COMPUTE_ITERATIONS, TIME_STEP);
 printf("----------------------------------------------");
 printf("----------------------------------------------\n");

 while(iterations > 0){

   /* Compute */
   update_particles(particle_system);

   /* Display */
   //render(particle_system);

   /* Update Time */
   simulationTime = simulationTime + TIME_STEP;
   printf("----------------------------------");
   printf("Simulation Time: %f |",simulationTime);
   quad_count = get_quadrant_count(particle_system);
   qc = (int*)&quad_count;
   printf(" q1:%d q2:%d q3:%d q4:%d",qc[0], qc[1], qc[2], qc[3]);
   printf("----------------------------------\n");

   iterations --;
 }

 return 0;
}
コード例 #23
0
ファイル: serial.cpp プロジェクト: joelpet/id1217-project
//
//  benchmarking program
//
int main( int argc, char **argv )
{    
    if( find_option( argc, argv, "-h" ) >= 0 )
    {
        printf( "Options:\n" );
        printf( "-h to see this help\n" );
        printf( "-n <int> to set the number of particles\n" );
        printf( "-s <int> to set the number of steps in the simulation\n");
        printf( "-o <filename> to specify the output file name\n" );
        printf( "-f <int> to set the frequency of saving particle coordinates (e.g. each ten's step)");
        return 0;
    }
    
    int n = read_int(argc, argv, "-n", 1000);
    int s = read_int(argc, argv, "-s", NSTEPS);
    int f = read_int(argc, argv, "-f", SAVEFREQ);

    char *savename = read_string( argc, argv, "-o", NULL );
    
    FILE *fsave = savename ? fopen( savename, "w" ) : NULL;
    particle_t *particles = (particle_t*) malloc( n * sizeof(particle_t) );
    set_size( n );
    init_particles( n, particles );

    prtcl::GridHashSet* grid = new prtcl::GridHashSet(n, size, cutoff);
    insert_into_grid(n, particles, grid);

    //
    //  simulate a number of time steps
    //
    double simulation_time = read_timer( );
    for( int step = 0; step < s; step++ )
    {
        //
        //  compute forces
        //
        for (int i = 0; i < n; ++i) {
            particles[i].ax = particles[i].ay = 0;

            // Iterate over all neighbors in the surrounding of current particle.
            // This should be constant w.r.t. n.
            prtcl::GridHashSet::surr_iterator neighbors_it;
            prtcl::GridHashSet::surr_iterator neighbors_it_end = grid->surr_end(
                    particles[i]);

            for (neighbors_it = grid->surr_begin(particles[i]);
                    neighbors_it != neighbors_it_end; ++neighbors_it) {
                apply_force(particles[i], **neighbors_it);
            }
 
        }

        //
        //  move particles
        //
        for( int i = 0; i < n; i++ ) {
            move( particles[i] );
        }

        // Update grid hash set.
        grid->clear();
        insert_into_grid(n, particles, grid);

        
        //
        //  save if necessary
        //
        if( fsave && (step % f) == 0 )
            save( fsave, n, particles );
    }
    simulation_time = read_timer( ) - simulation_time;
    
    printf("n = %d, steps = %d, savefreq = %d, simulation time = %g seconds\n", n, s, f, simulation_time);
    
    delete grid;
    free( particles );
    if( fsave )
        fclose( fsave );
    
    return 0;
}
コード例 #24
0
ファイル: init.c プロジェクト: Sir-Odie/Eternal-Lands
void init_stuff()
{
	int i;
	int seed;

	chdir(DATA_DIR);
	
#ifndef WINDOWS
	setlocale(LC_NUMERIC,"en_US");
#endif
	init_translatables();

	//create_error_mutex();
	init_globals();
	init_crc_tables();
	init_zip_archives();
	cache_system_init(MAX_CACHE_SYSTEM);
	init_texture_cache();

	init_vars();
	
	read_config();

	file_check_datadir();

#ifdef LOAD_XML
	//Well, the current version of the map editor doesn't support having a datadir - will add that later ;-)
	load_translatables();
#endif

#ifdef LINUX
#ifdef GTK2
	init_filters();
#else
	file_selector = create_fileselection();
#endif
#endif	//LINUX

	init_gl();

	window_resize();
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
//	glDepthFunc(GL_LEQUAL);
    glEnable(GL_TEXTURE_2D);
	glShadeModel(GL_SMOOTH);
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glEnable(GL_NORMALIZE);
	glClearColor( 0.0, 0.0, 0.0, 0.0 );
	glClearStencil(0);

	seed = time (NULL);
  	srand (seed);

	init_texture_cache();
	init_particles ();
	init_e3d_cache();
	init_2d_obj_cache();

	for(i=0; i<256; i++)
        tile_list[i]=0;

	for (i = 0; i < MAX_LIGHTS; i++)
		lights_list[i] = NULL;

	new_map(256,256);
	load_all_tiles();

	//lights setup
	build_global_light_table();
	build_sun_pos_table();
	reset_material();
	init_lights();
	//disable_local_lights();
	//clear_error_log();

	// Setup the new eye candy system
#ifdef	EYE_CANDY
	ec_init();
#endif	//EYE_CANDY

	init_gl_extensions();

	if(have_multitexture)
#ifdef	NEW_TEXTURES
		ground_detail_text = load_texture_cached("./textures/ground_detail.bmp", tt_mesh);
#else	/* NEW_TEXTURES */
		ground_detail_text = load_texture_cache ("./textures/ground_detail.bmp",255);
#endif	/* NEW_TEXTURES */

	//load the fonts texture
	init_fonts();
#ifdef	NEW_TEXTURES
	icons_text=load_texture_cached("./textures/gamebuttons.bmp", tt_gui);
	buttons_text=load_texture_cached("./textures/buttons.bmp", tt_gui);
#else	/* NEW_TEXTURES */
	icons_text=load_texture_cache("./textures/gamebuttons.bmp",0);
	buttons_text=load_texture_cache("./textures/buttons.bmp",0);
#endif	/* NEW_TEXTURES */
	//get the application home dir

	have_multitexture=0;//debug only

#ifndef LINUX
	GetCurrentDirectory(sizeof(exec_path),exec_path);
#else
	exec_path[0]='.';exec_path[1]='/';exec_path[2]=0;
#endif
	init_browser();

    if(SDL_InitSubSystem(SDL_INIT_TIMER)<0)
    { 
        char str[120];
        snprintf(str, sizeof(str), "Couldn't initialize the timer: %s\n", SDL_GetError());
        log_error(__FILE__, __LINE__, str);
        SDL_Quit();
	    exit(1);
    }

	SDL_SetTimer (1000/(18*4), my_timer);

	SDL_EnableUNICODE(1);

    //we might want to do this later.

	// creating windows
	display_browser();
	toggle_window(browser_win);

	display_o3dow();
	toggle_window(o3dow_win);

	display_replace_window();
	toggle_window(replace_window_win);

	display_edit_window();
	toggle_window(edit_window_win);

	create_particles_window ();
}
コード例 #25
0
ファイル: main.c プロジェクト: 9578577/parallella-examples
int main(int argc, char** argv)
{
	int i,j,k;
	struct timeval t0,t1;
	double time,gflops;
	int validate = 0;
	int repeat = 0;

	int n = NPARTICLE;
	int cnt = STEPS;
	int s = SIZE;
	int d = ECORE;
	int res;
	float dt = 0.10;
	float es = 0.01;
	unsigned int *fp;

	fb = open(FB, O_RDWR);
	if (fb == -1) {
		perror("Unable to open fb " FB);
		return 1;
	}
	res = ioctl(fb, FBIOGET_FSCREENINFO, &fix);
	if (res != 0) {
		perror("getscreeninfo failed");
		close(fb);
		return 1;
	}


	res = ioctl(fb, FBIOGET_VSCREENINFO, &var);
	if (res != 0) {
		perror("getscreeninfo failed");
		close(fb);
		return 1;
	}

	//printf("size %dx%d @ %d bits per pixel\n", var.xres_virtual, var.yres_virtual, var.bits_per_pixel);

	i = 1;
	while (i < argc) {
		if (!strcmp(argv[i],"-n")) n = atoi(argv[++i]);
		else if (!strcmp(argv[i],"-i")) cnt = atoi(argv[++i]);
		else if (!strcmp(argv[i],"-s")) s = atoi(argv[++i]);
		else if (!strcmp(argv[i],"-d")) d = atoi(argv[++i]);
		else if (!strcmp(argv[i],"-t")) dt = atof(argv[++i]);
		else if (!strcmp(argv[i],"-r")) repeat = 1;
		else if (!strcmp(argv[i],"--validate")) validate = 1;
		else if (!strcmp(argv[i],"--help") || !strcmp(argv[i],"-h")) goto help;
		else {
			fprintf(stderr,"unrecognized option: %s\n",argv[i]);
help:
			ERROR("use -n [number of particles] -s [off-chip scale factor] -i [iteration step count] -d [number of Epiphany cores/threads] --validate\n");
		}
		++i;
	}

	int N = n*s;
	//printf("Using -n=%d, -i=%d -s=%d, dt=%f, es=%f\n", n, cnt, s, dt, es);

	// allocate memory on device and write a value
	Particle* p = (Particle*)malloc(N*sizeof(Particle));
	ParticleV* v = (ParticleV*)malloc(N*sizeof(ParticleV));

	// keep initial conditions around for CPU validation
	Particle* p_validate;
	ParticleV* v_validate;
	system("setterm -cursor off");
	system("setterm -blank 0");
	while(1){
		system("clear");
		init_particles(p, v, N);
		if (validate) {
			p_validate = (Particle*)malloc(N*sizeof(Particle));
			v_validate = (ParticleV*)malloc(N*sizeof(ParticleV));
			memcpy(p_validate,p,N*sizeof(Particle));
			memcpy(v_validate,v,N*sizeof(ParticleV));
		}

		//PRINTP(p,0);
		gettimeofday(&t0,0);
		update_particles_epiphany(p, v, n, s, dt, es, cnt, d);
		gettimeofday(&t1,0);
		//PRINTP(p,0);
		if(repeat == 0)
			break;

		time = t1.tv_sec - t0.tv_sec + 1e-6*(t1.tv_usec - t0.tv_usec);
		gflops = __gflops(time, cnt, N);
		printf("Epiphany Performance : %f GFLOPS (includes overhead)\n",gflops);
		printf("Execution time...... : %f seconds\n",time);
		sleep(4);
	}

	if (validate) {
		printf("Validating on CPU host....\n");
		gettimeofday(&t0,0);
		update_particles_cpu(p_validate, v_validate, n, s, dt, es, cnt);
		gettimeofday(&t1,0);

		PRINTP(p_validate,0);

		float max_diff = 0.0f;
		int errors = validate_particles(p, p_validate, N, &max_diff);

		time = t1.tv_sec - t0.tv_sec + 1e-6*(t1.tv_usec - t0.tv_usec);
		gflops = __gflops(time, cnt, n*s);
		printf("ARM CPU Performance : %f GFLOPS\n",gflops);
		printf("Execution time..... : %f seconds\n",time);
		printf("Errors............. : %d\n", errors);
		printf("Max position delta. : %f\n", max_diff);
	}

}
コード例 #26
0
ファイル: sph.c プロジェクト: njbooher/cs5220_group
int main(int argc, char** argv)
{
  sim_param_t params;
  if (get_params(argc, argv, &params) != 0)
    exit(-1);

  // Create global
  sim_state_t* globalState = init_particles(&params);

#pragma omp parallel shared(globalState, params) 
  {
    int proc = omp_get_thread_num();
    int nproc = omp_get_num_threads();

    FILE* fp    = fopen(params.fname, "w");
    int nframes = params.nframes;
    int npframe = params.npframe;
    float dt    = params.dt;
    int n       = globalState->n;

    // Processor information and holder
    proc_info* pInfo = malloc(sizeof(proc_info)); 
    pInfo->proc = proc;
    pInfo->nproc = nproc;
    pInfo->beg = round((proc/(double)nproc)*n);
    pInfo->end = round(((proc+1)/(double)nproc)*n);
    pInfo->forceAccu = calloc(3*n, sizeof(float)); // Never used this...


    if (proc == 0) {
      printf("Running in parallel with %d processor\n", nproc);
    }

    normalize_mass(globalState, pInfo, &params);

    double t_start = omp_get_wtime();

    if (proc == 0) { // We only write for one processor
      write_header(fp, n, nframes, params.h);
      write_frame_data(fp, n, globalState, NULL);
    }

    if (proc == 0) {
      hash_particles(globalState, params.h);
    }
    //hash_particles_parallel(globalState, pInfo, params.h);

#pragma omp barrier // Need the hashing to be done

    compute_accel(globalState, pInfo, &params);

#pragma omp barrier
    leapfrog_start(globalState, pInfo, dt);
    check_state(globalState, pInfo);
    for (int frame = 1; frame < nframes; ++frame) {

      // We sort according to Z-Morton to ensure locality, need to implement paralle qsort
      if (frame % 5 == 0) {

        // Dividing into chunks of sorting each chunk
        // This alone turned out to better than sorting the entire array
        qsort(globalState->part+pInfo->beg, pInfo->end-pInfo->beg ,sizeof(particle_t),compPart);
        // Sorting the array consisting of sorted chunks
        // This turned out to actually lower the performance. That's why
        // I commented it.
        // #pragma omp barrier
        //   if( pInfo->nproc >1 ) arraymerge(globalState->part, globalState->n, pInfo);
//#pragma omp barrier*/

        // Serial version
        /*#pragma omp single // Implied barrier
          qsort(globalState->part, n, sizeof(particle_t), compPart);*/
      }
      /*else if (frame % 49) {*/
        /*if (proc == 0) {*/
        /*}*/
      /*}*/

#pragma omp barrier // Need sort to finish

    for (int i = 0; i < npframe; ++i) {
      if (proc == 0 && npframe % 4 == 0) { // Ammortize hashing cost
        hash_particles(globalState, params.h);        
      }

#pragma omp barrier
      compute_accel(globalState, pInfo, &params);
      leapfrog_step(globalState, pInfo, dt);
      check_state(globalState, pInfo);
#pragma omp barrier
    }

    if (proc == 0) {
      printf("Frame: %d of %d - %2.1f%%\n",frame, nframes, 
          100*(float)frame/nframes);
      write_frame_data(fp, n, globalState, NULL);
    }
  }

  double t_end = omp_get_wtime();

  if (proc == 0) {
    printf("Ran in %g seconds\n", t_end-t_start);
  }

  free(pInfo);
  fclose(fp);
}

free_state(globalState);
}
コード例 #27
0
ファイル: md_opt.c プロジェクト: bragilee/project
int main(int argc, char** argv)
{
  //printf("%f\n",GRID_NUM);
  struct timespec diff(struct timespec start, struct timespec end);
  struct timespec time1, time2;
  struct timespec time_stamp;


  int npart,i,j,Num;

  params param;
  mols mol;
  adjacent adj;

  param.npart = N_BODY_NUM;
  param.dt = DT;
  param.eps_lj = EPS;
  param.sig_lj = SIG;

  mol.x = malloc(2*param.npart * sizeof(float));
  mol.v = malloc(2*param.npart * sizeof(float));
  mol.a = malloc(2*param.npart * sizeof(float));
  mol.F = malloc(2*param.npart * sizeof(float));
#if (NEAREST)
  double Blength = BLOCK_LENGTH(GRID_NUM,BOX_SIZE);
  printf("Blength: %lf\n",Blength);
  Num = EST_NUM(GRID_NUM,N_BODY_NUM);
  Num = 4*Num;
  if(!Num)
  {
     Num = 4;
  }
  
  if(N_BODY_NUM < Num)
  {
    Num = N_BODY_NUM;
  }

  adj.n = malloc(sizeof(int) * GRID_NUM * GRID_NUM * Num);
  memset(adj.n,-1,sizeof(int) * GRID_NUM * GRID_NUM *  Num);
  printf("Num: %d\n",Num);
#endif

  npart = init_particles(param.npart, mol.x , mol.v, &param);
  if(npart < param.npart)
  {
    fprintf(stderr, "Could not generate %d particles, Trying %d particles instead\n",param.npart,npart);
    param.npart = npart;
  }
  else
  {
    fprintf(stdout,"Generated %d particles\n",param.npart);
  }

  init_particles_va( param.npart, mol.v,mol.a, &param);

#if(NEAREST)
  printf("Before gridSort\n");
  gridSort(npart, GRID_NUM, Num, adj.n, mol.x);
  printf("After gridSort\n");
#endif

  /*for(i=0;i<npart;i++)
    printf("myBlockNum: %d\n",getMyBlock(param.npart,2*i, adj.n, Num/2));

    for(i=0; i < param.npart; i++)
    {
    printf("nBody-Num: %d Posx: %f Velx: %f Accx: %f Forcex: %f\n",i,
    mol.x[2*i],mol.v[2*i],mol.a[2*i],mol.F[2*i]);
    printf("nBody-Num: %d Posy: %f Vely: %f Accy: %f Forcey: %f\n",i,
    mol.x[2*i+1],mol.v[2*i+1],mol.a[2*i+1],mol.F[2*i+1]);
    }
    */

#if(LINUX)

  clock_gettime(CLOCK_REALTIME, &time1);

#endif
#if(NEAREST)
  compute_forces_nearby(param.npart, adj.n, mol.x, mol.F, GRID_NUM, Num);

#elif(OPT)  
  compute_forces(param.npart,mol.x,mol.F);
#else
    compute_forces_naive(param.npart,mol.x,mol.F);

#endif
  printf("After First ComputeForces\n");
  for(i=0;i<ITERS;i++)
  {
#if(NEAREST)
    gridSort(npart, GRID_NUM, Num, adj.n, mol.x);		    // Added in the gridSort function for each iteration
#endif
    verletInt1(param.npart,param.dt , mol.x, mol.v,mol.a);
    box_reflect(param.npart,mol.x,mol.v,mol.a );
#if(NEAREST)
    compute_forces_nearby(param.npart, adj.n, mol.x, mol.F, GRID_NUM, Num);
#elif(OPT)
    compute_forces(param.npart,mol.x,mol.F);
#else
    compute_forces_naive(param.npart,mol.x,mol.F);
#endif
    verletInt2(param.npart,param.dt, mol.x, mol.v, mol.a);
    memset(mol.F, 0 , 2*param.npart * sizeof(float));
  }

#if(LINUX)

  clock_gettime(CLOCK_REALTIME, &time2);

#endif

  /*
     for(i=0; i < param.npart; i++)
     {
     printf("nBody-Num: %d Posx: %f Velx: %f Accx: %f Forcex: %f\n",i,
     mol.x[2*i],mol.v[2*i],mol.a[2*i],mol.F[2*i]);
     printf("nBody-Num: %d Posy: %f Vely: %f Accy: %f Forcey: %f\n",i,
     mol.x[2*i+1],mol.v[2*i+1],mol.a[2*i+1],mol.F[2*i+1]);
     }
     */

#if(LINUX)

  double blength = BLOCK_LENGTH(GRID_NUM,BOX_SIZE);
  printf("Boxsize: %lf,Blocksize: %lf,MaxBodiesPerBlock: %d\n",BOX_SIZE,blength, maxNumPartPerBlock(blength,SIG));
  time_stamp = diff(time1,time2);
  printf("Execution time: %lf\n",(double)((time_stamp.tv_sec + (time_stamp.tv_nsec/1.0e9))));

#else

  printf("Boxsize: %lf,BlockNum: %lf,MaxBodiesPerBlock: %d\n",BOX_SIZE,GRID_NUM, maxNumPartPerBlock(GRID_NUM,SIG));

#endif

  /*        // test statements for the grid allocation
            int count =0;
            for(i=0;i<GRID_NUM*GRID_NUM*Num/2;i++)
            {
            if(adj.n[i]!=-1)
            {
            count++;
            }
            }
            printf("%d\n",count);

*/
#if(NEAREST)
  free(adj.n);
#endif
  free(mol.x);
  free(mol.v);
  free(mol.a);
  free(mol.F);
  printf("Done\n");

  return 0;
}
コード例 #28
0
ファイル: pthreads.cpp プロジェクト: Chunming/CS267-hw2
//
//  benchmarking program
//
int main( int argc, char **argv )
{    
  //
  //  process command line
  //
  if( find_option( argc, argv, "-h" ) >= 0 )
    {
      printf( "Options:\n" );
      printf( "-h to see this help\n" );
      printf( "-n <int> to set the number of particles\n" );
      printf( "-p <int> to set the number of threads\n" );
      printf( "-o <filename> to specify the output file name\n" );
      return 0;
    }
    
  n = read_int( argc, argv, "-n", 1000 );
  n_threads = read_int( argc, argv, "-p", 2 );
  char *savename = read_string( argc, argv, "-o", "pthreads.txt" );
  
  //
  //  allocate resources
  //
  fsave = savename ? fopen( savename, "w" ) : NULL;

  particles = (particle_t*) malloc( n * sizeof(particle_t) );
  
  set_size( n );
  init_particles( n, particles );

  blks_num = max(2 * size / sqrt((MAX_PART_THREADS)*(3.14159)*cutoff*cutoff), 1);
  blks_size =  size / ((double) blks_num);
  subblks_num = max(2 * blks_size / sqrt((MAX_PART_SUBB)*(3.14159)*cutoff*cutoff), 1);
  subblks_size = blks_size / ((double) subblks_num);
  totblks_num = blks_num * subblks_num;
  part_int = n/( blks_num * blks_num ) + 1;

  printf("blks_num %d, blks_size %f, subblks_num %d, subblks_size %f, totblks_num %d \n", blks_num, blks_size, subblks_num, subblks_size, totblks_num);

  printf("size %f, totblks_num * subblks_size %f \n", size, totblks_num * subblks_size);

  //printf("n %d, part_int %d, blks_num %d, cutoff %f \n", n, part_int, blks_num, cutoff);
  
  bins = (particle_t **) malloc( MAX_PART_SUBB * totblks_num * totblks_num * sizeof(particle_t*));
  bin_part_num = (int *) malloc( totblks_num * totblks_num * sizeof(int));
  bin_mutexes = (pthread_mutex_t*) malloc( totblks_num * totblks_num * sizeof(pthread_mutex_t));
  memset(bin_part_num, 0, totblks_num * totblks_num * sizeof(int));
  

  pthread_attr_t attr;
  P( pthread_attr_init( &attr ) );
  P( pthread_barrier_init( &barrier, NULL, blks_num * blks_num ) );
  pthread_mutex_init( &set_count_zero, NULL );
  pthread_cond_init( &count_zero_cond, NULL );

  for(int i=0; i<totblks_num*totblks_num; ++i)
  {
      if(pthread_mutex_init(&bin_mutexes[i], NULL))
	{
	  printf("\nsetupBins(): Unable to initialize the %i th mutex\n", i);
	}
  }

  int *thread_ids = (int *) malloc( blks_num * blks_num * sizeof( int ) );
  for( int i = 0; i < blks_num*blks_num; i++ ) 
    thread_ids[i] = i;

  pthread_t *threads = (pthread_t *) malloc( blks_num * blks_num * sizeof( pthread_t ) );
    
  printf("shit allocated \n");

  //
  //  do the parallel work
  //
  simulation_time = read_timer( );
  for( int i = 1; i < blks_num * blks_num; i++ ) 
    P( pthread_create( &threads[i], &attr, thread_routine, &thread_ids[i] ) );
    
  printf("pthreads created \n");

  thread_routine( &thread_ids[0] );
    
  printf("first thread runs \n");

  for( int i = 1; i < blks_num * blks_num; i++ ) 
    P( pthread_join( threads[i], NULL ) );

  simulation_time = read_timer( ) - simulation_time;
    
  printf( "n = %d, n_threads = %d, simulation time = %g seconds\n", n, blks_num*blks_num, simulation_time );
    
  //
  //  release resources
  //
  P( pthread_barrier_destroy( &barrier ) );
  P( pthread_attr_destroy( &attr ) );
  pthread_mutex_destroy(&set_count_zero);
  pthread_cond_destroy(&count_zero_cond);

  for(int i=0; i<totblks_num*totblks_num; i++)
  {
      pthread_mutex_destroy(&bin_mutexes[i]);
  }

  free( thread_ids );
  free( threads );
  free( bin_mutexes );
  free( bin_part_num );
  free( bins );
  free( particles );
  if( fsave )
    fclose( fsave );
    
  return 0;
}
コード例 #29
0
int main(int argc, char *argv[]) {

  /* Settings */
  int use_smoothing = 0;
  int use_flow = 1;
  int use_multiple_predictions = 0;
  int use_variance = 0;

  if (argc < 2) {
    printf("Please specify: test, train, or preds and data set size");
    return -1;
  }

  int SIZE_SIFT = atoi(argv[2]);

  /* Create arrays for measurements */
  struct measurement measurements[SIZE_SIFT];
  struct measurement measurements_2[SIZE_SIFT]; /* If multiply regressors are used */
  struct measurement measurements_3[SIZE_SIFT]; /* If multiply regressors are used */

  struct measurement opticalflow[SIZE_SIFT];

  char *filename_out;

  /* For test set */
  if (strcmp(argv[1], "test") == 0) {   
    filename_out = "sift_filtered_test_2.csv";
    //char filename_in[] = "/home/pold/Documents/Internship/datasets/board_test_pos.csv";
    char filename_in[] = "/home/pold/Documents/Internship/datasets/board_test_2_pos.csv";
    read_measurements_from_csv(measurements, filename_in, SIZE_SIFT);
  }

  /* For training set */
  else if (strcmp(argv[1], "train") == 0) {
    filename_out = "sift_filtered_train_vel.csv";
    char filename_in[] = "/home/pold/Documents/Internship/datasets/board_train_pos.csv";
    read_measurements_from_csv(measurements, filename_in, SIZE_SIFT);
  }

  /* For predictions */
  else if (strcmp(argv[1], "preds") == 0) {
    filename_out = "predictions_filtered_lasso.csv";
    char filename_in[] = "/home/pold/Documents/treXton/predictions_cross.csv";
    char filename_in_2[] = "/home/pold/Documents/treXton/predictions.csv";

    char filename_optical_flow[] = "/home/pold/Documents/trexton_pprz/edgeflow_diff.csv";
    //char filename_in_3[] = "/home/pold/Documents/Internship/treXton/predictions_3.csv";
    read_predictions_from_csv(measurements, filename_in, SIZE_SIFT, 1);
    read_predictions_from_csv(measurements_2, filename_in_2, SIZE_SIFT, 0);

    read_predictions_from_csv(opticalflow, filename_optical_flow, SIZE_SIFT, 0);
    /* read_predictions_from_csv(measurements_3, filename_in_3, SIZE_SIFT); */


  } else {
    printf("No argument specified");
    return -1;
  }
  
  /* Create and initialize particles */
  struct particle particles[N];
  init_particles(particles);

  struct particle particles_backward[N];
  init_particles(particles_backward);

  /* Run particle filter for every measurement */
  int i = 0, j = 0, k;
  FILE *fp = fopen(filename_out, "w");
  fprintf(fp, "x,y\n");

  /* Tables for dynamic programming */
  struct particle ps_forward[SIZE_SIFT];
  struct particle ps_backward[SIZE_SIFT];
  struct particle uncertainties[SIZE_SIFT];

  /* Fill in dynamic programming table */
  for (i = 0; i < SIZE_SIFT; i++) {
    printf(" iteration: %d\n", i);
    fflush(stdout);

    /* Use predictions form multiple regressors */ 
    if (use_multiple_predictions) {
      particle_filter_multiple(particles, &measurements[i], &measurements_2[i], use_variance);
    } else {
      particle_filter(particles, &measurements[i], &opticalflow[i], use_variance, use_flow);
    }


    /* Forward-backward smoothing */
    if (use_smoothing) {
      k = SIZE_SIFT - i;
      particle_filter(particles_backward, &measurements[k], &opticalflow[i], use_variance, use_flow);
      struct particle p_backward = weighted_average(particles_backward, N);
      ps_backward[k] = p_backward;
    }


    struct particle p_forward = weighted_average(particles, N);
    uncertainties[i] = calc_uncertainty(particles, p_forward, N);

    printf("Uncertainty: x: %f y: %f", uncertainties[i].x, uncertainties[i].y);
    
    ps_forward[i] = p_forward;

  }

  for (i = 0; i < SIZE_SIFT; i++) {

    struct particle p;

    printf("measurement %f %f\n", measurements[i].x, measurements[i].y);

    if (use_smoothing)
      p = weight_forward_backward(ps_forward[i], ps_backward[i], i, (SIZE_SIFT - i));
    
    else
      p = ps_forward[i];

    printf("x: %f y: %f", p.x, p.y);
    fprintf(fp, "%f,%f\n" , p.x, p.y);
  }

  fclose(fp);
  return 0;
}
コード例 #30
0
ファイル: spacerace.c プロジェクト: demonslayer/spacerace
int main(int argc,char* argv[])
{
   //  Initialize GLUT and process user parameters
   glutInit(&argc,argv);
   //  Request double buffered, true color window with Z buffering at 600x600
   glutInitWindowSize(800,800);
   glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
   //  Create the window
   glutCreateWindow("Objects");
   //  Tell GLUT to call "idle" when there is nothing else to do
   glutIdleFunc(idle);
   //  Tell GLUT to call "display" when the scene should be drawn
   glutDisplayFunc(display);
   //  Tell GLUT to call "reshape" when the window is resized
   glutReshapeFunc(reshape);
   //  Tell GLUT to call "special" when an arrow key is pressed
   glutSpecialFunc(special);
   //  Tell GLUT to call "key" when a key is pressed
   glutKeyboardFunc(key);


   // Load Textures
   texture[0] = LoadTexBMP("znorl.bmp");
   texture[1] = LoadTexBMP("metal.bmp");
   texture[2] = LoadTexBMP("turquoise.bmp");
   texture[3] = LoadTexBMP("stars.bmp");
   texture[4] = LoadTexBMP("particle.bmp");
   texture[5] = LoadTexBMP("zekador.bmp");
   texture[6] = LoadTexBMP("ishthar.bmp");
   texture[7] = LoadTexBMP("nesk.bmp");
   texture[8] = LoadTexBMP("centura.bmp");
   texture[9] = LoadTexBMP("tenav.bmp");
   texture[10] = LoadTexBMP("tsarvia.bmp");
   texture[11] = LoadTexBMP("kolatanevat.bmp");
   texture[12] = LoadTexBMP("falarn.bmp");
   texture[13] = LoadTexBMP("grass.bmp");
   texture[14] = LoadTexBMP("wood.bmp");
   texture[15] = LoadTexBMP("pine.bmp");
   texture[16] = LoadTexBMP("water.bmp");
   texture[17] = LoadTexBMP("blue.bmp");
   texture[18] = LoadTexBMP("red.bmp");
   texture[19] = LoadTexBMP("darkmetal.bmp");

   // Load Maya objects
   //int num_vertices, int num_normals, int num_tex, int num_faces, char *filename
   // double *vertices, double *normals, double *texs, int *faces
   load_obj(num_vertices_voyager, num_normals_voyager, num_tex_voyager, num_faces_voyager, "voyagereng.obj", voyager_vertices, voyager_normals, voyager_texs, voyager_faces);
   load_obj(num_vertices_asteroid, num_normals_asteroid, num_tex_asteroid, num_faces_asteroid, "asteroid1.obj", asteroid_1_vertices, asteroid_1_normals, asteroid_1_texs, asteroid_1_faces);
   load_obj(num_vertices_asteroid, num_normals_asteroid, num_tex_asteroid, num_faces_asteroid, "asteroid2.obj", asteroid_2_vertices, asteroid_2_normals, asteroid_2_texs, asteroid_2_faces);
   load_obj(num_vertices_asteroid, num_normals_asteroid, num_tex_asteroid, num_faces_asteroid, "asteroid3.obj", asteroid_3_vertices, asteroid_3_normals, asteroid_3_texs, asteroid_3_faces);
   load_obj(num_vertices_asteroid, num_normals_asteroid, num_tex_asteroid, num_faces_asteroid, "asteroid_city.obj", asteroid_city_vertices, asteroid_city_normals, asteroid_city_texs, asteroid_city_faces);
   load_obj(num_vertices_city, num_normals_city, num_tex_city, num_faces_city, "city.obj", city_vertices, city_normals, city_texs, city_faces);
   load_obj(num_vertices_renegade, num_normals_renegade, num_tex_renegade, num_faces_renegade, "renegade.obj", renegade_vertices, renegade_normals, renegade_texs, renegade_faces);
   load_obj(num_vertices_phantom, num_normals_phantom, num_tex_phantom, num_faces_phantom, "phantom.obj", phantom_vertices, phantom_normals, phantom_texs, phantom_faces);




   init_particles(sun_particle, MAX_SUN_PARTICLES, 0.01, 10, 10, 1, 1, 0, 1.0, 0);
   init_particles(ship_particle, MAX_SHIP_PARTICLES, 0.01, 10, 10, 1, 1, 1, 1.0, 10);
   //  Pass control to GLUT so it can interact with the user
   glutMainLoop();
   return 0;
}