Пример #1
0
	Matrix4 FPSview(Vector3 cameraPosition, float pitch, float yaw)
	{
		// If the pitch and yaw angles are in degrees,
		// they need to be converted to radians. Here
		// I assume the values are already converted to radians.
		float cosPitch = cos(pitch);
		float sinPitch = sin(pitch);
		float cosYaw = cos(yaw);
		float sinYaw = sin(yaw);
 
		Vector3 xaxis( cosYaw, 0, -sinYaw);
		Vector3 yaxis( sinYaw * sinPitch, cosPitch, cosYaw * sinPitch);
		Vector3 zaxis( sinYaw * cosPitch, -sinPitch, cosPitch * cosYaw);
 
		// Create a 4x4 view matrix from the right, up, forward and eye position vectors
		Matrix4 viewMatrix 
		( 
		    Vector4(				   xaxis.x,					 yaxis.x,				   zaxis.x,     0 ),
		    Vector4(				   xaxis.y,					 yaxis.y,				   zaxis.y,     0 ),
		    Vector4(				   xaxis.z,					 yaxis.z,				   zaxis.z,     0 ),
		    Vector4(-xaxis.dot(cameraPosition), -yaxis.dot(cameraPosition), -zaxis.dot(cameraPosition), 1 )
		);
		 
		return viewMatrix;
	}
