示例#1
0
char *video_save (int row1, int col1, int row2, int col2)
{
    char    *s;
    int     r, ws, lw, lls;

    col1 = max1 (0, min1 (col1, COLS-1));
    col2 = max1 (0, min1 (col2, COLS-1));
    row1 = max1 (0, min1 (row1, ROWS-1));
    row2 = max1 (0, min1 (row2, ROWS-1));
    
    ws  = (row2-row1+1)*(col2-col1+1);
    lw  = col2-col1+1;
    lls = sizeof(int) * 4;
    s   = malloc (ws*2 + lls);

    ((int *)s)[0] = row1;
    ((int *)s)[1] = col1;
    ((int *)s)[2] = row2;
    ((int *)s)[3] = col2;

    for (r=row1; r<=row2; r++)
    {
        memcpy (s+(r-row1)*lw+lls, scrn_cache_chars+r*COLS+col1, lw);
        memcpy (s+(r-row1)*lw+ws+lls, scrn_cache_attrs+r*COLS+col1, lw);
    }
    return s;
}
示例#2
0
bool ch_att::normalAtt()
{
	long xx,yy,tx,ty,mx=0,my=0,ax=0,ay=0,max=0,maxexp=-oo;
	long est=0,id,estexp=0,estlev=0;
	for (int i=0;i<=sp;i++)
	 for (int j=0;j<=i;j++)
	  for (int d1=-1;d1<=1;d1+=2)
	   for (int d2=-1;d2<=1;d2+=2)
	    {
			xx=x+j*d1;
			yy=y+(i-j)*d2;
			if (!legal(xx,yy) || (g[xx][yy]!=EMPTY && g[xx][yy]!=myID))
			 continue;
			for (int k=0;k<4;k++)
			  {
				tx=xx+dir[k][0],ty=yy+dir[k][1];
				if (!legal(tx,ty) || !g[tx][ty] || g[tx][ty]==myID)
				 continue;
				estexp=1;
				if (g[tx][ty]==FOOD)
				 est=max1(2,maxhp/10);
				else
				 {
					id=g[tx][ty];
					if (att>=p[id].hp)
					 {
						estlev=estLevel(id);
						estexp=max1(1,estlev/2);
					 }
					else
					 continue;
					if (estexp>=levelUpRequire())
					 est=6;
					else
					 est=0;
				 }
				if (estexp>maxexp || (estexp==maxexp && est>max))
				 {
					max=est;
					maxexp=estexp;
					mx=xx,my=yy;
					ax=tx,ay=ty;
				 }
			  }
		}
	if (!mx)
	 return 0;
	move(mx,my);
	attack(ax,ay);
	return 1;
}
示例#3
0
void main()
{
	printf("(9+10)*2=%d\n",SUM*2);
	printf("int在内存中占用 %ld 个字节\n",INT_SIZE);
	/*
	使用undef来设定宏的作用域
	#undef N
	#undef INT_SIZE
	下面这两句同样的代码会编译出错
	printf("(9+10)*2=%d\n",SUM*2);
	printf("int在内存中占用 %ld 个字节\n",INT_SIZE);
	*/
	printf("不要再字符串中使用宏,比如字符串中的STR是不会被替换成:%s\n",STR);

	printf("----------\n");

	//一般情况下,这两个宏都能得到正确结果
	int a=5,b=6;
	printf("max1:%d,%d max is %d\n",a,b,max1(a,b));
	printf("max2:%d,%d max is %d\n",a,b,max2(a,b));

	
	//但是有时可能会出错,max1会严格的检查参数类型,下面的语句max1就会编译报错,而max2则会有隐患
	char c='a';
	int d=6;
	//这一句因为参数类型不一致导致编译失败
	//printf("max1:%c,%d max is %d\n",c,d,max1(c,d));
	printf("max2:%c,%d max is %d\n",c,d,max2(c,d));
	
	
	//typeof(x) _x=(x);typeof(y) _y=(y)如果不加该语句得到的将会是意想不到的结果
	//比较x和y++的大小,其实质还是比较x和y,y++是在执行比较操作后才应该++操作
	int x=1,y=2;
	//在完整的宏定义下,输出最大值2后再执行y++,y=3
	printf("max1 result is %d\n",max1(x,y++));
	int x1=1,y1=2;
	//但不完整的宏定义下,先比较出最大的y=2,然后在执行y++,y=3,最后才输出3,但这样的结果很可能不是自己想要的
	printf("max2 result is %d\n",max2(x1,y1++));

	printf("----------\n");

	print1("print1:hello world\n");
	print2("print2:hello world,%s\n","test");

	printf("----------\n");

	printf("嵌套宏定义的和为:%d\n",N_SUM);
}
示例#4
0
/*  Jacobi iterative method for M * x = b

        | M(1,1) M(1,2) M(1,3) .  M(1,N)| |x(1)|     |b(1)|
        | M(2,1) M(2,2) M(2,3) .  M(2,N)| |x(2)|     |b(2)|
        | M(3,1) M(3,2) M(3,3) .  M(3,N)| |x(3)|     |b(3)|
        |   .      .      .    .    .   | | .  |  =  | .  |
        | M(N,1) M(N,2) M(N,3) .  M(N,N)| |x(N)|     |b(N)|
INPUT:
   M is N x N array of coefficients
   b is the vector of r.h.s.
   x - initial approximation
   eps - accuracy
   itermax - iteration limit
OUTPUT:
   solution vector x */
bool JacobiIter(FArr2D& M, FArr1D& x, FArr1D& b, real eps, int itermax)
{
  int h = M.H1();
  int l = M.L1();
  int iter = 0;
  double delta, sum;
  FArr1D y(l,h);

  assert( (l == M.L2()) && (h == M.H2()) );
  do
  {
    iter++;
    delta = 0.0;
    for (int i = l; i <= h; i++)
    {
      sum = 0.0;
      y = x;
      for (int j = l; j <= h; j++)
        if (j != i) sum += M(i,j)*x(j);
      x(i) = (b(i)-sum)/M(i,i);
      delta = max1(delta, abs(x(i)-y(i)));
    };  
  } while ( (delta > eps) && (iter < itermax) );
  return (iter < itermax);
} // JacobiIter <------------------------------------------------------------
 int maxProfit(vector<int> &prices) {
     int n=prices.size();
     if(n<2) return 0;
     vector<int> max1(n,0);
     int maxprofit=0;
     int lmin=prices[0];
     for(int i=1;i<n;i++){
         int profit=prices[i]-lmin;
         if(profit>maxprofit) maxprofit=profit;
         max1[i]=maxprofit;
         lmin=min(lmin,prices[i]);
     }
     
     int ret=max1[n-1];
     int high=prices[n-1];
     maxprofit=0;
     for(int i=n-2;i>=0;i--){
         int profit=high-prices[i];
         if(profit>maxprofit) maxprofit=profit;
         if(maxprofit+max1[i]>ret)
             ret=maxprofit+max1[i];
         high=max(high,prices[i]);
     }
     return ret;
 }
