Esempio n. 1
0
void Raytracer::forwardTrace(Photon* photon, const int bouncesLeft, const int numberOfPhotons) 
{
	if (bouncesLeft > 0)
	{
		Tri::Intersector intersector;
		float distance = inf();
		Ray photonRay(photon->position, photon->direction);

		if (_triTree.intersectRay(photonRay, intersector, distance))
		{
			Color3 pixelColor;
			Vector3 position, normal;
			Vector2 texCoord;
			intersector.getResult(position, normal, texCoord);
			photon->position = position + normal * 0.0001f;

			Photon* photonCopy = new Photon(photon);
			//if (bouncesLeft != _settings._forwardBounces)
			{
				_photonMap->insert(photon);
			}

			SurfaceSample surfaceSample(intersector);
			if (scatter(intersector, photonCopy))
			{
				forwardTrace(photonCopy, bouncesLeft - 1, numberOfPhotons);
			}
		}
	}
}
Esempio n. 2
0
/**
 * Place 'num' sleeping monsters near (x, y).
 * \param c the current chunk
 * \param y1 co-ordinates to place the monsters near
 * \param x1 co-ordinates to place the monsters near
 * \param depth generation depth
 * \param num number of monsters to place
 */
void vault_monsters(struct chunk *c, int y1, int x1, int depth, int num)
{
    int k, i, y, x;

	/* If the starting location is illegal, don't even start */
	if (!square_in_bounds(c, y1, x1)) return;

    /* Try to summon "num" monsters "near" the given location */
    for (k = 0; k < num; k++) {
		/* Try nine locations */
		for (i = 0; i < 9; i++) {
			int d = 1;

			/* Pick a nearby location */
			scatter(c, &y, &x, y1, x1, d, true);

			/* Require "empty" floor grids */
			if (!square_isempty(c, y, x)) continue;

			/* Place the monster (allow groups) */
			pick_and_place_monster(c, y, x, depth, true, true,
								   ORIGIN_DROP_SPECIAL);

			break;
		}
    }
}
Esempio n. 3
0
void
Stokhos::SmolyakPseudoSpectralOperator<ordinal_type,value_type,point_compare_type>::
transformPCE2QP_smolyak(
  const value_type& alpha, 
  const Teuchos::SerialDenseMatrix<ordinal_type,value_type>& input,
  Teuchos::SerialDenseMatrix<ordinal_type,value_type>& result, 
  const value_type& beta,
  bool trans) const {
  Teuchos::SerialDenseMatrix<ordinal_type,value_type> op_input, op_result;
  result.scale(beta);

  for (ordinal_type i=0; i<operators.size(); i++) {
    Teuchos::RCP<operator_type> op = operators[i];
    if (trans) {
      op_input.reshape(input.numRows(), op->coeff_size());
      op_result.reshape(result.numRows(), op->point_size());
    }
    else {
      op_input.reshape(op->coeff_size(), input.numCols());
      op_result.reshape(op->point_size(), result.numCols());
    }
    
    gather(scatter_maps[i], input, trans, op_input);
    op->transformPCE2QP(smolyak_coeffs[i], op_input, op_result, 0.0, trans);
    scatter(gather_maps[i], op_result, trans, result);
  }
}
Esempio n. 4
0
/*
 * Summon a creature of the specified type
 *
 * This function is rather dangerous XXX XXX XXX
 */
