void BoatDetector::houghline(IplImage* edgeImage, IplImage* image, IplImage* lineImage) {

	//validation
	int points = 50; // points per row
	int rows = 3; // number of rows
	int ver_dist = 10; // vertical distance between points
	int hor_dist = image->width / points; // horizontal distance between points

	cvCopy(edgeImage, lineImage);

	CvSeq* hough_lines = 0;

	CvScalar line_color = cvScalar(120);

	hough_lines = cvHoughLines2( edgeImage, hough_storage, CV_HOUGH_STANDARD, 1, CV_PI/180, 100, 0, 0 );


	if(hough_lines->total == 0) {
		return;
	}

	bool find = false;

	CvPoint pt1, pt2;
	float* line;
	float theta;
	float rho;
	double a, b, x0, y0;
	for( int i = 0; i < min(hough_lines->total, 100); i++ )
	{
		line = (float*)cvGetSeqElem(hough_lines, i);
		theta = line[1];
		if(theta < 1.50 || theta > 1.60) {
			continue;
		}
		rho = line[0];

		a = cos(theta);
		b = sin(theta);
		x0 = a*rho;
		y0 = b*rho;
		pt1.x = cvRound(x0 + 1000*(-b));
		pt1.y = cvRound(y0 + 1000*(a));
		pt2.x = cvRound(x0 - 1000*(-b));
		pt2.y = cvRound(y0 - 1000*(a));		

		cvLine( lineImage, pt1, pt2, line_color, 2, CV_AA, 0 );
		find = true;
	}
	if(!find) {
		return;
	}

	bool run = true;
	int search_limit = lineImage->height - (ver_dist * rows);
	int line_step = lineImage->widthStep/sizeof(char);
	int img_step = image->widthStep/sizeof(char);
	int max_left, max_right;
	int tmp_limit;
	double count;
	while(run) {
		max_left = 0;
		max_right = 0;
		for(int i = ver_dist * rows; i < search_limit; i++) {
			if(((uchar)lineImage->imageData[i*line_step+3]) == line_color.val[0]) {
				if(i > max_left) {
					max_left = i;
				}
			}
			if(((uchar)lineImage->imageData[i*line_step + (lineImage->width-3)]) == line_color.val[0]) {
				if(i > max_right) {
					max_right = i;
				}
			}		
		}
		if(max_left == 0 || max_right == 0) {
			run = false;
			continue;
		}

		tmp_limit = (max_left + max_right) / 2;

		//limit validation
		count = 0;
		if(abs(max_left - max_right) < 10) {

			for(int i = tmp_limit - (ver_dist * rows), k = 0, t = rows*2; k < rows; i+=ver_dist, k++, t-=2) {
				for(int j = hor_dist; j < image->width; j+=hor_dist) {
					if(abs(image->imageData[i*img_step + j] -
						image->imageData[(i+t*ver_dist)*img_step + j] ) > 10 )
					{
						count++;
					}
				}
			}
		}
		if((count / (points * rows)) > 0.9 ) {

			sea_limit = tmp_limit;

			/*
			IplImage* ao = cvCloneImage(image);
			for(int i = tmp_limit - (ver_dist * rows), k = 0, t = rows*2; k < rows; i+=ver_dist, k++, t-=2) {
				for(int j = hor_dist; j < image->width; j+=hor_dist) {
					if(abs(image->imageData[i*img_step + j] -
							image->imageData[(i+t*ver_dist)*img_step + j] ) > 10 )
					{
						cvLine(ao, cvPoint(j,i), cvPoint(j,i), CV_RGB(0,0,0), 3);
						cvLine(ao, cvPoint(j,i+t*ver_dist), cvPoint(j,i+t*ver_dist), CV_RGB(255,255,255), 3);
					}
				}
			}

			cvShowImage("ao",ao);
			cvWaitKey(0);
			*/

			run = false;
		}
		else {
			search_limit = max(max_left, max_right);
		}
	}
}
Exemple #2
0
/*** PROGRAM BEGIN *************************************/
int main(int argc, char *argv[])
{
/*** VARIABLE DECLARATION ******************************/
     FILE *in_file,*out_file,*freq_file;
     double real,imag,phi,abs_data;
     float sw,delta_f;
     int data_int;
     short data_short;
     int i,j,lsfid,no_bytes;
     int bit[16],n,file_status,fs;
     double x;
     int nblks, npts;
     union u_tag {
      float fval;
      int   ival;
     } uval;


/*** CONTROL OF INPUT PARAMETERS ***********************/
     if (argc<2)
         {
         printf("\nName of input file was not passed!\n");
         exit (3);
         }  

     if (argc<3)
         {
         printf("\nName of output file was not passed!\n");
         exit (3);
         }

     if (argc<4)
         {
         printf("\nName of frequency file was not passed!\n");
         exit (3);
         }

     if ((in_file=fopen(argv[1],"rb"))==NULL)
        {
        printf("\nCan not open input file");
        exit (3);
        }

     rewind(in_file);  


     if (fread(&datafilehead,sizeof(datafilehead),1,in_file) != 1)
         {
         fprintf (stderr, "Error in reading input data (datafilehead)\n");
         exit (3);
         }  


     if ((out_file=fopen(argv[2],"wb"))==NULL)
        {
        printf("\nCan not open output file");
        exit (3);
        }

     rewind(out_file);   

     if (fwrite(&datafilehead,sizeof(datafilehead),1,out_file) != 1)
         {
         fprintf (stderr, "Error in writting output data (datafilehead)\n");
         exit (3);
         }

     if ((freq_file=fopen(argv[3],"rb"))==NULL)
        {
        printf("\nCan not open frequency file");
        exit (3);
        }

     fscanf(freq_file,"%f",&sw);
     fscanf(freq_file,"%d",&lsfid);

     no_bytes = ntohl(datafilehead.ebytes);
     

/*** FILE STATUS  ********************************/

     file_status = ntohs(datafilehead.status);
     fs = file_status;
     
     for (n=15;n>=0;n--)
         {
         x = pow(2.0,(double)n);
         bit[n] = 0;
         if (fs >= (int)x)
            {
            fs += -(int)x;
            bit[n] = 1;
            }
         }

     fprintf (stderr, "\n******* B0 DRIFT CORRECTION ********\n");
     fprintf (stderr, "FILE STATUS = %d\n",file_status);
          
     if (bit[3] == 0)
        {
        fprintf (stderr, "bit[3] = %d   Type of data: INTEGER\n",bit[3]);
        }
     if (bit[3] == 1)
        {
        fprintf (stderr, "bit[3] = %d   Type of data: FLOATING POINT\n",bit[3]);
        }


/*** FREQUENCY SHIFT CORRECTION  *******************/

     fprintf (stderr, "sw = %8.1f Hz   lsfid = %d\n",sw,lsfid);
     fprintf (stderr,"\n Spectrum\t Frequency\n");

     nblks = htonl(datafilehead.nblocks);
     npts = htonl(datafilehead.np);
     for (i=0;i<nblks;++i)
         {

         fscanf(freq_file,"%f",&delta_f);
         fprintf(stderr," spect[%3d]\t%+7.3f Hz\n",i+1,delta_f);

         if (fread(&datablockhead,sizeof(datablockhead),1,in_file) != 1)
            {
            fprintf (stderr, "Error in reading input data (datablockhead)\n");
            exit (3);
            }  

         if (fwrite(&datablockhead,sizeof(datablockhead),1,out_file) != 1)
            {
            fprintf (stderr, "Error in writting output data (datablockhead)\n");
            exit (3);
            }

         for (j=0;j<npts/2;++j)
             {
             if (no_bytes == 2)
             {
                if (fread(&data_short,no_bytes,1,in_file) != 1)
                   {
                   fprintf (stderr, "Error in reading input data (short)\n");
                   exit (3);
                   }
                real=(double) ntohs(data_short);
 
                if (fread(&data_short,no_bytes,1,in_file) != 1)
                   {
                   fprintf (stderr, "Error in reading input data (short)\n");
                   exit (3);
                   }
                imag=(double) ntohs(data_short);
               
             }
             else
             {
                if (fread(&data_int,no_bytes,1,in_file) != 1)
                   {
                   fprintf (stderr, "Error in reading input data (int/float)\n");
                   exit (3);
                   }
                uval.ival = ntohl(data_int);
                if (bit[3] == 0)
                   real = (double) uval.ival;
                else
                   real = (double) uval.fval;
                if (fread(&data_int,no_bytes,1,in_file) != 1)
                   {
                   fprintf (stderr, "Error in reading input data (int/float)\n");
                   exit (3);
                   }
                uval.ival = ntohl(data_int);
                if (bit[3] == 0)
                   imag = (double) uval.ival;
                else
                   imag = (double) uval.fval;
             }             

             phi=atan2(imag,real);

             phi=phi+2.0* M_PI *delta_f*(j-lsfid)/sw;

             abs_data=sqrt(real*real+imag*imag);

             real=abs_data*cos(phi);  
             imag=abs_data*sin(phi);   

             if (no_bytes == 2)
                {
                data_short = (short)real;
                data_short = htons(data_short);
                if (fwrite(&data_short,no_bytes,1,out_file) != 1)
                   {
                   fprintf (stderr, "Error in writting output data (short)\n");
                   exit (3);
                   }     
 
                data_short = (short)imag;
                data_short = htons(data_short);
                if (fwrite(&data_short,no_bytes,1,out_file) != 1)
                   {
                   fprintf (stderr, "Error in writting output data (short)\n");
                   exit (3);
                   }
                }
              else
                {
                     
                if (bit[3] == 0)
                   uval.ival = (int)real;
                else
                   uval.fval = (float) real;
                data_int = htonl(uval.ival);
                if (fwrite(&data_int,no_bytes,1,out_file) != 1)
                   {
                   fprintf (stderr, "Error in writting output data (int/float)\n");
                   exit (3);
                   }     
                if (bit[3] == 0)
                   uval.ival = (int)imag;
                else
                   uval.fval = (float) imag;
                data_int = htonl(uval.ival);
 
                if (fwrite(&data_int,no_bytes,1,out_file) != 1)
                   {
                   fprintf (stderr, "Error in writting output data (int/float)\n");
                   exit (3);
                   }          
                }
            }
        }
   fprintf (stderr, "\nB0 CORRECTION WAS PERFORMED!\n");
   
/*** CLOSING FILES *************************************/                                 

      if (fclose(in_file) != 0) 
         {
         printf ("Error closing input file"); 
         exit (3);      
         }

      if (fclose(out_file) != 0) 
         {
         printf ("Error closing output file"); 
         exit (3);      
         }   
   exit(EXIT_SUCCESS);
}
Exemple #3
0
void
set_M(QLA_ColorMatrix *m, int i)
{
#if 0
  static QLA_ColorMatrix t;
  for(int j=0; j<QLA_Nc; j++) {
    for(int k=0; k<QLA_Nc; k++) {
      QLA_c_eq_r_plus_ir(QLA_elem_M(*m,j,k),
			 (((j-k+QLA_Nc+1)*(j+k+1))%19)+cos(i),
			 (((j+4)*(k+1))%17)+sin(i));
      //QLA_real(QLA_elem_M(*m,j,k)) = 1;
      //QLA_imag(QLA_elem_M(*m,j,k)) = 0;
    }
  }
#endif
  for(int j=0; j<QLA_Nc; j++) {
    for(int k=0; k<QLA_Nc; k++) {
      QLA_c_eq_r(QLA_elem_M(*m,j,k), 0);
    }
  }
  QLA_Real step = 1e-5;
  if(Mtype&MtypeNZ) {
    for(int j=0; j<QLA_Nc; j++) {
      QLA_c_peq_r_plus_ir(QLA_elem_M(*m,j,j), step, -step);
    }
  }
  int ii=i;
  if((Mtype&MtypeNN)==0) ii>>=QLA_Nc;
  for(int j=0,k=1; ii; ii>>=1,j++) {
    if(j>=QLA_Nc) { j=0; k*=2; }
    if(ii&1) QLA_c_peq_r_plus_ir(QLA_elem_M(*m,j,j), k*step, -k*step);
  }
  ii = i;
  if((Mtype&MtypeNN)==0) {
    for(int j=0; j<QLA_Nc; j++) {
      if(ii&1) QLA_c_eqm_c(QLA_elem_M(*m,j,j), QLA_elem_M(*m,j,j));
      ii >>= 1;
    }
  }
  if(Mtype&MtypeH) { // make Hermitian
    QLA_ColorMatrix m2;
    QLA_M_eq_M(&m2, m);
    QLA_M_peq_Ma(&m2, m);
    QLA_M_eq_M(m, &m2);
  }
  if((Mtype&MtypeP)&&(Mtype&MtypeH)) { // make positive Hermitian
    QLA_ColorMatrix m2;
    QLA_M_eq_M_times_Ma(&m2, m, m);
    QLA_M_eq_M(m, &m2);
  }
  if(Mtype&MtypeA) { // make anti-Hermitian
    QLA_ColorMatrix m2;
    QLA_M_eq_M(&m2, m);
    QLA_M_meq_Ma(&m2, m);
    QLA_M_eq_M(m, &m2);
  }
  if((Mtype&MtypeT)&&(Mtype&MtypeA)) { // make traceless anti-Hermitian
    QLA_ColorMatrix m2;
    QLA_M_eq_antiherm_M(&m2, m);
    QLA_M_eq_M(m, &m2);
  }
  //QLA_Real n2;
  //QLA_r_eq_norm2_M(&n2, m);
  //printf("%i\t%g\n", i, n2);
}
Exemple #4
0
static void HandleEntityAdjustment(void)
{
	char		*value;
	vec3_t		origin, newOrigin, angles;
	char		temp[MAX_QPATH];
	float		rotation;

	G_SpawnString("origin", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		if ( sscanf( value, "%f %f %f", &origin[0], &origin[1], &origin[2] ) != 3 ) {
			G_Printf( "HandleEntityAdjustment: failed sscanf on 'origin' (%s)\n", value );
			VectorClear( origin );
		}
	}
	else
	{
		origin[0] = origin[1] = origin[2] = 0.0;
	}

	rotation = DEG2RAD(level.mRotationAdjust);
	newOrigin[0] = origin[0]*cos(rotation) - origin[1]*sin(rotation);
	newOrigin[1] = origin[0]*sin(rotation) + origin[1]*cos(rotation);
	newOrigin[2] = origin[2];
	VectorAdd(newOrigin, level.mOriginAdjust, newOrigin);
	// damn VMs don't handle outputing a float that is compatible with sscanf in all cases
	Com_sprintf(temp, sizeof( temp ), "%0.0f %0.0f %0.0f", newOrigin[0], newOrigin[1], newOrigin[2]);
	AddSpawnField("origin", temp);

	G_SpawnString("angles", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		if ( sscanf( value, "%f %f %f", &angles[0], &angles[1], &angles[2] ) != 3 ) {
			G_Printf( "HandleEntityAdjustment: failed sscanf on 'angles' (%s)\n", value );
			VectorClear( angles );
		}

		angles[YAW] = fmod(angles[YAW] + level.mRotationAdjust, 360.0f);
		// damn VMs don't handle outputing a float that is compatible with sscanf in all cases
		Com_sprintf(temp, sizeof( temp ), "%0.0f %0.0f %0.0f", angles[0], angles[1], angles[2]);
		AddSpawnField("angles", temp);
	}
	else
	{
		G_SpawnString("angle", NOVALUE, &value);
		if (Q_stricmp(value, NOVALUE) != 0)
		{
			angles[YAW] = atof( value );
		}
		else
		{
			angles[YAW] = 0.0;
		}
		angles[YAW] = fmod(angles[YAW] + level.mRotationAdjust, 360.0f);
		Com_sprintf(temp, sizeof( temp ), "%0.0f", angles[YAW]);
		AddSpawnField("angle", temp);
	}

	// RJR experimental code for handling "direction" field of breakable brushes
	// though direction is rarely ever used.
	G_SpawnString("direction", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		if ( sscanf( value, "%f %f %f", &angles[0], &angles[1], &angles[2] ) != 3 ) {
			G_Printf( "HandleEntityAdjustment: failed sscanf on 'direction' (%s)\n", value );
			VectorClear( angles );
		}
	}
	else
	{
		angles[0] = angles[1] = angles[2] = 0.0;
	}
	angles[YAW] = fmod(angles[YAW] + level.mRotationAdjust, 360.0f);
	Com_sprintf(temp, sizeof( temp ), "%0.0f %0.0f %0.0f", angles[0], angles[1], angles[2]);
	AddSpawnField("direction", temp);


	AddSpawnField("BSPInstanceID", level.mTargetAdjust);

	G_SpawnString("targetname", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value);
		AddSpawnField("targetname", temp);
	}

	G_SpawnString("target", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value);
		AddSpawnField("target", temp);
	}

	G_SpawnString("killtarget", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value);
		AddSpawnField("killtarget", temp);
	}

	G_SpawnString("brushparent", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value);
		AddSpawnField("brushparent", temp);
	}

	G_SpawnString("brushchild", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value);
		AddSpawnField("brushchild", temp);
	}

	G_SpawnString("enemy", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value);
		AddSpawnField("enemy", temp);
	}

	G_SpawnString("ICARUSname", NOVALUE, &value);
	if (Q_stricmp(value, NOVALUE) != 0)
	{
		Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value);
		AddSpawnField("ICARUSname", temp);
	}
}
Exemple #5
0
	double n2;\
    double XS;\
    double YS;