Пример #2
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 = deviceManager->getAnyDevice();

  if (device) {

    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];

    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 ) ) );
  }

  *successptr = success;
}
Пример #3
0
nemo_main()
{
    real xtrans(real), ytrans(real);

    formalaxis = getbparam("formalaxis");
    xlabdn = getdparam("xlabdn");
    xszlab = getdparam("xszlab");
    ylablf = getdparam("ylablf");
    yszlab = getdparam("yszlab");
    plinit("***", 0.0, 20.0, 0.0, 20.0);
    xaxis( 2.0,  2.0, 16.0, xrange, -3, xtrans, "x");
    xaxis( 2.0, 18.0, 16.0, xrange, -3, xtrans, NULL);
    yaxis( 2.0,  2.0, 16.0, yrange, -7, ytrans, "y");
    yaxis(18.0,  2.0, 16.0, yrange, -7, ytrans, NULL);
    plstop();
}
Пример #4
0
Vector3d Track::getUp(double t) const
{	
	//Vector3d vup = getNonNormalizedNormalVector(t);
	//assert (vup.x==vup.x && vup.y==vup.y && vup.z==vup.z); // Ensure is not NAN
	//if (vup.length() < VECTORLENGHTMINIMUM) return Vector3d(0,0,0);
	//return vup;

	 // Find out in which interval we are on the spline
    int p = (int)(t / delta_t);
	double lt = (t - delta_t*(double)p) / delta_t;
	#define BOUNDS2(pp) { if (pp < 0) pp = 0; else if (pp >= (int)rotations.size()-2) pp = rotations.size() - 2; }
	BOUNDS2(p);
	//double angle0 = rotations[p];
	//double angle1 = rotations[p+1];
	//double angleinterpolated = (angle1-angle0)*lt;

	// TODO: if y axis and tangent is almost parallel, we get gimbal lock. FIX!
	Vector3d yaxis(0,1,0);
	Vector3d tangent = getTangentVector(t);
	
	// Find the unit right/binormal vector in the right-hand system (tangent, (0,1,0), right).
	// Note that this will lead to problems if the tangent vector is very close to +- (0,1,0)
	Vector3d right = tangent.cross(yaxis).normalizedCopy();
	Vector3d up = -tangent.cross(right).normalizedCopy();
	
	// Interpolate the angle linearly between this and next point
	double angleInterpolated = rotations[p] + (rotations[p+1]-rotations[p]) * lt;
	up = cos(angleInterpolated)*up + sin(angleInterpolated)*right;
	return up.normalizedCopy();

}
Пример #5
0
int yaxis(node *temp)
{
	if(temp==NULL)
		return NULL;
	if(temp->right!=NULL)
	{
		printf("%d\n",temp->data);
		yaxis(temp->right);
	}
	else
	{
		printf("%d\n",temp->data);
		yaxis(temp->left);
	}



}
Пример #6
0
SbRotation
SoBillboard::calculateRotation(SoState *state)
{
    SbRotation rot;
#ifdef INVENTORRENDERER
    const SbViewVolume &viewVolume = SoViewVolumeElement::get(state);

    if (SbVec3f(0.0f, 0.0f, 0.0f) == axis.getValue())
    {
        rot = viewVolume.getAlignRotation();
    }
#else
    const SbMatrix &mm = SoModelMatrixElement::get(state);
    SbMatrix imm = mm.inverse();

    SbVec3f toviewer;
    SbVec3f cameray(0.0f, 1.0f, 0.0f);
    const SbViewVolume &vv = SoViewVolumeElement::get(state);

    toviewer = -vv.getProjectionDirection();
    imm.multDirMatrix(toviewer, toviewer);

    (void)toviewer.normalize();

    SbVec3f rotaxis = this->axis.getValue();

    if (rotaxis == SbVec3f(0.0f, 0.0f, 0.0f))
    {
        // 1. Compute the billboard-to-viewer vector.
        // 2. Rotate the Z-axis of the billboard to be collinear with the
        //    billboard-to-viewer vector and pointing towards the viewer's position.
        // 3. Rotate the Y-axis of the billboard to be parallel and oriented in the
        //    same direction as the Y-axis of the viewer.
        rot.setValue(SbVec3f(0.f, 0.0f, 1.0f), toviewer);
        SbVec3f viewup = vv.getViewUp();
        imm.multDirMatrix(viewup, viewup);

        SbVec3f yaxis(0.0f, 1.0f, 0.0f);
        rot.multVec(yaxis, yaxis);
        SbRotation rot2(yaxis, viewup);

        SbVec3f axis;
        float angle;
        rot.getValue(axis, angle);
        rot2.getValue(axis, angle);
        rot = rot * rot2;
        //SoModelMatrixElement::rotateBy(state, (SoNode*) this, rot);
    }
#endif
    else
    {
        fprintf(stderr, "SoBillboard: axis != (0.0, 0.0, 0.0) not implemented\n");
    }

    return rot;
}
Пример #7
0
void GUI3DDirectionArrow::handleMsg( ZMsg *msg ) {
	if( zmsgIs(type,MouseClickOn) && zmsgIs(which,L) && zmsgIs(dir,D) ) {
		startDrag = FVec2( zmsgF(localX), zmsgF(localY) );
		startDragMat = mat;
		requestExclusiveMouse( 1, 1 );
		zMsgUsed();
		sendMsg();
	}
	else if( zmsgIs(type,MouseReleaseDrag) ) {
		requestExclusiveMouse( 1, 0 );
		zMsgUsed();
	}
	else if( zmsgIs(type,MouseDrag) ) {
		FVec2 mouseDelta( zmsgF(localX), zmsgF(localY) );
		mouseDelta.sub( startDrag );
		mouseDelta.mul( 0.03f );
		mat = startDragMat;
		FMat4 eye = mat;
		eye.setTrans( FVec3::Origin );
		eye.inverse();
		FVec3 yEye = eye.mul( FVec3::YAxisMinus );
		FVec3 xEye = eye.mul( FVec3::XAxis );
		mat.cat( rotate3D( yEye, mouseDelta.x ) );
		mat.cat( rotate3D( xEye, mouseDelta.y ) );
		zMsgUsed();
		sendMsg();
	}
	else if( zmsgIs(type,SetDir) ) {
		FVec3 xaxis( zmsgF(x), zmsgF(y), zmsgF(z) );
		xaxis.mul(-1.f);
		FVec3 yaxis( 0.f, 1.f, 0.f );
		yaxis.cross( xaxis );
		FVec3 zaxis = yaxis;
		zaxis.cross( xaxis );
		xaxis.normalize();
		yaxis.normalize();
		zaxis.normalize();
		mat.m[0][0] = xaxis.x;
		mat.m[0][1] = xaxis.y;
		mat.m[0][2] = xaxis.z;
		mat.m[0][3] = 0.f;
		mat.m[1][0] = yaxis.x;
		mat.m[1][1] = yaxis.y;
		mat.m[1][2] = yaxis.z;
		mat.m[1][3] = 0.f;
		mat.m[2][0] = zaxis.x;
		mat.m[2][1] = zaxis.y;
		mat.m[2][2] = zaxis.z;
		mat.m[2][3] = 0.f;
		mat.m[3][0] = 0.f;
		mat.m[3][1] = 0.f;
		mat.m[3][2] = 0.f;
		mat.m[3][3] = 1.f;
	}
}
Пример #8
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();
}
Пример #9
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();
}
Пример #10
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;
}
Пример #11
0
int _tmain(int argc, _TCHAR* argv[])
{
	
	root=insert(20);
	root->left=insert(13);
	//root->right=insert(40);
	root->left->left=insert(3);
	root->left->right=NULL;
	//root->right->left=NULL;
	//root->right->right=insert(45);
	root->left->left->left=NULL;
	root->left->left->right=insert(8);
	//root->right->right->left=insert(43);
	//root->right->right->right=NULL;
	printf("the inorder traversal of the above tree is\n");
	inorder(root);
	yaxis(root);
	return 0;
}
Пример #12
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();

}
Пример #13
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();
}
Пример #14
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);
}
Пример #15
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();
}
Пример #16
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;

}
Пример #17
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;
}
Пример #18
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();
}
Пример #19
0
bool QuaternionTest::test()
{
    // ctor tests
    Quaterniond tquaternion_test( 8., 1., 6., 3. );
    for ( size_t i = 0; i < 4; ++i )
    {
        if ( _quaternion.wxyz[i] != tquaternion_test.wxyz[i] )
        {
            cout << "test: Quaternion::Quaternion( ... ) failed!" << endl;
            failed();
            assert( 0 );            
        }
	}
	
	Quaterniond squaternion_test( 8., Vector3d( 1., 6., 3. ) );
	for ( size_t i = 0; i < 4; ++i )
	{
		if ( _quaternion.wxyz[i] != squaternion_test.wxyz[i] )
		{
            cout << "test: Quaternion::Quaternion( ... ) failed!" << endl;
            failed();
            assert( 0 );            
        }
	}
	
	Quaterniond uquaternion_test( Matrix3d( 1., 0., 0., 0., 0., 1., 0., -1., 0. ) );
	for ( size_t i = 0; i < 4; ++i )
	{
		if ( i == 0  )
			if ( uquaternion_test.wxyz[0] != ( sqrt( 2. ) / 2. ) )
				{
					cout << "test: Quaternion::Quaternion( ... ) failed!" << endl;
					failed();
					assert( 0 );            
				}
		if ( i == 1  )
			if ( uquaternion_test.wxyz[1] != - ( 1 / sqrt( 2. ) ) )
				{
					cout << "test: Quaternion::Quaternion( ... ) failed!" << endl;
					failed();
					assert( 0 );            
				}
		if ( i != 0 && i != 1 )
			if ( uquaternion_test.wxyz[i] != 0. )
				{
					cout << "test: Quaternion::Quaternion( ... ) failed!" << endl;
					failed();
					assert( 0 );            
				}

	}
	
	// set test
	uquaternion_test.set ( 8., 1., 6., 3. );
	for ( size_t i = 0; i < 4; ++i )
	{
		if ( _quaternion.wxyz[i] != uquaternion_test.wxyz[i] )
		{
            cout << "test: Quaternion::set( ... ) failed!" << endl;
            failed();
            assert( 0 );            
        }
	}
	 
	// operator = tests
	tquaternion_test = 1.;
	Quaterniond IDENTITY( 1., 0., 0., 0. );
	for ( size_t i = 0; i < 4; ++i )
	{
		if ( IDENTITY.wxyz[i] != tquaternion_test.wxyz[i] )
		{
            cout << "test: Quaternion::operator=( ... ) failed!" << endl;
            failed();
            assert( 0 );            
        }
	}
	
	uquaternion_test = _quaternion;
	for ( size_t i = 0; i < 4; ++i )
	{
		if ( _quaternion.wxyz[i] != uquaternion_test.wxyz[i] )
		{
            cout << "test: Quaternion::operator=( ... ) failed!" << endl;
            failed();
            assert( 0 );            
        }
	}
	
	//quaternion == / != tests
	if ( tquaternion_test != 1. )
    {
        cout << "test: Quaternion::operator ==() / !=() failed!" << endl;
        failed();
        assert( 0 );
    }  
	
	if ( _quaternion != uquaternion_test )
    {
        cout << "test: Quaternion::operator ==() / !=() failed!" << endl;
        failed();
        assert( 0 );
    }  
	
	if ( _quaternion == tquaternion_test )
	{
        cout << "test: Quaternion::operator ==() / !=() failed!" << endl;
        failed();
        assert( 0 );
    }  
	
	//abs() test
	if ( _quaternion.abs() !=  sqrt( 110 ) )
    {
        cout << "test: Quaternion::abs() failed!" << endl;
        failed();
        assert( 0 );
    }  
	
	//conjug() test
	Quaterniond cquaternion_test( 8., -1., -6., -3. );
	if ( _quaternion.conjug() != cquaternion_test )
	    {
        cout << "test: Quaternion::conjug() failed!" << endl;
        failed();
        assert( 0 );
    } 
	
	//quaternion/scalar tests
	tquaternion_test.set( 1., 2., 3., 4. );
	Quaterniond vquaternion_test( 3., 6., 9., 12. );
	tquaternion_test = tquaternion_test * 3.0;
	if ( tquaternion_test - vquaternion_test != 0.0 )
	{
        cout << "test: Quaternion::operator*/( scalar ) failed!" << endl;
		cout << tquaternion_test << endl;
        failed();
        assert( 0 );
    }  
	
	// quaternion/quaternion tests
	tquaternion_test.set( 1., 2., 3., 4. );
	if ( tquaternion_test + tquaternion_test + tquaternion_test -vquaternion_test != 0.0f  )
	{
        cout << "test: Quaternion::operator+-( quaternion ) failed!" << endl;
        failed();
        assert( 0 );
    }  
	
	squaternion_test.set( -24., 2., 28., 44 ); 
	
	if ( squaternion_test != tquaternion_test * uquaternion_test )
	{
        cout << "test: Quaternion::operator*( quaternion ) failed!" << endl;
        failed();
        assert( 0 );
    }  
	
	Quaterniond rquaternion_test( 8. / 110., -1. / 110., -6. / 110., -3. / 110. );
	
	if ( _quaternion.invert() != rquaternion_test )
	{
		cout << "test: Quaternion::invert() failed!" << endl;
        failed();
        assert( 0 );
	}
	
	if ( tquaternion_test.dot( _quaternion ) != 40. )
	{
		cout << "test: Quaternion::dot( quaternion ) failed!" << endl;
        failed();
        assert( 0 );
	}
		
	Vector3d vector3_test( -30., -4., 18. );
	if ( tquaternion_test.cross( _quaternion ) != vector3_test )
	{
		cout << "test: Quaternion::cross( quaternion ) failed!" << endl;
        failed();
        assert( 0 );
	}
	
	Vector3d yaxis( 1., 0., 0. );
	Quaterniond svector3_test( 0., 18., -30., -4. );
	Quaterniond result_test( _quaternion.rotate( M_PI / 2.f, yaxis, vector3_test ) );	
	if ( abs( result_test.abs() - svector3_test.abs() ) > 1e-13 )
	{
		cout << "test: Quaternion::rotate( T, Vector3, Vector3 ) failed!" << endl;
		failed();
		assert( 0 );
	}

    if ( ok )
        cout << "Quaternion: all tests passed!" << endl;
		
	return ok;
}
Пример #20
0
RagDoll::RagDoll (btDynamicsWorld* ownerWorld, const btVector3& positionOffset, 
				  btScalar scale_ragdoll)	: m_ownerWorld (ownerWorld) {

	// setup colors
	for (int i = 0; i < BODYPART_COUNT; i++) {
//		ofVec4f col = ofVec4f(ofRandom(0.7, 1.0),
//								ofRandom(0.5, 1.0),
//								ofRandom(0.7, 1.0),
//								1.0);
		ofVec4f col = ofVec4f(0.7,
								0.7,
								0.7,
								1.0);		
		colors.push_back(col);
	}

	// Setup the geometry
	m_shapes[BODYPART_PELVIS] = new btCapsuleShape(btScalar(scale_ragdoll*0.15), btScalar(scale_ragdoll*0.20));
	m_shapes[BODYPART_SPINE] = new btCapsuleShape(btScalar(scale_ragdoll*0.15), btScalar(scale_ragdoll*0.28));
	m_shapes[BODYPART_HEAD] = new btCapsuleShape(btScalar(scale_ragdoll*0.10), btScalar(scale_ragdoll*0.05));
	m_shapes[BODYPART_LEFT_UPPER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.07), btScalar(scale_ragdoll*0.45));
	m_shapes[BODYPART_LEFT_LOWER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.37));
	m_shapes[BODYPART_RIGHT_UPPER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.07), btScalar(scale_ragdoll*0.45));
	m_shapes[BODYPART_RIGHT_LOWER_LEG] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.37));
	m_shapes[BODYPART_LEFT_UPPER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.33));
	m_shapes[BODYPART_LEFT_LOWER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.04), btScalar(scale_ragdoll*0.25));
	m_shapes[BODYPART_RIGHT_UPPER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.05), btScalar(scale_ragdoll*0.33));
	m_shapes[BODYPART_RIGHT_LOWER_ARM] = new btCapsuleShape(btScalar(scale_ragdoll*0.04), btScalar(scale_ragdoll*0.25));

	// Setup all the rigid bodies
	btTransform offset; offset.setIdentity();
	offset.setOrigin(positionOffset);
	
	// fix the rotation
	double angle = (double)180*(TWO_PI/360.0);
	btVector3 zaxis(0.0,0.0,1.0);
	btQuaternion zquat(zaxis,angle);
	btVector3 yaxis(0.0,1.0,0.0);
	btQuaternion yquat(yaxis,angle);
	btQuaternion quat = zquat*yquat;	
	offset.setRotation(quat);	

	btTransform transform;
	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.), btScalar(0.)));
	m_bodies[BODYPART_PELVIS] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_PELVIS]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.2), btScalar(0.)));
	m_bodies[BODYPART_SPINE] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_SPINE]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.), btScalar(scale_ragdoll*1.6), btScalar(0.)));
	m_bodies[BODYPART_HEAD] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_HEAD]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(0.65*scale_ragdoll),