static void do_cmd_wiz_named(int r_idx, bool slp)
{
	int py = p_ptr->py;
	int px = p_ptr->px;

	int i, x, y;

	/* Paranoia */
	if (!r_idx) return;
	if (r_idx >= z_info->r_max-1) return;

	/* Try 10 times */
	for (i = 0; i < 10; i++) {
		int d = 1;

		/* Pick a location */
		scatter(&y, &x, py, px, d, 0);

		/* Require empty grids */
		if (!cave_empty_bold(y, x)) continue;

		/* Place it (allow groups) */
		if (place_new_monster(cave, y, x, r_idx, slp, TRUE, ORIGIN_DROP_WIZARD)) break;
	}
}
/* intersection filter function */
void intersectionFilterN(int* valid,
                                  void* ptr,
                                  const RTCIntersectContext* context,
                                  RTCRayN* ray,
                                  const RTCHitN* potentialHit,
                                  const size_t N)
{
  /* avoid crashing when debug visualizations are used */
  if (context == nullptr)
    return;

  /* iterate over all rays in ray packet */
  for (unsigned int ui=0; ui<N; ui+=1)
  {
    /* calculate loop and execution mask */
    unsigned int vi = ui+0;
    if (vi>=N) continue;

    /* ignore inactive rays */
    if (valid[vi] != -1) continue;

    /* read ray from ray structure */
    Vec3fa ray_org = Vec3fa(RTCRayN_org_x(ray,N,ui),RTCRayN_org_y(ray,N,ui),RTCRayN_org_z(ray,N,ui));
    Vec3fa ray_dir = Vec3fa(RTCRayN_dir_x(ray,N,ui),RTCRayN_dir_y(ray,N,ui),RTCRayN_dir_z(ray,N,ui));
    unsigned ray_mask = RTCRayN_mask(ray,N,ui);
    float hit_t = RTCHitN_t(potentialHit,N,ui);

    /* decode ray IDs */
    int pid = (ray_mask & 0xFFFF) / 1;
    int rid = (ray_mask & 0xFFFF) % 1;

    /* calculate transparency */
    Vec3fa h = ray_org + ray_dir*hit_t;
    float T = transparencyFunction(h);

    /* ignore hit if completely transparent */
    if (T >= 1.0f) valid[vi] = 0;

    /* otherwise accept hit and remember transparency */
    else
    {
      RTCRayN_instID(ray,N,ui) = RTCHitN_instID(potentialHit,N,ui);
      RTCRayN_geomID(ray,N,ui) = RTCHitN_geomID(potentialHit,N,ui);
      RTCRayN_primID(ray,N,ui) = RTCHitN_primID(potentialHit,N,ui);

      RTCRayN_u(ray,N,ui) = RTCHitN_u(potentialHit,N,ui);
      RTCRayN_v(ray,N,ui) = RTCHitN_v(potentialHit,N,ui);
      RTCRayN_tfar(ray,N,ui) = RTCHitN_t(potentialHit,N,ui);

      RTCRayN_Ng_x(ray,N,ui) = RTCHitN_Ng_x(potentialHit,N,ui);
      RTCRayN_Ng_y(ray,N,ui) = RTCHitN_Ng_y(potentialHit,N,ui);
      RTCRayN_Ng_z(ray,N,ui) = RTCHitN_Ng_z(potentialHit,N,ui);

      if (context) {
        RTCRay2* eray = (RTCRay2*) context->userRayExt;
        scatter(eray->transparency,sizeof(RTCRay2),pid,rid,T);
      }
    }
  }
}
Esempio n. 6
0
/*
 * Hack -- Place some sleeping monsters near the given location
 */
void vault_monsters(int y1, int x1, int num)
{
    int k, i, y, x;
    cave_type *c_ptr;

    /* Try to summon "num" monsters "near" the given location */
    for (k = 0; k < num; k++)
    {
        /* Try nine locations */
        for (i = 0; i < 9; i++)
        {
            int d = 1;

            /* Pick a nearby location */
            scatter(&y, &x, y1, x1, d, 0);

            /* Require "empty" floor grids */
            c_ptr = &cave[y][x];
            if (!cave_empty_grid(c_ptr)) continue;

            /* Place the monster (allow groups) */
            monster_level = base_level + 2;
            (void)place_monster(y, x, (PM_ALLOW_SLEEP | PM_ALLOW_GROUP));
            monster_level = base_level;
        }
    }
}
Esempio n. 7
0
/**
 * Lets the given monster attempt to reproduce.
 *
 * Note that "reproduction" REQUIRES empty space.
 *
 * Returns true if the monster successfully reproduced.
 */
bool multiply_monster(const struct monster *mon)
{
	int i, y, x;

	bool result = false;

	/* Try up to 18 times */
	for (i = 0; i < 18; i++) {
		int d = 1;

		/* Pick a location */
		scatter(cave, &y, &x, mon->fy, mon->fx, d, true);

		/* Require an "empty" floor grid */
		if (!square_isempty(cave, y, x)) continue;

		/* Create a new monster (awake, no groups) */
		result = place_new_monster(cave, y, x, mon->race, false, false,
			ORIGIN_DROP_BREED);

		/* Done */
		break;
	}

	/* Result */
	return (result);
}
Esempio n. 8
0
/*
 * Summon a creature of the specified type
 *
 * XXX XXX XXX This function is rather dangerous
 */
static void do_cmd_wiz_named(int r_idx, bool slp)
{
	int py = p_ptr->py;
	int px = p_ptr->px;

	int i, x, y;

	cave_type *c_ptr;

	/* Paranoia */
	/* if (!r_idx) return; */

	/* Prevent illegal monsters */
	if (r_idx >= max_r_idx) return;

	/* Try 10 times */
	for (i = 0; i < 10; i++)
	{
		int d = 1;

		/* Pick a location */
		scatter(&y, &x, py, px, d);

		/* paranoia */
		if (!in_bounds2(y, x)) continue;

		/* Require empty grids */
		c_ptr = area(y, x);
		if (!cave_empty_grid(c_ptr)) continue;

		/* Place it (allow groups) */
		if (place_monster_aux(y, x, r_idx, slp, TRUE, FALSE, FALSE)) break;
	}
}
Esempio n. 9
0
/**
 * Summon a creature of the specified type
 *
 * This function is rather dangerous XXX XXX XXX
 */