示例#6
0
float arrmax1(int n)
{
    if (n == 1)
        return x[0];
    else
        return max1(x[n - 1], arrmax1(n - 1));
}
示例#7
0
long ch_att::targetSpeed()
{
	long low=oo,high=-oo,sec_low=oo,sec_high=-oo;
	long speed=0,ans=0;
	for (int i=1;i<=MAX_PLAYER;i++)
	 if (i!=myID)
	  {
		speed=p[i].sp;
		if (speed>high)
		 {
			sec_high=high;
			high=speed;
		 }
		else if (speed>sec_high)
		 sec_high=speed;
		
		if (speed<low)
		 {
			sec_low=low;
			low=speed;
		 }
		else if (speed<sec_low)
		 sec_low=speed;
	  }
	ans=(long)(sec_low+(sec_high-sec_low)*0.618);
	return (long)(max1(ans,1+lev*0.5));
}
示例#8
0
void ch_att::getMap() // Get all infos about the map and the players.
{
	for (int i=1;i<=MAX_PLAYER;i++)
	 if (i!=myID)
	  {
		p[i].status=DEAD;
		p[i].lastx=p[i].x;
		p[i].lasty=p[i].y;
		p[i].x=0;
		p[i].y=0;
		p[i].hp=askHP(i);
	  }
	for (int i=1,dis,id;i<=N;i++)
	 for (int j=1;j<=M;j++)
	  {
		g[i][j]=askWhat(i,j);
		if (g[i][j]>EMPTY && g[i][j]!=myID)
		 {
			id=g[i][j];
			p[id].x=i;
			p[id].y=j;
			p[id].status=ALIVE;
			if (p[id].lastx>0)
			 {
				dis=abs1(p[id].lastx-p[id].x)+abs1(p[id].lasty-p[id].y);
				p[id].maxmove=max1(p[id].maxmove,dis);
				p[id].sp=(long)(speedEstimate*p[id].maxmove);
			 }
		 }
	  }
	for (int i=1;i<=MAX_PLAYER;i++)
	 if (i!=myID && p[i].status==DEAD)
	  p[i].dietime++;
}
// minimize a single link (see "PatchMatch" - page 4)
void minimizeLinkNNF(NNF_P nnf, int x, int y, int dir)
{
	int xp,yp,dp,wi, xpi, ypi;
	//Propagation Up/Down
	if (x-dir>0 && x-dir<nnf->input->image->height) {
		xp = nnf->field[x-dir][y][0]+dir;
		yp = nnf->field[x-dir][y][1];
		dp = distanceNNF(nnf,x,y, xp,yp);
		if (dp<nnf->field[x][y][2]) {
			nnf->field[x][y][0] = xp;
			nnf->field[x][y][1] = yp;
			nnf->field[x][y][2] = dp;
		}
	}
	//Propagation Left/Right
	if (y-dir>0 && y-dir<nnf->input->image->width) {
		xp = nnf->field[x][y-dir][0];
		yp = nnf->field[x][y-dir][1]+dir;
		dp = distanceNNF(nnf,x,y, xp,yp);
		if (dp<nnf->field[x][y][2]) {
			nnf->field[x][y][0] = xp;
			nnf->field[x][y][1] = yp;
			nnf->field[x][y][2] = dp;
		}
	}
	//Random search
	wi=nnf->output->image->width;
	xpi=nnf->field[x][y][0];
	ypi=nnf->field[x][y][1];
	int r=0;
    while (wi>0) {
		r=(rand() % (2*wi)) -wi;
		xp = xpi + r;
		r=(rand() % (2*wi)) -wi;
		yp = ypi + r;
		xp = (int)(max1(0, min1(nnf->output->image->height-1, xp )));
		yp = (int)(max1(0, min1(nnf->output->image->width-1, yp )));

		dp = distanceNNF(nnf,x,y, xp,yp);
		if (dp<nnf->field[x][y][2]) {
			nnf->field[x][y][0] = xp;
			nnf->field[x][y][1] = yp;
			nnf->field[x][y][2] = dp;
		}
		wi/=2;
	}
}
示例#10
0
文件: 7.cpp 项目: igolka97/ispu-quest
int main()
{
    int m,n,i,j,k,p;
    int *o;
    printf("vvedite kol-vo strok\n");
    scanf("%d", &m);
    printf("vvedite kol-co stolbcov\n");
    scanf("%d",&n);
    printf("\n");
    int **x;
    x=new int *[m];
    for (i=0;i<m;i++)
    {
        x[i]=new int[n];
    }
    srand(time(NULL));
    for (i=0; i<m; i++)
    {
        for (j=0; j<n; j++)
        {
            x[i][j]=rand()/100000000;
            printf("%d ",x[i][j]);
        }
        printf("\n");
    }
    printf("\n");
    int *max;
    max=new int [m];
    for (i=0; i<m; i++)
    {
        max[i]=max1(n,x[i]);
        printf("max=%d\n",max[i]);
    }
    printf("\n");
    for (k=0;k<(m-1);k++) //сортировка
    {
        for (i=0;i<(m-1);i++)
        {
            if (max[i]<max[i+1])
            {
                o=x[i];
                x[i]=x[i+1];
                x[i+1]=o;
                p=max[i];
                max[i]=max[i+1];
                max[i+1]=p;
            }
        }
    }
    printf("\n");
    for (i=0; i<m; i++)
    {
        for (j=0; j<n; j++)
        {
            printf("%d ",x[i][j]);
        }
        printf("\n");
    }
}
示例#11
0
// convolve one column of I by a 2rx1 max filter
void convMaxY( float *I, float *O, float *T, int h, int r ) {
  int y, y0, y1, yi, m=2*r+1;
  #define max1(a,b) a>b ? a : b;
  #define maxk(y0,y1) { O[y]=I[y0]; \
    for( yi=y0+1; yi<=y1; yi++ ) { if(I[yi]>O[y]) O[y]=I[yi]; }}
  for( y=0; y<r; y++ ) { y1=y+r; if(y1>h-1) y1=h-1; maxk(0,y1); }
  for( ; y<=h-m-r; y+=m ) {
    T[m-1] = I[y+r];
    for( yi=1; yi<m; yi++ ) T[m-1-yi] = max1( T[m-1-yi+1], I[y+r-yi] );
    for( yi=1; yi<m; yi++ ) T[m-1+yi] = max1( T[m-1+yi-1], I[y+r+yi] );
    for( yi=0; yi<m; yi++ ) O[y+yi] = max1( T[yi], T[yi+m-1] );
  }
  for( ; y<h-r; y++ ) { maxk(y-r,y+r); }
  for( ; y<h; y++ ) { y0=y-r; if(y0<0) y0=0; maxk(y0,h-1); }
  #undef maxk
  #undef max1
}
示例#12
0
int main()
{
    int array[MAX] = {1,2,3,4,5,6,7,7,8,9,9,0};
    int num, i;
    num = max1(array);
    //num = max1(array[]) 会报错;
    printf("the largest_num is %d\n", num);
    return 0;
}
示例#13
0
double hubfun_(short int* IX, float* A, float* FA, int* M_ptr, int* MMAX_ptr)
{
    
     /* never used M_ptr or MMAX_ptr, so no need to dereference */
     /* rename used common block variables */
     int NEEDIT = drfake_.needit;
     
     /* substance of function begins here */
     float HALF   = 0.5f;
     float EXPMIN = -23.0f;

     float X,Y;
     float A5, A7;
     float T5, T6, T7, T1;
     float DENOM, DDDT, PEXP;
     float HUBFUN;

     X  = (float)IX[0] - A[1];
     Y  = (float)IX[1] - A[2];
     A5 = 1.0f/A[4];
     A7 = 1.0f/A[6];
     T5 = A5*X     ;
     T6 = A[5]*Y   ;
     T7 = A7*Y     ;
     T1 = HALF*((T5+2.0f*T6)*X + T7*Y);
     if (T1 > 0.0f){
          DENOM = 1.0f + T1  ;
          DDDT  = 1.0f       ;
          PEXP  = 1.0f/DENOM ;
     }
     else{
          T1    = max1(T1, EXPMIN);
          PEXP  = expf(-T1)        ;
          DENOM = 1.0f            ;
          DDDT  = 1.0f            ;
     }
     FA[3] = PEXP        ;
     PEXP = A[3]*PEXP    ;
     HUBFUN = PEXP + A[0];
     if (NEEDIT){
          FA[5] = PEXP*DDDT/DENOM    ;
          FA[1] = (T5 + T6)*FA[5]    ;
          FA[2] = (A[5]*X + T7)*FA[5];
          FA[4] = HALF*T5*T5*FA[5]   ;
          FA[6] = HALF*T7*T7*FA[5]   ;
          FA[5] = -X*Y*FA[5]         ;
          FA[0] = 1.0f               ;
     }

     return HUBFUN;
}
示例#14
0
int main()
{
int a[100000],n,i;
int t;
scanf("%d",&t);
while(t-->0)
{
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int check=0;int k=0,k1=0,k11=0,c=0;

for(i=0;i<n;i++)
{
	if(a[i]<0)
	check=1;
}

if(check==1)
{
	for(i=0;i<n;i++)
	if(a[i]<0)
	c++;

	if(c==n)
	{
	k=min(a,n);
	k1=min(a,n);
	}
	else{

 k=max(a,n);
 k1=max1(a,n);
}
}

else
{
 k=max(a,n);
 k1=max(a,n);
}

printf("%d\t%d\n",k,k1);
}
system("pause");
}
示例#15
0
///
//Checks for collision between two axis aligned bounding box by seeing 
//if they overlap on each axis.
//
//Parameters:
//	aabb1: The first axis aligned bounding box to test
//	aabb2: The second axis aligned bounding box to test
//
//Returns:
//	true if colliding, else false.
bool CheckCollision(const AABB &aabb1, const AABB &aabb2)
{
	//Find the max and min points for each box
	glm::vec3 min1(aabb1.center - (aabb1.dimensions*0.5f));
	glm::vec3 max1(aabb1.center + (aabb1.dimensions*0.5f));
	glm::vec3 min2(aabb2.center - (aabb2.dimensions*0.5f));
	glm::vec3 max2(aabb2.center + (aabb2.dimensions*0.5f));

	//If there is overlap on each axis, we have a collision
	if (max1.x > min2.x && min1.x < max2.x)
		if (max1.y > min2.y && min1.y < max2.y)
			if (max1.z > min2.z && min1.z < max2.z)
				return true;

	return false;
}
示例#16
0
double ch_att::risk(long x,long y)
{
	double ans=0,rate;
	long id,estStrength=0,rest,dis;
	for (int i=1;i<=N;i++)
	 for (int j=1;j<=M;j++)
	  if (g[i][j]>0 && g[i][j]!=myID)
	   {
			id=g[i][j];
			estStrength=(long)(p[id].sp*1.2);
			rest=max1(0,hp-estStrength);
			rate=(double)rest/(double)maxhp;
			dis=abs1(i-x)+abs1(j-y);
			ans+=1/(rate+eps)/(rate+eps)*p[id].sp/dis;
	   }
	return ans;
}
示例#17
0
double ch_att::benefit(long x,long y)
{
	double ans=0,rate;
	long id,rest,dis;
	for (int i=1;i<=N;i++)
	 for (int j=1;j<=M;j++)
	  if (g[i][j]>0 && g[i][j]!=myID)
	   {
			id=g[i][j];
			rest=max1(0,p[id].hp-att);
			rate=(double)rest/(double)maxhp;
			dis=abs1(i-x)+abs1(j-y);
			ans+=1/(rate+eps)/(rate+eps)*sp/dis*(1+log(estLevel(id)));
	   }
	  else if (g[i][j]==FOOD)
	   ans+=1/eps*sp/dis;
	return ans;
}
int main(int argc, char* argv[])
{
	Mat<float> hwd((float)4,3,1);
	
	BoxShape box( NULL, hwd);
	
	
	Mat<float> pointsB1[8];
	for(int i=8;i--;)	pointsB1[i] = Mat<float>(0.0f,3,1);
	
	//register the position of the 8 points composing b1:
	Mat<float> min1((float)0,3,1);
	Mat<float> max1((float)0,3,1);
	
	min1.set( -box.getHeight()/2.0f, 1,1);
	min1.set( -box.getWidth()/2.0f, 2,1);
	min1.set( -box.getDepth()/2.0f, 3,1);
	max1.set( -min1.get(1,1), 1,1);
	max1.set( -min1.get(2,1), 2,1);
	max1.set( -min1.get(3,1), 3,1);
	
	int col = 0;
	
	for(int pm1=2;pm1--;)
	{
		for(int pm2=2;pm2--;)
		{
			for(int pm3=2;pm3--;)
			{
				pointsB1[col].set( pm1*( min1.get(1,1) ) + (1-pm1)*( max1.get(1,1) ), 1,1);
				pointsB1[col].set( pm2*( min1.get(2,1) ) + (1-pm2)*( max1.get(2,1) ), 2,1);
				pointsB1[col].set( pm3*( min1.get(3,1) ) + (1-pm3)*( max1.get(3,1) ), 3,1);
				
				col++;
			}
		}
	}
	
	
	for(int i=8;i--;)	pointsB1[i].afficher();
	
	
	return 0;
}
示例#19
0
Vec2 CollisionDetector::AABBToAABB(const Rect& rect1, const Rect& rect2) {
	// Prevents false collision if either rects has no width and height
	if ((rect1.GetW() == 0 && rect1.GetH() == 0) ||
		(rect2.GetW() == 0 && rect2.GetH() == 0)) {
		return Vec2(0.0, 0.0); 
	}

	Vec2 min1(rect1.GetX(), rect1.GetY());
	Vec2 max1(rect1.GetX() + rect1.GetW(), rect1.GetY() + rect1.GetH());
	Vec2 min2(rect2.GetX(), rect2.GetY());
	Vec2 max2(rect2.GetX() + rect2.GetW(), rect2.GetY() + rect2.GetH());

	if ((max1.GetX() < min2.GetX()) || (max1.GetY() < min2.GetY())) {
		return Vec2(0.0, 0.0);
	}

	if ((max2.GetX() < min1.GetX()) || (max2.GetY() < min1.GetY())) {
		return Vec2(0.0, 0.0);
	}

	// Potential resolution offsets
	double negX = max1.GetX() - min2.GetX();
	double posX = max2.GetX() - min1.GetX();
	double negY = max1.GetY() - min2.GetY();
	double posY = max2.GetY() - min1.GetY();

	// Returns the component vector that needs the least offset to resolve the collision
	if (negX <= posX && negX <= negY && negX <= posY) {
		return Vec2(-negX, 0.0);
	}
	else if (posX <= negY && posX <= posY) {
		return Vec2(posX, 0.0);
	}
	else if (negY <= posY) {
		return Vec2(0.0, -negY);
	}
	else {
		return Vec2(0.0, posY);
	}

	return Vec2(0.0, 0.0);
}
示例#20
0
文件: ef.c 项目: OS2World/LIB-libfly
/* ------------------------------------------------------------
 
 -------------------------------------------------------------- */
