Ejemplo n.º 1
0
 void GenProcessor::procSmooth(quint8 *dst, const quint8 **src, quint8 index, quint8 octave) {
     quint8 t = 1 << octave;
     const quint8 y[3] = {ny(index - t), ny(index), ny(index + t)};
     quint32 count = m_size >> octave;
     quint32 x[3] = {m_size - t, 0, t};
     dst[0] = smooth(src, x, y);
     x[0] = x[1]; x[1] = x[2]; x[2] += t;
     for (quint32 i = 0; i < count; i++) {
         m_mutex.lock();
         dst[x[1]] = smooth(src, x, y);
         for (quint8 k = 0; k < t; k++) {
             if (octave != 0 && k != 0) {
                 dst[x[0] + k] = interpolate(dst[x[0]], dst[x[1]], m_steps[k << (5 - octave)]);
             }
             if (m_releasing != -1) {
                 m_semaphores[m_releasing].release();
             }
             m_iter++;
         }
         x[0] = x[1]; x[1] = x[2];
         if (i != count - 3) {
             x[2] += t;
         } else {
             x[2] = 0;
         }
         m_mutex.unlock();
     }
 }
Ejemplo n.º 2
0
/***********************************************************************//**
 * @brief Computes the maximum radius (in degrees) around a given source
 *        direction that fits spatially into the event cube
 *
 * @param[in] srcDir Source direction.
 * @return Maximum radius in degrees that fully fits into event cube.
 *
 * By computing the sky directions of the event cube boundaries, the maximum
 * radius is computed that fits fully within the event cube. This method is
 * used for PSF normalization.
 ***************************************************************************/
double GLATEventCube::maxrad(const GSkyDir& srcDir) const
{
    // Initialise radius
    double radius = 0.0;

    // Continue only if sky direction is within sky map
    if (m_map.contains(srcDir)) {

        // Set to largest possible radius
        radius = 180.0;

        // Move along upper edge in longitude
        int iy = 0;
        for (int ix = 0; ix < nx(); ++ix) {
            GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
            double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
            if (distance < radius) {
                radius = distance;
            }
        }

        // Move along lower edge in longitude
        iy = ny()-1;
        for (int ix = 0; ix < nx(); ++ix) {
            GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
            double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
            if (distance < radius) {
                radius = distance;
            }
        }

        // Move along left edge in latitude
        int ix = 0;
        for (int iy = 0; iy < ny(); ++iy) {
            GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
            double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
            if (distance < radius) {
                radius = distance;
            }
        }

        // Move along right edge in latitude
        ix = nx()-1;
        for (int iy = 0; iy < ny(); ++iy) {
            GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
            double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
            if (distance < radius) {
                radius = distance;
            }
        }
    
    } // endif: sky direction within sky map

    // Return radius
    return radius;
}
Ejemplo n.º 3
0
/*******************************************************************
 * 
 * NAME :               compute_gradient()  
 * 
 *
 * DESCRIPTION :        The functions calculates the gradient of 
 *                      particle i and stores it in the global 
 *                      variable gradient.
 * 
 */
void Slater::compute_gradient(int i) {
    gradient = zeros(1, dim);

    if (i < N) {
        for (int j = 0; j < N; j++) { // Spin up.
            gradient += orbital->get_gradient(r_new.row(i), nx(j), ny(j)) * Dp_inv(j, i);
        }
    } else {
        for (int j = 0; j < N; j++) { // Spin down.
            gradient += orbital->get_gradient(r_new.row(i), nx(j), ny(j)) * Dm_inv(j, i - N);
        }
    }
}
Ejemplo n.º 4
0
/*******************************************************************
 * 
 * NAME :               evaluate(mat r)  
 * 
 *
 * DESCRIPTION :        Returns the determinant of D(r) using 
 *                      Armadillos determinant function. This
 *                      function is used if we have to evaluate
 *                      the WF in unrelated new coordinates.
 * 
 */
double Slater::evaluate(mat r) {
    mat D_p = zeros(N, N);
    mat D_m = zeros(N, N);

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            D_p(j, i) = orbital->evaluate(r.row(i), nx(j), ny(j));
            D_m(j, i) = orbital->evaluate(r.row(i + N), nx(j), ny(j));
        }
    }

    return det(D_p) * det(D_m);
}
Ejemplo n.º 5
0
/*******************************************************************
 * 
 * NAME :               get_laplace()  
 * 
 *
 * DESCRIPTION :        The functions calculates the Laplacian of 
 *                      particle i and returns the result.
 * 
 */
double Slater::get_laplacian(int i) {

    double sum = 0;
    if (i < N) {
        for (int j = 0; j < N; j++) { // Spin up.
            sum += orbital->evaluate_laplacian(r_new.row(i), nx(j), ny(j)) * Dp_inv(j, i);
        }
    } else {
        for (int j = 0; j < N; j++) { // Spin down.
            sum += orbital->evaluate_laplacian(r_new.row(i), nx(j), ny(j)) * Dm_inv(j, i - N);
        }
    }

    return sum;
}
Ejemplo n.º 6
0
/***********************************************************************//**
 * @brief Computes the maximum radius (in degrees) around a given source
 *        direction that fits spatially into the event cube
 *
 * @param[in] srcDir Source direction.
 * @return Maximum radius in degrees that fully fits into event cube.
 *
 * By computing the sky directions of the event cube boundaries, the maximum
 * radius is computed that fits fully within the event cube. This method is
 * used for PSF normalization.
 ***************************************************************************/