static void do_cmd_wiz_named(int r_idx, bool slp)
{
	monster_race *r_ptr = &r_info[r_idx];

	int py = p_ptr->py;
	int px = p_ptr->px;

	int i, x, y;

	/* Paranoia */
	if (!r_idx)
		return;
	if (r_idx >= z_info->r_max)
		return;

	/* Try 10 times */
	for (i = 0; i < 10; i++) {
		int d = 1;

		/* Pick a location */
		scatter(&y, &x, py, px, d, 0);

		/* Require grids that the monster can exist in */
		if (!cave_exist_mon(r_ptr, y, x, FALSE))
			continue;

		/* Place it (allow groups) */
		if (place_monster_aux(y, x, r_idx, slp, TRUE))
			break;
	}
}
Esempio n. 10
0
/**
 * Creates magical stairs after finishing a quest monster.
 */
static void build_quest_stairs(int y, int x)
{
	int ny, nx;

	/* Stagger around */
	while (!cave_valid_bold(y, x)) {
		int d = 1;

		/* Pick a location */
		scatter(&ny, &nx, y, x, d, FALSE);

		/* Stagger */
		y = ny; x = nx;
	}

	/* Destroy any objects */
	delete_object(y, x);

	/* Explain the staircase */
	msg("A magical staircase appears...");

	/* Create stairs down */
	/* XXX: fake depth = 0 to always produce downstairs */
	cave_add_stairs(cave, y, x, 0);

	/* Update the visuals */
	p_ptr->update |= (PU_UPDATE_VIEW | PU_MONSTERS);

	/* Fully update the flow */
	p_ptr->update |= (PU_FORGET_FLOW | PU_UPDATE_FLOW);
}
Esempio n. 11
0
Color Tracer::traceLocation(double dx, double dy) const
{
	Ray ray( Vector( 0.0, 0.0, 1.0 ), Vector( dx, dy, -1.0 ).normalized() );

	Path path;

	while( !path.isFull() )
	{
		IntersectDescr node = intersect( ray );

		if( node.isValid() )
		{
			path.addNode( node );
			if( !scatter( node, ray ) )
			{
				break;
			}
		}
		else
		{
			// nothing hit, so we quit
			break;
		}
	}

	return path.integrate();
}
Esempio n. 12
0
/* Summon a horde of monsters */
static void do_cmd_summon_horde(void)
{
	int px = p_ptr->px;
	int py = p_ptr->py;

	int wy = py, wx = px;
	int attempts = 1000;
	cave_type *c_ptr;


	while (--attempts)
	{
		scatter(&wy, &wx, py, px, 3);

		/* paranoia */
		if (!in_bounds2(wy, wx)) continue;

		c_ptr = area(wy, wx);
		if (cave_naked_grid(c_ptr)) break;

		/* Not under the player */
		if ((wy == py) && (wx == px)) break;
	}

	(void)alloc_horde(wy, wx);
}
Esempio n. 13
0
/*
 * Create magical stairs after finishing a quest monster.
 */
static void build_quest_stairs(int y, int x)
{
	int ny, nx;

	/* Stagger around */
	while (!cave_clean_bold(y, x))
	{

		/* Pick a location */
		scatter(&ny, &nx, y, x, 5, 1);

		/* Stagger */
		y = ny; x = nx;
	}

	/* Destroy any objects */
	delete_object(y, x);

	/* Explain the staircase */
	msg_print("A magical staircase appears...");

	/* Create stairs down */
	cave_set_feat(y, x, FEAT_MORE);

	light_spot(y, x);

	/* Update the visuals */
	p_ptr->update |= (PU_UPDATE_VIEW | PU_MONSTERS);

}
Esempio n. 14
0
/**
 * Creates magical stairs after finishing a quest monster.
 */
