Example #1
0
static void
sweep (sonar_configuration *sp)
{
  sonar_bogie *b;

  /* Move the sweep forward (clockwise).
   */
  GLfloat prev_sweep, this_sweep, tick;
  GLfloat cycle_secs = 30 / speed;  /* default to one cycle every N seconds */
  this_sweep = ((cycle_secs - fmod (double_time() - sp->start_time +
                                    sp->sweep_offset,
                                    cycle_secs))
                / cycle_secs
                * M_PI * 2);
  prev_sweep = sp->sweep_th;
  tick = prev_sweep - this_sweep;
  while (tick < 0) tick += M_PI*2;

  sp->sweep_th = this_sweep;

  if (this_sweep < 0 || this_sweep >= M_PI*2) abort();
  if (prev_sweep < 0)  /* skip first time */
    return;

  if (tick < 0 || tick >= M_PI*2) abort();


  /* Go through the 'pending' sensor data, find those bogies who are
     just now being swept, and move them from 'pending' to 'displayed'.
     (Leave bogies that have not yet been swept alone: we'll get to
     them when the sweep moves forward.)
   */
  b = sp->pending;
  while (b)
    {
      sonar_bogie *next = b->next;
      if (point_in_wedge (b->th, this_sweep, prev_sweep))
        {
          if (debug_p > 1) {
            time_t t = time((time_t *) 0);
            fprintf (stderr,
                     "%s: sweep hit: %02d:%02d: %s: (%5.2f %5.2f %5.2f;"
                     " th=[%.2f < %.2f <= %.2f])\n", 
                     progname,
                     (int) (t / 60) % 60, (int) t % 60,
                     b->name, b->r, b->th, b->ttl,
                     this_sweep, b->th, prev_sweep);
          }
          b->ttl = M_PI * 2.1;
          copy_and_insert_bogie (sp->ssd, b, &sp->displayed);
          delete_bogie (sp->ssd, b, &sp->pending);
        }
      b = next;
    }


  /* Update TTL on all currently-displayed bogies; delete the dead.

     Request sensor updates on the ones just now being swept.

     Any updates go into 'pending' and might not show up until
     the next time the sweep comes around.  This is to prevent
     already-drawn bogies from jumping to a new position without
     having faded out first.
  */
  b = sp->displayed;
  while (b)
    {
      sonar_bogie *next = b->next;
      b->ttl -= tick;

      if (b->ttl <= 0)
        {
          if (debug_p > 1)
            fprintf (stderr, "%s: TTL expired: %s (%5.2f %5.2f %5.2f)\n",
                     progname, b->name, b->r, b->th, b->ttl);
          delete_bogie (sp->ssd, b, &sp->displayed);
        }
      b = next;
    }

  update_sensor_data (sp);
}
Example #2
0
void RepRapSerial::SendNextLine()
{
	if ( com->errorStatus() ) 
	{
		m_bConnecting = false;
		m_bConnected = false;
		m_bPrinting = false;
		{
			ToolkitLock guard;
			gui->MVC->serialConnectionLost();
		}
		return;
	}
	if (m_bPrinting == false)
		return;
	if (m_iLineNr < buffer.size())
	{
		string a = buffer[m_iLineNr];
		SendData(a.c_str(), m_iLineNr++);
	}
	else	// we are done
	{
		ToolkitLock guard;

		m_bPrinting = false;
		buffer.clear();
		gui->ProgressBar->label("Print done");
		gui->MVC->PrintDone();
		return;
	}
	if (gui) {
		unsigned long time = Platform::getTickCount();
		if (startTime == 0)
			startTime = time;
		// it is just wasteful to update the GUI > once per sec.
		if (time - lastUpdateTime > 1000) {
			ToolkitLock guard;

			double elapsed = (time - startTime) / 1000.0;
			double max = gui->ProgressBar->maximum();
			double lines_per_sec = elapsed > 1 ? (double)m_iLineNr / elapsed : 1.0;
			double remaining = (double)(max - m_iLineNr) / lines_per_sec;

			/*
			 * Fltk has no way of knowing if this is a meaningful
			 * change, and has a habit of doing expensive re-draws.
			 * Detect whether there will be any visible change and
			 * if not, don't update.
			 */
			if (fabs (((double)m_iLineNr - gui->ProgressBar->value()) / max) > 1.0/1000.0)
				gui->ProgressBar->value ((float)m_iLineNr);

			int remaining_seconds = (int)fmod (remaining, 60.0);
			int remaining_minutes = ((int)fmod (remaining, 3600.0) - remaining_seconds) / 60;
			int remaining_hours = (int)remaining / 3600;

			std::stringstream oss;

			/*
			 * Trade accuracy for reduced UI update frequency.
			 */
			if (remaining_hours > 0)
				oss << setw(2) << remaining_hours << "h" << remaining_minutes << "m";
			else if (remaining_minutes > 5)
				oss << setw(2) << remaining_minutes << "m";
			else if (remaining_seconds > 0)
				oss << setw(2) << remaining_minutes << "m" << remaining_seconds << "s";
			else
				oss << "Progress";

			std::string s = oss.str();
			const char *old_label = gui->ProgressBar->label();
			if (!old_label || strcmp (old_label, s.c_str()))
				gui->ProgressBar->copy_label(s.c_str());
		}

	}

}
Example #3
0
void
RandomKnot::prepareAnimation(Position extent, bool xRepeat, bool yRepeat)
{
    // Find a random position within the window where the knot will be visible.
    const GLfloat knotWidth = 2.0 * extent.x;
    const GLfloat knotHeight = 2.0 * extent.y;
    if (knotWidth < mWindowWidth && knotHeight < mWindowHeight) {
        mBasePosition =
            Position(randomFloat(mWindowWidth - knotWidth),
                     randomFloat(mWindowHeight - knotHeight))
            + extent;
    } else {
        mBasePosition = Position(randomFloat() * mWindowWidth,
                                 randomFloat() * mWindowHeight);
    }

    // Give the knot a random speed, direction, angle and spin.
    mSpeed = randomFloat(mPrefs.minSpeed(), mPrefs.maxSpeed()) + 0.1;

    GLfloat dir;
    if (randomFloat() < mPrefs.skewProbability()) {
        dir = randomFloat(0.0, M_PI * 2.0);

        if (xRepeat) {
            mAngle = fmod(dir + M_PI_2, M_PI * 2.0);
        } else if (yRepeat) {
            mAngle = dir;
        } else {
            mAngle = randomFloat(0.0, M_PI * 2.0);
        }

    } else {
        int quad;
        if (xRepeat) {
            quad = 2 * randomInteger(2) + 1;
        } else if (yRepeat) {
            quad = 2 * randomInteger(2);
        } else {
            quad = randomInteger(4);
        }
        dir = quad * M_PI_2;
        mAngle = 0.0;
    }
    mDirection = Position(cos(dir), sin(dir));

    if (randomFloat() < mPrefs.spinProbability()) {
        mSpin = randomFloat(mPrefs.minSpin(), mPrefs.maxSpin())
            * ((randomFloat() < 0.5) ? 1.0 : -1.0)
            / 180.0 * M_PI;
    } else {
        mSpin = 0.0;
    }

    // Calculate the starting and stopping times, i.e., the time at which
    // the knot's bounding circle is tangent to the window's bounding circle.
    //
    // - project window midpoint to point P0 on line of movement at time T0.
    // - use Pythagoras to compute distance from P0 to center of knot
    // - calculate T0 - distance and T0 + distance
    const Position midPosition(mWindowWidth * 0.5, mWindowHeight * 0.5);
    const GLfloat t0 = (midPosition - mBasePosition) * mDirection;
    const Position p0 = mBasePosition + t0 * mDirection;

    const GLfloat hyp = norm(midPosition) + norm(extent);
    const GLfloat cat = norm(midPosition - p0);
    const GLfloat distance = sqrt(hyp * hyp - cat * cat);

    mTime    = t0 - distance;
    mMaxTime = t0 + distance;

    // Adjust the spin rate so the angle is consistent at start and stop.
    GLfloat iterations = floor((mMaxTime - mTime) / mSpeed);
    mSpin = floor(mSpin / M_PI * iterations) * M_PI / iterations;
}
Example #4
0
double AlembicNode::computeRetime(const double inputTime,
                                  const double firstTime,
                                  const double lastTime,
                                  const short playStyle)
{
    const double playTime = lastTime - firstTime;
    static const double eps = 0.001;
    double retime = inputTime;

    switch (playStyle)
    {
      case PLAYTYPE_HOLD:
          break;
      case PLAYTYPE_LOOP:
          if (inputTime < (firstTime - eps) || inputTime > (lastTime + eps))
          {
              const double timeOffset = inputTime - firstTime;
              const double playOffset = floor(timeOffset/playTime);
              const double fraction = fabs(timeOffset/playTime - playOffset);

              retime = firstTime + playTime * fraction;
          }
          break;
      case PLAYTYPE_REVERSE:
          if (inputTime > (firstTime + eps) && inputTime < (lastTime - eps))
          {
              const double timeOffset = inputTime - firstTime;
              const double playOffset = floor(timeOffset/playTime);
              const double fraction = fabs(timeOffset/playTime - playOffset);

              retime = lastTime - playTime * fraction;
          }
          else if (inputTime < (firstTime + eps))
          {
              retime = lastTime;
          }
          else
          {
              retime = firstTime;
          }
          break;
      case PLAYTYPE_BOUNCE:
          if (inputTime < (firstTime - eps) || inputTime > (lastTime + eps))
          {
              const double timeOffset = inputTime - firstTime;
              const double playOffset = floor(timeOffset/playTime);
              const double fraction = fabs(timeOffset/playTime - playOffset);

              // forward loop
              if (fmod(playOffset, 2.0)==0.0)
              {
                  retime = firstTime + playTime * fraction;
              }
              // backward loop
              else
              {
                  retime = lastTime - playTime * fraction;
              }
          }
          break;
    }

    return retime;
}
Example #5
0
Object *float_mod( Object *me, Object *op ){
    double a = ob_float_ucast(me)->value,
           b = ob_fvalue(op);

    return (Object *)gc_new_float( fmod( a, b ) );
}
Example #6
0
void Simulator::xMODR()
{
    GET_P1; GET_P2; GET_P3;
    p1->m_type = ValueType::REAL;
    p1->m_real = fmod(p2->m_real, p3->m_real);
}
Example #7
0
 double posMod(double posIn) const {return fmod(posIn,circ);}        // get position modulo circumference
