Exemple #1
0
TriMeshf box(float xDim, float yDim, float zDim, const vec4f& color) {
	std::vector<TriMeshf::Vertexf> vv(8);
	std::vector<UINT> vi(12 * 3);

	// Vertices
	for (int i = 0; i < 8; i++) {
		vv[i].position = vec3f(cubeVData[i][0], cubeVData[i][1], cubeVData[i][2]);
		vv[i].normal = vec3f(1.0f, 0.0f, 0.0f);  // TODO(ms): write and call generateNormals() function
		vv[i].color = color;
	}

	// Triangles
	for (int i = 0; i < 12; i++) {
		vi[i * 3 + 0] = cubeIData[i][0];
		vi[i * 3 + 1] = cubeIData[i][1];
		vi[i * 3 + 2] = cubeIData[i][2];
	}

	TriMeshf mesh(vv, vi);
	mesh.scale(vec3f(0.5f * xDim, 0.5f * yDim, 0.5f * zDim));

	return mesh;
}
Exemple #2
0
void PlaneViewer::draw(TImageP img) {
  {
    TRasterImageP ri(img);
    if (ri) {
      draw(ri);
      return;
    }
  }
  {
    TToonzImageP ti(img);
    if (ti) {
      draw(ti);
      return;
    }
  }
  {
    TVectorImageP vi(img);
    if (vi) {
      draw(vi);
      return;
    }
  }
}
CVersionInfo CompatibilityList::GetVersionInfoFromDocProvPtr(CStdString sServiceID, CComPtr<IUnknown> pDocProv)
{
	if (m_CachedVersions.find(sServiceID)!=m_CachedVersions.end())
		return m_CachedVersions[sServiceID];

	CComQIPtr<IWSComponent> pComponent = pDocProv;

	if (pComponent == NULL)
		return CVersionInfo(); // default - 0,0,0,0

	long lMajor, lMinor, lPatch, lBuild;

	HRESULT hr = pComponent->GetVersion(&lMajor, &lMinor, &lPatch, &lBuild);

	if (FAILED(hr))
		return CVersionInfo();

	CVersionInfo vi((WORD)lMajor, (WORD)lMinor, (WORD)lPatch, (WORD)lBuild);

	m_CachedVersions[sServiceID] = vi;

	return vi;
}
Bool MeshEnt::UnSelectFace( U16 index)
{
  if (selData)
  {
    List<U16>::Iterator vi( &selData->faces);

    U16 * ii;
    while ((ii = vi++) != NULL)
    {
      if (*ii == index)
      {
        break;
      }
    }
    if (ii)
    {
      selData->faces.Dispose( ii);

      return TRUE;
    }
  }
  return FALSE;
}
Exemple #5
0
int main(void) {

  valarray_t::value_type
      ibuf[22] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10,
                   11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 };

  // Create a valarray of ints
  valarray_t  vi (ibuf,(sizeof ibuf / sizeof *ibuf));

  // Print out the valarray
  std::cout << "original valarray vi:\n\n" << vi << "\n\n";

  // Get a two dimensional diagonal slice out of the middle
  std::size_t length_ary[] = {4, 2};
  std::size_t stride_ary[] = {4, 6};

  std::valarray<std::size_t> length_val(length_ary, 2);
  std::valarray<std::size_t> stride_val(stride_ary, 2);


  // Print out the slices starting at positions 0 and 2 and respectively.
  std::cout << "vi[gslice(0,[4,2],[4,6])]\n\n"
            << vi[std::gslice(0,length_val,stride_val)] << "\n\n";

  std::cout << "vi[gslice(2,[4,2],[4,6])]\n\n"
            << vi[std::gslice(2,length_val,stride_val)] << "\n\n";

  // Multiply the first slice by the second.
  vi[std::gslice(0,length_val,stride_val)]
      *= static_cast<valarray_t > (vi[std::gslice(2,length_val,stride_val)]);

  std::cout << "vi[gslice(0,[4,2],[4,8])] *= vi[gslice(2,[4,2],[4,6])]\n\n"
            << vi << std::endl;

  return 0;

}
Bool MeshEnt::SelectFace( U16 index, Bool append) // = FALSE)
{
  if (!selData)
  {
    selData = new SelectData;
  }
  if (!append)
  {
    selData->faces.DisposeAll();
    selData->verts.DisposeAll();
  }

  List<U16>::Iterator vi( &selData->faces);
  U16 * ii;
  while ((ii = vi++) != NULL)
  {
    if (*ii == index)
    {
      break;
    }
  }
  if (ii)
  {
    return FALSE;
  }

  selData->faces.Append( new U16( index));

  FaceObj &face = RootPriv().faces[index];
  U32 j;
  for (j = 0; j < 3; j++)
  {
    selData->verts.Append( new U16( face.verts[j]));
  }

  return TRUE;
}
Exemple #7
0
int main(void) {

    // Create a valarray of integers.
    valarray_t::value_type vbuf[10] = {0,1,2,3,4,5,6,7,8,9};
    valarray_t vi(vbuf, (sizeof vbuf / sizeof *vbuf));

    // Create a valarray of indices for a selector.
    selector_t::value_type sbuf[6] = {0,2,3,4,7,8};
    selector_t selector(sbuf, (sizeof sbuf / sizeof *sbuf));

    // Print out the valarray<int>.
    std::cout << "original valarray vi\n\n" << vi << "\n\n";

    // Print out the selective array.
    std::cout << "vi[0,2,3,4,7,8]\n\n" <<  vi[selector] << "\n\n";

    // Double the selected values.
    vi[selector] += vi[selector];

    // Print out the modified valarray.
    std::cout << "vi[0,2,3,4,7,8] += vi[0,2,3,4,7,8]\n\n" << vi << std::endl;

    return 0;
}
Exemple #8
0
TEST_F(VectorTest, Copy) {
  skelcl::Vector<int> vi(5);
  for(unsigned i = 0; i < 5; ++i) {
    vi[i] = 5;
  }

  EXPECT_FALSE(vi.empty());
  EXPECT_EQ(5, vi.size());
  for (unsigned i = 0; i < 5; ++i) {
    EXPECT_EQ(5, vi[i]);
  }

  skelcl::Vector<int> copy(vi);

  for (unsigned i = 0; i < 5; ++i) {
    vi[i] = 0;
  }

  EXPECT_FALSE(copy.empty());
  EXPECT_EQ(vi.size(), copy.size());
  for (unsigned i = 0; i < vi.size(); ++i) {
    EXPECT_EQ(5, copy[i]);
  }
}
Exemple #9
0
void test_cuba(){
    Cuba_common c;
    c.nvec    = 1;
    c.epsabs  = 0;
    c.epsrel  = 1e-4;
    c.flags   = 0x00;
    c.mineval = 10000;
    c.maxeval = 1000000;
    c.statefile = nullptr;
    c.spin      = nullptr;
    
    Integrator_vegas vi(c);
    vi.seed   = 1234;
    vi.nstart = 1000;
    vi.nincrease = 100;
    vi.nbatch = 100;
    vi.gridno = 0;
    
    Integrator_cuhre ci(c);
    ci.key = 0;
    
    run_integration_tests(vi,"Vegas");
    run_integration_tests(ci,"Cuhre");
}
// Parse triples: i, i/j/k, i//k, i/j
static vertex_index parseTriple(
  const char* &token,
  int vsize,
  int vnsize,
  int vtsize)
{
    vertex_index vi(-1);

    vi.v_idx = fixIndex(atoi(token), vsize);
    token += strcspn(token, "/ \t\r");
    if (token[0] != '/') {
      return vi;
    }
    token++;

    // i//k
    if (token[0] == '/') {
      token++;
      vi.vn_idx = fixIndex(atoi(token), vnsize);
      token += strcspn(token, "/ \t\r");
      return vi;
    }

    // i/j/k or i/j
    vi.vt_idx = fixIndex(atoi(token), vtsize);
    token += strcspn(token, "/ \t\r");
    if (token[0] != '/') {
      return vi;
    }

    // i/j/k
    token++;  // skip '/'
    vi.vn_idx = fixIndex(atoi(token), vnsize);
    token += strcspn(token, "/ \t\r");
    return vi;
}
void KX_NavMeshObject::DrawNavMesh(NavMeshRenderMode renderMode)
{
	if (!m_navMesh)
		return;
	MT_Vector3 color(0.f, 0.f, 0.f);
	
	switch (renderMode)
	{
	case RM_POLYS :
	case RM_WALLS : 
		for (int pi=0; pi<m_navMesh->getPolyCount(); pi++)
		{
			const dtStatPoly* poly = m_navMesh->getPoly(pi);

			for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++)
			{
				if (poly->n[j] && renderMode==RM_WALLS) 
					continue;
				const float* vif = m_navMesh->getVertex(poly->v[i]);
				const float* vjf = m_navMesh->getVertex(poly->v[j]);
				MT_Point3 vi(vif[0], vif[2], vif[1]);
				MT_Point3 vj(vjf[0], vjf[2], vjf[1]);
				vi = TransformToWorldCoords(vi);
				vj = TransformToWorldCoords(vj);
				KX_RasterizerDrawDebugLine(vi, vj, color);
			}
		}
		break;
	case RM_TRIS : 
		for (int i = 0; i < m_navMesh->getPolyDetailCount(); ++i)
		{
			const dtStatPoly* p = m_navMesh->getPoly(i);
			const dtStatPolyDetail* pd = m_navMesh->getPolyDetail(i);

			for (int j = 0; j < pd->ntris; ++j)
			{
				const unsigned char* t = m_navMesh->getDetailTri(pd->tbase+j);
				MT_Point3 tri[3];
				for (int k = 0; k < 3; ++k)
				{
					const float* v;
					if (t[k] < p->nv)
						v = m_navMesh->getVertex(p->v[t[k]]);
					else
						v =  m_navMesh->getDetailVertex(pd->vbase+(t[k]-p->nv));
					float pos[3];
					rcVcopy(pos, v);
					flipAxes(pos);
					tri[k].setValue(pos);
				}

				for (int k=0; k<3; k++)
					tri[k] = TransformToWorldCoords(tri[k]);

				for (int k=0; k<3; k++)
					KX_RasterizerDrawDebugLine(tri[k], tri[(k+1)%3], color);
			}
		}
		break;
	default:
		/* pass */
		break;
	}
}
Exemple #12
0
double LCOrbits::ArmCompute(int em, int rec, double trec)
{
	double tA(0.), tij;
	
	if ((em<1)||(em>NARMMAX)||((rec<1)&&(rec>NARMMAX))){
		std::cerr << "ERROR in LCOrbits::ArmCompute : Spacecraft number must be in [0," << NARMMAX << "]  ! " << Endl;
		throw std::invalid_argument ("ERROR in LCOrbits::ArmCompute : Spacecraft number must be in [0,NARMMAX]  ! ");
	}
	/*
	if(OrderArm != -10)
		OrderArm = order_default;
	if ((OrderArm<-2)||(OrderArm>2))
		throw std::invalid_argument ("ERROR in LCOrbits::ArmCompute : Order must be 0 (for 0), 1 (for 1/2), 2 (for 1) or -1 (for analytical MLDC eccentric formulation)");
	 */
	
	if(OrderArm >= 0){
		LCVector ri(MT), rj(MT), vi(MT), vj(MT), rij(MT), nij(MT), n(MT);
		
		/*! **** Read positions and velocities and compute related quantities
		 *	Index i refers to receiver and j to emitter
		 *  \f{eqnarray*}{
		 *	\vec{r}_{ij} & = & \vec{r}_j - \vec{r}_i = \vec{r}_{em} - \vec{r}_{rec}  \\
		 *	\vec{n}_{ij} & = & \vec{r}_{ij} / | \vec{r}_{ij} | \\
		 *	\hat{n}  & = & - \vec{n}_{ij} \\
		 *	t_{ij}   & = & - | \vec{r}_{ij} | / c = - | \vec{r}_{em} - \vec{r}_{rec} | / c
		 *  \f}
		 */ 
		
		ri = position(rec, trec);
		vi = velocity(rec, trec);
		vi = vi/LC::c_SI;
		
		rj = position(em, trec);
		vj = velocity(em, trec);
		vj = vj/LC::c_SI;
		
		/*
		ri.p[0] = 5.e9;
		ri.p[1] = 0.;
		ri.p[2] = 0.;
		rj.p[0] = -1.e-5;
		rj.p[1] = 0.;
		rj.p[2] = 0.;
		rij = rj-ri;
		*/
		
		 
		rij = rj-ri;
		nij = rij.unit();
		n = nij*(-1.);
		
		tij = rij.norm()/LC::c_SI;
		tij = -tij;  
		
		/*
		MT->o->precision(16);
		Cout << "em = " << em << "  -> rec = " << rec << " : " << rij.norm() << " ==> " << tij << Endl;
		for(int i=0; i<3; i++)
			Cout << "\t\t" << ri.p[i] << "\t\t" << rj.p[i] << "\t\t" << rij.p[i] << Endl;   
		*/
		 
		if (OrderArm>=0)
			tA += ArmOrderContrib(0, tij, ri, rj, vi, vj, rij, nij, n);
		
		if (OrderArm>=1)
			tA += ArmOrderContrib(1, tij, ri, rj, vi, vj, rij, nij, n);
		
		if (OrderArm>=2)
			tA += ArmOrderContrib(2, tij, ri, rj, vi, vj, rij, nij, n);
		
		return (tA);
			
	}else{
		return( ArmSpecific(em, rec, trec) );
	}
}
Exemple #13
0
PView *GMSH_HarmonicToTimePlugin::execute(PView * v)
{
  int rIndex = (int)HarmonicToTimeOptions_Number[0].def;
  int iIndex = (int)HarmonicToTimeOptions_Number[1].def;
  int nSteps = (int)HarmonicToTimeOptions_Number[2].def;
  int iView = (int)HarmonicToTimeOptions_Number[3].def;

  PView *v1 = getView(iView, v);
  if(!v1) return v;
  PViewData *data1 = v1->getData();

  if(data1->hasMultipleMeshes()){
    Msg::Error("HarmonicToTime plugin cannot be applied to multi-mesh views");
    return v1;
  }

  if(rIndex < 0 || rIndex >= data1->getNumTimeSteps() ||
     iIndex < 0 || iIndex >= data1->getNumTimeSteps()){
    Msg::Error("Wrong real or imaginary part index");
    return v1;
  }

  if(nSteps <= 0){
    Msg::Error("nSteps should be > 0");
    return v1;
  }

  PView *v2 = new PView();
  PViewDataList *data2 = getDataList(v2);
  
  for(int ent = 0; ent < data1->getNumEntities(0); ent++){
    for(int ele = 0; ele < data1->getNumElements(0, ent); ele++){
      if(data1->skipElement(0, ent, ele)) continue;
      int numNodes = data1->getNumNodes(0, ent, ele);
      int type = data1->getType(0, ent, ele);
      int numComp = data1->getNumComponents(0, ent, ele);
      std::vector<double> *out = data2->incrementList(numComp, type, numNodes);
      std::vector<double> x(numNodes), y(numNodes), z(numNodes);
      std::vector<double> vr(numNodes * numComp), vi(numNodes * numComp);
      for(int nod = 0; nod < numNodes; nod++){
        data1->getNode(0, ent, ele, nod, x[nod], y[nod], z[nod]);
        for(int comp = 0; comp < numComp; comp++){
          data1->getValue(rIndex, ent, ele, nod, comp, vr[numComp * nod + comp]);
          data1->getValue(iIndex, ent, ele, nod, comp, vi[numComp * nod + comp]);
        }
      }
      for(int nod = 0; nod < numNodes; nod++) out->push_back(x[nod]); 
      for(int nod = 0; nod < numNodes; nod++) out->push_back(y[nod]); 
      for(int nod = 0; nod < numNodes; nod++) out->push_back(z[nod]); 
      for(int t = 0; t < nSteps; t++) {
        double p = 2. * M_PI * t / nSteps;
        for(int nod = 0; nod < numNodes; nod++) {
          for(int comp = 0; comp < numComp; comp++) {
            double val = vr[numComp * nod + comp] * cos(p) - 
              vi[numComp * nod + comp] * sin(p);
            out->push_back(val);
          }
        }
      }
    }
  }

  for(int i = 0; i < nSteps; i++){
    double p = 2. * M_PI * i / (double)nSteps;
    data2->Time.push_back(p);
  }
  data2->setName(data1->getName() + "_HarmonicToTime");
  data2->setFileName(data1->getName() + "_HarmonicToTime.pos");
  data2->finalize();

  return v2;
}
Exemple #14
0
/*
 * editor --
 *	Main editor routine.
 *
 * PUBLIC: int editor(GS *, int, char *[]);
 */
