Beispiel #1
0
void mrqmin(float x[], float y[], float sig[], int ndata, float a[], int ia[],
	int ma, float **covar, float **alpha, float *chisq,
	void (*funcs)(float, float [], float *, float [], int), float *alamda)
{
	void covsrt(float **covar, int ma, int ia[], int mfit);
	void gaussj(float **a, int n, float **b, int m);
	void mrqcof(float x[], float y[], float sig[], int ndata, float a[],
		int ia[], int ma, float **alpha, float beta[], float *chisq,
		void (*funcs)(float, float [], float *, float [], int));
	int j,k,l,m;
	static int mfit;
	static float ochisq,*atry,*beta,*da,**oneda;

	if (*alamda < 0.0) {
		atry=vector(1,ma);
		beta=vector(1,ma);
		da=vector(1,ma);
		for (mfit=0,j=1;j<=ma;j++)
			if (ia[j]) mfit++;
		oneda=matrix(1,mfit,1,1);
		*alamda=0.001;
		mrqcof(x,y,sig,ndata,a,ia,ma,alpha,beta,chisq,funcs);
		ochisq=(*chisq);
		for (j=1;j<=ma;j++) atry[j]=a[j];
	}
	for (j=0,l=1;l<=ma;l++) {
		if (ia[l]) {
			for (j++,k=0,m=1;m<=ma;m++) {
				if (ia[m]) {
					k++;
					covar[j][k]=alpha[j][k];
				}
			}
			covar[j][j]=alpha[j][j]*(1.0+(*alamda));
			oneda[j][1]=beta[j];
		}
	}
	gaussj(covar,mfit,oneda,1);
	for (j=1;j<=mfit;j++) da[j]=oneda[j][1];
	if (*alamda == 0.0) {
		covsrt(covar,ma,ia,mfit);
		free_matrix(oneda,1,mfit,1,1);
		free_vector(da,1,ma);
		free_vector(beta,1,ma);
		free_vector(atry,1,ma);
		return;
	}
	for (j=0,l=1;l<=ma;l++)
		if (ia[l]) atry[l]=a[l]+da[++j];
	mrqcof(x,y,sig,ndata,atry,ia,ma,covar,da,chisq,funcs);
	if (*chisq < ochisq) {
		*alamda *= 0.1;
		ochisq=(*chisq);
		for (j=0,l=1;l<=ma;l++) {
			if (ia[l]) {
				for (j++,k=0,m=1;m<=ma;m++) {
					if (ia[m]) {
						k++;
						alpha[j][k]=covar[j][k];
					}
				}
				beta[j]=da[j];
				a[l]=atry[l];
			}
		}
	} else {
		*alamda *= 10.0;
		*chisq=ochisq;
	}
}
/*!\rst
  Check that ``Ax`` works for the special cases of ``A`` being:

  1. triangular
  2. symmetric

  Assuming that dgemv() is correct, we then check (using random matrices):

  1. Assert that dtrmv (triangular) matches dgemv for the appropriate matrices.
  2. Assert that dsymv (symmetric) match dgemv for the appropriate matrices.

  \return
    number of cases where matrix-vector multiply does not match triangular or symmetric specialized multiplies.
\endrst*/
OL_WARN_UNUSED_RESULT int TestSpecialMatrixVectorMultiply() {
  int total_errors_dsymv = 0;
  int total_errors_dtrmv = 0;
  int total_errors_dtrmv_T = 0;
  const int num_tests = 3;
  const int sizes[num_tests] = {3, 11, 20};

  UniformRandomGenerator uniform_generator(34187);
  for (int i = 0; i < num_tests; ++i) {
    std::vector<double> matrix(sizes[i]*sizes[i]);
    std::vector<double> lower_triangular_part_matrix(sizes[i]*sizes[i]);
    std::vector<double> upper_triangular_part_matrix(sizes[i]*sizes[i]);
    std::vector<double> multiplicand_vector(sizes[i]);
    std::vector<double> product_by_dgemv(sizes[i]);
    std::vector<double> product_by_dsymv(sizes[i]);
    std::vector<double> product_by_dtrmv(sizes[i]);

    BuildRandomSymmetricMatrix(sizes[i], -1.0, 1.0, &uniform_generator, matrix.data());
    ExtractLowerTriangularPart(matrix.data(), sizes[i], lower_triangular_part_matrix.data());
    BuildRandomVector(sizes[i], -2.0, 2.0, &uniform_generator, multiplicand_vector.data());

    // testing dsymv
    // generate truth value
    GeneralMatrixVectorMultiply(matrix.data(), 'N', multiplicand_vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_by_dgemv.data());

    // generate test value
    // note: dsymv does not access the upper triangular part, so we will check this
    // by giving it a matrix where that region is all 0s
    SymmetricMatrixVectorMultiply(lower_triangular_part_matrix.data(), multiplicand_vector.data(), sizes[i], product_by_dsymv.data());

    for (int j = 0; j < sizes[i]; ++j) {
      if (!CheckDoubleWithinRelative(product_by_dsymv[j], product_by_dgemv[j], 1000*std::numeric_limits<double>::epsilon())) {
        ++total_errors_dsymv;
      }
    }

    // testing dtrmv, no transpose
    // generate truth value
    GeneralMatrixVectorMultiply(lower_triangular_part_matrix.data(), 'N', multiplicand_vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_by_dgemv.data());

    // generate test value
    // note: dsymv does not access the upper triangular part, so we will check this
    // by giving it a matrix where that region is populated
    std::copy(multiplicand_vector.begin(), multiplicand_vector.end(), product_by_dtrmv.begin());
    TriangularMatrixVectorMultiply(matrix.data(), 'N', sizes[i], product_by_dtrmv.data());

    for (int j = 0; j < sizes[i]; ++j) {
      if (!CheckDoubleWithinRelative(product_by_dtrmv[j], product_by_dgemv[j], 1000*std::numeric_limits<double>::epsilon())) {
        ++total_errors_dtrmv;
      }
    }

    // testing dtrmv, transpose
    // generate truth value
    GeneralMatrixVectorMultiply(lower_triangular_part_matrix.data(), 'T', multiplicand_vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_by_dgemv.data());

    // generate test value
    // note: dsymv does not access the upper triangular part, so we will check this
    // by giving it a matrix where that region is populated
    std::copy(multiplicand_vector.begin(), multiplicand_vector.end(), product_by_dtrmv.begin());
    TriangularMatrixVectorMultiply(matrix.data(), 'T', sizes[i], product_by_dtrmv.data());

    for (int j = 0; j < sizes[i]; ++j) {
      if (!CheckDoubleWithinRelative(product_by_dtrmv[j], product_by_dgemv[j], 1000*std::numeric_limits<double>::epsilon())) {
        ++total_errors_dtrmv_T;
      }
    }
  }

  if (total_errors_dsymv != 0) {
    OL_ERROR_PRINTF("dsymv failed\n");
  }
  if (total_errors_dtrmv != 0) {
    OL_ERROR_PRINTF("dtrmv failed\n");
  }
  if (total_errors_dtrmv_T != 0) {
    OL_ERROR_PRINTF("dtrmv_T failed\n");
  }

  return total_errors_dsymv + total_errors_dtrmv + total_errors_dtrmv_T;
}
Beispiel #3
0
bool Do_matrix_smoothings()
{
	int   loop, col, loop2, x, y;
	float prev_alpha, **m_stack[MAX_SPP_COUNT];
	char  txt[1024];

	hmat = fpmatrix(0,yd,0,xd); // compulsory
	if (!hmat)
		return false;
	for(y=0;y<=yd;y++)
		for(x=0; x<=xd; x++)
			hmat[y][x]=0;

	if (comm_set.edge_effect_fn!="")
	{
		Form1->Memo1->Lines->Add("Loading edge correction file from "+comm_set.edge_effect_fn);
		EdgeFixMap.normalize = false;     // xxxEdgeFix
		if (!EdgeFixMap.load_from_file(comm_set.edge_effect_fn, 0, 0))
		{
			use_edge_fix=false;
			Form1->Memo1->Lines->Add("WARNING: load unsuccessful - NOT using edge corrections.");
			Form1->Memo1->Lines->Add("");
		}
		else
		{
			use_edge_fix=true;
			Form1->Memo1->Lines->Add("      *** load successful");
		}
		if (use_edge_fix)
		{
			edge_corr_mat = matrix(0,yd,0,xd);
		}
	}

	for(y=0;y<yd;y++)
	{
		for(x=0;x<xd;x++)
		{
			if (vmat[y][x])
			{
				hmat[y][x]= (float *)calloc(comm_set.ct_cnt+1, sizeof(float));
				if (!hmat[y][x])
				{
					ShowMessage("out of memory allocating for matrix connectivity");
					return false; // dealloc???
				}
				for(loop=0; loop<comm_set.ct_cnt; loop++)
					hmat[y][x][loop]=0.0f;
			}
		}
	}
#if 0
	for(loop=0; loop<comm_set.ct_cnt; loop++)
	{
		m_stack[loop] = matrix(0,yd,0,xd);
		if (!m_stack[loop])
		{
			ShowMessage("Out of memory allocating matrix connectivity clalculation memory, matrix # "+IntToStr(loop));
			for(loop2=0; loop2<loop; loop2++)
				free_matrix(m_stack[loop2], 0,yd,0,xd);
			return;
		}
	}
#endif

	prev_alpha=-123456.1f;
	float ed_max=-100000;
	float ed_min=1000000;
	for(loop=0; loop<comm_set.ct_cnt; loop++)
	{
		Application->ProcessMessages();

		if (spp[loop].alpha!=prev_alpha)
		{
		  calc_fftwf_kernel(spp[loop].alpha, spp[loop].grp_arb_kernel_matrix);
		  prev_alpha=spp[loop].alpha;
		  if (use_edge_fix)
		    {
		      copy_matrix_to_fftwf_LS_edge(0, EdgeFixMap.m);
		      //              copy_matrix_to_fftwf_LS(0, EdgeFixMap.m);
		      fftwf_connectivity();
		      for(y=0; y<yd; y++)
			for(x=0; x<xd; x++)
			  {
			    edge_corr_mat[y][x] = conn_LS[y][x];
			    if (edge_corr_mat[y][x]<ed_min)
			      ed_min=edge_corr_mat[y][x];
			    if (edge_corr_mat[y][x]>ed_max)
			      ed_max=edge_corr_mat[y][x];
			  }
		      Form1->Memo1->Lines->Add("Edge correction matrix min - max values are " + FloatToStr(ed_min)+ "  " +FloatToStr(ed_max));
		    }
		}

		copy_occ_to_fftwf_LS(0, 0, sim_mat[loop][0]);
		for(col=1; col<comm_set.ct_cnt; col++)
			copy_occ_to_fftwf_LS(col, 1, sim_mat[loop][col]);
		Application->ProcessMessages();

		fftwf_connectivity();

		//      multiply_smoothed_distr_to(loop, 1.0f);
		save_smoothed_distr_to_matrix(loop, 1.0f, use_edge_fix, edge_corr_mat);//, m_stack[loop]);

		sprintf(txt, "Input feature %i transformed via matrix connectivity calculations using alpha %f.",
			loop, spp[loop].alpha);

		Form1->Memo1->Lines->Add(txt);
		Application->ProcessMessages();
	}

	for(y=0; y<yd; y++)
		for(x=0; x<xd; x++)
			if (vmat[y][x])
			{
				for(loop=0; loop<comm_set.ct_cnt; loop++)
					if (vmat[y][x][loop]!=-1)
						vmat[y][x][loop]=hmat[y][x][loop]; //m_stack[loop][y][x];
			}

	//  for(loop=0; loop<comm_set.ct_cnt; loop++)
	//    free_matrix(m_stack[loop], 0,yd,0,xd);

	if (hmat)
	{
		for(y=0; y<yd; y++)
			for(x=0; x<xd; x++)
				if (hmat[y][x])
				{
					free(hmat[y][x]);
					hmat[y][x]=0;
				}
		free_fpmatrix(hmat, 0,yd,0,xd);
		hmat=0;
	}

	if (use_edge_fix)
	{
		EdgeFixMap.free_matrix_m();
		free_matrix(edge_corr_mat, 0,yd,0,xd);
	}

	return true;
}
Beispiel #4
0
void hessian(int nshots, int SHOTINC, float *** green_vx, float *** greeni_vx, float *** green_vy, float *** greeni_vy, float *** green_sxx, float *** greeni_sxx, float *** green_syy, float *** greeni_syy,
             float *** green_sxy, float *** greeni_sxy, float ** prho, float ** pu, float ** ppi){
  
extern float DT,TIME;
extern float FC_HESSIAN;        	
extern int NX, NY, IDX, IDY, DTINV, INVMAT1, MYID, POS[4], FDORDER;
extern char JACOBIAN[STRING_SIZE];

/* local variables */
int i, j, k, l, ns_hess, ishot, irec, nd, NSRC_HESSIAN, RECINC;
double trig1,trig2;
double t=0.0;
const double pi=4.0*atan(1.0);
char jac[STRING_SIZE];

float complex green_x, green_y, tmp_mu1_shot, tmp_mu2_shot, tmp_mu3_shot, tmp_mu5_shot, tmp_mu6_shot;
float tmp_mu1, tmp_mu2, tmp_mu3;
float complex tmp_jac_lam, tmp_jac_mu, tmp_jac_rho, tmp_jac_vp, tmp_jac_vs, tmp_fft_fsignal;

float ** abs_green, omega, mulamratio, lamss, muss, HESS_SCALE;
float ** hessian, ** hessian_u, ** hessian_rho, ** hessian_lam, ** hessian_mu;

float ** hvxx_shot, ** hvxxi_shot, ** hvyy_shot, ** hvyyi_shot, ** hvxy_shot, ** hvxyi_shot,  ** hvyx_shot, ** hvyxi_shot;
float *psource_hess=NULL, *Hess_for_real=NULL, *Hess_for_complex=NULL;

FILE *FP4;

HESS_SCALE = 1e5;
RECINC = 1;
NSRC_HESSIAN=nshots;

nd = FDORDER/2 + 1;
abs_green = matrix(-nd+1,NY+nd,-nd+1,NX+nd);

/* Diagonal elements of the Hessian*/
hessian = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
hessian_u = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
hessian_lam = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
hessian_mu = matrix(-nd+1,NY+nd,-nd+1,NX+nd); 
hessian_rho = matrix(-nd+1,NY+nd,-nd+1,NX+nd);

hvxx_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
hvxxi_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
        
hvyy_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
hvyyi_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
        
hvyx_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
hvyxi_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
        
hvxy_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);
hvxyi_shot = matrix(-nd+1,NY+nd,-nd+1,NX+nd);

Hess_for_real = vector(1,1);
Hess_for_complex = vector(1,1);
        
for (i=1;i<=NX;i=i+IDX){
    for (j=1;j<=NY;j=j+IDY){
           hessian[j][i]=0.0;
           hessian_lam[j][i]=0.0;
           hessian_u[j][i]=0.0;  
           hessian_mu[j][i]=0.0; 
           hessian_rho[j][i]=0.0;
    }
}

/* assemble Hessian */
/* ----------------------------------------------------------------- */
/* calculate absolute values of impulse responses */
for (ishot=1;ishot<=nshots;ishot=ishot+SHOTINC){
    for (i=1;i<=NX;i=i+IDX){
        for (j=1;j<=NY;j=j+IDY){
        
           green_x = green_vx[j][i][ishot] + greeni_vx[j][i][ishot] * I;
           green_y = green_vy[j][i][ishot] + greeni_vy[j][i][ishot] * I;
                                                                        
           /*abs_green[j][i] += creal((green_x*conj(green_x))+(green_y*conj(green_y)));*/
           abs_green[j][i] = 1.0;
        
           /*printf("green_x = %e \n",green_sxx[j][i][ishot]);*/
           
        }
    }
}    
     
omega = 2.0*M_PI*FC_HESSIAN;

/*printf("omega = %e \n",omega);
printf("NSRC = %d \n",NSRC_HESSIAN);*/

/*psource_hess=rd_sour(&ns_hess,fopen(SIGNAL_FILE,"r"));
FFT_data(psource_hess,Hess_for_real,Hess_for_complex,NT);
                                                         
MPI_Barrier(MPI_COMM_WORLD);                             

tmp_fft_fsignal = Hess_for_real[1] + Hess_for_complex[1] * I;*/

tmp_fft_fsignal = 1.0;