static void build_quest_stairs(int y, int x)
{
	int ny, nx;

	/* Stagger around */
	while (!square_changeable(cave, y, x) && !square_iswall(cave, y, x) &&
		   !square_isdoor(cave, y, x)) {
		/* Pick a location */
		scatter(cave, &ny, &nx, y, x, 1, FALSE);

		/* Stagger */
		y = ny; x = nx;
	}

	/* Push any objects */
	push_object(y, x);

	/* Explain the staircase */
	msg("A magical staircase appears...");

	/* Create stairs down */
	square_set_feat(cave, y, x, FEAT_MORE);

	/* Update the visuals */
	player->upkeep->update |= (PU_UPDATE_VIEW | PU_MONSTERS);

	/* Fully update the flow */
	player->upkeep->update |= (PU_FORGET_FLOW | PU_UPDATE_FLOW);
}
Esempio n. 15
0
/** 
 * Helper function to place monsters that appear as friends or escorts
 */
 bool place_friends(struct cave *c, int y, int x, monster_race *race, 
		monster_race *friends_race, int total, bool sleep, byte origin)
 {
	int level_difference, extra_chance, nx, ny;
	bool is_unique, success = TRUE;
	
	/* Find the difference between current dungeon depth and monster level */
	level_difference = p_ptr->depth - friends_race->level + 5;
	
	/* Handle unique monsters */
	is_unique = rf_has(friends_race->flags, RF_UNIQUE);
	
	/* Make sure the unique hasn't been killed already */
	if (is_unique){
		total = friends_race->cur_num < friends_race->max_num ? 1 : 0;
	}
	
	/* More than 4 levels OoD, no groups allowed */
	if (level_difference <= 0 && !is_unique){
		return FALSE;
	}
	
	/* Reduce group size within 5 levels of natural depth*/
	if (level_difference < 10 && !is_unique){
		extra_chance = (total * level_difference) % 10;
		total = total * level_difference / 10;
		
		/* Instead of flooring the group value, we use the decimal place
		   as a chance of an extra monster */
		if (randint0(10) > extra_chance){
			total += 1;
		}
	}
	
	/* No monsters in this group */
	if (total <= 0){
		return FALSE;
	}
	
	/* Handle friends same as original monster */
	if (race->ridx == friends_race->ridx){
		place_new_monster_group(c, y, x, race, sleep, total, origin);
	}
	
	/* Find a nearby place to put the other groups */
	for (int j = 0; j < 50; j++){
		scatter(&ny, &nx, y, x, GROUP_DISTANCE, FALSE);
		if (cave_isopen(cave, ny, nx)) break;
	}
		
	/* Place the monsters */
	success = place_new_monster_one(ny, nx, friends_race, sleep, origin);
	if (total > 1){
		success = place_new_monster_group(c, ny, nx, friends_race, sleep, total, origin);
	}
	
	return success;
	
}
Esempio n. 16
0
void
flushBuffer(int tag,
		std::vector<T>& input,
		std::vector< std::vector<T> >& output,
		boost::mpi::communicator& world)
{
	broadcast(world, tag, MASTER);
	scatter(world, output, input, MASTER);
	for(typename std::vector< std::vector<T> >::iterator i = output.begin(); i != output.end(); ++i) {
		i->clear();
	}
}
Esempio n. 17
0
/*!
 * @brief ウィザードモード用モンスターの群れ生成 / Summon a horde of monsters
 * @return なし
 */
static void do_cmd_summon_horde(void)
{
	int wy = p_ptr->y, wx = p_ptr->x;
	int attempts = 1000;

	while (--attempts)
	{
		scatter(&wy, &wx, p_ptr->y, p_ptr->x, 3, 0);
		if (cave_empty_bold(wy, wx)) break;
	}

	(void)alloc_horde(wy, wx);
}
Esempio n. 18
0
int main(int argc, char **argv){

    if(data_size * 8 > 4096){
        coarray_init(2*4*data_size, argc, argv);
    } else {
        coarray_init(4096,argc, argv);
    }

    local_array<int> gather_result(num_images() * data_size);
    coarray<int, 1> source(dims{data_size});//parenthesis do not work here
    coarray<int, 1> scatter_result(dims{data_size});

    for( int i = 0; i < data_size; i++ ) {
        source[i] = data_size * this_image() + i;
    }
    print(source);

    gather(gather_result, source);

    if(this_image() == 0) {
        cout << "Gather result:" << endl;
        for(int i = 0; i < num_images() * data_size; i++) {
            cout << gather_result[i] << ", ";
            gather_result[i]++;// = gather_result[i] + 1;
        }
        cout << endl;

        scatter(gather_result, scatter_result);

    }
    sync_all();
    for(int i = 0; i < num_images(); i++) {
        if(this_image() != i) {
            cout << "scatter result(" << this_image() << "): ";
            for(int i = 0; i < data_size; i++)
                cout << scatter_result[i] << ", ";
            cout << endl;
        }
    }

    sync_all();

    if(this_image() == 0) {
        collect(gather_result, scatter_result);
        cout << "collect result:" << endl;
        for(int i = 0; i < data_size; i++)
            cout << scatter_result[i] << ", ";
        cout << endl;
    }
}
Esempio n. 19
0
int main(int argc, char *argv[]){    
	const int tmax=atoi(argv[1]); /* number of simulation rounds */
	const int gran=atoi(argv[2]); /* granularity */
	const char *pName=argv[3]; /* bodies file name */
	double time, time1, time2, time3; /* total, scatter, simulate, and gather running times */ 
	int rank, size; /* rank of process, number of processes */
	
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &size);

	body *bodies = (body *) malloc(gran*sizeof(body));

	time = MPI_Wtime();
	/****************************************************************
	1. Scatter:
	Reading the input from file and assigning each line to a process
	****************************************************************/
	time1 = MPI_Wtime();
	scatter(pName, rank, size, gran, bodies);
	time1 = MPI_Wtime() - time1;
	if(rank==0) printf("Scatter time is %.4f seconds\n", time1);	
	/****************************************************************
	2. Simulate:
	Passing the data of each process to other processes and simulate
	****************************************************************/
	time2 = MPI_Wtime();
	simulate(tmax, rank, size, gran, bodies);
	time2 = MPI_Wtime() - time2;
	if(rank==0) printf("Simulate time is %.4f seconds\n", time2);	
	/****************************************************************
	3. Gather:
	Writing the the last positions to "peval_out.txt" 
	****************************************************************/
	time3 = MPI_Wtime();
	gather(rank, size, gran, bodies);
	time3 = MPI_Wtime() - time3;
	if(rank==0) printf("Gather time is %.4f seconds\n", time3);	
	
	/* Finalizing */
	free(bodies);
	time = MPI_Wtime() - time;
	if(rank==0) printf("Computation time is %.4f seconds\n", time);	
	MPI_Finalize();
	return(0);
}
Esempio n. 20
0
void Ghost::move()
{
    if(isInsideGhostHouse())
    {
        if(isFree())
        {
            if(!isCaught())
            {
                release();
            }
        }
    }
    else if(isOnTheMove()) localMove();
    else if(isCaught()) goHome();
    else if(areGhostsScared()) escape();
    else if(isScattering()) scatter();
    else chase();
}
Esempio n. 21
0
/* Function to be called recursively to calculate contributions from
   scattering up to order "norder" */