double GLATEventCube::maxrad(const GSkyDir& srcDir) const
{
    // Initialise radius
    double radius = 180.0;

    // Move along upper edge in longitude
    int iy = 0;
    for (int ix = 0; ix < nx(); ++ix) {
        GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
        double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
        if (distance < radius) {
            radius = distance;
        }
    }

    // Move along lower edge in longitude
    iy = ny()-1;
    for (int ix = 0; ix < nx(); ++ix) {
        GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
        double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
        if (distance < radius) {
            radius = distance;
        }
    }

    // Move along left edge in latitude
    int ix = 0;
    for (int iy = 0; iy < ny(); ++iy) {
        GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
        double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
        if (distance < radius) {
            radius = distance;
        }
    }

    // Move along right edge in latitude
    ix = nx()-1;
    for (int iy = 0; iy < ny(); ++iy) {
        GSkyPixel pixel    = GSkyPixel(double(ix), double(iy));
        double    distance = m_map.pix2dir(pixel).dist_deg(srcDir);
        if (distance < radius) {
            radius = distance;
        }
    }

    // Return radius
    return radius;
}
Ejemplo n.º 7
0
GLuint FileAssociatedTexture::getOrCreateCube(
	const QString & fileNames
,   OpenGLFunctions & gl
,	const GLenum mag_filter
,	const GLenum min_filter)
{
    if (s_texturesByFilePath.contains(fileNames))
        return s_texturesByFilePath[fileNames];

    QString px(fileNames); px.replace("?", "px");
    QString nx(fileNames); nx.replace("?", "nx");
    QString py(fileNames); py.replace("?", "py");
    QString ny(fileNames); ny.replace("?", "ny");
    QString pz(fileNames); pz.replace("?", "pz");
    QString nz(fileNames); nz.replace("?", "nz");

    QStringList files = QStringList() << px << nx << py << ny << pz << nz;
    QStringList absolutes;
    foreach(const QString & file, files)
    {
        QFileInfo fi(file);
        if (!fi.exists())
        {
            qWarning() << file << " does not exist: texture has no associated file.";
            return -1;
        }
        absolutes << fi.absoluteFilePath();
    }
Ejemplo n.º 8
0
/**
 * Fit to a function.
 * @param fun :: A function.
 */
void Chebfun2DSpline::fit( AFunction2D fun )
{
  auto& xv = m_xBase->x;
  auto& yv = m_yBase->x;
  std::vector<double> px(nx() + 1);
  std::vector<double> py(ny() + 1);
  for(size_t ix = 0; ix < m_xFuns.size(); ++ix)
  {
    const double y = m_yLines[ix];
    for( size_t i = 0 ; i < px.size(); ++i)
    {
      px[i] = fun(xv[i], y);
    }
    m_xFuns[ix].setP( px );
  }
  for(size_t iy = 0; iy < m_yFuns.size(); ++iy)
  {
    const double x = m_xLines[iy];
    for( size_t i = 0 ; i < py.size(); ++i)
    {
      py[i] = fun(x, yv[i]);
    }
    m_yFuns[iy].setP( py );
  }
}
bool Foam::patchDistMethods::advectionDiffusion::correct
(
    volScalarField& y,
    volVectorField& n
)
{
    if (!predicted_)
    {
        pdmPredictor_->correct(y);
        predicted_ = true;
    }

    volVectorField ny
    (
        IOobject
        (
            "ny",
            mesh_.time().timeName(),
            mesh_,
            IOobject::NO_READ,
            IOobject::NO_WRITE,
            false
        ),
        mesh_,
        dimensionedVector("ny", dimless, vector::zero),
        patchTypes<vector>(mesh_, patchIDs_)
    );

    const fvPatchList& patches = mesh_.boundary();

    forAllConstIter(labelHashSet, patchIDs_, iter)
    {
        label patchi = iter.key();
        ny.boundaryField()[patchi] == -patches[patchi].nf();
    }
Ejemplo n.º 10
0
int main(){
  V3f x(0,0,1); V3f xr(rot_x(x, 0.87)); same("x rotation", x.dot(xr), cos(0.87));
  V3f y(0,0,1); V3f yr(rot_y(y, 0.23)); same("y rotation", y.dot(yr), cos(0.23));
  V3f z(1,0,0); V3f zr(rot_z(z, 0.19)); same("z rotation", z.dot(zr), cos(0.19));

  V3f nx(3,2,5);
  V3f ny(-2,3,4);
  V3f nz(-4,4,3.8);

  V3f nnx(3,2,5);
  V3f nny(-2,3,4);
  V3f nnz(-4,4,3.8);

  ortoNormalize(nnx, nny, nnz);
  
  same("x unit", nnx.length(), 1.0);
  same("y unit", nny.length(), 1.0);
  same("z unit", nnz.length(), 1.0);

  V3f tmp; tmp.cross(nnx, nx);

  same("x colinear", tmp.length(), 0.0);
  
  tmp.cross(nnx, nny); tmp-=nnz; same("x orto", tmp.length(), 0);
  tmp.cross(nny, nnz); tmp-=nnx; same("y orto", tmp.length(), 0);
  tmp.cross(nnz, nnx); tmp-=nny; same("z orto", tmp.length(), 0);


};
Ejemplo n.º 11
0
/*******************************************************************
 * 
 * NAME :               Slater(int dim, int n_particles, double alpha)
 * 
 *
 * DESCRIPTION :        Constructor.
 * 
 */
Slater::Slater(int dim, int n_particles, Orbital *orbital)
: dim(dim), N(n_particles / 2), n_particles(n_particles), orbital(orbital) {

    Dp = zeros(N, N);
    Dm = zeros(N, N);
    Dp_new = zeros(N, N);
    Dm_new = zeros(N, N);
    Dp_inv = zeros(N, N);
    Dm_inv = zeros(N, N);
    Dp_inv_new = zeros(N, N);
    Dm_inv_new = zeros(N, N);

    // Computing the Quantum Numbers.
    nx.set_size(N);
    ny.set_size(N);
    int l = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j <= i; j++) {
            nx(l) = i - j;
            ny(l) = j;
            l++;
            // Breaking the loop if we have enough numbers.
            if (l == N)
                i = j = N;
        }
    }

}
Ejemplo n.º 12
0
int
main(){
  double x1 = -5;
  double x2 = 10;
  double dx = 0.01;

  double y1 = -5;
  double y2 = 5;
  double dy = 0.2;

  double x,y;
  for (y=y1; y<y2; y+=dy){
    double f, fp=y, fpp=y;
    for (x=x1; x<x2; x+=dx){
      double fx=(fp-fpp)/dx;
      double fxx=(ny(x,fp)-fx*nx(x,fp))*(1+fx*fx)/n(x,fp);

      f=2*fp-fpp+fxx*dx*dx;

      printf("%10f %10f %10f %10f\n", x, y, n(x,y), f);

      fpp=fp; fp=f;
    }
    printf("\n");
  }
}
Ejemplo n.º 13
0
/***********************************************************************//**
 * @brief Set sky directions and solid angles of events cube.
 *
 * @exception GLATException::no_sky
 *            No sky pixels found in event cube.
 *
 * This method computes the sky directions and solid angles for all event
 * cube pixels. Sky directions are stored in an array of GLATInstDir objects
 * while solid angles are stored in units of sr in a double precision array.
 ***************************************************************************/
