示例#1
0
文件: ctbin.cpp 项目: lyang54/ctools
/***********************************************************************//**
 * @brief Get application parameters
 *
 * Get all task parameters from parameter file or (if required) by querying
 * the user. Most parameters are only required if no observation exists so
 * far in the observation container. In this case, a single CTA observation
 * will be added to the container, using the definition provided in the
 * parameter file.
 ***************************************************************************/
void ctbin::get_parameters(void)
{
    // If there are no observations in container then load them via user
    // parameters
    if (m_obs.size() == 0) {

        // Throw exception if no input observation file is given
        require_inobs(G_GET_PARAMETERS);

        // Get observation container without response (not needed)
        m_obs = get_observations(false);

    } // endif: there was no observation in the container

    // Create an event cube based on task parameters
    GCTAEventCube cube = create_cube(m_obs);

    // Get the skymap from the cube and initialise all pixels to zero
    m_cube = cube.map();
    m_cube = 0.0;

    // Get energy boundaries
    m_ebounds  = cube.ebounds();

    // Optionally read ahead parameters so that they get correctly
    // dumped into the log file
    if (read_ahead()) {
        m_outcube = (*this)["outcube"].filename();
    }

    // Return
    return;
}
auto_release_ptr<MeshObject> create_primitive_mesh(const char* name, const ParamArray& params)
{
    const char* primitive_type = params.get("primitive");

    // Parametric surfaces.

    if (strcmp(primitive_type, "grid") == 0)
        return create_parametric_surface<ParametricGrid>(name, params);

    if (strcmp(primitive_type, "disk") == 0)
        return create_parametric_surface<ParametricDisk>(name, params);

    if (strcmp(primitive_type, "sphere") == 0)
        return create_parametric_surface<ParametricSphere>(name, params);

    if (strcmp(primitive_type, "torus") == 0)
        return create_parametric_surface<ParametricTorus>(name, params);

    // Other, non-parametric primitives.

    if (strcmp(primitive_type, "cube") == 0)
        return create_cube(name, params);

    RENDERER_LOG_ERROR("unknown primitive type: %s", primitive_type);
    return auto_release_ptr<MeshObject>();
}
示例#3
0
void nemo_main()
{
  stream  outstr;
  int     nx, ny, nz;  
  int     ix, iy, iz;
  imageptr optr=NULL;        /* pointer to image, needs to be NULL to force new */
  real    tmp, sum = 0.0;

  outstr = stropen(getparam("out"), "w");

  nx = getiparam("nx");
  ny = getiparam("ny");
  nz = getiparam("nz");

  dprintf(0,"Creating image cube (size : %d x %d x %d)\n",nx,ny,nz);

  create_cube(&optr,nx,ny,nz);

  for (iz=0; iz<nz; iz++) {
    for (iy=0; iy<ny; iy++) {
      for (ix=0; ix<nx/2; ix++) {
        CubeValue(optr,ix,iy,iz) = 0.0;
      }
    }
  }

  write_image(outstr, optr);



}
示例#4
0
/*
 *  create new map from scratch, using %x and %y as position parameters 
 *		0..nx-1 and 0..ny-1
 */
local void do_create(int nx, int ny,int nz)
{
    double m_min, m_max, total;
    real   fin[5], fout;
    int    ix, iy, iz;
    int    badvalues;
    
    m_min = HUGE; m_max = -HUGE;
    total = 0.0;		/* count total intensity in new map */
    badvalues = 0;		/* count number of bad operations */

    if (nz > 0) {
      warning("cube");
      if (!create_cube (&iptr, nx, ny, nz))	/* create default empty image */
        error("Could not create 3D image from scratch");
#if 0      
      Axis(iptr) = 1;      /* set linear axistype with a fits-style reference pixel */
#endif
      wcs_f2i(3,crpix,crval,cdelt,iptr);

      for (iz=0; iz<nz; iz++) {
        fin[2] = iz-crpix[2]+1;   /* crpix is 1 for first pixel (FITS convention) */
        for (iy=0; iy<ny; iy++) {
	  fin[1] = iy-crpix[1]+1;
	  for (ix=0; ix<nx; ix++) {
	    fout = 0.0;
	    CubeValue(iptr,ix,iy,iz) = fout;
	    m_min = MIN(m_min,fout);         /* and check for new minmax */
	    m_max = MAX(m_max,fout);
	    total += fout;                   /* add up totals */
	  }
        }
      }
    } else {
      warning("2d-map");
      if (!create_image (&iptr, nx, ny))	
        error("Could not create 2D image from scratch");
      wcs_f2i(2,crpix,crval,cdelt,iptr);

      for (iy=0; iy<ny; iy++) {
	fin[1] = iy;
	for (ix=0; ix<nx; ix++) {
	  fout = 0.0;
	  MapValue(iptr,ix,iy) = fout;
	  m_min = MIN(m_min,fout);         /* and check for new minmax */
	  m_max = MAX(m_max,fout);
	  total += fout;                   /* add up totals */
	}
      }
    } 
    
    MapMin(iptr) = m_min;
    MapMax(iptr) = m_max;

    dprintf(1,"New min and max in map are: %f %f\n",m_min,m_max);
    dprintf(1,"New total brightness/mass is %f\n",
			total*Dx(iptr)*Dy(iptr));
    if (badvalues)
    	warning ("There were %d bad operations in dofie",badvalues);
}
示例#5
0
void nemo_main ()
{
  setparams();			/* set par's in globals */

  instr = stropen (infile, "r");
  read_image (instr,&iptr);
				/* set some global paramters */
  nx = Nx(iptr);	
  ny = Ny(iptr);
  nz = Nz(iptr);
  xmin = Xmin(iptr);
  ymin = Ymin(iptr);
  zmin = Zmin(iptr);
  dx = Dx(iptr);
  dy = Dy(iptr);
  dz = Dz(iptr);
  create_cube(&iptr1, nx, ny, nz);
  
  report_minmax("old");

  if(hasvalue("gauss"))
    make_gauss_beam(getparam("dir"));

  outstr = stropen (outfile,"w");
  smooth_it();
  write_image (outstr,iptr);
  
  strclose(instr);
  strclose(outstr);
}
示例#6
0
/***********************************************************************//**
 * @brief Get application parameters
 *
 * Get all task parameters from parameter file or (if required) by querying
 * the user. The parameters are read in the correct order.
 ***************************************************************************/
void ctexpcube::get_parameters(void)
{
    // Setup observations from "inobs" parameter. Do not accept counts cubes.
    setup_observations(m_obs, true, true, false);

    // Get the incube filename
    std::string incube = (*this)["incube"].filename();

    // If the "incube" file name is valid then setup the exposure cube from
    // the counts cube. Otherwise create a counts cube from the user
    // parameters
    GCTAEventCube cube = is_valid_filename(incube) ? GCTAEventCube(incube)
                                                   : create_cube(m_obs);
    
    // Define exposure cube
    m_expcube = GCTACubeExposure(cube);

    // Get remaining parameters
    m_addbounds = (*this)["addbounds"].boolean();
    m_publish   = (*this)["publish"].boolean();
    m_chatter   = static_cast<GChatter>((*this)["chatter"].integer());

    // Read output filename (if needed)
    if (read_ahead()) {
        m_outcube = (*this)["outcube"].filename();
    }

    // Write parameters into logger
    log_parameters(TERSE);

    // Return
    return;
}
void ShZshapeManager::create_shape(const char* content)
{
	if (content == "cube")
	{
		create_cube();
	}

	if (content == "cylinder")
	{
		create_cylinder();
	}

	if (content == "pipe")
	{
		create_pipe();
	}

	if (content == "cone")
	{
		create_cone();
	}

	if (content == "circle")
	{
		create_circle();
	}

	if (content == "ring")
	{
		create_ring();
	}

	if (content == "pyramid")
	{
		create_pyramid();
	}

	if (content == "triangle")
	{
		create_triangle();
	}

	if (content == "rectangle")
	{
		create_rectangle();
	}

	if (content == "polygon")
	{
		create_polygon();
	}

	if (content == "multigonalStar")
	{
		create_multigonalStar();
	}

}
示例#8
0
文件: cube.cpp 项目: Naturlix/FAllSM
int main()
{
	int timer=0;
	sf::RenderWindow window(sf::VideoMode(resolution_X, resolution_Y), "My window",sf::Style::None);
	cube* last=new cube;
	cube* curent;
	last=create_cube(last);	
	cube* first=last;
	
		while (window.isOpen()){
		sf::Event event;
        	timer++;
		
		while (window.pollEvent(event)){ if (event.key.code == sf::Keyboard::Escape) window.close();}
	
		if(timer%COMPLEXITY==0) last=create_cube(last); //ever 1000 create a cube


		curent=first;//start to calculating a movement of all cubes

		do{
		movement_calc(curent,first);
		curent->name->setPosition((curent->position.x),(curent->position.y));
		curent->name->setRotation(curent->angle);
		if(curent->next!=NULL)curent=curent->next;
		} while(curent->next!=NULL);

		
        	window.clear(sf::Color::Black);//clear screen

	
        	curent=first;//display all cubes
		do{			
			window.draw(*(curent->name));
       			if(curent->next!=NULL)curent=curent->next;
		}while(curent->next!=NULL);
	
		window.display();
    		}

    return 0;
}
示例#9
0
/***********************************************************************//**
 * @brief Get application parameters
 *
 * Get all task parameters from parameter file or (if required) by querying
 * the user. The parameters are read in the correct order.
 ***************************************************************************/
