Beispiel #1
0
void Cloud::update() {
	switch (state) {
		case 1:	//delay and cw
			if (millis () - startTime > _delayTime ) {
				cw ();
				state = 2;
				startTime = millis();
			}
			break;
		case 2:	//check left
			if (digitalRead (_limitPinL) == 0 || (millis () - startTime > 8000) ) {
				stop();
				state = 3;
				startTime = millis();
			}
			break;
		case 3:	//delay and ccw
			if (millis () - startTime > _delayTime ) {
				state = 4;
				ccw ();
				startTime = millis();
			}
			break;
		case 4:	//check right
			if (digitalRead (_limitPinR) == 0 || (millis () - startTime > 8000) ) {
				stop ();
				state = 1;
				startTime = millis();
			}
			break;

	}
}
Beispiel #2
0
void Foam::CV2D::fast_restore_Delaunay(Vertex_handle vh)
{
    int i;
    Face_handle f = vh->face(), next, start(f);

    do
    {
        i=f->index(vh);
        if (!is_infinite(f))
        {
            if (!internal_flip(f, cw(i))) external_flip(f, i);
            if (f->neighbor(i) == start) start = f;
        }
        f = f->neighbor(cw(i));
    } while (f != start);
}
Beispiel #3
0
Event::CW&
Event::getCW() {
  typedef typename v8::juice::convert::MemFuncInvocationCallbackCreator<Event> ICM;
  CW & cw( CW::Instance() );
  
  if( cw.IsSealed() )
  {
      return cw;
  }
  
  cw.BindGetter<bool,&Event::bubbles>( "bubbles" );
  cw.BindGetter<bool,&Event::cancelable>( "cancelable" );
  cw.BindGetter<v8::Handle<v8::Value>,&Event::currentTarget>( "currentTarget" );
  ///FIXME: bind CAPTURING_PHASE etc. enumerations
  cw.BindGetter<int,&Event::eventPhase>( "eventPhase" );
  cw.BindGetter<v8::Handle<v8::Value>,&Event::target>( "target" );
  cw.BindGetter<Core::String,&Event::type>( "type" );
  
  cw.Set( "stopPropagation", ICM::M0::Invocable<void, &Event::stopPropagation>);

  
  cw.Seal(); // ends the binding process
  
  return cw;
}
Beispiel #4
0
QJsonDocument jsonparser::jsonOpenFile(QString filename){
    QFile jDocFile;
    QFileInfo cw(filename);
    if(startDir.isEmpty()){
        startDir = cw.absolutePath();
        jDocFile.setFileName(startDir+"/"+cw.fileName());
    }else
        jDocFile.setFileName(startDir+"/"+cw.fileName());
    if (!jDocFile.exists()) {
        sendProgressTextUpdate(tr("Failed due to the file %1 not existing").arg(jDocFile.fileName()));
        return QJsonDocument();
    }
    if (!jDocFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        sendProgressTextUpdate(tr("Failed to open the requested file"));
        return QJsonDocument();
    }
    QJsonParseError initError;
    QJsonDocument jDoc = QJsonDocument::fromJson(jDocFile.readAll(),&initError);
    if (initError.error != 0){
        reportError(2,tr("ERROR: jDoc: %s\n").arg(initError.errorString()));
        sendProgressTextUpdate(tr("An error occured. Please take a look at the error message to see what went wrong."));
        return QJsonDocument();
    }
    if (jDoc.isNull() || jDoc.isEmpty()) {
        sendProgressTextUpdate(tr("Failed to import file"));
        return QJsonDocument();
    }
    return jDoc;
}
Beispiel #5
0
int main(int argc, char **argv)
{
	QApplication a(argc, argv);
	ControlWidget cw(a.desktop());
	cw.show();
	QObject::connect(&cw, SIGNAL(endApp()), &a, SLOT(quit()));
	return a.exec();
}
Beispiel #6
0
double ArtificialPlayer::RNNFitness(RNN &c)
{
  sg->Start();
  while (sg->Result == 0 && sg->Turn < sg->Tiles*sg->Tiles) {
    sg->CheckInput(c->ComputeOutput(sg->Repr));
  }
  sg->End();
  return cw(sg);
}
Beispiel #7
0
void ChannelEditor::edit()
{
    id = list->getValue().toInt();
    ChannelWizard cw(id, source->getValue().toUInt());
    cw.exec();
    
    list->fillSelections();
    list->setFocus();
}
Beispiel #8
0
void ChannelEditor::edit(MythUIButtonListItem *item)
{
    if (!item)
        return;

    int chanid = item->GetData().toInt();
    ChannelWizard cw(chanid, m_sourceFilter);
    cw.exec();

    fillList();
}
HTMLElementGeneric::CW&
HTMLElementGeneric::getCW() {
  CW & cw( CW::Instance() );
  
  if( cw.IsSealed() )
  {
      return cw;
  }
  
  cw.Inherit(super::getCW());
  
  cw.Seal(); // ends the binding process
  
  return cw;
}
Beispiel #10
0
//!  \ingroup fir
//!  \brief dolph chebyshev window design
std::vector<float_type> cheby(int nf, float_type r_db) {
	/*! parameters
		- nf = filter length in samples
		- r_db = Sidelobe level attenuation
	*/
	float_type r = pow(10.0,r_db/20.0);
	float_type x0 = cosh(acosh(r)/(nf-1.0));
	std::vector<float_type> w(nf);

	for (int i = 0; i < nf; i++) {
		float_type a = fabs(x0*cos(i*M_PI/nf));
		w[i] = cheby_poly(nf-1,a);
		if (nf%2 == 0) {
			if (i>nf/2) w[i] *= -1;
		}
	}
	
	if (nf%2 == 0) {
		// For even, need complex input to fft
		std::vector<std::complex<float_type>> cw(nf);
		for (int j = 0; j < nf; j++) cw[j] = w[j] * std::complex<float_type>(cos(M_PI*j/nf),sin(M_PI*j/nf));
		real_dft(cw,nf);
		for (int i = 0; i < nf; i++) w[i] = real(cw[i]);
	} else {
		real_dft(w,nf);
	}
	
	if (nf%2 == 0) {
		for (int i=0;i<nf/2;i++) w[i+nf/2] = w[i];
		for (int i=0;i<nf/2;i++) w[nf/2-1-i] = w[i+nf/2];
	} else {
		for (int i=0;i<nf/2+1;i++) w[nf-1-i] = w[nf/2-i];
		for (int i=0;i<nf/2;i++) w[nf/2-1-i] = w[nf/2+1+i];
	}
	float_type max_v=0;
	// normalize
	for (int i = 0; i < nf; i++) if (fabs(w[i]) > max_v) max_v = fabs(w[i]);
	for (int i = 0; i < nf; i++) w[i] /= max_v;
	return (w);
}
void NetILTraceBuilder::VisitBasicBlock(BBType *bb, BBType *comingFrom)
{
	if (m_ValidationPass)
	{
		bb->Valid = true;
		return;
	}

	if (!bb->Valid)
		return;

	if (bb->Kind != BB_CFG_ENTRY)
	{
		//CodeList *bbCode = &bb->Code;
		std::list<MIRONode*> bbCode = bb->getCode();
		nbASSERT(bbCode.size() > 0, "basic block code should not be empty");
		StmtMIRONode *last = dynamic_cast<StmtMIRONode*>(*bbCode.rbegin());
		std::cout << "BB: " << bb->getId() << "TRACE:  Esamino il nodo: ";
		last->printNode(std::cout, false);
		std::cout << std::endl;

		if (last->Kind == STMT_JUMP || last->Kind == STMT_JUMP_FIELD)
		{
			JumpMIRONode *jump = dynamic_cast<JumpMIRONode*>(last);
			//if it's a conditional branch:
			if (jump->FalseBranch)
			{
				BBType *trueBB = m_CFG->LookUpLabel(jump->TrueBranch->Name);
				nbASSERT(trueBB != NULL, "basic block should exist");
				if (comingFrom == trueBB)
					InvertBranch(jump);
			}
		}
		CodeWriter cw(m_Stream);
		cw.DumpNetIL(bb->getMIRNodeCode());
	}
}
Beispiel #12
0
HTMLDocument::CW&
HTMLDocument::getCW() {
  CW & cw( CW::Instance() );
  typedef v8::juice::convert::MemFuncInvocationCallbackCreator<HTMLDocument> ICM;
  
  if( cw.IsSealed() )
  {
      return cw;
  }
  
  // cw.BindGetter<Core::String,
              // &HTMLElementBase::tagName>
              // ("tagName");

  cw.BindGetter<v8::Handle<v8::Value>,
              &self_type::body>
              ("body");

  cw.BindGetter<v8::Handle<v8::Value>,
              &self_type::documentElement>
              ("documentElement");

  
  cw.Set( "createComment", ICM::M1::Invocable<v8::Handle<v8::Value>, const Core::String&, &HTMLDocument::createComment>);
  cw.Set( "createElement", ICM::M1::Invocable<v8::Handle<v8::Value>, const Core::String&, &HTMLDocument::createElement>);
  cw.Set( "createTextNode", ICM::M1::Invocable<v8::Handle<v8::Value>, const Core::String&, &HTMLDocument::createTextNode>);
  cw.Set( "createDocumentFragment", ICM::M0::Invocable<v8::Handle<v8::Value>, &HTMLDocument::createDocumentFragment>);
  cw.Set( "getElementById", ICM::M1::Invocable<v8::Handle<v8::Value>, const Core::String&, &HTMLDocument::getElementById>);
  cw.Set( "getElementsByTagName", ICM::M1::Invocable<v8::Handle<v8::Value>, const Core::String&, &HTMLDocument::getElementsByTagName>);
  cw.Set( "write", ICM::M1::Invocable<void, const Core::String&, &HTMLDocument::write>);
  cw.Set( "writeln", ICM::M1::Invocable<void, const Core::String&, &HTMLDocument::writeln>);

  
  cw.Seal(); // ends the binding process
  
  return cw;
}
Beispiel #13
0
void zebraPattern() {
  // int bqc = 99;
  
  /* for(Q=0; Q<65536; Q++) {
    if((Q & (Q>>1)) & 0x5555) continue;
    qconflict = false;
    cellwalker cw(cwt);
    cwstep(cw); cwspin(cw, 1);
    qconflict = 0;
    allconflict = "";
    zebra(cw, 3, 0, "");
    if(qconflict < bqc) bqc = qconflict;
    // if(qconflict == bqc) 
    printf("%X - X-%sX\n", Q, allconflict.c_str());
    }
    
  Q = 0xFFFB; */
  
  cellwalker cw(cwt);
  cwstep(cw); cwspin(cw, 1);
  setzebra(cw, 7, 0, "", -999);
  // cw.c->
  // printf("Conflicts: %d\n", qconflict);
  }
    int Cornea::computeCentre(const std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > &led_pos, // LED locations
                              const std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > &glint_pos,
                              std::vector<double> &gx_guesses,
                              Eigen::Vector3d &centre,
                              double &err) {

        // initialise the cornea tracker
        create(led_pos, glint_pos);

        /*
         * Check out usage and more info about GSL:
         * http://www.csse.uwa.edu.au/programming/gsl-1.0/gsl-ref_35.html
         */

        const size_t n = 3 * pairsOfTwo(data.size());	// number of functions
        const size_t p = gx_guesses.size();				// number of parameters

        // initial guesses
        gsl_vector_const_view x = gsl_vector_const_view_array(gx_guesses.data(), p);

        gsl_multifit_function_fdf f;
        f.f			= &my_f;	// function
        f.df		= &my_df;	// derivative
        f.fdf		= &my_fdf;	// both
        f.n			= n;		// number of functions
        f.p			= p;		// number of parameters
        f.params	= this;		// additional parameter

        const gsl_multifit_fdfsolver_type *T = gsl_multifit_fdfsolver_lmsder;
        gsl_multifit_fdfsolver *solver = gsl_multifit_fdfsolver_alloc(T, n, p);
        gsl_multifit_fdfsolver_set(solver, &f, &x.vector);


        int status;
        unsigned int iter = 0;

        do {
            iter++;
            status = gsl_multifit_fdfsolver_iterate(solver);

            if(status) {
                break;
            }

            status = gsl_multifit_test_delta(solver->dx, solver->x, PRECISION, PRECISION);

        }
        while(status == GSL_CONTINUE && iter < MAX_ITER);

        if(iter == MAX_ITER) {
            printf("Cornea::computeCentre(): iter = MAX_ITER\n");
        }


        gsl_matrix *covar = gsl_matrix_alloc(p, p);
        gsl_multifit_covar(solver->J, 0.0, covar);

        // for(int row = 0; row < p; ++row) {
        //     for(int col = 0; col < p; ++col) {
        //         printf("%.2f ", covar->data[row * p + col]);
        //     }
        //     printf("\n");
        // }
        // printf("*****************************\n");

        /***********************************************************************
         * Compute the fit error
         **********************************************************************/

        err = 0;
        for(size_t i = 0; i < p; i++) {
            err += gsl_matrix_get(covar, i, i);
        }
        err = std::sqrt(err);


        Eigen::Vector3d cw(0.0, 0.0, 0.0);

        // cornea sphere radius
        const double RHO = trackerSettings.RHO;

        // remove this
        double dMaxX = -10.0;

        for(size_t i = 0; i < data.size(); ++i) {

            const DATA_FOR_CORNEA_COMPUTATION &cur_data = data[i];

            const double gx_guess = gsl_vector_get(solver->x, i);

            const double B_aux = atan2(gx_guess * tan(cur_data.alpha_aux), (cur_data.l_aux - gx_guess));

            // calculate the corneal sphere centers in the auxiliary coordinate systems
            const Eigen::Vector3d c_aux(gx_guess - RHO * sin((cur_data.alpha_aux - B_aux) / 2.),
                                        0.,
                                        gx_guess * tan(cur_data.alpha_aux) + RHO * cos((cur_data.alpha_aux - B_aux) / 2.));

            const Eigen::Vector3d tmp = cur_data.R * c_aux;

            cw(0) += tmp(0);
            cw(1) += tmp(1);
            cw(2) += tmp(2);

            if(tmp(0) > dMaxX) {
                dMaxX = tmp(0);
            }

            //        printf("%i: centre (mm): %.2f %.2f %.2f\n", (int)i, 1000.0*tmp(0), 1000.0*tmp(1), 1000.0*tmp(2));

        }

        const double nof_samples = (double)data.size();
        centre << cw(0) / nof_samples, cw(1) / nof_samples, cw(2) / nof_samples;


        // printf("Avg: %.2f %.2f %.2f\n", 1000.0*centre(0), 1000.0*centre(1), 1000.0*centre(2));
        // printf("*********************************\n");

        gsl_multifit_fdfsolver_free(solver);
        gsl_matrix_free(covar);

        return (int)iter;

    }
