示例#1
0
int point_crossover(void *t1, void *t2)
{
    int *indicies = random_indicies_new(t1, t2);
    struct node *n1 = ((struct tree *) t1)->chromosome[indicies[0]];
    struct node *n2 = ((struct tree *) t2)->chromosome[indicies[1]];
    struct node *n1_old_parent = n1->parent;
    struct node *n2_old_parent = n2->parent;
    int n1_old_nth_child = n1->nth_child;
    int n2_old_nth_child = n2->nth_child;

    /* update parents */
    if (n1->parent != NULL) {
        n1->parent->children[n1->nth_child] = n2;
    }

    if (n2->parent != NULL) {
        n2->parent->children[n2->nth_child] = n1;
    }

    /* crossover */
    n1->parent = n2_old_parent;
    n2->parent = n1_old_parent;
    n1->nth_child = n2_old_nth_child;
    n2->nth_child = n1_old_nth_child;

    /* update tree */
    tree_update(t1);
    tree_update(t2);

    /* clean up */
    free(indicies);
    return 0;
}
示例#2
0
int main() {
	int n; scanf("%d", &n);

	for (int i = 0; i < n; i++)
		scanf("%d", &ts[i].x);
	for (int i = 0; i < n; i++) 
		scanf("%d", &ts[i].y);
	for (int i = 0; i < n; i++)
		scanf("%d", &ts[i].z);

	sort(0, n-1);

	for (int i = 0; i < n; i++)
		fprintf(stderr, "%d %d %d\n", ts[i].x, ts[i].y, ts[i].z);

	for (int i = 0; i < n; i++)
		ys[i] = ts[i].y;

	sort_ys(0, n-1);
	ys_n = 1;
	for (int i = 1; i < n; i++) 
		if (ys[i] != ys[i-1])
			ys[ys_n++] = ys[i];

	tree_init(ys_n+1);
	int c = 0;

	for (int i = n-1; i >= 0; i--) {
		int j = ys_n-ys_find(ts[i].y);
		fprintf(stderr, "j = %d\n", j);
		int v = tree_max(j-1);
		fprintf(stderr, "v = %d\n", v);
		if (v > ts[i].z)
			c++;
		tree_update(j, ts[i].z);
	}

	printf("%d\n", c);

	return 0;
}
示例#3
0
void leimkuhler_tree(double maxtime)
{
    int i;
    const double tinterval = 1.0;
    float time_start, time_end;

    if (verbosity > 0)
    {
        fprintf(err, "Using leimkuhler_tree integrator.\n"
                     "TIME_CAP:      %3i\n", 
                     TIME_CAP);
        fprintf(err, "-------------------------------------------------\n");
    }

    /*========================================================================
     * Calculate the initial forces and time steps, start the integrator
     * by first drifting.
     *======================================================================*/
    for (i=0; i < NPARTICLES; i++)
        lkACCEL_AND_POTENTIAL(ps[i], 0);

    for (i=0; i < NPARTICLES; i++)
    {
        double h2 = sqrt(SELECT_TIME_STEP(ps[i]));
        DRIFT(ps[i], h2);
        ps[i]->time = 0;
        ps[i]->timeNext = h2;
    }
    write_state(0);

    /*========================================================================
     * Put each particle into the priority queue
     *======================================================================*/
    struct pqNode *head = ps[0];
    for (i=1; i < NPARTICLES; i++)
    {
        struct pqNode *p = ps[i];
        PQ_MERGE(head, p);
    }

    pTree *tree;

    tree = pintBuildTree(ps, NULL);

#if 1
    time_start = CPUTIME;
    for (i=0; i < 50000; i++)
        tree = pintBuildTree(ps, NULL);
    time_end   = CPUTIME;
#endif
#if DYNAMIC_TREE
    //fprintf(err, "tree->cell.fMass = %e\n", tree->cell.fMass);
#endif
    fprintf(err, "comparisonCount = %i\n", comparisonCount);
    fprintf(err, "nodeCount = %i\n", nodeCount);
    fprintf(err, "tree construction time = %e\n", (time_end - time_start) / 50000.);
    //fprintf(err, "tree construction time = %e\n", (time_end - time_start) );
    //assert(tree->cell.fMass == 1.0);

#if 0
#if DYNAMIC_TREE
    int len = walk_tree(tree, NULL, 0);
    fprintf(err, "\n");
#else
    int len = walk_tree(tree, ps, 0);
    fprintf(err, "\n");
#endif
#endif

#if 0
#if DYNAMIC_TREE
    fprintf(err, "\n\n");
    struct pqNode **ps2 = (struct pqNode **)malloc(NPARTICLES * sizeof(struct pqNode *));
    int len = walk_tree(tree, ps2, 0);
    fprintf(err, "len = %i\n", len);
    assert(len == NPARTICLES);

    struct pqNode *ps3 = (struct pqNode *)malloc(NPARTICLES * sizeof(struct pqNode));
    assert(ps3 != NULL);
    for (i=0; i < NPARTICLES; i++)
        memcpy(&(ps3[i]), ps2[i], sizeof(struct pqNode));

    for (i=0; i < NPARTICLES; i++)
        ps2[i] = &(ps3[i]);

    time_start = CPUTIME;
    for (i=0; i < 5000; i++)
        tree = pintBuildTree(ps2, NULL);
    time_end   = CPUTIME;
    fprintf(err, "tree->cell.fMass = %e\n", tree->cell.fMass);
    fprintf(err, "tree construction time = %e\n", (time_end - time_start) / 5000.);
#endif
#endif
    //assert(tree->cell.fMass == 1.0);

    return;

    /*========================================================================
     * Run the simulation
     *======================================================================*/
    double prevtimeNext = 0;
    double tout = tinterval;

    fflush(out);
    fflush(err);

    RESET_ACCEL_HIST();
    while (1)
    {
        struct pqNode *p;
        PQ_REMOVE_MIN(head, p);

        assert(prevtimeNext <= p->timeNext);
        prevtimeNext = p->timeNext;

        fprintf(out, "%i %f %f %f\n", p->id, p->r[0], p->r[1], p->r[2]);
        fflush(out);

        /*====================================================================
         * Write output
         *==================================================================*/
        if (p->timeNext < tout && tout <= head->timeNext) 
        {
            tout += tinterval;
            RESET_ACCEL_HIST();
            for (i=0; i < NPARTICLES; i++) ACCEL_HIST(ps[i]->a);

            write_state(p->timeNext);
            AccelCount = 0;

            if (p->timeNext < maxtime && maxtime <= head->timeNext) break;

#if !DYNAMIC_TREE
            //tree = pintBuildTree2(ps, tree);
            tree = pintBuildTree(ps, NULL);
#endif
        }

        /*====================================================================
         * Drift, Kick, Drift
         *==================================================================*/
        double h1 = p->timeNext - p->time;
        DRIFT(p, h1);
        lkACCEL_AND_POTENTIAL(p, p->timeNext);
        KICK(p, h1);
        double h2 = SELECT_TIME_STEP(p) / h1;
        KICK(p, h2);
        DRIFT(p, h2);

        /*====================================================================
         * Update particle's time and put it back in the queue
         *==================================================================*/
        p->time = p->timeNext + h2;
        p->timeNext = p->time + h2;

#if DYNAMIC_TREE
        _DA_ time_start = CPUTIME;
        tree = tree_update(p, tree);
        _DA_ time_end = CPUTIME;
        _DA_ fprintf(err, "tree update time = %e\n", time_end - time_start);
#endif

#if 0
#if DYNAMIC_TREE
        _DA_ time_start = CPUTIME;
        tree = tree_insert(p, tree);
        _DA_ time_end = CPUTIME;
        _DA_ fprintf(err, "tree insert time = %e\n", time_end - time_start);
#endif
#endif
        PQ_MERGE(head, p);
    }
}
示例#4
0
void iterate(void){	
	// A 'DKD'-like integrator will do the first 'D' part.
	PROFILING_START()
	integrator_part1();
	PROFILING_STOP(PROFILING_CAT_INTEGRATOR)

	// Check for root crossings.
	PROFILING_START()
	boundaries_check();     
	PROFILING_STOP(PROFILING_CAT_BOUNDARY)

	// Update and simplify tree. 
	// Prepare particles for distribution to other nodes. 
	// This function also creates the tree if called for the first time.
	PROFILING_START()
#ifdef TREE
	tree_update();          
#endif //TREE

#ifdef MPI
	// Distribute particles and add newly received particles to tree.
	communication_mpi_distribute_particles();
#endif // MPI

#ifdef GRAVITY_TREE
	// Update center of mass and quadrupole moments in tree in preparation of force calculation.
	tree_update_gravity_data(); 
	
#ifdef MPI
	// Prepare essential tree (and particles close to the boundary needed for collisions) for distribution to other nodes.
	tree_prepare_essential_tree_for_gravity();

	// Transfer essential tree and particles needed for collisions.
	communication_mpi_distribute_essential_tree_for_gravity();
#endif // MPI
#endif // GRAVITY_TREE

	// Calculate accelerations. 
	gravity_calculate_acceleration();
	if (N_megno){
		gravity_calculate_variational_acceleration();
	}
	// Calculate non-gravity accelerations. 
	if (problem_additional_forces) problem_additional_forces();
	if (problem_additional_forces_with_parameters) problem_additional_forces_with_parameters(particles, t, dt, G, N, N_megno);
	PROFILING_STOP(PROFILING_CAT_GRAVITY)

	// A 'DKD'-like integrator will do the 'KD' part.
	PROFILING_START()
	integrator_part2();
	if (problem_post_timestep_modifications){
		integrator_synchronize();
		problem_post_timestep_modifications();
		if (integrator == WHFAST || integrator == HYBRID){
			integrator_whfast_recalculate_jacobi_this_timestep = 1;
		}
	}
	if (problem_post_timestep_modifications_with_parameters){
		integrator_synchronize();
		problem_post_timestep_modifications_with_parameters(particles, t, dt, G, N, N_megno);
		if (integrator == WHFAST || integrator == HYBRID){
			integrator_whfast_recalculate_jacobi_this_timestep = 1;
		}
	}
	PROFILING_STOP(PROFILING_CAT_INTEGRATOR)

	// Do collisions here. We need both the positions and velocities at the same time.
#ifndef COLLISIONS_NONE
	// Check for root crossings.
	PROFILING_START()
	boundaries_check();     
	PROFILING_STOP(PROFILING_CAT_BOUNDARY)

	// Search for collisions using local and essential tree.
	PROFILING_START()
	collisions_search();

	// Resolve collisions (only local particles are affected).
	collisions_resolve();
	PROFILING_STOP(PROFILING_CAT_COLLISION)
#endif  // COLLISIONS_NONE

#ifdef OPENGL
	PROFILING_START()
	display();
	PROFILING_STOP(PROFILING_CAT_VISUALIZATION)
#endif // OPENGL
	problem_output();
	// Check if the simulation finished.
#ifdef MPI
	int _exit_simulation = 0;
	MPI_Allreduce(&exit_simulation, &_exit_simulation,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
	exit_simulation = _exit_simulation;
#endif // MPI
	// @TODO: Adjust timestep so that t==tmax exaclty at the end.
	if((t+dt>tmax && tmax!=0.0) || exit_simulation==1){
#ifdef GRAVITY_GRAPE
		gravity_finish();
#endif // GRAVITY_GRAPE
		problem_finish();
		struct timeval tim;
		gettimeofday(&tim, NULL);
		double timing_final = tim.tv_sec+(tim.tv_usec/1000000.0);
		printf("\nComputation finished. Total runtime: %f s\n",timing_final-timing_initial);
#ifdef MPI
		MPI_Finalize();
#endif // MPI
		exit(0);
	}
}
示例#5
0
void display(){
	if (display_pause) return;
#ifdef TREE
	if (display_tree){
		tree_update();
#ifdef GRAVITY_TREE
		tree_update_gravity_data();
#endif
	}
#endif
	if (display_clear){
	        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
	}
	if (!display_wire) {
	if (display_spheres){
		glDisable(GL_BLEND);                    
		glDepthMask(GL_TRUE);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		GLfloat lightpos[] = {0, boxsize_max, boxsize_max, 0.f};
		glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
	}else{
		glEnable(GL_BLEND);                    
		glDepthMask(GL_FALSE);
		glDisable(GL_DEPTH_TEST);
		glDisable(GL_LIGHTING);
		glDisable(GL_LIGHT0);
	}
	}
	glEnable(GL_POINT_SMOOTH);
	glVertexPointer(3, GL_DOUBLE, sizeof(struct particle), particles);
	int _N_active = (N_active==-1)?N:N_active;
	if (display_reference>=0){
		glTranslatef(-particles[display_reference].x,-particles[display_reference].y,-particles[display_reference].z);
	}
	glRotatef(display_rotate_x,1,0,0);
	glRotatef(display_rotate_z,0,0,1);
	for (int i=-display_ghostboxes*nghostx;i<=display_ghostboxes*nghostx;i++){
	for (int j=-display_ghostboxes*nghosty;j<=display_ghostboxes*nghosty;j++){
	for (int k=-display_ghostboxes*nghostz;k<=display_ghostboxes*nghostz;k++){
		struct ghostbox gb = boundaries_get_ghostbox(i,j,k);
		glTranslatef(gb.shiftx,gb.shifty,gb.shiftz);
		if (!(!display_clear&&display_wire)){
			if (display_spheres){
				// Drawing Spheres
				glColor4f(1.0,1.0,1.0,1.0);
#ifndef COLLISIONS_NONE
				for (int i=0;i<N;i++){
					struct particle p = particles[i];
					glTranslatef(p.x,p.y,p.z);
					glScalef(p.r,p.r,p.r);
#ifdef _APPLE
					glCallList(display_dlist_sphere);
#else //_APPLE
					glutSolidSphere(1,40,10);
#endif //_APPLE
					glScalef(1./p.r,1./p.r,1./p.r);
					glTranslatef(-p.x,-p.y,-p.z);
				}
#endif // COLLISIONS_NONE
			}else{
				// Drawing Points
				glEnableClientState(GL_VERTEX_ARRAY);
				glPointSize(3.);
				glColor4f(1.0,1.0,1.0,0.5);
				glDrawArrays(GL_POINTS, _N_active, N-_N_active);
				glColor4f(1.0,1.0,0.0,0.9);
				glPointSize(5.);
				glDrawArrays(GL_POINTS, 0, _N_active);
				glDisableClientState(GL_VERTEX_ARRAY);
			}
		}
		// Drawing wires
		if (display_wire){
#ifndef INTEGRATOR_SEI
			double radius = 0;
			struct particle com = particles[0];
			for (int i=1;i<N;i++){
				struct particle p = particles[i];
				if (N_active>0){
					// Different colors for active/test particles
					if (i>=N_active){
						glColor4f(0.9,1.0,0.9,0.9);
					}else{
						glColor4f(1.0,0.9,0.0,0.9);
					}
				}else{
					// Alternating colors
					if (i%2 == 1){
						glColor4f(0.0,1.0,0.0,0.9);
					}else{
						glColor4f(0.0,0.0,1.0,0.9);
					}
				}
				struct orbit o = tools_p2orbit(p,com);
				glPushMatrix();
				
				glTranslatef(com.x,com.y,com.z);
				glRotatef(o.Omega/DEG2RAD,0,0,1);
				glRotatef(o.inc/DEG2RAD,1,0,0);
				glRotatef(o.omega/DEG2RAD,0,0,1);
				
				glBegin(GL_LINE_LOOP);
				for (double trueAnom=0; trueAnom < 2.*M_PI; trueAnom+=M_PI/100.) {
					//convert degrees into radians
					radius = o.a * (1. - o.e*o.e) / (1. + o.e*cos(trueAnom));
					glVertex3f(radius*cos(trueAnom),radius*sin(trueAnom),0);
				}
				glEnd();
				glPopMatrix();
				com = tools_get_center_of_mass(p,com);
			}
#else 	// INTEGRATOR_SEI
			for (int i=1;i<N;i++){
				struct particle p = particles[i];
				glBegin(GL_LINE_LOOP);
				for (double _t=-100.*dt;_t<=100.*dt;_t+=20.*dt){
					double frac = 1.-fabs(_t/(120.*dt));
					glColor4f(1.0,(_t+100.*dt)/(200.*dt),0.0,frac);
					glVertex3f(p.x+p.vx*_t, p.y+p.vy*_t, p.z+p.vz*_t);
				}
				glEnd();
			}

#endif 	// INTEGRATOR_SEI
		}
		// Drawing Tree
		glColor4f(1.0,0.0,0.0,0.4);
#ifdef TREE
		if (display_tree){
			glColor4f(1.0,0.0,0.0,0.4);
			display_entire_tree();
		}
#endif // TREE
		glTranslatef(-gb.shiftx,-gb.shifty,-gb.shiftz);
	}
	}
	}
	glColor4f(1.0,0.0,0.0,0.4);
	glScalef(boxsize_x,boxsize_y,boxsize_z);
	glutWireCube(1);
	glScalef(1./boxsize_x,1./boxsize_y,1./boxsize_z);
	glRotatef(-display_rotate_z,0,0,1);
	glRotatef(-display_rotate_x,1,0,0);
	if (display_reference>=0){
		glTranslatef(particles[display_reference].x,particles[display_reference].y,particles[display_reference].z);
	}
	glutSwapBuffers();
}
示例#6
0
文件: main.c 项目: Davier/WildForest
int main()
{
    // Ressources
    unsigned long t_debut, t_fin;
    float dt, waitShoot = 0;
    BITMAP *buffer;
    int fin = 0, v = 200;
    Map *map;
    DepthList *depthList;
    Rect screen_pos, map_pos;
    Actor *joueur;

    // Initialisation
    fprintf(stderr,"Initialisation ...\n");
    timeBeginPeriod(1);
    set_uformat(U_ASCII);
    set_color_depth(32);
    allegro_init();
    install_keyboard();
    install_mouse();
    srand(time(NULL));

    if(set_gfx_mode(GFX_AUTODETECT_WINDOWED, 1024, 768, 0, 0))
        ERREUR("Echec du lancement du mode graphique.");
    buffer = create_bitmap(SCREEN_W, SCREEN_H);
    resman_loadSprites();

    fprintf(stderr,"Chargement des ressources ...\n");
    map = new_map("media/map/test1");
    map_pos.x = map_pos.y = 0;
    map_pos.w = map->w;
    map_pos.h = map->h;
    actList = new_glist();
    root = new_tree(map_pos);
    map_addEntities(map, actList, root);
    depthList = new_dlist();
    screen_pos.w = SCREEN_W;
    screen_pos.h = SCREEN_H;

    // Ajout du joueur
    joueur = actor_addJoueur(actList, root, 500, 500);

    // Intro
    debut();

    // Boucle principale
    fprintf(stderr,"Debut !\n");
    t_debut = timeGetTime();
    while(!fin)
    {
        // Gestion clavier
        if(key[KEY_ESC])
        {
            fin = 1;
        }
        if(key[KEY_W])
        {
            joueur->vit_y = -v;
            joueur->direction_regard = HAUT;
            joueur->etat = ETAT_MARCHE;
        }
        else if(key[KEY_S])
        {
            joueur->vit_y = v;
            joueur->direction_regard = BAS;
            joueur->etat = ETAT_MARCHE;
        }
        else
            joueur->vit_y = 0;
        if(key[KEY_A])
        {
            joueur->vit_x = -v;
            joueur->direction_regard = GAUCHE;
            joueur->etat = ETAT_MARCHE;
        }
        else if(key[KEY_D])
        {
            joueur->vit_x = v;
            joueur->direction_regard = DROITE;
            joueur->etat = ETAT_MARCHE;
        }
        else
            joueur->vit_x = 0;
        if(joueur->vit_x != 0 && joueur->vit_y != 0)
        {
            joueur->vit_x /= sqrt(2);
            joueur->vit_y /= sqrt(2);
        }
        if(!key[KEY_W] && !key[KEY_D] && !key[KEY_S] && !key[KEY_A])
            joueur->etat = ETAT_REPOS;
        if(key[KEY_Q])
        {
            if(waitShoot <= 0)
            {
                waitShoot = .1;
                actor_addTree(actList, root, mouse_x + screen_pos.x, mouse_y + screen_pos.y);
            }
        }
        waitShoot -= dt;
        if(mouse_b&1)
        {
            float vx, vy, v;
            if(waitShoot <= 0)
            {
                waitShoot = .3;
                vx = mouse_x - (joueur->pos_x - screen_pos.x);
                vy = mouse_y - (joueur->pos_y - screen_pos.y);
                v = sqrt(vx*vx + vy*vy);
                vx = vx/v;
                vy = vy/v;
                actor_addMissile(actList, root, joueur->pos_x + vx*joueur->w*1.5, joueur->pos_y + vy*joueur->h*1.5, vx*300, vy*300);
            }
        }
        if(key[KEY_P])
        {
            FILE *fd = fopen("arbres.txt", "w+");
            Actor *act;
            glist_startIter(actList);
            while(!glist_endIter(actList))
            {
                act = glist_getCurrentData(actList);
                if(act->type == ACT_TREE)
                    fprintf(fd, "%d\n%d\n", (int) act->pos_x, (int) act->pos_y);
                glist_iter(actList);
            }
            fclose(fd);
        }


        // Double buffer
        clear_bitmap(buffer);
        render_map(buffer, map, screen_pos.x, screen_pos.y);


        // Mises à jour
        resman_updateSprites(&dt);
        actor_spawnMonster(actList, root);
        actor_ia(actList, joueur);
        // Deplacement
        glist_startIter(actList);
        while(!glist_endIter(actList))
        {
            actor_update(glist_getCurrentData(actList), map_pos, map, dt);
            if( ((Actor*) glist_getCurrentData(actList))->deleting)
            {
                glist_remCell(actList, glist_getCurrentId(actList));
            }
            else
                glist_iter(actList);
        }
        // Cadrage ecran
        screen_pos.x = joueur->pos_x - SCREEN_W/2;
        screen_pos.y = joueur->pos_y - SCREEN_H/2;

        // Collision
        tree_collisionDetection(root);

        // Affichage
        tree_update(root);
        dlist_getActorsFromTree(depthList, root, screen_pos);
        dlist_update(depthList, screen_pos);
        dlist_blit(depthList, buffer, screen_pos);
        draw_cursor(buffer);
        textprintf_centre_ex(buffer, font, SCREEN_W/2, 5, makecol(0, 0, 0), makecol(255, 0, 0), "   Vies restantes : %d   |   Score : %d   ", joueur->vie, score);

        // Rafraichissement écran
        vsync();
        blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);

        // Gestion du temps
        t_fin = timeGetTime();
        dt = ((float)t_fin - t_debut)/1000;
        t_debut = t_fin;

        // Test fin de jeu
        if(joueur->deleting)
            fin = 1;
        resman_freeList();
    }
    // Game over
    gameover();

    // Fin
    timeEndPeriod(1);
    delete_map(map);
    del_tree(root);
    del_dlist(depthList);
    del_glist(actList);
    destroy_bitmap(buffer);
    resman_freeSprites();
    allegro_exit();
    return 0;
}