コード例 #1
0
ファイル: shapeintersect.cpp プロジェクト: Dingf/Paper-TD
bool RectConeIntersect(const Rect * rect, const Cone * cone)
{
	Circle circle(cone->GetVertex(), cone->GetHeight());
	if (Intersect(rect, &circle) == true)
	{
		Point2D corners[4] = 
		{
			Point2D(rect->GetLeft(),	rect->GetTop()),
			Point2D(rect->GetLeft(),	rect->GetBottom()),
			Point2D(rect->GetRight(),	rect->GetBottom()),
			Point2D(rect->GetRight(),	rect->GetTop()),
		};

		if (rect->ContainsPoint(cone->GetVertex()) == true)
		{
			return true;
		}
		for (uint8 i = 0; i < 4; i++)
		{
			if (cone->ContainsPoint(corners[i]) == true)
			{
				return true;
			}
		}

		Vector3D direction(cone->GetVertex(), cone->GetVertex() + cone->GetDirection());
		Float angle = direction.GetZeroAngleD();

		Float angle1 = angle + cone->GetAngle();
		Float angle2 = angle - cone->GetAngle();

		Float height = cone->GetHeight();
		Point3D vertex = cone->GetVertex();

		LineSegment line1(vertex, Point3D(vertex.GetX() + (CosD(angle1) * height), vertex.GetY() + (SinD(angle1) * height), 0));
		LineSegment line2(vertex, Point3D(vertex.GetX() + (CosD(angle2) * height), vertex.GetY() + (SinD(angle2) * height), 0));

		return ((Intersect(rect, &line1) == true) || (Intersect(rect, &line2) == true));
	}
	return false;
}
コード例 #2
0
MMatrix sgHair_controlJoint::getAngleWeightedMatrix( const MMatrix& targetMtx, double weight )
{
	MMatrix mtx;
	if( m_bStaticRotation )
	{
		mtx = MMatrix() * ( weight-1 ) + targetMtx * weight;
		cleanMatrix( mtx );
	}
	else
	{
		MVector vUpDefault( 0, 1, 0 );
		MVector vCrossDefault( 0,0,1 );
		MVector vUpInput( targetMtx(1,0), targetMtx(1,1), targetMtx(1,2) );

		double angleUp = vUpInput.angle( vUpDefault ) * weight;

		if( vUpInput.x == 0 && vUpInput.z == 0 ) vUpInput.x = 1;
		MVector direction( vUpInput.x, 0, vUpInput.z );
		direction.normalize();

		MVector vUp( sin( angleUp ) * direction.x, cos( angleUp ), sin( angleUp ) * direction.z );
		double dot = vUp * MVector( 0.0, 0.0, 1.0 );
		MVector vCross( 0.0, -dot, (dot+1) );
		MVector vAim = vUp ^ vCross;

		vAim.normalize();
		vUp.normalize();
		vCross = vAim ^ vUp;

		mtx( 0, 0 ) = vAim.x;
		mtx( 0, 1 ) = vAim.y;
		mtx( 0, 2 ) = vAim.z;
		mtx( 1, 0 ) = vUp.x;
		mtx( 1, 1 ) = vUp.y;
		mtx( 1, 2 ) = vUp.z;
		mtx( 2, 0 ) = vCross.x;
		mtx( 2, 1 ) = vCross.y;
		mtx( 2, 2 ) = vCross.z;
	}
	return mtx;
}
コード例 #3
0
ファイル: shape.cpp プロジェクト: rikshot/sandbox
bool shape::intersects(shape const& shape) const {
  vector direction(shape.centroid() - centroid());

  std::vector<vector> simplex;
  simplex.push_back(vertices_[support(direction)] - shape.vertices()[shape.support(-direction)]);
  direction = -direction;

  for(;;) {
    vector const a(vertices_[support(direction)] - shape.vertices()[shape.support(-direction)]);
    if(a.dot(direction) <= 0.0f)
      return false;
    simplex.push_back(a);
    vector const ao(-a);

    if(simplex.size() == 3) {
      vector const b(simplex[1]);
      vector const c(simplex[0]);
      vector const ab(b - a);
      vector const ac(c - a);

      vector const ab_triple(vector::triple_product_left(ac, ab, ab));
      if(ab_triple.dot(ao) >= 0.0f) {
        simplex.erase(simplex.begin());
        direction = ab_triple;
      } else {
        vector const ac_triple(vector::triple_product_left(ab, ac, ac));
        if(ac_triple.dot(ao) >= 0.0f) {
          simplex.erase(simplex.begin() + 1);
          direction = ac_triple;
        } else
          return true;
      }
    } else {
      vector const b(simplex[0]);
      vector const ab(b - a);
      direction = vector::triple_product_left(ab, ao, ab);
      if(!direction)
        direction = ab.left();
    }
  }
}
コード例 #4
0
void
vpDrawable::ConvertToPhysics_Rigid()
{
	m_objectCount = 1;
	m_object = new vsCollisionObject *[1];

	bool isStatic = false;
	if ( m_drawMode == DrawMode_Static )
		isStatic = true;

	m_object[0] = new vsCollisionObject( ColFlag_Player, ColFlag_All, isStatic );
	// for each line of our optimised model, add a box to our collision object!

	for ( int i = 0; i < m_optimisedIndexCount-1; i++ )
	{
		const vsVector2D &start = m_samplePos[m_optimisedIndex[i]];
		const vsVector2D &end = m_samplePos[m_optimisedIndex[i+1]];

		vsVector2D direction(end.x-start.x,end.y-start.y);
		vsAngle ang = vsAngle::FromForwardVector(direction);
		float length = direction.Length();

		if ( length > 0.f )
		{
			float density = 1.0f;
			float width = 0.15f;

			if ( m_drawMode == DrawMode_Static )
				density = 0.f;

			vsVector2D extent( width, length );
			vsVector2D midpoint = 0.5f * (start + end);

			m_object[0]->AddBox( extent, midpoint, ang, density );
		}
	}

	m_object[0]->SetCollisionsActive(true);
	m_object[0]->SetUserData(this);
	m_object[0]->SetResponder(this);
}
コード例 #5
0
ファイル: system_controls.hpp プロジェクト: svenstaro/bgj09
	void update(entityx::EntityManager &es, entityx::EventManager &events, double dt)
	{
		entityx::ComponentHandle<Moveable> moveable;
		entityx::ComponentHandle<Position> position;
		entityx::ComponentHandle<Player> player;

		for(entityx::Entity entity : es.entities_with_components(player))
		{
			float x = 0.0f;
			float y = 0.0f;

			const Uint8 *state = SDL_GetKeyboardState(NULL);
			if(state[SDL_SCANCODE_W])
			{
				y-=1.0f;
			}
			if(state[SDL_SCANCODE_A])
			{
				x-=1.0f;
			}
			if(state[SDL_SCANCODE_S])
			{
				y+=1.0f;
			}
			if(state[SDL_SCANCODE_D])
			{
				x+=1.0f;
			}
			if(state[SDL_SCANCODE_SPACE])
			{
				events.emit<PlayerInstructionLight>(entity);
			}
			if(x != 0.0f || y != 0.0f)
			{
				glm::vec2 direction(x,y);
				direction = glm::normalize(direction);// *(float) dt;
				events.emit<PlayerInstructionEvent>(direction,entity);
			}
			
		}
	}