void GLATEventCube::set_directions(void)
{
    // Throw an error if we have no sky pixels
    if (npix() < 1) {
        throw GLATException::no_sky(G_SET_DIRECTIONS, "Every LAT event cube"
                                   " needs a definition of the sky pixels.");
    }

    // Clear old pixel directions and solid angle
    m_dirs.clear();
    m_solidangle.clear();

    // Reserve space for pixel directions and solid angles
    m_dirs.reserve(npix());
    m_solidangle.reserve(npix());

    // Set pixel directions and solid angles
    for (int iy = 0; iy < ny(); ++iy) {
        for (int ix = 0; ix < nx(); ++ix) {
            GSkyPixel pixel = GSkyPixel(double(ix), double(iy));
            m_dirs.push_back(GLATInstDir(m_map.pix2dir(pixel)));
            m_solidangle.push_back(m_map.solidangle(pixel));
        }
    }

    // Return
    return;
}
Ejemplo n.º 14
0
int collide(int *a, int *b)
{
	 // sanity checking
	 if (a == 000 || b == 000)
		  return -1; // bad args
	 if (b[0] < 1)
		  return -2; // x at 0
	 if (b[1] < 1)
		  return -3; // y at 0
	 if (b[2] < 1)
		  return -4; // z at 0
	 if (b[0] > xres)
		  return -5; // x at max
	 if (b[0] > yres)
		  return -6; // y at max
	 if (b[0] > zres)
		  return -7; // z at max

	 int vec[3] = {(b[0]-a[0]), (b[1]-a[1]), (b[2]-a[2])}; // vector
	 int result = 0;

	 /* below is a fairly basic algo to keep checking until there is no conflict
	  * may be optimizable
	  */
	 do
	 {
		  result = 0;
		  if (vec[0] > 0)
		  {
				result += px(&b[0]);
		  }
		  if (vec[1] > 0)
		  {
				result += py(&b[1]);
		  }
		  if (vec[2] > 0)
		  {
				result += pz(&b[2]);
		  }
		  if (vec[0] < 0)
		  {
				result += nx(&b[0]);
		  }
		  if (vec[1] < 0)
		  {
				result += ny(&b[1]);
		  }
		  if (vec[2] < 0)
		  {
				result += nz(&b[2]);
		  }
		  vec[0] = (b[0]-a[0]);
		  vec[1] = (b[1]-a[1]);
		  vec[2] = (b[2]-a[2]); // recalc. should eliminate unnecessary checks
	 }
	 while (result != 0);

	 return 0;
}
Ejemplo n.º 15
0
void MatrixSkinStorage::toStream(std::ostream & os) const {
  int i,j;
  for(i=0; i<nx(); i++) {
    for(j=0; j<ny(); j++ ) {
       os<<(*this)(i,j)<<"  ";
    }
    os<<"\n";
  }
}
Ejemplo n.º 16
0
//---------------------------------------------------------
void NDG3D::Normals3D()
//---------------------------------------------------------
{
  // function [nx, ny, nz, sJ] = Normals3D()
  // Purpose : Compute outward pointing normals at
  //	    elements faces as well as surface Jacobians

  GeometricFactors3D();

  // interpolate geometric factors to face nodes
  DMat frx=rx(Fmask,All),  fsx=sx(Fmask,All),  ftx=tx(Fmask,All);
  DMat fry=ry(Fmask,All),  fsy=sy(Fmask,All),  fty=ty(Fmask,All);
  DMat frz=rz(Fmask,All),  fsz=sz(Fmask,All),  ftz=tz(Fmask,All);

  // build normals
  nx.resize(4*Nfp, K); ny.resize(4*Nfp, K); nz.resize(4*Nfp, K);
  Index1D fid1(1,Nfp), fid2(Nfp+1,2*Nfp), fid3(2*Nfp+1,3*Nfp), fid4(3*Nfp+1,4*Nfp);

  // face 1
  nx(fid1, All) = -ftx(fid1,All);
  ny(fid1, All) = -fty(fid1,All);
  nz(fid1, All) = -ftz(fid1,All);

  // face 2
  nx(fid2, All) = -fsx(fid2,All);
  ny(fid2, All) = -fsy(fid2,All);
  nz(fid2, All) = -fsz(fid2,All);

  // face 3
  nx(fid3, All) = frx(fid3,All) + fsx(fid3,All) + ftx(fid3,All);
  ny(fid3, All) = fry(fid3,All) + fsy(fid3,All) + fty(fid3,All);
  nz(fid3, All) = frz(fid3,All) + fsz(fid3,All) + ftz(fid3,All);

  // face 4
  nx(fid4, All) = -frx(fid4,All);
  ny(fid4, All) = -fry(fid4,All);
  nz(fid4, All) = -frz(fid4,All);

  // normalise
  sJ = sqrt(sqr(nx) + sqr(ny) + sqr(nz));
  
  nx.div_element(sJ); ny.div_element(sJ); nz.div_element(sJ);
  sJ.mult_element(J(Fmask, All));  //sJ=sJ.*J(Fmask(:),:);
}
Ejemplo n.º 17
0
/*******************************************************************
 * 
 * NAME :               init(); 
 * 
 *
 * DESCRIPTION :        Initializes the Slater matrix with position 
 *                      values.
 * 
 */
