Beispiel #1
0
	BroadphaseDemo(sf::RenderWindow &window) : Demo(window), broadphase(100, 100), mouseObject(sf::Vector2f(50, 50)) {
		// set up our mouse object
		mouseObject.setOrigin(mouseObject.getSize() / 2.0f);
		mouseObject.setOutlineThickness(2);
		mouseObject.setFillColor(sf::Color(0, 200, 0));

		// set up some random rectangles
		for (size_t i = 0; i < 2500; ++i) {
			sf::RectangleShape *object = new sf::RectangleShape(sf::Vector2f(randb(5, 15), randb(5, 15)));
			object->setOrigin(object->getSize() / 2.0f);
			object->setOutlineThickness(2);
			objects.push_back(object);
		}
	}
Beispiel #2
0
int
CA_STEP5_derive_keys(const EAC_CTX *ctx, const BUF_MEM *pub,
                   BUF_MEM **nonce, BUF_MEM **token)
{
    BUF_MEM *r = NULL;
    BUF_MEM *authentication_token = NULL;

    check((ctx && ctx->ca_ctx && ctx->ca_ctx->ka_ctx && nonce && token),
            "Invalid arguments");

    /* Generate nonce  and derive k_mac and k_enc*/
    r = randb(CA_NONCE_SIZE);
    if (!r || !KA_CTX_derive_keys(ctx->ca_ctx->ka_ctx, r, ctx->md_ctx))
        goto err;

    /* Compute authentication token */
    authentication_token = get_authentication_token(ctx->ca_ctx->protocol,
            ctx->ca_ctx->ka_ctx, ctx->bn_ctx, ctx->tr_version,
            pub);
    check(authentication_token, "Failed to compute authentication token");

    *nonce = r;
    *token = authentication_token;

    return 1;

err:
    BUF_MEM_clear_free(r);

    return 0;
}
Beispiel #3
0
BUF_MEM *
ecdh_im_generate_key(const PACE_CTX * ctx, BN_CTX *bn_ctx)
{
    check_return((ctx && ctx->ka_ctx), "Invalid arguments");

    return randb(EVP_CIPHER_key_length(ctx->ka_ctx->cipher));
}
point TargetControl::genTarget(point currentPos, bool directionMatters)
{
	double theta;
	point targetPos;
		
	if(!directionMatters) //Direction not constrained this trial
	{	
		do 
		{
			theta=randb(0,360);
			targetPos=currentPos+point(cos(theta),sin(theta))*spawnDist;
		} 	while(targetPos.mag()>innerRadius);
		return targetPos;
	}
	
	//If direction predetermined, use it
	if (nextDirection>=0) {targetPos=currentPos+point(cos(nextDirection),sin(nextDirection))*spawnDist; nextDirection=-1; return targetPos;} 
	
	//Make sure we haven't bottomed out
	int sum=0;
	for(int k=0;k<directions;k++) 
	{
		sum+=((timesUsed[k]>=minUses)?0:1);
	}
	if (sum==0) minUses++;
	
	//Find the best direction
	double min=std::numeric_limits<double>::infinity();
	int index=-1;
	double mag;
	point bestPos;
	for(int k=0;k<directions;k++)
	{
		targetPos=currentPos+point(cos(direction[k]),sin(direction[k]))*spawnDist;
		mag=targetPos.mag();
		if((mag<min)&&(timesUsed[k]<minUses)&&(mag<innerRadius)) {min=mag; index=k; bestPos=targetPos;}
	}
	if(index != -1)
	{
		timesUsed[index]++;
		return bestPos;
	}
	
	//If no direction can produce a legal target pick randomly among the least used and set up for it
	int m=INT_MAX;
	int i;
	int * shuffle = new int[directions];
	shuffle[0]=directions;
	randperm(shuffle);
	for(int k=0;k<directions;k++)
		if(timesUsed[shuffle[k]]<m) {m=timesUsed[shuffle[k]]; i=shuffle[k];}
	timesUsed[i]++;
	nextDirection=direction[i];
	theta=atan2(currentPos.Y()+spawnDist*sin(direction[i]),currentPos.X()+spawnDist*cos(direction[i]));
	targetPos=currentPos - point(cos(theta),sin(theta))*spawnDist;
	return (targetPos.mag()<=maxRadius)?targetPos:point(0,0); 
}
Beispiel #5
0
int port_from_args(int argc, char const *argv[])
{
    int port;
    if (argc == 1)
    {
        port = randb(MIN_PORT, MAX_PORT);
        return port;
    }
    else if (argc == 2)
    {
        port = atoi(argv[1]);
        if (port < MIN_PORT || port > MAX_PORT)
            return -2;
        else
            return port;

    }
    else
    {
        return -1;
    }
}
Beispiel #6
0
BUF_MEM *
PACE_STEP1_enc_nonce(const EAC_CTX * ctx, const PACE_SEC * pi)
{
    BUF_MEM * enc_nonce = NULL;
    BUF_MEM * key = NULL;

    check((ctx && ctx->pace_ctx && ctx->pace_ctx->ka_ctx &&
                ctx->pace_ctx->ka_ctx->cipher),
            "Invalid arguments");

    key = kdf_pi(pi, NULL, ctx->pace_ctx->ka_ctx, ctx->md_ctx);
    check(key, "Key derivation function failed");

    BUF_MEM_clear_free(ctx->pace_ctx->nonce);
    ctx->pace_ctx->nonce = randb(EVP_CIPHER_block_size(ctx->pace_ctx->ka_ctx->cipher));
    check(ctx->pace_ctx->nonce, "Failed to create nonce");

    enc_nonce = cipher_no_pad(ctx->pace_ctx->ka_ctx, ctx->cipher_ctx, key, ctx->pace_ctx->nonce, 1);

err:
    BUF_MEM_clear_free(key);

    return enc_nonce;
}
Beispiel #7
0
void TrackTube::GetVertexInfo(float segmentLength, float radius, float randomness, int smoothingPasses){
	vinfo = new VertexInfo[TUBESIDES*(NUMTUBESEGMENTS+1)];
	//setup verticies
	//double length = segment->GetLength();
	for (int i = 0; i < NUMTUBESEGMENTS + 1; i++){
		float distanceDownTube = segmentLength*((float)i/NUMTUBESEGMENTS);
		Vector center = Vector(1,0,0)*distanceDownTube;
		Vector v1 = Vector(0,1,0);
		Vector v2 = Vector(0,0,1);
		Vector randomOffset = Vector(0, 0, 0);
		if (i != 0 && i != NUMTUBESEGMENTS && randb(0,1) < randomness){
			//if its not the front or end of the segment add some randomness to look more wormholey
			randomOffset = Vector(randb(-randomness * radius, randomness * radius), 
								  randb(-randomness * radius, randomness * radius), 
								  randb(-randomness * radius, randomness * radius));
		}
		for (int k = 0; k < TUBESIDES; k++){
			vinfo[i*TUBESIDES + k].position = center + radius*(v1*((float)cos(k*2*PI/TUBESIDES)) + v2*((float)sin(k*2*PI/TUBESIDES)));
			vinfo[i*TUBESIDES + k].distance = distanceDownTube;
		}
		int start = (int) randb(0, TUBESIDES);
		int length = (int) randb(0, TUBESIDES);
		for (int k = 0; k < length; k++){
			vinfo[i*TUBESIDES + ((k + start)%TUBESIDES)].position = vinfo[i*TUBESIDES + ((k + start)%TUBESIDES)].position + randomOffset;
		}

	}
	//apply smoothing
	for (int j = 0; j < smoothingPasses; j++){
		Vector * vSmooth = new Vector[TUBESIDES*(NUMTUBESEGMENTS+1)];
		for (int i = 0; i < NUMTUBESEGMENTS + 1; i++){
			for (int k = 0; k < TUBESIDES; k++){
				float prevX = vinfo[i*TUBESIDES + k].position.x;
				Vector p0 = vinfo[i*TUBESIDES + k].position;
				Vector pup = vinfo[i*TUBESIDES + (k+1)%TUBESIDES].position;
				Vector pdown = vinfo[i*TUBESIDES + (k-1+TUBESIDES)%TUBESIDES].position;
				Vector pright = vinfo[((i + 1) % (NUMTUBESEGMENTS + 1)) * TUBESIDES + k].position;
				Vector pleft = vinfo[((i - 1 + (NUMTUBESEGMENTS + 1)) % (NUMTUBESEGMENTS + 1))*TUBESIDES + k].position;
				//vinfo[i*TUBESIDES + k].position = 0.2*(p0 + pup + pdown + pright + pleft);
				vSmooth[i*TUBESIDES + k] = 0.2*(p0 + pup + pdown + pright + pleft);
				if (i == 0 || i == NUMTUBESEGMENTS){
					vSmooth[i*TUBESIDES + k].x = prevX;
				}
			}
		}
		//copy over smoothed vertices
		for (int i = 0; i < NUMTUBESEGMENTS + 1; i++){
			for (int k = 0; k < TUBESIDES; k++){
				vinfo[i*TUBESIDES + k].position = vSmooth[i*TUBESIDES + k];
			}
		}
		delete [] vSmooth;
		vSmooth = 0;
	}

	//calculate normals	
	for (int i = 0; i < NUMTUBESEGMENTS + 1; i++){
		for (int k = 0; k < TUBESIDES; k++){
			if (i == 0){  //border case
				vinfo[i*TUBESIDES + k].normal = Vector(-1, -1, -1);
				
				Vector p0 = vinfo[i*TUBESIDES + k].position;
				Vector pup = vinfo[i*TUBESIDES + (k+1)%TUBESIDES].position - p0;
				Vector pdown = vinfo[i*TUBESIDES + (k-1+TUBESIDES)%TUBESIDES].position - p0;
				Vector pright = vinfo[(i+1)*TUBESIDES + k].position - p0;
				//Vector pleft = vinfo[(i-1)*TUBESIDES + k].position - p0;
				Vector norm = pright.cross(pup) + pdown.cross(pright);
				vinfo[i*TUBESIDES + k].normal = norm/norm.length();
				
			}
			else if (i == NUMTUBESEGMENTS){  //other end
				Vector p0 = vinfo[i*TUBESIDES + k].position;
				Vector pup = vinfo[i*TUBESIDES + (k+1)%TUBESIDES].position - p0;
				Vector pdown = vinfo[i*TUBESIDES + (k-1+TUBESIDES)%TUBESIDES].position - p0;
				//Vector pright = vinfo[(i+1)*TUBESIDES + k].position - p0;
				Vector pleft = vinfo[(i-1)*TUBESIDES + k].position - p0;
				Vector norm = pup.cross(pleft) + pleft.cross(pdown);
				vinfo[i*TUBESIDES + k].normal = norm/norm.length();
			}
			else {
				Vector p0 = vinfo[i*TUBESIDES + k].position;
				Vector pup = vinfo[i*TUBESIDES + (k+1)%TUBESIDES].position - p0;
				Vector pdown = vinfo[i*TUBESIDES + (k-1+TUBESIDES)%TUBESIDES].position - p0;
				Vector pright = vinfo[(i+1)*TUBESIDES + k].position - p0;
				Vector pleft = vinfo[(i-1)*TUBESIDES + k].position - p0;
				Vector norm = pright.cross(pup) + pup.cross(pleft) + pleft.cross(pdown) + pdown.cross(pright);
				vinfo[i*TUBESIDES + k].normal = norm/norm.length();
			}
			/*
			if (k == 0){
				std::ostringstream oss;
				oss << "Normal at: " << i << ": " << vinfo[i*TUBESIDES + k].normal.x << ", " << vinfo[i*TUBESIDES + k].normal.y << ", " << vinfo[i*TUBESIDES + k].normal.z;
				textDump(oss.str());
			}
			*/
		}
	}
	
}
Beispiel #8
0
void KisFilterNoise::processImpl(KisPaintDeviceSP device,
                                 const QRect& applyRect,
                                 const KisFilterConfiguration* config,
                                 KoUpdater* progressUpdater
                                ) const
{
    Q_ASSERT(!device.isNull());

    if (progressUpdater) {
        progressUpdater->setRange(0, applyRect.width() * applyRect.height());
    }
    int count = 0;

    const KoColorSpace * cs = device->colorSpace();

    QVariant value;
    int level = (config && config->getProperty("level", value)) ? value.toInt() : 50;
    int opacity = (config && config->getProperty("opacity", value)) ? value.toInt() : 100;

    KisSequentialIterator it(device, applyRect);

    quint8* interm = new quint8[cs->pixelSize()];
    double threshold = (100.0 - level) * 0.01;

    qint16 weights[2];
    weights[0] = (255 * opacity) / 100;
    weights[1] = 255 - weights[0];

    const quint8* pixels[2];
    pixels[0] = interm;

    KoMixColorsOp * mixOp = cs->mixColorsOp();

    int seedThreshold = rand();
    int seedRed = rand();
    int seedGreen = rand();
    int seedBlue = rand();

    if (config) {
        seedThreshold = config->getInt("seedThreshold", seedThreshold);
        seedRed = config->getInt("seedRed", seedRed);
        seedGreen = config->getInt("seedGreen", seedGreen);
        seedBlue = config->getInt("seedBlue", seedBlue);
    }

    KisRandomGenerator randt(seedThreshold);
    KisRandomGenerator randr(seedRed);
    KisRandomGenerator randg(seedGreen);
    KisRandomGenerator randb(seedBlue);

    do {
        if (randt.doubleRandomAt(it.x(), it.y()) > threshold) {
            // XXX: Added static_cast to get rid of warnings
            QColor c = qRgb(static_cast<int>((double)randr.doubleRandomAt(it.x(), it.y()) * 255),
                            static_cast<int>((double)randg.doubleRandomAt(it.x(), it.y()) * 255),
                            static_cast<int>((double)randb.doubleRandomAt(it.x(), it.y()) * 255));
            cs->fromQColor(c, interm, 0);
            pixels[1] = it.oldRawData();
            mixOp->mixColors(pixels, weights, 2, it.rawData());
        }
        if (progressUpdater) progressUpdater->setValue(++count);
    } while (it.nextPixel() && !(progressUpdater && progressUpdater->interrupted()));

    delete [] interm;
}
int main(int argc, char *argv[])
{
	int i,j,k;			//Counter variable
	
	bvec b_source_bits, b_decoded_bits, b_encoded_bits;
	ivec i_decoded_bits, i_decoded_symbols;
	cvec c_received_signals;
	vec  d_received_llr;
	ivec No_of_Errors, No_of_Bits, No_of_BlockErrors, No_of_Blocks;
	
	//Channel setup
	cvec channel_gains;
	TDL_Channel ray_channel; // default: uncorrelated Rayleigh fading channel
        AWGN_Channel awgn_channel; // AWGN channel
	
	//-------------------------------------------------------CONV
	//Convolutional codes module, CONV
	CONV conv;
	char *ctrlfile;
	if(argc==1) ctrlfile = "control.conv.par";
	else        ctrlfile = argv[1];
	
	conv.set_parameters_from_file(ctrlfile);
	conv.initialise();
	
	//result file
	FILE *f;  char *resultfile= conv.get_result_filename();
	f=fopen(resultfile, "w");
	
	//print out parameters
	conv.print_parameters(stdout);    
	conv.print_parameters(f);
	//-------------------------------------------------------CONV	
	
	// read simulation parameters
	FILE *sim_file;
	FILESERVICE fileser;
	sim_file = fopen("control.sim.par", "r");
	if(sim_file==NULL) it_error("control.sim.par not found");
	int max_nrof_frame = fileser.scan_integer(sim_file);
	double SNR_start  = fileser.scan_double(sim_file); 
	double SNR_step   = fileser.scan_double(sim_file);
	double SNR_end    = fileser.scan_double(sim_file);
	double G_sd        = fileser.scan_double(sim_file);
	double G_sr        = fileser.scan_double(sim_file);
	double G_rd        = fileser.scan_double(sim_file);
	int channel_type   = fileser.scan_integer(sim_file);
	int mapper_bps     = fileser.scan_integer(sim_file);
	fclose(sim_file);
	char text[100];
	sprintf( text, "%f:%f:%f", SNR_start, SNR_step, SNR_end );
	
	//SNR setup
	vec SNRdB = text;	//Setting the simulation Eb/N0 range in dB


	int M = 1<<mapper_bps;
        PSK psk(M);
	cvec source_frame;
	
	double rate = (double)mapper_bps * conv.get_rate(); 

	printf (  "! %d-PSK (mapper_bps=%d) :: Overall_Rate=%.4f\n!\n", M, mapper_bps, rate);
	fprintf(f,"! %d-PSK (mapper_bps=%d) :: Overall_Rate=%.4f\n!\n", M, mapper_bps, rate);

	vec SNR    = pow(10.0, SNRdB/10.0);
	vec N0     = 1.0/SNR;
	vec sigma2 = N0/2;

	
	BERC berc;			//BER counter
	BLERC blerc;			//FER counter
	Real_Timer tt;			//Time counter

	vec ber(SNRdB.length());	//allocate memory for vector to store BER
	vec bler(SNRdB.length());	//allocate memory for vector to store FER
	
	ber.clear();			//Clear up buffer of BER counter
	bler.clear();			//Clear up buffer of FER counter	
	
	blerc.set_blocksize((long)conv.get_info_bit_length());	//set blocksize of the FER counter
	
	tt.tic();					//Start timer
	
	//RNG_randomize();				//construct random source 
	RNG_reset(0);                                   //reset random seed 
	
	b_source_bits.set_size(conv.get_info_bit_length(), false);
	b_encoded_bits.set_size(conv.get_coded_bit_length(), false);
	c_received_signals.set_size(conv.get_sym_length(), false);
	d_received_llr.set_size(conv.get_coded_bit_length(), false);
	b_decoded_bits.set_size(conv.get_info_bit_length(), false);
	
	No_of_Errors.set_size(SNRdB.length(), false);		//Set the length
	No_of_Bits.set_size(SNRdB.length(), false);		//for ivectors storing the no	
	No_of_BlockErrors.set_size(SNRdB.length(),false);	//of errors bits or error frames
	No_of_Blocks.set_size(SNRdB.length(),false);
			
	No_of_Errors.clear();
	No_of_Bits.clear();
	No_of_BlockErrors.clear();
	No_of_Blocks.clear();
	
	printf (  "!SNR(dB)\tEbN0(dB)\tBER\t\tFER\t\tnrof Frames\n");
	fprintf(f,"!SNR(dB)\tEbN0(dB)\tBER\t\tFER\t\tnrof Frames\n");
	
	for(i=0; i< SNRdB.length(); i++)
	{
		//Set channel noise level
		awgn_channel.set_noise(N0(i));
		
		for(j=0;j<max_nrof_frame;j++)
		{			
		        //Generate random source bits
			b_source_bits = randb(conv.get_info_bit_length());
			
			//CONV encode
			conv.encode_bits(b_source_bits, b_encoded_bits);
			
			source_frame = psk.modulate_bits(b_encoded_bits);
			
			// Fast Rayleigh channel + AWGN transmission 
			channel_gains = my_channel(channel_type, source_frame.length(), G_sd, ray_channel); 
			c_received_signals = elem_mult(source_frame, channel_gains);
			c_received_signals = awgn_channel( c_received_signals );
			
			//Demodulation to get llr
			psk.demodulate_soft_bits(c_received_signals, channel_gains, N0(i), d_received_llr);
			//Convert to Log(Pr=1/Pr=0)
                        d_received_llr = -1 * d_received_llr;

			//CONV decode
			conv.assign_apr_codeword(d_received_llr);
			conv.decode(i_decoded_bits, i_decoded_symbols);

			b_decoded_bits = to_bvec(i_decoded_bits.left(conv.get_info_bit_length())); 
			// remove dummy bits if trellis/code termination is used
			
			berc.clear();
			blerc.clear();
			
			berc.count (b_source_bits, b_decoded_bits);	//Count error bits in a word
			blerc.count (b_source_bits, b_decoded_bits);	//Count frame errors
			
			No_of_Errors(i) += berc.get_errors();		//Updating counters	
			No_of_Bits(i) += berc.get_errors()+berc.get_corrects();
			No_of_BlockErrors(i) +=blerc.get_errors();
			No_of_Blocks(i)++;
			
			if(No_of_Errors(i)>100000)
				break;
		}
		
		ber(i) = (double)No_of_Errors(i)/No_of_Bits(i);
		bler(i) = (double)No_of_BlockErrors(i)/No_of_Blocks(i);
		
		double EbN0dB = SNRdB(i) - 10*log10(rate);
		
		printf("%f\t%f\t%e\t%e\t%d\n",    SNRdB(i), EbN0dB, ber(i), bler(i), No_of_Blocks(i));
		fprintf(f,"%f\t%f\t%e\t%e\t%d\n", SNRdB(i), EbN0dB, ber(i), bler(i), No_of_Blocks(i));
		
		if(ber(i)<1e-5)  break;			
	}

	fprintf(f,"!Elapsed time = %d s\n", tt.get_time());		//output simulation time
	tt.toc();							//Stop timer and output simulation time
	
	fclose(f);							//close output file	
	return 0 ;							//exit program
}
CORASMA_BER_Test::CORASMA_BER_Test()
{
    modem=new Modem_CORASMA();
    int L=1;
    int OF=1;

    cmat fading;
    cvec channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,channel9,channel10,channel11,channel12,channel13,channel14,channel15,channel16;
    bvec transmitted_bits;
    bvec received_bits;
    cvec sum_chips;
    cvec transmitted_symbols;
    cvec received_chips;
    double norm_fading;
    BERC berc,berc1,berc2;
    AWGN_Channel channel;

    vec EbN0dB = linspace(1000, 1000, 1);
    vec EbN0 = pow(10, EbN0dB / 10);
    double Eb = 1.0;
    vec N0 = Eb * pow(EbN0, -1.0);
    int NumOfBits = modem->nb_bits;
    int MaxIterations = 10;
    int MaxNrOfErrors = 200;
    int MinNrOfErrors = 5;
    vec ber;
    ber.set_size(EbN0dB.size(), false);
    ber.clear();
    RNG_randomize();



    for (int i=0;i<EbN0dB.length();i++){

        cout << endl << "Simulating point nr " << i + 1 << endl;
        berc.clear();
        berc1.clear();
        berc2.clear();
        channel.set_noise(N0(i));

        for (int j=0;j<MaxIterations;j++) {

            transmitted_bits = randb(NumOfBits);
            sum_chips=modem->modulate(transmitted_bits);


            transmitted_symbols.set_length(sum_chips.length()+L+1);
            transmitted_symbols.zeros();

            fading.set_size(L,sum_chips.length());
            fading.zeros();

            channel1.set_length(sum_chips.length());
/*          channel2.set_length(sum_chips.length());
            channel3.set_length(sum_chips.length());
            channel4.set_length(sum_chips.length());
            channel5.set_length(sum_chips.length());
            channel6.set_length(sum_chips.length());
            channel7.set_length(sum_chips.length());
            channel8.set_length(sum_chips.length());
            channel9.set_length(sum_chips.length());
            channel10.set_length(sum_chips.length());
            channel11.set_length(sum_chips.length());
            channel12.set_length(sum_chips.length());
            channel13.set_length(sum_chips.length());
            channel14.set_length(sum_chips.length());
            channel15.set_length(sum_chips.length());
            channel16.set_length(sum_chips.length());*/


            for(int k=0;k<sum_chips.length()/OF;k++){


                channel1.replace_mid(k*OF,ones_c(OF));

/*              channel1.replace_mid(k*OF,randn_c()*ones(OF));
                channel2.replace_mid(k*OF,randn_c()*ones(OF));
                channel3.replace_mid(k*OF,randn_c()*ones(OF));
                channel4.replace_mid(k*OF,randn_c()*ones(OF));
                channel5.replace_mid(k*OF,randn_c()*ones(OF));
                channel6.replace_mid(k*OF,randn_c()*ones(OF));
                channel7.replace_mid(k*OF,randn_c()*ones(OF));
                channel8.replace_mid(k*OF,randn_c()*ones(OF));
                channel9.replace_mid(k*OF,randn_c()*ones(OF));
                channel10.replace_mid(k*OF,randn_c()*ones(OF));
                channel11.replace_mid(k*OF,randn_c()*ones(OF));
                channel12.replace_mid(k*OF,randn_c()*ones(OF));
                channel13.replace_mid(k*OF,randn_c()*ones(OF));
                channel14.replace_mid(k*OF,randn_c()*ones(OF));
                channel15.replace_mid(k*OF,randn_c()*ones(OF));
                channel16.replace_mid(k*OF,randn_c()*ones(OF));*/

            }


            norm_fading=1./sqrt(inv_dB(0)*norm(channel1)*norm(channel1)/sum_chips.length()/*+inv_dB(0)*norm(channel2)*norm(channel2)/sum_chips.length()+inv_dB(0)*norm(channel3)*norm(channel3)/sum_chips.length()+inv_dB(0)*norm(channel4)*norm(channel4)/sum_chips.length()+inv_dB(0)*norm(channel5)*norm(channel5)/sum_chips.length()+inv_dB(0)*norm(channel6)*norm(channel6)/sum_chips.length()+inv_dB(0)*norm(channel7)*norm(channel7)/sum_chips.length()+inv_dB(0)*norm(channel8)*norm(channel8)/sum_chips.length()+inv_dB(0)*norm(channel9)*norm(channel9)/sum_chips.length()+inv_dB(0)*norm(channel10)*norm(channel10)/sum_chips.length()+inv_dB(0)*norm(channel11)*norm(channel11)/sum_chips.length()+inv_dB(0)*norm(channel12)*norm(channel12)/sum_chips.length()+inv_dB(0)*norm(channel13)*norm(channel13)/sum_chips.length()+inv_dB(0)*norm(channel14)*norm(channel14)/sum_chips.length()+inv_dB(0)*norm(channel15)*norm(channel15)/sum_chips.length()+inv_dB(0)*norm(channel16)*norm(channel16)/sum_chips.length()*/);
            fading.set_row(0,norm_fading*channel1);
/*          fading.set_row(1,norm_fading*channel2);
            fading.set_row(2,norm_fading*channel3);
            fading.set_row(3,norm_fading*channel4);
            fading.set_row(4,norm_fading*channel5);
            fading.set_row(5,norm_fading*channel6);
            fading.set_row(6,norm_fading*channel7);
            fading.set_row(7,norm_fading*channel8);
            fading.set_row(8,norm_fading*channel9);
            fading.set_row(9,norm_fading*channel10);
            fading.set_row(10,norm_fading*channel11);
            fading.set_row(11,norm_fading*channel12);
            fading.set_row(12,norm_fading*channel13);
            fading.set_row(13,norm_fading*channel14);
            fading.set_row(14,norm_fading*channel15);
            fading.set_row(15,norm_fading*channel16);*/

            for (int k=0;k<L;k++){
                transmitted_symbols+=concat(zeros_c(k),elem_mult(to_cvec(sum_chips),fading.get_row(k)),zeros_c(L+1-k));
            }
            received_chips = channel(/*transmitted_symbols*/sum_chips);

            cvec constellation;
            int time_offset_estimate;
            received_bits=modem->demodulate(received_chips,constellation,time_offset_estimate);
            bvec received_bits_inverted=received_bits+bin(1);
            //Generic Transmitter + First Receiver M&M + Costas
            berc1.count(transmitted_bits, received_bits);
            ber(i) = berc1.get_errorrate();
            berc=berc1;
            berc2.count(transmitted_bits, received_bits_inverted);
            if(berc2.get_errorrate()<ber(i)){
                ber(i) = berc2.get_errorrate();
                berc=berc2;
            }
            cout << "   Iteration " << j + 1 << ": ber = " << berc.get_errorrate() << endl;
            if (berc.get_errors() > MaxNrOfErrors) {
                cout << "Breaking on point " << i + 1 << " with " << berc.get_errors() << " errors." << endl;
                break;
            }

        }

        if (berc.get_errors() < MinNrOfErrors) {
            cout << "Exiting Simulation on point " << i + 1 << endl;
            break;
        }

    }

    //Print results:
    cout << endl;
    cout << "EbN0dB = " << EbN0dB << endl;
    cout << "ber = " << ber << endl;

}
Beispiel #11
0
int UHD_SAFE_MAIN(int argc, char *argv[]){



    if (uhd::set_thread_priority_safe(1,true)) {
       std::cout << "set priority went well " << std::endl;
    };


    //variables to be set by po
    std::string args;
    double seconds_in_future;
    size_t total_num_samps;
    double tx_rate, freq, LOoffset;
    float gain;
    bool demoMode, use_8bits;
    bool use_external_10MHz; 
    std::string filename;
    uhd::tx_streamer::sptr tx_stream;
    uhd::device_addr_t dev_addr;
    uhd::usrp::multi_usrp::sptr dev;
    uhd::stream_args_t stream_args;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
      ("help", "help message")
      ("args", po::value<std::string>(&args)->default_value(""), "simple uhd device address args")
      ("secs", po::value<double>(&seconds_in_future)->default_value(3), "number of seconds in the future to transmit")
      ("nsamps", po::value<size_t>(&total_num_samps)->default_value(37028), "total number of samples to transmit")//9428
      ("txrate", po::value<double>(&tx_rate)->default_value(100e6/4), "rate of outgoing samples")
      ("freq", po::value<double>(&freq)->default_value(70e6), "rf center frequency in Hz")
      ("LOoffset", po::value<double>(&LOoffset)->default_value(0), "Offset between main LO and center frequency")
      ("demoMode",po::value<bool>(&demoMode)->default_value(true), "demo mode")
      ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), 
       "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
      ("filename",po::value<std::string>(&filename)->default_value("codedData.dat"), "input filename")
      ("gain",po::value<float>(&gain)->default_value(0), "gain of transmitter(0-13) ")
      ("8bits",po::value<bool>(&use_8bits)->default_value(false), "Use eight bits/sample to increase bandwidth")
    ;

    
    
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    
    //print the help message
    if (vm.count("help")){
      std::cout << boost::format("tx %s") % desc << std::endl;
      return ~0;
    }
    
 ///////////////////////////////////////////////////////////////// START PROCESSING /////////////////////////////////////////////////////////////////////
    
    std::complex<int16_t> *buffer0;
    buffer0 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer1;
    buffer1 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer2;
    buffer2 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer3;
    buffer3 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer4;
    buffer4 = new std::complex<int16_t>[total_num_samps];

    
    int16_t *aux0;
    aux0 = new int16_t[2*total_num_samps];
    int16_t *aux1;
    aux1 = new int16_t[2*total_num_samps];
    int16_t *aux2;
    aux2 = new int16_t[2*total_num_samps];
    int16_t *aux3;
    aux3 = new int16_t[2*total_num_samps];
    int16_t *aux4;
    aux4 = new int16_t[2*total_num_samps];
    
    //generate the picture as grayscale
    int r=system("octave image_transmition.m &");
    if(r){
      std::cout<<" loading picture - check!\n";
    }
    
    int nPicRaw = 16384;//size of the image in grayscale 128*128
    double nBinPac = 27200;//size of binary data in one packet
 

    //loading picture as grayscale
    int16_t pictureRaw[nPicRaw];
    std::ifstream ifs( "data_toSend.dat", std::ifstream::in );
    ifs.read((char * )pictureRaw,nPicRaw*sizeof(int16_t));
    ifs.close();  
    
    //converting grayscale to binary and XOR with pseudonoise
    itpp::bvec picBinInter = prepairPic(pictureRaw,nPicRaw);//transforms grayscale in binary data

    //cutting the large binary data into 5 packets
    bvec dataBinTmp0;
    dataBinTmp0.ins(dataBinTmp0.length(),picBinInter.get(0,(nBinPac-1)));
    bvec dataBinTmp1;
    dataBinTmp1.ins(dataBinTmp1.length(),picBinInter.get(nBinPac,(2*nBinPac-1)));
    bvec dataBinTmp2;
    dataBinTmp2.ins(dataBinTmp2.length(),picBinInter.get(2*nBinPac,(3*nBinPac-1)));
    bvec dataBinTmp3;
    dataBinTmp3.ins(dataBinTmp3.length(),picBinInter.get(3*nBinPac,(4*nBinPac-1)));
    bvec dataBinTmp4;
    dataBinTmp4.ins(dataBinTmp4.length(),picBinInter.get(4*nBinPac,picBinInter.length()));
    dataBinTmp4.ins(dataBinTmp4.length(),randb(nBinPac-dataBinTmp4.length())); //filling the last packet with random data

    //saving the binary picture
    it_file my_file("binPicture.it");
    my_file << Name("picBinInter") << picBinInter;
    my_file.flush();
    my_file.close();
    
    
    //processing each packet
    tx_funct(aux0,dataBinTmp0,dataBinTmp0.length());
    tx_funct(aux1,dataBinTmp1,dataBinTmp1.length());
    tx_funct(aux2,dataBinTmp2,dataBinTmp2.length());
    tx_funct(aux3,dataBinTmp3,dataBinTmp3.length());
    tx_funct(aux4,dataBinTmp4,dataBinTmp4.length());
    
    //filling the output buffer
    for(int i=0,count1=0;i<(int)(2*total_num_samps);i=i+2){
      buffer0[count1]=std::complex<short>(aux0[i],aux0[i+1]);
      buffer1[count1]=std::complex<short>(aux1[i],aux1[i+1]);
      buffer2[count1]=std::complex<short>(aux2[i],aux2[i+1]);
      buffer3[count1]=std::complex<short>(aux3[i],aux3[i+1]);
      buffer4[count1]=std::complex<short>(aux4[i],aux4[i+1]);
      count1++;
    }
 
    
   
    // Save data to file to check what was sent
    std::ofstream ofs( "sent0.dat" , std::ifstream::out );
    ofs.write((char * ) buffer0, 2*total_num_samps*sizeof(int16_t));
    ofs.flush();
    ofs.close();
    // Save data to file to check what was sent
    std::ofstream ofs1( "sent1.dat" , std::ifstream::out );
    ofs1.write((char * ) buffer1, 2*total_num_samps*sizeof(int16_t));
    ofs1.flush();
    ofs1.close();
    // Save data to file to check what was sent
    std::ofstream ofs2( "sent2.dat" , std::ifstream::out );
    ofs2.write((char * ) buffer2, 2*total_num_samps*sizeof(int16_t));
    ofs2.flush();
    ofs2.close();
    // Save data to file to check what was sent
    std::ofstream ofs3( "sent3.dat" , std::ifstream::out );
    ofs3.write((char * ) buffer3, 2*total_num_samps*sizeof(int16_t));
    ofs3.flush();
    ofs3.close();
    // Save data to file to check what was sent
    std::ofstream ofs4( "sent4.dat" , std::ifstream::out );
    ofs4.write((char * ) buffer4, 2*total_num_samps*sizeof(int16_t));
    ofs4.flush();
    ofs4.close();

    //Conjugate!!!
    for(int i=0; i<(int)(total_num_samps);i++){
      buffer0[i]=std::conj(buffer0[i]);
      buffer1[i]=std::conj(buffer1[i]);
      buffer2[i]=std::conj(buffer2[i]);
      buffer3[i]=std::conj(buffer3[i]);
      buffer4[i]=std::conj(buffer4[i]);
    } 
    
    

    std::cout << " ----------- " << std::endl;
    std::cout<<" Conjugated! \n";
    std::cout << " ----------- " << std::endl;
    
    ///////////////////////////////////////////////////////////////// END  PROCESSING /////////////////////////////////////////////////////////////////////
    
    //create a usrp device and streamer
    dev_addr["addr0"]="192.168.10.2";
    dev = uhd::usrp::multi_usrp::make(dev_addr);    


    // Internal variables 
    uhd::clock_config_t my_clock_config; 

    if (!demoMode) {
      dev->set_time_source("external");
    };

    if (use_external_10MHz) { 
      dev->set_clock_source("external");
    }
    else {
      dev->set_clock_source("internal");
    };


    uhd::usrp::dboard_iface::sptr db_iface;
    db_iface=dev->get_tx_dboard_iface(0);

    board_60GHz_TX  my_60GHz_TX(db_iface);  //60GHz 
    my_60GHz_TX.set_gain(gain); // 60GHz 

    uhd::tune_result_t tr;
    uhd::tune_request_t trq(freq,LOoffset); //std::min(tx_rate,10e6));
    tr=dev->set_tx_freq(trq,0);
    

    //dev->set_tx_gain(gain);
    std::cout << tr.to_pp_string() << "\n";
 

    stream_args.cpu_format="sc16";
    if (use_8bits)
      stream_args.otw_format="sc8";
    else
      stream_args.otw_format="sc16";

    tx_stream=dev->get_tx_stream(stream_args);


    //set properties on the device
    std::cout << boost::format("Setting TX Rate: %f Msps...") % (tx_rate/1e6) << std::endl;
    dev->set_tx_rate(tx_rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (dev->get_tx_rate()/1e6) << std::endl;
    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;


    

    uhd::tx_metadata_t md;


    if(demoMode){

    dev->set_time_now(uhd::time_spec_t(0.0));
    md.start_of_burst = true;
    md.end_of_burst = false;
    md.has_time_spec = false;
    md.time_spec = uhd::time_spec_t(seconds_in_future);

   
    tx_stream->send(buffer0,total_num_samps,md,60);
    
    tx_stream->send(buffer1,total_num_samps,md,3);
    
    tx_stream->send(buffer2,total_num_samps,md,3);

    tx_stream->send(buffer3,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    md.start_of_burst = false;

    std::cout << " " << std::endl;
    std::cout<< "picture transmitted once!" << std::endl;
    std::cout << " " << std::endl;
    
    int f=system("octave toMatlab.m");
    if(f){
      std::cout << " Programm Paused - Press Any Key To leave! " << std::endl;
    }


    }
    else
    {
    
    dev->set_time_now(uhd::time_spec_t(0.0));
    md.start_of_burst = true;
    md.end_of_burst = false;
    md.has_time_spec = false;
    md.time_spec = uhd::time_spec_t(seconds_in_future);

      
    tx_stream->send(buffer0,total_num_samps,md,60);
    
    tx_stream->send(buffer1,total_num_samps,md,3);
    
    tx_stream->send(buffer2,total_num_samps,md,3);

    tx_stream->send(buffer3,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    md.start_of_burst = false;

    std::cout << " " << std::endl;
    std::cout<< "picture transmitted once!" << std::endl;
    std::cout << " " << std::endl;

    };

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;


    return 0;
}
MCDAAOFDM_BER_Test::MCDAAOFDM_BER_Test()
{

    modem=new Modem_MCDAAOFDM();
    int L=1;
    int quasi_static=modem->Nfft+modem->Ncp;

    cmat fading;
    cvec channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,channel9,channel10,channel11,channel12,channel13,channel14,channel15,channel16;
    bvec transmitted_bits;
    bvec received_bits;
    cvec modulated_ofdm;
    cvec transmitted_symbols;
    cvec received_ofdm;
    double norm_fading;
    BERC berc;
    AWGN_Channel channel;

    vec EbN0dB = linspace(0, 40, 41);
    vec EbN0 = pow(10, EbN0dB / 10);
    double Eb = 1.0;
    vec N0 = Eb * pow(EbN0, -1.0);
    int NumOfBits = 1000000;
    int MaxIterations = 10;
    int MaxNrOfErrors = 200;
    int MinNrOfErrors = 5;
    vec ber;
    ber.set_size(EbN0dB.size(), false);
    ber.clear();
    RNG_randomize();



    for (int i=0;i<EbN0dB.length();i++){

        cout << endl << "Simulating point nr " << i + 1 << endl;
        berc.clear();
        channel.set_noise(N0(i));

        for (int j=0;j<MaxIterations;j++) {

            transmitted_bits = randb(NumOfBits);
            modulated_ofdm=sqrt(modem->Nfft+modem->Ncp)/sqrt(modem->Nfft)*modem->modulate_mask_qpsk(transmitted_bits,0);

            transmitted_symbols.set_length(modulated_ofdm.length()+L+1);
            transmitted_symbols.zeros();

            fading.set_size(L,modulated_ofdm.length());
            fading.zeros();

            channel1.set_length(modulated_ofdm.length());
/*          channel2.set_length(modulated_ofdm.length());
            channel3.set_length(modulated_ofdm.length());
            channel4.set_length(modulated_ofdm.length());
            channel5.set_length(modulated_ofdm.length());
            channel6.set_length(modulated_ofdm.length());
            channel7.set_length(modulated_ofdm.length());
            channel8.set_length(modulated_ofdm.length());
            channel9.set_length(modulated_ofdm.length());
            channel10.set_length(modulated_ofdm.length());
            channel11.set_length(modulated_ofdm.length());
            channel12.set_length(modulated_ofdm.length());
            channel13.set_length(modulated_ofdm.length());
            channel14.set_length(modulated_ofdm.length());
            channel15.set_length(modulated_ofdm.length());
            channel16.set_length(modulated_ofdm.length());*/


            for(int k=0;k<modulated_ofdm.length()/quasi_static;k++){


                channel1.replace_mid(k*quasi_static,ones_c(quasi_static));
                //complex<double> random_complex= randn_c();
                //double canal=sqrt(real(random_complex*conj(random_complex)));
              //channel1.replace_mid(k*quasi_static,canal*ones_c(quasi_static));
              //channel1.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
 /*               channel2.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel3.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel4.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel5.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel6.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel7.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel8.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel9.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel10.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel11.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel12.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel13.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel14.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel15.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel16.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));*/

            }


            norm_fading=1./sqrt(inv_dB(0)*norm(channel1)*norm(channel1)/modulated_ofdm.length()/*+inv_dB(0)*norm(channel2)*norm(channel2)/modulated_ofdm.length()+inv_dB(0)*norm(channel3)*norm(channel3)/modulated_ofdm.length()+inv_dB(0)*norm(channel4)*norm(channel4)/modulated_ofdm.length()+inv_dB(0)*norm(channel5)*norm(channel5)/modulated_ofdm.length()+inv_dB(0)*norm(channel6)*norm(channel6)/modulated_ofdm.length()+inv_dB(0)*norm(channel7)*norm(channel7)/modulated_ofdm.length()+inv_dB(0)*norm(channel8)*norm(channel8)/modulated_ofdm.length()+inv_dB(0)*norm(channel9)*norm(channel9)/modulated_ofdm.length()+inv_dB(0)*norm(channel10)*norm(channel10)/modulated_ofdm.length()+inv_dB(0)*norm(channel11)*norm(channel11)/modulated_ofdm.length()+inv_dB(0)*norm(channel12)*norm(channel12)/modulated_ofdm.length()+inv_dB(0)*norm(channel13)*norm(channel13)/modulated_ofdm.length()+inv_dB(0)*norm(channel14)*norm(channel14)/modulated_ofdm.length()+inv_dB(0)*norm(channel15)*norm(channel15)/modulated_ofdm.length()+inv_dB(0)*norm(channel16)*norm(channel16)/modulated_ofdm.length()*/);
            fading.set_row(0,norm_fading*channel1);
/*          fading.set_row(1,norm_fading*channel2);
            fading.set_row(2,norm_fading*channel3);
            fading.set_row(3,norm_fading*channel4);
            fading.set_row(4,norm_fading*channel5);
            fading.set_row(5,norm_fading*channel6);
            fading.set_row(6,norm_fading*channel7);
            fading.set_row(7,norm_fading*channel8);
            fading.set_row(8,norm_fading*channel9);
            fading.set_row(9,norm_fading*channel10);
            fading.set_row(10,norm_fading*channel11);
            fading.set_row(11,norm_fading*channel12);
            fading.set_row(12,norm_fading*channel13);
            fading.set_row(13,norm_fading*channel14);
            fading.set_row(14,norm_fading*channel15);
            fading.set_row(15,norm_fading*channel16);*/

            for (int k=0;k<L;k++){
                transmitted_symbols+=concat(zeros_c(k),elem_mult(to_cvec(modulated_ofdm),fading.get_row(k)),zeros_c(L+1-k));
            }
            received_ofdm = channel(transmitted_symbols);

            //received_chips = sum_chips;
            cvec constellation;
            vec estimated_channel;
            double metric;
            //bool is_ofdm=modem->detection(received_ofdm,metric);
            modem->time_offset_estimate=0;
            modem->frequency_offset_estimate=0;
            cvec demodulated_ofdm_symbols=modem->equalizer_fourth_power(received_ofdm,0,estimated_channel);
            received_bits=modem->demodulate_mask_gray_qpsk(demodulated_ofdm_symbols,0,constellation);
            berc.count(transmitted_bits, received_bits);
            ber(i) = berc.get_errorrate();

            cout << "   Iteration " << j + 1 << ": ber = " << berc.get_errorrate() << endl;
            if (berc.get_errors() > MaxNrOfErrors) {
                cout << "Breaking on point " << i + 1 << " with " << berc.get_errors() << " errors." << endl;
                break;
            }

        }

        if (berc.get_errors() < MinNrOfErrors) {
            cout << "Exiting Simulation on point " << i + 1 << endl;
            break;
        }

    }

    //Print results:
    cout << endl;
    cout << "EbN0dB = " << EbN0dB << endl;
    cout << "ber = " << ber << endl;

}
point TargetControl::genTarget(point currentPos, bool directionMatters)
{
	double theta;
	point targetPos;
		
	if(!directionMatters) //Direction not constrained this trial
	{	
		do 
		{
			theta=randb(0,360);
			targetPos=currentPos+point(cos(theta),sin(theta))*spawnDist;
		} 	while(targetPos.mag()>innerRadius);
		return targetPos;
	}
	
	//If direction predetermined, use it
	if (nextDirection>=0) {targetPos=currentPos+point(cos(nextDirection),sin(nextDirection))*spawnDist; nextDirection=-1; return targetPos;} 
	
	//Make sure we haven't bottomed out
	int sum=0;
	for(int k=0;k<directions;k++) 
	{
		sum+=((timesUsed[k]>=minUses)?0:1);
	}
	if (sum==0) minUses++;
	
	//Find the best direction
	double min=std::numeric_limits<double>::infinity();
	int index=-1;
	double mag;
	point bestPos;
	for(int k=0;k<directions;k++)
	{
		targetPos=currentPos+point(cos(direction[k]),sin(direction[k]))*spawnDist;
		mag=targetPos.mag();
		if((mag<min)&&(timesUsed[k]<minUses)&&(mag<innerRadius)) {min=mag; index=k; bestPos=targetPos;}
	}
	if(index != -1)
	{
		timesUsed[index]++;
		return bestPos;
	}
	
	//If no direction can produce a legal target pick randomly among the least used and set up for it
	int m=INT_MAX;
	int i;
	int * shuffle = new int[directions];
	randperm(shuffle,directions);
	for(int k=0;k<directions;k++)
		if(timesUsed[shuffle[k]]<m) {m=timesUsed[shuffle[k]]; i=shuffle[k];}
	timesUsed[i]++;
	nextDirection=direction[i];
	theta=atan2(currentPos.Y()+spawnDist*sin(direction[i]),currentPos.X()+spawnDist*cos(direction[i]))-3.14159265;
	targetPos=currentPos - point(cos(theta),sin(theta))*spawnDist;
	if (targetPos.mag()>innerRadius)
	{
		point V=point(spawnDist*cos(direction[i]),spawnDist*sin(direction[i]));
		point center=currentPos+V;
		double distance=center.mag();
		double xi=(pow(distance,2)+pow(innerRadius,2)-pow(spawnDist,2))/(2*distance);
		double yi=sqrt(pow(innerRadius,2)-pow(xi,2));
		point i1=center*(xi/distance)+point(-center.Y(),center.X())*(yi/distance);
		point i2=center*(xi/distance)-point(-center.Y(),center.X())*(yi/distance);
		double angle1=atan2(i1.Y()-V.Y()-currentPos.Y(),i1.X()-V.X()-currentPos.X());
		double angle2=atan2(i2.Y()-V.Y()-currentPos.Y(),i2.X()-V.X()-currentPos.X());
		point p1p=currentPos+point(cos(angle1),sin(angle1))*spawnDist;
		point p1m=currentPos+point(cos(angle2),sin(angle2))*spawnDist;
		if (p1p.mag()>p1m.mag()) targetPos=p1m;
		else targetPos=p1p;
	}
	return (targetPos.mag()<=maxRadius)?targetPos:point(0,0); 
}
Beispiel #14
0
	void draw() {
		// update the mouse position and add it to the broadphase
		auto mousePosition = static_cast<sf::Vector2f>(sf::Mouse::getPosition(window));
		const auto mouseSize = mouseObject.getSize();
		mouseObject.setPosition(mousePosition);
		mousePosition -= mouseObject.getOrigin();
		broadphase.addRectangle(
			mousePosition.x,
			mousePosition.y,
			mouseSize.x,
			mouseSize.y,
			&mouseObject);

		// move the rectangles around and add them to the broadphase
		for (const auto& object : objects) {
			object->setPosition(randb(0, window.getSize().x), randb(0,  window.getSize().y));
			const auto objectPosition = object->getPosition() - object->getOrigin();
			const auto objectSize = object->getSize();
			broadphase.addRectangle(
				objectPosition.x,
				objectPosition.y,
				objectSize.x,
				objectSize.y,
				object);

			object->setFillColor(sf::Color(0x00, 0x8B, 0x8B));
			object->setOutlineColor(sf::Color::White);
		}

		// now query the collision pairs and change the color of objects that hit the mouse object to red
		const auto &collisionPairs = broadphase.getCollisionPairs();
		for (const auto &pair : collisionPairs) {
			sf::RectangleShape *other = nullptr;
			if (pair.first == &mouseObject)
				other = (sf::RectangleShape*)pair.second;
			else if (pair.second == &mouseObject)
				other = (sf::RectangleShape*)pair.first;
			else {
				((sf::RectangleShape*)pair.first)->setOutlineColor(sf::Color::Cyan);
				((sf::RectangleShape*)pair.second)->setOutlineColor(sf::Color::Cyan);
			}
			if (other != nullptr)
				other->setFillColor(sf::Color(200, 0, 0));
		}

		// clear out the broadphase for the next run
		broadphase.clear();

		// clear the window with black color
		window.clear(sf::Color::Black);

		for (const auto& object : objects)
			window.draw(*object);

		window.draw(mouseObject);

		// draw a grid to outline the buckets
		const float lineThickness = 5;
		const sf::Color lineColor(150, 150, 150);
		sf::RectangleShape verticalLine(sf::Vector2f(lineThickness, window.getSize().y));
		verticalLine.setFillColor(lineColor);
		for (size_t i = 1; i < (window.getSize().x / broadphase.getCellWidth()); ++i) {
			verticalLine.setPosition(i * broadphase.getCellWidth(), 0);
			window.draw(verticalLine);
		}
		sf::RectangleShape horizontalLine(sf::Vector2f(window.getSize().x, lineThickness));
		horizontalLine.setFillColor(lineColor);
		for (size_t i = 1; i < (window.getSize().y / broadphase.getCellHeight()); ++i) {
			horizontalLine.setPosition(0, i * broadphase.getCellHeight());
			window.draw(horizontalLine);
		}
	}