예제 #1
0
/*
 * makesphere
 *
 *	make a sphere object
 */
makesphere()
{
	float	r, z;
	int	i, a;

	makeobj(SPHERE);

		/*
		 * create the latitudinal rings
		 */
		for (i = 0; i < 1800; i += 200) {
			pushmatrix();
				rotate(i, 'y');
				circ(0.0, 0.0, RADIUS);
			popmatrix();
		}
		
		/*
		 * create the longitudinal rings
		 */
		pushmatrix();
			rotate(900, 'x');
			for (a = -900; a < 900; a += 200) {
				r = RADIUS * cos((double)a * PI / 180.0);
				z = RADIUS * sin((double)a * PI / 180.0);
				pushmatrix();
					translate(0.0, 0.0, -z);
					circ(0.0, 0.0, r);
				popmatrix();	
			}
		popmatrix();
	closeobj();

}
예제 #2
0
void	cw_regongrid(t_cwar *cwar, unsigned char *reg, int i, t_proc *proc)
{
	int	j;

	j = 0;
	while (j < REG_SIZE)
	{
		cwar->arena_color[circ(i, j)][0] = (proc->player_id % 4) + 1;
		cwar->arena[circ(i, j)] = reg[j];
		++j;
	}
}
예제 #3
0
void main()
{
  int gd=DETECT,gm,i;
  initgraph(&gd,&gm,"");
  setcolor(YELLOW);
  settextstyle(1,0,6);
  outtextxy(0,240,"Count the black dots...");
  sleep(4);
  cleardevice();
  dot();
  getch();
  cleardevice();
  setcolor(YELLOW);
  settextstyle(1,0,4);
  outtextxy(0,240,"I bet the lines of rectangle are straight....");
  sleep(4);
  getch();
  cleardevice();
  circ();
  getch();
  cleardevice();
  setcolor(YELLOW);
  settextstyle(1,0,4);
  outtextxy(0,240,"I bet the circle is rounding...");
  sleep(4);
  getch();
  cleardevice();
  bulb();
  getch();
  closegraph();

}
예제 #4
0
/*Put count items into the circular buffer
   the "enter" will NOT return until it completes.
   this may mean that it waits until more items are
   "removed" from the buffer to make room.
 */