コード例 #6
0
int MovingObject::status()
{
    printf("Method: %c\n", _method);
    printf("First: %d - Last: %d\n", _first(), _last);
    printf("RealQueueSize: %d\n", _realQueueSize);
    printf("Filled: %s\n", _filled?"true":"false");
    printf("Valorized: %s\n", _valorized()?"true":"false");

    int i, count;
    if (_valorized()) {
        for(i=_first(), count=0; _filled?count<_realQueueSize:i<=_last; i++, count++) {
            i=i%_realQueueSize;
            printf("   Values[%d]: %f, %f\n", i, _lastValues_X[i], _lastValues_Y[i]);
        }
    }
    printf("Distance: %f\n", coveredDistance());
    printf("Speed: %f\n", speed());
    printf("Direction: %f\n", direction()*180/PI);
    printf("---\n");
    return 0;
}
コード例 #7
0
ファイル: decoObjects.cpp プロジェクト: AlohaWu/M.A.R.S.
    void drawArrow(Vector2f const& from,  Vector2f const& to, Color3f const& color, float width) {

        Vector2f direction((to-from).normalize()*width*0.5f);
        Vector2f normal(direction.y_, -direction.x_);

        glBlendFunc(GL_ONE, GL_ONE);
        glLineWidth(width);

        glBegin(GL_TRIANGLES);
            (color*0.5f).gl3f();
            glVertex2f(from.x_,from.y_);

            color.gl3f();
            glVertex2f(to.x_-normal.x_,to.y_-normal.y_);
            glVertex2f(to.x_+normal.x_,to.y_+normal.y_);

            glVertex2f(to.x_+direction.x_*3.f,to.y_+direction.y_*3.f);
            glVertex2f(to.x_+normal.x_*2.f,to.y_+normal.y_*2.f);
            glVertex2f(to.x_-normal.x_*2.f,to.y_-normal.y_*2.f);
        glEnd();
    }