#define PJ_LIB__
# include	"projects.h"
PROJ_HEAD(gstmerc, "Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)")
	"\n\tCyl, Sph&Ell\n\tlat_0= lon_0= k_0=";
FORWARD(s_forward); /* spheroid */
	double L, Ls, sinLs1, Ls1;
	L= P->n1*lp.lam;
    Ls= P->c+P->n1*log(pj_tsfn(-1.0*lp.phi,-1.0*sin(lp.phi),P->e));
    sinLs1= sin(L)/cosh(Ls);
    Ls1= log(pj_tsfn(-1.0*asin(sinLs1),0.0,0.0));
    xy.x= (P->XS + P->n2*Ls1)*P->ra;
    xy.y= (P->YS + P->n2*atan(sinh(Ls)/cos(L)))*P->ra;
    /*fprintf(stderr,"fwd:\nL      =%16.13f\nLs     =%16.13f\nLs1    =%16.13f\nLP(%16.13f,%16.13f)=XY(%16.4f,%16.4f)\n",L,Ls,Ls1,lp.lam+P->lam0,lp.phi,(xy.x*P->a + P->x0)*P->to_meter,(xy.y*P->a + P->y0)*P->to_meter);*/
	return (xy);
}
INVERSE(s_inverse); /* spheroid */
	double L, LC, sinC;
	L= atan(sinh((xy.x*P->a - P->XS)/P->n2)/cos((xy.y*P->a - P->YS)/P->n2));
    sinC= sin((xy.y*P->a - P->YS)/P->n2)/cosh((xy.x*P->a - P->XS)/P->n2);
    LC= log(pj_tsfn(-1.0*asin(sinC),0.0,0.0));
    lp.lam= L/P->n1;
    lp.phi= -1.0*pj_phi2(P->ctx, exp((LC-P->c)/P->n1),P->e);
    /*fprintf(stderr,"inv:\nL      =%16.13f\nsinC   =%16.13f\nLC     =%16.13f\nXY(%16.4f,%16.4f)=LP(%16.13f,%16.13f)\n",L,sinC,LC,((xy.x/P->ra)+P->x0)/P->to_meter,((xy.y/P->ra)+P->y0)/P->to_meter,lp.lam+P->lam0,lp.phi);*/
	return (lp);
}
FREEUP; if (P) pj_dalloc(P); }
ENTRY0(gstmerc)
char Ziehe_KreisNO90(short xr1,short zp1,short xr2,short zp2,short xrm,short zpm,char g03g02)
{
  double sx=(double)zp1,sy=(double)xr1,
	 ex=(double)zp2,ey=(double)xr2,
	 mx=(double)zpm,my=(double)xrm;
  double dx,dy,w,cosw,sinw;
  double rad1,rad2,stw,endw,step=(double)schritt_g02;
  char quadr1,quadr2,endprg=0;
  short x,y;

  dx=sx-mx;
  dy=sy-my;
  rad1=sqrt(dx*dx+dy*dy);
  cosw=dx/rad1;
  sinw=dy/rad1;
  stw=arc_wi(sinw,cosw,&quadr1);

  dx=ex-mx;
  dy=ey-my;
  rad2=sqrt(dx*dx+dy*dy);
  cosw=dx/rad2;
  sinw=dy/rad2;
  endw=arc_wi(sinw,cosw,&quadr2);

  if (quadr1!=quadr2) { /* Routine zZ noch nicht in Funktion */
			Meldung("M99 Quadranten-Fehler!");
			Status("Fehler!");
			getch();
			endprg=1;
		      }

  if (fabs(fabs(rad1)-fabs(rad2))>160)
    {
      Meldung("M99-0,8mm-Toleranz �berschritten");
      Status("Fehler");
      getch();
      endprg=1; /* Nur zZ */
    }

  if (!endprg)
    {
      if (g03g02)
	{ /* G02 */
	   if (endw<stw) stw-=360.0;
	   for(w=stw;w<endw && !endprg;w+=step)
	      {
		x=(short)(mx+rad1*cos(w*deg));
		y=(short)(my+rad1*sin(w*deg));
		Setzte_Stahl(y,x,tool);
		Koordinaten(y,x);
		xrad=y;
		zpos=x;
		Wait(prgconfig.wait_g01);
		endprg=Check_FlagTasten();
	      }
	} else { /* g03 */
		 if (endw>stw) endw-=360.0;
		 for(w=stw;w>endw && !endprg;w-=step)
		  {
		    x=(short)(mx+rad1*cos(w*deg));
		    y=(short)(my+rad1*sin(w*deg));
		    Setzte_Stahl(y,x,tool);
		    Koordinaten(y,x);
		    xrad=y;
		    zpos=x;
		    Wait(prgconfig.wait_g01);
		    endprg=Check_FlagTasten();
		  }
	       } /* von g03 */
    } /* von if !endprg */

    if (!endprg)
       {
	 Setzte_Stahl(xr2,zp2,tool);
	 xrad=xr2;
	 zpos=zp2;
	 Koordinaten(xr2,zp2);
       }

  return endprg;
}
Exemple #7
0
int main(void) {
//	int i, j;
	int sine_table[NTABLE], cosine_table[NTABLE];
	int mseq_table[CYCLES * NTABLE * MSEQ_LENGTH];
	float size;
	float s;
//	float aI, aQ;
//	float uI[M];                // Store last M samples of yI
//	float uQ[M];                // Store last M samples of yQ
//	float vI, vQ;
//	float xI, xQ;
//	float w = 0;
//	float wq = 0;
	int spb = MSEQ_LENGTH * CYCLES * NTABLE;
	int last_samples[spb * MSG_LEN];
	int i = 0;

	USART_initialize(3000000, 1); 	// set baud rate to 3,000,000

	DAC_initialize(FS); 			// set sample rate
	DAC_ready_flag = 0; 		// clear the DAC ready flag
	DAC_start();				// start the DAC running
	ADC_initialize(FS);
	ADC_start();
	ADC_ready_flag = 0; 		// clear the ADC ready flag
	int mseq[MSEQ_LENGTH] = { 1, 0, 1, 0, 1, 0, 1 };
	int msg_table[MSG_LEN * CYCLES * NTABLE];
	int recieved[MSG_LEN];
	//char message[MSG_LEN] = "testing";
	int msg[MSG_LEN] = { 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0 };
	size = (float) (NTABLE / TABCYCLES);
	for (i = 0; i < NTABLE; i++) {
		sine_table[i] = (int) floor(32767 * sin(2.0 * PI * i / (float) size));
		cosine_table[i] = (int) floor(32767 * cos(2.0 * PI * i / (float) size));
	}
	for (i = 0; i < spb; i++) {
		mseq_table[i] =
				(mseq[i / (NTABLE * CYCLES)]) ?
						-sine_table[i % NTABLE] : cosine_table[i % NTABLE];
	}
	for (i = 0; i < CYCLES * NTABLE * MSG_LEN; i++) {
		msg_table[i] =
				(msg[i / (CYCLES * NTABLE)]) ?
						-sine_table[i % NTABLE] : sine_table[i % NTABLE];
	}
	for (i = 0; i < MSG_LEN; i++) {
		recieved[i] = 0;
	}

	i = 0;
	int m = 0;
	int strength = 0;
	int maxstrength = 0;
	for (i = 0; i < spb; i++) {
		last_samples[i] = 0;
	}
	int cycles = 0;
	int seconds = 0;
	int state = 0; // 0: listening for mseq
				   // 4: initializing collection of packet data
				   // 5: collecting packet data
				   // 6: decoding & printing data
	while (1) {

		if (ADC_ready_flag != 0 && DAC_ready_flag != 0) {
			ADC_ready_flag = 0;
			DAC_ready_flag = 0;

			if (state == 0) {
				DAC1_value = mseq_table[m];
				s = ADC1_value + 15000;                   // PIN 35A - Grab ADC value
				last_samples[m] = s;

				strength = 0;
				for (i = 0; i < spb; i++) { // Slow?
					strength +=
							(last_samples[(m + 1 + i) % spb] * mseq_table[i])
									/ 32767;
				}
				strength /= 100;
				m++;
				m = m % spb;
				cycles++;
				cycles = cycles % FS;
				if (strength > 7500)
					printf("Convolution: %i \n", strength);
				if (strength > 7500) {
					printf("CAUGHT MSEQ\n");
					state = 4;
					m = 0;
				}
				if (strength > maxstrength) {
					maxstrength = strength;
					printf("Max Strength: ");
					printf("%i", maxstrength);
					printf("\n");
				}
				if (cycles == 0) {
					seconds++;
					printf("[O3] Seconds elapsed: ");
					printf("%i", seconds);
					printf("\n");
				}

			} else if (state == 4) {
				if (m == -1) {
					m = 0;
					state = 5;
					last_samples[m] = ADC1_value + 15000;
					m = 1;
					DAC1_value = msg_table[m];
				} else {
					m = -1;
				};
				DAC1_value = msg_table[0];
			} else if (state == 5) {
				s = ADC1_value + 15000;
				last_samples[m] = s;
				int zero_s = 0;
				int one_s = 0;
				if (((m + 1) % (CYCLES * NTABLE)) == 0) {
					zero_s = 0;
					one_s = 0;
					for (i = (((m + 1) - (CYCLES * NTABLE))); i <= m; i++) {
						one_s += ((last_samples[i]) / 100)
								* ((-sine_table[i % NTABLE]) / 100);
						zero_s += ((last_samples[i]) / 100)
								* ((sine_table[i % NTABLE]) / 100);
					}
					printf("zero strength: %i\n", zero_s);
					printf("one strength: %i\n", one_s);
					if (zero_s > one_s) {
						printf("got 0\n");
						recieved[((m + 1) / (CYCLES * NTABLE)) - 1] += 0;
					} else {
						printf("got 1\n");
						recieved[((m + 1) / (CYCLES * NTABLE)) - 1] += 1;
					}
				}
				if (m == CYCLES * NTABLE * MSG_LEN)
					state = 6;
				m++;
				DAC1_value = msg_table[m];
			} else if (state == 6) {
				if (m < 20000)
					m++;
				else {
					state = 4;
					for (i = 0; i < MSG_LEN; i++) {
						printf("%i ", recieved[i]);
					}
					printf("\n");
				}
			}
		}
	}
}
Exemple #8
0
StkFloat Whistle :: tick( unsigned int )
{
  StkFloat soundMix, tempFreq;
  StkFloat envOut = 0, temp, temp1, temp2, tempX, tempY;
  double phi, cosphi, sinphi;
  double gain = 0.5, mod = 0.0;

  if ( --subSampCount_ <= 0 )	{
    tempVectorP_ = pea_.getPosition();
    subSampCount_ = subSample_;
    temp = bumper_.isInside( tempVectorP_ );
#ifdef WHISTLE_ANIMATION
    frameCount += 1;
    if ( frameCount >= (1470 / subSample_) ) {
      frameCount = 0;
      printf("%f %f %f\n",tempVectorP_->getX(),tempVectorP_->getY(),envOut);
      fflush(stdout);
    }
#endif
    envOut = envelope_.tick();

    if (temp < (BUMP_RADIUS + PEA_RADIUS)) {
      tempX = envOut * tickSize_ * 2000 * noise_.tick();
      tempY = -envOut * tickSize_ * 1000 * (1.0 + noise_.tick());
      pea_.addVelocity( tempX, tempY, 0 ); 
      pea_.tick( tickSize_ );
    }

    mod  = exp(-temp * 0.01);	  // exp. distance falloff of fipple/pea effect
    temp = onepole_.tick(mod);	// smooth it a little
    gain = (1.0 - (fippleGainMod_*0.5)) + (2.0 * fippleGainMod_ * temp);
    gain *= gain;	              // squared distance/gain
    //    tempFreq = 1.0				//  Normalized Base Freq
    //			+ (fippleFreqMod_ * 0.25) - (fippleFreqMod_ * temp) // fippleModulation 
    //			- (blowFreqMod_) + (blowFreqMod_ * envOut); // blowingModulation
    // short form of above
    tempFreq = 1.0 + fippleFreqMod_*(0.25-temp) + blowFreqMod_*(envOut-1.0);
    tempFreq *= baseFrequency_;

    sine_.setFrequency(tempFreq);

    tempVectorP_ = pea_.getPosition();
    temp = can_.isInside(tempVectorP_);
    temp  = -temp;       // We know (hope) it's inside, just how much??
    if (temp < (PEA_RADIUS * 1.25)) {
      pea_.getVelocity( &tempVector_ );  // This is the can/pea collision
      tempX = tempVectorP_->getX();     // calculation.  Could probably
      tempY = tempVectorP_->getY();     // simplify using tables, etc.
      phi = -atan2(tempY,tempX);

      cosphi = cos(phi);
      sinphi = sin(phi);
      temp1 = (cosphi*tempVector_.getX()) - (sinphi*tempVector_.getY());
      temp2 = (sinphi*tempVector_.getX()) + (cosphi*tempVector_.getY());
      temp1 = -temp1;
      tempX = (cosphi*temp1) + (sinphi*temp2);
      tempY = (-sinphi*temp1) + (cosphi*temp2);
      pea_.setVelocity(tempX, tempY, 0);
      pea_.tick(tickSize_);
      pea_.setVelocity( tempX*canLoss_, tempY*canLoss_, 0 );
      pea_.tick(tickSize_);
    }

    temp = tempVectorP_->getLength();	
    if (temp > 0.01) {
      tempX = tempVectorP_->getX();
      tempY = tempVectorP_->getY();
      phi = atan2( tempY, tempX );
      phi += 0.3 * temp / CAN_RADIUS;
      cosphi = cos(phi);
      sinphi = sin(phi);
      tempX = 3.0 * temp * cosphi;
      tempY = 3.0 * temp * sinphi;
    }
    else {
      tempX = 0.0;
      tempY = 0.0;
    }

    temp = (0.9 + 0.1*subSample_*noise_.tick()) * envOut * 0.6 * tickSize_;
    pea_.addVelocity( temp * tempX, (temp*tempY) - (GRAVITY*tickSize_), 0 );
    pea_.tick( tickSize_ );

    // bumper_.tick(0.0);
  }

  temp = envOut * envOut * gain / 2;
  soundMix = temp * ( sine_.tick() + ( noiseGain_*noise_.tick() ) );
  lastFrame_[0] = 0.20 * soundMix; // should probably do one-zero filter here

  return lastFrame_[0];
}
Exemple #9
0
void lsat_bandctes(lsat_data * lsat, int i, char method,
		   double percent, int dark, double rayleigh)
{
    double pi_d2, sin_e, cos_v;

    /* TAUv  = at. transmittance surface-sensor */
    /* TAUz  = at. transmittance sun-surface    */
    /* Edown = diffuse sky spectral irradiance  */
    double TAUv, TAUz, Edown;

    pi_d2 = (double)(PI * lsat->dist_es * lsat->dist_es);
    sin_e = (double)(sin(D2R * lsat->sun_elev));
    cos_v = (double)(cos(D2R * (lsat->number < 4 ? 9.2 : 8.2)));

    /** Global irradiance on the sensor.
	 * Radiance to reflectance coefficient, only NO thermal bands.
	 * K1 and K2 variables are also utilized as thermal constants
     */
    if (lsat->band[i].thermal == 0) {
	switch (method) {
	case DOS2:
	    {
		TAUv = 1.;
		TAUz = (lsat->band[i].wavemax < 1.) ? sin_e : 1.;
		Edown = 0.;
		break;
	    }
	case DOS2b:
	    {
		TAUv = (lsat->band[i].wavemax < 1.) ? cos_v : 1.;
		TAUz = (lsat->band[i].wavemax < 1.) ? sin_e : 1.;
		Edown = 0.;
		break;
	    }
	case DOS3:
	    {
		double t;

		t = 2. / (lsat->band[i].wavemax + lsat->band[i].wavemin);
		t = 0.008569 * t * t * t * t * (1 + 0.0113 * t * t + 0.000013 * t * t * t * t);
		TAUv = exp(-t / cos_v);
		TAUz = exp(-t / sin_e);
		Edown = rayleigh;
		break;
	    }
	case DOS4:
	    {
		double Ro =
		    (lsat->band[i].lmax - lsat->band[i].lmin) * (dark -
								 lsat->
								 band[i].
								 qcalmin) /
		    (lsat->band[i].qcalmax - lsat->band[i].qcalmin) +
		    lsat->band[i].lmin;
		double Tv = 1.;
		double Tz = 1.;
		double Lp = 0.;

		do {
		    TAUz = Tz;
		    TAUv = Tv;
		    Lp = Ro - percent * TAUv * (lsat->band[i].esun * sin_e * TAUz + PI * Lp) / pi_d2;
		    Tz = 1. - (4. * pi_d2 * Lp) / (lsat->band[i].esun * sin_e);
		    if (Tz <= 0)
			G_fatal_error(_("The DOS4 method is not applicable here: approximation of atmospheric transmittance coefficients is unstable. Use another DOS method or use other sun_elevation parameter"));
		    Tv = exp(sin_e * log(Tz) / cos_v);
		} while (TAUv != Tv && TAUz != Tz);
		TAUz = (Tz < 1. ? Tz : 1.);
		TAUv = (Tv < 1. ? Tv : 1.);
		Edown = (Lp < 0. ? 0. : PI * Lp);
		break;
	    }
	default:		/* DOS1 and Without atmospheric-correction */
	    TAUv = 1.;
	    TAUz = 1.;
	    Edown = 0.;
	    break;
	}
	lsat->band[i].K2 = 0.;
	lsat->band[i].K1 = TAUv * (lsat->band[i].esun * sin_e * TAUz + Edown) / pi_d2;
	if (method > DOS)
	    G_verbose_message("... TAUv = %.5f, TAUz = %.5f, Edown = %.5f\n", TAUv, TAUz, Edown);
    }

    /** Digital number to radiance coefficients.
	 * Without atmospheric calibration for thermal bands.
     */
    lsat->band[i].gain = (lsat->band[i].lmax - lsat->band[i].lmin) / (lsat->band[i].qcalmax - lsat->band[i].qcalmin);

    if (method == UNCORRECTED || lsat->band[i].thermal) {
	/* L = G * (DN - Qmin) + Lmin
	 *  -> bias = Lmin - G * Qmin    
	 */
	lsat->band[i].bias = (lsat->band[i].lmin - lsat->band[i].gain * lsat->band[i].qcalmin);
    }
    else if (method > DOS) {
	/* L = Lsat - Lpath = G * DNsat + B - (G *  + B - p * rad_sun) 
	 *   = G * DNsat - G *  + p * rad_sun
	 *  -> bias = p * rad_sun - G 
	 */
	lsat->band[i].bias = percent * lsat->band[i].K1 - lsat->band[i].gain * dark;
    }
}
Exemple #10
0
void presidency_init(t_presidency *x, short initialized)
{
	int i;
	long oldsize,newsize;
	int oldN = x->N;
	int oldN2 = x->N2;
	int oldNw = x->Nw;
	int last_framecount = x->framecount;
	x->lock = 1;
	x->virgin = 1;
	
	if(!power_of_two(x->winfac))
		x->winfac = 1;
	if(!power_of_two(x->overlap))
		x->overlap = 4;
	if(!x->R)
		x->R = 44100;
	if(!x->D){
		x->D = 256;
		x->vector_size = x->D;
	}
	x->N = x->D * x->overlap;
	x->Nw = x->N * x->winfac;
	limit_fftsize(&x->N, &x->Nw, OBJECT_NAME);
	
	x->N2 = (x->N)>>1;
	x->Nw2 = (x->Nw)>>1;
	x->inCount = -(x->Nw);
	x->mult = 1. / (float) x->N;
//	post("mult %f N %d",x->mult,x->N);
	x->current_frame = 0;
	x->fpos = x->last_fpos = 0;
	x->tadv = (float)x->D/(float)x->R;
	x->c_fundamental = (float)x->R/((x->N2)<<1);
	x->c_factor_in = (float) x->R/((float)x->D * TWOPI);
	x->c_factor_out = TWOPI * (float)x->D / (float)x->R;
	x->table_length = 8192;
	x->table_si = (float) x->table_length / (float) x->R;
	x->pitch_increment = 1.0 * x->table_si;
	
	if( x->duration <= 0 ){
		x->duration = 1.0;
	}
	
	x->framecount =  x->duration / x->tadv ;
	x->hopsize = (float)x->N / x->overlap;
	x->read_me = 0;
	
	if(!initialized){
		x->mute = 0;
		x->in2_connected = 0;
		x->in3_connected = 0;
		x->sync = 0;
		x->playthrough = 0;
		x->frame_increment = 1.0;
		x->verbose = 0;
		x->table = (float *) getbytes(x->table_length * sizeof(float));
		x->Wanal = (float *) getbytes(MAX_Nw*sizeof(float));	
		x->Wsyn = (float *) getbytes(MAX_Nw*sizeof(float));	
		x->input = (float *) getbytes(MAX_Nw*sizeof(float));	
		x->Hwin = (float *) getbytes(MAX_Nw*sizeof(float));
		x->bindex = (float *) getbytes( (MAX_N+1) * sizeof(float) );
		x->buffer = (float *) getbytes(MAX_N*sizeof(float));
		x->channel = (float *) getbytes((MAX_N+2)*sizeof(float));
		x->output = (float *) getbytes(MAX_Nw*sizeof(float));
		x->bitshuffle = (int *) getbytes((MAX_N*2)*sizeof(int));
		x->trigland = (float *) getbytes((MAX_N*2)*sizeof(float));
		x->c_lastphase_in = (float *) getbytes((MAX_N2+1)*sizeof(float));
		x->c_lastphase_out = (float *) getbytes((MAX_N2+1)*sizeof(float));
		x->lastamp = (float *) getbytes((MAX_N+1) * sizeof(float));
		x->lastfreq = (float *) getbytes((MAX_N+1) * sizeof(float));
		x->local_frame = (float *) getbytes((MAX_N+2)*sizeof(float));
		x->loveboat = (float **) getbytes(x->framecount*sizeof(float *));
		

		/* here we stay with old reallocation approach and pray */
		for(i=0;i<x->framecount;i++){
			x->loveboat[i] = (float *) getbytes(((x->N)+2)*sizeof(float));
			if(x->loveboat[i] == NULL){
				error("memory error");
				return;
			}
			memset((char *)x->loveboat[i],0,(x->N+2)*sizeof(float));
		}
	} else if(initialized == 1) {
		//free and allocate
		oldsize = (oldN+2)*sizeof(float);
		for(i = 0; i < last_framecount; i++){
			freebytes(x->loveboat[i],oldsize) ;
		}
		oldsize = last_framecount*sizeof(float *);
		freebytes(x->loveboat,oldsize);
		x->loveboat = (float **) getbytes(x->framecount*sizeof(float *));  
		for(i=0;i<x->framecount;i++){
			x->loveboat[i] = (float *) getbytes((x->N+2)*sizeof(float));
			if(x->loveboat[i] == NULL){
				error("memory error");
				return;
			}
			memset((char *)x->loveboat[i],0,(x->N+2)*sizeof(float));
		}
	}  
	memset((char *)x->input,0,x->Nw * sizeof(float));
	memset((char *)x->output,0,x->Nw * sizeof(float));
	memset((char *)x->c_lastphase_in,0,(x->N2+1) * sizeof(float));
	memset((char *)x->lastamp,0,(x->N+1)*sizeof(float));
	memset((char *)x->lastfreq,0,(x->N+1)*sizeof(float));
	memset((char *)x->bindex,0,(x->N+1)*sizeof(float));
	memset((char *)x->buffer,0,x->N * sizeof(float));
	if(!x->vector_size){
		post("zero vector size - something is really screwed up here!");
		return;
	}
	for ( i = 0; i < x->table_length; i++ ) {
		x->table[i] = (float) x->N * cos((float)i * TWOPI / (float)x->table_length);
	}	
	x->c_fundamental =  (float) x->R/(float)x->N ;
	x->c_factor_in =  (float) x->R/((float)x->vector_size * TWOPI);
	
	if( x->hi_freq < x->c_fundamental ) {
		x->hi_freq = x->topfreq ;
	}
	x->hi_bin = 1;  
	x->curfreq = 0;
	while( x->curfreq < x->hi_freq ) {
		++(x->hi_bin);
		x->curfreq += x->c_fundamental ;
	}
	
	x->lo_bin = 0;  
	x->curfreq = 0;
	while( x->curfreq < x->lo_freq ) {
		++(x->lo_bin);
		x->curfreq += x->c_fundamental ;
	}
	
	if( x->hi_bin > x->N2)
		x->hi_bin = x->N2 ;
	if(x->lo_bin > x->hi_bin)
		x->lo_bin = x->hi_bin;
	
	x->i_vector_size = 1.0/x->vector_size;
	x->pitch_increment = x->P*x->table_length/x->R;
	
	makewindows( x->Hwin, x->Wanal, x->Wsyn, x->Nw, x->N, x->D);
	init_rdft( x->N, x->bitshuffle, x->trigland);

		  
	x->lock = 0;
}
Exemple #11
0
static void assign_param(t_functype ftype,t_iparams *newparam,
			 real old[MAXFORCEPARAM],int comb,double reppow)
{
  int  i,j;
  real tmp;

  /* Set to zero */
  for(j=0; (j<MAXFORCEPARAM); j++) 
    {
      newparam->generic.buf[j]=0.0;
    }
  switch (ftype) {
  case F_G96ANGLES:
    /* Post processing of input data: store cosine iso angle itself */
    newparam->harmonic.rA =cos(old[0]*DEG2RAD);
    newparam->harmonic.krA=old[1];
    newparam->harmonic.rB =cos(old[2]*DEG2RAD);
    newparam->harmonic.krB=old[3];
    break;
  case F_G96BONDS:
    /* Post processing of input data: store square of length itself */
    newparam->harmonic.rA =sqr(old[0]);
    newparam->harmonic.krA=old[1];
    newparam->harmonic.rB =sqr(old[2]);
    newparam->harmonic.krB=old[3];
    break;
  case F_FENEBONDS:
    newparam->fene.bm=old[0];
    newparam->fene.kb=old[1];
    break;
  case F_RESTRBONDS:
    newparam->restraint.lowA = old[0];
    newparam->restraint.up1A = old[1];
    newparam->restraint.up2A = old[2];
    newparam->restraint.kA   = old[3];
    newparam->restraint.lowB = old[4];
    newparam->restraint.up1B = old[5];
    newparam->restraint.up2B = old[6];
    newparam->restraint.kB   = old[7];
    break;
  case F_TABBONDS:
  case F_TABBONDSNC:
  case F_TABANGLES:
  case F_TABDIHS:
    newparam->tab.table = round_check(old[0],0,ftype,"table index");
    newparam->tab.kA    = old[1];
    newparam->tab.kB    = old[3];
    break;
  case F_CROSS_BOND_BONDS:
    newparam->cross_bb.r1e=old[0];
    newparam->cross_bb.r2e=old[1];
    newparam->cross_bb.krr=old[2];
    break;
  case F_CROSS_BOND_ANGLES:
    newparam->cross_ba.r1e=old[0];
    newparam->cross_ba.r2e=old[1];
    newparam->cross_ba.r3e=old[2];
    newparam->cross_ba.krt=old[3];
    break;
  case F_UREY_BRADLEY:
    newparam->u_b.thetaA=old[0];
    newparam->u_b.kthetaA=old[1];
    newparam->u_b.r13A=old[2];
    newparam->u_b.kUBA=old[3];
    newparam->u_b.thetaB=old[4];
    newparam->u_b.kthetaB=old[5];
    newparam->u_b.r13B=old[6];
    newparam->u_b.kUBB=old[7];
    break;
  case F_QUARTIC_ANGLES:
    newparam->qangle.theta=old[0];
    for(i=0; i<5; i++)
      newparam->qangle.c[i]=old[i+1];
    break;
  case F_LINEAR_ANGLES:
    newparam->linangle.aA    = old[0];
    newparam->linangle.klinA = old[1];
    newparam->linangle.aB    = old[2];
    newparam->linangle.klinB = old[3];
    break;
  case F_BONDS:
  case F_ANGLES:
  case F_HARMONIC:
  case F_IDIHS:
    newparam->harmonic.rA =old[0];
    newparam->harmonic.krA=old[1];
    newparam->harmonic.rB =old[2];
    newparam->harmonic.krB=old[3];
    break;
  case F_MORSE:
    newparam->morse.b0A    =old[0];
    newparam->morse.cbA    =old[1];
    newparam->morse.betaA  =old[2];
    newparam->morse.b0B    =old[3];
    newparam->morse.cbB    =old[4];
    newparam->morse.betaB  =old[5];
    break;
  case F_CUBICBONDS:
    newparam->cubic.b0    =old[0];
    newparam->cubic.kb    =old[1];
    newparam->cubic.kcub  =old[2];
    break;
  case F_CONNBONDS:
    break;
  case F_POLARIZATION:
    newparam->polarize.alpha = old[0];
    break;
  case F_ANHARM_POL:
    newparam->anharm_polarize.alpha = old[0];
    newparam->anharm_polarize.drcut = old[1];
    newparam->anharm_polarize.khyp  = old[2];
    break;
  case F_WATER_POL:
    newparam->wpol.al_x   =old[0];
    newparam->wpol.al_y   =old[1];
    newparam->wpol.al_z   =old[2];
    newparam->wpol.rOH    =old[3];
    newparam->wpol.rHH    =old[4];
    newparam->wpol.rOD    =old[5];
    break;
  case F_THOLE_POL:
    newparam->thole.a      = old[0];
    newparam->thole.alpha1 = old[1];
    newparam->thole.alpha2 = old[2];
    if ((old[1] > 0) && (old[2] > 0))
      newparam->thole.rfac = old[0]*pow(old[1]*old[2],-1.0/6.0);
    else
      newparam->thole.rfac = 1;
    break;
  case F_BHAM:
    newparam->bham.a = old[0];
    newparam->bham.b = old[1];
    newparam->bham.c = old[2];
    break;
  case F_LJ14:
    set_ljparams(comb,reppow,old[0],old[1],&newparam->lj14.c6A,&newparam->lj14.c12A);
    set_ljparams(comb,reppow,old[2],old[3],&newparam->lj14.c6B,&newparam->lj14.c12B);
    break;
  case F_LJC14_Q:
    newparam->ljc14.fqq = old[0];
    newparam->ljc14.qi  = old[1];
    newparam->ljc14.qj  = old[2];
    set_ljparams(comb,reppow,old[3],old[4],&newparam->ljc14.c6,&newparam->ljc14.c12);
    break;
  case F_LJC_PAIRS_NB:
    newparam->ljcnb.qi = old[0];
    newparam->ljcnb.qj = old[1];
    set_ljparams(comb,reppow,old[2],old[3],&newparam->ljcnb.c6,&newparam->ljcnb.c12);
    break;
  case F_LJ:
    set_ljparams(comb,reppow,old[0],old[1],&newparam->lj.c6,&newparam->lj.c12);
    break;
  case F_PDIHS:
  case F_PIDIHS:
  case F_ANGRES:
  case F_ANGRESZ:
    newparam->pdihs.phiA = old[0];
    newparam->pdihs.cpA  = old[1];
		  
    /* Dont do any checks if all parameters are zero (such interactions will be removed).
     * Change 20100720: Amber occasionally uses negative multiplicities (mathematically OK),
     * so I have changed the lower limit to -99 /EL
     *
     * Second, if the force constant is zero in both A and B states, we set the phase
     * and multiplicity to zero too so the interaction gets removed during clean-up.
     */	
    newparam->pdihs.phiB = old[3];
    newparam->pdihs.cpB  = old[4];
          
    if( fabs(newparam->pdihs.cpA) < GMX_REAL_MIN && fabs(newparam->pdihs.cpB) < GMX_REAL_MIN )
    {
        newparam->pdihs.phiA = 0.0; 
        newparam->pdihs.phiB = 0.0; 
        newparam->pdihs.mult = 0; 
    } 
    else
    {
        newparam->pdihs.mult = round_check(old[2],-99,ftype,"multiplicity");
    }
          
    break;
  case F_POSRES:
    newparam->posres.fcA[XX]   = old[0];
    newparam->posres.fcA[YY]   = old[1];
    newparam->posres.fcA[ZZ]   = old[2];
    newparam->posres.fcB[XX]   = old[3];
    newparam->posres.fcB[YY]   = old[4];
    newparam->posres.fcB[ZZ]   = old[5];
    newparam->posres.pos0A[XX] = old[6];
    newparam->posres.pos0A[YY] = old[7];
    newparam->posres.pos0A[ZZ] = old[8];
    newparam->posres.pos0B[XX] = old[9];
    newparam->posres.pos0B[YY] = old[10];
    newparam->posres.pos0B[ZZ] = old[11];
    break;
  case F_FBPOSRES:
    newparam->fbposres.geom     = round_check(old[0],0,ftype,"geometry");
    if ( ! (newparam->fbposres.geom > efbposresZERO && newparam->fbposres.geom < efbposresNR))
    {
      gmx_fatal(FARGS,"Invalid geometry for flat-bottomed position restraint.\n"
		"Expected number between 1 and %d. Found %d\n", efbposresNR-1,
		newparam->fbposres.geom);
    }
    newparam->fbposres.r        = old[1];
    newparam->fbposres.k        = old[2];
    newparam->fbposres.pos0[XX] = old[3];
    newparam->fbposres.pos0[YY] = old[4];
    newparam->fbposres.pos0[ZZ] = old[5];
    break;
  case F_DISRES:
    newparam->disres.label = round_check(old[0],0,ftype,"label");
    newparam->disres.type  = round_check(old[1],1,ftype,"type'");
    newparam->disres.low   = old[2];
    newparam->disres.up1   = old[3];
    newparam->disres.up2   = old[4];
    newparam->disres.kfac  = old[5];
    break;
  case F_ORIRES:
    newparam->orires.ex    = round_check(old[0],1,ftype,"experiment") - 1;
    newparam->orires.label = round_check(old[1],1,ftype,"label");
    newparam->orires.power = round_check(old[2],0,ftype,"power");
    newparam->orires.c     = old[3];
    newparam->orires.obs   = old[4];
    newparam->orires.kfac  = old[5];
    break;
  case F_DIHRES:
    newparam->dihres.phiA  = old[0];
    newparam->dihres.dphiA = old[1];
    newparam->dihres.kfacA = old[2];
    newparam->dihres.phiB   = old[3];
    newparam->dihres.dphiB  = old[4];
    newparam->dihres.kfacB  = old[5];
    break;
  case F_RBDIHS:
    for (i=0; (i<NR_RBDIHS); i++) {
      newparam->rbdihs.rbcA[i]=old[i]; 
      newparam->rbdihs.rbcB[i]=old[NR_RBDIHS+i]; 
    }
    break;
  case F_FOURDIHS:
    /* Read the dihedral parameters to temporary arrays,
     * and convert them to the computationally faster
     * Ryckaert-Bellemans form.
     */   
    /* Use conversion formula for OPLS to Ryckaert-Bellemans: */
    newparam->rbdihs.rbcA[0]=old[1]+0.5*(old[0]+old[2]);
    newparam->rbdihs.rbcA[1]=0.5*(3.0*old[2]-old[0]);
    newparam->rbdihs.rbcA[2]=4.0*old[3]-old[1];
    newparam->rbdihs.rbcA[3]=-2.0*old[2];
    newparam->rbdihs.rbcA[4]=-4.0*old[3];
    newparam->rbdihs.rbcA[5]=0.0;

    newparam->rbdihs.rbcB[0]=old[NR_FOURDIHS+1]+0.5*(old[NR_FOURDIHS+0]+old[NR_FOURDIHS+2]);
    newparam->rbdihs.rbcB[1]=0.5*(3.0*old[NR_FOURDIHS+2]-old[NR_FOURDIHS+0]);
    newparam->rbdihs.rbcB[2]=4.0*old[NR_FOURDIHS+3]-old[NR_FOURDIHS+1];
    newparam->rbdihs.rbcB[3]=-2.0*old[NR_FOURDIHS+2];
    newparam->rbdihs.rbcB[4]=-4.0*old[NR_FOURDIHS+3];
    newparam->rbdihs.rbcB[5]=0.0;
    break;    
  case F_CONSTR:
  case F_CONSTRNC:
    newparam->constr.dA = old[0];
    newparam->constr.dB = old[1];
    break;
  case F_SETTLE:
    newparam->settle.doh=old[0];
    newparam->settle.dhh=old[1];
    break;
  case F_VSITE2:
  case F_VSITE3:
  case F_VSITE3FD:
  case F_VSITE3OUT:
  case F_VSITE4FD:
  case F_VSITE4FDN:
    newparam->vsite.a=old[0];
    newparam->vsite.b=old[1];
    newparam->vsite.c=old[2];
    newparam->vsite.d=old[3];
    newparam->vsite.e=old[4];
    newparam->vsite.f=old[5];
    break;
  case F_VSITE3FAD:
    newparam->vsite.a=old[1] * cos(DEG2RAD * old[0]);
    newparam->vsite.b=old[1] * sin(DEG2RAD * old[0]);
    newparam->vsite.c=old[2];
    newparam->vsite.d=old[3];
    newparam->vsite.e=old[4];
    newparam->vsite.f=old[5];
    break;
  case F_VSITEN:
    newparam->vsiten.n = round_check(old[0],1,ftype,"number of atoms");
    newparam->vsiten.a = old[1];
    break;
  case F_CMAP:
    newparam->cmap.cmapA=old[0];
    newparam->cmap.cmapB=old[1];
    break;
  case F_GB12:
  case F_GB13:
  case F_GB14:
    newparam->gb.sar  = old[0];
    newparam->gb.st   = old[1];
    newparam->gb.pi   = old[2];
    newparam->gb.gbr  = old[3];
    newparam->gb.bmlt = old[4];
    break;
  default:
    gmx_fatal(FARGS,"unknown function type %d in %s line %d",
	      ftype,__FILE__,__LINE__);
  }
}
Exemple #12
0
int  HBblocks(char * fname)
{ FILE * f=fopen(fname,"a");
  double tb,sb,cb,alpha,sa,ca,ta,samb,camb,dMb,MbHl,MbSM,MbH,MbH3,Q;
  if(!f) return 1;
  Q=findValW("Q");
  if(slhaDecayExists(pNum("h")) <0)  slhaDecayPrint("h", f);
  if(slhaDecayExists(pNum("H")) <0)  slhaDecayPrint("H", f);
  if(slhaDecayExists(pNum("H3"))<0)  slhaDecayPrint("H3",f);
  if(slhaDecayExists(pNum("t")) <0)  slhaDecayPrint("t", f);
  if(slhaDecayExists(pNum("H+"))<0)  slhaDecayPrint("H+",f);

  tb=findValW("tB");  
    sb=tb/sqrt(1+tb*tb);
    cb=1/sqrt(1+tb*tb);
  alpha=findValW("alpha");
    sa=sin(alpha);
    ca=cos(alpha);
    ta=sa/ca;
    samb=sa*cb-ca*sb;
    camb=ca*cb+sa*sb;
  dMb=findValW("dMb");


  MbSM=findValW("Mb");
  MbH= MbSM/(1+dMb)*(1+dMb*ta/tb);  
  MbH3=MbSM/(1+dMb)*(1-dMb/tb/tb);
  MbHl=MbSM/(1+dMb)*(1-dMb/ta/tb);
 
  fprintf(f,"Block HiggsBoundsInputHiggsCouplingsBosons\n");
  fprintf(f,"# Effective coupling normalised to SM one and squared\n");
  fprintf(f,"# For (*) normalized on Sin(2*W)\n"); 
  fprintf(f," %12.4E  3    25    24    24 # higgs-W-W \n",        SQR(samb)  );
  fprintf(f," %12.4E  3    25    23    23 # higgs-Z-Z \n",        SQR(samb)  );
  fprintf(f," %12.4E  3    25    25    23 # higgs-higgs-Z \n",    0.   );

  { assignVal("Q",pMass("h"));
    calcMainFunc();
    fprintf(f," %12.4E  3    25    21    21 # higgs-gluon-gluon\n",  SQR(findValW("LGGh")/findValW("LGGSM")) );           
    fprintf(f," %12.4E  3    25    22    22 # higgs-gamma-gamma\n",  SQR(findValW("LAAh")/findValW("LAASM")) );
  }                          
 
  fprintf(f," %12.4E  3    35    24    24 # higgs-W-W \n",        SQR(camb)  );
  fprintf(f," %12.4E  3    35    23    23 # higgs-Z-Z \n",        SQR(camb)  );
  fprintf(f," %12.4E  3    35    25    23 # higgs-higgs-Z \n",    0.  );
  fprintf(f," %12.4E  3    35    35    23 # higgs-higgs-Z \n",    0.  );
  
  
  { assignVal("Q",pMass("H"));
    calcMainFunc();
    fprintf(f," %12.4E  3    35    21    21 # higgs-gluon-gluon\n",SQR(findValW("LGGH")/findValW("LGGSM"))  );   
    fprintf(f," %12.4E  3    35    22    22 # higgs-gamma-gamma\n",SQR(findValW("LAAH")/findValW("LAASM"))  );
  }
  

  fprintf(f," %12.4E  3    36    24    24 # higgs-W-W \n",        0.  );
  fprintf(f," %12.4E  3    36    23    23 # higgs-Z-Z \n",        0.  );
  
  { assignVal("Q",pMass("H3"));
    calcMainFunc();
    fprintf(f," %12.4E  3    36    21    21 # higgs-gluon-gluon\n",SQR(findValW("LGGH3")/2/findValW("LGGSM")) );
    fprintf(f," %12.4E  3    36    22    22 # higgs-gamma-gamma\n",SQR(findValW("LAAH3")/2/findValW("LAASM")) );             
  }
  
  fprintf(f," %12.4E  3    36    25    23 #*higgs-higgs-Z \n",    SQR(camb)  );
  fprintf(f," %12.4E  3    36    35    23 #*higgs-higgs-Z \n",    SQR(samb)  );
  fprintf(f," %12.4E  3    36    36    23 #* higgs-higgs-Z \n",   0.  );

  fprintf(f,"Block HiggsBoundsInputHiggsCouplingsFermions\n");
  fprintf(f,"# Effective coupling normalised to SM one and squared\n");
  fprintf(f," %12.4E   %12.4E   3    25     5    5 # higgs-b-b \n"    ,SQR((sa/cb)*(MbHl/MbSM)),0.);
  fprintf(f," %12.4E   %12.4E   3    25     6    6 # higgs-top-top \n",SQR(ca/sb)              ,0.);
  fprintf(f," %12.4E   %12.4E   3    25    15   15 # higgs-tau-tau \n",SQR(sa/cb)              ,0.);

  fprintf(f," %12.4E   %12.4E   3    35     5    5 # higgs-b-b \n"    ,SQR((ca/cb)*(MbH/MbSM))  ,0.);
  fprintf(f," %12.4E   %12.4E   3    35     6    6 # higgs-top-top \n",SQR(sa/sb)              ,0.);  
  fprintf(f," %12.4E   %12.4E   3    35    15   15 # higgs-tau-tau \n",SQR(ca/cb)  ,0.);

  fprintf(f," %12.4E   %12.4E   3    36     5    5 # higgs-b-b \n"    ,0.,SQR(tb*(MbH3/MbSM)));
  fprintf(f," %12.4E   %12.4E   3    36     6    6 # higgs-top-top \n",0.,SQR(1/tb)          );
  fprintf(f," %12.4E   %12.4E   3    36    15   15 # higgs-tau-tau \n",0.,SQR(tb)            );
  
  assignValW("Q",Q);
  calcMainFunc();    
  fclose(f);
   
  return 0;
}
Exemple #13
0
/*
  Program to test polygon functionality
*/
int main(int argc, char *argv[]) {
  Image *src;
  const int rows = 300;
  const int cols = 400;
  Polygon *p;
  Color Red;
  Color Orange;
  Color White;
  Color Blue;
  Point pt[100];
  int i;
  
  srand(42);

  color_set(&Red, 0.9, 0.2, 0.1 );
  color_set(&Orange, 0.95, 0.7, 0.3 );
  color_set(&White, 1.0, 1.0, 1.0 );
  color_set(&Blue, 0.2, 0.1, 0.95 );

  src = image_create(rows, cols);

  // make a simple square to test proper areas and locations
  // the square ought to be 20x20, include pixel (30,30) and exclude pixel (50, 50)
  point_set2D(&(pt[0]), 30, 30);
  point_set2D(&(pt[1]), 50, 30);
  point_set2D(&(pt[2]), 50, 50);
  point_set2D(&(pt[3]), 30, 50);

  p = polygon_createp(4, pt);

  printf("drawing a square\n");
  polygon_drawFill(p, src, Blue);

  // something more interesting
  for(i=0;i<50;i++) {
    float dr = rand() % 20;
    point_set2D(&(pt[i]), 
    200 + cos((float)i * M_PI * 2.0 / 50.0)*(70 + dr),
    150 + sin((float)i * M_PI * 2.0 / 50.0)*(70 + dr));
  }
  polygon_set(p, 50, pt);

  printf("drawing first big polygon\n");
  polygon_drawFill(p, src, Red);

  for(i=0;i<50;i++) {
    float dr = rand() % 15;
    point_set2D(&(pt[i]), 
    200 + cos((float)i * M_PI * 2.0 / 50.0)*(50 + dr),
    150 + sin((float)i * M_PI * 2.0 / 50.0)*(50 + dr));
  }
  polygon_set(p, 50, pt);

  printf("drawing second big polygon\n");
  polygon_drawFill(p, src, Orange);

  for(i=0;i<50;i++) {
    float dr = rand() % 10;
    point_set2D(&(pt[i]), 
    200 + cos((float)i * M_PI * 2.0 / 50.0)*(30 + dr),
    150 + sin((float)i * M_PI * 2.0 / 50.0)*(30 + dr));
  }
  polygon_set(p, 50, pt);

  printf("drawing third big polygon\n");
  polygon_drawFill(p, src, White);

  printf("writing output\n");
  image_write(src, "test4a.ppm");

  image_free(src);

  return(0);
}
Exemple #14
0
static void *SpVali_RayPath_Thread(void *tid_p)
{
	size_t tid = *((size_t *)tid_p);
	Zone *zp, *zone;
	SpPhys *pp, *zone_pp;
	size_t i, plane, izone;
	GeRay ray;
	double r, theta, phi, t;
	gsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlux);

	gsl_rng_set(rng, (unsigned long)time(NULL));

	for(izone = 0, zone = Zone_GetMinLeaf(v_raypath_model.grid); zone; izone++, zone = Zone_AscendTree(zone)) {
		zone_pp = zone->data;

		/* Skip empty and non-leaf zones */
		if(!zone_pp->non_empty_leaf)
			continue;

		if((izone % Sp_MPISIZE) != Sp_MPIRANK)
			continue;
			
		if(((izone / Sp_MPISIZE) % Sp_NTHREAD) != tid)
			continue;

		#define NRAY 5000

		/* This samples a random number uniformly in the
		 * interval [0, 1) */
		#define RAND()\
			gsl_rng_uniform(rng)
		/* This samples a random number uniformly in the
		 * interval (0, 1) */
		#define PRAND()\
			gsl_rng_uniform_pos(rng)

		for(i = 0; i < NRAY; i++) {
			if(1) {
				ray = GeRay_Rand(rng, &zone->voxel);
			}
			else {
				Mem_BZERO(&ray);

				/* Init random ray origin */
				ray.e = zone->voxel.cen;
				r = GeRay_E(ray, 0);
				theta = PRAND() * PI;
				phi = RAND() * TWOPI;

				/* Convert to rectangular coordinates */
				GeRay_E(ray, 0) = r * sin(theta) * cos(phi);
				GeRay_E(ray, 1) = r * sin(theta) * sin(phi);
				GeRay_E(ray, 2) = r * cos(theta);

				/* Set random ray direction: first obtain direction in spherical
				 * coordinates then convert to rectangular coordinates */

				/* theta must be sampled with PRAND() or there may be a
				 * bias towards the theta=0 direction */
				theta = asin(2.0 * RAND() - 1.0) + 0.5 * PI;

				/* phi must be sampled with RAND() to avoid insufficient
				 * samples in the phi=0 direction */
				phi = PRAND() * TWOPI;

				/* Convert to rectangular coordinates */
				GeRay_D(ray, 0) = sin(theta) * cos(phi);
				GeRay_D(ray, 1) = sin(theta) * sin(phi);
				GeRay_D(ray, 2) = cos(theta);
			}

			zp = zone;

			/* Calculate radiative transfer along this direction */
			/* Propagate the ray through the cloud until we've
			 * reached the edge */
			while(zp) {
				/* Calculate path to next boundary */
				GeRay_TraverseVoxel(&ray, &zp->voxel, &t, &plane);

				/* Pointer to physical parameters associated with this zone */
				pp = zp->data;

				/* Do radiative transfer only if there are molecules in
				 * this zone */
				if(pp->non_empty_leaf) {
					zone_pp->ds += t;
				}

				/* Propagate ray to next position */
				ray = GeRay_Inc(&ray, t);

				/* Get next zone to traverse to */
				zp = Zone_GetNext(zp, plane, &ray);
			}
		}
		zone_pp->ds /= (double)NRAY;
	}

	return NULL;
}
Exemple #15
0
// Generates a normal random variable with 
// zero mean and stddev s
double gaussian_rand(double s)
{
  double U1 = uniform_rand(1);
  double U2 = uniform_rand(1);
  return s*sqrt(-2*log(U1))*cos(2*PI*U2);
}
Exemple #16
0
void	FPSCamera::Update( float _DeltaTime, float _TranslationSpeed, float _RotationSpeed, float _SpeedBoostWithShift )
{

	//////////////////////////////////////////////////////////////////////////
	// Handle mouse manipulation
	//
	if ( gs_WindowInfos.Events.Mouse.dbuttons[0] > 0 )
	{	// Button down
		SetCapture( gs_WindowInfos.hWnd );

		m_ButtonDownMouseX = gs_WindowInfos.Events.Mouse.x;
		m_ButtonDownMouseY = gs_WindowInfos.Events.Mouse.y;
		m_ButtonDownPosition = m_Position;
		m_ButtonDownTarget = m_Target;
	}
	else if ( gs_WindowInfos.Events.Mouse.dbuttons[0] < 0 )
	{	// Button up
		ReleaseCapture();
	}

	if ( gs_WindowInfos.Events.Mouse.buttons[0] != 0 )
	{
		int		MouseDx = gs_WindowInfos.Events.Mouse.x - m_ButtonDownMouseX;
		int		MouseDy = gs_WindowInfos.Events.Mouse.y - m_ButtonDownMouseY;
		float	DAngleX = (_RotationSpeed * TWOPI) * MouseDx / RESX;
		float	DAngleY = (_RotationSpeed * PI) * MouseDy / RESY;

		float3	At = m_ButtonDownTarget - m_ButtonDownPosition;
		float		Distance2Target = At.Length();
		At = At / Distance2Target;

		float	Theta = asinf( At.y );
		float	Phi = atan2f( At.x, At.z );

		Theta = CLAMP( Theta - DAngleY, -0.99f * HALFPI, +0.99f * HALFPI );	// Never completly up or down to avoid gimbal lock
		Phi -= DAngleX;

		float3	NewAt( sinf(Phi)*cosf(Theta), sinf(Theta), cosf(Phi)*cos(Theta) );

		m_Target = m_Position + Distance2Target * NewAt;

// 		Vector3	Euler = GetEuler( m_ButtonDownTransform );
// 		Matrix	CamRotYMatrix = Matrix.RotationY( fAngleY + Euler.Y );
// 		Matrix	CamRotXMatrix = Matrix.RotationX( fAngleX + Euler.X );
// 		Matrix	CamRotZMatrix = Matrix.RotationZ( Euler.Z );
// 
// 		Matrix	RotateMatrix = CamRotXMatrix * CamRotYMatrix * CamRotZMatrix;
	}

	float3	At = (m_Target - m_Position).Normalize();
	float3	Right = At.Cross( m_Up ).Normalize();
	float3	Up = Right.Cross( At );

	//////////////////////////////////////////////////////////////////////////
	// Handle keyboard manipulation
	//
	float		Speed = _DeltaTime * _TranslationSpeed;
	if ( gs_WindowInfos.Events.Keyboard.State[KEY_LSHIFT] )
		Speed *= _SpeedBoostWithShift;

	float3	Delta = float3::Zero;
	if ( gs_WindowInfos.pKeys['Q'] )
	{	// Strafe left
		Delta = Delta - Speed * Right;
	}
	if ( gs_WindowInfos.pKeys['D'] )
	{	// Strafe right
		Delta = Delta + Speed * Right;
	}
	if ( gs_WindowInfos.pKeys['Z'] )
	{	// Forward
		Delta = Delta + Speed * At;
	}
	if ( gs_WindowInfos.pKeys['S'] )
	{	// Backward
		Delta = Delta - Speed * At;
	}
	if ( gs_WindowInfos.pKeys[' '] )
	{	// Up
		Delta = Delta + Speed * Up;
	}
	if ( gs_WindowInfos.Events.Keyboard.State[KEY_LCONTROL] )
	{	// Down
		Delta = Delta - Speed * Up;
	}

	m_Position = m_Position + Delta;
	m_Target = m_Target + Delta;

	//////////////////////////////////////////////////////////////////////////
	// Rebuild camera matrix
	m_Camera.LookAt( m_Position, m_Target, m_Up );
}
Exemple #17
0
void Mist::createRing(float x, float y, float radius, float width) {
  offsets.push_back(vertices.size());

  float resolution = 60.0;
  float angle = TWO_PI/resolution;
  float outer_radius = radius + width;

  for(int i = 0; i < resolution; ++i) {
    float c0 = cos( (i + 0) * angle);
    float s0 = sin( (i + 0) * angle);
    float c1 = cos( (i + 1) * angle);
    float s1 = sin( (i + 1) * angle);
    
    // positions
    vec3 pa(c0 * radius, s0 * radius, 0.0f);
    vec3 pb(c1 * radius, s1 * radius, 0.0f);
    vec3 pc(c1 * outer_radius, s1 * outer_radius, 0.0f);
    vec3 pd(c0 * outer_radius, s0 * outer_radius, 0.0f);

    // texcoords
    float u0 = float(i+0)/resolution;
    float u1 = float(i+1)/resolution;
    vec3 ta(u0, 0.0f, 1.0f);
    vec3 tb(u1, 0.0f, 1.0f);
    vec3 tc(u1, 1.0f, 1.0f);
    vec3 td(u0, 1.0f, 1.0f);

    // calculate distances from the corners to the centers
    vec3 intersection;
    if(!intersect(pa, pc, pb, pd, intersection)) {
      printf("The vertices of the dist do not intersect. Error.\n");
      ::exit(EXIT_FAILURE);
    }

    float d0 = length(pa - intersection);
    float d1 = length(pb - intersection);
    float d2 = length(pc - intersection);
    float d3 = length(pd - intersection);

    ta = ta * ((d0 + d2)/d2);
    tb = tb * ((d1 + d3)/d3);
    tc = tc * ((d2 + d0)/d0);
    td = td * ((d3 + d1)/d1);

    // store the vertices
    VertexPT3 a(pa,ta);
    VertexPT3 b(pb,tb);
    VertexPT3 c(pc,tc);
    VertexPT3 d(pd,td);

    vertices.push_back(a);
    vertices.push_back(b);
    vertices.push_back(c);

    vertices.push_back(a);
    vertices.push_back(c);
    vertices.push_back(d);
  }

  counts.push_back(vertices.size()-offsets.back());
  needs_update = true;
}
void KisMaskGenerator::init()
{
    d->cs = cos(- 2 * M_PI / d->spikes);
    d->ss = sin(- 2 * M_PI / d->spikes);
    d->empty = (d->ratio == 0.0 || d->diameter == 0.0);
}
Exemple #19
0
double f(double x)
{
	return cos(log(x));
}
Exemple #20
0
	double
