Пример #1
0
void
Airport::generate_flight()
{


	std::cerr<<"Generate new flight";
	float angle, x, y, z;
	float bear, inc;
	char id[6];

	angle = toRadians((float)(rand() % 360 - 180));

	x = fabs(AIRPORT_DISTANCE_MAX * cos(angle)); //Only positive, for GyV3D!!!!!!!!!!!
	y = AIRPORT_DISTANCE_MAX * sin(angle);
	z = FLIGHT_HEIGHT + (float)(rand() % 2000);

	Position ipos(x, y, z);
	Position pos0(0.0, 0.0, 0.0);

	pos0.angles(ipos, bear, inc);

	sprintf(id, "IB%4.4d", sec++);
	std::cerr<<": ["<<id;
	Flight *aux;
	aux = new Flight(id, ipos, bear, 0.0, 200.0);
	flights.push_back(aux);

	if(flights.size() == 1)
		NextFocus();
	std::cerr<<"]"<<std::endl;
}
Пример #2
0
void
AirController::doWork()
{
			std::list<Flight*> flights = Airport::getInstance()->getFlights();
			std::list<Flight*>::iterator it;

			Position pos0(3500.0, 0.0, 100.0);
			Position pos1(1500.0, 0.0, 50.0);
			Position pos2(200.0, 0.0, 25.0);
			Position pos3(-750.0, 0.0, 25.0);

			Route r0, r1, r2, r3;

			r0.pos = pos0;
			r0.speed = 500.0;
			r1.pos = pos1;
			r1.speed = 100.0;
			r2.pos = pos2;
			r2.speed = 19.0;
			r3.pos = pos3;
			r3.speed = 15.0;

			for(it = flights.begin(); it!=flights.end(); ++it)
			{
				if((*it)->getRoute()->empty())
				{
					(*it)->getRoute()->push_back(r3);
					(*it)->getRoute()->push_front(r2);
					(*it)->getRoute()->push_front(r1);
					(*it)->getRoute()->push_front(r0);
				}
			}

}
Пример #3
0
Foam::tmp<Foam::volScalarField> Foam::dragModels::SyamlalOBrien::CdRe() const
{
    volScalarField alpha2
    (
        max(scalar(1) - pair_.dispersed(), pair_.continuous().residualAlpha())
    );

    volScalarField A(pow(alpha2, 4.14));
    volScalarField B
    (
        neg(alpha2 - 0.85)*(0.8*pow(alpha2, 1.28))
      + pos0(alpha2 - 0.85)*(pow(alpha2, 2.65))
    );
    volScalarField Re(pair_.Re());
    volScalarField Vr
    (
        0.5
       *(
            A - 0.06*Re + sqrt(sqr(0.06*Re) + 0.12*Re*(2.0*B - A) + sqr(A))
        )
    );
    volScalarField CdsRe(sqr(0.63*sqrt(Re) + 4.8*sqrt(Vr)));

    return
        CdsRe
       *max(pair_.continuous(), pair_.continuous().residualAlpha())
       /sqr(Vr);
}
Пример #4
0
	void DrawVertexList(const VertexBuffer& vertexBuffer)
	{
		std::vector<VertexList*>::const_iterator bufferIt = vertexBuffer.lists.begin();
		std::vector<VertexList*>::const_iterator bufferItEnd = vertexBuffer.lists.end();
		for(; bufferIt != bufferItEnd; bufferIt++) {
			const VertexList& vertexList = **bufferIt;

			Graphic& graphic = Graphic::Instance();
			int indexCount = (int)vertexList.indices.size();
			for(int i = 0; ((i + 1) * 3) <= indexCount; i++) {

				int idx0 = vertexList.indices[i * 3];
				int idx1 = vertexList.indices[(i * 3) + 1];
				int idx2 = vertexList.indices[(i * 3) + 2];

				Vector2 pos0(vertexList.vertices[idx0].xyz.x, vertexList.vertices[idx0].xyz.y);
				Vector2 pos1(vertexList.vertices[idx1].xyz.x, vertexList.vertices[idx1].xyz.y);
				Vector2 pos2(vertexList.vertices[idx2].xyz.x, vertexList.vertices[idx2].xyz.y);

				graphic.DrawLine(pos0, pos1, 0xFF0000FF);
				graphic.DrawLine(pos1, pos2, 0xFF0000FF);
				graphic.DrawLine(pos2, pos0, 0xFF0000FF);
			}
		}

	}