コード例 #8
0
ファイル: rgbmatrix.cpp プロジェクト: Babbsdrebbler/qlcplus
void RGBMatrix::preRun(MasterTimer* timer)
{
    Q_UNUSED(timer);

    FixtureGroup* grp = doc()->fixtureGroup(fixtureGroup());
    {
        QMutexLocker algorithmLocker(&m_algorithmMutex);
        if (grp != NULL && m_algorithm != NULL)
        {
            m_direction = direction();

            Q_ASSERT(m_fader == NULL);
            m_fader = new GenericFader(doc());
            m_fader->adjustIntensity(getAttributeValue(Intensity));

            if (m_direction == Forward)
            {
                m_step = 0;
                m_stepColor = m_startColor.rgb();
            }
            else
            {
                m_step = m_algorithm->rgbMapStepCount(grp->size()) - 1;
                if (m_endColor.isValid())
                {
                    m_stepColor = m_endColor.rgb();
                }
                else
                {
                    m_stepColor = m_startColor.rgb();
                }
            }
            calculateColorDelta();
        }
    }

    m_roundTime->start();

    Function::preRun(timer);
}
コード例 #9
0
ファイル: baselinedetect.cpp プロジェクト: ArnoldWu/tess-two
// Refits the baseline to a constrained angle, using the stored block
// skew if good enough, otherwise the supplied default skew.
void BaselineBlock::ParallelizeBaselines(double default_block_skew) {
  if (non_text_block_) return;
  if (!good_skew_angle_) skew_angle_ = default_block_skew;
  if (debug_level_ > 0)
    tprintf("Adjusting block to skew angle %g\n", skew_angle_);
  FCOORD direction(cos(skew_angle_), sin(skew_angle_));
  for (int r = 0; r < rows_.size(); ++r) {
    BaselineRow* row = rows_[r];
    row->AdjustBaselineToParallel(debug_level_, direction);
    if (debug_level_ > 1)
      row->Print();
  }
  if (rows_.size() < 3 || !ComputeLineSpacing())
    return;
  // Enforce the line spacing model on all lines that don't yet have a good
  // baseline.
  // Start by finding the row that is best fitted to the model.
  int best_row = 0;
  double best_error = SpacingModelError(rows_[0]->PerpDisp(direction),
                                        line_spacing_, line_offset_);
  for (int r = 1; r < rows_.size(); ++r) {
    double error = SpacingModelError(rows_[r]->PerpDisp(direction),
                                     line_spacing_, line_offset_);
    if (error < best_error) {
      best_error = error;
      best_row = r;
    }
  }
  // Starting at the best fitting row, work outwards, syncing the offset.
  double offset = line_offset_;
  for (int r = best_row + 1; r < rows_.size(); ++r) {
    offset = rows_[r]->AdjustBaselineToGrid(debug_level_, direction,
                                            line_spacing_, offset);
  }
  offset = line_offset_;
  for (int r = best_row - 1; r >= 0; --r) {
    offset = rows_[r]->AdjustBaselineToGrid(debug_level_, direction,
                                            line_spacing_, offset);
  }
}
コード例 #10
0
void LevelFactory::LoadDirectionalLights(XMLReader& aReader, tinyxml2::XMLElement* aLevelElement)
{
	for (tinyxml2::XMLElement* entityElement = aReader.FindFirstChild(aLevelElement, "directionallight"); entityElement != nullptr;
		entityElement = aReader.FindNextElement(entityElement, "directionallight"))
	{
		tinyxml2::XMLElement* directionalElement = aReader.ForceFindFirstChild(entityElement, "rotation");

		Prism::DirectionalLight* newDirLight = new Prism::DirectionalLight();

		

		CU::Vector3<float> lightDirection;
		aReader.ForceReadAttribute(directionalElement, "X", lightDirection.x);
		aReader.ForceReadAttribute(directionalElement, "Y", lightDirection.y);
		aReader.ForceReadAttribute(directionalElement, "Z", lightDirection.z);

		CU::Matrix44<float> orientation;
		
		CU::GetOrientation(orientation, lightDirection);
		CU::Vector3<float> direction(0.f, 0.f, 1.f);

		direction = direction * orientation;

		newDirLight->SetDir(direction);

		//newDirLight->SetOrientation(orientation);
		//newDirLight->SetDir(lightDirection);

		directionalElement = aReader.ForceFindFirstChild(entityElement, "color");

		CU::Vector4<float> lightColor;
		aReader.ForceReadAttribute(directionalElement, "R", lightColor.myR);
		aReader.ForceReadAttribute(directionalElement, "G", lightColor.myG);
		aReader.ForceReadAttribute(directionalElement, "B", lightColor.myB);
		aReader.ForceReadAttribute(directionalElement, "A", lightColor.myA);
		newDirLight->SetColor(lightColor);

		myDirectionalLights.Add(newDirLight);
	}
}
コード例 #11
0
ファイル: rgbmatrix.cpp プロジェクト: janosvitok/qlcplus
void RGBMatrix::preRun(MasterTimer* timer)
{
    {
        QMutexLocker algorithmLocker(&m_algorithmMutex);

        m_group = doc()->fixtureGroup(m_fixtureGroupID);
        if (m_group == NULL)
        {
            // No fixture group to control
            stop(FunctionParent::master());
            return;
        }

        if (m_algorithm != NULL)
        {
            Q_ASSERT(m_fader == NULL);
            m_fader = new GenericFader(doc());
            m_fader->adjustIntensity(getAttributeValue(Intensity));
            m_fader->setBlendMode(blendMode());

            // Copy direction from parent class direction
            m_stepHandler->initializeDirection(direction(), m_startColor, m_endColor, m_stepsCount);

            if (m_algorithm->type() == RGBAlgorithm::Script)
            {
                RGBScript *script = static_cast<RGBScript*> (m_algorithm);
                QHashIterator<QString, QString> it(m_properties);
                while(it.hasNext())
                {
                    it.next();
                    script->setProperty(it.key(), it.value());
                }
            }
        }
    }

    m_roundTime->restart();

    Function::preRun(timer);
}
コード例 #12
0
void stokesFifthProperties::set( Ostream& os)
{
    scalar k = waveNumber();

    // Write the beginning of the sub-dictionary
    writeBeginning( os );

    // Write the already given parameters
    writeGiven( os, "waveType" );

    writeGiven( os, "height");
    writeGiven( os, "period" );

    writeGiven( os, "depth" );
    writeGiven( os, "stokesDrift");
    writeGiven( os, "direction" );

    if (dict_.found( "Tsoft" ))
    {
        writeGiven( os, "Tsoft");
    }

    writeGiven( os, "phi");

    if (write_)
    {
        vector direction( vector(dict_.lookup("direction")));
        direction /= Foam::mag(direction);
        direction *= k;

        writeDerived(os, "waveNumber", direction);
        writeDerived(os, "omega", omega_);
    }

    // Write the relaxation zone
    writeRelaxationZone( os );

    // Write the closing bracket
    writeEnding( os );
}
コード例 #13
0
void CylinderMy::draw_with_name(unsigned int i) const {
    glPushName(i);
    {
        GLUquadricObj* qobj = gluNewQuadric();
        glPushMatrix();
        glTranslatef(base_center_.x(), base_center_.y(), base_center_.z());

        double angle = 0.0;
        double x = 1.0;
        double y = 0.0;
        double z = 0.0;

        //--- Compute orientation of normal
        // TODO: Comparing doubles with == or != is not safe
        Vector3d dir = direction();
        if((dir.x() == 0.0f) && (dir.y() == 0.0f)) {
            if(dir.z() > 0)
                angle = 0.0f;
            else
                angle = 180.0f;
        }
        else {
            Vector3d k(0.0f, 0.0f, 1.0f);

            Vector3d tmp = CGAL::cross_product(dir, k);
            angle = std::acos(dir * k);
            angle = -180.0f * angle / M_PI;
            x = tmp[0];
            y = tmp[1];
            z = tmp[2];
        }

        glRotatef(angle, x, y, z);
        gluCylinder(qobj, radius_, radius_, height(), 30, 1);
        glPopMatrix();

        gluDeleteQuadric(qobj);
    }
    glPopName();
}
コード例 #14
0
ファイル: world.cpp プロジェクト: DeadFuze/swarm-sdk
CBaseEntity *CDecal::GetDecalEntityAndPosition( Vector *pPosition, bool bStatic )
{
	CBaseEntity *pEntity = NULL;
	if ( !m_entityName )
	{
		trace_t trace;
		Vector start = GetAbsOrigin();
		Vector direction(1,1,1);
		if ( GetAbsAngles() == vec3_angle )
		{
			start -= direction * 5;
		}
		else
		{
			GetVectors( &direction, NULL, NULL );
		}
		Vector end = start + direction * 10;
		if ( bStatic )
		{
			CTraceFilterValidForDecal traceFilter( this, COLLISION_GROUP_NONE );
			UTIL_TraceLine( start, end, MASK_SOLID, &traceFilter, &trace );
		}
		else
		{
			UTIL_TraceLine( start, end, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trace );
		}
		if ( trace.DidHitNonWorldEntity() )
		{
			*pPosition = trace.endpos;
			return trace.m_pEnt;
		}
	}
	else
	{
		pEntity = gEntList.FindEntityByName( NULL, m_entityName );
	}

	*pPosition = GetAbsOrigin();
	return pEntity;
}
コード例 #15
0
TextRun SVGInlineTextBox::constructTextRun(RenderStyle* style, const SVGTextFragment& fragment) const
{
    ASSERT(style);
    ASSERT(textRenderer());

    RenderText* text = textRenderer();
    ASSERT(text);

    // FIXME(crbug.com/264211): This should not be necessary but can occur if we
    //                          layout during layout. Remove this when 264211 is fixed.
    RELEASE_ASSERT(!text->needsLayout());

    TextRun run(static_cast<const LChar*>(0) // characters, will be set below if non-zero.
                , 0 // length, will be set below if non-zero.
                , 0 // xPos, only relevant with allowTabs=true
                , 0 // padding, only relevant for justified text, not relevant for SVG
                , TextRun::AllowTrailingExpansion
                , direction()
                , dirOverride() || style->rtlOrdering() == VisualOrder /* directionalOverride */);

    if (fragment.length) {
        if (text->is8Bit())
            run.setText(text->characters8() + fragment.characterOffset, fragment.length);
        else
            run.setText(text->characters16() + fragment.characterOffset, fragment.length);
    }

    if (textRunNeedsRenderingContext(style->font()))
        run.setRenderingContext(SVGTextRunRenderingContext::create(text));

    run.disableRoundingHacks();

    // We handle letter & word spacing ourselves.
    run.disableSpacing();

    // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
    run.setCharactersLength(text->textLength() - fragment.characterOffset);
    ASSERT(run.charactersLength() >= run.length());
    return run;
}
コード例 #16
0
ファイル: channel.cpp プロジェクト: rayslava/chatsync
TEST(FileChannel, files)
{
  unlink("output");
  const auto hub = new Hub::Hub ("Hub");

  const auto ich = channeling::ChannelFactory::create("file", hub, "data://direction=input\nname=infile");
  const int buffer_size = sizeof(testLine) + ich->name().length() + 2 + 5;   // file: and ": " sizes
  const std::string valid_line = "file:" + ich->name() + ": " + testLine;
  const auto buffer = new char[buffer_size];

  channeling::ChannelFactory::create("file", hub, "data://direction=output\nname=outfile");

  // Check that at least constructor works
  ASSERT_EQ(ich->name(),      "infile");
  ASSERT_EQ(ich->direction(), channeling::ChannelDirection::Input);

  // Open input pipe from file channel
  hub->activate();
  int fd = open("input", O_WRONLY | O_SYNC, 0666);
  ASSERT_NE(fd, -1);

  int err = write(fd, testLine, sizeof(testLine));
  ASSERT_EQ(err, sizeof(testLine));
  std::this_thread::sleep_for( std::chrono::milliseconds (50) );
  hub->deactivate();
  std::this_thread::sleep_for( std::chrono::milliseconds (50) );
  delete hub;

  close(fd);    // @todo move after adding file close support in poll thread

  fd = open("output", O_RDONLY | O_SYNC);
  ASSERT_NE(fd, -1);
  bzero(buffer, buffer_size);
  err = read(fd, buffer, buffer_size - 1);
  ASSERT_EQ(err, buffer_size - 1);
  close(fd);
  ASSERT_STREQ(buffer, valid_line.c_str());
  delete[] buffer;
}
コード例 #17
0
/*
			Ramps up the voltage on a dc motor.
 */
