void QPaintEngineEx::drawRects(const QRectF *rects, int rectCount)
{
    for (int i=0; i<rectCount; ++i) {
        const QRectF &r = rects[i];
        qreal right = r.x() + r.width();
        qreal bottom = r.y() + r.height();
        qreal pts[] = { r.x(), r.y(),
                        right, r.y(),
                        right, bottom,
                        r.x(), bottom,
                        r.x(), r.y() };
        QVectorPath vp(pts, 5, 0, QVectorPath::RectangleHint);
        draw(vp);
    }
}
bool NeuroPolicy::init(const int observation_dim, const int action_dim, double deltat, const char* fname, const char* chapter)
{
    ValueParser vp(fname, chapter==0?"Controller":chapter);

    char filename[255];
    if (vp.get("filename", filename, 255) < 1)
        EOUT("No filename specified.");
    _net = new Net();
    _net->load_net(filename);

    _adim = action_dim;
    _sdim = observation_dim;

    return true;
}
Exemple #3
0
RS_Vector RS_Circle::getNearestPointOnEntity(const RS_Vector& coord,
        bool /*onEntity*/, double* dist, RS_Entity** entity)const {

    if (entity!=NULL) {
        *entity = const_cast<RS_Circle*>(this);
    }
    RS_Vector vp(coord - data.center);
    double d(vp.magnitude());
    if( d < RS_TOLERANCE ) return RS_Vector(false);
    vp =data.center+vp*(data.radius/d);
    if(dist!=NULL){
        *dist=coord.distanceTo(vp);
    }
    return vp;
}
/**
  * this function creates offset
  *@coord, position indicates the direction of offset
  *@distance, distance of offset
  * return true, if success, otherwise, false
  *
  *Author: Dongxu Li
  */
bool RS_Line::offset(const RS_Vector& coord, const double& distance) {
	RS_Vector direction{getEndpoint()-getStartpoint()};
    double ds(direction.magnitude());
    if(ds< RS_TOLERANCE) return false;
    direction /= ds;
    RS_Vector vp(coord-getStartpoint());
//    RS_Vector vp1(getStartpoint() + direction*(RS_Vector::dotP(direction,vp))); //projection
    direction.set(-direction.y,direction.x); //rotate pi/2
    if(RS_Vector::dotP(direction,vp)<0.) {
        direction *= -1.;
    }
    direction*=distance;
    move(direction);
    return true;
}
Exemple #5
0
/**
  * find the closest grid point
  *@return the closest grid to given point
  *@coord: the given point
  */