static
int
scatter(int n, int start_gate, int order, int norder, int output_dist,
	const ms_real *range,
	areal energy, areal width2, areal zeta2, areal cov,
	const areal *fs_fraction, const areal *theta2, 
	const ms_real *rho2range2, areal *bscat_ratio_out) {
  areal start_factor = 0.5;
  int i;
  
  for (i = start_gate; i < n; i++) {
    ms_real range_diff = fabs(range[i] - range[start_gate]);
    areal width2i = width2 + 2.0*cov*range_diff
      + zeta2*range_diff*range_diff;
    /* Add backscatter contribution */
    areal bscat_contrib = energy*start_factor
      *(1.0-exp(-rho2range2[i]/width2i));
    bscat_ratio_out[i] += bscat_contrib;
    /*
    if (order == 2) {
      ms_bscat_double[i] += bscat_contrib;
    }
    else {
      ms_bscat_multi[i] += bscat_contrib;
    }
    if (output_dist && i == n-1) {
      ms_increment_distribution(order, i, energy*start_factor, width2i);
    }
    */

    if (order < norder) {
      scatter(n, i, order+1, norder, output_dist, range,
	      energy*start_factor*fs_fraction[i], /* New energy */
	      width2i, /* New positional variance */
	      zeta2+theta2[i], /* New angular variance */
	      cov+zeta2*range_diff, /* New covariance */
	      fs_fraction, theta2, rho2range2, bscat_ratio_out);
    }
    start_factor = 1.0;
  }
  
  return MS_SUCCESS;
}
void actualSort( const TestInfo *ti, Data *data )
{
	PhaseHandle sortingP, sequentialSortP;
	srand( time(0) );
	
	// init phase "computation
	computationP = startPhase( ti, "computation" );
	stopPhase( ti, computationP );

	sortingP = startPhase( ti, "sorting" );
		scatter( ti, data ); // scattering

		resumePhase( ti, computationP );
			sequentialSortP = startPhase( ti, "sequential sort" );
			sequentialSort( ti, data );
			stopPhase( ti, sequentialSortP );
		stopPhase( ti, computationP );
	stopPhase( ti, sortingP );

	gather( ti, data ); // gathering
}
Esempio n. 23
0
int main(int argc, char *argv[]) {

    int board[N][N];
    int x = 0, y = 0;
    char user; 


    srand(time(NULL));

    erase(board);
    scatter(N * N / 5, board);

    do {
	show(board, x, y, 60, 30);
	scanf(" %c", &user);
	user = tolower(user);

	switch(user){
	    case 'w':
		if (y<N-1)
		    y++;
		break;
	    case 'a':
		if (x>0)
		    x--;
		break;
	    case 's':
		if (y>0)
		    y--;
		break;
	    case 'd':
		if (x<N-1)
		    x++;
		break;
	}
    } while (user != 'q');


    return EXIT_SUCCESS;
}
Esempio n. 24
0
/*
 * Summon a creature of the specified type
 *
 * This function is rather dangerous XXX XXX XXX
 */
static void do_cmd_wiz_named(monster_race *r, bool slp)
{
	int py = p_ptr->py;
	int px = p_ptr->px;

	int i, x, y;

	/* Paranoia */
	assert(r);

	/* Try 10 times */
	for (i = 0; i < 10; i++) {
		int d = 1;

		/* Pick a location */
		scatter(&y, &x, py, px, d, TRUE);

		/* Require empty grids */
		if (!cave_isempty(cave, y, x)) continue;

		/* Place it (allow groups) */
		if (place_new_monster(cave, y, x, r, slp, TRUE, ORIGIN_DROP_WIZARD)) break;
	}
}
Esempio n. 25
0
 // ******************
 template <class Type> void MyVector<Type>::scatter() {
   buildOffset();
   scatter(_offset);
 }
