Example #1
0
void fiberForwardModel( float fiber[3][MAX_FIB_LEN], unsigned int pts )
{
    static Vector<double> S1, S2, S1m, S2m, P;
    static Vector<double> vox, vmin, vmax, dir;
    static double         len, t;
    static int            i, j, k;

    FiberSegments.clear();
    for(i=nPointsToSkip; i<pts-1-nPointsToSkip ;i++)
    {
        // original segment to be processed
        S1.Set( fiber[0][i]   + fiberShiftXmm, fiber[1][i]   + fiberShiftYmm, fiber[2][i]   + fiberShiftZmm );
        S2.Set( fiber[0][i+1] + fiberShiftXmm, fiber[1][i+1] + fiberShiftYmm, fiber[2][i+1] + fiberShiftZmm );

        // get a normal to the vector to move
        dir.x = S2.x-S1.x;
        dir.y = S2.y-S1.y;
        dir.z = S2.z-S1.z;
        dir.Normalize();
        if ( doIntersect==false )
            segmentForwardModel( S1, S2 );
        else
            while( 1 )
            {
                len = sqrt( pow(S2.x-S1.x,2) + pow(S2.y-S1.y,2) + pow(S2.z-S1.z,2) ); // in mm
                if ( len <= minSegLen )
                    break;

                // compute AABB of the first point (in mm)
                vmin.x = floor( (S1.x + 1e-6*dir.x)/pixdim.x ) * pixdim.x;
                vmin.y = floor( (S1.y + 1e-6*dir.y)/pixdim.y ) * pixdim.y;
                vmin.z = floor( (S1.z + 1e-6*dir.z)/pixdim.z ) * pixdim.z;
                vmax.x = vmin.x + pixdim.x;
                vmax.y = vmin.y + pixdim.y;
                vmax.z = vmin.z + pixdim.z;

                if ( rayBoxIntersection( S1, dir, vmin, vmax, t ) && t>0 && t<len )
                {
                    // add the portion S1P, and then reiterate
                    P.Set( S1.x + t*dir.x, S1.y + t*dir.y, S1.z + t*dir.z );
                    segmentForwardModel( S1, P );
                    S1.Set( P.x, P.y, P.z );
                }
                else
                {
                    // add the segment S1S2 and stop iterating
                    segmentForwardModel( S1, S2 );
                    break;
                }
            }
    }
}
  void SymScaledMatrix::MultVectorImpl(Number alpha, const Vector &x,
                                       Number beta, Vector &y) const
  {
    DBG_ASSERT(IsValid(matrix_));

    // Take care of the y part of the addition
    if ( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    // need some temporary vectors
    SmartPtr<Vector> tmp_x = x.MakeNewCopy();
    SmartPtr<Vector> tmp_y = y.MakeNew();

    if (IsValid(owner_space_->RowColScaling())) {
      tmp_x->ElementWiseMultiply(*owner_space_->RowColScaling());
    }

    matrix_->MultVector(1.0, *tmp_x, 0.0, *tmp_y);

    if (IsValid(owner_space_->RowColScaling())) {
      tmp_y->ElementWiseMultiply(*owner_space_->RowColScaling());
    }

    y.Axpy(1.0, *tmp_y);
  }
Example #3
0
  void MultiVectorMatrix::LRMultVector(Number alpha, const Vector &x,
                                       Number beta, Vector &y) const
  {
    DBG_START_METH("MultiVectorMatrix::LRMultVector(",
                   dbg_verbosity);

    DBG_ASSERT(NRows()==x.Dim());
    DBG_ASSERT(NRows()==y.Dim());

    DBG_PRINT((1, "alpha = %e beta = %e\n", alpha, beta));
    DBG_PRINT_VECTOR(2, "x", x);

    if ( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);
    }

    DBG_PRINT_VECTOR(2, "beta*y", y);
    for (Index i=0; i<NCols(); i++) {
      DBG_PRINT_VECTOR(2, "ConstVec(i)", *ConstVec(i));
      y.AddOneVector(alpha*ConstVec(i)->Dot(x), *ConstVec(i), 1.);
      DBG_PRINT_VECTOR(2, "y mid", y);
    }
  }