void Slater::init() {

    // Updating the whole matrix.
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            Dp(j, i) = orbital->evaluate(r_new.row(i), nx(j), ny(j));
            Dm(j, i) = orbital->evaluate(r_new.row(i + N), nx(j), ny(j));
        }
    }
    Dp_new = Dp;
    Dm_new = Dm;

    // Calulating the inverse using Armadillo.
    Dp_inv = inv(Dp).t();
    Dm_inv = inv(Dm).t();

    Dp_inv_new = Dp_inv;
    Dm_inv_new = Dm_inv;
}
Ejemplo n.º 18
0
Matrixf3& Matrixf3::operator *= (const Matrixf3& m)
{
	Pointf3 nx(x ^ m.CX(), x ^ m.CY(), x ^ m.CZ());
	Pointf3 ny(y ^ m.CX(), y ^ m.CY(), y ^ m.CZ());
	Pointf3 nz(z ^ m.CX(), z ^ m.CY(), z ^ m.CZ());
	x = nx;
	y = ny;
	z = nz;
	a *= m;
	return *this;
}
Ejemplo n.º 19
0
void populateCities(std::vector<City>& cities)
{
    cities.clear();

    City kathmandu("Kathmandu", "Nepal");

    City ny("New York", "USA");

    cities.push_back(kathmandu);
    cities.push_back(ny);
}
void Mesh::makeSurfaceMesh()
{  // Hill, F.S. Jr., "Computer Graphics using OpenGL", 2nd edition, 2002, p.355,
   //   Case Study 6.13, Drawing smooth parametric surfaces.
        int i, j;
        double pi = 3.141592653589793 ;
        int numValsU = 40; 
        int numValsV = 40;       // set these
	/*double u, v, uMin = -pi;
        double vMin = -pi;
	double uMax = pi;
        double vMax = pi;*/
        double u, v, uMin = -pi/4;
        double vMin = -pi/4;
	double uMax = pi/4;
        double vMax = pi/4;
	double delU = (uMax - uMin)/(numValsU - 1);
	double delV = (vMax - vMin)/(numValsV - 1);

	numVerts = numValsU * numValsV + 1; // total # of vertices
	numFaces = (numValsU -1) * (numValsV - 1) ; // # of faces
	numNormals = numVerts; // for smooth shading - one normal per vertex
	pt   = new Point3[numVerts];   // make space 
	face = new Face[numFaces];    
	norm = new Vector3[numNormals]; 

	for(i = 0, u = uMin; i < numValsU; i++, u += delU)
		for(j = 0, v = vMin; j < numValsV; j++, v += delV)
		{
			int whichVert = i * numValsV + j; //index of the vertex and normal
			// set this vertex: use functions X, Y, and Z
			pt[whichVert].set(X(u, v),Y(u, v),Z(u, v));
			// set the normal at this vertex: use functions nx, ny, nz
			norm[whichVert].set(nx(u, v), ny(u, v), nz(u, v));
			norm[whichVert].normalize();
			// make quadrilateral
			if(i > 0 && j > 0) // when to compute next face
			{
				int whichFace =(i - 1) * (numValsV - 1) + (j - 1); 
				face[whichFace].vert = new VertexID[4];
				//assert(face[whichFace].vert != NULL);
				face[whichFace].nVerts = 4;
				face[whichFace].vert[0].vertIndex = // same as norm index
				face[whichFace].vert[0].normIndex = whichVert;
				face[whichFace].vert[1].vertIndex = 
				face[whichFace].vert[1].normIndex = whichVert - 1;
				face[whichFace].vert[2].vertIndex = 
				face[whichFace].vert[2].normIndex = whichVert - numValsV - 1;
				face[whichFace].vert[3].vertIndex = 
				face[whichFace].vert[3].normIndex = whichVert - numValsV;
			}
		}
}
Ejemplo n.º 21
0
std::string name(int t)
{
  char buf[16];
  std::string res;
  int i=0;
  while (names[i].name != NULL && names[i].t != t)
    ++i;
  if (names[i].name != NULL)
  {
    res = names[i].name;
  }
  else if (isMatrix(t))
  {
    res = "Mat<";
    snprintf(buf,sizeof(buf),"%d",ny(t));
    res += buf;
    res += ",";
    snprintf(buf,sizeof(buf),"%d",nx(t));
    res += buf;
    res += ",";
    res += name(toSingle(t));
    res += ">";
  }
  else if (isVector(t))
  {
    res = "Vec<";
    snprintf(buf,sizeof(buf),"%d",nx(t));
    res += buf;
    res += ",";
    res += name(toSingle(t));
    res += ">";
  }
  else if (isString(t))
  {
    if (size(t)==0)
      res = "String";
    else
    {
      res = "String<";
      snprintf(buf,sizeof(buf),"%d",size(t));
      res += buf;
      res += ">";
    }
  }
  else
  {
    snprintf(buf,sizeof(buf),"0x%x",t);
    res = buf;
  }
  return res;
}
Ejemplo n.º 22
0
clearbatch()
{
nl();
nl();
put("1Really clear batch [4y/N1]:2 ");
if(ny())
	{
	nl();
	pl("4Batch not cleared.");
	}
else
	{
	nl();
	pl("4Batch cleared.");
	que.files=0;
	}
}
Ejemplo n.º 23
0
/**
 * Returns a V3D object from the Python object given
 * to the converter
 * @returns A newly constructed V3D object converted
 * from the PyObject.
 */