int enter_cbuf(cbuf * buffer, buf_t * bytes, int count)
{
    int j, actual;

    actual = 0;
    pthread_mutex_lock(buffer->writelock);
    for (j = (buffer->tail + 1) % (buffer->bufsize); actual < count; j = (j + 1) % (buffer->bufsize)) {
	pthread_mutex_lock(buffer->writeable_lock);
	buffer->writeable = (j != circ((buffer->head - 1), buffer->bufsize));
	while (!buffer->writeable) {
	    pthread_mutex_lock(buffer->readable_lock);
	    buffer->readable = 1;
	    pthread_cond_signal(buffer->cond_readable);
	    pthread_mutex_unlock(buffer->readable_lock);
	    pthread_cond_wait(buffer->cond_writeable, buffer->writeable_lock);
	}
	pthread_mutex_unlock(buffer->writeable_lock);
	(buffer->buf)[j] = bytes[actual];
	actual++;
	buffer->tail = (buffer->tail + 1) % (buffer->bufsize);
    }
    if (actual > 0) {
	pthread_mutex_lock(buffer->readable_lock);
	buffer->readable = 1;
	pthread_cond_signal(buffer->cond_readable);
	pthread_mutex_unlock(buffer->readable_lock);
    }
    pthread_mutex_unlock(buffer->writelock);
    return (actual);
}
예제 #5
0
int     load_first_instructions(t_vm *vm, t_chp *champs, t_opc **op)
{
  t_chp *cur;
  int   code;

  cur = champs;
  while ((cur))
    {
      code = vm->mem[circ(cur->pc++)];

      my_printf("first instruction [%x]\n", code);
      if (code >= 1 && code <= 16)
        {
          cur->inst = op[code - 1];
          my_printf("cur keyword [%s]\n", cur->inst->keyword);
          cur->ticks = cur->inst->nb_cycles;
        }
      else
        {
          cur->ticks = 1;
          cur->inst = NULL;
        }
      cur = cur->next;
    }
  return (SUCCESS);
}
// draw all constraint arcs
void ArcBall::drawConstraints ()
{
	if(axisSet == NoAxes)
		return;

	int setSize = setSizes[axisSet];
	double *set = sets[axisSet];

	Quat axis;
	for(int axisI=0; axisI<setSize; ++axisI)
	{
		if(axisIndex != axisI)
		{
			if(dragging) continue;
			glColor4fv(farColor.elem);
		}
		else
			glColor4fv(nearColor.elem);

		axis = *(Quat *)&set[4*axisI];

		if(axis.z == 1)
			circ();
		else
			drawHalfArc(axis);
	}
}
예제 #7
0
bool random_circuit_command::execute()
{
  if ( !is_set( "seed" ) )
  {
    seed = std::chrono::system_clock::now().time_since_epoch().count();
  }

  auto negative = is_set( "negative" );
  std::default_random_engine generator( seed );

  auto& circuits = env->store<circuit>();

  if ( is_set( "insert_gate" ) )
  {
    std::uniform_int_distribution<unsigned> dist( 0u, gates - 1u );
    create_random_gate( circuits.current().insert_gate( dist( generator ) ), lines, negative, generator );
  }
  else
  {
    circuit circ( lines );
    for ( auto i = 0u; i < gates; ++i )
    {
      create_random_gate( circ.append_gate(), lines, negative, generator );
    }

    if ( circuits.empty() || is_set( "new" ) )
    {
      circuits.extend();
    }
    circuits.current() = circ;
  }

  return true;
}
예제 #8
0
int             prep_instruction(t_chp *cur, t_vm *vm)
{
  t_param       par;
  int           i;
  int           pc_save;

  if (cur->inst == NULL)
    return (SUCCESS);
  pc_save = cur->pc - 1;
  i = -1;
  if (no_bytecode_inst(cur->inst->hexcode))
    {
      par.val[0] = get_param(vm, cur, T_DIR);
      exec_instruction_no_code(cur, vm, &par, pc_save);
    }
  else
    {
      get_bytecode(vm->mem[circ(cur->pc++)], par.type);
      while (++i < cur->inst->nb_args)
        {
          par.val[i] = get_param(vm, cur, par.type[i]);
        }
      exec_instruction_coded(cur, vm, &par, pc_save);
    }
  return (SUCCESS);
}
/// \brief		Nonlinear process model for needle steering
void UnscentedKalmanFilter::f(vnl_vector<double> x1, vnl_vector<double> u, 
	vnl_vector<double> &x2)
{
	// initialize the output to 0
	x2.fill(0.0);
	// isolate the position and orientation components of the input vector
	vnl_vector<double> p = x1.extract(3,0);
	vnl_vector<double> r = x1.extract(3,3);
	// change rotation vector representation to quaternion
	vnl_vector<double> r_norm = r;
	r_norm.normalize();
	vnl_quaternion<double> q(r_norm,r.magnitude());
	
	// isolate specific input variables
	double d_th = u[0];
	double ro = u[1];
	double l = u[2];

	// define x,z axes as vectors
	vnl_matrix<double> I(3,3); I.set_identity();
	vnl_vector<double> x_axis = I.get_column(0);
	vnl_vector<double> z_axis = I.get_column(2);

	// Update position
	
	// define rotation matrix for d_th about z_axis
	vnl_matrix<double> Rz_dth = vnl_rotation_matrix( (d_th*z_axis) );
	
	// define circular trajectory in y-z plane
	vnl_vector<double> circ(3,0.0);
	circ[1] = ro*(1-cos(l/ro));
	circ[2] = ro*sin(l/ro);

	// define delta position vector in current frame
	vnl_vector<double> d_p = Rz_dth*circ;

	// Transform delta vector into world frame using quaternion rotation
	vnl_vector<double> d_p_world = q.rotate(d_p);

	// add rotated vector to original position
	vnl_vector<double> p2 = d_p_world + p;

	// Update orientation

	// form quaternions for x-axis and z-axis rotations
	vnl_quaternion<double> q_b(z_axis,d_th);
	vnl_quaternion<double> q_a(x_axis,-l/ro);
	// multiply original orientation quaternion
	vnl_quaternion<double> q2 = q*q_b*q_a;
	vnl_vector<double> r2 = q2.axis()*q2.angle();

	// Compose final output
	for( int i = 0; i < 3; i++)
	{
		x2[i] = p2[i];
		x2[i+3] = r2[i];
	}
}
예제 #10
0
파일: main.cpp 프로젝트: gauravjsingh/FIFE
void randomHammingCircuit(Circuit **circuit, int length) {
  std::vector<int> circ(length);

  for (size_t i = 0; i < circ.size(); i++) {
    circ[i] = rand() % 2;
  }

  *circuit = new HammingCircuit(circ);
}
예제 #11
0
파일: main.cpp 프로젝트: gauravjsingh/FIFE
void randomLevenshteinCircuit(Circuit **circuit, int inputLen, int circuitLen, int alphabetBits) {
  std::vector<int> circ(circuitLen);

  for (size_t i = 0; i < circ.size(); i++) {
    circ[i] = rand() % (1 << alphabetBits);
  }

  *circuit = new LevenshteinCircuit(circ, inputLen, alphabetBits);
}
예제 #12
0
파일: main.cpp 프로젝트: gauravjsingh/FIFE
// Generate a random instance of the given circuit type
void randomInnerProductModPCircuit(Circuit **circuit, int mod, int length) {
  std::vector<int> circ(length);

  for (size_t i = 0; i < circ.size(); i++) {
    circ[i] = rand() % mod;
  }

  *circuit = new InnerProductModPCircuit(mod, circ);
}
예제 #13
0
int	write_champ(t_chp *champ, char *mem)
{
  int	warning;
  int	j;

  warning = 0;
  j = 0;
  while (j < champ->header.prog_size)
    {
      if (!warning && mem[circ((champ->pc + j))] != 0)
	{
	  my_putstr2("warning : one of the programs is overwriting another. "
		     "If this is an issue, make sure to set a proper adress "
		     "or to load less or smaller programs !\n");
	  ++warning;
	}
      mem[circ((champ->pc + j))] = champ->raw[j];
      j++;
    }
  return (SUCCESS);
}
예제 #14
0
int main()
{
    // create a window
    sf::RenderWindow window(sf::VideoMode(300, 300), "Controlling Shapes");
    //Create a shape 
    // circle
    sf::CircleShape circ(50);
    circ.setFillColor(sf::Color::Red);
    circ.setOutlineColor(sf::Color::Blue);
    circ.setOutlineThickness(3);

    // rectangle
    sf::RectangleShape rect(sf::Vector2f(50,50));
    rect.setFillColor(sf::Color::Green);
    bool moving{false}; 
    // game loop 
    while(window.isOpen())
    {
        // handle events 
        sf::Event event;
        while(window.pollEvent(event))
        {
            // close 
            if(event.type == sf::Event::Closed)
               window.close();
           
            if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Right)
               moving = true ;

            if(event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Right)
               moving = false;


        }
        
        if(moving)
        {
            // move the objects
            rect.move(sf::Vector2f(.5f, 0));
        }
        // update the scene
        rect.setRotation(30);
        // render cycle
        window.clear(sf::Color::Black);
        // draw the objects
        window.draw(circ);
        window.draw(rect);
        window.display();

    }

 return 0;
}
예제 #15
0
파일: GameState.cpp 프로젝트: ace13/ld26
void GameState::drawUi(sf::RenderTarget& target)
{
    if (!mInEditor)
        return;

    Kunlaboro::Message msg = sendGlobalQuestion("Get.GameView");
    sf::View& gameView = *boost::any_cast<sf::View*>(msg.payload);

    std::vector<Kunlaboro::Component*> comps = getEntitySystem()->getAllComponentsOnEntity(mPlayer, "Components.ShapeDrawable");

    for (auto it = comps.begin(); it != comps.end(); ++it)
    {
        auto comp = static_cast<Components::ShapeDrawable*>(*it);
        if (comp == NULL)
            continue;
        
        sf::Shape* shape = comp->getShape();
        sf::Vector2f scale = target.getView().getSize();
        scale.x /= gameView.getSize().x;
        scale.y /= gameView.getSize().y;

        for (int i = 0; i < shape->getPointCount(); ++i)
        {
            sf::Vector2f pos = shape->getPoint(i) - shape->getOrigin();
            {
                sf::Transform rot;
                rot.rotate(shape->getRotation()-gameView.getRotation());
                pos = rot.transformPoint(pos);
            }
            pos += shape->getPosition();
            pos -= gameView.getCenter();
            pos.x *= scale.x + 0.25;
            pos.y *= scale.y + 0.25;
            pos += target.getView().getCenter();

            sf::CircleShape circ(4.f);
            circ.setOrigin(4,4);
            circ.setFillColor(sf::Color::Transparent);
            circ.setOutlineColor(sf::Color::Black);
            circ.setOutlineThickness(4.f);

            circ.setPosition(pos);

            target.draw(circ);
        }
    }
}
예제 #16
0
int     load_next_instruction(t_vm *vm, t_chp *cur, t_opc **op)
{
  int   code;

  code = vm->mem[circ(cur->pc++)];
  my_printf("next instruction [%x]\n", code);
  if (code >= 1 && code <= 16)
    {
      cur->inst = op[code - 1];
      my_printf("cur keyword [%s]\n", cur->inst->keyword);
      cur->ticks = cur->inst->nb_cycles;
    }
  else
    {
      cur->ticks = 1;
      cur->inst = NULL;
    }
  cur = cur->next;
  return (SUCCESS);
}
예제 #17
0
char	cw_fillreg(t_cwar *cwar, t_proc *proc, unsigned char regnum, int i)
{
	int j;
	int	carry;

	carry = 0;
	if (regnum && regnum <= REG_NUMBER)
	{
		j = 0;
		while (j < REG_SIZE)
		{
			carry <<= 8;
			proc->reg[regnum][j++] = cwar->arena[i];
			carry += cwar->arena[i];
			i = circ(i, 1);
		}
		return (carry == 0) ? 1 : 0;
	}
	return (proc->carry);
}
void prod_impl(viennacl::circulant_matrix<NumericT, AlignmentV> const & mat,
               viennacl::vector_base<NumericT> const & vec,
               viennacl::vector_base<NumericT>       & result)
{
  assert(mat.size1() == result.size() && bool("Dimension mismatch"));
  assert(mat.size2() == vec.size() && bool("Dimension mismatch"));
  //result.clear();

  //Rcpp::Rcout << "prod(circulant_matrix" << ALIGNMENT << ", vector) called with internal_nnz=" << mat.internal_nnz() << std::endl;

  viennacl::vector<NumericT> circ(mat.elements().size() * 2);
  viennacl::linalg::real_to_complex(mat.elements(), circ, mat.elements().size());

  viennacl::vector<NumericT> tmp(vec.size() * 2);
  viennacl::vector<NumericT> tmp2(vec.size() * 2);

  viennacl::linalg::real_to_complex(vec, tmp, vec.size());
  viennacl::linalg::convolve(circ, tmp, tmp2);
  viennacl::linalg::complex_to_real(tmp2, result, vec.size());

}
예제 #19
0
파일: Polygon.cpp 프로젝트: mraggi/Graph
Polygon Polygon::RegularPolygon(int num, real radius, Point pos)
{
    Circle circ(pos, radius);
    return Polygon(circ, num);
}
예제 #20
0
void ArcBall::drawOuterRing ()
{
//	glColor4fv(rimColor.elem);
	glColor3ub(0, 255, 0);
	circ();
}
예제 #21
0
QgsGeometry QgsInternalGeometryEngine::variableWidthBuffer( int segments, const std::function< std::unique_ptr< double[] >( const QgsLineString *line ) > &widthFunction ) const
{
  if ( !mGeometry )
  {
    return QgsGeometry();
  }

  std::vector< std::unique_ptr<QgsLineString > > linesToProcess;

  const QgsMultiCurve *multiCurve = qgsgeometry_cast< const QgsMultiCurve * >( mGeometry );
  if ( multiCurve )
  {
    for ( int i = 0; i < multiCurve->partCount(); ++i )
    {
      if ( static_cast< const QgsCurve * >( multiCurve->geometryN( i ) )->nCoordinates() == 0 )
        continue; // skip 0 length lines

      linesToProcess.emplace_back( static_cast<QgsLineString *>( multiCurve->geometryN( i )->clone() ) );
    }
  }

  const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( mGeometry );
  if ( curve )
  {
    if ( curve->nCoordinates() > 0 )
      linesToProcess.emplace_back( static_cast<QgsLineString *>( curve->segmentize() ) );
  }

  if ( linesToProcess.empty() )
  {
    QgsGeometry g;
    g.mLastError = QStringLiteral( "Input geometry was not a curve type geometry" );
    return g;
  }

  QVector<QgsGeometry> bufferedLines;

  for ( std::unique_ptr< QgsLineString > &line : linesToProcess )
  {
    QVector<QgsGeometry> parts;
    QgsPoint prevPoint;
    double prevRadius = 0;
    QgsGeometry prevCircle;

    std::unique_ptr< double[] > widths = widthFunction( line.get() ) ;
    for ( int i = 0; i < line->nCoordinates(); ++i )
    {
      QgsPoint thisPoint = line->pointN( i );
      QgsGeometry thisCircle;
      double thisRadius = widths[ i ] / 2.0;
      if ( thisRadius > 0 )
      {
        QgsGeometry p = QgsGeometry( thisPoint.clone() );

        QgsCircle circ( thisPoint, thisRadius );
        thisCircle = QgsGeometry( circ.toPolygon( segments * 4 ) );
        parts << thisCircle;
      }
      else
      {
        thisCircle = QgsGeometry( thisPoint.clone() );
      }

      if ( i > 0 )
      {
        if ( prevRadius > 0 || thisRadius > 0 )
        {
          QVector< QgsPointXY > points = generateSegmentCurve( prevPoint, prevRadius, thisPoint, thisRadius );
          if ( !points.empty() )
          {
            // snap points to circle vertices

            int atVertex = 0;
            int beforeVertex = 0;
            int afterVertex = 0;
            double sqrDist = 0;
            double sqrDistPrev = 0;
            for ( int j = 0; j < points.count(); ++j )
            {
              QgsPointXY pA = prevCircle.closestVertex( points.at( j ), atVertex, beforeVertex, afterVertex, sqrDistPrev );
              QgsPointXY pB = thisCircle.closestVertex( points.at( j ), atVertex, beforeVertex, afterVertex, sqrDist );
              points[j] = sqrDistPrev < sqrDist ? pA : pB;
            }
            // close ring
            points.append( points.at( 0 ) );

            std::unique_ptr< QgsPolygon > poly = qgis::make_unique< QgsPolygon >();
            poly->setExteriorRing( new QgsLineString( points ) );
            if ( poly->area() > 0 )
              parts << QgsGeometry( std::move( poly ) );
          }
        }
      }
      prevPoint = thisPoint;
      prevRadius = thisRadius;
      prevCircle = thisCircle;
    }

    bufferedLines << QgsGeometry::unaryUnion( parts );
  }

  return QgsGeometry::collectGeometry( bufferedLines );
}
예제 #22
0
// This shouldn't go here... but it's so long
Scene::Scene(std::string& pyinitScript) :
    m_ContactSolver(100),   // 100 solver iterations
    m_EffectManager(Mix_AllocateChannels(-1)) // -1 returns channel count
{
    auto check = [](bool cond, std::string msg = "") {
        if (!msg.empty())
            std::cout << msg << "----" << (cond ? " succeeded! " : " failed! ") << std::endl;
        assert(cond);
    };
    
    // Expose sound effect manager
    Python::Expose_Object(&m_EffectManager, "SndEffManager", Python::GetPyLiaisonModule().get());
    
    // Convert the relative python path to the absolute, load module
    std::string initStrPath = FixBackslash(RelPathToAbs(SCRIPT_DIR ) + pyinitScript);
    Python::Object pyinitModule = Python::Object::from_script(initStrPath);
    
    // Get main module name and load it
    std::string mainModName;
    pyinitModule.call_function("GetMainModuleName").convert(mainModName);
    m_MainPyModule = Python::Object::from_script(mainModName);
    
    // Set up the shader
    std::map<std::string, std::string> shaderInfo;
    pyinitModule.call_function("GetShaderSrc").convert(shaderInfo);
    m_Shader = Shader(shaderInfo["vert"], shaderInfo["frag"], SHADER_DIR);
    
    // Get position handle
    auto sBind = m_Shader.ScopeBind();
    GLint posHandle = m_Shader[shaderInfo["Position"]];
    Drawable::SetPosHandle(posHandle);
    
    // Initialize Camera
    pyinitModule.call_function("InitCamera", &m_Camera);
    
    // Like a mini factory (no collision info for now, just circles)
    using EntInfo = std::tuple<
    vec2, // velocity
    vec2, // Position
    vec2, // Scale
    float, // Rotation about +z
    float, // mass
    float, // elasticity
    vec4, // Color
    std::string>;
    
    // Now loop through all named tuples in the script
    std::vector<EntInfo> v_EntInfo;
    pyinitModule.call_function("GetEntities").convert(v_EntInfo);
    
    // Preallocate all entities, since we'll need their pointers
    m_vEntities.resize(v_EntInfo.size());
    
    // Create individual entities and components
    for (int i = 0; i < m_vEntities.size(); i++) {
        // Get the tuple
        auto ei = v_EntInfo[i];
        
        // Unpack tuple
        vec2 vel(std::get<0>(ei));
        vec3 pos(std::get<1>(ei), 0.f);
        vec2 scale(std::get<2>(ei));
        float rot = std::get<3>(ei);
        float m = std::get<4>(ei);
        float e = clamp(std::get<5>(ei),0.f,1.f);
        vec4 color = glm::clamp(std::get<6>(ei), vec4(0), vec4(1));
        std::string pyEntModScript = std::get<7>(ei);
        
        // Load the python module
        auto pyEntModule = Python::Object::from_script(SCRIPT_DIR + pyEntModScript);
        
        // Create Entity
        Entity ent(i, this, pyEntModule);
        m_vEntities[i] = ent;
        
        // Get the entity's resources as a tuple (wow)
        std::tuple<std::string, std::string, std::list<std::string> > eRsrc;
        pyEntModule.call_function("GetResources").convert(eRsrc);
        
        // IQM File
        std::string iqmFile = std::get<0>(eRsrc);
//        check(pyEntModule.get_attr("r_IqmFile").convert(iqmFile), "Getting IqmFile from module " + pyEntModScript);
        
        
        // Collision primitives (this will get more complicated)
        std::string colPrim = std::get<1>(eRsrc);
       // check(pyEntModule.get_attr("r_ColPrim").convert(colPrim), "Getting basic collision primitive from ent module");
        
        // Make collision resource, (assume uniform scale, used for mass and r)
        // TODO add mass, elasticity to init tuple
        if (colPrim == "AABB") {  // AABBs are assumed to be "walls" of high mass for now
            AABB box(vel, vec2(pos), m, e, scale);
            box.SetEntity(&m_vEntities[i]);
            m_vAABB.push_back(box);
        }
        else if (colPrim == "OBB") {
            OBB box(vel, vec2(pos), m, e, scale, rot);
            box.SetEntity(&m_vEntities[i]);
            //box.w = (omegaDir++ % 2 ? -10.f : 0.f);
            m_vOBB.push_back(box);
        }
        else {
            Circle circ(vel, vec2(pos), m, e, maxEl(scale));
            circ.SetEntity(&m_vEntities[i]);;
            m_vCircles.push_back(circ);
        }
    
        // Sounds
        std::list<std::string> sndFiles = std::get<2>(eRsrc);
        //check(pyEntModule.get_attr("r_Sounds").convert(sndFiles), "Getting all sounds from module " + pyEntModScript);
        for (auto& file : sndFiles)
            m_EffectManager.RegisterEffect(file);
        
        // Make drawable
        fquat rotQ(cos(rot / 2.f), vec3(0, 0, sin(rot / 2.f)));
        Drawable dr(iqmFile, color, quatvec(pos, rotQ), scale);
        dr.SetEntity(&m_vEntities[i]);
        m_vDrawables.push_back(dr);
    }
    
    // Fix entity pointers (I hate this)
    for (auto& circle : m_vCircles)
        circle.GetEntity()->SetColCmp(&circle);
    for (auto& box : m_vAABB)
        box.GetEntity()->SetColCmp(&box);
    for (auto& box : m_vOBB)
        box.GetEntity()->SetColCmp(&box);
    for (auto& drawable : m_vDrawables)
        drawable.GetEntity()->SetDrCmp(&drawable);
    
    // Expose in python, mapping ent ID to Exposed Entity
    // TODO Entities should be globally accessible via the PyLiaison module,
    // so find a way fo adding a container to it
    // PyDict_New...
    for (auto& ent : m_vEntities)
        ent.GetPyModule().call_function("AddEntity", ent.GetID(), &ent);
}
예제 #23
0
bool	build_convex_polygon(
				Pmwx::Ccb_halfedge_circulator									ccb,
				vector<pair<Pmwx::Halfedge_handle, Pmwx::Halfedge_handle> >&	sides,
				const CoordTranslator2&											trans,
				Polygon2&														metric_bounds,
				double															max_err_mtrs,
				double															min_side_len)
{
	double	e_sq = max_err_mtrs*max_err_mtrs;
	sides.clear();
	metric_bounds.clear();
	
	Pmwx::Ccb_halfedge_circulator circ(ccb);
//	Bbox2				bounds;
//	
//	do {
//		bounds += cgal2ben(circ->source()->point());
//	} while (++circ != ccb);

	Pmwx::Ccb_halfedge_circulator start,next;
	start = ccb;
	do {
		--start;
		if(!sides_can_merge(start,ccb))
			break;
		if(!within_err_metric(start,ccb,trans,e_sq))
			break;		
	} while(start != ccb);
	++start;
	
	// now we can go around.

	circ = start;
	//int ne = count_circulator(start);
	//printf("Poly has %d sides.\n", ne);
	do {
	 
		Pmwx::Ccb_halfedge_circulator stop(circ);
		do {
			++stop;
		} while(sides_can_merge(circ,stop) && within_err_metric(circ,stop,trans,e_sq) && stop != start);
	
		--stop;
		//printf("Pushing side of %d, %d\n", circulator_distance_to(start, circ),circulator_distance_to(start,stop));
		sides.push_back(pair<Pmwx::Halfedge_handle,Pmwx::Halfedge_handle>(circ, stop));
		++stop;
		circ = stop;
	
	} while(circ != start);
	
	if(sides.size() < 3)	
	{
		//debug_mesh_point(bounds.centroid(),1,1,1);
		return false;
	}
	
	int i, j, k;
	
	vector<Segment2>	msides;
	for(i = 0; i < sides.size(); ++i)
	{
		j = (i + 1) % sides.size();		
		DebugAssert(sides[i].second->target() == sides[j].first->source());
		msides.push_back(Segment2(
						trans.Forward(cgal2ben(sides[i].first->source()->point())),
						trans.Forward(cgal2ben(sides[i].second->target()->point()))));						
	}	
	vector<Segment2>	debug(msides);
	for(i = 0; i < sides.size(); ++i)
	{
		j = (i + 1) % sides.size();		
		Vector2	v1(msides[i].p1,msides[i].p2);
		Vector2	v2(msides[j].p1,msides[j].p2);
		v1.normalize();
		v2.normalize();
		if(v1.dot(v2) > 0.9998 ||
			!v1.left_turn(v2))
		{
			//debug_mesh_point(trans.Reverse(msides[i].p2),1,0,0);
			return false;
		}
		double w = width_for_he(sides[i].first);
		if(w)
		{
			v1 = v1.perpendicular_ccw();
			v1 *= w;
			msides[i].p1 += v1;
			msides[i].p2 += v1;
		}
	}
	for(j = 0; j < sides.size(); ++j)
	{
		i = (j + sides.size() - 1) % sides.size();
		Line2 li(msides[i]), lj(msides[j]);
		Point2	p;
		if(!li.intersect(lj,p))
		{
			Assert(!"Failure to intersect.\n");
			return false;
		}
		metric_bounds.push_back(p);
	}
	
	for(i = 0; i < metric_bounds.size(); ++i)
	{
		j = (i + 1) % metric_bounds.size();
		k = (i + 2) % metric_bounds.size();
		if(metric_bounds.side(i).squared_length() < (min_side_len*min_side_len))
		{
			//debug_mesh_line(trans.Reverse(metric_bounds.side(i).p1),trans.Reverse(metric_bounds.side(i).p2),1,1,0,1,1,0);
			return false;
		}
		if(!left_turn(metric_bounds[i],metric_bounds[j],metric_bounds[k]))
		{
			//debug_mesh_point(trans.Reverse(metric_bounds[j]),1,1,0);
			return false;
		}
		if(Vector2(msides[i].p1,msides[i].p2).dot(Vector2(metric_bounds[i],metric_bounds[j])) < 0.0)
		{
			//debug_mesh_line(trans.Reverse(msides[i].p1),trans.Reverse(msides[i].p2),1,0,0,1,0,0);
			return false;
		}
	}
	DebugAssert(metric_bounds.size() == msides.size());
	DebugAssert(msides.size() == sides.size());
		
	return true;
}
예제 #24
0
void filledCirc (COORDS figure, HDC hdc, COLORREF color) {
	HBRUSH hBrush = CreateSolidBrush (color);
	HGDIOBJ orig = SelectObject (hdc, hBrush);
	circ (figure, hdc);
	deleteFilledObjetFigure (orig, hdc, hBrush);
}
예제 #25
0
static void ruler_info_draw_pixel(const struct bContext *C, ARegion *ar, void *arg)
{
	Scene *scene = CTX_data_scene(C);
	UnitSettings *unit = &scene->unit;
	RulerItem *ruler_item;
	RulerInfo *ruler_info = arg;
	RegionView3D *rv3d = ruler_info->ar->regiondata;
//	ARegion *ar = ruler_info->ar;
	const float cap_size = 4.0f;
	const float bg_margin = 4.0f * U.pixelsize;
	const float bg_radius = 4.0f * U.pixelsize;
	const float arc_size = 64.0f * U.pixelsize;
#define ARC_STEPS 24
	const int arc_steps = ARC_STEPS;
	int i;
	//unsigned int color_act = 0x666600;
	unsigned int color_act = 0xffffff;
	unsigned int color_base = 0x0;
	unsigned char color_back[4] = {0xff, 0xff, 0xff, 0x80};
	unsigned char color_text[3];
	unsigned char color_wire[3];

	/* anti-aliased lines for more consistent appearance */
	glEnable(GL_LINE_SMOOTH);

	BLF_enable(blf_mono_font, BLF_ROTATION);
	BLF_size(blf_mono_font, 14 * U.pixelsize, U.dpi);
	BLF_rotation(blf_mono_font, 0.0f);

	UI_GetThemeColor3ubv(TH_TEXT, color_text);
	UI_GetThemeColor3ubv(TH_WIRE, color_wire);

	for (ruler_item = ruler_info->items.first, i = 0; ruler_item; ruler_item = ruler_item->next, i++) {
		const bool is_act = (i == ruler_info->item_active);
		float dir_ruler[2];
		float co_ss[3][2];
		int j;

		/* should these be checked? - ok for now not to */
		for (j = 0; j < 3; j++) {
			ED_view3d_project_float_global(ar, ruler_item->co[j], co_ss[j], V3D_PROJ_TEST_NOP);
		}

		glEnable(GL_BLEND);

		cpack(is_act ? color_act : color_base);

		if (ruler_item->flag & RULERITEM_USE_ANGLE) {
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j++) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			cpack(0xaaaaaa);
			setlinestyle(3);
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j++) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			setlinestyle(0);

			/* arc */
			{
				float dir_tmp[3];
				float co_tmp[3];
				float arc_ss_coords[ARC_STEPS + 1][2];

				float dir_a[3];
				float dir_b[3];
				float quat[4];
				float axis[3];
				float angle;
				const float px_scale = (ED_view3d_pixel_size(rv3d, ruler_item->co[1]) *
				                        min_fff(arc_size,
				                                len_v2v2(co_ss[0], co_ss[1]) / 2.0f,
				                                len_v2v2(co_ss[2], co_ss[1]) / 2.0f));

				sub_v3_v3v3(dir_a, ruler_item->co[0], ruler_item->co[1]);
				sub_v3_v3v3(dir_b, ruler_item->co[2], ruler_item->co[1]);
				normalize_v3(dir_a);
				normalize_v3(dir_b);

				cross_v3_v3v3(axis, dir_a, dir_b);
				angle = angle_normalized_v3v3(dir_a, dir_b);

				axis_angle_to_quat(quat, axis, angle / arc_steps);

				copy_v3_v3(dir_tmp, dir_a);

				glColor3ubv(color_wire);

				for (j = 0; j <= arc_steps; j++) {
					madd_v3_v3v3fl(co_tmp, ruler_item->co[1], dir_tmp, px_scale);
					ED_view3d_project_float_global(ar, co_tmp, arc_ss_coords[j], V3D_PROJ_TEST_NOP);
					mul_qt_v3(quat, dir_tmp);
				}

				glEnableClientState(GL_VERTEX_ARRAY);
				glVertexPointer(2, GL_FLOAT, 0, arc_ss_coords);
				glDrawArrays(GL_LINE_STRIP, 0, arc_steps + 1);
				glDisableClientState(GL_VERTEX_ARRAY);
			}

			/* text */
			{
				char numstr[256];
				float numstr_size[2];
				float pos[2];
				const int prec = 2;  /* XXX, todo, make optional */

				ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);

				BLF_width_and_height(blf_mono_font, numstr, sizeof(numstr), &numstr_size[0], &numstr_size[1]);

				pos[0] = co_ss[1][0] + (cap_size * 2.0f);
				pos[1] = co_ss[1][1] - (numstr_size[1] / 2.0f);

				/* draw text (bg) */
				glColor4ubv(color_back);
				uiSetRoundBox(UI_CNR_ALL);
				uiRoundBox(pos[0] - bg_margin,                  pos[1] - bg_margin,
				           pos[0] + bg_margin + numstr_size[0], pos[1] + bg_margin + numstr_size[1],
				           bg_radius);
				/* draw text */
				glColor3ubv(color_text);
				BLF_position(blf_mono_font, pos[0], pos[1], 0.0f);
				BLF_rotation(blf_mono_font, 0.0f);
				BLF_draw(blf_mono_font, numstr, sizeof(numstr));
			}

			/* capping */
			{
				float rot_90_vec_a[2];
				float rot_90_vec_b[2];
				float cap[2];

				sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[1]);
				rot_90_vec_a[0] = -dir_ruler[1];
				rot_90_vec_a[1] =  dir_ruler[0];
				normalize_v2(rot_90_vec_a);

				sub_v2_v2v2(dir_ruler, co_ss[1], co_ss[2]);
				rot_90_vec_b[0] = -dir_ruler[1];
				rot_90_vec_b[1] =  dir_ruler[0];
				normalize_v2(rot_90_vec_b);

				glEnable(GL_BLEND);

				glColor3ubv(color_wire);

				glBegin(GL_LINES);

				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, -cap_size);
				glVertex2fv(cap);

				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, -cap_size);
				glVertex2fv(cap);

				/* angle vertex */
				glVertex2f(co_ss[1][0] - cap_size, co_ss[1][1] - cap_size);
				glVertex2f(co_ss[1][0] + cap_size, co_ss[1][1] + cap_size);
				glVertex2f(co_ss[1][0] - cap_size, co_ss[1][1] + cap_size);
				glVertex2f(co_ss[1][0] + cap_size, co_ss[1][1] - cap_size);
				glEnd();

				glDisable(GL_BLEND);
			}
		}
		else {
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j += 2) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			cpack(0xaaaaaa);
			setlinestyle(3);
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j += 2) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			setlinestyle(0);

			sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[2]);

			/* text */
			{
				char numstr[256];
				float numstr_size[2];
				const int prec = 6;  /* XXX, todo, make optional */
				float pos[2];

				ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);

				BLF_width_and_height(blf_mono_font, numstr, sizeof(numstr), &numstr_size[0], &numstr_size[1]);

				mid_v2_v2v2(pos, co_ss[0], co_ss[2]);

				/* center text */
				pos[0] -= numstr_size[0] / 2.0f;
				pos[1] -= numstr_size[1] / 2.0f;

				/* draw text (bg) */
				glColor4ubv(color_back);
				uiSetRoundBox(UI_CNR_ALL);
				uiRoundBox(pos[0] - bg_margin,                  pos[1] - bg_margin,
				           pos[0] + bg_margin + numstr_size[0], pos[1] + bg_margin + numstr_size[1],
				           bg_radius);
				/* draw text */
				glColor3ubv(color_text);
				BLF_position(blf_mono_font, pos[0], pos[1], 0.0f);
				BLF_draw(blf_mono_font, numstr, sizeof(numstr));
			}

			/* capping */
			{
				float rot_90_vec[2] = {-dir_ruler[1], dir_ruler[0]};
				float cap[2];

				normalize_v2(rot_90_vec);

				glEnable(GL_BLEND);
				glColor3ubv(color_wire);

				glBegin(GL_LINES);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, -cap_size);
				glVertex2fv(cap);

				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, -cap_size);
				glVertex2fv(cap);
				glEnd();

				glDisable(GL_BLEND);
			}
		}
	}

	glDisable(GL_LINE_SMOOTH);

	BLF_disable(blf_mono_font, BLF_ROTATION);