for (ishot=1;ishot<=nshots;ishot=ishot+SHOTINC){
        
        /*for (i=1;i<=NX;i=i+IDX){
            for (j=1;j<=NY;j=j+IDY){*/
            
                /* calculate spatial derivatives of the forward wavefields */
                 /*hvxx_shot[j][i] = (green_vx[j][i][ishot]-green_vx[j][i-1][ishot])/DH;
                hvxxi_shot[j][i] = (greeni_vx[j][i][ishot]-greeni_vx[j][i-1][ishot])/DH;
                           
                 hvyy_shot[j][i] = (green_vy[j][i][ishot]-green_vy[j-1][i][ishot])/DH;
                hvyyi_shot[j][i] = (greeni_vy[j][i][ishot]-greeni_vy[j-1][i][ishot])/DH;
                           
                 hvyx_shot[j][i] = (green_vy[j][i+1][ishot]-green_vy[j][i][ishot])/DH; 
                hvyxi_shot[j][i] = (greeni_vy[j][i+1][ishot]-greeni_vy[j][i][ishot])/DH;
                           
                 hvxy_shot[j][i] = (green_vx[j+1][i][ishot]-green_vx[j][i][ishot])/DH;
                hvxyi_shot[j][i] = (greeni_vx[j+1][i][ishot]-greeni_vx[j][i][ishot])/DH;*/

        /*    }
        }*/

 for (irec=nshots;irec<=nshots;irec=irec+RECINC){

        /* construct Hessian for different material parameters */
            for (i=1;i<=NX;i=i+IDX){
                for (j=1;j<=NY;j=j+IDY){
            
                    /* Hessian for Lame parameter lambda, mu and rho */
                    tmp_mu1_shot = (green_sxx[j][i][ishot] + greeni_sxx[j][i][ishot] * I);
                    tmp_mu2_shot = (green_syy[j][i][ishot] + greeni_syy[j][i][ishot] * I);
                    tmp_mu3_shot = (green_sxy[j][i][ishot] + greeni_sxy[j][i][ishot] * I);
                    
                    tmp_mu5_shot = omega*((green_vx[j+1][i][ishot] * I) - greeni_vx[j+1][i][ishot]);
                    tmp_mu6_shot = omega*((green_vy[j+1][i][ishot] * I) - greeni_vy[j+1][i][ishot]);

                    tmp_mu1 = green_sxx[j][i][irec] + greeni_sxx[j][i][irec] * I;
                    tmp_mu2 = green_syy[j][i][irec] + greeni_syy[j][i][irec] * I;
                    tmp_mu3 = green_sxy[j][i][irec] + greeni_sxy[j][i][irec] * I;

                    if(INVMAT1==1){
                       muss = prho[j][i] * pu[j][i] * pu[j][i];
                      lamss = prho[j][i] * ppi[j][i] * ppi[j][i] - 2.0 * muss;}
                    
                    if(INVMAT1=3){
                       muss = pu[j][i];
                      lamss = ppi[j][i];}
                    
                    /*mulamratio = (muss * muss)/((lamss+muss)*(lamss+muss));*/
                                                                    
                    /*tmp_jac_lam = (1.0/(4.0 * (lamss+muss) * (lamss+muss))) * ((tmp_mu1_shot + tmp_mu2_shot) * (tmp_mu1_shot + tmp_mu2_shot));*/
                    
                    tmp_jac_lam =  (tmp_mu1_shot + tmp_mu2_shot) * (tmp_mu1 + tmp_mu2);
                    
                    tmp_jac_mu = ((1.0/(muss*muss))*(tmp_mu3_shot * tmp_mu3_shot)) + ((1.0/4.0) * ((tmp_mu1_shot + tmp_mu2_shot) * (tmp_mu1_shot + tmp_mu2_shot)) / ((lamss+muss)*(lamss+muss)))
                                                                                  + ((1.0/4.0) * ((tmp_mu1_shot - tmp_mu2_shot) * (tmp_mu1_shot - tmp_mu2_shot)) / (muss*muss));
                    
                    /*tmp_jac_mu = (tmp_mu3_shot * tmp_mu3) + (((mulamratio*((tmp_mu1_shot + tmp_mu2_shot) * (tmp_mu1 + tmp_mu2))) + ((tmp_mu1_shot - tmp_mu2_shot) * (tmp_mu1 - tmp_mu2)))/4.0);*/
                   
                    tmp_jac_rho = (tmp_mu5_shot*tmp_mu5_shot) + (tmp_mu6_shot*tmp_mu6_shot);
                    
                    /* Assemble Hessian for lambda, mu and rho */
                    if(INVMAT1==3){
                         hessian[j][i] += HESS_SCALE * creal(tmp_jac_lam*abs_green[j][i]*conj(tmp_jac_lam));
                       hessian_u[j][i] += HESS_SCALE * creal(tmp_jac_mu*abs_green[j][i]*conj(tmp_jac_mu));  
                     hessian_rho[j][i] += HESS_SCALE * creal(tmp_jac_rho*abs_green[j][i]*conj(tmp_jac_rho));
                    }

                    /* Assemble Hessian for Vp, Vs and rho*/
                    if(INVMAT1==1){
                    
                         tmp_jac_vp = 2.0 * ppi[j][i] * prho[j][i] * tmp_jac_lam;          
                         tmp_jac_vs = (- 4.0 * prho[j][i] * pu[j][i] * tmp_jac_lam) + (2.0 * prho[j][i] * pu[j][i] * tmp_jac_mu);                  
                         tmp_jac_rho += (((ppi[j][i] * ppi[j][i])-(2.0 * pu[j][i] * pu[j][i])) * tmp_jac_lam) + (pu[j][i] * pu[j][i] * tmp_jac_mu);
                    
                         hessian[j][i] += HESS_SCALE * creal(tmp_jac_vp*abs_green[j][i]*conj(tmp_jac_vp));  
                       hessian_u[j][i] += HESS_SCALE * creal(tmp_jac_vs*abs_green[j][i]*conj(tmp_jac_vs));  
                     hessian_rho[j][i] += HESS_SCALE * creal(tmp_jac_rho*abs_green[j][i]*conj(tmp_jac_rho));
                     
                    }
                  
                 }
             }
 }
}

/* save Hessian for Vp */
/* ----------------------- */
sprintf(jac,"%s_hessian.%i%i",JACOBIAN,POS[1],POS[2]);
FP4=fopen(jac,"wb");

/* output of the gradient */
for (i=1;i<=NX;i=i+IDX){
   for (j=1;j<=NY;j=j+IDY){ 
        fwrite(&hessian[j][i],sizeof(float),1,FP4);
   }
}

fclose(FP4);
    
MPI_Barrier(MPI_COMM_WORLD);

/* merge gradient file */   
sprintf(jac,"%s_hessian",JACOBIAN);
if (MYID==0) mergemod(jac,3);

/* save HESSIAN for mu */
/* ----------------------- */
sprintf(jac,"%s_hessian_u.%i%i",JACOBIAN,POS[1],POS[2]);
FP4=fopen(jac,"wb");

/* output of the gradient */
for (i=1;i<=NX;i=i+IDX){
   for (j=1;j<=NY;j=j+IDY){ 
        fwrite(&hessian_u[j][i],sizeof(float),1,FP4);
   }
}

fclose(FP4);
    
MPI_Barrier(MPI_COMM_WORLD);

/* merge gradient file */   
sprintf(jac,"%s_hessian_u",JACOBIAN);
if (MYID==0) mergemod(jac,3);

/* save HESSIAN for rho */   
/* ----------------------- */
sprintf(jac,"%s_hessian_rho.%i%i",JACOBIAN,POS[1],POS[2]);
FP4=fopen(jac,"wb");

/* output of the gradient */
for (i=1;i<=NX;i=i+IDX){
   for (j=1;j<=NY;j=j+IDY){ 
       fwrite(&hessian_rho[j][i],sizeof(float),1,FP4);
   }
}
    
fclose(FP4);
    
MPI_Barrier(MPI_COMM_WORLD);

/* merge gradient file */
sprintf(jac,"%s_hessian_rho",JACOBIAN);
if (MYID==0) mergemod(jac,3);