void DCMotor::speed (double _speed)
	{

	 clock_t start_time,stop_time;

	 //  ramps up the motor to a  certain speed...
		direction ();
		start_time = clock ();
		double voltsinc;
		//accelerate or deccelerate?
		if (_speed > cur_speed) voltsinc = DCACCEL_DCRES;
		else voltsinc = -DCACCEL_DCRES;
		// start at the current speed.
		double volts = cur_speed;
		AD_board->generate_volts (dac,volts);

//		cerr <<"SLEW SPEED TO "<<_speed<<"  from:"<<cur_speed<<endl;

 //char buf[256];
 //sprintf (buf,"speed:%lf",volts);
 //debug.post (buf);
//(_speed > cur_speed?(volts < _speed):(volts > _speed))
		while (  matchspeed (_speed,volts,cur_speed) &&
						 volts <= max_speed) {
			stop_time = clock ();
			if ((stop_time-start_time) > DCRES_INV*CLK_TCK) {
			 volts += voltsinc;
			 AD_board->generate_volts (dac,volts);
//debug3 = volts;
			 start_time = clock ();
			}
		}

		AD_board->generate_volts (dac,_speed);
		cur_speed = _speed;
//debug3 = cur_speed;
		if (cur_speed == 0.0) stop_dome (); // the dome requires that the fwd & rev
												 // ttl lines be set to 0v.
	}