void str_insert_at (int cline, int k, int ccol)
{
    char  *p;
    int   l;

    l = max1 (strlen(lines[cline])+1, ccol+1);
    p = malloc (l+1);

    if (ccol < strlen(lines[cline]))
    {
        strcpy (p, lines[cline]);
        str_insert (p, k, ccol);
    }
    else
    {
        strcpy (p, lines[cline]);
        memset (p+strlen(lines[cline]), ' ', ccol-strlen(lines[cline]));
        p[ccol] = k;
        p[ccol+1] = '\0';
    }

    free (lines[cline]);
    lines[cline] = p;
}
示例#21
0
文件: 10ptr.c 项目: huaweili/esd
int main(){
	int num = 3,num1 = 7;
	int *p_num = max1(&num,&num1);
	printf("*p_num is %d\n",*p_num);
	return 0;
}
示例#22
0
double gauss2d_(short int* IX, float* A, float* FA, int* M_ptr, int* fitcall_ptr)
{

     // A[0] = SKY,
     // A[1] = MAX intensity
     // A[2], [3], x, y, positions in field
     // A[4], [5], [6], sigmax^2, sigmaxy, sigmay^2

     // if call from chisq, the parameters may be in a different
     // space, i.e. log space and will need to be converted.
     // else, the parameters will be in linear space.
     // fitcall == 1 means gaussian2d was called from chisq
     int fitcall = *fitcall_ptr;

     /* rename used common block variables */
     int   NEEDIT = drfake_.needit;

     /* substance of function begins here */
     double X,Y;
     double sigx, sigy;
     double Z, A1;
     double DIDZ, PEXP;
     double GAUSSIAN2D;

     double HALF   = 0.5;
     double EXPMIN = -23.0;

     /* Changed indices */
     X = (double)(IX[0]) - A[2];
     Y = (double)(IX[1]) - A[3];

     sigx = 1.0/A[4];
     sigy = 1.0/A[6];
     Z = HALF*(sigx*X*X + 2.0*A[5]*Y*X + sigy*Y*Y); 

     if (Z < 0.0){
          Z    = max1(Z, EXPMIN);
     }
     PEXP = exp(-Z);

     /* Changed indices */
     if (fitcall == 1){
          A1    = exp(A[1]); //log case
          FA[1] = A1*PEXP; //log case
     }
     else{
          A1    = A[1]; //linear case
          FA[1] = PEXP; //linear case
     }
     DIDZ = A1*PEXP;
     GAUSSIAN2D = A1*PEXP + A[0];

     if (NEEDIT){
          /* Changed indices */
          FA[0] = 1.0                       ;
          FA[2] = DIDZ*(sigx*X + A[5]*Y)    ;
          FA[3] = DIDZ*(A[5]*X + sigy*Y)    ;
          FA[4] = DIDZ*(HALF*sigx*sigx*X*X);
          FA[5] = DIDZ*(-X*Y)               ;
          FA[6] = DIDZ*(HALF*sigy*sigy*Y*Y);
     }

     return GAUSSIAN2D;
}
示例#23
0
double pgauss2d_(short int* ix, float* a, float* fa, int* m_ptr, int* fitcall_ptr)
{
     // a[0] = sky,
     // a[1] = max intensity
     // a[2], [3], x, y, positions in field
     // a[4], [5], [6], sigmax^2, sigmaxy, sigmay^2

     // if call from chisq, the parameters may be in a different
     // space, i.e. log space and will need to be converted.
     // else, the parameters will be in linear space.
     // fitcall == 1 means pseud2d was called from chisq
     int fitcall = *fitcall_ptr;

     /* rename used common block variables */
     double beta4  = (double)tune17_.beta4;
     double beta6  = (double)tune17_.beta6;
     int   needit = drfake_.needit;

     /* substance of function begins here */
     double x,y;
     double sigx, sigy;
     double tx, ty, z, z2, a1;
     double denom, dddt, pexp;
     double pseud2d;

     double half   = 0.5;
     double third  = 0.3333333;
     double expmin = -23.0;

     /* changed indices */
     x = (double)(ix[0]) - a[2];
     y = (double)(ix[1]) - a[3];

     sigx = 1.0/a[4];
     sigy = 1.0/a[6];
     tx = sigx*x     ;
     ty = sigy*y     ;
     z = half*(tx*x + 2.0*a[5]*y*x + ty*y);

     if (z >= 0.0){
          z2    = half*z*z;
          denom = 1.0 + z + beta4*z2 + (beta6*third)*z*z2;
          dddt  = 1.0 + beta4*z + beta6*z2;
          pexp  = 1.0/denom;
     }
     else{
          z    = max1(z, expmin);
          pexp  = exp(-z);
          denom = 1.0;
          dddt  = 1.0;
     }
     
     /* changed indices */
     if (fitcall == 1){
          a1    = exp(a[1]); //log case
          fa[1] = a1*pexp; //log case
     }
     else{
          a1    = a[1]; //linear case
          fa[1] = pexp; //linear case
     }
     pexp  = a1*pexp;
     pseud2d = pexp + a[0];

     if (needit){
          /* changed indices */
          fa[5] = pexp*dddt/denom    ;
          fa[2] = (tx + a[5]*y)*fa[5]    ;
          fa[3] = (a[5]*x + ty)*fa[5];
          fa[4] = half*tx*tx*fa[5]   ;
          fa[6] = half*ty*ty*fa[5]   ;
          fa[5] = -x*y*fa[5]         ;
          fa[0] = 1.0                ;
     }
     return pseud2d;
}
示例#24
0
/* read binary data from socket until exhaustion.
 returns number of bytes read, or negative value on
 error. does not close socket. 'buf' is returned,
 malloc()ed (and NUL-terminated, but NUL byte
 is not included into the returned byte count).
 when 0 is returned, 'buf' is not allocated. */