Example #4
0
  void MultiVectorMatrix::MultVectorImpl(Number alpha, const Vector &x,
                                         Number beta, Vector &y) const
  {
    //  A few sanity checks
    DBG_ASSERT(NCols()==x.Dim());
    DBG_ASSERT(NRows()==y.Dim());

    // Take care of the y part of the addition
    if ( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    // See if we can understand the data
    const DenseVector* dense_x = static_cast<const DenseVector*>(&x);
    DBG_ASSERT(dynamic_cast<const DenseVector*>(&x));

    // We simply add all the Vectors one after the other
    if (dense_x->IsHomogeneous()) {
      Number val = dense_x->Scalar();
      for (Index i=0; i<NCols(); i++) {
        y.AddOneVector(alpha*val, *ConstVec(i), 1.);
      }
    }
    else {
      const Number* values = dense_x->Values();
      for (Index i=0; i<NCols(); i++) {
        y.AddOneVector(alpha*values[i], *ConstVec(i), 1.);
      }
    }
  }
Example #5
0
float Plane::DistToPoint(float x, float y, float z)
{
   Vector p;

   p.Set(x, y, z);

   return m_normal.Dot(p) + m_d;
}
Example #6
0
  void SymTMatrix::MultVectorImpl(Number alpha, const Vector &x, Number beta,
                                  Vector &y) const
  {
    //  A few sanity checks
    DBG_ASSERT(Dim()==x.Dim());
    DBG_ASSERT(Dim()==y.Dim());

    // Take care of the y part of the addition
    DBG_ASSERT(initialized_);
    if( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    // See if we can understand the data
    const DenseVector* dense_x = dynamic_cast<const DenseVector*>(&x);
    DBG_ASSERT(dense_x); /* ToDo: Implement others */
    DenseVector* dense_y = dynamic_cast<DenseVector*>(&y);
    DBG_ASSERT(dense_y); /* ToDo: Implement others */

    if (dense_x && dense_y) {
      const Index*  irn=Irows();
      const Index*  jcn=Jcols();
      const Number* val=values_;
      Number* yvals=dense_y->Values();

      if (dense_x->IsHomogeneous()) {
        Number as = alpha *  dense_x->Scalar();
        for(Index i=0; i<Nonzeros(); i++) {
          yvals[*irn-1] += as * (*val);
          if (*irn!=*jcn) {
            // this is not a diagonal element
            yvals[*jcn-1] += as * (*val);
          }
          val++;
          irn++;
          jcn++;
        }
      }
      else {
        const Number* xvals=dense_x->Values();
        for(Index i=0; i<Nonzeros(); i++) {
          yvals[*irn-1] += alpha* (*val) * xvals[*jcn-1];
          if (*irn!=*jcn) {
            // this is not a diagonal element
            yvals[*jcn-1] += alpha* (*val) * xvals[*irn-1];
          }
          val++;
          irn++;
          jcn++;
        }
      }
    }
  }
Example #7
0
Vector CStar::NearestStar(Vector _oldnear){
	if (Alive){
		Vector vsMePos;
		vsMePos.Set(DrawPos.x-WINDOW_WIDTH/2, DrawPos.y-WINDOW_HEIGHT/2);
		if (vsMePos.GetLength() < _oldnear.GetLength()){
			return vsMePos;	
		}
	}
	return _oldnear;
}
Example #8
0
void Vector::GetRightUp(Vector &right, Vector &up)
{
   Vector n(X(), Y(), Z());
   Vector fn(fabsf(n.X()), fabsf(n.Y()), fabsf(n.Z()));
   int major = 0;

   if (fn[1] > fn[major]) major = 1;
   if (fn[2] > fn[major]) major = 2;

   // build right vector by hand
   if (fabsf(fn[0]-1.0f) < FLT_EPSILON || fabsf(fn[1]-1.0f) < FLT_EPSILON || fabsf(fn[2]-1.0f) < FLT_EPSILON)
   {
      if (major == 0 && n[0] > 0.f)
      {
         right.Set(0.f, 0.f, -1.f);
      }
      else if (major == 0)
      {
         right.Set(0.f, 0.f, 1.f);
      }
      
      if (major == 1 || (major == 2 && n[2] > 0.f))
      {
         right.Set(1.f, 0.f, 0.f);
      }
   
      if (major == 2 && n[2] < 0.0f)
      {
         right.Set(-1.f, 0.f, 0.f);
      }
   }
   else
   {
      right = axis[major].Cross(n);
   }
  
   up = n.Cross(right);
   right.Normalize();
   up.Normalize();
}
Example #9
0
Vector Vector::operator+ (Vector &v)
{
   float x, y, z;
   Vector vec;

   x = X() + v.X();
   y = Y() + v.Y();
   z = Z() + v.Z();

   vec.Set(x, y, z);

   return vec;
}
Example #10
0
Vector Vector::Cross(Vector &v)
{
   float x, y, z;
   Vector cp;

   x = Y() * v.Z() - Z() * v.Y();
   y = Z() * v.X() - X() * v.Z();
   z = X() * v.Y() - Y() * v.X();

   cp.Set(x, y, z);

   return cp;
}
Example #11
0
void CEnemy::Move(Vector _mypos, Vector _starpos, int _timecount){
	if(Alive){
		if(_timecount-AppearTime>=AliveTime){
			Alive=FALSE;
		}

		if(MoveType==0){	//ランダム直進
		}

		if(MoveType==1){	//自機追尾
			Vector direction;
				direction = GetDirection(_mypos);
				direction.Multiple(0.2);
			Velocity.Add(direction);
			if(Velocity.GetLength()>MaxSpeed) Velocity.Multiple(MaxSpeed/Velocity.GetLength());
		}
		if(MoveType==2){	//母星追尾
			Vector direction;
				direction = GetDirection(_starpos);
				direction.Multiple(0.1);
			Velocity.Add(direction);
			if(Velocity.GetLength()>MaxSpeed) Velocity.Multiple(MaxSpeed/Velocity.GetLength());
		}
		if(MoveType==3){	//出現速度で回転移動
			Vector acceleration;
			int r = 240;
				acceleration.Set(cos((long double)(_timecount-AppearTime)*MaxSpeed/r),sin((long double)(_timecount-AppearTime)*MaxSpeed/r));
				acceleration.Multiple(-1*r*(MaxSpeed/r)*(MaxSpeed/r));
			Velocity.Add(acceleration);
			if(Velocity.GetLength()>MaxSpeed) Velocity.Multiple(MaxSpeed/Velocity.GetLength());
		}
		if(MoveType==4){	//母星の周りを回転移動
			int spin_begin_time = 100;
	
			if(_timecount-AppearTime==spin_begin_time){
				Velocity.Set(0, 0);
				AngleSpeed = (MaxSpeed/(Pos.x-_starpos.x));		//角速度設定
			}else if(_timecount-AppearTime>spin_begin_time){
				Pos.Set(_starpos.x + MaxSpeed*cos((_timecount-AppearTime-spin_begin_time)*AngleSpeed)/AngleSpeed, _starpos.y + MaxSpeed*sin((_timecount-AppearTime-spin_begin_time)*AngleSpeed)/AngleSpeed);
			}
		}

		Pos.Add(Velocity);
			if(Pos.x>WORLD_WIDTH)Pos.x-=WORLD_WIDTH;
			if(Pos.x<0)Pos.x+=WORLD_WIDTH;
			if(Pos.y>WORLD_HEIGHT)Pos.y-=WORLD_HEIGHT;
			if(Pos.y<0)Pos.y+=WORLD_HEIGHT;
	}

}
  void GenTMatrix::TransMultVectorImpl(Number alpha, const Vector &x, Number beta,
                                       Vector &y) const
  {
    //  A few sanity checks
    DBG_ASSERT(NCols()==y.Dim());
    DBG_ASSERT(NRows()==x.Dim());

    // Take care of the y part of the addition
    DBG_ASSERT(initialized_);
    if ( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    // See if we can understand the data
    const DenseVector* dense_x = static_cast<const DenseVector*>(&x);
    DBG_ASSERT(dynamic_cast<const DenseVector*>(&x));
    DenseVector* dense_y = static_cast<DenseVector*>(&y);
    DBG_ASSERT(dynamic_cast<DenseVector*>(&y));

    if (dense_x && dense_y) {
      const Index*  irows=Irows();
      const Index*  jcols=Jcols();
      const Number* val=values_;
      Number* yvals=dense_y->Values();
      yvals--;

      if (dense_x->IsHomogeneous()) {
        Number as = alpha * dense_x->Scalar();
        for (Index i=0; i<Nonzeros(); i++) {
          yvals[*jcols] += as * (*val);
          val++;
          jcols++;
        }
      }
      else {
        const Number* xvals=dense_x->Values();
        xvals--;
        for (Index i=0; i<Nonzeros(); i++) {
          yvals[*jcols] += alpha* (*val) * xvals[*irows];
          val++;
          irows++;
          jcols++;
        }
      }
    }
  }
Example #13
0
  void ZeroMatrix::TransMultVectorImpl(Number alpha, const Vector &x,
                                       Number beta, Vector &y) const
  {
    //  A few sanity checks
    DBG_ASSERT(NCols()==y.Dim());
    DBG_ASSERT(NRows()==x.Dim());

    // Take care of the y part of the addition
    if ( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }
  }
Example #14
0
Vector CEnemy::GetDirection(Vector _targetpos){

		if(Pos.x-_targetpos.x>WORLD_WIDTH/2){
			_targetpos.x+=WORLD_WIDTH;
		}else if(Pos.x-_targetpos.x<-WORLD_WIDTH/2){
			_targetpos.x-=WORLD_WIDTH;
		}
		if(Pos.y-_targetpos.y>WORLD_HEIGHT/2){
			_targetpos.y+=WORLD_HEIGHT;
		}else if(Pos.y-_targetpos.y<-WORLD_HEIGHT/2){
			_targetpos.y-=WORLD_HEIGHT;
		}
	
	Vector direction;
		direction.Set(_targetpos.x-Pos.x, _targetpos.y-Pos.y);
		direction.Multiple(1/direction.GetLength());
	
	return direction;
}
Example #15
0
//--------------------------------------------------------------------------------------
Value* Vector::Clone() const
{
    HRESULT hr;

    Vector* pNewVector = new Vector( Type(), Length() );
    if( NULL == pNewVector )
        return NULL;

    for( UINT i=0; i < Length(); i++ )
    {
        hr = pNewVector->Set( i, Get(i) );
        if( FAILED(hr) )
        {
            // TODO - Error string
            SAFE_DELETE(pNewVector);
            return NULL;
        }
    }

    return pNewVector;
}
Example #16
0
  void SumSymMatrix::MultVectorImpl(Number alpha, const Vector &x,
                                    Number beta, Vector &y) const
  {
    //  A few sanity checks
    DBG_ASSERT(Dim()==x.Dim());
    DBG_ASSERT(Dim()==y.Dim());

    // Take care of the y part of the addition
    if( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    for (Index iterm=0; iterm<NTerms(); iterm++) {
      DBG_ASSERT(IsValid(matrices_[iterm]));
      matrices_[iterm]->MultVector(alpha*factors_[iterm], x,
                                   1.0, y);
    }
  }
Example #17
0
  void DiagMatrix::MultVectorImpl(Number alpha, const Vector &x,
                                  Number beta, Vector &y) const
  {
    //  A few sanity checks
    DBG_ASSERT(Dim()==x.Dim());
    DBG_ASSERT(Dim()==y.Dim());
    DBG_ASSERT(IsValid(diag_));

    // Take care of the y part of the addition
    if ( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    SmartPtr<Vector> tmp_vec = y.MakeNew();
    tmp_vec->Copy(x);
    tmp_vec->ElementWiseMultiply(*diag_);
    y.Axpy(alpha, *tmp_vec);
  }
    //
    // Execute
    //
    U32 Guard::Execute(const U8 *data, Player &player)
    {
      const Data *d = (Data *) data;

      // Create an iterator
      for (UnitObjList::Iterator i(&player.GetSelectedList()); *i; i++)
      {
        // Get the unit
        UnitObj *unit = **i;

        // Can it ever guard
        if (Tasks::UnitGuard::CanGuard(unit))
        {
          switch (d->type)
          {
            case Target::OBJECT:
            {
              // Convert ID into a pointer
              if (MapObj *mapObj = Resolver::Object<MapObj, MapObjType>(d->object))
              {
                IssueTask(d->mod, unit, new Tasks::UnitGuard(unit, Target(mapObj)), player);
              }
              break;
            }

            case Target::LOCATION:
            {
              Vector v;
              v.Set(d->location.x, d->location.y, d->location.z);
              IssueTask(d->mod, unit, new Tasks::UnitGuard(unit, Target(v)), player);
              break;
            }
          }
        }
      }

      return (sizeof (Data));
    }
void GFXVertexList::RenormalizeNormals()
{
    if (data.colors == 0 && data.vertices == 0)
        return;          //
    if (numVertices > 0) {
        Vector firstNormal;
        if (changed&HAS_COLOR)
            firstNormal = data.colors[0].GetNormal();
        else
            firstNormal = data.vertices[0].GetNormal();
        float mag = firstNormal.Magnitude();
        if (mag > GFX_SCALE/1.5 && mag < GFX_SCALE*1.5)
            return;
        if (mag < GFX_SCALE/100 && mag < .00001)
            firstNormal.Set( 1, 0, 0 );
        firstNormal.Normalize();
        if (changed&HAS_COLOR)
            data.colors[0].SetNormal( firstNormal );
        else
            data.vertices[0].SetNormal( firstNormal );
        if (changed&HAS_COLOR) {
            for (int i = 0; i < numVertices; i++) {
                //data.colors[i].SetNormal(data.colors[i].GetNormal().Normalize());
                data.colors[i].i *= GFX_SCALE;
                data.colors[i].j *= GFX_SCALE;
                data.colors[i].k *= GFX_SCALE;
            }
        } else {
            for (int i = 0; i < numVertices; i++) {
                //data.vertices[i].SetNormal(data.vertices[i].GetNormal().Normalize());
                data.vertices[i].i *= GFX_SCALE;
                data.vertices[i].j *= GFX_SCALE;
                data.vertices[i].k *= GFX_SCALE;
            }
        }
    }
}
  void CompoundSymMatrix::MultVectorImpl(Number alpha, const Vector &x,
                                         Number beta, Vector &y) const
  {
    if (!matrices_valid_) {
      matrices_valid_ = MatricesValid();
    }
    DBG_ASSERT(matrices_valid_);

    // The vectors are assumed to be compound Vectors as well
    const CompoundVector* comp_x = dynamic_cast<const CompoundVector*>(&x);
    CompoundVector* comp_y = dynamic_cast<CompoundVector*>(&y);

    //  A few sanity checks
    if (comp_x) {
      DBG_ASSERT(NComps_Dim()==comp_x->NComps());
    }
    else {
      DBG_ASSERT(NComps_Dim() == 1);
    }
    if (comp_y) {
      DBG_ASSERT(NComps_Dim()==comp_y->NComps());
    }
    else {
      DBG_ASSERT(NComps_Dim() == 1);
    }

    // Take care of the y part of the addition
    if( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    for (Index irow=0; irow<NComps_Dim(); irow++) {
      SmartPtr<Vector> y_i;
      if (comp_y) {
        y_i = comp_y->GetCompNonConst(irow);
      }
      else {
        y_i = &y;
      }
      DBG_ASSERT(IsValid(y_i));

      for (Index jcol=0; jcol<=irow; jcol++) {
        SmartPtr<const Vector> x_j;
        if (comp_x) {
          x_j = comp_x->GetComp(irow);
        }
        else {
          x_j = &x;
        }
        DBG_ASSERT(IsValid(x_j));

        if (ConstComp(irow,jcol)) {
          ConstComp(irow,jcol)->MultVector(alpha, *comp_x->GetComp(jcol),
                                           1., *comp_y->GetCompNonConst(irow));
        }
      }

      for (Index jcol = irow+1; jcol < NComps_Dim(); jcol++) {
        if (ConstComp(jcol,irow)) {
          ConstComp(jcol,irow)->TransMultVector(alpha, *comp_x->GetComp(jcol),
                                                1., *comp_y->GetCompNonConst(irow));
        }
      }
    }
  }
Example #21
0
void Camera::SetupView()
{
  if (rect.Width() && rect.Height())
  {
    halfHeight = ((F32) rect.Height()) * 0.5f;
    halfWidth  = ((F32) rect.Width())  * 0.5f;
    aspectHW   = halfHeight / halfWidth;

    if (!isIso)
    {
      projMatrix.SetProjection( nearPlane, farPlane * zoom, fov / zoom, aspectHW);

      if (Vid::renderState.status.clipVis)
      {
        halfHeight -= (F32) 64 * aspectHW;
        halfWidth  -= (F32) 64;
      }
      aspectHW   = halfHeight / halfWidth;

      invProjX = aspectHW / ( projMatrix.right.x * halfHeight);
      invProjY = 1 / (-projMatrix.up.y * halfHeight);
    }
    else
    {
      if (Vid::renderState.status.clipVis)
      {
        halfHeight -= (F32) 64 * aspectHW;
        halfWidth  -= (F32) 64;
      }
      aspectHW   = halfHeight / halfWidth;

      invProjX = 1 / ( projMatrix.right.x * halfHeight);
      invProjY = 1 / (-projMatrix.up.y * halfHeight);
    }

    invDepth  = 1.0f / (farPlane - nearPlane);

    F32 proj23 = projMatrix.frontw == 0 ? 1 : projMatrix.frontw;

    invProjX *= proj23;
    invProjY *= proj23;

  #ifdef __DO_XMM_BUILD
    AllocXmm();
    SetupXmm();
  #endif

    F32 guard = (F32) Vid::renderState.clipGuardSize;

    // guard planes
    //
    F32 kx, ky, z = nearPlane;
    if (isIso)
    {
      kx = invProjX;
      ky = invProjY;
    }
    else
    {
      kx = (z * projMatrix.frontw + projMatrix.positw) * invProjX;
      ky = (z * projMatrix.frontw + projMatrix.positw) * invProjY;
    }

    frustrum[0].x = (-halfWidth  - guard) * kx;
    frustrum[0].y = (-halfHeight - guard) * ky;
    frustrum[0].z = z;

    frustrum[1].x = ( halfWidth  + guard) * kx;
    frustrum[1].y = frustrum[0].y;
    frustrum[1].z = z;

    frustrum[2].x = frustrum[1].x;
    frustrum[2].y = ( halfHeight + guard) * ky;
    frustrum[2].z = z;

    frustrum[3].x = frustrum[0].x;
    frustrum[3].y = frustrum[2].y;
    frustrum[3].z = z;

    z  = farPlane * zoom;
    if (isIso)
    {
      kx = 1.0f * invProjX;
      ky = 1.0f * invProjY;
    }
    else
    {
      kx = (z * projMatrix.frontw + projMatrix.positw) * invProjX;
      ky = (z * projMatrix.frontw + projMatrix.positw) * invProjY;
    }

    frustrum[4].x = (-halfWidth  - guard) * kx;
    frustrum[4].y = (-halfHeight - guard) * ky;
    frustrum[4].z = z;

    frustrum[5].x = ( halfWidth  + guard) * kx;
    frustrum[5].y = frustrum[4].y;
    frustrum[5].z = z;

    frustrum[6].x = frustrum[5].x;
    frustrum[6].y = ( halfHeight + guard) * ky;
    frustrum[6].z = z;

    frustrum[7].x = frustrum[4].x;
    frustrum[7].y = frustrum[6].y;
    frustrum[7].z = z;

    Vector origin;
    origin.Set( 0.0, 0.0, 0.0);

    // near
    guardPlanes[0].Set( frustrum[0], frustrum[1], frustrum[2]);
    guardPlanes[0].Normalize();
    
    // far
    guardPlanes[1].Set( frustrum[4], frustrum[5], frustrum[6]);
    guardPlanes[1].Normalize();

    // left
    guardPlanes[2].Set( origin, frustrum[4], frustrum[7]);
    guardPlanes[2].Normalize();

    // right
    guardPlanes[3].Set( origin, frustrum[5], frustrum[6]);
    guardPlanes[3].Normalize();

    // top
    guardPlanes[4].Set( origin, frustrum[4], frustrum[5]);
    guardPlanes[4].Normalize();

    // bottom
    guardPlanes[5].Set( origin, frustrum[6], frustrum[7]);
    guardPlanes[5].Normalize();

    // fixup direction of plane equations
    U32 i;
    for (i = 0 ; i < 8; i++)
    {
      origin += frustrum[i];
    }
    // all plane equation normals must point towards 'origin'
    // which is the center of all the frustrum points
    origin *= 0.125f;

    for (i = 0; i < 6 ; i++)
    {
      if (guardPlanes[i].Evalue( origin) < 0.0f)
      {
        // change sign of plane equation
        guardPlanes[i] *= -1.0f;
      }
    }

    // real planes
    //
    z = nearPlane;
    if (isIso)
    {
      kx = 1.0f * invProjX;
      ky = 1.0f * invProjY;
    }
    else
    {
      kx = (z * projMatrix.frontw + projMatrix.positw) * invProjX;
      ky = (z * projMatrix.frontw + projMatrix.positw) * invProjY;
    }

    frustrum[0].x = (-halfWidth)  * kx;
    frustrum[0].y = (-halfHeight) * ky;
    frustrum[0].z = z;

    frustrum[1].x = ( halfWidth)  * kx;
    frustrum[1].y = frustrum[0].y;
    frustrum[1].z = z;

    frustrum[2].x = frustrum[1].x;
    frustrum[2].y = ( halfHeight) * ky;
    frustrum[2].z = z;

    frustrum[3].x = frustrum[0].x;
    frustrum[3].y = frustrum[2].y;
    frustrum[3].z = z;

    z  = farPlane * zoom;
    if (isIso)
    {
      kx = 1.0f * invProjX;
      ky = 1.0f * invProjY;
    }
    else
    {
      kx = (z * projMatrix.frontw + projMatrix.positw) * invProjX;
      ky = (z * projMatrix.frontw + projMatrix.positw) * invProjY;
    }

    frustrum[4].x = (-halfWidth)  * kx;
    frustrum[4].y = (-halfHeight) * ky;
    frustrum[4].z = z;

    frustrum[5].x = ( halfWidth)  * kx;
    frustrum[5].y = frustrum[4].y;
    frustrum[5].z = z;

    frustrum[6].x = frustrum[5].x;
    frustrum[6].y = ( halfHeight) * ky;
    frustrum[6].z = z;

    frustrum[7].x = frustrum[4].x;
    frustrum[7].y = frustrum[6].y;
    frustrum[7].z = z;

    origin.Set( 0.0, 0.0, 0.0);

    // near
    planes[0].Set( frustrum[0], frustrum[1], frustrum[2]);
    planes[0].Normalize();

    // far
    planes[1].Set( frustrum[4], frustrum[5], frustrum[6]);
    planes[1].Normalize();

    // left
    planes[2].Set( origin, frustrum[4], frustrum[7]);
    planes[2].Normalize();

    // right
    planes[3].Set( origin, frustrum[5], frustrum[6]);
    planes[3].Normalize();

    // top
    planes[4].Set( origin, frustrum[4], frustrum[5]);
    planes[4].Normalize();

    // bottom
    planes[5].Set( origin, frustrum[6], frustrum[7]);
    planes[5].Normalize();

    // fixup direction of plane equations
    for (i = 0 ; i < 8; i++)
    {
      origin += frustrum[i];
    }
    // all plane equation normals must point towards 'origin'
    // which is the center of all the frustrum points
    origin *= 0.125f;

    for (i = 0; i < 6 ; i++)
    {
      if (planes[i].Evalue( origin) < 0.0f)
      {
        // change sign of plane equation
        planes[i] *= -1.0f;
      }
    }
  }
  if (Vid::curCamera == this)
  {
    Vid::SetCamera( *this, TRUE);
  }
}
Example #22
0
bool	Game::StaticSphereCollisionDetection(Circle* circle1, Circle* circle2, ContactManifold* contactManifold)
{

	// no check if both circles sleep
	if (circle1->getActive() == false && circle2->getActive() == false)
		return false;

	bool loop = false;
	Vector pos1 = circle1->GetPos();
	Vector pos2 = circle2->GetPos();
	float r1 = circle1->GetRadius();
	float r2 = circle2->GetRadius();

	float dist = pos1.distance(pos2);
	dist -= (r1 + r2);

	if(dist < 0.0f)
	{
		// set support var
		circle1->support++;
		circle2->support++;
		////

		// many balls -> poss. that pos1==pos2 -> colNormal = NaN after normalization
		Vector colNormal = (pos1 - pos2).normalise();

		Vector n1, n2;
		n1 = n2 = colNormal;

		Vector hitPoint = pos1 + circle1->GetRadius() * (pos1-pos2).normalise();
		// Save the penetration value in the unused Z component 
		hitPoint.Set(hitPoint.GetX(), hitPoint.GetY(), -dist);

			ManifoldPoint mpoint;
			mpoint.contactID1 = circle1;
			mpoint.contactID2 = circle2;
			mpoint.contactPoint = hitPoint;
			mpoint.responded = false;
			mpoint.impulse = 0.0f;
			mpoint.t_impulse = 0;
			mpoint.t = -1;
			mpoint.contactNormal = colNormal;
			contactManifold->Add(mpoint);
			
			circle1->setActive(true);
			circle2->setActive(true);
			return false;

		pos1 = pos1 - (n1 * dist * 1.1f);
		pos2 = pos2 + (n2 * dist * 1.1f);


		// critical section
		circle1->SetPos(pos1.GetX(), pos1.GetY());
		circle2->SetPos(pos2.GetX(), pos2.GetY());
		// critical section

		// make sure collided circles are awake
		circle1->setActive(true);
		circle2->setActive(true);

		loop = true;
	}

	return loop;
}
Example #23
0
// =========================
// Function called by CYTHON
// =========================
int trk2dictionary(
    char* strTRKfilename, int Nx, int Ny, int Nz, float Px, float Py, float Pz, int n_count, int n_scalars, int n_properties, 		float fiber_shiftX, float fiber_shiftY, float fiber_shiftZ, int points_to_skip, float min_seg_len,
    float* ptrPEAKS, int Np, float vf_THR, int ECix, int ECiy, int ECiz,
    float* _ptrMASK, float* ptrTDI, char* path_out, int c
)
{
    /*=========================*/
    /*     IC compartments     */
    /*=========================*/
    float          fiber[3][MAX_FIB_LEN];
    float          fiberNorm, fiberLen;
    unsigned int   N, totICSegments = 0, totFibers = 0;
    unsigned char  kept;
    Vector<double> P;
    std::string    filename;
    std::string    OUTPUT_path(path_out);
    std::map<segKey,float>::iterator it;

    std::map<segInVoxKey,float> FiberNorm;
    std::map<segInVoxKey,float>::iterator itNorm;
    segInVoxKey         inVoxKey;

    printf( "\t* Exporting IC compartments:\n" );

    FILE* fpTRK = fopen(strTRKfilename,"r+b");
    if (fpTRK == NULL) return 0;
    fseek(fpTRK,1000,SEEK_SET);

    // set global variables
    dim.Set( Nx, Ny, Nz );
    pixdim.Set( Px, Py, Pz );
    nPointsToSkip = points_to_skip;
    fiberShiftXmm = fiber_shiftX * pixdim.x; // shift in mm for the coordinates
    fiberShiftYmm = fiber_shiftY * pixdim.y;
    fiberShiftZmm = fiber_shiftZ * pixdim.z;
    ptrMASK       = _ptrMASK;
    doIntersect   = c > 0;
    minSegLen     = min_seg_len;

    // open files
    filename = OUTPUT_path+"/dictionary_TRK_norm.dict";   FILE* pDict_TRK_norm = fopen(filename.c_str(),"wb");
    if ( !pDict_TRK_norm )
    {
        printf( "\n[trk2dictionary] Unable to create output files" );
        return 0;
    }
    filename = OUTPUT_path+"/dictionary_IC_f.dict";        FILE* pDict_IC_f      = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_IC_vx.dict";       FILE* pDict_IC_vx     = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_IC_vy.dict";       FILE* pDict_IC_vy     = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_IC_vz.dict";       FILE* pDict_IC_vz     = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_IC_ox.dict";       FILE* pDict_IC_ox     = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_IC_oy.dict";       FILE* pDict_IC_oy     = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_IC_len.dict";      FILE* pDict_IC_len    = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_TRK_len.dict";     FILE* pDict_TRK_len   = fopen(filename.c_str(),"wb");
    filename = OUTPUT_path+"/dictionary_TRK_kept.dict";    FILE* pDict_TRK_kept  = fopen(filename.c_str(),"wb");

    // iterate over fibers
    ProgressBar PROGRESS( n_count );
    PROGRESS.setPrefix("\t  ");
    for(int f=0; f<n_count ;f++)
    {
        PROGRESS.inc();
        N = read_fiber( fpTRK, fiber, n_scalars, n_properties );
        fiberForwardModel( fiber, N );

        kept = 0;
        if ( FiberSegments.size() > 0 )
        {
            // add segments to files
            fiberNorm = 0;
			fiberLen = 0;
            for (it=FiberSegments.begin(); it!=FiberSegments.end(); it++)
            {
                fwrite( &totFibers,      4, 1, pDict_IC_f );
                fwrite( &(it->first.x),  1, 1, pDict_IC_vx );
                fwrite( &(it->first.y),  1, 1, pDict_IC_vy );
                fwrite( &(it->first.z),  1, 1, pDict_IC_vz );
                fwrite( &(it->first.ox), 1, 1, pDict_IC_ox );
                fwrite( &(it->first.oy), 1, 1, pDict_IC_oy );
                fwrite( &(it->second),   4, 1, pDict_IC_len );
                ptrTDI[ it->first.z + dim.z * ( it->first.y + dim.y * it->first.x ) ] += it->second;
                inVoxKey.set( it->first.x, it->first.y, it->first.z );
                FiberNorm[inVoxKey] += it->second;
				fiberLen += it->second;
            }
            for (itNorm=FiberNorm.begin(); itNorm!=FiberNorm.end(); itNorm++)
            {
                fiberNorm += pow(itNorm->second,2);
            }
            fiberNorm = sqrt(fiberNorm);
            FiberNorm.clear();
            fwrite( &fiberNorm,  1, 4, pDict_TRK_norm ); // actual length considered in optimization
			fwrite( &fiberLen,  1, 4, pDict_TRK_len );
            totICSegments += FiberSegments.size();
            totFibers++;
            kept = 1;
        }
        fwrite( &kept, 1, 1, pDict_TRK_kept );
    }
    PROGRESS.close();

    fclose( fpTRK );
    fclose( pDict_TRK_norm );
    fclose( pDict_IC_f );
    fclose( pDict_IC_vx );
    fclose( pDict_IC_vy );
    fclose( pDict_IC_vz );
    fclose( pDict_IC_ox );
    fclose( pDict_IC_oy );
    fclose( pDict_IC_len );
    fclose( pDict_TRK_len );
    fclose( pDict_TRK_kept );

    printf("\t  [ %d fibers kept, %d segments in total ]\n", totFibers, totICSegments );


    /*=========================*/
    /*     EC compartments     */
    /*=========================*/
    unsigned int totECSegments = 0, totECVoxels = 0;

    printf( "\t* Exporting EC compartments:\n" );

    filename = OUTPUT_path+"/dictionary_EC_vx.dict";       FILE* pDict_EC_vx  = fopen( filename.c_str(),   "wb" );
    filename = OUTPUT_path+"/dictionary_EC_vy.dict";       FILE* pDict_EC_vy  = fopen( filename.c_str(),   "wb" );
    filename = OUTPUT_path+"/dictionary_EC_vz.dict";       FILE* pDict_EC_vz  = fopen( filename.c_str(),   "wb" );
    filename = OUTPUT_path+"/dictionary_EC_ox.dict";       FILE* pDict_EC_ox  = fopen( filename.c_str(),   "wb" );
    filename = OUTPUT_path+"/dictionary_EC_oy.dict";       FILE* pDict_EC_oy  = fopen( filename.c_str(),   "wb" );

    if ( ptrPEAKS != NULL )
    {
        Vector<double> dir;
        double         longitude, colatitude;
        segKey         ec_seg;
        int            ix, iy, iz, id, atLeastOne;
        float          peakMax;
        float          norms[ Np ];
        float          *ptr;

        PROGRESS.reset( dim.z );
        for(iz=0; iz<dim.z ;iz++)
        {
            PROGRESS.inc();
            for(iy=0; iy<dim.y ;iy++)
            for(ix=0; ix<dim.x ;ix++)
            {
                // check if in mask previously computed from IC segments
                if ( ptrTDI[ iz + dim.z * ( iy + dim.y * ix ) ] == 0 ) continue;

                peakMax = -1;
                for(id=0; id<Np ;id++)
                {
                    ptr = ptrPEAKS + 3*(id + Np * ( iz + dim.z * ( iy + dim.y * ix ) ));
                    dir.x = ptr[0];
                    dir.y = ptr[1];
                    dir.z = ptr[2];
                    norms[id] = dir.norm();
                    if ( norms[id] > peakMax )
                        peakMax = norms[id];
                }

                if ( peakMax > 0 )
                {
                    ec_seg.x  = ix;
                    ec_seg.y  = iy;
                    ec_seg.z  = iz;
                    atLeastOne = 0;
                    for(id=0; id<Np ;id++)
                    {
                        if ( norms[id]==0 || norms[id] < vf_THR*peakMax ) continue; // peak too small, don't consider it

                        // store this orientation (invert axes if needed)
                        ptr = ptrPEAKS + 3*(id + Np * ( iz + dim.z * ( iy + dim.y * ix ) ));
                        dir.x = ECix * ptr[0];
                        dir.y = ECiy * ptr[1];
                        dir.z = ECiz * ptr[2];
                        if ( dir.y < 0 )
                        {
                            // ensure to be in the right hemisphere (the one where kernels were pre-computed)
                            dir.x = -dir.x;
                            dir.y = -dir.y;
                            dir.z = -dir.z;
                        }
                        colatitude = atan2( sqrt(dir.x*dir.x + dir.y*dir.y), dir.z );
                        longitude  = atan2( dir.y, dir.x );
                        ec_seg.ox = (int)round(colatitude/M_PI*180.0);
                        ec_seg.oy = (int)round(longitude/M_PI*180.0);
                        fwrite( &ec_seg.x,   1, 1, pDict_EC_vx );
                        fwrite( &ec_seg.y,   1, 1, pDict_EC_vy );
                        fwrite( &ec_seg.z,   1, 1, pDict_EC_vz );
                        fwrite( &ec_seg.ox,  1, 1, pDict_EC_ox );
                        fwrite( &ec_seg.oy,  1, 1, pDict_EC_oy );
                        totECSegments++;
                        atLeastOne = 1;
                    }
                    if ( atLeastOne>0 )
                        totECVoxels++;
                }
            }
        }
        PROGRESS.close();
    }

    fclose( pDict_EC_vx );
    fclose( pDict_EC_vy );
    fclose( pDict_EC_vz );
    fclose( pDict_EC_ox );
    fclose( pDict_EC_oy );

    printf("\t  [ %d voxels, %d segments ]\n", totECVoxels, totECSegments );

    return 1;
}
Example #24
0
// draw atom spheres and residue labels here
bool Residue::Draw(const AtomSet *atomSet) const
{
    if (!atomSet) {
        ERRORMSG("Residue::Draw(data) - NULL AtomSet*");
        return false;
    }

    // verify presense of OpenGLRenderer
    if (!parentSet->renderer) {
        WARNINGMSG("Residue::Draw() - no renderer");
        return false;
    }

    // get Molecule parent
    const Molecule *molecule;
    if (!GetParentOfType(&molecule)) return false;

    // get object parent
    const StructureObject *object;
    if (!GetParentOfType(&object)) return false;

    // is this residue labeled?
    const StyleSettings& settings = parentSet->styleManager->GetStyleForResidue(object, molecule->id, id);
    bool proteinLabel = (IsAminoAcid() && settings.proteinLabels.spacing > 0 &&
        (id-1)%settings.proteinLabels.spacing == 0);
    bool nucleotideLabel = (IsNucleotide() && settings.nucleotideLabels.spacing > 0 &&
        (id-1)%settings.nucleotideLabels.spacing == 0);

    bool overlayEnsembles = parentSet->showHideManager->OverlayConfEnsembles();
    AtomStyle atomStyle;
    const AtomCoord *atom, *l1 = NULL, *l2 = NULL, *l3 = NULL;
    Vector labelColor;
    bool alphaVisible = false, alphaOnly = false;

    // iterate atoms; key is atomID
    AtomInfoMap::const_iterator a, ae = atomInfos.end();
    for (a=atomInfos.begin(); a!=ae; ++a) {

        // get AtomCoord* for appropriate altConf
        AtomPntr ap(molecule->id, id, a->first);
        atom = atomSet->GetAtom(ap, overlayEnsembles, true);
        if (!atom) continue;

        // get Style
        if (!parentSet->styleManager->GetAtomStyle(this, ap, atom, &atomStyle))
            return false;

        // highlight atom if necessary
        if (atomStyle.isHighlighted)
            atomStyle.color = GlobalColors()->Get(Colors::eHighlight);

        // draw the atom
        if (atomStyle.style != StyleManager::eNotDisplayed && atomStyle.radius > 0.0)
            parentSet->renderer->DrawAtom(atom->site, atomStyle);

        // store coords for positioning label, based on backbone coordinates
        if ((proteinLabel || nucleotideLabel) && a->second->classification != eSideChainAtom) {
            if (IsAminoAcid()) {
                if (a->second->name == " CA ") {
                    l1 = atom;
                    labelColor = atomStyle.color;
                    alphaVisible = (atomStyle.style != StyleManager::eNotDisplayed);
                }
                else if (a->second->name == " C  ") l2 = atom;
                else if (a->second->name == " N  ") l3 = atom;
            } else if (IsNucleotide()) {
                if (a->second->name == " P  ") {
                    l1 = atom;
                    labelColor = atomStyle.color;
                    alphaVisible = (atomStyle.style != StyleManager::eNotDisplayed);
                }
                // labeling by alphas seems to work better for nucleotides
//                else if (a->second->name == " C4*") l2 = atom;
//                else if (a->second->name == " C5*") l3 = atom;
            }
        }
    }

    // if not all backbone atoms present (e.g. alpha only), use alpha coords of neighboring residues
    if (l1 && (!l2 || !l3)) {
        Molecule::ResidueMap::const_iterator prevRes, nextRes;
        const AtomCoord *prevAlpha, *nextAlpha;
        if ((prevRes=molecule->residues.find(id - 1)) != molecule->residues.end() &&
            prevRes->second->alphaID != NO_ALPHA_ID &&
            (prevAlpha=atomSet->GetAtom(AtomPntr(molecule->id, id - 1, prevRes->second->alphaID))) != NULL &&
            (nextRes=molecule->residues.find(id + 1)) != molecule->residues.end() &&
            nextRes->second->alphaID != NO_ALPHA_ID &&
            (nextAlpha=atomSet->GetAtom(AtomPntr(molecule->id, id + 1, nextRes->second->alphaID))) != NULL)
        {
            l2 = prevAlpha;
            l3 = nextAlpha;
            alphaOnly = true;
        }
    }

    // draw residue (but not terminus) labels, assuming we have the necessary coordinates and
    // that alpha atoms are visible
    if (alphaVisible && (proteinLabel|| nucleotideLabel)) {
        Vector labelPosition;
        CNcbiOstrstream oss;

        double contrast = Colors::IsLightColor(settings.backgroundColor) ? 0 : 1;

        // protein label
        if (IsAminoAcid() && l1 && l2 && l3) {
            // position
            if (alphaOnly) {
                Vector forward = - ((l2->site - l1->site) + (l3->site - l1->site));
                forward.normalize();
                labelPosition = l1->site + 1.5 * forward;
            } else {
                Vector up = vector_cross(l2->site - l1->site, l3->site - l1->site);
                up.normalize();
                Vector forward = (-((l2->site - l1->site) + (l3->site - l1->site)) / 2);
                forward.normalize();
                labelPosition = l1->site + 1.5 * forward + 1.5 * up;
            }
            // text
            if (settings.proteinLabels.type == StyleSettings::eOneLetter) {
                oss << code;
            } else if (settings.proteinLabels.type == StyleSettings::eThreeLetter) {
                for (unsigned int i=0; i<nameGraph.size() && i<3; ++i)
                    oss << ((i == 0) ? (char) toupper((unsigned char) nameGraph[0]) : (char) tolower((unsigned char) nameGraph[i]));
            }
            // add number if necessary
            if (settings.proteinLabels.numbering == StyleSettings::eSequentialNumbering)
                oss << ' ' << id;
            else if (settings.proteinLabels.numbering == StyleSettings::ePDBNumbering)
                oss << namePDB;
            // contrasting color? (default to CA's color)
            if (settings.proteinLabels.white) labelColor.Set(contrast, contrast, contrast);
        }

        // nucleotide label
        else if (IsNucleotide() && l2 && l3) {
            if (alphaOnly) {
                Vector forward = - ((l2->site - l1->site) + (l3->site - l1->site));
                forward.normalize();
                labelPosition = l1->site + 3 * forward;
            } else {
                labelPosition = l3->site + 3 * (l3->site - l2->site);
            }
            // text
            if (settings.nucleotideLabels.type == StyleSettings::eOneLetter) {
                oss << code;
            } else if (settings.nucleotideLabels.type == StyleSettings::eThreeLetter) {
                for (unsigned int i=0; i<3; ++i)
                    if (nameGraph.size() > i && nameGraph[i] != ' ')
                        oss << nameGraph[i];
            }
            // add number if necessary
            if (settings.nucleotideLabels.numbering == StyleSettings::eSequentialNumbering)
                oss << ' ' << id;
            else if (settings.nucleotideLabels.numbering == StyleSettings::ePDBNumbering)
                oss << namePDB;
            // contrasting color? (default to C4*'s color)
            if (settings.nucleotideLabels.white) labelColor.Set(contrast, contrast, contrast);
        }

        // draw label
        if (oss.pcount() > 0) {
            string labelText = (string) CNcbiOstrstreamToString(oss);

            // apply highlight color if necessary
            if (GlobalMessenger()->IsHighlighted(molecule, id))
                labelColor = GlobalColors()->Get(Colors::eHighlight);

            parentSet->renderer->DrawLabel(labelText, labelPosition, labelColor);
        }
    }

    return true;
}
Example #25
0
 /** Compute the max-norm of the columns in the matrix.  The result
  *  is stored in cols_norms  The vector is assumed to be initialized
  *  of init is false. */
 void ComputeColAMax(Vector& cols_norms, bool init=true) const
 {
   DBG_ASSERT(NCols() == cols_norms.Dim());
   if (init) cols_norms.Set(0.);
   ComputeColAMaxImpl(cols_norms, init);
 }
Example #26
0
 /** Compute the max-norm of the rows in the matrix.  The result is
  *  stored in rows_norms.  The vector is assumed to be initialized
  *  of init is false. */
 void ComputeRowAMax(Vector& rows_norms, bool init=true) const
 {
   DBG_ASSERT(NRows() == rows_norms.Dim());
   if (init) rows_norms.Set(0.);
   ComputeRowAMaxImpl(rows_norms, init);
 }
Example #27
0
File: main.C Project: gberan/HMBI
/*
HMBI code.  Invoke as:
      hmbi <input file> [# of processors]

The number of processors is optional, and the default is 1.  To run
in code in parallel, the source code must be compiled with -DPARALLEL,
and MPI is required.

*/
main(int argc, char ** argv) {
  
  if (argc < 2) {
    printf("HMBI syntax:: hmbi <input file> [ # of processors (optional)]\n");
    exit(1);
  }
  
  int nproc = 1;
  if (argc > 2) {
    string tmp = argv[2];
    nproc = atoi(tmp.c_str());
  }

#ifdef PARALLEL
  int mynode=0,totalnodes;

  if (nproc > 1) {
    MPI_Init(&argc, &argv);
    MPI_Comm io_comm;
    
    MPI_File *fh, *fg;      
    MPI_Info info;       

    MPI_Comm_size(MPI_COMM_WORLD, &totalnodes); // get totalnodes
    MPI_Comm_rank(MPI_COMM_WORLD, &mynode);     // get mynode
    if (mynode==0) 
      printf("Running MPI parallel version with %d processors\n",nproc);

  }

  if (mynode == 0) {  
#endif /* PARALLEL */

    // Set the number of processors
    Params::Parameters().SetNumberOfProcessors(nproc);

    // Store the primary process ID of the job.  Used to create unique
    // scratch files
    int pid = getpid();
    Params::Parameters().SetPID(pid);

    // Start wall clock timer
    time_t start_time, stop_time;
    start_time = time(NULL);
     
    // Open input file
    const int maxlength = 50;
    char filename[maxlength];
    strcpy(filename, argv[1]);

    ifstream infile;
    infile.open(filename);
    assert(infile.is_open()); 
    
    // Initialize Cluster object
    Cluster::cluster().Initialize(infile,nproc);
    printf("Cluster initialization complete\n");

    if (! Params::Parameters().DoForces())
      Params::Parameters().SetUseDLFind(false);

    // Compute the Energy (and forces, if requested)
    if (!Params::Parameters().UseDLFind()) {
      Cluster::cluster().RunJobsAndComputeEnergy();
    }

    if ( Params::Parameters().PrintLevel() > 0)
      Cluster::cluster().ComputeDistanceMatrix();

    // For debugging: Compute finite difference stress tensor
    bool do_finite_difference_stress_tensor = false;
    if (do_finite_difference_stress_tensor) {
      double delta = 0.001; // step size, in Angstroms

      Vector a1(3), a2(3), a3(3); // original unit cell vectors
      Vector new_a1(3),new_a2(3), new_a3(3); // deformed unit cell vectors
      Matrix Strain(3,3), Stress(3,3); 
      Stress.Set();
      
      // Grab original unit cell vectors
      a1 = Cluster::cluster().GetUnitCellVector(0);
      a2 = Cluster::cluster().GetUnitCellVector(1);
      a3 = Cluster::cluster().GetUnitCellVector(2);
      printf("Original lattice vectors (Ang):\n");
      printf("a1 = (%f, %f, %f)\n",a1[0],a1[1],a1[2]);
      printf("a2 = (%f, %f, %f)\n",a2[0],a2[1],a2[2]);
      printf("a3 = (%f, %f, %f)\n",a3[0],a3[1],a3[2]);

      // Get cell volume, convert to Bohr^3
      double V = Cluster::cluster().GetCellvolume() * AngToBohr * AngToBohr * AngToBohr;

      // Get the atomic coords.  We use these when triggering the
      // reset of the dimer images, even though we don't change the atomic
      // positions at all.
      Vector Coords = Cluster::cluster().GetCurrentCoordinates();

	// Loop over elements of the strain tensor e_ij
	for (int i=0;i<3;i++) {
	  for (int j=0;j<3;j++) {

	    // Set one element of the strain tensor to +delta
	    printf("Setting Strain(%d,%d) to +%f\n",i,j,delta);
	    Strain.Set(); new_a1.Set(); new_a2.Set(); new_a3.Set();
	    Strain(i,j) = delta;
	    Strain.Print("Strain tensor");
	    
	    // Deform the lattice vectors: new_ai = ai + Strain * ai
	    new_a1 = Strain.MatrixTimesVector(a1);
	    new_a1 += a1;
	    new_a2 = Strain.MatrixTimesVector(a2);
	    new_a2 += a2;
	    new_a3 = Strain.MatrixTimesVector(a3);
	    new_a3 += a3;
	    
	    printf("Updated lattice vectors (Ang):\n");
	    printf("a1 = (%f, %f, %f)\n",new_a1[0],new_a1[1],new_a1[2]);
	    printf("a2 = (%f, %f, %f)\n",new_a2[0],new_a2[1],new_a2[2]);
	    printf("a3 = (%f, %f, %f)\n",new_a3[0],new_a3[1],new_a3[2]);

	    // Set the new lattice vectors and get the energy
	    Cluster::cluster().SetUnitCellVectors(new_a1, new_a2, new_a3);
	    Cluster::cluster().SetNewCoordinates(Coords);
	    Cluster::cluster().RunJobsAndComputeEnergy();
	    double E1 = Cluster::cluster().GetHMBIEnergy();

	    // Repeat for strain tensor element -delta
	    printf("Setting Strain(%d,%d) to -%f\n",i,j,delta);
	    Strain.Set(); new_a1.Set(); new_a2.Set(); new_a3.Set();
	    Strain(i,j) = -delta;
	    Strain.Print("Strain tensor");
	    
	    // Deform the lattice vectors: new_ai = ai + Strain * ai
	    new_a1 = Strain.MatrixTimesVector(a1);
	    new_a1 += a1;
	    new_a2 = Strain.MatrixTimesVector(a2);
	    new_a2 += a2;
	    new_a3 = Strain.MatrixTimesVector(a3);
	    new_a3 += a3;
	    
	    printf("Updated lattice vectors (Ang):\n");
	    printf("a1 = (%f, %f, %f)\n",new_a1[0],new_a1[1],new_a1[2]);
	    printf("a2 = (%f, %f, %f)\n",new_a2[0],new_a2[1],new_a2[2]);
	    printf("a3 = (%f, %f, %f)\n",new_a3[0],new_a3[1],new_a3[2]);

	    // Set the new lattice vectors and get the energy
	    Cluster::cluster().SetUnitCellVectors(new_a1, new_a2, new_a3);
	    Cluster::cluster().SetNewCoordinates(Coords);
	    Cluster::cluster().RunJobsAndComputeEnergy();
	    double E2 = Cluster::cluster().GetHMBIEnergy();

	    // Final Stress tensor element stress(i,j) = 1/V dE/dstrain(i,j)
	    Stress(i,j) = (1.0/V)*(E1 - E2)/(2*delta);
	  }
	}

	printf("Finite Difference Stress Tensor:\n");
	for (int i=0;i<3;i++) {
	  printf("%15.9f  %15.9f  %15.9f\n",Stress(i,0), Stress(i,1), Stress(i,2));
	}
    }



  
    // For debugging: Compute finite difference gradients
    bool do_finite_difference_grad = Params::Parameters().UseFiniteDifferenceGradients();
    if (do_finite_difference_grad && Params::Parameters().DoForces()) {

      Vector Grad = Cluster::cluster().GetHMBIGradient();
      Grad.Print("Analytical HMBI Gradient");
      int Natoms = Cluster::cluster().GetTotalNumberOfAtoms();
      Vector Eplus(3*Natoms), Eminus(3*Natoms);
      Vector Original_coords = Cluster::cluster().GetCurrentCoordinates();

      Vector LatticeGradient(6);
      LatticeGradient.Set();

      // Do the finite difference
      double delta = 0.001; // step size, in Angstroms
      /*
      for (int i=0;i<3*Natoms;i++) {

	printf("Shifting coord %d by -%f\n",i,delta);
	Vector Coords = Original_coords;
	Coords[i] -= delta;
	// Update the coordinates & get the energy
	Cluster::cluster().SetNewCoordinates(Coords);
	Cluster::cluster().RunJobsAndComputeEnergy();
	Eplus[i] = Cluster::cluster().GetHMBIEnergy();

	printf("Shifting coord %d by +%f\n",i,delta);
	Coords[i] += 2.0*delta;
	// Update the coordinates & get the energy
	Cluster::cluster().SetNewCoordinates(Coords);
	Cluster::cluster().RunJobsAndComputeEnergy();
	Eminus[i] = Cluster::cluster().GetHMBIEnergy();
      
      }
      */
      // Now do finite difference over the lattice parameters, if appropriate
      double deltaTheta = 0.01;
      if (Params::Parameters().IsPeriodic() ) {
	string *params;
	params = new string[6];
	params[0] = "a"; params[1] = "b"; params[2] = "c";
	params[3] = "alpha", params[4] = "beta"; params[5] = "gamma";

	Vector Coords = Original_coords; // we need these to trigger the reset of the
	// dimer images, even if we don't change the atomic positions at all.

	for (int i=0;i<6;i++) {
	  double current = Cluster::cluster().GetUnitCellParameter(params[i]);
	  double new1,new2;
	  if (i < 3) {
	    printf("Shifting coord %s by -%f\n",params[i].c_str(),delta);
	    new1 = current - delta;
	  }
	  else {
	    printf("Shifting coord %s by -%f\n",params[i].c_str(),deltaTheta);
	    new1 = current - deltaTheta;
	  }
	  Cluster::cluster().SetUnitCellParameter(params[i],new1);
	  Cluster::cluster().SetNewCoordinates(Coords);
	  Cluster::cluster().RunJobsAndComputeEnergy();
	  double E1 = Cluster::cluster().GetHMBIEnergy();

	  if (i < 3) {
	    printf("Shifting coord %s by +%f\n",params[i].c_str(),delta);
	    new2 = current + delta;
	  }
	  else {
	    printf("Shifting coord %s by +%f\n",params[i].c_str(),deltaTheta);
	    new2 = current + deltaTheta;
	  }
	  // Update the coordinates & get the energy
	  Cluster::cluster().SetUnitCellParameter(params[i],new2);
	  Cluster::cluster().SetNewCoordinates(Coords);
	  Cluster::cluster().RunJobsAndComputeEnergy();
	  double E2 = Cluster::cluster().GetHMBIEnergy();

	  if (i < 3) {
	    LatticeGradient[i] = (E2 - E1) / ((new2 - new1)*AngToBohr);
	  }
	  else{
	    LatticeGradient[i] = (E2 - E1) / ((new2 - new1)*DegreesToRadians);
	  }

	  // Reset the lattice parameter to its original value
	  Cluster::cluster().SetUnitCellParameter(params[i],current);

	}

      }

      // Form the actual gradient, G = (Eminus - Eplus)/(2*delta)
      Grad.Set();
      Grad = Eminus;
      Grad -= Eplus;
      Grad.Scale(1.0/(2*delta*AngToBohr));

      Grad.Print("Finite Difference HMBI Gradient");

      LatticeGradient.Print("Finite Difference Lattice Parameter Gradient");

      printf("*** Finished with finite difference.");
      exit(1);
    }
    // End finite difference debug code

    
    // Optimize geometry, if requested
    if ( Params::Parameters().DoForces() ) {
      if (Params::Parameters().UseDLFind()) {
	// Use DL-FIND for geometry optimization
	int Natoms = Cluster::cluster().GetTotalNumberOfAtoms();
	int nvarin = 3*Natoms;
	int nvarin2 = 5*Natoms;// nframe*nat*3 + nweight + nmass + n_po_scaling
	int nspec = 2*Natoms; // nspec= nat + nz + 5*ncons + 2*nconn
	int master = 1; // work is done on the master node
	printf("Using DL-FIND for optimization\n");
	dl_find_(&nvarin, &nvarin2, &nspec, &master);

	// Final energy printing doesn't work, because final
	//dlf_put_coords erases energies...  
	double energy =	Cluster::cluster().GetHMBIEnergy();
	printf("HMBI Final Energy = %15.9f\n",energy);

	printf("\n");
	Cluster::cluster().ComputeDistanceMatrix();

	// Save a copy of the new geometry in a new input file.
	FILE *input;
	string input_file = "new_geom.in";
	if ((input = fopen(input_file.c_str(),"w"))==NULL) {
	  printf("OptimizeGeometry() : Cannot open file '%s'\n",input_file.c_str());
	  exit(1);
	}
	
	Cluster::cluster().PrintInputFile(input);
	printf("\nNew input file written to '%s'\n",input_file.c_str());
	fclose(input);

      }
      else{
	
	string type = "SteepestDescent";
	//string type = "ConjugateGradients";
	OptimizeGeometry(type );
      }
    }



    if ( Params::Parameters().GetJobTypeStr() == "hessian" ) {
      printf("Computing finite difference Hessian\n");  fflush(stdout);
      Vector Original_coords = Cluster::cluster().GetCurrentCoordinates();
      int imon = Params::Parameters().GetFrequencyForMonomer();
      printf("Computing the vibrational frequencies for Monomer %d\n",imon);
      Matrix Hessian = GetFiniteDifferenceHessian(Original_coords,imon);

      Cluster::cluster().ComputeHarmonicFrequencies(Hessian);

	

    }
    
    infile.close();

    
    if (Params::Parameters().CheckWarnings() > 0) {
      printf("\nHMBI job completed, but with %d warning(s).\n",Params::Parameters().CheckWarnings());
    }
    else {
      printf("\nHMBI job succesful!!!\n");
    } 

#ifdef PARALLEL    
    // Tell all nodes to shut down
    if (nproc > 1) {
      MPI_Comm_size(MPI_COMM_WORLD, &totalnodes); // get totalnodes
      for (int rank = 1; rank < totalnodes; rank++) {
	MPI_Send(0, 0, MPI_INT, rank, DIETAG, MPI_COMM_WORLD);
      }
    }
#endif /* PARALLEL */

    // Stop the timer and print out the time
    stop_time = time(NULL);
    double elapsed_time = difftime(stop_time,start_time);
    printf("Total job wall time = %.0f seconds\n",elapsed_time);

#ifdef PARALLEL
  }
  
  else {
    /* Slave node controller: just accept & run the jobs */

    int MPI_PrintLevel = 0;

    MPI_Comm_size(MPI_COMM_WORLD, &totalnodes); // get totalnodes
    MPI_Comm_rank(MPI_COMM_WORLD, &mynode);     // get mynode      

    while (1) {
      char job[BUFFSIZE];
      int success;
      MPI_Status status;
      while (1) {
	success = 0;
	// run the job
	MPI_Recv(&job,BUFFSIZE,MPI_CHAR,0,MPI_ANY_TAG,MPI_COMM_WORLD,&status);
	
	/* Check the tag of the received message. */
	if (status.MPI_TAG == DIETAG) {
	  //printf("%d: Received DIETAG\n",mynode);
	  break;
	}
	else if (status.MPI_TAG == QCHEM_TAG) {
	  if (MPI_PrintLevel > 0 )
	    printf("%d: Q-chem job: %s\n",mynode,job);
	}
	else if (status.MPI_TAG == TINKER_TAG) {
	  if (MPI_PrintLevel > 0 )
	    printf("%d: Tinker job: %s\n",mynode,job);
	}
	else if (status.MPI_TAG == CAMCASP_TAG) {
	  if (MPI_PrintLevel > 0 )
	    printf("%d: CamCasp job: %s\n",mynode,job);
	}
	else {
	  printf("Unknown MPI tag\n");
	}

	// Go ahead and run the job 
	system(job);
	string jobstr = job;
	success = CheckIfJobSuccessful(jobstr,status.MPI_TAG);
	
	//MPI_Send(&success,1,MPI_INT,0,0,MPI_COMM_WORLD);
	MPI_Send(&success,1,MPI_INT,0,status.MPI_TAG,MPI_COMM_WORLD);
      }
      if (MPI_PrintLevel > 0 )
	printf("MPI: Node %d exiting\n",mynode);
      break;
    } 
  }
  // Finalize MPI and exit
  fflush(stdout);
  MPI_Finalize();
#endif /* PARALLEL */
}
Example #28
0
  void CompoundMatrix::MultVectorImpl(Number alpha, const Vector &x,
                                      Number beta, Vector &y) const
  {
    if (!matrices_valid_) {
      matrices_valid_ = MatricesValid();
    }
    DBG_ASSERT(matrices_valid_);

    // The vectors are assumed to be compound Vectors as well
    const CompoundVector* comp_x = dynamic_cast<const CompoundVector*>(&x);
    CompoundVector* comp_y = dynamic_cast<CompoundVector*>(&y);

#ifndef ALLOW_NESTED
    //  A few sanity checks
    if (comp_x) {
      DBG_ASSERT(NComps_Cols()==comp_x->NComps());
    }
    else {
      DBG_ASSERT(NComps_Cols() == 1);
    }

    if (comp_y) {
      DBG_ASSERT(NComps_Rows()==comp_y->NComps());
    }
    else {
      DBG_ASSERT(NComps_Rows() == 1);
    }
#endif
    if (comp_x) {
      if (NComps_Cols()!=comp_x->NComps()) {
        comp_x = NULL;
      }
    }
    if (comp_y) {
      if (NComps_Rows()!=comp_y->NComps()) {
        comp_y = NULL;
      }
    }

    // Take care of the y part of the addition
    if ( beta!=0.0 ) {
      y.Scal(beta);
    }
    else {
      y.Set(0.0);  // In case y hasn't been initialized yet
    }

    for ( Index irow = 0; irow < NComps_Rows(); irow++ ) {
      SmartPtr<Vector> y_i;
      if (comp_y) {
        y_i = comp_y->GetCompNonConst(irow);
      }
      else {
        y_i = &y;
      }
      DBG_ASSERT(IsValid(y_i));

      for ( Index jcol = 0; jcol < NComps_Cols(); jcol++ ) {
        if ( (owner_space_->Diagonal() && irow == jcol)
             || (!owner_space_->Diagonal() && ConstComp(irow,jcol)) ) {
          SmartPtr<const Vector> x_j;
          if (comp_x) {
            x_j = comp_x->GetComp(jcol);
          }
          else if (NComps_Cols() == 1) {
            x_j = &x;
          }
          DBG_ASSERT(IsValid(x_j));

          ConstComp(irow, jcol)->MultVector(alpha, *x_j,
                                            1., *y_i);
        }
      }
    }
  }
Example #29
0
bool Unit::InsideCollideTree( Unit *smaller,
                              QVector &bigpos,
                              Vector &bigNormal,
                              QVector &smallpos,
                              Vector &smallNormal,
                              bool bigasteroid,
                              bool smallasteroid )
{
    if (smaller->colTrees == NULL || this->colTrees == NULL)
        return false;
    if (hull < 0) return false;
    if (smaller->colTrees->usingColTree() == false || this->colTrees->usingColTree() == false)
        return false;
    csOPCODECollider::ResetCollisionPairs();
    Unit *bigger = this;

    csReversibleTransform bigtransform( bigger->cumulative_transformation_matrix );
    csReversibleTransform smalltransform( smaller->cumulative_transformation_matrix );
    smalltransform.SetO2TTranslation( csVector3( smaller->cumulative_transformation_matrix.p
                                                 -bigger->cumulative_transformation_matrix.p ) );
    bigtransform.SetO2TTranslation( csVector3( 0, 0, 0 ) );
    //we're only gonna lerp the positions for speed here... gahh!
    
    // Check for shield collisions here prior to checking for mesh on mesh or ray collisions below. 
    csOPCODECollider *tmpCol = smaller->colTrees->colTree( smaller, bigger->GetWarpVelocity() );
    if ( tmpCol
        && ( tmpCol->Collide( *bigger->colTrees->colTree( bigger,
                                                         smaller->GetWarpVelocity() ), &smalltransform, &bigtransform ) ) ) {
        csCollisionPair *mycollide = csOPCODECollider::GetCollisions();
        unsigned int     numHits   = csOPCODECollider::GetCollisionPairCount();
        if (numHits) {
            smallpos.Set( (mycollide[0].a1.x+mycollide[0].b1.x+mycollide[0].c1.x)/3.0f,
                         (mycollide[0].a1.y+mycollide[0].b1.y+mycollide[0].c1.y)/3.0f,
                         (mycollide[0].a1.z+mycollide[0].b1.z+mycollide[0].c1.z)/3.0f );
            smallpos = Transform( smaller->cumulative_transformation_matrix, smallpos );
            bigpos.Set( (mycollide[0].a2.x+mycollide[0].b2.x+mycollide[0].c2.x)/3.0f,
                       (mycollide[0].a2.y+mycollide[0].b2.y+mycollide[0].c2.y)/3.0f,
                       (mycollide[0].a2.z+mycollide[0].b2.z+mycollide[0].c2.z)/3.0f );
            bigpos = Transform( bigger->cumulative_transformation_matrix, bigpos );
            csVector3 sn, bn;
            sn.Cross( mycollide[0].b1-mycollide[0].a1, mycollide[0].c1-mycollide[0].a1 );
            bn.Cross( mycollide[0].b2-mycollide[0].a2, mycollide[0].c2-mycollide[0].a2 );
            sn.Normalize();
            bn.Normalize();
            smallNormal.Set( sn.x, sn.y, sn.z );
            bigNormal.Set( bn.x, bn.y, bn.z );
            smallNormal = TransformNormal( smaller->cumulative_transformation_matrix, smallNormal );
            bigNormal   = TransformNormal( bigger->cumulative_transformation_matrix, bigNormal );
            return true;
        }
    }
    un_iter i;
    static float rsizelim = XMLSupport::parse_float( vs_config->getVariable( "physics", "smallest_subunit_to_collide", ".2" ) );
    clsptr  bigtype = bigasteroid ? ASTEROIDPTR : bigger->isUnit();
    clsptr  smalltype     = smallasteroid ? ASTEROIDPTR : smaller->isUnit();
    if ( bigger->SubUnits.empty() == false
        && (bigger->graphicOptions.RecurseIntoSubUnitsOnCollision == true || bigtype == ASTEROIDPTR) ) {
        i = bigger->getSubUnits();
        float rad = smaller->rSize();
        for (Unit *un; (un = *i); ++i) {
            float subrad = un->rSize();
            if ( (bigtype != ASTEROIDPTR) && (subrad/bigger->rSize() < rsizelim) ) {
                break;
            }
            if ( ( un->Position()-smaller->Position() ).Magnitude() <= subrad+rad ) {
                if ( ( un->InsideCollideTree( smaller, bigpos, bigNormal, smallpos, smallNormal, bigtype == ASTEROIDPTR,
                                              smalltype == ASTEROIDPTR ) ) )
                    return true;
            }
        }
    }
    if ( smaller->SubUnits.empty() == false
        && (smaller->graphicOptions.RecurseIntoSubUnitsOnCollision == true || smalltype == ASTEROIDPTR) ) {
        i = smaller->getSubUnits();
        float rad = bigger->rSize();
        for (Unit *un; (un = *i); ++i) {
            float subrad = un->rSize();
            if ( (smalltype != ASTEROIDPTR) && (subrad/smaller->rSize() < rsizelim) )
                break;
            if ( ( un->Position()-bigger->Position() ).Magnitude() <= subrad+rad ) {
                if ( ( bigger->InsideCollideTree( un, bigpos, bigNormal, smallpos, smallNormal, bigtype == ASTEROIDPTR,
                                                  smalltype == ASTEROIDPTR ) ) )
                    return true;
            }
        }
    }
    //FIXME
    //doesn't check all i*j options of subunits vs subunits
    return false;
}
Example #30
0
/*
 * Class:     org_upp_AndroidMath_Vector
 * Method:    set
 * Signature: (IF)V
 */
JNIEXPORT void JNICALL Java_org_upp_AndroidMath_Vector_set
  (JNIEnv *env, jobject obj, jint id, jfloat value)
{
	Vector* vec = mm.Get(env, obj);
	vec->Set(id, value);
}