void ctpsfcube::get_parameters(void)
{
    // If there are no observations in container then load them via user
    // parameters
    if (m_obs.size() == 0) {

        // Throw exception if no input observation file is given
        require_inobs(G_GET_PARAMETERS);

        // Build observation container
        m_obs = get_observations();

    } // endif: there was no observation in the container

    // Get the incube filename
    std::string incube = (*this)["incube"].filename();

    // Get additional binning parameters
    double amax     = (*this)["amax"].real();
    int    anumbins = (*this)["anumbins"].integer();

    // Check for filename validity
    if ((incube == "NONE") || (gammalib::strip_whitespace(incube) == "")) {

        // Create an event cube based on task parameters
        GCTAEventCube cube = create_cube(m_obs);

        // Define psf cube
        m_psfcube = GCTACubePsf(cube, amax, anumbins);

    }

    // ... otherwise setup the exposure cube from the counts map
    else {

        // Load event cube from filename
        GCTAEventCube cube(incube);

        // Define psf cube
        m_psfcube = GCTACubePsf(cube, amax, anumbins);

    } // endelse: cube loaded from file

    // Read energy dispersion flag
    m_apply_edisp = (*this)["edisp"].boolean();

    // Read output filename (if needed)
    if (read_ahead()) {
        m_outcube = (*this)["outcube"].filename();
    }

    // Return
    return;
}
void ShZshapeManager::create_shape(const char* content, GLdouble positionX, GLdouble positionY, GLdouble positionZ, GLdouble l_rin, GLdouble h_rout, GLdouble w_h)
{
	if (content == "cube")
	{
		create_cube(positionX, positionY, positionZ, l_rin, h_rout, w_h);
	}

	if (content == "pipe")
	{
		create_pipe(positionX, positionY, positionZ, l_rin, h_rout, w_h);
	}
}
void prep_mesh( double A_f, int valence )
{

  //create the initial geometry and mesh it
  create_cube();

  //Get all of the surface ModelEnts
  
  //Now to find one of the surfaces that is constant in z (for convenience)
  moab::EntityHandle hv_surf;
  get_hv_surf( hv_surf );

  //refacet the surface using the desired area fraction for the hv region
  refacet_surface( hv_surf, A_f, valence );

}
示例#12
0
文件: scale.c 项目: cutplane/cutplane
  void
create_scalebbox(worldptr world)
{
  vfeptr thisvfe;
  evfptr thisevf;
  fveptr thisfve;
  ;
  /* scalebbox_obj is a global object that gets copied when primary */
  /* world objects get picked, so that they can be scaled.  */
  
  scalebbox_obj = create_cube(environment_world,100.0,100.0,100.0);

  scalebbox_obj->drawtechnique = draw_scalebbox_technique;
  scalebbox_obj->selectechnique = set_scalebbox_selectable;
  set_object_name(scalebbox_obj,"Scalebbox");
  add_property((featureptr) scalebbox_obj, transparent_prop);

  add_property((featureptr) scalebbox_obj, noshadow_prop);
  add_property((featureptr) scalebbox_obj, sectioninvisible_prop);
  add_property((featureptr) scalebbox_obj, selectinvisible_prop);
  add_property((featureptr) scalebbox_obj, pickedinvisible_prop);

  add_property((featureptr) scalebbox_obj, scalebbox_prop);
  del_property((featureptr) scalebbox_obj, visible_prop);
  thisvfe = First_obj_vfe(scalebbox_obj);
  while (thisvfe != Nil)
  {
    add_property((featureptr) thisvfe, scalebbox_prop);
    thisvfe = thisvfe->next;
  }
  thisevf = First_obj_evf(scalebbox_obj);
  while (thisevf != Nil)
  {
    add_property((featureptr) thisevf, scalebbox_prop);
    thisevf = thisevf->next;
  }
  thisfve = First_obj_fve(scalebbox_obj);
  while (thisfve != Nil)
  {
    add_property((featureptr) thisfve, scalebbox_prop);
    thisfve = thisfve->next;
  }
}
示例#13
0
/*
 * create a velocity field (GIPSY method)
 *              0..nx-1 and 0..ny-1 
 *      start from pixel, work back to gal plane and interpolate
 *      (a.k.a. retracing method)
 *
 */