int
editor(GS *gp, int argc, char *argv[])
{
	extern int optind;
	extern char *optarg;
	const char *p;
	EVENT ev;
	FREF *frp;
	SCR *sp;
	size_t len;
	u_int flags;
	int ch, flagchk, lflag, secure, startup, readonly, rval, silent;
	char *tag_f, *wsizearg, path[256];
	CHAR_T *w;
	size_t wlen;

	/* Initialize the busy routine, if not defined by the screen. */
	if (gp->scr_busy == NULL)
		gp->scr_busy = vs_busy;
	/* Initialize the message routine, if not defined by the screen. */
	if (gp->scr_msg == NULL)
		gp->scr_msg = vs_msg;
	gp->catd = (nl_catd)-1;

	/* Common global structure initialization. */
	TAILQ_INIT(gp->dq);
	TAILQ_INIT(gp->hq);
	SLIST_INIT(gp->ecq);
	SLIST_INSERT_HEAD(gp->ecq, &gp->excmd, q);
	gp->noprint = DEFAULT_NOPRINT;

	/* Structures shared by screens so stored in the GS structure. */
	TAILQ_INIT(gp->frefq);
	TAILQ_INIT(gp->dcb_store.textq);
	SLIST_INIT(gp->cutq);
	SLIST_INIT(gp->seqq);

	/* Set initial screen type and mode based on the program name. */
	readonly = 0;
	if (!strcmp(getprogname(), "ex") || !strcmp(getprogname(), "nex"))
		LF_INIT(SC_EX);
	else {
		/* Nview, view are readonly. */
		if (!strcmp(getprogname(), "nview") ||
		    !strcmp(getprogname(), "view"))
			readonly = 1;
		
		/* Vi is the default. */
		LF_INIT(SC_VI);
	}

	/* Convert old-style arguments into new-style ones. */
	if (v_obsolete(argv))
		return (1);

	/* Parse the arguments. */
	flagchk = '\0';
	tag_f = wsizearg = NULL;
	lflag = secure = silent = 0;
	startup = 1;

	/* Set the file snapshot flag. */
	F_SET(gp, G_SNAPSHOT);

#ifdef DEBUG
	while ((ch = getopt(argc, argv, "c:D:eFlRrSsT:t:vw:")) != EOF)
#else
	while ((ch = getopt(argc, argv, "c:eFlRrSst:vw:")) != EOF)
#endif
		switch (ch) {
		case 'c':		/* Run the command. */
			/*
			 * XXX
			 * We should support multiple -c options.
			 */
			if (gp->c_option != NULL) {
				warnx("only one -c command may be specified.");
				return (1);
			}
			gp->c_option = optarg;
			break;
#ifdef DEBUG
		case 'D':
			switch (optarg[0]) {
			case 's':
				startup = 0;
				break;
			case 'w':
				attach(gp);
				break;
			default:
				warnx("usage: -D requires s or w argument.");
				return (1);
			}
			break;
#endif
		case 'e':		/* Ex mode. */
			LF_CLR(SC_VI);
			LF_SET(SC_EX);
			break;
		case 'F':		/* No snapshot. */
			F_CLR(gp, G_SNAPSHOT);
			break;
		case 'l':		/* Set lisp, showmatch options. */
			lflag = 1;
			break;
		case 'R':		/* Readonly. */
			readonly = 1;
			break;
		case 'r':		/* Recover. */
			if (flagchk == 't') {
				warnx("only one of -r and -t may be specified.");
				return (1);
			}
			flagchk = 'r';
			break;
		case 'S':
			secure = 1;
			break;
		case 's':
			silent = 1;
			break;
#ifdef DEBUG
		case 'T':		/* Trace. */
			if ((gp->tracefp = fopen(optarg, "w")) == NULL) {
				warn("%s", optarg);
				goto err;
			}
			(void)fprintf(gp->tracefp,
			    "\n===\ntrace: open %s\n", optarg);
			break;
#endif
		case 't':		/* Tag. */
			if (flagchk == 'r') {
				warnx("only one of -r and -t may be specified.");
				return (1);
			}
			if (flagchk == 't') {
				warnx("only one tag file may be specified.");
				return (1);
			}
			flagchk = 't';
			tag_f = optarg;
			break;
		case 'v':		/* Vi mode. */
			LF_CLR(SC_EX);
			LF_SET(SC_VI);
			break;
		case 'w':
			wsizearg = optarg;
			break;
		case '?':
		default:
			(void)gp->scr_usage();
			return (1);
		}
	argc -= optind;
	argv += optind;

	/*
	 * -s option is only meaningful to ex.
	 *
	 * If not reading from a terminal, it's like -s was specified.
	 */
	if (silent && !LF_ISSET(SC_EX)) {
		warnx("-s option is only applicable to ex.");
		goto err;
	}
	if (LF_ISSET(SC_EX) && F_ISSET(gp, G_SCRIPTED))
		silent = 1;

	/*
	 * Build and initialize the first/current screen.  This is a bit
	 * tricky.  If an error is returned, we may or may not have a
	 * screen structure.  If we have a screen structure, put it on a
	 * display queue so that the error messages get displayed.
	 *
	 * !!!
	 * Everything we do until we go interactive is done in ex mode.
	 */
	if (screen_init(gp, NULL, &sp)) {
		if (sp != NULL)
			TAILQ_INSERT_HEAD(gp->dq, sp, q);
		goto err;
	}
	F_SET(sp, SC_EX);
	TAILQ_INSERT_HEAD(gp->dq, sp, q);

	if (v_key_init(sp))		/* Special key initialization. */
		goto err;

	{ int oargs[5], *oargp = oargs;
	if (lflag) {			/* Command-line options. */
		*oargp++ = O_LISP;
		*oargp++ = O_SHOWMATCH;
	}
	if (readonly)
		*oargp++ = O_READONLY;
	if (secure)
		*oargp++ = O_SECURE;
	*oargp = -1;			/* Options initialization. */
	if (opts_init(sp, oargs))
		goto err;
	}
	if (wsizearg != NULL) {
		ARGS *av[2], a, b;
		(void)snprintf(path, sizeof(path), "window=%s", wsizearg);
		a.bp = (CHAR_T *)path;
		a.len = strlen(path);
		b.bp = NULL;
		b.len = 0;
		av[0] = &a;
		av[1] = &b;
		(void)opts_set(sp, av, NULL);
	}
	if (silent) {			/* Ex batch mode option values. */
		O_CLR(sp, O_AUTOPRINT);
		O_CLR(sp, O_PROMPT);
		O_CLR(sp, O_VERBOSE);
		O_CLR(sp, O_WARN);
		F_SET(sp, SC_EX_SILENT);
	}

	sp->rows = O_VAL(sp, O_LINES);	/* Make ex formatting work. */
	sp->cols = O_VAL(sp, O_COLUMNS);

	if (!silent && startup) {	/* Read EXINIT, exrc files. */
		if (ex_exrc(sp))
			goto err;
		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
			if (screen_end(sp))
				goto err;
			goto done;
		}
	}

	/*
	 * List recovery files if -r specified without file arguments.
	 * Note, options must be initialized and startup information
	 * read before doing this.
	 */
	if (flagchk == 'r' && argv[0] == NULL) {
		if (rcv_list(sp))
			goto err;
		if (screen_end(sp))
			goto err;
		goto done;
	}

	/*
	 * !!!
	 * Initialize the default ^D, ^U scrolling value here, after the
	 * user has had every opportunity to set the window option.
	 *
	 * It's historic practice that changing the value of the window
	 * option did not alter the default scrolling value, only giving
	 * a count to ^D/^U did that.
	 */
	sp->defscroll = (O_VAL(sp, O_WINDOW) + 1) / 2;

	/*
	 * If we don't have a command-line option, switch into the right
	 * editor now, so that we position default files correctly, and
	 * so that any tags file file-already-locked messages are in the
	 * vi screen, not the ex screen.
	 *
	 * XXX
	 * If we have a command-line option, the error message can end
	 * up in the wrong place, but I think that the combination is
	 * unlikely.
	 */
	if (gp->c_option == NULL) {
		F_CLR(sp, SC_EX | SC_VI);
		F_SET(sp, LF_ISSET(SC_EX | SC_VI));
	}

	/* Open a tag file if specified. */
	if (tag_f != NULL) {
		CHAR2INT(sp, tag_f, strlen(tag_f) + 1, w, wlen);
		if (ex_tag_first(sp, w))
			goto err;
	}

	/*
	 * Append any remaining arguments as file names.  Files are recovery
	 * files if -r specified.  If the tag option or ex startup commands
	 * loaded a file, then any file arguments are going to come after it.
	 */
	if (*argv != NULL) {
		if (sp->frp != NULL) {
			/* Cheat -- we know we have an extra argv slot. */
			*--argv = strdup(sp->frp->name);
			if (*argv == NULL) {
				warn(NULL);
				goto err;
			}
		}
		sp->argv = sp->cargv = argv;
		F_SET(sp, SC_ARGNOFREE);
		if (flagchk == 'r')
			F_SET(sp, SC_ARGRECOVER);
	}

	/*
	 * If the ex startup commands and or/the tag option haven't already
	 * created a file, create one.  If no command-line files were given,
	 * use a temporary file.
	 */
	if (sp->frp == NULL) {
		if (sp->argv == NULL) {
			if ((frp = file_add(sp, NULL)) == NULL)
				goto err;
		} else  {
			if ((frp = file_add(sp, sp->argv[0])) == NULL)
				goto err;
			if (F_ISSET(sp, SC_ARGRECOVER))
				F_SET(frp, FR_RECOVER);
		}

		if (file_init(sp, frp, NULL, 0))
			goto err;
		if (EXCMD_RUNNING(gp)) {
			(void)ex_cmd(sp);
			if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
				if (screen_end(sp))
					goto err;
				goto done;
			}
		}
	}

	/*
	 * Check to see if we need to wait for ex.  If SC_SCR_EX is set, ex
	 * was forced to initialize the screen during startup.  We'd like to
	 * wait for a single character from the user, but we can't because
	 * we're not in raw mode.  We can't switch to raw mode because the
	 * vi initialization will switch to xterm's alternate screen, causing
	 * us to lose the messages we're pausing to make sure the user read.
	 * So, wait for a complete line.  
	 */
	if (F_ISSET(sp, SC_SCR_EX)) {
		p = msg_cmsg(sp, CMSG_CONT_R, &len);
		(void)write(STDOUT_FILENO, p, len);
		for (;;) {
			if (v_event_get(sp, &ev, 0, 0))
				goto err;
			if (ev.e_event == E_INTERRUPT ||
			    (ev.e_event == E_CHARACTER &&
			     (ev.e_value == K_CR || ev.e_value == K_NL)))
				break;
			(void)gp->scr_bell(sp);
		}
	}

	/* Switch into the right editor, regardless. */
	F_CLR(sp, SC_EX | SC_VI);
	F_SET(sp, LF_ISSET(SC_EX | SC_VI) | SC_STATUS_CNT);

	/*
	 * Main edit loop.  Vi handles split screens itself, we only return
	 * here when switching editor modes or restarting the screen.
	 */
	while (sp != NULL)
		if (F_ISSET(sp, SC_EX) ? ex(&sp) : vi(&sp))
			goto err;

