コード例 #1
0
ファイル: ir-builder.cpp プロジェクト: Ronnrein/hhvm
SSATmp* IRBuilder::preOptimizeCheckStk(IRInstruction* inst) {
  auto const newType = inst->typeParam();
  auto sp = inst->src(0);
  auto offset = inst->extra<CheckStk>()->offset;

  auto stkVal = getStackValue(sp, offset);
  auto const oldType = stkVal.knownType;

  if (newType < oldType) {
    // The new type is strictly better than the old type.
    return nullptr;
  }

  if (newType >= oldType) {
    // The new type isn't better than the old type.
    return sp;
  }

  if (newType.not(oldType)) {
    if (oldType.isBoxed() && newType.isBoxed()) {
      /* This CheckStk serves to update the inner type hint for a boxed
       * value, which requires no runtime work. This depends on the type being
       * boxed, and constraining it with DataTypeCountness will do it.  */
      constrainStack(sp, offset, DataTypeCountness);
      return gen(AssertStk, newType, StackOffset(offset), sp);
    }
    /* This check will always fail. It's probably due to an incorrect
     * prediction. Generate a Jmp, and return the source because
     * following instructions may depend on the output of CheckStk
     * (they'll be DCEd later).  Note that we can't use convertToJmp
     * because the return value isn't nullptr, so the original
     * instruction won't be inserted into the stream. */
    gen(Jmp, inst->taken());
    return sp;
  }

  return nullptr;
}
コード例 #2
0
ファイル: smpi_pmpi_request.cpp プロジェクト: mpoquet/simgrid
int PMPI_Wait(MPI_Request * request, MPI_Status * status)
{
  int retval = 0;

  smpi_bench_end();

  simgrid::smpi::Status::empty(status);

  if (request == nullptr) {
    retval = MPI_ERR_ARG;
  } else if (*request == MPI_REQUEST_NULL) {
    retval = MPI_SUCCESS;
  } else {
    //for tracing, save the handle which might get overriden before we can use the helper on it
    MPI_Request savedreq = *request;
    if (savedreq != MPI_REQUEST_NULL && not(savedreq->flags() & MPI_REQ_FINISHED))
      savedreq->ref();//don't erase te handle in Request::wait, we'll need it later
    else
      savedreq = MPI_REQUEST_NULL;

    int my_proc_id = (*request)->comm() != MPI_COMM_NULL
                         ? simgrid::s4u::this_actor::get_pid()
                         : -1; // TODO: cheinrich: Check if this correct or if it should be MPI_UNDEFINED
    TRACE_smpi_comm_in(my_proc_id, __func__, new simgrid::instr::NoOpTIData("wait"));

    simgrid::smpi::Request::wait(request, status);
    retval = MPI_SUCCESS;

    //the src may not have been known at the beginning of the recv (MPI_ANY_SOURCE)
    TRACE_smpi_comm_out(my_proc_id);
    trace_smpi_recv_helper(&savedreq, status);
    if (savedreq != MPI_REQUEST_NULL)
      simgrid::smpi::Request::unref(&savedreq);
  }

  smpi_bench_begin();
  return retval;
}
コード例 #3
0
void LMap::update_include_rgbd(RoboCompRGBD::PointSeq *points, QString rgbdID)
{
	int minHeight = 100;
	int maxHeight = 1900;
	int minHeightNeg = -200;

	RTMat TRr = innerModel->getTransformationMatrix("robot", rgbdID); // WARNING This was used because it could be fater than calling transform multiple times
	const uint32_t rgbd_size = points->size();
	uint32_t pw = 640;
	uint32_t ph = 480;
	uint32_t stepW = 10;
	uint32_t stepH = 16;
	if (points->size() == 320*240) { pw=320; ph=240; stepW=7; stepH=10; }
	if (points->size() == 160*120) { pw=160; ph=120; stepW=4; stepH=6;  }
	if (points->size() == 80*60)   { pw= 80; ph= 60; stepW=3; stepH=2;  }
	#pragma omp parallel for
	for (uint32_t rr=0; rr<ph; rr+=stepH)
	{
		for (uint32_t cc=0; cc<pw; cc+=stepW)
		{
			uint32_t ioi = rr*pw+cc;
			if (ioi<rgbd_size)
			{
				if (std::isnan(points->operator[](ioi).x) or std::isnan(points->operator[](ioi).y) or std::isnan(points->operator[](ioi).z))
					continue;
				if (points->operator[](ioi).z<0)
					continue;
				const QVec pRobot = (TRr * QVec::vec4(points->operator[](ioi).x, points->operator[](ioi).y, points->operator[](ioi).z, 1)).fromHomogeneousCoordinates();
				if (not ( (pRobot(1)>=minHeight and pRobot(1)<=maxHeight) or (pRobot(1)<minHeightNeg) ))
					continue;
				const QVec mapCoord = fromReferenceToImageCoordinates(pRobot, "robot");
				if (mapCoord(0)<=2 or mapCoord(0)>=bins-2 or mapCoord(2)<=2 or mapCoord(2)>=bins-2)
					continue;
				addToRGBDsCoordinates(mapCoord(0), mapCoord(2));
			}
		}
	}
}
コード例 #4
0
ファイル: CompressibleTpfa.cpp プロジェクト: 00liujj/opm-core
    /// Compute well potentials.
    void CompressibleTpfa::computeWellPotentials(const BlackoilState& state)
    {
        if (wells_ == NULL) return;

        const int nw = wells_->number_of_wells;
        const int np = props_.numPhases();
        const int nperf = wells_->well_connpos[nw];
        const int dim = grid_.dimensions;
        const double grav = gravity_ ? gravity_[dim - 1] : 0.0;
        wellperf_wdp_.clear();
        wellperf_wdp_.resize(nperf, 0.0);
        if (not (std::abs(grav) > 0.0)) {
            return;
        }

        // Temporary storage for perforation A matrices and densities.
        std::vector<double> A(np*np, 0.0);
        std::vector<double> rho(np, 0.0);

        // Main loop, iterate over all perforations,
        // using the following formula (by phase):
        //    wdp(perf) = g*(perf_z - well_ref_z)*rho(perf)
        // where the total density rho(perf) is taken to be
        //    sum_p (rho_p*saturation_p) in the perforation cell.
        for (int w = 0; w < nw; ++w) {
            const double ref_depth = wells_->depth_ref[w];
            for (int j = wells_->well_connpos[w]; j < wells_->well_connpos[w + 1]; ++j) {
                const int cell = wells_->well_cells[j];
                const double cell_depth = grid_.cell_centroids[dim * cell + dim - 1];
                props_.matrix(1, &state.pressure()[cell], &state.surfacevol()[np*cell], &cell, &A[0], 0);
                props_.density(1, &A[0], &rho[0]);
                for (int phase = 0; phase < np; ++phase) {
                    const double s_phase = state.saturation()[np*cell + phase];
                    wellperf_wdp_[j] += s_phase*rho[phase]*grav*(cell_depth - ref_depth);
                }
            }
        }
    }