RS_Vector RS_Grid::snapGrid(const RS_Vector& coord) const {
    if( cellV.x<RS_TOLERANCE || cellV.y<RS_TOLERANCE) return coord;
    RS_Vector vp(coord-baseGrid);
    if(isometric){
        //use remainder instead of fmod to locate the left-bottom corner for both positive and negative displacement
        RS_Vector vp1( vp-RS_Vector( remainder(vp.x-0.5*cellV.x,cellV.x)+0.5*cellV.x, remainder(vp.y-0.5*cellV.y,cellV.y)+0.5*cellV.y));
        RS_VectorSolutions sol(vp1,vp1+cellV,vp1+cellV*0.5);
        sol.push_back(vp1+RS_Vector(cellV.x,0.));
        sol.push_back(vp1+RS_Vector(0.,cellV.y));
        vp1=sol.getClosest(vp);
        return baseGrid+vp1;

    }else{
        return baseGrid+vp-RS_Vector(remainder(vp.x,cellV.x),remainder(vp.y,cellV.y));
    }
}
void QPaintEngineEx::drawRects(const QRect *rects, int rectCount)
{
    for (int i=0; i<rectCount; ++i) {
        const QRect &r = rects[i];
        // ### Is there a one off here?
        qreal right = r.x() + r.width();
        qreal bottom = r.y() + r.height();
        qreal pts[] = { qreal(r.x()), qreal(r.y()),
                        right, qreal(r.y()),
                        right, bottom,
                        qreal(r.x()), bottom,
                        qreal(r.x()), qreal(r.y()) };
        QVectorPath vp(pts, 5, 0, QVectorPath::RectangleHint);
        draw(vp);
    }
}
Exemple #7
0
//------------------------------------------------------------------------------
void
Menu::render()
{
    hgeResourceManager * rm( Engine::rm() );
    ViewPort * vp( Engine::vp() );

    m_gui->Render();
    float cx( 0.5f * vp->screen().x );
    rm->GetSprite( "title" )->Render( cx, 60.0f );

    hgeFont * font( rm->GetFont( "menu" ) );
    font->SetColor( 0xFFFFFFFF );
    font->printf( cx, 110.0f, HGETEXT_CENTER, "A RocketHands Experiment by Lloyd Kranzky" );
    font->printf( cx, vp->screen().y - 70.0f, HGETEXT_CENTER, "Copyright (c) 2009 RocketHands Pty. Ltd.  All rights reserved." );
    font->printf( cx, vp->screen().y - 40.0f, HGETEXT_CENTER, "http://rockethands.com/ProjectIce" );
}
Exemple #8
0
void ThinLens::render_scene(World& w) {
	RGBColor L;
	Ray ray;
	ViewPlane vp(w.vp);
	FreeImage_Initialise();
	FIBITMAP* bitmap = FreeImage_Allocate(vp.hres, vp.vres, 24);
	RGBQUAD color;
	int depth = 0;

	Point2D sp;
	Point2D pp;
	Point2D dp;
	Point2D lp;

	vp.s /= zoom;

	for(int r = 0; r < vp.vres; r++)
		for(int c = 0 ; c < vp.hres; c++) {
			L = black;

			for(int n = 0; n < vp.num_samples; n++) {
				sp = vp.sampler_ptr -> sample_unit_square();
				pp.x = vp.s * (c - vp.hres / 2.0 + sp.x);
				pp.y = vp.s * (r - vp.vres / 2.0 + sp.y);

				dp = sampler_ptr -> sample_unit_disk();
				lp = dp * lens_radius;

				ray.o = eye + lp.x * u + lp.y * v;
				ray.d = ray_direction(pp, lp);
				L += w.tracer_ptr -> trace_ray(ray);
			}

			L /= vp.num_samples;
			L *= exposure_time;
			w.display_pixel(r, c, L);
			color.rgbRed = (int)(L.r*255);
			color.rgbGreen = (int)(L.g*255);
			color.rgbBlue = (int)(L.b*255);
			FreeImage_SetPixelColor(bitmap, c, r, &color);
		}
	if (FreeImage_Save(FIF_PNG, bitmap, "test.png", 0))
		std::cout << "Image Successfully Saved!" << std::endl;

	FreeImage_DeInitialise();

}
void Lathe::addToTriangleBuffer(TriangleBuffer& buffer) const
	{
		assert( mShapeToExtrude && "Shape must not be null!");
		int numSegShape = mShapeToExtrude->getSegCount();
		assert(numSegShape>1 && "Shape must contain at least two points");
		int offset =0;

		buffer.rebaseOffset();
		buffer.estimateIndexCount(mNumSeg*numSegShape*6);
		buffer.estimateVertexCount((numSegShape+1)*(mNumSeg+1));

		for (int i=0;i<=mNumSeg;i++)
		{
			Real angle = i/(Real)mNumSeg*Math::TWO_PI;
			Quaternion q;
			q.FromAngleAxis((Radian)angle,Vector3::UNIT_Y);

			for (int j=0;j<=numSegShape;j++)
			{
				Vector2 v0 = mShapeToExtrude->getPoint(j);
				Vector3 vp(v0.x,v0.y,0);
				Vector2 vp2direction = mShapeToExtrude->getAvgDirection(j);
				Vector2 vp2normal = vp2direction.perpendicular();
				Vector3 normal(vp2normal.x, vp2normal.y, 0);
				normal.normalise();
				if (mShapeToExtrude->getOutSide() == SIDE_LEFT)
				{
					normal = -normal;
				}

				addPoint(buffer, q*vp,
								 q*normal,
								 Vector2(i/(Real)mNumSeg, j/(Real)numSegShape));

				if (j <numSegShape && i <mNumSeg)
				{
					buffer.index(offset + numSegShape + 2);
					buffer.index(offset);
					buffer.index(offset + numSegShape + 1);
					buffer.index(offset + numSegShape + 2);
					buffer.index(offset + 1);
					buffer.index(offset);
				}
				offset ++;
			}
		}
	}