Пример #5
0
int bulk_extractor_analyze_buf(BEFILE *bef,uint8_t *buf,size_t buflen)
{
    pos0_t pos0("");
    const sbuf_t sbuf(pos0,buf,buflen,buflen,false);
    be13::plugin::process_sbuf(scanner_params(scanner_params::PHASE_SCAN,sbuf,bef->cfs));
    return 0;
}
void turbulentMixingLengthDissipationRateInletFvPatchScalarField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    // Lookup Cmu corresponding to the turbulence model selected
    const turbulenceModel& turbModel = db().lookupObject<turbulenceModel>
    (
        IOobject::groupName
        (
            turbulenceModel::propertiesName,
            internalField().group()
        )
    );

    const scalar Cmu =
        turbModel.coeffDict().lookupOrDefault<scalar>("Cmu", 0.09);

    const scalar Cmu75 = pow(Cmu, 0.75);

    const fvPatchScalarField& kp =
        patch().lookupPatchField<volScalarField, scalar>(kName_);

    const fvsPatchScalarField& phip =
        patch().lookupPatchField<surfaceScalarField, scalar>(this->phiName_);

    this->refValue() = Cmu75*kp*sqrt(kp)/mixingLength_;
    this->valueFraction() = 1.0 - pos0(phip);

    inletOutletFvPatchScalarField::updateCoeffs();
}
void Foam::interfaceCompressionFvPatchScalarField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    operator==(pos0(this->patchInternalField() - 0.5));

    fixedValueFvPatchScalarField::updateCoeffs();
}
void Foam::inletOutletTotalTemperatureFvPatchScalarField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    const fvPatchVectorField& Up =
        patch().lookupPatchField<volVectorField, vector>(UName_);

    const fvsPatchField<scalar>& phip =
        patch().lookupPatchField<surfaceScalarField, scalar>(this->phiName_);

    const fvPatchField<scalar>& psip =
        patch().lookupPatchField<volScalarField, scalar>(psiName_);

    scalar gM1ByG = (gamma_ - 1.0)/gamma_;

    this->refValue() =
        T0_/(1.0 + 0.5*psip*gM1ByG*(1.0 - pos0(phip))*magSqr(Up));
    this->valueFraction() = 1.0 - pos0(phip);

    inletOutletFvPatchScalarField::updateCoeffs();
}
void NodeGraphNodeConnector::drawConnection( const NodeGraphDrawContext& context, const he::vec2& other )
{
    he::vec2 pos0(m_LayoutBound.x + m_LayoutBound.width / 2.0f, m_LayoutBound.y + m_LayoutBound.height / 2.0f);
    he::vec2 tan0, tan1;
    if (m_Type == eNodeGraphNodeConnectorType_Input)
        tan0 = he::vec2(-1, 0);
    else
        tan0 = he::vec2(1, 0);
    pos0 = context.transform * pos0;
    he::vec2 otherTransformd(context.transform * other);
    tan0 *= abs((pos0.x - otherTransformd.x) / 2.0f);
    tan1 = -tan0;

    context.canvas->setColor(he::Color(1.0f, 1.0f, 1.0f, 1.0f));
    context.canvas->fillCurve(pos0, tan0, tan1, otherTransformd, 2.0f);
}
Foam::tmp<Foam::volScalarField> Foam::dragModels::GidaspowSchillerNaumann::K
(
    const volScalarField& Ur
) const
{
    volScalarField alpha2(max(phase2_, scalar(1e-6)));
    volScalarField bp(pow(alpha2, -2.65));

    volScalarField Re(max(alpha2*Ur*phase1_.d()/phase2_.nu(), scalar(1.0e-3)));
    volScalarField Cds
    (
        neg(Re - 1000)*(24.0*(1.0 + 0.15*pow(Re, 0.687))/Re)
      + pos0(Re - 1000)*0.44
    );

    return 0.75*Cds*phase2_.rho()*Ur*bp/phase1_.d();
}
void Foam::inletOutletFvPatchField<Type>::updateCoeffs()
{
    if (this->updated())
    {
        return;
    }

    const Field<scalar>& phip =
        this->patch().template lookupPatchField<surfaceScalarField, scalar>
        (
            phiName_
        );

    this->valueFraction() = 1.0 - pos0(phip);

    mixedFvPatchField<Type>::updateCoeffs();
}
void Foam::pressureInletOutletParSlipVelocityFvPatchVectorField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    const surfaceScalarField& phi =
        db().lookupObject<surfaceScalarField>(phiName_);

    const fvsPatchField<scalar>& phip =
        patch().patchField<surfaceScalarField, scalar>(phi);

    tmp<vectorField> n = patch().nf();
    const Field<scalar>& magSf = patch().magSf();

    // Get the tangential component from the internalField (zero-gradient)
    vectorField Ut(patchInternalField());
    Ut -= n()*(Ut & n());

    if (phi.dimensions() == dimVelocity*dimArea)
    {
        refValue() = Ut + n*phip/magSf;
    }
    else if (phi.dimensions() == dimDensity*dimVelocity*dimArea)
    {
        const fvPatchField<scalar>& rhop =
            patch().lookupPatchField<volScalarField, scalar>(rhoName_);

        refValue() = Ut + n*phip/(rhop*magSf);
    }
    else
    {
        FatalErrorInFunction
            << "dimensions of phi are not correct" << nl
            << "    on patch " << this->patch().name()
            << " of field " << this->internalField().name()
            << " in file " << this->internalField().objectPath()
            << exit(FatalError);
    }

    valueFraction() = 1.0 - pos0(phip);

    mixedFvPatchVectorField::updateCoeffs();
}
Пример #13
0
void Triangle::build() 
{

  //Dessin 2D
  //glm::vec3 pos0(-1.0f, -1.0f, 0.0f);
  glm::vec3 pos0(-1.f, -1.f, 0.0f);
  glm::vec3 norm0(0.f, 0.f, 1.0f);
  glm::vec2 uv0(0.f, 0.f);

  //glm::vec3 pos1(1.0f, -1.0f, 0.0f);
  glm::vec3 pos1(3.f, -1.f, 0.0f);
  glm::vec3 norm1(0.f, 0.f, 1.0f);
  glm::vec2 uv1(2.f, 0.f);

	//glm::vec3 pos2(0.f, 0.5f, 0.0f);
	glm::vec3 pos2(-1.f, 3.0f, 0.0f);
  glm::vec3 norm2(0.f, 0.f, 1.0f);
  glm::vec2 uv2(0.f, 2.f);

  /*
    Pour un triangle faisant tout l'écran

    -1.0  -1.0  0.000000
    1.0  -1.0  0.000000
    0.0  0.5  0.000000
  */

  _vertices[0].position = pos0;
  _vertices[0].normal = norm0;
  _vertices[0].uv = uv0;


  _vertices[1].position = pos1;
  _vertices[1].normal = norm1;
  _vertices[1].uv = uv1;

  _vertices[2].position = pos2;
  _vertices[2].normal = norm2;
  _vertices[2].uv = uv2;

  _indices[0] = 0;
  _indices[1] = 1;
  _indices[2] = 2;

}
void Foam::turbulentIntensityKineticEnergyInletFvPatchScalarField::
updateCoeffs()
{
    if (updated())
    {
        return;
    }

    const fvPatchVectorField& Up =
        patch().lookupPatchField<volVectorField, vector>(UName_);

    const fvsPatchScalarField& phip =
        patch().lookupPatchField<surfaceScalarField, scalar>(this->phiName_);

    this->refValue() = 1.5*sqr(intensity_)*magSqr(Up);
    this->valueFraction() = 1.0 - pos0(phip);

    inletOutletFvPatchScalarField::updateCoeffs();
}
Пример #15
0
tmp<volScalarField> SpalartAllmarasIDDES<BasicTurbulenceModel>::dTilda
(
    const volScalarField& chi,
    const volScalarField& fv1,
    const volTensorField& gradU
) const
{
    const volScalarField alpha(this->alpha());
    const volScalarField expTerm(exp(sqr(alpha)));
    const volScalarField magGradU(mag(gradU));

    tmp<volScalarField> fHill =
        2*(pos0(alpha)*pow(expTerm, -11.09) + neg(alpha)*pow(expTerm, -9.0));

    tmp<volScalarField> fStep = min(2*pow(expTerm, -9.0), scalar(1));
    const volScalarField fHyb(max(1 - fd(magGradU), fStep));
    tmp<volScalarField> fAmp = 1 - max(ft(magGradU), fl(magGradU));
    tmp<volScalarField> fRestore = max(fHill - 1, scalar(0))*fAmp;

    // IGNORING ft2 terms
    const volScalarField Psi
    (
        sqrt
        (
            min
            (
                scalar(100),
                (
                    1
                  - this->Cb1_*this->fv2(chi, fv1)
                   /(this->Cw1_*sqr(this->kappa_)*fwStar_)
                 )/max(small, fv1)
            )
        )
    );

    return max
    (
        dimensionedScalar(dimLength, small),
        fHyb*(1 + fRestore*Psi)*this->y_
      + (1 - fHyb)*this->CDES_*Psi*this->delta()
    );
}
Пример #16
0
static void process_open_path(const image_process &p,std::string path,scanner_params::PrintOptions &po,
                              const size_t process_path_bufsize)
{
    /* Check for "/r" in path which means print raw */
    if(path.size()>2 && path.substr(path.size()-2,2)=="/r"){
	path = path.substr(0,path.size()-2);
    }

    std::string  prefix = get_and_remove_token(path);
    int64_t offset = stoi64(prefix);

    /* Get the offset into the buffer process */
    u_char *buf = (u_char *)calloc(process_path_bufsize,1);
    if(!buf){
        std::cerr << "Cannot allocate " << process_path_bufsize << " buffer\n";
        return;
    }
    int count = p.pread(buf,process_path_bufsize,offset);
    if(count<0){
        std::cerr << p.image_fname() << ": " << strerror(errno) << " (Read Error)\n";
	return;
    }

    /* make up a bogus feature recorder set and with a disabled feature recorder.
     * Then we call the path printer, which throws an exception after the printing
     * to prevent further printing.
     *
     * The printer is called when a PRINT token is found in the
     * forensic path, so that has to be added.
     */
    feature_recorder_set fs(feature_recorder_set::SET_DISABLED,feature_recorder_set::null_hasher,
                            feature_recorder_set::NO_INPUT,feature_recorder_set::NO_OUTDIR);

    pos0_t pos0(path+"-PRINT"); // insert the PRINT token
    sbuf_t sbuf(pos0,buf,count,count,true); // sbuf system will free
    scanner_params sp(scanner_params::PHASE_SCAN,sbuf,fs,po);
    try {
        process_path_printer(sp);
    }
    catch (path_printer_finished &e) {
    }
}
void Foam::pressureNormalInletOutletVelocityFvPatchVectorField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    const surfaceScalarField& phi =
        db().lookupObject<surfaceScalarField>(phiName_);

    const fvsPatchField<scalar>& phip =
        patch().patchField<surfaceScalarField, scalar>(phi);

    tmp<vectorField> n = patch().nf();
    const Field<scalar>& magS = patch().magSf();

    if (phi.dimensions() == dimVelocity*dimArea)
    {
        refValue() = n*phip/magS;
    }
    else if (phi.dimensions() == dimDensity*dimVelocity*dimArea)
    {
        const fvPatchField<scalar>& rhop =
            patch().lookupPatchField<volScalarField, scalar>(rhoName_);

        refValue() = n*phip/(rhop*magS);
    }
    else
    {
        FatalErrorInFunction
            << "dimensions of phi are not correct"
            << "\n    on patch " << this->patch().name()
            << " of field " << this->internalField().name()
            << " in file " << this->internalField().objectPath()
            << exit(FatalError);
    }

    valueFraction() = 1.0 - pos0(phip);

    mixedFvPatchVectorField::updateCoeffs();
}
Пример #18
0
constantRadiation::constantRadiation
(
    surfaceFilmRegionModel& film,
    const dictionary& dict
)
:
    filmRadiationModel(typeName, film, dict),
    qrConst_
    (
        IOobject
        (
            typeName + ":qrConst",
            film.time().timeName(),
            film.regionMesh(),
            IOobject::MUST_READ,
            IOobject::AUTO_WRITE
        ),
        film.regionMesh()
    ),
    mask_
    (
        IOobject
        (
            typeName + ":mask",
            film.time().timeName(),
            film.regionMesh(),
            IOobject::READ_IF_PRESENT,
            IOobject::AUTO_WRITE
        ),
        film.regionMesh(),
        dimensionedScalar(dimless, 1.0)
    ),
    absorptivity_(readScalar(coeffDict_.lookup("absorptivity"))),
    timeStart_(readScalar(coeffDict_.lookup("timeStart"))),
    duration_(readScalar(coeffDict_.lookup("duration")))
{
    mask_ = pos0(mask_);
}
Пример #19
0
void Foam::CLASS::updateCoeffs()
{
    if (this->updated())
    {
        return;
    }

    PARENT::operator==
    (
        data_
      + fieldData_
      + scalarData_*timeVsData_->value(t())
    );

    const scalarField& phip =
        this->patch().template lookupPatchField<surfaceScalarField, scalar>
        (
            "phi"
        );
    this->valueFraction() = 1.0 - pos0(phip);

    PARENT::updateCoeffs();
}
Пример #20
0
void Node::computeDistance(){

  if(getNode(1) == NULL || getNode(2) == NULL){
    std::cout << "undefined link" << std::endl;
    exit(-1);
  }
  
  sf::Vector2f pos0(getPos());
  sf::Vector2f pos1(getNode(1)->getPos());
  sf::Vector2f pos2(getNode(2)->getPos());

  float dis1x = pos0.x - pos1.x;
  float dis1y = pos0.y - pos1.y;

  float dis2x = pos0.x - pos2.x;
  float dis2y = pos0.y - pos2.y;

  _n1_distance = sqrt((dis1x*dis1x) + (dis1y*dis1y));

  _n2_distance = sqrt((dis2x*dis2x) + (dis2y*dis2y));
  

}
Пример #21
0
Foam::tmp<Foam::volScalarField> Foam::dragModels::Tenneti::CdRe() const
{
    volScalarField alpha1
    (
        max(pair_.dispersed(), pair_.continuous().residualAlpha())
    );

    volScalarField alpha2
    (
        max(pair_.continuous(), pair_.continuous().residualAlpha())
    );

    volScalarField Res(alpha2*pair_.Re());

    volScalarField CdReIsolated
    (
        neg(Res - 1000)*24*(1 + 0.15*pow(Res, 0.687))
      + pos0(Res - 1000)*0.44*max(Res, residualRe_)
    );

    volScalarField F0
    (
        5.81*alpha1/pow3(alpha2) + 0.48*pow(alpha1, 1.0/3.0)/pow4(alpha2)
    );

    volScalarField F1
    (
        pow3(alpha1)*Res*(0.95 + 0.61*pow3(alpha1)/sqr(alpha2))
    );

    // Tenneti et al. correlation includes the mean pressure drag.
    // This was removed here by multiplying F by alpha2 for consistency with
    // the formulation used in OpenFOAM
    return
        CdReIsolated + 24*sqr(alpha2)*(F0 + F1);
}
Пример #22
0
int main() {
	std::mt19937 generator(time(nullptr));

	sys::ComputeSystem cs;

	cs.create(sys::ComputeSystem::_gpu);

	sys::ComputeProgram prog;

	prog.loadFromFile("resources/neoKernels.cl", cs);

	// --------------------------- Create the Sparse Coder ---------------------------

	cl::Image2D inputImage = cl::Image2D(cs.getContext(), CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_FLOAT), 64, 64);

	std::ifstream fromFile("resources/train-images.idx3-ubyte", std::ios::binary | std::ios::in);

	if (!fromFile.is_open()) {
		std::cerr << "Could not open train-images.idx3-ubyte!" << std::endl;

		return 1;
	}

	std::vector<neo::PredictiveHierarchy::LayerDesc> layerDescs(4);

	layerDescs[0]._size = { 64, 64 };
	layerDescs[0]._feedForwardRadius = 8;

	layerDescs[1]._size = { 48, 48 };

	layerDescs[2]._size = { 32, 32 };

	layerDescs[3]._size = { 24, 24 };

	neo::PredictiveHierarchy ph;

	ph.createRandom(cs, prog, { 64, 64 }, layerDescs, { -0.01f, 0.01f }, { 0.01f, 0.05f }, 0.1f, generator);

	float avgError = 1.0f;

	float avgErrorDecay = 0.1f;

	sf::RenderWindow window;

	window.create(sf::VideoMode(1024, 512), "MNIST Video Test");

	vis::Plot plot;

	plot._curves.push_back(vis::Curve());

	plot._curves[0]._name = "Squared Error";

	std::uniform_int_distribution<int> digitDist(0, 59999);
	std::uniform_real<float> dist01(0.0f, 1.0f);

	sf::RenderTexture rt;

	rt.create(64, 64);

	sf::Image digit0;
	sf::Texture digit0Tex;
	sf::Image digit1;
	sf::Texture digit1Tex;

	sf::Image pred;
	sf::Texture predTex;

	digit0.create(28, 28);
	digit1.create(28, 28);

	pred.create(rt.getSize().x, rt.getSize().y);

	const float boundingSize = (64 - 28) / 2;
	const float center = 32;
	const float minimum = center - boundingSize;
	const float maximum = center + boundingSize;

	float avgError2 = 1.0f;

	const float avgError2Decay = 0.01f;

	std::vector<float> prediction(64 * 64, 0.0f);

	for (int iter = 0; iter < 10000; iter++) {
		// Select digit indices
		int d0 = digitDist(generator);
		int d1 = digitDist(generator);

		// Load digits
		Image img0, img1;

		loadMNISTimage(fromFile, d0, img0);
		loadMNISTimage(fromFile, d1, img1);

		for (int x = 0; x < digit0.getSize().x; x++)
			for (int y = 0; y < digit0.getSize().y; y++) {
				int index = x + y * digit0.getSize().x;

				sf::Color c = sf::Color::White;

				c.a = img0._intensities[index];

				digit0.setPixel(x, y, c);
			}

		digit0Tex.loadFromImage(digit0);

		for (int x = 0; x < digit1.getSize().x; x++)
			for (int y = 0; y < digit1.getSize().y; y++) {
				int index = x + y * digit1.getSize().x;

				sf::Color c = sf::Color::White;

				c.a = img1._intensities[index];

				digit1.setPixel(x, y, c);
			}

		digit1Tex.loadFromImage(digit1);

		sf::Vector2f vel0(dist01(generator) * 2.0f - 1.0f, dist01(generator) * 2.0f - 1.0f);
		sf::Vector2f vel1(dist01(generator) * 2.0f - 1.0f, dist01(generator) * 2.0f - 1.0f);

		sf::Vector2f pos0(dist01(generator) * (maximum - minimum) + minimum, dist01(generator) * (maximum - minimum) + minimum);
		sf::Vector2f pos1(dist01(generator) * (maximum - minimum) + minimum, dist01(generator) * (maximum - minimum) + minimum);

		float vel0mul = dist01(generator) * 6.0f / std::max(1.0f, std::sqrt(vel0.x * vel0.x + vel0.y + vel0.y));

		vel0 *= vel0mul;

		float vel1mul = dist01(generator) * 6.0f / std::max(1.0f, std::sqrt(vel1.x * vel1.x + vel1.y + vel1.y));

		vel1 *= vel1mul;

		// Render video
		for (int f = 0; f < 20; f++) {
			sf::Event windowEvent;

			while (window.pollEvent(windowEvent)) {
				switch (windowEvent.type) {
				case sf::Event::Closed:
					return 0;
				}
			}

			pos0 += vel0;

			pos1 += vel1;

			if (pos0.x < minimum) {
				pos0.x = minimum;

				vel0.x *= -1.0f;
			}
			else if (pos0.x > maximum) {
				pos0.x = maximum;

				vel0.x *= -1.0f;
			}

			if (pos0.y < minimum) {
				pos0.y = minimum;

				vel0.y *= -1.0f;
			}
			else if (pos0.y > maximum) {
				pos0.y = maximum;

				vel0.y *= -1.0f;
			}

			if (pos1.x < minimum) {
				pos1.x = minimum;

				vel1.x *= -1.0f;
			}
			else if (pos1.x > maximum) {
				pos1.x = maximum;

				vel1.x *= -1.0f;
			}

			if (pos1.y < minimum) {
				pos1.y = minimum;

				vel1.y *= -1.0f;
			}
			else if (pos1.y > maximum) {
				pos1.y = maximum;

				vel1.y *= -1.0f;
			}

			window.clear();
			rt.clear(sf::Color::Black);

			sf::Sprite s0;

			s0.setTexture(digit0Tex);

			s0.setOrigin(28 / 2, 28 / 2);

			s0.setPosition(pos0);

			rt.draw(s0);

			sf::Sprite s1;

			s1.setTexture(digit1Tex);

			s1.setOrigin(28 / 2, 28 / 2);

			s1.setPosition(pos1);

			rt.draw(s1);

			rt.display();

			// Get input image
			sf::Image res = rt.getTexture().copyToImage();

			// Show RT
			const float scale = 4.0f;

			sf::Sprite s;

			s.setScale(scale, scale);

			s.setTexture(rt.getTexture());

			window.draw(s);

			std::vector<float> input(64 * 64);

			// Train
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::T)) {
				for (int x = 0; x < res.getSize().x; x++)
					for (int y = 0; y < res.getSize().y; y++) {
						input[x + y * 64] = prediction[x + y * 64];
					}
			}
			else {
				const float predictionIncorporateRatio = 0.1f;

				for (int x = 0; x < res.getSize().x; x++)
					for (int y = 0; y < res.getSize().y; y++) {
						input[x + y * 64] = (1.0f - predictionIncorporateRatio) * res.getPixel(x, y).r / 255.0f + predictionIncorporateRatio * prediction[x + y * 64];
					}
			}

			// Error
			float error = 0.0f;

			for (int x = 0; x < res.getSize().x; x++)
				for (int y = 0; y < res.getSize().y; y++) {
					error += std::pow(res.getPixel(x, y).r / 255.0f - prediction[x + y * 64], 2);
				}

			error /= res.getSize().x * res.getSize().y;

			avgError2 = (1.0f - avgError2Decay) * avgError2 + avgError2Decay * error;

			std::cout << "Squared Error: " << avgError2 << std::endl;

			cs.getQueue().enqueueWriteImage(inputImage, CL_TRUE, { 0, 0, 0 }, { 64, 64, 1 }, 0, 0, input.data());

			ph.simStep(cs, inputImage);

			cs.getQueue().enqueueReadImage(ph.getPrediction(), CL_TRUE, { 0, 0, 0 }, { 64, 64, 1 }, 0, 0, prediction.data());

			// Show prediction
			for (int x = 0; x < rt.getSize().x; x++)
				for (int y = 0; y < rt.getSize().y; y++) {
					sf::Color c = sf::Color::White;

					c.r = c.b = c.g = std::min(1.0f, std::max(0.0f, prediction[x + y * 64])) * 255.0f;

					pred.setPixel(x, y, c);
				}

			predTex.loadFromImage(pred);

			sf::Sprite sp;

			sp.setTexture(predTex);

			sp.setScale(scale, scale);

			sp.setPosition(window.getSize().x - scale * rt.getSize().x, 0);

			window.draw(sp);

			/*sf::Image sdr;

			sdr.create(prsdr.getLayerDescs().front()._width, prsdr.getLayerDescs().front()._height);

			for (int x = 0; x < sdr.getSize().x; x++)
				for (int y = 0; y < sdr.getSize().y; y++) {
					sf::Color c = sf::Color::White;

					c.r = c.g = c.b = prsdr.getLayers().front()._sdr.getHiddenState(x, y) * 255.0f;

					sdr.setPixel(x, y, c);
				}

			sf::Texture sdrTex;

			sdrTex.loadFromImage(sdr);

			sf::Sprite sdrS;

			sdrS.setTexture(sdrTex);

			sdrS.setPosition(0.0f, window.getSize().y - sdrTex.getSize().y * scale);

			sdrS.setScale(scale, scale);

			window.draw(sdrS);*/

			window.display();
	
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
				return 0;
		}
	}

	/*sf::RenderTexture rt;

	rt.create(1024, 1024);

	sf::Texture lineGradientTexture;

	lineGradientTexture.loadFromFile("resources/lineGradient.png");

	sf::Font tickFont;

	tickFont.loadFromFile("resources/arial.ttf");

	plot.draw(rt, lineGradientTexture, tickFont, 1.0f, sf::Vector2f(0.0f, step), sf::Vector2f(0.0f, 1.0f), sf::Vector2f(128.0f, 128.0f), sf::Vector2f(500.0f, 0.1f), 2.0f, 3.0f, 1.5f, 3.0f, 20.0f, 6);

	rt.display();

	rt.getTexture().copyToImage().saveToFile("plot.png");*/

	return 0;
}
Пример #23
0
void MeshFusion::intoMesh(Matrix4f invm, MyTri *scanned)
{

	int nnode[2048];

	int ocase = -1;
	int	nface = scanned->totalFace / 3;
	for (int i = 0; i < nface; i++)
	{
		int n0 = scanned->meshTri[3 * i];
		int n1 = scanned->meshTri[3 * i + 1];
		int n2 = scanned->meshTri[3 * i + 2];
		Point2  first_vertex = scanned->meshProj[n0];
		Point2  second_vertex = scanned->meshProj[n1];
		Point2  third_vertex = scanned->meshProj[n2];

		bool s0 = scanned->stat[n0];
		bool s1 = scanned->stat[n1];
		bool s2 = scanned->stat[n2];

		if (!s0 && !s1 && !s2)
		{
			Vector3f pos0(scanned->meshVertex[n0].x, scanned->meshVertex[n0].y, scanned->meshVertex[n0].z);
			Vector3f pos1(scanned->meshVertex[n1].x, scanned->meshVertex[n1].y, scanned->meshVertex[n1].z);
			Vector3f pos2(scanned->meshVertex[n2].x, scanned->meshVertex[n2].y, scanned->meshVertex[n2].z);

			Vector3f ipos0 = invm *pos0;
			Vector3f ipos1 = invm *pos1;
			Vector3f ipos2 = invm *pos2;

			// if (nnode[n0] <= 0)
			{
				mytriData.meshVertex[mytriData.totalVertex].x = ipos0.x;
				mytriData.meshVertex[mytriData.totalVertex].y = ipos0.y;
				mytriData.meshVertex[mytriData.totalVertex].z = ipos0.z;
				nnode[n0] = mytriData.totalVertex;
				mytriData.totalVertex++;
			}

			//if (nnode[n1] <= 0)
			{
				mytriData.meshVertex[mytriData.totalVertex].x = ipos1.x;
				mytriData.meshVertex[mytriData.totalVertex].y = ipos1.y;
				mytriData.meshVertex[mytriData.totalVertex].z = ipos1.z;
				nnode[n1] = mytriData.totalVertex;
				mytriData.totalVertex++;
			}

			//if (nnode[n2] <= 0)
			{
				mytriData.meshVertex[mytriData.totalVertex].x = ipos2.x;
				mytriData.meshVertex[mytriData.totalVertex].y = ipos2.y;
				mytriData.meshVertex[mytriData.totalVertex].z = ipos2.z;
				nnode[n2] = mytriData.totalVertex;
				mytriData.totalVertex++;
			}

			mytriData.meshTri[mytriData.totalFace++] = nnode[n0];
			mytriData.meshTri[mytriData.totalFace++] = nnode[n1];
			mytriData.meshTri[mytriData.totalFace++] = nnode[n2];

		}


	}

}
Пример #24
0
void
AirController::assignRoute(std::list<Flight*>::iterator flight)
{
	//Crea una ruta para cada vuelo sin rutas según la posición desde la que empiezan y la
	//cola existente.
	//Se coloca al avión en la cola según el tiempo que tardará en llegar a la pista
	//Si la diferencia de dicho tiempo según dicha ruta con respecto al resto de rutas ya
	//asignadas es mayor que cierto tiempo de seguridad, se le asigna dicha ruta
	//Instancia de todos los vuelos
	std::list<Flight*> flights = Airport::getInstance()->getFlights();
	std::list<Flight*>::iterator otherflight;

	//Definición últimos puntos de  ruta bajada y aterrizaje
	Route r0, r1, r2, r3;
	Position pos0(POS0_x, POS0_y, POS0_z); //Posición antes de procedimiento de bajada
	Position pos1(POS1_x, POS1_y, POS1_z); //Mitad de la bajada
	Position pos2(POS2_x, POS2_y, POS2_z); //Avión en suelo, principio de pista
	Position pos3(POS3_x, POS3_y, POS3_z); //Final de pista
	r0.pos = pos0;
	r0.speed = SPEED_0;
	r1.pos = pos1;
	r1.speed = SPEED_1;
	r2.pos = pos2;
	r2.speed = SPEED_2;
	r3.pos = pos3;
	r3.speed = SPEED_3;

	//Definición de variables que nos serán útiles
	int i,j,pointofroute,k;
	//float timetoarrive;
	//float speedf = 120; //Velocidad en la ruta
	long ta;
	float xd, yd,zd;
	bool freeroute = false; //Bool que al intinerar nos permitirá ver si un punto ruta está libre
	//gettimeofday(&tv, NULL);

	ta = Airport::getInstance()->getTotalCrono()/1000000.0; //Se ha escogido Crono para tener en cuenta las
															//aceleraciones en tiempo que pueden existir al aumentar
															//o disminuir el paso del tiemp

	//NextPositions nextp;



	float angle;
	long timetopoint = 0;
	long timetocenter;
	Position posbeforeland = pos0;
	Position newpoint = posbeforeland;
	Position newpointroute;

	float xnext,ynext,znext;
	float speednext;
	Route nextroute,newroute;
	float landingtime;
	int numeroderutasfun;
	float velFinTramo; //Guarda en cada tramo, la velocidad con la que acaba el avión
	float timebeforelanding;
	float landtimefun;

	//Iniciamos borrando cualquier ruta que pueda tener(util en caso de necesitar reininciar)
	//(*flight)->getRoute()->clear();
	//Aignamos

	//R1 R2 y R3 son las rutas de pos final de descenso, principio pista y final. Comun a todos
	(*flight)->getRoute()->push_back(r3);
	(*flight)->getRoute()->push_front(r2);
	(*flight)->getRoute()->push_front(r1);
	//Angulo de entrada del avion en grados
	angle = atan2((*flight)->getPosition().get_y(),(*flight)->getPosition().get_x())*180/3.1415;
	//Según angulo se asigna una ruta distinta
	if(abs(angle)<60){ //Ruta de la izq
		xd = DISROUTE;
		yd = 0;
	} else if(angle>60) { //Ruta de la der
		xd = -DISROUTE*cos(60*pi/180);
		yd = DISROUTE*sin(60*pi/180);
	} else { //Ruta del centro
		xd = -DISROUTE*cos(60*pi/180);
		yd = -DISROUTE*sin(60*pi/180);
	}



	//Cada punto de ruta es un punto a una distancia fija del anterior de cada una de las tres rutas
	pointofroute = 0;

	//Comprobar si una a una distancia pointfroute*DISROUTE de r0 cumple con la seguridad
	//ir aumentando pointofroute hasta que lo haga
	while(true)
	{
		//Punto (y ruta) de entrada a ruta a probar
		newpoint.set_x(posbeforeland.get_x()+xd*pointofroute);
		newpoint.set_y(posbeforeland.get_y()+yd*pointofroute);
		newpoint.set_y(posbeforeland.get_z()+HEIGHTDIFFERENCEPOINTS*pointofroute);
		newroute.pos = newpoint;
		newroute.speed = SPEED_0 + pointofroute*DIFFSPEED;

		//Tiempo que tarda el avión desde su pos ini hasta dicho punto
		timetopoint = (*flight)->getTimeToPoint(newroute,velFinTramo);
		//Tiempo que tardara en alcanzar al centro sumando el tiempo a dicho punto, el de aterrizaje y el de cada
		//franja
		timetocenter = timetopoint;
		if(pointofroute>0)
		{
			for(k=pointofroute;k>=0;k--)
			{
				timetocenter += timeBetweenTwoRoutes(DISROUTE,velFinTramo,SPEED_0+(k-1)*DIFFSPEED,MAXACC,velFinTramo);

			}
		}


		//Timpo que se tarda en recorrer los últimos cuatro puntos especificados arriba
		landingtime = timeBetweenTwoRoutes(r0.pos.distance(r1.pos),velFinTramo,r1.speed,MAXACC,velFinTramo);
		landingtime += timeBetweenTwoRoutes(r1.pos.distance(r2.pos),velFinTramo,r2.speed,MAXACC,velFinTramo);
		landingtime += timeBetweenTwoRoutes(r2.pos.distance(r3.pos),velFinTramo,r3.speed,MAXACC,velFinTramo);
		timebeforelanding = timetocenter;
		timetocenter +=  landingtime;
		//Comprobar si dicho punto cumple con seguridad con el resto de tiempos del resto de aviones
		//Si al pasar por todos los aviones, freeroute sigue verdadero, es que cumple con seg
		freeroute = true;
		for(otherflight = flights.begin();otherflight!=flights.end();++otherflight)
		{
			if((*otherflight)->getId()!=(*flight)->getId() && (*otherflight)->getTimeToCenter()>-1)
			{
				//En caso de que no cumpla con SECTIME, free route false
				if(abs((*otherflight)->getTimeToCenter()-timetocenter)<SECTIME){
					freeroute = false;
					pointofroute++;
					break;
				}
			}
		}
		//Caso que si cumpla, se asigna el nuevo punto de ruta y cada punto intermedio
		if(freeroute){
			for(i=0;i<=pointofroute;i++){
				xnext = posbeforeland.get_x() + i*xd;
				ynext = posbeforeland.get_y() + i*yd;
				znext = posbeforeland.get_z() + i*HEIGHTDIFFERENCEPOINTS;
				speednext = SPEED_0+i*20;
				newpointroute.set_x(xnext);
				newpointroute.set_y(ynext);
				newpointroute.set_z(znext);
				nextroute.pos = newpointroute;
				nextroute.speed = speednext;
				(*flight)->getRoute()->push_front(nextroute);
			}
			break;
		}
	}

}
void ColladaAnimatedMesh::UpdateSkinnedMesh( float32 time )
{
	if (mesh == 0)return;
	if (joints[0].node == 0)return;
	
//	for (int k = 0; k < (int)joints.size(); ++k)
//	{
//		if (joints[k].node)
//		{
//			joints[k].colladaLocalTransform = joints[k].node->originalNode->CalculateLocalTransform();
//			joints[k].colladaWorldTransform = joints[k].node->originalNode->CalculateWorldTransform();
//		}
//	}
	for (int k = 0; k < (int)joints.size(); ++k)
	{
		Joint & currentJoint = joints[k];
		if (joints[k].node)
		{
			//FMMatrix44 colladaLocalTransform = joints[k].node->originalNode->CalculateLocalTransform();
			//joints[k].localTransform = ConvertMatrix(colladaLocalTransform);
			joints[k].localTransform = joints[k].node->localTransform;
			// code to compute worldMatrixes using localMatrixes
//			FMMatrix44 colladaWorldTransform = joints[k].node->originalNode->CalculateWorldTransform();
//			Matrix4 worldTransform = ConvertMatrix(colladaWorldTransform);
//			if (currentJoint.parentIndex != -1)
//			{
//				Joint & parentJoint = joints[currentJoint.parentIndex];
//			
//				joints[k].worldTransform =  joints[k].localTransform * parentJoint.worldTransform;
//			}else
//			{
//				FMMatrix44 realWorldTransform = joints[k].node->originalNode->CalculateWorldTransform();
//				// get parent joint world transform
//				joints[k].worldTransform = ConvertMatrix(realWorldTransform); ////joints[k].localTransform;
//			}

			//printf("joint: %d: %s p:%d isEq: %d\n", k, currentJoint.node->originalNode->GetDaeId().c_str(), currentJoint.parentIndex, (int)(worldTransform == joints[k].worldTransform));
			//PrintMatrix(worldTransform);
			//PrintMatrix(joints[k].worldTransform);

		
//			joints[k].localTranslation.x = joints[k].localTransform._30;
//			joints[k].localTranslation.y = joints[k].localTransform._31;
//			joints[k].localTranslation.z = joints[k].localTransform._32;
//			
//			joints[k].localQuat.Construct(joints[k].localTransform);
//
//			
//			Matrix4 localTransformTrans;
//			Matrix4 localTransformRot;
//			Matrix4 localTransformFinal;
//			localTransformTrans.CreateTranslation(joints[k].localTranslation);
//			localTransformRot = joints[k].localQuat.GetMatrix();
//			
//			joints[k].localTransform = localTransformRot * localTransformTrans;
//			
//			FMMatrix44 colladaWorldTransform = joints[k].node->originalNode->CalculateWorldTransform();
//			Matrix4 worldTransform = ConvertMatrix(colladaWorldTransform);
			if (currentJoint.parentIndex != -1)
			{
				Joint & parentJoint = joints[currentJoint.parentIndex];
			
				joints[k].worldTransform =  joints[k].localTransform * parentJoint.worldTransform;
			}else
			{
				joints[k].worldTransform = joints[k].node->worldTransform; ////joints[k].localTransform;
			}
			
		}
	}
	
	for (int poly = 0; poly < (int)mesh->polygons.size(); ++poly)
	{
		ColladaPolygonGroup * polyGroup = mesh->polygons[poly];	
		
		for (int vi = 0; vi < (int)polyGroup->skinVerteces.size(); ++vi)
		{
			ColladaVertex & v0 = polyGroup->unoptimizedVerteces[vi];
			ColladaVertex & v = polyGroup->skinVerteces[vi];
			
			v.position = Vector3(0.0, 0.0, 0.0);

			for (int jointIndex = 0; jointIndex < v.jointCount; ++jointIndex)
			{
				//FMVector3 pos(v0.position.x, v0.position.y, v0.position.z);
				//FMMatrix44 jointT = joints[v0.joint[jointIndex]].colladaWorldTransform * joints[v0.joint[jointIndex]].colladaInverse0 * bindShapeMatrix;
				//pos = jointT.TransformCoordinate(pos);
				
				Vector3 pos0(v0.position.x, v0.position.y, v0.position.z);
				Vector3 pos;
				Matrix4 finalJointMatrix = bindShapeMatrix * joints[v0.joint[jointIndex]].inverse0 * joints[v0.joint[jointIndex]].worldTransform;
//				Matrix4 finalJointMatrix = joints[v0.joint[jointIndex]].worldTransform * joints[v0.joint[jointIndex]].inverse0 * bindShapeMatrix; 
				pos = pos0 * finalJointMatrix;
				
				float weight = v0.weight[jointIndex]; 
				
				v.position.x += pos.x * weight;
				v.position.y += pos.y * weight;
				v.position.z += pos.z * weight;
			}
		}	
	}
}
void Foam::fvMotionSolverEngineMesh::move()
{
    scalar deltaZ = engineDB_.pistonDisplacement().value();
    Info<< "deltaZ = " << deltaZ << endl;

    // Position of the top of the static mesh layers above the piston
    scalar pistonPlusLayers = pistonPosition_.value() + pistonLayers_.value();

    scalar pistonSpeed = deltaZ/engineDB_.deltaTValue();

    motionSolver_.pointMotionU().boundaryFieldRef()[pistonIndex_] ==
        pistonSpeed;

    {
        scalarField linerPoints
        (
            boundary()[linerIndex_].patch().localPoints().component(vector::Z)
        );

        motionSolver_.pointMotionU().boundaryFieldRef()[linerIndex_] ==
            pistonSpeed*pos0(deckHeight_.value() - linerPoints)
           *(deckHeight_.value() - linerPoints)
           /(deckHeight_.value() - pistonPlusLayers);
    }

    motionSolver_.solve();

    if (engineDB_.foundObject<surfaceScalarField>("phi"))
    {
        surfaceScalarField& phi =
            engineDB_.lookupObjectRef<surfaceScalarField>("phi");

        const volScalarField& rho =
            engineDB_.lookupObject<volScalarField>("rho");

        const volVectorField& U =
            engineDB_.lookupObject<volVectorField>("U");

        bool absolutePhi = false;
        if (moving())
        {
            phi += fvc::interpolate(rho)*fvc::meshPhi(rho, U);
            absolutePhi = true;
        }

        movePoints(motionSolver_.curPoints());

        if (absolutePhi)
        {
            phi -= fvc::interpolate(rho)*fvc::meshPhi(rho, U);
        }
    }
    else
    {
        movePoints(motionSolver_.curPoints());
    }


    pistonPosition_.value() += deltaZ;

    Info<< "clearance: " << deckHeight_.value() - pistonPosition_.value() << nl
        << "Piston speed = " << pistonSpeed << " m/s" << endl;
}
void Foam::JohnsonJacksonParticleThetaFvPatchScalarField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    // lookup the fluid model and the phase
    const twoPhaseSystem& fluid = db().lookupObject<twoPhaseSystem>
    (
        "phaseProperties"
    );

    const phaseModel& phased
    (
        fluid.phase1().name() == internalField().group()
      ? fluid.phase1()
      : fluid.phase2()
    );

    // lookup all the fields on this patch
    const fvPatchScalarField& alpha
    (
        patch().lookupPatchField<volScalarField, scalar>
        (
            phased.volScalarField::name()
        )
    );

    const fvPatchVectorField& U
    (
        patch().lookupPatchField<volVectorField, vector>
        (
            IOobject::groupName("U", phased.name())
        )
    );

    const fvPatchScalarField& gs0
    (
        patch().lookupPatchField<volScalarField, scalar>
        (
            IOobject::groupName("gs0", phased.name())
        )
    );

    const fvPatchScalarField& kappa
    (
        patch().lookupPatchField<volScalarField, scalar>
        (
            IOobject::groupName("kappa", phased.name())
        )
    );

    const scalarField Theta(patchInternalField());

    // lookup the packed volume fraction
    dimensionedScalar alphaMax
    (
        "alphaMax",
        dimless,
        db()
       .lookupObject<IOdictionary>
        (
            IOobject::groupName("turbulenceProperties", phased.name())
        )
       .subDict("RAS")
       .subDict("kineticTheoryCoeffs")
       .lookup("alphaMax")
    );

    // calculate the reference value and the value fraction
    if (restitutionCoefficient_.value() != 1.0)
    {
        this->refValue() =
            (2.0/3.0)
           *specularityCoefficient_.value()
           *magSqr(U)
           /(scalar(1) - sqr(restitutionCoefficient_.value()));

        this->refGrad() = 0.0;

        scalarField c
        (
             constant::mathematical::pi
            *alpha
            *gs0
            *(scalar(1) - sqr(restitutionCoefficient_.value()))
            *sqrt(3*Theta)
            /max(4*kappa*alphaMax.value(), small)
        );

        this->valueFraction() = c/(c + patch().deltaCoeffs());
    }

    // for a restitution coefficient of 1, the boundary degenerates to a fixed
    // gradient condition
    else
    {
        this->refValue() = 0.0;

        this->refGrad() =
            pos0(alpha - small)
           *constant::mathematical::pi
           *specularityCoefficient_.value()
           *alpha
           *gs0
           *sqrt(3*Theta)
           *magSqr(U)
           /max(6*kappa*alphaMax.value(), small);

        this->valueFraction() = 0;
    }

    mixedFvPatchScalarField::updateCoeffs();
}
Пример #28
0
void updateHaptics(void)
{
    double timeV = 0.0;

    cLabel* label = new cLabel();
    cLabel* label2 = new cLabel();
    rootLabels->addChild(label);
    rootLabels->addChild(label2);
    label->setPos(0, 0, 0);
    label2->setPos(0, -20, 0);
    label->m_fontColor.set(1.0, 1.0, 1.0);
    label2->m_fontColor.set(1.0, 1.0, 1.0);

    // main haptic simulation loop
    while(simulationRunning)
    {
        float deltaTime = pClock.getCurrentTimeSeconds() - lastTime;
        lastTime = pClock.getCurrentTimeSeconds();

        cVector3d equilibrium (0.0, 0.0, 0.0);
        cVector3d pos0 (0.0, 0.0, 0.0), pos1 (0.0, 0.0, 0.0);

        // for each device
        int i=0;
        while (i < numHapticDevices)
        {
            // read position of haptic device
            cVector3d newPosition;
            hapticDevices[i]->getPosition(newPosition);
            newPosition = deviceToWorld(newPosition, i);

            ((i == 0)? pos0 : pos1) = newPosition;

            // read orientation of haptic device
            cMatrix3d newRotation;
            hapticDevices[i]->getRotation(newRotation);

            // update position and orientation of cursor
            cursors[i]->setPos(newPosition);
            cursors[i]->setRot(newRotation);

            // read linear velocity from device
            cVector3d linearVelocity;
            hapticDevices[i]->getLinearVelocity(linearVelocity);

            // update arrow
//            velocityVectors[i]->m_pointA = newPosition;
//            velocityVectors[i]->m_pointB = cAdd(newPosition, linearVelocity);

            // read user button status
            bool buttonStatus;
            hapticDevices[i]->getUserSwitch(0, buttonStatus);

            // adjustthe  color of the cursor according to the status of
            // the user switch (ON = TRUE / OFF = FALSE)
            if (i == 0)
                cursors[i]->m_material = matCursor2;
            else
                cursors[i]->m_material = matCursor1;

            // increment counter
            i++;
        }

        double f0, f1;
        f0 = pos0.length();
        f1 = pos1.length();

        f0 = f0/(f0 + f1);
        f1 = 1.0 - f0;

        equilibrium = pos1 + (pos0 - pos1)*f0;

        // Update the position of the sun
        cVector3d dir = pos1 - pos0;
        double dist = dir.length();
        dir.normalize();

        double vibrationSpeed = 20.0;
        double vibrationAmount = 0.02;

        //sun->setPos(sun->getPos()*(1.0 - deltaTime*speed) + equilibrium*(deltaTime*speed));
        //timeV += deltaTime*vibrationSpeed*(0.7 - cAbs(f0 - 0.5)*2.0);
        sun->setPos(equilibrium /*+ vibrationAmount*dir*cSinRad(timeV)*/);

        // Update logic
        if (!calibrationFinished) {
            label->m_string = "Calibrating, please move the haptic devices around in order to determine their limitations in movement.";
            label2->m_string = "Press 'c' to finish calibration.";

            if (sun->getPos().x < min.x)
                min.x = sun->getPos().x;
            if (sun->getPos().y < min.y)
                min.y = sun->getPos().y;
            if (sun->getPos().z < min.z)
                min.z = sun->getPos().z;

            if (sun->getPos().x > max.x)
                max.x = sun->getPos().x;
            if (sun->getPos().y > max.y)
                max.y = sun->getPos().y;
            if (sun->getPos().z > max.z)
                max.z = sun->getPos().z;
        } else if (logic->isReady()) {
            if (logic->gameIsOver() && !scoreDisplayed) {
                std::stringstream strs;
                strs << logic->playTime();
                std::string playString = strs.str();

                // define its position, color and string message
                label->m_string = "Congratulation! Your Time: " + playString;
                label2->m_string = "Press 'r' to restart!";

                for (i = 0; i < numHapticDevices; i++) {
                    cVector3d zero(0.0, 0.0, 0.0);
                    hapticDevices[i]->setForce(zero);
                }

                scoreDisplayed = true;
            } else if (!scoreDisplayed) {
                label->m_string = "";
                label2->m_string = "";

                logic->update(deltaTime);

            }

            for (i = 0; i < numHapticDevices; i++) {
                // compute a reaction force
                cVector3d newForce (0,0,0);

                cVector3d devicePosition;
                hapticDevices[i]->getPosition(devicePosition);
                devicePosition = deviceToWorld(devicePosition, i);

                double k = 0.4;
                if (test == 1) k = 0.3;
                double dist = (devicePosition - sun->getPos()).length();
                //dist=dist-0.1;

                newForce = k*(devicePosition - sun->getPos())/(dist*dist*dist);
                //double intensity = (newForce.length())*1.0;
                //newForce.normalize();
                //newForce *= intensity;

    //            newForce = k*(devicePosition - sun->getPos())/(dist*dist*dist);

                if (i == 0) {  // Device on positive X (RIGHT)
                    newForce.x *= -1.0;
                    newForce.y *= -1.0;
                }

                // send computed force to haptic device
    //            bool status = true;
    //            if (hapticDevices[i]->getUserSwitch(0))
    //                printf("button pressed\n");

                // Check if the sphere is in the target area. If so, vibrate
                cVector3d vibrationForce(0.0, 0.0, 0.0);
                if (logic->sphereInTarget() && !logic->gameIsOver()) {
                    Cube* target = logic->getTarget();
                    double dist = target->getPos().distance(sun->getPos());
                    double factor = 1.0 - dist/(target->size/2.0);
                    timeV += deltaTime * (0.5 + factor/2.0);

                    double f = 2*cSinRad(40*timeV);
                    vibrationForce = cVector3d(f, f, f);
                }

                newForce += vibrationForce;
                if (test <= 2 || i == 0)
                    hapticDevices[i]->setForce(newForce);
                else {
                    cVector3d zero;
                    zero.zero();
                    hapticDevices[i]->setForce(zero);
                }
          }
        }
    }
    
    // exit haptics thread
    simulationFinished = true;
}
Пример #29
0
void DataSetView::viewportChanged()
{
	if(_viewportX != _viewportX || _viewportY != _viewportY || _viewportW != _viewportW || _viewportH != _viewportH ) //only possible if they are NaN
		return;

#ifdef DEBUG_VIEWPORT
	std::cout << "viewportChanged!\n" <<std::flush;
#endif
	QVector2D leftTop(_viewportX, _viewportY);
	QVector2D viewSize(_viewportW, _viewportH);
	QVector2D rightBottom(leftTop + viewSize);

	int currentViewportColMin = -1, currentViewportColMax = -1, currentViewportRowMin = -1, currentViewportRowMax = -1;

	float cumulative = 0;
	for(int col=0; col<_model->columnCount() && currentViewportColMax == -1; col++)
	{
		if(currentViewportColMax == -1 && cumulative > rightBottom.x())
			currentViewportColMax = col;

		cumulative += _dataColsMaxWidth[col];

		if(currentViewportColMin == -1 && cumulative > leftTop.x())
			currentViewportColMin = col;
	}

	if(currentViewportColMax == -1)
		currentViewportColMax = _model->columnCount();

	currentViewportColMin = std::max(0,						currentViewportColMin - _viewportMargin);
	currentViewportColMax = std::min(_model->columnCount(),	currentViewportColMax + _viewportMargin);

	currentViewportRowMin = std::max(qRound(leftTop.y()		/ _dataRowsMaxHeight) - 1,	0);
	currentViewportRowMax = std::min(qRound(rightBottom.y()	/ _dataRowsMaxHeight) + 1,	_model->rowCount());

	// remove superflouous textItems if they exist (aka store them in stack)
	if(_previousViewportRowMin != -1 && _previousViewportRowMax != -1 && _previousViewportColMin != -1 && _previousViewportColMax != -1)
	{
		for(int col=_previousViewportColMin; col<_previousViewportColMax; col++)
		{
			for(int row=_previousViewportRowMin; row < currentViewportRowMin; row++)
				storeTextItem(row, col);

			for(int row=currentViewportRowMax; row < _previousViewportRowMax; row++)
				storeTextItem(row, col);
		}

		for(int row=_previousViewportRowMin; row<_previousViewportRowMax; row++)
		{
			for(int col=_previousViewportColMin; col < currentViewportColMin; col++)
				storeTextItem(row, col);

			for(int col=currentViewportColMax; col < _previousViewportColMax; col++)
				storeTextItem(row, col);
		}

		for(int row=_previousViewportRowMin; row < currentViewportRowMin; row++)
			storeRowNumber(row);

		for(int row=currentViewportRowMax; row < _previousViewportRowMax; row++)
			storeRowNumber(row);
	}

	_lines.clear();

	//and now we should create some new ones!

	for(int col=currentViewportColMin; col<currentViewportColMax; col++)
		for(int row=currentViewportRowMin; row<currentViewportRowMax; row++)
		{
			QVector2D pos0(_colXPositions[col],					_dataRowsMaxHeight + row * _dataRowsMaxHeight);
			QVector2D pos1(pos0.x() + _dataColsMaxWidth[col],	pos0.y()+ _dataRowsMaxHeight);

			int lineFlags = _model->data(_model->index(row, col), _roleNameToRole["lines"]).toInt();

			bool	left	= (lineFlags & 1 > 0)	&& pos0.x()  > _rowNumberMaxWidth + _viewportX,
					right	= (lineFlags & 2 > 0)	&& pos1.x()  > _rowNumberMaxWidth + _viewportX,
					up		= lineFlags & 4 > 0		&& pos0.y()  > _dataRowsMaxHeight + _viewportY,
					down	= lineFlags & 8 > 0		&& pos1.y()  > _dataRowsMaxHeight + _viewportY;

			createTextItem(row, col);


			if(left)	_lines.push_back(std::make_pair(QVector2D(pos0.x(),	pos1.y()),	pos0));
			if(up)		_lines.push_back(std::make_pair(QVector2D(pos1.x(),	pos0.y()),	pos0));
			if(right)	_lines.push_back(std::make_pair(QVector2D(pos1.x(),	pos0.y()),	pos1));
			if(down)	_lines.push_back(std::make_pair(QVector2D(pos0.x(),	pos1.y()),	pos1));

		}

	_lines.push_back(std::make_pair(QVector2D(_viewportX,						_viewportY),						QVector2D(_viewportX,						_viewportY + _viewportH)));
	_lines.push_back(std::make_pair(QVector2D(_viewportX + _rowNumberMaxWidth,	_viewportY),						QVector2D(_viewportX + _rowNumberMaxWidth,	_viewportY + _viewportH)));

	_lines.push_back(std::make_pair(QVector2D(_viewportX,						_viewportY),						QVector2D(_viewportX + _viewportW,			_viewportY)));
	_lines.push_back(std::make_pair(QVector2D(_viewportX,						_viewportY + _dataRowsMaxHeight),	QVector2D(_viewportX + _viewportW,			_viewportY + _dataRowsMaxHeight)));


	for(int row=currentViewportRowMin; row<currentViewportRowMax; row++)
	{
		createRowNumber(row);

		QVector2D pos0(_viewportX,						(1 + row) * _dataRowsMaxHeight);
		QVector2D pos1(_viewportX + _rowNumberMaxWidth, (2 + row) * _dataRowsMaxHeight);

		if(pos0.y() > _dataRowsMaxHeight + _viewportY)
			_lines.push_back(std::make_pair(QVector2D(pos0.x(), pos0.y()), QVector2D(pos1.x(), pos0.y())));


		if(row == _model->rowCount() - 1 && pos1.y() > _dataRowsMaxHeight + _viewportY)
			_lines.push_back(std::make_pair(QVector2D(pos0.x(), pos1.y()), QVector2D(pos1.x(), pos1.y())));
	}

	for(int col=currentViewportColMin; col<currentViewportColMax; col++)
	{

		createColumnHeader(col);

		QVector2D pos0(_colXPositions[col],					_viewportY);
		QVector2D pos1(pos0.x() + _dataColsMaxWidth[col],	pos0.y() + _dataRowsMaxHeight);

		if(pos0.x()  > _rowNumberMaxWidth + _viewportX)
			_lines.push_back(std::make_pair(QVector2D(pos0.x(), pos0.y()), QVector2D(pos0.x(), pos1.y())));


		if(col == _model->columnCount() - 1 && pos1.x()  > _rowNumberMaxWidth + _viewportX)
			_lines.push_back(std::make_pair(QVector2D(pos1.x(), pos0.y()), QVector2D(pos1.x(), pos1.y())));
	}


	createleftTopCorner();


	update();

#ifdef DEBUG_VIEWPORT
	std::cout << "viewport X: " << _viewportX << " Y: " << _viewportY << " W: " << _viewportW << " H: " << _viewportH <<  std::endl << std::flush;
	std::cout << "_previousViewport ColMin: "<<_previousViewportColMin<<" ColMax: "<<_previousViewportColMax<<" RowMin: "<<_previousViewportRowMin<<" RowMax: "<<_previousViewportRowMax<<"\n";
	std::cout << "currentViewport ColMin: "<<currentViewportColMin<<" ColMax: "<<currentViewportColMax<<" RowMin: "<<currentViewportRowMin<<" RowMax: "<<currentViewportRowMax<<"\n"<<std::flush;
#endif

	_previousViewportColMin = currentViewportColMin;
	_previousViewportColMax = currentViewportColMax;
	_previousViewportRowMin = currentViewportRowMin;
	_previousViewportRowMax = currentViewportRowMax;
}