Esempio n. 26
0
//--------------|-------|-------------------------------------
void
rsort(RSREC ** recv, int nrecs)
{
    int i, k = 256, maxleng = 0;
    int *lengv = calloc(k, sizeof(*lengv));

    for (i = 0; i < nrecs; ++i) {
        int leng = KEYLENG(recv[i]);
        if (leng >= k) {
            int kk = k;
            while (kk <= leng)
                kk <<= 1;
            lengv = realloc(lengv, kk * sizeof(int));
            memset(lengv + k, 0, (kk - k) * sizeof(int));
            k = kk;
        }

        ++lengv[leng];
        if (maxleng < leng)
            maxleng = leng;
    }

    DIAG_NRECS(nrecs);

    if (maxleng == 0) {         // edge case: empty input 
        free(lengv);
        return;
    }

    int pos = 0, nsrcs = 1, skip;
    PART *pdata = malloc((nrecs + 1) * sizeof(PART));
    PARTNO *partv = malloc(MAXPARTS * sizeof(*partv));
    int rsize = ((nrecs - 1) / MINRANGE + 1) * sizeof(RANGE);
    RANGE *srcv = malloc(rsize);
    RANGE *dstv = malloc(rsize);
    PARTNO *mapv[maxleng + 1];
    PARTNO mdata[MAXMAPS][256];

    for (i = 0; i <= maxleng; ++i)
        mapv[i] = 0;
    for (i = 1; i < MAXMAPS; ++i)
        *mdata[i] = UNUSED;

    // mdata[0] is permanently all 0. It is used to "map"
    //        bytes in the middle of the range (pos;len) that
    //        have exactly one value.
    memset(mdata[0], 0, sizeof(mdata[0]));

    // pdata[0]: a dummy list terminator; simplifies a loop 
    pdata[0] = (PART) { 0, NULL, NULL};

    // Initial srcv: a single range of the entire input 
    srcv[0] = (RANGE) {recv, recv + nrecs};
    for (pos = 0; nsrcs; pos += skip) {
        int len, nparts;

        DIAG_TICK(t1);
        nparts = analyze(maxleng, lengv, nsrcs, srcv,
                         mapv, mdata, &pos, &skip, &len);
        DIAG_TICK(t2);

        // Initialize partv[] to the index of dummy pdata[0]. 
        for (i = 0; i < nparts; ++i)
            partv[i] = 0;

        scatter(nsrcs, srcv, pos, len, mapv, partv, pdata);

        for (i = 0; i < len; ++i)
            *mapv[pos + i] = UNUSED;
        mdata[0][0] = 0;        // Undo "freeing" of mdata[0] 
#if DIAG
        int maxpart = -1;
        for (i = k = 0; i < nparts; ++i) {
            k += !!partv[i];
            if (partv[i]) maxpart = i;
        }
        fprintf(stderr, "# %9d recs %5d rngs on"
                " %d:%d%s %d/%d parts max=%d",
                _nrecs, nsrcs, pos, pos + len - 1,
                len == skip ? "" : "+", k, nparts, maxpart);
        DIAG_TICK(t3);
        DIAG_NRECS(0);          // updated by gather() 
#endif
        nsrcs = gather(pos + skip, nparts, partv, pdata, dstv);
#if DIAG
        fprintf(stderr, "\t%.3f %.3f %.3f secs\n",
                t2 - t1, t3 - t2, tick() - t3);
#endif
        RANGE *tmp = srcv;
        srcv = dstv;
        dstv = tmp;
    }

    free(dstv);
    free(srcv);
    free(partv);
    free(pdata);
    free(lengv);
}
ProcForestPatch::ProcForestPatch(std::string& name, Ogre::SceneManager* sceneMgr, GrowingSurface* surface, TreeParameters& min_params, TreeParameters& max_params, unsigned int density)
:mSceneMgr(sceneMgr),mSurface(surface), mName(name),mDensity(density), mMinParams(min_params) , mMaxParams(max_params)	
{
	scatter(SCATTERMETHOD::GRID);
}
Esempio n. 28
0
int main(){

  scatter();

  cout << "Gaussian " << gauss_rand() << endl;

  ALMcl core;
  core.init(10,"landmarks.dat");
  
  drovector pos_(4);
  pos_.zero();
  
  cout << "landmark 0 " <<  core.vision_simulator(pos_,rovec_read(core.landmarks,0)) <<endl;
  cout << "landmark 1 " <<  core.vision_simulator(pos_,rovec_read(core.landmarks,1)) <<endl;
  cout << "landmark 2 " <<  core.vision_simulator(pos_,rovec_read(core.landmarks,2)) <<endl;
  cout << "landmark 3 " <<  core.vision_simulator(pos_,rovec_read(core.landmarks,3)) <<endl;


  //ここまでdebug

  	ALMcl engine, sim, pure;//engine = localization engine, sim = real world simulator
	//pure is for simulation excluding noise term
	//	pure.forward_noise = 0;
  	//pure.theta_noise = 0;

	drovector pos(4),purepos(4);
	pos.zero();purepos.zero();

	engine.init(100,"landmarks.dat");

	dgematrix senario;
	senario.read("senario.txt");

	dgematrix logPos(T,4),logPure(T,4),logEst(T,4);
	sim.forward_noise = 1.0;
	sim.theta_noise = 0.1;
	sim.vision_noise = 1.0;

	pure.forward_noise = 0;
	pure.theta_noise = 0;
	pure.vision_noise = 1.0;

	engine.forward_noise = 1.0;
	engine.theta_noise = 0.1;
	engine.vision_noise = 1.0;

       


	cout <<"sim fn " <<  sim.forward_noise << endl;
	cout <<"sim tn " << sim.theta_noise << endl; 

	cout <<"pure fn " <<  pure.forward_noise << endl;
	cout <<"pure tn " << pure.theta_noise << endl; 


	


       
	for(int t=0;t<T;t++){
	  //command and move
	  pos = sim.move(pos,senario(t,0),senario(t,1),1);
	  cout << "pos " << pos << endl; 
	  //pure movement 
	  purepos = pure.move(purepos,senario(t,0),senario(t,1),1);
	  cout << "purepos " << purepos << endl;
	  //	getchar();
	  
	  //obtaining view
	  drovector vision = engine.vision_simulator(pos,rovec_read(engine.landmarks,t%4)); //each time t%4 landmark is observed
	  cout << "landmark " << vision << endl;
	  dgematrix view(0,2);// vec_set(view,0,vision);
	  //updating localization engine
	  engine.update(senario(t,0),senario(t,1),1,view);
	  cout << "updated particles "<< endl <<  engine.X << endl;
	  cout << "updated weight " << endl << engine.w << endl;
	  getchar();//estimated self position
		engine.get_pos();
		
		//loginmg
		vec_set(logPos,t,pos);
		vec_set(logPure,t,purepos);
		vec_set(logEst,t,engine.get_pos());
		
	}
	
  logPos.write("logPos.txt");
  logPure.write("logPure.txt");
  logEst.write("logEst.txt");
  
  return 0;

}
Esempio n. 29
0
/**
 * Places a monster (of the specified "type") near the given
 * location.  Return the siummoned monster's level iff a monster was
 * actually summoned.
 *
 * We will attempt to place the monster up to 10 times before giving up.
 *
 * This function takes the "monster level"
 * of the summoning monster as a parameter, and use that, along with
 * the current dungeon level, to help determine the level of the
 * desired monster.  Note that this is an upper bound, and also
 * tends to "prefer" monsters of that level.  Currently, we use
 * the average of the dungeon and monster levels, and then add
 * five to allow slight increases in monster power.
 *
 * Note that we use the new "monster allocation table" creation code
 * to restrict the "get_mon_num()" function to the set of "legal"
 * monsters, making this function much faster and more reliable.
 *
 * Note that this function may not succeed, though this is very rare.
 */
