/*Function of the 1th (radial) momentum component differential equation for the geodesics.
${p1}^{dot} = f1(x^{\alpha},p^{\alpha})$.*/
mydbl geodesic_equation_r(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r)
{
  double t = (double)(1.0*x0/C);
  mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);
  mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);
  mydbl f = - (der_potential(r)*p0*p0)/(a*a*C*C*(1.0 - 2.0*potential(r)/(C*C))) - (2.0*adot*p0*pr)/(C*a) + (der_potential(r)/(C*C))*(pr*pr)/(1.0 - 2.0*potential(r)/(C*C));
  return f;
}
Beispiel #2
0
    std::vector<Volatility> SabrVolSurface::volatilitySpreads(const Date& d) const {

        Size nOptionsTimes = optionTimes_.size();
        Size nAtmRateSpreads = atmRateSpreads_.size();
        std::vector<Volatility> interpolatedVols(nAtmRateSpreads);

        std::vector<Volatility> vols(nOptionsTimes); // the volspread at a given strike
        for (Size i=0; i<nAtmRateSpreads; ++i) {
            for (Size j=0; j<nOptionsTimes; ++j) {
                vols[j] = (**volSpreads_[j][i]).value();
            }
            LinearInterpolation interpolator(optionTimes_.begin(), optionTimes_.end(),
                                             vols.begin());
            interpolatedVols[i] = interpolator(timeFromReference(d),true);
        }
        return interpolatedVols;
    }
Beispiel #3
0
bool THRawBitmap::_checkScaled(THRenderTarget* pCanvas, SDL_Rect& rcDest)
{
    float fFactor;
    if(!pCanvas->shouldScaleBitmaps(&fFactor))
        return false;
    int iScaledWidth = (int)((float)m_pBitmap->w * fFactor);
    if(!m_pCachedScaledBitmap || m_pCachedScaledBitmap->w != iScaledWidth)
    {
        SDL_FreeSurface(m_pCachedScaledBitmap);
        Uint32 iRMask, iGMask, iBMask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
        iRMask = 0xff000000;
        iGMask = 0x00ff0000;
        iBMask = 0x0000ff00;
#else
        iRMask = 0x000000ff;
        iGMask = 0x0000ff00;
        iBMask = 0x00ff0000;
#endif

        m_pCachedScaledBitmap = SDL_CreateRGBSurface(SDL_SWSURFACE, iScaledWidth, (int)((float)m_pBitmap->h * fFactor), 24, iRMask, iGMask, iBMask, 0);
        SDL_LockSurface(m_pCachedScaledBitmap);
        SDL_LockSurface(m_pBitmap);

        typedef agg::pixfmt_rgb24_pre pixfmt_pre_t;
        typedef agg::renderer_base<pixfmt_pre_t> renbase_pre_t;
        typedef image_accessor_clip_rgb24_pal8<pixfmt_pre_t> imgsrc_t;
        typedef agg::span_interpolator_linear<> interpolator_t;
        typedef agg::span_image_filter_rgb_2x2<imgsrc_t, interpolator_t> span_gen_type;
        agg::scanline_p8 sl;
        agg::span_allocator<pixfmt_pre_t::color_type> sa;
        agg::image_filter<agg::image_filter_bilinear> filter;
        agg::trans_affine_scaling img_mtx(1.0 / fFactor);
        agg::rendering_buffer rbuf_src(m_pData, m_pBitmap->w, m_pBitmap->h, m_pBitmap->pitch);
        imgsrc_t img_src(rbuf_src, *m_pPalette, agg::rgba(0.0, 0.0, 0.0));
        interpolator_t interpolator(img_mtx);
        span_gen_type sg(img_src, interpolator, filter);
        agg::rendering_buffer rbuf(reinterpret_cast<unsigned char*>(m_pCachedScaledBitmap->pixels), m_pCachedScaledBitmap->w, m_pCachedScaledBitmap->h, m_pCachedScaledBitmap->pitch);
        pixfmt_pre_t pixf_pre(rbuf);
        renbase_pre_t rbase_pre(pixf_pre);
        rasterizer_scanline_rect ras(0, 0, rbuf.width(), rbuf.height());
        rbase_pre.clear(agg::rgba(1.0,0,0,0));
        agg::render_scanlines_aa(ras, sl, rbase_pre, sa, sg);

        SDL_UnlockSurface(m_pBitmap);
        SDL_UnlockSurface(m_pCachedScaledBitmap);
    }
    rcDest.x = (Sint16)((float)rcDest.x * fFactor);
    rcDest.y = (Sint16)((float)rcDest.y * fFactor);
    return true;
}
Beispiel #4
0
int agg2RenderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj * style)
{
  AGG2Renderer *r = AGG_RENDERER(img);
  rasterBufferObj *pixmap = symbol->pixmap_buffer;
  assert(pixmap->type == MS_BUFFER_BYTE_RGBA);
  rendering_buffer b(pixmap->data.rgba.pixels,pixmap->width,pixmap->height,pixmap->data.rgba.row_step);
  pixel_format pf(b);

  r->m_rasterizer_aa.reset();
  r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
  if ( (style->rotation != 0 && style->rotation != MS_PI*2.)|| style->scale != 1) {
    mapserver::trans_affine image_mtx;
    image_mtx *= mapserver::trans_affine_translation(-(pf.width()/2.),-(pf.height()/2.));
    /*agg angles are antitrigonometric*/
    image_mtx *= mapserver::trans_affine_rotation(-style->rotation);
    image_mtx *= mapserver::trans_affine_scaling(style->scale);



    image_mtx *= mapserver::trans_affine_translation(x,y);
    image_mtx.invert();
    typedef mapserver::span_interpolator_linear<> interpolator_type;
    interpolator_type interpolator(image_mtx);
    mapserver::span_allocator<color_type> sa;

    // "hardcoded" bilinear filter
    //------------------------------------------
    typedef mapserver::span_image_filter_rgba_bilinear_clip<pixel_format, interpolator_type> span_gen_type;
    span_gen_type sg(pf, mapserver::rgba(0,0,0,0), interpolator);
    mapserver::path_storage pixmap_bbox;
    int ims_2 = MS_NINT(MS_MAX(pixmap->width,pixmap->height)*style->scale*1.415)/2+1;

    pixmap_bbox.move_to(x-ims_2,y-ims_2);
    pixmap_bbox.line_to(x+ims_2,y-ims_2);
    pixmap_bbox.line_to(x+ims_2,y+ims_2);
    pixmap_bbox.line_to(x-ims_2,y+ims_2);

    r->m_rasterizer_aa.add_path(pixmap_bbox);
    mapserver::render_scanlines_aa(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_base, sa, sg);
  } else {
    //just copy the image at the correct location (we place the pixmap on
    //the nearest integer pixel to avoid blurring)
    r->m_renderer_base.blend_from(pf,0,MS_NINT(x-pixmap->width/2.),MS_NINT(y-pixmap->height/2.));
  }
  return MS_SUCCESS;
}
Beispiel #5
0
TEST(InterpolatorTests, ShouldInterpolateNumbers){
    Vector p1(-7, 5, 3);
    int p1Value = 10;

    Vector p2(3, 2, 3);
    int p2Value = 2;

    Vector p3(-2, -2, 3);
    int p3Value = -20;

    Vector interpolatedPoint(-1, 0, 3);
    Triangle3DInterpolator<double> interpolator(p1, p1Value, p2, p2Value, p3, p3Value);

    double interpolatedValue = interpolator.Interpolate(interpolatedPoint);

    EXPECT_NEAR(interpolatedValue, -9.928, 0.001);
}
Beispiel #6
0
 void render_raster_marker(agg::trans_affine const& marker_tr,
                           double opacity)
 {
     double width  = src_.width();
     double height = src_.height();
     double p[8];
     p[0] = 0;     p[1] = 0;
     p[2] = width; p[3] = 0;
     p[4] = width; p[5] = height;
     p[6] = 0;     p[7] = height;
     marker_tr.transform(&p[0], &p[1]);
     marker_tr.transform(&p[2], &p[3]);
     marker_tr.transform(&p[4], &p[5]);
     marker_tr.transform(&p[6], &p[7]);
     ras_.move_to_d(p[0],p[1]);
     ras_.line_to_d(p[2],p[3]);
     ras_.line_to_d(p[4],p[5]);
     ras_.line_to_d(p[6],p[7]);
     agg::span_allocator<color_type> sa;
     agg::image_filter_bilinear filter_kernel;
     agg::image_filter_lut filter(filter_kernel, false);
     agg::rendering_buffer marker_buf((unsigned char *)src_.getBytes(),
                                      src_.width(),
                                      src_.height(),
                                      src_.width()*4);
     agg::pixfmt_rgba32_pre pixf(marker_buf);
     typedef agg::image_accessor_clone<agg::pixfmt_rgba32_pre> img_accessor_type;
     typedef agg::span_interpolator_linear<agg::trans_affine> interpolator_type;
     typedef agg::span_image_filter_rgba_2x2<img_accessor_type,
                                             interpolator_type> span_gen_type;
     typedef agg::renderer_scanline_aa_alpha<renderer_base,
             agg::span_allocator<color_type>,
             span_gen_type> renderer_type;
     img_accessor_type ia(pixf);
     interpolator_type interpolator(agg::trans_affine(p, 0, 0, width, height) );
     span_gen_type sg(ia, interpolator, filter);
     renderer_type rp(renb_,sa, sg, unsigned(opacity*255));
     agg::render_scanlines(ras_, sl_, rp);
 }