mayr_kernel(double x, void * n) {
	return (pow(cos(x), *(double*)n));
}
Foam::sixDoFRigidBodyMotionSolver::sixDoFRigidBodyMotionSolver
(
    const polyMesh& mesh,
    const dictionary& dict
)
:
    displacementMotionSolver(mesh, dict, typeName),
    motion_
    (
        coeffDict(),
        IOobject
        (
            "sixDoFRigidBodyMotionState",
            mesh.time().timeName(),
            "uniform",
            mesh
        ).typeHeaderOk<IOdictionary>(true)
      ? IOdictionary
        (
            IOobject
            (
                "sixDoFRigidBodyMotionState",
                mesh.time().timeName(),
                "uniform",
                mesh,
                IOobject::READ_IF_PRESENT,
                IOobject::NO_WRITE,
                false
            )
        )
      : coeffDict()
    ),
    patches_(wordReList(coeffDict().lookup("patches"))),
    patchSet_(mesh.boundaryMesh().patchSet(patches_)),
    di_(readScalar(coeffDict().lookup("innerDistance"))),
    do_(readScalar(coeffDict().lookup("outerDistance"))),
    test_(coeffDict().lookupOrDefault<Switch>("test", false)),
    rhoInf_(1.0),
    rhoName_(coeffDict().lookupOrDefault<word>("rho", "rho")),
    scale_
    (
        IOobject
        (
            "motionScale",
            mesh.time().timeName(),
            mesh,
            IOobject::NO_READ,
            IOobject::NO_WRITE,
            false
        ),
        pointMesh::New(mesh),
        dimensionedScalar(dimless, 0)
    ),
    curTimeIndex_(-1)
{
    if (rhoName_ == "rhoInf")
    {
        rhoInf_ = readScalar(coeffDict().lookup("rhoInf"));
    }

    // Calculate scaling factor everywhere
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    {
        const pointMesh& pMesh = pointMesh::New(mesh);

        pointPatchDist pDist(pMesh, patchSet_, points0());

        // Scaling: 1 up to di then linear down to 0 at do away from patches
        scale_.primitiveFieldRef() =
            min
            (
                max
                (
                    (do_ - pDist.primitiveField())/(do_ - di_),
                    scalar(0)
                ),
                scalar(1)
            );

        // Convert the scale function to a cosine
        scale_.primitiveFieldRef() =
            min
            (
                max
                (
                    0.5
                  - 0.5
                   *cos(scale_.primitiveField()
                   *Foam::constant::mathematical::pi),
                    scalar(0)
                ),
                scalar(1)
            );

        pointConstraints::New(pMesh).constrain(scale_);
        scale_.write();
    }
}
void RV_Orientation::DrawArrow(oapi::Sketchpad *skp, bool fill, bool straight, int x, int y, int scale, VECTOR3 drot) {
  const int si = scale / 4;
  const double s = (double) si;
  int ptn = 12;
  VECTOR3 rot = {drot.x*PI/180,drot.y*PI/180,drot.z*PI/180};
  const VECTOR3 e = {0,0,500};
  VECTOR3 pt[24];
  const VECTOR3 straightArrow[8] = {
      {   s, -2*s, 0},
      {   s, -6*s, 0},
      { 4*s, -6*s, 0},
      {   0,-10*s, 0},
      {-4*s, -6*s, 0},
      {-1*s, -6*s, 0},
      {  -s, -2*s, 0},
      {   s, -2*s, 0}
  };
  const VECTOR3 curveArrow[24] = {
      {-1.000*s, -2.000*s, 0},
      {-1.076*s, -2.868*s, 0},
      {-1.302*s, -3.710*s, 0},
      {-1.670*s, -4.500*s, 0},
      {-2.170*s, -5.214*s, 0},
      {-2.786*s, -5.830*s, 0},
      {-3.500*s, -6.330*s, 0},
      {-4.290*s, -6.698*s, 0},
      {-5.132*s, -6.924*s, 0},
      {-6.000*s, -7.000*s, 0},
      {-6.000*s, -10.000*s, 0},
      {-8.000*s, -6.000*s, 0},
      {-6.000*s, -2.000*s, 0},
      {-6.000*s, -5.000*s, 0},
      {-5.479*s, -4.954*s, 0},
      {-4.974*s, -4.819*s, 0},
      {-4.500*s, -4.598*s, 0},
      {-4.072*s, -4.298*s, 0},
      {-3.702*s, -3.928*s, 0},
      {-3.402*s, -3.500*s, 0},
      {-3.181*s, -3.026*s, 0},
      {-3.046*s, -2.521*s, 0},
      {-3.000*s, -2.000*s, 0},
      {-1.000*s, -2.000*s, 0}
  };

  if (straight) {
    ptn=8;
    for (int i=0;i<ptn;i++) pt[i] = straightArrow[i];
  } else {
    ptn=24;
    for (int i=0;i<ptn;i++) pt[i] = curveArrow[i];
  }

  oapi::IVECTOR2 rpt[24];

  const MATRIX3 Xrot = {1,0,0,0,cos(rot.x),-sin(rot.x),0,sin(rot.x),cos(rot.x)};
  const MATRIX3 Yrot = {cos(rot.y),0,sin(rot.y),0,1,0,-sin(rot.y),0,cos(rot.y)};
  const MATRIX3 Zrot = {cos(rot.z),-sin(rot.z),0,sin(rot.z),cos(rot.z),0,0,0,1};
  const MATRIX3 Trot = mul(Xrot,mul(Yrot,Zrot));

  for (int i=0; i<ptn; i++) {
//    pt[i] = mul(Zrot,pt[i]);
//    pt[i] = mul(Yrot,pt[i]);
//    pt[i] = mul(Xrot,pt[i]);
    pt[i] = mul(Trot,pt[i]);
    rpt[i].x = (long) ((pt[i].x - e.x) * ((e.z - pt[i].z)/e.z) + x);
    rpt[i].y = (long) ((pt[i].y - e.y) * ((e.z - pt[i].z)/e.z) + y);
  }
 
  if (fill) {
    skp->Polygon(rpt,ptn); 
  } else {
    skp->Polyline(rpt,ptn); 
  }
  return;
}
bool ModelClass::LoadCylinder(float Radius, float Height, int numRSlice, int numVSlice, float texScale)
{
	m_vertexCount = 6 * ((numRSlice+1) * (numVSlice+1)) + 6 * (numRSlice);
	m_indexCount = m_vertexCount;
	
	ModelType** side = new ModelType*[numVSlice+1];
	if(!side)
	{
		return false;
	}
	ModelType* top = new ModelType[numRSlice + 1];
	if(!top)
	{
		return false;
	}
	ModelType* bottom = new ModelType[numRSlice + 1];
	if(!bottom)
	{
		return false;
	}

	int index = 0;
	float ang, hAct;
	float x, z;
	float u, v;
	int h1, a1;

	// Create temporary points for the side

	for (int h = 0; h <= numVSlice; h++)
	{
		side[h] = new ModelType[numRSlice+1];
		for (int a = 0; a <= numRSlice; a++)
		{
			ang = (float)a * 2 * D3DX_PI / numRSlice;
			hAct = h * Height / numVSlice;
			side[h][a].x = Radius * cos(ang);
			side[h][a].y = hAct;
			side[h][a].z = Radius * sin(ang);
			side[h][a].tu = ang / (2*D3DX_PI) * texScale;
			side[h][a].tv = (Height - hAct) / Height * texScale;
			side[h][a].nx = cos(ang);
			side[h][a].ny = 0;
			side[h][a].nz = sin(ang);
			side[h][a].bx = -sin(ang);
			side[h][a].by = 0;
			side[h][a].bz = cos(ang);
			side[h][a].tx = 0;
			side[h][a].ty = -1;
			side[h][a].tx = 0;
		}
	}
	
	// Create temporary points on the top and bottom caps

	for (int a = 0; a < numRSlice; a++)
	{
		ang = (float)a * 2 * D3DX_PI / numRSlice;
		x = Radius * cos(ang);
		z = Radius * sin(ang);
		u = (cos(ang) + 1) * .5f;
		v = (sin(ang) + 1) * .5f;
		
		top[index].x = x;
		top[index].y = Height;
		top[index].z = z;
		top[index].tu = u * texScale;
		top[index].tv = v * texScale;
		top[index].bx = 1.0f;
		top[index].by = 0.0f;
		top[index].bz = 0.0f;
		top[index].tx = 0.0f;
		top[index].ty = 0.0f;
		top[index].tz = 1.0f;

		bottom[index].x = x;
		bottom[index].y = 0;
		bottom[index].z = z;
		bottom[index].tu = u * texScale;
		bottom[index++].tv = v * texScale;
		bottom[index].bx = 0.0f;
		bottom[index].by = 0.0f;
		bottom[index].bz = 1.0f;
		bottom[index].tx = 1.0f;
		bottom[index].ty = 0.0f;
		bottom[index].tz = 0.0f;
	}

	top[index].x = 0;
	top[index].y = Height;
	top[index].z = 0;

	top[index].tu = .5f * texScale;
	top[index].tv = .5f * texScale;

	bottom[index].x = 0;
	bottom[index].y = 0;
	bottom[index].z = 0;

	bottom[index].tu = .5f * texScale;
	bottom[index].tv = .5f * texScale;



	// Fill in actual vertices

	m_model = new ModelType[m_vertexCount];
	if(!m_model)
	{
		return false;
	}

	index = 0;

	for (int h = 0; h < numVSlice; h++)
	{
		for (int a = 0; a < numRSlice; a++)
		{
			h1 = h+1;
			a1 = a+1;
			// first triangle
			m_model[index].x = side[h][a].x;
			m_model[index].y = side[h][a].y - Height * .5f;
			m_model[index].z = side[h][a].z;
			m_model[index].tu = side[h][a].tu;
			m_model[index].tv = side[h][a].tv;
			m_model[index].nx = side[h][a].nx;
			m_model[index].ny = side[h][a].ny;
			m_model[index].nz = side[h][a].nz;
			m_model[index].tx = side[h][a].tx;
			m_model[index].ty = side[h][a].ty;
			m_model[index].tz = side[h][a].tz;
			m_model[index].bx = side[h][a].by;
			m_model[index].by = side[h][a].by;
			m_model[index++].bz = side[h][a].bz;

			m_model[index].x = side[h1][a1].x;
			m_model[index].y = side[h1][a1].y - Height * .5f;
			m_model[index].z = side[h1][a1].z;
			m_model[index].tu = side[h1][a1].tu;
			m_model[index].tv = side[h1][a1].tv;
			m_model[index].nx = side[h1][a1].nx;
			m_model[index].ny = side[h1][a1].ny;
			m_model[index].nz = side[h1][a1].nz;
			m_model[index].tx = side[h1][a1].tx;
			m_model[index].ty = side[h1][a1].ty;
			m_model[index].tz = side[h1][a1].tz;
			m_model[index].bx = side[h1][a1].by;
			m_model[index].by = side[h1][a1].by;
			m_model[index++].bz = side[h1][a1].bz;

			m_model[index].x = side[h][a1].x;
			m_model[index].y = side[h][a1].y - Height * .5f;
			m_model[index].z = side[h][a1].z;
			m_model[index].tu = side[h][a1].tu;
			m_model[index].tv = side[h][a1].tv;
			m_model[index].nx = side[h][a1].nx;
			m_model[index].ny = side[h][a1].ny;
			m_model[index].nz = side[h][a1].nz;
			m_model[index].tx = side[h][a1].tx;
			m_model[index].ty = side[h][a1].ty;
			m_model[index].tz = side[h][a1].tz;
			m_model[index].bx = side[h][a1].by;
			m_model[index].by = side[h][a1].by;
			m_model[index++].bz = side[h][a1].bz;

			// second triangle
			m_model[index].x = side[h][a].x;
			m_model[index].y = side[h][a].y - Height * .5f;
			m_model[index].z = side[h][a].z;
			m_model[index].tu = side[h][a].tu;
			m_model[index].tv = side[h][a].tv;
			m_model[index].nx = side[h][a].nx;
			m_model[index].ny = side[h][a].ny;
			m_model[index].nz = side[h][a].nz;
			m_model[index].tx = side[h][a].tx;
			m_model[index].ty = side[h][a].ty;
			m_model[index].tz = side[h][a].tz;
			m_model[index].bx = side[h][a].by;
			m_model[index].by = side[h][a].by;
			m_model[index++].bz = side[h][a].bz;

			m_model[index].x = side[h1][a].x;
			m_model[index].y = side[h1][a].y - Height * .5f;
			m_model[index].z = side[h1][a].z;
			m_model[index].tu = side[h1][a].tu;
			m_model[index].tv = side[h1][a].tv;
			m_model[index].nx = side[h1][a].nx;
			m_model[index].ny = side[h1][a].ny;
			m_model[index].nz = side[h1][a].nz;
			m_model[index].tx = side[h1][a].tx;
			m_model[index].ty = side[h1][a].ty;
			m_model[index].tz = side[h1][a].tz;
			m_model[index].bx = side[h1][a].by;
			m_model[index].by = side[h1][a].by;
			m_model[index++].bz = side[h1][a].bz;

			m_model[index].x = side[h1][a1].x;
			m_model[index].y = side[h1][a1].y - Height * .5f;
			m_model[index].z = side[h1][a1].z;
			m_model[index].tu = side[h1][a1].tu;
			m_model[index].tv = side[h1][a1].tv;
			m_model[index].nx = side[h1][a1].nx;
			m_model[index].ny = side[h1][a1].ny;
			m_model[index].nz = side[h1][a1].nz;
			m_model[index].tx = side[h1][a1].tx;
			m_model[index].ty = side[h1][a1].ty;
			m_model[index].tz = side[h1][a1].tz;
			m_model[index].bx = side[h1][a1].by;
			m_model[index].by = side[h1][a1].by;
			m_model[index++].bz = side[h1][a1].bz;
		}
	}

	// fill the top and bottom caps

	for(int i=0; i<numRSlice; i++)
	{
		// one from the top	
		m_model[index].x = top[i].x;
		m_model[index].y = top[i].y - Height * .5f;
		m_model[index].z = top[i].z;
		m_model[index].tu = top[i].tu;
		m_model[index].tv = top[i].tv;
		m_model[index].nx = 0.0f;
		m_model[index].ny = 1.0f;
		m_model[index].nz = 0.0f;
		m_model[index].tx = 0.0f;
		m_model[index].ty = 0.0f;
		m_model[index].tz = 1.0f;
		m_model[index].bx = 1.0f;
		m_model[index].by = 0.0f;
		m_model[index++].bz = 0.0f;

		m_model[index].x = top[numRSlice].x;
		m_model[index].y = top[numRSlice].y - Height * .5f;
		m_model[index].z = top[numRSlice].z;
		m_model[index].tu = top[numRSlice].tu;
		m_model[index].tv = top[numRSlice].tv;
		m_model[index].nx = 0.0f;
		m_model[index].ny = 1.0f;
		m_model[index].nz = 0.0f;
		m_model[index].tx = 0.0f;
		m_model[index].ty = 0.0f;
		m_model[index].tz = 1.0f;
		m_model[index].bx = 1.0f;
		m_model[index].by = 0.0f;
		m_model[index++].bz = 0.0f;

		m_model[index].x = top[(i + 1)%numRSlice].x;
		m_model[index].y = top[(i + 1)%numRSlice].y - Height * .5f;
		m_model[index].z = top[(i + 1)%numRSlice].z;
		m_model[index].tu = top[(i + 1)%numRSlice].tu;
		m_model[index].tv = top[(i + 1)%numRSlice].tv;
		m_model[index].nx = 0.0f;
		m_model[index].ny = 1.0f;
		m_model[index].nz = 0.0f;
		m_model[index].tx = 0.0f;
		m_model[index].ty = 0.0f;
		m_model[index].tz = 1.0f;
		m_model[index].bx = 1.0f;
		m_model[index].by = 0.0f;
		m_model[index++].bz = 0.0f;
		
		//one from the bottom
		m_model[index].x = bottom[i].x;
		m_model[index].y = bottom[i].y - Height * .5f;
		m_model[index].z = bottom[i].z;
		m_model[index].tu = bottom[i].tu;
		m_model[index].tv = bottom[i].tv;
		m_model[index].nx = 0.0f;
		m_model[index].ny = -1.0f;
		m_model[index++].nz = 0.0f;

		
		m_model[index].x = bottom[(i + 1)%numRSlice].x;
		m_model[index].y = bottom[(i + 1)%numRSlice].y - Height * .5f;
		m_model[index].z = bottom[(i + 1)%numRSlice].z;
		m_model[index].tu = bottom[(i + 1)%numRSlice].tu;
		m_model[index].tv = bottom[(i + 1)%numRSlice].tv;
		m_model[index].nx = 0.0f;
		m_model[index].ny = -1.0f;
		m_model[index++].nz = 0.0f;

		m_model[index].x = bottom[numRSlice].x;
		m_model[index].y = bottom[numRSlice].y - Height * .5f;
		m_model[index].z = bottom[numRSlice].z;
		m_model[index].tu = bottom[numRSlice].tu;
		m_model[index].tv = bottom[numRSlice].tv;		
		m_model[index].nx = 0.0f;
		m_model[index].ny = -1.0f;
		m_model[index++].nz = 0.0f;
	}


	//if(!CalculateBNT())
	//{
	//	return false;
	//}

	// Clean up
	for(int i=0; i<numVSlice; i++)
	{
		delete [] side[i];
		side[i] = 0;
	}
	delete [] side;
	side = 0;

	delete[] top;
	top = 0;

	delete[] bottom;
	bottom = 0;

	return true;
}
Exemple #24
0
std::vector<cv::Point> Ask_Circle(cv::Mat &src_im, cv::Point center, cv::Mat &draw_im){
    //src_im    ->  入力画像(2値価画像
    //center    ->  求める円の中心
    //draw_im   ->  描画用の画像

    // ラベリング
    cv::Mat label, state, centroids;
    int nLabels = cv::connectedComponentsWithStats(~src_im, label, state, centroids, 8);

    // 中心座標を含んだ外周を求める
    cv::Mat dst = cv::Mat::zeros(src_im.rows, src_im.cols, CV_8UC1);

    int a = 0;

    for(int i = 1; i < nLabels; i++){
        int l = state.at<int>(i, cv::CC_STAT_LEFT);
        int r = l + state.at<int>(i, cv::CC_STAT_WIDTH);
        int t = state.at<int>(i, cv::CC_STAT_TOP);
        int u = t + state.at<int>(i, cv::CC_STAT_HEIGHT);

        if(l < center.x && center.x < r && t < center.y && center.y < u){
            a++;
            if(a > 0) {
                cv::Point point = RasterScan(label, i);
                Ask_Perimeter(label, i, point, 2, dst);   //周囲辺を描画
                break;
            }
        }
    }

    cv::namedWindow("testdao", CV_WINDOW_AUTOSIZE);
    cv::imshow("testdao", org);

    // スターバースト(もどき)
    std::vector<cv::Point> iris_age;
    int min_rad = Ask_Minimum_rad(center, cv::Point(src_im.cols, src_im.rows));

    for(int theta = -50; theta <= 50; theta++){
        bool l_flg = false, r_flg = false;
        int  l_rad = 0, r_rad = 0;

        for(int rad = 1; rad < min_rad; rad++){
            int x = (int)(center.x + rad * cos(theta * (CV_PI/180)));
            int y = (int)(center.y + rad * sin(theta * (CV_PI/180)));
            int x2 = (int)(center.x - rad * cos(theta * (CV_PI/180)));
            int y2 = (int)(center.y - rad * sin(theta * (CV_PI/180)));

            if(dst.data[ y * dst.step + x * dst.elemSize()] == 200 && !r_flg){
                r_rad = rad;
                r_flg = true;
            }

            if(dst.data[ y2 * dst.step + x2 * dst.elemSize()] == 200 && !l_flg){
                l_rad = rad;
                l_flg = true;
            }

            if(r_flg && l_flg){
                //if(abs(l_rad-r_rad) < 15){
                if(r_rad > 115 && l_rad > 115){
                    x = (int)(center.x + r_rad * cos(theta * (CV_PI/180)));
                    y = (int)(center.y + r_rad * sin(theta * (CV_PI/180)));
                    x2 = (int)(center.x - l_rad * cos(theta * (CV_PI/180)));
                    y2 = (int)(center.y - l_rad * sin(theta * (CV_PI/180)));
                    iris_age.push_back(cv::Point(x,y));
                    iris_age.push_back(cv::Point(x2,y2));
                    if(&draw_im != (cv::Mat *)nullptr){
                        //cv::line(draw_im, center, cv::Point(x,y), CV_RGB(200, 0, 0));
                        //cv::line(draw_im, center, cv::Point(x2,y2), CV_RGB(200, 0, 0));
                    }
                //std::cout << r_rad << ", " << l_rad << std::endl;
                }
                break;
            }
        }
    }

    //cv::RotatedRect box = cv::fitEllipse(iris_age);
    //cv::ellipse(org, box,cv::Scalar(255,0,0),2,8);

    std::vector<cv::Point> circle_element;

    if ((int)iris_age.size() < 2) return circle_element;

    // RANSACを用いて最適解の選定
    int all_element = (int)iris_age.size();
    int sample_element = 4;
    int repeat = 100;

    int best_rad = -1;
    int min_error = 10000000;

    for(int i = 0; i < repeat; i++){
        // サンプル作成
        int sample_rad = 0;
        for(int j = 0; j < sample_element; j++){
            int sample_num = rand()%all_element;
            sample_rad += sqrt(Square(center.x-iris_age[sample_num].x) + Square(center.y-iris_age[sample_num].y));
        }

        // サンプルの平均半径を算出
        sample_rad /= sample_element;

        // 実際のデータとサンプルを比較
        int total_error = 0;
        for(int k = 0; k < all_element; k++){
            int element_rad = (int)sqrt(Square(center.x-iris_age[k].x) + Square(center.y-iris_age[k].y));
            total_error += abs(element_rad - sample_rad);
        }

        // 誤差が今までで最小なら保持
        if(total_error < min_error){
            min_error = total_error;
            best_rad = sample_rad;
        }
    }

    // 円の点群(72点)を取得
    for(int theta = 0; theta < 359; theta += 5){
        int x = (int)(center.x + best_rad * cos(theta * (CV_PI/180)));
        int y = (int)(center.y + best_rad * sin(theta * (CV_PI/180)));
        circle_element.push_back(cv::Point(x,y));
    }

    // 円の描画
    if(best_rad > 0 && &draw_im != (cv::Mat *)nullptr){
        //cv::circle(draw_im, center, best_rad, CV_RGB(0,200,0));
    }

    return circle_element;
}
Exemple #25
0
    void UpdateAI(const uint32 uiDiff)
    {
// Phase_Idle
        if (m_uiPhase == PHASE_IDLE)
        {
            if (m_uiOrdersTimer < uiDiff)
            {
                switch (rand()%5)
                {
                case 0:
                    DoScriptText(SAY_OFFCOMBAT1, m_creature);
                    break;
                case 1:
                    DoScriptText(SAY_OFFCOMBAT2, m_creature);
                    break;
                case 2:
                    DoScriptText(SAY_OFFCOMBAT3, m_creature);
                    break;
                case 3:
                    DoScriptText(SAY_OFFCOMBAT4, m_creature);
                    break;
                case 4:
                    DoScriptText(SAY_OFFCOMBAT5, m_creature);
                    break;
                }
                m_uiOrdersTimer = 30000;
            }
            else m_uiOrdersTimer -= uiDiff;
            // break;   // might be needed went know till play testing
        }

        if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
            return;

        // Legion Lighting all phases
        if (m_uiLegionLightingTimer < uiDiff)
        {
            DoCast(m_creature->getVictim(), SPELL_LEGION_LIGHTING);
            m_uiLegionLightingTimer = 11000;
        } else m_uiLegionLightingTimer -= uiDiff;

        // soul flay all phases
        if (m_uiSoulFlayTimer < uiDiff)
        {
            DoCast(m_creature->getVictim(), SPELL_SOULFLAY);
            m_uiSoulFlayTimer = 7000;
        } else m_uiSoulFlayTimer -= uiDiff;

// Phase_One
        if (m_uiPhase == PHASE_ONE)
        {
            if (m_uiShieldOrbTimer < uiDiff)  // needs a trigger like a bool that keeps it from casting at everytime the bool would reset every phase or something not sure yet 8)
            {
                for(uint8 i = 0; i < m_uiMaxShieldOrbs; ++i)
                {
                    float angle = (float) rand()*360/RAND_MAX + 1;
                    float homeX = m_creature->GetPositionX() + 20*cos(angle*(M_PI/180));
                    float homeY = m_creature->GetPositionY() + 20*sin(angle*(M_PI/180));
                    m_creature->SummonCreature(NPC_SHIELD_ORB, homeX, homeY, m_creature->GetPositionZ()+15, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
                }
                m_uiShieldOrbTimer = 50000;
            }
            else m_uiShieldOrbTimer -= uiDiff;

            //if (m_creature->GetHealthPercent() < 85.0f)
            //m_uiPhase = PHASE_TWO;
        }


    }
Exemple #26
0
void Game::tick(Keys keys)
{
    ship_.tick(keys);
    if (keys[KEY_FIRE] && (bullets_.size() == 0 || bullets_.back().live > 200))
    {
        Bullet b;
        b.vx = 100 * cos(ship_.angel());
        b.vy = 100 * sin(ship_.angel());
        b.x = 20 * cos(ship_.angel());
        b.y = 20 * sin(ship_.angel());
        bullets_.push_back(b);
    };
    
    Vector v = { 0, 0 };
    if (keys[KEY_UP])
    {
        v.x = -200 * cos(ship_.angel());
        v.y = -200 * sin(ship_.angel());
    }
    if (keys[KEY_DOWN])
    {
        v.x = 200 * cos(ship_.angel());
        v.y = 200 * sin(ship_.angel());
    }
    for (Bullets::iterator i = bullets_.begin(); i != bullets_.end(); ++i)
        i -> tick(v);
    for (Stars::iterator i = stars_.begin(); i != stars_.end(); ++i)
        i -> tick(v);
    for (Asteroids::const_iterator i = asteroids_.begin(); i != asteroids_.end(); ++i)
        (*i) -> tick(v);
    for (Asteroids::const_iterator a = asteroids_.begin(); a != asteroids_.end(); ++a)
        for (Bullets::iterator b = bullets_.begin(); b != bullets_.end(); ++b)
        {
            float d = sqrt((b -> x - (*a) -> x) * (b -> x - (*a) -> x) + (b -> y - (*a) -> y) * (b -> y - (*a) -> y));
            if (d < ((*a) -> size + 1.5))
            {
                if ((*a) -> size > 8)
                {
                    (*a) -> size /= 1.414;
                    Asteroid *aa = new Asteroid(**a);
                    aa -> vx += rand() % 31 - 15;
                    aa -> vy += rand() % 31 - 15;
                    asteroids_.insert(aa);
                }
                else
                {
                    delete *a;
                    asteroids_.erase(*a);
                    if (asteroids_.size() == 0)
                    {
                        ++level_;
                        reset();
                        return;
                    }
                }
                goto a;
            }
        }
    a:
    for (Asteroids::const_iterator a = asteroids_.begin(); a != asteroids_.end(); ++a)
    {
        float d = sqrt((*a) -> x * (*a) -> x + (*a) -> y * (*a) -> y);
        if (d < ((*a) -> size + 15))
        {
            reset();
            return;
        }
    }
    while (bullets_.size() != 0 && bullets_.front().live > 3000)
        bullets_.pop_front();
}
Exemple #27
0
void mapRoverTask( void *param ){
//static portTASK_FUNCTION( mapRoverTask, pvParameters )
	RoverMapStruct *roverMapStruct = (RoverMapStruct *) param;
	
	MapCorner receivedCorner;

	double totalAngle = 0;
	double totalCalcAngle = 90.0;
	double area;
	
	char buf[20];
	double number;
	//int intPart, decimalPart;
	uint8_t cornersCount = 0;

	sprintf(guiMapCoordinates, "");
	polyComp = 0;
	
	for(;;){
		if (xQueueReceive(roverMapStruct->inQ, (void *) &receivedCorner, portMAX_DELAY) != pdTRUE) {
			VT_HANDLE_FATAL_ERROR(0);
		}

		if(strlen(guiMapCoordinates) >= (BUFFER_SIZE - 10)){
			sprintf(guiMapCoordinates, "");
		}
		if(strlen(debugBuf) >= (BUFFER_SIZE - 10)){
			sprintf(debugBuf, "");
		}
		printFloat("QReced:", receivedCorner.distSide, 1);
		// Print the received distance reading
		vtLEDToggle(0x40);
		printFloat("Angle: ", receivedCorner.angleCornerExterior, 0);;
		double ang;
		if(roverMapStruct->taskFlags == REGULAR && roverMapStruct->numberSides != 0){
			receivedCorner.angleCornerExterior = 360.0/roverMapStruct->numberSides;
		}
		else{
			ang = receivedCorner.angleCornerExterior;
			receivedCorner.angleCornerExterior = receivedCorner.angleCornerExterior + receivedCorner.tempBefore/2.0;
			if(receivedCorner.angleCornerExterior>90) receivedCorner.angleCornerExterior = 90;
		}
		//printFloat("Side Dist: ", receivedCorner.distSide, 1);
		receivedCorner.tempPow = mapCorners[cornersCount-1].distFromSide * pow(receivedCorner.angleCornerExterior/90.0, 5);
		
		totalAngle += receivedCorner.angleCornerExterior;
		if(cornersCount != 0){
			//totalAngle += receivedCorner.angleCornerExterior;
			//receivedCorner.distSide += mapCorners[cornersCount-1].distFromSide;
			printFloat("PrevSide:", mapCorners[cornersCount-1].distFromSide, 1);
			printFloat("WithPrevSide:", receivedCorner.distSide, 1);
			
			// Teja experimenting
			receivedCorner.distSide +=  receivedCorner.tempFrontDist + mapCorners[cornersCount-1].distFromSide*sin(mapCorners[cornersCount-1].angleCornerExterior*M_PI/180.0)*sin(mapCorners[cornersCount-1].angleCornerExterior*M_PI/180.0);

			// Yasir's conversion to coordinates
			xPoints[cornersCount] = xPoints[cornersCount - 1] + receivedCorner.distSide*cos(totalCalcAngle*M_PI/180.0);
			yPoints[cornersCount] = yPoints[cornersCount - 1] + receivedCorner.distSide*sin(totalCalcAngle*M_PI/180.0);
			totalCalcAngle -= receivedCorner.angleCornerExterior;

			sprintf(buf, "C=%d Deg=%.2f Dist=%.2f A=%.2f\n", cornersCount+1, receivedCorner.angleCornerExterior, receivedCorner.distSide, calculateArea(cornersCount+1, xPoints, yPoints));
			strcat(debugBuf, buf);

			//sprintf(buf, "Deg=%.1f F=%.1f OA=%.1f SB=%.1f SD=%.1f SDP=%1.f FD=%.1f Dist=%.1f S=%d\n", receivedCorner.angleCornerExterior,receivedCorner.tempFront, ang, receivedCorner.tempBefore, mapCorners[cornersCount-1].distFromSide, receivedCorner.tempPow, receivedCorner.tempFrontDist, receivedCorner.distSide, cornersCount);
			//strcat(debugBuf, buf);

			//sprintf(buf, "A=%f\n", calculateArea(cornersCount+1, xPoints, yPoints));
			//strcat(debugBuf, buf);
			if ((totalAngle) >= TOTAL_ANGLE_THRESHOLD){
				// TODO: calculate area;
				// param for calculateArea (side) is 1 minus the number of sides
				if(polyComp == 0){
					polyComp = -1;
					sprintf(buf, "%d,%d ", (int)(xPoints[cornersCount]*MAP_SCALE_FACTOR + MAP_X_OFFSET), (int)(yPoints[cornersCount]*-MAP_SCALE_FACTOR + MAP_Y_OFFSET));
					strcat(guiMapCoordinates, buf);
				}
				else{
					polyComp = cornersCount;
					sprintf(buf, "%d,%d", MAP_X_OFFSET, MAP_Y_OFFSET);
					strcat(guiMapCoordinates, buf);
				}
				sprintf(buf, "\n** Polygon complete ** Corners=%d A=%f\n\n", cornersCount+1,calculateArea(cornersCount+1, xPoints, yPoints));
				strcat(debugBuf, buf);
			}
			else{
				sprintf(buf, "%d,%d ", (int)(xPoints[cornersCount]*MAP_SCALE_FACTOR + MAP_X_OFFSET), (int)(yPoints[cornersCount]*-MAP_SCALE_FACTOR + MAP_Y_OFFSET));
				strcat(guiMapCoordinates, buf);
			}
		}
		else{
			totalCalcAngle = 90;
			xPoints[0] = 0;
			xPoints[0] = 0;
			sprintf(buf, "%d,%d ", (int)(xPoints[cornersCount]*MAP_SCALE_FACTOR + MAP_X_OFFSET), (int)(yPoints[cornersCount]*-MAP_SCALE_FACTOR + MAP_Y_OFFSET));
			strcat(guiMapCoordinates, buf);
		}

		if(cornersCount < MAXIMUM_CORNERS){
			mapCorners[cornersCount] = receivedCorner;
			++cornersCount;
		}


		
	}
}
Exemple #28
0
int main()
{
	sf::RenderWindow window;
	sf::Texture circle_texture;
	sf::Sprite circle;
	sf::Clock clock;
	sf::Vector2f circle_position;
	sf::Vector2i mouse_position;
	sf::Vector2i destination;

	bool stop_circle = true;
	float angle;
	float move_x;
	float move_y;
	float distance;
	float distance_x;
	float distance_y;

	window.create(sf::VideoMode(WIDTH, HEIGHT), "SFML Movement");

	if (!circle_texture.loadFromFile("circle.png"))
		std::cout << "Error: could not load player image" << std::endl;

	circle.setTexture(circle_texture);
	circle.setOrigin(16, 16);
	circle.setPosition(WIDTH/2, HEIGHT/2);

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			switch (event.type)
			{
				case sf::Event::Closed:
					window.close();
					break;
				case sf::Event::MouseButtonPressed:
					if (event.mouseButton.button == sf::Mouse::Right)
					{
						stop_circle = false;
						destination = sf::Mouse::getPosition(window);

						// get the angle between the circle and mouse click using arc tangent
						angle = atan2(destination.y - circle_position.y, destination.x - circle_position.x);
					}
					break;
				case sf::Event::KeyPressed:
					if (event.key.code == sf::Keyboard::S)
					{
						stop_circle = true;
					}
					break;
			}
		}

		// Vector to hold circle position
		circle_position = circle.getPosition();

		// Current mouse position
		mouse_position = sf::Mouse::getPosition(window);

		// Distance
		distance_x = destination.x - circle_position.x;
		distance_y = destination.y - circle_position.y;
		distance = sqrt(distance_x * distance_x + distance_y * distance_y);

		// Frames and movement
		if (stop_circle == false)
		{
			move_x = cos(angle);
			move_y = sin(angle);

			circle.move(move_x, move_y);

			if (distance < 2)
				stop_circle = true;
		}
		//test
		system("clear");
		std::cout << "Circle X: " << circle_position.x << " Circle Y: " << circle_position.y << std::endl;
		std::cout << "Mouse X: " << mouse_position.x << " Mouse Y: " << mouse_position.y << std::endl;
		std::cout << "Destination " << destination.x << ", " << destination.y << std::endl;
		std::cout << "Angle: " << angle * 180 / PI << std::endl;
		std::cout << "move_x: " << move_x << " move_y: " << move_y << std::endl;
		float x = destination.x - circle_position.x;
		float y = destination.y - circle_position.y;
		std::cout << "Distance: " << sqrt(x * x + y * y) << std::endl;

		window.draw(circle);
		window.display();
		window.clear();
	}
}
Exemple #29
0
void
set_R(QLA_Real *r, int i)
{
  *r = 1+cos(i);
}
/*
================
idSecurityCamera::Spawn
================
*/
void idSecurityCamera::Spawn( void ) {
	idStr	str;

	sweepAngle	= spawnArgs.GetFloat( "sweepAngle", "90" );
	health		= spawnArgs.GetInt( "health", "100" );
	scanFov		= spawnArgs.GetFloat( "scanFov", "90" );
	scanDist	= spawnArgs.GetFloat( "scanDist", "200" );
	flipAxis	= spawnArgs.GetBool( "flipAxis" );

	modelAxis	= spawnArgs.GetInt( "modelAxis" );
	if ( modelAxis < 0 || modelAxis > 2 ) {
		modelAxis = 0;
	}

	spawnArgs.GetVector( "viewOffset", "0 0 0", viewOffset );

	if ( spawnArgs.GetBool( "spotLight" ) ) {
		PostEventMS( &EV_SecurityCam_AddLight, 0 );
	}

	negativeSweep = ( sweepAngle < 0 ) ? true : false;
	sweepAngle = fabs( sweepAngle );

	scanFovCos = cos( scanFov * idMath::PI / 360.0f );

	angle = GetPhysics()->GetAxis().ToAngles().yaw;
	StartSweep();
	SetAlertMode( SCANNING );
	BecomeActive( TH_THINK );

	if ( health ) {
		fl.takedamage = true;
	}

	pvsArea = gameLocal.pvs.GetPVSArea( GetPhysics()->GetOrigin() );
	// if no target specified use ourself
	str = spawnArgs.GetString( "cameraTarget" );
	if ( str.Length() == 0 ) {
		spawnArgs.Set( "cameraTarget", spawnArgs.GetString( "name" ) );
	}

	// check if a clip model is set
	spawnArgs.GetString( "clipmodel", "", str );
	if ( !str[0] ) {
		str = spawnArgs.GetString( "model" );		// use the visual model
	}

	if ( !collisionModelManager->TrmFromModel( str, trm ) ) {
		gameLocal.Error( "idSecurityCamera '%s': cannot load collision model %s", name.c_str(), str.c_str() );
		return;
	}

	GetPhysics()->SetContents( CONTENTS_SOLID );
	// SR CONTENTS_RESPONSE FIX
	if( m_StimResponseColl->HasResponse() )
		physicsObj.SetContents( physicsObj.GetContents() | CONTENTS_RESPONSE );

	GetPhysics()->SetClipMask( MASK_SOLID | CONTENTS_BODY | CONTENTS_CORPSE | CONTENTS_MOVEABLECLIP );
	// setup the physics
	UpdateChangeableSpawnArgs( NULL );
}