Example #8
0
/*!
	\param value Value to convert
	\param text	String up to length char
	\param maxLen Maximal length of the string
*/
void AudioEffect::float2string (float value, char* text, VstInt32 maxLen)
{
	VstInt32 c = 0, neg = 0;
	char string[32];
	char* s;
	double v, integ, i10, mantissa, m10, ten = 10.;
	
	v = (double)value;
	if (v < 0)
	{
		neg = 1;
		value = -value;
		v = -v;
		c++;
		if (v > 9999999.)
		{
			vst_strncpy (string, "Huge!", 31);
			return;
		}
	}
	else if (v > 99999999.)
	{
		vst_strncpy (string, "Huge!", 31);
		return;
	}

	s = string + 31;
	*s-- = 0;
	*s-- = '.';
	c++;
	
	integ = floor (v);
	i10 = fmod (integ, ten);
	*s-- = (char)((VstInt32)i10 + '0');
	integ /= ten;
	c++;
	while (integ >= 1. && c < 8)
	{
		i10 = fmod (integ, ten);
		*s-- = (char)((VstInt32)i10 + '0');
		integ /= ten;
		c++;
	}
	if (neg)
		*s-- = '-';
	vst_strncpy (text, s + 1, maxLen);
	if (c >= 8)
		return;

	s = string + 31;
	*s-- = 0;
	mantissa = fmod (v, 1.);
	mantissa *= pow (ten, (double)(8 - c));
	while (c < 8)
	{
		if (mantissa <= 0)
			*s-- = '0';
		else
		{
			m10 = fmod (mantissa, ten);
			*s-- = (char)((VstInt32)m10 + '0');
			mantissa /= 10.;
		}
		c++;
	}
	vst_strncat (text, s + 1, maxLen);
}
Example #9
0
static TRI_aql_node_t* OptimiseBinaryArithmeticOperation (TRI_aql_context_t* const context,
                                                          TRI_aql_node_t* node) {
  TRI_aql_node_t* lhs = TRI_AQL_NODE_MEMBER(node, 0);
  TRI_aql_node_t* rhs = TRI_AQL_NODE_MEMBER(node, 1);
  bool isEligibleLhs;
  bool isEligibleRhs;
  double value;
  
  if (!lhs || !rhs) {
    return node;
  } 

  isEligibleLhs = TRI_IsConstantValueNodeAql(lhs);
  isEligibleRhs = TRI_IsConstantValueNodeAql(rhs);

  if (isEligibleLhs && !TRI_IsNumericValueNodeAql(lhs)) {
    // node is not a numeric value => error
    TRI_SetErrorContextAql(context, TRI_ERROR_QUERY_INVALID_ARITHMETIC_VALUE, NULL);
    return node;
  }

  
  if (isEligibleRhs && !TRI_IsNumericValueNodeAql(rhs)) {
    // node is not a numeric value => error
    TRI_SetErrorContextAql(context, TRI_ERROR_QUERY_INVALID_ARITHMETIC_VALUE, NULL);
    return node;
  }
  

  if (!isEligibleLhs || !isEligibleRhs) {
    return node;
  }
  
  assert(node->_type == TRI_AQL_NODE_OPERATOR_BINARY_PLUS ||
         node->_type == TRI_AQL_NODE_OPERATOR_BINARY_MINUS ||
         node->_type == TRI_AQL_NODE_OPERATOR_BINARY_TIMES ||
         node->_type == TRI_AQL_NODE_OPERATOR_BINARY_DIV ||
         node->_type == TRI_AQL_NODE_OPERATOR_BINARY_MOD);

  if (node->_type == TRI_AQL_NODE_OPERATOR_BINARY_PLUS) {
    value = TRI_GetNumericNodeValueAql(lhs) + TRI_GetNumericNodeValueAql(rhs);
  }
  else if (node->_type == TRI_AQL_NODE_OPERATOR_BINARY_MINUS) {
    value = TRI_GetNumericNodeValueAql(lhs) - TRI_GetNumericNodeValueAql(rhs);
  }
  else if (node->_type == TRI_AQL_NODE_OPERATOR_BINARY_TIMES) {
    value = TRI_GetNumericNodeValueAql(lhs) * TRI_GetNumericNodeValueAql(rhs);
  }
  else if (node->_type == TRI_AQL_NODE_OPERATOR_BINARY_DIV) {
    if (TRI_GetNumericNodeValueAql(rhs) == 0.0) {
      // division by zero
      TRI_SetErrorContextAql(context, TRI_ERROR_QUERY_DIVISION_BY_ZERO, NULL);
      return node;
    }
    value = TRI_GetNumericNodeValueAql(lhs) / TRI_GetNumericNodeValueAql(rhs);
  }
  else if (node->_type == TRI_AQL_NODE_OPERATOR_BINARY_MOD) {
    if (TRI_GetNumericNodeValueAql(rhs) == 0.0) {
      // division by zero
      TRI_SetErrorContextAql(context, TRI_ERROR_QUERY_DIVISION_BY_ZERO, NULL);
      return node;
    }
    value = fmod(TRI_GetNumericNodeValueAql(lhs), TRI_GetNumericNodeValueAql(rhs));
  }
  else {
    value = 0.0;
  }
  
  node = TRI_CreateNodeValueDoubleAql(context, value);

  if (!node) {
    TRI_SetErrorContextAql(context, TRI_ERROR_OUT_OF_MEMORY, NULL);
    return NULL;
  }
  
  LOG_TRACE("optimised away binary arithmetic operation");

  return node;
}
Example #10
0
void f0ext_theFunction(t_f0ext *x) {
	long
    i
    ,
    j
	,
    k
    ,
    l
	,
    m
    ;
    m
	=
    (long)round
    (
     pow
     (
      2
      ,
      x->valRight
      )
     )
	;
    for
        (
         i
         =
         0
         ;
         i
         <
         m
         ;
         i++
         )
    {
        for
            (j=
             0
             ;
             j
             <
             m
             ;
             j++
             )
        {		for
			(
             k
             =0
             ;
             k<
             m
             ;
             k++
             )
        {
			for
                
                (
                 l
                 =
                 0;
                 l
                 <
                 m
                 ;
                 l++
                 )
			{
                x->dummy= fmod(
                     l				,
                     3.1415
                     )
                ;
            }
        }}
	}
}
Example #11
0
void map::renderTileMap(Tile* tileMap, const Uint8 r, const Uint8 g, const Uint8 b, bool showText, int xoffset) {
	SDL_Rect clip2;
	SDL_Rect clip3;
	/*clip2.x = this->ViewportInfo.gui_x;
	clip2.y = this->ViewportInfo.gui_y;
	clip2.w = this->ptrScreen->VIEWPORT_WIDTH;
	clip2.h = this->ptrScreen->VIEWPORT_HEIGHT;*/
	
	


	for (int i = 0; i < this->WorldInfo.total_tiles; i++) {
		if (tileMap[i].Occupied == true) {
			//if (this->ptrWorld->Map->path_map[i].Occupied == true) {
			int yT = (int)(i / this->WorldInfo.tiles_count_x);		
			int xT = fmod(i*1.0f,this->WorldInfo.tiles_count_x*1.0f);

			int xP = xT*this->WorldInfo.tile_size;
			int yP = yT*this->WorldInfo.tile_size;

			
			if (this->inViewport(xP,yP,this->WorldInfo.tile_size,this->WorldInfo.tile_size)) {

				clip2.x = xP;
				clip2.y = yP;
				clip2.w = 32;
				clip2.h = 32;

				//clip2 = this->clipToViewport(xP,yP,clip2);

				int xViewOffset = this->ViewportInfo.gui_x + (xP - this->ViewportInfo.x);
				int yViewOffset = this->ViewportInfo.gui_y + ((yP) - this->ViewportInfo.y);

				clip3.x = xViewOffset+xoffset;
				clip3.y = yViewOffset;
				clip3.w = 32;
				clip3.h = 32;

				

				
				SDL_FillRect( ptrScreen->screen, &clip3, SDL_MapRGB( ptrScreen->screen->format, r, g, b ) );
				
#ifdef SHOW_DEBUG_TEXT
				if (showText){ 
					sstr.str("");
					//sstr.str("speed: ");
					//sstr<<this->vector<<" - "<<this->targetvector;
					//sstr<<tileMap[i].OccupyData.size();

					//extra if statement for thread safety
					if (tileMap[i].Occupied == true) {
						sstr<<tileMap[i].OccupyData[0];
					}
					//sstr<<this->animation_list.curAnimFrame<<" - "<<this->angle.frame;
					str1 = sstr.str();
					ptrWorld->ptrScreen->printText(xViewOffset+xoffset,yViewOffset,str1.c_str());
				}
#endif

				//this->ptrScreen->apply_surface(xViewOffset,yViewOffset,
				//this->ResID->surface,this->ptrScreen->screen,&clip);

			}
		}
	}
}
Example #12
0
ATerm SSL_modr(ATerm x, ATerm y)
{ 
  assert_is_real(x);
  assert_is_real(y);
  return((ATerm) ATmakeReal(fmod(_get_real(x), _get_real(y))));
}
Example #13
0
muFloat_t Mod(muFloat_t x, muFloat_t y)
{
	return fmod(x, y);
}
CVector2<double> TextureMapping(CVector3 inPoint, CVector3 normalVector,
	const cObjectData &objectData, const cMaterial *material, CVector3 *textureVectorX,
	CVector3 *textureVectorY)
{
	CVector2<double> textureCoordinates;
	CVector3 point = inPoint - objectData.position;
	point = objectData.rotationMatrix.RotateVector(point);
	point /= objectData.size;
	point = material->rotMatrix.RotateVector(point);

	switch (material->textureMappingType)
	{
		case cMaterial::mappingPlanar:
		{
			textureCoordinates = CVector2<double>(point.x, point.y);
			textureCoordinates.x /= -material->textureScale.x;
			textureCoordinates.y /= material->textureScale.y;
			textureCoordinates.x -= material->textureCenter.x;
			textureCoordinates.y -= material->textureCenter.y;

			if (textureVectorX && textureVectorY)
			{
				CVector3 texX(1.0, 0.0, 0.0);
				texX = objectData.rotationMatrix.Transpose().RotateVector(texX);
				texX = material->rotMatrix.Transpose().RotateVector(texX);
				*textureVectorX = texX;

				CVector3 texY(0.0, -1.0, 0.0);
				texY = objectData.rotationMatrix.Transpose().RotateVector(texY);
				texY = material->rotMatrix.Transpose().RotateVector(texY);
				*textureVectorY = texY;
			}
			break;
		}
		case cMaterial::mappingCylindrical:
		{
			double alphaTexture = fmod(point.GetAlpha() + 2.0 * M_PI, 2.0 * M_PI);
			textureCoordinates.x = alphaTexture / (2.0 * M_PI);
			textureCoordinates.y = -point.z;
			textureCoordinates.x /= material->textureScale.x;
			textureCoordinates.y /= material->textureScale.y;
			textureCoordinates.x -= material->textureCenter.x;
			textureCoordinates.y -= material->textureCenter.y;

			if (textureVectorX && textureVectorY)
			{
				CVector3 texY(0.0, 0.0, 1.0);
				CVector3 texX = point.Cross(texY);
				texX = objectData.rotationMatrix.Transpose().RotateVector(texX);
				texX = material->rotMatrix.Transpose().RotateVector(texX);
				*textureVectorX = texX;
				texY = objectData.rotationMatrix.Transpose().RotateVector(texY);
				texY = material->rotMatrix.Transpose().RotateVector(texY);
				*textureVectorY = texY;
			}

			break;
		}
		case cMaterial::mappingSpherical:
		{
			double alphaTexture = fmod(point.GetAlpha() + 2.0 * M_PI, 2.0 * M_PI);
			double betaTexture = -point.GetBeta();
			textureCoordinates.x = alphaTexture / (2.0 * M_PI);
			textureCoordinates.y = (betaTexture / M_PI);
			textureCoordinates.x /= material->textureScale.x;
			textureCoordinates.y /= material->textureScale.y;
			textureCoordinates.x -= material->textureCenter.x;
			textureCoordinates.y -= material->textureCenter.y;

			CVector3 texY(0.0, 0.0, -1.0);
			CVector3 texX = texY.Cross(point);
			texX.Normalize();
			texY = texX.Cross(point);

			if (textureVectorX && textureVectorY)
			{
				texX = objectData.rotationMatrix.Transpose().RotateVector(texX);
				texX = material->rotMatrix.Transpose().RotateVector(texX);
				*textureVectorX = texX;
				texY = objectData.rotationMatrix.Transpose().RotateVector(texY);
				texY = material->rotMatrix.Transpose().RotateVector(texY);
				*textureVectorY = texY;
			}

			break;
		}
		case cMaterial::mappingCubic:
		{
			point /= material->textureScale;
			point -= material->textureCenter;

			CVector3 texX, texY;
			if (fabs(normalVector.x) > fabs(normalVector.y))
			{
				if (fabs(normalVector.x) > fabs(normalVector.z))
				{
					// x
					if (normalVector.x > 0)
						textureCoordinates = CVector2<double>(point.y, -point.z);
					else
						textureCoordinates = CVector2<double>(-point.y, -point.z);

					if (textureVectorX && textureVectorY)
					{
						if (normalVector.x > 0)
						{
							texX = CVector3(0.0, -1.0, 0.0);
							texY = CVector3(0.0, 0.0, 1.0);
						}
						else
						{
							texX = CVector3(0.0, 1.0, 0.0);
							texY = CVector3(0.0, 0.0, 1.0);
						}
					}
				}
				else
				{
					// z
					if (normalVector.z > 0)
						textureCoordinates = CVector2<double>(-point.x, point.y);
					else
						textureCoordinates = CVector2<double>(point.x, point.y);

					if (textureVectorX && textureVectorY)
					{
						if (normalVector.z > 0)
						{
							texX = CVector3(1.0, 0.0, 0.0);
							texY = CVector3(0.0, -1.0, 0.0);
						}
						else
						{
							texX = CVector3(-1.0, 0.0, 0.0);
							texY = CVector3(0.0, -1.0, 0.0);
						}
					}
				}
			}
			else
			{
				if (fabs(normalVector.y) > fabs(normalVector.z))
				{
					// y
					if (normalVector.y > 0)
						textureCoordinates = CVector2<double>(-point.x, -point.z);
					else
						textureCoordinates = CVector2<double>(point.x, -point.z);

					if (textureVectorX && textureVectorY)
					{
						if (normalVector.y > 0)
						{
							texX = CVector3(1.0, 0.0, 0.0);
							texY = CVector3(0.0, 0.0, 1.0);
						}
						else
						{
							texX = CVector3(-1.0, 0.0, 0.0);
							texY = CVector3(0.0, 0.0, 1.0);
						}
					}
				}
				else
				{
					// z
					if (normalVector.z > 0)
						textureCoordinates = CVector2<double>(-point.x, point.y);
					else
						textureCoordinates = CVector2<double>(point.x, point.y);

					if (textureVectorX && textureVectorY)
					{
						if (normalVector.z > 0)
						{
							texX = CVector3(1.0, 0.0, 0.0);
							texY = CVector3(0.0, -1.0, 0.0);
						}
						else
						{
							texX = CVector3(-1.0, 0.0, 0.0);
							texY = CVector3(0.0, -1.0, 0.0);
						}
					}
				}
			}

			if (textureVectorX && textureVectorY)
			{
				texX = objectData.rotationMatrix.Transpose().RotateVector(texX);
				texX = material->rotMatrix.Transpose().RotateVector(texX);
				*textureVectorX = texX;
				texY = objectData.rotationMatrix.Transpose().RotateVector(texY);
				texY = material->rotMatrix.Transpose().RotateVector(texY);
				*textureVectorY = texY;
			}

			break;
		}
	}
	return textureCoordinates;
}
Example #15
0
void Bullet::move()
{
    //move with rotation of tank
    //convert degrees to radians
    float degrees;
    float radians;

    if(game->player->rotation()<0)
    {
        degrees = -fmod(game->player->rotation() , 360)+90;
        radians = qDegreesToRadians(degrees);
    }
    else
    {
        degrees = 90-fmod(game->player->rotation() , 360);
        radians = qDegreesToRadians(degrees);
    }
    //move bullet
    if(degrees==90)
        setPos(x(),y()-5);
    else if(degrees==270)
        setPos(x(),y()+5);
    else if(degrees>90 && degrees<270)
        setPos(x()-5, y()+(qTan(radians)*5));
    else if(degrees>270 && degrees<90)
        setPos(x()+5, y()-(qTan(radians)*5));
    //colliding bullet with objects
    QList<QGraphicsItem *> items = collidingItems();
            for(int i=0 ; i<items.size() ;i++)
            {
                if(typeid(*(items[i]))==typeid(Square)){
                    QVector<Object *>::Iterator it = game->objects.begin();
                    for(int j=0 ; j<game->objects.size() ;j++)
                    {
                        if(game->objects.at(j) == items[i])
                        {
                                if(game->objects.at(j)->health ==1)
                                {
                                    scene()->removeItem(items[i]);
                                    game->objects.erase(it+j);
                                }
                                else
                                {
                                    game->objects.at(j)->health--;
                                }
                        }

                    }
                                game->score->increase();
                                scene()->removeItem(this);
                                delete this;
                                return;

                }
                if(typeid(*(items[i]))==typeid(Triangle)){
                    QVector<Object *>::Iterator it = game->objects.begin();
                    for(int j=0 ; j<game->objects.size() ;j++)
                    {
                        if(game->objects.at(j) == items[i])
                        {
                                if(game->objects.at(j)->health ==1)
                                {
                                    scene()->removeItem(items[i]);
                                    game->objects.erase(it+j);
                                }
                                else
                                {
                                    game->objects.at(j)->health--;
                                }
                        }

                    }

                    game->score->increase();
                    scene()->removeItem(this);
                    delete this;
                    return;
                }
                if(typeid(*(items[i]))==typeid(Pentagon)){
                    QVector<Object *>::Iterator it = game->objects.begin();
                    for(int j=0 ; j<game->objects.size() ;j++)
                    {
                        if(game->objects.at(j) == items[i])
                        {
                                if(game->objects.at(j)->health ==1)
                                {
                                    scene()->removeItem(items[i]);
                                    game->objects.erase(it+j);
                                }
                                else
                                {
                                    game->objects.at(j)->health--;
                                }
                        }

                    }
                    game->score->increase();
                    scene()->removeItem(this);
                    delete this;
                    return;
                }
            }
            if(pos().y() < 0)
            {
                delete this;
            }
}
Example #16
0
File: setup.c Project: GCZhang/SNAP
/*******************************************************************************
 * Setup the material according to mat_opt.
 *
 * There are only two materials max; one per cell. mat_opt defines the
 * material layout and has a similar meaning for 1-D, 2-D, 3-D problems.
 *
 * 0 = Homogeneous (mat1) problem, regardless of dimension
 * 1 = Center. mat1 is the base. 1-D: 25%mat1/50%mat2/25%mat1
 *     2/D: same as 1-D but in two dimensions, so mat2 region is a square
 *     3/D: same as 1-D but in three dimensions, so mat2 is a cube
 * 2 = Corner. Same concept as 1, but move slab/square/cube to origin
 *
 * Return starting/ending indices for printint an echo.
 *******************************************************************************/