btScalar(0.)));
	m_bodies[BODYPART_LEFT_UPPER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(0.2*scale_ragdoll), btScalar(0.)));
	m_bodies[BODYPART_LEFT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(0.65*scale_ragdoll), btScalar(0.)));
	m_bodies[BODYPART_RIGHT_UPPER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(0.2*scale_ragdoll), btScalar(0.)));
	m_bodies[BODYPART_RIGHT_LOWER_LEG] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_LEG]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.35*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
	transform.getBasis().setEulerZYX(0,0,SIMD_HALF_PI);
	m_bodies[BODYPART_LEFT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_UPPER_ARM]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(-0.7*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
	transform.getBasis().setEulerZYX(0,0,SIMD_HALF_PI);
	m_bodies[BODYPART_LEFT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_LEFT_LOWER_ARM]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.35*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
	transform.getBasis().setEulerZYX(0,0,-SIMD_HALF_PI);
	m_bodies[BODYPART_RIGHT_UPPER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_UPPER_ARM]);

	transform.setIdentity();
	transform.setOrigin(btVector3(btScalar(0.7*scale_ragdoll), btScalar(1.45*scale_ragdoll), btScalar(0.)));
	transform.getBasis().setEulerZYX(0,0,-SIMD_HALF_PI);
	m_bodies[BODYPART_RIGHT_LOWER_ARM] = localCreateRigidBody(btScalar(1.), offset*transform, m_shapes[BODYPART_RIGHT_LOWER_ARM]);

	// Setup some damping on the m_bodies
	for (int i = 0; i < BODYPART_COUNT; ++i)
	{
		m_bodies[i]->setDamping(0.05, 0.85);
		m_bodies[i]->setDeactivationTime(0.8);
		m_bodies[i]->setSleepingThresholds(1.6, 2.5);
	}