Beispiel #7
0
bool ConfigureInterpolatorItem(const TiXmlElement *element, std::vector<unsigned int> &buffer, int width, const char * const names[], const float data[])
{
	if (!element->FirstChildElement())
		return false;

	// temporary interpolator
	InterpolatorTemplate interpolator(width);

	// start at zero time
	float time = 0.0f;
	element->QueryFloatAttribute("time", &time);

	// get time scale
	float scale = 1.0f;
	element->QueryFloatAttribute("timescale", &scale);
	if (element->QueryFloatAttribute("rate", &scale) == TIXML_SUCCESS)
		scale = 1.0f / scale;

	// process child elements
	for (const TiXmlElement *child = element->FirstChildElement(); child != NULL; child = child->NextSiblingElement())
	{
		const char *label = child->Value();
		switch (Hash(label))
		{
		case 0x0691ea25 /* "constant" */:
			{
				// TO DO: process constant interpolator
			}
			break;

		case 0xd00594c0 /* "linear" */:
			{
				// process linear interpolator
				time = ConfigureInterpolatorKeyItems(child, interpolator, time, scale, names, data);
			}
			break;

		case 0x9c265311 /* "hermite" */:
			{
				// TO DO: process hermite interpolator
			}
			break;

		case 0x6815c86c /* "key" */:
			{
				ConfigureInterpolatorKeyItem(child, interpolator, time, scale, names, data);
			}
			break;

		case 0xc7441a0f /* "step" */:
			{
				ConfigureInterpolatorKeyItem(child, interpolator, time, 0, names, data);
				float duration = 0.0f;
				if (child->QueryFloatAttribute("time", &duration) == TIXML_SUCCESS)
					time += duration * scale;
			}
			break;
		}
	}

	// if not enough keys...
	if (interpolator.mCount < 2)
	{
		// add a final key
		float *key = interpolator.AddKey(time);
		if (interpolator.mCount == 1)
		{
			memcpy(&key[1], data, interpolator.mWidth*sizeof(float));
			key = interpolator.AddKey(time);
		}
		memcpy(&key[1], interpolator.GetValues(interpolator.mCount-2), interpolator.mWidth*sizeof(float));
	}

	// push into the buffer
	buffer.push_back(interpolator.mCount);
	for (int i = 0; i < interpolator.mCount * interpolator.mStride; i++)
		buffer.push_back(*reinterpret_cast<unsigned int *>(&interpolator.mKeys[i]));
	return true;
}
    virtual void on_draw()
    {
        pixfmt            pixf(rbuf_window());
        pixfmt_pre        pixf_pre(rbuf_window());
        renderer_base     rb(pixf);
        renderer_base_pre rb_pre(pixf_pre);

        if(!m_test_flag)
        {
            rb.clear(agg::rgba(1, 1, 1));
        }

        if(m_trans_type.cur_item() == 0)
        {
            // For the affine parallelogram transformations we
            // calculate the 4-th (implicit) point of the parallelogram
            m_quad.xn(3) = m_quad.xn(0) + (m_quad.xn(2) - m_quad.xn(1));
            m_quad.yn(3) = m_quad.yn(0) + (m_quad.yn(2) - m_quad.yn(1));
        }

        if(!m_test_flag)
        {
            //--------------------------
            // Render the "quad" tool and controls
            g_rasterizer.add_path(m_quad);
            agg::render_scanlines_aa_solid(g_rasterizer, g_scanline, rb, agg::rgba(0, 0.3, 0.5, 0.6));

            //--------------------------
            agg::render_ctrl(g_rasterizer, g_scanline, rb, m_trans_type);
        }

        // Prepare the polygon to rasterize. Here we need to fill
        // the destination (transformed) polygon.
        g_rasterizer.clip_box(0, 0, width(), height());
        g_rasterizer.reset();
        g_rasterizer.move_to_d(m_quad.xn(0), m_quad.yn(0));
        g_rasterizer.line_to_d(m_quad.xn(1), m_quad.yn(1));
        g_rasterizer.line_to_d(m_quad.xn(2), m_quad.yn(2));
        g_rasterizer.line_to_d(m_quad.xn(3), m_quad.yn(3));


        typedef agg::span_allocator<color_type> span_alloc_type;
        span_alloc_type sa;
        agg::image_filter<agg::image_filter_hanning> filter;
    
        typedef agg::wrap_mode_reflect_auto_pow2 remainder_type;
        typedef agg::image_accessor_wrap<pixfmt, 
                                         remainder_type, 
                                         remainder_type> img_source_type;

        pixfmt img_pixf(rbuf_img(0));
        img_source_type img_src(img_pixf);

        enum subdiv_shift_e { subdiv_shift = 2 };
         
        switch(m_trans_type.cur_item())
        {
            case 0:
            {
                // Note that we consruct an affine matrix that transforms
                // a parallelogram to a rectangle, i.e., it's inverted.
                // It's actually the same as:
                // tr(g_x1, g_y1, g_x2, g_y2, m_triangle.polygon());
                // tr.invert();
                agg::trans_affine tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);

                // Also note that we can use the linear interpolator instead of 
                // arbitrary span_interpolator_trans. It works much faster, 
                // but the transformations must be linear and parellel.
                typedef agg::span_interpolator_linear<agg::trans_affine> interpolator_type;
                interpolator_type interpolator(tr);

                typedef span_image_filter_2x2<img_source_type,
                                              interpolator_type> span_gen_type;
                span_gen_type sg(img_src, interpolator, filter);
                agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                break;
            }

            case 1:
            {
                agg::trans_bilinear tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
                if(tr.is_valid())
                {
                    typedef agg::span_interpolator_linear<agg::trans_bilinear> interpolator_type;
                    interpolator_type interpolator(tr);

                    typedef span_image_filter_2x2<img_source_type,
                                                  interpolator_type> span_gen_type;
                    span_gen_type sg(img_src, interpolator, filter);
                    agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                }
                break;
            }

            case 2:
            {
                agg::trans_perspective tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
                if(tr.is_valid())
                {
                    typedef agg::span_interpolator_linear_subdiv<agg::trans_perspective, 8> interpolator_type;
                    interpolator_type interpolator(tr);

                    typedef span_image_filter_2x2<img_source_type,
                                                  interpolator_type> span_gen_type;
                    span_gen_type sg(img_src, interpolator, filter);
                    agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                }
                break;
            }
        }
    }
    virtual void on_draw()
    {
        if(m_gamma.value() != m_old_gamma)
        {
            m_gamma_lut.gamma(m_gamma.value());
            load_img(0, "spheres");
            pixfmt pixf(rbuf_img(0));
            pixf.apply_gamma_dir(m_gamma_lut);
            m_old_gamma = m_gamma.value();
        }

        pixfmt            pixf(rbuf_window());
        pixfmt_pre        pixf_pre(rbuf_window());
        renderer_base     rb(pixf);
        renderer_base_pre rb_pre(pixf_pre);

        renderer_solid r(rb);

        rb.clear(agg::rgba(1, 1, 1));

        if(m_trans_type.cur_item() < 2)
        {
            // For the affine parallelogram transformations we
            // calculate the 4-th (implicit) point of the parallelogram
            m_quad.xn(3) = m_quad.xn(0) + (m_quad.xn(2) - m_quad.xn(1));
            m_quad.yn(3) = m_quad.yn(0) + (m_quad.yn(2) - m_quad.yn(1));
        }

        //--------------------------
        // Render the "quad" tool and controls
        g_rasterizer.add_path(m_quad);
        r.color(agg::rgba(0, 0.3, 0.5, 0.1));
        agg::render_scanlines(g_rasterizer, g_scanline, r);

        // Prepare the polygon to rasterize. Here we need to fill
        // the destination (transformed) polygon.
        g_rasterizer.clip_box(0, 0, width(), height());
        g_rasterizer.reset();
        int b = 0;
        g_rasterizer.move_to_d(m_quad.xn(0)-b, m_quad.yn(0)-b);
        g_rasterizer.line_to_d(m_quad.xn(1)+b, m_quad.yn(1)-b);
        g_rasterizer.line_to_d(m_quad.xn(2)+b, m_quad.yn(2)+b);
        g_rasterizer.line_to_d(m_quad.xn(3)-b, m_quad.yn(3)+b);

        typedef agg::span_allocator<color_type> span_alloc_type;
        span_alloc_type sa;
        agg::image_filter_bilinear filter_kernel;
        agg::image_filter_lut filter(filter_kernel, true);

        pixfmt pixf_img(rbuf_img(0));
        typedef agg::image_accessor_clone<pixfmt> source_type;
        source_type source(pixf_img);

        start_timer();
        switch(m_trans_type.cur_item())
        {
            case 0:
            {
                agg::trans_affine tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);

                typedef agg::span_interpolator_linear<agg::trans_affine> interpolator_type;
                interpolator_type interpolator(tr);

                typedef image_filter_2x2_type<source_type, 
                                              interpolator_type> span_gen_type;
                span_gen_type sg(source, interpolator, filter);
                agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                break;
            }

            case 1:
            {
                agg::trans_affine tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);

                typedef agg::span_interpolator_linear<agg::trans_affine> interpolator_type;
                typedef image_resample_affine_type<source_type> span_gen_type;

                interpolator_type interpolator(tr);
                span_gen_type sg(source, interpolator, filter);
                sg.blur(m_blur.value());
                agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                break;
            }

            case 2:
            {
                agg::trans_perspective tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
                if(tr.is_valid())
                {
                    typedef agg::span_interpolator_linear_subdiv<agg::trans_perspective> interpolator_type;
                    interpolator_type interpolator(tr);

                    typedef image_filter_2x2_type<source_type,
                                                  interpolator_type> span_gen_type;
                    span_gen_type sg(source, interpolator, filter);
                    agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                }
                break;
            }

            case 3:
            {
                agg::trans_perspective tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
                if(tr.is_valid())
                {
                    typedef agg::span_interpolator_trans<agg::trans_perspective> interpolator_type;
                    interpolator_type interpolator(tr);

                    typedef image_filter_2x2_type<source_type, 
                                                  interpolator_type> span_gen_type;
                    span_gen_type sg(source, interpolator, filter);
                    agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                }
                break;
            }

            case 4:
            {
                typedef agg::span_interpolator_persp_lerp<> interpolator_type;
                typedef agg::span_subdiv_adaptor<interpolator_type> subdiv_adaptor_type;

                interpolator_type interpolator(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
                subdiv_adaptor_type subdiv_adaptor(interpolator);

                if(interpolator.is_valid())
                {
                    typedef image_resample_type<source_type, 
                                                subdiv_adaptor_type> span_gen_type;
                    span_gen_type sg(source, subdiv_adaptor, filter);
                    sg.blur(m_blur.value());
                    agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                }
                break;
            }

            case 5:
            {
                typedef agg::span_interpolator_persp_exact<> interpolator_type;
                typedef agg::span_subdiv_adaptor<interpolator_type> subdiv_adaptor_type;

                interpolator_type interpolator(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
                subdiv_adaptor_type subdiv_adaptor(interpolator);

                if(interpolator.is_valid())
                {
                    typedef image_resample_type<source_type, 
                                                subdiv_adaptor_type> span_gen_type;
                    span_gen_type sg(source, subdiv_adaptor, filter);
                    sg.blur(m_blur.value());
                    agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
                }
                break;
            }
        }
        double tm = elapsed_time();
        pixf.apply_gamma_inv(m_gamma_lut);

        char buf[64]; 
        agg::gsv_text t;
        t.size(10.0);

        agg::conv_stroke<agg::gsv_text> pt(t);
        pt.width(1.5);

        sprintf(buf, "%3.2f ms", tm);
        t.start_point(10.0, 70.0);
        t.text(buf);

        g_rasterizer.add_path(pt);
        r.color(agg::rgba(0,0,0));
        agg::render_scanlines(g_rasterizer, g_scanline, r);

        //--------------------------
        agg::render_ctrl(g_rasterizer, g_scanline, rb, m_trans_type);
        agg::render_ctrl(g_rasterizer, g_scanline, rb, m_gamma);
        agg::render_ctrl(g_rasterizer, g_scanline, rb, m_blur);
    }
void CellByCellUniformSampling::generate_particles( const kvs::StructuredVolumeObject* volume )
{
    CellByCellSampling::ParticleDensityMap density_map;
    density_map.setSamplingStep( m_sampling_step );
    density_map.attachCamera( m_camera );
    density_map.attachObject( volume );
    density_map.create( BaseClass::transferFunction().opacityMap() );

    const kvs::Vec3ui ncells( volume->resolution() - kvs::Vector3ui::All(1) );
    const kvs::ColorMap color_map( BaseClass::transferFunction().colorMap() );

    // Calculate number of particles.
    size_t N = 0;
    kvs::ValueArray<kvs::UInt32> nparticles( ncells.x() * ncells.y() * ncells.z() );
    KVS_OMP_PARALLEL()
    {
        kvs::TrilinearInterpolator interpolator( volume );
        CellByCellSampling::GridSampler<T> sampler( &interpolator, &density_map );

        KVS_OMP_FOR( reduction(+:N) )
        for ( kvs::UInt32 z = 0; z < ncells.z(); ++z )
        {
            size_t cell_index_counter = z * ncells.x() * ncells.y();
            for ( kvs::UInt32 y = 0; y < ncells.y(); ++y )
            {
                for ( kvs::UInt32 x = 0; x < ncells.x(); ++x )
                {
                    sampler.bind( kvs::Vec3ui( x, y, z ) );
                    const size_t n = sampler.numberOfParticles();
                    const kvs::UInt32 index = cell_index_counter++;
                    nparticles[index] = n;
                    N += n;
                }
            }
        }
    }

    // Genrate a set of particles.
    const kvs::UInt32 repetitions = m_repetition_level;
    CellByCellSampling::ColoredParticles particles( color_map );
    particles.allocate( N * repetitions );
/*
    kvs::ValueArray<kvs::Real32> coords( 3 * N * repetitions );
    kvs::ValueArray<kvs::Real32> normals( 3 * N * repetitions );
    kvs::ValueArray<kvs::UInt8> colors( 3 * N * repetitions );
*/
    KVS_OMP_PARALLEL()
    {
        kvs::TrilinearInterpolator interpolator( volume );
        CellByCellSampling::GridSampler<T> sampler( &interpolator, &density_map );
        KVS_OMP_FOR( schedule(static) )
        for ( kvs::UInt32 r = 0; r < repetitions; ++r )
        {
            size_t cell_index_counter = 0;
            size_t particle_index_counter = N * r;
            for ( kvs::UInt32 z = 0; z < ncells.z(); ++z )
            {
                for ( kvs::UInt32 y = 0; y < ncells.y(); ++y )
                {
                    for ( kvs::UInt32 x = 0; x < ncells.x(); ++x )
                    {
                        const kvs::UInt32 index = cell_index_counter++;
                        const size_t n = nparticles[index];
                        if ( n == 0 ) continue;

                        sampler.bind( kvs::Vec3ui( x, y, z ) );
                        for ( size_t i = 0; i < n; ++i )
                        {
                            sampler.sample();
                            const CellByCellSampling::Particle& p = sampler.accept();
                            const size_t particle_index = particle_index_counter++;
                            particles.push( particle_index, p );
                            /*
                            const kvs::RGBColor color = color_map.at( p.scalar );
                            const size_t index3 = ( particle_index_counter++ ) * 3;
                            coords[ index3 + 0 ] = p.coord.x();
                            coords[ index3 + 1 ] = p.coord.y();
                            coords[ index3 + 2 ] = p.coord.z();
                            normals[ index3 + 0 ] = p.normal.x();
                            normals[ index3 + 1 ] = p.normal.y();
                            normals[ index3 + 2 ] = p.normal.z();
                            colors[ index3 + 0 ] = color.r();
                            colors[ index3 + 1 ] = color.g();
                            colors[ index3 + 2 ] = color.b();
                            */
                        }
                    }
                }
            }
        }
    }

    SuperClass::setCoords( particles.coords() );
    SuperClass::setColors( particles.colors() );
    SuperClass::setNormals( particles.normals() );
    SuperClass::setSize( 1.0f );
}
Beispiel #11
0
    virtual void on_draw()
    {
        typedef agg::renderer_base<pixfmt>     renderer_base;
        typedef agg::renderer_base<pixfmt_pre> renderer_base_pre;

        pixfmt            pixf(rbuf_window());
        pixfmt_pre        pixf_pre(rbuf_window());
        renderer_base     rb(pixf);
        renderer_base_pre rb_pre(pixf_pre);

        rb.clear(agg::rgba(1.0, 1.0, 1.0));

        agg::trans_affine src_mtx;
        src_mtx *= agg::trans_affine_translation(-initial_width()/2 - 10, -initial_height()/2 - 20 - 10);
        src_mtx *= agg::trans_affine_rotation(m_angle.value() * agg::pi / 180.0);
        src_mtx *= agg::trans_affine_scaling(m_scale.value());
        src_mtx *= agg::trans_affine_translation(initial_width()/2, initial_height()/2 + 20);
        src_mtx *= trans_affine_resizing();

        agg::trans_affine img_mtx;
        img_mtx *= agg::trans_affine_translation(-initial_width()/2 + 10, -initial_height()/2 + 20 + 10);
        img_mtx *= agg::trans_affine_rotation(m_angle.value() * agg::pi / 180.0);
        img_mtx *= agg::trans_affine_scaling(m_scale.value());
        img_mtx *= agg::trans_affine_translation(initial_width()/2, initial_height()/2 + 20);
        img_mtx *= trans_affine_resizing();
        img_mtx.invert();

        agg::span_allocator<color_type> sa;

        typedef agg::span_interpolator_linear<> interpolator_type;
        interpolator_type interpolator(img_mtx);

        typedef agg::image_accessor_clip<pixfmt> img_source_type;

        pixfmt img_pixf(rbuf_img(0));
        img_source_type img_src(img_pixf, agg::rgba_pre(0, 0.4, 0, 0.5));

        /*
                // Version without filtering (nearest neighbor)
                //------------------------------------------
                typedef agg::span_image_filter_rgb_nn<img_source_type,
                                                      interpolator_type> span_gen_type;
                span_gen_type sg(img_src, interpolator);
                //------------------------------------------
        */

        // Version with "hardcoded" bilinear filter and without
        // image_accessor (direct filter, the old variant)
        //------------------------------------------
        typedef agg::span_image_filter_rgb_bilinear_clip<pixfmt,
                interpolator_type> span_gen_type;
        span_gen_type sg(img_pixf, agg::rgba_pre(0, 0.4, 0, 0.5), interpolator);
        //------------------------------------------

        /*
                // Version with arbitrary 2x2 filter
                //------------------------------------------
                typedef agg::span_image_filter_rgb_2x2<img_source_type,
                                                       interpolator_type> span_gen_type;
                agg::image_filter<agg::image_filter_kaiser> filter;
                span_gen_type sg(img_src, interpolator, filter);
                //------------------------------------------
        */
        /*
                // Version with arbitrary filter
                //------------------------------------------
                typedef agg::span_image_filter_rgb<img_source_type,
                                                   interpolator_type> span_gen_type;
                agg::image_filter<agg::image_filter_spline36> filter;
                span_gen_type sg(img_src, interpolator, filter);
                //------------------------------------------
        */

        agg::rasterizer_scanline_aa<> ras;
        ras.clip_box(0, 0, width(), height());
        agg::scanline_u8 sl;
        double r = initial_width();
        if(initial_height() - 60 < r) r = initial_height() - 60;
        agg::ellipse ell(initial_width()  / 2.0 + 10,
                         initial_height() / 2.0 + 20 + 10,
                         r / 2.0 + 16.0,
                         r / 2.0 + 16.0, 200);


        agg::conv_transform<agg::ellipse> tr(ell, src_mtx);

        ras.add_path(tr);
        agg::render_scanlines_aa(ras, sl, rb_pre, sa, sg);

        agg::render_ctrl(ras, sl, rb, m_angle);
        agg::render_ctrl(ras, sl, rb, m_scale);
    }