Kernel::Matrix<double> PyObjectToMatrix::operator()() {
  if (m_alreadyMatrix) {
    return extract<Kernel::Matrix<double>>(m_obj)();
  }
  PyArrayObject *ndarray = (PyArrayObject *)PyArray_View(
      (PyArrayObject *)m_obj.ptr(), PyArray_DescrFromType(NPY_DOUBLE),
      &PyArray_Type);
  const auto shape = PyArray_DIMS(ndarray);
  npy_intp nx(shape[0]), ny(shape[1]);
  Kernel::Matrix<double> matrix(nx, ny);
  for (npy_intp i = 0; i < nx; i++) {
    auto row = matrix[i];
    for (npy_intp j = 0; j < ny; j++) {
      row[j] = *((double *)PyArray_GETPTR2(ndarray, i, j));
    }
  }
  return matrix;
}
Ejemplo n.º 24
0
void vertex_t::texture_coords_and_derivs( Imath::V2f& uv, Imath::V2f& duv_dx, Imath::V2f& duv_dy) const
{
	float w = 1.0f / inv_w;
	uv.x = this->uv.x * w;
	uv.y = this->uv.y * w;

	w = 1.0f / nyuv.z;
	Imath::V2f ny( nyuv.x * w, nyuv.y * w);

	w = 1.0f / nxuv.z;
	Imath::V2f nx( nxuv.x * w, nxuv.y * w);

	duv_dx = nx - uv;
	duv_dx *= 0.5f;

	duv_dy = ny - uv;
	duv_dy *= 0.5f;
}
Ejemplo n.º 25
0
bool 
Sol_MultigridPressure3DBase::initialize_base_storage(int nx_val, int ny_val, int nz_val, double hx_val, double hy_val, double hz_val)
{
  // pre-validate
  if (!check_float(hx_val) || !check_float(hy_val) || !check_float(hz_val)) {
    printf("[ERROR] Sol_MultigridPressure3DBase::initialize_storage - garbage hx,hy,hz value %f %f %f\n", hx_val, hy_val, hz_val);
    return false;
  }

  // do allocation and initialization
  _num_levels = num_levels(nx_val, ny_val, nz_val);

  _h = new double[_num_levels];
  _dim = new int3[_num_levels];
  _h[0] = min3(hx_val, hy_val, hz_val);
  _fx = (_h[0] * _h[0]) / (hx_val * hx_val);
  _fy = (_h[0] * _h[0]) / (hy_val * hy_val);
  _fz = (_h[0] * _h[0]) / (hz_val * hz_val);
  _omega = optimal_omega(_fx, _fy, _fz);
  _dim[0].x = nx_val;
  _dim[0].y = ny_val;
  _dim[0].z = nz_val;

  int level;
  for (level=1; level < _num_levels; level++) {
    int this_nx = nx(level-1)/2;
    int this_ny = ny(level-1)/2;
    int this_nz = nz(level-1)/2;

    _h[level] = get_h(level-1)*2;
    _dim[level].x = this_nx;
    _dim[level].y = this_ny;
    _dim[level].z = this_nz;
  }

  return true;
}
Ejemplo n.º 26
0
//---------------------------------------------------------
void CurvedINS2D::INSLiftDrag2D(double ra)
//---------------------------------------------------------
{
  // function [Cd, Cl, dP, sw, stri] = INSLiftDrag2D(Ux, Uy, PR, ra, nu, time, tstep, Nsteps)
  // Purpose: compute coefficients of lift, drag and pressure drop at cylinder

  static FILE* fid; 
  static DVec sw1, sw2; 
  static int Nc=0, stri1=0, stri2=0;

  if (1 == tstep) {
    char buf[50]; sprintf(buf, "liftdraghistory%d.dat", N);
    fid = fopen(buf, "w");
    fprintf(fid, "timeCdCldP = [...\n");

    // Sample location and weights for pressure drop
    // Note: the VolkerCylinder test assumes the 2 
    // sample points (-ra, 0), (ra, 0), are vertices 
    // located on the internal cylinder boundary

    Sample2D(-ra, 0.0,  sw1, stri1);
    Sample2D( ra, 0.0,  sw2, stri2);

    Nc = mapC.size()/Nfp;
  }

  bool bDo=false; 
  if (1==tstep || tstep==Nsteps || !umMOD(tstep,10)) { bDo=true; }
  else if (time > 3.90 && time < 3.96) { bDo=true; } // catch C_d  (3.9362)
  else if (time > 5.65 && time < 5.73) { bDo=true; } // catch C_l  (5.6925)
  else if (time > 7.999) { bDo=true; } // catch dP  (8.0)
  if (!bDo) return;

  DVec PRC, nxC, nyC, wv, tv;
  DMat dUxdx,dUxdy, dUydx,dUydy, MM1D, V1D;
  DMat dUxdxC,dUxdyC, dUydxC,dUydyC, hforce, vforce, sJC;
  double dP=0.0, Cd=0.0, Cl=0.0;

  dP = sw1.inner(PR(All,stri1)) - sw2.inner(PR(All,stri2));

  // compute derivatives
  Grad2D(Ux, dUxdx,dUxdy);  dUxdxC=dUxdx(vmapC); dUxdyC=dUxdy(vmapC);
  Grad2D(Uy, dUydx,dUydy);  dUydxC=dUydx(vmapC); dUydyC=dUydy(vmapC);

  PRC=PR(vmapC); nxC=nx(mapC); nyC=ny(mapC); sJC=sJ(mapC);
  hforce = -PRC.dm(nxC) + nu*( nxC.dm(  2.0 *dUxdxC) + nyC.dm(dUydxC+dUxdyC) );
  vforce = -PRC.dm(nyC) + nu*( nxC.dm(dUydxC+dUxdyC) + nyC.dm(  2.0 *dUydyC) );

  hforce.reshape(Nfp, Nc);
  vforce.reshape(Nfp, Nc);
  sJC   .reshape(Nfp, Nc);

  // compute weights for integrating (1,hforce) and (1,vforce)
  V1D = Vandermonde1D(N, r(Fmask(All,1)));
  MM1D = trans(inv(V1D)) / V1D;

  wv = MM1D.col_sums();
  tv = wv*(sJC.dm(hforce));  Cd=tv.sum();  // Compute drag coefficient
  tv = wv*(sJC.dm(vforce));  Cl=tv.sum();  // Compute lift coefficient

  // Output answers for plotting
  fprintf(fid, "%15.14f %15.14f %15.14f %15.14f;...\n", time, Cd/ra, Cl/ra, dP);
  fflush(fid);

  // LOG report
  if (1==tstep || tstep==Nsteps || !umMOD(tstep,Nreport)) { 
    umLOG(1, "%7d   %6.3lf   %9.5lf  %10.6lf  %9.5lf\n", 
              tstep, time, Cd/ra, Cl/ra, dP);
  }

  if (tstep==Nsteps) {
    fprintf(fid, "];\n");
    fclose(fid); fid=NULL;
  }
}
Ejemplo n.º 27
0
    osg::Node* createCube(unsigned int mask)
    {
        osg::Geode* geode = new osg::Geode;

        osg::Geometry* geometry = new osg::Geometry;
        geode->addDrawable(geometry);

        osg::Vec3Array* vertices = new osg::Vec3Array;
        geometry->setVertexArray(vertices);

        osg::Vec3Array* normals = new osg::Vec3Array;
        geometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX);

        osg::Vec4Array* colours = new osg::Vec4Array;
        geometry->setColorArray(colours, osg::Array::BIND_OVERALL);
        colours->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));


        osg::Vec3 origin(0.0f,0.0f,0.0f);
        osg::Vec3 dx(2.0f,0.0f,0.0f);
        osg::Vec3 dy(0.0f,1.0f,0.0f);
        osg::Vec3 dz(0.0f,0.0f,1.0f);

        osg::Vec3 px(1.0f,0.0,0.0f);
        osg::Vec3 nx(-1.0f,0.0,0.0f);
        osg::Vec3 py(0.0f,1.0f,0.0f);
        osg::Vec3 ny(0.0f,-1.0f,0.0f);
        osg::Vec3 pz(0.0f,0.0f,1.0f);
        osg::Vec3 nz(0.0f,0.0f,-1.0f);

        if (mask & FRONT_FACE)
        {
            // front face
            vertices->push_back(origin);
            vertices->push_back(origin+dx);
            vertices->push_back(origin+dx+dz);
            vertices->push_back(origin+dz);
            normals->push_back(ny);
            normals->push_back(ny);
            normals->push_back(ny);
            normals->push_back(ny);
        }

        if (mask & BACK_FACE)
        {
            // back face
            vertices->push_back(origin+dy);
            vertices->push_back(origin+dy+dz);
            vertices->push_back(origin+dy+dx+dz);
            vertices->push_back(origin+dy+dx);
            normals->push_back(py);
            normals->push_back(py);
            normals->push_back(py);
            normals->push_back(py);
        }

        if (mask & LEFT_FACE)
        {
            // left face
            vertices->push_back(origin+dy);
            vertices->push_back(origin);
            vertices->push_back(origin+dz);
            vertices->push_back(origin+dy+dz);
            normals->push_back(nx);
            normals->push_back(nx);
            normals->push_back(nx);
            normals->push_back(nx);
        }

        if (mask & RIGHT_FACE)
        {
            // right face
            vertices->push_back(origin+dx+dy);
            vertices->push_back(origin+dx+dy+dz);
            vertices->push_back(origin+dx+dz);
            vertices->push_back(origin+dx);
            normals->push_back(px);
            normals->push_back(px);
            normals->push_back(px);
            normals->push_back(px);
        }

        if (mask & TOP_FACE)
        {
            // top face
            vertices->push_back(origin+dz);
            vertices->push_back(origin+dz+dx);
            vertices->push_back(origin+dz+dx+dy);
            vertices->push_back(origin+dz+dy);
            normals->push_back(pz);
            normals->push_back(pz);
            normals->push_back(pz);
            normals->push_back(pz);
        }

        if (mask & BOTTOM_FACE)
        {
            // bottom face
            vertices->push_back(origin);
            vertices->push_back(origin+dy);
            vertices->push_back(origin+dx+dy);
            vertices->push_back(origin+dx);
            normals->push_back(nz);
            normals->push_back(nz);
            normals->push_back(nz);
            normals->push_back(nz);
        }

        geometry->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, vertices->size()));

        return geode;
    }