コード例 #18
0
ファイル: TaskCubeMap.cpp プロジェクト: devgoeson/sandbox
void TaskCubeMap::update( void )
{
	glClearColor( 0.2f, 0.2f, 0.2f, 1.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	const horizon::input::PadState& pad = horizon::input::getPadState( 0 );

	if( pad.stick.right.y != 0.0f ) {
		mCamera.rotation().x -= DEG_TO_RAD( pad.stick.right.y );
	}
	if( pad.stick.right.x != 0.0f ) {
		mCamera.rotation().y -= DEG_TO_RAD( pad.stick.right.x );
	}

	glm::vec4 direction( -pad.stick.left.x, 0.0f, - pad.stick.left.y, 0.0f );
	glm::mat4 identityMtx( 1.0f );
	direction = glm::rotate( identityMtx, mCamera.rotation().x, GLM_X_AXIS ) * direction;
	direction = glm::rotate( identityMtx, mCamera.rotation().y, GLM_Y_AXIS ) * direction;
	mCamera.position().x += direction.x;
	mCamera.position().y += direction.y;
	mCamera.position().z += direction.z;

	mCamera.apply();

	mCubeMap.useProgram();
	mCubeMap.bindTexture( 0, mTextureCubeChapel );

	mCubeMap.getProgram().setUniform( "SkyBox", 1 );
	mSkyBox.draw();


	glClear( GL_DEPTH_BUFFER_BIT );

	mCubeMap.getProgram().setUniform( "SkyBox", 0 );
	mSphere.draw();

	mShader_PresentNormal.useProgram();
	mSphere.draw();
}
コード例 #19
0
DateTimeNumericFieldElement::DateTimeNumericFieldElement(Document* document, FieldOwner& fieldOwner, int minimum, int maximum, const String& placeholder, const DateTimeNumericFieldElement::Parameters& parameters)
    : DateTimeFieldElement(document, fieldOwner)
    , m_lastDigitCharTime(0)
    , m_placeholder(placeholder)
    , m_range(minimum, maximum)
    , m_value(0)
    , m_hasValue(false)
    , m_step(parameters.step)
    , m_stepBase(parameters.stepBase)
{
    ASSERT(m_step);

    // We show a direction-neutral string such as "--" as a placeholder. It
    // should follow the direction of numeric values.
    if (localeForOwner().isRTL()) {
        Direction dir = direction(formatValue(this->maximum())[0]);
        if (dir == LeftToRight || dir == EuropeanNumber || dir == ArabicNumber) {
            setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueBidiOverride);
            setInlineStyleProperty(CSSPropertyDirection, CSSValueLtr);
        }
    }
}
コード例 #20
0
ファイル: CylinderShape.cpp プロジェクト: Mertank/ToneArm
/*
==========
CylinderShape::BuildPoints

	Generates the points for the cylinder.
==========
*/
void CylinderShape::BuildPoints( void ) {
	float angleIncrements = 360.0f / m_subdivisions;
	float currentAngle = 0.0f;
	glm::vec3 direction( 0.0f );
	const glm::mat4& modelMat = m_transform.GetModelMatrix();
	
	for ( unsigned int i = 0; i < m_subdivisions; ++i ) {
		direction.x = cos( glm::radians( currentAngle ) );
		direction.z = sin( glm::radians( currentAngle ) );

		direction	= glm::normalize( direction );
		direction   = direction * m_radius;

		m_points[i] = glm::vec4( direction.x, m_height * 0.5f, direction.z, 1.0f );
		m_points[i + m_subdivisions] = glm::vec4( direction.x, -m_height * 0.5f, direction.z, 1.0f );

		m_points[i] = modelMat * m_points[i];
		m_points[i + m_subdivisions] = modelMat * m_points[i + m_subdivisions];

		currentAngle += angleIncrements;
	}
}
コード例 #21
0
void CreateSphereGeometry(size_t sliceCount, float radius, SphereGeometry *result)
{
    size_t parellelCount = sliceCount / 2;
    size_t vertexCount = (parellelCount + 1) * (sliceCount + 1);
    size_t indexCount = parellelCount * sliceCount * 6;
    float angleStep = static_cast<float>(2.0f * M_PI) / sliceCount;

    result->positions.resize(vertexCount);
    result->normals.resize(vertexCount);
    for (size_t i = 0; i < parellelCount + 1; i++)
    {
        for (size_t j = 0; j < sliceCount + 1; j++)
        {
            Vector3 direction(sinf(angleStep * i) * sinf(angleStep * j),
                              cosf(angleStep * i),
                              sinf(angleStep * i) * cosf(angleStep * j));

            size_t vertexIdx = i * (sliceCount + 1) + j;
            result->positions[vertexIdx] = direction * radius;
            result->normals[vertexIdx] = direction;
        }
    }

    result->indices.clear();
    result->indices.reserve(indexCount);
    for (size_t i = 0; i < parellelCount; i++)
    {
        for (size_t j = 0; j < sliceCount; j++)
        {
            result->indices.push_back(static_cast<unsigned short>( i      * (sliceCount + 1) +  j     ));
            result->indices.push_back(static_cast<unsigned short>((i + 1) * (sliceCount + 1) +  j     ));
            result->indices.push_back(static_cast<unsigned short>((i + 1) * (sliceCount + 1) + (j + 1)));

            result->indices.push_back(static_cast<unsigned short>( i      * (sliceCount + 1) +  j     ));
            result->indices.push_back(static_cast<unsigned short>((i + 1) * (sliceCount + 1) + (j + 1)));
            result->indices.push_back(static_cast<unsigned short>( i      * (sliceCount + 1) + (j + 1)));
        }
    }
}
コード例 #22
0
ファイル: Map.cpp プロジェクト: ignorer/hot-pursuit-game
	void CMap::DrawFinishLine( std::pair<CCoordinates, CCoordinates> finishLine ) const
	{
		glEnable( GL_TEXTURE_2D );
		glBindTexture( GL_TEXTURE_2D, CDrawing::finish );
		glColor3f( 1, 1, 1 );
		glBegin( GL_POLYGON );
		{
			auto point1 = transateToWcoord( finishLine.first.x + 0.5, finishLine.first.y + 0.5, cellSize, indent, GetSize() );
			auto point2 = transateToWcoord( finishLine.second.x + 0.5, finishLine.second.y + 0.5, cellSize, indent, GetSize() );
			double distance = std::hypot( finishLine.first.x - finishLine.second.x, finishLine.first.y - finishLine.second.y );
			double distanceWindow = std::hypot( point1.x - point2.x, point1.y - point2.y );
			std::pair<double, double> direction( (point2.x - point1.x) /  distanceWindow, (point2.y - point1.y) / distanceWindow );
			direction = std::make_pair( direction.second, -direction.first );
			glTexCoord2f( 0.0f, 0.0f ); glVertex2f( point1.x - 5 * direction.first, point1.y - 5 * direction.second );
			glTexCoord2f( distance, 0.0f ); glVertex2f( point2.x - 5 * direction.first, point2.y - 5 * direction.second );
			glTexCoord2f( distance, 1.0f ); glVertex2f( point2.x + 5 * direction.first, point2.y + 5 * direction.second );
			glTexCoord2f( 0.0f, 1.0f ); glVertex2f( point1.x + 5 * direction.first, point1.y + 5 * direction.second );
		}
		glEnd();
		glDisable( GL_BLEND );
		glDisable( GL_TEXTURE_2D );
	}