#undef ARC_STEPS

	/* draw snap */
	if ((ruler_info->snap_flag & RULER_SNAP_OK) && (ruler_info->state == RULER_STATE_DRAG)) {
		ruler_item = ruler_item_active_get(ruler_info);
		if (ruler_item) {
			/* size from drawSnapping */
			const float size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
			float co_ss[3];
			ED_view3d_project_float_global(ar, ruler_item->co[ruler_item->co_index], co_ss, V3D_PROJ_TEST_NOP);

			cpack(color_act);
			circ(co_ss[0], co_ss[1], size * U.pixelsize);
		}
	}

}
void Foam::featurePointConformer::createMasterAndSlavePoints
(
    const extendedFeatureEdgeMesh& feMesh,
    const label ptI,
    DynamicList<Vb>& pts
) const
{
    typedef DynamicList<autoPtr<plane> >          planeDynList;
    typedef indexedVertexEnum::vertexType         vertexType;
    typedef extendedFeatureEdgeMesh::edgeStatus   edgeStatus;

    const Foam::point& featPt = feMesh.points()[ptI];

    if
    (
        (
            Pstream::parRun()
         && !foamyHexMesh_.decomposition().positionOnThisProcessor(featPt)
        )
     || geometryToConformTo_.outside(featPt)
    )
    {
        return;
    }

    const scalar ppDist = foamyHexMesh_.pointPairDistance(featPt);

    // Maintain a list of master points and the planes to relect them in
    DynamicList<Foam::point> masterPoints;
    DynamicList<vertexType> masterPointsTypes;
    Map<planeDynList> masterPointReflections;

    const labelList& featPtEdges = feMesh.featurePointEdges()[ptI];

    pointFeatureEdgesTypes pointEdgeTypes(feMesh, ptI);

    const List<extendedFeatureEdgeMesh::edgeStatus> allEdStat =
        pointEdgeTypes.calcPointFeatureEdgesTypes();

//    Info<< nl << featPt << "  " << pointEdgeTypes;

    const_circulator<labelList> circ(featPtEdges);

    // Loop around the edges of the feature point
    if (circ.size()) do
    {
//        const edgeStatus eStatusPrev = feMesh.getEdgeStatus(circ.prev());
        const edgeStatus eStatusCurr = feMesh.getEdgeStatus(circ());
//        const edgeStatus eStatusNext = feMesh.getEdgeStatus(circ.next());

//        Info<< "    Prev = "
//            << extendedFeatureEdgeMesh::edgeStatusNames_[eStatusPrev]
//            << " Curr = "
//            << extendedFeatureEdgeMesh::edgeStatusNames_[eStatusCurr]
////            << " Next = "
////            << extendedFeatureEdgeMesh::edgeStatusNames_[eStatusNext]
//            << endl;

        // Get the direction in which to move the point in relation to the
        // feature point
        label sign = getSign(eStatusCurr);

        const vector n = sharedFaceNormal(feMesh, circ(), circ.next());

        const vector pointMotionDirection = sign*0.5*ppDist*n;

//        Info<< "    Shared face normal      = " << n << endl;
//        Info<< "    Direction to move point = " << pointMotionDirection
//            << endl;

        if (masterPoints.empty())
        {
            // Initialise with the first master point
            Foam::point pt = featPt + pointMotionDirection;

            planeDynList firstPlane;
            firstPlane.append(autoPtr<plane>(new plane(featPt, n)));

            masterPoints.append(pt);

            masterPointsTypes.append
            (
                sign == 1
              ? Vb::vtExternalFeaturePoint // true
              : Vb::vtInternalFeaturePoint // false
            );

            //Info<< "    " << " " << firstPlane << endl;

//            const Foam::point reflectedPoint = reflectPointInPlane
//            (
//                masterPoints.last(),
//                firstPlane.last()()
//            );

            masterPointReflections.insert
            (
                masterPoints.size() - 1,
                firstPlane
            );
        }
//        else if
//        (
//            eStatusPrev == extendedFeatureEdgeMesh::INTERNAL
//         && eStatusCurr == extendedFeatureEdgeMesh::EXTERNAL
//        )
//        {
//            // Insert a new master point.
//            Foam::point pt = featPt + pointMotionDirection;
//
//            planeDynList firstPlane;
//            firstPlane.append(autoPtr<plane>(new plane(featPt, n)));
//
//            masterPoints.append(pt);
//
//            masterPointsTypes.append
//            (
//                sign == 1
//              ? Vb::vtExternalFeaturePoint // true
//              : Vb::vtInternalFeaturePoint // false
//            );
//
//            masterPointReflections.insert
//            (
//                masterPoints.size() - 1,
//                firstPlane
//            );
//        }
//        else if
//        (
//            eStatusPrev == extendedFeatureEdgeMesh::EXTERNAL
//         && eStatusCurr == extendedFeatureEdgeMesh::INTERNAL
//        )
//        {
//
//        }
        else
        {
            // Just add this face contribution to the latest master point

            masterPoints.last() += pointMotionDirection;

            masterPointReflections[masterPoints.size() - 1].append
            (
                autoPtr<plane>(new plane(featPt, n))
            );
        }

    } while (circ.circulate(CirculatorBase::CLOCKWISE));

    addMasterAndSlavePoints
    (
        masterPoints,
        masterPointsTypes,
        masterPointReflections,
        pts,
        ptI
    );
}
예제 #27
0
void normalCirc (COORDS figure, HDC hdc, HPEN& hPen) {
	HGDIOBJ orig = SelectObject (hdc, hPen);
	circ (figure, hdc);
	deleteNormalObjetFigure (orig, hdc, hPen);
}
예제 #28
0
파일: main.cpp 프로젝트: uzgoren/girdap
int main() {
  Block2 grid({0, 0, 0}, {1, 1, 0}, 20, 20);
  Block1 lin({0.2, 0.3, 0}, {0.8, 0.6, 0}, 20); //checks
  lin.writeVTK("lin");
  
  Block1 poly({{0.1, 0.1}, {0.2, 0.3}, {0.6, 0.2}
      , {0.3, 0.2}, {0.4, 0.15}, {0.3, 0.09}, {0.1,0.1}}, 0.02); // check resolve
  poly.writeVTK("poly");
  
  Block1 circ(new Geo1Circle(Vec3(0.5, 0.75), 0.15, 360, 0), 4); // OK
  circ.writeVTK("circ");
  
  poly.add(circ); // OK
  poly.writeVTK("poly");
  
  // //--- Circular arc ----
  Block1 arc(new Geo1Circle(Vec3(0.5, 0.75), 0.15, 30, 120), 40); // OK
  arc.writeVTK("arc");
  
  // //--- Rotated polygon "equal sided"
  Block1 rotsqr(new Geo1Circle(Vec3(0.5,0.75), 0.15, 30, 400), 4); // OK
  rotsqr.resolve(0.15/sqrt(2)*0.1);
  rotsqr.writeVTK("rotsqr"); 
  
  Block1 rotpenta(new Geo1Circle(Vec3(0.5,0.75), 0.15, 30, 400), 5); //OK
  rotpenta.resolve(0.01);
  rotpenta.writeVTK("rotpenta");

  lin.add(0.0, 1.0, 10
	       , [](double t) -> Vec3 {return Vec3(0.0) + t*Vec3(0.2, -0.1)/10;} );
  lin.writeVTK("lin");

  Block1 sine;
  sine.add(0.0, 1.0, 50
		, [](double t) -> Vec3 {return Vec3(t, 0.1*sin(5*t*3.14), 0);} );
  sine.writeVTK("sine"); 

  Block1 arc2;
  arc2.add(0, 360, 20
	      , [](double t) -> Vec3 {return Vec3(0.5,0.75) + 0.15*Vec3(cos(t*3.14/180), sin(t*3.14/180)); } ); 
  arc2.writeVTK("ccc");

  Block1 line2(new Geo1Sine(Vec3(0.2, 0.4), Vec3(0.5, 0.5), 0.1, 5), 50);
  line2.add(new Geo1Line(Vec3(0.5, 0.5), Vec3(0.8, 0.6)), 20); 
  line2.writeVTK("sdsd"); 

  Geo1Circle* g0 = new Geo1Circle(Vec3(0.5, 0.5), 0.2);  
  Block1 arc3(g0, 30);
  delete g0; 
  arc3.writeVTK("newCircle"); 
  
  // grid->addVertex({ {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0} }); 

  // grid->addCell( {0, 1, 2, 3} ) ; 

  // for (auto i =0; i<3; ++i) {
  //   grid->listCell[0]->adapt = {1, 1}; 
  //   grid->adapt(); 
  //   grid->writeVTK("myFirstGrid_"); 
  // }
  
  //delete(grid); 

  // Block2* volgrid = new Block2({0,0,0}, {1,1,0}, 10, 10); 
  // Grid* surf = new Grid(); 

  // surf->addVertex({{0.5,0.4}, {0.6,0.5}, {0.5,0.6}, {0.4,0.5}}); 
  // surf->addCell({{0,1}, {1,2}, {2,3}, {3,0}}); 

  // volgrid->writeVTK("vol"); 
  // surf->writeVTK("surf"); 

  // delete(volgrid); 
  // delete(surf); 
  //double pi = 4*atan(1.0); 

  // Block2* volgrid = new Block2({0,0,0}, {1,1,0}, 5, 5); 
  
  // // add a new variable
  // volgrid->addVar("f"); 
  // auto f = volgrid->getVar("f"); // variable handle
  
  // f->setBC("east", "grad", 0);   // This is the default
  // f->setBC("north", "val", 1);   //   

  // for (auto i=0; i < 4; ++i) { 
  //   for (auto c : volgrid->listCell) {
  //     auto x = c->getCoord(); // cell-centers
  //     f->set(c->id, sin(3*pi*x[0])*cos(2*pi*x[1]));
  //   }
  //   volgrid->solBasedAdapt2(volgrid->getError(f)); 
  //   volgrid->adapt(); 
  //   volgrid->writeVTK("field_"); 
  // }
  
  // delete(volgrid); 


  // Block2* volgrid = new Block2({0,0,0}, {1,1,0}, 50, 50); 

  // // Velocity field
  // auto uv = volgrid->getVar("u"); auto vv = volgrid->getVar("v"); 
  // uv->set(1.0); // set velocity
  // vv->set(-0.5); // set velocity
  // // New variable at cell center
  // volgrid->addVar("f"); auto f = volgrid->getVar("f"); 

  // Grid* surf = new Grid(); 

  // surf->addVertex({{0.55,0.32}, {0.58,0.5}, {0.45,0.68}, {0.42,0.46}}); 
  // surf->addCell({{0,1}, {1,2}, {2,3}, {3,0}}); 
  // // Refine cell; 
  // for (auto i=0; i<4; ++i) {
  //   for (auto c: surf->listCell) if (c->vol().abs() > 0.02) c->adapt[0] = 1;
  //   surf->adapt(); 
  // }
  // volgrid->updateOtherVertex(surf);
  // // mark location of this surface
  // volgrid->indicator(surf, f);

  // // Assign velocity variables to surface at vertex  
  // surf->addVec("u",1);

  // // Get velocity on the surface
  // auto us = surf->getVar("u"); auto vs = surf->getVar("v");   
  // volgrid->passVar(surf, uv, us); 
  // volgrid->passVar(surf, vv, vs);   

  // volgrid->writeVTK("vol"); 
  // surf->writeVTK("surf"); 

  // delete(volgrid); 
  // delete(surf); 

  // // Problem parameters
  // auto k = 2.0; auto qdot = 5e3; auto h = 50; auto Tinf = 20;
  // // Grid
  // Block2* grid = new Block2({0, 0, 0}, {1, 1, 0}, 10, 10); 
  // grid->levelHighBound[0] = 2; 
  // grid->levelHighBound[1] = 2; 
  // grid->addVar("T"); 
  // // Variables
  // auto T = grid->getVar("T");
  // // Linear solver
  // T->solver = "BiCGSTAB";
  // T->itmax = 1000; 
  // T->set(100); 
  // // Boundary conditions
  // T->setBC("south", "grad", 0); 
  // T->setBC("north", "grad", h/k*Tinf, -h/k);
  // T->setBC("east", "val", 200); 
  // T->setBC("west", "val", 100); 
  
  // for (auto i = 0; i< 4; ++i) {
  //   grid->solBasedAdapt2(grid->getError2(T), 2e-3, 2e-1);
  //   grid->adapt();  
    
  //   // Equation 
  //   grid->lockBC(T); 	
  //   T->solve( grid->laplace(k) 
  // 	      + grid->source(0, qdot) ); 
  //   grid->unlockBC();
    
  //   grid->writeVTK("heat"); 
  // }
    
  // delete(grid); 
  
  // Block2* grid = new Block2({0, 0, 0}, {1, 1, 0}, 10, 10);
  // double time= 0; double endTime = 1; //dt*50; 
  // // Problem constants
  // auto k = 2.0; auto qdot = 5e4; auto h = 20; auto Tinf = 20;
  // auto rho=1000, cp=4000;
  // // Field variables, velocity already defined
  // grid->addVar("T"); 

  // auto u = grid->getVar("u"); 
  // auto v = grid->getVar("v"); 
  // auto T = grid->getVar("T"); 

  // T->set(100); 
  // T->setBC("west", "val", 20);
  // T->setBC("south", "val", 20);
  // T->itmax = 50; 

  // u->set(1); 
  // v->set(0.2); 

  // grid->cfl = 0.5; 
  // int it = 0; 
  // while (time < endTime) {
  //   grid->setDt(0.5); // CFL condition     
  //   auto vel = grid->getVel(); // freeze velocity! 

  //   // Advection-diffusion equation ---
  //   grid->lockBC(T); 
  //   T->solve(
  // 	     grid->ddt(1.0) 
  // 	     + grid->div(vel, 1.0)
  // 	     - grid->laplace(k/rho/cp) 
  // 	     - grid->source(0, qdot/rho/cp)
  // 	     ); 
  //   grid->unlockBC();     
  //   grid->writeVTK("heattime_"); 
    
  //   if (it++ % 5 == 0) {
  //     grid->solBasedAdapt(grid->valGrad(T));
  //     grid->adapt(); 
  //   }

  //   time += grid->dt; 
  // }


  // // GRID 
  // Block2* grid = new Block2({0, 0, 0}, {10, 1, 0}, 20, 20);

  // // CONST variables; 
  // double rho = 1; double mu = 0.01; 

  // // FIELD variables; Vorticity to appear in the output
  // grid->addVar({"p", "vor"}); 
    
  // // initial and bc values; 
  // auto u = grid->getVar("u"); 
  // u->set(0.0);
  // u->setBC("west", "val", 1.0); u->setBC("east", "val", 0);
  // u->setBC("south", "val", 0); u->setBC("north", "val", 0); 
 
  // auto v = grid->getVar("v"); 
  // v->set(0.0);
  // v->setBC("west", "val", 0); v->setBC("east", "val", 0);
  // v->setBC("south", "val", 0); v->setBC("north", "val", 0); 

  // auto p = grid->getVar("p");
  // p->set(0.0);

  // auto vor = grid->getVar("vor");

  // // Solver behavior
  // u->solver = "Gauss"; u->itmax = 20; u->tol = 1e-4; 
  // v->solver = "Gauss"; v->itmax = 20; v->tol = 1e-4; 
  // p->solver = "BiCGSTAB"; p->itmax = 10000; p->tol = 1e-6; 

  // auto gp = grid->valGrad(p);   
 
  // // Time control 
  // grid->setDt(1.0); 
  // double time= 0; double endTime = 10; 
  // int it = 0, writeInt = 4; 

  // while (time < endTime) {
  //   auto vel = grid->getVel();
  //   // Compute vorticity; 
  //   vor->set(grid->valGrad(v).comp(0) - grid->valGrad(u).comp(1)); 
    
  //   // Solve for u*
  //   grid->lockBC(u); 
  //   u->solve(grid->ddt(rho) + grid->div(vel, rho) - grid->laplace(mu) );
  //   grid->unlockBC();

  //   // Solve for v*
  //   grid->lockBC(v); 
  //   v->solve(grid->ddt(rho) + grid->div(vel, rho) - grid->laplace(mu) ); 
  //   grid->unlockBC();     

  //   // Adapt grid using vorticity (0.9 sigma up/down for refine/coarsen); 
  //   if (it == 1 || (it % writeInt == 0)) { 
  //     grid->solBasedAdapt(vor->data, 0.9); 
  //     grid->adapt(); 
  //   }

  //   // Get Vel*
  //   auto velstar = grid->getVel();    

  //   // Solve for pressure Poisson equation
  //   grid->lockBC(p); 
  //   p->solve(grid->laplace(1.0/rho) - grid->source(0, grid->valDiv(velstar)/dt));
  //   grid->unlockBC(); 

  //   // Correct velocities; 
  //   u->set(velstar.comp(0)-dt/rho*gp.comp(0));  // 
  //   v->set(velstar.comp(1)-dt/rho*gp.comp(1));  //

  //   // Set new time step 
  //   grid->setDt(dt); 
  //   time += grid->dt; 

  //   //Write output at intervals; 
  //   if ( ( it++ % writeInt) == 0) {
  //     grid->writeVTK(); //
  //   } 

  // }

 
  // delete(grid);
  


  return 0; 
};