// ######################################################################
void SuperPixelRoadSegmenter::updateImage(Image<PixRGB<byte> >ima)
{
    if(!ima.initialized()) return;
    itsDebugWinCounter = 0;
    LINFO("Image width %d height %d",ima.getWidth(),ima.getHeight());
    Timer timer(1000000);
    float time,total_time;
    timer.reset();
    time = timer.get()/1000.0F;
    total_time = timer.get()/1000.0F;
    //Dims dims = ima.getDims();
    int w = ima.getWidth();
    int h = ima.getHeight();

    //LINFO("create image");
    //itsImage(Image<PixRGB<byte> > (w,h,ZEROS));

    //LINFO("Creat debug image");
    //itsImage = ima;
    //debugWin(ima,"Image Input");
    //itsImage = Image<PixRGB<byte> > (ima.getDims(),ZEROS);


    itsFrameID++; // don't increment itsProcessedFrameID until we compute all features
//	itsSpf.predictState();
//	itsSpf.predictObservation(itszNoise);

    //LINFO("rescale image");
    //80x60
    Image<PixRGB<byte> > downSizeImg  = rescale(ima,80,60);

    //LINFO("scale image back");
    itsSuperPixelMap = rescale(getSuperPixel(downSizeImg), w,h);
    LINFO("Segment time: %f", timer.get()/1000.0F - time);
    time = timer.get()/1000.0F;
    itsRoadFindingMap = findRoad();
    LINFO("Find Road time: %f", timer.get()/1000.0F - time);
    LINFO(">>>>Total time: %f", timer.get()/1000.0F - total_time);
    itsProcessedFrameID ++;

    Point2D<int> vp(160,120);
    Point2D<int> lp(150,230);
    Point2D<int> rp(170,230);

    PixRGB<byte> rc = getFanAreaColor(vp,lp,rp,ima);
    itsFanImg = drawFanArea(vp,lp,rp,ima,rc);
}
void SamtoolsMpileupTask::run() {
    ProcessRun samtools = ExternalToolSupportUtils::prepareProcess("SAMtools", settings.getMpiliupArgs(), "", QStringList(), stateInfo, getListener(0));
    CHECK_OP(stateInfo, );
    QScopedPointer<QProcess> sp(samtools.process);
    ExternalToolLogParser sLogParser;
    ExternalToolRunTaskHelper sHelper(samtools.process, &sLogParser, stateInfo);
    setListenerForHelper(&sHelper, 0);

    ProcessRun bcftools = ExternalToolSupportUtils::prepareProcess("BCFtools", settings.getBcfViewArgs(), "", QStringList(), stateInfo, getListener(1));
    CHECK_OP(stateInfo, );
    QScopedPointer<QProcess> bp(bcftools.process);
    ExternalToolLogParser bLogParser;
    ExternalToolRunTaskHelper bHelper(bcftools.process, &bLogParser, stateInfo);
    setListenerForHelper(&bHelper, 1);

    ProcessRun vcfutils = ExternalToolSupportUtils::prepareProcess("vcfutils", settings.getVarFilterArgs(), "", QStringList(), stateInfo, getListener(2));
    CHECK_OP(stateInfo, );
    QScopedPointer<QProcess> vp(vcfutils.process);
    ExternalToolLogParser vLogParser;
    ExternalToolRunTaskHelper vHelper(vcfutils.process, &vLogParser, stateInfo);
    setListenerForHelper(&vHelper, 2);

    samtools.process->setStandardOutputProcess(bcftools.process);
    bcftools.process->setStandardOutputProcess(vcfutils.process);
    vcfutils.process->setStandardOutputFile(settings.variationsUrl);

    start(samtools, "SAMtools");
    CHECK_OP(stateInfo, );
    start(bcftools, "BCFtools");
    CHECK_OP(stateInfo, );
    start(vcfutils, "vcfutils");
    CHECK_OP(stateInfo, );

    while(!vcfutils.process->waitForFinished(1000)){
        if (isCanceled()) {
            CmdlineTaskRunner::killProcessTree(samtools.process);
            CmdlineTaskRunner::killProcessTree(bcftools.process);
            CmdlineTaskRunner::killProcessTree(vcfutils.process);
            return;
        }
    }

    checkExitCode(vcfutils.process, "vcfutils");
    checkExitCode(bcftools.process, "BCFtools");
    checkExitCode(samtools.process, "SAMtools");
}
// Point list
// +0      int         id
// +4      int         size
// +8      int         n_verts
// +12     int         n_norms
// +16     int         offset from start of chunk to vertex data
// +20     n_verts*char    norm_counts
// +offset             vertex data. Each vertex n is a point followed by norm_counts[n] normals.     
void model_collide_defpoints(ubyte * p)
{
	int n;
	int nverts = w(p+8);	
	int offset = w(p+16);	

	ubyte * normcount = p+20;
	vec3d *src = vp(p+offset);
	
	Assert( Mc_point_list != NULL );

	for (n=0; n<nverts; n++ ) {
		Mc_point_list[n] = src;

		src += normcount[n]+1;
	} 
}
Exemple #13
0
void
Canvas::DrawPolygon(const RasterPoint *points, unsigned num_points)
{
  if (brush.IsHollow() && !pen.IsDefined())
    return;

#ifdef USE_GLSL
  OpenGL::solid_shader->Use();
#endif

  ScopeVertexPointer vp(points);

  if (!brush.IsHollow() && num_points >= 3) {
    brush.Bind();
    
    std::unique_ptr<const GLBlend> blend; 
    if(!brush.IsOpaque()) {
      blend = std::make_unique<const GLBlend>(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }
    
    static AllocatedArray<GLushort> triangle_buffer;
    unsigned idx_count = PolygonToTriangles(points, num_points,
                                            triangle_buffer);
    if (idx_count > 0)
      glDrawElements(GL_TRIANGLES, idx_count, GL_UNSIGNED_SHORT,
                     triangle_buffer.begin());
  }

  if (IsPenOverBrush()) {
    pen.Bind();

    if (pen.GetWidth() <= 2) {
      glDrawArrays(GL_LINE_LOOP, 0, num_points);
    } else {
      unsigned vertices = LineToTriangles(points, num_points, vertex_buffer,
                                          pen.GetWidth(), true);
      if (vertices > 0) {
        vp.Update(vertex_buffer.begin());
        glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices);
      }
    }

    pen.Unbind();
  }
}
bool JoystickController::read_options(const char* fname, const char* chapter)
{
  ValueParser vp(fname,chapter);
  char paramstr[1024];
  int nread;

  if ((nread=vp.get("xwork", paramstr, 1024)) > 0) {
    if (!xwork.parseStr(paramstr , odim)) {
      EOUT("in parsing xwork!");
      return false;
    }
  }

  int jd=0;
  char jdbuf[200];
  vp.get("jdev" , jd);
  sprintf(jdbuf,"/dev/input/js%d",jd);
  joydev = jdbuf;

  vp.get("rdev" , jd);
  sprintf(jdbuf,"/dev/input/event%d",jd);
  rumbdev = jdbuf;

  if ((nread=vp.get("fail_controller_name", paramstr, 1024)) > 0) {
    fail_controller_name = paramstr;
  }
  if ((nread=vp.get("fail_controller_fname", paramstr, 1024)) > 0) {
    fail_controller_fname = paramstr;
  }

  for (int i=0; i<MAX_CONTROLLER; i++) {
    char strbuf[1024];

    sprintf(strbuf , "aux_controller_name%d" , i+1);
    if ((nread=vp.get(strbuf, paramstr, 1024)) > 0) {
      aux_controller_name[i] = paramstr;
    }
    sprintf(strbuf , "aux_controller_fname%d" , i+1);
    if ((nread=vp.get(strbuf, paramstr, 1024)) > 0) {
      aux_controller_fname[i] = paramstr;
    }
  }

  return true;
}
Exemple #15
0
inline bool OmniApp::onFrame() {
	FPS::onFrame();

	while(oscRecv().recv()) {}
	
	nav().step();
	
	onAnimate(dt);
	
	Viewport vp(width(), height());
	
	if (bOmniEnable) {
		mOmni.onFrame(*this, lens(), nav(), vp);
	} else {
		mOmni.onFrameFront(*this, lens(), nav(), vp);
	}
	return true;
}
Exemple #16
0
RS_Vector RS_Circle::getNearestPointOnEntity(const RS_Vector& coord,
        bool /*onEntity*/, double* dist, RS_Entity** entity)const {

	if (entity) {
        *entity = const_cast<RS_Circle*>(this);
    }
	RS_Vector vp(coord - data.center);
    double d(vp.magnitude());
    if( d < RS_TOLERANCE ) return RS_Vector(false);
	vp =data.center+vp*(data.radius/d);
//    RS_DEBUG->print(RS_Debug::D_ERROR, "circle(%g, %g), r=%g: distance to point (%g, %g)\n",data.center.x,data.center.y,coord.x,coord.y);

	if(dist){
        *dist=coord.distanceTo(vp);
//        RS_DEBUG->print(RS_Debug::D_ERROR, "circle(%g, %g), r=%g: distance to point (%g, %g)=%g\n",data.center.x,data.center.y,coord.x,coord.y,*dist);
    }
    return vp;
}
inline bool OmniStereoGraphicsRenderer::onFrame() {
  FPS::onFrame();

  // if running on a laptop?
  //
  nav().step();

  onAnimate(dt);

  Viewport vp(width(), height());

  if (bOmniEnable) {
    mOmni.onFrame(*this, lens(), pose, vp);
  } else {
    mOmni.onFrameFront(*this, lens(), pose, vp);
  }
  return true;
}
Exemple #18
0
    unsigned int
    add_arc_as_single_cubic(int max_recursion, Builder *B, float tol,
                            vec2 from_pt, vec2 to_pt, float angle)
    {
      vec2 vp(to_pt - from_pt);
      vec2 jp(-vp.y(), vp.x());
      float d(t_tan(angle * 0.25f));
      vec2 c0, c1;

      vp *= ((1.0f - d * d) / 3.0f);
      jp *= (2.0f * d / 3.0f);
      c0 = from_pt + vp - jp;
      c1 = to_pt - vp - jp;

      return add_cubic_adaptive(max_recursion, B,
                                vecN<vec2, 4>(from_pt, c0, c1, to_pt),
                                tol);
    }