///////////////////////////// SETTING THE CONSTRAINTS /////////////////////////////////////////////7777
	// Now setup the constraints
	btGeneric6DofConstraint * joint6DOF;
	btTransform localA, localB;
	bool useLinearReferenceFrameA = true;
/// ******* SPINE HEAD ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(0.), btScalar(0.30*scale_ragdoll), btScalar(0.)));

		localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.)));

		joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_HEAD], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.3f,-SIMD_EPSILON,-SIMD_PI*0.3f));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.5f,SIMD_EPSILON,SIMD_PI*0.3f));
#endif
		m_joints[JOINT_SPINE_HEAD] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_SPINE_HEAD], true);
	}
/// *************************** ///




/// ******* LEFT SHOULDER ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(-0.2*scale_ragdoll), btScalar(0.15*scale_ragdoll), btScalar(0.)));

		localB.getBasis().setEulerZYX(SIMD_HALF_PI,0,-SIMD_HALF_PI);
		localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.18*scale_ragdoll), btScalar(0.)));

		joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_LEFT_UPPER_ARM], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.8f,-SIMD_EPSILON,-SIMD_PI*0.5f));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.8f,SIMD_EPSILON,SIMD_PI*0.5f));
#endif
		m_joints[JOINT_LEFT_SHOULDER] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_SHOULDER], true);
	}