Ejemplo n.º 28
0
//---------------------------------------------------------
void NDG3D::PoissonIPDG3D(CSd& spOP, CSd& spMM)
//---------------------------------------------------------
{
  // function [OP,MM] = PoissonIPDG3D()
  //
  // Purpose: Set up the discrete Poisson matrix directly
  //          using LDG. The operator is set up in the weak form


  DVec faceR("faceR"), faceS("faceS"), faceT("faceT");
  DMat V2D;  IVec Fm("Fm");  IVec i1_Nfp = Range(1,Nfp);
  double opti1=0.0, opti2=0.0; int i=0; 

  umLOG(1, "\n ==> {OP,MM} assembly: ");
  opti1 = timer.read(); // time assembly

  // build local face matrices
  DMat massEdge[5]; // = zeros(Np,Np,Nfaces);
  for (i=1; i<=Nfaces; ++i) {
    massEdge[i].resize(Np,Np);
  }

  // face mass matrix 1
  Fm = Fmask(All,1); faceR=r(Fm); faceS=s(Fm); 
  V2D = Vandermonde2D(N, faceR, faceS);
  massEdge[1](Fm,Fm) = inv(V2D*trans(V2D));

  // face mass matrix 2
  Fm = Fmask(All,2); faceR = r(Fm); faceT = t(Fm);
  V2D = Vandermonde2D(N, faceR, faceT);
  massEdge[2](Fm,Fm) = inv(V2D*trans(V2D));

  // face mass matrix 3
  Fm = Fmask(All,3); faceS = s(Fm); faceT = t(Fm);
  V2D = Vandermonde2D(N, faceS, faceT); 
  massEdge[3](Fm,Fm) = inv(V2D*trans(V2D));

  // face mass matrix 4
  Fm = Fmask(All,4); faceS = s(Fm); faceT = t(Fm);
  V2D = Vandermonde2D(N, faceS, faceT); 
  massEdge[4](Fm,Fm) = inv(V2D*trans(V2D));

  // build local volume mass matrix
  MassMatrix = trans(invV)*invV;

  DMat Dx("Dx"),Dy("Dy"),Dz("Dz"), Dx2("Dx2"),Dy2("Dy2"),Dz2("Dz2");
  DMat Dn1("Dn1"),Dn2("Dn2"), mmE("mmE"), OP11("OP11"), OP12("OP12");
  DMat mmE_All_Fm1, mmE_Fm1_Fm1, Dn2_Fm2_All;
  IMat rows1,cols1,rows2,cols2;  int k1=0,f1=0,k2=0,f2=0,id=0;
  Index1D entries, entriesMM, idsM;  IVec fidM,vidM,Fm1,vidP,Fm2;
  double lnx=0.0,lny=0.0,lnz=0.0,lsJ=0.0,hinv=0.0,gtau=0.0;
  double N1N1 = double((N+1)*(N+1)); int NpNp = Np*Np;

  // build DG derivative matrices
  int max_OP = (K*Np*Np*(1+Nfaces));
  int max_MM = (K*Np*Np);

  // "OP" triplets (i,j,x), extracted to {Ai,Aj,Ax}
  IVec OPi(max_OP), OPj(max_OP), Ai,Aj; DVec OPx(max_OP), Ax;
  // "MM" triplets (i,j,x)
  IVec MMi(max_MM), MMj(max_MM); DVec MMx(max_MM);
  IVec OnesNp = Ones(Np);

  // global node numbering
  entries.reset(1,NpNp); entriesMM.reset(1,NpNp);

  OP12.resize(Np,Np);

  for (k1=1; k1<=K; ++k1)
  {
    if (! (k1%250)) { umLOG(1, "%d, ",k1); }

    rows1 = outer( Range((k1-1)*Np+1,k1*Np), OnesNp );
    cols1 = trans(rows1);

    // Build local operators  
    Dx = rx(1,k1)*Dr + sx(1,k1)*Ds + tx(1,k1)*Dt;   
    Dy = ry(1,k1)*Dr + sy(1,k1)*Ds + ty(1,k1)*Dt;
    Dz = rz(1,k1)*Dr + sz(1,k1)*Ds + tz(1,k1)*Dt;

    OP11 = J(1,k1)*(trans(Dx)*MassMatrix*Dx + 
                    trans(Dy)*MassMatrix*Dy + 
                    trans(Dz)*MassMatrix*Dz);

    // Build element-to-element parts of operator
    for (f1=1; f1<=Nfaces; ++f1) {
      k2 = EToE(k1,f1); f2 = EToF(k1,f1); 

      rows2 = outer( Range((k2-1)*Np+1, k2*Np), OnesNp );
      cols2 = trans(rows2);

      fidM  = (k1-1)*Nfp*Nfaces + (f1-1)*Nfp + i1_Nfp;
      vidM = vmapM(fidM); Fm1 = mod(vidM-1,Np)+1;
      vidP = vmapP(fidM); Fm2 = mod(vidP-1,Np)+1;

      id = 1+(f1-1)*Nfp + (k1-1)*Nfp*Nfaces;
      lnx = nx(id);  lny = ny(id);  lnz = nz(id); lsJ = sJ(id); 
      hinv = std::max(Fscale(id), Fscale(1+(f2-1)*Nfp, k2));    

      Dx2 = rx(1,k2)*Dr + sx(1,k2)*Ds + tx(1,k2)*Dt;   
      Dy2 = ry(1,k2)*Dr + sy(1,k2)*Ds + ty(1,k2)*Dt;
      Dz2 = rz(1,k2)*Dr + sz(1,k2)*Ds + tz(1,k2)*Dt;
      
      Dn1 = lnx*Dx  + lny*Dy  + lnz*Dz;
      Dn2 = lnx*Dx2 + lny*Dy2 + lnz*Dz2;

      mmE = lsJ*massEdge[f1];

      gtau = 2.0 * N1N1 * hinv; // set penalty scaling

      if (EToE(k1,f1)==k1) {
        OP11 += ( gtau*mmE - mmE*Dn1 - trans(Dn1)*mmE ); // ok
      }
      else 
      {
        // interior face variational terms
        OP11 += 0.5*( gtau*mmE - mmE*Dn1 - trans(Dn1)*mmE );

        // extract mapped regions:
        mmE_All_Fm1 = mmE(All,Fm1);
        mmE_Fm1_Fm1 = mmE(Fm1,Fm1);
        Dn2_Fm2_All = Dn2(Fm2,All);

        OP12 = 0.0;   // reset to zero
        OP12(All,Fm2)  = -0.5*(       gtau*mmE_All_Fm1 );
        OP12(Fm1,All) -=  0.5*(            mmE_Fm1_Fm1*Dn2_Fm2_All );
      //OP12(All,Fm2) -=  0.5*(-trans(Dn1)*mmE_All_Fm1 );
        OP12(All,Fm2) +=  0.5*( trans(Dn1)*mmE_All_Fm1 );

        // load this set of triplets
#if (1)
        OPi(entries)=rows1; OPj(entries)=cols2, OPx(entries)=OP12;
        entries += (NpNp);
#else
        //###########################################################
        // load only the lower triangle (after droptol test?)
        sk=0; start=entries(1);
        for (int i=1; i<=NpNp; ++i) {
          eid = start+i;
          id=entries(eid); rid=rows1(i); cid=cols2(i);
          if (rows1(rid) >= cid) {          // take lower triangle
            if ( fabs(OP12(id)) > 1e-15) {  // drop small entries
              ++sk; OPi(id)=rid; OPj(id)=cid, OPx(id)=OP12(id);
            }
          }
        }
        entries += sk;
        //###########################################################
#endif
      }
    }

    OPi(entries  )=rows1; OPj(entries  )=cols1, OPx(entries  )=OP11;
    MMi(entriesMM)=rows1; MMj(entriesMM)=cols1; MMx(entriesMM)=J(1,k1)*MassMatrix;
    entries += (NpNp); entriesMM += (NpNp);
  }
  umLOG(1, "\n ==> {OP,MM} to sparse\n");

  entries.reset(1, entries.hi()-Np*Np);

  // Extract triplets from the large buffers. Note: this 
  // requires copying each array, and since these arrays 
  // can be HUGE(!), we force immediate deallocation:

  Ai=OPi(entries);  OPi.Free();
  Aj=OPj(entries);  OPj.Free();
  Ax=OPx(entries);  OPx.Free();
  umLOG(1, " ==> triplets ready (OP) nnz = %10d\n", entries.hi());

  // adjust triplet indices for 0-based sparse operators
  Ai -= 1; Aj -= 1; MMi -= 1; MMj -= 1;  int npk=Np*K;

#if defined(NDG_USE_CHOLMOD) || defined(NDG_New_CHOLINC)
  // load only the lower triangle tril(OP)        free args?
  spOP.load(npk,npk, Ai,Aj,Ax, sp_LT, false,1e-15, true);  // {LT, false} -> TriL
#else
  // select {upper,lower,both} triangles
//spOP.load(npk,npk, Ai,Aj,Ax, sp_LT, true,1e-15,true);   // LT -> enforce symmetry
//spOP.load(npk,npk, Ai,Aj,Ax, sp_All,true,1e-15,true);   // All-> includes "noise"
//spOP.load(npk,npk, Ai,Aj,Ax, sp_UT, false,1e-15,true);  // UT -> triu(OP) only
#endif

  Ai.Free();  Aj.Free();  Ax.Free();

  umLOG(1, " ==> triplets ready (MM) nnz = %10d\n", entriesMM.hi());

  //-------------------------------------------------------
  // The mass matrix operator will NOT be factorised, 
  // Load ALL elements (both upper and lower triangles):
  //-------------------------------------------------------
  spMM.load(npk,npk, MMi,MMj,MMx, sp_All,false,1.00e-15,true);
  MMi.Free(); MMj.Free(); MMx.Free();

  opti2 = timer.read(); // time assembly
  umLOG(1, " ==> {OP,MM} converted to csc.  (%g secs)\n", opti2-opti1);
}
Ejemplo n.º 29
0
/*	Render Modes are
 *	-Vertex Color Interpolation
 *  -Texture Mapping
 *	Renders the triangle mess, shades using the sence lights.
 *  Shadow Mapping implimented 
 */