int BRecv (int sock, char **buf)
{
    int   n, na, nb, bufsize, rc;
    char  *buffer, *p;
    struct  timeval timeout;
    fd_set  rdfds;

    bufsize = 8192;
    buffer  = xmalloc (bufsize);

    /* see if we already have string ready in the buffer */
    if (leftover != NULL)
    {
        na = bufsize + strlen (leftover);
        n  = strlen (leftover);
        p  = xmalloc (na);
        memcpy (p, leftover, n);
    }
    else
    {
        na = 8192;
        n  = 0;
        p  = xmalloc (na);
    }

    while (TRUE)
    {
        if (timelimit != -1.0)
        {
            timeout.tv_sec = timelimit;
            timeout.tv_usec = 0;
            FD_ZERO (&rdfds);
            FD_SET (sock, &rdfds);
            nb = -1;
            rc = select (FD_SETSIZE, &rdfds, NULL, NULL, &timeout);
            if (rc != 1)
            {
                break;
            }
        }

        nb = recv (sock, buffer, bufsize, 0);
        if (nb <= 0) break;
        if (n+nb > na-1)
        {
            na = max1 (na*2, n+nb+1);
            p = xrealloc (p, na);
        }
        memcpy (p+n, buffer, nb);
        n += nb;
    }
    free (buffer);

    if (n == 0)
    {
        free (p);
        if (nb < 0) return -1;
        return 0;
    }

    /* trim buffer allowing one extra byte for NUL */
    p = xrealloc (p, n+1);
    p[n] = '\0';
    *buf = p;

    return n;
}
示例#25
0
文件: ef.c 项目: OS2World/LIB-libfly
void editor (char *filename, int startpos)
{
    int stop    = FALSE; // exit main loop?
    int fline   = 0;     // no. of first displayed line
    int cline   = 0;     // no. of line with cursor
    int shift   = 0;     // shift to the right
    int ccol    = 0;     // column of the cursor position in the file window

    int        k, i, ndisp, rc, reply;
    char       *p, buf[1024];

    if (editor_open_file (filename) < 0) return;
    cline = min1 (startpos, nl-1);
    fline = max1 (0, cline - video_vsize()/2);

    // enter the loop
    while (1)
    {
        if (stop)
        {
            rc = 0;
            if (changed)
            {
                rc = -1;
                reply = fly_ask (0, "   Save file `%s'?   ", " Yes \n No \n Cancel ", filename);
                if (reply == 1) rc = editor_save_file (filename);
                if (reply == 2) rc = 0;
                if (reply == 3) stop = FALSE;
            }
            if (rc == 0) break;
        }
        
        ndisp = video_vsize()-1;
        // draw the screen
        for (i=0; i<ndisp; i++)
        {
            video_put_n_cell (' ', _BackWhite+_Black, video_hsize(), i, 0);
            if (i+fline < nl)
                editor_display_line (i, fline+i, shift);
        }
        video_put_n_cell (' ', _BackBlue+_White, video_hsize(), video_vsize()-1, 0);
        snprintf1 (buf, sizeof(buf), "L%d:C%d:S%d %c %s%s", cline, ccol, shift, fl_sym.v,
                 changed ? "*" : "", filename);
        video_put (buf, video_vsize()-1, 0);
        video_set_cursor (cline-fline, ccol-shift);
        video_update (0);

        // get a keyboard/mouse event and process it
        k = getmessage (-1);
        if (IS_KEY(k))
        {
            switch (k)
            {
                // Navigation keys
                
            case _Up:
            case _Down:
            case _PgUp:
            case _PgDn:
                fly_scroll_it (k, &fline, &cline, nl, video_vsize()-1);
                break;

            case _Right:
                ccol++;
                if (ccol-shift > video_hsize()-1) shift = ccol-video_hsize()+1;
                break;

            case _Left:
                ccol = max1 (ccol-1, 0);
                if (ccol < shift) shift = ccol;
                break;

            case _Home:
                ccol = 0; shift = 0;
                break;

            case _End:
                ccol = strlen(lines[cline]);
                if (ccol-shift > video_hsize()-1) shift = ccol-video_hsize()+1;
                break;

            case _CtrlHome:
                fline = 0; cline = 0; ccol = 0; shift = 0; break;

            case _CtrlEnd:
                fline = max1 (0, nl-video_vsize()+1);
                cline = min1 (fline+video_vsize()-1, nl-1);
                shift = 0;
                ccol = 0;
                break;

                // Action keys

            case _CtrlY:
                put_clipboard (lines[cline]);
                free (lines[cline]);
                for (i=cline; i<nl-1; i++)
                    lines[i] = lines[i+1];
                nl--;
                changed = TRUE;
                break;

            case _ShiftInsert:
            case _CtrlV:
                p = get_clipboard ();
                if (p == NULL || *p == '\0') break;
                if (nl == na)
                {
                    na *= 2;
                    lines = realloc (lines, sizeof(char *) * na);
                }
                for (i=nl-1; i>cline; i--)
                    lines[i+1] = lines[i];
                lines[cline+1] = p;
                ccol = 0;
                shift = 0;
                cline++;
                if (cline-fline == video_vsize()-1) fline++;
                nl++;
                changed = TRUE;
                break;

            case _BackSpace:
                if (ccol == 0)
                {
                    // ccol == 0: glue this line to the previous
                    if (cline == 0) break;
                    p = malloc (strlen (lines[cline])+strlen(lines[cline-1])+1);
                    strcpy (p, lines[cline-1]);
                    strcat (p, lines[cline]);
                    ccol = strlen (lines[cline-1]);
                    if (ccol-shift > video_hsize()-1) shift = ccol-video_hsize()+1;
                    free (lines[cline-1]);
                    free (lines[cline]);
                    lines[cline-1] = p;
                    for (i=cline; i<nl-1; i++)
                        lines[i] = lines[i+1];
                    cline--;
                    nl--;
                }
                else
                {
                    // ccol != 0: delete char at ccol-1, move cursor left
                    str_delete (lines[cline], lines[cline]+ccol-1);
                    ccol--;
                    if (ccol < shift) shift = ccol;
                }
                changed = TRUE;
                break;

            case _Enter:
                if (nl == na)
                {
                    na *= 2;
                    lines = realloc (lines, sizeof(char *) * na);
                }
                for (i=nl-1; i>cline; i--)
                    lines[i+1] = lines[i];
                if (ccol < strlen (lines[cline]))
                {
                    lines[cline+1] = strdup (lines[cline]+ccol);
                    lines[cline][ccol] = '\0';
                }
                else
                {
                    lines[cline+1] = strdup ("");
                }
                ccol = 0;
                shift = 0;
                cline++;
                if (cline-fline == video_vsize()-1) fline++;
                nl++;
                changed = TRUE;
                break;

            case _Delete:
                if (ccol >= strlen (lines[cline]))
                {
                    // glue previous line to this one
                    if (cline == nl-1) break;
                    p = malloc (ccol+strlen(lines[cline+1])+1);
                    strcpy (p, lines[cline]);
                    memset (p+strlen(lines[cline]), ' ', ccol-strlen(lines[cline]));
                    strcpy (p+ccol, lines[cline+1]);
                    free (lines[cline]);
                    free (lines[cline+1]);
                    lines[cline] = p;
                    for (i=cline+1; i<nl-1; i++)
                        lines[i] = lines[i+1];
                    nl--;
                }
                else
                {
                    // ccol != 0: delete char at ccol-1, move cursor left
                    str_delete (lines[cline], lines[cline]+ccol);
                }
                changed = TRUE;
                break;

            case _F2:
                rc = editor_save_file (filename);
                if (rc == 0) changed = FALSE;
                break;
                
            case _Esc:
            case _F10:
                stop = TRUE; break;

                // character keys
                
            default:
                if (k >= ' ' && k <= 255)
                {
                    str_insert_at (cline, k, ccol);
                    ccol++;
                    changed = TRUE;
                }
            }
        }
        else if (IS_MOUSE(k))
        {
        }
        else if (IS_SYSTEM(k))
        {
            switch (SYS_TYPE(k))
            {
            case SYSTEM_QUIT:
                stop = TRUE; break;
            }
        }
    }

    if (nl != 0 && lines != NULL)
        for (i=0; i<nl; i++)
            free (lines[i]);
    if (na != 0 && lines != NULL) free (lines);
    na = 0;
    lines = NULL;
}
示例#26
0
/* if whichmodel = 0, varipar_plane
   if whichmodel = 1, varipar_hub
*/
void varipar_(int* NSTOT_ptr, int* NFAST_ptr, int* NSLOW_ptr, int whichmodel)
{
     /* recasting pointers */
     int NSTOT = *NSTOT_ptr;
     int NFAST = *NFAST_ptr;
     int NSLOW = *NSLOW_ptr;
     /* renaming used common blocks */
     float* SKYPAR;
     if (whichmodel == 0){
          SKYPAR = skyvar_.skypar;
     }
     if (whichmodel == 1){
          SKYPAR = hubvar_.hubpar;
     }
     int lverb  = tune14_.lverb;
     float SKYGUESS = tune1_.skyguess;
     float* AVA = tune15_.ava;
     int MAX_PERF = tune15_.max_perf;
     float* PARMS = parpred_.parms;
     float*  Z = subraster_.z;
     short int** XX = subraster_.xx;
     float* YE = subraster_.ye;
     float*  A = fitarrays_.a;
     float* FA = fitarrays_.fa;
     float* C_ptr = fitarrays_.c; //note, actually 2x2, but not used, only
                                  //passed to chisq, so not recast here
     int*    IMTYPE  = starlist_.IMTYPE;
     float**  STARPAR = starlist_.starpar;
     float**  SHADOW  = starlist_.shadow;
     float**  SHADERR = starlist_.shaderr;
     int*  WHICH_STAR_MODEL = model_.which_model;

     /* substance of subroutine begins here */
     float* PARWT  = free_parking_.npmaxarray_1;
     float* ROOTS  = free_parking_.npmaxarray_2;
     float* WEIGHT = free_parking_.npmaxarray_3;
     float* PARVAL = free_parking_.npmaxarray_4;
     //none of PARWT, ROOTS, WEIGHT, PARVAL are gaurenteed to be 0, 

     static int MINRMS = 5;
     static int ITSKY  = 100;
     static int K[NPMAX-3];
     static int NK = 4;
     static int frst = 1;// true
     // the 7 following are sky model dependent,
     // first 3 for planar
     static int MINSKY = 25;
     static float SKYACC[NPSKY];
     static float SKYLIM[NPSKY];
     // these 4 for hubble
     static int MINHUB = 100;
     static float HACC[NPHUB];
     static float HLIM[NPHUB];
     float* SKYPARINIT;
     // will use only one set depending on model

     int POSITIVE, GOODSTAR, PERFECT, TYPE1, TYPE3, CONV;
     int I, J;
     int NPERF, NGOOD;
     float SKYMAX, XM, YM;
     float TEMP, USQ, SQ, WT;
     double chisq_return, parinterp_return;
     int NSKYFIT_loc; //passed to chisq
     if (whichmodel == 0){
          NSKYFIT_loc = NSKYFIT;
     }
     if (whichmodel == 1){
          NSKYFIT_loc = NHUBFIT; 
          SKYPARINIT = malloc_float_1darr(NPHUB);
     }

     /* initializing arrays */
     if (frst){
          if (tune4_.nfit2 > 7) NK += (tune4_.nfit2 - 7);
          K[0] = 0;
          K[1] = 4;
          K[2] = 5;
          K[3] = 6;
          if (NK > 4){
               for (I = 4; I < NK; I++){
                    K[I] = I + 3;
               }
          }
          
          if (whichmodel == 0){
               for (J = 0; J < NPSKY; J++){
                    SKYACC[J] = 0.001f;
                    SKYLIM[J] = 0.0f;
               }
          }
          if (whichmodel == 1){
               HACC[0] = 0.01f;
               HACC[1] = -0.1f;
               HACC[2] = -0.1f;
               for (J = 3; J < NPHUB; J++){
                    HACC[J] = 0.1f;
               }
               for (J = 0; J < 4; J++){
                    HLIM[J] = -1.0e-5f;
               }
               for (J = 4; J < NPHUB; J++){
                    HLIM[J] = -1.0e-6f;
               }
          }
          frst = 0;//false
     }

     if (whichmodel == 0){
          for(J = 0; J < NPMAX; J++){
               PARMS[J]  = 0.0f;
          }
     }
     if (whichmodel == 1){
          for(J = 0; J < 4; J++){
               PARMS[K[J]]  = 0.0f;
          }
     }

     //none of PARWT, ROOTS, WEIGHT, PARVAL are gaurenteed to be 0, 
     //so initialize all
     for (J = 0; J < NPMAX; J++){
          PARWT[J]  = 0.0f;
          ROOTS[J]  = 0.0f;
          WEIGHT[J] = 0.0f;
          PARVAL[J] = 0.0f;
     }

     /* TWO PASSES, ONE TO COMPUTE EXPECTED VALUE AND ONE TO COMPUTE RMS */
     CONV  = 1; //true
     NPERF = 0;
     NGOOD = 0;
     SKYMAX = -1.0e-10f;
     for(I = 0; I < NSTOT; I++){
          GOODSTAR = (SHADOW[I][0] > 0.0f);
          TYPE1    = ( (IMTYPE[I] == 1) || (IMTYPE[I] == 11) );
          TYPE3    = ( (IMTYPE[I] == 3) || (IMTYPE[I] == 13) );
          PERFECT  = ( (GOODSTAR) && (TYPE1) );
          PERFECT  = ( (PERFECT) && (WHICH_STAR_MODEL[I] == 0));
          GOODSTAR = ( (GOODSTAR) && (TYPE1 || TYPE3) );
          if ( (PERFECT) && (NPERF <= MAX_PERF) ){
               PARWT[0]  += 1.0f;
               PARVAL[0] += STARPAR[I][0];
               for (J = 1; J < NK; J++){
                    TEMP = 1.0f/SHADERR[I][K[J]];
                    PARWT[K[J]] += TEMP;
                    PARVAL[K[J]] += TEMP*SHADOW[I][K[J]];
               }
               NPERF     += 1;
          }
          if (GOODSTAR){
               if (NGOOD < MAXFIL){ //MAXFIL is the dimension of subraster arrays
                    if (STARPAR[I][0] > SKYMAX){
                         SKYMAX = STARPAR[I][0];
                         /* Changed indices. */
                         XM = STARPAR[I][2];
                         YM = STARPAR[I][3];
                    }
                    NGOOD += 1;
                    /* Changed indices. */
                    XX[NGOOD-1][0] = (short int)(STARPAR[I][2] + 0.5f);
                    XX[NGOOD-1][1] = (short int)(STARPAR[I][3] + 0.5f);
                    Z[NGOOD-1]  = STARPAR[I][0];
                    YE[NGOOD-1]  = 1.0f;
               }
          } 
     } //end I loop
     
     if (lverb > 10){
          fprintf(logfile, "# of stars available for computing typical ");
          fprintf(logfile, "SHAPE (Nperf) = %d \n", NPERF);
          fprintf(logfile, "# of stars available for computing ");
          fprintf(logfile, "MODEL SKY (Ngood) = %d \n", NGOOD);
     }

     if (NPERF >= 1){
          for(J = 0; J < NK; J++){
               PARVAL[K[J]] = PARVAL[K[J]]/PARWT[K[J]];
               AVA[K[J]]    = PARVAL[K[J]];
          } 
          if (lverb > 10){
               fprintf(logfile, "WEIGHTED MEANS: ");
               for(J = 0; J < NPMAX; J++){
                    fprintf(logfile, "%f ", PARVAL[J]);
               }
               fprintf(logfile, "\n");
          }

          if (whichmodel == 0){
               if (NGOOD >= MINSKY){
                    if (SKYPAR[0] == 0.0f){
                         SKYPAR[0] = AVA[0];
                         for(J = 1; J < NPSKY; J++){
                              SKYPAR[J] = 0.0f;
                         }
                    }
                    /* Call the appropriate sky function. */
                    /* skyfun_ declared in skyfun_plane.h */
                    chisq_return = chisq_(&skyfun_, XX, Z, YE, &NGOOD, 
                                          SKYPAR, FA, C_ptr, &NSKYFIT_loc, 
                                          SKYACC, SKYLIM, &ITSKY); 
               }
               else{
                    SKYPAR[0] = AVA[0];
                    for(J = 1; J < NPSKY; J++){
                         SKYPAR[J] = 0.0f;
                    }
               } //end NGOOD> MINSKY if/else
          }

          if (whichmodel == 1){
               if (NGOOD >= MINHUB){
                    if (SKYPAR[3] == 0.0f){
                         SKYPAR[0] = SKYGUESS;
                         SKYPAR[1] = XM;
                         SKYPAR[2] = YM;
                         SKYPAR[3] = SKYMAX - SKYPAR[0];
                         SKYPAR[4] = (float)NFAST;
                         SKYPAR[5] = 0.0f;
                         SKYPAR[6] = (float)NSLOW;
                    }
                    for(J = 0; J < NPHUB; J++){
                         SKYPAR[J] = SKYPAR[J];
                    }
                    /* Call the appropriate sky function. */
                    /* hubfun_ declared in skyfun_hub.h */
                    chisq_return = chisq_(&hubfun_, XX, Z, YE, &NGOOD,
                                          SKYPAR, FA, C_ptr, &NSKYFIT_loc,
                                          HACC, HLIM, &ITSKY);
                    CONV = ((float)chisq_return < 1.0e10f);
                    if (!CONV){
                         for(J = 0; J < NPHUB; J++){
                              SKYPAR[J] = SKYPARINIT[J];
                         }
                    }
               }
               else{
                    SKYPAR[0] = SKYGUESS;
                    SKYPAR[1] = (float)NFAST/2.0f;
                    SKYPAR[2] = (float)NSLOW/2.0f;
                    SKYPAR[3] = 0.0f;
                    SKYPAR[4] = (float)NFAST;
                    SKYPAR[5] = 0.0f;
                    SKYPAR[6] = (float)NSLOW;
               }
               if (lverb > 10){
                    fprintf(logfile, "HUBFUN PARAMETERS: \n");
                    for(J = 0; J < NSKYFIT_loc; J++){
                         fprintf(logfile, "%f ", SKYPAR[J]);
                    }
                    fprintf(logfile, "\n");
               }
          }

          if (lverb > 10){
               if (whichmodel == 0){
                    fprintf(logfile, "SKYFUN PARAMETERS: \n");
               }
               if (whichmodel == 1){
                    fprintf(logfile, "HUBFUN PARAMETERS: \n");
               }
               for(J = 0; J < NSKYFIT_loc; J++){
                    fprintf(logfile, "%f ", SKYPAR[J]);
               }
               fprintf(logfile, "\n");
          }
          if (NPERF >= MINRMS){
               for(I = 0; I < NSTOT; I++){
                    PERFECT = ( (IMTYPE[I] == 1) || (IMTYPE[I] == 11) );
                    PERFECT = ( (PERFECT) && (SHADOW[I][0] != 0.0f) );
                    PERFECT = ( (PERFECT) && (WHICH_STAR_MODEL[I] == 0) );
                    if (PERFECT){
                         /* Changed indices. */
                         parinterp_return = parinterp_(STARPAR[I]+2, STARPAR[I]+3, A);
                         for (J = 0; J < 4; J++){
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
C:  I HAVE CONVINCED MYSELF THAT THE UNCERTAINTY PER RESIDUAL SQUARED IS
C:  IS 2*DELTA*(O-C).  BUT IF I USE 1/THIS AS A WEIGHT, ACCIDENTAL CANCELLATIONS
C:  GIVE SCREWEY RESULTS.  SO WE'LL TAKE THE LARGER OF O-C**2 AND SHADERR.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
                              USQ = (SHADOW[I][K[J]] - A[K[J]]);
                              SQ  = USQ*USQ;
                              WT  = (1.0f/SHADERR[I][K[J]]) /max1(SHADERR[I][K[J]],SQ);
                              WEIGHT[K[J]] += WT;
                              PARMS[K[J]]  += WT*SQ;
                         }
                    }
               }//end I loop
               POSITIVE = 1; //true
               for(J = 0; J < 4; J++){
                    PARMS[K[J]] = PARMS[K[J]]/WEIGHT[K[J]];
                    POSITIVE = ( POSITIVE && (PARMS[K[J]] >= 0.0f) );
                    if (PARMS[K[J]] >= 0.0f){
                         ROOTS[K[J]] = sqrtf(PARMS[K[J]]);
                    }
                    else{
                         if (lverb > 10){
                              fprintf(logfile, "NEGATIVE SCATTER : \n");
                              fprintf(logfile, "PARAM# & SCATTER = %d %f \n",
                                                K[J], PARMS[K[J]]);
                         } 
                         PARMS[K[J]] = 0.0f;
                         ROOTS[K[J]] = 0.0f;
                    }
               }// end J loop
               if (lverb > 10){
                    fprintf(logfile, "SCATTER:");
                    for(J = 0; J < NPMAX; J++){
                         fprintf(logfile, "%f ", ROOTS[J]);
                    }
                    fprintf(logfile, "\n");
               } 
          }//end NPERF > MINRMS if

     }
     else{
          if (whichmodel == 0){
               SKYPAR[0] = AVA[0];
               for(J = 1; J < NPSKY; J++){
                    SKYPAR[J] = 0.0f;
               }  
          }
          if (whichmodel == 1){
               SKYPAR[0] = SKYGUESS;
               SKYPAR[1] = (float)NFAST/2.0f;
               SKYPAR[2] = (float)NSLOW/2.0f;
               SKYPAR[3] = 0.0f;
               SKYPAR[4] = (float)NFAST;
               SKYPAR[5] = 0.0f;
               SKYPAR[6] = (float)NSLOW;
          }
  
          if (lverb > 10){
               if (whichmodel == 0){
                    fprintf(logfile, "SKYFUN PARAMETERS: \n");
               }
               if (whichmodel == 1){
                    fprintf(logfile, "HUBFUN PARAMETERS: \n");
               }
               for(J = 0; J < NSKYFIT_loc; J++){
                    fprintf(logfile, "%f ", SKYPAR[J]);
               }
               fprintf(logfile, "\n");
          }
     }// end NPERF >=1 if/else

     /* free locally allocated memory */
     if (whichmodel == 1){
          free(SKYPARINIT);
     }
}
示例#27
0
///
//Performs a dynamic collision check between a moving AABB and a static AABB.
//
//Overview:
//	This algorithm detects potentially missed collisions by performing a moving version of the 
//	separating axis test. First we must determine the distances along each axis signifying
//	the distance to begin collision (dFirst) & the distance to separate from that collision (dLast). Then
//	we can easily determine the time at which these distances will be reached by dividing them by the magnitude of the
//	velocity along the axis (tFirst / tLast). If we keep the largest tFirst and the smallest tLast from all axes,
//	we will determine the time interval which the boxes will be intersecting! If tLast < tFirst, the boxes will not overlap.
//	Alternatively, if tFirst > 1.0f,  the boxes will not overlap!
//
//Parameters:
//	aabb1: The moving aabb
//	aabb2: The static aabb
//	mvmt: The relative movement vector of box 1 from an observer on box 2
//
//Returns:
//	a t value between 0 and 1 indicating the "relative time" since the start of this frame that the collision occurred.
//	a t value of 0.0f would indicate the very start of this frame, a t value of 1.0f would indicate the very end of this frame.
float CheckDynamicCollision(const AABB &aabb1, const AABB &aabb2, const glm::vec3 &mvmt)
{
	//If we start out colliding, we do not need to perform the test.
	if (CheckCollision(aabb1, aabb2))
	{
		return 0.0f;
	}

	float tFirst = 0.0f;
	float tLast = 1.0f;
	float tCurrent = 0.0f;

	//Get the minimum and maximum dimensions in world space for each box
	glm::vec2 min1(aabb1.center - (aabb1.dimensions*0.5f));
	glm::vec2 max1(aabb1.center + (aabb1.dimensions*0.5f));
	glm::vec2 min2(aabb2.center - (aabb2.dimensions*0.5f));
	glm::vec2 max2(aabb2.center + (aabb2.dimensions*0.5f));

	//For every axis (X, and Y axes in this case)
	for (int i = 0; i < 3; i++)
	{
		//Check the direction of the projection of the movement vector on this axis
		if (mvmt[i] < 0.0f)
		{
			//In this case object 1 is moving in the negative direction along axis from an observer on object 2.
			//So if object 1 is more negative in direction than object 2, they will not collide on this axis.
			if (max1[i] < min2[i]) return -1.0f;
			//Is the "low part" object 1 higher than the "high part" object 2 along this axis?
			if (min1[i] > max2[i])
			{
				//If so, the shapes are not yet colliding on this axis, so determine when they first will collide on this axis
				tCurrent = (max2[i] - min1[i]) / mvmt[i];		//We solve for a negative distance here, because we are dividing by a negative velocity to get a positive time
				//This strange ordering prevents us from needing to make a call to fabs (absolute value function)
				//If it is larger than the current tFirst, change tFirst
				if (tCurrent > tFirst) tFirst = tCurrent;
			}
			//Is the "High Part" of object 1 higher than the low part of object 2 along this axis?
			if (max1[i] > min2[i])
			{
				//If so, the shapes have not yet separated on this axis, so determine when they will finish colliding
				tCurrent = (min2[i] - max1[i]) / mvmt[i];		//Note the wierd ordering again, for the same reason as above
				//If it is smaller than current tLast, update tLast
				if (tCurrent < tLast) tLast = tCurrent;
			}
		}
		else if (mvmt[i] > 0.0f)
		{
			//If object 1 is more positive along the axis than object 2, they will not collide
			if (min1[i] > max2[i]) return -1.0f;
			//Is the "High part" of object 1 lower than the "low part" of object 2 along this axis?
			if (max1[i] < min2[i])
			{
				//If so, the shapes are not yet colliding on this axis so determine when they will first collide on this axis
				tCurrent = (min2[i] - max1[i]) / mvmt[i];
				//If it is larger than the current tFirst, update tFirst
				if (tCurrent > tFirst) tFirst = tCurrent;
			}
			//Is the "Low part" of object 1 lower than the "high part" of object 2 along this axis?
			if (min1[i] < max2[i])
			{
				//If so, the shapes have not yet separated on this axis, so determine when they will finish collidiing
				tCurrent = (max2[i] - min1[i]) / mvmt[i];
				//If it is smaller than the current tLast, update tLast
				if (tCurrent < tLast) tLast = tCurrent;
			}
		}
	}

	//If there was no overlap
	if (tLast < tFirst) return -1.0f;

	return tFirst;

}
int main(int argc, char **argv) {
  MPI_Init(&argc, &argv);

  QUESO::EnvOptionsValues options;
  options.m_numSubEnvironments = 1;
  options.m_subDisplayFileName = "outputData/testIntersectionSubsetContains";
  options.m_subDisplayAllowAll = 0;
  options.m_subDisplayAllowedSet.insert(0);
  options.m_seed = 1.0;
  options.m_checkingLevel = 1;
  options.m_displayVerbosity = 55;

  QUESO::FullEnvironment *env = new QUESO::FullEnvironment(MPI_COMM_WORLD, "",
            "", &options);

  std::vector<std::string> names(1);
  names[0] = "my_name";

  // Create a vector space
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> vec_space(*env,
      "vec_prefix", 1, &names);

  // Create two vector sets
  QUESO::GslVector min1(vec_space.zeroVector());
  min1[0] = 0.0;
  QUESO::GslVector max1(vec_space.zeroVector());
  max1[0] = 1.0;
  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> set1("set1", vec_space,
      min1, max1);

  // Now for the second one
  QUESO::GslVector min2(vec_space.zeroVector());
  min2[0] = 0.5;
  QUESO::GslVector max2(vec_space.zeroVector());
  max2[0] = 1.5;
  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> set2("set1", vec_space,
      min2, max2);

  // Create their intersection
  QUESO::IntersectionSubset<QUESO::GslVector, QUESO::GslMatrix> intersection(
      "intersection", vec_space, 1.0, set1, set2);

  // Test the containment
  bool does_contain;
  QUESO::GslVector test_vec(vec_space.zeroVector());

  // Should be true
  test_vec[0] = 0.75;
  does_contain = intersection.contains(test_vec);
  if (!does_contain) {
    std::cerr << "First IntersectionSubset contains test failed" << std::endl;
    return 1;
  }

  // Should be false
  test_vec[0] = 2.0;
  does_contain = intersection.contains(test_vec);
  if (does_contain) {
    std::cerr << "Second contains test failed" << std::endl;
    return 1;
  }

  // Print out some info
  intersection.print(std::cout);

  MPI_Finalize();

  return 0;
}
示例#29
0
static BOOL CALLBACK EditBookMarkProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	HMENU hMenu;
	MENUITEMINFO mInfo;
	int Cur;
	int Max;
	char Tmp[BMARK_MARK_LEN + FMAX_PATH * 2 + BMARK_SEP_LEN + 1];

	static DIALOGSIZE DlgSize = {
		{ BMARK_NEW, BMARK_SET, BMARK_DEL, BMARK_DOWN, BMARK_UP, IDHELP, BMARK_SIZEGRIP, -1 },
		{ IDOK, BMARK_JUMP, BMARK_SIZEGRIP, -1 },
		{ BMARK_LIST, -1 },
		{ 0, 0 },
		{ 0, 0 }
	};

	switch (message)
	{
		case WM_INITDIALOG :
			if(ListFont != NULL)
				SendDlgItemMessage(hDlg, BMARK_LIST, WM_SETFONT, (WPARAM)ListFont, MAKELPARAM(TRUE, 0));

			hMenu = GetSubMenu(GetMenu(GetMainHwnd()), BMARK_SUB_MENU);
			Max = GetMenuItemCount(hMenu);
			for(Cur = DEFAULT_BMARK_ITEM; Cur < Max; Cur++)
			{
				mInfo.cbSize = sizeof(MENUITEMINFO);
				mInfo.fMask = MIIM_TYPE;
				mInfo.dwTypeData = Tmp;
				mInfo.cch = FMAX_PATH;
				if(GetMenuItemInfo(hMenu, Cur, TRUE, &mInfo) == TRUE)
					SendDlgItemMessage(hDlg, BMARK_LIST, LB_ADDSTRING, 0, (LPARAM)Tmp);
			}
			DlgSizeInit(hDlg, &DlgSize, &BmarkDlgSize);
		    return(TRUE);

		case WM_COMMAND :
			switch(GET_WM_COMMAND_ID(wParam, lParam))
			{
				case BMARK_JUMP :
					if((Cur = SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCURSEL, 0, 0)) != LB_ERR)
						PostMessage(GetMainHwnd(), WM_COMMAND, MAKEWPARAM(Cur+MENU_BMARK_TOP, 0), 0);
					/* ここに break はない */

				case IDCANCEL :
				case IDOK :
					ClearBookMark();
					Max = SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCOUNT, 0, 0);
					for(Cur = 0; Cur < Max; Cur++)
					{
						SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETTEXT, Cur, (LPARAM)Tmp);
						AddBookMark(Tmp);
					}
					AskDlgSize(hDlg, &DlgSize, &BmarkDlgSize);
					EndDialog(hDlg, YES);
					break;

				case BMARK_SET :
					if((Cur = SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCURSEL, 0, 0)) != LB_ERR)
					{
						SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETTEXT, Cur, (LPARAM)Tmp);
						if(DialogBoxParam(GetFtpInst(), MAKEINTRESOURCE(bmark_edit_dlg), hDlg, BookMarkEditCallBack, (LPARAM)Tmp) == YES)
						{
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_DELETESTRING, Cur, 0);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_INSERTSTRING, Cur, (LPARAM)Tmp);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_SETCURSEL, Cur, 0);
						}
					}
					break;

				case BMARK_NEW :
					strcpy(Tmp, "");
					if(DialogBoxParam(GetFtpInst(), MAKEINTRESOURCE(bmark_edit_dlg), hDlg, BookMarkEditCallBack, (LPARAM)Tmp) == YES)
					{
						SendDlgItemMessage(hDlg, BMARK_LIST, LB_ADDSTRING, 0, (LPARAM)Tmp);
						Cur = SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCOUNT, 0, 0) - 1;
						SendDlgItemMessage(hDlg, BMARK_LIST, LB_SETCURSEL, Cur, 0);
					}
					break;

				case BMARK_DEL :
					if((Cur = SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCURSEL, 0, 0)) != LB_ERR)
					{
						SendDlgItemMessage(hDlg, BMARK_LIST, LB_DELETESTRING, Cur, 0);
						if(Cur >= SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCOUNT, 0, 0))
							Cur = max1(0, SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCOUNT, 0, 0)-1);
						if(SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCOUNT, 0, 0) > 0)
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_SETCURSEL, Cur, 0);
					}
					break;

				case BMARK_UP :
					if((Cur = SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCURSEL, 0, 0)) != LB_ERR)
					{
						if(Cur > 0)
						{
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETTEXT, Cur, (LPARAM)Tmp);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_DELETESTRING, Cur, 0);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_INSERTSTRING, --Cur, (LPARAM)Tmp);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_SETCURSEL, Cur, 0);
						}
					}
					break;

				case BMARK_DOWN :
					if((Cur = SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCURSEL, 0, 0)) != LB_ERR)
					{
						if(Cur < SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETCOUNT, 0, 0)-1)
						{
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_GETTEXT, Cur, (LPARAM)Tmp);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_DELETESTRING, Cur, 0);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_INSERTSTRING, ++Cur, (LPARAM)Tmp);
							SendDlgItemMessage(hDlg, BMARK_LIST, LB_SETCURSEL, Cur, 0);
						}
					}
					break;

				case IDHELP :
					hHelpWin = HtmlHelp(NULL, AskHelpFilePath(), HH_HELP_CONTEXT, IDH_HELP_TOPIC_0000019);
					break;
			}
			return(TRUE);

		case WM_SIZING :
			DlgSizeChange(hDlg, &DlgSize, (RECT *)lParam, (int)wParam);
		    return(TRUE);

	}
    return(FALSE);
}
示例#30
0
/*	Returns a matrix made up with the coordinates of intersecting points in the World frame of b1 that are within b2. If there are none, it returns a zero 3x8 matrix.
*/
Mat<float> testOBBOBB( RigidBody& b1, RigidBody& b2, bool& intersect)
{
	float precision = 1e-3f;
	Mat<float> ret((float)0,3,1);
	bool initialized = false;
	BoxShape& box1 = (BoxShape&)(b1.getShapeReference());
	BoxShape& box2 = (BoxShape&)(b2.getShapeReference());
	
	Mat<float> pointsB1((float)0,3,8);
	//register the position of the 8 points composing b1:
	Mat<float> min1((float)0,3,1);
	Mat<float> max1((float)0,3,1);
	
	min1.set( -box1.getHeight()/2.0f, 1,1);
	min1.set( -box1.getWidth()/2.0f, 2,1);
	min1.set( -box1.getDepth()/2.0f, 3,1);
	max1.set( -min1.get(1,1), 1,1);
	max1.set( -min1.get(2,1), 2,1);
	max1.set( -min1.get(3,1), 3,1);
	
	int col = 1;
	Mat<float> temp(3,1);
	Mat<float> voronoiTemp(3,1);
	
	for(int pm1=2;pm1--;)
	{
		for(int pm2=2;pm2--;)
		{
			for(int pm3=2;pm3--;)
			{
				Mat<float> tempL(3,1);
				tempL.set( pm1*( min1.get(1,1) ) + (1-pm1)*( max1.get(1,1) ), 1,1);
				tempL.set( pm2*( min1.get(2,1) ) + (1-pm2)*( max1.get(2,1) ), 2,1);
				tempL.set( pm3*( min1.get(3,1) ) + (1-pm3)*( max1.get(3,1) ), 3,1);
				
				
				//--------------------
				//let us compute its coordinate in the world frame :
				temp = b1.getPointInWorld( tempL);
#ifdef debug				
				b1.getPose().exp().afficher();
				b2.getPose().exp().afficher();
				tempL.afficher();
				temp.afficher();
#endif
				//----------------------
				//let us find its associated projected point :
				voronoiTemp = closestPointWOfBOXGivenPointW( b2, temp);
				
				//----------------------
				//let us find out if there was an intersection
				// <==> voronoiTemp = temp, because it would means that the projected point is already the closest to b2 for it is within it.
				if( equals(voronoiTemp,temp,precision) )
				{
					//let us refill pointsB1 with it :
					pointsB1.set( temp.get(1,1), 1,col);
					pointsB1.set( temp.get(2,1), 2,col);
					pointsB1.set( temp.get(3,1), 3,col);
					
					if(initialized)
					{
						ret = operatorL( ret, temp);
					}
					else
					{
						initialized = true;
						ret = temp;
					}
					intersect = true;
					
#ifdef debug
std::cout << "COLLISION DETECTOR : midnarrowphase : testOBBOBB : voronoi and temp : " << std::endl;
std::cout << " ids : b1 = " << b1.getID() << " ; b2 = " << b2.getID() << std::endl;
operatorL(voronoiTemp,temp).afficher();
//std::cout << "COLLISION POINTS :" << std::endl;
//ret.afficher();
//tempL.afficher();
#endif				
				}
				else
				{
#ifdef debug
std::cout << "COLLISION DETECTOR : ELSE : midnarrowphase : testOBBOBB : voronoi and temp : " << std::endl;
std::cout << " ids : b1 = " << b1.getID() << " ; b2 = " << b2.getID() << std::endl;
operatorL(voronoiTemp,temp).afficher();
//std::cout << "COLLISION POINTS :" << std::endl;
//ret.afficher();
//tempL.afficher();
#endif
				}
				
				
				col++;
			}
		}
	}
	
	return ret;
}