int summon_specific(int y1, int x1, int lev, int type, bool delay, bool call)
{
	int i, x = 0, y = 0;

	struct monster *mon;
	struct monster_race *race;

	/* Look for a location, allow up to 4 squares away */
	for (i = 0; i < 60; ++i) {
		/* Pick a distance */
		int d = (i / 15) + 1;

		/* Pick a location */
		scatter(cave, &y, &x, y1, x1, d, true);

		/* Require "empty" floor grid */
		if (!square_isempty(cave, y, x)) continue;

		/* No summon on glyphs */
		if (square_iswarded(cave, y, x) || square_isdecoyed(cave, y, x)) {
			continue;
		}

		/* Okay */
		break;
	}

	/* Failure */
	if (i == 60) return (0);

	/* Save the "summon" type */
	summon_specific_type = type;

	/* Use the new calling scheme if requested */
	if (call && (type != summon_name_to_idx("UNIQUE")) &&
		(type != summon_name_to_idx("WRAITH"))) {
		return (call_monster(y, x));
	}

	/* Prepare allocation table */
	get_mon_num_prep(summon_specific_okay);

	/* Pick a monster, using the level calculation */
	race = get_mon_num((player->depth + lev) / 2 + 5);

	/* Prepare allocation table */
	get_mon_num_prep(NULL);

	/* Handle failure */
	if (!race) return (0);

	/* Attempt to place the monster (awake, don't allow groups) */
	if (!place_new_monster(cave, y, x, race, false, false, ORIGIN_DROP_SUMMON))
		return (0);

	/* Success, return the level of the monster */
	mon = square_monster(cave, y, x);

	/* If delay, try to let the player act before the summoned monsters,
	 * including slowing down faster monsters for one turn */
	/* XXX should this now be hold monster for a turn? */
	if (delay) {
		mon->energy = 0;
		if (mon->race->speed > player->state.speed)
			mon_inc_timed(mon, MON_TMD_SLOW, 1,	MON_TMD_FLG_NOMESSAGE, false);
	}

	return (mon->race->level);
}
double radixSort(cl_mem& d_source, int length, PlatInfo info) {
    
    double totalTime = 0;
    
    int blockSize = 47;             //local memory size: 47KB
    int gridSize = 64;
    
    cl_int status;
    int argsNum = 0;

    int bits = 8;                   //each pass sort 8 bits
    int radix = (1<<bits);
    
    uint hisSize = blockSize * gridSize * radix;
    uint isExclusive = 1;
    
    //kernel reading
    char sortPath[100] = PROJECT_ROOT;
    strcat(sortPath, "/Kernels/radixSortKernel.cl");
    std::string sortKerAddr = sortPath;
    
    char countHisSource[100] = "countHis";
    char writeHisSource[100] = "writeHis";
    
    KernelProcessor sortReader(&sortKerAddr,1,info.context);
    
    cl_kernel countHisKernel = sortReader.getKernel(countHisSource);
    cl_kernel writeHisKernel = sortReader.getKernel(writeHisSource);
    
    size_t testLocal[1] = {(size_t)blockSize};
    size_t testGlobal[1] = {(size_t)(blockSize * gridSize)};
    
    struct timeval start, end;
    
    cl_mem d_temp = clCreateBuffer(info.context, CL_MEM_READ_WRITE, sizeof(Record)*length, NULL, &status);
    checkErr(status, ERR_HOST_ALLOCATION);
    cl_mem d_histogram = clCreateBuffer(info.context, CL_MEM_READ_WRITE, sizeof(uint)* hisSize, NULL, &status);
    checkErr(status, ERR_HOST_ALLOCATION);
    cl_mem d_loc = clCreateBuffer(info.context, CL_MEM_READ_WRITE, sizeof(uint)*length, NULL, &status);
    checkErr(status, ERR_HOST_ALLOCATION);
    
    for(uint shiftBits = 0; shiftBits < sizeof(int) * 8; shiftBits += bits) {
        
        isExclusive = 1;        //reset the exclusive
        //data preparation

        argsNum = 0;
        status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(cl_mem), &d_source);
        status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(int), &length);
        status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(cl_mem), &d_histogram);
        status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(ushort)*radix*blockSize, NULL);
        status |= clSetKernelArg(countHisKernel, argsNum++, sizeof(uint), &shiftBits);
        checkErr(status, ERR_SET_ARGUMENTS);
        