コード例 #5
0
ファイル: OutputCRPropa2.cpp プロジェクト: msettimo/CRPropa3
void CRPropa2EventOutput3D::process(Candidate *c) const {
	if (not (c->hasProperty("Detected")))
		return;

	// remove flag so that the particle is not written to output again in the next step
	c->removeProperty("Detected");

	char buffer[256]; // max. 256 characters per line
	size_t p = 0; // length of line

	p += sprintf(buffer + p, "%i ", convertToCRPropa2NucleusId(c->current.getId()));
	p += sprintf(buffer + p, "%i ", convertToCRPropa2NucleusId(c->source.getId()));

	const Vector3d &ipos = c->source.getPosition() / Mpc;
	p += sprintf(buffer + p, "%.4f %.4f %.4f ", ipos.x, ipos.y, ipos.z);

	double iPhi = c->source.getDirection().getPhi();
	double iTheta = c->source.getDirection().getTheta();
	double iE = c->source.getEnergy() / EeV;
	p += sprintf(buffer + p, "%.4f %.4f %.4f ", iE, iPhi, iTheta);

	double t = comoving2LightTravelDistance(c->getTrajectoryLength()) / Mpc;
	p += sprintf(buffer + p, "%.4f ", t);

	const Vector3d &pos = c->current.getPosition() / Mpc;
	p += sprintf(buffer + p, "%.4f %.4f %.4f ", pos.x, pos.y, pos.z);

	double phi = c->current.getDirection().getPhi();
	double theta = c->current.getDirection().getTheta();
	double E = c->current.getEnergy() / EeV;
	p += sprintf(buffer + p, "%.4f %.4f %.4f\n", E, phi, theta);

#pragma omp critical
	{
		outfile.write(buffer, p);
		outfile.flush();
	}
}
コード例 #6
0
log_double UniformPrior::accountForMeanSubstChange( TreeAln &traln, const AbstractParameter* param, double oldFc, double newFc )const 
{
  auto result = 0.; 

  auto maxV =  exp( - getMin() / newFc) , 
    minV = exp(  - getMax() / newFc) ; 

  for(auto &b : traln.extractBranches(param))
    {
      bool less = b.getLength().getValue() < minV; 
      bool greater = b.getLength().getValue() > maxV; 
	      
      assert(not (less && greater)); 

      if(less || greater)
	{
	  // tout << b.getLength() << " is not okay (" << b.getInterpretedLength(traln,param) << ")" << std::endl; 
	  result += - std::numeric_limits<double>::infinity();
	}
    }
  
  return log_double::fromAbs(result); 
} 
コード例 #7
0
double NuclearDecay::meanFreePath(int id, double gamma) {
	if (not (isNucleus(id)))
		return std::numeric_limits<double>::max();

	int A = massNumber(id);
	int Z = chargeNumber(id);
	int N = A - Z;

	// check if particle can decay
	const std::vector<DecayMode> &decays = decayTable[Z * 31 + N];
	if (decays.size() == 0)
		return std::numeric_limits<double>::max();

	double totalRate = 0;

	for (size_t i = 0; i < decays.size(); i++) {
		double rate = decays[i].rate;
		rate /= gamma;
		totalRate += rate;
	}

	return 1. / totalRate;
}
コード例 #8
0
ファイル: OutputCRPropa2.cpp プロジェクト: msettimo/CRPropa3
void CRPropa2EventOutput1D::process(Candidate *c) const {
	if (not (c->hasProperty("Detected")))
		return;

	// remove flag so that the particle is not written to output again in the next step
	c->removeProperty("Detected");

	char buffer[256];
	size_t p = 0;

	p += sprintf(buffer + p, "%i ", convertToCRPropa2NucleusId(c->current.getId()));
	p += sprintf(buffer + p, "%.4f ", c->current.getEnergy() / EeV);
	double t = comoving2LightTravelDistance(c->getTrajectoryLength()) / Mpc;
	p += sprintf(buffer + p, "%.4f ", t);
	p += sprintf(buffer + p, "%i ", convertToCRPropa2NucleusId(c->source.getId()));
	p += sprintf(buffer + p, "%.4f\n", c->source.getEnergy() / EeV);

#pragma omp critical
	{
		outfile.write(buffer, p);
		outfile.flush();
	}
}
コード例 #9
0
ファイル: pruebas.cpp プロジェクト: FiubaDaniel/7506pontiac
int pruebaEstragiaCompresionAlmacenamiento1(char nombre_archivo[]){
	AtributoVariable<string> nombre("N");
	AtributoVariable<int> numeros("#");
	AtributoFijo<int> num("n");
	Registro registro(3,&nombre,&numeros,&num);
	Bloque bloque(&registro);
	Clave clave(&registro,1,"N");
	ComparadorRegistroVariable comparador;
	EstrategiaCompresion compresion;
	EABloques estrategia(&bloque,125,0.8f);
	estrategia.setClave(&clave);
	estrategia.setComparador(&comparador);
	Archivo archivo(&estrategia);
	/*archivo original*/
	archivo.crear(nombre_archivo);
	if(not compresion.descompresion(&archivo)){
		for(int i=0;i<5;i++){
			*(AtributoVariable<string>*)registro.get(0)=Terminos::obtenerTermino(i).c_str();
			((AtributoVariable<int>*)registro.get(1))->getVector().clear();
			for(int j=0;j< i%4+1;j++){
				((AtributoVariable<int>*)registro.get(1))->getVector().push_back(j);
			};
			*((AtributoFijo<int>*)registro.get(2))=i;
			if(not ((Almacenamiento&)archivo).insertar(&registro))
				cout<<"Problema"<<endl;
		}
		//archivo.imprimir(cout);
		compresion.compresion(&archivo,512);
		cout<<"/***************COMPRIMIENDO************************/"<<endl;
	}else{
		archivo.imprimir(cout);
		cout<<"/***************DESCOMPRIMIDO**********************/"<<endl;
	}
	archivo.cerrar();
	remove(nombre_archivo);
	return 0;
}
void Reservoir::normalize_to_echo() 
{
    double target = 1-m_EPSILON/2.;    // we will try to reach this rho in the effective matrix
    double rho_estimation = 100.0;       // initial rho estimation
    double h = m_DT/m_TAU;   // convenience decay constant
    mat I = eye(m_N,m_N);    // convenience identity matrix
    
    // first create a matrix of rho 1 based on 
    // alpha beta and gammma parameters
    m_w = randomize();
    m_w = normalize(m_w, 1.0);

    // evaluate the effective dynamical matrix
    mat e_w = h*rho_estimation*m_w + (1 - h)*I;
  
    // initial effective rho estimation
    double effective_rho_estimation = evaluate_rho(e_w); 

    // we try to reach the leaky echo-state condition
    while (   not (( (1-m_EPSILON) < effective_rho_estimation) and (effective_rho_estimation<1.0)) ) 
    {
        // evaluate the effective dynamical matrix
        e_w = h*rho_estimation*m_w + (1 - h)*I;
     
        // evaluate its spectral radius
        effective_rho_estimation = evaluate_rho(e_w);
      
        // update the real spectral radius based on 
        // the amount of distance to the leaky-echo-state condition
        rho_estimation += (1.0/h)*(target-effective_rho_estimation);
    }
 
    // finally modify the weight matrix to the 
    // converged spectral radius
    m_w = rho_estimation*m_G*m_w;
 
}
コード例 #11
0
float TeamInformation::getTimeToBall()
{
    float time = 600;
    
    Self& self = m_objects->self;
    MobileObject& ball = m_objects->mobileFieldObjects[FieldObjects::FO_BALL];
    float balldistance = ball.estimatedDistance();
    float ballbearing = ball.estimatedBearing();
    if (m_data->isIncapacitated())                                   // if we are incapacitated then we can't chase a ball
        return time;
    else if (m_player_number == 1 and balldistance > 150)            // goal keeper is a special case, don't chase balls too far away
        return time;
    else if (m_objects->mobileFieldObjects[FieldObjects::FO_BALL].TimeSinceLastSeen() < 5000)
    {   // if neither the ball or self are lost or if we can see the ball then we can chase.
        vector<float> walkspeed, maxspeed;
        bool walk_speed_good = m_data->get(NUSensorsData::MotionWalkSpeed, walkspeed);
        bool max_speed_good = m_data->get(NUSensorsData::MotionWalkMaxSpeed, maxspeed);

        // If walk speed is not available, then we may not be able to get to the ball.
        if(not (walk_speed_good and max_speed_good))
        {
            debug << "Warning: Walk values not available - walk_speed_good: " << walk_speed_good << " max_speed_good: " <<  max_speed_good << std::endl;
            return time;
        }

        // Add time for the movement to the ball
        time = balldistance/maxspeed[0] + fabs(ballbearing)/maxspeed[2];
        
        if (balldistance > 30)
        {   // Add time for the 'acceleration' from the current speed to the speed required to the ball
            time += 1.5*fabs(cos(ballbearing) - walkspeed[0]/maxspeed[0]) + 1.5*fabs(sin(ballbearing) - walkspeed[1]/maxspeed[1]) + 1.5*fabs(ballbearing - walkspeed[2]/maxspeed[2]);
        }
        if (self.lost())
            time += 3;
    }
    return time;
}
コード例 #12
0
// Hard classify each read using its responsibility
// read_id_[i] = -1 means the i-th read is classified as an outlier.
// read_id_[i] = 0 means the i-th read is classified as ref.
// read_id_[i] = 1 means the i-th read is classified as the variant allele 1, and so on.
void EnsembleEval::ApproximateHardClassifierForReads(){
	read_id_.clear();
	strand_id_.clear();
	dist_to_left_.clear();
	dist_to_right_.clear();

    read_id_.assign(read_stack.size(), -1);
	strand_id_.assign(read_stack.size(), false);
	dist_to_left_.assign(read_stack.size(), -1);
	dist_to_right_.assign(read_stack.size(), -1);

	int position0 = variant->position -1; // variant->position 1-base: vcflib/Variant.h

	for (unsigned int i_read = 0; i_read < read_stack.size(); ++i_read) {
		// compute read_id_
		if(allele_eval.total_theory.my_hypotheses[i_read].success){
	        read_id_[i_read] = allele_eval.total_theory.my_hypotheses[i_read].MostResponsible() - 1; // -1 = null, 0 = ref , ...
		}
		else{
	        read_id_[i_read] = -1; // failure = outlier
	    }

		// not an outlier
		if(read_id_[i_read] > -1){
		    //fprintf(stdout, "position0 =%d, read_stack[i_read]->align_start = %d, read_stack[i_read]->align_end = %d, read_stack[i_read]->left_sc = %d, read_stack[i_read]->right_sc = %d\n", (int)position0, (int)read_stack[i_read]->align_start, (int)read_stack[i_read]->align_end, (int)read_stack[i_read]->left_sc, (int)read_stack[i_read]->right_sc);
		    //fprintf(stdout, "dist_to_left[%d] = =%d, dist_to_right[%d] = %d\n", (int)i_read, (int)(position0 - read_stack[i_read]->align_start), (int)i_read, (int)(read_stack[i_read]->align_end - position0));
	        dist_to_left_[i_read] = position0 - read_stack[i_read]->align_start;
		    assert ( dist_to_left_[i_read] >=0 );
		    dist_to_right_[i_read] = read_stack[i_read]->align_end - position0;
		    assert ( dist_to_right_[i_read] >=0 );
	    }
	    //compute strand_id_
	    strand_id_[i_read] = not (read_stack[i_read]->is_reverse_strand);
	}

	is_hard_classification_for_reads_done_ = true;
}
コード例 #13
0
ファイル: ir-builder.cpp プロジェクト: Ronnrein/hhvm
SSATmp* IRBuilder::preOptimizeCheckType(IRInstruction* inst) {
  SSATmp* src  = inst->src(0);
  auto const oldType = src->type();
  auto const newType = inst->typeParam();

  if (oldType.not(newType)) {
    if (oldType.isBoxed() && newType.isBoxed()) {
      /* This CheckType serves to update the inner type hint for a boxed
       * value, which requires no runtime work.  This depends on the type being
       * boxed, and constraining it with DataTypeCountness will do it.  */
      constrainValue(src, DataTypeCountness);
      return gen(AssertType, newType, src);
    }
    /* This check will always fail. It's probably due to an incorrect
     * prediction. Generate a Jmp, and return src because
     * following instructions may depend on the output of CheckType
     * (they'll be DCEd later). Note that we can't use convertToJmp
     * because the return value isn't nullptr, so the original
     * instruction won't be inserted into the stream. */
    gen(Jmp, inst->taken());
    return src;
  }

  if (newType >= oldType) {
    /*
     * The type of the src is the same or more refined than type, so the guard
     * is unnecessary.
     */
    return src;
  }
  if (newType < oldType) {
    assert(!src->isConst());
    return nullptr;
  }

  return nullptr;
}
コード例 #14
0
ファイル: InteractiveTypeBox.cpp プロジェクト: SJasson/vle
bool InteractiveTypeBox::isValid()
{
    mState = false;
    if (mBase) {
        switch (mBase->getType()) {
        case vpz::Base::VLE_VPZ_CLASSES:
            mState = not (dynamic_cast< vpz::Classes* >(mBase))->exist(mEntry->get_text());
            break;
        case vpz::Base::VLE_VPZ_CONDITIONS:
            mState = not (dynamic_cast< vpz::Conditions* >(mBase))->exist(mEntry->get_text());
            break;
        case vpz::Base::VLE_VPZ_DYNAMICS:
            mState = not (dynamic_cast< vpz::Dynamics* >(mBase))->exist(mEntry->get_text());
            break;
        case vpz::Base::VLE_VPZ_OBSERVABLES:
            mState = not (dynamic_cast< vpz::Observables* >(mBase))->exist(mEntry->get_text());
            break;
        case vpz::Base::VLE_VPZ_OUTPUTS:
            mState = not (dynamic_cast< vpz::Outputs* >(mBase))->exist(mEntry->get_text());
            break;
        case vpz::Base::VLE_VPZ_VIEWS:
            mState = not (dynamic_cast< vpz::Views* >(mBase))->exist(mEntry->get_text());
            break;
        default:
            Error(_("Unknown argument type."));
            return false;
        }
    } else {
        mState = not mCoupledModel->exist(mEntry->get_text());
    }

    if (mState && not (mEntry->get_text().empty())) {
        mImage.set(Gtk::StockID(Gtk::Stock::YES), Gtk::IconSize(1));
        return true;
    } else {
        mImage.set(Gtk::StockID(Gtk::Stock::NO), Gtk::IconSize(1));
        return false;
    }
}
コード例 #15
0
//calculates the scheme
vector<gate> scheme::calc(vector<int>& v)
{
	list<gate>::iterator LIter;
	vector<int>::iterator VIter = v.begin();
	vector<gate> vg; 

	for( LIter = sch[0].begin(); LIter != sch[0].end(); LIter++ )
	{
		(*LIter).val = (*VIter); 
		VIter++;
	}

	for(int i=1;i<sch.size();i++)
	{
		for( LIter = sch[i].begin(); LIter != sch[i].end(); LIter++ )
		{
			//here smth happens with current gate - (*LIter)
			int d1 = (*this).find((*LIter).dep1);
			int d2 = -1;
			if((*LIter).dep2 != 0) d2 = (*this).find((*LIter).dep2);
			
			//cout << (*LIter).id << " " << d1 << " " << d2 << endl;

			switch ((*LIter).type)
			{
			case '&': (*LIter).val = min(d1, d2); break;
		    case '|': (*LIter).val = max(d1, d2); break;
			case '~': (*LIter).val = not(d1); break;	
			case '<': (*LIter).val = d1; vg.push_back(*LIter); break;
			default : (*LIter).val = -1; break;
	        }
		}
    }

	return(vg);
}
コード例 #16
0
ファイル: wvrgcalfeedback.cpp プロジェクト: keflavich/casa
  AntITable::AntITable(const aname_t &names,
		       const LibAIR2::AntSet &flag,
                       const LibAIR2::AntSet &nowvr,                       
		       const std::vector<double> &rms,
		       const std::vector<double> &disc,
		       const LibAIR2::AntSet &interpolImpossibleAnts)
  {
    for(aname_t::const_iterator i=names.begin(); i !=names.end(); ++i)
    {
      AntennaInfo x;
      x.no= i->first;
      x.name= i->second;
      x.haswvr=(not (nowvr.count(x.no)));
      x.flag=flag.count(x.no);
      x.pathRMS=rms[x.no];
      x.pathDisc=disc[x.no];
      if((x.flag>0) && (interpolImpossibleAnts.count(x.no)>0))
      {
	x.pathRMS = 0.;
	x.pathDisc = 0.;
      }
      push_back(x);
    }
  }