Exemple #19
0
vector<ProgramBinary> Program::get_Binaries() {
	vector<ProgramBinary> r;

	vector<Device> devs = Devices;
	if (cl_uint n = devs.size()) {
		vector<size_t> vSize(n);
		ClCheck(::clGetProgramInfo(Handle(), CL_PROGRAM_BINARY_SIZES, sizeof(size_t)*n, &vSize[0], 0));
		r.resize(n);
		vector<void*> vp(n);
		for (int i=0; i<n; ++i) {
			r[i].Device = devs[i];
			r[i].Binary.Size = vSize[i];
			vp[i] = r[i].Binary.data();
		}
		ClCheck(::clGetProgramInfo(Handle(), CL_PROGRAM_BINARIES,	sizeof(void*)*n, &vp[0], 0));
	}
	return r;
}
void QQmlVMEMetaObject::writeProperty(int id, const QVariant &value)
{
    if (id >= firstVarPropertyIndex) {
        if (!ensureVarPropertiesAllocated())
            return;

        QV4::Scope scope(varProperties.engine());

        // Importantly, if the current value is a scarce resource, we need to ensure that it
        // gets automatically released by the engine if no other references to it exist.
        QV4::ScopedObject vp(scope, varProperties.value());
        QV4::Scoped<QV4::VariantObject> oldv(scope, vp->getIndexed(id - firstVarPropertyIndex));
        if (!!oldv)
            oldv->removeVmePropertyReference();

        // And, if the new value is a scarce resource, we need to ensure that it does not get
        // automatically released by the engine until no other references to it exist.
        QV4::ScopedValue newv(scope, QQmlEnginePrivate::get(ctxt->engine)->v8engine()->fromVariant(value));
        QV4::Scoped<QV4::VariantObject> v(scope, newv);
        if (!!v)
            v->addVmePropertyReference();

        // Write the value and emit change signal as appropriate.
        QVariant currentValue = readPropertyAsVariant(id);
        vp->putIndexed(id - firstVarPropertyIndex, newv);
        if ((currentValue.userType() != value.userType() || currentValue != value))
            activate(object, methodOffset() + id, 0);
    } else {
        bool needActivate = false;
        if (value.userType() == QMetaType::QObjectStar) {
            QObject *o = *(QObject **)value.data();
            needActivate = (data[id].dataType() != QMetaType::QObjectStar || data[id].asQObject() != o);
            data[id].setValue(o, this, id);
        } else {
            needActivate = (data[id].dataType() != qMetaTypeId<QVariant>() ||
                            data[id].asQVariant().userType() != value.userType() ||
                            data[id].asQVariant() != value);
            data[id].setValue(value);
        }

        if (needActivate)
            activate(object, methodOffset() + id, 0);
    }
}
void QQmlVMEMetaObject::writeVarProperty(int id, const QV4::ValueRef value)
{
    Q_ASSERT(id >= firstVarPropertyIndex);
    if (!ensureVarPropertiesAllocated())
        return;

    QV4::Scope scope(varProperties.engine());
    // Importantly, if the current value is a scarce resource, we need to ensure that it
    // gets automatically released by the engine if no other references to it exist.
    QV4::ScopedObject vp(scope, varProperties.value());
    QV4::Scoped<QV4::VariantObject> oldv(scope, vp->getIndexed(id - firstVarPropertyIndex));
    if (!!oldv)
        oldv->removeVmePropertyReference();

    QObject *valueObject = 0;
    QQmlVMEVariantQObjectPtr *guard = getQObjectGuardForProperty(id);

    QV4::ScopedObject o(scope, value);
    if (o) {
        // And, if the new value is a scarce resource, we need to ensure that it does not get
        // automatically released by the engine until no other references to it exist.
        if (QV4::VariantObject *v = o->as<QV4::VariantObject>()) {
            v->addVmePropertyReference();
        } else if (QV4::QObjectWrapper *wrapper = o->as<QV4::QObjectWrapper>()) {
            // We need to track this QObject to signal its deletion
            valueObject = wrapper->object();

            // Do we already have a QObject guard for this property?
            if (valueObject && !guard) {
                guard = new QQmlVMEVariantQObjectPtr(true);
                varObjectGuards.append(guard);
            }
        }
    }

    if (guard) {
        guard->setGuardedValue(valueObject, this, id);
    }

    // Write the value and emit change signal as appropriate.
    vp->putIndexed(id - firstVarPropertyIndex, value);
    activate(object, methodOffset() + id, 0);
}
Exemple #22
0
float SCgBus::dotPos(const QPointF &point) const
{
    // get sector with minimal distance to point
    // and calculates relative dot position on it

    qreal minDist = -1.f;
    qreal result = 0.f;
    QPointF np = mapFromScene(point);

    for (int i = 1; i < mPoints.size(); i++)
    {
        QPointF p1 = mPoints[i - 1];
        QPointF p2 = mPoints[i];

        QVector2D v(p2 - p1);
        QVector2D vp(np - p1);

        QVector2D vn = v.normalized();
        //vp.normalize();

        // calculate point on line
        QVector2D p = QVector2D(p1) + vn * QVector2D::dotProduct(vn, vp);
        if(v.length() == 0)
            return result;
        qreal dotPos = QVector2D(p.toPointF() - p1).length() / v.length();

        if (dotPos < 0.f || dotPos > 1.f)
            continue;

        // we doesn't need to get real length, because we need minimum
        // so we get squared length to make that procedure faster
        qreal d = QVector2D(np - p.toPointF()).lengthSquared();

        // compare with minimum distance
        if (minDist < 0.f || minDist > d)
        {
            minDist = d;
            result = (i - 1) + dotPos;
        }
    }

    return result;
}
Exemple #23
0
void Fisheye::render_scene(World& w) {
	RGBColor L;
	ViewPlane vp(w.vp);
	FreeImage_Initialise();
	FIBITMAP* bitmap = FreeImage_Allocate(vp.hres, vp.vres, 24);
	RGBQUAD color;
	int hres = vp.hres;
	int vres = vp.vres;
	float s = vp.s;
	Ray ray;
	int depth = 0;
	Point2D sp;
	Point2D pp;
	float r_squared;

	ray.o  = eye;

	for(int r = 0; r < vres; r++)
		for(int c = 0; c < hres; c++) {
			L = black;

			for(int j = 0; j < vp.num_samples; j++) {
				sp = vp.sampler_ptr -> sample_unit_square();
				pp.x = s * (c - hres / 2.0 + sp.x);
				pp.y = s * (r - vres / 2.0 + sp.y);
				ray.d = ray_direction(pp, hres, vres, s, r_squared);

				if(r_squared <= 1.0)
					L += w.tracer_ptr -> trace_ray(ray);
			}

			L /= vp.num_samples;
			L *= exposure_time;
			w.display_pixel(r, c, L);
			color.rgbRed = (int)(L.r*255);
			color.rgbGreen = (int)(L.g*255);
			color.rgbBlue = (int)(L.b*255);
			FreeImage_SetPixelColor(bitmap, c, r, &color);
		}
	if (FreeImage_Save(FIF_PNG, bitmap, "test.png", 0))
		std::cout << "Image Successfully Saved!" << std::endl;
	FreeImage_DeInitialise();
}
Exemple #24
0
/**
  *create circle inscribled in a triangle
  *
  *Author: Dongxu Li
  */