#ifdef PRINT_KERNEL
        printExecutingKernel(countHisKernel);
#endif
        gettimeofday(&start, NULL);
        status = clEnqueueNDRangeKernel(info.currentQueue, countHisKernel, 1, 0, testGlobal, testLocal, 0, 0, 0);
        status = clFinish(info.currentQueue);
        gettimeofday(&end, NULL);
        checkErr(status, ERR_EXEC_KERNEL);
        totalTime += diffTime(end, start);
        
        totalTime += scan(d_histogram,hisSize,1,info);
        
        argsNum = 0;
        status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(cl_mem), &d_source);
        status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(uint), &length);
        status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(cl_mem), &d_histogram);
        status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(cl_mem), &d_loc);
        status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(uint)*radix*blockSize, NULL);
        status |= clSetKernelArg(writeHisKernel, argsNum++, sizeof(uint), &shiftBits);
        checkErr(status, ERR_SET_ARGUMENTS);
        
#ifdef PRINT_KERNEL
        printExecutingKernel(writeHisKernel);
#endif
        gettimeofday(&start, NULL);
        status = clEnqueueNDRangeKernel(info.currentQueue, writeHisKernel, 1, 0, testGlobal, testLocal, 0, 0, 0);
        status = clFinish(info.currentQueue);
        gettimeofday(&end, NULL);
        checkErr(status, ERR_EXEC_KERNEL);
        totalTime += diffTime(end, start);
        
        //scatter
        totalTime += scatter(d_source, d_temp, length, d_loc, 512, 32768, info);
        
        //copy the buffer for another loop
        status = clEnqueueCopyBuffer(info.currentQueue, d_temp, d_source, 0, 0, sizeof(Record)*length,0 , 0, 0);
        checkErr(status, ERR_COPY_BUFFER);
    }
    
    status = clReleaseMemObject(d_temp);
    checkErr(status, ERR_RELEASE_MEM);
    status = clReleaseMemObject(d_histogram);
    checkErr(status, ERR_RELEASE_MEM);
    status = clReleaseMemObject(d_loc);
    checkErr(status, ERR_RELEASE_MEM);

    return totalTime;
}