コード例 #23
0
void AMyBallClass::homingBallfunc()
{
	AAdder_DodgeBallCharacter* currentTarget;
	FVector currentLocation = FVector(this->GetActorLocation().X, this->GetActorLocation().Y, this->GetActorLocation().Z);
	FVector direction(0, 0, 0);
	float distance = 5000;
	for (TActorIterator <AAdder_DodgeBallCharacter> itr(GetWorld()); itr; ++itr)
	{
		if ((itr->GetActorLocation() - this->GetActorLocation()).Size() < distance)
		{
			if (teamNumber != itr->teamNumber)
			{
				currentTarget = *itr;
				direction = (currentTarget->GetActorLocation() - this->GetActorLocation()).GetSafeNormal();
			}
		}
	}
	
	this->SetActorLocation(currentLocation + (direction * 20), false, NULL, ETeleportType::TeleportPhysics);
	if (homingDuration > 1000)
		ResetStats();
}
コード例 #24
0
ファイル: Vector3.cpp プロジェクト: 281627166/NoahGameFrame
Vector3 Vector3::refractionDirection(
    const Vector3&  normal,
    float           iInside,
    float           iOutside) const
{

    // From pg. 24 of Henrik Wann Jensen. Realistic Image Synthesis
    // Using Photon Mapping.  AK Peters. ISBN: 1568811470. July 2001.

    // Invert the directions from Wann Jensen's formulation
    // and normalize the vectors.
    const Vector3 W = -direction();
    Vector3 N = normal.direction();

    float h1 = iOutside;
    float h2 = iInside;

    if (normal.dot(*this) > 0.0f)
    {
        h1 = iInside;
        h2 = iOutside;
        N  = -N;
    }

    const float hRatio = h1 / h2;
    const float WdotN = W.dot(N);

    float det = 1.0f - (float)square(hRatio) * (1.0f - (float)square(WdotN));

    if (det < 0)
    {
        // Total internal reflection
        return Vector3::zero();
    }
    else
    {
        return -hRatio * (W - WdotN * N) - N * sqrt(det);
    }
}
コード例 #25
0
TextRun InlineTextBox::constructTextRun(const ComputedStyle& style, const Font& font, StringView string, int maximumLength, StringBuilder* charactersWithHyphen) const
{
    if (charactersWithHyphen) {
        const AtomicString& hyphenString = style.hyphenString();
        charactersWithHyphen->reserveCapacity(string.length() + hyphenString.length());
        charactersWithHyphen->append(string);
        charactersWithHyphen->append(hyphenString);
        string = charactersWithHyphen->toString().createView();
        maximumLength = string.length();
    }

    ASSERT(maximumLength >= static_cast<int>(string.length()));

    TextRun run(string, textPos().toFloat(), expansion(), expansionBehavior(), direction(), dirOverride() || style.rtlOrdering() == VisualOrder);
    run.setTabSize(!style.collapseWhiteSpace(), style.tabSize());
    run.setTextJustify(style.textJustify());

    // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
    run.setCharactersLength(maximumLength);
    ASSERT(run.charactersLength() >= run.length());
    return run;
}
コード例 #26
0
ファイル: monster_ai.cpp プロジェクト: MitchellMarx/keeperrl
 virtual MoveInfo getMove() {
   if (!visited(creature->getPosition()))
     updateMem(creature->getPosition());
   Vec2 direction(0, 0);
   double val = 0.0001;
   Vec2 pos = creature->getPosition();
   for (Vec2 dir : Vec2::directions8(true))
     if (!visited(pos + dir) && creature->canMove(dir)) {
       direction = dir;
       break;
     }
   if (direction == Vec2(0, 0))
     for (Vec2 dir : Vec2::directions8(true))
       if (creature->canMove(dir)) {
         direction = dir;
         break;
       }
   if (direction == Vec2(0, 0))
     return {val, [this]() { creature->wait(); }};
   else
     return {val, [this, direction]() { creature->move(direction); updateMem(creature->getPosition());}};
 }