コード例 #17
0
ファイル: producer.cpp プロジェクト: franciscod/openage
std::unique_ptr<UnitProducer> ProducerLoader::load_living(const gamedata::unit_living &unit) {

	// find and load graphics
	auto tex_die    = this->main->find_graphic(unit.graphic_dying0);
	auto tex_stand  = this->main->find_graphic(unit.graphic_standing0);
	auto tex_walk   = this->main->find_graphic(unit.walking_graphics0);
	auto tex_attack = this->main->find_graphic(unit.attack_graphic);

	// check graphics exist
	if (not (tex_die && tex_stand && tex_walk && tex_attack)) {
		return nullptr;
	}

	// get required sounds
	TestSound *snd_create  = this->main->find_sound(unit.sound_creation0);
	TestSound *snd_destroy = this->main->find_sound(unit.sound_dying);
	TestSound *snd_move    = this->main->find_sound(unit.move_sound);

	return util::make_unique<UnitTypeTest>(
		&unit,
		tex_die, tex_stand, tex_walk, tex_attack,
		snd_create, snd_destroy, snd_move, snd_move
	);
}
コード例 #18
0
ファイル: cubeAdapter.cpp プロジェクト: 400dama/USD
void 
UsdImagingCubeAdapter::TrackVariability(UsdPrim const& prim,
                                        SdfPath const& cachePath,
                                        int requestedBits,
                                        int* dirtyBits,
                                        UsdImagingInstancerContext const* 
                                            instancerContext)
{
    BaseAdapter::TrackVariability(
        prim, cachePath, requestedBits, dirtyBits, instancerContext);
    // WARNING: This method is executed from multiple threads, the value cache
    // has been carefully pre-populated to avoid mutating the underlying
    // container during update.
    
    UsdTimeCode time(1.0);
    if (requestedBits & HdChangeTracker::DirtyTransform) {
        if (not (*dirtyBits & HdChangeTracker::DirtyTransform)) {
            _IsVarying(prim, UsdGeomTokens->size,
                          HdChangeTracker::DirtyTransform,
                          UsdImagingTokens->usdVaryingXform,
                          dirtyBits, /*inherited*/false);
        }
    }
}
コード例 #19
0
ファイル: pratica2-2.c プロジェクト: akira2nd/CODES
int snprimos(int n)
{
	int d=2,num=2,soma=0,cont=1;
	while(n!=0)
	{
		if(d != num && not(num%d))
		{
			d = 2;
			num++;
		}
		else if (d==num)
		{
			printf("%d", num);
			soma += num; 
			num ++;
			d = 2;
			n--;
			if(n!=0){printf(" + ");}
			else{printf(" = ");}
		}
		else if (num%d){d++;}
	}
	return soma;
}
コード例 #20
0
ファイル: lexer.cpp プロジェクト: yonn/metal-lang
	bool is_number_token(const std::string& token)
	{
		bool period = false;
		bool hex = false;

		if (token.size() >= 2 and token[0] == '0' and (token[1] == 'x' or token[1] == 'X')) hex = true;

		for (size_t i = 0; i < token.size(); i++) {
			auto c = token[i];

			if (hex) {
				if (i < 3) continue;
				if (is_hex_digit(c)) continue;
			}
			
			if (c == '.' and not period) {
				period = true;
				continue;	
			} else if (not is_number(c) and not (c == '_')) {
				return false;
			}
		}
		return true;
	}