bool RS_Circle::createInscribe(const RS_Vector& coord, const std::vector<RS_Line*>& lines){
    if(lines.size()<3) return false;
	std::vector<RS_Line*> tri(lines);
    RS_VectorSolutions sol=RS_Information::getIntersectionLineLine(tri[0],tri[1]);
    if(sol.getNumber() == 0 ) {//move parallel to opposite
        std::swap(tri[1],tri[2]);
        sol=RS_Information::getIntersectionLineLine(tri[0],tri[1]);
    }
    if(sol.getNumber() == 0 ) return false;
    RS_Vector vp0(sol.get(0));
    sol=RS_Information::getIntersectionLineLine(tri[2],tri[1]);
    if(sol.getNumber() == 0 ) return false;
    RS_Vector vp1(sol.get(0));
    RS_Vector dvp(vp1-vp0);
    double a(dvp.squared());
    if( a< RS_TOLERANCE2) return false; //three lines share a common intersecting point
    RS_Vector vp(coord - vp0);
    vp -= dvp*(RS_Vector::dotP(dvp,vp)/a); //normal component
    RS_Vector vl0(tri[0]->getEndpoint() - tri[0]->getStartpoint());
    a=dvp.angle();
    double angle0(0.5*(vl0.angle() + a));
    if( RS_Vector::dotP(vp,vl0) <0.) {
        angle0 += 0.5*M_PI;
    }

    RS_Line line0(vp0, vp0+RS_Vector(angle0));//first bisecting line
    vl0=(tri[2]->getEndpoint() - tri[2]->getStartpoint());
    angle0=0.5*(vl0.angle() + a+M_PI);
    if( RS_Vector::dotP(vp,vl0) <0.) {
        angle0 += 0.5*M_PI;
    }
    RS_Line line1(vp1, vp1+RS_Vector(angle0));//second bisection line
    sol=RS_Information::getIntersectionLineLine(&line0,&line1);
    if(sol.getNumber() == 0 ) return false;

	bool ret=createFromCR(sol.get(0),tri[1]->getDistanceToPoint(sol.get(0)));
	if(!ret) return false;
	for(auto p: lines){
		if(! p->isTangent(data)) return false;
	}
	return true;
}
Exemple #25
0
void ObjectViewer::transform_model( bool keep_rotation )
{
    float dx = m_mouse.x - m_mouse.press.x;
    float dy = m_mouse.y - m_mouse.press.y;
    if ( dx*dx + dy*dy < 0.05f ) return;
    float ratio = float(m_width)/float(m_height);
    glm::mat4 projection = glm::perspective( m_camera.fov, ratio, 0.1f, 100.0f );
    //glm::mat4 projection(1.f);
    glm::mat4 view = glm::lookAt( glm::vec3(0,0,5), glm::vec3(0,0,0), glm::vec3(0,1,0) );
    glm::vec4 vp( 0.f, 0.f, m_width, m_height );
    //
    glm::vec3 mpos0( m_mouse.press.x, m_mouse.press.y, 0.f );
    auto pos0 = glm::unProject( mpos0, view, projection, vp );
    //std::cerr << "o: " << m_mouse.press.x << ", " << m_mouse.press.y << std::endl;
    //std::cerr << "ow: " << pos0.x << " " << pos0.y << " " << pos0.z << std::endl;
    //
    glm::vec3 mpos1( m_mouse.x, m_mouse.y, 0.f );
    auto pos1 = glm::unProject( mpos1, view, projection, vp );
    //std::cerr << "d: " << m_mouse.x << ", " << m_mouse.y << std::endl;
    //std::cerr << "dw: " << pos1.x << " " << pos1.y << " " << pos1.z << std::endl;
    //
    auto v0 = glm::normalize(pos0);
    auto v1 = glm::normalize(pos1);
    auto ref = glm::cross( v0, v1 );
    auto angle = glm::orientedAngle( v0, v1, ref );
    //auto rotation = glm::rotate( glm::mat4(1.0f), 180.f*angle/glm::pi<float>(), ref);
    auto rotation = glm::rotate( glm::mat4(1.0f), 100.f*angle, ref);
    //auto rotation = glm::rotate( glm::mat4(1.0f), glm::pi<float>()/4.f, ref);
    /*
    std::cerr << "angle: " << angle << " graus:" << 180.f*angle/glm::pi<float>()
        << " dot:" << std::acos( glm::dot(v0, v1) ) << " pi:" << glm::pi<float>()
        << " dot(v0,v1):" << glm::dot(v0, v1) << " dot(v1,v1):" << glm::dot(v1,v1)
        << " " << std::endl;
       */
    if ( !keep_rotation ) {
        update_model_view_projection(rotation);
    }
    else {
        m_rotation = rotation * m_rotation;
        update_model_view_projection();
    }
}
/**
 * create a tangent line which is orthogonal to the given RS_Line(normal)
 * @coord, the tangent line closest to this point
 * @normal, the line orthogonal to the tangent line
 * @circle, arc/circle/ellipse for tangent line
 *
 * Author: Dongxu Li
 */