コード例 #27
0
ファイル: AnimatedObject.cpp プロジェクト: soullem/Dawn
void AnimatedObject::update(double seconds)
{
	// info updates	
	if(_idleSinceUpdate)
		setAction(Action::ACT_IDLE);

	Ogre::Vector3 pos = position();
	Ogre::Vector3 dir = direction();
	Ogre::Real speed, rotSpeed=1.57;

	switch(_actionType)
	{
	case Action::ACT_WALK:
		speed = 10;
		break;
	case Action::ACT_RUN:
		speed = 20;
		break;
	}

	if(_actionModif & Action::MDF_LEFT)
		rotate((Ogre::Radian)0,(Ogre::Radian)(rotSpeed*seconds),(Ogre::Radian)0);
	if(_actionModif & Action::MDF_RIGHT)
		rotate((Ogre::Radian)0,(Ogre::Radian)(-rotSpeed*seconds),(Ogre::Radian)0);
	if(_actionModif & Action::MDF_FRONT)
		setPosition(position()+dir*speed*seconds);
	if(_actionModif & Action::MDF_BACK)
		setPosition(position()-dir*speed*seconds);

	// mesh/node updates
	if(_reverseAnim) seconds = -seconds;
	if(_anim[_actionType]) 
		_anim[_actionType]->addTime(seconds);

	_idleSinceUpdate=true;
	_actionModif = Action::MDF_NONE;
	_reverseAnim=false;
}
コード例 #28
0
void Camera::generate_rays(unsigned width, unsigned height, 
							std::vector<Ray> & rays)
{
	float distance = ((width/2) / tan(fov_x_ * M_PI / 360)); 

	for (int y = ((int)height/-2); y < (int)height/2; ++y)
	{
		for (int x = ((int)width/-2); x < (int)width/2; ++x)
		{
			glm::vec3 direction(x, y, -(distance));
			
			//Scale Camera if not default
			if (eye_.x != 0 || eye_.y != 0 || eye_.z != 0 ||
				dir_.x != 0 || dir_.y != 0 || dir_.z != -1 ||
				up_.x != 0 || up_.y != 1 || up_.z != 0 )
			{
				glm::vec4 direct_temp(x, y, -(distance), 1);
				glm::vec3 u = glm::normalize(glm::cross(dir_, up_));
				glm::vec3 v = glm::normalize(glm::cross(u, dir_));
				dir_ = glm::normalize(dir_);
				// Matrix is implemented column x row
				glm::mat4 matrix(u.x, u.y, u.z, 0,
								 v.x, v.y, v.z, 0,
								 (dir_.x*-1), (dir_.y*-1), (dir_.z*-1),0,
								 eye_.x, eye_.y, eye_.z, 1);
				// Matrix x Vector
				glm::vec4 new_direct = matrix * direct_temp;

				direction.x = new_direct.x;
				direction.y = new_direct.y;
				direction.z = new_direct.z;
			}

			Ray temp_ray(eye_, direction);
			rays.push_back(temp_ray);
		}
	}
}
コード例 #29
0
ファイル: CLaser.cpp プロジェクト: UCLanGroup/GameProject
void CLaser::Fire()
{
	//Get matrix for current player location and forward vector
	tlx::CMatrix4x4 matrix;
	GetParent()->GetMatrix(matrix.m);

	//Create forward vector (z axis)
	CVector3 direction(matrix.m[8], matrix.m[9], matrix.m[10]);

	//Get position from matrix
	//Since we've already got the matrix it's slightly more efficient than calling GetParent()->GetCenterPoint()
	CVector3 pos(matrix.m[12], OFF_SCREEN_Y, matrix.m[14]);

	//Calculate the rotation of the parent entity, just so it only needs to be calculated once
	float rotation = GetParent()->GetRotation();

	//Makes the space between invisible bullets 2.0f instead of 1.0f
	direction *= 2.0f;

	for (int i = 0; i < 70; i++)
	{
		CProjectile* bullet = new CProjectile();

		bullet->SetPosition(pos);
		bullet->SetRotation(rotation);

		bullet->SetDamage(GetDamage());
		bullet->SetSpeed(GetProjSpeed());
		bullet->SetParent(GetParent());
		bullet->SetExplodeable(false);

		GetBulletList()->push_back(unique_ptr<CProjectile>(bullet));

		//Increment position of next bullet
		pos += direction;
	}

}
コード例 #30
0
ファイル: cgal_utility.cpp プロジェクト: yangyanli/FPNN
double computeSegment(const std::vector<CgalPoint>& points, const CgalPoint& centroid, CgalSegment& segment) {
  CgalLine line;

  // assemble covariance matrix
  double covariance[6];
  covariance[0] = covariance[1] = covariance[2] = covariance[3] = covariance[4] = covariance[5] = 0.0;
  for (std::vector<CgalPoint>::const_iterator it = points.begin(); it != points.end(); it++) {
    CgalVector d = *it - centroid;
    covariance[0] += d.x() * d.x();
    covariance[1] += d.x() * d.y();
    covariance[2] += d.y() * d.y();
    covariance[3] += d.x() * d.z();
    covariance[4] += d.y() * d.z();
    covariance[5] += d.z() * d.z();
  }

  // compute fitting line
  double eigen_values[3];
  double eigen_vectors[9];
  double fitting_score = 0.0;

  CGAL::internal::eigen_symmetric<double>(covariance, 3, eigen_vectors, eigen_values);

  if (eigen_values[0] == eigen_values[1] && eigen_values[0] == eigen_values[2]) {
    // assemble a default line along x axis which goes
    // through the centroid.
    line = CgalLine(centroid, CgalVector(1.0, 0.0, 0.0));
  } else {
    // regular case
    CgalVector direction(eigen_vectors[0], eigen_vectors[1], eigen_vectors[2]);
    line = CgalLine(centroid, direction);
    fitting_score = 1.0 - eigen_values[1] / eigen_values[0];
  }

  computeSegment(points, line, segment);

  return fitting_score;
}