Beispiel #12
0
    virtual void on_draw()
    {
        typedef agg::pixfmt_bgr24 pixfmt;
        typedef agg::renderer_base<pixfmt> renderer_base;

        pixfmt pixf(rbuf_window());
        renderer_base rb(pixf);

        rb.clear(agg::rgba(1.0, 1.0, 1.0));

        agg::trans_affine src_mtx;
        src_mtx *= agg::trans_affine_translation(-initial_width()/2, -initial_height()/2);
        src_mtx *= agg::trans_affine_rotation(10.0 * agg::pi / 180.0);
        src_mtx *= agg::trans_affine_translation(initial_width()/2, initial_height()/2);
        src_mtx *= trans_affine_resizing();

        agg::trans_affine img_mtx = src_mtx;
        img_mtx.invert();

        typedef agg::span_allocator<agg::rgba8> span_alloc;

        unsigned i;

        unsigned char brightness_alpha_array[agg::span_conv_brightness_alpha_rgb8::array_size];
        for(i = 0; i < agg::span_conv_brightness_alpha_rgb8::array_size; i++)
        {
            brightness_alpha_array[i] = 
                agg::int8u(m_alpha.value(double(i) / 
                         double(agg::span_conv_brightness_alpha_rgb8::array_size)) * 255.0);
        }
        agg::span_conv_brightness_alpha_rgb8 color_alpha(brightness_alpha_array);



        typedef agg::image_accessor_clip<pixfmt> img_source_type;
        typedef agg::span_interpolator_linear<> interpolator_type; 
        typedef agg::span_image_filter_rgb_bilinear<img_source_type,
                                                    interpolator_type> span_gen;
        typedef agg::span_converter<span_gen,
                                    agg::span_conv_brightness_alpha_rgb8> span_conv;


        span_alloc sa;
        interpolator_type interpolator(img_mtx);
        pixfmt img_pixf(rbuf_img(0));
        img_source_type img_src(img_pixf, agg::rgba(0,0,0,0));
        span_gen sg(img_src, interpolator);
        span_conv sc(sg, color_alpha);
        agg::ellipse ell;
        agg::rasterizer_scanline_aa<> ras;
        agg::scanline_u8 sl;
        
        for(i = 0; i < 50; i++)
        {
            ell.init(m_x[i], m_y[i], m_rx[i], m_ry[i], 50);
            ras.add_path(ell);
            agg::render_scanlines_aa_solid(ras, sl, rb, m_colors[i]);
        }


        ell.init(initial_width()  / 2.0, 
                 initial_height() / 2.0, 
                 initial_width()  / 1.9, 
                 initial_height() / 1.9, 200);


        agg::conv_transform<agg::ellipse> tr(ell, src_mtx);


        ras.add_path(tr);
        agg::render_scanlines_aa(ras, sl, rb, sa, sc);

        agg::render_ctrl(ras, sl, rb, m_alpha);
    }