done:	rval = 0;
	if (0)
err:		rval = 1;

	/* Clean out the global structure. */
	v_end(gp);

	return (rval);
}
Exemple #15
0
RefinedGeometry * GeometryRefiner::Refine (int Geom, int Times, int ETimes)
{
   int i, j, k, l;

   const double *cp = NULL;
   if (type)
      cp = poly1d.ClosedPoints(Times);

   switch (Geom)
   {
   case Geometry::SEGMENT:
   {
      const int g = Geometry::SEGMENT;
      if (RGeom[g] != NULL && RGeom[g]->Times == Times)
         return RGeom[g];
      delete RGeom[g];
      RGeom[g] = new RefinedGeometry(Times+1, 2*Times, 0);
      RGeom[g]->Times = Times;
      RGeom[g]->ETimes = 0;
      for (i = 0; i <= Times; i++)
      {
         IntegrationPoint &ip = RGeom[g]->RefPts.IntPoint(i);
         ip.x = (type == 0) ? double(i) / Times : cp[i];
      }
      Array<int> &G = RGeom[g]->RefGeoms;
      for (i = 0; i < Times; i++)
      {
         G[2*i+0] = i;
         G[2*i+1] = i+1;
      }

      return RGeom[g];
   }

   case Geometry::TRIANGLE:
   {
      if (RGeom[2] != NULL && RGeom[2]->Times == Times &&
          RGeom[2]->ETimes == ETimes)
         return RGeom[2];

      if (RGeom[2] != NULL)
         delete RGeom[2];
      RGeom[2] = new RefinedGeometry ((Times+1)*(Times+2)/2, 3*Times*Times,
                                      3*Times*(ETimes+1));
      RGeom[2]->Times = Times;
      RGeom[2]->ETimes = ETimes;
      for (k = j = 0; j <= Times; j++)
         for (i = 0; i <= Times-j; i++, k++)
         {
            IntegrationPoint &ip = RGeom[2]->RefPts.IntPoint(k);
            if (type == 0)
            {
               ip.x = double(i) / Times;
               ip.y = double(j) / Times;
            }
            else
            {
               ip.x = cp[i]/(cp[i] + cp[j] + cp[Times-i-j]);
               ip.y = cp[j]/(cp[i] + cp[j] + cp[Times-i-j]);
            }
         }
      Array<int> &G = RGeom[2]->RefGeoms;
      for (l = k = j = 0; j < Times; j++, k++)
         for (i = 0; i < Times-j; i++, k++)
         {
            G[l++] = k;
            G[l++] = k+1;
            G[l++] = k+Times-j+1;
            if (i+j+1 < Times)
            {
               G[l++] = k+1;
               G[l++] = k+Times-j+2;
               G[l++] = k+Times-j+1;
            }
         }
      Array<int> &E = RGeom[2]->RefEdges;
      // horizontal edges
      for (l = k = 0; k < Times; k += Times/ETimes)
      {
         j = k*(Times+1)-((k-1)*k)/2;
         for (i = 0; i < Times-k; i++)
         {
            E[l++] = j; j++;
            E[l++] = j;
         }
      }
      // diagonal edges
      for (k = Times; k > 0; k -= Times/ETimes)
      {
         j = k;
         for (i = 0; i < k; i++)
         {
            E[l++] = j; j += Times-i;
            E[l++] = j;
         }
      }
      // vertical edges
      for (k = 0; k < Times; k += Times/ETimes)
      {
         j = k;
         for (i = 0; i < Times-k; i++)
         {
            E[l++] = j; j += Times-i+1;
            E[l++] = j;
         }
      }

      return RGeom[2];
   }

   case Geometry::SQUARE:
   {
      if (RGeom[3] != NULL && RGeom[3]->Times == Times &&
          RGeom[3]->ETimes == ETimes)
         return RGeom[3];

      if (RGeom[3] != NULL)
         delete RGeom[3];
      RGeom[3] = new RefinedGeometry ((Times+1)*(Times+1), 4*Times*Times,
                                      4*(ETimes+1)*Times);
      RGeom[3]->Times = Times;
      RGeom[3]->ETimes = ETimes;
      for (k = j = 0; j <= Times; j++)
         for (i = 0; i <= Times; i++, k++)
         {
            IntegrationPoint &ip = RGeom[3]->RefPts.IntPoint(k);
            if (type == 0)
            {
               ip.x = double(i) / Times;
               ip.y = double(j) / Times;
            }
            else
            {
               ip.x = cp[i];
               ip.y = cp[j];
            }
         }
      Array<int> &G = RGeom[3]->RefGeoms;
      for (l = k = j = 0; j < Times; j++, k++)
         for (i = 0; i < Times; i++, k++)
         {
            G[l++] = k;
            G[l++] = k+1;
            G[l++] = k+Times+2;
            G[l++] = k+Times+1;
         }
      Array<int> &E = RGeom[3]->RefEdges;
      // horizontal edges
      for (l = k = 0; k <= Times; k += Times/ETimes)
      {
         for (i = 0, j = k*(Times+1); i < Times; i++)
         {
            E[l++] = j; j++;
            E[l++] = j;
         }
      }
      // vertical edges (in right-to-left order)
      for (k = Times; k >= 0; k -= Times/ETimes)
      {
         for (i = 0, j = k; i < Times; i++)
         {
            E[l++] = j; j += Times+1;
            E[l++] = j;
         }
      }

      return RGeom[3];
   }

   case Geometry::CUBE:
   {
      const int g = Geometry::CUBE;
      if (RGeom[g] != NULL && RGeom[g]->Times == Times &&
          RGeom[g]->ETimes == ETimes)
         return RGeom[g];

      if (RGeom[g] != NULL)
         delete RGeom[g];
      RGeom[g] = new RefinedGeometry ((Times+1)*(Times+1)*(Times+1),
                                      8*Times*Times*Times, 0);
      RGeom[g]->Times = Times;
      RGeom[g]->ETimes = ETimes;
      for (l = k = 0; k <= Times; k++)
         for (j = 0; j <= Times; j++)
            for (i = 0; i <= Times; i++, l++)
            {
               IntegrationPoint &ip = RGeom[g]->RefPts.IntPoint(l);
               if (type == 0)
               {
                  ip.x = double(i) / Times;
                  ip.y = double(j) / Times;
                  ip.z = double(k) / Times;
               }
               else
               {
                  ip.x = cp[i];
                  ip.y = cp[j];
                  ip.z = cp[k];
               }
            }
      Array<int> &G = RGeom[g]->RefGeoms;
      for (l = k = 0; k < Times; k++)
         for (j = 0; j < Times; j++)
            for (i = 0; i < Times; i++)
            {
               G[l++] = i+0 + (j+0 + (k+0) * (Times+1)) * (Times+1);
               G[l++] = i+1 + (j+0 + (k+0) * (Times+1)) * (Times+1);
               G[l++] = i+1 + (j+1 + (k+0) * (Times+1)) * (Times+1);
               G[l++] = i+0 + (j+1 + (k+0) * (Times+1)) * (Times+1);
               G[l++] = i+0 + (j+0 + (k+1) * (Times+1)) * (Times+1);
               G[l++] = i+1 + (j+0 + (k+1) * (Times+1)) * (Times+1);
               G[l++] = i+1 + (j+1 + (k+1) * (Times+1)) * (Times+1);
               G[l++] = i+0 + (j+1 + (k+1) * (Times+1)) * (Times+1);
            }

      return RGeom[g];
   }

   case Geometry::TETRAHEDRON:
   {
      const int g = Geometry::TETRAHEDRON;
      if (RGeom[g] != NULL && RGeom[g]->Times == Times &&
          RGeom[g]->ETimes == ETimes)
         return RGeom[g];

      if (RGeom[g] != NULL)
         delete RGeom[g];

      // subdivide the tetrahedron with vertices
      // (0,0,0), (0,0,1), (1,1,1), (0,1,1)

      // vertices: 0 <= i <= j <= k <= Times
      // (3-combination with repetitions)
      // number of vertices: (n+3)*(n+2)*(n+1)/6, n = Times

      // elements: the vertices are: v1=(i,j,k), v2=v1+u1, v3=v2+u2, v4=v3+u3
      // where 0 <= i <= j <= k <= n-1 and
      // u1,u2,u3 is a permutation of (1,0,0),(0,1,0),(0,0,1)
      // such that all v2,v3,v4 have non-decreasing components
      // number of elements: n^3

      const int n = Times;
      RGeom[g] = new RefinedGeometry((n+3)*(n+2)*(n+1)/6, 4*n*n*n, 0);
      // enumerate and define the vertices
      Array<int> vi((n+1)*(n+1)*(n+1));
      vi = -1;
      int m = 0;
      for (k = 0; k <= n; k++)
         for (j = 0; j <= k; j++)
            for (i = 0; i <= j; i++)
            {
               IntegrationPoint &ip = RGeom[g]->RefPts.IntPoint(m);
               // map the coordinates to the reference tetrahedron
               // (0,0,0) -> (0,0,0)
               // (0,0,1) -> (1,0,0)
               // (1,1,1) -> (0,1,0)
               // (0,1,1) -> (0,0,1)
               if (type == 0)
               {
                  ip.x = double(k - j) / n;
                  ip.y = double(i) / n;
                  ip.z = double(j - i) / n;
               }
               else
               {
                  double w = cp[k-j] + cp[i] + cp[j-i] + cp[Times-k];
                  ip.x = cp[k-j]/w;
                  ip.y = cp[i]/w;
                  ip.z = cp[j-i]/w;
               }
               l = i + (j + k * (n+1)) * (n+1);
               vi[l] = m;
               m++;
            }
      if (m != (n+3)*(n+2)*(n+1)/6)
         mfem_error("GeometryRefiner::Refine() for TETRAHEDRON #1");
      // elements
      Array<int> &G = RGeom[g]->RefGeoms;
      m = 0;
      for (k = 0; k < n; k++)
         for (j = 0; j <= k; j++)
            for (i = 0; i <= j; i++)
            {
               // the ordering of the vertices is chosen to ensure:
               // 1) correct orientation
               // 2) the x,y,z edges are in the set of edges
               //    {(0,1),(2,3), (0,2),(1,3)}
               //    (goal is to ensure that subsequent refinement using
               //    this procedure preserves the six tetrahedral shapes)

               // zyx: (i,j,k)-(i,j,k+1)-(i+1,j+1,k+1)-(i,j+1,k+1)
               G[m++] = vi[i+0 + (j+0 + (k+0) * (n+1)) * (n+1)];
               G[m++] = vi[i+0 + (j+0 + (k+1) * (n+1)) * (n+1)];
               G[m++] = vi[i+1 + (j+1 + (k+1) * (n+1)) * (n+1)];
               G[m++] = vi[i+0 + (j+1 + (k+1) * (n+1)) * (n+1)];
               if (j < k)
               {
                  // yzx: (i,j,k)-(i+1,j+1,k+1)-(i,j+1,k)-(i,j+1,k+1)
                  G[m++] = vi[i+0 + (j+0 + (k+0) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+1 + (k+1) * (n+1)) * (n+1)];
                  G[m++] = vi[i+0 + (j+1 + (k+0) * (n+1)) * (n+1)];
                  G[m++] = vi[i+0 + (j+1 + (k+1) * (n+1)) * (n+1)];
                  // yxz: (i,j,k)-(i,j+1,k)-(i+1,j+1,k+1)-(i+1,j+1,k)
                  G[m++] = vi[i+0 + (j+0 + (k+0) * (n+1)) * (n+1)];
                  G[m++] = vi[i+0 + (j+1 + (k+0) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+1 + (k+1) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+1 + (k+0) * (n+1)) * (n+1)];
               }
               if (i < j)
               {
                  // xzy: (i,j,k)-(i+1,j,k)-(i+1,j+1,k+1)-(i+1,j,k+1)
                  G[m++] = vi[i+0 + (j+0 + (k+0) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+0 + (k+0) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+1 + (k+1) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+0 + (k+1) * (n+1)) * (n+1)];
                  if (j < k)
                  {
                     // xyz: (i,j,k)-(i+1,j+1,k+1)-(i+1,j,k)-(i+1,j+1,k)
                     G[m++] = vi[i+0 + (j+0 + (k+0) * (n+1)) * (n+1)];
                     G[m++] = vi[i+1 + (j+1 + (k+1) * (n+1)) * (n+1)];
                     G[m++] = vi[i+1 + (j+0 + (k+0) * (n+1)) * (n+1)];
                     G[m++] = vi[i+1 + (j+1 + (k+0) * (n+1)) * (n+1)];
                  }
                  // zxy: (i,j,k)-(i+1,j+1,k+1)-(i,j,k+1)-(i+1,j,k+1)
                  G[m++] = vi[i+0 + (j+0 + (k+0) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+1 + (k+1) * (n+1)) * (n+1)];
                  G[m++] = vi[i+0 + (j+0 + (k+1) * (n+1)) * (n+1)];
                  G[m++] = vi[i+1 + (j+0 + (k+1) * (n+1)) * (n+1)];
               }
            }
      if (m != 4*n*n*n)
         mfem_error("GeometryRefiner::Refine() for TETRAHEDRON #2");
      for (i = 0; i < m; i++)
         if (G[i] < 0)
            mfem_error("GeometryRefiner::Refine() for TETRAHEDRON #3");

      return RGeom[g];
   }

   default:

      return RGeom[0];
   }
}
Exemple #16
0
            int A, B, C, D;
            in >> A >> B >> C >> D;
            X1[i] = min(A, C);
            Y1[i] = min(B, D);
            X2[i] = max(A, C);
            Y2[i] = max(B, D);
        }
        X1[N] = S;
        Y1[N] = T;
        X2[N] = U;
        Y2[N] = V;

        W = compress(X1, X2, W)+1;
        H = compress(Y1, Y2, H)+1;

        vvi maze(W+2, vi(H+2, 0));
        rep(i, N) {
            rep(j, N) {
                rer(k, X1[i], X2[i]) {
                    rer(l, Y1[j], Y2[j]) {
                        maze[k][l] = -1;
                    }
                }
            }
        }

        Q.push(pii(4, pi(X1[N], Y1[N])));
        maze[X1[N]][Y1[N]] = 0;
        while (!Q.empty())
        {
            pii tmp = Q.front();
void CalculateAngleDerivativesE2(vtkPolyData* mesh, const arma::sp_mat& edge_lengths, const arma::vec& radii) {
    //calculate the power center for each triangle as follows
    //for 2 circles centered at c1 and c2 solve for p:
    //|p-c1|^2 - r1^2 = |p-c2|^2 - r2^2    -- this is power line
    //add one more condition for the third circle to get one point
    //  Funny part: the paper says that the circle of radius sqrt(|c1-p|^2 - r1^2)
    //  is perpendicular to all three circles. But this works only when the 3 circles do not intersect
    const int npts = mesh->GetNumberOfPoints();
    const int ncells = mesh->GetNumberOfCells();

    vtkSmartPointer<vtkIdList> cellIdList = vtkSmartPointer<vtkIdList>::New();
    vtkSmartPointer<vtkIdList> pointIdList = vtkSmartPointer<vtkIdList>::New();

    //for every face calculate gamma_ijk
    arma::vec gamma_percell(ncells);
    for (vtkIdType i = 0; i < ncells; i++) {
        pointIdList->Reset();
        mesh->GetCellPoints(cellIdList->GetId(i), pointIdList);


        const int ind_i = pointIdList->GetId(0);
        const int ind_j = pointIdList->GetId(1);
        const int ind_k = pointIdList->GetId(2);

        const double ri = radii[ind_i];
        const double rj = radii[ind_j];
        const double rk = radii[ind_k];

        arma::vec ci(3), cj(3), ck(3);
        mesh->GetPoint(ind_i, ci.memptr());
        mesh->GetPoint(ind_j, cj.memptr());
        mesh->GetPoint(ind_k, ck.memptr());

        //create local 2D coordinates, and map vertices
        arma::vec vji = cj - ci;
        arma::vec v   = ck - ci;

        arma::vec n = arma::cross(vji, v); //normal
        arma::vec vki = arma::cross(n, vji); //creates local y' axis

        const double lenX = arma::norm(vji,2);
        const double lenY = arma::norm(vki,2);
        
        vji /= lenX; //normalize axes
        vki /= lenY;
        
        //2D coordinates
        arma::vec vi(3,0); //(0,0)
        arma::vec vj(3);
        arma::vec vk(3);

        vj(0) = lenX;
        vj(1) = 0.0;
        vk(0) = arma::dot(v, vji);
        vk(1) = arma::dot(v, vki);
        
        //form matrices for system of linear equations and solve
        //A = [2*(c2-c1)'; 2*(c2-c3)'];
        //B = [ c2'*c2 - c1'*c1 + r1^2 - r2^2; c2'*c2 - c3'*c3 + r3^2 - r2^2];
        //P = A\B;
        arma::mat A(2,2);
        arma::vec B(2);
        
        A.insert_rows( 0, 2.0*(cj-ci) );
        A.insert_rows( 1, 2.0*(cj-ck) );
        B(0) = arma::dot(cj, cj) - arma::dot(ci, ci) + ri*ri - rj*rj;
        B(1) = arma::dot(cj, cj) - arma::dot(ck, ck) + rk*rk - rj*rj;
        arma::vec P = arma::solve( A, B ); 
        
        //calculate distance from P to all the edges: hi, hj, hk
        //http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
        const double hi = arma::norm( arma::cross(cj-ck, ck-P), 2 ) / arma::norm(cj-ck, 2);
        const double hj = arma::norm( arma::cross(ci-ck, ck-P), 2 ) / arma::norm(ci-ck, 2);
        const double hk = arma::norm( arma::cross(cj-ci, ci-P), 2 ) / arma::norm(cj-ci, 2);
        
        const double li = edge_lengths(ind_j, ind_k);
        const double lj = edge_lengths(ind_i, ind_k);
        const double lk = edge_lengths(ind_i, ind_j);
        
        const double dTi_duj = hk/lk;
        const double dTj_duk = hi/li;
        const double dTk_dui = hj/lj;

        const double dTi_dui = - dTi_duj - dTk_dui;
        const double dTj_duj = - dTj_duk - dTi_duj;
        const double dTk_duk = - dTj_duk - dTk_dui;


    }
    
    
    
}
Exemple #18
0
Bool MeshRoot::MRMGen( List<U16> * verts) // = NULL)
{
#ifndef DOMRMGEN
  verts;

  return FALSE;

#else

	// Initialize COM:
	CoInitialize(NULL);

	// Ok, Now create the mrmgen COM object:
	IMRMGen2 * s_lpMRMGen = NULL;
	HRESULT hr = CoCreateInstance(CLSID_CMRMGEN, NULL, CLSCTX_INPROC_SERVER, IID_IMRMGEN2,(void ** ) &s_lpMRMGen);

	// Did we get a valid interface:
  if( (FAILED(hr)) || (!(s_lpMRMGen)) ) 
	{
    LOG_DIAG( ("couldn't connect to mrmgen.dll; is it registered?") );
    return FALSE;
	}

  IMESH *imesh = new IMESH;
	initIMESH( imesh);

  MeshRootToIMesh( *this, *imesh);

//#define DOWRITEMRM
#ifdef DOWRITEMRM
	MRMWrite( imesh, NULL, "in.mrm");
#endif

	Utils::Memset( &params, 0, sizeof( params));
	params.size = sizeof(MRMGenParams);
	params.flags = 0;  // no parameters are valid
  params.flags |= MRMGP_MERGETHRESH | MRMGP_NORMALSMODE | MRMGP_CREASEANGLE;
  params.mergeThresh = Vid::Var::mrmMergeThresh;
  params.normalsCreaseAngle = Vid::Var::mrmNormalCrease;
 	params.normalsMode = Vid::Var::mrmMultiNormals ? PerFacePerVertex : PerVertex;

#define VERTTHRESH  0.1f

  // automatic shadow plane base verts
  //
  U32 baseCount = 0, heapSize = vertices.count << 2;
  U32 * baseIndices = (U32 *) Vid::Heap::Request( heapSize);

  if (shadowPlane)
  {
    Mesh *mesh = NULL;
    U32 i, j;
    for (i = 0; i < states.count; i++)
    {
    	if (!strnicmp(states[i].GetMeshFromRoot()->name.str, "sp-", 3))
      {
        mesh = states[i].GetMeshFromRoot();
        break;
      }
    }
    if (mesh && mesh->local)
    {
      for (i = 0; i < mesh->local->vertices.count; i++)
      {
        Vector v0;
        mesh->WorldMatrix().Transform( v0, mesh->local->vertices[i]);

        for (j = 0; j < vertices.count; j++)
        {
          Vector &v1 = vertices[j];
          if ((F32)fabs(v0.x - v1.x) < VERTTHRESH
           && (F32)fabs(v0.y - v1.y) < VERTTHRESH
           && (F32)fabs(v0.z - v1.z) < VERTTHRESH)
          {
            baseIndices[baseCount] = j;
            baseCount++;
          }
        }
      }
    }
  }

  // selected base verts
  //
  if (verts)
  {
    U32 startBaseCount = baseCount;

    List<U16>::Iterator vi( verts);
    U16 * index;
    while ((index = vi++) != NULL)
    {
      U32 i, hit = FALSE; 
      for (i = 0; i < startBaseCount; i++)
      {
        if (*index == baseIndices[i])
        {
          hit = TRUE;
          break;
        }
      }
      if (!hit)
      {
        baseIndices[baseCount] = *index;
        baseCount++;
      }
    }
  } 

  if (baseCount)
  {
    params.flags |= MRMGP_NUMBASEVERTICES;
    params.numBaseVertices = baseCount;
    params.baseVertices = baseIndices;
    LOG_DIAG( ("MeshRoot::MRMGen: baseCount = %d", baseCount) );
  }

  MRMResults *mrmResults;

  // Invoke the algorithm and collect the results:
	s_lpMRMGen->GenerateMRM(imesh, &params, &mrmResults);

  // baseIndices
  Vid::Heap::Restore( heapSize);

  MRMUpdates *mrmUpdates = mrmResults->pMrmUpdates;
  if (!mrmUpdates)
  {
    // Free memory associated with the results:
	  s_lpMRMGen->FreeMRMResults(mrmResults);

  	// Release memory:
	  freeIMESH( imesh);

  	hr = s_lpMRMGen->Release();

	// Shut down COM:
  	CoUninitialize();

    return FALSE;
  }
  IMESH *orderedImesh = mrmResults->pIMesh;

//  ASSERT( orderedImesh->numFaces == faces.count);

#ifdef DOWRITEMRM
	MRMWrite (orderedImesh, mrmUpdates, "out.mrm");
#endif

  // copy ordered geometry data, if its not empty
  //
  if ((orderedImesh->numVertices == 0 || orderedImesh->numFaces == 0) 
   || !IMeshToMeshRoot( *this, *orderedImesh, *mrmResults))
  {
    // Free memory associated with the results:
	  s_lpMRMGen->FreeMRMResults(mrmResults);

  	// Release memory:
	  freeIMESH( imesh);

  	hr = s_lpMRMGen->Release();

	// Shut down COM:
  	CoUninitialize();

    return FALSE;
  }

  if (verts)
  {
    List<U16>::Iterator vi( verts);
    U16 * index;
    while ((index = vi++) != NULL)
    {
      if (mrmResults->pVertexMap[*index] == mrmResults->undefIndexValue)
      {
        verts->Unlink( index);
      }
      else
      {
        *index = (U16) mrmResults->pVertexMap[*index];
      }
    }
  }

  // allocate mrm data
  if (mrm)
  {
    delete mrm;
    mrm = NULL;
  }

  mrm = new MRM;
  ASSERT( mrm);
  mrm->vertCount = (U16)orderedImesh->numVertices;
  mrm->maxVertCount = mrm->vertCount;
  mrm->minMinVertCount = U16(baseCount > 7 ? baseCount : 7);
  if (mrm->minMinVertCount > mrm->vertCount)
  {
    mrm->minMinVertCount = mrm->vertCount;
  }
  mrm->minVertCount = mrm->minMinVertCount;

  mrm->vertex = new MRM::Vertex[mrm->vertCount];
  ASSERT( mrm->vertex);

//#define DOWRITEDATA
#ifdef DOWRITEDATA
  FILE *fp;
  fp = fopen( "mrmdata.txt", "w");
#endif

  FaceUpdate *update;
  // count total number of faceupdates
  U32 i, j, l, k = 0;
  for (i = 0; i < mrm->vertCount; i++)
  {
    U16 numfu = mrmUpdates->vertexUpdates[i].numFaceUpdates;
#ifdef DOWRITEDATA
    fprintf( fp, "\nverts %d : newfaces %d : faceupdates %d\n", 
      i, mrmUpdates->vertexUpdates[i].numNewFaces, numfu);
#endif
    for (j = l = 0; j < numfu; j++)
    {
      update = &mrmUpdates->vertexUpdates[i].faceUpdates[j];

      // validate mrm data
	    switch (update->attribToken)
		  {
		  case VertexA:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : VertexA %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
        l++;
			  break;
		  case VertexB:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : VertexB %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
        l++;
			  break;
		  case VertexC:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : VertexC %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
        l++;
			  break;

		  case NormalA:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : NormalA %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
//        if (!indexed)
        {
          l++;
        }
			  break;
      case NormalB:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : NormalB %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
//        if (!indexed)
        {
          l++;
        }
			  break;
		  case NormalC:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : NormalC %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
//        if (!indexed)
        {
          l++;
        }
			  break;

		  case TexCoord1A:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : TexCrdA %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
//        if (!indexed)
        {
          l++;
        }
			  break;
		  case TexCoord1B:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : TexCrdB %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
//        if (!indexed)
        {
          l++;
        }
			  break;
		  case TexCoord1C:
#ifdef DOWRITEDATA
        fprintf( fp, "face %d : TexCrdC %d : %d\n", update->faceIndex, update->value[0], update->value[1]);
#endif
//        if (!indexed)
        {
          l++;
        }
			  break;
		  }
    }
    mrmUpdates->vertexUpdates[i].numFaceUpdates = (U16) l;
    k += l;
  }
#ifdef DOWRITEDATA
  if (fp)
  {
    fclose(fp);
  }
#endif

  if (k == 0)
  {
    // Free memory associated with the results:
	  s_lpMRMGen->FreeMRMResults(mrmResults);

  	// Release memory:
	  freeIMESH( imesh);

  	hr = s_lpMRMGen->Release();

	// Shut down COM:
  	CoUninitialize();


    delete [] mrm->vertex;
    delete mrm;
    mrm = NULL;

    return FALSE;
  }

  mrm->faceCount = (U16)k;
  MRM::Face *mrmFace = new MRM::Face[k];
  ASSERT( mrmFace);
  mrm->vertex[0].face = mrmFace;

  // copy mrm data
  for (i = 0; i < mrm->vertCount; i++)
  {
    U16 numfu = mrmUpdates->vertexUpdates[i].numFaceUpdates;
    mrm->vertex[i].faceCount = numfu;
//    mrmUpdates->vertexUpdates[i].numFaceUpdates = (U16) numfu;
    mrm->vertex[i].face = mrmFace;
    mrm->vertex[i].newFaceCount = mrmUpdates->vertexUpdates[i].numNewFaces;
    mrm->vertex[i].newNormCount = mrmUpdates->vertexUpdates[i].numNewNormals;
    mrm->vertex[i].newTextCount = mrmUpdates->vertexUpdates[i].numNewTexCoords;

    for (j = 0; j < numfu; j++)
    {
      // validate mrm data
      FaceUpdate &fupdate = mrmUpdates->vertexUpdates[i].faceUpdates[j];
	    switch (fupdate.attribToken)
		  {
		  case VertexA:
		  case VertexB:
		  case VertexC:
        ASSERT( fupdate.value[0] < vertices.count);
        ASSERT( fupdate.value[1] < vertices.count);

        mrmFace->token = (MRM::Face::Token) fupdate.attribToken;
        mrmFace->index[0] = (U16) fupdate.value[0];
        mrmFace->index[1] = (U16) fupdate.value[1];
        mrmFace->face = (U16) fupdate.faceIndex;
        mrmFace++;
			  break;
		  case NormalA:
		  case NormalB:
		  case NormalC:
//        if (!indexed)
        ASSERT( fupdate.value[0] < normals.count);
        ASSERT( fupdate.value[1] < normals.count);

        mrmFace->token = (MRM::Face::Token) fupdate.attribToken;
        mrmFace->index[0] = (U16) fupdate.value[0];
        mrmFace->index[1] = (U16) fupdate.value[1];
        mrmFace->face = (U16) fupdate.faceIndex;
        mrmFace++;
  		  break;
		  case TexCoord1A:
		  case TexCoord1B:
		  case TexCoord1C:
//        if (!indexed)
        ASSERT( fupdate.value[0] < uvs.count);
        ASSERT( fupdate.value[1] < uvs.count);

        mrmFace->token = (MRM::Face::Token) fupdate.attribToken;
        mrmFace->index[0] = (U16) fupdate.value[0];
        mrmFace->index[1] = (U16) fupdate.value[1];
        mrmFace->face = (U16) fupdate.faceIndex;
        mrmFace++;
			  break;
		  }
    }
  }

  // Free memory associated with the results:
	s_lpMRMGen->FreeMRMResults(mrmResults);

	// Release memory:
	freeIMESH( imesh);

	hr = s_lpMRMGen->Release();

	// Shut down COM:
	CoUninitialize();

  Setup();
	SetupPlanes();
	CalcBoundingSphere();
  SortFaces();

  return TRUE;
#endif
}
Exemple #19
0
void ModernPosit::run(cv::Mat &rot, cv::Point3f &trans, std::vector<cv::Point2f> imagePts, std::vector<cv::Point3f> worldPts, double focalLength, cv::Point2f center, int maxIterations)
{
	int nbPoints = imagePts.size();

	std::vector<cv::Point2f>::iterator imagePtsIt;
	std::vector<cv::Point2f> centeredImage;
	for (imagePtsIt = imagePts.begin(); imagePtsIt != imagePts.end(); ++imagePtsIt)
		centeredImage.push_back(*imagePtsIt - center);
	for (imagePtsIt = centeredImage.begin(); imagePtsIt != centeredImage.end(); ++imagePtsIt)
	{
		imagePtsIt->x /= focalLength;
		imagePtsIt->y /= focalLength;
	}

	std::vector<double> ui(nbPoints);
	std::vector<double> vi(nbPoints);
	std::vector<double> oldUi(nbPoints);
	std::vector<double> oldVi(nbPoints);
	std::vector<double> deltaUi(nbPoints);
	std::vector<double> deltaVi(nbPoints);

	/*double ui[nbPoints];
	double vi[nbPoints];
	double oldUi[nbPoints];
	double oldVi[nbPoints];
	double deltaUi[nbPoints];
	double deltaVi[nbPoints];*/
	for (int i = 0; i < nbPoints; ++i)
	{
		ui[i] = centeredImage[i].x;
		vi[i] = centeredImage[i].y;
	}

	cv::Mat homogeneousWorldPts(nbPoints,4,CV_32F);
	for (int i = 0; i < nbPoints; ++i)
	{
		cv::Point3f worldPoint = worldPts[i];
		homogeneousWorldPts.at<float>(i,0) = worldPoint.x;
		homogeneousWorldPts.at<float>(i,1) = worldPoint.y;
		homogeneousWorldPts.at<float>(i,2) = worldPoint.z;
		homogeneousWorldPts.at<float>(i,3) = 1; // homogeneous
	}

	cv::Mat objectMat;
	cv::invert(homogeneousWorldPts,objectMat,cv::DECOMP_SVD);

	/*
	std::cout << "objectmat: " << std::endl;
	for (int j = 0; j < 4; ++j)
	{
		for (int i = 0; i < nbPoints; ++i)
			std::cout << objectMat.at<float>(j,i) << " ";
		std::cout << std::endl;
	}
	*/

	bool converged = false;
	int iterationCount = 0;

	double Tx = 0.0;
	double Ty = 0.0;
	double Tz = 0.0;
	double r1T[4];
	double r2T[4];
	double r1N[4];
	double r2N[4];
	double r3[4];

	while ((!converged) && ((maxIterations < 0 ) || (iterationCount < maxIterations)))
	{
		// r1T= objectMat * ui; % pose vectors
		// r2T = objectMat * vi;
		for (int j=0; j < 4; ++j)
		{
			r1T[j] = 0;
			r2T[j] = 0;
			for (int i=0; i < nbPoints; ++i)
			{
				r1T[j] += ui[i] * objectMat.at<float>(j,i);
				r2T[j] += vi[i] * objectMat.at<float>(j,i);
			}
		}

		// Tz1 = 1/sqrt(r1T(1)*r1T(1) + r1T(2)*r1T(2)+ r1T(3)*r1T(3)); % 1/Tz1 is norm of r1T
		// Tz2 = 1/sqrt(r2T(1)*r2T(1) + r2T(2)*r2T(2)+ r2T(3)*r2T(3)); % 1/Tz2 is norm of r2T
		double Tz1,Tz2;
		Tz1 = 1/sqrt(r1T[0]*r1T[0] + r1T[1]*r1T[1]+ r1T[2]*r1T[2]);
		Tz2 = 1/sqrt(r2T[0]*r2T[0] + r2T[1]*r2T[1]+ r2T[2]*r2T[2]);

		// Tz = sqrt(Tz1*Tz2); % geometric average instead of arithmetic average of classicPosit.m
		Tz = sqrt(Tz1*Tz2);

		for (int j=0; j < 4; ++j)
		{
			r1N[j] = r1T[j]*Tz;
			r2N[j] = r2T[j]*Tz;
		}

		// DEBUG
		for (int j=0; j < 3; ++j)
		{
			if ((r1N[j] > 1.0) || (r1N[j] < -1.0))
			{
				//std::cout << "WARNING: r1N[" << j << "] == " << r1N[j] << std::endl;
				r1N[j] = std::max(-1.0,std::min(1.0,r1N[j]));
			}
			if ((r2N[j] > 1.0) || (r2N[j] < -1.0))
			{
				//std::cout << "WARNING: r2N[" << j << "] == " << r2N[j] << std::endl;
				r2N[j] = std::max(-1.0,std::min(1.0,r2N[j]));
			}
		}

		// r1 = r1N(1:3);
		// r2 = r2N(1:3);
		// r3 = cross(r1,r2);
		// r3T= [r3; Tz];
		r3[0] = r1N[1]*r2N[2] - r1N[2]*r2N[1];
		r3[1] = r1N[2]*r2N[0] - r1N[0]*r2N[2];
		r3[2] = r1N[0]*r2N[1] - r1N[1]*r2N[0];
		r3[3] = Tz;

		Tx = r1N[3];
		Ty = r2N[3];

		// wi= homogeneousWorldPts * r3T /Tz;
		
		std::vector<double> wi(nbPoints);
		//double wi[nbPoints];
		
		for (int i = 0; i < nbPoints; ++i)
		{
			wi[i] = 0;
			for (int j = 0; j < 4; ++j)
				wi[i] += homogeneousWorldPts.at<float>(i,j) * r3[j] / Tz;
		}

		// oldUi = ui;
		// oldVi = vi;
		// ui = wi .* centeredImage(:,1)
		// vi = wi .* centeredImage(:,2)
		// deltaUi = ui - oldUi;
		// deltaVi = vi - oldVi;
		for (int i = 0; i < nbPoints; ++i)
		{
			oldUi[i] = ui[i];
		    oldVi[i] = vi[i];
		    ui[i] = wi[i] * centeredImage[i].x;
		    vi[i] = wi[i] * centeredImage[i].y;
			deltaUi[i] = ui[i] - oldUi[i];
			deltaVi[i] = vi[i] - oldVi[i];
		}

		// delta = focalLength * focalLength * (deltaUi' * deltaUi + deltaVi' * deltaVi)
		double delta = 0.0;
		for (int i = 0; i < nbPoints; ++i)
			delta += deltaUi[i] * deltaUi[i] + deltaVi[i] * deltaVi[i];
		delta = delta*focalLength * focalLength;

		/*
		std::cout << "delta: " << delta << std::endl ;
		std::cout << "r1N: " << r1N[0] << " " << r1N[1] << " " << r1N[2] << " " << r1N[3] << std::endl;
		std::cout << "r2N: " << r2N[0] << " " << r2N[1] << " " << r2N[2] << " " << r2N[3] << std::endl;
		std::cout << "r1T: " << r1T[0] << " " << r1T[1] << " " << r1T[2] << " " << r1T[3] << std::endl;
		std::cout << "r2T: " << r2T[0] << " " << r2T[1] << " " << r2T[2] << " " << r2T[3] << std::endl;
		std::cout << "r3: " << r3[0] << " " << r3[1] << " " << r3[2] << " " << r3[3] << std::endl;
		*/

		// converged = (count>0 & delta < 1)
		converged = (iterationCount > 0) && (delta < 0.01);
		++iterationCount;

		//std::cout << "delta " << delta << std::endl;
	}
	// trans = [Tx; Ty; Tz];
	// rot = [r1'; r2'; r3'];
	//std::cout << "iter count " << iterationCount << std::endl;

	trans.x = Tx;
	trans.y = Ty;
	trans.z = Tz;

	rot.create(3,3,CV_32F);
	for (int i = 0; i < 3; ++i)
	{
		rot.at<float>(0,i) = r1N[i];
		rot.at<float>(1,i) = r2N[i];
		rot.at<float>(2,i) = r3[i];
	}
}
Exemple #20
0
TEST(SharedValueTest, ctorInt)
{
    int i = -324523;
    unsigned u = 0x334234u;
    char c = -22;
    short s = 289;
    unsigned char uc = 244;
    unsigned short us = 3467;
    long long ll = -20398574395872907ll;
    unsigned long long ull = 985734209239847656ull;

    EXPECT_NO_THROW(Value v(i));
    EXPECT_NO_THROW(Value v(u));
    EXPECT_NO_THROW(Value v(c));
    EXPECT_NO_THROW(Value v(s));
    EXPECT_NO_THROW(Value v(uc));
    EXPECT_NO_THROW(Value v(us));
    EXPECT_NO_THROW(Value v(ll));
    EXPECT_NO_THROW(Value v(ull));

    Value vi(i);
    EXPECT_EQ(vi.as<int>(), i);
    Value vu(u);
    EXPECT_EQ(vu.as<unsigned>(), u);
    Value vc(c);
    EXPECT_EQ(vc.as<char>(), c);
    Value vs(s);
    EXPECT_EQ(vs.as<short>(), s);
    Value vuc(uc);
    EXPECT_EQ(vuc.as<unsigned char>(), uc);
    Value vus(us);
    EXPECT_EQ(vus.as<unsigned short>(), us);
    Value vll(ll);
    EXPECT_NE(vll.as<long long>(), ll); // 32 bit storage overfflow
    EXPECT_EQ(vll.as<long long>(), static_cast<long long>(int(ll)));
    Value vull(ull);
    EXPECT_NE(vull.as<unsigned long long>(), ull); // 32 bit storage overfflow
    EXPECT_EQ(vull.as<unsigned long long>(), static_cast<unsigned long long>(int(ull)));

    Value vllNoOverflow(-42424ll); // no 32 bit storage overflow
    EXPECT_EQ(vllNoOverflow.as<long long>(), -42424ll);
    Value vullNoOverflow(0x43424242ull); // no 32 bit storage overflow
    EXPECT_EQ(vullNoOverflow.as<unsigned long long>(), 0x43424242ull);

    EXPECT_EQ(vi.type(), typeid(int));
    EXPECT_EQ(vu.type(), typeid(int));
    EXPECT_EQ(vc.type(), typeid(int));
    EXPECT_EQ(vs.type(), typeid(int));
    EXPECT_EQ(vuc.type(), typeid(int));
    EXPECT_EQ(vus.type(), typeid(int));
    EXPECT_EQ(vll.type(), typeid(int));
    EXPECT_EQ(vull.type(), typeid(int));

    // copy
    EXPECT_NO_THROW(Value v(vi));
    EXPECT_NO_THROW(Value v(vu));
    EXPECT_NO_THROW(Value v(vc));
    EXPECT_NO_THROW(Value v(vs));
    EXPECT_NO_THROW(Value v(vuc));
    EXPECT_NO_THROW(Value v(vus));
    EXPECT_NO_THROW(Value v(vll));
    EXPECT_NO_THROW(Value v(vull));

    Value vi2(vi);
    EXPECT_EQ(vi2.as<int>(), i);
    Value vu2(vu);
    EXPECT_EQ(vu2.as<unsigned>(), u);
    Value vc2(vc);
    EXPECT_EQ(vc2.as<char>(), c);
    Value vs2(vs);
    EXPECT_EQ(vs2.as<short>(), s);
    Value vuc2(vuc);
    EXPECT_EQ(vuc2.as<unsigned char>(), uc);
    Value vus2(vus);
    EXPECT_EQ(vus2.as<unsigned short>(), us);
    Value vll2(vll);
    EXPECT_NE(vll.as<long long>(), ll);
    EXPECT_EQ(vll2.as<long long>(), static_cast<long long>(int(vll)));
    Value vull2(vull);
    EXPECT_NE(vull.as<unsigned long long>(), ull);
    EXPECT_EQ(vull2.as<unsigned long long>(), static_cast<unsigned long long>(int(vull)));

    EXPECT_EQ(vi2.type(), typeid(int));
    EXPECT_EQ(vu2.type(), typeid(int));
    EXPECT_EQ(vc2.type(), typeid(int));
    EXPECT_EQ(vs2.type(), typeid(int));
    EXPECT_EQ(vuc2.type(), typeid(int));
    EXPECT_EQ(vus2.type(), typeid(int));
    EXPECT_EQ(vll2.type(), typeid(int));
    EXPECT_EQ(vull2.type(), typeid(int));
}
Exemple #21
0
static void
HoughLinesSDiv( const Mat& img,
                float rho, float theta, int threshold,
                int srn, int stn,
                std::vector<Vec2f>& lines, int linesMax,
                double min_theta, double max_theta )
{
    #define _POINT(row, column)\
        (image_src[(row)*step+(column)])

    int index, i;
    int ri, ti, ti1, ti0;
    int row, col;
    float r, t;                 /* Current rho and theta */
    float rv;                   /* Some temporary rho value */

    int fn = 0;
    float xc, yc;

    const float d2r = (float)(CV_PI / 180);
    int sfn = srn * stn;
    int fi;
    int count;
    int cmax = 0;

    std::vector<hough_index> lst;

    CV_Assert( img.type() == CV_8UC1 );
    CV_Assert( linesMax > 0 );

    threshold = MIN( threshold, 255 );

    const uchar* image_src = img.ptr();
    int step = (int)img.step;
    int w = img.cols;
    int h = img.rows;

    float irho = 1 / rho;
    float itheta = 1 / theta;
    float srho = rho / srn;
    float stheta = theta / stn;
    float isrho = 1 / srho;
    float istheta = 1 / stheta;

    int rn = cvFloor( std::sqrt( (double)w * w + (double)h * h ) * irho );
    int tn = cvFloor( 2 * CV_PI * itheta );

    lst.push_back(hough_index(threshold, -1.f, 0.f));

    // Precalculate sin table
    std::vector<float> _sinTable( 5 * tn * stn );
    float* sinTable = &_sinTable[0];

    for( index = 0; index < 5 * tn * stn; index++ )
        sinTable[index] = (float)cos( stheta * index * 0.2f );

    std::vector<uchar> _caccum(rn * tn, (uchar)0);
    uchar* caccum = &_caccum[0];

    // Counting all feature pixels
    for( row = 0; row < h; row++ )
        for( col = 0; col < w; col++ )
            fn += _POINT( row, col ) != 0;

    std::vector<int> _x(fn), _y(fn);
    int* x = &_x[0], *y = &_y[0];

    // Full Hough Transform (it's accumulator update part)
    fi = 0;
    for( row = 0; row < h; row++ )
    {
        for( col = 0; col < w; col++ )
        {
            if( _POINT( row, col ))
            {
                int halftn;
                float r0;
                float scale_factor;
                int iprev = -1;
                float phi, phi1;
                float theta_it;     // Value of theta for iterating

                // Remember the feature point
                x[fi] = col;
                y[fi] = row;
                fi++;

                yc = (float) row + 0.5f;
                xc = (float) col + 0.5f;

                /* Update the accumulator */
                t = (float) fabs( cvFastArctan( yc, xc ) * d2r );
                r = (float) std::sqrt( (double)xc * xc + (double)yc * yc );
                r0 = r * irho;
                ti0 = cvFloor( (t + CV_PI*0.5) * itheta );

                caccum[ti0]++;

                theta_it = rho / r;
                theta_it = theta_it < theta ? theta_it : theta;
                scale_factor = theta_it * itheta;
                halftn = cvFloor( CV_PI / theta_it );
                for( ti1 = 1, phi = theta_it - (float)(CV_PI*0.5), phi1 = (theta_it + t) * itheta;
                     ti1 < halftn; ti1++, phi += theta_it, phi1 += scale_factor )
                {
                    rv = r0 * std::cos( phi );
                    i = (int)rv * tn;
                    i += cvFloor( phi1 );
                    assert( i >= 0 );
                    assert( i < rn * tn );
                    caccum[i] = (uchar) (caccum[i] + ((i ^ iprev) != 0));
                    iprev = i;
                    if( cmax < caccum[i] )
                        cmax = caccum[i];
                }
            }
        }
    }

    // Starting additional analysis
    count = 0;
    for( ri = 0; ri < rn; ri++ )
    {
        for( ti = 0; ti < tn; ti++ )
        {
            if( caccum[ri * tn + ti] > threshold )
                count++;
        }
    }

    if( count * 100 > rn * tn )
    {
        HoughLinesStandard( img, rho, theta, threshold, lines, linesMax, min_theta, max_theta );
        return;
    }

    std::vector<uchar> _buffer(srn * stn + 2);
    uchar* buffer = &_buffer[0];
    uchar* mcaccum = buffer + 1;

    count = 0;
    for( ri = 0; ri < rn; ri++ )
    {
        for( ti = 0; ti < tn; ti++ )
        {
            if( caccum[ri * tn + ti] > threshold )
            {
                count++;
                memset( mcaccum, 0, sfn * sizeof( uchar ));

                for( index = 0; index < fn; index++ )
                {
                    int ti2;
                    float r0;

                    yc = (float) y[index] + 0.5f;
                    xc = (float) x[index] + 0.5f;

                    // Update the accumulator
                    t = (float) fabs( cvFastArctan( yc, xc ) * d2r );
                    r = (float) std::sqrt( (double)xc * xc + (double)yc * yc ) * isrho;
                    ti0 = cvFloor( (t + CV_PI * 0.5) * istheta );
                    ti2 = (ti * stn - ti0) * 5;
                    r0 = (float) ri *srn;

                    for( ti1 = 0; ti1 < stn; ti1++, ti2 += 5 )
                    {
                        rv = r * sinTable[(int) (std::abs( ti2 ))] - r0;
                        i = cvFloor( rv ) * stn + ti1;

                        i = CV_IMAX( i, -1 );
                        i = CV_IMIN( i, sfn );
                        mcaccum[i]++;
                        assert( i >= -1 );
                        assert( i <= sfn );
                    }
                }

                // Find peaks in maccum...
                for( index = 0; index < sfn; index++ )
                {
                    i = 0;
                    int pos = (int)(lst.size() - 1);
                    if( pos < 0 || lst[pos].value < mcaccum[index] )
                    {
                        hough_index vi(mcaccum[index],
                                       index / stn * srho + ri * rho,
                                       index % stn * stheta + ti * theta - (float)(CV_PI*0.5));
                        lst.push_back(vi);
                        for( ; pos >= 0; pos-- )
                        {
                            if( lst[pos].value > vi.value )
                                break;
                            lst[pos+1] = lst[pos];
                        }
                        lst[pos+1] = vi;
                        if( (int)lst.size() > linesMax )
                            lst.pop_back();
                    }
                }
            }
        }
    }

    for( size_t idx = 0; idx < lst.size(); idx++ )
    {
        if( lst[idx].rho < 0 )
            continue;
        lines.push_back(Vec2f(lst[idx].rho, lst[idx].theta));
    }
}
 sparse_table(vi arr) {
   m.push_back(arr);
   for (int k = 0; (1<<(++k)) <= size(arr); ) {
     m.push_back(vi(size(arr)-(1<<k)+1));
     rep(i,0,size(arr)-(1<<k)+1)
       m[k][i] = min(m[k-1][i], m[k-1][i+(1<<(k-1))]); } }
void test_one ()
{
//  Note: The literal values here are tested against directly, careful if you change them:
    int some_numbers[] = { 1, 1, 2, 3, 5 };
    std::vector<int> vi(some_numbers, some_numbers + 5);
    std::list<int>   li(vi.begin(), vi.end ());
    
    int some_letters[] = { 'a', 'q', 'n', 'y', 'n' };
    std::vector<char> vc(some_letters, some_letters + 5);
    
    BOOST_CHECK (!ba::one_of_equal ( vi,                                  1 ));
    BOOST_CHECK (!ba::one_of       ( vi,                       is_<int> ( 1 )));
    BOOST_CHECK (!ba::one_of_equal ( vi.begin(),     vi.end(),            1 ));
    BOOST_CHECK (!ba::one_of       ( vi.begin(),     vi.end(), is_<int> ( 1 )));

    BOOST_CHECK (!ba::one_of_equal ( vi,                                  0 ));
    BOOST_CHECK (!ba::one_of       ( vi,                       is_<int> ( 0 )));
    BOOST_CHECK (!ba::one_of_equal ( vi.begin(),     vi.end(),            0 ));
    BOOST_CHECK (!ba::one_of       ( vi.begin(),     vi.end(), is_<int> ( 0 )));
    
    BOOST_CHECK ( ba::one_of_equal ( vi,                                  2 ));
    BOOST_CHECK ( ba::one_of       ( vi,                       is_<int> ( 2 )));
    BOOST_CHECK ( ba::one_of_equal ( vi.begin(),     vi.end(),            2 ));
    BOOST_CHECK ( ba::one_of       ( vi.begin(),     vi.end(), is_<int> ( 2 )));

//  Check for a match at the end
    BOOST_CHECK ( ba::one_of_equal ( vi,                                  5 ));
    BOOST_CHECK ( ba::one_of       ( vi,                       is_<int> ( 5 )));
    BOOST_CHECK ( ba::one_of_equal ( vi.begin(),     vi.end(),            5 ));
    BOOST_CHECK ( ba::one_of       ( vi.begin(),     vi.end(), is_<int> ( 5 )));

    BOOST_CHECK ( ba::one_of_equal ( vi.begin() + 1, vi.end(),            1 ));
    BOOST_CHECK ( ba::one_of       ( vi.begin() + 1, vi.end(), is_<int> ( 1 )));
    
    BOOST_CHECK ( ba::one_of_equal ( vc.begin() + 1, vc.begin() + 2,             'q' ));
    BOOST_CHECK ( ba::one_of       ( vc.begin() + 1, vc.begin() + 2, is_<char> ( 'q' )));

    BOOST_CHECK (!ba::one_of_equal ( vc, '!' ));
    BOOST_CHECK (!ba::one_of       ( vc, is_<char> ( '!' )));
    
    BOOST_CHECK (!ba::one_of_equal ( vc, 'n' ));
    BOOST_CHECK (!ba::one_of       ( vc, is_<char> ( 'n' )));

//  Empty range check
    BOOST_CHECK (!ba::one_of_equal ( vi.begin(), vi.begin(),   1 ));
    BOOST_CHECK (!ba::one_of_equal ( vc.begin(), vc.begin(), 'a' ));
    BOOST_CHECK (!ba::one_of       ( vi.begin(), vi.begin(), is_<int>  (   1 )));
    BOOST_CHECK (!ba::one_of       ( vc.begin(), vc.begin(), is_<char> ( 'a' )));
    
    BOOST_CHECK (!ba::one_of_equal ( li,                                  1 ));
    BOOST_CHECK (!ba::one_of       ( li,                       is_<int> ( 1 )));
    BOOST_CHECK (!ba::one_of_equal ( li.begin(),     li.end(),            1 ));
    BOOST_CHECK (!ba::one_of       ( li.begin(),     li.end(), is_<int> ( 1 )));
    
    std::list<int>::iterator l_iter = li.begin ();
    l_iter++; l_iter++; l_iter++;
    BOOST_CHECK (!ba::one_of_equal ( li.begin(), l_iter,            1 ));
    BOOST_CHECK (!ba::one_of       ( li.begin(), l_iter, is_<int> ( 1 )));
    BOOST_CHECK ( ba::one_of_equal ( li.begin(), l_iter,            2 ));
    BOOST_CHECK ( ba::one_of       ( li.begin(), l_iter, is_<int> ( 2 )));
    BOOST_CHECK (!ba::one_of_equal ( li.begin(), l_iter,            3 ));
    BOOST_CHECK (!ba::one_of       ( li.begin(), l_iter, is_<int> ( 3 )));

}
		void CSphereCallback::FillMeshData(Engine::Graphics::IMesh *pMesh)
		{
			// Declaration
			SVertexElement elems[4];
			elems[0] = SVertexElement(0, ETYPE_FLOAT3, USG_POSITION, 0);
			elems[1] = SVertexElement(sizeof(float) * 3, ETYPE_FLOAT3, USG_NORMAL, 0);
			elems[2] = SVertexElement(sizeof(float) * 6, ETYPE_FLOAT2, USG_TEXCOORD, 0);
			elems[3] = END_DECLARATION();
			pMesh->SetVertexDeclaration(elems);
			pMesh->setPrimitiveType(PT_INDEXED_TRIANGLE_LIST);

			// Data
			const int n_verts = (mRings + 1) * (mSegments + 1);
			const int n_indcs = 6 * mRings * (mSegments + 1);
			void *vertices, *indices;
			
			IBuffer* vb = pMesh->GetVertexBuffer();
			IBuffer* ib = pMesh->GetIndexBuffer();

			vb->Resize(n_verts * sizeof(float) * 8);
			ib->Resize(n_indcs * sizeof(int));

			vb->Lock(&vertices, LOCK_DISCARD);
			ib->Lock(&indices, LOCK_DISCARD);

			const float PI = 3.1415926f;
			float fDeltaRingAngle = (PI / mRings);
			float fDeltaSegAngle = (2.0f * PI / mSegments);
			unsigned short wVerticeIndex = 0 ;

			float* pVertex = (float*)vertices;
			int* pIndices = (int*)indices;

			// Generate the group of rings for the sphere
			for(int ring = 0; ring <= mRings; ring++)
			{
				float r0 = mRadius * sinf (ring * fDeltaRingAngle);
				float y0 = mRadius * cosf (ring * fDeltaRingAngle);

				// Generate the group of segments for the current ring
				for(int seg = 0; seg <= mSegments; seg++)
				{
					float x0 = r0 * sinf(seg * fDeltaSegAngle);
					float z0 = r0 * cosf(seg * fDeltaSegAngle);

					// Position
					*pVertex++ = x0;
					*pVertex++ = y0;
					*pVertex++ = z0;

					// Normal
					VML::Vector3 vNormal(x0, y0, z0);
					vNormal.normalize();

					*pVertex++ = vNormal.getX();
					*pVertex++ = vNormal.getY();
					*pVertex++ = vNormal.getZ();

					// Texture coordinates
					*pVertex++ = 1.0f - (float) seg / (float) mSegments;
					*pVertex++ = (float) ring / (float) mRings;

					if (ring != mRings) 
					{
						// each vertex (except the last) has six indices pointing to it
						*pIndices++ = wVerticeIndex + mSegments + 1;
						*pIndices++ = wVerticeIndex;               
						*pIndices++ = wVerticeIndex + mSegments;
						*pIndices++ = wVerticeIndex + mSegments + 1;
						*pIndices++ = wVerticeIndex + 1;
						*pIndices++ = wVerticeIndex;
						wVerticeIndex ++;
					}
				} // end for seg
			} // end for ring


			vb->Unlock();
			ib->Unlock();

			// Subset
			IGeometry::TInterval vi(0, n_verts);
			IGeometry::TInterval ii(0, n_indcs);
			pMesh->AddSubset(vi, ii);

			SBoundingVolume bv(VML::Vector3(0), mRadius);
			pMesh->SetBoundingVolume(bv);
		}
CoupleItem BppSolver::ryanFosterCouple(BranchNode& node)
{
	// get var values
	auto& Xs = BPmodel.getPrimalValues();
	

#ifdef DBG_OUTPUT
	for (int i = 0; i < BPVars.getSize(); i++)
		std::cout << Xs[i] << " ";
	std::cout << std::endl;
#endif

	std::vector<std::size_t> vec_shuffled(Xs.getSize());
	std::iota(vec_shuffled.begin(), vec_shuffled.end(), 0);
	// shuffle

	auto engine = std::default_random_engine(std::random_device{}());
	std::shuffle(vec_shuffled.begin(), vec_shuffled.end(), engine);

	std::list<std::size_t> vi(vec_shuffled.begin(), vec_shuffled.end());
	std::shuffle(vec_shuffled.begin(), vec_shuffled.end(), engine);
	std::list<std::size_t> vj(vec_shuffled.begin(), vec_shuffled.end());

	for (auto it = vi.begin(); it != vi.end(); it++)
	{
		int i = *it;
		auto jt = vj.begin();
		while (jt != vj.end())
		{
			int j = *jt;
			if (i == j)
				jt = vj.erase(jt);
			else
			{
				IloExpr::LinearIterator it_i = BPmodel.getLinearCoefIterator(i);
				IloExpr::LinearIterator it_j = BPmodel.getLinearCoefIterator(j);

				real sumVars = 0.0;
				for (; ; )
				{
					// get index of the variables via thier names
					std::string name_i(it_i.getVar().getName());
					std::string name_j(it_j.getVar().getName());
					// si and sj are the column index of the iterators
					int si = std::stoi(name_i.substr(1));
					int sj = std::stoi(name_j.substr(1));
					// booleans for validity of the columns
					bool validColumn_it = true;

					// i and j are in the same bin
					if (si == sj)
					{
						for (auto cols : node.incumbentInvalidColumns) {
							if (!(validColumn_it = (cols->find(sj) == cols->end())))
								break;
						}

						if (validColumn_it)
							validColumn_it = (node.invalidColumns->find(si) == node.invalidColumns->end());

						if (validColumn_it && (Xs[si] > 0.0))
							sumVars += Xs[si];
					}
					// some requirement to increment the iterator 
					// since they itarate only over non zero coefs
					if (si <= sj)
						++it_i;
					++it_j;
					// stop condition
					if (!it_i.ok() || !it_j.ok())
						break;
				}
				real _dumy;
				real frac = modf(sumVars, &_dumy);
				if (frac >= 0.0001) {
					return std::make_pair(i, j);
				}
				++jt;
			}
		}
	}
}
		void CBoxCallback::FillMeshData(Engine::Graphics::IMesh *pMesh)
		{
			// Declaration
			SVertexElement elems[4];
			elems[0] = SVertexElement(0, ETYPE_FLOAT3, USG_POSITION, 0);
			elems[1] = SVertexElement(sizeof(float) * 3, ETYPE_FLOAT3, USG_NORMAL, 0);
			elems[2] = SVertexElement(sizeof(float) * 6, ETYPE_FLOAT2, USG_TEXCOORD, 0);
			elems[3] = END_DECLARATION();
			pMesh->SetVertexDeclaration(elems);
			pMesh->setPrimitiveType(PT_INDEXED_TRIANGLE_LIST);

			// Data
			const int n_verts = 36;
			struct Vert { float data[8]; };
			Vert v[] =
			{
				{ mA[0],  mB[1], mA[2], 0, 1, 0 ,  0, 1 },
				{ mA[0],  mB[1], mB[2], 0, 1, 0 ,  0, 0 },
				{ mB[0],  mB[1], mB[2], 0, 1, 0 ,  1, 0 },

				{ mB[0],  mB[1], mB[2], 0, 1, 0 ,  1, 0 },
				{ mB[0],  mB[1], mA[2], 0, 1, 0 ,  1, 1 },
				{ mA[0],  mB[1], mA[2], 0, 1, 0 ,  0, 1 },

				{ mA[0],  mA[1], mA[2], 0, 0, -1 ,  0, 1 },
				{ mA[0],  mB[1], mA[2], 0, 0, -1 ,  0, 0 },
				{ mB[0],  mB[1], mA[2], 0, 0, -1 ,  1, 0 },

				{ mB[0],  mB[1], mA[2], 0, 0, -1 ,  1, 0 },
				{ mB[0],  mA[1], mA[2], 0, 0, -1 ,  1, 1 },
				{ mA[0],  mA[1], mA[2], 0, 0, -1 ,  0, 1 },

				{ mA[0],  mA[1], mB[2], -1, 0, 0 ,  0, 1 },
				{ mA[0],  mB[1], mB[2], -1, 0, 0 ,  0, 0 },
				{ mA[0],  mB[1], mA[2], -1, 0, 0 ,  1, 0 },

				{ mA[0],  mB[1], mA[2], -1, 0, 0 ,  1, 0 },
				{ mA[0],  mA[1], mA[2], -1, 0, 0 ,  1, 1 },
				{ mA[0],  mA[1], mB[2], -1, 0, 0 ,  0, 1 },

				{ mA[0],  mB[1], mB[2], 0, 0, 1 ,  1, 0 },
				{ mA[0],  mA[1], mB[2], 0, 0, 1 ,  1, 1 },
				{ mB[0],  mA[1], mB[2], 0, 0, 1 ,  0, 1 },

				{ mB[0],  mA[1], mB[2], 0, 0, 1 ,  0, 1 },
				{ mB[0],  mB[1], mB[2], 0, 0, 1 ,  0, 0 },
				{ mA[0],  mB[1], mB[2], 0, 0, 1 ,  1, 0 },

				{ mB[0],  mA[1], mA[2], 1, 0, 0 ,  0, 1 },
				{ mB[0],  mB[1], mA[2], 1, 0, 0 ,  0, 0 },
				{ mB[0],  mB[1], mB[2], 1, 0, 0 ,  1, 0 },

				{ mB[0],  mB[1], mB[2], 1, 0, 0 ,  1, 0 },
				{ mB[0],  mA[1], mB[2], 1, 0, 0 ,  1, 1 },
				{ mB[0],  mA[1], mA[2], 1, 0, 0 ,  0, 1 },

				{ mA[0],  mA[1], mB[2], 0, -1, 0 ,  0, 1 },
				{ mA[0],  mA[1], mA[2], 0, -1, 0 ,  0, 0 },
				{ mB[0],  mA[1], mA[2], 0, -1, 0 ,  1, 0 },

				{ mB[0],  mA[1], mA[2], 0, -1, 0 ,  1, 0 },
				{ mB[0],  mA[1], mB[2], 0, -1, 0 ,  1, 1 },
				{ mA[0],  mA[1], mB[2], 0, -1, 0 ,  0, 1 },
			};

			int i[] = {	
				0,1,2, 3,4,5, 6,7,8, 9,10,11,
				12,13,14, 15,16,17, 18,19,20, 21,22,23,
				24,25,26, 27,28,29, 30,31,32, 33,34,35, };

			IBuffer *vb = pMesh->GetVertexBuffer();
			vb->Resize(sizeof(Vert) * n_verts);
			void *pData;
			vb->Lock(&pData, LOCK_DISCARD);
			memcpy(pData, v, sizeof(Vert) * n_verts);
			vb->Unlock();

			IBuffer *ib = pMesh->GetIndexBuffer();
			ib->Resize(sizeof(int) * n_verts);
			ib->Lock(&pData, LOCK_DISCARD);
			memcpy(pData, i, sizeof(int) * n_verts);
			ib->Unlock();

			// Subset
			IGeometry::TInterval vi(0, n_verts);
			IGeometry::TInterval ii(0, n_verts);
			pMesh->AddSubset(vi, ii);

			VML::Vector3 vmin(mA[0], mA[1], mA[2]);
			VML::Vector3 vmax(mB[0], mB[1], mB[2]);
			SBoundingVolume bv(vmin, vmax);
			pMesh->SetBoundingVolume(bv);
		}
Exemple #27
0
void run_example(
	const x11::Display& display,
	const char* screenshot_path,
	const char* framedump_prefix,
	int argc,
	char ** argv
)
{
	static int visual_attribs[] =
	{
		GLX_X_RENDERABLE    , True,
		GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
		GLX_RENDER_TYPE     , GLX_RGBA_BIT,
		GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
		GLX_RED_SIZE        , 8,
		GLX_GREEN_SIZE      , 8,
		GLX_BLUE_SIZE       , 8,
		GLX_ALPHA_SIZE      , 8,
		GLX_DEPTH_SIZE      , 24,
		GLX_STENCIL_SIZE    , 8,
		GLX_DOUBLEBUFFER    , True,
		None
	};
	glx::Version version(display);
	version.AssertAtLeast(1, 3);

	glx::FBConfig fbc = glx::FBConfigs(
		display,
		visual_attribs
	).FindBest(display);

	x11::VisualInfo vi(display, fbc);

	const GLuint width = framedump_prefix?852:800;
	const GLuint height = framedump_prefix?480:600;

	x11::Window win(
		display,
		vi,
		x11::Colormap(display, vi),
		"OGLplus example",
		width, height
	);

	x11::ScreenNames screen_names;

	ExampleParams params(argc, argv);
	if(framedump_prefix) params.quality = 1.0;
	params.max_threads = 128;
	params.num_gpus = screen_names.size(); // TODO: something more reliable
	setupExample(params);
	params.Check();

	glx::Context ctx(display, fbc, 3, 3);

	ctx.MakeCurrent(win);

	// The clock for animation timing
	ExampleClock clock;

	std::vector<std::thread> threads;
	ThreadSemaphore thread_ready, master_ready;
	ExampleThreadData::Common example_thread_common_data = {
		nullptr,
		params,
		clock,
		screen_names,
		display,
		vi,
		fbc,
		ctx,
		thread_ready,
		master_ready,
		false /*failure*/,
		false /*done*/
	};
	try
	{
		// Initialize the GL API library (GLEW/GL3W/...)
		oglplus::GLAPIInitializer api_init;

		// things required for multi-threaded examples
		std::vector<ExampleThreadData> thread_data;

		// prepare the example data
		for(unsigned t=0; t!=params.num_threads; ++t)
		{
			ExampleThreadData example_thread_data = {
				t, nullptr, std::string(),
				&example_thread_common_data
			};
			thread_data.push_back(example_thread_data);
		}

		// start the examples and let them
		// create their own contexts shared with
		// the main context
		for(unsigned t=0; t!=params.num_threads; ++t)
		{
			threads.emplace_back(
				call_example_thread_main,
				std::ref(thread_data[t])
			);
			// wait for the thread to create
			// an off-screen context
			thread_ready.Wait();
			// check for errors
			if(!thread_data[t].error_message.empty())
			{
				example_thread_common_data.failure = true;
				example_thread_common_data.master_ready.Signal(t);
				throw std::runtime_error(
					thread_data[t].error_message
				);
			}
		}

		// make the example
		std::unique_ptr<Example> example(makeExample(params));

		// tell the threads about the example
		// and let them call makeExampleThread
		example_thread_common_data.example = example.get();
		for(unsigned t=0; t!=params.num_threads; ++t)
		{
			// signal that the example is ready
			master_ready.Signal();
			// wait for the threads to call makeExampleThread
			thread_ready.Wait();
		}
		// check for potential errors and let
		// the example do additional thread-related preparations
		for(unsigned t=0; t!=params.num_threads; ++t)
		{
			if(!thread_data[t].error_message.empty())
			{
				example_thread_common_data.failure = true;
				example_thread_common_data.master_ready.Signal(
					params.num_threads
				);
				throw std::runtime_error(
					thread_data[t].error_message
				);
			}
			assert(thread_data[t].example_thread);
			example->PrepareThread(t,*thread_data[t].example_thread);
		}
		// signal that the example threads may start
		// rendering
		master_ready.Signal(params.num_threads);

		example->Reshape(width, height);
		example->MouseMove(width/2, height/2, width, height);

		if(screenshot_path)
		{
			make_screenshot(
				display,
				win,
				ctx,
				example,
				clock,
				width,
				height,
				screenshot_path
			);
		}
		else if(framedump_prefix)
		{
			run_framedump_loop(
				display,
				win,
				ctx,
				example,
				clock,
				width,
				height,
				framedump_prefix
			);
		}
		else
		{
			run_example_loop(
				display,
				win,
				ctx,
				example,
				example_thread_common_data,
				clock,
				width,
				height
			);
		}
		example_thread_common_data.done = true;
		// cancel the example threads
		for(unsigned t=0; t!=params.num_threads; ++t)
		{
			if(thread_data[t].example_thread)
				thread_data[t].example_thread->Cancel();
		}
		// join the example threads
		for(unsigned t=0; t!=params.num_threads; ++t)
		{
			threads[t].join();
		}

		for(unsigned t=0; t!=params.num_threads; ++t)
		{
			if(!thread_data[t].error_message.empty())
				throw std::runtime_error(
					thread_data[t].error_message
				);
		}
	}
	catch(...)
	{
		example_thread_common_data.failure = true;
		master_ready.Signal(params.num_threads);
		try {for(auto& thread : threads) thread.join(); }
		catch(...){ }
		throw;
	}
	ctx.Release(display);
}
/*后序遍历*/
void BTreeBackOrderTraverse(BiTree T, void(*vi)(TElemType e)) {
    if (!T || !vi) return;
    BTreeBackOrderTraverse(T->lchild,vi);
    BTreeBackOrderTraverse(T->rchild,vi);
    vi(T->data);
}
bool convertFromPythonExisting(PyObject *lst, TExample &example)
{
  PDomain dom=example.domain;

  if (PyOrExample_Check(lst)) {
    const TExample &orex = PyExample_AS_ExampleReference(lst);
    if (orex.domain != dom)
      dom->convert(example, orex);
    else
      example = orex;
    return true;
  }

  if (!PyList_Check(lst)) {
    PyErr_Format(PyExc_TypeError, "invalid argument type (expected list, got '%s)", lst ? lst->ob_type->tp_name : "None");
    return false;
  }

  int const nvars = dom->variables->size() + dom->classVars->size();
  if (Py_ssize_t(nvars) != PyList_Size(lst)) {
    PyErr_Format(PyExc_IndexError, "invalid list size (got %i, expected %i items)",
        PyList_Size(lst), nvars);
    return false;
  }

  Py_ssize_t pos = 0;
  TExample::iterator ei(example.begin());
  TVarList::iterator vi(dom->variables->begin());
  TVarList::const_iterator const ve(dom->variables->end());
  TVarList::const_iterator const ce(dom->classVars->end());
  while(vi != ce && vi != ve) {
    PyObject *li=PyList_GetItem(lst, pos++);
    if (!li)
      PYERROR(PyExc_SystemError, "can't read the list", false);

    if (PyOrValue_Check(li))
      if (PyValue_AS_Variable(li) ? (PyValue_AS_Variable(li) != *vi) : (PyValue_AS_Value(li).varType=!(*vi)->varType) ) {
        PyErr_Format(PyExc_TypeError, "wrong value type for attribute no. %i (%s)", pos, (*vi)->get_name().c_str());
        return false;
      }
      else
        *(ei++)=PyValue_AS_Value(li);

    else {
      if (li == Py_None) {
        *(ei++) = (*vi)->DK();
      }
        
      else if (PyString_Check(li))
          (*vi)->str2val(string(PyString_AsString(li)), *(ei++));

      else if ((*vi)->varType==TValue::INTVAR) {
        if (PyInt_Check(li))
          *(ei++)=TValue(int(PyInt_AsLong(li)));
        else {
          PyErr_Format(PyExc_TypeError, "attribute no. %i (%s) is ordinal, string value expected", pos, (*vi)->get_name().c_str());
          return false;
        }
      }
      else if ((*vi)->varType==TValue::FLOATVAR) {
        float f;
        if (PyNumber_ToFloat(li, f))
          *(ei++) = TValue(f);
        else {
          PyErr_Format(PyExc_TypeError, "attribute no. %i (%s) is continuous, float value expected", pos, (*vi)->get_name().c_str());
          return false;
        }
      }
      else
        ei++;
    }
    if (++vi == ve) {
        vi = dom->classVars->begin();
    }
  }

  return true;
}
Exemple #30
0
int main_GLX(AppData& app_data)
{
	::XInitThreads();
	x11::Display display;
	glx::Version version(display);
	version.AssertAtLeast(1, 3);

	static const int visual_attribs[] =
	{
		GLX_X_RENDERABLE    , True,
		GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT|GLX_PBUFFER_BIT,
		GLX_RENDER_TYPE     , GLX_RGBA_BIT,
		GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
		GLX_RED_SIZE        , 8,
		GLX_GREEN_SIZE      , 8,
		GLX_BLUE_SIZE       , 8,
		GLX_ALPHA_SIZE      , 8,
		GLX_DOUBLEBUFFER    , True,
		None
	};

	glx::FBConfig fbc = glx::FBConfigs(
		display,
		visual_attribs
	).FindBest(display);

	x11::VisualInfo vi(display, fbc);
	glx::Context context(display, fbc, 3, 3);

	if(app_data.render_offscreen)
	{
		const int pbuffer_attribs [] = {
			GLX_PBUFFER_WIDTH  , int(app_data.render_width),
			GLX_PBUFFER_HEIGHT , int(app_data.render_height),
			None
		};

		glx::Pbuffer pbuffer(display, fbc, pbuffer_attribs);

		context.MakeCurrent(pbuffer);

		GLAPIInitializer api_init;

		call_drawable_loop(
			app_data,
			display,
			context,
			pbuffer,
			pbuffer_loop
		);
	}
	else
	{
		x11::Window window(
			display,
			vi,
			x11::Colormap(display, vi),
			"CloudTrace",
			app_data.render_width,
			app_data.render_height
		);

		context.MakeCurrent(window);

		GLAPIInitializer api_init;

		call_drawable_loop(
			app_data,
			display,
			context,
			window,
			window_loop
		);
	}

	context.Release(display);

	return 0;
}