void setup_mat ( input_data *input_vars, geom_data *geom_vars, data_data *data_vars,
                 int *i1, int *i2, int *j1, int *j2, int *k1, int *k2 )
{
/*******************************************************************************
 * Local variables
 *******************************************************************************/
    int i, j, k, jj, kk;

/*******************************************************************************
 * Form the base with mat1. Use dimension and mat_opt to determine
 * the rest of the layout.
 *******************************************************************************/
    for (k = 0; k < NZ; k++)
    {
        for (j = 0; j < NY; j++)
        {
            for (i=0; i < NX; i++)
            {
                MAT_3D(i,j,k) = 1;
            }
        }
    }

    *i1 = 1;
    *i2 = 1;

    *j1 = 1;
    *j2 = 1;

    *k1 = 1;
    *k2 = 1;

    if ( MAT_OPT == 1 )
    {
        *i1 = NX / 4 + 1;
        *i2 = 3 * NX / 4;

        if ( NDIMEN > 1 )
        {
            *j1 = NY_GL / 4 + 1;
            *j2 = 3 * NY_GL / 4;

            if ( NDIMEN > 2 )
            {
                *k1 = NZ_GL / 4 + 1;
                *k2 = 3 * NZ_GL / 4;
            }
        }
    }

    else if ( MAT_OPT == 2 )
    {
        *i2 = NX / 2;
        if ( NDIMEN > 1 )
        {
            *j2 = NY_GL / 2;
            if ( NDIMEN > 2 )
            {
                *k2 = NZ_GL / 2;
            }
        }
    }

    if ( MAT_OPT > 0 )
    {
        for ( k = *k1; k <= *k2; k++ )
        {
            if ( (KLB <= k) && (k <= KUB) )
            {
                kk = fmod( (k-1), NZ ) + 1;

                for ( j = *j1; j <= *j2; j++ )
                {
                    if ( (JLB <= j) && (j <= JUB) )
                    {
                        jj = fmod( (j-1), NY ) + 1;

                        for ( i = *i1; i <= *i2; i++ )
                        {
                            MAT_3D((i-1), (jj-1), (kk-1)) = 2;
                        }
                    }
                }
            }
        }
    }
}
Example #17
0
/// <summary>
/// Draw the chart according to user selection and display it in the ChartViewer.
/// </summary>
/// <param name="viewer">The ChartViewer object to display the chart.</param>
void CFinancedemoDlg::drawChart(CChartViewer *viewer)
{
    // In this demo, we just assume we plot up to the latest time. So endDate is now.
    double endDate = Chart::chartTime2((int)time(0));

    // If the trading day has not yet started (before 9:30am), or if the end date is on
    // on Sat or Sun, we set the end date to 4:00pm of the last trading day     
    while ((fmod(endDate, 86400) < 9 * 3600 + 30 * 60) || 
        (Chart::getChartWeekDay(endDate) == 0)
        || (Chart::getChartWeekDay(endDate) == 6))
        endDate = endDate - fmod(endDate, 86400) - 86400 + 16 * 3600;

     // The duration selected by the user
    int durationInDays = (int)_tcstol((const TCHAR *)m_TimeRange.GetItemDataPtr(
        m_TimeRange.GetCurSel()), 0, 0);

    // Compute the start date by subtracting the duration from the end date.
    double startDate;
    if (durationInDays >= 30)
    {
        // More or equal to 30 days - so we use months as the unit
        int YMD = Chart::getChartYMD(endDate);
        int startMonth = (YMD / 100) % 100 - durationInDays / 30;
        int startYear = YMD / 10000;
        while (startMonth < 1)
        {
            --startYear;
            startMonth += 12;
        }
        startDate = Chart::chartTime(startYear, startMonth, 1);
    }
    else
    {
        // Less than 30 days - use day as the unit. The starting point of the axis is
        // always at the start of the day (9:30am). Note that we use trading days, so
        // we skip Sat and Sun in counting the days.
        startDate = endDate - fmod(endDate, 86400) + 9 * 3600 + 30 * 60;
        for (int i = 1; i < durationInDays; ++i)
        {
            if (Chart::getChartWeekDay(startDate) == 1)
                startDate -= 3 * 86400;
            else
                startDate -= 86400;
        }
    }

    // The first moving average period selected by the user.
    CString avgText;
    m_MovAvg1.GetWindowText(avgText);
    m_avgPeriod1 = (int)_tcstol(avgText, 0, 0);
    if (m_avgPeriod1 < 0)
        m_avgPeriod1 = 0;
    if (m_avgPeriod1 > 300)
        m_avgPeriod1 = 300;

    // The second moving average period selected by the user.
    m_MovAvg2.GetWindowText(avgText);
    m_avgPeriod2 = (int)_tcstol(avgText, 0, 0);
    if (m_avgPeriod2 < 0)
        m_avgPeriod2 = 0;
    if (m_avgPeriod2 > 300)
        m_avgPeriod2 = 300;

    // We need extra leading data points in order to compute moving averages.
    int extraPoints = (m_avgPeriod1 > m_avgPeriod2) ? m_avgPeriod1 : m_avgPeriod2;
    if (extraPoints < 25)
        extraPoints = 25;

    // The data series we want to get.
    CString tickerKey = 
        (const TCHAR *)m_TickerSymbol.GetItemDataPtr(m_TickerSymbol.GetCurSel());

    // In this demo, we can get 15 min, daily, weekly or monthly data depending on
    // the time range.
    int resolution;
    if (durationInDays <= 10) 
    {
        // 10 days or less, we assume 15 minute data points are available
        resolution = 900;

        // We need to adjust the startDate backwards for the extraPoints. We assume 
        // 6.5 hours trading time per day, and 5 trading days per week.
        double dataPointsPerDay = 6.5 * 3600 / resolution;
        double adjustedStartDate = startDate - fmod(startDate, 86400) - 
            (int)(extraPoints / dataPointsPerDay * 7 / 5 + 2.9999999) * 86400;

        // Get the required 15 min data
        get15MinData(tickerKey, adjustedStartDate, endDate);
    }
    else if (durationInDays >= 4.5 * 360)
    {
        // 4 years or more - use monthly data points.
        resolution = 30 * 86400;
            
        // Adjust startDate backwards to cater for extraPoints
        int YMD = Chart::getChartYMD(startDate);
        int adjustedMonth = (YMD / 100) % 100 - extraPoints;
        int adjustedYear = YMD / 10000;
        while (adjustedMonth < 1)
        {
            --adjustedYear;
            adjustedMonth += 12;
        }
        double adjustedStartDate = Chart::chartTime(adjustedYear, adjustedMonth, 1);
        
        // Get the required monthly data
        getMonthlyData(tickerKey, adjustedStartDate, endDate);
    }
    else if (durationInDays >= 1.5 * 360)
    {
        // 1 year or more - use weekly points. 
        resolution = 7 * 86400;
 
        //Note that we need to add extra points by shifting the starting weeks backwards
        double adjustedStartDate = startDate - (extraPoints * 7 + 6) * 86400;
            
        // Get the required weekly data
        getWeeklyData(tickerKey, adjustedStartDate, endDate);
    }
    else
    {
        // Default - use daily points
        resolution = 86400;
            
        // Adjust startDate backwards to cater for extraPoints. We multiply the days 
        // by 7/5 as we assume 1 week has 5 trading days.
        double adjustedStartDate = startDate - fmod(startDate, 86400) - 
            ((extraPoints * 7 + 4) / 5 + 2) * 86400;

        // Get the required daily data
        getDailyData(tickerKey, adjustedStartDate, endDate);
    }
    
    // We now confirm the actual number of extra points (data points that are before
    // the start date) as inferred using actual data from the database.
    for (extraPoints = 0; extraPoints < m_noOfPoints; ++extraPoints)
    {
        if (m_timeStamps[extraPoints] >= startDate)
            break;
    }

    // Check if there is any valid data
    if (extraPoints >= m_noOfPoints)
    {
        // No data - just display the no data message.
        MultiChart errMsg(400, 50);
        errMsg.addTitle(Chart::TopLeft, "No data available for the specified time period", 
            "arial.ttf", 10);
        viewer->setChart(&errMsg);
        return;
    }

    // In some finance chart presentation style, even if the data for the latest day 
    // is not fully available, the axis for the entire day will still be drawn, where
    // no data will appear near the end of the axis.
    int extraTrailingPoints = 0;
    if (resolution <= 86400)
    {
        // Add extra points to the axis until it reaches the end of the day. The end
        // of day is assumed to be 16:00 (it depends on the stock exchange).
        double lastTime = m_timeStamps[m_noOfPoints - 1];
        int extraTrailingPoints = (int)((16 * 3600 - fmod(lastTime, 86400)) / resolution);
        if (extraTrailingPoints > 0)
        {
            double *extendedTimeStamps = new double[m_noOfPoints + extraTrailingPoints];
            memcpy(extendedTimeStamps, m_timeStamps, sizeof(double) * m_noOfPoints);
            for (int i = 0; i < extraTrailingPoints; ++i)
                extendedTimeStamps[m_noOfPoints + i] = lastTime + resolution * (i + 1);
            delete[] m_timeStamps;
            m_timeStamps = extendedTimeStamps;
        }
    }

    //
    // At this stage, all data is available. We can draw the chart as according to 
    // user input.
    //

    //
    // Determine the chart size. In this demo, user can select 4 different chart sizes.
    // Default is the large chart size.
    //
    int width = 780;
    int mainHeight = 250;
    int indicatorHeight = 80;

    CString selectedSize = (const TCHAR *)m_ChartSize.GetItemDataPtr(m_ChartSize.GetCurSel());
    if (selectedSize == _T("S"))
    {
        // Small chart size
        width = 450;
        mainHeight = 160;
        indicatorHeight = 60;
    }
    else if (selectedSize == _T("M"))
    {
        // Medium chart size
        width = 620;
        mainHeight = 210;
        indicatorHeight = 65;
    }
    else if (selectedSize == _T("H"))
    {
        // Huge chart size
        width = 1000;
        mainHeight = 320;
        indicatorHeight = 90;
    }

    // Create the chart object using the selected size
    FinanceChart m(width);

    // Set the data into the chart object
    m.setData(DoubleArray(m_timeStamps, m_noOfPoints + extraTrailingPoints), 
        DoubleArray(m_highData, m_noOfPoints), DoubleArray(m_lowData, m_noOfPoints), 
        DoubleArray(m_openData, m_noOfPoints), DoubleArray(m_closeData, m_noOfPoints),
        DoubleArray(m_volData, m_noOfPoints), extraPoints);

    //
    // We configure the title of the chart. In this demo chart design, we put the
    // company name as the top line of the title with left alignment.
    //
    CString companyName;
    m_TickerSymbol.GetLBText(m_TickerSymbol.GetCurSel(), companyName);
    m.addPlotAreaTitle(Chart::TopLeft, TCHARtoUTF8(companyName));

    // We displays the current date as well as the data resolution on the next line.
    const char *resolutionText = "";
    if (resolution == 30 * 86400)
        resolutionText = "Monthly";
    else if (resolution == 7 * 86400)
        resolutionText = "Weekly";
    else if (resolution == 86400)
        resolutionText = "Daily";
    else if (resolution == 900)
        resolutionText = "15-min";

    char buffer[1024];
    sprintf(buffer, "<*font=arial.ttf,size=8*>%s - %s chart", 
        m.formatValue(Chart::chartTime2((int)time(0)), "mmm dd, yyyy"), resolutionText);
    m.addPlotAreaTitle(Chart::BottomLeft, buffer);

    // A copyright message at the bottom left corner the title area
    m.addPlotAreaTitle(Chart::BottomRight, 
        "<*font=arial.ttf,size=8*>(c) Advanced Software Engineering");

    //
    // Set the grid style according to user preference. In this simple demo user
    // interface, the user can enable/disable grid lines. The grid line colors are
    // hard coded to 0xdddddd (light grey), and the plot area background color is 
    // hard coded to 0xfffff0 (pale yellow).
    //
    int vGridColor = m_VGrid.GetCheck() ? 0xdddddd : Chart::Transparent;
    int hGridColor = m_HGrid.GetCheck() ? 0xdddddd : Chart::Transparent;
    m.setPlotAreaStyle(0xfffff0, hGridColor, vGridColor, hGridColor, vGridColor);

    //
    // Set log or linear scale according to user preference
    //
    m.setLogScale(m_LogScale.GetCheck() != 0);

    //
    // Add the first techical indicator according. In this demo, we draw the first
    // indicator on top of the main chart.
    //
    addIndicator(&m, (const TCHAR *)m_Indicator1.GetItemDataPtr(m_Indicator1.GetCurSel()), 
        indicatorHeight);

    // Add the main chart
    m.addMainChart(mainHeight);

    //
    // Draw the main chart depending on the chart type the user has selected
    //
    CString selectedType = (const TCHAR *)m_ChartType.GetItemDataPtr(m_ChartType.GetCurSel());
    if (selectedType == _T("Close"))
        m.addCloseLine(0x40);
    else if (selectedType == _T("TP"))
        m.addTypicalPrice(0x40);
    else if (selectedType == _T("WC"))
        m.addWeightedClose(0x40);
    else if (selectedType == _T("Median"))
        m.addMedianPrice(0x40);

    //
    // Add moving average lines.
    //
    addMovingAvg(&m, (const TCHAR *)m_AvgType1.GetItemDataPtr(m_AvgType1.GetCurSel()), 
        m_avgPeriod1, 0x663300);
    addMovingAvg(&m, (const TCHAR *)m_AvgType2.GetItemDataPtr(m_AvgType2.GetCurSel()), 
        m_avgPeriod2, 0x9900ff);

    //
    // Draw the main chart if the user has selected CandleStick or OHLC. We
    // draw it here to make sure it is drawn behind the moving average lines
    // (that is, the moving average lines stay on top.)
    //
    if (selectedType == _T("CandleStick"))
        m.addCandleStick(0x33ff33, 0xff3333);
    else if (selectedType == _T("OHLC"))
        m.addHLOC(0x8000, 0x800000);

    //
    // Add price band/channel/envelop to the chart according to user selection
    //
    CString selectedBand = (const TCHAR *)m_Band.GetItemDataPtr(m_Band.GetCurSel());
    if (selectedBand == _T("BB"))
        m.addBollingerBand(20, 2, 0x9999ff, 0xc06666ff);
    else if (selectedBand == _T("DC"))
        m.addDonchianChannel(20, 0x9999ff, 0xc06666ff);
    else if (selectedBand == _T("Envelop"))
        m.addEnvelop(20, 0.1, 0x9999ff, 0xc06666ff);

    //
    // Add volume bars to the main chart if necessary
    //
    if (m_Volume.GetCheck())
        m.addVolBars(indicatorHeight, 0x99ff99, 0xff9999, 0xc0c0c0);

    //
    // Add additional indicators as according to user selection.
    //
    addIndicator(&m, (const TCHAR *)m_Indicator2.GetItemDataPtr(m_Indicator2.GetCurSel()), 
        indicatorHeight);
    addIndicator(&m, (const TCHAR *)m_Indicator3.GetItemDataPtr(m_Indicator3.GetCurSel()), 
        indicatorHeight);
    addIndicator(&m, (const TCHAR *)m_Indicator4.GetItemDataPtr(m_Indicator4.GetCurSel()), 
        indicatorHeight);

    // Set the chart to the viewer
    viewer->setChart(&m);

    // Set image map (for tool tips) to the viewer
    sprintf(buffer, "title='%s {value|G}'", m.getToolTipDateFormat());
    viewer->setImageMap(m.getHTMLImageMap("", "", buffer));
}
Example #18
0
File: setup.c Project: GCZhang/SNAP
/*******************************************************************************
* Setup the material according to src_opt.
*
* Source is either on at strength 1.0 or off, per cell. src_opt defines
* the layout and has a similar meaning for 1-D, 2-D, 3-D problems.
*
* 0 = Source everywhere, regardless of dimension
* 1 = Source occupies the slab/square/cube center of the problem
*     1/D: 25%/50%/25% = source off/on/off
*     2/D: same as 1-D but in two dimensions
*     3/D: same as 1-D but in three dimensions
* 2 = Corner. Same concept as 1, but move slab/square/cube to origin
* 3 = MMS option, f = sin(pi*x/lx)
* All options isotropic source
*
* Return starting/ending indices for printing an echo.
 *******************************************************************************/