Beispiel #13
0
int main(int argc, char *argv[])
{
    #include "setRootCase.H"
    #include "createTime.H"
    #include "createMesh.H"

{
    scalarField samples(4);
    samples[0] = 0;
    samples[1] = 1;
    samples[2] = 2;
    samples[3] = 3;
    scalarField values(4);
    values = 1.0;
    //values[0] = 0.0;
    //values[1] = 1.0;

    //linearInterpolationWeights interpolator
    splineInterpolationWeights interpolator
    (
        samples
    );
    labelList indices;
    scalarField weights;

    interpolator.integrationWeights(1.1, 1.2, indices, weights);
    Pout<< "indices:" << indices << endl;
    Pout<< "weights:" << weights << endl;

    scalar baseSum = interpolator.weightedSum
    (
        weights,
        UIndirectList<scalar>(values, indices)
    );
    Pout<< "baseSum=" << baseSum << nl << nl << endl;


//    interpolator.integrationWeights(-0.01, 0, indices, weights);
//    scalar partialSum = interpolator.weightedSum
//    (
//        weights,
//        UIndirectList<scalar>(values, indices)
//    );
//    Pout<< "partialSum=" << partialSum << nl << nl << endl;
//
//
//    interpolator.integrationWeights(-0.01, 1, indices, weights);
//    //Pout<< "samples:" << samples << endl;
//    //Pout<< "indices:" << indices << endl;
//    //Pout<< "weights:" << weights << endl;
//    scalar sum = interpolator.weightedSum
//    (
//        weights,
//        UIndirectList<scalar>(values, indices)
//    );
//    Pout<< "integrand=" << sum << nl << nl << endl;


    return 1;
}

    IOdictionary dataEntryProperties
    (
        IOobject
        (
            "dataEntryProperties",
            runTime.constant(),
            mesh,
            IOobject::MUST_READ_IF_MODIFIED,
            IOobject::NO_WRITE
        )
    );

    autoPtr<DataEntry<scalar> > dataEntry
    (
        DataEntry<scalar>::New
        (
            "dataEntry",
            dataEntryProperties
        )
    );

    scalar x0 = readScalar(dataEntryProperties.lookup("x0"));
    scalar x1 = readScalar(dataEntryProperties.lookup("x1"));

    Info<< "Data entry type: " << dataEntry().type() << nl << endl;

    Info<< "Inputs" << nl
        << "    x0 = " << x0 << nl
        << "    x1 = " << x1 << nl
        << endl;

    Info<< "Interpolation" << nl
        << "    f(x0) = " << dataEntry().value(x0) << nl
        << "    f(x1) = " << dataEntry().value(x1) << nl
        << endl;

    Info<< "Integration" << nl
        << "    int(f(x)) lim(x0->x1) = " << dataEntry().integrate(x0, x1) << nl
        << endl;

    return 0;
}
Beispiel #14
0
Py::Object
Image::resize(const Py::Tuple& args) {
  _VERBOSE("Image::resize");
  
  args.verify_length(2);
  
  if (bufferIn ==NULL) 
    throw Py::RuntimeError("You must first load the image"); 
  
  int numcols = Py::Int(args[0]);
  int numrows = Py::Int(args[1]);
  
  colsOut = numcols;
  rowsOut = numrows;
  
  
  size_t NUMBYTES(numrows * numcols * BPP);
  agg::int8u *buffer = new agg::int8u[NUMBYTES];  
  if (buffer ==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("Image::resize could not allocate memory");
  
  rbufOut = new agg::rendering_buffer;
  rbufOut->attach(buffer, numcols, numrows, numcols * BPP);
  
  // init the output rendering/rasterizing stuff
  pixfmt pixf(*rbufOut);
  renderer_base rb(pixf);
  rb.clear(bg);
  agg::rasterizer_scanline_aa<> ras;
  agg::scanline_u8 sl;

  
  //srcMatrix *= resizingMatrix;
  //imageMatrix *= resizingMatrix;
  imageMatrix.invert();
  interpolator_type interpolator(imageMatrix); 
  
  
  
  
  agg::image_filter_base* filter = 0;  
  agg::span_allocator<agg::rgba8> sa;	
  agg::rgba8 background(agg::rgba8(int(255*bg.r),
				   int(255*bg.g),
				   int(255*bg.b),
				   int(255*bg.a)));




  // the image path
  agg::path_storage path;
  agg::int8u *bufferPad = NULL;
  agg::rendering_buffer rbufPad;

  double x0, y0, x1, y1;
  
  if (interpolation==NEAREST) {
    x0 = 0.0;
    x1 = colsIn;
    y0 = 0.0;
    y1 = rowsIn;
  }
  else {
    // if interpolation != nearest, create a new input buffer with the
    // edges mirrored on all size.  Then new buffer size is colsIn+2 by
    // rowsIn+2

    x0 = 1.0;
    x1 = colsIn+1;
    y0 = 1.0;
    y1 = rowsIn+1;

    bufferPad = new agg::int8u[(rowsIn+2) * (colsIn+2) * BPP];
    if (bufferPad ==NULL) 
      throw Py::MemoryError("Image::resize could not allocate memory");
    //pad the input buffer
    for (size_t rowNum=0; rowNum<rowsIn+2; rowNum++)
      for (size_t colNum=0; colNum<colsIn+2; colNum++) {
	if ( (colNum==0) && (rowNum==1||(rowNum==rowsIn+1))) {
	  //rewind to begining of column
	  bufferIn -= colsIn * BPP; 
	}
	*bufferPad++ = *bufferIn++;       //red
	*bufferPad++ = *bufferIn++;       //green
	*bufferPad++ = *bufferIn++;       //blue
	*bufferPad++ = *bufferIn++;       //alpha

	//rewind one byte on the first and next to last columns
	if ( colNum==0 || colNum==colsIn) bufferIn-=4;
      }
    //rewind the input buffers
    bufferIn  -= rowsIn * colsIn * BPP;
    bufferPad -= (rowsIn+2) * (colsIn+2) * BPP;
    rbufPad.attach(bufferPad, colsIn+2, rowsIn+2, (colsIn+2) * BPP);
  }



    
  if (buffer ==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("Image::resize could not allocate memory");
  
  path.move_to(x0, y0);
  path.line_to(x1, y0);
  path.line_to(x1, y1);
  path.line_to(x0, y1);
  path.close_polygon();
  agg::conv_transform<agg::path_storage> imageBox(path, srcMatrix);
  ras.add_path(imageBox);

  switch(interpolation)
    {
    case NEAREST:
      {
	
	typedef agg::span_image_filter_rgba32_nn<agg::order_rgba32,
	  interpolator_type> span_gen_type;
	typedef agg::renderer_scanline_aa<renderer_base, span_gen_type> renderer_type;
	       
	span_gen_type sg(sa, *rbufIn, background, interpolator);
	renderer_type ri(rb, sg);
	agg::render_scanlines(ras, sl, ri);
	
      }
      break;
      
    case BILINEAR:
      {

       
	typedef agg::span_image_filter_rgba32_bilinear<agg::order_rgba32,
	  interpolator_type> span_gen_type;
	typedef agg::renderer_scanline_aa<renderer_base, span_gen_type> renderer_type;
		
	span_gen_type sg(sa, rbufPad, background, interpolator);
	renderer_type ri(rb, sg);
	agg::render_scanlines(ras, sl, ri);
      }
      break;
      
    case BICUBIC:     filter = new agg::image_filter<agg::image_filter_bicubic>;
    case SPLINE16:    filter = new agg::image_filter<agg::image_filter_spline16>;
    case SPLINE36:    filter = new agg::image_filter<agg::image_filter_spline36>;   
    case SINC64:      filter = new agg::image_filter<agg::image_filter_sinc64>;     
    case SINC144:     filter = new agg::image_filter<agg::image_filter_sinc144>;    
    case SINC256:     filter = new agg::image_filter<agg::image_filter_sinc256>;    
    case BLACKMAN64:  filter = new agg::image_filter<agg::image_filter_blackman64>; 
    case BLACKMAN100: filter = new agg::image_filter<agg::image_filter_blackman100>;
    case BLACKMAN256: filter = new agg::image_filter<agg::image_filter_blackman256>;
      
      typedef agg::span_image_filter_rgba32<agg::order_rgba32,
	interpolator_type> span_gen_type;
      typedef agg::renderer_scanline_aa<renderer_base, span_gen_type> renderer_type;
      span_gen_type sg(sa, rbufPad, background, interpolator, *filter);
      renderer_type ri(rb, sg);
      agg::render_scanlines(ras, sl, ri);
      
    }
  
  /*
    std::ofstream of2( "image_out.raw", std::ios::binary|std::ios::out);
    for (size_t i=0; i<NUMBYTES; ++i)
    of2.write((char*)&buffer[i], sizeof(char));
  */
  
  
  bufferOut = buffer;
  delete [] bufferPad;

  return Py::Object();
  
}
Beispiel #15
0
    virtual void on_draw()
    {
        double img_width = rbuf_img(0).width();
        double img_height = rbuf_img(0).height();
    
        typedef agg::pixfmt_bgr24 pixfmt; 
        typedef agg::renderer_base<pixfmt> renderer_base;

        pixfmt pixf(rbuf_window());
        pixfmt img_pixf(rbuf_img(0));

        renderer_base rb(pixf);

        rb.clear(agg::rgba(1.0, 1.0, 1.0));

        agg::trans_affine src_mtx;
        src_mtx *= agg::trans_affine_translation(-img_width/2, -img_height/2);
        src_mtx *= agg::trans_affine_rotation(m_angle.value() * agg::pi / 180.0);
        src_mtx *= agg::trans_affine_translation(img_width/2 + 10, img_height/2 + 10 + 40);
        src_mtx *= trans_affine_resizing();

        agg::trans_affine img_mtx;
        img_mtx *= agg::trans_affine_translation(-img_width/2, -img_height/2);
        img_mtx *= agg::trans_affine_rotation(m_angle.value() * agg::pi / 180.0);
        img_mtx *= agg::trans_affine_scaling(m_scale.value());
        img_mtx *= agg::trans_affine_translation(img_width/2 + 10, img_height/2 + 10 + 40);
        img_mtx *= trans_affine_resizing();
        img_mtx.invert();


        typedef agg::span_allocator<agg::rgba8> span_alloc_type;

        span_alloc_type sa;
        
        typedef agg::span_interpolator_adaptor<agg::span_interpolator_linear<>, 
                                               periodic_distortion> interpolator_type;

        periodic_distortion*  dist = 0;
        distortion_wave       dist_wave;
        distortion_swirl      dist_swirl;
        distortion_wave_swirl dist_wave_swirl;
        distortion_swirl_wave dist_swirl_wave;

        switch(m_distortion.cur_item())
        {
            case 0: dist = &dist_wave;       break;
            case 1: dist = &dist_swirl;      break;
            case 2: dist = &dist_wave_swirl; break;
            case 3: dist = &dist_swirl_wave; break;
        }

        dist->period(m_period.value());
        dist->amplitude(m_amplitude.value());
        dist->phase(m_phase);
        double cx = m_center_x;
        double cy = m_center_y;
        img_mtx.transform(&cx, &cy);
        dist->center(cx, cy);

        interpolator_type interpolator(img_mtx, *dist);

        typedef agg::image_accessor_clip<pixfmt> img_source_type;
        img_source_type img_src(img_pixf, agg::rgba(1,1,1));

/*
        // Version without filtering (nearest neighbor)
        //------------------------------------------
        typedef agg::span_image_filter_rgb_nn<img_source_type,
                                              interpolator_type> span_gen_type;
        span_gen_type sg(img_src, interpolator);
        //------------------------------------------
*/

        // Version with "hardcoded" bilinear filter and without 
        // image_accessor (direct filter, the old variant)
        //------------------------------------------
        typedef agg::span_image_filter_rgb_bilinear_clip<pixfmt,
                                                         interpolator_type> span_gen_type;
        span_gen_type sg(img_pixf, agg::rgba(1,1,1), interpolator);
        //------------------------------------------

/*
        // Version with arbitrary 2x2 filter
        //------------------------------------------
        typedef agg::span_image_filter_rgb_2x2<img_source_type,
                                               interpolator_type> span_gen_type;
        agg::image_filter<agg::image_filter_kaiser> filter;
        span_gen_type sg(img_src, interpolator, filter);
        //------------------------------------------
*/
/*
        // Version with arbitrary filter
        //------------------------------------------
        typedef agg::span_image_filter_rgb<img_source_type,
                                           interpolator_type> span_gen_type;
        agg::image_filter<agg::image_filter_spline36> filter;
        span_gen_type sg(img_src, interpolator, filter);
        //------------------------------------------
*/


        agg::rasterizer_scanline_aa<> ras;
        agg::scanline_u8 sl;
        double r = img_width;
        if(img_height < r) r = img_height;
        agg::ellipse ell(img_width  / 2.0, 
                         img_height / 2.0, 
                         r / 2.0 - 20.0, 
                         r / 2.0 - 20.0, 200);


        agg::conv_transform<agg::ellipse> tr(ell, src_mtx);

        ras.add_path(tr);
        agg::render_scanlines_aa(ras, sl, rb, sa, sg);

        src_mtx *= ~trans_affine_resizing();
        src_mtx *= agg::trans_affine_translation(img_width - img_width/10, 0.0);
        src_mtx *= trans_affine_resizing();

        ras.add_path(tr);
        agg::render_scanlines_aa_solid(ras, sl, rb, agg::rgba8(0,0,0));

        typedef agg::span_gradient<agg::rgba8, 
                                   interpolator_type,
                                   agg::gradient_circle,
                                   color_array_type> gradient_span_gen;

        agg::gradient_circle gradient_function;

        color_array_type gradient_colors(m_gradient_colors);
        gradient_span_gen span_gradient(interpolator, 
                                        gradient_function, 
                                        gradient_colors, 
                                        0, 180);

        agg::trans_affine gr1_mtx;
        gr1_mtx *= agg::trans_affine_translation(-img_width/2, -img_height/2);
        gr1_mtx *= agg::trans_affine_scaling(0.8);
        gr1_mtx *= agg::trans_affine_rotation(m_angle.value() * agg::pi / 180.0);
        gr1_mtx *= agg::trans_affine_translation(img_width - img_width/10 + img_width/2 + 10, 
                                                 img_height/2 + 10 + 40);
        gr1_mtx *= trans_affine_resizing();

        agg::trans_affine gr2_mtx;
        gr2_mtx *= agg::trans_affine_rotation(m_angle.value() * agg::pi / 180.0);
        gr2_mtx *= agg::trans_affine_scaling(m_scale.value());
        gr2_mtx *= agg::trans_affine_translation(img_width - img_width/10 + img_width/2 + 10 + 50, 
                                                 img_height/2 + 10 + 40 + 50);
        gr2_mtx *= trans_affine_resizing();
        gr2_mtx.invert();

        cx = m_center_x + img_width - img_width/10;
        cy = m_center_y;
        gr2_mtx.transform(&cx, &cy);
        dist->center(cx, cy);

        interpolator.transformer(gr2_mtx);

        agg::conv_transform<agg::ellipse> tr2(ell, gr1_mtx);

        ras.add_path(tr2);
        agg::render_scanlines_aa(ras, sl, rb, sa, span_gradient);

        agg::render_ctrl(ras, sl, rb, m_angle);
        agg::render_ctrl(ras, sl, rb, m_scale);
        agg::render_ctrl(ras, sl, rb, m_amplitude);
        agg::render_ctrl(ras, sl, rb, m_period);
        agg::render_ctrl(ras, sl, rb, m_distortion);
    }
Beispiel #16
0
Py::Object
Image::resize(const Py::Tuple& args) {
    _VERBOSE("Image::resize");

    args.verify_length(2);

    if (bufferIn ==NULL)
        throw Py::RuntimeError("You must first load the image");

    int numcols = Py::Int(args[0]);
    int numrows = Py::Int(args[1]);

    colsOut = numcols;
    rowsOut = numrows;


    size_t NUMBYTES(numrows * numcols * BPP);
    agg::int8u *buffer = new agg::int8u[NUMBYTES];
    if (buffer ==NULL) //todo: also handle allocation throw
        throw Py::MemoryError("Image::resize could not allocate memory");

    rbufOut = new agg::rendering_buffer;
    rbufOut->attach(buffer, numcols, numrows, numcols * BPP);

    // init the output rendering/rasterizing stuff
    pixfmt pixf(*rbufOut);
    renderer_base rb(pixf);
    rb.clear(bg);
    agg::rasterizer_scanline_aa<> ras;
    agg::scanline_u8 sl;


    //srcMatrix *= resizingMatrix;
    //imageMatrix *= resizingMatrix;
    imageMatrix.invert();
    interpolator_type interpolator(imageMatrix);

    // the image path
    agg::path_storage path;
    path.move_to(0, 0);
    path.line_to(colsIn, 0);
    path.line_to(colsIn, rowsIn);
    path.line_to(0, rowsIn);
    path.close_polygon();
    agg::conv_transform<agg::path_storage> imageBox(path, srcMatrix);
    ras.add_path(imageBox);



    agg::image_filter_base* filter = 0;
    agg::span_allocator<agg::rgba8> sa;
    switch(interpolation)
    {
    case NEAREST:
    {
        typedef agg::span_image_filter_rgba32_nn<agg::order_rgba32,
                interpolator_type> span_gen_type;
        typedef agg::renderer_scanline_u<renderer_base, span_gen_type> renderer_type;

        span_gen_type sg(sa, *rbufIn, agg::rgba(1,1,1,0), interpolator);
        renderer_type ri(rb, sg);
        ras.add_path(imageBox);
        ras.render(sl, ri);
    }
    break;

    case BILINEAR:
    {
        typedef agg::span_image_filter_rgba32_bilinear<agg::order_rgba32,
                interpolator_type> span_gen_type;
        typedef agg::renderer_scanline_u<renderer_base, span_gen_type> renderer_type;

        span_gen_type sg(sa, *rbufIn, agg::rgba(1,1,1,0), interpolator);
        renderer_type ri(rb, sg);
        ras.add_path(imageBox);
        ras.render(sl, ri);
    }
    break;

    case BICUBIC:
        filter = new agg::image_filter<agg::image_filter_bicubic>;
    case SPLINE16:
        filter = new agg::image_filter<agg::image_filter_spline16>;
    case SPLINE36:
        filter = new agg::image_filter<agg::image_filter_spline36>;
    case SINC64:
        filter = new agg::image_filter<agg::image_filter_sinc64>;
    case SINC144:
        filter = new agg::image_filter<agg::image_filter_sinc144>;
    case SINC256:
        filter = new agg::image_filter<agg::image_filter_sinc256>;
    case BLACKMAN64:
        filter = new agg::image_filter<agg::image_filter_blackman64>;
    case BLACKMAN100:
        filter = new agg::image_filter<agg::image_filter_blackman100>;
    case BLACKMAN256:
        filter = new agg::image_filter<agg::image_filter_blackman256>;

        typedef agg::span_image_filter_rgba32<agg::order_rgba32,
                interpolator_type> span_gen_type;
        typedef agg::renderer_scanline_u<renderer_base, span_gen_type> renderer_type;

        span_gen_type sg(sa, *rbufIn, agg::rgba(1,1,1,0), interpolator, *filter);
        renderer_type ri(rb, sg);
        ras.render(sl, ri);

    }

    /*
      std::ofstream of2( "image_out.raw", std::ios::binary|std::ios::out);
      for (size_t i=0; i<NUMBYTES; ++i)
      of2.write((char*)&buffer[i], sizeof(char));
    */


    bufferOut = buffer;


    return Py::Object();

}
Beispiel #17
0
int main()
{
    // Create model from sample Predicted Parameterized Times
    // (from cycle accurate simulator or real machine)
  EventInterpolator interpolator(CYCLE_TIMES_FILE, KEEP_RATIO);
  int totalProcs, numX, numY, numZ, numCth, numWth, numPes;
	double ratio_sum=0.0;
	unsigned long ratio_count= 0;
	double ratio_bracketed_sum=0.0;
	unsigned long ratio_bracketed_count = 0;

	double old_times_sum=0.0;
	double old_bracketed_times_sum=0.0;
	double new_bracketed_times_sum=0.0;

	ofstream of_ratio_all("ratio_all");
	ofstream of_ratio_bracketed("ratio_bracketed");

	interpolator.printCoefficients();

    // load bg trace summary file
    printf("Loading bgTrace ... \n");
    int status = BgLoadTraceSummary("bgTrace", totalProcs, numX, numY, numZ, numCth, numWth, numPes);
    if (status == -1) exit(1);
    printf("========= BgLog Version: %d ========= \n", bglog_version);
    printf("Found %d (%dx%dx%d:%dw-%dc) emulated procs on %d real procs.\n", totalProcs, numX, numY, numZ, numWth, numCth, numPes);

    int* allNodeOffsets = BgLoadOffsets(totalProcs,numPes);

    printf("========= Loading All Logs ========= \n");

    // load each individual trace file for each bg proc

    unsigned found_event_count=0;
    unsigned total_count=0;
    bool negative_durations_occured = false;

    printf("Loading bgTrace files ...\n");

    // Create output directory
    mkdir(OUTPUTDIR, 0777);

		int numNodes = totalProcs / numWth;

    for (int fileNum=0; fileNum<numPes; fileNum++){
        BgTimeLineRec *tlinerecs = new BgTimeLineRec[totalProcs/numPes+1];
        int rec_count = 0;

        //for(int procNum=fileNum;procNum<totalProcs;procNum+=numPes){
				 for (int nodeNum=fileNum;nodeNum<numNodes;nodeNum+=numPes) {
						for (int procNum=nodeNum*numWth; procNum<(nodeNum+1)*numWth; procNum++) {

            BgTimeLineRec &tlinerec = tlinerecs[rec_count];
            rec_count++;

            currTline = &tlinerec;
            currTlineIdx = procNum;
            int fileNum = BgReadProc(procNum,numWth,numPes,totalProcs,allNodeOffsets,tlinerec);
            CmiAssert(fileNum != -1);

#ifdef DEBUG
        		printf("Load log of BG proc %d from bgTrace%d... \n", procNum, fileNum);
#endif

            BgTimeLine &timeLine = tlinerec.timeline; // Really a CkQ< BgTimeLog *>

#ifdef DEBUG
            printf("%d entries in timeLine\n", timeLine.length());
#endif

            // Scan through each event for this emulated processor
            for(int j=0;j<timeLine.length();j++){
                BgTimeLog* timeLog = timeLine[j];
                std::string name(timeLog->name);
                total_count++;

                double old_start = timeLog->startTime;
                double old_end   = timeLog->endTime;
                double old_duration = old_end-old_start;

						double old_bracket_start=0.0;
						double old_bracket_end=0.0;
						int have_bracket_start=0;
						int have_bracket_end=0;
						double begin_piece=0.0;
						double middle_piece=old_duration;
						double end_piece=0.0;
						assert(old_duration >= 0.0);
						assert(old_end >= 0.0);
						if(old_end > old_start){
						  old_times_sum += old_duration;
						  //FIXME: check only the right kind of events.
						  // Look for BG_EVENT_PRINT 'events' inside this event.
						  for(int i=0;i<timeLog->evts.length();i++){
								char *data = (char*)timeLog->evts[i]->data;
								if(strncmp(data,"startTraceBigSim",16)==0){
								  old_bracket_start = old_start+timeLog->evts[i]->rTime;
					  			have_bracket_start = 1;
								}
								else if(strncmp(data,"endTraceBigSim",14)==0){
					  			old_bracket_end = old_start+timeLog->evts[i]->rTime;
									  have_bracket_end = 1;
                 }
						  }
						  // If we have bracketed timings, the middle part will be the old
						  // bracketed time region, and the begin and end pieces will be non-zero
						  if(have_bracket_end && have_bracket_start){
								begin_piece = old_bracket_start - old_start;
								middle_piece = old_bracket_end - old_bracket_start;
								end_piece = old_duration - begin_piece - middle_piece;
								old_bracketed_times_sum += middle_piece;
								assert(begin_piece >= 0.0);
								assert(middle_piece >= 0.0);
								assert(end_piece >= 0.0);
				  		}
						  else{
								old_bracket_start = old_start;
								old_bracket_end = old_end;
								assert(old_bracket_end - old_bracket_start >= 0.0);
						  }
				  		// If this event occurs in the paramerter file and cycle-accurate simulations, use that data to predict its runtime
				  		if( interpolator.haveNewTiming(procNum,timeLog->seqno) ) {
								double old_middle_piece = middle_piece;
								
								// GAGAN : Making it directly based on the model 
								//middle_piece = interpolator.getNewTiming(procNum,timeLog->seqno) * sec_per_cycle;
								
								middle_piece = interpolator.getNewTiming(procNum,timeLog->seqno);
								
								found_event_count ++;
								double ratio =  old_middle_piece / middle_piece;
								if(ratio > 1e-10 && ratio < 1e10){
								  ratio_bracketed_sum += ratio;
								  ratio_bracketed_count ++;
									of_ratio_bracketed << ratio << endl;
								}
//								cout<<" used interpolation tool"<<endl;
							}
				  		// If event is not in parameter file then we just scale its duration by a simple constant
						  else {
	//							cout<<" used time dilation for "<< procNum <<"  "<< timeLog->seqno<<endl;
								middle_piece = middle_piece*time_dilation_factor ;
							}
				  if(middle_piece < 0.0) {
						middle_piece=0.0;
						negative_durations_occured=true;
				  }
				  if(have_bracket_end && have_bracket_start){
						new_bracketed_times_sum += middle_piece;
				  }
				  // Scale the begin and end pieces by time_dilation_factor;
				  begin_piece = begin_piece*time_dilation_factor;
				  end_piece = end_piece*time_dilation_factor;
				  assert(begin_piece >= 0.0);
				  assert(middle_piece >= 0.0);
				  assert(end_piece >= 0.0);
				  double new_start    = old_start;
				  double new_duration = begin_piece + middle_piece + end_piece;
				  double new_end      = new_start + new_duration;
				  timeLog->startTime = new_start;
				  timeLog->endTime   = new_end;
				  timeLog->execTime  = new_duration;
				  double new_bracket_start = new_start+begin_piece;
				  double new_bracket_end = new_start+begin_piece+middle_piece;
#ifdef PRINT_NEW_TIMES
				  printf("Rewriting duration of event %d name=%s from [%.10lf , %.10lf] (%.10lf) to [%.10lf , %.10lf] (%.10lf) ratio=%.10lf\n", j, timeLog->name, old_start,old_end,old_end-old_start,new_start,new_end,new_end-new_start,(old_end-old_start)/(new_end-new_start));
#endif
				  double ratio = (old_duration)/(new_duration);
				  if(ratio >= 1e-10 && ratio <= 1e10){
						ratio_sum += ratio;
						ratio_count ++;
						of_ratio_all << ratio << endl;
				  }
				  // Rewrite times of messages sent from this event
				  for(int m=0;m<timeLog->msgs.length();m++){
						double old_send = timeLog->msgs[m]->sendTime;
						double new_send, new_recv;
						double old_recv;
						assert(old_send <= old_end);
						assert(old_send >= old_start);
						// We have three places where the message is coming from
						// We linearly map the value into the beginning, middle, or end piece
						if(old_send < old_bracket_start){
						  new_send = map_linearly_to_interval(old_send, old_start,old_bracket_start,new_start,new_bracket_start);
						}
						else if(old_send < old_bracket_end){
					  	new_send = map_linearly_to_interval(old_send, old_bracket_start,old_bracket_end,new_bracket_start,new_bracket_end);
						}
						else {
						  new_send = map_linearly_to_interval(old_send, old_bracket_end,old_end,new_bracket_end,new_end);
						}
					timeLog->msgs[m]->sendTime = new_send;
#ifdef PRINT_NEW_TIMES
					printf("pe=%d changing message %d send time from %.10lf to %.10lf\n", procNum, m, old_send, new_send);
					printf("pe=%d compare %d send time from %.10lf to recv time %.10lf\n", procNum, m, new_send,timeLog->msgs[m]->recvTime  );
#endif
					old_recv = timeLog->msgs[m]->recvTime ;
					new_recv = (old_recv - old_send) + new_send;
					timeLog->msgs[m]->recvTime = new_recv; 
					assert(new_send <= new_end);
					assert(new_send >= new_start);
				  assert(old_recv >= old_send);
					if(new_recv < new_send)
					{
							printf( "Bad case send: %.10f recv: %.10f \n", new_send, new_recv); 
					}
					assert(new_recv >= new_send);
				  }
				}
      }
    }
   }
#ifdef WRITE_OUTPUT_FILES
            // Write out the file
            cout << "writing " << rec_count << " simulated processors to this bgTrace file" << endl;
            BgWriteTimelines(fileNum,tlinerecs,rec_count,OUTPUTDIR);
#endif
        delete[] tlinerecs;

  }
  if(negative_durations_occured){
		cerr << "======================  WARNING ======================" << endl;
		cerr << "||  One or more new durations were less than zero. \n||  This probably means your model or input times are \n||  not good enough." << endl;
		cerr << "======================================================" << endl;
  }
  interpolator.printMinInterpolatedTimes();
  printf("Writing new bgTrace files ...\n");
	printf("average duration speedup(including unbracketed pieces): %.8lf\n", ratio_sum / (double)ratio_count);
	printf("average bracketed speedup: %.8lf\n", ratio_bracketed_sum / (double)ratio_bracketed_count);
	cout << "Sum of times of bracketed portions of input logs: " << old_bracketed_times_sum << endl;
	cout << "Sum of times of bracketed portions of output logs: " << new_bracketed_times_sum << endl;
  const char* fname = "bgTrace";
#ifdef WRITE_OUTPUT_FILES
  // Write out the timelines to the same number of files as we started with.
  BgWriteTraceSummary(numPes, numX, numY, numZ, numWth, numCth, fname , OUTPUTDIR);
#endif
  delete [] allNodeOffsets;
  cout << "Of the " << total_count << " events found in the bgTrace files, " << found_event_count << " were found in the param files" << endl;
  interpolator.printMatches();
	cout << "The sum of all positive duration events from the original bgTrace files is: " << old_times_sum << endl;
  cout << "End of program" << endl;
}
Beispiel #18
0
MAPNIK_DECL void warp_image (T & target, T const& source, proj_transform const& prj_trans,
                 box2d<double> const& target_ext, box2d<double> const& source_ext,
                 double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor)
{
    using image_type = T;
    using pixel_type = typename image_type::pixel_type;
    using pixfmt_pre = typename detail::agg_scaling_traits<image_type>::pixfmt_pre;
    using color_type = typename detail::agg_scaling_traits<image_type>::color_type;
    using renderer_base = agg::renderer_base<pixfmt_pre>;
    using interpolator_type = typename detail::agg_scaling_traits<image_type>::interpolator_type;

    constexpr std::size_t pixel_size = sizeof(pixel_type);

    view_transform ts(source.width(), source.height(),
                      source_ext);
    view_transform tt(target.width(), target.height(),
                      target_ext, offset_x, offset_y);

    std::size_t mesh_nx = std::ceil(source.width()/double(mesh_size) + 1);
    std::size_t mesh_ny = std::ceil(source.height()/double(mesh_size) + 1);

    image_gray64f xs(mesh_nx, mesh_ny, false);
    image_gray64f ys(mesh_nx, mesh_ny, false);

    // Precalculate reprojected mesh
    for(std::size_t j = 0; j < mesh_ny; ++j)
    {
        for (std::size_t i=0; i<mesh_nx; ++i)
        {
            xs(i,j) = std::min(i*mesh_size,source.width());
            ys(i,j) = std::min(j*mesh_size,source.height());
            ts.backward(&xs(i,j), &ys(i,j));
        }
    }
    prj_trans.backward(xs.getData(), ys.getData(), nullptr, mesh_nx*mesh_ny);

    agg::rasterizer_scanline_aa<> rasterizer;
    agg::scanline_bin scanline;
    agg::rendering_buffer buf(target.getBytes(),
                              target.width(),
                              target.height(),
                              target.width() * pixel_size);
    pixfmt_pre pixf(buf);
    renderer_base rb(pixf);
    rasterizer.clip_box(0, 0, target.width(), target.height());
    agg::rendering_buffer buf_tile(
        const_cast<unsigned char*>(source.getBytes()),
        source.width(),
        source.height(),
        source.width() * pixel_size);

    pixfmt_pre pixf_tile(buf_tile);

    using img_accessor_type = agg::image_accessor_clone<pixfmt_pre>;
    img_accessor_type ia(pixf_tile);

    agg::span_allocator<color_type> sa;
    // Project mesh cells into target interpolating raster inside each one
    for (std::size_t j = 0; j < mesh_ny - 1; ++j)
    {
        for (std::size_t i = 0; i < mesh_nx - 1; ++i)
        {
            double polygon[8] = {xs(i,j), ys(i,j),
                                 xs(i+1,j), ys(i+1,j),
                                 xs(i+1,j+1), ys(i+1,j+1),
                                 xs(i,j+1), ys(i,j+1)};
            tt.forward(polygon+0, polygon+1);
            tt.forward(polygon+2, polygon+3);
            tt.forward(polygon+4, polygon+5);
            tt.forward(polygon+6, polygon+7);

            rasterizer.reset();
            rasterizer.move_to_d(std::floor(polygon[0]), std::floor(polygon[1]));
            rasterizer.line_to_d(std::floor(polygon[2]), std::floor(polygon[3]));
            rasterizer.line_to_d(std::floor(polygon[4]), std::floor(polygon[5]));
            rasterizer.line_to_d(std::floor(polygon[6]), std::floor(polygon[7]));

            std::size_t x0 = i * mesh_size;
            std::size_t y0 = j * mesh_size;
            std::size_t x1 = (i+1) * mesh_size;
            std::size_t y1 = (j+1) * mesh_size;
            x1 = std::min(x1, source.width());
            y1 = std::min(y1, source.height());
            agg::trans_affine tr(polygon, x0, y0, x1, y1);
            if (tr.is_valid())
            {
                interpolator_type interpolator(tr);
                if (scaling_method == SCALING_NEAR)
                {
                    using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_filter;
                    span_gen_type sg(ia, interpolator);
                    agg::render_scanlines_bin(rasterizer, scanline, rb, sa, sg);
                }
                else
                {
                    using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_resample_affine;
                    agg::image_filter_lut filter;
                    detail::set_scaling_method(filter, scaling_method, filter_factor);
                    span_gen_type sg(ia, interpolator, filter);
                    agg::render_scanlines_bin(rasterizer, scanline, rb, sa, sg);
                }
            }

        }
    }
}
Beispiel #19
0
    void transform_image(double angle)
    {
        double width = rbuf_img(0).width();
        double height = rbuf_img(0).height();

        pixfmt pixf(rbuf_img(0));
        pixfmt_pre pixf_pre(rbuf_img(0));
        renderer_base rb(pixf);
        renderer_base_pre rb_pre(pixf_pre);

        rb.clear(agg::rgba(1.0, 1.0, 1.0));

        agg::rasterizer_scanline_aa<> ras;
        agg::scanline_u8 sl;
        agg::span_allocator<color_type> sa;

        agg::trans_affine src_mtx;
        src_mtx *= agg::trans_affine_translation(-width/2.0, -height/2.0);
        src_mtx *= agg::trans_affine_rotation(angle * agg::pi / 180.0);
        src_mtx *= agg::trans_affine_translation(width/2.0, height/2.0);

        agg::trans_affine img_mtx = src_mtx;
        img_mtx.invert();

        double r = width;
        if(height < r) r = height;

        r *= 0.5;
        r -= 4.0;
        agg::ellipse ell(width  / 2.0, 
                         height / 2.0, 
                         r, r, 200);
        agg::conv_transform<agg::ellipse> tr(ell, src_mtx);

        m_num_pix += r * r * agg::pi;

        typedef agg::span_interpolator_linear<> interpolator_type;
        interpolator_type interpolator(img_mtx); 

        agg::image_filter_lut filter;
        bool norm = m_normalize.status();

        switch(m_filters.cur_item())
        {
        case 0:
            {
                typedef agg::span_image_filter_nn<color_type,
#ifdef AGG_COMPONENT_ORDER
                                                  component_order,
#endif
                                                  interpolator_type> span_gen_type;
                typedef agg::renderer_scanline_aa<renderer_base_pre, 
                                                  span_gen_type> renderer_type;

                span_gen_type sg(sa, rbuf_img(1), agg::rgba(0,0,0,0), interpolator);
                renderer_type ri(rb_pre, sg);
                ras.add_path(tr);
                agg::render_scanlines(ras, sl, ri);
            }
            break;

        case 1:
            {
                typedef agg::span_image_filter_bilinear<color_type,
#ifdef AGG_COMPONENT_ORDER
                                                        component_order,
#endif
                                                        interpolator_type> span_gen_type;
                typedef agg::renderer_scanline_aa<renderer_base_pre, 
                                                  span_gen_type> renderer_type;

                span_gen_type sg(sa, rbuf_img(1), agg::rgba(0,0,0,0), interpolator);
                renderer_type ri(rb_pre, sg);
                ras.add_path(tr);
                agg::render_scanlines(ras, sl, ri);
            }
            break;

        case 5:
        case 6:
        case 7:
            {
                switch(m_filters.cur_item())
                {
                case 5:  filter.calculate(agg::image_filter_hanning(),  norm); break; 
                case 6:  filter.calculate(agg::image_filter_hamming(),  norm); break; 
                case 7:  filter.calculate(agg::image_filter_hermite(),  norm); break; 
                }

                typedef agg::span_image_filter_2x2<color_type,
#ifdef AGG_COMPONENT_ORDER
                                                   component_order,
#endif
                                                   interpolator_type> span_gen_type;
                typedef agg::renderer_scanline_aa<renderer_base_pre, 
                                                  span_gen_type> renderer_type;

                span_gen_type sg(sa, rbuf_img(1), agg::rgba(0,0,0,0), interpolator, filter);
                renderer_type ri(rb_pre, sg);
                ras.add_path(tr);
                agg::render_scanlines(ras, sl, ri);
            }
            break;

        case 2:
        case 3:
        case 4:
        case 8:  
        case 9:  
        case 10: 
        case 11: 
        case 12: 
        case 13: 
        case 14: 
        case 15: 
        case 16: 
            {
                switch(m_filters.cur_item())
                {
                case 2:  filter.calculate(agg::image_filter_bicubic(),                  norm); break; 
                case 3:  filter.calculate(agg::image_filter_spline16(),                 norm); break; 
                case 4:  filter.calculate(agg::image_filter_spline36(),                 norm); break; 
                case 8:  filter.calculate(agg::image_filter_kaiser(),                   norm); break; 
                case 9:  filter.calculate(agg::image_filter_quadric(),                  norm); break; 
                case 10: filter.calculate(agg::image_filter_catrom(),                   norm); break; 
                case 11: filter.calculate(agg::image_filter_gaussian(),                 norm); break; 
                case 12: filter.calculate(agg::image_filter_bessel(),                   norm); break; 
                case 13: filter.calculate(agg::image_filter_mitchell(),                 norm); break; 
                case 14: filter.calculate(agg::image_filter_sinc(m_radius.value()),     norm); break; 
                case 15: filter.calculate(agg::image_filter_lanczos(m_radius.value()),  norm); break; 
                case 16: filter.calculate(agg::image_filter_blackman(m_radius.value()), norm); break; 
                }

                typedef agg::span_image_filter<color_type,
#ifdef AGG_COMPONENT_ORDER
                                              component_order,
#endif
                                              interpolator_type> span_gen_type;
                typedef agg::renderer_scanline_aa<renderer_base_pre, 
                                                  span_gen_type> renderer_type;

                span_gen_type sg(sa, rbuf_img(1), agg::rgba(0,0,0,0), interpolator, filter);
                renderer_type ri(rb_pre, sg);
                ras.add_path(tr);
                agg::render_scanlines(ras, sl, ri);
            }
            break;
        }

    }
Beispiel #20
0
void reproject_and_scale_raster(raster & target, raster const& source,
                      proj_transform const& prj_trans,
                      double offset_x, double offset_y,
                      unsigned mesh_size,
                      double filter_radius,
                      scaling_method_e scaling_method)
{
    CoordTransform ts(source.data_.width(), source.data_.height(),
                      source.ext_);
    CoordTransform tt(target.data_.width(), target.data_.height(),
                      target.ext_, offset_x, offset_y);
    unsigned i, j;
    unsigned mesh_nx = ceil(source.data_.width()/double(mesh_size)+1);
    unsigned mesh_ny = ceil(source.data_.height()/double(mesh_size)+1);

    ImageData<double> xs(mesh_nx, mesh_ny);
    ImageData<double> ys(mesh_nx, mesh_ny);

    // Precalculate reprojected mesh
    for(j=0; j<mesh_ny; j++) {
        for (i=0; i<mesh_nx; i++) {
            xs(i,j) = i*mesh_size;
            ys(i,j) = j*mesh_size;
            ts.backward(&xs(i,j), &ys(i,j));
        }
    }
    prj_trans.backward(xs.getData(), ys.getData(), NULL, mesh_nx*mesh_ny);

    // Initialize AGG objects
    typedef agg::pixfmt_rgba32 pixfmt;
    typedef pixfmt::color_type color_type;
    typedef agg::renderer_base<pixfmt> renderer_base;
    typedef agg::pixfmt_rgba32_pre pixfmt_pre;
    typedef agg::renderer_base<pixfmt_pre> renderer_base_pre;

    agg::rasterizer_scanline_aa<> rasterizer;
    agg::scanline_u8  scanline;
    agg::rendering_buffer buf((unsigned char*)target.data_.getData(),
                              target.data_.width(),
                              target.data_.height(),
                              target.data_.width()*4);
    pixfmt_pre pixf_pre(buf);
    renderer_base_pre rb_pre(pixf_pre);
    rasterizer.clip_box(0, 0, target.data_.width(), target.data_.height());
    agg::rendering_buffer buf_tile(
        (unsigned char*)source.data_.getData(),
        source.data_.width(),
        source.data_.height(),
        source.data_.width() * 4);

    pixfmt pixf_tile(buf_tile);

    typedef agg::image_accessor_clone<pixfmt> img_accessor_type;
    img_accessor_type ia(pixf_tile);

    agg::span_allocator<color_type> sa;

    // Initialize filter
    agg::image_filter_lut filter;
    switch(scaling_method)
    {
    case SCALING_NEAR: break;
    case SCALING_BILINEAR8: // TODO - impl this or remove?
    case SCALING_BILINEAR:
        filter.calculate(agg::image_filter_bilinear(), true); break;
    case SCALING_BICUBIC:
        filter.calculate(agg::image_filter_bicubic(), true); break;
    case SCALING_SPLINE16:
        filter.calculate(agg::image_filter_spline16(), true); break;
    case SCALING_SPLINE36:
        filter.calculate(agg::image_filter_spline36(), true); break;
    case SCALING_HANNING:
        filter.calculate(agg::image_filter_hanning(), true); break;
    case SCALING_HAMMING:
        filter.calculate(agg::image_filter_hamming(), true); break;
    case SCALING_HERMITE:
        filter.calculate(agg::image_filter_hermite(), true); break;
    case SCALING_KAISER:
        filter.calculate(agg::image_filter_kaiser(), true); break;
    case SCALING_QUADRIC:
        filter.calculate(agg::image_filter_quadric(), true); break;
    case SCALING_CATROM:
        filter.calculate(agg::image_filter_catrom(), true); break;
    case SCALING_GAUSSIAN:
        filter.calculate(agg::image_filter_gaussian(), true); break;
    case SCALING_BESSEL:
        filter.calculate(agg::image_filter_bessel(), true); break;
    case SCALING_MITCHELL:
        filter.calculate(agg::image_filter_mitchell(), true); break;
    case SCALING_SINC:
        filter.calculate(agg::image_filter_sinc(filter_radius), true); break;
    case SCALING_LANCZOS:
        filter.calculate(agg::image_filter_lanczos(filter_radius), true); break;
    case SCALING_BLACKMAN:
        filter.calculate(agg::image_filter_blackman(filter_radius), true); break;
    }

    // Project mesh cells into target interpolating raster inside each one
    for(j=0; j<mesh_ny-1; j++) {
        for (i=0; i<mesh_nx-1; i++) {
            double polygon[8] = {xs(i,j), ys(i,j),
                                 xs(i+1,j), ys(i+1,j),
                                 xs(i+1,j+1), ys(i+1,j+1),
                                 xs(i,j+1), ys(i,j+1)};
            tt.forward(polygon+0, polygon+1);
            tt.forward(polygon+2, polygon+3);
            tt.forward(polygon+4, polygon+5);
            tt.forward(polygon+6, polygon+7);

            rasterizer.reset();
            rasterizer.move_to_d(polygon[0]-1, polygon[1]-1);
            rasterizer.line_to_d(polygon[2]+1, polygon[3]-1);
            rasterizer.line_to_d(polygon[4]+1, polygon[5]+1);
            rasterizer.line_to_d(polygon[6]-1, polygon[7]+1);

            unsigned x0 = i * mesh_size;
            unsigned y0 = j * mesh_size;
            unsigned x1 = (i+1) * mesh_size;
            unsigned y1 = (j+1) * mesh_size;

            agg::trans_affine tr(polygon, x0, y0, x1, y1);
            if (tr.is_valid())
            {
                typedef agg::span_interpolator_linear<agg::trans_affine>
                    interpolator_type;
                interpolator_type interpolator(tr);

                if (scaling_method == SCALING_NEAR) {
                    typedef agg::span_image_filter_rgba_nn
                        <img_accessor_type, interpolator_type>
                        span_gen_type;
                    span_gen_type sg(ia, interpolator);
                    agg::render_scanlines_aa(rasterizer, scanline, rb_pre,
                                             sa, sg);
                } else {
                    typedef mapnik::span_image_resample_rgba_affine
                        <img_accessor_type> span_gen_type;
                    span_gen_type sg(ia, interpolator, filter);
                    agg::render_scanlines_aa(rasterizer, scanline, rb_pre,
                                             sa, sg);
                }
            }

        }
    }
}
Beispiel #21
0
Ephemeris* PlatformPosition::Interpolate(JSDDateTime date)
{
   const double JOURCIVIL_LENGTH = 86400.0 ;
   Ephemeris* ephem = NULL;
   if (_nbrData<=1)
   {
      std::cout << "a..." << std::endl;
      ephem = NULL;
   }
   else
   {
      /*
       * The first element of the list is cloned to ensure that the output ephemeris is expressed in the same coordinate system as input ones
       */
      ephem = _data[0]->Clone();

      /* NORMAL CASE */
      /*------------*/
      double * x = new double[_nbrData];
      double * y = new double[_nbrData];
      double * yd = new double[_nbrData];
      double dt = 0.0;
      //double d;

      x[0] = 0.0 ;
      for (int i = 1 ; i < _nbrData ; i++)
      {
         x[i] =   (_data[i]->get_date().get_day0hTU().get_julianDate() - _data[0]->get_date().get_day0hTU().get_julianDate())
            * JOURCIVIL_LENGTH
            + _data[i]->get_date().get_second()   - _data[0]->get_date().get_second()
            + _data[i]->get_date().get_decimal()     - _data[0]->get_date().get_decimal();
      }

      if (ephem != NULL)
      {
         ephem->set_date(date);

         dt =  (date.get_day0hTU().get_julianDate() - _data[0]->get_date().get_day0hTU().get_julianDate()) * JOURCIVIL_LENGTH
            + date.get_second()   - _data[0]->get_date().get_second()
            + date.get_decimal()     - _data[0]->get_date().get_decimal();

         /* Computation by Everett  */
         /*---------------------*/
         double pos[3];
         double vit[3];
         for (int j = 0 ; j < 3 ; j++)
         {
            for (int i = 0 ; i < _nbrData ; i++)
            {
               y[i] = _data[i]->get_position()[j] ;
               yd[i] = _data[i]->get_vitesse()[j] ;
            }
            HermiteInterpolator interpolator(_nbrData,x,y,yd);
            interpolator.Interpolate(dt, pos[j], vit[j]);
         }
         ephem->set_position(pos);
         ephem->set_vitesse(vit);

      }

      delete[] x;
      delete[] y;
      delete[] yd;

   }
   return ephem;
}
void CellByCellMetropolisSampling::generate_particles( const kvs::StructuredVolumeObject* volume )
{
    kvs::TrilinearInterpolator interpolator( volume );

    kvs::CellByCellSampling::ParticleDensityMap density_map;
    density_map.setSamplingStep( m_sampling_step );
    density_map.setSubpixelLevel( m_subpixel_level );
    density_map.attachCamera( m_camera );
    density_map.attachObject( volume );
    density_map.create( BaseClass::transferFunction().opacityMap() );

    // Generate particles for each cell.
    kvs::CellByCellSampling::GridSampler<T> sampler( &interpolator, &density_map );
    const kvs::Vec3ui ncells( volume->resolution() - kvs::Vec3ui::All(1) );
    const kvs::ColorMap color_map( BaseClass::transferFunction().colorMap() );
    for ( kvs::UInt32 z = 0; z < ncells.z(); ++z )
    {
        for ( kvs::UInt32 y = 0; y < ncells.y(); ++y )
        {
            for ( kvs::UInt32 x = 0; x < ncells.x(); ++x )
            {
                sampler.bind( kvs::Vec3ui( x, y, z ) );

                const size_t nparticles = sampler.numberOfParticles();
                const size_t max_loops = nparticles * 10;
                if ( nparticles == 0 ) continue;

                size_t nduplications = 0;
                size_t counter = 0;
                kvs::Real32 density = sampler.sample( max_loops );
                while ( counter < nparticles )
                {
                    // Trial point.
                    const kvs::Real32 density_trial = sampler.trySample();
                    const kvs::Real32 ratio = density_trial / density;
                    if ( ratio >= 1.0f )
                    {
                        sampler.acceptTrial( color_map );
                        density = density_trial;
                        counter++;
                    }
                    else
                    {
                        if ( ratio >= kvs::CellByCellSampling::RandomNumber() )
                        {
                            sampler.acceptTrial( color_map );
                            density = density_trial;
                            counter++;
                        }
                        else
                        {
#ifdef DUPLICATION
                            sampler.accept( color_map );
                            counter++;
#else
                            if ( ++nduplications > max_loops ) { break; }
#endif
                        }
                    }
                } // end of 'paricle' while-loop
            } // end of 'x' loop
        } // end of 'y' loop
    } // end of 'z' loop

    SuperClass::setCoords( sampler.particles().coords() );
    SuperClass::setColors( sampler.particles().colors() );
    SuperClass::setNormals( sampler.particles().normals() );
    SuperClass::setSize( 1.0f );
}
Beispiel #23
0
void scale_image_agg(T & target, T const& source, scaling_method_e scaling_method,
                     double image_ratio_x, double image_ratio_y, double x_off_f, double y_off_f,
                     double filter_factor)
{
    // "the image filters should work namely in the premultiplied color space"
    // http://old.nabble.com/Re:--AGG--Basic-image-transformations-p1110665.html
    // "Yes, you need to use premultiplied images only. Only in this case the simple weighted averaging works correctly in the image fitering."
    // http://permalink.gmane.org/gmane.comp.graphics.agg/3443
    using image_type = T;
    using pixel_type = typename image_type::pixel_type;
    using pixfmt_pre = typename detail::agg_scaling_traits<image_type>::pixfmt_pre;
    using color_type = typename detail::agg_scaling_traits<image_type>::color_type;
    using img_src_type = typename detail::agg_scaling_traits<image_type>::img_src_type;
    using interpolator_type = typename detail::agg_scaling_traits<image_type>::interpolator_type;
    using renderer_base_pre = agg::renderer_base<pixfmt_pre>;
    constexpr std::size_t pixel_size = sizeof(pixel_type);

    // define some stuff we'll use soon
    agg::rasterizer_scanline_aa<> ras;
    agg::scanline_u8 sl;
    agg::span_allocator<color_type> sa;

    // initialize source AGG buffer
    agg::rendering_buffer rbuf_src(const_cast<unsigned char*>(source.bytes()),
                                   source.width(), source.height(), source.width() * pixel_size);
    pixfmt_pre pixf_src(rbuf_src);

    img_src_type img_src(pixf_src);

    // initialize destination AGG buffer (with transparency)
    agg::rendering_buffer rbuf_dst(target.bytes(), target.width(), target.height(), target.width() * pixel_size);
    pixfmt_pre pixf_dst(rbuf_dst);
    renderer_base_pre rb_dst_pre(pixf_dst);

    // create a scaling matrix
    agg::trans_affine img_mtx;
    img_mtx /= agg::trans_affine_scaling(image_ratio_x, image_ratio_y);

    // create a linear interpolator for our scaling matrix
    interpolator_type interpolator(img_mtx);
    // draw an anticlockwise polygon to render our image into
    double scaled_width = target.width();
    double scaled_height = target.height();
    ras.reset();
    ras.move_to_d(x_off_f,                y_off_f);
    ras.line_to_d(x_off_f + scaled_width, y_off_f);
    ras.line_to_d(x_off_f + scaled_width, y_off_f + scaled_height);
    ras.line_to_d(x_off_f,                y_off_f + scaled_height);

    if (scaling_method == SCALING_NEAR)
    {
        using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_filter;
        span_gen_type sg(img_src, interpolator);
        agg::render_scanlines_aa(ras, sl, rb_dst_pre, sa, sg);
    }
    else
    {
        using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_resample_affine;
        agg::image_filter_lut filter;
        detail::set_scaling_method(filter, scaling_method, filter_factor);
        span_gen_type sg(img_src, interpolator, filter);
        agg::render_scanlines_aa(ras, sl, rb_dst_pre, sa, sg);
    }

}
Beispiel #24
0
void qAnimationDlg::preview()
{
	//we'll take the rendering time into account!
	QElapsedTimer timer;
	timer.start();

	setEnabled(false);

	size_t vp1 = previewFromSelectedCheckBox->isChecked() ? static_cast<size_t>(getCurrentStepIndex()) : 0;

	//count the total number of frames
	int frameCount = countFrames(loopCheckBox->isChecked() ? 0 : vp1);
	int fps = fpsSpinBox->value();

	//show progress dialog
	QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
	progressDialog.setWindowTitle("Preview");
	progressDialog.show();
	progressDialog.setModal(true);
	progressDialog.setAutoClose(false);
	QApplication::processEvents();

	assert(stepSelectionList->count() >= m_videoSteps.size());

	int frameIndex = 0;
	size_t vp2 = 0;
	while (getNextSegment(vp1, vp2))
	{
		Step& step1 = m_videoSteps[vp1];
		Step& step2 = m_videoSteps[vp2];

		//theoretical waiting time per frame
		qint64 delay_ms = static_cast<int>(1000 * step1.duration_sec / fps);
		int frameCount = static_cast<int>( fps * step1.duration_sec );

		ViewInterpolate interpolator(step1.viewport, step2.viewport);
		interpolator.setMaxStep(frameCount);
		cc2DViewportObject currentParams;
		while ( interpolator.nextView( currentParams ) )
		{
			timer.restart();
			applyViewport ( &currentParams );
			qint64 dt_ms = timer.elapsed();

			progressDialog.setValue(++frameIndex);
			QApplication::processEvents();
			if (progressDialog.wasCanceled())
			{
				break;
			}

			//remaining time
			if (dt_ms < delay_ms)
			{
				int wait_ms = static_cast<int>(delay_ms - dt_ms);
#if defined(CC_WINDOWS)
				::Sleep( wait_ms );
#else
				usleep( wait_ms * 1000 );
#endif
			}
		}
		if (progressDialog.wasCanceled())
		{
			break;
		}

		if (vp2 == 0)
		{
			assert(loopCheckBox->isChecked());
			frameIndex = 0;
		}
		vp1 = vp2;
	}

	//reset view
	onCurrentStepChanged(getCurrentStepIndex());

	setEnabled(true);
}
int main(void)
{
  /***READ SCALE FACTOR DATA AND PREPARE OBJECTS FOR INTERPOLATION ***/
  int i;            //For array manipulation
  
  /*Pointer to scale_factor.data file*/
  FILE *frw;        
  frw = fopen("scale_factor.dat","r");

  /*Variables and arrays to read the data*/
  double cosmictime[NLINESFRW], conftime, scale_factor[NLINESFRW], der_scale_factor[NLINESFRW];

  /*Reading the data*/
  for(i=0; i<NLINESFRW; i++)
    {
      fscanf(frw,"%lf %lf %lf %lf", &cosmictime[i], &conftime, &scale_factor[i], &der_scale_factor[i]);
    }

  /*Free space in memory*/
  fclose(frw);
  
  /*** Initializes objects for interpolation. 1 is for interpolation of scale factor, 2 is for interpolation of derivative of scale factor ***/

  /*Allocate space in memory*/
  gsl_interp_accel *acc1 = gsl_interp_accel_alloc();  //Acceleration type object (for index lookup)
  gsl_interp_accel *acc2 = gsl_interp_accel_alloc();
  gsl_spline *spline1 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW);  //Spline type object (define interpolation type and space in memory, works for both)
  gsl_spline *spline2 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW);

  /*Initializes objects for interpolation*/
  gsl_spline_init(spline1, cosmictime, scale_factor, NLINESFRW);  //Initializes spline object for data cosmictime, scale_factor of size NLINES
  gsl_spline_init(spline2, cosmictime, der_scale_factor, NLINESFRW);  //Initializes spline object for data cosmictime, der_scale_factor of size NLINES

  /************************************************************************************/
  
  /***SOLVES GEODESIC EQUATIONS FOR PERTURBED FRW UNIVERSE WITH STATIC PLUMMER POTENTIAL ***/

  /*Initial conditions*/
  mydbl ti = 7.0 ,x0, r = -500.0, p0 = 1.0e-3, pr, lambda = 0.0, energy1, energy, v, difft, difference;
  double difftfrw, aem, aobs;
  x0 = C*ti;
  aem = interpolator(spline1, (double)(1.0*ti), acc1);
  pr = condition_factor(r, aem)*p0;
  energy1 = C*energy_factor(r)*p0;
  v = violation(r, p0, pr, aem);
  difft = (energy1 - energy1)/energy1;
  difftfrw = (aem/aem) - 1.0;
  difference = difft - (mydbl)(1.0*difftfrw);
  

  /*Pointer to file where solution of differential equation will be saved.*/
  FILE *geodesic;
  geodesic = fopen("geodesic_solution.dat","w");

  /*Write line of initial values in file*/
  fprintf(geodesic, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le\n", lambda, x0, r, p0, pr, energy1, v, difft, difftfrw, difference);

  long long int ii;

  /*Solution of the differential equation*/
  for(ii=0; ii< NSTEPS; ii++)
    {
      runge_kutta_4(spline1, acc1, spline2, acc2, &x0, &r, &p0, &pr, &lambda);
      if((ii%(NSTEPS/NLINES)) == 0)
	{
	  energy = C*energy_factor(r)*p0;
	  difft = (energy - energy1)/energy1;
	  ti = x0/C;
	  aobs = interpolator(spline1, (double)(1.0*ti), acc1);
	  v = violation(r, p0, pr, aobs);
	  difftfrw = (aem/aobs) - 1.0;
	  difference = difft - (mydbl)(1.0*difftfrw);
	  fprintf(geodesic, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le\n", lambda, x0, r, p0, pr, energy, v, difft, difftfrw, difference);
	} 
    }

  /************************************************************************************/

  /*** Releasing all used space in memory ***/
  fclose(geodesic); //Close file storing the results
  gsl_spline_free(spline1);  //Free memory of spline object
  gsl_spline_free(spline2);
  gsl_interp_accel_free(acc1);  //Free memory of accel object
  gsl_interp_accel_free(acc2);
}
Beispiel #26
0
    void render_raster_marker(agg::trans_affine const& marker_tr,
                              double opacity)
    {
        using pixfmt_pre = agg::pixfmt_rgba32_pre;
        agg::scanline_u8 sl_;
        double width  = src_.width();
        double height = src_.height();
        if (std::fabs(1.0 - scale_factor_) < 0.001
            && (std::fabs(1.0 - marker_tr.sx) < agg::affine_epsilon)
            && (std::fabs(0.0 - marker_tr.shy) < agg::affine_epsilon)
            && (std::fabs(0.0 - marker_tr.shx) < agg::affine_epsilon)
            && (std::fabs(1.0 - marker_tr.sy) < agg::affine_epsilon))
        {
            agg::rendering_buffer src_buffer((unsigned char *)src_.getBytes(),src_.width(),src_.height(),src_.width() * 4);
            pixfmt_pre pixf_mask(src_buffer);
            if (snap_to_pixels_)
            {
                renb_.blend_from(pixf_mask,
                                 0,
                                 std::floor(marker_tr.tx + .5),
                                 std::floor(marker_tr.ty + .5),
                                 unsigned(255*opacity));
            }
            else
            {
                renb_.blend_from(pixf_mask,
                                 0,
                                 marker_tr.tx,
                                 marker_tr.ty,
                                 unsigned(255*opacity));
            }
        }
        else
        {
            using img_accessor_type = agg::image_accessor_clone<pixfmt_pre>;
            using interpolator_type = agg::span_interpolator_linear<>;
            //using span_gen_type = agg::span_image_filter_rgba_2x2<img_accessor_type,interpolator_type>;
            using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>;
            using renderer_type = agg::renderer_scanline_aa_alpha<renderer_base,
                                                                  agg::span_allocator<color_type>,
                                                                  span_gen_type>;

            double p[8];
            p[0] = 0;     p[1] = 0;
            p[2] = width; p[3] = 0;
            p[4] = width; p[5] = height;
            p[6] = 0;     p[7] = height;
            marker_tr.transform(&p[0], &p[1]);
            marker_tr.transform(&p[2], &p[3]);
            marker_tr.transform(&p[4], &p[5]);
            marker_tr.transform(&p[6], &p[7]);
            agg::span_allocator<color_type> sa;
            agg::image_filter_lut filter;
            filter.calculate(agg::image_filter_bilinear(), true);
            agg::rendering_buffer marker_buf((unsigned char *)src_.getBytes(),
                                             src_.width(),
                                             src_.height(),
                                             src_.width()*4);
            pixfmt_pre pixf(marker_buf);
            img_accessor_type ia(pixf);
            agg::trans_affine final_tr(p, 0, 0, width, height);
            if (snap_to_pixels_)
            {
                final_tr.tx = std::floor(final_tr.tx+.5);
                final_tr.ty = std::floor(final_tr.ty+.5);
            }
            interpolator_type interpolator(final_tr);
            span_gen_type sg(ia, interpolator, filter);
            renderer_type rp(renb_,sa, sg, unsigned(opacity*255));
            ras_.move_to_d(p[0],p[1]);
            ras_.line_to_d(p[2],p[3]);
            ras_.line_to_d(p[4],p[5]);
            ras_.line_to_d(p[6],p[7]);
            agg::render_scanlines(ras_, sl_, rp);
        }
    }
Beispiel #27
0
    virtual void on_draw()
    {
        pixfmt pixf(rbuf_window());
        renderer_base rb(pixf);

        rb.clear(agg::rgba(1.0, 1.0, 1.0));
        rb.copy_from(rbuf_img(0), 0, 110, 35);

        agg::rasterizer_scanline_aa<> ras;
        agg::scanline_u8 sl;

        agg::rendering_buffer img_rbuf(g_image, 4, 4, 4*4);

        double para[] = { 200, 40, 200+300, 40, 200+300, 40+300, 200, 40+300 };
        agg::trans_affine img_mtx(para, 0,0,4,4);

        typedef agg::span_interpolator_linear<> interpolator_type;
        interpolator_type interpolator(img_mtx);
        agg::span_allocator<agg::rgba8> sa;

        pixfmt img_pixf(img_rbuf);
        typedef agg::image_accessor_clone<pixfmt> img_source_type;
        img_source_type source(img_pixf);

        ras.reset();
        ras.move_to_d(para[0], para[1]);
        ras.line_to_d(para[2], para[3]);
        ras.line_to_d(para[4], para[5]);
        ras.line_to_d(para[6], para[7]);

        switch(m_filters.cur_item())
        {
        case 0:
        {
            typedef agg::span_image_filter_rgba_nn<img_source_type,
                    interpolator_type> span_gen_type;

            span_gen_type sg(source, interpolator);
            agg::render_scanlines_aa(ras, sl, rb, sa, sg);
        }
        break;

        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
        case 11:
        case 12:
        case 13:
        case 14:
        case 15:
        case 16:
        {
            agg::image_filter_lut filter;
            bool norm = m_normalize.status();
            switch(m_filters.cur_item())
            {
            case 1:
                filter.calculate(agg::image_filter_bilinear(),                 norm);
                break;
            case 2:
                filter.calculate(agg::image_filter_bicubic(),                  norm);
                break;
            case 3:
                filter.calculate(agg::image_filter_spline16(),                 norm);
                break;
            case 4:
                filter.calculate(agg::image_filter_spline36(),                 norm);
                break;
            case 5:
                filter.calculate(agg::image_filter_hanning(),                  norm);
                break;
            case 6:
                filter.calculate(agg::image_filter_hamming(),                  norm);
                break;
            case 7:
                filter.calculate(agg::image_filter_hermite(),                  norm);
                break;
            case 8:
                filter.calculate(agg::image_filter_kaiser(),                   norm);
                break;
            case 9:
                filter.calculate(agg::image_filter_quadric(),                  norm);
                break;
            case 10:
                filter.calculate(agg::image_filter_catrom(),                   norm);
                break;
            case 11:
                filter.calculate(agg::image_filter_gaussian(),                 norm);
                break;
            case 12:
                filter.calculate(agg::image_filter_bessel(),                   norm);
                break;
            case 13:
                filter.calculate(agg::image_filter_mitchell(),                 norm);
                break;
            case 14:
                filter.calculate(agg::image_filter_sinc(m_radius.value()),     norm);
                break;
            case 15:
                filter.calculate(agg::image_filter_lanczos(m_radius.value()),  norm);
                break;
            case 16:
                filter.calculate(agg::image_filter_blackman(m_radius.value()), norm);
                break;
            }

            typedef agg::span_image_filter_rgba<img_source_type,
                    interpolator_type> span_gen_type;

            span_gen_type sg(source, interpolator, filter);
            agg::render_scanlines_aa(ras, sl, rb, sa, sg);

            agg::gamma_lut<agg::int8u, agg::int8u, 8, 8> gamma(m_gamma.value());
            pixf.apply_gamma_inv(gamma);

            double x_start = 5.0;
            double x_end   = 195.0;
            double y_start = 235.0;
            double y_end   = initial_height() - 5.0;
            double x_center = (x_start + x_end) / 2;

            agg::path_storage p;
            agg::conv_stroke<agg::path_storage> stroke(p);
            stroke.width(0.8);

            unsigned i;
            for(i = 0; i <= 16; i++)
            {
                double x = x_start + (x_end - x_start) * i / 16.0;
                p.remove_all();
                p.move_to(x+0.5, y_start);
                p.line_to(x+0.5, y_end);
                ras.add_path(stroke);
                agg::render_scanlines_aa_solid(ras, sl, rb,
                                               agg::rgba8(0, 0, 0, i == 8 ? 255 : 100));
            }

            double ys = y_start + (y_end - y_start) / 6.0;
            p.remove_all();
            p.move_to(x_start, ys);
            p.line_to(x_end,   ys);
            ras.add_path(stroke);
            agg::render_scanlines_aa_solid(ras, sl, rb, agg::rgba8(0, 0, 0));

            double radius = filter.radius();
            unsigned n = unsigned(radius * 256 * 2);
            double dx = (x_end - x_start) * radius / 8.0;
            double dy = y_end - ys;

            const agg::int16* weights = filter.weight_array();
            double xs = (x_end + x_start)/2.0 - (filter.diameter() * (x_end - x_start) / 32.0);
            unsigned nn = filter.diameter() * 256;
            p.remove_all();
            p.move_to(xs+0.5, ys + dy * weights[0] / agg::image_filter_scale);
            for(i = 1; i < nn; i++)
            {
                p.line_to(xs + dx * i / n + 0.5,
                          ys + dy * weights[i] / agg::image_filter_scale);
            }
            ras.add_path(stroke);
            agg::render_scanlines_aa_solid(ras, sl, rb, agg::rgba8(100, 0, 0));
        }
        break;
        }

        agg::render_ctrl(ras, sl, rb, m_gamma);
        if(m_filters.cur_item() >= 14)
        {
            agg::render_ctrl(ras, sl, rb, m_radius);
        }
        agg::render_ctrl(ras, sl, rb, m_filters);
        agg::render_ctrl(ras, sl, rb, m_normalize);
    }
Beispiel #28
0
// _DrawBitmap32
void
Painter::_DrawBitmap32(const agg::rendering_buffer& srcBuffer,
					   BRect actualBitmapRect, BRect bitmapRect, BRect viewRect) const
{
typedef agg::span_allocator<agg::rgba8> span_alloc_type;
typedef agg::span_interpolator_linear<> interpolator_type;
typedef agg::span_image_filter_rgba32_nn<agg::order_bgra32,
										 interpolator_type> span_gen_type;
typedef agg::renderer_scanline_aa<renderer_base, span_gen_type> image_renderer_type;

	if (bitmapRect.IsValid() && bitmapRect.Intersects(actualBitmapRect)
		&& viewRect.IsValid()) {

		// compensate for the lefttop offset the actualBitmapRect might have
// NOTE: I have no clue why enabling the next call gives a wrong result!
// According to the BeBook, bitmapRect is supposed to be in native
// bitmap space!
//		bitmapRect.OffsetBy(-actualBitmapRect.left, -actualBitmapRect.top);
		actualBitmapRect.OffsetBy(-actualBitmapRect.left, -actualBitmapRect.top);

		// calculate the scaling
		double xScale = (viewRect.Width() + 1) / (bitmapRect.Width() + 1);
		double yScale = (viewRect.Height() + 1) / (bitmapRect.Height() + 1);

		// constrain rect to passed bitmap bounds
		// and transfer the changes to the viewRect
		if (bitmapRect.left < actualBitmapRect.left) {
			float diff = actualBitmapRect.left - bitmapRect.left;
			viewRect.left += diff * xScale;
			bitmapRect.left = actualBitmapRect.left;
		}
		if (bitmapRect.top < actualBitmapRect.top) {
			float diff = actualBitmapRect.top - bitmapRect.top;
			viewRect.top += diff;
			bitmapRect.top = actualBitmapRect.top;
		}
		if (bitmapRect.right > actualBitmapRect.right) {
			float diff = bitmapRect.right - actualBitmapRect.right;
			viewRect.right -= diff;
			bitmapRect.right = actualBitmapRect.right;
		}
		if (bitmapRect.bottom > actualBitmapRect.bottom) {
			float diff = bitmapRect.right - actualBitmapRect.bottom;
			viewRect.bottom -= diff;
			bitmapRect.bottom = actualBitmapRect.bottom;
		}

		float xOffset = viewRect.left - (bitmapRect.left * xScale);
		float yOffset = viewRect.top - (bitmapRect.top * yScale);

		agg::trans_affine srcMatrix;
//		srcMatrix *= agg::trans_affine_translation(-actualBitmapRect.left, -actualBitmapRect.top);
		srcMatrix *= agg::trans_affine_scaling(fScale, fScale);
		srcMatrix *= agg::trans_affine_translation(fOrigin.x, fOrigin.y);

		agg::trans_affine imgMatrix;
		imgMatrix *= agg::trans_affine_scaling(xScale, yScale);
		imgMatrix *= agg::trans_affine_translation(xOffset, yOffset);
		imgMatrix *= agg::trans_affine_scaling(fScale, fScale);
		imgMatrix *= agg::trans_affine_translation(fOrigin.x, fOrigin.y);
		imgMatrix.invert();
		
		span_alloc_type sa;
		interpolator_type interpolator(imgMatrix);

		span_gen_type sg(sa, srcBuffer, agg::rgba(0, 0, 0, 0), interpolator);

		image_renderer_type ri(*fBaseRenderer, sg);

		agg::rasterizer_scanline_aa<> pf;
		agg::scanline_u8 sl;

		// path encloses image
		agg::path_storage path;
		path.move_to(viewRect.left, viewRect.top);
		path.line_to(viewRect.right + 1, viewRect.top);
		path.line_to(viewRect.right + 1, viewRect.bottom + 1);
		path.line_to(viewRect.left, viewRect.bottom + 1);
		path.close_polygon();

		agg::conv_transform<agg::path_storage> tr(path, srcMatrix);

		pf.add_path(tr);
		agg::render_scanlines(pf, sl, ri);
	}
}
Beispiel #29
0
void qAnimationDlg::render()
{
	if (!m_view3d)
	{
		assert(false);
		return;
	}
	QString outputFilename = outputFileLineEdit->text();

	//save to persistent settings
	{
		QSettings settings;
		settings.beginGroup("qAnimation");
		settings.setValue("filename", outputFilename);
		settings.endGroup();
	}

	setEnabled(false);

	//count the total number of frames
	int frameCount = countFrames(0);
	int fps = fpsSpinBox->value();
	int superRes = superResolutionSpinBox->value();

	//show progress dialog
	QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
	progressDialog.setWindowTitle("Render");
	progressDialog.show();
	QApplication::processEvents();

#ifdef QFFMPEG_SUPPORT
	//get original viewport size
	QSize originalViewSize = m_view3d->size();

	//hack: as the encoder requires that the video dimensions are multiples of 8, we resize the window a little bit...
	{
		//find the nearest multiples of 8
		QSize customSize = originalViewSize;
		if (originalViewSize.width() % 8 || originalViewSize.height() % 8)
		{
			if (originalViewSize.width() % 8)
				customSize.setWidth((originalViewSize.width() / 8 + 1) * 8);
			if (originalViewSize.height() % 8)
				customSize.setHeight((originalViewSize.height() / 8 + 1) * 8);
			m_view3d->resize(customSize);
			QApplication::processEvents();
		}
	}

	int bitrate = bitrateSpinBox->value() * 1024;
	int gop = fps;
	QVideoEncoder encoder(outputFilename, m_view3d->width(), m_view3d->height(), bitrate, gop, static_cast<unsigned>(fpsSpinBox->value()));
	QString errorString;
	if (!encoder.open(&errorString))
	{
		QMessageBox::critical(this, "Error", QString("Failed to open file for output: %1").arg(errorString));
		setEnabled(true);
		return;
	}
#endif

	bool lodWasEnabled = m_view3d->isLODEnabled();
	m_view3d->setLODEnabled(false);

	int frameIndex = 0;
	bool success = true;
	size_t vp1 = 0, vp2 = 0;
	while (getNextSegment(vp1, vp2))
	{
		Step& step1 = m_videoSteps[vp1];
		Step& step2 = m_videoSteps[vp2];

		ViewInterpolate interpolator(step1.viewport, step2.viewport);
		int frameCount = static_cast<int>( fps * step1.duration_sec );
		interpolator.setMaxStep(frameCount);

		cc2DViewportObject current_params;
		while ( interpolator.nextView( current_params ) )
		{
			applyViewport ( &current_params );

			//render to image
			QImage image = m_view3d->renderToImage(superRes, false, false, true );

			if (image.isNull())
			{
				QMessageBox::critical(this, "Error", "Failed to grab the screen!");
				success = false;
				break;
			}

			if (superRes > 1)
			{
				image = image.scaled(image.width()/superRes, image.height()/superRes, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
			}

#ifdef QFFMPEG_SUPPORT
			if (!encoder.encodeImage(image, frameIndex, &errorString))
			{
				QMessageBox::critical(this, "Error", QString("Failed to encode frame #%1: %2").arg(frameIndex+1).arg(errorString));
				success = false;
				break;
			}
#else
			QString filename = QString("frame_%1.png").arg(frameIndex, 6, 10, QChar('0'));
			QString fullPath = QDir(outputFilename).filePath(filename);
			if (!image.save(fullPath))
			{
				QMessageBox::critical(this, "Error", QString("Failed to save frame #%1").arg(frameIndex+1));
				success = false;
				break;
			}
#endif
			++frameIndex;
			progressDialog.setValue(frameIndex);
			QApplication::processEvents();
			if (progressDialog.wasCanceled())
			{
				QMessageBox::warning(this, "Warning", QString("Process has been cancelled"));
				success = false;
				break;
			}
		}

		if (!success)
		{
			break;
		}

		if (vp2 == 0)
		{
			//stop loop here!
			break;
		}
		vp1 = vp2;
	}

	m_view3d->setLODEnabled(lodWasEnabled);

#ifdef QFFMPEG_SUPPORT
	encoder.close();

	//hack: restore original size
	m_view3d->resize(originalViewSize);
	QApplication::processEvents();
#endif
	
	progressDialog.hide();
	QApplication::processEvents();

	if (success)
	{
		QMessageBox::information(this, "Job done", "The animation has been saved successfully");
	}

	setEnabled(true);
}
Beispiel #30
0
  //------------------------------------------------------------------------
  virtual void on_draw() {
    typedef agg::renderer_base<pixfmt> renderer_base;
    typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid;

    pixfmt pixf(rbuf_window());
    pixfmt pixf_img(rbuf_img(0));
    renderer_base rb(pixf);
    renderer_solid rs(rb);

    rb.clear(agg::rgba(1.0, 1.0, 1.0));

    agg::trans_affine image_mtx;
    agg::trans_affine polygon_mtx;

    polygon_mtx *= agg::trans_affine_translation(-m_polygon_cx, -m_polygon_cy);
    polygon_mtx *=
        agg::trans_affine_rotation(m_polygon_angle.value() * agg::pi / 180.0);
    polygon_mtx *= agg::trans_affine_scaling(m_polygon_scale.value());
    polygon_mtx *= agg::trans_affine_translation(m_polygon_cx, m_polygon_cy);

    switch (m_example.cur_item()) {
      default:
      case 0:
        // --------------(Example 0, Identity matrix)
        break;

      case 1:
        // --------------(Example 1)
        image_mtx *=
            agg::trans_affine_translation(-m_image_center_x, -m_image_center_y);
        image_mtx *= agg::trans_affine_rotation(m_polygon_angle.value() *
                                                agg::pi / 180.0);
        image_mtx *= agg::trans_affine_scaling(m_polygon_scale.value());
        image_mtx *= agg::trans_affine_translation(m_polygon_cx, m_polygon_cy);
        image_mtx.invert();
        break;

      case 2:
        // --------------(Example 2)
        image_mtx *=
            agg::trans_affine_translation(-m_image_center_x, -m_image_center_y);
        image_mtx *=
            agg::trans_affine_rotation(m_image_angle.value() * agg::pi / 180.0);
        image_mtx *= agg::trans_affine_scaling(m_image_scale.value());
        image_mtx *= agg::trans_affine_translation(m_image_cx, m_image_cy);
        image_mtx.invert();
        break;

      case 3:
        // --------------(Example 3)
        image_mtx *=
            agg::trans_affine_translation(-m_image_center_x, -m_image_center_y);
        image_mtx *=
            agg::trans_affine_rotation(m_image_angle.value() * agg::pi / 180.0);
        image_mtx *= agg::trans_affine_scaling(m_image_scale.value());
        image_mtx *= agg::trans_affine_translation(m_polygon_cx, m_polygon_cy);
        image_mtx.invert();
        break;

      case 4:
        // --------------(Example 4)
        image_mtx *= agg::trans_affine_translation(-m_image_cx, -m_image_cy);
        image_mtx *= agg::trans_affine_rotation(m_polygon_angle.value() *
                                                agg::pi / 180.0);
        image_mtx *= agg::trans_affine_scaling(m_polygon_scale.value());
        image_mtx *= agg::trans_affine_translation(m_polygon_cx, m_polygon_cy);
        image_mtx.invert();
        break;

      case 5:
        // --------------(Example 5)
        image_mtx *=
            agg::trans_affine_translation(-m_image_center_x, -m_image_center_y);
        image_mtx *=
            agg::trans_affine_rotation(m_image_angle.value() * agg::pi / 180.0);
        image_mtx *= agg::trans_affine_rotation(m_polygon_angle.value() *
                                                agg::pi / 180.0);
        image_mtx *= agg::trans_affine_scaling(m_image_scale.value());
        image_mtx *= agg::trans_affine_scaling(m_polygon_scale.value());
        image_mtx *= agg::trans_affine_translation(m_image_cx, m_image_cy);
        image_mtx.invert();
        break;

      case 6:
        // --------------(Example 6)
        image_mtx *= agg::trans_affine_translation(-m_image_cx, -m_image_cy);
        image_mtx *=
            agg::trans_affine_rotation(m_image_angle.value() * agg::pi / 180.0);
        image_mtx *= agg::trans_affine_scaling(m_image_scale.value());
        image_mtx *= agg::trans_affine_translation(m_image_cx, m_image_cy);
        image_mtx.invert();
        break;
    }

    typedef agg::span_interpolator_linear<> interpolator_type;
    interpolator_type interpolator(image_mtx);
    agg::span_allocator<color_type> sa;

    // "hardcoded" bilinear filter
    //------------------------------------------
    typedef agg::span_image_filter_rgba_bilinear_clip<pixfmt, interpolator_type>
        span_gen_type;
    span_gen_type sg(pixf_img, agg::rgba(1, 1, 1), interpolator);
    //------------------------------------------

    agg::rasterizer_scanline_aa<> ras;
    agg::scanline_u8 sl;
    agg::path_storage ps;
    create_star(ps);

    agg::conv_transform<agg::path_storage> tr(ps, polygon_mtx);

    ras.add_path(tr);
    agg::render_scanlines_aa(ras, sl, rb, sa, sg);

    agg::ellipse e1(m_image_cx, m_image_cy, 5, 5, 20);
    agg::ellipse e2(m_image_cx, m_image_cy, 2, 2, 20);
    agg::conv_stroke<agg::ellipse> c1(e1);

    rs.color(agg::rgba(0.7, 0.8, 0));
    ras.add_path(e1);
    agg::render_scanlines(ras, sl, rs);

    rs.color(agg::rgba(0, 0, 0));
    ras.add_path(c1);
    agg::render_scanlines(ras, sl, rs);

    ras.add_path(e2);
    agg::render_scanlines(ras, sl, rs);

    agg::render_ctrl(ras, sl, rb, m_polygon_angle);
    agg::render_ctrl(ras, sl, rb, m_polygon_scale);
    agg::render_ctrl(ras, sl, rb, m_image_angle);
    agg::render_ctrl(ras, sl, rb, m_image_scale);
    agg::render_ctrl(ras, sl, rb, m_rotate_polygon);
    agg::render_ctrl(ras, sl, rb, m_rotate_image);
    agg::render_ctrl(ras, sl, rb, m_example);
  }