コード例 #21
0
ファイル: CvarSystem.cpp プロジェクト: Kangz/Unvanquished
void InternalSetValue(const std::string& cvarName, std::string value, int flags, bool rom, bool warnRom) {
    CvarMap& cvars = GetCvarMap();

    auto it = cvars.find(cvarName);
    // TODO: rom means the cvar should have been created before?
    if (it == cvars.end()) {
        if (!Cmd::IsValidCvarName(cvarName)) {
            Com_Printf("Invalid cvar name '%s'", cvarName.c_str());
            return;
        }

        // The user creates a new cvar through a command.
        cvarRecord_t cvar{
                value, value, flags | CVAR_USER_CREATED, "user created", nullptr, {}};
        cvars[cvarName] = new cvarRecord_t(std::move(cvar));
        Cmd::AddCommand(cvarName, cvarCommand, "cvar - user created");
        GetCCvar(cvarName, *cvars[cvarName]);

    } else {
        cvarRecord_t* cvar = it->second;

        if (not(cvar->flags & CVAR_USER_CREATED)) {
            if (cvar->flags & (CVAR_ROM | CVAR_INIT) and not rom) {
                Com_Printf("%s is read only.\n", cvarName.c_str());
                return;
            }

            if (rom and warnRom and not(cvar->flags & (CVAR_ROM | CVAR_INIT))) {
                Com_Printf("SetValueROM called on non-ROM cvar '%s'\n",
                           cvarName.c_str());
            }

            if (not cheatsAllowed && cvar->flags & CHEAT) {
                Com_Printf("%s is cheat-protected.\n", cvarName.c_str());
                return;
            }
        }

        std::string oldValue = std::move(cvar->value);
        cvar->value = std::move(value);
        cvar->flags |= flags;

        // mark for archival if flagged as archive-on-change
        if (cvar->flags & ARCHIVE) {
            cvar->flags |= USER_ARCHIVE;
        }

        if (cvar->proxy) {
            // Tell the cvar proxy about the new value
            OnValueChangedResult result = cvar->proxy->OnValueChanged(cvar->value);

            if (result.success) {
                ChangeCvarDescription(cvarName, cvar, result.description);
            } else {
                // The proxy could not parse the value, rollback
                Com_Printf("Value '%s' is not valid for cvar %s: %s\n",
                           cvar->value.c_str(),
                           cvarName.c_str(),
                           result.description.c_str());
                cvar->value = std::move(oldValue);
            }
        }
        SetCCvar(*cvar);
    }
}
コード例 #22
0
ファイル: value.cpp プロジェクト: 400dama/USD
bool
JsValue::operator!=(const JsValue& other) const
{
    return not (*this == other);
}
コード例 #23
0
ファイル: disassemble.hpp プロジェクト: h0wl/baresifter
inline bool operator!=(decoded_instruction const &a, decoded_instruction const &b)
{
  return not (a == b);
}
コード例 #24
0
ファイル: daybooksubs3.cpp プロジェクト: exodusdb/exodusdb
function main(in mode) {
	//seems to be used only for VAL.PERIOD and RAISEUNPOSTEDMINIMUM
	//garbagecollect;
	//y2k2
	// daybook batch header validation and interface routines

	interactive = not SYSTEM.a(33);

	//equ printtypes to register(10)<3>
	//equ tstore2 to register(10)<4>

	//removed so we can call raise.unposted.minimum without setting @id
	//t=field(@id,'*',1)
	//IF t NE CURR.COMPANY THEN
	// IF t THEN
	// *CURR.COMPANY=t
	// CALL INIT.COMPANY(t)
	// if interactive then
	// MSG='YOU HAVE JUST CHANGED BACK TO ':QUOTE(CURR.COMPANY):' COMPANY'
	// GOSUB NOTE3
	// end
	// END
	// END

	win.redisplaylist = "";
	var tt = "";
	//do not set valid because valid used in prewrite to indicate failed
	//valid=1

	//none used from web
	if (mode eq "DEF.BATCH.REF") {

		if (not(win.wlocked or RECORD)) {
			if (not(ID.field("*", 1))) {
				ID = ID.fieldstore("*", 1, 1, fin.currcompany);
			}
			if (not(ID.field("*", 2))) {
				ID = ID.fieldstore("*", 2, 1, win.registerx(10).a(1));
			}

			tt = ":%" ^ ID.field("*", 1, 2) ^ "%:BATCHES:" ^ ID.field("*", 1, 2) ^ "*";
			//eg t=":%H*INV%:BATCHES:H*INV*"

			tt = nextkey(tt, "");

			ID = tt;
			win.isdflt = tt.field("*", 3);
			ANS = "";
		}
		win.registerx(4) = win.isdflt;

/*
	/////////////
} else if (mode eq "F2.BATCH.REF") {
	/////////////
	gosub keychange();
	if (not win.valid) {
		return 0;
	}

	if (authorised("JOURNAL ACCESS POSTED", msg, "")) {
		if (not(decide("", "Posted batches" _VM_ "Unposted batches", reply))) {
			return 0;
		}
	}else{
		reply = 2;
	}
	if (reply == 1) {
		suffix = "";
	}else{
		suffix = "*U";
	}

	var refs = getbatchcodes(fin.currcompany, win.registerx(10).a(1), suffix, fin.batches);
	if (not refs) {
		msg = "No batches found";
		goto invalid2;
	}

	//select a batch
	if (suffix) {
		temp = "Entered by";
	}else{
		temp = "Posted By";
	}
	var params = "BATCH_REFERENCE:5:R::Batch\\FIRST_VOUCHER:10:R::1st Vouch.\\CONTRA_ACCOUNT_NAME:30:::First account\\WHO:10:::" ^ temp ^ "\\23:7:R:[ADDCENT]:Period\\ACTION:1:::";
	tt = "Which batch(es) do you want ?";
	if (suffix) {
		tt ^= "|(unposted batches)";
	}
	ANS = pop_up(0, 0, "@BATCHES", refs, params, "T", "1", tt, "", "", "", "K");
	if (not ANS) {
		return 0;
	}
	ANS.converter(FM, VM);
	if (ANS.index(VM, 1)) {
		while (true) {
		///BREAK;
		if (not(ANS.index(VM ^ VM, 1))) break;;
			ANS.swapper(VM ^ VM, VM);
		}//loop;
		win.newbrowse = 1;
		ANS.transfer(win.browsenext);
		win.reset = 4;
	}
	ANS = ANS.field("*", 3);

	//force prefix into @ID
	if (suffix) {
		ID = ID.fieldstore("*", 4, 1, suffix[2]);
	}

	DATA ^= "" "\r";

	return 0;
}

	//////////////
valbatchref:
	//////////////
	gosub EOF_516();
	if (not win.valid) {
		return;
	}
	if (win.is ne win.registerx(4) and win.is ne win.isorig) {

		gosub keychange();
		if (not win.valid) {
			return;
		}

		//query by voucher number
		if (win.is[1] == "V") {
			if (not(win.is.readv(fin.vouchers, ID.field("*", 2) ^ "*" ^ win.is.substr(2, 99) ^ "*" ^ fin.currcompany, 12))) {
				{}
			}
		}

		suffix = "";
		if (var(".U").index(win.is[1], 1)) {
			suffix = "*U";
			win.is.splicer(1, 1, "");
		}
		if (not(tt.read(win.srcfile, ID.fieldstore("*", 3, 1, win.is) ^ suffix))) {
			msg = DQ ^ (win.is ^ DQ) ^ " " "NO SUCH BATCH - IF YOU WANT TO START A|NEW BATCH JUST PRESS [Enter]";
			win.is = "";
			gosub invalid2();
			win.reset = 4;
			return;
		}
		if (suffix) {
			ID = ID.fieldstore("*", 4, 1, "U");
		}

		//check allowed access to posted batches
		if (not(ID.field("*", 4))) {
			if (not(authorised("JOURNAL ACCESS POSTED BATCHES", msg, ""))) {
				goto invalid2;
			}
		}

		//check if own batch
		if (not(tt.locate(USERNAME, temp, 25))) {
			if (not(authorised("JOURNAL ACCESS OTHER PEOPLES", msg, ""))) {
				win.is = "";
				goto invalid2;
			}
		}

	}
	return;

} else if (mode eq "DEF.PERIOD") {

	win.isdflt = fin.currperiod ^ "/" ^ addcent(fin.curryear);

*/


	} else if (mode eq "VAL.PERIOD") {

		//also used by REVERSALS and REVAL
		win.isdflt = "";
		if (not win.is) {
			return 0 ;
		}
		if (win.is == win.isorig) {
			return 0 ;
		}

		//no leading zero
		if (win.is[1] == "0") {
			win.is.splicer(1, 1, "");
		}

		//add current year
		win.is.converter(" ", "/");
		tt = win.is.field("/", 2);
		if (tt == "") {
			if (win.is > fin.currperiod) {
				tt = (addcent(fin.curryear - 1)).oconv("R(0)#2");
			}else{
				tt = fin.curryear;
			}
			win.is = win.is.fieldstore("/", 2, 1, tt);
		}else{
			win.is = win.is.fieldstore("/", 2, 1, var("00" ^ tt).substr(-2, 2));
		}

		//check period
		//var isperiod = win.is;
		gosub chkperiod(win.is);
		if (not win.valid)
			return 0;


	} else if (mode.field(".", 1) eq "TRACE") {

		var action = mode.field(".", 2);
		if (action == "A" and authorised("JOURNAL REPOST WITHOUT RECORD", msg, "NEOSYS")) {
			return 0;
		}
		RECORD.inserter(24, 1, action);
		RECORD.inserter(25, 1, USERNAME);
		//R=INSERT(R,26,1,0,ICONV(DATE(),'HEX'))
		RECORD.inserter(26, 1, var().date());
		RECORD.inserter(27, 1, var().time());


	} else if (mode.field("*", 1) == "RAISE.UNPOSTED.MINIMUM") {
		raisebatchtype = mode.field("*", 2);
		if (not raisebatchtype) {
			raisebatchtype = win.registerx(10).a(1);
		}

		//if this is the lowest batch number then update the minimum batch number
		var seqkey = "%" ^ fin.currcompany ^ "*" ^ raisebatchtype ^ "*U%";
		var min,max;
		if (min.read(fin.batches, seqkey ^ "*")) {
			min = min.a(1);
			if (min == ID.field("*", 3)) {
				if (max.read(fin.batches, seqkey)) {
					max = max.a(1);
				} else {
					max = min;
				}
				//go from minimum+1 to maximum but stopping at any existing batch;
				for (var min = 1; min <= max; ++min) {
					if (not(tt.read(fin.batches, fin.currcompany ^ "*" ^ raisebatchtype ^ "*" ^ min ^ "*U"))) {
						tt = "";
					}
					///BREAK;
					if (tt)
						break;;
				};//min;
			}
			if (min > max) {
				min = max;
			}
			min.writev(fin.batches, seqkey ^ "*", 1);
		}

	} else {
		//unknown mode
		msg = "SYSTEM ERROR IN DAYBOOK.SUBS3|INVALID MODE " ^ (DQ ^ (mode ^ DQ)) ^ " IGNORED";
		//goto note3;
		return invalid(msg);
	}

	return 0;

}
コード例 #25
0
ファイル: type.cpp プロジェクト: skynet/hhvm
TEST(Type, Const) {
  auto five = Type::cns(5);
  EXPECT_LT(five, Type::Int);
  EXPECT_NE(five, Type::Int);
  EXPECT_TRUE(five.isConst());
  EXPECT_EQ(5, five.intVal());
  EXPECT_TRUE(five.isConst(Type::Int));
  EXPECT_TRUE(five.isConst(5));
  EXPECT_FALSE(five.isConst(5.0));
  EXPECT_TRUE(Type::Gen.maybe(five));
  EXPECT_EQ(Type::Int, five | Type::Int);
  EXPECT_EQ(Type::Int, five | Type::cns(10));
  EXPECT_EQ(five, five | Type::cns(5));
  EXPECT_EQ(five, Type::cns(5) & five);
  EXPECT_EQ(five, five & Type::Int);
  EXPECT_EQ(five, Type::Gen & five);
  EXPECT_EQ("Int<5>", five.toString());
  EXPECT_EQ(five, five - Type::Arr);
  EXPECT_EQ(five, five - Type::cns(1));
  EXPECT_EQ(Type::Int, Type::Int - five); // conservative
  EXPECT_EQ(Type::Bottom, five - Type::Int);
  EXPECT_EQ(Type::Bottom, five - five);
  EXPECT_EQ(Type::PtrToGen,
            (Type::PtrToGen|Type::Nullptr) - Type::Nullptr);
  EXPECT_EQ(Type::Int, five.dropConstVal());
  EXPECT_TRUE(five.not(Type::cns(2)));

  auto True = Type::cns(true);
  EXPECT_EQ("Bool<true>", True.toString());
  EXPECT_LT(True, Type::Bool);
  EXPECT_NE(True, Type::Bool);
  EXPECT_TRUE(True.isConst());
  EXPECT_EQ(true, True.boolVal());
  EXPECT_TRUE(Type::Uncounted.maybe(True));
  EXPECT_FALSE(five <= True);
  EXPECT_FALSE(five > True);

  EXPECT_TRUE(five.not(True));
  EXPECT_EQ(Type::Int | Type::Bool, five | True);
  EXPECT_EQ(Type::Bottom, five & True);

  EXPECT_TRUE(Type::Uninit.isConst());
  EXPECT_TRUE(Type::InitNull.isConst());
  EXPECT_FALSE(Type::Null.isConst());
  EXPECT_FALSE((Type::Uninit | Type::Bool).isConst());
  EXPECT_FALSE(Type::Int.isConst());

  auto array = make_packed_array(1, 2, 3, 4);
  auto arrData = ArrayData::GetScalarArray(array.get());
  auto constArray = Type::cns(arrData);
  auto packedArray = Type::Arr.specialize(ArrayData::kPackedKind);
  auto mixedArray = Type::Arr.specialize(ArrayData::kMixedKind);

  EXPECT_TRUE(constArray <= packedArray);
  EXPECT_TRUE(constArray < packedArray);
  EXPECT_FALSE(packedArray <= constArray);
  EXPECT_TRUE(constArray <= constArray);
  EXPECT_FALSE(packedArray <= mixedArray);
  EXPECT_FALSE(mixedArray <= packedArray);
  EXPECT_FALSE(constArray <= mixedArray);
  EXPECT_EQ(constArray, constArray & packedArray);

  ArrayTypeTable::Builder ratBuilder;
  auto rat1 = ratBuilder.packedn(RepoAuthType::Array::Empty::No,
                                 RepoAuthType(RepoAuthType::Tag::Str));
  auto ratArray1 = Type::Arr.specialize(rat1);
  auto rat2 = ratBuilder.packedn(RepoAuthType::Array::Empty::No,
                                 RepoAuthType(RepoAuthType::Tag::Int));
  auto ratArray2 = Type::Arr.specialize(rat2);
  EXPECT_EQ(Type::Arr, ratArray1 & ratArray2);
  EXPECT_TRUE(ratArray1 < Type::Arr);
  EXPECT_TRUE(ratArray1 <= ratArray1);
  EXPECT_TRUE(ratArray1 < (Type::Arr|Type::Obj));
  EXPECT_FALSE(ratArray1 < ratArray2);
  EXPECT_NE(ratArray1, ratArray2);

  auto packedRat = packedArray & ratArray1;
  EXPECT_EQ("Arr=PackedKind:N([Str])", packedRat.toString());
  EXPECT_TRUE(packedRat <= packedArray);
  EXPECT_TRUE(packedRat < packedArray);
  EXPECT_TRUE(packedRat <= ratArray1);
  EXPECT_TRUE(packedRat < ratArray1);
  EXPECT_EQ(packedRat, packedRat & packedArray);
  EXPECT_EQ(packedRat, packedRat & ratArray1);
}
コード例 #26
0
bool Point::operator !=(const Point &P) {
    return not ((fabs(x - P.x) < EPSILON) and (fabs(y - P.y) < EPSILON));
}
コード例 #27
0
// ------------------------------------------------------------------------------
//   STARTUP
// ------------------------------------------------------------------------------
void
Autopilot_Interface::
start()
{
	int result;

	// --------------------------------------------------------------------------
	//   CHECK SERIAL PORT
	// --------------------------------------------------------------------------

	if ( serial_port->status != 1 ) // SERIAL_PORT_OPEN
	{
		fprintf(stderr,"ERROR: serial port not open\n");
		throw 1;
	}
	//--------------------
	// 	LISTEN_KEYBOARD
	//--------------------
	printf("START LISTEN KEYBOARD THREAD \n");
	result = pthread_create(&listen_tid,NULL,&start_autopilot_interface_listen_thread, this);
	if (result) throw result;
	printf("\n");
	// --------------------------------------------------------------------------
	//   READ THREAD
	// --------------------------------------------------------------------------

	printf("START READ THREAD \n");

	result = pthread_create( &read_tid, NULL, &start_autopilot_interface_read_thread, this );
	if ( result ) throw result;

	// now we're reading messages
	printf("\n");


	// --------------------------------------------------------------------------
	//   CHECK FOR MESSAGES
	// --------------------------------------------------------------------------

	printf("CHECK FOR MESSAGES\n");

	while ( not current_messages.sysid )
	{
		if ( time_to_exit )
			return;
		usleep(500000); // check at 2Hz
	}

	printf("Found\n");

	// now we know autopilot is sending messages
	printf("\n");


	// --------------------------------------------------------------------------
	//   GET SYSTEM and COMPONENT IDs
	// --------------------------------------------------------------------------

	// This comes from the heartbeat, which in theory should only come from
	// the autopilot we're directly connected to it.  If there is more than one
	// vehicle then we can't expect to discover id's like this.
	// In which case set the id's manually.

	// System ID
	if ( not system_id )
	{
		system_id = current_messages.sysid;
		printf("GOT VEHICLE SYSTEM ID: %i\n", system_id );
	}

	// Component ID
	if ( not autopilot_id )
	{
		autopilot_id = current_messages.compid;
		printf("GOT AUTOPILOT COMPONENT ID: %i\n", autopilot_id);
		printf("\n");
	}


	// --------------------------------------------------------------------------
	//   GET INITIAL POSITION
	// --------------------------------------------------------------------------

	// Wait for initial position ned
	while ( not ( current_messages.time_stamps.local_position_ned &&
				  current_messages.time_stamps.attitude            )  )
	{
		if ( time_to_exit )
			return;
		usleep(500000);
	}

	// copy initial position ned
	Mavlink_Messages local_data = current_messages;
	initial_position.x        = local_data.local_position_ned.x;
	initial_position.y        = local_data.local_position_ned.y;
	initial_position.z        = local_data.local_position_ned.z;
	initial_position.vx       = local_data.local_position_ned.vx;
	initial_position.vy       = local_data.local_position_ned.vy;
	initial_position.vz       = local_data.local_position_ned.vz;
	initial_position.yaw      = local_data.attitude.yaw;
	initial_position.yaw_rate = local_data.attitude.yawspeed;

	printf("INITIAL POSITION XYZ = [ %.4f , %.4f , %.4f ] \n", initial_position.x, initial_position.y, initial_position.z);
	printf("INITIAL POSITION YAW = %.4f \n", initial_position.yaw);
	printf("\n");

	// we need this before starting the write thread


	// --------------------------------------------------------------------------
	//   WRITE THREAD
	// --------------------------------------------------------------------------
	printf("START WRITE THREAD \n");

	result = pthread_create( &write_tid, NULL, &start_autopilot_interface_write_thread, this );
	if ( result ) throw result;

	// wait for it to be started
	while ( not writing_status )
		usleep(100000); // 10Hz

	// now we're streaming setpoint commands
	printf("\n");


	// Done!
	return;

}
コード例 #28
0
ファイル: Utils.hpp プロジェクト: dmlys/QtTools
	/// возвращает color group по QStyleOption
	inline QPalette::ColorGroup ColorGroup(const QStyleOption & opt) noexcept
	{
		return not (opt.state & QStyle::State_Enabled) ? QPalette::Disabled :
		       not (opt.state & QStyle::State_Active)  ? QPalette::Inactive
		                                               : QPalette::Normal;
	}