RS_Line* RS_Creation::createLineOrthTan(const RS_Vector& coord,
                                        RS_Line* normal,
                                        RS_Entity* circle) {
    RS_Line* ret = NULL;

    // check given entities:
    if (circle==NULL||normal==NULL
            ||!coord.valid ||
            (   circle->rtti()!=RS2::EntityArc
                && circle->rtti()!=RS2::EntityCircle
                && circle->rtti()!=RS2::EntityEllipse)) {

        return ret;
    }
    //if( normal->getLength()<RS_TOLERANCE) return ret;//line too short
    RS_Vector t0;

    // calculate tangent points for arcs / circles:
    t0= circle->getNearestOrthTan(coord,*normal,false);
    if(!t0.valid) return ret;
    RS_Vector vp(normal->getStartpoint());
    RS_Vector direction(normal->getEndpoint() - vp);
    RS_Vector vpt(t0 - vp);
    double a=direction.squared();
    if( a <RS_TOLERANCE*RS_TOLERANCE) {
        return NULL;//undefined direction
    } else {
        //find projection on the normal line
        vp += direction*( RS_Vector::dotP(direction,vpt)/a);
        if( fabs(vp.x - t0.x) <=RS_TOLERANCE || fabs(vp.y-t0.y)<=RS_TOLERANCE) {
            //t0 already on the given line, need to extend in the normal direction
            vp += RS_Vector(-direction.y,direction.x);
        }
    }
    if (document!=NULL && handleUndo) {
        document->startUndoCycle();
    }
    ret = new RS_Line(container, RS_LineData(vp,t0));
    ret->setLayerToActive();
    ret->setPenToActive();
    return ret;
}
Exemple #27
0
void CMatrix44f::Rotate(float rad, const float3& axis)
{
	const float sr = math::sin(rad);
	const float cr = math::cos(rad);

	for(int a=0;a<3;++a){
		float3 v(m[a*4],m[a*4+1],m[a*4+2]);

		float3 va(axis*v.dot(axis));
		float3 vp(v-va);
		float3 vp2(axis.cross(vp));

		float3 vpnew(vp*cr+vp2*sr);
		float3 vnew(va+vpnew);

		m[a*4]     = vnew.x;
		m[a*4 + 1] = vnew.y;
		m[a*4 + 2] = vnew.z;
	}
}
Exemple #28
0
int main(void) {
	static v_code insn[1000]; 	/* Memory to hold code in. */

        /* Test jump and link instruction */
        v_lambda("jump-and-link", "", 0, V_NLEAF, insn, sizeof insn);
        {
                static v_code *linked_addr;
                v_reg_type rdp, rr;
                v_label_type l;

		/* Allocate two registers persistent accross procedure calls. */
                v_getreg(&rdp, V_P, V_VAR);
		/* Allocate register to hold return pointer */
                v_getreg(&rr, V_P, V_VAR);

                l = v_genlabel(); 	  /* Allocate label */
                v_dlabel(&linked_addr, l); /* mark memory to hold target address */
                v_setp(rdp, &linked_addr); /* Load address */
                v_ldpi(rdp, rdp, 0);

                v_scallv((v_vptr)printf, "%P", "Jumping!\n");
                v_jalp(rr, rdp); 	   /* Jump to it. */

                v_scallv((v_vptr)printf, "%P", "Returning!\n");
                v_retv();		/* Done */

                v_label(l);
                        v_scallv((v_vptr)printf, "%P", "Jumping back!\n");
                        v_jp(rr);	/* Jump back to caller. */
        }
        v_end(0).v();
#if 0
{
	v_vptr vp = v_end(0).v;
	v_dump(vp);
	vp();
}
#endif

	return 0;
}
int model_collide_parse_bsp_defpoints(ubyte * p)
{
	int n;
	int nverts = w(p+8);	
	int offset = w(p+16);	

	ubyte * normcount = p+20;
	vec3d *src = vp(p+offset);

	model_collide_allocate_point_list(nverts);

	Assert( Mc_point_list != NULL );

	for (n=0; n<nverts; n++ ) {
		Mc_point_list[n] = src;

		src += normcount[n]+1;
	} 

	return nverts;
}
Exemple #30
0
void contour3d(Contour* c){
  int i,j,*k;
  vecp v;
  matp m;
  if (c->initialized==0){
    c->tva=malloc((c->vaakt+1)*sizeof(vec));
    c->na=malloc((c->polakt+1)*sizeof(vec));
    c->sp=malloc((c->polakt+1)*sizeof(vec));
    c->points=malloc((c->polakt+1)*sizeof(DPoint));    
    c->Garray=malloc((c->polakt+1)*sizeof(Gobject));
    for (i=0;i<=c->polakt;i++) {
      c->Garray[i].na=c->na;
      c->Garray[i].tva=c->tva;
      c->Garray[i].poswc=(vecp) &c->sp[i]; /* compiler distinguishes between
                                              vec* and vecp */
      c->Garray[i].points=c->points;
      c->Garray[i].polygons=&c->pol[i*6];
      c->Garray[i].drawstruct=drawtrianglelight;
      j=c->pol[i*6];
      veq(c->na[i],vnorm(vp(vdiff(c->va[j+4],c->va[j+3]),vdiff(c->va[j+5],c->va[j+3]))));
    }
    c->initialized=1;
  }
  /* Transformation, die jedes Mal durchlaufen wird. */
  meq(c->mc2wcmn,getmc2wcmn());
  meq(c->mc2wcm,getmc2wcm());
  veq(c->mc2wcv,getmc2wcv());
  m=c->mc2wcm;
  v=c->mc2wcv;
  for (i=0;i<=c->vaakt;i++) {
    veq(c->tva[i],vsum(matvecmul(m,c->va[i]),v));
    wc2dc(&c->points[i].x,&c->points[i].y,c->tva[i]);
  }
  for (i=0;i<=c->polakt;i++){ /* Schwerpunkt in Weltkoordinaten */
    k=&c->pol[i*6+3];
    veq(c->sp[i],sm(0.33333,
		    vsum(vsum(c->tva[*k],c->tva[*(k+1)]),c->tva[*(k+2)])));
    insertGobject(&c->Garray[i]);
  }
}