Пример #1
0
void
openplt(long n0, long n1, int sq0off, int sq1off, 
	char *xtitle, char *ytitle)
{
  char *sptr;
  time_t tt;
  int tick = 6;

  tt = time(NULL);

  if (strlen(lvstr)>0) {
    sscanf(lvstr,"%lg %lg %lg",&elinval[0],&elinval[1],&elinval[2]);
  }
  else if ((sptr=getenv("LINEVAL"))!=NULL && strlen(sptr)>0) {
    sscanf(sptr,"%lg %lg %lg",&elinval[0],&elinval[1],&elinval[2]);
  }
	
  printf("<?xml version=\"1.0\" standalone=\"no\"?>\n");
  printf("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n");
  printf("\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n\n");

  printf("<svg width=\"564\" height=\"612\" version=\"1.1\"\n");
  printf("xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n\n");

  pmaxx = n0;
  pmaxy = n1;

  fxscal = (double)(max_x-1)/(double)(n1);
  fyscal = (double)(max_y-1)/(double)(n0);

  if (fxscal > fyscal) fxscal = fyscal;
  else fyscal = fxscal;

  if (fyscal * n0 < (double)max_y/5.0) 
    fyscal = (double)(max_y-1)/((double)(n0)*5.0);

  fxscal *= 0.9; fxoff = (double)(max_x-1)/11.0;
  fyscal *= 0.9; fyoff = (double)(max_y-1)/11.0;

  /*   printf("currentlinewidth 1.5 mul setlinewidth\n"); */

  printf("<rect x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\"\n",
	 SX(0),SY(n1+1), SX(n0+1)-SX(0), SY(0) - SY(n1+1));
  printf("stroke=\"black\" stroke-width=\"2.0\" fill=\"none\" />\n");

  xaxis(n0,sq1off, xtitle);
  yaxis(n1,sq0off, ytitle);
  legend();
}
Пример #2
0
void nemo_main()
{
    stream istr;
    char msg[128];
    int  i, ndim;
    string *fn;
    
    setparams();
    compfuncs();	/* btrrtans snapplot-like interface */

    plinit("***", 0.0, 20.0, 0.0, 20.0);

    xaxis( 2.0,  2.0, 16.0, xrange, -7, xtrans, xlabel);
    xaxis( 2.0, 18.0, 16.0, xrange, -7, xtrans, NULL);
    yaxis( 2.0,  2.0, 16.0, yrange, -7, ytrans, ylabel);
    yaxis(18.0,  2.0, 16.0, yrange, -7, ytrans, NULL);
    sprintf(msg, "File: %s", input);
    pltext(msg, 2.0, 18.4, 0.32, 0.0);

    optr = NULL;
    ndim = NDIM;
    allocate_orbit(&optr,ndim,maxsteps);    /* allocate a large orbit */

    fn = burststring(input," ,");
    for (i=0; fn[i]; i++) {             /* loop over all files */
        istr = stropen(fn[i], "r");             /* open orbit file */
        while (read_orbit(istr,&optr)) {         /* while an orbit found....*/
            dprintf(0,"Read orbit with %d phase-points\n",Nsteps(optr));
            plot_path(optr,trange[0],trange[1],nplot);
            Nsteps(optr) = maxsteps;             /* reset for next orbit */
        }
        strclose(istr);
    }

    plstop();
}
Пример #3
0
AM2DProcessVariableDataSource::AM2DProcessVariableDataSource(const AMProcessVariable *data, const QString &name, int rowLength, QObject *parent)
	: QObject(parent), AMDataSource(name)
{
	data_ = data;
	sx_ = 1;
	sy_ = 1;
	length_ = rowLength;
	connect(data_, SIGNAL(valueChanged()), this, SLOT(onDataChanged()));
	connect(data_, SIGNAL(hasValuesChanged(bool)), this, SLOT(onStateChanged()));

	AMAxisInfo xaxis("xAxis", length_, "Image X-axis");
	xaxis.isUniform = true;
	xaxis.increment = sx_;
	AMAxisInfo yaxis("yAxis", data_->count()/length_, "Image Y-axis");
	yaxis.isUniform = true;
	yaxis.increment = sy_;
	axes_ << xaxis << yaxis;
}
Пример #4
0
  void MesherFixedEvenStem::getCap(otVertices* vertices, bool end)
  {
    float spline_pos = float((end?curveRes:0))/(curveRes);
    pos = stem->getPosSpline()->getPoint(spline_pos);
    z = stem->getPosSpline()->getTangent(spline_pos);
    
    if (!end && stem->parent)
    {
      pos = stem->parent->getPosSpline()->getPoint(stem->offset);
    }

    otMatrix t;
    otVector3 xaxis(z & otVector3(0,0,1));
    t.lrotateRad(asin(xaxis.length()),xaxis);

    float radius = stem->getRadSpline()->getPoint(spline_pos);

    MesherCyl cylmesh;
    cylmesh.getCap(vertices, end, circleRes, pos, t, radius);
  }