/// *************************** ///


/// ******* RIGHT SHOULDER ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(0.2*scale_ragdoll), btScalar(0.15*scale_ragdoll), btScalar(0.)));
		localB.getBasis().setEulerZYX(0,0,SIMD_HALF_PI);
		localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.18*scale_ragdoll), btScalar(0.)));
		joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_SPINE], *m_bodies[BODYPART_RIGHT_UPPER_ARM], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else

		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.8f,-SIMD_EPSILON,-SIMD_PI*0.5f));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.8f,SIMD_EPSILON,SIMD_PI*0.5f));
#endif
		m_joints[JOINT_RIGHT_SHOULDER] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_SHOULDER], true);
	}
/// *************************** ///

/// ******* LEFT ELBOW ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18*scale_ragdoll), btScalar(0.)));
		localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.)));
		joint6DOF =  new btGeneric6DofConstraint (*m_bodies[BODYPART_LEFT_UPPER_ARM], *m_bodies[BODYPART_LEFT_LOWER_ARM], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7,SIMD_EPSILON,SIMD_EPSILON));
#endif
		m_joints[JOINT_LEFT_ELBOW] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_ELBOW], true);
	}
/// *************************** ///

/// ******* RIGHT ELBOW ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(0.), btScalar(0.18*scale_ragdoll), btScalar(0.)));
		localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.14*scale_ragdoll), btScalar(0.)));
		joint6DOF =  new btGeneric6DofConstraint (*m_bodies[BODYPART_RIGHT_UPPER_ARM], *m_bodies[BODYPART_RIGHT_LOWER_ARM], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7,SIMD_EPSILON,SIMD_EPSILON));