free_matrix(hessian,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(hessian_u,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(hessian_lam,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(hessian_mu,-nd+1,NY+nd,-nd+1,NX+nd);
free_matrix(hessian_rho,-nd+1,NY+nd,-nd+1,NX+nd);

}
Beispiel #5
0
matrix operator*(matrix m1,matrix m2){
	m1=transpose(m1);
	return matrix(m1*m2.x,m1*m2.y,m1*m2.z);
}
void dgCollisionChamferCylinder::Init (dgFloat32 radius, dgFloat32 height)
{
	m_rtti |= dgCollisionChamferCylinder_RTTI;
	m_radius = dgAbsf (radius);
	m_height = dgAbsf (height * dgFloat32 (0.5f));

	dgFloat32 sliceAngle = dgFloat32 (0.0f);
	dgFloat32 sliceStep = dgPI  / DG_CHAMFERCYLINDER_SLICES; 
	dgFloat32 breakStep = dgPI2 / DG_CHAMFERCYLINDER_BRAKES;

	dgMatrix rot (dgPitchMatrix (breakStep));	
	dgInt32 index = 0;
	for (dgInt32 j = 0; j <= DG_CHAMFERCYLINDER_SLICES; j ++) {
		dgVector p0 (-m_height * dgCos(sliceAngle), dgFloat32 (0.0f), m_radius + m_height * dgSin(sliceAngle), dgFloat32 (0.0f));
		sliceAngle += sliceStep;
		for (dgInt32 i = 0; i < DG_CHAMFERCYLINDER_BRAKES; i ++) {
			m_vertex[index] = p0;
			index ++;
			p0 = rot.UnrotateVector (p0);
		}
	}

	m_edgeCount = (4 * DG_CHAMFERCYLINDER_SLICES + 2)* DG_CHAMFERCYLINDER_BRAKES;
	m_vertexCount = DG_CHAMFERCYLINDER_BRAKES * (DG_CHAMFERCYLINDER_SLICES + 1);
	dgCollisionConvex::m_vertex = m_vertex;

	if (!m_shapeRefCount) {
		dgPolyhedra polyhedra(m_allocator);
		dgInt32 wireframe[DG_CHAMFERCYLINDER_SLICES + 10];

		for (dgInt32 i = 0; i < DG_MAX_CHAMFERCYLINDER_DIR_COUNT; i ++) {
			dgMatrix matrix (dgPitchMatrix (dgFloat32 (dgPI2 * i) / DG_MAX_CHAMFERCYLINDER_DIR_COUNT));
			m_shapesDirs[i] = matrix.RotateVector (dgVector (dgFloat32 (0.0f), dgFloat32 (1.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)));
		}


		dgInt32 index = 0;
		for (dgInt32 j = 0; j < DG_CHAMFERCYLINDER_SLICES; j ++) {
			dgInt32 index0 = index + DG_CHAMFERCYLINDER_BRAKES - 1;
			for (dgInt32 i = 0; i < DG_CHAMFERCYLINDER_BRAKES; i ++) {
				wireframe[0] = index;
				wireframe[1] = index0;
				wireframe[2] = index0 + DG_CHAMFERCYLINDER_BRAKES;
				wireframe[3] = index + DG_CHAMFERCYLINDER_BRAKES;

				index0 = index;
				index ++;
				polyhedra.AddFace (4, wireframe);
			}
		}

		for (dgInt32 i = 0; i < DG_CHAMFERCYLINDER_BRAKES; i ++) { 
			wireframe[i] = i;
		}
		polyhedra.AddFace (DG_CHAMFERCYLINDER_BRAKES, wireframe);

		for (dgInt32 i = 0; i < DG_CHAMFERCYLINDER_BRAKES; i ++) { 
			wireframe[i] = DG_CHAMFERCYLINDER_BRAKES * (DG_CHAMFERCYLINDER_SLICES + 1) - i - 1;
		}
		polyhedra.AddFace (DG_CHAMFERCYLINDER_BRAKES, wireframe);
		polyhedra.EndFace ();

		dgAssert (SanityCheck (polyhedra));

		dgUnsigned64 i = 0;
		dgPolyhedra::Iterator iter (polyhedra);
		for (iter.Begin(); iter; iter ++) {
			dgEdge* const edge = &(*iter);
			edge->m_userData = i;
			i ++;
		}

		for (iter.Begin(); iter; iter ++) {
			dgEdge* const edge = &(*iter);

			dgConvexSimplexEdge* const ptr = &m_edgeArray[edge->m_userData];
			ptr->m_vertex = edge->m_incidentVertex;
			ptr->m_next = &m_edgeArray[edge->m_next->m_userData];
			ptr->m_prev = &m_edgeArray[edge->m_prev->m_userData];
			ptr->m_twin = &m_edgeArray[edge->m_twin->m_userData];
		}
	}

	m_shapeRefCount ++;
	dgCollisionConvex::m_simplex = m_edgeArray;

	SetVolumeAndCG ();
}
Beispiel #7
0
void Image::drawPattern(GraphicsContext* context,
                        const FloatRect& floatSrcRect,
                        const AffineTransform& patternTransform,
                        const FloatPoint& phase,
                        ColorSpace styleColorSpace,
                        CompositeOperator compositeOp,
                        const FloatRect& destRect)
{
#if PLATFORM(CHROMIUM)
    TRACE_EVENT("Image::drawPattern", this, 0);
#endif
    FloatRect normSrcRect = normalizeRect(floatSrcRect);
    if (destRect.isEmpty() || normSrcRect.isEmpty())
        return; // nothing to draw

    NativeImageSkia* bitmap = nativeImageForCurrentFrame();
    if (!bitmap)
        return;

    SkIRect srcRect = enclosingIntRect(normSrcRect);

    // Figure out what size the bitmap will be in the destination. The
    // destination rect is the bounds of the pattern, we need to use the
    // matrix to see how big it will be.
    float destBitmapWidth, destBitmapHeight;
    TransformDimensions(patternTransform, srcRect.width(), srcRect.height(),
                        &destBitmapWidth, &destBitmapHeight);

    // Compute the resampling mode.
    ResamplingMode resampling;
    if (context->platformContext()->isAccelerated() || context->platformContext()->printing())
        resampling = RESAMPLE_LINEAR;
    else
        resampling = computeResamplingMode(context->platformContext(), *bitmap, srcRect.width(), srcRect.height(), destBitmapWidth, destBitmapHeight);
    resampling = limitResamplingMode(context->platformContext(), resampling);

    // Load the transform WebKit requested.
    SkMatrix matrix(patternTransform);

    SkShader* shader;
    if (resampling == RESAMPLE_AWESOME) {
        // Do nice resampling.
        int width = static_cast<int>(destBitmapWidth);
        int height = static_cast<int>(destBitmapHeight);
        SkBitmap resampled = bitmap->resizedBitmap(srcRect, width, height);
        shader = SkShader::CreateBitmapShader(resampled, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode);

        // Since we just resized the bitmap, we need to undo the scale set in
        // the image transform.
        matrix.setScaleX(SkIntToScalar(1));
        matrix.setScaleY(SkIntToScalar(1));
    } else {
        // No need to do nice resampling.
        SkBitmap srcSubset;
        bitmap->bitmap().extractSubset(&srcSubset, srcRect);
        shader = SkShader::CreateBitmapShader(srcSubset, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode);
    }

    // We also need to translate it such that the origin of the pattern is the
    // origin of the destination rect, which is what WebKit expects. Skia uses
    // the coordinate system origin as the base for the patter. If WebKit wants
    // a shifted image, it will shift it from there using the patternTransform.
    float adjustedX = phase.x() + normSrcRect.x() *
                      narrowPrecisionToFloat(patternTransform.a());
    float adjustedY = phase.y() + normSrcRect.y() *
                      narrowPrecisionToFloat(patternTransform.d());
    matrix.postTranslate(SkFloatToScalar(adjustedX),
                         SkFloatToScalar(adjustedY));
    shader->setLocalMatrix(matrix);

    SkPaint paint;
    paint.setShader(shader)->unref();
    paint.setXfermodeMode(WebCoreCompositeToSkiaComposite(compositeOp));
    paint.setFilterBitmap(resampling == RESAMPLE_LINEAR);

    context->platformContext()->paintSkPaint(destRect, paint);
}
STDMETHODIMP CompositeOverlayImpl<B>::Render(long _hdc)
{
	short count = 0;
	Count(&count);

	REAL el[6];
	CumulativeTransform(el);
	Matrix matrix(el[0], el[1], el[2], el[3], el[4], el[5]);

	// Firstly, if us or our parents don't transform the coordinate space, life is simple.
	if (matrix.IsIdentity())
	{
		ModernRender(_hdc);
	}
	else
	{
		// Check if all children are of type ISimpleOverlay2
		bool iso2 = true;
		for (int i=count-1; i>=0; i--)
		{
			IOverlay *pItem;
			Item(CComVariant(i), &pItem);
			VARIANT_BOOL vis;
			pItem->get_Visible(&vis);
			if (vis)
			{
				ISimpleOverlay2 *pISO2 = NULL;
				HRESULT hr = pItem->QueryInterface(__uuidof(ISimpleOverlay2), (void **)&pISO2);
				if (!SUCCEEDED(hr))
					iso2 = false;
				else
					pISO2->Release();
			}
			pItem->Release();
		}

		// If all children are of type ISimpleOverlay2, life is also simple.
		if (iso2)
		{
			ModernRender(_hdc);
		}
		else
		{
			// Otherwise, draw into a pre-transformed hdc.
			long width = 128;
			long height = 128;
			model->get_Width(&width);
			model->get_Height(&height);

			HDCImage hdc((HDC)_hdc, width, height);

			for (int i=count-1; i>=0; i--)
			{
				IOverlay *pItem;
				Item(CComVariant(i), &pItem);
				VARIANT_BOOL vis;
				pItem->get_Visible(&vis);
				if (vis)
					pItem->Render(hdc);
				pItem->Release();
			}

			Graphics g((HDC)_hdc);
			g.SetInterpolationMode(InterpolationModeHighQuality);
			g.SetSmoothingMode(SmoothingModeAntiAlias);
			g.MultiplyTransform(&matrix);
			g.DrawImage(&hdc.GetImage(), 0, 0);
		}
	}

	return S_OK;
}
Foam::solverPerformance Foam::paralution_AMG::solve
(
    scalarField& psi,
    const scalarField& source,
    const direction cmpt
) const
{

    word precond_name = lduMatrix::preconditioner::getName(controlDict_);
    double div   = controlDict_.lookupOrDefault<double>("div", 1e+08);
    bool accel   = controlDict_.lookupOrDefault<bool>("useAccelerator", true);
    word mformat = controlDict_.lookupOrDefault<word>("MatrixFormat", "CSR");
    word pformat = controlDict_.lookupOrDefault<word>("PrecondFormat", "CSR");
    word sformat = controlDict_.lookupOrDefault<word>("SmootherFormat", "CSR");
    word solver_name = controlDict_.lookupOrDefault<word>("CoarseGridSolver", "CG");
    word smoother_name = controlDict_.lookupOrDefault<word>("smoother", "paralution_MultiColoredGS");
    int MEp      = controlDict_.lookupOrDefault<int>("MEp", 1);
    word LBPre   = controlDict_.lookupOrDefault<word>("LastBlockPrecond", "paralution_Jacobi");
    int iterPreSmooth = controlDict_.lookupOrDefault<int>("nPreSweeps", 1);
    int iterPostSmooth = controlDict_.lookupOrDefault<int>("nPostSweeps", 2);
    double epsCoupling = controlDict_.lookupOrDefault<double>("couplingStrength", 0.01);
    int coarsestCells = controlDict_.lookupOrDefault<int>("nCellsInCoarsestLevel", 300);
    int ILUp = controlDict_.lookupOrDefault<int>("ILUp", 0);
    int ILUq = controlDict_.lookupOrDefault<int>("ILUq", 1);
    double relax = controlDict_.lookupOrDefault<double>("Relaxation", 1.0);
    double aggrrelax = controlDict_.lookupOrDefault<double>("AggrRelax", 2./3.);
    bool scaling = controlDict_.lookupOrDefault<bool>("scaleCorrection", true);
    word interp_name = controlDict_.lookupOrDefault<word>("InterpolationType", "SmoothedAggregation");

    solverPerformance solverPerf(typeName + '(' + precond_name + ')', fieldName_);

    register label nCells = psi.size();

    scalarField pA(nCells);
    scalarField wA(nCells);

    // --- Calculate A.psi
    matrix_.Amul(wA, psi, interfaceBouCoeffs_, interfaces_, cmpt);

    // --- Calculate initial residual field
    scalarField rA(source - wA);

    // --- Calculate normalisation factor
    scalar normFactor = this->normFactor(psi, source, wA, pA);

    // --- Calculate normalised residual norm
    solverPerf.initialResidual() = gSumMag(rA)/normFactor;
    solverPerf.finalResidual() = solverPerf.initialResidual();

    if ( !solverPerf.checkConvergence(tolerance_, relTol_) ) {

      paralution::_matrix_format mf = paralution::CSR;
      if      (mformat == "CSR")   mf = paralution::CSR;
      else if (mformat == "DIA")   mf = paralution::DIA;
      else if (mformat == "HYB")   mf = paralution::HYB;
      else if (mformat == "ELL")   mf = paralution::ELL;
      else if (mformat == "MCSR")  mf = paralution::MCSR;
      else if (mformat == "BCSR")  mf = paralution::BCSR;
      else if (mformat == "COO")   mf = paralution::COO;
      else if (mformat == "DENSE") mf = paralution::DENSE;

      paralution::_interp ip = paralution::SmoothedAggregation;
      if      (interp_name == "SmoothedAggregation") ip = paralution::SmoothedAggregation;
      else if (interp_name == "Aggregation")         ip = paralution::Aggregation;

      paralution::LocalVector<double> x;
      paralution::LocalVector<double> rhs;
      paralution::LocalMatrix<double> mat;

      paralution::AMG<paralution::LocalMatrix<double>,
                      paralution::LocalVector<double>,
                      double> ls;

      paralution::import_openfoam_matrix(matrix(), &mat);
      paralution::import_openfoam_vector(source, &rhs);
      paralution::import_openfoam_vector(psi, &x);

      ls.SetOperator(mat);

      // coupling strength
      ls.SetCouplingStrength(epsCoupling);
      // number of unknowns on coarsest level
      ls.SetCoarsestLevel(coarsestCells);
      // interpolation type for grid transfer operators
      ls.SetInterpolation(ip);
      // Relaxation parameter for smoothed interpolation aggregation
      ls.SetInterpRelax(aggrrelax);
      // Manual smoothers
      ls.SetManualSmoothers(true);
      // Manual course grid solver
      ls.SetManualSolver(true);
      // grid transfer scaling
      ls.SetScaling(scaling);
      // operator format
      ls.SetOperatorFormat(mf);
      ls.SetSmootherPreIter(iterPreSmooth);
      ls.SetSmootherPostIter(iterPostSmooth);

      ls.BuildHierarchy();

      int levels = ls.GetNumLevels();

      // Smoother via preconditioned FixedPoint iteration
      paralution::IterativeLinearSolver<paralution::LocalMatrix<double>,
                                        paralution::LocalVector<double>,
                                        double > **fp = NULL;
      fp = new paralution::IterativeLinearSolver<paralution::LocalMatrix<double>,
                                                 paralution::LocalVector<double>,
                                                 double >*[levels-1];
      paralution::Preconditioner<paralution::LocalMatrix<double>,
                                 paralution::LocalVector<double>,
                                 double > **sm = NULL;
      sm = new paralution::Preconditioner<paralution::LocalMatrix<double>,
                                          paralution::LocalVector<double>,
                                          double >*[levels-1];

      for (int i=0; i<levels-1; ++i) {
        fp[i] = paralution::GetIterativeLinearSolver<double>("paralution_FixedPoint", relax);
        sm[i] = paralution::GetPreconditioner<double>(smoother_name, LBPre, sformat, ILUp, ILUq, MEp);
        fp[i]->SetPreconditioner(*sm[i]);
        fp[i]->Verbose(0);
      }

      // Coarse Grid Solver and its Preconditioner
      paralution::IterativeLinearSolver<paralution::LocalMatrix<double>,
                                        paralution::LocalVector<double>,
                                        double > *cgs = NULL;
      cgs = paralution::GetIterativeLinearSolver<double>(solver_name, relax);
      cgs->Verbose(0);
      paralution::Preconditioner<paralution::LocalMatrix<double>,
                                 paralution::LocalVector<double>,
                                 double > *cgp = NULL;
      cgp = paralution::GetPreconditioner<double>(precond_name, LBPre, pformat, ILUp, ILUq, MEp);
      if (cgp != NULL) cgs->SetPreconditioner(*cgp);

      ls.SetSmoother(fp);
      ls.SetSolver(*cgs);

      // Switch to L1 norm to be consistent with OpenFOAM solvers
      ls.SetResidualNorm(1);

      ls.Init(tolerance_*normFactor, // abs
              relTol_,    // rel
              div,        // div
              maxIter_);  // max iter

      ls.Build();

      if (accel) {
        mat.MoveToAccelerator();
        rhs.MoveToAccelerator();
        x.MoveToAccelerator();
        ls.MoveToAccelerator();
      }

      switch(mf) {
        case paralution::DENSE:
          mat.ConvertToDENSE();
          break;
        case paralution::CSR:
          mat.ConvertToCSR();
          break;
        case paralution::MCSR:
          mat.ConvertToMCSR();
          break;
        case paralution::BCSR:
          mat.ConvertToBCSR();
          break;
        case paralution::COO:
          mat.ConvertToCOO();
          break;
        case paralution::DIA:
          mat.ConvertToDIA();
          break;
        case paralution::ELL:
          mat.ConvertToELL();
          break;
        case paralution::HYB:
          mat.ConvertToHYB();
          break;
      }

      ls.Verbose(0);

      // Solve linear system
      ls.Solve(rhs, &x);

      paralution::export_openfoam_vector(x, &psi);

      solverPerf.finalResidual()   = ls.GetCurrentResidual() / normFactor; // divide by normFactor, see lduMatrixSolver.C
      solverPerf.nIterations()     = ls.GetIterationCount();
      solverPerf.checkConvergence(tolerance_, relTol_);

      // Clear MultiGrid object
      ls.Clear();

      // Free all structures
      for (int i=0; i<levels-1; ++i) {
        delete fp[i];
        delete sm[i];
      }
      cgs->Clear();

      if (cgp != NULL)
        delete cgp;

      delete[] fp;
      delete[] sm;
      delete cgs;

    }

    return solverPerf;

}
Beispiel #10
0
void wxGL_PMFCanvas::OnMouseEvt(wxMouseEvent& event)
{
	bool update_omnipoints = false;

	if(event.Leaving() || event.ButtonUp()){
		mainpanel->control_panel->push_undo();
	}

	//if(!event.Leaving()){
	//	if(this != FindFocus()){
	//		previus_focus = FindFocus();
	//		SetFocus();
	//	}
	//}else{
	//	if(previus_focus)previus_focus->SetFocus();
	//}

	if (!model.GetSOBJCount())
	{
		event.Skip();
		return;
	}
	
	//glsz
	if (event.GetEventType() == wxEVT_LEFT_DOWN || 
		event.GetEventType() == wxEVT_RIGHT_DOWN )
	{
		mouse_start = wxPoint(event.GetX(), event.GetY());
	}
	else if (event.GetEventType() == wxEVT_MOTION && 
				event.Dragging())
	{
//########################start mouse movement code########################//
		if(event.m_controlDown){
	//------------------------start omnipoint code------------------------//
			//if control is down we move the selected omnipoint
			if(omni.point.size() > 0 && omni_selected_list >-1 && omni_selected_list < (int)omni.point.size() && omni_selected_item >-1 && omni_selected_item < (int)omni.point[omni_selected_list].size()){
				//but only if we have omnipoints and our selected coords are valid

				omnipoint&point = omni.point[omni_selected_list][omni_selected_item];

				double M[16], P[16];
				int v[4];
				glGetDoublev(GL_MODELVIEW_MATRIX, M);
				glGetDoublev(GL_PROJECTION_MATRIX, P);
				glGetIntegerv(GL_VIEWPORT, v);

				
				vector3d start;
				vector3d start_dir;
				vector3d end;
				vector3d end_dir;

				ray_cast(event.GetX(), event.GetY(), end, end_dir);
				ray_cast(mouse_start.x, mouse_start.y, start, start_dir);

				vector3d global_point = point.pos+model.get_model_offset(point.model);
					
					bool s = true, s2 = true;

				vector3d delta(0,0,0);

				if(event.m_leftDown){

					delta = filter_movement_delta(	plane_line_intersect(global_point, get_movement_plane_norm(),end, end_dir, &s)
														-	plane_line_intersect(global_point, get_movement_plane_norm(),start, start_dir, &s2));
					//if left button is down we move along x and y
				}else if(event.m_rightDown){
					//if right is down we move along y
					delta = closest_point_between_lines(global_point, get_movement_plane_norm(), end, end_dir)
										-closest_point_between_lines(global_point, get_movement_plane_norm(), start, start_dir);
				}
				if(s &&s2 && !null_vec(delta)){
					point.pos = point.pos + delta;
					update_omnipoints = true;
				}
			}
	//------------------------end omnipoint code------------------------//
		} else if(event.m_altDown){
			//------------------------start transform code------------------------//
			if(event.m_leftDown){
				//if left button is down we move along x and y
				bool s = true, s2 = true;
				vector3d start;
				vector3d start_dir;
				vector3d end;
				vector3d end_dir;

				ray_cast(event.GetX(), event.GetY(), end, end_dir);
				ray_cast(mouse_start.x, mouse_start.y, start, start_dir);

				// XXX: Should this have a value?
				vector3d global_point = vector3d();
				vector3d delta;

				delta = filter_movement_delta(	plane_line_intersect(global_point, get_movement_plane_norm(),end, end_dir, &s)
						-	plane_line_intersect(global_point, get_movement_plane_norm(),start, start_dir, &s2));
				if(s &&s2 && !null_vec(delta)){
					mainpanel->control_panel->transform(matrix(), delta);
				}
			}else if(event.m_rightDown){
				//if right is down we rotate about z
				float angle = (mouse_start.y - event.GetY());
				matrix transform(get_movement_plane_norm());
				if(angle){
					mainpanel->control_panel->transform(transform.invert() % matrix(angle) % transform, vector3d());
				}
			}
		//------------------------end transform code------------------------//
	}else{
	//++++++++++++++++++++++++start view code++++++++++++++++++++++++//
			if (!event.m_shiftDown)
			{
				//if shift is not down we rotate
				if (event.m_leftDown)
				{
					//we rotate about x and y when the left button is down
					rotation.y -= (mouse_start.x - event.GetX());
					rotation.x -= (mouse_start.y - event.GetY());
				}
				else
				{
					//we rotate about z when the right is down
					rotation.z -= (mouse_start.y - event.GetY());
				}
			}
			else
			{
				//if shift is down them we move the position
				if (event.m_leftDown)
				{
					//we move x and y when the left is down
					position.x -= model.SOBJ(0).radius * 
							(float(mouse_start.x - event.GetX())/100.0) ;
					position.y += model.SOBJ(0).radius *
						(float(mouse_start.y - event.GetY())/100.0);
				}
				else
				{
					//we move along z when the right is down
					position.z -= model.SOBJ(0).radius *
						(float(mouse_start.y - event.GetY())/100.0);
				}
			}
	//++++++++++++++++++++++++end view code++++++++++++++++++++++++//
		}
		mouse_start = wxPoint(event.GetX(), event.GetY());
		Render();
//########################end mouse movement code########################//
	}
	
	if (event.GetEventType() == wxEVT_MOUSEWHEEL){
//************************start scroll code************************//
		if(event.m_controlDown){
	//------------------------start omnipoint code------------------------//
			//if control is down we scale the selected omnipoint
			if(omni.flags & OMNIPOINT_RAD && omni.point.size() > 0 && omni_selected_list >-1 && omni_selected_list < (int)omni.point.size() && omni_selected_item >-1 && omni_selected_item < (int)omni.point[omni_selected_list].size()){
				//if the omnipoint has a radius
				//and the coords are valid
				if(omni.point[omni_selected_list][omni_selected_item].rad < 0.000001)omni.point[omni_selected_list][omni_selected_item].rad = model.get_avg_dimintion()/61.80f;
				if(event.GetWheelRotation()>0)
					omni.point[omni_selected_list][omni_selected_item].rad *= float(event.GetWheelRotation()/event.GetWheelDelta())*1.15;
				else
					omni.point[omni_selected_list][omni_selected_item].rad /= float(-event.GetWheelRotation()/event.GetWheelDelta())*1.15;

				update_omnipoints=true;
			}
	//------------------------end omnipoint code------------------------//
		} else if(event.m_altDown){
			//------------------------start transform code------------------------//
			float scale;
			if(event.GetWheelRotation()>0) {
				scale = float(event.GetWheelRotation()/event.GetWheelDelta())*1.15;
			} else {
				scale = 1 / (float(-event.GetWheelRotation()/event.GetWheelDelta())*1.15);
			}
			matrix transform;
			for (int i = 0; i < 3; i++) {
				transform.a2d[i][i] = scale;
			}
			if(scale != 1.0f){
				mainpanel->control_panel->transform(transform, vector3d());
			}
			//------------------------end transform code------------------------//
		}else{
	//++++++++++++++++++++++++start view code++++++++++++++++++++++++//
			position.z -= float(	event.GetWheelRotation()/event.GetWheelDelta()	) * position.z/50.0f;
	//++++++++++++++++++++++++end view code++++++++++++++++++++++++//
		}
//************************end scroll code************************//
		Render();
	}
	else
		event.Skip();

	if(update_omnipoints){
		mainpanel->control_panel->set_omnipoints(omni);
		set_omnipoints(mainpanel->control_panel->get_omnipoints());
	}
//	Render();
}
Beispiel #11
0
NzSubMesh* NzMesh::BuildSubMesh(const NzPrimitive& primitive, const NzMeshParams& params)
{
	#if NAZARA_UTILITY_SAFE
	if (!m_impl)
	{
		NazaraError("Mesh not created");
		return nullptr;
	}

	if (m_impl->animationType != nzAnimationType_Static)
	{
		NazaraError("Mesh must be static");
		return nullptr;
	}

	if (!params.IsValid())
	{
		NazaraError("Parameters must be valid");
		return nullptr;
	}
	#endif

	NzBoxf aabb;
	std::unique_ptr<NzIndexBuffer> indexBuffer;
	std::unique_ptr<NzVertexBuffer> vertexBuffer;

	NzMatrix4f matrix(primitive.matrix);
	matrix.ApplyScale(params.scale);

	NzVertexDeclaration* declaration = NzVertexDeclaration::Get(nzVertexLayout_XYZ_Normal_UV_Tangent);

	switch (primitive.type)
	{
		case nzPrimitiveType_Box:
		{
			unsigned int indexCount;
			unsigned int vertexCount;
			NzComputeBoxIndexVertexCount(primitive.box.subdivision, &indexCount, &vertexCount);

			indexBuffer.reset(new NzIndexBuffer(vertexCount > std::numeric_limits<nzUInt16>::max(), indexCount, params.storage, nzBufferUsage_Static));
			indexBuffer->SetPersistent(false);

			vertexBuffer.reset(new NzVertexBuffer(declaration, vertexCount, params.storage, nzBufferUsage_Static));
			vertexBuffer->SetPersistent(false);

			NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
			NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);

			NzGenerateBox(primitive.box.lengths, primitive.box.subdivision, matrix, primitive.textureCoords, static_cast<NzMeshVertex*>(vertexMapper.GetPointer()), indexMapper.begin(), &aabb);
			break;
		}

		case nzPrimitiveType_Cone:
		{
			unsigned int indexCount;
			unsigned int vertexCount;
			NzComputeConeIndexVertexCount(primitive.cone.subdivision, &indexCount, &vertexCount);

			indexBuffer.reset(new NzIndexBuffer(vertexCount > std::numeric_limits<nzUInt16>::max(), indexCount, params.storage, nzBufferUsage_Static));
			indexBuffer->SetPersistent(false);

			vertexBuffer.reset(new NzVertexBuffer(declaration, vertexCount, params.storage, nzBufferUsage_Static));
			vertexBuffer->SetPersistent(false);

			NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
			NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);

			NzGenerateCone(primitive.cone.length, primitive.cone.radius, primitive.cone.subdivision, matrix, primitive.textureCoords, static_cast<NzMeshVertex*>(vertexMapper.GetPointer()), indexMapper.begin(), &aabb);
			break;
		}

		case nzPrimitiveType_Plane:
		{
			unsigned int indexCount;
			unsigned int vertexCount;
			NzComputePlaneIndexVertexCount(primitive.plane.subdivision, &indexCount, &vertexCount);

			indexBuffer.reset(new NzIndexBuffer(vertexCount > std::numeric_limits<nzUInt16>::max(), indexCount, params.storage, nzBufferUsage_Static));
			indexBuffer->SetPersistent(false);

			vertexBuffer.reset(new NzVertexBuffer(declaration, vertexCount, params.storage, nzBufferUsage_Static));
			vertexBuffer->SetPersistent(false);

			NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
			NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);

			NzGeneratePlane(primitive.plane.subdivision, primitive.plane.size, matrix, primitive.textureCoords, static_cast<NzMeshVertex*>(vertexMapper.GetPointer()), indexMapper.begin(), &aabb);
			break;
		}

		case nzPrimitiveType_Sphere:
		{
			switch (primitive.sphere.type)
			{
				case nzSphereType_Cubic:
				{
					unsigned int indexCount;
					unsigned int vertexCount;
					NzComputeCubicSphereIndexVertexCount(primitive.sphere.cubic.subdivision, &indexCount, &vertexCount);

					indexBuffer.reset(new NzIndexBuffer(vertexCount > std::numeric_limits<nzUInt16>::max(), indexCount, params.storage, nzBufferUsage_Static));
					indexBuffer->SetPersistent(false);

					vertexBuffer.reset(new NzVertexBuffer(declaration, vertexCount, params.storage, nzBufferUsage_Static));
					vertexBuffer->SetPersistent(false);

					NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
					NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);

					NzGenerateCubicSphere(primitive.sphere.size, primitive.sphere.cubic.subdivision, matrix, primitive.textureCoords, static_cast<NzMeshVertex*>(vertexMapper.GetPointer()), indexMapper.begin(), &aabb);
					break;
				}

				case nzSphereType_Ico:
				{
					unsigned int indexCount;
					unsigned int vertexCount;
					NzComputeIcoSphereIndexVertexCount(primitive.sphere.ico.recursionLevel, &indexCount, &vertexCount);

					indexBuffer.reset(new NzIndexBuffer(vertexCount > std::numeric_limits<nzUInt16>::max(), indexCount, params.storage, nzBufferUsage_Static));
					indexBuffer->SetPersistent(false);

					vertexBuffer.reset(new NzVertexBuffer(declaration, vertexCount, params.storage, nzBufferUsage_Static));
					vertexBuffer->SetPersistent(false);

					NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
					NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);

					NzGenerateIcoSphere(primitive.sphere.size, primitive.sphere.ico.recursionLevel, matrix, primitive.textureCoords, static_cast<NzMeshVertex*>(vertexMapper.GetPointer()), indexMapper.begin(), &aabb);
					break;
				}

				case nzSphereType_UV:
				{
					unsigned int indexCount;
					unsigned int vertexCount;
					NzComputeUvSphereIndexVertexCount(primitive.sphere.uv.sliceCount, primitive.sphere.uv.stackCount, &indexCount, &vertexCount);

					indexBuffer.reset(new NzIndexBuffer(vertexCount > std::numeric_limits<nzUInt16>::max(), indexCount, params.storage, nzBufferUsage_Static));
					indexBuffer->SetPersistent(false);

					vertexBuffer.reset(new NzVertexBuffer(declaration, vertexCount, params.storage, nzBufferUsage_Static));
					vertexBuffer->SetPersistent(false);

					NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
					NzIndexMapper indexMapper(indexBuffer.get(), nzBufferAccess_WriteOnly);

					NzGenerateUvSphere(primitive.sphere.size, primitive.sphere.uv.sliceCount, primitive.sphere.uv.stackCount, matrix, primitive.textureCoords, static_cast<NzMeshVertex*>(vertexMapper.GetPointer()), indexMapper.begin(), &aabb);
					break;
				}
			}
			break;
		}
	}

	std::unique_ptr<NzStaticMesh> subMesh(new NzStaticMesh(this));
	if (!subMesh->Create(vertexBuffer.get()))
	{
		NazaraError("Failed to create StaticMesh");
		return nullptr;
	}
	vertexBuffer.release();

	if (params.optimizeIndexBuffers)
		indexBuffer->Optimize();

	subMesh->SetIndexBuffer(indexBuffer.get());
	indexBuffer.release();

	subMesh->SetAABB(aabb);
	AddSubMesh(subMesh.get());

	return subMesh.release();
}
Beispiel #12
0
int main(int argc, char **argv)
{
	SegyReel reel;
	SegyHead *header;
	char *dbin;
	char *outfile;
	FILE *fp;
	Pf *pf;  
	Arr *channels;  /* channel order list */
	Arr *table_list;  /* array of valid tables */
	int nchan;
	char *stest;

	float **traces;
	char reel1[3200];
	Dbptr db, trdb, dbj;
	Dbptr trdbss;  
	int nsamp0;
	double time0, endtime0, samprate0;
	long int nsamp;
	double samprate;
	int i,j;
	char stime[30],etime[30];
	char s[128];
	double tlength;
	double phi, theta;
	char *newchan_standard[3]={"X1","X2","X3"};
	char *trsubset="chan=~/X./";
	char *newchan[3]={"R","T","Z"};
	Tbl *sortkeys=newtbl(0);
	char sta[10],chan[10];
	double lat, lon, elev, dnorth, deast, edepth;
	char refsta[10];
	int total_traces=0;
	char *time_str;
	long int evid,shotid=1;
	int rotate=0;
	long int ntraces;
        int ichan;
	int map_to_cdp;  /* logical switch to output data like cdp stacked data */
	char *fmt="%Y %j %H %M %S %s";
	char *pfname;
	int Verbose=0;
	/* New features added 2009 */
	/* this is a boolean.  If true (nonzero) it is assumed stdin will
	contain four numbers:  time,lat, lon, elev.  If false, only the
	time field is read and remainder of any input on each line is dropped.*/
	int input_source_coordinates;
	/* scale factor for source coordinates.  Needed because segy uses
	an int to store source coordinates.  Sensible choices are 
	3600 for arc seconds and 10000 for a pseudodecimal. Note this
	parameter is ignored unless input_source_coordinates is true.*/
	int coordScale;
	/* If true use passcal 32 bit extension num_samps as record length. 
	SEGY standard uses a 16 bit entry that easily overflows with large
	shots at long offset.  In this ase assume the 16 bit quantity is
	meaningless. */
	int use_32bit_nsamp;
	/* This is switched on by argument switch.  When set to a nonzero
	(default) the reel headers are written.  When 0 `
	the reel heades will not be written -- used by seismic unix 
r
	and passcal*/
	int write_reel_headers=1;
	char *substr=NULL;

	if(argc < 3) usage();
	dbin = argv[1];
	outfile = argv[2];
	pfname = NULL;
	for(i=3;i<argc;++i)
	{
		if(!strcmp(argv[i],"-pf"))
		{
			++i;
			pfname = argv[i];
		}
		else if(!strcmp(argv[i],"-SU"))
		{
			write_reel_headers=0;
		}
		else if(!strcmp(argv[i],"-v"))
		{
			Verbose=1;
		}
		else if(!strcmp(argv[i],"-ss"))
		{
			++i;
			substr=argv[i];
		}
		else
		{
			usage();
		}
	}
	if(pfname == NULL) pfname = strdup("db2segy");

	elog_init(argc, argv);

	if(pfread(pfname,&pf)) 
		die(0,"pfread error for pf file %s.pf\n",argv[0]);
	/* rotation parameters */
	rotate=pfget_boolean(pf,"rotate");
	if(rotate)
	{
		phi = pfget_double(pf,"phi");
		theta = pfget_double(pf,"theta");
	}
	/* This function creates the channel order list keyed by
	station channel names */
	channels = build_stachan_list(pf,&nchan,Verbose);

	map_to_cdp = pfget_boolean(pf,"map_to_cdp");
	if(map_to_cdp && Verbose) 
		fprintf(stdout,"Casting data as CDP stacked section\n");
	if(dbopen(dbin,"r",&db) == dbINVALID) 
	{
		fprintf(stderr,"Cannot open db %s\n", dbin);
		usage();
	}
	/* We grab the sample rate and trace length (in seconds) and
	use this to define global sample rates for the data.  
	segy REQUIRES fixed length records and sample rates, so
	irregular sample rates will cause this program to die. 
	One could add a decimate/interpolate function, but this 
	is not currently implemented */
	samprate0 = pfget_double(pf,"sample_rate");
	tlength = pfget_double(pf,"trace_length");
	nsamp0 = (int)(tlength*samprate0);
	use_32bit_nsamp=pfget_boolean(pf,"use_32bit_nsamp");

	/* nsamp in segy is a 16 bit field.  Handling depends on
	setting of use_32bit_nsamp boolean */
	if(nsamp0 > 32767) 
	{
	    if(use_32bit_nsamp)
	    {
	    	elog_notify(0,"Warning:  segy ues a 16 bit entity to store number of samples\nThat field is garbage. Using the 32 bit extension field.\n");
	    }
	    else
	    {
		elog_complain(0,
		  "Warning:  segy uses a 16 bit entity to store number of samples\nRequested %d samples per trace.  Trucated to 32767\n",nsamp0);
		nsamp0 = 32767;
	    }
	}
	input_source_coordinates=pfget_boolean(pf,"input_source_coordinates");
	if(input_source_coordinates)
	{
		coordScale=pfget_int(pf,"coordinate_scale_factor");
	}
	else
	{
		coordScale=1;
	}
	/* boolean.  When nonzero set coordinates as geographic arc seconds values */
	int use_geo_coordinates=pfget_boolean(pf,"use_geo_coordinates");
	/* check list of tables defined in pf.  Return array of
	logicals that define which tables are valid and join 
	tables. */
	table_list = check_tables(db,pf);
	check_for_required_tables(table_list);
	dbj = join_tables(db,pf,table_list);
	if(dbj.record == dbINVALID) die(0,"dbjoin error\n");
	if(substr!=NULL) dbj=dbsubset(dbj,substr,0);
	long int ndbrows;
	dbquery(dbj,dbRECORD_COUNT,&ndbrows);
	if(ndbrows<=0)
	{
		fprintf(stderr,"Working database view is empty\n");
		if(substr!=NULL) fprintf(stderr,"Subset condtion =%s a likely problem\n",
				substr);
		usage();
	}

	fp = fopen(outfile,"w");
	if(fp == NULL) 
	{
		fprintf(stderr,"Cannot open output file %s\n",outfile);
		usage();
	}

	/* These are needed for sort below */
	pushtbl(sortkeys,"sta");
	pushtbl(sortkeys,"chan");

	/*The reel1 header in true blue segy is ebcdic.  We are goingto 
	just fill it with nulls and hope for the best */
	for(i=0;i<3200;i++) reel1[i] = '\0';

	/* Just blindly write this turkey. Bad form, but tough*/
	if(write_reel_headers) fwrite(reel1,1,3200,fp);

	/* memory allocation for trace data.  This is a large matrix
	that is cleared for each event.  This model works because of
	segy's fixed length format.  This routine is a descendent of
	numerical recipes routine found in libgenloc.  This is not
	the most efficient way to do this, but it simplifies the
	algorithm a lot. */
	traces = matrix(0,nchan,0,nsamp0);
	if(traces == NULL) 
		die(0,"Cannot alloc trace data matrix work space of size %d by %d\n",
			nchan, nsamp0);
	header = (SegyHead *)calloc((size_t)nchan,sizeof(SegyHead));
	if(header == NULL)
			die(0,"Cannot alloc memory for %d segy header workspace\n",nchan);
	if(write_reel_headers)
	{

		/* now fill in the binary reel header and write it */
		reel.kjob = 1;
		reel.kline = 1;
		reel.kreel = 1;
		reel.kntr = (int16_t)nchan;
		reel.knaux = 0;
		reel.sr = (int16_t)(1000000.0/samprate0);
		reel.kfldsr = reel.sr;
		reel.knsamp = (int16_t)nsamp0;
		reel.kfsamp = (int16_t)nsamp0;
		reel.dsfc=5;  /* This is ieee floats*/
		reel.kmfold = 0;
		if(map_to_cdp)
			reel.ksort = 2;
		else
			reel.ksort = 1;
		reel.kunits = 1;  /* This sets units to always be meters */
		for(i=0;i<344;++i)reel.unused2[i]='\0';
	
		if(fwrite((void *)(&reel),sizeof(SegyReel),1,fp) != 1) 
		{
			fprintf(stderr,"Write error for binary reel header\n");
			exit(-2);
		}
	}

	/* Now we enter a loop over stdin reading start times.  
	Program will blindly ask for data from each start time to 
	time+tlength.  The trace buffer will be initialized to 
	zeros at the top of the loop always.  If nothing is found
	only zeros will be written to output.  
	*/
	while((stest=fgets(s,80,stdin)) != NULL)
	{
		double slat,slon,selev;  /* Used when reading source location*/
		if(Verbose)
			fprintf(stdout,"Processing:  %s\n",s);
		for(i=0;i<nchan;++i)
		{
			initialize_header(&(header[i]));
			header[i].lineSeq = total_traces + i + 1;
			header[i].reelSeq = header[i].lineSeq;
			if(map_to_cdp)
			{
				header[i].cdpEns = i + 1;
				header[i].traceInEnsemble = 1;  /* 1 trace per cdp faked */
			}
			else
			{
				header[i].channel_number = i + 1;
			}
			header[i].event_number = shotid;
			header[i].energySourcePt=shotid;
			for(j=0;j<nsamp0;++j)  traces[i][j] = (Trsample)0.0;
		}
		if(input_source_coordinates)
		{
			char stmp[40];
			sscanf(s,"%s%ld%lf%lf%lf",stmp,&shotid,&slon,&slat,&selev);
			time0=str2epoch(stmp);
		}
		else
		{
			time0 = str2epoch(s);
		}
		endtime0 = time0 + tlength;
		sprintf(stime,"%20.4f",time0);
		sprintf(etime,"%20.4f",endtime0);
		trdb.database = -1;
		if(trload_css(dbj,stime,etime,&trdb,0, 0) < 0)
		{
			if(Verbose) 
			{
			  fprintf(stdout,"trload_css failed for shotid=%ld",shotid);
			  fprintf(stdout,"  No data in time range %s to %s\n",
			  	strtime(time0),strtime(endtime0) );
			  fprintf(stdout,"No data written for this shotid block.");
			  fprintf(stdout,"  Handle this carefully in geometry definitions.\n");
			}

			continue;
		}
		/* This does gap processing */
		repair_gaps(trdb);
		
		trapply_calib(trdb);
			
		if(rotate)
		{
			if(rotate_to_standard(trdb,newchan_standard))
				elog_notify(0,"Data loss in rotate_to_standard for event %s to %s\n",
					stime, etime);
			/* This is need to prevent collisions of channel 
			names */
			trdbss = dbsubset(trdb,trsubset,0);
			if(trrotate(trdbss,phi,theta,newchan))
				elog_notify(0,"Data loss in trrotate for event %s to %s\n",
					stime, etime);
		}
		if(Verbose)
			fprintf(stdout,"Station  chan_name  chan_number seq_number shotid  evid\n");
		trdb = dbsort(trdb,sortkeys,0,0);
		dbquery(trdb,dbRECORD_COUNT,&ntraces);
		if(Verbose) fprintf(stdout,"Read %ld traces for event at time%s\n",
			ntraces,strtime(time0));
		for(trdb.record=0;trdb.record<ntraces;++trdb.record)
		{
			Trsample *trdata;
			if(dbgetv(trdb,0,
			    "evid",&evid,
			    "sta",sta,
			    "chan",chan,
			    "nsamp", &nsamp,
			    "samprate",&samprate,
			    "data",&trdata,
			    "lat", &lat,
			    "lon", &lon,
			    "elev",&elev,
			    "refsta",refsta,
			    "dnorth",&dnorth,
			    "deast",&deast,
			    "edepth",&edepth,
					NULL) == dbINVALID)
			{
				elog_complain(0," dbgetv error reading record %ld\nTrace will be skipped for station %s and channel %s\n",
				trdb.record,sta,chan);
				continue;
			}
			/* Allow 1 percent samprate error before killing */
			double fsrskew=fabs((samprate-samprate0)/samprate0);
			double frskewcut=0.01;
			if(fsrskew>frskewcut) 
			{
				elog_complain(0,"%s:%s sample rate %f is significantly different from base sample rate of %f\nTrace skipped -- segy requires fixed sample rates\n",
					sta,chan,samprate,samprate0);
				continue;
			}
			if(nsamp > nsamp0)
			{
				elog_complain(0,"%s:%s trace has extra samples=%ld\nTruncated to length %d\n",
					sta, chan, nsamp, nsamp0);
				nsamp = nsamp0;
			}
			else if(nsamp < nsamp0)
			{
				elog_complain(0,"%s:%s trace is shorter than expected %d samples\nZero padded after sample %ld\n",
					sta, chan, nsamp0, nsamp);
			}

			ichan = get_channel_index(channels,sta,chan);
			if(ichan > nchan) die(0,"Channel index %d outside limit of %d\nCannot continue\n",
					ichan, nchan);
			if(ichan >= 0)
			{
				if(Verbose) 
				   fprintf(stdout,"%s:%s\t%-d\t%-d\t%-ld\t%-ld\n",
					sta,chan,ichan+1,
                                        header[ichan].reelSeq,
					shotid, evid);
				header[ichan].traceID = 1;
				for(j=0;j<nsamp;++j) 
				   traces[ichan][j] = (float)trdata[j];
				/* header fields coming from trace table */
				header[ichan].samp_rate = (int32_t)
						(1000000.0/samprate0);
				if(!use_geo_coordinates && ( coordScale==1))
				{
				  header[ichan].recLongOrX = (int32_t)(deast*1000.0);
				  header[ichan].recLatOrY = (int32_t)(dnorth*1000.0);
				}
				else
				{
				/* Note negative here.  This is a oddity
				of segy that - means divide by this to
				get actual.  Always make this negative in case 
				user inputs a negative number. */
				  header[ichan].coordScale=-abs(coordScale);
				  /* Force 2 = geographic coordinates.  Standard says when this is
				  so units are arc seconds, hence we multiply deg by 3600*coordScale */
				  if(use_geo_coordinates)
				  {
				    header[ichan].coordUnits=2;
				    header[ichan].recLongOrX
				     =(int32_t)(lon*3600.0*(double)coordScale);
				    header[ichan].recLatOrY
				     =(int32_t)(lat*3600.0*(double)coordScale);
				  }
				  else
				  {
				    header[ichan].recLongOrX
				     =(int32_t)(lon*(double)coordScale);
				    header[ichan].recLatOrY
				     =(int32_t)(lat*(double)coordScale);
				  }
				}
				header[ichan].recElevation = (int32_t)(elev*1000.0);
				header[ichan].deltaSample = (int16_t) 
						(1000000.0/samprate0);
				header[ichan].sampleLength = (int16_t)nsamp0;
				header[ichan].num_samps = (int32_t)nsamp0;
				/* This cracks the time fields */
				time_str = epoch2str(time0,fmt);
				sscanf(time_str,"%hd %hd %hd %hd %hd %hd",
					&header[ichan].year,
					&header[ichan].day,
					&header[ichan].hour,
					&header[ichan].minute,
					&header[ichan].second,
					&header[ichan].m_secs);
				/* These are PASSCAL extensions, but we'll
				go ahead and set them anyway.*/
				header[ichan].trigyear = header[ichan].year;
				header[ichan].trigday = header[ichan].day;
				header[ichan].trighour = header[ichan].hour;
				header[ichan].trigminute = header[ichan].minute;
				header[ichan].trigsecond = header[ichan].second;
				free(time_str);
				if(input_source_coordinates)
				{
				  if(use_geo_coordinates)
				  {
					slat*=3600.0;
					slon*=3600.0;
				  }
				  header[ichan].sourceLongOrX
				    =(int32_t)(slon*(double)coordScale);
				  header[ichan].sourceLatOrY
				    =(int32_t)(slat*(double)coordScale);
				  header[ichan].sourceSurfaceElevation
				             =(int32_t)selev;
				  /* No easy way to specify both elev and depth*/
				  header[ichan].sourceDepth=0;
				}
				else if(map_to_cdp)
				{
				/* When faking CDP data we make this look 
				like a zero offset, single fold data set */
				  header[ichan].sourceLongOrX = header[ichan].recLongOrX;
				  header[ichan].sourceLatOrY = header[ichan].recLatOrY;
				  header[ichan].sourceSurfaceElevation = header[ichan].recElevation;
				  header[ichan].sourceDepth = 0;
				  header[ichan].sourceToRecDist = 0;
				}
				else
				{
				/* This is the mechanism for adding other
				information with added tables.  The one
				table currently supported is a "shot" table 
				that holds shot coordinates.  If other tables
				were added new functions could be added with
				a similar calling sequence.  This procedure
				silently does nothing if a shot table is not
				present.*/
					set_shot_variable(db,table_list,
						evid,&header[ichan]);
				}
			}			
			else
			{
				if(Verbose)
					fprintf(stdout,"Station %s and channel %s skipped\n",
						sta,chan);
			}

		}
		/* Now we write the data */
		for(i=0;i<nchan;++i)
		{
			if(fwrite((void *)(&(header[i])),sizeof(SegyHead),1,fp) != 1)
				die(0,"Write error on header for trace %d\n",total_traces+i);		
			if(fwrite((void *)traces[i],sizeof(float),
					(size_t)nsamp0,fp) != nsamp0)
				die(0,"Write error while writing data for trace %d\n",
					total_traces+i);
		}
		total_traces += nchan;
		trdestroy(&trdb);		
		if(!input_source_coordinates) ++shotid;
	}
	return 0 ;
}
void CreateScene (NewtonWorld* world, SceneManager* sceneManager)
{
	Entity* floor;
	Entity* smilly;
	Entity* frowny;
	NewtonBody* floorBody;
	NewtonBody* smillyBody;
	NewtonBody* frownyBody;
	NewtonCollision* shape;

	// initialize the camera
	InitCamera (dVector (-15.0f, 5.0f, 0.0f, 0.0f), dVector (1.0f, 0.0f, 0.0f));


	// Create a large body to be the floor
	floor = sceneManager->CreateEntity();
	floor->LoadMesh ("FloorBox.dat");

	// add static floor Physics
	shape = CreateNewtonBox (world, floor, 0);
	floorBody = CreateRigidBody (world, floor, shape, 0.0f);
	NewtonDestroyCollision(shape);

	// set the Transformation Matrix for this rigid body
	dMatrix matrix (floor->m_curRotation, floor->m_curPosition);
	NewtonBodySetMatrix (floorBody, &matrix[0][0]);

	// add some visual entities.
	smilly = sceneManager->CreateEntity();
	smilly->LoadMesh ("Smilly.dat");
	smilly->m_curPosition.m_y = 10.0f;
	smilly->m_prevPosition = smilly->m_curPosition;

	// add a body with a box shape
	shape = CreateNewtonBox (world, smilly, 0);
	smillyBody = CreateRigidBody (world, smilly, shape, 10.0f);
	NewtonDestroyCollision(shape);


	// add some visual entities.
	frowny = sceneManager->CreateEntity();
	frowny->LoadMesh ("Frowny.dat");
	frowny->m_curPosition.m_z = 0.4f;
	frowny->m_curPosition.m_y = 10.0f + 0.4f;
	frowny->m_prevPosition = frowny->m_curPosition;

	// add a body with a Convex hull shape
	shape = CreateNewtonConvex (world, frowny, 0);
	frownyBody = CreateRigidBody (world, frowny, shape, 10.0f);
	NewtonDestroyCollision(shape);

	
	// we will Link the Frowny Body to the world with Hinge regenerated from a Generic 6DOF joint.
	 matrix = GetIdentityMatrix();
	 matrix.m_posit = frowny->m_curPosition;
	 matrix.m_posit.m_z += 0.2f;
	 matrix.m_posit.m_y += 0.4f;

	 // specify the limits for defining a Hinge around the x axis
	 dVector minLinearLimits (0.0f, 0.0f, 0.0f, 0.0f);
	 dVector maxLinearLimits (0.0f, 0.0f, 0.0f, 0.0f);

	 dVector minAngulaLimits (-0.5f * 3.1416f, 0.0f, 0.0f, 0.0f);
	 dVector maxAngulaLimits ( 0.5f * 3.1416f, 0.0f, 0.0f, 0.0f);

	 NewtonUserJoint* frownyHinge;
	 // Create a 6DOF joint 
	 frownyHinge = CreateCustomJoint6DOF (&matrix[0][0], &matrix[0][0], frownyBody, NULL);

	 // set the hinge Limits
 	 CustomJoint6DOF_SetLinearLimits (frownyHinge, &minLinearLimits[0], &maxLinearLimits[0]);
 	 CustomJoint6DOF_SetAngularLimits (frownyHinge, &minAngulaLimits[0], &maxAngulaLimits[0]);

	
	// now we will link the body of Smilly and Frowny with a specialize Hinge Joint 
	 NewtonUserJoint* smillyFrownyHinge;
	 matrix.m_posit = smilly->m_curPosition;
	 matrix.m_posit.m_z += 0.2f;
	 matrix.m_posit.m_y += 0.4f;

	 smillyFrownyHinge = CreateCustomHinge (&matrix[0][0], smillyBody, frownyBody);
	 HingeEnableLimits (smillyFrownyHinge, 1);
	 HingeSetLimits (smillyFrownyHinge, -0.5f * 3.1416f, 0.5f * 3.1416f);

//	 smillyFrownyHinge = CreateCustomBallAndSocket (&matrix[0][0], smillyBody, frownyBody);
//	 BallAndSocketSetConeAngle (smillyFrownyHinge, 0.5f * 3.1416f);
//	 BallAndSocketSetTwistAngle (smillyFrownyHinge, -0.5f * 3.1416f, 0.5f * 3.1416f);

//	 smillyFrownyHinge = CreateCustomSlider (&matrix[0][0], smillyBody, frownyBody);
//	 SliderEnableLimits (smillyFrownyHinge, 1);
//	 SliderSetLimis (smillyFrownyHinge, -0.5f * 3.1416f, 0.5f * 3.1416f);

	 {
		// adding two Kinematic controlled object
		frowny = sceneManager->CreateEntity();
		frowny->LoadMesh ("Frowny.dat");
		frowny->m_curPosition.m_z = 4.0f;
		frowny->m_curPosition.m_y = 7.0f;
		frowny->m_prevPosition = frowny->m_curPosition;
		shape = CreateNewtonConvex (world, frowny, 0);
		frownyBody = CreateRigidBody (world, frowny, shape, 10.0f);
		NewtonDestroyCollision(shape);
		 
		 
		FollowPath* path;
		NewtonUserJoint* g_pathFollow;

		path = (FollowPath*) malloc (sizeof (FollowPath));

		NewtonBodyGetMatrix (frownyBody, &matrix[0][0]);
		path->m_origin = matrix.m_posit;
		path->m_angle = 0.0f;
		path->radius = 3.0f;

		g_pathFollow = CreateCustomKinematicController (frownyBody, &matrix.m_posit[0]);
		CustomKinematicControllerSetPickMode (g_pathFollow, 1);
		CustomKinematicControllerSetMaxAngularFriction (g_pathFollow, 200.0f);
		CustomKinematicControllerSetMaxLinearFriction (g_pathFollow, 1000.0f);
		CustomSetUserData(g_pathFollow, path);
		CustomSetDestructorCallback(g_pathFollow, FollowPath::Destroy);
		CustomSetSubmitContraintCallback (g_pathFollow, FollowPath::EvaluatePath);

		matrix = path->BuildMatrix (0.0f);
		NewtonBodySetMatrix(frownyBody, &matrix[0][0]);
	 }

	 {
		// adding two Kinematic controlled object
		frowny = sceneManager->CreateEntity();
		frowny->LoadMesh ("Frowny.dat");
		frowny->m_curPosition.m_z = -4.0f;
		frowny->m_curPosition.m_y =  6.0f;
		frowny->m_prevPosition = frowny->m_curPosition;
		shape = CreateNewtonConvex (world, frowny, 0);
		frownyBody = CreateRigidBody (world, frowny, shape, 10.0f);
		NewtonDestroyCollision(shape);


		FollowPath* path;
		NewtonUserJoint* g_pathFollow;

		path = (FollowPath*) malloc (sizeof (FollowPath));

		NewtonBodyGetMatrix (frownyBody, &matrix[0][0]);
		path->m_origin = matrix.m_posit;
		path->m_angle = 3.1416f;
		path->radius = 3.0f;

		g_pathFollow = CreateCustomKinematicController (frownyBody, &matrix.m_posit[0]);
		CustomKinematicControllerSetPickMode (g_pathFollow, 1);
		CustomKinematicControllerSetMaxAngularFriction (g_pathFollow, 200.0f);
		CustomKinematicControllerSetMaxLinearFriction (g_pathFollow, 1000.0f);
		CustomSetUserData(g_pathFollow, path);
		CustomSetDestructorCallback(g_pathFollow, FollowPath::Destroy);
		CustomSetSubmitContraintCallback (g_pathFollow, FollowPath::EvaluatePath);

		matrix = path->BuildMatrix (0.0f);
		NewtonBodySetMatrix(frownyBody, &matrix[0][0]);
	 }
}
void Restitution (DemoEntityManager* const scene)
{
	scene->CreateSkyBox();

	// customize the scene after loading
	// set a user friction variable in the body for variable friction demos
	// later this will be done using LUA script
	NewtonWorld* const world = scene->GetNewton();
	dMatrix offsetMatrix (dGetIdentityMatrix());

	int defaultMaterialID = NewtonMaterialGetDefaultGroupID (world);
	NewtonMaterialSetCollisionCallback (world, defaultMaterialID, defaultMaterialID, NULL, UserContactRestitution); 


	CreateLevelMesh (scene, "flatPlane.ngd", 1);

	dVector location (0.0f, 0.0f, 0.0f, 0.0f);

	// create some spheres 
	dVector sphSize (2.0f, 2.0f, 2.0f, 0.0f);
	NewtonCollision* const sphereCollision = CreateConvexCollision (world, offsetMatrix, sphSize, _SPHERE_PRIMITIVE, 0);
	DemoMesh* const sphereMesh = new DemoMesh("sphere", sphereCollision, "smilli.tga", "smilli.tga", "smilli.tga");

	// create some boxes too
	dVector boxSize (2.0f, 2.0f, 2.0f, 0.0f);
	NewtonCollision* const boxCollision = CreateConvexCollision (world, offsetMatrix, boxSize, _BOX_PRIMITIVE, 0);
	DemoMesh* const boxMesh = new DemoMesh("box", boxCollision, "smilli.tga", "smilli.tga", "smilli.tga");

	int zCount = 10;
	dFloat spacing = 4.0f;
	dMatrix matrix (dGetIdentityMatrix());
	dVector origin (matrix.m_posit);
	origin.m_x -= 0.0f;

	// create a simple scene
	for (int i = 0; i < zCount; i ++) {
		dFloat restitution = 0.1f * (i + 1);

		dFloat z;
		dFloat x;
		dFloat mass;

		x = origin.m_x;
		z = origin.m_z + (i - zCount / 2) * spacing;

		mass = 1.0f;
		matrix.m_posit = FindFloor (world, dVector (x, 100.0f, z), 200.0f);
		matrix.m_posit.m_w = 1.0f;

		matrix.m_posit.m_y += 6.0f;
		CreateResititionBody(scene, sphereMesh, mass, matrix, sphereCollision, defaultMaterialID, restitution);

		matrix.m_posit.m_y += 6.0f;
		CreateResititionBody(scene, sphereMesh, mass, matrix, sphereCollision, defaultMaterialID, restitution);

		matrix.m_posit.m_y += 6.0f;
		CreateResititionBody(scene, sphereMesh, mass, matrix, sphereCollision, defaultMaterialID, restitution);

		matrix.m_posit.m_y += 6.0f;
		CreateResititionBody(scene, boxMesh, mass, matrix, boxCollision, defaultMaterialID, restitution);
	}

	boxMesh->Release();
	sphereMesh->Release();
	NewtonDestroyCollision(boxCollision);
	NewtonDestroyCollision(sphereCollision);


	dMatrix camMatrix (dGetIdentityMatrix());
	dQuaternion rot (camMatrix);
	origin = dVector (-25.0f, 5.0f, 0.0f, 0.0f);
	scene->SetCameraMatrix(rot, origin);

}
Beispiel #15
0
int main(int argc, char **argv)
{
	/* Locals */

	FILE	*input;		/* data file */
	FILE	*output;	/* data file */
	char	s[256];		/* Buffer */
	register int i;
	float	rmsres;
	float	maxres;
	int	nparam = 1;	/* Motor movement */
	float	**param = NULL; /* 1..ndata, 1..param */
	int	ndata = 0;
	float	*var;		/* 1..nvar, Offset, Amplitude and Phase */
	float	*fit_data;	/* 1..ndata */
	int	nvar = 3;
	float	theta[MAX_DATA];
	float	x[MAX_DATA];
	float	y[MAX_DATA];
	float dx,dy;
	float	x_off, x_amp, x_phase;
	float	y_off, y_amp, y_phase;
	float	temp;
	

	/* Open the input file */

	if (argc > 1)
	{
		if ((input = fopen(argv[1],"r")) == NULL)
		{
			fprintf(stderr,"Could not open file %s.\n",argv[1]);
			exit(-2);
		}
	}
	else
	{
		input = stdin;
	}

	/* Open the output file */

	if (argc > 2)
	{
		if ((output = fopen(argv[2],"r")) != NULL)
		{
			fprintf(stderr,"File %s already exists.\n",argv[2]);
			exit(-3);
		}
		if ((output = fopen(argv[2],"w")) == NULL)
		{
			fprintf(stderr,"Could not open file %s.\n",argv[2]);
			exit(-4);
		}
	}
	else
	{
		output = NULL;
	}

	if (input == stdin)
	{
		printf("# file : stdin\n");
	}
	else	
	{
		printf("# file : %s \n\n",argv[1]);
	}

	/* Read in the data and doit */

	ndata = 0;
	x[0]=0;
	y[0]=0;
	while(fgets(s,256,input) != NULL)
	{
		if (sscanf(s,"%f %f %f %f",
			&temp, theta+ndata,&dx,&dy) != 4) continue;
		if (ndata > 0){
			x[ndata] = x[ndata-1] + dx;
			y[ndata] = y[ndata-1] + dy;
		}
		theta[ndata] *= (M_PI/180.0);
		if (++ndata > MAX_DATA) break;
	}
	if (input != stdin) fclose(input);

	printf("# Number of data points : %d\n\n",ndata);

	/* Allocate the memory */

	var = vector(1, nvar);
	param = matrix(1, ndata, 1, nparam);
	fit_data = vector(1, ndata);

	/* Do fit for X including first guess */

	var[1] = 0.0;
	for(i=0; i<ndata; i++)
	{
		param[i+1][1] = theta[i];
		var[1] += (fit_data[i+1] = x[i]);
	}

	var[1] /= ndata;
	var[2] = -1e32;
	for(i=0; i<ndata; i++)
	{
		if (fabs(x[i] - var[1]) > var[2])
		{
			var[2] = fabs(x[i] - var[1]);
			var[3] = theta[i] - M_PI/2.0;
		}
	}
	
	non_linear_fit(nvar, var, ndata, fit_data, nparam, param, 0,
		fit_sin_func, &rmsres, &maxres, 2.0, 100, SHOW_NOTHING);

	printf("# Results of X fit : \n");
	printf("# RMS residue %le\n",rmsres);
	printf("# MAX residue %le\n",maxres);
	printf("# Offset    = %f\n",var[1]);
	printf("# Amplitude = %f\n",var[2]);
	printf("# Phase     = %f\n\n",var[3]*180.0/M_PI);

	x_off = var[1];
	x_amp = var[2];
	x_phase = var[3];

	/* Do fit for Y including first guess */

	var[1] = 0.0;
	for(i=0; i<ndata; i++)
	{
		param[i+1][1] = theta[i];
		var[1] += (fit_data[i+1] = y[i]);
	}

	var[1] /= ndata;
	var[2] = -1e32;
	for(i=0; i<ndata; i++)
	{
		if (fabs(y[i] - var[1]) > var[2])
		{
			var[2] = fabs(y[i] - var[1]);
			var[3] = theta[i] - M_PI/2.0;
		}
	}
	
	non_linear_fit(nvar, var, ndata, fit_data, nparam, param, 0,
		fit_sin_func, &rmsres, &maxres, 2.0, 100, SHOW_NOTHING);

	printf("# Results of Y fit : \n");
	printf("# RMS residue %le\n",rmsres);
	printf("# MAX residue %le\n",maxres);
	printf("# Offset    = %f\n",var[1]);
	printf("# Amplitude = %f\n",var[2]);
	printf("# Phase     = %f\n",var[3]*180.0/M_PI);

	y_off = var[1];
	y_amp = var[2];
	y_phase = var[3];

	for(i=0; i<ndata; i++)
	{
		printf("%.1f\t %.1f\t %.1f %.1f %.1f\n",
			theta[i]/M_PI*180.0,
			x[i],
			x_off + x_amp * sin(theta[i] + x_phase),
			y[i],
			y_off + y_amp * sin(theta[i] + y_phase));
	}
			
	exit(0);
}
Beispiel #16
0
float wolfels_TE(struct fwiTE *fwiTE, struct waveAC *waveAC, struct PML_AC *PML_AC, struct matTE *matTE, float ** srcpos, int nshots, int ** recpos, int ntr, int iter, int nstage, float alpha, float L2){

	/* declaration of global variables */
        extern int NX, NY, GRAD_METHOD, STEPMAX, MYID;
        extern float EPS_SCALE, C1, C2, SCALEFAC;
	extern float MAT1_NORM, MAT2_NORM; 

        /* declaration of local variables */
        float normg, mu, nu, ft, ** Snp1;
        float ** gt_sigma, ** gt_epsilon, g0s0, gts0, maxgrad, maxsigma, tmp;     
	int lsiter, done;

        gt_sigma =  matrix(1,NY,1,NX);
        gt_epsilon =  matrix(1,NY,1,NX);

        /* copy -> gt */
	store_mat((*fwiTE).grad_sigma,gt_sigma,NX,NY);
	store_mat((*fwiTE).grad_epsilon,gt_epsilon,NX,NY);

	/* normalize material parameters */
	scale_grad((*matTE).sigma,1.0/MAT1_NORM,(*matTE).sigmar,NX,NY);
	scale_grad((*matTE).epsilon,1.0/MAT2_NORM,(*matTE).epsilonr,NX,NY);

        /* calculate initial step length */
        if(iter==1){

           /*normg = norm_matrix((*fwiTE).grad_sigma,NX,NY);
           normg += norm_matrix((*fwiTE).grad_epsilon,NX,NY);
           alpha = 1.0/normg;*/

           /*maxgrad = maximum_m((*fwiTE).Hgrad_sigma,NX,NY);
           maxsigma = maximum_m((*matTE).sigmar,NX,NY);

           alpha = EPS_SCALE * maxsigma/maxgrad;*/

	   alpha = 1.0;

        }else{

           alpha = 1.0;

        }

        lsiter = 0;
	done = 0;
	mu = 0.0;
        nu = 1e30;        

        if(MYID==0){
           printf(" Estimate step length by Wolfe line search \n");
           printf(" ----------------------------------------- \n");
        }

	while(done!=1){
    
              if(lsiter < STEPMAX){

                 if(MYID==0){
                    printf("gradient evaluation %d ... \n",lsiter);
                    printf("alpha = %e ... \n",alpha);
                 }

          	 /* copy sigmar -> sigma_old */
                 /* copy epsilonr -> epsilon_old */
	         store_mat((*matTE).sigmar,(*fwiTE).sigma_old,NX,NY);
	  	 store_mat((*matTE).epsilonr,(*fwiTE).epsilon_old,NX,NY);

          	 /* test sigmar and epsilonr-update */
	         calc_mat_change_wolfe_multi_para((*fwiTE).Hgrad_sigma,(*matTE).sigmar,(*fwiTE).sigma_old,alpha,1);
	         calc_mat_change_wolfe_multi_para((*fwiTE).Hgrad_epsilon,(*matTE).epsilonr,(*fwiTE).epsilon_old,alpha,2);

          	 /* convert sigmar -> sigma and epsilonr -> epsilon to perform forward modelling */
	  	 scale_grad((*matTE).sigmar,MAT1_NORM,(*matTE).sigma,NX,NY);
	  	 scale_grad((*matTE).epsilonr,MAT2_NORM,(*matTE).epsilon,NX,NY);

		 ft = grad_obj_TE(fwiTE,waveAC,PML_AC,matTE,srcpos,nshots,recpos,ntr,iter,nstage);
		 
		 /*descent((*fwiTE).grad_sigma,gt_sigma);
 		 descent((*fwiTE).grad_epsilon,gt_epsilon);*/
	  	 store_mat((*fwiTE).grad_sigma,gt_sigma,NX,NY);
	  	 store_mat((*fwiTE).grad_epsilon,gt_epsilon,NX,NY);

	  	 /* copy sigma_old -> sigmar */
	  	 /* copy epsilon_old -> epsilonr */
	  	 store_mat((*fwiTE).sigma_old,(*matTE).sigmar,NX,NY);
	  	 store_mat((*fwiTE).epsilon_old,(*matTE).epsilonr,NX,NY);

                 lsiter++;

              }else{

                 alpha = 0.0;
                 break;

              }
           
              gts0 = dotp_matrix(gt_sigma,(*fwiTE).Hgrad_sigma,NX,NY);
              gts0+= dotp_matrix(gt_epsilon,(*fwiTE).Hgrad_epsilon,NX,NY);

              g0s0 = dotp_matrix((*fwiTE).grad_sigma,(*fwiTE).Hgrad_sigma,NX,NY);
              g0s0+= dotp_matrix((*fwiTE).grad_epsilon,(*fwiTE).Hgrad_epsilon,NX,NY);

              if(MYID==0){
                 printf("Wolfe Conditions \n");
                 printf("---------------- \n");
                 printf("ft = %e \t <= L2  = %e \n",ft,L2);
                 printf("ft = %e \t <= L2 + C1*alpha*g0s0 = %e \n",ft,L2 + C1*alpha*g0s0);
                 printf("gts0 = %e \t >= C2*g0s0 = %e \n",gts0,C2*g0s0);
              }
 
              if (ft > (L2 + C1*alpha*g0s0)){
                  nu = alpha;
	          alpha = (nu + mu)/SCALEFAC;
              }else if(gts0 < (C2*g0s0)){
                  mu = alpha;
		  if(nu==1e30){
                     alpha = SCALEFAC*alpha;
                  }else{
		     alpha = (nu + mu)/SCALEFAC;
		  }
              }else{
                  done = 1;
              }

        }

        if(MYID==0){
           printf("final alpha = %e \n",alpha);
        }

	/* convert sigmar -> sigma and epsilonr -> epsilon to perform forward modelling */
	scale_grad((*matTE).sigmar,MAT1_NORM,(*matTE).sigma,NX,NY);
	scale_grad((*matTE).epsilonr,MAT2_NORM,(*matTE).epsilon,NX,NY);

        free_matrix(gt_sigma,1,NY,1,NX);
        free_matrix(gt_epsilon,1,NY,1,NX);

return alpha;
                	    
}
Beispiel #17
0
FX_RECT CPDF_CIDFont::GetCharBBox(uint32_t charcode) {
  if (charcode < 256 && m_CharBBox[charcode].right != -1)
    return m_CharBBox[charcode];

  FX_RECT rect;
  bool bVert = false;
  int glyph_index = GlyphFromCharCode(charcode, &bVert);
  FXFT_Face face = m_Font.GetFace();
  if (face) {
    if (FXFT_Is_Face_Tricky(face)) {
      int err = FXFT_Load_Glyph(face, glyph_index,
                                FXFT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH);
      if (!err) {
        FXFT_BBox cbox;
        FXFT_Glyph glyph;
        err = FXFT_Get_Glyph(((FXFT_Face)face)->glyph, &glyph);
        if (!err) {
          FXFT_Glyph_Get_CBox(glyph, FXFT_GLYPH_BBOX_PIXELS, &cbox);
          int pixel_size_x = ((FXFT_Face)face)->size->metrics.x_ppem;
          int pixel_size_y = ((FXFT_Face)face)->size->metrics.y_ppem;
          if (pixel_size_x == 0 || pixel_size_y == 0) {
            rect = FX_RECT(cbox.xMin, cbox.yMax, cbox.xMax, cbox.yMin);
          } else {
            rect = FX_RECT(cbox.xMin * 1000 / pixel_size_x,
                           cbox.yMax * 1000 / pixel_size_y,
                           cbox.xMax * 1000 / pixel_size_x,
                           cbox.yMin * 1000 / pixel_size_y);
          }
          rect.top = std::min(rect.top,
                              static_cast<int>(FXFT_Get_Face_Ascender(face)));
          rect.bottom = std::max(
              rect.bottom, static_cast<int>(FXFT_Get_Face_Descender(face)));
          FXFT_Done_Glyph(glyph);
        }
      }
    } else {
      int err = FXFT_Load_Glyph(face, glyph_index, FXFT_LOAD_NO_SCALE);
      if (err == 0) {
        rect = FX_RECT(TT2PDF(FXFT_Get_Glyph_HoriBearingX(face), face),
                       TT2PDF(FXFT_Get_Glyph_HoriBearingY(face), face),
                       TT2PDF(FXFT_Get_Glyph_HoriBearingX(face) +
                                  FXFT_Get_Glyph_Width(face),
                              face),
                       TT2PDF(FXFT_Get_Glyph_HoriBearingY(face) -
                                  FXFT_Get_Glyph_Height(face),
                              face));
        rect.top += rect.top / 64;
      }
    }
  }
  if (!m_pFontFile && m_Charset == CIDSET_JAPAN1) {
    uint16_t CID = CIDFromCharCode(charcode);
    const uint8_t* pTransform = GetCIDTransform(CID);
    if (pTransform && !bVert) {
      CFX_Matrix matrix(CIDTransformToFloat(pTransform[0]),
                        CIDTransformToFloat(pTransform[1]),
                        CIDTransformToFloat(pTransform[2]),
                        CIDTransformToFloat(pTransform[3]),
                        CIDTransformToFloat(pTransform[4]) * 1000,
                        CIDTransformToFloat(pTransform[5]) * 1000);
      CFX_FloatRect rect_f(rect);
      matrix.TransformRect(rect_f);
      rect = rect_f.GetOuterRect();
    }
  }
  if (charcode < 256)
    m_CharBBox[charcode] = rect;

  return rect;
}
Beispiel #18
0
main (int argc, char *argv[])
{
  bool verbose;
  bool very_verbose;
  bool exponential;
  bool ignore;
  bool temp_mode;
  char *option;
  char *gpdfile;
  int col_start;
  int row_start;
  int cols;
  int rows;
  char *corfile;
  bool do_correction;
  char line[MAX_STRING];
  int count_input;
  int count_output;
  double col;
  double row;
  double elev;
  double temperature;
  float lat;
  float lon;
  grid_class *grid_def;
  int status;
  int bytes_per_cell;
  int bytes_per_row;
  float **correction;
  int jcol;
  int irow;
  FILE *fp_cor;
  bool in_region;

/*
 *	set defaults
 */
  verbose = FALSE;
  very_verbose = FALSE;
  exponential = FALSE;
  ignore = FALSE;
  gpdfile = "Sa0.gpd";
  do_correction = FALSE;
  temp_mode = 0;

/* 
 *	get command line options
 */
  while (--argc > 0 && (*++argv)[0] == '-') {
    for (option = argv[0]+1; *option != '\0'; option++) {
      switch (*option) {
      case 'v':
	if (verbose)
	  very_verbose = TRUE;
	verbose = TRUE;
	break;
      case 'e':
	exponential = TRUE;
	break;
      case 'i':
        ignore = TRUE;
	break;
      case 'g':
	++argv; --argc;
 	if (argc <= 0)
	  DisplayInvalidParameter("gpdfile");
	gpdfile = *argv;
	break;
      case 'c':
	do_correction = TRUE;
	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("col_start");
	if (sscanf(*argv, "%d", &col_start) != 1)
	  DisplayInvalidParameter("col_start");
 	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("row_start");
	if (sscanf(*argv, "%d", &row_start) != 1)
	  DisplayInvalidParameter("row_start");
	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("cols");
	if (sscanf(*argv, "%d", &cols) != 1)
	  DisplayInvalidParameter("cols");
	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("rows");
	if (sscanf(*argv, "%d", &rows) != 1)
	  DisplayInvalidParameter("rows");
	++argv; --argc;
 	if (argc <= 0)
	  DisplayInvalidParameter("corfile");
	corfile = *argv;
	break;
      case 't':
	temp_mode = TRUE;
	break;
    default:
	fprintf(stderr,"invalid option %c\n", *option);
	DisplayUsage();
      }
    }
  }

/*
 *	get command line arguments
 */
  if (argc != 0)
    DisplayUsage();

  if (verbose) {
    fprintf(stderr, "lle2cre: %s\n", lle2cre_c_rcsid);
    fprintf(stderr, "  very_verbose = %d\n", very_verbose);
    fprintf(stderr, "  exponential  = %d\n", exponential);
    fprintf(stderr, "  ignore       = %d\n", ignore);
    fprintf(stderr, "  gpdfile      = %s\n", gpdfile);
    if (do_correction) {
      fprintf(stderr, "  col_start    = %d\n", col_start);
      fprintf(stderr, "  row_start    = %d\n", row_start);
      fprintf(stderr, "  cols         = %d\n", cols);
      fprintf(stderr, "  rows         = %d\n", rows);
      fprintf(stderr, "  corfile      = %s\n", corfile);
    }
    fprintf(stderr, "  temp_mode    = %d\n", temp_mode);
  }

  /*
   *  initialize grid
   */

  grid_def = init_grid(gpdfile);
  if (NULL == grid_def)
    exit(ABORT);

  if (do_correction) {
    /*
     *  allocate memory for correction
     */
    
    bytes_per_cell = sizeof(float);
    if ((correction =
	 (float **)matrix(rows, cols, bytes_per_cell, 1)) == NULL) {
      fprintf(stderr, "cr2cre: error allocating memory for correction");
      perror("lle2cre");
      error_exit("lle2cre");
    }
    
    /*
     *  read in entire correction
     */
    
    if ((fp_cor = fopen(corfile, "r")) == NULL) {
      fprintf(stderr, "lle2cre: error opening %s\n", corfile);
      perror("lle2cre");
      error_exit("lle2cre");
    }
    bytes_per_row = bytes_per_cell * cols;
    if (fread(&correction[0][0], bytes_per_row, rows, fp_cor) != rows) {
      fprintf(stderr, "lle2cre: error reading %s\n", corfile);
      perror("lle2cre");
      error_exit("lle2cre");
    }
    fclose(fp_cor);
  }

  count_input = 0;
  count_output = 0;
  while (fgets(line, sizeof(line), stdin)) {

    /*
     *  read and parse input line
     */

    count_input++;
    if (sscanf(line, "%f%f%lf", &lat, &lon, &elev) != 3) {
      fprintf(stderr, "error parsing input line %d:\n%s\n", count_input, line);
    } else {

      if (temp_mode) {
	temperature = elev;
	elev = 0.0;
      }

      /*
       *  convert lat-lon pair to col-row pair
       */
      
      in_region = TRUE;
      status = forward_grid(grid_def, lat, lon, &col, &row);
      if (status == 0) {
	if (very_verbose || !ignore) {
	  fprintf(stderr, "Error mapping lat-lon to col-row on line %d:\n",
		  count_input);
	  fprintf(stderr, "  %s\n", line);
	}
	if (ignore)
	  in_region = FALSE;
      }
      
      /*
       *  perform correction as needed
       */
      
      if (do_correction) {
	irow = (int)(row - row_start + 0.5);
	jcol = (int)(col - col_start + 0.5);
	if (irow >= 0 && irow < rows &&
	    jcol >= 0 && jcol < cols) {
	  elev += correction[irow][jcol];
	} else {
	  in_region = FALSE;
	}
      }
      
      /*
       *  write output line
       */
      
      if (in_region) {
	if (temp_mode)
	  if (exponential)
	    printf("%15.8le %15.8le %15.8le %15.8le\n",
		   col, row, elev, temperature);
	  else
	    printf("%11.5lf %11.5lf %11.6lf %11.5lf\n",
		   col, row, elev, temperature);
	else
	  if (exponential)
	    printf("%15.8le %15.8le %15.8le\n", col, row, elev);
	  else
	    printf("%11.5lf %11.5lf %11.6lf\n", col, row, elev);
	count_output++;
      }
    }
  }

  /*
   *  close grid
   */

  close_grid(grid_def);

  /*
   *  deallocate memory for correction
   */

  if (do_correction)
    free(correction);

  /*
   *  print number of lines processed
   */

  if (verbose) {
    fprintf(stderr, "  %d lines input\n", count_input);
    fprintf(stderr, "  %d lines output\n", count_output);
  }
  exit(EXIT_SUCCESS);
}
void LLDrawPoolTree::renderTree(BOOL selecting)
{
	LLGLState normalize(GL_NORMALIZE, TRUE);
	
	// Bind the texture for this tree.
	gGL.getTexUnit(sDiffTex)->bind(mTexturep.get(), TRUE);
		
	U32 indices_drawn = 0;

	gGL.matrixMode(LLRender::MM_MODELVIEW);
	
	for (std::vector<LLFace*>::iterator iter = mDrawFace.begin();
		 iter != mDrawFace.end(); iter++)
	{
		LLFace *face = *iter;
		LLDrawable *drawablep = face->getDrawable();

		if (drawablep->isDead() || !face->getVertexBuffer())
		{
			continue;
		}

		face->getVertexBuffer()->setBuffer(LLDrawPoolTree::VERTEX_DATA_MASK);
		U16* indicesp = (U16*) face->getVertexBuffer()->getIndicesPointer();

		// Render each of the trees
		LLVOTree *treep = (LLVOTree *)drawablep->getVObj().get();

		LLColor4U color(255,255,255,255);

		if (!selecting || treep->mGLName != 0)
		{
			if (selecting)
			{
				S32 name = treep->mGLName;
				
				color = LLColor4U((U8)(name >> 16), (U8)(name >> 8), (U8)name, 255);
			}
			
			gGLLastMatrix = NULL;
			gGL.loadMatrix(gGLModelView);
			//gGL.pushMatrix();

			LLMatrix4 matrix(gGLModelView);
			
			// Translate to tree base  HACK - adjustment in Z plants tree underground
			const LLVector3 &pos_agent = treep->getPositionAgent();
			//gGL.translatef(pos_agent.mV[VX], pos_agent.mV[VY], pos_agent.mV[VZ] - 0.1f);
			LLMatrix4 trans_mat;
			trans_mat.setTranslation(pos_agent.mV[VX], pos_agent.mV[VY], pos_agent.mV[VZ] - 0.1f);
			trans_mat *= matrix;
			
			// Rotate to tree position and bend for current trunk/wind
			// Note that trunk stiffness controls the amount of bend at the trunk as 
			// opposed to the crown of the tree
			// 
			const F32 TRUNK_STIFF = 22.f;
			
			LLQuaternion rot = 
				LLQuaternion(treep->mTrunkBend.magVec()*TRUNK_STIFF*DEG_TO_RAD, LLVector4(treep->mTrunkBend.mV[VX], treep->mTrunkBend.mV[VY], 0)) *
				LLQuaternion(90.f*DEG_TO_RAD, LLVector4(0,0,1)) *
				treep->getRotation();

			LLMatrix4 rot_mat(rot);
			rot_mat *= trans_mat;

			F32 radius = treep->getScale().magVec()*0.05f;
			LLMatrix4 scale_mat;
			scale_mat.mMatrix[0][0] = 
				scale_mat.mMatrix[1][1] =
				scale_mat.mMatrix[2][2] = radius;

			scale_mat *= rot_mat;

			//TO-DO: Make these set-able?
			const F32 THRESH_ANGLE_FOR_BILLBOARD = 7.5f; //Made LoD now a little less aggressive here -Shyotl
			const F32 BLEND_RANGE_FOR_BILLBOARD = 1.5f;

			F32 droop = treep->mDroop + 25.f*(1.f - treep->mTrunkBend.magVec());
			
			S32 stop_depth = 0;
			F32 app_angle = treep->getAppAngle()*LLVOTree::sTreeFactor;
			F32 alpha = 1.0;
			S32 trunk_LOD = LLVOTree::sMAX_NUM_TREE_LOD_LEVELS;

			for (S32 j = 0; j < 4; j++)
			{

				if (app_angle > LLVOTree::sLODAngles[j])
				{
					trunk_LOD = j;
					break;
				}
			} 
			if(trunk_LOD >= LLVOTree::sMAX_NUM_TREE_LOD_LEVELS)
			{
				continue ; //do not render.
			}

			if (app_angle < (THRESH_ANGLE_FOR_BILLBOARD - BLEND_RANGE_FOR_BILLBOARD))
			{
				//
				//  Draw only the billboard 
				//
				//  Only the billboard, can use closer to normal alpha func.
				stop_depth = -1;
				LLFacePool::LLOverrideFaceColor clr(this, color); 
				indices_drawn += treep->drawBranchPipeline(scale_mat, indicesp, trunk_LOD, stop_depth, treep->mDepth, treep->mTrunkDepth, 1.0, treep->mTwist, droop, treep->mBranches, alpha);
			}
			else // if (app_angle > (THRESH_ANGLE_FOR_BILLBOARD + BLEND_RANGE_FOR_BILLBOARD))
			{
				//
				//  Draw only the full geometry tree
				//
				LLFacePool::LLOverrideFaceColor clr(this, color); 
				indices_drawn += treep->drawBranchPipeline(scale_mat, indicesp, trunk_LOD, stop_depth, treep->mDepth, treep->mTrunkDepth, 1.0, treep->mTwist, droop, treep->mBranches, alpha);
			}
			
			//gGL.popMatrix();
		}
	}
}//
Beispiel #20
0
dVector dQuaternion::UnrotateVector (const dVector& point) const
{
	dMatrix matrix (*this, dVector (0.0f, 0.0f, 0.0f, 1.0f));
	return matrix.UnrotateVector(point);
}
Beispiel #21
0
int main (int argc, char * argv[])
{
    int nrows = 101;
    int ncols = 101;

    if (argc == 3) {
        nrows = atoi (argv[1]);
        ncols = atoi (argv[2]);
    }

    munkres_cpp::Matrix<double> matrix (nrows, ncols);

    srandom ( time (nullptr) ); // Seed random number generator.

    // Initialize matrix with random values.
    for (int row = 0; row < nrows; row++) {
        for (int col = 0; col < ncols; col++) {
            matrix (row,col) = (double)random ();
        }
    }

    // Display begin matrix state.
    for (int row = 0; row < nrows; row++) {
        for (int col = 0; col < ncols; col++) {
            std::cout.width (2);
            std::cout << matrix (row,col) << ",";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;

    // Apply Munkres algorithm to matrix.
    munkres_cpp::Munkres<double> m;
    m.solve (matrix);

    // Display solved matrix.
    for (int row = 0; row < nrows; row++) {
        for (int col = 0; col < ncols; col++) {
            std::cout.width (2);
            std::cout << matrix (row,col) << ",";
        }
        std::cout << std::endl;
    }

    std::cout << std::endl;


    for (int row = 0; row < nrows; row++) {
        int rowcount = 0;
        for (int col = 0; col < ncols; col++) {
            if (matrix (row,col) == 0)
                rowcount++;
        }
        if (rowcount != 1)
            std::cerr << "Row " << row << " has " << rowcount << " columns that have been matched." << std::endl;
    }

    for (int col = 0; col < ncols; col++) {
        int colcount = 0;
        for (int row = 0; row < nrows; row++) {
            if (matrix (row,col) == 0)
                colcount++;
        }
        if (colcount != 1)
            std::cerr << "Column " << col << " has " << colcount << " rows that have been matched." << std::endl;
    }

    return 0;
}
Beispiel #22
0
dVector dQuaternion::GetEulerAngles (dEulerAngleOrder order) const
{
	dMatrix matrix (*this, dVector (0.0f,0.0f,0.0f,1.0f));
	return matrix.GetEulerAngles (order);
}
Beispiel #23
0
// Matrix Implementation
matrix transpose(matrix m) {
	return matrix(	Vector(m.x.x,m.y.x,m.z.x),
					Vector(m.x.y,m.y.y,m.z.y),
					Vector(m.x.z,m.y.z,m.z.z));
}
Beispiel #24
0
// Compute Non-zero basis functions and their derivatives.
//
// INPUT:
//
//   d  - spline degree         integer
//   k  - knot sequence         double  vector(nk)
//   u  - parametric point      double
//   s  - knot span             integer
//   n  - number of derivatives integer
//
// OUTPUT:
//
//   dN -  Basis functions      double  matrix(n+1,d+1)
//         and derivatives upto the nth derivative (n < d)
//
// Algorithm A2.3 from 'The NURBS BOOK' pg72.
static void _dersbasisfuns(int d, double *k, int nk, double u, int s,int n, double **ders)
{
  int i,j,r,s1,s2,rk,pk,j1,j2;
  double temp, saved, der;
  double **ndu, **a, *left, *right;

  ndu = matrix(d+1, d+1);
  a = matrix(d+1, 2);
  left = (double *) malloc((d+1)*sizeof(double));
  right = (double *) malloc((d+1)*sizeof(double));

  ndu[0][0] = 1.0;
  
  // debug:
  //printf("d=%d, nk=%d, u=%g, s/i=%d, n/k=%d\n",d,nk,u,s,n);
  //printf("k[0]=%g k[-1]=%g\n",k[0], k[nk-1]);
  for( j = 1; j <= d; j++ )
  {
    left[j] = u - k[s+1-j];
    right[j] = k[s+j]-u;
    saved = 0.0;
    for( r = 0; r < j; r++ )
    {
	  //printf("r = %d\n",r);
      ndu[r][j] = right[r+1] + left[j-r];
      temp = ndu[j-1][r]/ndu[r][j];
      
      ndu[j][r] = saved + right[r+1]*temp;
      saved = left[j-r]*temp;
    }
    ndu[j][j] = saved;
	// ok same. printf("%g ",saved);
  }
// identical  for (j=0; j<=d; j++)
// identical	  for (r=0; r<=d; r++)
// identical		  printf("ndu[%d,%d] = %g\n",j,r,ndu[j][r]);

 //  printf("ndu %g\n", ndu[2][2]);
 //  printf("dders %g\n",ders[1][0]);
  for( j = 0; j <= d; j++ )
    ders[j][0] = ndu[d][j];

  for( r = 0; r <= d; r++ )
  {
    //printf("r=%d\n",r);
    s1 = 0;    s2 = 1;
    a[0][0] = 1.0;

    for( i = 1; i <= n; i++ )
    {
	//   if (r == 2)
	// 	  printf("i=%d\n",i);
	  //printf("i/l = %d\n",i);
      der = 0.0;
      rk = r-i;  pk = d-i;
      
      if( r >= i )
      {
        a[0][s2] = a[0][s1] / ndu[rk][pk+1];
        der = a[0][s2] * ndu[pk][rk];
  		//printf("der1 %g\n",der);
      }  
      if( rk >= -1 )
        j1 = 1;
      else
        j1 = -rk;  
      if( r-1 <= pk ) //r=0: i=1 --: -1 <= 2-1: true. j2=0
        j2 = i-1;
      else
		  // BUG
        //j2 = der-r;  
        j2 = d-r;  

	  //printf("j1=%d, j2=%d\n", j1, j2);
      for( j = j1; j <= j2; j++ )
      {
        a[j][s2] = (a[j][s1] - a[j-1][s1]) / ndu[rk+j][pk+1];
        der += a[j][s2] * ndu[pk][rk+j];
  		//printf("der2 %g\n",der);
      }  
      if( r <= pk )
      {
		//printf("rpk: r=%d, pk=%d, -a[%d][%d] = %g\n",r, pk, s1, i-1, -a[i-1][s1]);
        a[i][s2] = -a[i-1][s1] / ndu[r][pk+1];
        der += a[i][s2] * ndu[pk][r];
      }  
      ders[r][i] = der;
	  //printf("ddddder %g\n", der);
      j = s1; s1 = s2; s2 = j;
    }        
  }
  
  r = d;
  for( i = 1; i <= n; i++ )
  {
    for( j = 0; j <= d; j++ )
      ders[j][i] *= r;
    r *= d-i;
  }    
  //printf("ders %g\n",ders[0][0]);

  freematrix(ndu);
  freematrix(a);
  free(left);
  free(right);
}
/*!\rst
  Test that SPDMatrixInverse and CholeskyFactorLMatrixVectorSolve are  working correctly
  against some especially bad named matrices and some random inputs.
  Outline:

  1. Construct matrices, ``A``
  2. Select a solution, ``x``, randomly.
  3. Construct RHS by doing ``A*x``.
  4. Solve ``Ax = b`` using backsolve and direct-inverse; check the size of ``\|b - Ax\|``.

  \return
    number of test cases where the solver error is too large
\endrst*/
OL_WARN_UNUSED_RESULT int TestSPDLinearSolvers() {
  int total_errors = 0;

  // simple/small case where numerical factors are not present.
  // taken from: http://en.wikipedia.org/wiki/Cholesky_decomposition#Example
  {
    constexpr int size = 3;
    std::vector<double> matrix =
        {  4.0,   12.0, -16.0,
          12.0,   37.0, -43.0,
         -16.0,  -43.0,  98.0};

    const std::vector<double> cholesky_factor_L_truth =
        { 2.0, 6.0, -8.0,
          0.0, 1.0, 5.0,
          0.0, 0.0, 3.0};
    std::vector<double> rhs = {-20.0, -43.0, 192.0};
    std::vector<double> solution_truth = {1.0, 2.0, 3.0};

    int local_errors = 0;
    // check factorization is correct; only check lower-triangle
    if (ComputeCholeskyFactorL(size, matrix.data()) != 0) {
      ++total_errors;
    }
    for (int i = 0; i < size; ++i) {
      for (int j = 0; j < size; ++j) {
        if (j >= i) {
          if (!CheckDoubleWithinRelative(matrix[i*size + j], cholesky_factor_L_truth[i*size + j], 0.0)) {
            ++local_errors;
          }
        }
      }
    }

    // check the solve is correct
    CholeskyFactorLMatrixVectorSolve(matrix.data(), size, rhs.data());
    for (int i = 0; i < size; ++i) {
      if (!CheckDoubleWithinRelative(rhs[i], solution_truth[i], 0.0)) {
        ++local_errors;
      }
    }

    total_errors += local_errors;
  }

  const int num_tests = 10;
  const int num_test_sizes = 3;
  const int sizes[num_test_sizes] = {5, 11, 20};

  // following tolerances are based on numerical experiments and/or computations
  // of the matrix condition numbers (in MATLAB)
  const double tolerance_backsolve_max_list[3][num_test_sizes] =
      { {10*std::numeric_limits<double>::epsilon(), 100*std::numeric_limits<double>::epsilon(), 100*std::numeric_limits<double>::epsilon()},       // prolate
        {100*std::numeric_limits<double>::epsilon(), 1.0e4*std::numeric_limits<double>::epsilon(), 1.0e6*std::numeric_limits<double>::epsilon()},  // moler
        {50*std::numeric_limits<double>::epsilon(), 1.0e3*std::numeric_limits<double>::epsilon(), 5.0e4*std::numeric_limits<double>::epsilon()}    // random
      };
  const double tolerance_inverse_max_list[3][num_test_sizes] =
      { {1.0e-13, 1.0e-9, 1.0e-2},  // prolate
        {5.0e-13, 2.0e-8, 1.0e1},   // moler
        {7.0e-10, 7.0e-6, 1.0e2}    // random
      };

  UniformRandomGenerator uniform_generator(34187);
  // In each iteration, we form some an ill-conditioned SPD matrix.  We are using
  // prolate, moler, and random matrices.
  // Then we compute L * L^T = A.
  // We want to test solutions of A * x = b using two methods:
  //   1) Inverse: using L, we form A^-1 explicitly (ILL-CONDITIONED!)
  //   2) Backsolve: we never form A^-1, but instead backsolve L and L^T against b.
  // The resulting residual norms, ||b - A*x||_2 are computed; we check that
  // backsolve is accurate and inverse is affected strongly by conditioning.
  for (int j = 0; j < num_tests; ++j) {
    for (int i = 0; i < num_test_sizes; ++i) {
      std::vector<double> matrix(sizes[i]*sizes[i]);
      std::vector<double> inverse_matrix(sizes[i]*sizes[i]);
      std::vector<double> cholesky_factor(sizes[i]*sizes[i]);
      std::vector<double> rhs(sizes[i]);
      std::vector<double> solution(2*sizes[i]);

      double tolerance_backsolve_max;
      double tolerance_inverse_max;
      switch (j) {
        case 0: {
          BuildProlateMatrix(kProlateDefaultParameter, sizes[i], matrix.data());
          tolerance_backsolve_max = tolerance_backsolve_max_list[0][i];
          tolerance_inverse_max = tolerance_inverse_max_list[0][i];
          break;
        }
        case 1: {
          BuildMolerMatrix(-1.66666666666, sizes[i], matrix.data());
          tolerance_backsolve_max = tolerance_backsolve_max_list[1][i];
          tolerance_inverse_max = tolerance_inverse_max_list[1][i];
          break;
        }
        default: {
          if (j <= 1 || j > num_tests) {
            OL_THROW_EXCEPTION(BoundsException<int>, "Invalid switch option.", j, 2, num_tests);
          } else {
            BuildRandomSPDMatrix(sizes[i], &uniform_generator, matrix.data());
            tolerance_backsolve_max = tolerance_backsolve_max_list[2][i];
            tolerance_inverse_max = tolerance_inverse_max_list[2][i];
            break;
          }
        }
      }
      // cholesky-factor A, form A^-1
      std::copy(matrix.begin(), matrix.end(), cholesky_factor.begin());
      if (ComputeCholeskyFactorL(sizes[i], cholesky_factor.data()) != 0) {
        ++total_errors;
      }
      SPDMatrixInverse(cholesky_factor.data(), sizes[i], inverse_matrix.data());

      // set b = A*random_vector.  This way we know the solution explicitly.
      // this also allows us to ignore ||A|| in our computations when we
      // normalize the RHS.
      BuildRandomVector(sizes[i], 0.0, 1.0, &uniform_generator, solution.data());
      SymmetricMatrixVectorMultiply(matrix.data(), solution.data(), sizes[i], rhs.data());

      // re-scale the RHS so that its norm can be ignored in later computations
      double rhs_norm = VectorNorm(rhs.data(), sizes[i]);
      VectorScale(sizes[i], 1.0/rhs_norm, rhs.data());
      std::copy(rhs.begin(), rhs.end(), solution.begin());

      // Solve L * L^T * x1 = b (backsolve) and compute x2 = A^-1 * b
      CholeskyFactorLMatrixVectorSolve(cholesky_factor.data(), sizes[i], solution.data());
      SymmetricMatrixVectorMultiply(inverse_matrix.data(), rhs.data(), sizes[i], solution.data() + sizes[i]);

      double norm_residual_via_backsolve = ResidualNorm(matrix.data(), solution.data(), rhs.data(), sizes[i]);
      double norm_residual_via_inverse = ResidualNorm(matrix.data(), solution.data() + sizes[i], rhs.data(), sizes[i]);

      if (norm_residual_via_backsolve > tolerance_backsolve_max) {
        ++total_errors;
        OL_ERROR_PRINTF("experiment %d, size[%d] = %d, norm_backsolve = %.18E > %.18E = tol\n", j, i, sizes[i],
               norm_residual_via_backsolve, tolerance_backsolve_max);
      }

      if (norm_residual_via_inverse > tolerance_inverse_max) {
        ++total_errors;
        OL_ERROR_PRINTF("experiment %d, size[%d] = %d, norm_inverse = %.18E > %.18E = tol\n", j, i, sizes[i],
               norm_residual_via_inverse, tolerance_inverse_max);
      }
    }
  }

  return total_errors;
}
void Camera::applyInProgram(std::unique_ptr<Program>& program)
{
    glUniform3fv(program->getVariableID("cPosition"), 1, glm::value_ptr(_position));
    glUniformMatrix4fv(program->getVariableID("camera"), 1, false, glm::value_ptr(matrix()));
}
Beispiel #27
0
int main(void)
{
	unsigned long i,j,k,*ija,*ijb,*ijbt,*ijc;
	float *sa,*sb,*sbt,*sc,**a,**b,**c,**ab;
	static float ainit[NP][NP]={
		1.0,0.5,0.0,0.0,0.0,
		0.5,2.0,0.5,0.0,0.0,
		0.0,0.5,3.0,0.5,0.0,
		0.0,0.0,0.5,4.0,0.5,
		0.0,0.0,0.0,0.5,5.0};
	static float binit[NP][NP]={
		1.0,1.0,0.0,0.0,0.0,
		1.0,2.0,1.0,0.0,0.0,
		0.0,1.0,3.0,1.0,0.0,
		0.0,0.0,1.0,4.0,1.0,
		0.0,0.0,0.0,1.0,5.0};

	ija=lvector(1,NMAX);
	ijb=lvector(1,NMAX);
	ijbt=lvector(1,NMAX);
	ijc=lvector(1,NMAX);
	sa=vector(1,NMAX);
	sb=vector(1,NMAX);
	sbt=vector(1,NMAX);
	sc=vector(1,NMAX);
	c=matrix(1,NP,1,NP);
	ab=matrix(1,NP,1,NP);
	a=convert_matrix(&ainit[0][0],1,NP,1,NP);
	b=convert_matrix(&binit[0][0],1,NP,1,NP);
	sprsin(a,NP,0.5,NMAX,sa,ija);
	sprsin(b,NP,0.5,NMAX,sb,ijb);
	sprstp(sb,ijb,sbt,ijbt);
	/* specify tridiagonal output, using fact that a is tridiagonal */
	for (i=1;i<=ija[ija[1]-1]-1;i++) ijc[i]=ija[i];
	sprspm(sa,ija,sbt,ijbt,sc,ijc);
	for (i=1;i<=NP;i++) {
		for (j=1;j<=NP;j++) {
			ab[i][j]=0.0;
			for (k=1;k<=NP;k++) {
				ab[i][j]=ab[i][j]+a[i][k]*b[k][j];
			}
		}
	}
	printf("Reference matrix:\n");
	for (i=1;i<=NP;i++) {
		for (j=1;j<=NP;j++) printf("%5.2f\t",ab[i][j]);
		printf("\n");
	}
	printf("sprspm matrix (should show only tridiagonals):\n");
	for (i=1;i<=NP;i++) for (j=1;j<=NP;j++) c[i][j]=0.0;
	for (i=1;i<=NP;i++) {
		c[i][i]=sc[i];
		for (j=ijc[i];j<=ijc[i+1]-1;j++) c[i][ijc[j]]=sc[j];
	}
	for (i=1;i<=NP;i++) {
		for (j=1;j<=NP;j++) printf("%5.2f\t",c[i][j]);
		printf("\n");
	}
	free_convert_matrix(b,1,NP,1,NP);
	free_convert_matrix(a,1,NP,1,NP);
	free_matrix(ab,1,NP,1,NP);
	free_matrix(c,1,NP,1,NP);
	free_vector(sc,1,NMAX);
	free_vector(sbt,1,NMAX);
	free_vector(sb,1,NMAX);
	free_vector(sa,1,NMAX);
	free_lvector(ijc,1,NMAX);
	free_lvector(ijbt,1,NMAX);
	free_lvector(ijb,1,NMAX);
	free_lvector(ija,1,NMAX);
	return 0;
}
void PrecessingTops (DemoEntityManager* const scene)
{
	scene->CreateSkyBox();

	// customize the scene after loading
	// set a user friction variable in the body for variable friction demos
	// later this will be done using LUA script
	dMatrix offsetMatrix (dGetIdentityMatrix());

	CreateLevelMesh (scene, "flatPlane.ngd", 1);

	dVector location (0.0f, 0.0f, 0.0f, 0.0f);
	dVector size (3.0f, 2.0f, 0.0f, 0.0f);

	// create an array of cones 
	const int count = 10;

	// all shapes use the x axis as the  axis of symmetry, to make an upright cone we apply a 90 degree rotation local matrix
	dMatrix shapeOffsetMatrix (dRollMatrix(-3.141592f/2.0f));
	AddPrimitiveArray(scene, 50.0f, location, size, count, count, 5.0f, _CONE_PRIMITIVE, 0, shapeOffsetMatrix);

	// till the cont 30 degrees, and apply a local high angular velocity
	dMatrix matrix (dRollMatrix (-25.0f * 3.141592f / 180.0f));
	dVector omega (0.0f, 50.0f, 0.0f);
	omega = matrix.RotateVector (omega);
	dVector damp (0.0f, 0.0f, 0.0f, 0.0f);

	int topscount = 0;
	NewtonBody* array[count * count];
	NewtonWorld* const world = scene->GetNewton();
	for (NewtonBody* body = NewtonWorldGetFirstBody(world); body; body = NewtonWorldGetNextBody(world, body)) {
		NewtonCollision* const collision = NewtonBodyGetCollision(body);
		dVector com;
		if (NewtonCollisionGetType (collision) == SERIALIZE_ID_CONE) {
			array[topscount] = body;
			topscount ++;
		}
	}

	for (int i = 0; i < topscount ; i ++) {
		dMatrix bodyMatrix;
		NewtonBody* const body = array[i];
		NewtonBodyGetMatrix(body, &bodyMatrix[0][0]);
		matrix.m_posit = bodyMatrix.m_posit;
		matrix.m_posit.m_y += 1.0f; 
		NewtonBodySetMatrix(body, &matrix[0][0]);

		dFloat Ixx;
		dFloat Iyy;
		dFloat Izz;
		dFloat mass;
		NewtonBodyGetMassMatrix(body, &mass, &Ixx, &Iyy, &Izz);
		NewtonBodySetMassMatrix(body, mass, Ixx, Iyy * 8.0f, Izz);
		NewtonBodySetOmega (body, &omega[0]);

		NewtonBodySetAutoSleep (body, 0);
		NewtonBodySetLinearDamping(body, 0.0f);
		NewtonBodySetAngularDamping (body, &damp[0]);

	}

	// place camera into position
	dMatrix camMatrix (dGetIdentityMatrix());
	dQuaternion rot (camMatrix);
	dVector origin (-40.0f, 5.0f, 0.0f, 0.0f);
	scene->SetCameraMatrix(rot, origin);
}
NewtonCollision* CreateConvexCollision (NewtonWorld* world, const dMatrix& srcMatrix, const dVector& originalSize, PrimitiveType type, int materialID__)
{
	dVector size (originalSize);

	NewtonCollision* collision = NULL;
	switch (type) 
	{
		case _NULL_PRIMITIVE:
		{
			collision = NewtonCreateNull (world); 
			break;
		}

		case _SPHERE_PRIMITIVE:
		{
			// create the collision 
			collision = NewtonCreateSphere (world, size.m_x * 0.5f, 0, NULL); 
			break;
		}

		case _BOX_PRIMITIVE:
		{
			// create the collision 
			collision = NewtonCreateBox (world, size.m_x, size.m_y, size.m_z, 0, NULL); 
			break;
		}


		case _CONE_PRIMITIVE:
		{
			dFloat r = size.m_x * 0.5f;
			dFloat h = size.m_y;

			// create the collision 
			collision = NewtonCreateCone (world, r, h, 0, NULL); 
			break;
		}

		case _CYLINDER_PRIMITIVE:
		{
			// create the collision 
			collision = NewtonCreateCylinder (world, size.m_x * 0.5f, size.m_z * 0.5f, size.m_y, 0, NULL); 
			break;
		}


		case _CAPSULE_PRIMITIVE:
		{
			// create the collision 
			collision = NewtonCreateCapsule (world, size.m_x * 0.5f, size.m_z * 0.5f, size.m_y, 0, NULL); 
			break;
		}

		case _CHAMFER_CYLINDER_PRIMITIVE:
		{
			// create the collision 
			collision = NewtonCreateChamferCylinder (world, size.m_x * 0.5f, size.m_y, 0, NULL); 
			break;
		}

		case _RANDOM_CONVEX_HULL_PRIMITIVE:
		{
			// Create a clouds of random point around the origin
			#define SAMPLE_COUNT 200
			dVector cloud [SAMPLE_COUNT];

			// make sure that at least the top and bottom are present
			cloud [0] = dVector ( size.m_x * 0.5f, 0.0f, 0.0f, 0.0f);
			cloud [1] = dVector (-size.m_x * 0.5f, 0.0f, 0.0f, 0.0f);
			cloud [2] = dVector ( 0.0f,  size.m_y * 0.5f, 0.0f, 0.0f); 
			cloud [3] = dVector ( 0.0f, -size.m_y * 0.5f, 0.0f, 0.0f);
			cloud [4] = dVector (0.0f, 0.0f,  size.m_z * 0.5f, 0.0f); 
			cloud [5] = dVector (0.0f, 0.0f, -size.m_z * 0.5f, 0.0f); 

			int count = 6;
			// populate the cloud with pseudo Gaussian random points
			for (int i = 6; i < SAMPLE_COUNT; i ++) {
				cloud [i].m_x = RandomVariable(size.m_x);
				cloud [i].m_y = RandomVariable(size.m_y);
				cloud [i].m_z = RandomVariable(size.m_z);
				count ++;
			}
			collision = NewtonCreateConvexHull (world, count, &cloud[0].m_x, sizeof (dVector), 0.01f, 0, NULL); 
			break;
		}

		case _REGULAR_CONVEX_HULL_PRIMITIVE:
		{
			// Create a clouds of random point around the origin
			#define STEPS_HULL 6
			//#define STEPS_HULL 3

			//dVector cloud [STEPS_HULL * 4 + 256];
			dFloat cloud [STEPS_HULL * 4 + 256][3];
			int count = 0;
			dFloat radius = size.m_y;
			dFloat height = size.m_x * 0.999f;
			dFloat x = - height * 0.5f;
			dMatrix rotation (dPitchMatrix(2.0f * 3.141592f / STEPS_HULL));
			for (int i = 0; i < 4; i ++) {
				dFloat pad = ((i == 1) || (i == 2)) * 0.25f * radius;
				dVector p (x, 0.0f, radius + pad);
				x += 0.3333f * height;
				dMatrix acc (dGetIdentityMatrix());
				for (int j = 0; j < STEPS_HULL; j ++) {
					dVector tmp (acc.RotateVector(p)); 
					cloud[count][0] = tmp.m_x;
					cloud[count][1] = tmp.m_y;
					cloud[count][2] = tmp.m_z;
					acc = acc * rotation;
					count ++;
				}
			}

			collision = NewtonCreateConvexHull (world, count, &cloud[0][0], 3 * sizeof (dFloat), 0.02f, 0, NULL); 
			break;
		}

		case _COMPOUND_CONVEX_CRUZ_PRIMITIVE:
		{
			//dMatrix matrix (GetIdentityMatrix());
			dMatrix matrix (dPitchMatrix(15.0f * 3.1416f / 180.0f) * dYawMatrix(15.0f * 3.1416f / 180.0f) * dRollMatrix(15.0f * 3.1416f / 180.0f));
//			NewtonCollision* const collisionA = NewtonCreateBox (world, size.m_x, size.m_x * 0.25f, size.m_x * 0.25f, 0, &matrix[0][0]); 
//			NewtonCollision* const collisionB = NewtonCreateBox (world, size.m_x * 0.25f, size.m_x, size.m_x * 0.25f, 0, &matrix[0][0]); 
//			NewtonCollision* const collisionC = NewtonCreateBox (world, size.m_x * 0.25f, size.m_x * 0.25f, size.m_x, 0, &matrix[0][0]); 

matrix.m_posit = dVector (size.m_x * 0.5f, 0.0f, 0.0f, 1.0f);
NewtonCollision* const collisionA = NewtonCreateBox (world, size.m_x, size.m_x * 0.25f, size.m_x * 0.25f, 0, &matrix[0][0]); 
matrix.m_posit = dVector (0.0f, size.m_x * 0.5f, 0.0f, 1.0f);
NewtonCollision* const collisionB = NewtonCreateBox (world, size.m_x * 0.25f, size.m_x, size.m_x * 0.25f, 0, &matrix[0][0]); 
matrix.m_posit = dVector (0.0f, 0.0f, size.m_x * 0.5f, 1.0f);
NewtonCollision* const collisionC = NewtonCreateBox (world, size.m_x * 0.25f, size.m_x * 0.25f, size.m_x, 0, &matrix[0][0]); 


			collision = NewtonCreateCompoundCollision (world, 0);

			NewtonCompoundCollisionBeginAddRemove(collision);

			NewtonCompoundCollisionAddSubCollision (collision, collisionA);
			NewtonCompoundCollisionAddSubCollision (collision, collisionB);
			NewtonCompoundCollisionAddSubCollision (collision, collisionC);

			NewtonCompoundCollisionEndAddRemove(collision);	

			NewtonDestroyCollision(collisionA);
			NewtonDestroyCollision(collisionB);
			NewtonDestroyCollision(collisionC);
			break;
		}

		default: dAssert (0);
	}


	dMatrix matrix (srcMatrix);
	matrix.m_front = matrix.m_front.Scale (1.0f / dSqrt (matrix.m_front % matrix.m_front));
	matrix.m_right = matrix.m_front * matrix.m_up;
	matrix.m_right = matrix.m_right.Scale (1.0f / dSqrt (matrix.m_right % matrix.m_right));
	matrix.m_up = matrix.m_right * matrix.m_front;
	NewtonCollisionSetMatrix(collision, &matrix[0][0]);

	return collision;
}
static NewtonBody* CreateBackgroundWallsAndCellingBody(NewtonWorld* world)
{
	// make a flat quad 
	dFloat floor[4][3] =
	{
		{ -100.0f, 0.0f, 100.0f },
		{ 100.0f, 0.0f, 100.0f },
		{ 100.0f, 0.0f, -100.0f },
		{ -100.0f, 0.0f, -100.0f },
	};

	dFloat wall_N[4][3] =
	{
		{ -100.0f, 0.0f, 100.0f },
		{ -100.0f, 100.0f, 100.0f },
		{ 100.0f, 100.0f, 100.0f },
		{ 100.0f, 0.0f, 100.0f },
	};

	dFloat wall_W[4][3] =
	{
		{ 100.0f, 0.0f, 100.0f },
		{ 100.0f, 100.0f, 100.0f },
		{ 100.0f, 100.0f, -100.0f },
		{ 100.0f, 0.0f, -100.0f },
	};

	dFloat wall_S[4][3] =
	{
		{ 100.0f, 0.0f, -100.0f },
		{ 100.0f, 100.0f, -100.0f },
		{ -100.0f, 100.0f, -100.0f },
		{ -100.0f, 0.0f, -100.0f },
	};

	dFloat wall_E[4][3] =
	{
		{ -100.0f, 0.0f, -100.0f },
		{ -100.0f, 100.0f, -100.0f },
		{ -100.0f, 100.0f, 100.0f },
		{ -100.0f, 0.0f, 100.0f },
	};

	dFloat celling[4][3] =
	{
		{ -100.0f, 100.0f, -100.0f },
		{ 100.0f, 100.0f, -100.0f },
		{ 100.0f, 100.0f, 100.0f },
		{ -100.0f, 100.0f, 100.0f },
	};

	// crate a collision tree
	NewtonCollision* const collision = NewtonCreateTreeCollision(world, 0);

	// start building the collision mesh
	NewtonTreeCollisionBeginBuild(collision);

	// add the face one at a time
	NewtonTreeCollisionAddFace(collision, 4, &floor[0][0], 3 * sizeof (dFloat), 0);
	NewtonTreeCollisionAddFace(collision, 4, &wall_N[0][0], 3 * sizeof (dFloat), 0);
	NewtonTreeCollisionAddFace(collision, 4, &wall_W[0][0], 3 * sizeof (dFloat), 0);
	NewtonTreeCollisionAddFace(collision, 4, &wall_S[0][0], 3 * sizeof (dFloat), 0);
	NewtonTreeCollisionAddFace(collision, 4, &wall_E[0][0], 3 * sizeof (dFloat), 0);
	NewtonTreeCollisionAddFace(collision, 4, &celling[0][0], 3 * sizeof (dFloat), 0);

	// finish building the collision
	NewtonTreeCollisionEndBuild(collision, 1);

	// create a body with a collision and locate at the identity matrix position 
	dMatrix matrix(dGetIdentityMatrix());
	NewtonBody* const body = NewtonCreateDynamicBody(world, collision, &matrix[0][0]);

	// do no forget to destroy the collision after you not longer need it
	NewtonDestroyCollision(collision);
	return body;
}