Beispiel #15
0
void Foam::CV2D::extractPatches
(
    wordList& patchNames,
    labelList& patchSizes,
    EdgeMap<label>& mapEdgesRegion,
    EdgeMap<label>& indirectPatchEdge
) const
{
    label nPatches = qSurf_.patchNames().size() + 1;
    label defaultPatchIndex = qSurf_.patchNames().size();

    patchNames.setSize(nPatches);
    patchSizes.setSize(nPatches, 0);
    mapEdgesRegion.clear();

    const wordList& existingPatches = qSurf_.patchNames();

    forAll(existingPatches, sP)
    {
        patchNames[sP] = existingPatches[sP];
    }

    patchNames[defaultPatchIndex] = "CV2D_default_patch";

    for
    (
        Triangulation::Finite_edges_iterator eit = finite_edges_begin();
        eit != finite_edges_end();
        ++eit
    )
    {
        Face_handle fOwner = eit->first;
        Face_handle fNeighbor = fOwner->neighbor(eit->second);

        Vertex_handle vA = fOwner->vertex(cw(eit->second));
        Vertex_handle vB = fOwner->vertex(ccw(eit->second));

        if
        (
            (vA->internalOrBoundaryPoint() && !vB->internalOrBoundaryPoint())
         || (vB->internalOrBoundaryPoint() && !vA->internalOrBoundaryPoint())
        )
        {
            point ptA = toPoint3D(vA->point());
            point ptB = toPoint3D(vB->point());

            label patchIndex = qSurf_.findPatch(ptA, ptB);

            if (patchIndex == -1)
            {
                patchIndex = defaultPatchIndex;

                WarningInFunction
                    << "Dual face found that is not on a surface "
                    << "patch. Adding to CV2D_default_patch."
                    << endl;
            }

            edge e(fOwner->faceIndex(), fNeighbor->faceIndex());
            patchSizes[patchIndex]++;
            mapEdgesRegion.insert(e, patchIndex);

            if (!pointPair(*vA, *vB))
            {
                indirectPatchEdge.insert(e, 1);
            }
        }
    }
}
Beispiel #16
0
CSS2Properties::CW&
CSS2Properties::getCW() {
  CW & cw( CW::Instance() );
  
  if( cw.IsSealed() )
  {
      return cw;
  }
  typedef v8::juice::convert::MemFuncInvocationCallbackCreator<self_type> ICM;  
  
  
  // cw.BindGetterSetter<Core::String,
                   // &self_type::azimuth,
                   // void,const Core::String&,&self_type::azimuth>
                   // ( "azimuth");
  
  // cw.BindGetterSetter<Core::String,
                   // &self_type::background,
                   // void,const Core::String&,&self_type::background>
                   // ( "background");
  
  // cw.BindGetterSetter<Core::String,
                   // &self_type::backgroundAttachment,
                   // void,const Core::String&,&self_type::backgroundAttachment>
                   // ( "backgroundAttachment");
  
  // cw.BindGetterSetter<Core::String,
                   // &self_type::backgroundColor,
                   // void,const Core::String&,&self_type::backgroundColor>
                   // ( "backgroundColor");
  
  // cw.BindGetterSetter<Core::String,
                   // &self_type::backgroundImage,
                   // void,const Core::String&,&self_type::backgroundImage>
                   // ( "backgroundImage");
  
  
  
  
  
  
  
  
  
  cw.BindGetterSetter<Core::String,
                   &self_type::display,
                   void,const Core::String&,&self_type::display>
                   ( "display");
  
  
  
  
  
  
  
  
  
  
  
  
  cw.BindGetterSetter<Core::String,
                   &self_type::visibility,
                   void,const Core::String&,&self_type::visibility>
                   ( "visibility");
  
  cw.Seal(); // ends the binding process
  
  return cw;
}
Beispiel #17
0
void patternFiftyAt(cell *c) {
  if(!map50.count(c)) return;
  
  state50 s = map50[c];
  
  // c->wall = waCIsland;
  
  // if(c->heat > ii) return;
  
  // printf("pfifty %p\n", c);
  
  if(style == 1 && s.polarity2) {
      spill50(c, waCamelot, 3);
      spill50(c, waNone, 2);

      for(int i=0; i<c->type; i++) {
        cellwalker cw(c, i);
        cwstep(cw); // cw.c->item = itSilver;
        cwspin(cw, 4); // 6
        cwstep(cw); // cw.c->item = itSilver;
        cwspin(cw, 3); // 6
        cwstep(cw); cw.c->wall = waFloorA; cwstep(cw);
        cwspin(cw, 1);
        cwstep(cw); cw.c->wall = waFloorA; cwstep(cw);
        }
      }
   
  /*switch(ii) {
    case 0:
      spill50(c, waNone, 3);
      break;

    case 1:
      spill50(c, waNone, 3);
      break;

    case 2:
      spill50(c, waNone, 3);
      break;

    case 3:
      spill50(c, waNone, 3);
      break;
    } */
    
  if(style == 2) {
    spill50(c, waCavefloor, 2);
    spill50(c, waFloorA, 1);
    }
  
  if(style == 3) {
    spill50(c, colorwalls[s.color], 3);
    // c->item = itGold;
//  if(s.polarity2) return;
    }

  encode(c, s, 0, 0);
  
  int sgn = s.polarity2 ? 1 : -1;
  int sgn1 = s.polarity1 ? 1 : -1;

  int col2 = s.color2, sw = s.wc2;
  
  while(col2 != 7-s.color) {
    sw += (s.polarity1?1:-1); sw %= 7;
    while(true) { col2++; col2 &= 7; if(col2 != s.color) break; }
    }  

  for(int i=0; i<c->type; i++) {
    cellwalker cw(c, sw);
    cwspin(cw, sgn1 * i);
    cwstep(cw);
    cwspin(cw, sgn*4);
    cwstep(cw); 
    if(cw.spin < 0 || cw.spin >= 7 || cw.c->type != 7) exit(1);
    encode(cw.c, s, 1+i, cw.spin);
    }
  
  for(int i=0; i<c->type; i++) {
    cellwalker cw(c, sw);
    cwspin(cw, sgn1 * i);
    cwstep(cw);
    cwspin(cw, 3);
    cwstep(cw);
    cwspin(cw, 3);
    cwstep(cw);
    if(cw.spin < 0 || cw.spin >= 7 || cw.c->type != 7) exit(1);
    encode(cw.c, s, 8+i, cw.spin);
    }
  
  // c->heat = s.color + 
    
  for(int i=0; i<c->type; i++) {
    cellwalker cw(c, s.wc2);
    cwspin(cw, sgn1 * i);
    cwstep(cw); 
    if(style == 0) cw.c->wall = waCamelot;
    // cw.c->item = itSilver;
    cwspin(cw, sgn*4); //6
    cwstep(cw); if(style == 0) cw.c->wall = waFloorA;

    // cw.c->item = itSilver;
    cwspin(cw, sgn*4); //7
    cwstep(cw); if(style == 0) cw.c->wall = waFloorA;
    // cw.c->item = itSilver;
    cwspin(cw, 3); //6
    cwstep(cw); if(style == 0) cw.c->wall = waFloorA;
    // cw.c->item = itSilver;
    cwspin(cw, 3); //6
    cwstep(cw); if(style == 0) cw.c->wall = waFloorA;
    // cw.c->item = itSilver;
    cwspin(cw, sgn*3); //7
    cwstep(cw); if(style == 0) cw.c->wall = waCamelot;
    // cw.c->item = itSilver;
    cwspin(cw, sgn*2); //6
    cwstep(cw); // cw.c->item = itGold;
    // setdist(cw.c, 8, NULL);
    state50 s2 = s; s2.polarity1 = !s.polarity1;
    s2.wc2 = (cw.spin + sgn1 * i + sgn + 42) % 7;
    progress(cw.c, s2);
    // printf("heat set %f\n", cw.c->heat);
    }
    
  int newcol = s.color2;
  
  // if(s.polarity2) return;
  
  for(int i=0; i<c->type; i++) {
    cellwalker cw(c, s.wc2);
    cwspin(cw, sgn1 * i);
    cwstep(cw); // cw.c->item = itSilver;
//  cw.c->item = itDiamond;
    cwspin(cw, 3); // 6
    cwstep(cw); // cw.c->item = itSilver;
//  cw.c->item = itDiamond;
    cwspin(cw, sgn*4); // 6
    cwstep(cw); // cw.c->item = itSilver;
//  cw.c->item = itDiamond;
    cwspin(cw, sgn*2); // 6
    cwstep(cw); // cw.c->item = itSilver;
//  cw.c->item = itDiamond;
    cwspin(cw, 3); // 6
    cwstep(cw); // cw.c->item = itSilver;
//  cw.c->item = itDiamond;
    cwspin(cw, sgn*3); // 7
    cwstep(cw); // cw.c->item = itSilver;
//  cw.c->item = itDiamond;
    cwspin(cw, sgn*4); // 6
    cwstep(cw); // cw.c->item = itSilver;
    // setdist(cw.c, 8, NULL);
    state50 s2 = s; 
    s2.polarity2 = !s.polarity2;
    if(s.polarity2) s2.polarity1 = !s.polarity1;
    s2.color2 = s2.color;
    s2.color = newcol;
    s2.wc2 = cw.spin;
    progress(cw.c, s2);
    while(true) { newcol++; newcol &= 7; if(newcol != s2.color && newcol != s.color) break; }
    // printf("heat set %f\n", cw.c->heat);
    }
  
  }