void setup_src ( input_data *input_vars, para_data *para_vars, geom_data *geom_vars,
                 sn_data *sn_vars, data_data *data_vars, control_data *control_vars,
                 mms_data *mms_vars, int *i1, int *i2, int *j1, int *j2, int *k1,
                 int *k2, int *ierr, char **error )
{
/*******************************************************************************
 * Local variables
 *******************************************************************************/
    int i, j, k, jj, kk, pp;

/*******************************************************************************
 * Form the base by setting the src to 0 to start. Then assign src to
 * spatial cells according to ndimen and src_opt.
 *******************************************************************************/
    if ( SRC_OPT == 3 )
    {
        mms_setup ( input_vars, para_vars, geom_vars, data_vars,
                    sn_vars, control_vars, mms_vars, ierr, error );
        return;
    }

/*******************************************************************************
 * If src_opt is 0, source is everywhere
 *******************************************************************************/
    *i1 = 1;
    *i2 = NX;

    *j1 = 1;
    *j2 = NY_GL;

    *k1 = 1;
    *k2 = NZ_GL;

/*******************************************************************************
 * if src_opt is not 0, reset indices for source's spatial range
 *******************************************************************************/
    if ( SRC_OPT == 1 )
    {
        *i1 = NX / 4 + 1;
        *i2 = 3 * NX / 4;

        if ( NDIMEN > 1 )
        {
            *j1 = NY_GL / 4 + 1;
            *j2 = 3 * NY_GL / 4;

            if ( NDIMEN > 2 )
            {
                *k1 = NZ_GL / 4 + 1;
                *k2 = 3 * NZ_GL / 4;
            }
        }
    }

    else if ( SRC_OPT == 2 )
    {
        *i2 = NX / 2;
        if ( NDIMEN > 1 )
        {
            *j2 = NY_GL / 2;

            if ( NDIMEN > 2 )
            {
                *k2 = NZ_GL / 2;
            }
        }
    }

/*******************************************************************************
 * Indices are all known, so set the source to unity for that range
 *******************************************************************************/
    for ( k = *k1; k <= *k2; k++ )
    {
        if ( (KLB <= k) && (k <= KUB) )
        {
            kk = fmod( (k-1), NZ ) + 1;
            for ( j = *j1; j <= *j2; j++ )
            {
                if ( (JLB <= j) && (j <= JUB) )
                {
                    jj = fmod( (j-1), NY ) + 1;
                    for ( i = *i1; i <= *i2; i++ )
                    {
                        for ( pp = 0; pp < NG; pp++ )
                        {
                            QI_4D((i-1),(jj-1),(kk-1),pp) = 1;
                        }
                    }
                }
            }
        }
    }
}
int main(int argc, char *argv[])
{
  double mean = atof(argv[1]);
  double sigma = atof(argv[2]);
  //for cell 1
  double g_Na1 = atof(argv[3]); //uS/nF 
  double g_CaT1 = atof(argv[4]);//-0.5;
  double g_CaS1 = atof(argv[5]);//-0.5; 
  double g_A1 = atof(argv[6]);
  double g_KCa1 = atof(argv[7]);//+1000.0;
  double g_K1 = atof(argv[8]);
  double g_L1 = atof(argv[9]); //uS/nF  
  //for cell 2
  double g_Na2 = g_Na1;//atof(argv[11]); //uS/nF 
  double g_CaT2 = g_CaT1;//atof(argv[12]);//-0.5;
  double g_CaS2 = g_CaS1;//atof(argv[13]);//-0.5; 
  double g_A2 = g_A1;//atof(argv[14]);
  double g_KCa2 = g_KCa1;//atof(argv[15]);//+1000.0;
  double g_K2 = g_K1;//atof(argv[16]);
  double g_L2 = g_L1;//atof(argv[18]); //uS/nF  
  //synaptic
  double g_syn1 =  atof(argv[10]);
  double g_syn2 =  g_syn1;//atof(argv[20]);
  //
  double corr_coef = 0;//atof(argv[21]); //correlation coefficient of the input
  double tau_c = 0;//atof(argv[22]); //correlation time const
  int num_run = 0;//atof(argv[23]);

  //don't use, use voltage derivative
  double V_th = -15; //mV, threshold for detecting spikes

  /*open files where spikes will be recorded*/
  char sp_file1 [999];
  sprintf (sp_file1, "spikes1_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na1, g_CaT1, g_CaS1, g_A1, g_KCa1, g_K1, g_L1, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run);
  FILE *spfile1;
  spfile1 = fopen(sp_file1,"w");
  //
  char sp_file2 [999];
  sprintf (sp_file2, "spikes2_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na2, g_CaT2, g_CaS2, g_A2, g_KCa2, g_K2, g_L2, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run);
  FILE *spfile2;
  spfile2 = fopen(sp_file2,"w");
  
  char V_file1 [999];
  sprintf (V_file1, "V1_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na1, g_CaT1, g_CaS1, g_A1, g_KCa1, g_K1, g_L1, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run);
  FILE *Vfile1;
  Vfile1 = fopen(V_file1,"w");
  //
  char V_file2 [999];
  sprintf (V_file2, "V2_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na2, g_CaT2, g_CaS2, g_A2, g_KCa2, g_K2, g_L2, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run);
  FILE *Vfile2;
  Vfile2 = fopen(V_file2,"w");

   /*For random number generation:*/
  gsl_rng * r;
  r = gsl_rng_alloc (gsl_rng_default);
  gsl_rng_set(r, time(NULL));
  /*done*/

  int ii, jj, nn;

  /* Defining the model
     gate = [ m h ][4]   gating variables for the four conductances
     g = [ g_Na g_CaT g_CaS g_A g_KCa g_K g_H g_leak ]    maximal conductances
     E = [ E_Na E_CaT E_CaS E_A E_KCa E_K E_H E_leak ]    Nernst (reversal) potentials 
     gmh = [ conductances as a function of time ]
  */
  
  //reversal potentials
  double E_Na = 50; //mV or 30?
  double E_A = -80; //mV
  double E_K = -80; //mV
  double E_Ca[2]; E_Ca[0] = 80; E_Ca[1] = 80; //mV default, but will vary
  double E_L = -50; //mV
  double C = 0.628; //nF 
  double tau_Ca = 200; //ms
  double I_Ca[2]; 
  //synaptic
  double E_syn = -80; //mV
  double tau_syn = 100; //ms

  /*Initial conditions*/
  double V[2];
  V[0] = -50; //mV
  V[1] = -50;
  double Ca[2]; Ca[0] = 0.5; Ca[1] = 0.5;
  double Ca_inf[2]; Ca_inf[0] = Ca[0]; Ca_inf[1] = Ca[1];
  double g[6][2];
  double gate[2][6][2];
  double tau[2][6][2];
  double gate_inf[2][6][2];
  double E[6][2];
  int p[6];
  double gnmh[6][2];

  for (nn=0;nn<2;nn++)
    {
      gate_inf[0][0][nn] = Xinf(V[nn],25.5,-5.29); //m, Na
      gate_inf[1][0][nn] = Xinf(V[nn],48.9,5.18); //h, Na
      gate_inf[0][1][nn] = Xinf(V[nn],27.1,-7.2); //m, CaT
      gate_inf[1][1][nn] = Xinf(V[nn],32.1,5.5); //h, CaT
      gate_inf[0][2][nn] = Xinf(V[nn],33.0,-8.1); //m, CaS
      gate_inf[1][2][nn] = Xinf(V[nn],60.0,6.2); //h, CaT
      gate_inf[0][3][nn] = Xinf(V[nn],27.2,-8.7); //m, A
      gate_inf[1][3][nn] = Xinf(V[nn],56.9,4.9); //h, A
      gate_inf[0][4][nn] = m_KCainf(V[nn],Ca[nn]); //m, kCa 
      gate_inf[1][4][nn] = 0.0; //h, kCa
      gate_inf[0][5][nn] = Xinf(V[nn],12.3,-11.8); //m, Kd
      gate_inf[1][5][nn] = 0.0; //h, Kd	

      for (ii=0;ii<6;ii++)
	{
	  //gate[0][ii][nn] = 0.02; //m
	  //gate[1][ii][nn] = 0.7; //h
	  gate[0][ii][nn] =  gate_inf[0][ii][nn];
	  gate[1][ii][nn] =  gate_inf[1][ii][nn];
	  gnmh[ii][nn] = 0.0;
	} 
    }
  
  E[0][0] = E_Na; E[0][1] = E_Na;
  E[1][0] = E_Ca[0]; E[1][1] = E_Ca[1]; 
  E[2][0] = E_Ca[0]; E[2][1] = E_Ca[1];
  E[3][0] = E_A;  E[3][1] = E_A;
  E[4][0] = E_K;  E[4][1] = E_K; 
  E[5][0] = E_K;  E[5][1] = E_K;
  //
  p[0] = p_Na;
  p[1] = p_CaT;
  p[2] = p_CaS;
  p[3] = p_A;
  p[4] = p_KCa;
  p[5] = p_K;
 
  g[0][0] = g_Na1;   g[0][1] = g_Na2;
  g[1][0] = g_CaT1;  g[1][1] = g_CaT2;
  g[2][0] = g_CaS1;  g[2][1] = g_CaS2;
  g[3][0] = g_A1;    g[3][1] = g_A2;
  g[4][0] = g_KCa1;  g[4][1] = g_KCa2;
  g[5][0] = g_K1;    g[5][1] = g_K2;

  double g_L[2]; g_L[0] = g_L1; g_L[1] = g_L2;
  double current_time = 0.0;
  double s_c = mean;
  double s_1 = mean;
  double s_2 = mean;
  double s[2]; 
  double Svar[2];
  Svar[1] = Xinf(V[0],45.0,-2.0);
  Svar[0] = Xinf(V[1],45.0,-2.0); 
  double S_inf[2];
  S_inf[0] = Svar[0]; 
  S_inf[1] = Svar[1];
  double g_syn[2]; g_syn[0] = g_syn1; g_syn[1] = g_syn2;
  int counter = 0;

  int voltage_high1 = 0;
  double spike1 = 0.0; //to impose an absolute refractory period when reading spikes
  int voltage_high2 = 0;
  double spike2 = 0.0; //to impose an absolute refractory period when reading spikes
  double rand_g1 = 0.0;
  double rand_g2 = 0.0;
  double rand_g3 = 0.0;

  double ds = 0.0;
  //  double I_ion[2];   I_ion[0] = 0.0;     I_ion[1] = 0.0;
 
  double sum_g[2], sum_Eg[2], tau_V[2], V_inf[2];
  while (current_time < total_time)
   {       
     current_time += dt;
     counter ++;
     //printf("%f \n",current_time);
     //s = mean + sigma/sqrt(dt)*rand_g; //if white noise

     //common input
     rand_g1 = gsl_ran_gaussian (r,1.0);
     //if correlated noise with correlation time constant tau_c
     ds = (mean-s_c)*(1-exp(-dt/tau_c)) + sigma*sqrt(1-exp(-2*dt/tau_c))*rand_g1; 
     s_c += ds;
     //independent input cell 1
     rand_g2 = gsl_ran_gaussian (r,1.0);
     ds = (mean-s_1)*(1-exp(-dt/tau_c)) + sigma*sqrt(1-exp(-2*dt/tau_c))*rand_g2; 
     s_1 += ds;
     //independent input cell 2
     rand_g3 = gsl_ran_gaussian (r,1.0);
     ds = (mean-s_2)*(1-exp(-dt/tau_c)) + sigma*sqrt(1-exp(-2*dt/tau_c))*rand_g3; 
     s_2 += ds;

     s[0] = s_1*(1-corr_coef) + s_c*corr_coef; //input to cell 1
     s[1] = s_2*(1-corr_coef) + s_c*corr_coef; //input to cell 2

     /*
       Model equations:
       C dv/dt = s - I_ion
       I_ion = sum( gate.*(V-E) )
       d gate/dt = -1/tau(v).*(gate-gate_0(v))
     */

     for (nn=0;nn<2;nn++)
       {
	 
	 //E_Ca[nn] = 500.0*R_F*(T + 273.15)*log(3000.0/Ca[nn]);
	 E[1][nn] = E_Ca[nn];
	 E[2][nn] = E_Ca[nn];

	 tau[0][0][nn] = tauX(V[nn],1.32,1.26,120.0,-25); //m, Na
	 tau[1][0][nn] = tauhNa(V[nn]); //h, Na
	 tau[0][1][nn] = tauX(V[nn],21.7,21.3,68.1,-20.5); //m, CaT
	 tau[1][1][nn] = tauX(V[nn],105.0,89.8,55.0,-16.9); //h, CaT
	 tau[0][2][nn] = taumCaS(V[nn]); //m, CaS
	 tau[1][2][nn] = tauhCaS(V[nn]); //h, CaS
	 tau[0][3][nn] = tauX(V[nn],11.6,10.4,32.9,-15.2); //m, A
	 tau[1][3][nn] = tauX(V[nn],38.6,29.2,38.9,-26.5); //h, A
	 tau[0][4][nn] = tauX(V[nn],90.3,75.1,46.0,-22.7); //m, KCa
	 tau[1][4][nn] = 0.0; //h, kCa
	 tau[0][5][nn] = tauX(V[nn],7.2,6.4,28.3,-19.2); //m, Kd
	 tau[1][5][nn] = 0.0; //h, Kd	

	 gate_inf[0][0][nn] = Xinf(V[nn],25.5,-5.29); //m, Na
	 gate_inf[1][0][nn] = Xinf(V[nn],48.9,5.18); //h, Na
	 gate_inf[0][1][nn] = Xinf(V[nn],27.1,-7.2); //m, CaT
	 gate_inf[1][1][nn] = Xinf(V[nn],32.1,5.5); //h, CaT
	 gate_inf[0][2][nn] = Xinf(V[nn],33.0,-8.1); //m, CaS
	 gate_inf[1][2][nn] = Xinf(V[nn],60.0,6.2); //h, CaT
	 gate_inf[0][3][nn] = Xinf(V[nn],27.2,-8.7); //m, A
	 gate_inf[1][3][nn] = Xinf(V[nn],56.9,4.9); //h, A
	 gate_inf[0][4][nn] = m_KCainf(V[nn],Ca[nn]); //m, kCa 
	 gate_inf[1][4][nn] = 0.0; //h, kCa
	 gate_inf[0][5][nn] = Xinf(V[nn],12.3,-11.8); //m, Kd
	 gate_inf[1][5][nn] = 0.0; //h, Kd	
       }
 
     S_inf[1] = Xinf(V[0],45.0,-2.0);
     S_inf[0] = Xinf(V[1],45.0,-2.0);
       
     for (nn=0;nn<2;nn++)
       {       
	 //evolve Svar
	 Svar[nn] = Svar[nn] + (1-exp(-dt/tau_syn))*(S_inf[nn] - Svar[nn]);


	 //evolve the conductances, first order Euler
	 for (ii=0;ii<6;ii++)
	   {
	     gate[0][ii][nn] = gate[0][ii][nn] + (1-exp(-dt/tau[0][ii][nn]))*(gate_inf[0][ii][nn] - gate[0][ii][nn]);
	     gate[1][ii][nn] = gate[1][ii][nn] + (1-exp(-dt/tau[1][ii][nn]))*(gate_inf[1][ii][nn] - gate[1][ii][nn]);
	   }
	 //reset
	 gate[1][4][nn] = 1.0; //h, KCa
	 gate[1][5][nn] = 1.0; //h, Kd
     
	 sum_g[nn] = g_L[nn] + g_syn[nn]*Svar[nn];
	 sum_Eg[nn] = g_L[nn]*E_L + g_syn[nn]*Svar[nn]*E_syn;
	 for (ii=0;ii<6;ii++)
	   {
	     gnmh[ii][nn] = g[ii][nn]*get_power(gate[0][ii][nn],p[ii])*gate[1][ii][nn];
	     sum_g[nn] = sum_g[nn] + gnmh[ii][nn];
	     sum_Eg[nn] = sum_Eg[nn] + gnmh[ii][nn]*E[ii][nn];
	   }
	 I_Ca[nn] = (gnmh[1][nn] + gnmh[2][nn])*(V[nn]-E_Ca[nn]);
	 	 
	 Ca_inf[nn] = 0.05 - 0.94*I_Ca[nn]*10.0;    
	 // integrate Ca dynamics 
	 Ca[nn] = Ca[nn] + (1-exp(-dt/tau_Ca))*(Ca_inf[nn] - Ca[nn]);

	 tau_V[nn]  = C/sum_g[nn];  //Membrane time constant.
	 
	 // V_inf is steady-state voltage.
	 //V_inf[nn] = (sum_Eg[nn] + s[nn])*tau_V[nn];
         V_inf[nn] = (sum_Eg[nn])*tau_V[nn];
	 
	 //evolve the voltage using exponential Euler
	 V[nn] = V_inf[nn] + (V[nn]-V_inf[nn])*exp(-dt/tau_V[nn]);
       }
     
     
     if (fmod(current_time,0.1)<dt)
       {
	 //printf("%g \n",current_time);
	 fprintf(Vfile1,"%f \n", V[0]);
	 fprintf(Vfile2,"%f \n", V[1]);
       }
     
     
     //find out if there's a spike and record it
     if (V[0] > V_th  & current_time>5000)
       {
	 //if a high threshold was detected, record the spike
	 if (voltage_high1 == 0 && current_time-spike1>5) //5 is tau_abs
	   {
	     fprintf(spfile1,"%f \n", current_time);
	     spike1 = current_time;
	   }
	 
	 //if the high threshold was continuous (after spike has occured)
	 //then wait for it to cross the threshold again before recording
	 voltage_high1 ++;
       }
     else
       {
	 if (voltage_high1 > 0)
	   {
	     voltage_high1 = 0; //reset
	   }
       }

     //same for cell 2
     if (V[1] > V_th  & current_time>5000)
       {
	 //if a high threshold was detected, record the spike
	 if (voltage_high2 == 0 && current_time-spike2>5) //5 is tau_abs
	   {
	     fprintf(spfile2,"%f \n", current_time);
	     spike2 = current_time;
	   }
	 
	 //if the high threshold was continuous (after spike has occured)
	 //then wait for it to cross the threshold again before recording
	 voltage_high2 ++;
       }
     else
       {
	 if (voltage_high2 > 0)
	   {
	     voltage_high2 = 0; //reset
	   }
       }
    
   }
     
  fclose(spfile1);
  fclose(spfile2);
  fclose(Vfile1);
  fclose(Vfile2);
 
 return 0;
}
Example #20
0
void send_freq_to_FT817( double frequency )
{
  fd_set fds;
  int count;
  struct timeval tv;
  unsigned char command[12];
  char ghz,hmhz,dmhz,mhz,hkhz,dkhz,khz,hhz;

  frequency=frequency*10.0;

  ghz =(frequency-fmod(frequency,10000000))/10000000;
  frequency=fmod(frequency,10000000);
  hmhz=(frequency-fmod(frequency,1000000))/1000000;
  frequency=fmod(frequency,1000000);
  dmhz=(frequency-fmod(frequency,100000))/100000;
  frequency=fmod(frequency,100000);
  mhz =(frequency-fmod(frequency,10000))/10000;
  frequency=fmod(frequency,10000);
  hkhz=(frequency-fmod(frequency,1000))/1000;
  frequency=fmod(frequency,1000);
  dkhz=(frequency-fmod(frequency,100))/100;
  frequency=fmod(frequency,100);
  khz =(frequency-fmod(frequency,10))/10;
  frequency=fmod(frequency,10);
  hhz =frequency;
  frequency=fmod(frequency,10);
  hhz =frequency;

  command[0]=(hmhz<<4)|dmhz;
  command[1]=(mhz<<4)|hkhz;
  command[2]=(dkhz<<4)|khz;
  command[3]=(hhz<<4)|dhz;
  command[4]=0x01;

  /* Send it */
#ifdef DEBUG
  fprintf( stderr, "FT817: Sending command ... ");
  {int i;
  for(i=0;i<11;i++) fprintf(stderr," %02X",command[i]);
  fprintf(stderr,"\n");
  }
#endif

  FD_ZERO(&fds);
  FD_SET(port, &fds);
  tv.tv_sec = 5;
  tv.tv_usec = 0;

  if (select(port+1, NULL, &fds, NULL, &tv)) {
    if ((count = write(port, command, 11)) == -1) {
      perror("write");
      return;
    }
  }
  else {
    fprintf( stderr,"FT817: Timeout sending command !!!\n");
    perror("select");
    return;
  }
}
Example #21
0
void pattern_render(struct pattern * pattern, GLuint input_tex) {
    GLenum e;

    glLoadIdentity();
    glViewport(0, 0, config.pattern.master_width, config.pattern.master_height);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, pattern->fb);

    pattern->intensity_integral = fmod(pattern->intensity_integral + pattern->intensity / config.ui.fps, MAX_INTEGRAL);

    for (int i = pattern->n_shaders - 1; i >= 0; i--) {
        glUseProgramObjectARB(pattern->shader[i]);

        // Don't worry about this part.
        for(int j = 0; j < pattern->n_shaders; j++) {
            // Or, worry about it, but don't think about it.
            glActiveTexture(GL_TEXTURE1 + j);
            glBindTexture(GL_TEXTURE_2D, pattern->tex[(pattern->flip + j + (i < j)) % (pattern->n_shaders + 1)]);
        }
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,
                                  pattern->tex[(pattern->flip + i + 1) % (pattern->n_shaders + 1)], 0);

        if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));

        GLint loc;
        loc = glGetUniformLocationARB(pattern->shader[i], "iTime");
        glUniform1fARB(loc, time_master.beat_frac + time_master.beat_index);
        loc = glGetUniformLocationARB(pattern->shader[i], "iAudioHi");
        glUniform1fARB(loc, audio_hi);
        loc = glGetUniformLocationARB(pattern->shader[i], "iAudioMid");
        glUniform1fARB(loc, audio_mid);
        loc = glGetUniformLocationARB(pattern->shader[i], "iAudioLow");
        glUniform1fARB(loc, audio_low);
        loc = glGetUniformLocationARB(pattern->shader[i], "iAudioLevel");
        glUniform1fARB(loc, audio_level);
        loc = glGetUniformLocationARB(pattern->shader[i], "iResolution");
        glUniform2fARB(loc, config.pattern.master_width, config.pattern.master_height);
        loc = glGetUniformLocationARB(pattern->shader[i], "iIntensity");
        glUniform1fARB(loc, pattern->intensity);
        loc = glGetUniformLocationARB(pattern->shader[i], "iIntensityIntegral");
        glUniform1fARB(loc, pattern->intensity_integral);
        loc = glGetUniformLocationARB(pattern->shader[i], "iFPS");
        glUniform1fARB(loc, config.ui.fps);
        loc = glGetUniformLocationARB(pattern->shader[i], "iFrame");
        glUniform1iARB(loc, 0);
        loc = glGetUniformLocationARB(pattern->shader[i], "iChannel");
        glUniform1ivARB(loc, pattern->n_shaders, pattern->uni_tex);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, input_tex);

        if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));

        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_QUADS);
        glVertex2d(-1, -1);
        glVertex2d(-1, 1);
        glVertex2d(1, 1);
        glVertex2d(1, -1);
        glEnd();

        if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));
    }
    pattern->flip = (pattern->flip + 1) % (pattern->n_shaders + 1);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

    if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));
    pattern->tex_output = pattern->tex[pattern->flip];
}
/* 逆波兰计算器 */
main()
{
	int type;
	double op1, op2;
	char s[MAXOP];

	while ((type = getop(s)) != EOF) {
		switch (type) {
		case NUMBER:
			push(atof(s));
			break;
		case '+':
			push(pop() + pop());
			break;
		case '*':
			push(pop() * pop());
			break;
		case '-':
			op2 = pop();
			push(pop() - op2);
			break;
		case '/':
			op2 = pop();
			if (op2 != 0.0)
				push(pop() /op2);
			else
				printf("error: zero divisor\n");
			break;
		case '%':
			op2 = pop();
			if (op2 != 0.0)
				push(fmod(pop(), op2));
			else
				printf("error: zero divisor\n");
			break;
		case '?': /* print top element of the stack */
			op2 = pop();
			printf("\t%.8g\n", op2);
			push(op2);
			break;
		case 'c': /* clear the stack */
			clear();
			break;
		case 'd': /* duplicate top top of the stack */
			op2 = pop();
			push(op2);
			push(op2);
			break;
		case 's': /* swap the top two elements */
			op1 = pop();
			op2 = pop();
			push(op1);
			push(op2);
			break;
		case '\n':
			printf("\t%.8g\n", pop());
			break;
		default:
			printf("error: unknown command %s\n", s);
			break;
		}
	}
	return 0;
}
Example #23
0
ComputedTiming
KeyframeEffectReadonly::GetComputedTimingAt(
                          const Nullable<TimeDuration>& aLocalTime,
                          const AnimationTiming& aTiming)
{
  const TimeDuration zeroDuration;

  // Currently we expect negative durations to be picked up during CSS
  // parsing but when we start receiving timing parameters from other sources
  // we will need to clamp negative durations here.
  // For now, if we're hitting this it probably means we're overflowing
  // integer arithmetic in mozilla::TimeStamp.
  MOZ_ASSERT(aTiming.mIterationDuration >= zeroDuration,
             "Expecting iteration duration >= 0");

  // Always return the same object to benefit from return-value optimization.
  ComputedTiming result;

  result.mActiveDuration = ActiveDuration(aTiming);

  // The default constructor for ComputedTiming sets all other members to
  // values consistent with an animation that has not been sampled.
  if (aLocalTime.IsNull()) {
    return result;
  }
  const TimeDuration& localTime = aLocalTime.Value();

  // When we finish exactly at the end of an iteration we need to report
  // the end of the final iteration and not the start of the next iteration
  // so we set up a flag for that case.
  bool isEndOfFinalIteration = false;

  // Get the normalized time within the active interval.
  StickyTimeDuration activeTime;
  if (localTime >= aTiming.mDelay + result.mActiveDuration) {
    result.mPhase = ComputedTiming::AnimationPhase_After;
    if (!aTiming.FillsForwards()) {
      // The animation isn't active or filling at this time.
      result.mTimeFraction = ComputedTiming::kNullTimeFraction;
      return result;
    }
    activeTime = result.mActiveDuration;
    // Note that infinity == floor(infinity) so this will also be true when we
    // have finished an infinitely repeating animation of zero duration.
    isEndOfFinalIteration =
      aTiming.mIterationCount != 0.0 &&
      aTiming.mIterationCount == floor(aTiming.mIterationCount);
  } else if (localTime < aTiming.mDelay) {
    result.mPhase = ComputedTiming::AnimationPhase_Before;
    if (!aTiming.FillsBackwards()) {
      // The animation isn't active or filling at this time.
      result.mTimeFraction = ComputedTiming::kNullTimeFraction;
      return result;
    }
    // activeTime is zero
  } else {
    MOZ_ASSERT(result.mActiveDuration != zeroDuration,
               "How can we be in the middle of a zero-duration interval?");
    result.mPhase = ComputedTiming::AnimationPhase_Active;
    activeTime = localTime - aTiming.mDelay;
  }

  // Get the position within the current iteration.
  StickyTimeDuration iterationTime;
  if (aTiming.mIterationDuration != zeroDuration) {
    iterationTime = isEndOfFinalIteration
                    ? StickyTimeDuration(aTiming.mIterationDuration)
                    : activeTime % aTiming.mIterationDuration;
  } /* else, iterationTime is zero */

  // Determine the 0-based index of the current iteration.
  if (isEndOfFinalIteration) {
    result.mCurrentIteration =
      aTiming.mIterationCount == NS_IEEEPositiveInfinity()
      ? UINT64_MAX // FIXME: When we return this via the API we'll need
                   // to make sure it ends up being infinity.
      : static_cast<uint64_t>(aTiming.mIterationCount) - 1;
  } else if (activeTime == zeroDuration) {
    // If the active time is zero we're either in the first iteration
    // (including filling backwards) or we have finished an animation with an
    // iteration duration of zero that is filling forwards (but we're not at
    // the exact end of an iteration since we deal with that above).
    result.mCurrentIteration =
      result.mPhase == ComputedTiming::AnimationPhase_After
      ? static_cast<uint64_t>(aTiming.mIterationCount) // floor
      : 0;
  } else {
    result.mCurrentIteration =
      static_cast<uint64_t>(activeTime / aTiming.mIterationDuration); // floor
  }

  // Normalize the iteration time into a fraction of the iteration duration.
  if (result.mPhase == ComputedTiming::AnimationPhase_Before) {
    result.mTimeFraction = 0.0;
  } else if (result.mPhase == ComputedTiming::AnimationPhase_After) {
    result.mTimeFraction = isEndOfFinalIteration
                         ? 1.0
                         : fmod(aTiming.mIterationCount, 1.0f);
  } else {
    // We are in the active phase so the iteration duration can't be zero.
    MOZ_ASSERT(aTiming.mIterationDuration != zeroDuration,
               "In the active phase of a zero-duration animation?");
    result.mTimeFraction =
      aTiming.mIterationDuration == TimeDuration::Forever()
      ? 0.0
      : iterationTime / aTiming.mIterationDuration;
  }

  bool thisIterationReverse = false;
  switch (aTiming.mDirection) {
    case NS_STYLE_ANIMATION_DIRECTION_NORMAL:
      thisIterationReverse = false;
      break;
    case NS_STYLE_ANIMATION_DIRECTION_REVERSE:
      thisIterationReverse = true;
      break;
    case NS_STYLE_ANIMATION_DIRECTION_ALTERNATE:
      thisIterationReverse = (result.mCurrentIteration & 1) == 1;
      break;
    case NS_STYLE_ANIMATION_DIRECTION_ALTERNATE_REVERSE:
      thisIterationReverse = (result.mCurrentIteration & 1) == 0;
      break;
  }
  if (thisIterationReverse) {
    result.mTimeFraction = 1.0 - result.mTimeFraction;
  }

  return result;
}
Example #24
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   S h e a r I m a g e                                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ShearImage() creates a new image that is a shear_image copy of an existing
%  one.  Shearing slides one edge of an image along the X or Y axis, creating
%  a parallelogram.  An X direction shear slides an edge along the X axis,
%  while a Y direction shear slides an edge along the Y axis.  The amount of
%  the shear is controlled by a shear angle.  For X direction shears, x_shear
%  is measured relative to the Y axis, and similarly, for Y direction shears
%  y_shear is measured relative to the X axis.  Empty triangles left over from
%  shearing the image are filled with the background color defined by member
%  'background_color' of the image..  ShearImage() allocates the memory
%  necessary for the new Image structure and returns a pointer to the new image.
%
%  ShearImage() is based on the paper "A Fast Algorithm for General Raster
%  Rotatation" by Alan W. Paeth.
%
%  The format of the ShearImage method is:
%
%      Image *ShearImage(const Image *image,const double x_shear,
%        const double y_shear,ExceptionInfo *exception)
%
%  A description of each parameter follows.
%
%    o image: The image.
%
%    o x_shear, y_shear: Specifies the number of degrees to shear the image.
%
%    o exception: Return any errors or warnings in this structure.
%
%
*/
MagickExport Image *ShearImage(const Image *image,const double x_shear,
  const double y_shear,ExceptionInfo *exception)
{
  Image
    *integral_image,
    *shear_image;

  long
    x_offset,
    y_offset;

  PointInfo
    shear;

  RectangleInfo
    border_info;

  unsigned long
    y_width;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0))
    ThrowImageException(ImageError,"AngleIsDiscontinuous");
  if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0))
    ThrowImageException(ImageError,"AngleIsDiscontinuous");
  /*
    Initialize shear angle.
  */
  integral_image=CloneImage(image,0,0,MagickTrue,exception);
  if (integral_image == (Image *) NULL)
    ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
  shear.x=(-tan(DegreesToRadians(x_shear)));
  shear.y=tan(DegreesToRadians(y_shear));
  if ((shear.x == 0.0) && (shear.y == 0.0))
    return(integral_image);
  integral_image->storage_class=DirectClass;
  if (integral_image->matte == MagickFalse)
    SetImageOpacity(integral_image,OpaqueOpacity);
  /*
    Compute image size.
  */
  x_offset=(long) (fabs((double) image->rows*shear.x)+0.5);
  y_width=(unsigned long)
    (fabs((double) image->rows*shear.x)+image->columns+0.5);
  y_offset=(long) (fabs((double) y_width*shear.y)+0.5);
  /*
    Surround image with border.
  */
  integral_image->border_color=integral_image->background_color;
  border_info.width=(unsigned long) x_offset;
  border_info.height=(unsigned long) y_offset;
  shear_image=BorderImage(integral_image,&border_info,exception);
  if (shear_image == (Image *) NULL)
    ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
  integral_image=DestroyImage(integral_image);
  /*
    Shear the image.
  */
  if (shear_image->matte == MagickFalse)
    SetImageOpacity(shear_image,OpaqueOpacity);
  XShearImage(shear_image,shear.x,image->columns,image->rows,x_offset,
    ((long) shear_image->rows-image->rows)/2);
  YShearImage(shear_image,shear.y,y_width,image->rows,
    ((long) shear_image->columns-y_width)/2,y_offset);
  CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType) image->columns,
    (MagickRealType) image->rows,MagickFalse,exception);
  shear_image->page.width=0;
  shear_image->page.height=0;
  return(shear_image);
}
Example #25
0
double Random::Double(double minimum, double maximum) {
  return minimum + fmod(std::rand(), (maximum - minimum + 1.0));
}
Example #26
0
static double mod2pi(double a)
{
  return((double)((a=fmod(a, M_2PI))>0.0)?a:(FEQ(a,0.0,EPSILON)?0.0:(a + M_2PI)));
}
/* add_operator:
 *  Processes a new operator from the input string.
 */