local void cube_create(stream outstr)
{
  int  i, j, k, n, nx, ny;
  real m_min, m_max, sum;
  real den, vel, sig, velk, x;
  imageptr vptr;
  real f = 4.0;
  
  m_min = HUGE; m_max = -HUGE;
  nx = Nx(velptr);
  ny = Ny(velptr);
  
  if (!create_cube(&vptr, nx, ny, nz))   /* output data cube */
    error("Could not create cube from scratch");
  
  for (j=0; j<ny; j++)            /* Loop over all pixels */
    for (i=0; i<nx; i++) {
      for (k=0; k<nz; k++)
	CubeValue(vptr,i,j,k) = undef;       /* first set all to 'undefined' */
      sum = 0.0;
      vel = MapValue(velptr,i,j);

      if (denptr) {
	den = MapValue(denptr,i,j);
	if (den <= 0.0) continue;
      } else
	den = 1.0;

      if (sigptr) {
	sig = MapValue(sigptr,i,j);
	if (sig < 0.0) continue;
      } else
	sig = sigdef;
      if (sig == 0.0) {      /* special case, only populate 1 cell */
	k = (int) floor(    (vel-zrange[0])/zrange[2]   );
	if (k<0 || k>nz-1) continue;
	CubeValue(vptr,i,j,k) = den;
	sum = den;
      } else {               /* else use a gaussian profile */
	for (k=0, velk=zrange[0]+0.5*zrange[2]; k<nz; k++, velk += zrange[2]) {
	  x = (velk-vel)/sig;
	  x = ABS(x);
	  if (x > f) continue;
	  CubeValue(vptr,i,j,k) = den * exp(-0.5*x*x);
	  sum += CubeValue(vptr,i,j,k);
	}
      }
      sum = den/sum;              /* now normalize the spectrum so the sum is 'den' */
      for (k=0; k<nz; k++) {
	if (CubeValue(vptr,i,j,k) != undef)
	  CubeValue(vptr,i,j,k) *= sum;
      }
    }
      
  n=0;
  for (k=0; k<nz; k++)        /* get min and max in map */
    for (j=0; j<ny; j++)
      for (i=0; i<nx; i++) 
	if (CubeValue(vptr,i,j,k) != undef) {
	  m_min = MIN(CubeValue(vptr,i,j,k),m_min);
	  m_max = MAX(CubeValue(vptr,i,j,k),m_max);
	} else
	  n++;
  MapMin(vptr) = m_min;
  MapMax(vptr) = m_max;
  Dx(vptr) = Dx(velptr);
  Dy(vptr) = Dy(velptr);
  Dz(vptr) = zrange[2];
  Xmin(vptr) = Xmin(velptr);
  Ymin(vptr) = Ymin(velptr);
  Zmin(vptr) = zrange[0];
  
  if (n>0) warning("%d/%d cells with no signal",n,nx*ny*nz);
  printf("Min and max in map: %g %g\n",m_min,m_max);
  write_image (outstr,vptr);  
}
示例#14
0
void nemo_main()
{
    stream outstr;
    FITS *fitsfile;
    int ndim=3, naxis[3], nx, ny, nz, i, j, k, npl, p, planes[MAXPLANES];
    int nbval=0;
    real bval_out, rmin, rmax, tmp;
    FLOAT *buffer, *bp, bval_in;  /* fitsio- is in FLOAT !!! */
    FLOAT fdata_min, fdata_max, fnan;
    int mir_nan = -1;    /* MIRIAD's FITS NaN */
    imageptr iptr;
    string mode, blankval;
    bool   Qblank, Qrel, Qout;
    int axistype = getiparam("axistype");

    Qout = hasvalue("out");
    if (Qout)
      outstr = stropen(getparam("out"),"w");   /* open image file for output */
    npl = nemoinpi(getparam("planes"),planes,MAXPLANES);
    mode = getparam("mode");
    blankval = getparam("blank");
    Qblank = (*blankval != 0);
    Qrel = getbparam("relcoords");
    get_nanf(&fnan);
#if 1
    memcpy(&fnan,&mir_nan,sizeof(int));    /* PORTABILITY ! */
#endif    
    if (streq(mode,"fits"))
      fitsfile = fitopen(getparam("in"),"old",ndim,naxis);
    else if (streq(mode,"raw"))
      fitsfile = rawopen(getparam("in"),"old",ndim,naxis);
    else
      error("Illegal mode %s: must be one of {fits,raw}",mode);

    if (fitsfile==NULL) error("Could not open file %s in %s mode\n",
               getparam("in"),mode);
    nx = naxis[0];
    ny = naxis[1];
    nz = (npl>0) ? npl : naxis[2];
    if (nx*ny*nz==0) error("Bad fits image: nx*ny*nz=0");
    if (nx==1) warning("Fits image: nx=1");
    if (ny==1) warning("Fits image: ny=1");
    if (nz > 1) {
        dprintf(0,"FITS file: Image size %d %d %d\n",nx,ny,nz);
        create_cube(&iptr,nx,ny,nz);
    } else {
        dprintf(0,"FITS file: Image size %d %d\n",nx,ny);
        create_image(&iptr,nx,ny);
    }
    if (iptr==NULL) error("No memory to allocate image");

    if (streq(mode,"fits")) {
      make_fitheader(fitsfile,iptr,Qrel,Qout,axistype, &fdata_min, &fdata_max);
      dprintf(1,"Datamin/max read: %g - %g\n",fdata_min, fdata_max);
    } else if (streq(mode,"raw"))
      make_rawheader(fitsfile,iptr,Qrel);
    else
      error("Never Reached");

    if (!Qout) return;

    bval_out = 0.0;
    if (Qblank) {    
      if (streq(blankval,"datamin"))
	bval_in = fdata_min;
      else if (streq(blankval,"datamax"))
	bval_in = fdata_max;
      else if (streq(blankval,"mirnan")) {
	memcpy(&bval_in,&mir_nan,sizeof(int));    /* PORTABILITY ! */
      } else
	bval_in = (FLOAT) getdparam("blank");
      dprintf(0,"Substituting blank=%g [%s] with %g\n",
	      bval_in,blankval,bval_out);
    }


    buffer = (FLOAT *) allocate(nx*sizeof(FLOAT));

    rmin = HUGE;
    rmax = -HUGE;
    for (k=0; k<nz; k++) {          /* loop over all/selected planes */
        p = (npl>0) ? planes[k] : k;        /* select plane number */
        dprintf(2,"Reading plane %d\n",p);
        fitsetpl(fitsfile,1,&p);
        for (j=0; j<ny; j++) {      /* loop over all rows */
            fitread(fitsfile,j,buffer);     /* read it from fits file */
            for (i=0, bp=buffer; i<nx; i++, bp++) {   /* stuff it in memory */
                if (Qblank) {
		  if (is_feq((int *)bp,(int *)&bval_in)) {
		    nbval++;
		    *bp = bval_out;
		  } else if (isnan(*bp)) {
		    nbval++;
		    *bp = bval_out;
		  }
                } else {
		  if (is_feq((int *)bp,(int *)&fnan)) {
		    nbval++;
		    *bp = bval_out;
		  } else if (isnan(*bp)) {
		    nbval++;
		    *bp = bval_out;
		  }
		  dprintf(2,"%g %g %g %g, %d\n",*bp,fdata_min, fdata_max,fnan,nbval); 
		}
                tmp = CubeValue(iptr,i,j,k) = *bp;
                rmin=MIN(rmin,tmp);
                rmax=MAX(rmax,tmp);
            }
        }
    }
    if (rmin != MapMin(iptr)) {
        warning("Setting map minimum from %g to %g",MapMin(iptr),rmin);
        MapMin(iptr) = rmin;
    } 
    if (rmax != MapMax(iptr)) {
        warning("Setting map maximum from %g to %g",MapMax(iptr),rmax);
        MapMax(iptr) = rmax;
    }
    fitclose(fitsfile);
    write_image(outstr,iptr);
    if (nbval==0)
      dprintf(0,"There were no blank values set in the image\n");
    else
      dprintf(0,"There were %d blank values in the image\n",nbval);
    free(buffer);
}
示例#15
0
static inline bool valid_facerotations(cube_t *cube) {
    cube_t *ref_cube = create_cube(MIN_LAYERS);

    typedef uint8_t aln_t;
    enum aln_e {
        topside_aligned, rightside_aligned, frontside_aligned
    };

    aln_t side_aligned = topside_aligned;
    switch (cube->side_color[TOP_SIDE]) {
    case WHITE:
        move_cube(ref_cube, X_R180, 0, 0);
        break;
    case RED:
        move_cube(ref_cube, Z_R90_CW, 0, 0);
        side_aligned = rightside_aligned;
        break;
    case ORANGE:
        move_cube(ref_cube, Z_R90_C_CW, 0, 0);
        side_aligned = rightside_aligned;
        break;
    case BLUE:
        move_cube(ref_cube, Y_R90_C_CW, 0, 0);
        side_aligned = frontside_aligned;
        break;
    case GREEN:
        move_cube(ref_cube, Y_R90_CW, 0, 0);
        side_aligned = frontside_aligned;
    }

    switch (side_aligned) {
    case topside_aligned:
        switch (cube->side_color[RIGHT_SIDE]) {
        case ORANGE:
            move_cube(ref_cube, Y_R180, 0, 0);
            break;
        case BLUE:
            move_cube(ref_cube, Y_R90_C_CW, 0, 0);
            break;
        case GREEN:
            move_cube(ref_cube, Y_R90_CW, 0, 0);
        }
        break;
    case rightside_aligned:
        switch (cube->side_color[TOP_SIDE]) {
        case WHITE:
            move_cube(ref_cube, X_R180, 0, 0);
            break;
        case BLUE:
            move_cube(ref_cube, X_R90_C_CW, 0, 0);
            break;
        case GREEN:
            move_cube(ref_cube, X_R90_CW, 0, 0);
        }
        break;
    case frontside_aligned:
        switch (cube->side_color[TOP_SIDE]) {
        case WHITE:
            move_cube(ref_cube, Z_R180, 0, 0);
            break;
        case RED:
            move_cube(ref_cube, X_R90_CW, 0, 0);
            break;
        case ORANGE:
            move_cube(ref_cube, X_R90_C_CW, 0, 0);
        }
    }

    destroy_cube(ref_cube);

    for (color_t i = 0; i < TOTAL_COLORS; i++) {
        if (ref_cube->face_offset[i] != cube->face_offset[i])
            return false;
    }

    return true;
}
示例#16
0
文件: ccdrt.c 项目: jobovy/nemo
void nemo_main()
{
    stream  instr, outstr;
    int     nx, ny, nz, nx1, ny1, nz1;
    int     axis, mom;
    int     i,j,k, apeak, cnt;
    imageptr iptr=NULL, iptr1=NULL, iptr2=NULL;      /* pointer to images */
    real    tmp0, tmp1, tmp2, tmp00, newvalue, peakvalue, scale, offset;
    bool    Qpeak;

    instr = stropen(getparam("in"), "r");
    mom = 0;
    axis = 3;
    Qpeak = getbparam("peak");

    read_image( instr, &iptr);

    nx1 = nx = Nx(iptr);	
    ny1 = ny = Ny(iptr);
    nz1 = 1;
    nz  = Nz(iptr);

    outstr = stropen(getparam("out"), "w");

    create_cube(&iptr1,nx1,ny1,nz1);
    create_cube(&iptr2,nx1,ny1,nz1);


    scale = Dz(iptr);
    offset = Zmin(iptr);
    for(j=0; j<ny; j++)
      for(i=0; i<nx; i++) {
	tmp0 = tmp00 = tmp1 = tmp2 = 0.0;
	cnt = 0;
	peakvalue = CubeValue(iptr,i,j,0);
	for(k=0; k<nz; k++) {
	  if (out_of_range(CubeValue(iptr,i,j,k))) continue;
	  cnt++;
	  tmp0 += CubeValue(iptr,i,j,k);
	  tmp00 += sqr(CubeValue(iptr,i,j,k));
	  if (CubeValue(iptr,i,j,k) > peakvalue) {
	    apeak = k;
	    peakvalue = CubeValue(iptr,i,j,k);
	  }
	}
	if (cnt==0 || tmp0==0.0) {
	  newvalue = 0.0;
	} else {
	  if (Qpeak) 
	    newvalue = peakvalue;
	  else
	    newvalue = tmp0;
	}
	CubeValue(iptr1,i,j,1) = newvalue;
      }
    
     
    Xmin(iptr1) = Xmin(iptr);
    Ymin(iptr1) = Ymin(iptr);
    Zmin(iptr1) = Zmin(iptr) + 0.5*(nz-1)*Dz(iptr);
    Dx(iptr1) = Dx(iptr);
    Dy(iptr1) = Dy(iptr);
    Dz(iptr1) = nz * Dz(iptr);
    
    Namex(iptr1) = Namex(iptr); /* care: we're passing a pointer */
    Namey(iptr1) = Namey(iptr);
    Namez(iptr1) = Namez(iptr);
    
    write_image(outstr, iptr1);
}
示例#17
0
void Engine::init_scene() {
    Node* scene = nodes["scene"] = new Node(NULL);

    // shaders //

    // "simple_shader"
    shaders["simple_shader"] = make_shader("shaders/p_v.glsl",
                                           "shaders/unicolor_f.glsl");

    // "light1"
    {
        Shader* shader = shaders["light1"] =
                make_shader("shaders/pn_v.glsl", "shaders/light1_f.glsl");

        // TODO put uniforms in "material"-class or something?
        set_uniform(shader, "mycolor", glm::vec4(1.f));
        set_uniform(shader, "ambient_intensity", glm::vec4(.1f,.1f,.1f,1.f));
        set_uniform(shader, "diffuse_color", glm::vec4(.5f,.5f,.5f,1.f));
        set_uniform(shader, "specular_color", glm::vec4(1.f,1.f,1.f,1.f));

        set_uniform(shader, "atten_k", .04f);
        set_uniform(shader, "gauss_k", .1f);
    }

    // objects //

    // grid
    {
        Shader* shader = shaders["simple_shader"];

        Node* node = nodes["grid"] = new Node(scene);

        int no = 5;
        glm::vec3 scale = glm::vec3(20.f);
        VAO* vao = create_grid(no, scale);

        std::vector<Uniform*> material;

        glm::vec4 white = glm::vec4(1.f);
        StoredUniform<glm::vec4>* mycolor =
                new StoredUniform<glm::vec4>(shader, "mycolor", white);
        material.push_back(mycolor);

        renderables.push_back(
                    new BasicRenderObject(shader, node, vao, material));

        // mem
        vaos.push_back(vao);
        uniforms.push_back(mycolor);
    }

    // redcube
    {
        Shader* shader = shaders["light1"];

        Node* node = nodes["redcube"] = new Node(scene);
        node->position = glm::vec3(.5f,.5f,-1.7f);

        glm::vec3 scale = glm::vec3(.05f);
        VAO* vao = create_cube_with_normals(scale);

        std::vector<Uniform*> material;

        glm::vec4 red = glm::vec4(1.f,0.f,.5f,1.f);
        StoredUniform<glm::vec4>* mycolor =
                new StoredUniform<glm::vec4>(shader, "mycolor", red);
        material.push_back(mycolor);

        renderables.push_back(
                new LitRenderObject(shader, node, vao, material));


        // physics
        btCollisionShape* cube_shape = new btBoxShape(from_vec3(scale/2.f));

        float mass = 0.f;
        redcube_rb = create_rigid_body(mass, node, cube_shape);
        physics->add_rigid_body(redcube_rb);


        // mem
        vaos.push_back(vao);
        uniforms.push_back(mycolor);
        collision_shapes.push_back(cube_shape);
    }

    make_litcube("cyancube",
                 glm::vec4(0.f, 1.f, 1.f, 1.f),
                 glm::vec3(0.05f));
    nodes["cyancube"]->orientation =
            glm::angleAxis(glm::radians(45.f),
                           glm::normalize(glm::vec3(-1.f, 1.f, 1.f)));

    make_litcube("yellowcube",
                 glm::vec4(1.f, 1.f, 0.f, 1.f),
                 glm::vec3(0.05f));
    nodes["yellowcube"]->orientation = nodes["cyancube"]->orientation;

    make_litcube("bluecube",
                 glm::vec4(0.f, 0.f, 1.f, 1.f),
                 glm::vec3(1.f),
                 30.f,
                 glm::vec3(0.f, 1.5f, -5.f));

    // lightcube
    {
        Shader* shader = shaders["simple_shader"];

        Node* node = nodes["lightcube"] = new Node(scene);
        node->position = glm::vec3(0.f, 1.f, 0.f);

        glm::vec3 scale = glm::vec3(.3f,.3f,.3f);
        VAO* vao = create_cube(scale);

        std::vector<Uniform*> material;

        glm::vec4 white = glm::vec4(1.f,1.f,1.f,1.f);
        StoredUniform<glm::vec4>* mycolor =
                new StoredUniform<glm::vec4>(shader, "mycolor", white);
        material.push_back(mycolor);

        renderables.push_back(
                new BasicRenderObject(shader, node, vao, material));

        // sync point light with position
        PointLight light0(node, glm::vec4(.7f,.7f,.7f,1.f));
        set_uniform(shaders["light1"], "light.position",
                    glm::vec3(light0.get_position()));
        set_uniform(shaders["light1"], "light.intensity",
                    light0.get_intensity());

        // mem
        vaos.push_back(vao);
        uniforms.push_back(mycolor);
    }

    // plane
    {
        Shader* shader = shaders["light1"];

        Node* node = nodes["plane"] = new Node(scene);
        node->position = glm::vec3(0.f, -.5f, 0.f);

        glm::vec3 scale = glm::vec3(20.f, 1.f, 20.f);
        VAO* vao = create_cube_with_normals(scale);

        std::vector<Uniform*> material;

        glm::vec4 goldish = glm::vec4(1.f,1.f,0.f,1.f);
        StoredUniform<glm::vec4>* mycolor =
                new StoredUniform<glm::vec4>(shader, "mycolor", goldish);
        material.push_back(mycolor);

        renderables.push_back(
                new LitRenderObject(shader, node, vao, material));

        // physics
        btCollisionShape* shape = new btBoxShape(from_vec3(scale/2.f));

        float mass = 0.f;
        btRigidBody* rigid_body = create_rigid_body(mass, node, shape);
        physics->add_rigid_body(rigid_body);

        // mem
        uniforms.push_back(mycolor);
        vaos.push_back(vao);
        collision_shapes.push_back(shape);
    }

    // bound
    {
        Shader* shader = shaders["light1"];

        Node* node = nodes["bound"] = new Node(scene);

        glm::vec3 scale = glm::vec3(20.f);
        bool face_inward = true;
        VAO* vao = create_cube_with_normals(scale, face_inward);

        std::vector<Uniform*> material;

        glm::vec4 greenblueish = glm::vec4(0.f,1.f,1.f,1.f);
        StoredUniform<glm::vec4>* mycolor =
            new StoredUniform<glm::vec4>(shader, "mycolor", greenblueish);
        material.push_back(mycolor);

        renderables.push_back(
                new LitRenderObject(shader, node, vao, material));

        // mem
        vaos.push_back(vao);
        uniforms.push_back(mycolor);
    }

    // roboarm
    {
        nodes["roboarm0"] = new Node(scene);
        nodes["roboarm1"] = new Node(scene);
        nodes["roboarm2"] = new Node(scene);
        nodes["roboarm3"] = new Node(scene);

        glm::vec3 scale = glm::vec3(0.1f, 0.4f, 0.1f);

        nodes["roboarm0"]->position = glm::vec3(0.f, 1.f, -2.f);
        //nodes["roboarm0"]->orientation =
        //        glm::angleAxis(glm::radians(180.f), glm::vec3(1.f, 0.f, 0.f));

        nodes["roboarm1"]->position = nodes["roboarm0"]->position +
            nodes["roboarm0"]->orientation * glm::vec3(0.f, scale.y, 0.f);
        nodes["roboarm1"]->orientation = nodes["roboarm0"]->orientation;

        nodes["roboarm2"]->position = nodes["roboarm1"]->position +
            nodes["roboarm1"]->orientation * glm::vec3(0.f, scale.y, 0.f);
        nodes["roboarm2"]->orientation = nodes["roboarm1"]->orientation;

        nodes["roboarm3"]->position = nodes["roboarm2"]->position +
            nodes["roboarm2"]->orientation * glm::vec3(0.f, scale.y, 0.f);
        nodes["roboarm3"]->orientation = nodes["roboarm2"]->orientation;

        // render
        {
            Shader* shader = shaders["light1"];

            glm::vec4 black = glm::vec4(0.f,0.f,0.f,1.f);
            StoredUniform<glm::vec4>* mycolor =
                    new StoredUniform<glm::vec4>(shader, "mycolor", black);

            std::vector<Uniform*> material;
            material.push_back(mycolor);

            // TODO use rounder shapes...
            VAO* vao = create_cube_with_normals(scale);

            auto make_renderable =
                [&shader, &material, &vao] (Node* node) {
                    return new LitRenderObject(shader, node, vao, material);
                };

            renderables.insert(renderables.end(),
                {
                    make_renderable(nodes["roboarm0"]),
                    make_renderable(nodes["roboarm1"]),
                    make_renderable(nodes["roboarm2"]),
                    make_renderable(nodes["roboarm3"]),
                }
            );

            // mem
            uniforms.push_back(mycolor);
            vaos.push_back(vao);
        }

        btCollisionShape *shape = new btBoxShape(from_vec3(scale/2.f));
        float density = 1000.f,
              volume = scale.x * scale.y * scale.z,
              mass = density * volume;

        // mem
        collision_shapes.push_back(shape);


        btRigidBody *rb0 = create_rigid_body(0.f, nodes["roboarm0"], shape),
                    *rb1 = create_rigid_body(mass, nodes["roboarm1"], shape),
                    *rb2 = create_rigid_body(mass, nodes["roboarm2"], shape),
                    *rb3 = create_rigid_body(mass, nodes["roboarm3"], shape);

        rb1->setActivationState(DISABLE_DEACTIVATION);
        rb2->setActivationState(DISABLE_DEACTIVATION);
        rb3->setActivationState(DISABLE_DEACTIVATION);

        physics->add_rigid_body(rb0);
        physics->add_rigid_body(rb1);
        physics->add_rigid_body(rb2);
        physics->add_rigid_body(rb3);

        btMatrix3x3 rot;
        rot.setIdentity();

        btTransform trans_up(rot, btVector3(0.f, scale.y/2, 0.f)),
                    trans_down(rot, btVector3(0.f, -scale.y/2, 0.f));

        rc1 = new btHingeConstraint(*rb0, *rb1,
                                    trans_up, trans_down);

        rc2 = new btHingeConstraint(*rb1, *rb2,
                                    trans_up, trans_down);

        rc3 = new btHingeConstraint(*rb2, *rb3,
                                    trans_up, trans_down);

        float pi = glm::pi<float>();

        rc1->setLimit(-pi/2, pi/2);
        rc2->setLimit(-pi/2, pi/2);
        rc3->setLimit(-pi/2, pi/2);

        bool intercollision = false;
        physics->add_constraint(rc1, intercollision);
        physics->add_constraint(rc2, intercollision);
        physics->add_constraint(rc3, intercollision);

        roboarm0 = new KinematicChain(nullptr, rb0, nullptr);
        roboarm1 = new KinematicChain(roboarm0, rb1, rc1);
        roboarm2 = new KinematicChain(roboarm1, rb2, rc2);
        roboarm3 = new KinematicChain(roboarm2, rb3, rc3);
    }
}
示例#18
0
// The start of the Application
int App::start(const std::vector<CL_String> &args)
{
	CL_DisplayWindowDescription win_desc;
	win_desc.set_allow_resize(true);
	win_desc.set_title("Vertex Buffer Object Example");
	win_desc.set_depth_size(16);

	win_desc.set_size(CL_Size( 800, 600 ), false);

	CL_DisplayWindow window(win_desc);
	CL_Slot slot_quit = window.sig_window_close().connect(this, &App::on_window_close);
	CL_Slot slot_input_up = (window.get_ic().get_keyboard()).sig_key_up().connect(this, &App::on_input_up);

	CL_GraphicContext gc = window.get_gc();

	Shader shader(gc);

	// Prepare the display
	gc.set_map_mode(cl_user_projection);

	CL_PolygonRasterizer polygon_rasterizer;
	polygon_rasterizer.set_culled(true);
	polygon_rasterizer.set_face_cull_mode(cl_cull_back);
	polygon_rasterizer.set_front_face(cl_face_side_clockwise);
	gc.set_polygon_rasterizer(polygon_rasterizer);

	CL_BufferControl buffer_control;
	buffer_control.enable_depth_test(true);
	buffer_control.set_depth_compare_function(cl_comparefunc_lequal);
	buffer_control.enable_depth_write(true);
	gc.set_buffer_control(buffer_control);

	std::vector<CL_Vec3f> object_positions;
	std::vector<CL_Vec3f> object_normals;
	std::vector<CL_Vec4f> object_material_ambient;

	const int num_cubes = 20000;
	object_positions.reserve(num_cubes * 6 * 6);	// 6 faces, and 6 vertices per face
	object_normals.reserve(num_cubes * 6 * 6);
	object_material_ambient.reserve(num_cubes * 6 * 6);

	for (int cnt=0; cnt < num_cubes; cnt++)
	{
		create_cube(object_positions, object_normals, object_material_ambient);
	}

	CL_VertexArrayBuffer vb_positions(gc, &object_positions[0], sizeof(CL_Vec3f) * object_positions.size());
	CL_VertexArrayBuffer vb_normals(gc, &object_normals[0], sizeof(CL_Vec3f) * object_normals.size());
	CL_VertexArrayBuffer vb_material_ambient(gc, &object_material_ambient[0], sizeof(CL_Vec4f) * object_material_ambient.size());

	// ** Note, at this point "object_positions, object_normals and object_material_ambient"
	// ** can be destroyed. But for the purpose of this example, is it kept

	CL_Font fps_font(gc, "tahoma", 20);

	FramerateCounter frameratecounter;
	unsigned int time_last = CL_System::get_time();

	float angle = 0.0f;
	is_vertex_buffer_on = true;

	while (!quit)
	{
		unsigned int time_now = CL_System::get_time();
		float time_diff = (float) (time_now - time_last);
		time_last = time_now;

		gc.clear(CL_Colorf(0.0f, 0.0f, 0.0f, 1.0f));
		gc.clear_depth(1.0f);

		gc.set_map_mode(cl_map_2d_upper_left);
		CL_String fps = cl_format("%1 fps", frameratecounter.get_framerate());
		fps_font.draw_text(gc, gc.get_width() - 100, 30, fps);
		CL_String info = cl_format("%1 vertices", (int) object_positions.size());
		fps_font.draw_text(gc, 30, 30, info);

		fps_font.draw_text(gc, 30, gc.get_height() - 8, "Press any key to toggle the Vertex Buffer option");

		if (is_vertex_buffer_on)
		{
			fps_font.draw_text(gc, 200, 30, "Vertex Buffer = ON");
		}
		else
		{
			fps_font.draw_text(gc, 200, 30, "Vertex Buffer = OFF");
		}

		gc.set_map_mode(cl_user_projection);
		CL_Mat4f perp = CL_Mat4f::perspective(45.0f, ((float) gc.get_width()) / ((float) gc.get_height()), 0.1f, 100000.0f);
		gc.set_projection(perp);

		angle += time_diff / 20.0f;
		if (angle >= 360.0f)
			angle -= 360.0f;

		gc.push_modelview();
		gc.set_modelview(CL_Mat4f::identity());
		gc.mult_scale(1.0f,1.0f, -1.0f);	// So +'ve Z goes into the screen
		gc.mult_translate(0.0f, 0.0f, 800.0f);
		gc.mult_rotate(CL_Angle(angle*2.0f, cl_degrees), 0.0f, 1.0f, 0.0f, false);
		gc.mult_rotate(CL_Angle(angle, cl_degrees), 1.0f, 0.0f, 0.0f, false);

		shader.Set(gc);
		shader.Use(gc);

		CL_PrimitivesArray prim_array(gc);

		if (is_vertex_buffer_on)
		{
			prim_array.set_attributes(0, vb_positions, 3, cl_type_float, (void *) 0);
			prim_array.set_attributes(1, vb_normals, 3, cl_type_float, (void *) 0);
			prim_array.set_attributes(2, vb_material_ambient, 4, cl_type_float, (void *) 0);
		}
		else
		{
			prim_array.set_attributes(0, &object_positions[0]);
			prim_array.set_attributes(1, &object_normals[0]);
			prim_array.set_attributes(2, &object_material_ambient[0]);
		}
		gc.draw_primitives(cl_triangles, object_positions.size(), prim_array);

		gc.pop_modelview();

		gc.reset_program_object();

		window.flip(0);
		frameratecounter.frame_shown();

		CL_KeepAlive::process();
	}

	return 0;
}
示例#19
0
文件: ccdsharp3.c 项目: jobovy/nemo
void nemo_main()
{
  stream  instr, outstr;
  int     nx, ny, nz, mode;
  int     i,j,k;
  imageptr iptr1=NULL, iptr2=NULL, optr;      /* pointer to images */
  real    d1, d2, d3, d4, d5, d6, dx, dy, dz;
  bool    Qsym = TRUE;            /* symmetric derivates w.r.t. pixel point */
  
  match(getparam("mode"),valid_modes,&mode);
  if (mode==0) error("Not a valid mode; valid:%s",valid_modes);
  dprintf(0,"Image sharpening method #%d\n",mode);
  
  instr = stropen(getparam("in"), "r");
  read_image( instr, &iptr1);
  nx = Nx(iptr1);	
  ny = Ny(iptr1);
  nz = Nz(iptr1);
  dx = Dx(iptr1);
  dy = Dy(iptr1);
  dz = Dz(iptr1);
  if (mode & MODE_DIV || mode & MODE_VORT) {
    if (read_image(instr,&iptr2) == 0)
      error("No second image found in %s\n",getparam("in"));
    if (nx != Nx(iptr2))  
      error("Second image doesn't match in NX: %d <> %d\n",Nx(iptr2),nx);
    if (ny != Ny(iptr2))  
      error("Second image doesn't match in NY: %d <> %d\n",Ny(iptr2),ny);
    if (nz != Nz(iptr2))  
      error("Second image doesn't match in NZ: %d <> %d\n",Nz(iptr2),nz);
  }
  
  outstr = stropen(getparam("out"), "w");
  create_cube(&optr,nx,ny,nz);
  Dx(optr) = Dx(iptr1);
  Dy(optr) = Dy(iptr1);
  Dz(optr) = Dz(iptr1);
  Xmin(optr) = Xmin(iptr1);
  Ymin(optr) = Ymin(iptr1);
  Zmin(optr) = Zmin(iptr1);
  
  if (mode & MODE_LAPLACE) {
    for (k=1; k<nz-1; k++) {
      for (j=1; j<ny-1; j++) {
	for (i=1; i<nx-1; i++) {
	  d1 = CV1(i,j,k) - CV1(i-1,j,k);
	  d2 = CV1(i,j,k) - CV1(i+1,j,k);
	  d3 = CV1(i,j,k) - CV1(i,j-1,k);
	  d4 = CV1(i,j,k) - CV1(i,j+1,k);
	  d5 = CV1(i,j,k) - CV1(i,j,k-1);
	  d6 = CV1(i,j,k) - CV1(i,j,k+1);
	  CVO(i,j,k) = sqrt(d1*d1+d2*d2+d3*d3+d4*d4+d5*d5+d6*d6);
	}
	CVO(0,j,k)    = 0.0;
	CVO(nx-1,j,k) = 0.0;
      }
      for (i=0; i<nx; i++)
	CVO(i,0,k)    = CVO(i,ny-1,k) = 0.0;
    }
    for(j=0; j<ny; j++)
      for(i=0; i<nx; i++)
	CVO(i,j,0)    = CVO(i,j,nz-1) = 0.0;
  } else if (mode & MODE_DIV || mode & MODE_VORT) {
    warning("only 2D implemented");
    for (k=0; k<nz; k++) {
      for (j=0; j<ny-1; j++) {
	for (i=0; i<nx-1; i++) {
	  if (Qsym) {
	    if (i>0 && j>0) {
	      d1 = 0.5*(CV1(i+1,j,k) - CV1(i-1,j,k));         /* dv_x/dx */
	      d2 = 0.5*(CV1(i,j+1,k) - CV1(i,j-1,k));         /* dv_x/dy */
	      d3 = 0.5*(CV2(i+1,j,k) - CV2(i-1,j,k));         /* dv_y/dx */
	      d4 = 0.5*(CV2(i,j+1,k) - CV2(i,j-1,k));         /* dv_y/dy */
	    } else
	      d1 = d2 = d3 = d4 = 0.0;
	  } else {
	    d1 = CV1(i+1,j,k) - CV1(i,j,k);         /* dv_x/dx */
	    d2 = CV1(i,j+1,k) - CV1(i,j,k);         /* dv_x/dy */
	    d3 = CV2(i+1,j,k) - CV2(i,j,k);         /* dv_y/dx */
	    d4 = CV2(i,j+1,k) - CV2(i,j,k);         /* dv_y/dy */
	  }
	  if (mode&MODE_DIV)
	    CVO(i,j,k) = d1/dx + d4/dy;
	  else if (mode&MODE_VORT)
	    CVO(i,j,k) = d3/dx - d2/dy;
	}
	CVO(nx-1,j,k) = 0.0;
      }
      for (i=0; i<nx; i++) {
	CVO(i,ny-1,k) = 0.0;
      }
    }
  } else if (mode & MODE_AREGAN || mode & MODE_PREGAN) {
    warning("only 2D implemented");
    for (k=0; k<nz; k++) {
      for (j=0; j<ny-1; j++) {
	for (i=0; i<nx-1; i++) {
	  d1 = CV1(i,j,k)   - CV1(i+1,j,k);
	  d2 = CV1(i,j+1,k) - CV1(i+1,j+1,k);
	  d3 = CV1(i,j,k)   - CV1(i,j+1,k);
	  d4 = CV1(i+1,j,k) - CV1(i+1,j+1,k);
	  if (mode&MODE_AREGAN)
	    CVO(i,j,k) = sqrt(sqr(d1+d2)+sqr(d3+d4))/2;
	  else {
	    if (d3+d4==0.0 && d1+d2==0.0)
	      CVO(i,j,k) = 0.0;
	    else
	      CVO(i,j,k) = atan2(d3+d4,d1+d2) * 180 / PI;
	  }
	}
	CVO(nx-1,j,k) = 0.0;
      }
      for (i=0; i<nx; i++) {
	CVO(i,ny-1,k) = 0.0;
      }
    }
  }
  write_image(outstr, optr);
}
示例#20
0
bool create_cube(NodeInstance& node, const Context& context, uint32_t flags)
{
    add_part(node.mesh);
    return create_cube(node.mesh, context, flags);
}
示例#21
0
void nemo_main()
{
    stream  instr, outstr;
    int     nx, ny, nz;        /* size of scratch map */
    int     nx1, ny1, nz1, nz2;
    int     ni, i, ix, iy, iz, iz1;
    real    dmin, dmax;
    imageptr iptr[MAXIM], optr;        /* pointer to image */
    string  flipmode;

    instr = stropen(getparam("in"), "r");
    outstr = stropen(getparam("out"), "w");

    for (i=0; i<MAXIM; i++) {               /* loop over all to gather data */
      iptr[i] = 0;
      if (read_image( instr, &iptr[i]) == 0) break;
      nx1 = Nx(iptr[i]);	
      ny1 = Ny(iptr[i]);
      nz1 = Nz(iptr[i]);
      dprintf(1,"Image %d: %d x %d x %d\n",i,nx1,ny1,nz1);
      if (i==0) {
	nx = nx1;
	ny = ny1;
	nz = nz1;
	dmin = MapMin(iptr[i]);
	dmax = MapMax(iptr[i]);
      } else {
	if (nx != nx1) error("size nx: %d != %d",nx,nx1);
	if (ny != ny1) error("size ny: %d != %d",ny,ny1);
	nz += nz1;
	dmin = MIN(dmin,MapMin(iptr[i]));
	dmax = MAX(dmax,MapMax(iptr[i]));
      }
    }
    ni = i;
    dprintf(0,"Final cube: %d x %d x %d\n",nx,ny,nz);
    dprintf(0,"Data min/max: %g %g\n",dmin,dmax);
    create_cube(&optr,nx,ny,nz);
    MapMin(optr) = dmin;
    MapMax(optr) = dmax;
    Xmin(optr) = Xmin(iptr[0]);
    Ymin(optr) = Ymin(iptr[0]);
    Zmin(optr) = Zmin(iptr[0]);
    Xref(optr) = Xref(iptr[0]);
    Yref(optr) = Yref(iptr[0]);
    Zref(optr) = Zref(iptr[0]);
    Dx(optr) = Dx(iptr[0]);
    Dy(optr) = Dy(iptr[0]);
    Dz(optr) = Dz(iptr[0]);

    for (i=0, iz=0; i<ni; i++) {       /* grab all data in output cube */
      nz1 = Nz(iptr[i]);
      for (iz1=0; iz1< nz1; iz1++, iz++) {
	for (iy=0; iy<ny; iy++) {
	  for (ix=0; ix<nx; ix++) {
	    CubeValue(optr,ix,iy,iz) = CubeValue(iptr[i],ix,iy,iz1);
	  }
	}
      }
    }

    write_image(outstr, optr);
}
示例#22
0
game::game(const float3& position) :
physics_player(position),
action_handler_fct(this, &game::action_handler),
gui_callback(this, &game::draw_interface),
rendering_scene_callback(this, &game::draw_active_cube_hud) {
	old_tick = tick_push = SDL_GetTicks();
	tick_diff = 0;
	death_tex = t->add_texture(e->data_path("death_screen.png"), TEXTURE_FILTERING::LINEAR, 0, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);

	// fetch vis variables in order to speed up rendering process
	nvis_grab_color = conf::get<float4>("nvis_grab_color");
	nvis_push_color = conf::get<float4>("nvis_push_color");
	nvis_swap_color = conf::get<float4>("nvis_swap_color");
	nvis_bg_selected = conf::get<float4>("nvis_bg_selected");
	nvis_bg_selecting = conf::get<float4>("nvis_bg_selecting");
	nvis_line_interval = conf::get<float2>("nvis_line_interval");
	nvis_tex_interpolation = conf::get<float>("nvis_tex_interpolation");
	nvis_time_denominator = conf::get<float>("nvis_time_denominator");

	glGenBuffers(1, &laser_beam_vbo);

	// layout:
	//    0
	//
	// 1 ---- 2
	// 
	//   ...
	// 
	//    3

	const unsigned char laser_beam_indices[12] {
		0,1,3,
		0,2,3,
		1,2,3,
		0,1,2
	};
	glGenBuffers(1, &laser_beam_indices_vbo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, laser_beam_indices_vbo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 12 * sizeof(unsigned char), &laser_beam_indices[0], GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	eevt->add_internal_event_handler(action_handler_fct,
									 EVENT_TYPE::KEY_DOWN,
									 EVENT_TYPE::KEY_UP,
									 EVENT_TYPE::MOUSE_LEFT_DOWN,
									 EVENT_TYPE::MOUSE_LEFT_UP,
									 EVENT_TYPE::MOUSE_RIGHT_DOWN,
									 EVENT_TYPE::MOUSE_RIGHT_UP,
									 EVENT_TYPE::MOUSE_MIDDLE_DOWN,
									 EVENT_TYPE::MOUSE_MIDDLE_UP);

	create_cube(cube_vbo[CUBE_VBO_INDEX_VERT], cube_vbo[CUBE_VBO_INDEX_INDEX]);
	create_cube_tex_n_bn_tn(cube_vbo[CUBE_VBO_INDEX_TEX], cube_vbo[CUBE_VBO_INDEX_NORMAL],
							cube_vbo[CUBE_VBO_INDEX_BINORMAL], cube_vbo[CUBE_VBO_INDEX_TANGENT]);

	// load permutation data into tex_permutation and enforce NEAREST filtering to avoid interpolated values
	glGenTextures(1, &tex_permutation);
	glBindTexture(GL_TEXTURE_2D, tex_permutation);
	char4* permutation_data = new char4[permutation_tex_size * permutation_tex_size];
	for(size_t i = 0; i < permutation_tex_size; ++i) {
		for(size_t j = 0; j < permutation_tex_size; ++j) {
			char4* entry = permutation_data + (i * permutation_tex_size + j);
			unsigned char value = perm[(j + perm[i]) & permutation_tex_size];
			*reinterpret_cast<char3*>(entry) = (grad3[value & 16] * permutation_tex_size_fourth +
												char3(permutation_tex_size_fourth,
													  permutation_tex_size_fourth,
													  permutation_tex_size_fourth));
			entry->w = value;
		}
	}
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, permutation_tex_size, permutation_tex_size, 0, GL_RGBA, GL_UNSIGNED_BYTE, permutation_data);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	delete [] permutation_data;

	// load gradient data into tex_gradient and enforce NEAREST filtering to avoid interpolated values
	glGenTextures(1, &tex_gradient);
	glBindTexture(GL_TEXTURE_2D, tex_gradient);
	permutation_data = new char4[permutation_tex_size * permutation_tex_size];
	for(size_t i = 0; i < permutation_tex_size; ++i) {
		for(size_t j = 0; j < permutation_tex_size; ++j) {
			char4* entry = permutation_data + (i * permutation_tex_size + j);
			unsigned char value = perm[(j + perm[i]) & permutation_tex_size];
			*entry = grad4[value & 16] * permutation_tex_size_fourth + char4(permutation_tex_size_fourth,
																			 permutation_tex_size_fourth,
																			 permutation_tex_size_fourth,
																			 permutation_tex_size_fourth);
		}
	}
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, permutation_tex_size, permutation_tex_size, 0, GL_RGBA, GL_UNSIGNED_BYTE, permutation_data);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	delete [] permutation_data;
}
示例#23
0
文件: ctmodel.cpp 项目: jdevin/ctools
/***********************************************************************//**
 * @brief Get application parameters
 *
 * Get all task parameters from parameter file or (if required) by querying
 * the user. The parameters are read in the correct order.
 ***************************************************************************/