Пример #5
0
int MyCRCLServer::HandleMoveToType(MoveToType *cmd)
{
  double x, y, z;
  double xi, xj, xk;
  double zi, zj, zk;
  double r, p, w;

  x = cmd->EndPosition->Point->X->val;
  y = cmd->EndPosition->Point->Y->val;
  z = cmd->EndPosition->Point->Z->val;

  xi = cmd->EndPosition->XAxis->I->val;
  xj = cmd->EndPosition->XAxis->J->val;
  xk = cmd->EndPosition->XAxis->K->val;
  tf::Vector3 xaxis(xi, xj, xk);
  zi = cmd->EndPosition->ZAxis->I->val;
  zj = cmd->EndPosition->ZAxis->J->val;
  zk = cmd->EndPosition->ZAxis->K->val;
  tf::Vector3 zaxis(zi, zj, zk);
  tf::Vector3 yaxis = zaxis.cross(xaxis);
  tf::Matrix3x3 m(xi, yaxis.getX(), zi,
		  xj, yaxis.getY(), zj,
		  xk, yaxis.getZ(), zk);
  m.getRPY(r, p, w);

  status.setXYZ(x, y, z);
  status.setVec(xi, xj, xk, zi, zj, zk);
  status.setJointPosition(1, x);
  status.setJointPosition(2, y);
  status.setJointPosition(3, z);
  status.setJointPosition(4, r);
  status.setJointPosition(5, p);
  status.setJointPosition(6, w);

  printf("MoveToType(%d) %f %f %f / %f %f %f\n",
	 cmd->CommandID->val,
	 x, y, z, r, p, w);

  return 0;
}
Пример #6
0
void rgl_bbox(int* successptr,
              int* idata,
              double* ddata,
              double* xat, char** xtext,
              double* yat, char** ytext,
              double* zat, char** ztext)
{
  int success = RGL_FAIL;

  Device* device;

  if (deviceManager && (device = deviceManager->getAnyDevice())) {

    int   xticks     =        idata[0];
    int   yticks     =        idata[1];
    int   zticks     =        idata[2];
    int   xlen       =        idata[3];
    int   ylen       =        idata[4];
    int   zlen       =        idata[5];
    int   marklen_rel =       idata[6];

    float xunit      = (float) ddata[0];
    float yunit      = (float) ddata[1];
    float zunit      = (float) ddata[2];
    float marklen    = (float) ddata[3];
    float expand     = (float) ddata[4];    


    AxisInfo xaxis(xticks, xat, xtext, xlen, xunit);
    AxisInfo yaxis(yticks, yat, ytext, ylen, yunit);
    AxisInfo zaxis(zticks, zat, ztext, zlen, zunit);

    success = as_success( device->add( new BBoxDeco(currentMaterial, xaxis, yaxis, zaxis, marklen, (bool) marklen_rel, expand ) ) );
  }
  CHECKGLERROR;

  *successptr = success;
}
Пример #7
0
void osgParticleHPS::ParticleTrail::renderDebug( float scale ) const
{
    osg::Matrix rotMtx;
    osg::Vec3 ptA, ptB;
    osg::Vec3 xaxis( 1., 0., 0. );
    osg::Vec3 yaxis( 0., 1., 0. );
    osg::Vec3 zaxis( 0., 0., 1. );

    glBegin( GL_LINES );
    int i;
    int numPoints = positions_.size();
    for( i = 0; i < numPoints; i++ )
    {
        const HPSTrailPoint &point = positions_[i];
        float sTexCoord = (float)i / (float)numPoints;
        rotMtx.makeRotate(
            point.rpy[0], yaxis,
            point.rpy[1], xaxis,
            point.rpy[2], zaxis
        );

        ptA = osg::Vec3(scale, 0., 0.) * rotMtx;
        ptA += point.pos;

        glVertex3fv( point.pos.ptr() );
        glVertex3fv( ptA.ptr() );

        ptA = osg::Vec3(0., 0., scale) * rotMtx;
        ptA += point.pos;

        glVertex3fv( point.pos.ptr() );
        glVertex3fv( ptA.ptr() );
    }
    glEnd();

}
Пример #8
0
int main(){
	LHDlib::RhoTable rhoTable;

	
//		rhoTable.read("C:\\Users\\KeisukeFujii\\Dropbox\\visual_studio\\LHDdata\\flx\\lhd-r375q100b000a8020.flx");
	rhoTable.read("C:\\Users\\KeisukeFujii\\Dropbox\\visual_studio\\LHDdata\\flx\\lhd-r390q100g120b000a8020.flx");

	size_t size = 100;
	std::vector<double> R_10(size), Z_10(size);
	std::vector<double> R_11(size), Z_11(size);
	std::vector<double> R_12(size), Z_12(size);
	for (size_t i = 0; i < size; ++i){
		double theta = 2.0*myconst::pi / size*i;
		rhoTable.getRZfromRhoThetaPhi(1.0, theta, myconst::pi/10.0, R_10[i], Z_10[i]);
		rhoTable.getRZfromRhoThetaPhi(1.1, theta, myconst::pi/10.0, R_11[i], Z_11[i]);
		rhoTable.getRZfromRhoThetaPhi(1.2, theta, myconst::pi/10.0, R_12[i], Z_12[i]);
	}
	IGORdata::write_itx(R_10, Z_10, "RZ_10.itx", "RR_10", "ZZ_10");
	IGORdata::write_itx(R_11, Z_11, "RZ_11.itx", "RR_11", "ZZ_11");
	IGORdata::write_itx(R_12, Z_12, "RZ_12.itx", "RR_12", "ZZ_12");

	size = 48;
	std::vector<double> rho(size), Vp(size), dVpdrho(size), dVdrho(size);
	for (size_t i = 0; i < size; ++i){
		rho[i] = 1.2 / size*i;
		Vp[i] = rhoTable.get_Vp(0.0, rho[i]);
		dVpdrho[i] = rhoTable.get_dVpdrho(rho[i]);
		dVdrho[i] = rhoTable.get_dVdrho(rho[i]);
	}

	IGORdata::write_itx(rho, Vp, "rho_Vp.itx", "rho", "Vp");
	IGORdata::write_itx(dVpdrho, dVdrho, "dVdrho.itx", "dVpdrho", "dVdrho");

	size_t xsize = 100, ysize(101);
	std::vector<double> xaxis(xsize), yaxis(ysize);
	std::vector<std::vector<double>> rhoM(xsize), theta(xsize), drhodx(xsize), drhody(xsize), drhodz(xsize);
	for (size_t i = 0; i < xsize; ++i)
		xaxis[i] = 2.5 + 2.5 / xsize * i;
	for (size_t i = 0; i < ysize; ++i)
		yaxis[i] = -1.0 + 2.0 / ysize * i;

	for (size_t i = 0; i < xsize; ++i){
		for (size_t j = 0; j < ysize; ++j){
			double rho_, theta_;
			double drhodx_[3];
			rhoTable.get_rho_drho(xaxis[i], yaxis[j], myconst::pi*0.1, &rho_, &theta_, drhodx_);
			rhoM[i].push_back(rho_);
			theta[i].push_back(theta_);
			drhodx[i].push_back(drhodx_[0]);
			drhody[i].push_back(drhodx_[1]);
			drhodz[i].push_back(drhodx_[2]);
		}
	}
	IGORdata::write_edgeVector(xaxis, "xaxis.itx", "xaxis");
	IGORdata::write_edgeVector(yaxis, "yaxis.itx", "yaxis");
	IGORdata::write_itx(rhoM, "rhoMatrix.itx", "rhoMatrix");
	IGORdata::write_itx(theta, "theta.itx", "theta");
	IGORdata::write_itx(drhodx, "drhodx.itx", "drhodx");
	IGORdata::write_itx(drhody, "drhody.itx", "drhody");
	IGORdata::write_itx(drhodz, "drhodz.itx", "drhodz");
	return 0;
}
Пример #9
0
plot_map ()
{
    real m_range, brightness, dcm;
    real m_min, m_max;
    int    i, ix, iy;
    int    cnt;		/* counter of pixels */

    nsize = Nx(iptr);  /* old method forced square .. */			
    cell = Dx(iptr);   /* and forced so for gray scale due to LW mem-problems */
    size = nsize*cell;
    
    m_min = MapMin(iptr);	/* get min- and max from header */
    m_max = MapMax(iptr);
    dprintf (1,"Min and max in map from map-header are: %f %f\n",m_min,m_max);
 
    if (mmax==UNDEF)	/* reset default autoscales to user supplied if necessary */
	mmax=m_max;
    if (mmin==UNDEF)
    	mmin=m_min;
    m_range = mmax-mmin;
    if (m_range==0) {
    	mmax=mmin+1.0;
	if (gray) warning("%g; Plot-range was zero, mmax increased by 1",mmin);
    }
        
    dprintf (1,"User reset Min and max are: %f %f\n",mmin,mmax);

    
    sprintf (plabel,"File: %s",infile);			/* filename */
    sprintf (clabel,"Contours: %s",cntstr);             /* contour levels */
    sprintf (glabel,"Gray MinMax: %g %g",mmin,mmax);    /* grey scale minmax */
    sprintf (tlabel,"Time: %g",Time(iptr));             /* time of orig snapshot */

	/* set scales and labels along axes */
    if (xplot[0]==UNDEF || xplot[1]==UNDEF) {
    	xplot[0] = Xmin(iptr) - 0.5*Dx(iptr);
    	xplot[1] = xplot[0] + Nx(iptr)*Dx(iptr);
    }
    if (Namex(iptr))
        strncpy(xlabel,Namex(iptr),80);
    else
        strcpy (xlabel,"");

    if (yplot[0]==UNDEF || yplot[1]==UNDEF) {
    	yplot[0] = Ymin(iptr) - 0.5*Dy(iptr);
    	yplot[1] = yplot[0] + Ny(iptr)*Dy(iptr);
    }
    if (Namey(iptr))
        strncpy(ylabel,Namey(iptr),80);
    else
        strcpy (ylabel,"");
	
    dprintf (1,"Plotting area x=%f:%f y=%f:%f\n",
    	xplot[0], xplot[1], yplot[0], yplot[1]);

    if (gray) {		
				/* gray-scale */
       dcm = Dx(iptr) / (xplot[1]-xplot[0]) * 16.0;
       pl_matrix (Frame(iptr), nx, ny, 
		  xtrans(Xmin(iptr)), ytrans(Ymin(iptr)), dcm , mmin, mmax, power, blankval);
           /*  color_bar (100.0,500.0,32);  */
     } 
     		/* OLD ROUTINE, has to call relocate/frame ---> plcontour */
     plltype(lwidth,ltype);
     if (cmode==0) 
        contour (Frame(iptr),nx,ny,cntval,ncntval,
		Xmin(iptr), 
		Ymin(iptr), 
		Xmin(iptr)+(Nx(iptr)-1)*Dx(iptr),
		Ymin(iptr)+(Ny(iptr)-1)*Dy(iptr), lineto);
    
     else if (cmode==1)
         pl_contour (Frame(iptr),nx,ny,ncntval,cntval);
     plltype(1,1);

	/* draw axes and their labels */
    xaxis ( 2.0, 2.0, 16.0, xplot, -7, xtrans,  xlabel);
    xaxis ( 2.0,18.0, 16.0, xplot, -7, xtrans,  NULL);
    yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, ylabel);
    yaxis (18.0, 2.0, 16.0, yplot, -7, ytrans, NULL);

    pltext (plabel,2.0,18.4, 0.32, 0.0);	/* plot header with file name */
    pltext (clabel,2.0,19.0, 0.32, 0.0);        /* plot header with contour levels */
    pltext (glabel,2.0,19.6, 0.32, 0.0);        /* plot header with greyscale info */
    pltext (tlabel,10.0,19.6,0.32, 0.0);        /* time info */

    pljust(1);
    pltext (headline,10.0,18.4, 0.26, 0.0);     /* plot extra user suplied header */
    pljust(-1);
}
Пример #10
0
void osgParticleHPS::ParticleTrail::renderCrossRibbon() const
{
    osg::Matrix rotMtx;
    osg::Vec3 ptA, ptB;
    osg::Vec3 xaxis( 1., 0., 0. );
    osg::Vec3 yaxis( 0., 1., 0. );
    osg::Vec3 zaxis( 0., 0., 1. );
    int numPoints = positions_.size();

    float t = 0.;
    float tIncrement = 1. / maxNumPointsToRecord_;
    const osgParticleHPS::rangev4 &colorRange = getColorRange();
    const osgParticleHPS::Interpolator *colorInterp = getColorInterpolator();
    const osgParticleHPS::rangev3 &sizeRange = getSizeRange();
    const osgParticleHPS::Interpolator *sizeInterp = getSizeInterpolator();

    // This offset will give the ribbon texture a much smoother feel.
    // Without it, the texture would "pulse" and jump as the points at the
    // tail end of the ribbon are removed.
    float sTexCoordOffset = 1. / (float)numPoints;
    sTexCoordOffset *= (t0_ - timestampForLastNewPoint_) / timeBetweenPoints_;

    glBegin( GL_QUAD_STRIP );
    int i;
    for( i = 0; i < numPoints; i++ )
    {
        const HPSTrailPoint &point = positions_[i];
        osg::Vec4 interpColor = colorInterp->interpolate( t, colorRange );
        osg::Vec3 thisPosSize = sizeInterp->interpolate( t, sizeRange );
        t += tIncrement;
        float sTexCoord;

        if( stretchTexture )
        {
            sTexCoord = (float)i / (float)numPoints;
            if( i > 0 )
                sTexCoord += sTexCoordOffset;
        }
        else
        {
            if( totalHistoryPoints%2 )
                sTexCoord = (i%2) ? 0.0 : 1.0;
            else
                sTexCoord = (i%2) ? 1.0 : 0.0;
        }

        rotMtx.makeRotate(
            point.rpy[0], yaxis,
            point.rpy[1], xaxis,
            point.rpy[2], zaxis
        );
        ptA = osg::Vec3(thisPosSize.x(), 0., 0.) * rotMtx;
        ptB = ptA * -1.;
        ptA += point.pos;
        ptB += point.pos;

        glColor4f( interpColor[0], interpColor[1], interpColor[2], interpColor[3] );

        glTexCoord2f( sTexCoord, 1. );
        glVertex3fv( ptA.ptr() );

        glTexCoord2f( sTexCoord, 0. );
        glVertex3fv( ptB.ptr() );

    }
    glEnd();

    t = 0.0;

    glBegin( GL_QUAD_STRIP );
    for( i = 0; i < numPoints; i++ )
    {
        const HPSTrailPoint &point = positions_[i];
        osg::Vec4 interpColor = colorInterp->interpolate( t, colorRange );
        osg::Vec3 thisPosSize = sizeInterp->interpolate( t, sizeRange );
        t += tIncrement;
        float sTexCoord;

        if( stretchTexture )
        {
            sTexCoord = (float)i / (float)numPoints;
            if( i > 0 )
                sTexCoord += sTexCoordOffset;
        }
        else
        {
            if( totalHistoryPoints%2 )
                sTexCoord = (i%2) ? 0.0 : 1.0;
            else
                sTexCoord = (i%2) ? 1.0 : 0.0;
        }

        rotMtx.makeRotate(
            point.rpy[0], yaxis,
            point.rpy[1], xaxis,
            point.rpy[2], zaxis
        );
        ptA = osg::Vec3(0., 0., thisPosSize.z()) * rotMtx;
        ptB = ptA * -1.;
        ptA += point.pos;
        ptB += point.pos;

        glColor4f( interpColor[0], interpColor[1], interpColor[2], interpColor[3] );

        glTexCoord2f( sTexCoord, 1. );
        glVertex3fv( ptA.ptr() );

        glTexCoord2f( sTexCoord, 0. );
        glVertex3fv( ptB.ptr() );

    }

    glEnd();
}
Пример #11
0
void
openplt(long n0, long n1, int sq0off, int sq1off, 
	char *xtitle, char *ytitle)
{
  char *getenv(), *sptr;
  time_t tt;

  tt = time(NULL);

  if (strlen(lvstr)>0) {
    sscanf(lvstr,"%lg %lg %lg",&elinval[0],&elinval[1],&elinval[2]);
  }
  else if ((sptr=getenv("LINEVAL"))!=NULL && strlen(sptr)>0) {
    sscanf(sptr,"%lg %lg %lg",&elinval[0],&elinval[1],&elinval[2]);
  }
	
  printf("%%!PS-Adobe-2.0\n");
  printf("%%%%Creator: plalign\n");
  printf("%%%%CreationDate: %s",ctime(&tt));
  printf("%%%%DocumentFonts: Courier\n");
  printf("%%%%Pages: 1\n");
  printf("%%%%BoundingBox: 18 18 564 588\n");
  printf("%%%%EndComments\n");
  printf("%%%%EndProlog\n");
  printf("%%%%Page: 1 1\n");
  printf("/Courier findfont 14 scalefont setfont\n");
  printf("/vcprint { gsave 90 rotate dup stringwidth pop 2 div neg 0 rmoveto\n");
  printf("show newpath stroke grestore } def\n");
  printf("/hcprint { gsave dup stringwidth pop 2 div neg 0 rmoveto\n");
  printf("show newpath stroke grestore } def\n");
  printf("/hrprint { gsave dup stringwidth pop neg 0 rmoveto\n");
  printf("show newpath stroke grestore } def\n");
  printf("/hprint { gsave show newpath stroke grestore } def\n");

  pmaxx = n0;
  pmaxy = n1;

  fxscal = (double)(max_x-1)/(double)(n1);
  fyscal = (double)(max_y-1)/(double)(n0);

  if (fxscal > fyscal) fxscal = fyscal;
  else fyscal = fxscal;

  if (fyscal * n0 < (double)max_y/5.0) 
    fyscal = (double)(max_y-1)/((double)(n0)*5.0);

  fxscal *= 0.9; fxoff = (double)(max_x-1)/11.0;
  fyscal *= 0.9; fyoff = (double)(max_y-1)/11.0;

  printf("%% openplt - frame - %ld %ld\n", n0, n1);
  linetype(0);
  printf("gsave\n");
  printf("currentlinewidth 1.5 mul setlinewidth\n");
  newline();
  move(SX(0),SY(0));
  draw(SX(0),SY(n1+1));
  draw(SX(n0+1),SY(n1+1));
  draw(SX(n0+1),SY(0));
  draw(SX(0),SY(0));
  clsline(n0,n1,100000);
  printf("grestore\n");
  xaxis(n0,sq1off, xtitle);
  yaxis(n1,sq0off, ytitle);
  legend();
  printf("%% openplt done\n");
}
Пример #12
0
void nemo_main()
{
    int    i, dir, nrad, npots=0, ltype, ndim = NDIM, nx, ny, ns, ndat, nret;
    int    cols[4], n, idx, idx_max;
    real   pmax, symsize, rr, omk_max = 0.0, omk_rmax;
    real   rad[MAXPT], *vel, *vel1, *vel2, *vel3, *vel4, *curve;
    real   *ome, *kap, *opk, *omk, r0l[MAXPT+2], omega, *f;
    real   inrad[MAXPT], invel[MAXPT], inrade[MAXPT], invele[MAXPT];
    double pos[3], acc[3], pot, time = 0.0;
/*    char   *fmt, s[20], pfmt[256];    */
    char   headline[256], fmt1[80];
    string axis, mode, infile, plotlabel;
    stream instr;
    bool   Qtab, Qplot, Qome, Qvel, Qlv, Qin, QoILR;

    mode = getparam("mode");
    n = getiparam("n");
    plotlabel = getparam("headline");
    sprintf(fmt1,"%s ",getparam("format"));
    Qome = (*mode == 'o');      /*  options are: velocity|omega|lv */
    Qlv = (*mode == 'l');
    Qvel = (*mode == 'v');
    Qtab = getbparam("tab");
    Qplot = getbparam("plot");
    infile = getparam("in");
    Qin =  (*infile != 0);
    if (Qin) {
        nret = nemoinpi(getparam("cols"),cols,4);
        if (nret<0 || nret > 4) error("cols= requires 4 numbers");
        for (i=nret; i<4; i++)
            cols[i] = 0;
        instr = stropen(infile,"r");
        ndat = read_table(instr,MAXPT,inrad,invel,inrade,invele,cols);
        strclose(instr);
    }
    
    mypot1 = get_potential(getparam("name1"),getparam("pars1"),getparam("file1"));
    omega = get_pattern();
    dprintf(0,"Pattern speed: %f\n",omega);
    mypot2 = get_potential(getparam("name2"),getparam("pars2"),getparam("file2"));
    mypot3 = get_potential(getparam("name3"),getparam("pars3"),getparam("file3"));
    mypot4 = get_potential(getparam("name4"),getparam("pars4"),getparam("file4"));
    headline[0] = '\0';         /* accumulate headline */
    if (mypot1) {
        strcat(headline,getparam("name1"));
        strcat(headline,"(");
        strcat(headline,getparam("pars1"));
        strcat(headline,")");
        npots++;
    } 
    if (mypot2) {
        strcat(headline,getparam("name2"));
        strcat(headline,"(");
        strcat(headline,getparam("pars2"));
        strcat(headline,") ");
        npots++;
    }
    if (mypot3) {
        strcat(headline,getparam("name3"));
        strcat(headline,"(");
        strcat(headline,getparam("pars3"));
        strcat(headline,") ");
        npots++;
    }
    if (mypot4) {
        strcat(headline,getparam("name4"));
        strcat(headline,"(");
        strcat(headline,getparam("pars4"));
        strcat(headline,")");
        npots++;
    }

    nrad = nemoinpr(getparam("radii"),rad,MAXPT);   /* get radii */
    if (nrad <= 0)
        warning("Using %d radii is not very productive",nrad);
    vel  = (real *) allocate(sizeof(real) * nrad);  /* allocate stuff */
    vel1 = (real *) allocate(sizeof(real) * nrad);
    vel2 = (real *) allocate(sizeof(real) * nrad);
    vel3 = (real *) allocate(sizeof(real) * nrad);
    vel4 = (real *) allocate(sizeof(real) * nrad);
    if (Qome) {
        ome = (real *) allocate(4 * sizeof(real) * nrad);  /* plus spline */
        kap = (real *) allocate(sizeof(real) * nrad);
        opk = (real *) allocate(sizeof(real) * nrad);
        omk = (real *) allocate(sizeof(real) * nrad);
    } 

    axis = getparam("axis");
    dir = 0;
    if (*axis == 'x') dir=0;
    if (*axis == 'y') dir=1;
    if (*axis == 'z') dir=2;
    if (dir>NDIM) error("Axis %s not supported in NDIM=%d",axis,NDIM);

    pmax = 0.0;

    for (i=0; i<nrad; i++) {            /* loop to compute */
        CLRV(pos);                      /* clear positions */
        pos[dir] = rad[i];              /* set the right axis */
        vel[i] = 0.0;
        if (mypot1) {
            CLRV(acc);
            (*mypot1) (&ndim,pos,acc,&pot,&time);
            vel1[i] = -rad[i] * acc[dir];
            vel[i] += vel1[i];
            vel1[i] = sqrt(vel1[i]);        
        }
        if (mypot2) {
            CLRV(acc);
            (*mypot2) (&ndim,pos,acc,&pot,&time);
            vel2[i] = -rad[i] * acc[dir];
            vel[i] += vel2[i];
	    vel2[i] = sqrt(vel2[i]);        
        }
        if (mypot3) {
            CLRV(acc);
            (*mypot3) (&ndim,pos,acc,&pot,&time);
            vel3[i] = -rad[i] * acc[dir];
            vel[i] += vel3[i];
	    vel3[i] = sqrt(vel3[i]);        
        }
        if (mypot4) {
            CLRV(acc);
            (*mypot4) (&ndim,pos,acc,&pot,&time);
            vel4[i] = -rad[i] * acc[dir];
            vel[i] += vel4[i];
            vel4[i] = sqrt(vel4[i]);        
        }
        vel[i]  = sqrt(vel[i]);        
    }
    if (Qome) {
	lindblad(nrad,rad,vel,ome,kap,opk,omk,n);
        if (omega> 0.0) {                               /* compute resonances */
            f = opk;
            idx = nrad-1;
            if (omega < f[idx]) {
                warning("Radii not far enough out for OLR: %g",f[idx]);
                f = ome;
                if (omega < f[idx]) {
                    warning("Radii not far enough out for CR: %g",f[idx]);
                    f = omk;
                }
            }
            QoILR = FALSE;
            for(; idx>0; idx--) {
                if (omk[idx] > omk_max) {
                    idx_max = idx;
                    omk_max = omk[idx];
                }
                if (f==omk) {
                    if (QoILR) {
                        if (omega < f[idx]) continue;
                    } else {
                        if (omega > f[idx]) continue;
                    }
                } else {
                    if (omega > f[idx]) continue;
                }
                
                /* found a resonance: */

                rr = rad[idx] + (rad[idx+1]-rad[idx])*
                                (omega-f[idx])/(f[idx+1]-f[idx]);
                if (f == omk) {
#if 0                    
                    if (QoILR) {
                        dprintf(0,"iILR: %g\n",rr);
                        break;
                    } else {
                        dprintf(0,"oILR: %g\n",rr);
                        QoILR = TRUE;
                    }
#endif                    
                } else if (f == ome) {
                    dprintf(0,"CR: %g\n",rr);
                    f = omk;
                } else if (f == opk) {
                    dprintf(0,"OLR: %g\n",rr);
                    f = ome;
                } else
                    error("impossble resonance");
            }
            peak(nrad,rad,omk,idx_max,1, &omk_rmax, &omk_max);
            dprintf(0,"OMK_max: %g\n",omk_max);
            dprintf(0,"OMK_rmax: %g\n",omk_rmax);

            if (omega < omk_max) {			/* search for ILR */
            	for (idx=idx_max; idx<nrad; idx++) {
                    if (omega > omk[idx]) {
                        rr = rad[idx-1] + (rad[idx]-rad[idx-1])*
                                (omega-f[idx-1])/(f[idx]-f[idx-1]);
                        dprintf(0,"oILR: %g\n",rr);
                        break;
                    }
            	}
                for (idx=idx_max; idx>0; idx--) {
                    if (omega > omk[idx]) {
                        rr = rad[idx] + (rad[idx+1]-rad[idx])*
                               (omega-f[idx])/(f[idx+1]-f[idx]);
                        dprintf(0,"iILR: %g\n",rr);
                        break;
                    }
            	}
            }
        }
    }
    for (i=0; i<nrad; i++) {                            /* loop to print */
        if (Qtab) {
	  printf(fmt1,rad[i]);
	  printf(fmt1,vel[i]);
	}
	if (Qtab && npots>1 && !Qome) {
	    if (mypot1) printf(fmt1,vel1[i]);
	    if (mypot2) printf(fmt1,vel2[i]);
	    if (mypot3) printf(fmt1,vel3[i]);
	    if (mypot4) printf(fmt1,vel4[i]);
        }
        if (Qtab && Qome) {
	  printf(fmt1,ome[i]);
	  printf(fmt1,kap[i]);
	  printf(fmt1,opk[i]);
	  printf(fmt1,omk[i]);
	}
	if (Qtab) printf("\n");
        if (Qome)
            pmax = MAX(pmax,opk[i]);
        else
            pmax = MAX(pmax,vel[i]);
    }
    if (Qin && Qvel) 
        goodness(nrad,rad,vel,ndat,inrad,invel,(cols[3]>0?invele:NULL));
    if (Qplot) {
        plinit("***",0.0,20.0,0.0,20.0);                /* open device */
        nx = nemoinpr(getparam("xrange"),xplot,2);      /* get xrange in plot */
        switch(nx) {
         case 0:
            xplot[0] = rad[0];
         case 1:
            xplot[1] = rad[nrad-1];
            break;
         case 2:
            break;
         default:
            warning("xrange= only accepts two values");
            break;
        }
        ny = nemoinpr(getparam("yrange"),yplot,2);      /* get yrange in plot */
        switch(ny) {
         case 0:
            yplot[0] = 0.0;
            yplot[1] = 1.1 * pmax;      /* extra 10% for egde */
            break;
         case 1:
            yplot[1] = 1.1 * pmax;      /* extra 10% for egde */
            break;
         case 2:
            break;
         default:
            warning("yrange= only accepts two values");
            break;
        }
        xaxis ( 2.0, 2.0, 16.0, xplot, -7, xtrans, "R");    /* plot axes */
        xaxis ( 2.0,18.0, 16.0, xplot, -7, xtrans, NULL);
        if (Qome)
            yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "[V/R]");
        else
            yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "V");
        yaxis (18.0, 2.0, 16.0, yplot, -7, ytrans, NULL);
        if (*plotlabel)
            pltext(plotlabel,2.0,18.5,0.5,0.0);
        else
            pltext(headline,2.0,18.5,0.35,0.0);
        if (*plotmsg)
            pltext(plotmsg,8.0,2.5,0.25,0.0);

        curve = (Qome ? ome : vel);            /* assign first curve */
        plltype(3,1);                                 /* thick solid line */
        plmove(xtrans(rad[0]),ytrans(curve[0]));
        for (i=1; i<nrad; i++)
            plline(xtrans(rad[i]),ytrans(curve[i]));
        if (Qome) {                   /* if Lindblad - plot omk, opk */
            plltype(1,1);                      /* all regular solid lines */
            plmove(xtrans(rad[0]), ytrans(omk[0]));
            for (i=1; i<nrad; i++)
                plline(xtrans(rad[i]),ytrans(omk[i]));
            plmove(xtrans(rad[0]), ytrans(opk[0]));
            for (i=1; i<nrad; i++)
                plline(xtrans(rad[i]),ytrans(opk[i]));
        } else if (npots>1) {            /* if velocity and > 1 component */
            ltype = 1;
            if (mypot1) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel1[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel1[i]));
            }
            if (mypot2) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel2[i]));
            }
            if (mypot3) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel3[i]));
            }
            if (mypot4) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel4[i]));
            }
        }
	plltype(1,1); 
        symsize = 0.1;
        if (Qin && Qvel) {           /* if input file with velocities */
            for (i=0; i<ndat; i++)
                plbox(xtrans(inrad[i]),ytrans(invel[i]),symsize);
            if (cols[3]>0) {        /* if error bars in radius */
                for (i=0; i<ndat; i++) {
                    plmove(xtrans(inrad[i]-inrade[i]),ytrans(invel[i]));
                    plline(xtrans(inrad[i]+inrade[i]),ytrans(invel[i]));
                }
            }
            if (cols[4]>0) {        /* if error bars in velocity */
                for (i=0; i<ndat; i++) {
                    plmove(xtrans(inrad[i]),ytrans(invel[i]-invele[i]));
                    plline(xtrans(inrad[i]),ytrans(invel[i]+invele[i]));
                }
            }
        } else if (Qin && Qome) {       /* if input file with omega */
            for (i=0; i<ndat; i++)
                plbox(xtrans(inrad[i]),ytrans(invel[i]/inrad[i]),symsize);
        }
        plstop();
    }  /* if plot vel/ome */
    if (Qlv) {
        ns = nemoinpr(getparam("r0l"),r0l,MAXPT+2) - 2;
        if (ns < 0)
            error("r0l= needs at least two values: r0 and l");
        else if (ns==0)
            warning("r0l= no lv-radii array supplied");
        lv(nrad,rad,vel,r0l[0],r0l[1],ns,&r0l[2]);
    }
}
Пример #13
0
void IFXCharacter::CalcNodeRotations(bool lookback,IFXCoreNode &parent)
{
	IFXCharacter *character=parent.RootCharacter();
	IFXTransformStack &m_transforms=character->TransformStack();

	IFXVector3 worldvector,localvector;
	IFXVector3 parent_location,child_location,grandchild_location;

	IFXVector3 xaxis(1.0f,0.0f,0.0f);
	IFXVector3 zero(0.0f,0.0f,0.0f);

	IFXBoneNodeList &childlist=parent.Children();
	if(!childlist.GetNumberElements())
		return;

	IFXBoneNode *node;
	IFXListContext context;
	// F32 parentlength=0.0f;

	if(parent.IsBone())
	{
		node=(IFXBoneNode *)&parent;
		parent_location=node->StoredTransform().TranslationConst();
		// parentlength=node->GetLength();
	}
	else
		parent_location.Reset();

	childlist.ToHead(context);
	while( (node=childlist.PostIncrement(context)) != NULL)
	{
		child_location=node->StoredTransform().TranslationConst();

		if(lookback)
		{
			if(!parent.IsBone())
			{
				node->Displacement()=child_location;
				worldvector.Reset();
				localvector=xaxis;
			}
			else
			{
				worldvector.Subtract(child_location,parent_location);
				m_transforms.GetCurrent().ReverseTransformVector(child_location,
					localvector);
			}
		}
		else
		{
			IFXBoneNode *grandchild=node->Children().GetHead();
			if(grandchild)
			{
				grandchild_location=grandchild->StoredTransform()
					.TranslationConst();
				worldvector.Subtract(grandchild_location,child_location);
				m_transforms.GetCurrent().ReverseRotateVector(worldvector,
					localvector);
			}
			else
			{
				worldvector.Reset();
				localvector=xaxis;
			}
		}

		localvector.Normalize();

		node->SetLength(worldvector.CalcMagnitude());

		if(lookback)
		{
			//* for load ASE: create rotations
			if(node->GetLength()<0.1)
				node->Rotation().MakeIdentity();
			else
				node->Rotation().MakeRotation(xaxis,localvector);
		}
		else
		{
			//* for load ASH: find/create displacements
			m_transforms.GetCurrent().ReverseTransformVector(child_location,
				localvector);
			if(localvector.IsApproximately(zero,0.1f))
				node->Displacement().Reset();
			else
				node->Displacement()=localvector;
		}

		//* do child's new transform
		m_transforms.Push();

		m_transforms.GetCurrent().Translate(node->DisplacementConst());
		m_transforms.GetCurrent().Rotate(node->RotationConst());
		m_transforms.GetCurrent().Translate(node->GetLength(),0.0f,0.0f);

		CalcNodeRotations(lookback,*node);

		m_transforms.Pop();
	}
}
Пример #14
0
void CPropertiesCanvas::OnPropertyGridChange( wxPropertyGridEvent& event ) {
	wxPGProperty* p = event.GetPropertyPtr();

	Property* property = GetProperty(p);
	if(property == NULL)return;

	wxGetApp().CreateUndoPoint();

	switch(property->get_property_type()){
	case StringPropertyType:
		{
            wxString value;
            if (property->Evaluate(GetProperties(), event.GetPropertyValue().GetString(), value))
            {
                (*(((PropertyString*)property)->m_callbackfunc))(value, ((PropertyString*)property)->m_object);
            }
		}
		break;
	case DoublePropertyType:
		{
		    wxString value;
		    if (property->Evaluate(GetProperties(), event.GetPropertyValue().GetString(), value))
		    {
                (*(((PropertyDouble*)property)->m_callbackfunc))(strtod(value.utf8_str(),NULL), ((PropertyDouble*)property)->m_object);
		    }
		}
		break;
	case LengthPropertyType:
		{
		    wxString value;
		    if (property->Evaluate(GetProperties(), event.GetPropertyValue().GetString(), value))
		    {
                (*(((PropertyLength*)property)->m_callbackfunc))(strtod(value.utf8_str(),NULL) * wxGetApp().m_view_units, ((PropertyDouble*)property)->m_object);
		    }
		}
		break;
	case IntPropertyType:
		{
			(*(((PropertyInt*)property)->m_callbackfunc))(event.GetPropertyValue().GetLong(), ((PropertyInt*)property)->m_object);
		}
		break;
	case ColorPropertyType:
		{
			wxVariant var = event.GetPropertyValue();
			const wxColour* wcol = wxGetVariantCast(var,wxColour);
			HeeksColor col(wcol->Red(), wcol->Green(), wcol->Blue());
			(*(((PropertyColor*)property)->m_callbackfunc))(col, ((PropertyColor*)property)->m_object);
		}
		break;
	case VertexPropertyType:
		{
			if(p->GetName()[0] == 'x'){
				((PropertyVertex*)property)->m_x[0] = event.GetPropertyValue().GetDouble();
				if(((PropertyVertex*)property)->m_affected_by_view_units)((PropertyVertex*)property)->m_x[0] *= wxGetApp().m_view_units;
			}
			else if(p->GetName()[0] == 'y'){
				((PropertyVertex*)property)->m_x[1] = event.GetPropertyValue().GetDouble();
				if(((PropertyVertex*)property)->m_affected_by_view_units)((PropertyVertex*)property)->m_x[1] *= wxGetApp().m_view_units;
			}
			else if(p->GetName()[0] == 'z'){
				((PropertyVertex*)property)->m_x[2] = event.GetPropertyValue().GetDouble();
				if(((PropertyVertex*)property)->m_affected_by_view_units)((PropertyVertex*)property)->m_x[2] *= wxGetApp().m_view_units;
			}

			(*(((PropertyVertex*)property)->m_callbackfunc))(((PropertyVertex*)property)->m_x, ((PropertyVertex*)property)->m_object);
		}
		break;
	case TrsfPropertyType:
		{
			double pos[3];
			extract(((PropertyTrsf*)property)->m_trsf.TranslationPart(), pos);

			gp_Dir xaxis(1, 0, 0);
			xaxis.Transform(((PropertyTrsf*)p)->m_trsf);
			gp_Dir yaxis(0, 1, 0);
			yaxis.Transform(((PropertyTrsf*)p)->m_trsf);

			double vertical_angle = 0;
			double horizontal_angle = 0;
			double twist_angle = 0;
			CoordinateSystem::AxesToAngles(xaxis, yaxis, vertical_angle, horizontal_angle, twist_angle);

			if(p->GetName()[0] == 'x'){
				pos[0] = event.GetPropertyValue().GetDouble();
			}
			else if(p->GetName()[0] == 'y'){
				pos[1] = event.GetPropertyValue().GetDouble();
			}
			else if(p->GetName()[0] == 'z'){
				pos[2] = event.GetPropertyValue().GetDouble();
			}
			else if(p->GetName()[0] == 'v'){
				vertical_angle = event.GetPropertyValue().GetDouble();
			}
			else if(p->GetName()[0] == 'h'){
				horizontal_angle = event.GetPropertyValue().GetDouble();
			}
			else if(p->GetName()[0] == 't'){
				twist_angle = event.GetPropertyValue().GetDouble();
			}

			CoordinateSystem::AnglesToAxes(vertical_angle, horizontal_angle, twist_angle, xaxis, yaxis);

			((PropertyTrsf*)property)->m_trsf = make_matrix(make_point(pos), xaxis, yaxis);

			(*(((PropertyTrsf*)property)->m_callbackfunc))(((PropertyTrsf*)property)->m_trsf, ((PropertyTrsf*)property)->m_object);
		}
		break;
	case ChoicePropertyType:
		{
			(*(((PropertyChoice*)property)->m_callbackfunc))(event.GetPropertyValue().GetLong(), ((PropertyChoice*)property)->m_object);
		}
		break;
	case CheckPropertyType:
		{
			(*(((PropertyCheck*)property)->m_callbackfunc))(event.GetPropertyValue().GetBool(), ((PropertyCheck*)property)->m_object);
		}
		break;
	case ListOfPropertyType:
		{
		}
		break;
	case FilePropertyType:
		{
			(*(((PropertyFile*)property)->m_callbackfunc))(event.GetPropertyValue().GetString(), ((PropertyFile*)property)->m_object);
		}
		break;
	case DirectoryPropertyType:
		{
			(*(((PropertyDir*)property)->m_callbackfunc))(event.GetPropertyValue().GetString(), ((PropertyDir*)property)->m_object);
		}
		break;
	}

	wxGetApp().Changed();
}
Пример #15
0
local void histogram(void)
{
  int i,j,k, l, kmin, kmax, lcount = 0;
  real count[MAXHIST], under, over;
  real xdat,ydat,xplt,yplt,dx,r,sum,sigma2, q, qmax;
  real mean, sigma, mad, skew, kurt, h3, h4, lmin, lmax, median;
  real rmean, rsigma, rrange[2];
  Moment m;
  
  dprintf (0,"read %d values\n",npt);
  dprintf (0,"min and max value in column(s)  %s: %g  %g\n",getparam("xcol"),xmin,xmax);
  if (!Qauto) {
    xmin = xrange[0];
    xmax = xrange[1];
    dprintf (0,"min and max value reset to : %g  %g\n",xmin,xmax);
    lmin = xmax;
    lmax = xmin;
    for (i=0; i<npt; i++) {
      if (x[i]>xmin && x[i]<=xmax) {
	lmin = MIN(lmin, x[i]);
	lmax = MAX(lmax, x[i]);
      }
    }
    dprintf (0,"min and max value in range : %g  %g\n",lmin,lmax);
  } 
  
  for (k=0; k<nsteps; k++)
    count[k] = 0;		/* init histogram */
  under = over = 0;
  
  ini_moment(&m, 4, Qrobust||Qmad ? npt : 0);
  for (i=0; i<npt; i++) {
    if (Qbin) {
      k=ring_index(nsteps,bins,x[i]);
    } else {
      if (xmax != xmin)
	k = (int) floor((x[i]-xmin)/(xmax-xmin)*nsteps);
      else
	k = 0;
      dprintf(2,"%d k=%d %g\n",i,k,x[i]);
    }
    if (k==nsteps && x[i]==xmax) k--;     /* include upper edge */
    if (k<0)       { under++; continue; }
    if (k>=nsteps) { over++;  continue; }
    count[k] = count[k] + 1;
    dprintf (4,"%d : %f %d\n",i,x[i],k);
    accum_moment(&m,x[i],1.0);
  }
  if (under > 0) error("bug: under = %d",under);
  if (over  > 0) error("bug: over = %d",over);
  under = Nunder;
  over  = Nover;

  mean = mean_moment(&m);
  sigma = sigma_moment(&m);
  skew = skewness_moment(&m);
  kurt = kurtosis_moment(&m);
  h3 = h3_moment(&m);
  h4 = h4_moment(&m);
  if (Qmad) mad = mad_moment(&m);

  if (nsigma > 0) {    /* remove outliers iteratively, starting from the largest */
    iq = (int *) allocate(npt*sizeof(int));
    for (i=0; i<npt; i++) {
#if 1
      iq[i] = x[i] < xmin  || x[i] > xmax;
#else
      iq[i] = 0;
#endif
    }
    lcount = 0;
    do {               /* loop to remove outliers one by one */
      qmax = -1.0;
      for (i=0, l=-1; i<npt; i++) {     /* find largest deviation from current mean */
	if (iq[i]) continue;            /* but skip previously flagged points */
	q = (x[i]-mean)/sigma;
	q = ABS(q);
	if (q > qmax) {
	  qmax = q;
	  l = i;
	}
      }
      if (qmax > nsigma) {
	lcount++;
	iq[l] = 1;
	decr_moment(&m,x[l],1.0);
	mean = mean_moment(&m);
	sigma = sigma_moment(&m);
	skew = skewness_moment(&m);
	kurt = kurtosis_moment(&m);
	h3 = h3_moment(&m);
	h4 = h4_moment(&m);
	if (Qmad) mad = mad_moment(&m);
	dprintf(1,"%d/%d: removing point %d, m/s=%g %g qmax=%g\n",
		lcount,npt,l,mean,sigma,qmax);
	if (sigma <= 0) {
	  /* RELATED TO presetting MINMAX */
	  warning("BUG");
	  accum_moment(&m,x[l],1.0);
	  mean = mean_moment(&m);
	  sigma = sigma_moment(&m);
	  skew = skewness_moment(&m);
	  kurt = kurtosis_moment(&m);
	  h3 = h3_moment(&m);
	  h4 = h4_moment(&m);
	  dprintf(1,"%d/%d: LAST removing point %d, m/s=%g %g qmax=%g\n",
		  lcount,npt,l,mean,sigma,qmax);
	  break;
	  
	}
	
      } else
	dprintf(1,"%d/%d: keeping point %d, m/s=%g %g qmax=%g\n",
		lcount,npt,l,mean,sigma,qmax);
      
      /* if (lcount > npt/2) break; */
    } while (qmax > nsigma);
    dprintf(0,"Removed %d/%d points for nsigma=%g\n",lcount,npt,nsigma);
    
    /* @algorithm      left shift array values from mask array */
    /* now shift all points into the array, decreasing npt */
    /* otherwise the median is not correctly computed */
    for (i=0, k=0; i<npt; i++) {
      dprintf(1,"iq->%d\n",iq[i]);
      if (iq[i]) k++;
      if (k==0) continue;  /* ?? */
      if (i-k < 0) continue;
      dprintf(1,"SHIFT: %d <= %d\n",i-k,i);
      x[i-k] = x[i];
    }
    npt -= lcount;   /* correct for outliers */
    free(iq);
  } /* nsigma > 0 */
  
  if (npt != n_moment(&m))
    error("Counting error, probably in removing outliers...");
  dprintf (0,"Number of points     : %d\n",npt);
  if (npt>1)
    dprintf (0,"Mean and dispersion  : %g %g %g\n",mean,sigma,sigma/sqrt(npt-1.0));
  else
    dprintf (0,"Mean and dispersion  : %g %g 0.0\n",mean,sigma);

  if (Qmad)  dprintf (0,"MAD                  : %g\n",mad);
  dprintf (0,"Skewness and kurtosis: %g %g\n",skew,kurt);
  dprintf (0,"h3 and h4            : %g %g\n", h3, h4);
  if (Qmedian) {
    
    if (npt % 2) 
      median = x[(npt-1)/2];
    else
      median = 0.5 * (x[npt/2] + x[npt/2-1]);
    dprintf (0,"Median               : %g\n",median);
  } else if (Qtorben) {
    median = median_torben(npt,x,xmin,xmax);
    dprintf (0,"Median_torben        : %g\n",median);
  }
  dprintf (0,"Sum                  : %g\n",show_moment(&m,1));
  if (Qrobust) {
    compute_robust_moment(&m);
    rmean  = mean_robust_moment(&m);
    rsigma = sigma_robust_moment(&m);
    robust_range(&m, rrange);
    dprintf (0,"Robust N             : %d\n",n_robust_moment(&m));
    dprintf (0,"Robust Mean Disp     : %g %g\n",rmean,rsigma);
    dprintf (0,"Robust Range         : %g %g\n",rrange[0],rrange[1]);
    if (outstr) {
      for (i=0; i<npt; i++) {
	if (x[i]<rrange[0] || x[i]>rrange[1]) continue;
	fprintf(outstr,"%g %d\n",x[i],i+1);
      }
    }
  }
  
  if (lcount > 0) {
    warning("Recompute histogram because of outlier removals");
    /* recompute histogram if we've lost some outliers */
    for (k=0; k<nsteps; k++)
      count[k] = 0;		/* init histogram */
    under = over = 0;
    for (i=0; i<npt; i++) {
      if (xmax != xmin)
	k = (int) floor((x[i]-xmin)/(xmax-xmin)*nsteps);
      else
	k = 0;
      if (k==nsteps && x[i]==xmax) k--;     /* include upper edge */
      if (k<0)       { under++; continue; }
      if (k>=nsteps) { over++;  continue; }
      count[k] = count[k] + 1;
      dprintf (4,"%d : %f %d\n",i,x[i],k);
    }
    if (under > 0 || over > 0) error("under=%d over=%d in recomputed histo",under,over);
  }
  
  dprintf (3,"Histogram values : \n");
  dx=(xmax-xmin)/nsteps;
  kmax=0;
  sum=0.0;
  for (k=0; k<nsteps; k++) {
    sum = sum + dx*count[k];
    if (ylog) {
      if (count[k]>0.0)
	count[k] = log10(count[k]);
      else
	count[k] = -1.0;
    }
    if (count[k]>kmax)
      kmax=count[k];
    dprintf (3,"%f ",count[k]);
    if (Qcumul) {
      if (k==0)
	count[k] += under;
      else
	count[k] += count[k-1];
    }
  }
  dprintf (3,"\n");
  sigma2 = 2.0 * sigma * sigma;	/* gaussian */
  sum /= sigma * sqrt(2*PI);	/* scaling factor for equal area gauss */
  
  if (ylog && over>0)  over =  log10(over);
  if (ylog && under>0) under = log10(under);
  
  kmax *= 1.1;		/* add 10% */
  if (Qcumul) kmax = npt;
  if (maxcount>0)		/* force scaling by user ? */
    kmax=maxcount;	
  
  if (Qtab) {
    maxcount = 0;
    for (k=0; k<nsteps; k++)
      maxcount = MAX(maxcount,count[k]);
    if (maxcount>0)
      r = 29.0/maxcount;
    else
      r = 1.0;
    printf("  Bin    Value          Number\n");
    printf("       Underflow   %d\n",Nunder);
    for (k=0; k<nsteps; k++) {
      j = (int) (r*count[k]) + 1;
      if (ylog) printf("%3d %13.6g %13.6g ", 
		       k+1, xmin+(k+0.5)*dx, count[k]);
      else printf("%3d %13.6g %8d ", 
		  k+1, xmin+(k+0.5)*dx, (int)count[k]);
      while (j-- > 0) printf("*");
      printf("\n");
    }
    printf("       Overflow    %d\n",Nover);
    stop(0);
  }
  
#ifdef YAPP
  /*	PLOTTING */	
  plinit("***",0.0,20.0,0.0,20.0);

  xplot[0] = xmin;
  xplot[1] = xmax;
  yplot[0] = 0.0;
  yplot[1] = (real) kmax;
  xaxis (2.0, 2.0, 16.0, xplot, -7, xtrans, xlab);
  xaxis (2.0, 18.0,16.0, xplot, -7, xtrans, NULL);
  yaxis (2.0, 2.0, 16.0, yplot, -7, ytrans, ylab);
  yaxis (18.0, 2.0, 16.0, yplot, -7, ytrans, NULL);
  
  pljust(-1);     /* set to left just */
  pltext(input,2.0,18.2,0.32,0.0);             /* filename */
  pljust(1);
  pltext(headline,18.0,18.2,0.24,0.0);         /* headline */
  pljust(-1);     /* return to left just */
  
  xdat=xmin;
  dx=(xmax-xmin)/nsteps;
  plmove(xtrans(xmin),ytrans(0.0));
  for (k=0; k<nsteps; k++) {	/* nsteps= */
    xplt = xtrans(xdat);
    yplt = ytrans((real)count[k]);
    plline (xplt,yplt);
    xdat += dx;
    xplt = xtrans(xdat);
    plline (xplt,yplt);	
  }
  plline(xplt,ytrans(0.0));
  
  for (i=0; i<nxcoord; i++) {
    plmove(xtrans(xcoord[i]),ytrans(yplot[0]));
    plline(xtrans(xcoord[i]),ytrans(yplot[1]));
  }
  
  if (Qgauss) {                   /* plot model and residuals */
    if (ylog)
      plmove(xtrans(xmin),ytrans(-1.0));
    else
      plmove(xtrans(xmin),ytrans(0.0));
    for (k=0; k<100; k++) {
      xdat = xmin + (k+0.5)*(xmax-xmin)/100.0;
      ydat = sum * exp( -sqr(xdat-mean)/sigma2);
      if (ylog) ydat = log10(ydat);
      plline(xtrans(xdat), ytrans(ydat));
    }
  }
  
  if (Qresid) {
    
    plltype(0,2);   /* dotted residuals */
    xdat = xmin+0.5*dx;
    dprintf(1,"# residuals from gauss\n");
    for (k=0; k<nsteps; k++, xdat +=dx) {
      ydat = sum * exp( -sqr(xdat-mean)/sigma2);
      dprintf(1,"%g %g %g\n",xdat,count[k],ydat);
      if (ylog) ydat = log10(ydat);
      ydat = count[k] - ydat;
      if (k==0)
	plmove(xtrans(xdat),ytrans(ydat));
      else
	plline(xtrans(xdat),ytrans(ydat));
    }
    plltype(0,1);   /* back to normal line type */
    
  }
  plstop();
#endif
}
void fitEfficiency(float thres,
		   float mLow=45, float mHigh=70,
		   TString cutdef="pt_HLT>=20", TString cut_choice="HLT",
		   TString dirIn="/data_CMS/cms/ndaci/ndaci_2012/HTauTau/TriggerStudy/SingleMu/MuMu/Run2012A_PRV1/Pairs/", 
		   TString dirResults="/home//llr/cms/ndaci/SKWork/macro/HTauTau/results/TriggerStudies/MuMu/Run2012A_PRV1/",
		   TString lumi="200 pb", int nCPU=4, 
		   int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
		   TString fileIn="*.root", TString image="eff_HLT_MuTau")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // OUTPUT //
  TString name_image = dirResults+"/"+image;
  ofstream fichier(name_image+".txt", ios::out);

  // BINNING //
  const int nbinsEB = 14;
  Double_t binsEB[nbinsEB] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEB = RooBinning(nbinsEB-1, binsEB, "binningEB");

  const int nbinsEE = 14;
  Double_t binsEE[nbinsEE] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEE = RooBinning(nbinsEE-1, binsEE, "binningEE");

  // EB/EE eta cuts //
  TString etacutEB="eta>-1.479 && eta<1.479", etacutEE="eta<=-1.479 || eta>=1.479";
  TString cutdefEB, cutdefEE;
  if(cutdef=="") { 
    cutdefEB=etacutEB;
    cutdefEE=etacutEE;
  }
  else {
    cutdefEB=cutdef+" && "+etacutEB ;
    cutdefEB=cutdef+" && "+etacutEE ;
  }

  // INPUT DATA //
  TChain* treeTnP = new TChain("treeTnP");
  treeTnP->Add(dirIn+"/"+fileIn);

  RooRealVar xaxis("pt","P_{T} [GeV]",0,150) ;
  RooRealVar mass("mass","mass",mLow,mHigh) ;// consider only this mass range when importing data                                      
  RooRealVar eta("eta","eta",-3., 3) ;
  RooRealVar weight("weight","weight",-1,1000) ;
  RooRealVar pt_HLT_tag("pt_HLT_tag","P_{T} [GeV]",0,150) ;
  RooRealVar pt_HLT_tag_sanity("pt_HLT_tag_sanity","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L3("pt_L3","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L25("pt_L25","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L2("pt_L2","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1jet("et_L1_jet","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1tau("et_L1_tau","P_{T} [GeV]",0,150) ;

  // DEFINE EFFICIENCY CUT //
  RooCategory cutHLT("match","") ;
  cutHLT.defineType("accept",1) ;
  cutHLT.defineType("reject",0) ;

  RooCategory cutL1("L1match","") ;
  cutL1.defineType("accept",1) ;
  cutL1.defineType("reject",0) ;

  RooCategory cutL1L2("L1L2match","") ;
  cutL1L2.defineType("accept",1) ;
  cutL1L2.defineType("reject",0) ;

  RooCategory cutL1L2L25("L1L2L25match","") ;
  cutL1L2L25.defineType("accept",1) ;
  cutL1L2L25.defineType("reject",0) ;

  RooCategory cutL1L2L25L3("L1L2L25L3match","") ;
  cutL1L2L25L3.defineType("accept",1) ;
  cutL1L2L25L3.defineType("reject",0) ;

  RooCategory *cut;
  if(cut_choice=="HLT") cut = &cutHLT;
  if(cut_choice=="L1") cut = &cutL1;
  if(cut_choice=="L1L2") cut = &cutL1L2;
  if(cut_choice=="L1L2L25") cut = &cutL1L2L25;
  if(cut_choice=="L1L2L25L3") cut = &cutL1L2L25L3;

  RooDataSet dataSetEB("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEB) );
  
  RooDataSet dataSetEE("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEE) );
  
  dataSetEB.Print();
  dataSetEE.Print();

  // PLOT //
  RooPlot* frame = xaxis.frame(Bins(18000),Title("Fitted efficiency")) ;
  dataSetEB.plotOn(frame, Binning(binningEB), Efficiency(*cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSetEE.plotOn(frame, Binning(binningEE), Efficiency(*cut), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );

  // PARAMETRES ROOFIT CRYSTAL BALL //
  RooRealVar norm("norm","N",0.95,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.2,0.01,8);
  RooRealVar n("n","n",2,1.1,35);
  RooRealVar mean("mean","mean",10,5,30);
  mean.setVal(thres);
  RooRealVar sigma("sigma","#sigma",0.23,0.01,5);
  RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  FuncCB cb_EB("cb_EB","Fit function EB (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  FuncCB cb_EE("cb_EE","Fit function EE (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  
  RooEfficiency eff_EB("eff_EB","efficiency EB", cb_EB, *cut, "accept");
  RooEfficiency eff_EE("eff_EE","efficiency EE", cb_EE, *cut, "accept");  

  // FIT //
  double fit_cuts_min = thres-1.5 ;
  double fit_cuts_max = 150;
  xaxis.setRange("interesting",fit_cuts_min,fit_cuts_max);

  fichier << "Fit characteristics :" << endl
	  << "Threshold : "          << thres << endl 
	  << "Fit Range : ["         << fit_cuts_min << "," << fit_cuts_max << "]" << endl 
	  << endl << endl;

  RooFitResult* roofitres_EB = new RooFitResult("roofitres_EB","roofitres_EB");
  RooFitResult* roofitres_EE = new RooFitResult("roofitres_EE","roofitres_EE");

  // Fit #1 //
  roofitres_EB = eff_EB.fitTo(dataSetEB,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EB.plotOn(frame,LineColor(color1),LineWidth(2));

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;

  // Fit #2 //
  roofitres_EE = eff_EE.fitTo(dataSetEE,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EE.plotOn(frame,LineColor(color2),LineWidth(2));

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;


  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  //gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,150.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  TH1F *SCeta_EB = new TH1F("SCeta_EB","SCeta_EB",50,-2.5,2.5);
  TH1F *SCeta_EE = new TH1F("SCeta_EE","SCeta_EE",50,-2.5,2.5);

  SCeta_EB->SetLineColor(color1) ;
  SCeta_EB->SetMarkerColor(color1);
  SCeta_EB->SetMarkerStyle(style1);

  SCeta_EE->SetLineColor(color2) ;
  SCeta_EE->SetMarkerColor(color2);
  SCeta_EE->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.40, 0.14, 0.63, 0.34, NULL, "brNDC");
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.0244755);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);  
  leg->AddEntry("NULL","e #tau electrons efficiency","h");
  //    entry->SetLineColor(1);
  //    entry->SetLineStyle(1);
  //    entry->SetLineWidth(1);
  //    entry->SetMarkerColor(1);
  //    entry->SetMarkerStyle(21);
  //    entry->SetMarkerSize(1);
  //    entry->SetTextFont(62);
  leg->AddEntry(SCeta_EB,"Barrel","p");
  leg->AddEntry(SCeta_EE,"Endcaps","p");
  leg->Draw(); 
  
  ostringstream ossi("");
  ossi << thres;
  TString tossi = ossi.str();

  leg = new TLegend(0.40, 0.30, 0.50, 0.50, NULL, "brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.0297203);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+tossi+" GeV","h");
  leg->Draw();
  
  ca->Print(name_image+".C","C");
  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

  RooWorkspace *w = new RooWorkspace("workspace","workspace") ;

  w->import(dataSetEB);
  w->import(dataSetEE);
  
  w->import(*roofitres_EB,"roofitres_EB");
  w->import(*roofitres_EE,"roofitres_EE");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  // DELETE POINTERS
  // int a=0;
//   cin >> a;
//   delete treeTnP; delete cut; delete frame; delete roofitres_EB; delete roofitres_EE; delete ca; delete SCeta_EB; delete SCeta_EE; delete leg; delete w;

}
Пример #17
0
static void PlaceDetail( DetailModel_t const& model, const Vector& pt, const Vector& normal )
{
	// But only place it on the surface if it meets the angle constraints...
	float cosAngle = normal.z;

	// Never emit if the angle's too steep
	if (cosAngle < model.m_MaxCosAngle)
		return;

	// If it's between min + max, flip a coin...
	if (cosAngle < model.m_MinCosAngle)
	{
		float probability = (cosAngle - model.m_MaxCosAngle) / 
			(model.m_MinCosAngle - model.m_MaxCosAngle);

		float t = rand() / (float)RAND_MAX;
		if (t > probability)
			return;
	}

	// Compute the orientation of the detail
	QAngle angles;
	if (model.m_Flags & MODELFLAG_UPRIGHT)
	{
		// If it's upright, we just select a random yaw
		angles.Init( 0, 360.0f * rand() / (float)RAND_MAX, 0.0f );
	}
	else
	{
		// It's not upright, so it must conform to the ground. Choose
		// a random orientation based on the surface normal

		Vector zaxis;
		VectorCopy( normal, zaxis );

		// Choose any two arbitrary axes which are perpendicular to the normal
		Vector xaxis( 1, 0, 0 );
		if (fabs(xaxis.Dot(zaxis)) - 1.0 > -1e-3)
			xaxis.Init( 0, 1, 0 );
		Vector yaxis;
		CrossProduct( zaxis, xaxis, yaxis );
		CrossProduct( yaxis, zaxis, xaxis );
		VMatrix matrix;
		matrix.SetBasisVectors( xaxis, yaxis, zaxis );

		float rotAngle = 360.0f * rand() / (float)RAND_MAX;
		VMatrix rot = SetupMatrixAxisRot( Vector( 0, 0, 1 ), rotAngle );
		matrix = matrix * rot;

		MatrixToAngles( matrix, angles );
	}

	// FIXME: We may also want a purely random rotation too

	// Insert an element into the object dictionary if it aint there...
	switch ( model.m_Type )
	{
	case DETAIL_PROP_TYPE_MODEL:
		AddDetailToLump( model.m_ModelName.String(), pt, angles, model.m_Orientation );
		break;

	case DETAIL_PROP_TYPE_SPRITE:
		{
			float flScale = 1.0f;
			if ( model.m_flRandomScaleStdDev != 0.0f ) 
			{
				flScale = fabs( RandomGaussianFloat( 1.0f, model.m_flRandomScaleStdDev ) );
			}

			AddDetailSpriteToLump( pt, angles, model.m_Orientation, model.m_Pos, model.m_Tex, flScale );
		}
		break;
	}
}
bool OBBRayPicking::testRayOBBIntersection(
	glm::vec3 ray_origin,        // Ray origin, in world space
	glm::vec3 ray_direction,     // Ray direction (NOT target position!), in world space. Must be normalize()'d.
	glm::vec3 aabb_min,          // Minimum X,Y,Z coords of the mesh when not transformed at all.
	glm::vec3 aabb_max,          // Maximum X,Y,Z coords. Often aabb_min*-1 if your mesh is centered, but it's not always the case.
	const glm::mat4 &ModelMatrix,       // Transformation applied to the mesh (which will thus be also applied to its bounding box)
	const glm::vec3 &position, // the position because model matrix doesnt do anything in this game "right now"
	float &intersection_distance // Output : distance between ray_origin and the intersection with the OBB
	){

	// Intersection method from Real-Time Rendering and Essential Mathematics for Games

	float tMin = 0.0f;
	float tMax = 100000.0f;

	glm::vec3 OBBposition_worldspace(ModelMatrix[3].x * position.x, ModelMatrix[3].y * position.y, ModelMatrix[3].z * position.z);

	glm::vec3 delta = OBBposition_worldspace - ray_origin;

	// Test intersection with the 2 planes perpendicular to the OBB's X axis
	{
		glm::vec3 xaxis(ModelMatrix[0].x, ModelMatrix[0].y, ModelMatrix[0].z);
		float e = glm::dot(xaxis, delta);
		float f = glm::dot(ray_direction, xaxis);
		
		if (fabs(f) > 0.001f)
		{ // Standard case

			float t1 = (e + aabb_min.x) / f; // Intersection with the "left" plane
			float t2 = (e + aabb_max.x) / f; // Intersection with the "right" plane
			// t1 and t2 now contain distances betwen ray origin and ray-plane intersections

			// We want t1 to represent the nearest intersection, 
			// so if it's not the case, invert t1 and t2
			if (t1>t2){
				float w = t1; t1 = t2; t2 = w; // swap t1 and t2
			}

			// tMax is the nearest "far" intersection (amongst the X,Y and Z planes pairs)
			if (t2 < tMax)
				tMax = t2;
			// tMin is the farthest "near" intersection (amongst the X,Y and Z planes pairs)
			if (t1 > tMin)
				tMin = t1;

			// And here's the trick :
			// If "far" is closer than "near", then there is NO intersection.
			// See the images in the tutorials for the visual explanation.
			if (tMax < tMin)
				return false;

		}
		else
		{ // Rare case : the ray is almost parallel to the planes, so they don't have any "intersection"
			if (-e + aabb_min.x > 0.0f || -e + aabb_max.x < 0.0f)
				return false;
		}
	}


	// Test intersection with the 2 planes perpendicular to the OBB's Y axis
	// Exactly the same thing than above.
	{
		glm::vec3 yaxis(ModelMatrix[1].x, ModelMatrix[1].y, ModelMatrix[1].z);
		float e = glm::dot(yaxis, delta);
		float f = glm::dot(ray_direction, yaxis);

		if (fabs(f) > 0.001f){

			float t1 = (e + aabb_min.y) / f;
			float t2 = (e + aabb_max.y) / f;

			if (t1>t2){ float w = t1; t1 = t2; t2 = w; }

			if (t2 < tMax)
				tMax = t2;
			if (t1 > tMin)
				tMin = t1;
			if (tMin > tMax)
				return false;

		}
		else{
			if (-e + aabb_min.y > 0.0f || -e + aabb_max.y < 0.0f)
				return false;
		}
	}


	// Test intersection with the 2 planes perpendicular to the OBB's Z axis
	// Exactly the same thing than above.
	{
		glm::vec3 zaxis(ModelMatrix[2].x, ModelMatrix[2].y, ModelMatrix[2].z);
		float e = glm::dot(zaxis, delta);
		float f = glm::dot(ray_direction, zaxis);

		if (fabs(f) > 0.001f){

			float t1 = (e + aabb_min.z) / f;
			float t2 = (e + aabb_max.z) / f;

			if (t1>t2){ float w = t1; t1 = t2; t2 = w; }

			if (t2 < tMax)
				tMax = t2;
			if (t1 > tMin)
				tMin = t1;
			if (tMin > tMax)
				return false;

		}
		else{
			if (-e + aabb_min.z > 0.0f || -e + aabb_max.z < 0.0f)
				return false;
		}
	}

	intersection_distance = tMin;
	return true;

}
Пример #19
0
//--------------------------------------------------------------
// get avatar orientation under coordinate system
void SolarSystem::getCoordBasis(
  int coordSystem,
  mgMatrix4& basis)
{
  // get position of moon
  double angle = (2*PI*m_moonMonth)/360;
  mgPoint3 moonCenter(MOON_DISTANCE*sin(angle), 0, MOON_DISTANCE*cos(angle));

  // get coordinate system based on object
  mgPoint3 xaxis(1.0, 0.0, 0.0);
  mgPoint3 yaxis(0.0, 1.0, 0.0);
  mgPoint3 zaxis(0.0, 0.0, 1.0);

  switch (coordSystem)
  {
    case COORDS_PLANET:
      // y axis points away from center of planet
      yaxis = m_coordPosn;
      yaxis.normalize();

      // construct z axis orthonal to y
      zaxis = yaxis;
      zaxis.cross(mgPoint3(0.0, 1.0, 0.0));
      zaxis.normalize();

      // construct x axis
      xaxis = yaxis;
      xaxis.cross(zaxis);
      xaxis.normalize();
      break;

    case COORDS_MOON:
      // y axis points away from center of moon
      yaxis = m_coordPosn;
      yaxis.normalize();

      // construct z axis orthonal to y
      zaxis = yaxis;
      zaxis.cross(mgPoint3(0.0, 1.0, 0.0));
      zaxis.normalize();

      // construct x axis
      xaxis = yaxis;
      xaxis.cross(zaxis);
      xaxis.normalize();
      break;

    case COORDS_RING:
      // y axis points towards center of ring
      yaxis.x = -m_coordPosn.x;
      yaxis.z = -m_coordPosn.z;
      yaxis.y = 0.0;
      yaxis.normalize();

      // x axis is across the ring
      xaxis.x = 0.0; xaxis.y = 1.0; xaxis.z = 0.0;

      // construct z axis
      zaxis = xaxis;
      zaxis.cross(yaxis);
      zaxis.normalize();
      break;

    case COORDS_BELT:
      break;

    case COORDS_SPACE:
      // use default axis
      break;
  }

  // apply object surface orientation
  basis._11 = xaxis.x;
  basis._21 = xaxis.y;
  basis._31 = xaxis.z;
  basis._12 = yaxis.x;
  basis._22 = yaxis.y;
  basis._32 = yaxis.z;
  basis._13 = zaxis.x;
  basis._23 = zaxis.y;
  basis._33 = zaxis.z;
}
/*! The mouseMove is called by the viewer when the mouse is moved in the
    viewer and this handle is the active one.

    \param x the x-pos of the mouse (pixel)
    \param y the y-pos of the mouse (pixel)
 */
void PlaneMoveManipulator::mouseMove(const Int16 x,
                            const Int16 y)
{
    SLOG << "==============================" << endLog;
    SLOG << "PlaneMoveManipulator::mouseMove() enter x=" << x << " y=" << y << endLog;

    // get the beacon's core (must be ComponentTransform) and it's center
    if( getTarget() == NULL )
    {
        SWARNING << "Handle has no target.\n";
        return;
        
    }
    // get transformation of beacon
    Transform *t = dynamic_cast<Transform *>(getTarget()->getCore());

    if( t == NULL )
    {
        SWARNING << "handled object has no parent transform!\n";
        return;
    }

    Vec3f      translation;       // for matrix decomposition
    Quaternion rotation;
    Vec3f      scaleFactor;
    Quaternion scaleOrientation;

    t->getMatrix().getTransform(translation, rotation, scaleFactor,
                                scaleOrientation);

    OSG::Line viewray;
    getViewport()->getCamera()->calcViewRay(viewray, x, y, *getViewport());

    SLOG << "Manipulator::mouseMove(): viewray: " << viewray << endLog;

    // Get manipulator axes into world space
    OSG::Matrix tm = getTarget()->getToWorld();
    
    Vec3f rot_axis;
    tm.multFull(Vec3f(0,1,0), rot_axis);

    Plane pl(rot_axis, getClickPoint());

    Pnt3f plpoint;
    
    if (pl.intersect(viewray, plpoint) == true) // Ignore moving out of the plane...
    {
        SLOG << "Manipulator::mouseMove(): plpoint: " << plpoint << endLog;
         
        Vec3f      trans = getBaseTranslation();
        Quaternion rot   = getBaseRotation();

        // Get manipulator axes into world space
        Vec3f xp,zp;

        tm.multFull(Vec3f(1,0,0), xp);
        tm.multFull(Vec3f(0,0,1), zp);
        
        if (getActiveSubHandle() == getHandleXNode())
        {
            Line xaxis(getClickPoint(), xp);
            Line zaxis(getClickPoint(), zp);

            Real32 fx = xaxis.getClosestPointT(plpoint);
            Real32 fz = zaxis.getClosestPointT(plpoint);

            SLOG << "Manipulator::mouseMove(): xaxis: " << xaxis << " zaxis: " << zaxis <<endLog;
            SLOG << "Manipulator::mouseMove(): fx: " << fx << " fz: " << fz <<endLog;
        
            // Alternative: transform hitpoint into manip space
            OSG::Matrix m = getTarget()->getToWorld();
            m.invert();
            
            Pnt3f mpoint;
            m.mult(plpoint, mpoint);
            
            SLOG << "Manipulator::mouseMove(): mpoint:" << mpoint << endLog;

            trans = trans + xp * fx + zp * fz;
        }
        else if (getActiveSubHandle() == getHandleZNode())
        {
            Pnt3f wcenter;
            
            tm.multFull(Pnt3f(0,getLength()[1],0), wcenter);
            
            Vec3f vclick, vcurrent;
            
            vclick = getClickPoint() - wcenter;
            vcurrent = plpoint - wcenter;
            
            vclick.normalize();
            vcurrent.normalize();
            
            Real32 a = vclick.enclosedAngle(vcurrent);
            
            SLOG << "Manipulator::mouseMove(): wcenter:" << wcenter << "" <<endLog;
            SLOG << "Manipulator::mouseMove(): vclick:" << vclick << " vcurrent:" << vcurrent <<endLog;
            SLOG << "Manipulator::mouseMove(): angle:" << a << " deg: " << osgRad2Degree(a) << endLog;
        }
        
        Matrix m;

        m.setTransform(trans, rot, scaleFactor, scaleOrientation);

        t->setMatrix(m);
        
    }

    setLastMousePos(Pnt2f(Real32(x), Real32(y)));
    updateHandleTransform();

    //SLOG << "Manipulator::mouseMove() leave\n" << std::flush;
}
Пример #21
0
bool MPUtil::RayOBBIntersection(
	DCCore::Point_3  vA,        // Ray origin, in world space
	DCCore::Point_3  vB,     // Ray direction (NOT target position!), in world space. Must be normalize()'d.
	DCCore::Point_3  aabb_min,          // Minimum X,Y,Z coords of the mesh when not transformed at all.
	DCCore::Point_3  aabb_max,          // Maximum X,Y,Z coords. Often aabb_min*-1 if your mesh is centered, but it's not always the case.
	const double* ModelMatrix,       // Transformation applied to the mesh (which will thus be also applied to its bounding box)
	float& intersection_distance // Output : distance between ray_origin and the intersection with the OBB
	)
{
	DCCore::Point_3  ray_origin = vA;      // Ray origin, in world space
	DCCore::Point_3  ray_direction ; 
	DCCore::Point_3 temp = (vB-vA);

	temp.Normalize();
	ray_direction = temp;
	// Intersection method from Real-Time Rendering and Essential Mathematics for Games

	float tMin = 0.0f;
	float tMax = 100000.0f;

	DCCore::Point_3  OBBposition_worldspace(0, 0, 0);

	DCCore::Point_3 delta = OBBposition_worldspace - ray_origin;

	// Test intersection with the 2 planes perpendicular to the OBB's X axis
	{
		DCCore::Point_3 xaxis(1, 0, 0);
		float e = xaxis.Dot(delta);
		float f = ray_direction.Dot(xaxis);

		if ( fabs(f) > 0.001f ){ // Standard case

			float t1 = (e+aabb_min.x)/f; // Intersection with the "left" plane
			float t2 = (e+aabb_max.x)/f; // Intersection with the "right" plane
			// t1 and t2 now contain distances betwen ray origin and ray-plane intersections

			// We want t1 to represent the nearest intersection, 
			// so if it's not the case, invert t1 and t2
			if (t1>t2){
				float w=t1;t1=t2;t2=w; // swap t1 and t2
			}

			// tMax is the nearest "far" intersection (amongst the X,Y and Z planes pairs)
			if ( t2 < tMax )
				tMax = t2;
			// tMin is the farthest "near" intersection (amongst the X,Y and Z planes pairs)
			if ( t1 > tMin )
				tMin = t1;

			// And here's the trick :
			// If "far" is closer than "near", then there is NO intersection.
			// See the images in the tutorials for the visual explanation.
			if (tMax < tMin )
				return false;

		}else{ // Rare case : the ray is almost parallel to the planes, so they don't have any "intersection"
			if(-e+aabb_min.x > 0.0f || -e+aabb_max.x < 0.0f)
				return false;
		}
	}


	// Test intersection with the 2 planes perpendicular to the OBB's Y axis
	// Exactly the same thing than above.
	{
		DCCore::Point_3 yaxis(0, 1, 0);
		float e = yaxis.Dot(delta);
		float f = ray_direction.Dot(yaxis);

		if ( fabs(f) > 0.001f ){

			float t1 = (e+aabb_min.y)/f;
			float t2 = (e+aabb_max.y)/f;

			if (t1>t2){float w=t1;t1=t2;t2=w;}

			if ( t2 < tMax )
				tMax = t2;
			if ( t1 > tMin )
				tMin = t1;
			if (tMin > tMax)
				return false;

		}else{
			if(-e+aabb_min.y > 0.0f || -e+aabb_max.y < 0.0f)
				return false;
		}
	}


	// Test intersection with the 2 planes perpendicular to the OBB's Z axis
	// Exactly the same thing than above.
	{
		DCCore::Point_3 zaxis(0, 0, 1);
		float e = zaxis.Dot(delta);
		float f = ray_direction.Dot(zaxis);

		if ( fabs(f) > 0.001f ){

			float t1 = (e+aabb_min.z)/f;
			float t2 = (e+aabb_max.z)/f;

			if (t1>t2){float w=t1;t1=t2;t2=w;}

			if ( t2 < tMax )
				tMax = t2;
			if ( t1 > tMin )
				tMin = t1;
			if (tMin > tMax)
				return false;

		}else{
			if(-e+aabb_min.z > 0.0f || -e+aabb_max.z < 0.0f)
				return false;
		}
	}

	intersection_distance = tMin;
	return true;

}
Пример #22
0
void CPropertiesCanvas::AddProperty(Property* p, wxPGProperty* parent_prop)
{
	switch(p->get_property_type()){
	case StringPropertyType:
		{
			wxPGProperty *new_prop = wxStringProperty(p->GetShortString(),wxPG_LABEL, ((PropertyString*)p)->m_initial_value);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p);
			if(p->m_highlighted)m_pg->SetPropertyBackgroundColour(new_prop->GetId(), wxColour(71, 141, 248));
		}
		break;
	case DoublePropertyType:
	case LengthPropertyType:
		{
		    wxString initial_value;
		    initial_value << ((PropertyDouble*)p)->m_initial_value;
			// wxPGProperty *new_prop = wxFloatProperty(p->GetShortString(),wxPG_LABEL, ((PropertyDouble*)p)->m_initial_value);
			wxPGProperty *new_prop = wxStringProperty(p->GetShortString(),wxPG_LABEL, initial_value);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p);
		}
		break;
	case IntPropertyType:
		{
			wxPGProperty *new_prop = wxIntProperty(p->GetShortString(),wxPG_LABEL, ((PropertyInt*)p)->m_initial_value);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p);
		}
		break;
	case ColorPropertyType:
		{
			HeeksColor& col = ((PropertyColor*)p)->m_initial_value;
			wxColour wcol(col.red, col.green, col.blue);
			wxPGProperty *new_prop = wxColourProperty(p->GetShortString(),wxPG_LABEL, wcol);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p);
		}
		break;
	case ChoicePropertyType:
		{
			wxArrayString array_string;
			std::list< wxString >::iterator It;
			for(It = ((PropertyChoice*)p)->m_choices.begin(); It != ((PropertyChoice*)p)->m_choices.end(); It++){
				array_string.Add(wxString(It->c_str()));
			}
			wxPGProperty *new_prop = wxEnumProperty(p->GetShortString(),wxPG_LABEL,array_string, ((PropertyChoice*)p)->m_initial_index);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p );
		}
		break;
	case VertexPropertyType:
		{
			wxPGProperty* new_prop = wxParentProperty(p->GetShortString(),wxPG_LABEL);
			Append( parent_prop, new_prop, p );
			double x[3];
			unsigned int number_of_axes = 3;
			if(((PropertyVertex*)p)->xyOnly())number_of_axes = 2;
			memcpy(x, ((PropertyVertex*)p)->m_x, number_of_axes*sizeof(double));
			if(((PropertyVertex*)p)->m_affected_by_view_units)
			{
				for(unsigned int i = 0; i<number_of_axes; i++)x[i] /= wxGetApp().m_view_units;
			}
            wxPGProperty* x_prop = wxFloatProperty(_("x"),wxPG_LABEL, x[0]);
            if(!p->property_editable())x_prop->SetFlag(wxPG_PROP_READONLY);
            Append( new_prop, x_prop, p );
			wxPGProperty* y_prop = wxFloatProperty(_("y"),wxPG_LABEL, x[1]);
			if(!p->property_editable())y_prop->SetFlag(wxPG_PROP_READONLY);
			Append( new_prop, y_prop, p );
			if(!((PropertyVertex*)p)->xyOnly())
			{
				wxPGProperty* z_prop = wxFloatProperty(_("z"),wxPG_LABEL, x[2]);
				if(!p->property_editable())z_prop->SetFlag(wxPG_PROP_READONLY);
				new_prop->SetFlag(wxPG_PROP_READONLY);
				Append( new_prop, z_prop, p );
			}
		}
		break;
	case TrsfPropertyType:
		{
			double x[3];
			extract(((PropertyTrsf*)p)->m_trsf.TranslationPart(), x);

			gp_Dir xaxis(1, 0, 0);
			xaxis.Transform(((PropertyTrsf*)p)->m_trsf);
			gp_Dir yaxis(0, 1, 0);
			yaxis.Transform(((PropertyTrsf*)p)->m_trsf);

			double vertical_angle = 0;
			double horizontal_angle = 0;
			double twist_angle = 0;
			CoordinateSystem::AxesToAngles(xaxis, yaxis, vertical_angle, horizontal_angle, twist_angle);

			wxPGProperty* new_prop = wxParentProperty(p->GetShortString(),wxPG_LABEL);
			Append( parent_prop, new_prop, p );
			wxPGProperty* x_prop = wxFloatProperty(_("x"),wxPG_LABEL,x[0]);
			if(!p->property_editable())x_prop->SetFlag(wxPG_PROP_READONLY);
			Append( new_prop, x_prop, p );
			wxPGProperty* y_prop = wxFloatProperty(_("y"),wxPG_LABEL,x[1]);
			if(!p->property_editable())y_prop->SetFlag(wxPG_PROP_READONLY);
			Append( new_prop, y_prop, p );
			wxPGProperty* z_prop = wxFloatProperty(_("z"),wxPG_LABEL,x[2]);
			if(!p->property_editable())z_prop->SetFlag(wxPG_PROP_READONLY);
			Append( new_prop, z_prop, p );
			wxPGProperty* v_prop = wxFloatProperty(_("vertical angle"),wxPG_LABEL,vertical_angle);
			if(!p->property_editable())v_prop->SetFlag(wxPG_PROP_READONLY);
			Append( new_prop, v_prop, p );
			wxPGProperty* h_prop = wxFloatProperty(_("horizontal angle"),wxPG_LABEL,horizontal_angle);
			if(!p->property_editable())h_prop->SetFlag(wxPG_PROP_READONLY);
			Append( new_prop, h_prop, p );
			wxPGProperty* t_prop = wxFloatProperty(_("twist angle"),wxPG_LABEL,twist_angle);
			if(!p->property_editable())t_prop->SetFlag(wxPG_PROP_READONLY);
			new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( new_prop, t_prop, p );
		}
		break;
	case CheckPropertyType:
		{
			wxPGProperty* new_prop = wxBoolProperty(p->GetShortString(),wxPG_LABEL, ((PropertyCheck*)p)->m_initial_value);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p );
			m_pg->SetPropertyAttribute(new_prop, wxPG_BOOL_USE_CHECKBOX, true);
		}
		break;
	case ListOfPropertyType:
		{
			wxPGProperty* new_prop = wxParentProperty(p->GetShortString(),wxPG_LABEL);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p );
			std::list< Property* >::iterator It;
			for(It = ((PropertyList*)p)->m_list.begin(); It != ((PropertyList*)p)->m_list.end(); It++){
				Property* p2 = *It;
				AddProperty(p2, new_prop);
			}
		}
		break;
	case FilePropertyType:
		{
			wxPGProperty *new_prop = wxFileProperty(p->GetShortString(),wxPG_LABEL, ((PropertyFile*)p)->m_initial_value);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p);
			if(p->m_highlighted)m_pg->SetPropertyBackgroundColour(new_prop->GetId(), wxColour(71, 141, 248));
		}
		break;
	case DirectoryPropertyType:
		{
			wxPGProperty *new_prop = wxDirProperty(p->GetShortString(),wxPG_LABEL, ((PropertyDir*)p)->m_initial_value);
			if(!p->property_editable())new_prop->SetFlag(wxPG_PROP_READONLY);
			Append( parent_prop, new_prop, p);
			if(p->m_highlighted)m_pg->SetPropertyBackgroundColour(new_prop->GetId(), wxColour(71, 141, 248));
		}
		break;
	}
}
Пример #23
0
out_slit()
{
    real xsky, ysky, vrad, inv_surden, sigma, mass;
    real xslit, yslit, xplt, yplt, sinpa, cospa;
    real m_max, v_min, v_max, s_max;	      /* local min/max */
    int    i, islit;
    Body *bp;

    for (islit=0; islit<nslit; islit++)     /* reset local variables */
	v0star[islit] = v1star[islit] = v2star[islit] = 0.0;
    m_max = v_min = v_max = s_max = 0.0;
    inv_surden = 1.0 / (slit_width*slit_cell);
    sinpa = sin(pa); cospa = cos(pa);

    for(bp=btab, i=0; i<nobj; bp++, i++) {      /* loop over all particles */
 	xsky = xvar(bp,tsnap,i);
 	ysky = yvar(bp,tsnap,i);
 	vrad = zvar(bp,tsnap,i);
 	mass = evar(bp,tsnap,i) * inv_surden;
 	
	xsky -= origin[0];			/* translate to slit origin */
	ysky -= origin[1];
	xslit = -cospa*ysky + sinpa*xsky;	/* and rotate to slit frame */
	yslit =  sinpa*ysky + cospa*xsky;	/* !!! check signs !!! */

	if (fabs(yslit) > 0.5*slit_width) 
	   continue;			/* not in slit */

	islit =  (xslit+0.5*slit_length)/slit_cell;
	if (islit<0 || islit>=nslit)
	   continue;			/* not in slit */

	v0star[islit] += mass;
	v1star[islit] += vrad * mass;
	v2star[islit] += sqr(vrad) * mass;
     } /*-- end particles loop --*/


     while (nsmooth-- > 0) {            	/* convolution */
     	dprintf (0,"Convolving with %d-length beam: ",lsmooth);
     	for (i=0; i<lsmooth; i++) 
            dprintf (0,"%f ",smooth[i]);
    	convolve (v0star, nslit, smooth, lsmooth);
    	convolve (v1star, nslit, smooth, lsmooth);
    	convolve (v2star, nslit, smooth, lsmooth);
     	dprintf (0,"\n");
    }
    	
    for (islit=0; islit<nslit; islit++) { /* moment analysis: M, MV and MV^2 */
	if (v0star[islit]==0.0)
	    continue;		/* no data - skip to next pixel */
	v1star[islit] /= v0star[islit];
	sigma = v2star[islit]/v0star[islit] - sqr(v1star[islit]);
	if (sigma<0.0) {        /* should never happen */
	    warning("islit=%d sigma^2=%e < 0 !!!\n",islit,sigma);
	    v2star[islit] = 0.0;
	    continue;		/* something really wrong */
	}
	v2star[islit] = sqrt(sigma);

	if (v0star[islit] > m_max)  m_max = v0star[islit];
	if (v1star[islit] < v_min)  v_min = v1star[islit];
	if (v1star[islit] > v_max)  v_max = v1star[islit];
	if (v2star[islit] > s_max)  s_max = v2star[islit];
	if (Qtab) {
	    xslit = islit*slit_cell;
	    printf ("%g %g %g %g\n",
			xslit,v0star[islit], v1star[islit], v2star[islit]);
	}
    } /* for(islit) */
 
    if (Qtab)
        return(0);

    plinit ("***", 0.0, 20.0, 0.0, 20.0);

	/* reset default autoscales to user supplied if necessary */
    if (mmax==0.0) mmax=m_max;
    if (vmin==0.0) vmin=v_min;
    if (vmax==0.0) vmax=v_max;
    if (smax==0.0) smax=s_max;
    dprintf (0,"mmax=%f vmin=%f vmax=%f smax=%f  reset to:\n",m_max,v_min,v_max,s_max);
    if (mmax==0) mmax=1;
    if (vmin==0 && vmax==0) vmax=1;
    if (smax==0) smax=1;
    dprintf (0,"mmax=%f vmin=%f vmax=%f smax=%f           \n",mmax, vmin, vmax, smax);
    
	/* general plot header */
    sprintf (plabel,"File: %s; var{%s,%s,%s,%s} slit{%s %s %s %s}",
		infile,getparam("xvar"),getparam("yvar"),
		getparam("zvar"),getparam("evar"),
		getparam("origin"),getparam("pa"),getparam("width"),
		getparam("length"),getparam("cell"));
		
    pltext (plabel,2.0,18.4, 0.32, 0.0);
#if 0
    if (*headline!=NULL)				/* identification */
	pltext (headline,2.0,19.0,0.25,0.0);
#endif

    xplot[0] = -0.5*slit_length;            /* PLOT1: upper panel */
    xplot[1] =  0.5*slit_length;
    sprintf(xlabel,"slit: {x=%s,y=%s}",getparam("xvar"),getparam("yvar"));

    yplot[0]=0.0; 
    yplot[1]=mmax;  
    strcpy (ylabel,"mass surface density");

    xaxis ( 2.0,12.0, 16.0, xplot, -7, xtrans,  NULL);
    xaxis ( 2.0,17.0, 16.0, xplot, -7, xtrans,  NULL);
    yaxis ( 2.0,12.0,  5.0, yplot, -3, ytransm, ylabel);
    yaxis (18.0,12.0,  5.0, yplot, -3, ytransm, NULL);

    for (islit=0; islit<nslit; islit++) {
	xplt = xtrans (-0.5*slit_length + (islit+0.5)*slit_cell);
	yplt = ytransm (v0star[islit]);
	plbox (xplt, yplt, SYMBOLSIZE);
    }
                                           
    yplot[0]=vmin;                      /* PLOT2: middle panel */
    yplot[1]=vmax;  
    strcpy (ylabel,"velocity");

    xaxis (2.0, 7.0, 16.0, xplot, -7, xtrans,   NULL);	/* line ?? */
    yaxis (2.0, 7.0,  5.0, yplot, -3, ytransv1, ylabel);
    yaxis (18.0,7.0,  5.0, yplot, -3, ytransv1, NULL);

    for (islit=0; islit<nslit; islit++) {
	xplt = xtrans (-0.5*slit_length + (islit+0.5)*slit_cell);
	yplt = ytransv1 (v1star[islit]);
	plcross (xplt, yplt, SYMBOLSIZE);
    }
    if (vmin<0.0 || vmax>0.0) {
       plltype (1,2);	/* dashed line at v=0 */
       plmove (xtrans(xplot[0]), ytransv1(0.0));
       plline (xtrans(xplot[1]), ytransv1(0.0));
       plltype (1,1);
    }

    yplot[0]=0.0;                       /* PLOT3: bottom panel */
    yplot[1]=smax; 
    strcpy (ylabel,"velocity dispersion");
    xaxis (2.0, 2.0, 16.0, xplot, -7, xtrans,   xlabel);
    yaxis (2.0, 2.0,  5.0, yplot, -3, ytransv2, ylabel);
    yaxis (18.0,2.0,  5.0, yplot, -3, ytransv2, NULL);

    for (islit=0; islit<nslit; islit++) {
	xplt = xtrans (-0.5*slit_length + (islit+0.5)*slit_cell);
	yplt = ytransv2 (v2star[islit]);
	plcross (xplt, yplt, -SYMBOLSIZE);
    }

    plstop();
}
Пример #24
0
bool Matrix::decompose(Vector3* scale, Quaternion* rotation, Vector3* translation) const
{
    if (translation)
    {
        // Extract the translation.
        translation->x = m[12];
        translation->y = m[13];
        translation->z = m[14];
    }

    // Nothing left to do.
    if (scale == NULL && rotation == NULL)
        return true;

    // Extract the scale.
    // This is simply the length of each axis (row/column) in the matrix.
    Vector3 xaxis(m[0], m[1], m[2]);
    float scaleX = xaxis.length();

    Vector3 yaxis(m[4], m[5], m[6]);
    float scaleY = yaxis.length();

    Vector3 zaxis(m[8], m[9], m[10]);
    float scaleZ = zaxis.length();

    // Determine if we have a negative scale (true if determinant is less than zero).
    // In this case, we simply negate a single axis of the scale.
    float det = determinant();
    if (det < 0)
        scaleZ = -scaleZ;

    if (scale)
    {
        scale->x = scaleX;
        scale->y = scaleY;
        scale->z = scaleZ;
    }

    // Nothing left to do.
    if (rotation == NULL)
        return true;

    // Scale too close to zero, can't decompose rotation.
    if (scaleX < MATH_TOLERANCE || scaleY < MATH_TOLERANCE || fabs(scaleZ) < MATH_TOLERANCE)
        return false;

    float rn;

    // Factor the scale out of the matrix axes.
    rn = 1.0f / scaleX;
    xaxis.x *= rn;
    xaxis.y *= rn;
    xaxis.z *= rn;

    rn = 1.0f / scaleY;
    yaxis.x *= rn;
    yaxis.y *= rn;
    yaxis.z *= rn;

    rn = 1.0f / scaleZ;
    zaxis.x *= rn;
    zaxis.y *= rn;
    zaxis.z *= rn;

    // Now calculate the rotation from the resulting matrix (axes).
    float trace = xaxis.x + yaxis.y + zaxis.z + 1.0f;

    if (trace > MATH_EPSILON)
    {
        float s = 0.5f / sqrt(trace);
        rotation->w = 0.25f / s;
        rotation->x = (yaxis.z - zaxis.y) * s;
        rotation->y = (zaxis.x - xaxis.z) * s;
        rotation->z = (xaxis.y - yaxis.x) * s;
    }
    else
    {
        // Note: since xaxis, yaxis, and zaxis are normalized, 
        // we will never divide by zero in the code below.
        if (xaxis.x > yaxis.y && xaxis.x > zaxis.z)
        {
            float s = 0.5f / sqrt(1.0f + xaxis.x - yaxis.y - zaxis.z);
            rotation->w = (yaxis.z - zaxis.y) * s;
            rotation->x = 0.25f / s;
            rotation->y = (yaxis.x + xaxis.y) * s;
            rotation->z = (zaxis.x + xaxis.z) * s;
        }
        else if (yaxis.y > zaxis.z)
        {
            float s = 0.5f / sqrt(1.0f + yaxis.y - xaxis.x - zaxis.z);
            rotation->w = (zaxis.x - xaxis.z) * s;
            rotation->x = (yaxis.x + xaxis.y) * s;
            rotation->y = 0.25f / s;
            rotation->z = (zaxis.y + yaxis.z) * s;
        }
        else
        {
            float s = 0.5f / sqrt(1.0f + zaxis.z - xaxis.x - yaxis.y );
            rotation->w = (xaxis.y - yaxis.x ) * s;
            rotation->x = (zaxis.x + xaxis.z ) * s;
            rotation->y = (zaxis.y + yaxis.z ) * s;
            rotation->z = 0.25f / s;
        }
    }

    return true;
}
Пример #25
0
//--------------------------------------------------------------
// render the planet
void Planet::render(
  int graphicsWidth,
  int graphicsHeight,
  double angle)
{
  // if shader didn't compile, nothing we can do
  if (m_planetShader == 0)
    return;

  double atmos = 20.0;
  double radius = 1200.0;

  double eyeDist = m_eyePt.length()/radius;
  double a = 1.0;
  if (eyeDist < a)
    return;  // below surface, nothing to do 
  double b = sqrt(eyeDist*eyeDist - a*a);
  double h = (a*b)/eyeDist;
  double m = (a*a)/eyeDist;

  h += atmos/radius;

  // x axis from planet center towards eye
  mgPoint3 xaxis(m_eyePt);
  xaxis.normalize();

  // build y axis
  mgPoint3 yaxis(xaxis);
  yaxis.cross(mgPoint3(0.0, 1.0, 0.0));
  yaxis.normalize();

  mgPoint3 zaxis(yaxis);
  zaxis.cross(xaxis);
  zaxis.normalize();

  mgMatrix4 transform;
  transform._11 = xaxis.x;
  transform._12 = xaxis.y;
  transform._13 = xaxis.z;
  transform._21 = yaxis.x;
  transform._22 = yaxis.y;
  transform._23 = yaxis.z;
  transform._31 = zaxis.x;
  transform._32 = zaxis.y;
  transform._33 = zaxis.z;
  
  VertexPlanet tl, tr, bl, br;

  mgPoint3 pt;
  transform.mapPt(m, -h, h, pt.x, pt.y, pt.z);
  tl.setPoint(radius*pt.x, radius*pt.y, radius*pt.z);

  transform.mapPt(m, h, h, pt.x, pt.y, pt.z);
  tr.setPoint(radius*pt.x, radius*pt.y, radius*pt.z);

  transform.mapPt(m, -h, -h, pt.x, pt.y, pt.z);
  bl.setPoint(radius*pt.x, radius*pt.y, radius*pt.z);

  transform.mapPt(m, h, -h, pt.x, pt.y, pt.z);
  br.setPoint(radius*pt.x, radius*pt.y, radius*pt.z);

  // inverse of world transform
  mgMatrix4 model;
  model.rotateYDeg(-angle);

  mgPoint3 lightDir(1.0, 0.25, 0.0);
  lightDir.normalize();

  mgPoint3 modelLightDir;
  model.mapPt(lightDir, modelLightDir);
  transform.multiply(model);

  mgPoint3 modelEye; 
  transform.mapPt(eyeDist, 0.0, 0.0, modelEye.x, modelEye.y, modelEye.z);

  transform.mapPt(m, -h, h, pt.x, pt.y, pt.z);
  tl.setModelPoint(pt.x, pt.y, pt.z);

  transform.mapPt(m, h, h, pt.x, pt.y, pt.z);
  tr.setModelPoint(pt.x, pt.y, pt.z);

  transform.mapPt(m, -h, -h, pt.x, pt.y, pt.z);
  bl.setModelPoint(pt.x, pt.y, pt.z);

  transform.mapPt(m, h, -h, pt.x, pt.y, pt.z);
  br.setModelPoint(pt.x, pt.y, pt.z);

  mgMatrix4 viewMatrix;
  viewMatrix.translate(-m_eyePt.x, -m_eyePt.y, -m_eyePt.z);
  viewMatrix.multiply(m_eyeMatrix);

  mgMatrix4 worldProjection;
  createProjection(worldProjection, graphicsWidth, graphicsHeight);

  mgMatrix4 mvpMatrix(viewMatrix);
  mvpMatrix.multiply(worldProjection);

  setupShader(mvpMatrix, modelEye, modelLightDir);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_CUBE_MAP, m_surfaceTexture); 
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_CUBE_MAP, m_cloudsTexture); 

  glBindVertexArray(m_vertexArray);
  glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);

  VertexPlanet data[6];
  data[0] = tl;
  data[1] = tr;
  data[2] = bl;
  data[3] = bl;
  data[4] = tr;
  data[5] = br;
  int vertexSize = sizeof(VertexPlanet);
  int count = 6;
  glBufferData(GL_ARRAY_BUFFER, vertexSize * count, data, GL_DYNAMIC_DRAW);

  glDrawArrays(GL_TRIANGLES, 0, count);

  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);
  glActiveTexture(GL_TEXTURE0);
}