static void add_operator(char op)
{
   /* bodge for unary negation */
   if ((op == OP_MINUS) && (!current_valid))
      op = OP_NEGATE;

   /* check validity */
   if ((op == OP_PLUS)        || (op == OP_MINUS)          || 
       (op == OP_MUL)         || (op == OP_DIV)            || 
       (op == OP_POWER)       || (op == OP_MOD)            ||
       (op == OP_EQUALS)      || (op == OP_NOT_EQUALS)     ||
       (op == OP_LESS)        || (op == OP_GREATER)        ||
       (op == OP_LESS_EQUALS) || (op == OP_GREATER_EQUALS) ||
       (op == OP_OR)          || (op == OP_AND)) {

      if (!current_valid) {
	 evaluate_error = TRUE;
	 return;
      }
   }

   /* evaluate */
   if (op != OP_OPEN_PAREN) {
      while ((stack_depth > 0) && 
	     ((precedence(op) <= precedence(operator_stack[stack_depth-1]) && (!is_unary(operator_stack[stack_depth-1]))) ||
	      (precedence(op) < precedence(operator_stack[stack_depth-1]) && (is_unary(operator_stack[stack_depth-1]))))) {

	 stack_depth--;

	 switch (operator_stack[stack_depth]) {

	    case OP_PLUS:
	       current_val = value_stack[stack_depth] + current_val;
	       break;

	    case OP_MINUS:
	       current_val = value_stack[stack_depth] - current_val;
	       break;

	    case OP_MUL:
	       current_val = value_stack[stack_depth] * current_val;
	       break;

	    case OP_DIV:
	       if (current_val != 0)
		  current_val = value_stack[stack_depth] / current_val;
	       else
		  current_val = 0;
	       break;

	    case OP_POWER:
	       current_val = pow(value_stack[stack_depth], current_val);
	       break;

	    case OP_NEGATE:
	       current_val = -current_val;
	       break;

	    case OP_SQRT:
	       if (current_val >= 0)
		  current_val = sqrt(current_val);
	       else
		  current_val = 0;
	       break;

	    case OP_SIN:
	       current_val = sin(DEG2RAD(current_val));
	       break;

	    case OP_COS:
	       current_val = cos(DEG2RAD(current_val));
	       break;

	    case OP_TAN:
	       current_val = tan(DEG2RAD(current_val));
	       break;

	    case OP_ASIN:
	       if ((current_val >= -1) && (current_val <= 1))
		  current_val = RAD2DEG(asin(current_val));
	       else
		  current_val = 0;
	       break;

	    case OP_ACOS:
	       if ((current_val >= -1) && (current_val <= 1))
		  current_val = RAD2DEG(acos(current_val));
	       else
		  current_val = 0;
	       break;

	    case OP_ATAN:
	       current_val = RAD2DEG(atan(current_val));
	       break;

	    case OP_LOG:
	       if (current_val > 0)
		  current_val = log10(current_val);
	       else
		  current_val = 0;
	       break;

	    case OP_LN:
	       if (current_val > 0)
		  current_val = log(current_val);
	       else
		  current_val = 0;
	       break;

	    case OP_CEIL:
	       current_val = ceil(current_val);
	       break;

	    case OP_FLOOR:
	       current_val = floor(current_val);
	       break;

	    case OP_ROUND:
	       if (current_val < 0)
		  current_val = (int)(current_val - 0.5);
	       else
		  current_val = (int)(current_val + 0.5);
	       break;

	    case OP_ABS:
	       current_val = fabs(current_val);
	       break;

	    case OP_MOD:
	       if (current_val >= 1)
		  current_val = fmod(value_stack[stack_depth], current_val);
	       else
		  current_val = 0;
	       break;

	    case OP_EQUALS:
	       current_val = (value_stack[stack_depth] == current_val);
	       break;

	    case OP_NOT_EQUALS:
	       current_val = (value_stack[stack_depth] != current_val);
	       break;

	    case OP_LESS:
	       current_val = (value_stack[stack_depth] < current_val);
	       break;

	    case OP_GREATER:
	       current_val = (value_stack[stack_depth] > current_val);
	       break;

	    case OP_LESS_EQUALS:
	       current_val = (value_stack[stack_depth] <= current_val);
	       break;

	    case OP_GREATER_EQUALS:
	       current_val = (value_stack[stack_depth] >= current_val);
	       break;

	    case OP_OR:
	       current_val = ((int)value_stack[stack_depth] || (int)current_val);
	       break;

	    case OP_AND:
	       current_val = ((int)value_stack[stack_depth] && (int)current_val);
	       break;

	    case OP_NOT:
	       current_val = !(int)current_val;
	       break;

	    case OP_OPEN_PAREN:
	       if (op == OP_CLOSE_PAREN)
		  return;
	       break;
	 }
      }
   }

   /* push onto the stack */
   if (op != OP_CLOSE_PAREN) {
      operator_stack[stack_depth] = op;
      value_stack[stack_depth] = current_val;
      stack_depth++;
      current_val = 0;
      current_valid = FALSE;
   }
   else {
      if (stack_depth <= 0)
	 evaluate_error = TRUE;
   }
}
Example #28
0
File: 4-5.c Project: weezybusy/KnR2
int main(void)
{
        /* reverse Polish calculator */

        int type;
        double op2;
        char s[MAXOP];

        while ((type = getop(s)) != EOF) {
                switch (type) {
                case NUMBER:
                        push(atof(s) * sign);
                        sign = 1;    /* reset sign */
                        break;
                case SIN:
                        push(sin(pop()));
                        break;
                case COS:
                        push(cos(pop()));
                        break;
                case EXP:
                        push(exp(pop()));
                        break;
                case POW:
                        op2 = pop();
                        push(pow(pop(), op2));
                        break;
                case SQRT:
                        push(sqrt(pop()));
                        break;
                case '+':
                        push(pop() + pop());
                        break;
                case '*':
                        push(pop() * pop());
                        break;
                case '-':
                        op2 = pop();
                        push(pop() - op2);
                        break;
                case '/':
                        op2 = pop();
                        if (op2 != 0.0)
                                push(pop() / op2);
                        else
                                printf("error: zero devision\n");
                        break;
                case '%':
                        op2 = pop();
                        if (op2 != 0)
                                push(fmod(pop(), op2));
                        else
                                printf("error: zero devision\n");
                        break;
                case '\n':
                        if (popallowed)
                                printf("\t%.8g\n", pop());
                        else
                                popallowed = 1;
                        break;
                case '?':
                        printtop();
                        break;
                case '&':
                        dupetop();
                        break;
                case '~':
                        swaptop();
                        break;
                case '!':
                        clrstack();
                        break;
                default:
                        printf("error: unknown command\n");
                        break;
                }
        }
        return 0;
}
Example #29
0
PyObject * vdw(PyObject* self, PyObject *args)
{
  PyArrayObject* n_obj;
  PyArrayObject* q0_obj;
  PyArrayObject* R_obj;
  PyArrayObject* cell_obj;
  PyArrayObject* pbc_obj;
  PyArrayObject* repeat_obj;
  PyArrayObject* phi_obj;
  double ddelta;
  double dD;
  int iA;
  int iB;
  PyArrayObject* rhistogram_obj;
  double drhist;
  PyArrayObject* Dhistogram_obj;
  double dDhist;
  if (!PyArg_ParseTuple(args, "OOOOOOOddiiOdOd", &n_obj, &q0_obj, &R_obj,
                        &cell_obj, &pbc_obj, &repeat_obj,
                        &phi_obj, &ddelta, &dD, &iA, &iB,
                        &rhistogram_obj, &drhist,
                        &Dhistogram_obj, &dDhist))
    return NULL;

  int ndelta = PyArray_DIMS(phi_obj)[0];
  int nD = PyArray_DIMS(phi_obj)[1];
  const double* n = (const double*)DOUBLEP(n_obj);
  const int ni = PyArray_SIZE(n_obj);
  const double* q0 = (const double*)DOUBLEP(q0_obj);
  const double (*R)[3] = (const double (*)[3])DOUBLEP(R_obj);
  const double* cell = (const double*)DOUBLEP(cell_obj);
  const char* pbc = (const char*)(PyArray_DATA(pbc_obj));
  const long* repeat = (const long*)(PyArray_DATA(repeat_obj));
  const double (*phi)[nD] = (const double (*)[nD])DOUBLEP(phi_obj);
  double* rhistogram = (double*)DOUBLEP(rhistogram_obj);
  double* Dhistogram = (double*)DOUBLEP(Dhistogram_obj);

  int nbinsr = PyArray_DIMS(rhistogram_obj)[0];
  int nbinsD = PyArray_DIMS(Dhistogram_obj)[0];

  double energy = 0.0;
  if (repeat[0] == 0 && repeat[1] == 0 && repeat[2] == 0)
    for (int i1 = iA; i1 < iB; i1++)
      {
        const double* R1 = R[i1];
        double q01 = q0[i1];
        for (int i2 = 0; i2 <= i1; i2++)
          {
            double rr = 0.0;
            for (int c = 0; c < 3; c++)
              {
                double f = R[i2][c] - R1[c];
                if (pbc[c])
                  f = fmod(f + 1.5 * cell[c], cell[c]) - 0.5 * cell[c];
                rr += f * f;
              }
            double r = sqrt(rr);
            double d1 = r * q01;
            double d2 = r * q0[i2];
            double D = 0.5 * (d1 + d2);
            double e12 = (vdwkernel(D, d1, d2, nD, ndelta, dD, ddelta, phi) *
                          n[i1] * n[i2]);
            if (i1 == i2)
              e12 /= 2.0;
            int bin = (int)(r / drhist);
            if (bin < nbinsr)
              rhistogram[bin] += e12; 
            bin = (int)(D / dDhist);
            if (bin < nbinsD)
              Dhistogram[bin] += e12; 
            energy += e12;
          }
      }
  else
    for (int i1 = iA; i1 < iB; i1++)
      {
        const double* R1 = R[i1];
        double q01 = q0[i1];
        for (int a1 = -repeat[0]; a1 <= repeat[0]; a1++)
          for (int a2 = -repeat[1]; a2 <= repeat[1]; a2++)
            for (int a3 = -repeat[2]; a3 <= repeat[2]; a3++)
              {
                double x = 0.5;
                int i2max = ni-1;
                if (a1 == 0 && a2 == 0 && a3 == 0)
                  {
                    i2max = i1;
                    x = 1.0;
                  }
                double R1a[3] = {R1[0] + a1 * cell[0],
                                 R1[1] + a2 * cell[1],
                                 R1[2] + a3 * cell[2]};
                for (int i2 = 0; i2 <= i2max; i2++)
                  {
                    double rr = 0.0;
                    for (int c = 0; c < 3; c++)
                      {
                        double f = R[i2][c] - R1a[c];
                        rr += f * f;
                      }
                    double r = sqrt(rr);
                    double d1 = r * q01;
                    double d2 = r * q0[i2];
                    double D = 0.5 * (d1 + d2);
                    double e12 = (vdwkernel(D, d1, d2,
                                            nD, ndelta, dD, ddelta, phi) *
                                  n[i1] * n[i2] * x);
                    int bin = (int)(r / drhist);
                    if (bin < nbinsr)
                      rhistogram[bin] += e12; 
                    bin = (int)(D / dDhist);
                    if (bin < nbinsD)
                      Dhistogram[bin] += e12; 
                    energy += e12;
                  }
              }
      }
  return PyFloat_FromDouble(energy);
}
Example #30
0
static int GCol_TextChanged(GGadget *g, GEvent *e) {
    if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) {
	struct gcol_data *d = GDrawGetUserData(GGadgetGetWindow(g));
	double *offs[7] = { &d->col.h, &d->col.s, &d->col.v, &d->col.r, &d->col.g, &d->col.b, &d->col.alpha };
	int i, err = false;
	int low, high;
	double val;
	char text[50];

	if ( GGadgetGetCid(g)==CID_Alpha ) {
	    low = 3; high=7;
	    /* Didn't actually change the rgb values, but parse them */
	    /*  This is in case we need to clear the error flag */
	    d->col.hsv = false;
	    d->col.rgb = true;
	} else if ( GGadgetGetCid(g)>=CID_Hue ) {
	    low = 0; high=3;
	    d->col.hsv = true;
	    d->col.rgb = false;
	} else {
	    low = 3; high=6;
	    d->col.hsv = false;
	    d->col.rgb = true;
	}
	for ( i=low; i<high; ++i ) {
	    val = GetCalmReal8(d->gw,cids[i],_(labnames[i]),&err);
	    if ( err )
	break;
	    if ( i==0 ) {
		val = fmod(val,360);
		if ( val<0 ) val += 360;
	    } else {
		if ( val<0 || val>1 ) {
		    err = true;
	break;
		}
	    }
	    *offs[i] = val;
	}
	if ( err ) {
	    d->col.hsv = d->col.rgb = false;
	} else if ( d->col.hsv ) {
	    gHSV2RGB((struct hslrgb *) &d->col);
	    for ( i=3; i<6; ++i ) {
		sprintf( text, "%.2f", *offs[i]);
		GGadgetSetTitle8(GWidgetGetControl(d->gw,cids[i]),text);
	    }
	} else {
	    gRGB2HSV((struct hslrgb *) &d->col);
	    sprintf( text, "%3.0f", *offs[0]);
	    GGadgetSetTitle8(GWidgetGetControl(d->gw,cids[0]),text);
	    for ( i=1; i<3; ++i ) {
		sprintf( text, "%.2f", *offs[i]);
		GGadgetSetTitle8(GWidgetGetControl(d->gw,cids[i]),text);
	    }
	}
	GDrawRequestExpose(d->wheelw,NULL,false);
	GDrawRequestExpose(d->gradw,NULL,false);
	GDrawRequestExpose(d->colw,NULL,false);
    }
return( true );
}