template <typename T> PyObject *TypeNumberCommon<T>::mediator_nb_absolute(PyObject *arg)
{
  call_wrapper<&TypeNumberCommon<T>::absolute> cw(arg, __PRETTY_FUNCTION__);
  exceptionHandler::call(cw, reinterpret_cast<size_t>(mediator_nb_absolute));
  return cw.retval;
}
template <typename T> PyObject *TypeNumberCommon<T>::mediator_nb_index(PyObject *arg)
{
  call_wrapper<&TypeNumberCommon<T>::index> cw(arg, __PRETTY_FUNCTION__, raiseError);
  exceptionHandler::call(cw, reinterpret_cast<size_t>(mediator_nb_index));
  return cw.retval;
}
Beispiel #20
0
void Foam::CV2D::newPoints()
{
    const scalar relaxation = relaxationModel_->relaxation();

    Info<< "Relaxation = " << relaxation << endl;

    Field<point2D> dualVertices(number_of_faces());

    label dualVerti = 0;

    // Find the dual point of each tetrahedron and assign it an index.
    for
    (
        Triangulation::Finite_faces_iterator fit = finite_faces_begin();
        fit != finite_faces_end();
        ++fit
    )
    {
        fit->faceIndex() = -1;

        if
        (
            fit->vertex(0)->internalOrBoundaryPoint()
         || fit->vertex(1)->internalOrBoundaryPoint()
         || fit->vertex(2)->internalOrBoundaryPoint()
        )
        {
            fit->faceIndex() = dualVerti;

            dualVertices[dualVerti] = toPoint2D(circumcenter(fit));

            dualVerti++;
        }
    }

    dualVertices.setSize(dualVerti);

    Field<vector2D> displacementAccumulator
    (
        startOfSurfacePointPairs_,
        vector2D::zero
    );

    // Calculate target size and alignment for vertices
    scalarField sizes
    (
        number_of_vertices(),
        meshControls().minCellSize()
    );

    Field<vector2D> alignments
    (
        number_of_vertices(),
        vector2D(1, 0)
    );

    for
    (
        Triangulation::Finite_vertices_iterator vit = finite_vertices_begin();
        vit != finite_vertices_end();
        ++vit
    )
    {
        if (vit->internalOrBoundaryPoint())
        {
            point2D vert = toPoint2D(vit->point());

            // alignment and size determination
            pointIndexHit pHit;
            label hitSurface = -1;

            qSurf_.findSurfaceNearest
            (
                toPoint3D(vert),
                meshControls().span2(),
                pHit,
                hitSurface
            );

            if (pHit.hit())
            {
                vectorField norm(1);
                allGeometry_[hitSurface].getNormal
                (
                    List<pointIndexHit>(1, pHit),
                    norm
                );

                alignments[vit->index()] = toPoint2D(norm[0]);

                sizes[vit->index()] =
                    cellSizeControl_.cellSize
                    (
                        toPoint3D(vit->point())
                    );
            }
        }
    }

    // Info<< "Calculated alignments" << endl;

    scalar cosAlignmentAcceptanceAngle = 0.68;

    // Upper and lower edge length ratios for weight
    scalar u = 1.0;
    scalar l = 0.7;

    PackedBoolList pointToBeRetained(startOfSurfacePointPairs_, true);

    std::list<Point> pointsToInsert;

    for
    (
        Triangulation::Finite_edges_iterator eit = finite_edges_begin();
        eit != finite_edges_end();
        eit++
    )
    {
        Vertex_handle vA = eit->first->vertex(cw(eit->second));
        Vertex_handle vB = eit->first->vertex(ccw(eit->second));

        if (!vA->internalOrBoundaryPoint() || !vB->internalOrBoundaryPoint())
        {
            continue;
        }

        const point2D& dualV1 = dualVertices[eit->first->faceIndex()];
        const point2D& dualV2 =
            dualVertices[eit->first->neighbor(eit->second)->faceIndex()];

        scalar dualEdgeLength = mag(dualV1 - dualV2);

        point2D dVA = toPoint2D(vA->point());
        point2D dVB = toPoint2D(vB->point());

        Field<vector2D> alignmentDirsA(2);

        alignmentDirsA[0] = alignments[vA->index()];
        alignmentDirsA[1] = vector2D
        (
           -alignmentDirsA[0].y(),
            alignmentDirsA[0].x()
        );

        Field<vector2D> alignmentDirsB(2);

        alignmentDirsB[0] = alignments[vB->index()];
        alignmentDirsB[1] = vector2D
        (
           -alignmentDirsB[0].y(),
            alignmentDirsB[0].x()
        );

        Field<vector2D> alignmentDirs(alignmentDirsA);

        forAll(alignmentDirsA, aA)
        {
            const vector2D& a(alignmentDirsA[aA]);

            scalar maxDotProduct = 0.0;

            forAll(alignmentDirsB, aB)
            {
                const vector2D& b(alignmentDirsB[aB]);

                scalar dotProduct = a & b;

                if (mag(dotProduct) > maxDotProduct)
                {
                    maxDotProduct = mag(dotProduct);

                    alignmentDirs[aA] = a + sign(dotProduct)*b;

                    alignmentDirs[aA] /= mag(alignmentDirs[aA]);
                }
            }
        }

        vector2D rAB = dVA - dVB;

        scalar rABMag = mag(rAB);

        forAll(alignmentDirs, aD)
        {
            vector2D& alignmentDir = alignmentDirs[aD];

            if ((rAB & alignmentDir) < 0)
            {
                // swap the direction of the alignment so that has the
                // same sense as rAB
                alignmentDir *= -1;
            }

            scalar alignmentDotProd = ((rAB/rABMag) & alignmentDir);

            if (alignmentDotProd > cosAlignmentAcceptanceAngle)
            {
                scalar targetFaceSize =
                    0.5*(sizes[vA->index()] + sizes[vB->index()]);

                // Test for changing aspect ratio on second alignment (first
                // alignment is neartest surface normal)
                // if (aD == 1)
                // {
                //     targetFaceSize *= 2.0;
                // }

                alignmentDir *= 0.5*targetFaceSize;

                vector2D delta = alignmentDir - 0.5*rAB;

                if (dualEdgeLength < 0.7*targetFaceSize)
                {
                    delta *= 0;
                }
                else if (dualEdgeLength < targetFaceSize)
                {
                    delta *=
                        (
                            dualEdgeLength
                           /(targetFaceSize*(u - l))
                          - 1/((u/l) - 1)
                        );
                }

                if
                (
                    vA->internalPoint()
                 && vB->internalPoint()
                 && rABMag > 1.75*targetFaceSize
                 && dualEdgeLength > 0.05*targetFaceSize
                 && alignmentDotProd > 0.93
                )
                {
                    // Point insertion
                    pointsToInsert.push_back(toPoint(0.5*(dVA + dVB)));
                }
                else if
                (
                    (vA->internalPoint() || vB->internalPoint())
                 && rABMag < 0.65*targetFaceSize
                )
                {
                    // Point removal

                    // Only insert a point at the midpoint of the short edge
                    // if neither attached point has already been identified
                    // to be removed.
                    if
                    (
                        pointToBeRetained[vA->index()] == true
                     && pointToBeRetained[vB->index()] == true
                    )
                    {
                        pointsToInsert.push_back(toPoint(0.5*(dVA + dVB)));
                    }

                    if (vA->internalPoint())
                    {
                        pointToBeRetained[vA->index()] = false;
                    }

                    if (vB->internalPoint())
                    {
                        pointToBeRetained[vB->index()] = false;
                    }
                }
                else
                {
                    if (vA->internalPoint())
                    {
                        displacementAccumulator[vA->index()] += delta;
                    }

                    if (vB->internalPoint())
                    {
                        displacementAccumulator[vB->index()] += -delta;
                    }
                }
            }
        }
    }
file_chooser_widget_rep::file_chooser_widget_rep (
  command cmd2, string type2):
  attribute_widget_rep (1), cmd (cmd2), type (type2)
{
  ref_count++;

  tree t= stree_to_tree (call ("format-get-suffixes*", type));
  int i, n= N(t);
  for (i=0; i<n; i++)
    suffix << ("." * as_string (t[i]));
  if (n == 0) suffix << string ("");

  SI sep= 3*PIXEL;
  int cw2n= 5;
  if (type == "directory") cw2n= 3;
  array<wk_widget> cw2 (cw2n);
  array<string> cn2 (cw2n);
  cw2[0]= glue_wk_widget (false, true, sep);
  cw2[1]= canvas_widget (wk_widget (tm_new<file_list_widget_rep> (this, suffix, true)));
  cn2[1]= "directories";
  cw2[2]= glue_wk_widget (false, true, sep);
  if (type != "directory") {
    cw2[3]= canvas_widget (wk_widget (tm_new<file_list_widget_rep> (this, suffix, false)));
    cn2[3]= "files";
    cw2[4]= glue_wk_widget (false, true, sep-PIXEL);
  }

#ifdef OS_WIN32
  wk_widget drive_menu = vertical_menu (array<wk_widget> ());
  unsigned int driveMask = XGetDrivesMask();
  char driveString[4] = "A:\\";
  for (char x = 'A'; x <= 'Z'; x++)
    if(driveMask & (1 << (x - 'A'))) {
      driveString[0] = x;
      drive_menu << emit_insert (driveString,
	command_button (text_wk_widget (driveString),
			tm_new<drive_menu_command_rep> (this, driveString)));
    }
  array<wk_widget> drw (2);
  drw[0] = pullright_button (text_wk_widget (translate ("Drive")), drive_menu);
  drw[1] = text_wk_widget ("");
  // drw[1]= glue_wk_widget (false, true, sep);
#endif

  int BUTTON_OK= BUTTON_FILE_OK;
  if (type == "directory") BUTTON_OK= BUTTON_DIR_OK;

#ifdef OS_WIN32
  array<wk_widget> cw3 (11);
  cw3[0]= glue_wk_widget (false, false, sep);
  cw3[1]= pulldown_button (text_wk_widget (translate ("Drive")),
			   drive_menu, true);
  cw3[2]= glue_wk_widget (false, false, sep);
  cw3[3]= button_widget ("Home", BUTTON_HOME);
  cw3[4]= glue_wk_widget (false, false, sep);
  cw3[5]= button_widget ("Texts", BUTTON_TEXTS);
  cw3[6]= glue_wk_widget (true, false);
  cw3[7]= button_widget ("Ok", BUTTON_OK);
  cw3[8]= glue_wk_widget (false, false, sep);
  cw3[9]= button_widget ("Cancel", BUTTON_CANCEL);
  cw3[10]= glue_wk_widget (false, false, sep);
#else
  array<wk_widget> cw3 (9);
  cw3[0]= glue_wk_widget (false, false, sep);
  cw3[1]= button_widget ("Home", BUTTON_HOME);
  cw3[2]= glue_wk_widget (false, false, sep);
  cw3[3]= button_widget ("Texts", BUTTON_TEXTS);
  cw3[4]= glue_wk_widget (true, false);
  cw3[5]= button_widget ("Ok", BUTTON_OK);
  cw3[6]= glue_wk_widget (false, false, sep);
  cw3[7]= button_widget ("Cancel", BUTTON_CANCEL);
#ifdef OS_MACOS
  cw3[8]= glue_wk_widget (false, false, sep + 14*PIXEL);
#else
  cw3[8]= glue_wk_widget (false, false, sep);
#endif
#endif

  int cwn= 11;
  if (type == "image") cwn= 16;
  if (type == "directory") cwn= 7;
  array<wk_widget> cw (cwn);
  array<string> cn (cwn);
  cw[0]= glue_wk_widget (true, false, 0, sep);
  cw[1]= input_widget ("Directory:", "Directory:", CHANGE_DIR);
  cn[1]= "directory";
  cw[2]= glue_wk_widget (true, false, 0, sep);

  if (type == "directory") {
    cw[3]= horizontal_list (cw2, cn2);
    cn[3]= "list";
  }

  if (type != "directory") {
    cw[3]= input_widget ("File:", "Directory:", CHANGE_FILE);
    cn[3]= "file";
    cw[4]= glue_wk_widget (true, false, 0, sep);
    cw[5]= input_widget ("Suffixes:", "Directory:", CHANGE_SUFFIXES);
    cn[5]= "suffixes";
    cw[6]= glue_wk_widget (true, false, 0, sep);
    cw[7]= horizontal_list (cw2, cn2);
    cn[7]= "list";
  }

  if (type == "image") {
    array<wk_widget> imw (7);
    array<string> ims (7);
    imw[ 0]= input_widget ("width:", "y-position:", IMAGE_HSIZE);
    ims[ 0]= "hsize";
    imw[ 1]= glue_wk_widget (true, false, 0, sep);
    imw[ 2]= input_widget ("height:", "y-position:", IMAGE_VSIZE);
    ims[ 2]= "vsize";
    imw[ 3]= glue_wk_widget (true, false, 0, sep);
    imw[ 4]= input_widget ("x-position:", "y-position:", IMAGE_XPOS);
    ims[ 4]= "xpos";
    imw[ 5]= glue_wk_widget (true, false, 0, sep);
    imw[ 6]= input_widget ("y-position:", "y-position:", IMAGE_YPOS);
    ims[ 6]= "ypos";

    array<wk_widget> cw4 (5);
    array<string> cn4 (5);
    cw4[0] = glue_wk_widget (false, false, sep);
    cw4[1] = vertical_list (imw, ims);
    cn4[1] = "parameters";
    cw4[2] = glue_wk_widget (false, false, sep);
    cw4[3] = tm_new<image_widget_rep> ();
    cn4[3] = "image";
    cw4[4] = glue_wk_widget (false, false, sep);

    //cw[ 8] = glue_wk_widget (true, false, 0, sep);
    //cw[ 9] = separator_wk_widget ();
    cw[ 8] = glue_wk_widget (true, false, 0, sep);
    cw[ 9] = horizontal_list (cw4, cn4);
    cn[ 9] = "image";
    cw[10] = glue_wk_widget (true, false, 0, sep);
    cw[11] = separator_wk_widget ();
    cw[12] = glue_wk_widget (true, false, 0, sep);
  }

  cw[cwn-3]= glue_wk_widget (true, false, 0, sep);
  cw[cwn-2]= horizontal_list (cw3);
  cn[cwn-2]= "buttons";
  cw[cwn-1]= glue_wk_widget (true, false, 0, sep);

  a[0]= vertical_list (cw, cn);

  if (type != "directory") {
    string s;
    for (i=0; i<N(suffix); ++i) {
      if (i) s << " ";
      s << suffix[i];
    }
    a[0]["suffixes"]["input"] << set_string ("input", s);
  }

  ref_count--;
}
Beispiel #22
0
void draw(Rasterizer& raster, const Mesh& mesh, const arma::mat44& mat, const arma::mat44& rotmat,
        std::vector<BufferedVertice>& buff, ECULLING_MODE cull)
{
    const unsigned * idxs = mesh.getIndices();
    const unsigned idxc = mesh.getIndexCount();
    const unsigned vc = mesh.getVertexCount();
    arma::vec4 av;
    arma::vec4 nv;

    buff.clear();

    for(int i = 0; i < vc; ++i)
    {
        const Vertex& a = mesh.getVertex(i);

        av(0) = a.position.x;
        av(1) = a.position.y;
        av(2) = a.position.z;
        av(3) = 1.f;
        av = mat * av;

        nv(0) = a.normal.x;
        nv(1) = a.normal.y;
        nv(2) = a.normal.z;
        nv(3) = 1.f;
        nv = rotmat * nv;

        av(0) = av(0) * (kProjPlaneDist / std::fabs(av(2))) + halfscreenwidth;
        av(1) = av(1) * (kProjPlaneDist / std::fabs(av(2))) + halfscreenheight;

        buff.push_back(BufferedVertice(av(0), av(1), av(2), a.color, a.u, a.v, nv(0), nv(1), nv(2)));

    }//for

    int culled = 0;
    for(int i = 0; (i + 2) < idxc; i += 3)
    {
        const BufferedVertice& a = buff[idxs[i]];
        const BufferedVertice& b = buff[idxs[i + 1]];
        const BufferedVertice& c = buff[idxs[i + 2]];
        bool skip = cw(a, b, c);
        switch(cull)
        {
            case ECM_BACKFACE:
                skip = skip;
                break;
            case ECM_FRONTFACE:
                skip = !skip;
                break;
            default:
                skip = false;
                break;
        }//switch cull
        if(skip)
        {
            ++culled;
            continue;
        }
        raster.addVertex(a.x, a.y, a.c, a.z, a.u, a.v, a.nx, a.ny, a.nz);
        raster.addVertex(b.x, b.y, b.c, b.z, b.u, b.v, b.nx, b.ny, b.nz);
        raster.addVertex(c.x, c.y, c.c, c.z, c.u, c.v, c.nx, c.ny, c.nz);
    }//for
    std::printf("CULLED: %d\n", culled);
}
void mtsTeleOperationECM::RunEnabled(void)
{
    if (mIsClutched) {
        return;
    }

    /* --- Forces on MTMs --- */
    const vct3 frictionForceCoeff(-10.0, -10.0, -40.0);
    const double distanceForceCoeff = 150.0;

    //-1- vector between MTMs
    vct3 vectorLR;
    vectorLR.DifferenceOf(mMTMR.PositionCartesianCurrent.Position().Translation(),
                          mMTML.PositionCartesianCurrent.Position().Translation());
    // -2- mid-point, aka center of image
    vct3 c;
    c.SumOf(mMTMR.PositionCartesianCurrent.Position().Translation(),
            mMTML.PositionCartesianCurrent.Position().Translation());
    c.Multiply(0.5);
    vct3 directionC = c.Normalized();
    // -3- image up vector
    vct3 up;
    up.CrossProductOf(vectorLR, c);
    up.NormalizedSelf();
    // -4- Width of image
    vct3 side;
    side.CrossProductOf(c, up);
    side.NormalizedSelf();
    // -5- find desired position for L and R
    vct3 goalL(c);
    goalL.AddProductOf(-mInitial.w, side);
    goalL.AddProductOf(-mInitial.d, directionC);
    vct3 goalR(c);
    goalR.AddProductOf(mInitial.w, side);
    goalR.AddProductOf(mInitial.d, directionC);


    // compute forces on L and R based on error in position
    vct3 forceFriction;
    vct3 force;
    prmForceCartesianSet wrenchR, wrenchL;

    // MTMR
    // apply force
    force.DifferenceOf(goalR,
                       mMTMR.PositionCartesianCurrent.Position().Translation());
    force.Multiply(distanceForceCoeff);
    wrenchR.Force().Ref<3>(0).Assign(force);
    // add friction force
    forceFriction.ElementwiseProductOf(frictionForceCoeff,
                                       mMTMR.VelocityCartesianCurrent.VelocityLinear());
    wrenchR.Force().Ref<3>(0).Add(forceFriction);
    // apply
    mMTMR.SetWrenchBody(wrenchR);

    // MTML
    // apply force
    force.DifferenceOf(goalL,
                       mMTML.PositionCartesianCurrent.Position().Translation());
    force.Multiply(distanceForceCoeff);
    wrenchL.Force().Ref<3>(0).Assign(force);
    // add friction force
    forceFriction.ElementwiseProductOf(frictionForceCoeff,
                                       mMTML.VelocityCartesianCurrent.VelocityLinear());
    wrenchL.Force().Ref<3>(0).Add(forceFriction);
    // apply
    mMTML.SetWrenchBody(wrenchL);

    /* --- Joint Control --- */
    static const vct3 normXZ(0.0, 1.0, 0.0);
    static const vct3 normYZ(1.0, 0.0, 0.0);
    static const vct3 normXY(0.0, 0.0, 1.0);
    // Initial ECM joints
    vctVec goalJoints(mInitial.ECMPositionJoint);
    // Change in directions and joints
    vctVec changeJoints(4);
    vctVec changeDir(4);
    vct3 crossN;  // normal to direction of motion

    // - Direction 0 - left/right, movement in the XZ plane
    vct3  lr(c[0], 0.0, c[2]);
    lr.NormalizedSelf();
    if (mInitial.Lr.AlmostEqual(lr)) {
        changeDir[0] = 0.0;
    } else {
        changeDir[0] = -acos(vctDotProduct(mInitial.Lr, lr));
        crossN = vctCrossProduct(mInitial.Lr, lr);
        if (vctDotProduct(normXZ, crossN) < 0.0) {
            changeDir[0] = -changeDir[0];
        }
    }

    // - Direction 1 - up/down, movement in the YZ plane
    vct3  ud(0.0, c[1], c[2]);
    ud.NormalizedSelf();
    if (mInitial.Ud.AlmostEqual(ud)) {
        changeDir[1] = 0.0;
    } else {
        changeDir[1] = acos(vctDotProduct(mInitial.Ud, ud));
        crossN = vctCrossProduct(mInitial.Ud, ud);
        if (vctDotProduct(normYZ, crossN) < 0.0) {
            changeDir[1] = -changeDir[1];
        }
    }

    // - Direction 2 - in/out
    changeDir[2] = mScale * (mInitial.C.Norm() - c.Norm());

    // - Direction 3 - cc/ccw, movement in the XY plane
    vct3 cw(up[0], up[1], 0);
    cw.NormalizedSelf();
    if (mInitial.Cw.AlmostEqual(cw)) {
        changeDir[3] = 0.0;
    } else {
        changeDir[3] = -acos(vctDotProduct(mInitial.Cw, cw));
        crossN = vctCrossProduct(mInitial.Cw, cw);
        if (vctDotProduct(normXY, crossN) < 0) {
            changeDir[3] = -changeDir[3];
        }
    }

    // adjusting movement for camera orientation
    double totalChangeJoint3 = changeDir[3] + mInitial.ECMPositionJoint[3];
    changeJoints[0] = changeDir[0] * cos(totalChangeJoint3) - changeDir[1] * sin(totalChangeJoint3);
    changeJoints[1] = changeDir[1] * cos(totalChangeJoint3) + changeDir[0] * sin(totalChangeJoint3);
    changeJoints[2] = changeDir[2];
    changeJoints[3] = changeDir[3];

    goalJoints.Add(changeJoints);
    mECM.PositionJointSet.Goal().ForceAssign(goalJoints);
    mECM.SetPositionJoint(mECM.PositionJointSet);

    /* --- Lock Orientation --- */

    //Calculate new rotations of MTMs
    vctMatRot3 currMTMLRot;
    vctMatRot3 currMTMRRot;
    // Current ECM Rotation
    vctEulerZYXRotation3 finalEulerAngles;
    vctMatrixRotation3<double> currECMRot;
    vctMatrixRotation3<double> finalECMRot;

    finalEulerAngles.Assign(goalJoints[3], goalJoints[0], goalJoints[1]);
    vctEulerToMatrixRotation3(finalEulerAngles, finalECMRot);
    currECMRot = finalECMRot * mInitial.ECMRotEuler.Inverse();

    // Set MTM Orientation
    currMTMLRot = currECMRot.Inverse() * mInitial.MTMLRot;
    currMTMRRot = currECMRot.Inverse() * mInitial.MTMRRot;

    // set cartesian effort parameters
    mMTML.SetWrenchBodyOrientationAbsolute(true);
    mMTML.LockOrientation(currMTMLRot);
    mMTMR.SetWrenchBodyOrientationAbsolute(true);
    mMTMR.LockOrientation(currMTMRRot);
}