void ctmodel::get_parameters(void)
{
    // Reset cube append flag
    m_append_cube = false;

    // If there are no observations in container then load them via user
    // parameters.
    if (m_obs.size() == 0) {
        get_obs();
    }

    // If we have now excactly one CTA observation (but no cube has yet been
    // appended to the observation) then check whether this observation
    // is a binned observation, and if yes, extract the counts cube for
    // model generation
    if ((m_obs.size() == 1) && (m_append_cube == false)) {

        // Get CTA observation
        GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[0]);

        // Continue only if observation is a CTA observation
        if (obs != NULL) {

            // Check for binned observation
            if (obs->eventtype() == "CountsCube") {

                // Set cube from binned observation
                GCTAEventCube* evtcube = dynamic_cast<GCTAEventCube*>(const_cast<GEvents*>(obs->events()));

                cube(*evtcube);

                // Signal that cube has been set
                m_has_cube = true;

                // Signal that we are in binned mode
                m_binned = true;

            } // endif: observation was binned

        } // endif: observation was CTA

    } // endif: had exactly one observation

    // Read model definition file if required
    if (m_obs.models().size() == 0) {

        // Get model filename
        std::string inmodel = (*this)["inmodel"].filename();

        // Load models from file
        m_obs.models(inmodel);

    } // endif: there were no models

    // Get energy dispersion flag parameters
    m_apply_edisp = (*this)["edisp"].boolean();

    // If we do not have yet a counts cube for model computation then check
    // whether we should read it from the "incube" parameter or whether we
    // should create it from scratch using the task parameters
    if (!m_has_cube) {

        // Read cube definition file
        std::string incube = (*this)["incube"].filename();

        // If no cube file has been specified then create a cube from
        // the task parameters ...
        if ((incube == "NONE") ||
            (gammalib::strip_whitespace(incube) == "")) {
            
            // Create cube from scratch
            m_cube = create_cube(m_obs);

        }

        // ... otherwise load the cube from file and reset all bins
        // to zero
        else {

            // Load cube from given file
            m_cube.load(incube);

            // Set all cube bins to zero
            for (int i = 0; i < m_cube.size(); ++i) {
                m_cube[i]->counts(0.0);
            }
        }

        // Signal that cube has been set
        m_has_cube = true;

    } // endif: we had no cube yet

    // Read optionally output cube filenames
    if (read_ahead()) {
        m_outcube = (*this)["outcube"].filename();
    }

    // If cube should be appended to first observation then do that now.
    // This is a kluge that makes sure that the cube is passed as part
    // of the observation in case that a cube response is used. The kluge
    // is needed because the GCTACubeSourceDiffuse::set method needs to
    // get the full event cube from the observation. It is also at this
    // step that the GTI, which may just be a dummy GTI when create_cube()
    // has been used, will be set.
    if (m_append_cube) {

        //TODO: Check that energy boundaries are compatible

        // Attach GTI of observations to model cube
        m_cube.gti(m_obs[0]->events()->gti());
    
        // Attach model cube to observations
        m_obs[0]->events(m_cube);

    } // endif: cube was scheduled for appending

    // Return
    return;
}
示例#24
0
文件: ccdmedian.c 项目: jobovy/nemo
void nemo_main()
{
    stream  instr, outstr;
    int     nx, ny, nz;
    int     nstep,nstep1;
    int     i,j,k, n, n1, i1, j1, m;
    int     ix[2], iy[2];
    imageptr iptr=NULL, optr;      /* pointer to images */
    real    *vals, fraction;
    string  mode = getparam("mode");
    bool Qmedian = (*mode == 'm');
    bool Qmean = (*mode == 'a');

    nstep = getiparam("nstep");
    if (nstep%2 != 1) error("step size %d needs to be odd",nstep);
    nstep1 = (nstep-1)/2;

    n = getiparam("n");
    if (Qmedian)
      dprintf(1,"Median filter size %d\n",n);
    else if (Qmean) 
      dprintf(1,"Mean filter size %d\n",n);
    else
      dprintf(1,"Subtraction filter size %d\n",n);
    if (n%2 != 1) error("filter size %d needs to be odd",n);
    n1 = (n-1)/2;
    vals = (real *) allocate (sizeof(real) * (n*n + 1));

    instr = stropen(getparam("in"), "r");
    read_image( instr, &iptr);
    nx = Nx(iptr);	
    ny = Ny(iptr);
    nz = Nz(iptr);
    if (nz > 1) error("Cannot do 3D cubes properly; use 2D");

    if (hasvalue("x") && hasvalue("y")) {
      get_range("x",ix);
      get_range("y",iy);
    } else {
      ix[0] = 0;
      ix[1] = nx-1;
      iy[0] = 0;
      iy[1] = ny-1;
    }
    dprintf(1,"Xrange: %d - %d   Yrange: %d - %d\n",ix[0],ix[1],iy[0],iy[1]);
      
    outstr = stropen(getparam("out"), "w");
    create_cube(&optr,nx,ny,nz);
    Dx(optr) = Dx(iptr);
    Dy(optr) = Dy(iptr);
    Dz(optr) = Dz(iptr);
    Xmin(optr) = Xmin(iptr);
    Ymin(optr) = Ymin(iptr);
    Zmin(optr) = Zmin(iptr);

    if (nstep > 1) {
      warning("Cheat mode nstep=%d",nstep);

      for (j=nstep1; j<ny-nstep1; j+=nstep) {
	for (i=nstep1; i<nx-nstep1; i+=nstep) {
	  if (j<n1 || j >= ny-n1 || j < iy[0] || j > iy[1]) {
	    CVO(i,j) = CVI(i,j);
	    continue;
	  }
	  if (i<n1 || i >= nx-n1 || i < ix[0] || i > ix[1]) {
	    CVO(i,j) = CVI(i,j);
	    continue;
	  }
	  m = 0;
	  for (j1=j-n1; j1<=j+n1; j1++)
	    for (i1=i-n1; i1<=i+n1; i1++)
	      vals[m++] = CVI(i1,j1);
	  CVO(i,j) = median(m,vals,fraction);
	  for (j1=j-nstep1; j1<=j+nstep1; j1++)
	    for (i1=i-nstep1; i1<=i+nstep1; i1++)
	      CVO(i1,j1) = CVO(i,j);
	}
      }
    } else {

      for (j=0; j<ny; j++) {
	for (i=0; i<nx; i++) {
	  if (j<n1 || j >= ny-n1 || j < iy[0] || j > iy[1]) {
	    CVO(i,j) = CVI(i,j);
	    continue;
	  }
	  if (i<n1 || i >= nx-n1 || i < ix[0] || i > ix[1]) {
	    CVO(i,j) = CVI(i,j);
	    continue;
	  }
	  m = 0;
	  for (j1=j-n1; j1<=j+n1; j1++)
	    for (i1=i-n1; i1<=i+n1; i1++)
	      vals[m++] = CVI(i1,j1);

	  if (Qmedian)
	    CVO(i,j) = median(m,vals,fraction);
	  else if (Qmean)
	    CVO(i,j) = mean(m,vals,fraction);
	  else
	    CVO(i,j) = subtract(m,vals,fraction);
	}
      }

    }
    write_image(outstr, optr);
}
示例#25
0
void nemo_main()
{
    stream instr, outstr;
    real   tsnap, dr, aux, t0, dt;
    string times;
    Body *btab = NULL, *bp, *bq;
    int i, j, k, n, nbody, bits, nopt, ParticlesBit, ntime;
    char fmt[20],*pfmt;
    string *burststring(), *opt;
    rproc btrtrans(), fopt[MAXOPT];
    imageptr iptr = NULL; 
    bool Qfirst = getbparam("first");

    ParticlesBit = (MassBit | PhaseSpaceBit | PotentialBit | AccelerationBit |
            AuxBit | KeyBit | DensBit | EpsBit);
    instr = stropen(getparam("in"), "r");	
    outstr = stropen(getparam("out"), "w");

    opt = burststring(getparam("options"),", ");
    nopt = 0;					/* count options */
    while (opt[nopt]) {				/* scan through options */
        fopt[nopt] = btrtrans(opt[nopt]);
        nopt++;
        if (nopt==MAXOPT) {
            dprintf(0,"\n\nMaximum number of options = %d exhausted\n",MAXOPT);
            break;
        }
    }
    times = getparam("times");
    ntime = (hasvalue("ntime") ? getiparam("ntime") : 1);
    
    for(;;) {                /* repeating until first or all times are read */
	get_history(instr);
        if (!get_tag_ok(instr, SnapShotTag))
            break;                                  /* done with work */
        get_snap(instr, &btab, &nbody, &tsnap, &bits);
        if (!streq(times,"all") && !within(tsnap,times,0.0001))
            continue;                   /* skip work on this snapshot */
        if ( (bits & ParticlesBit) == 0)
            continue;                   /* skip work, only diagnostics here */
	dprintf(1,"Time=%g\n",tsnap);
	if (iptr == NULL) {
	  create_cube(&iptr,nbody,nopt,ntime);
	  k=0;
	  t0 = tsnap;
	  if (k==0) dt = 0.0;
	} 
	if (k==1) dt=tsnap-t0;    /* should be good for the whole snapshot */
	for (j=0; j<nopt; j++) {
	  for (bp = btab, i=0; bp < btab+nbody; bp++, i++) {
	    CubeValue(iptr,i,j,k) = fopt[j](bp,tsnap,i);
	  }
	}
	k++;

	if (k==ntime)  { /* cube is full */
	  fixheader(iptr,getparam("options"),t0,dt);
	  write_image(outstr,iptr);
	  free_image(iptr);
	  iptr = NULL;
	  k = 0;
	  if (Qfirst) break;
	}
    }
    if (!Qfirst && k) {
      warning("k=%d something not written yet, possible trailing garbage written",k);
      fixheader(iptr,getparam("options"),t0,dt);
      write_image(outstr,iptr);
    }
    strclose(instr);
    strclose(outstr);
}