コード例 #29
0
ファイル: .snippets.cpp プロジェクト: petersn/path-tracing
bool kdTreeNode::split_triangle(int split_axis, Real split_height, int triangle_index, Triangle tri, vector<int>* low_side_sorted, vector<int>* high_side_sorted, map<int, pair<vector<int>, vector<int>>>& split_table, vector<Triangle>* all_triangles) {
	assert(false); // XXX: I should never subdivide in this attempt.
	// Check if the triangle is in the split table.
	if (split_table.count(triangle_index) != 0) {
		// If so, just write out the cached values.
		pair<vector<int>, vector<int>>& p = split_table[triangle_index];
		vector<int>& add_to_low_side = p.first;
		vector<int>& add_to_high_side = p.second;
		// Add the already-split triangle indices to the low and high sides respectively.
		for_each(add_to_low_side.begin(), add_to_low_side.end(), [low_side_sorted](int& index){ low_side_sorted->push_back(index); });
		for_each(add_to_high_side.begin(), add_to_high_side.end(), [high_side_sorted](int& index){ high_side_sorted->push_back(index); });
		// Return false to indicate that we added no extra geometry to al_triangles.
		return false;
	}
	// Now we must figure out how to split this triangle.
	bool on_low_side[3];
	for (int i = 0; i < 3; i++)
		on_low_side[i] = tri.points[i](split_axis) <= split_height;
	// It should be the case that exactly one or two of the points are on the low side.
	// If not, then clearly the splitting plane doesn't actually intersect this triangle.
	int count_on_low_side = on_low_side[0] + on_low_side[1] + on_low_side[2];
	// XXX: Temporarily, for debugging, skip guys that aren't hit.
	if (not (count_on_low_side == 1 or count_on_low_side == 2))
		return false;
	assert(count_on_low_side == 1 or count_on_low_side == 2); // split_triangle called on non-intersected triangle!
	// Find the point that is all by itself on its side of the splitting plane,
	// and the two "popular points" that are together on the other side.
	Vec lonely;
	Vec popular[2];
	int next_popular = 0;
	bool lonely_on_low_side = count_on_low_side == 1;
	// TODO: I really need to make it the case that lonely, popular[0], popular[1] maintains the order of points[0], points[1], points[2] to preserve normals.
	for (int i = 0; i < 3; i++) {
		if (on_low_side[i] == lonely_on_low_side)
			lonely = tri.points[i];
		else
			popular[next_popular++] = tri.points[i];
	}
	assert(next_popular == 2); // Some dumb bug in the above loop logic.
	// Find the intersection of the line segments lonely <-> popular[0] and lonely <-> popular[1] with the splitting plane.
	Vec hits[2];
	for (int i = 0; i < 2; i++) {
		Vec direction = popular[i] - lonely;
		Real approach_rate = direction(split_axis);
		Real height_to_hit = split_height - lonely(split_axis);
		hits[i] = lonely + direction * (height_to_hit / approach_rate);
		// Do a quick sanity check of this hit.
		Real hit_error = hits[i](split_axis) - split_height;
		assert(fabsf(hit_error) < 1e-5); // Split sanity check failure. Maybe the geometry is very close to degenerate, or huge?
	}
	//cout << "Did a split!" << endl;
	// Grab the current length of all_triangles, because that's the next index we'll get upon inserting.
	unsigned int next_index = all_triangles->size();
	// Add new triangles.
	// TODO: XXX: Think carefully about the normals and triangle ordering in this case!
	// I think I got it right for these three triangles, assuming the above code gives lonely, popular[0], popular[1] in the right order.
	// Build the one triangle on the lonely side of the split.
	Triangle t1, t2, t3;
	all_triangles->push_back(t1 = Triangle(lonely, hits[0], hits[1]));
	// Build the two triangles on the popular side of the split.
	all_triangles->push_back(t2 = Triangle(hits[0], popular[0], hits[1]));
	all_triangles->push_back(t3 = Triangle(hits[1], popular[0], popular[1]));
	// Insert appropriate indices into the high and low side lists, and make a split_table entry noting that this was done.
	pair<vector<int>, vector<int>>& table_entry = split_table[triangle_index];
	if (lonely_on_low_side) {
		// I'm going to check that 
		//assert(t1.
		// XXX: TODO: Why isn't this causing sorting issues?
		// I'm not being particularly careful that I'm inserting these triangles in an order that maintains the invariant
		// that high_side_sorted is actually sorted by AABB maxima along split_axis...
		// I probably need to add a check to see if I should insert next_index+1 then next_index+2 or the other way around.
		// What's most bizarre to me is that my lack of carefulness isn't causing an assertion failure over at the first few
		// lines of kdTreeNode::kdTreeNode(), when I check this sortedness invariant.
		low_side_sorted->push_back(next_index);
		high_side_sorted->push_back(next_index+1);
		high_side_sorted->push_back(next_index+2);
		// The convention is that table_entry.first is the folks pushed into low_side_sorted, and table_entry.second is into high_side_sorted.
		table_entry.first.push_back(next_index);
		table_entry.second.push_back(next_index+1);
		table_entry.second.push_back(next_index+2);
	} else {
		// Everything here is the same as above, only the lonely node is on the high side.
		high_side_sorted->push_back(next_index);
		low_side_sorted->push_back(next_index+1);
		low_side_sorted->push_back(next_index+2);
		table_entry.second.push_back(next_index);
		table_entry.first.push_back(next_index+1);
		table_entry.first.push_back(next_index+2);
	}
	// We must access this triangle via all_triangles, rather than a pointer or a reference because vectors can reallocate on us.
	(*all_triangles)[triangle_index].from_split = true;
	// Indicate that we did make new geometry.
	return true;
}
コード例 #30
0
ファイル: Squad.cpp プロジェクト: talentlesshack/C2P2
Goal_Result Squad::Send_Troops_To_Rally
(
	AiMain *ai,							
	int last_agent,						
	int first_agent,					
	MapPointData &rally_pos,			
	ArmyGoal *the_goal					
)
{
	
	sint32 army_idx;					
	double utility;						
    Agent *agent=NULL;					
	ArmyAgent * the_army;				
	AGENT_STATE army_state;				
	MapPointData agent_pos;				
	
    
    BOOL revealed_unexplored = FALSE; 
    BOOL did_move = FALSE; 
    BOOL redo_explore = FALSE; 
    BOOL use_marked=FALSE;
    BOOL revealed_forign_units = FALSE; 
	sint32 first_one_there = -1;		
										
	BOOL is_unknown_id;					
	Goal_Result result = GOAL_COMPLETE; 
	

#ifdef DBGAILOG
	#ifdef LOG_SQUADS
	if (ai->AI_VERBOSITY >= LOG_PAINFUL_DETAILS)
		AILOG((wstr, "Squad::Send_Troops_To_Rally: Entering\n"));
	#endif
#endif DBGAILOG
	
	
	

	
	utility = the_goal->Compute_Raw_Priority(ai);

	
	army_idx = last_agent;

	
	
#ifdef _DEBUG
    sint32 finite_loop=0; 
#endif

    
    

	
	while (army_idx > first_agent)
	{
Assert(++finite_loop < 100000); 
		
		agent = (Agent *) my_agents.Return_Data_By_Number( army_idx );

		
		switch(agent->GetType())
		{
		
		case AGENT_TYPE_CITY:
			
			break;

		
		case AGENT_TYPE_ARMY:
			
			the_army = (ArmyAgent *) agent;

			
			
			
			the_army->GetPos(ai, agent_pos);

			
			army_state = the_army->GetState();

			
			if (not (
					(rally_pos.x is agent_pos.x) and
					(rally_pos.y is agent_pos.y) and
					(rally_pos.z is agent_pos.z) 
					))
			{
				
				the_goal->GotoTaskSolution(ai, 
					army_idx, the_army, 
					0, NULL, 
					rally_pos, SUB_TASK_RALLYING);
				
				
				if (ai->m_i_am_dead || the_goal->Get_Totally_Complete(ai)) 
				{ 
					
					return GOAL_COMPLETE; 
				} 



























			} 
			
			
			
			
			the_army->GetPos(ai, agent_pos);

			
			if ((
				(rally_pos.x is agent_pos.x) and
				(rally_pos.y is agent_pos.y) and
				(rally_pos.z is agent_pos.z) 
				))
			{
				
				if (first_one_there isnt -1)
				{
					
					Remove_Agent(the_army);

					
					
					
					ai->m_player->ArmyGroup(
						agent->GetID().GetVal(), 
						first_one_there, 
						&is_unknown_id
						);

					
					Assert(is_unknown_id == FALSE);

				} 
				
				else
				{
					first_one_there = agent->GetID().GetVal();
				} 

			} 
			else
				result = GOAL_IN_PROGRESS; 

			break;

		
		default:
			Assert(FALSE);
			break;
		} 

		
		army_idx--;

	} 

#ifdef DBGAILOG
	#ifdef LOG_SQUADS
	if (ai->AI_VERBOSITY >= LOG_PAINFUL_DETAILS)
		AILOG((wstr, "Squad::Send_Troops_To_Rally: Exiting\n"));
	#endif
#endif DBGAILOG

    return result;
	
}