void TMesh::RenderFilled(PPC *ppc, FrameBuffer *fb, unsigned int color, int lightsN, 
						 Light **L, float ka, FrameBuffer *texture, 
						 enviromap *cube, int renderMode) {

	//Project vertices on to the camera
	vector *pverts = new vector[vertsN];
	for (int vi = 0; vi < vertsN; vi++) {
		ppc->Project(verts[vi], pverts[vi]);
	}

	for (int tri = 0; tri < trisN; tri++) {
		int vinds[3];
		vinds[0] = tris[tri*3+0];
		vinds[1] = tris[tri*3+1];
		vinds[2] = tris[tri*3+2];

		if( pverts[vinds[0]][2] == FLT_MAX || 
			pverts[vinds[1]][2] == FLT_MAX || 
			pverts[vinds[2]][2] == FLT_MAX )
			continue;

		//Compute bounding box aabb of projected vertices
		AABB aabb(pverts[vinds[0]]);
		aabb.AddPoint(pverts[vinds[1]]);
		aabb.AddPoint(pverts[vinds[2]]);

		//Clip aabb with frame
		if(!aabb.Clip(0.0f, (float) fb->w, 0.0f, (float) fb->h)) 
			continue;

		int left = (int)(aabb.corners[0][0] + 0.5f);
		int right = (int)(aabb.corners[1][0] - 0.5f);
		int top = (int)(aabb.corners[0][1] + 0.5f);
		int bottom = (int)(aabb.corners[1][1] - 0.5f);

		vector red( cols[vinds[0]][0], cols[vinds[1]][0], cols[vinds[2]][0]); 
		vector green( cols[vinds[0]][1], cols[vinds[1]][1], cols[vinds[2]][1]); 
		vector blue( cols[vinds[0]][2], cols[vinds[1]][2], cols[vinds[2]][2]); 
		vector depth( pverts[vinds[0]][2], pverts[vinds[1]][2], pverts[vinds[2]][2] );

		vector rABC, gABC, bABC, zABC, nxABC, nyABC, nzABC, sABC, tABC;
		vector DEF;

		vector eeqs[3];
		SetEEQS( pverts[vinds[0]], pverts[vinds[1]], pverts[vinds[2]], eeqs);

		matrix ptm(pverts[vinds[0]], pverts[vinds[1]], pverts[vinds[2]]);
		ptm.setCol(2, vector(1.0f, 1.0f, 1.0f));
		ptm = invert(ptm);

		// Set up for normals
		vector nx( normals[vinds[0]][0], normals[vinds[1]][0], normals[vinds[2]][0] );
		vector ny( normals[vinds[0]][1], normals[vinds[1]][1], normals[vinds[2]][1] );
		vector nz( normals[vinds[0]][2], normals[vinds[1]][2], normals[vinds[2]][2] );
		// Set depth interpolation through screen space interpolation
		zABC = ptm * depth;

		//Matrix for Model Space interpolation
		matrix Q;
		Q = ComputeRastMatrix(ppc, verts[vinds[0]], verts[vinds[1]], verts[vinds[2]]);
		DEF = Q[0] + Q[1] + Q[2];
		//Compute Model Space interpolation constants
		SetModelRast(Q, nx, &nxABC); 
		SetModelRast(Q, ny, &nyABC); 
		SetModelRast(Q, nz, &nzABC); 
		//SetModelRast(Q, depth, &zABC);

		if( renderMode == VCI ) { 
			// Setup screen space linear variation of color 
			rABC = ptm * red;
			gABC = ptm * green;
			bABC = ptm * blue;

		}else if( renderMode == MCI ) {
			// Set Color Model Space Constants
			SetModelRast(Q, red, &rABC);
			SetModelRast(Q, green, &gABC);
			SetModelRast(Q, blue, &bABC);

		}else if( renderMode == TM) {
			//Get texture model space parameters
			vector s( tcs[2*vinds[0]+0], tcs[2*vinds[1]+0], tcs[2*vinds[2]+0]); 
			vector t( tcs[2*vinds[0]+1], tcs[2*vinds[1]+1], tcs[2*vinds[2]+1]); 
			SetModelRast(Q, s, &sABC);
			SetModelRast(Q, t, &tABC);

		}

		for( int v = top; v <= bottom; v++ ){
			for ( int u = left; u <= right; u++ ) {

				if(fb->IsOutsideFrame(u,v)) 
					continue;
				vector pv((float)u+0.5f, (float)v+0.5f, 1.0f);

				//Check whether pixel is inside triangle
				if (eeqs[0]*pv < 0.0f || eeqs[1]*pv < 0.0f || eeqs[2]*pv < 0.0f)
					continue;

				// Check whether triangle is closer than what was previously
				// seen at this pixel
				
				float currz = zABC * pv;
				//currz  /= (DEF * pv);
				if (fb->IsFarther(u, v, currz))
					continue;
				fb->SetZ(u, v, currz);
				
				// pixel is inside triangle and triangle is visible at pixel
				// compute color of pixel based on current triangle
				vector currColor;
				if ( renderMode == SM) 
					continue;
				if ( renderMode == VCI ){
					currColor = vector( rABC * pv, gABC * pv, bABC * pv );
				}else if ( renderMode == MCI ) {
					float r = ModelInterpolation(u, v, rABC, DEF);				
					float g = ModelInterpolation(u, v, gABC, DEF);				
					float b = ModelInterpolation(u, v, bABC, DEF);				
					currColor = vector(r,g,b);
				}
				if ( renderMode == TM) {
					int w = texture->w;
					int h = texture->h;
					float miS = ModelInterpolation(u, v, sABC, DEF);
					float miT = ModelInterpolation(u, v, tABC, DEF);
					miS = (miS * (float)w);
					miT = (miT * (float)h);

					int st = (h-1-(int)(miT)%h) * w+(int)(miS)%w;
					if(st < 0 || st > h*w) continue;
					currColor.SetFromColor(texture->pix[st]);
				}
				vector currNormal = vector(nxABC*pv/(DEF*pv), nyABC*pv/(DEF*pv), nzABC*pv/(DEF*pv)).norm();
				if ( renderMode == RFL ) {
					vector eye = ppc->C;
					vector P = ppc->UnProject(pv);
					vector ev = (eye - P);
					vector rv = currNormal*(currNormal*ev)*2.0f - ev; 
					rv = rv.norm();
					//currColor = (rv + vector(1.0f, 1.0f, 1.0f))/2.0f;
					currColor.SetFromColor(cube->getColor(rv));
				}
				//Calculated Color at pixel using phong equation
				for( int li = 0; li < lightsN; li++ ){
					if(!L[li]->on)
						continue;
					vector fullColor;
					fullColor.SetFromColor(color);
					vector lv;
					vector pp(pv);
					pp[2] = currz;
					lv = (L[li]->L->C - ppc->UnProject(pp)).norm();
					float kd = lv * currNormal;
					kd = (kd < 0.0f) ? 0.0f : kd;
					//currColor = currColor * ka ;
					//currColor = currColor * (ka + (1.0f-ka)*kd);
					
					vector point = ppc->UnProject(pp);
					vector SMp;
					L[li]->L->Project(point, SMp);
					float ul = SMp[0];
					float vl = SMp[1];
					if(L[li]->sm->IsOutsideFrame(ul, vl)) {
						currColor = currColor * ka ;
						//fb->Set(u,v, currColor.GetColor());
						continue;
					}
					//Check depth from light to calculate shadows
					float e = SMp[2]*.01;
					if(L[li]->sm->IsFarther((int)ul, (int)vl, SMp[2]+e)) {
						currColor = currColor * ka ;
						//fb->Set(u,v, currColor.GetColor());
					}else {
						currColor *= ka +(1.0f-ka)*kd;
						//fb->Set(u,v, currColor.GetColor());
					}
				}
				fb->Set(u,v, currColor.GetColor());
			}
		}
	}
	delete []pverts;

}
Ejemplo n.º 30
0
/*******************************************************************
 * 
 * NAME :               update_matrix()  
 * 
 *
 * DESCRIPTION :        Updates the Slater matrix with the 
 *                      coordinates of the active particle.
 * 
 */
void Slater::update_matrix() {
    if (active_particle < N) {
        for (int i = 0; i < N; i++) {
            Dp_new(i, active_particle) = orbital->evaluate(r_new.row(active_particle), nx(i), ny(i));
        }
    } else {
        for (int i = 0; i < N; i++) {
            Dm_new(i, active_particle - N) = orbital->evaluate(r_new.row(active_particle), nx(i), ny(i));
        }
    }
}