#endif

		m_joints[JOINT_RIGHT_ELBOW] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_ELBOW], true);
	}
/// *************************** ///


/// ******* PELVIS ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.getBasis().setEulerZYX(0,SIMD_HALF_PI,0);
		localA.setOrigin(btVector3(btScalar(0.), btScalar(0.15*scale_ragdoll), btScalar(0.)));
		localB.getBasis().setEulerZYX(0,SIMD_HALF_PI,0);
		localB.setOrigin(btVector3(btScalar(0.), btScalar(-0.15*scale_ragdoll), btScalar(0.)));
		joint6DOF =  new btGeneric6DofConstraint (*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_SPINE], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_PI*0.2,-SIMD_EPSILON,-SIMD_PI*0.3));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.2,SIMD_EPSILON,SIMD_PI*0.6));
#endif
		m_joints[JOINT_PELVIS_SPINE] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_PELVIS_SPINE], true);
	}
/// *************************** ///

/// ******* LEFT HIP ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(-0.18*scale_ragdoll), btScalar(-0.10*scale_ragdoll), btScalar(0.)));

		localB.setOrigin(btVector3(btScalar(0.), btScalar(0.225*scale_ragdoll), btScalar(0.)));

		joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_LEFT_UPPER_LEG], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_HALF_PI*0.5,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_HALF_PI*0.8,SIMD_EPSILON,SIMD_HALF_PI*0.6f));
#endif
		m_joints[JOINT_LEFT_HIP] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_HIP], true);
	}
/// *************************** ///


/// ******* RIGHT HIP ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(0.18*scale_ragdoll), btScalar(-0.10*scale_ragdoll), btScalar(0.)));
		localB.setOrigin(btVector3(btScalar(0.), btScalar(0.225*scale_ragdoll), btScalar(0.)));

		joint6DOF = new btGeneric6DofConstraint(*m_bodies[BODYPART_PELVIS], *m_bodies[BODYPART_RIGHT_UPPER_LEG], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_HALF_PI*0.5,-SIMD_EPSILON,-SIMD_HALF_PI*0.6f));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_HALF_PI*0.8,SIMD_EPSILON,SIMD_EPSILON));
#endif
		m_joints[JOINT_RIGHT_HIP] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_HIP], true);
	}
/// *************************** ///


/// ******* LEFT KNEE ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225*scale_ragdoll), btScalar(0.)));
		localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185*scale_ragdoll), btScalar(0.)));
		joint6DOF =  new btGeneric6DofConstraint (*m_bodies[BODYPART_LEFT_UPPER_LEG], *m_bodies[BODYPART_LEFT_LOWER_LEG], localA, localB,useLinearReferenceFrameA);
//
#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON));
#endif
		m_joints[JOINT_LEFT_KNEE] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_LEFT_KNEE], true);
	}
/// *************************** ///

/// ******* RIGHT KNEE ******** ///
	{
		localA.setIdentity(); localB.setIdentity();

		localA.setOrigin(btVector3(btScalar(0.), btScalar(-0.225*scale_ragdoll), btScalar(0.)));
		localB.setOrigin(btVector3(btScalar(0.), btScalar(0.185*scale_ragdoll), btScalar(0.)));
		joint6DOF =  new btGeneric6DofConstraint (*m_bodies[BODYPART_RIGHT_UPPER_LEG], *m_bodies[BODYPART_RIGHT_LOWER_LEG], localA, localB,useLinearReferenceFrameA);

#ifdef RIGID
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_EPSILON,SIMD_EPSILON,SIMD_EPSILON));
#else
		joint6DOF->setAngularLowerLimit(btVector3(-SIMD_EPSILON,-SIMD_EPSILON,-SIMD_EPSILON));
		joint6DOF->setAngularUpperLimit(btVector3(SIMD_PI*0.7f,SIMD_EPSILON,SIMD_EPSILON));
#endif
		m_joints[JOINT_RIGHT_KNEE] = joint6DOF;
		m_ownerWorld->addConstraint(m_joints[JOINT_RIGHT_KNEE], true);
	}
/// *************************** ///

}
Пример #21
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]);
    }
}
Пример #22
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
}
Пример #23
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");
}
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;

}
Пример #25
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;
}
Пример #26
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;
	}
}
Пример #27
0
bool quaternion_test::run()
{
    bool global_ok = true;
    quaternion< double > q;
    double QData[] = { 1., 6., 3., 8.  };
    for( size_t index = 0; index < 4; ++index )
    {
        q.array[ index ] = QData[ index ];
    }

    // operator==/!= tests
    {
        bool ok = true;
        quaterniond qq, qqq;
        qq.array[ 0 ] = qqq.array[ 0 ] = 1.0;
        qq.array[ 1 ] = qqq.array[ 1 ] = 6.0;
        qq.array[ 2 ] = qqq.array[ 2 ] = 3.0;
        qq.array[ 3 ] = qqq.array[ 3 ] = 8.0;
        TEST(qq == qqq);
        log( "operator==, operator!=", ok );
    }


    // operator= tests
    {
        bool ok = true;
        quaterniond tquaternion_test = q;
        TEST(tquaternion_test == q );

        tquaternion_test.iter_set< double* >( QData, QData + 4 );
        if ( ok )
            TEST(tquaternion_test == q);



        log( "operator=", ok );
    }

    // ctor tests
    {
        bool ok = true;
        quaterniond qq( q );
        TEST(q == qq);

        quaterniond t( 1., 6., 3., 8 );
        if ( ok )
            TEST(q == t);

        vector< 3, double > xyz;
        double xyzData[] = { 1., 6., 3. };
        xyz = xyzData;

        quaterniond s( xyz, 8 );
        if ( ok )
            TEST(q == s);

        matrix< 3, 3, double > mat;
        double matData[] = { 1., 0., 0., 0., 0., 1., 0., -1., 0. };
        mat = matData;
        const quaterniond u( mat );

        TEST( u.w() == sqrt( 2. ) / 2. &&
              u.x() == - ( 1 / sqrt( 2. ) ) &&
              (u.y() == 0 && u.z() == 0 ) );
        log( "constructors", ok );

    }

    // set test
    {
        bool ok = true;
        quaterniond qqq;
        qqq.set ( 1., 6., 3., 8. );
        TEST( qqq == q );
        log( "set( x,y,z,w )", ok );
    }

    // abs
    {
        bool ok = true;
        TEST(q.abs() == sqrt( 110.0 ) && q.squared_abs() == 110);
        log( "abs(), squared_abs()", ok );
    }


    //conjugate() test
    {
        bool ok = true;
        quaterniond conj(  -1., -6., -3., 8. );
        TEST( q.get_conjugate() == conj );

        conj.conjugate();
        if ( ok )
            TEST(q == conj);

        log( "conjugate()", ok );
    }

    // quat / scalar operations
    {
        bool ok = true;
        quaterniond t;
        t.set( 1, 2, 3, 4 );

        quaterniond t3;
        t3.set( 3, 6, 9, 12 );

        double f = 3.0;
        double rf = 1./ f;

        t *= f;
        TEST(t == t3);

        t.set( 1, 2, 3, 4 );
        t /= rf;
        if (ok)
            TEST(t == t3);

        t.set( 1, 2, 3, 4 );
        if (ok)
            TEST(t * f == t3);

        t.set( 1, 2, 3, 4 );
        if (ok)
            TEST(t / rf == t3);

        log( "quaternion / scalar operations: operator*, /, *=, /=", ok );
    }

    {
        bool ok = true;

        quaterniond qq;
        qq.set( 8, 3, 6, 1 );

        quaterniond qpqq;
        qpqq.set(  9., 9., 9., 9.   );

        // +, +=
        TEST(q + qq == qpqq );

        qq += q;
        if (ok)
            TEST(qq == qpqq);

        // -, -=
        qq.set( 8, 3, 6, 1 );
        if (ok)
            TEST(qpqq - qq == q);

        qpqq -= qq;
        if (ok)
            TEST(qpqq == q);

        // *, *=
        qq.set( 2, 3, 4, 1 );
        quaterniond q2( 3, 2, 1, 4 );
        quaterniond p = qq * q2;
        quaterniond pCorrect( 6, 24, 12, -12 );
        if (ok)
            TEST(p == pCorrect);

        p = qq;
        p *= q2;
        if (ok)
            TEST(p == pCorrect);

        log( "quaternion / quaternion operations: operator+, -, *, +=, -=, *=", ok );


    }

    {
        bool ok = true;

        quaterniond qq( 1, 2, 3, 4 );
        quaterniond q2( -6, 5, -4, 2 );

        vector< 3, double > v = qq.cross( q2 );

        vector< 3, double > v0( 1, 2, 3 );
        vector< 3, double > v1( -6, 5, -4 );

        TEST( v == v0.cross( v1 ) );

        log( "cross product ( vec3 = quat x quat ).", ok );
    }

    // TODO
//    {
//        // FIXME: find correct values -> actually test if you get the
//        // correct values
//        bool ok = true;
//
//        quaterniond qq(1., 2., 3., 4.);
//        quaterniond pp(1., 2., 3., 4.);
//        double a = 0.;
//
//        quaterniond x(1., 2., 3., 4.);
//
//        quaterniond::slerp(a, qq, pp);
//
//        quaterniond correct(0.0, 1.0, 1.0, 0.0);
//
//        TEST(correct == x);
//
//        log( "FIXME: todo slerp(a, p, q ).", ok );
//    }


#if 0
	Quaterniond rquaternion_test( 8. / 110., -1. / 110., -6. / 110., -3. / 110. );

	if ( _quaternion.invert() != rquaternion_test )
	{
		cout << "test: Quaternion::invert() failed!" << endl;
        failed();
        assert( 0 );
	}

	if ( tquaternion_test.dot( _quaternion ) != 40. )
	{
		cout << "test: Quaternion::dot( quaternion ) failed!" << endl;
        failed();
        assert( 0 );
	}

	Vector3d vector3_test( -30., -4., 18. );
	if ( tquaternion_test.cross( _quaternion ) != vector3_test )
	{
		cout << "test: Quaternion::cross( quaternion ) failed!" << endl;
        failed();
        assert( 0 );
	}

	Vector3d yaxis( 1., 0., 0. );
	Quaterniond svector3_test( 0., 18., -30., -4. );
	Quaterniond result_test( _quaternion.rotate( M_PI / 2.f, yaxis, vector3_test ) );
	if ( abs( result_test.abs() - svector3_test.abs() ) > 1e-13 )
	{
		cout << "test: Quaternion::rotate( T, Vector3, Vector3 ) failed!" << endl;
		failed();
		assert( 0 );
	}

    if ( ok )
        cout << "Quaternion: all tests passed!" << endl;

#endif
	return global_ok;
}
Пример #28
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;
}
Пример #29
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);
}