Пример #1
0
void KviTalWizard::setCurrentPage(KviTalWizardPageData * pData)
{
    m_p->pCurrentPage = pData;

    bool bCancelEnabled = true;
    bool bNextEnabled = false;
    bool bBackEnabled = false;
    bool bHelpEnabled = false;
    bool bFinishEnabled = false;

    QString szTitle;
    QString szSteps;

    bool bHaveNextPage = false;
    bool bHavePrevPage = false;

    if(pData)
    {
        bHavePrevPage = m_p->findPrevEnabledPage(pData->pWidget);
        bHaveNextPage = m_p->findNextEnabledPage(pData->pWidget);

        bNextEnabled = (pData->iEnableFlags & KviTalWizardPageData::EnableNext) && bHaveNextPage;
        bBackEnabled = (pData->iEnableFlags & KviTalWizardPageData::EnableBack) && bHavePrevPage;

        bCancelEnabled = (pData->iEnableFlags & KviTalWizardPageData::EnableCancel);
        bFinishEnabled = (pData->iEnableFlags & KviTalWizardPageData::EnableFinish);

        bHelpEnabled = (pData->iEnableFlags & KviTalWizardPageData::EnableHelp);

        m_p->pWidgetStack->setCurrentWidget(pData->pWidget);

        szTitle = "<b>";
        szTitle += pData->szTitle;
        szTitle += "</b>";
        QPalette pal = m_p->pStepsLabel->palette();
        QColor clrWin = pal.color(QPalette::Normal, QPalette::Window);
        QColor clrTxt = pal.color(QPalette::Normal, QPalette::WindowText);
        QColor clrMid = qRgb(
                            (clrWin.red() + clrTxt.red()) / 2,
                            (clrWin.green() + clrTxt.green()) / 2,
                            (clrWin.blue() + clrTxt.blue()) / 2);

        szSteps = "<font color=\"";
        szSteps += clrMid.name();
        szSteps += "\"><b>[";
        szSteps += QString("Step %1 of %2").arg(pData->iVisibleIndex).arg(m_p->iEnabledPageCount);
        szSteps += "]</b></font>";
    }

    m_p->pTitleLabel->setText(szTitle);
    m_p->pStepsLabel->setText(szSteps);

    m_p->pNextButton->setEnabled(bNextEnabled);
    if(bHaveNextPage)
    {
        m_p->pNextButton->show();
        m_p->pNextSpacer->show();
        m_p->pNextButton->setDefault(true);
    }
    else
    {
        m_p->pNextButton->hide();
        m_p->pNextSpacer->hide();
        m_p->pNextButton->setDefault(false);
    }

    m_p->pBackButton->setEnabled(bBackEnabled);
    if(bHavePrevPage)
        m_p->pBackButton->show();
    else
        m_p->pBackButton->hide();

    m_p->pHelpButton->setEnabled(bHelpEnabled);
    if(bHelpEnabled)
        m_p->pHelpButton->show();
    else
        m_p->pHelpButton->hide();

    m_p->pCancelButton->setEnabled(bCancelEnabled);
    m_p->pFinishButton->setEnabled(bFinishEnabled);

    if(bFinishEnabled)
    {
        m_p->pFinishButton->show();
        m_p->pFinishSpacer->show();
        m_p->pFinishButton->setDefault(true);
    }
    else
    {
        m_p->pFinishButton->hide();
        m_p->pFinishSpacer->hide();
        m_p->pFinishButton->setDefault(false);
    }
}
Пример #2
0
static
void read_jpeg_image(QImageIO* iio)
{
    QImage image;

    struct jpeg_decompress_struct cinfo;

    struct my_jpeg_source_mgr *iod_src = new my_jpeg_source_mgr(iio);
    struct my_error_mgr jerr;

    jpeg_create_decompress(&cinfo);

    cinfo.src = iod_src;

    cinfo.err = jpeg_std_error(&jerr);
    jerr.error_exit = my_error_exit;

    if (!setjmp(jerr.setjmp_buffer)) {
#if defined(_OS_UNIXWARE7_)
        (void) jpeg_read_header(&cinfo, B_TRUE);
#else
        (void) jpeg_read_header(&cinfo, TRUE);
#endif

        (void) jpeg_start_decompress(&cinfo);

        if ( cinfo.output_components == 3 || cinfo.output_components == 4) {
            image.create( cinfo.output_width, cinfo.output_height, 32 );
        } else if ( cinfo.output_components == 1 ) {
            image.create( cinfo.output_width, cinfo.output_height, 8, 256 );
            for (int i=0; i<256; i++)
                image.setColor(i, qRgb(i,i,i));
        } else {
            // Unsupported format
        }

        if (!image.isNull()) {
            uchar** lines = image.jumpTable();
            while (cinfo.output_scanline < cinfo.output_height)
                (void) jpeg_read_scanlines(&cinfo,
                                           lines + cinfo.output_scanline,
                                           cinfo.output_height);
            (void) jpeg_finish_decompress(&cinfo);
        }

        if ( cinfo.output_components == 3 ) {
            // Expand 24->32 bpp.
            for (uint j=0; j<cinfo.output_height; j++) {
                uchar *in = image.scanLine(j) + cinfo.output_width * 3;
                QRgb *out = (QRgb*)image.scanLine(j);

                for (uint i=cinfo.output_width; i--; ) {
                    in-=3;
                    out[i] = qRgb(in[0], in[1], in[2]);
                }
            }
        }
        iio->setImage(image);
        iio->setStatus(0);
    }

    jpeg_destroy_decompress(&cinfo);
    delete iod_src;
}
Пример #3
0
static
void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, QSize scaledSize, bool *doScaledRead, float screen_gamma=0.0)
{
    if (screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
        double file_gamma;
        png_get_gAMA(png_ptr, info_ptr, &file_gamma);
        png_set_gamma(png_ptr, screen_gamma, file_gamma);
    }

    png_uint_32 width;
    png_uint_32 height;
    int bit_depth;
    int color_type;
    png_bytep trans_alpha = 0;
    png_color_16p trans_color_p = 0;
    int num_trans;
    png_colorp palette = 0;
    int num_palette;
    int interlace_method;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_method, 0, 0);
    png_set_interlace_handling(png_ptr);

    if (color_type == PNG_COLOR_TYPE_GRAY) {
        // Black & White or 8-bit grayscale
        if (bit_depth == 1 && png_get_channels(png_ptr, info_ptr) == 1) {
            png_set_invert_mono(png_ptr);
            png_read_update_info(png_ptr, info_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_Mono) {
                image = QImage(width, height, QImage::Format_Mono);
                if (image.isNull())
                    return;
            }
            image.setColorCount(2);
            image.setColor(1, qRgb(0,0,0));
            image.setColor(0, qRgb(255,255,255));
        } else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
            png_set_expand(png_ptr);
            png_set_strip_16(png_ptr);
            png_set_gray_to_rgb(png_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_ARGB32) {
                image = QImage(width, height, QImage::Format_ARGB32);
                if (image.isNull())
                    return;
            }
            if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
                png_set_swap_alpha(png_ptr);

            png_read_update_info(png_ptr, info_ptr);
        } else {
            if (bit_depth == 16)
                png_set_strip_16(png_ptr);
            else if (bit_depth < 8)
                png_set_packing(png_ptr);
            int ncols = bit_depth < 8 ? 1 << bit_depth : 256;
            png_read_update_info(png_ptr, info_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_Indexed8) {
                image = QImage(width, height, QImage::Format_Indexed8);
                if (image.isNull())
                    return;
            }
            image.setColorCount(ncols);
            for (int i=0; i<ncols; i++) {
                int c = i*255/(ncols-1);
                image.setColor(i, qRgba(c,c,c,0xff));
            }
            if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_color_p) {
                const int g = trans_color_p->gray;
                if (g < ncols) {
                    image.setColor(g, 0);
                }
            }
        }
    } else if (color_type == PNG_COLOR_TYPE_PALETTE
               && png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)
               && num_palette <= 256)
    {
        // 1-bit and 8-bit color
        if (bit_depth != 1)
            png_set_packing(png_ptr);
        png_read_update_info(png_ptr, info_ptr);
        png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
        QImage::Format format = bit_depth == 1 ? QImage::Format_Mono : QImage::Format_Indexed8;
        if (image.size() != QSize(width, height) || image.format() != format) {
            image = QImage(width, height, format);
            if (image.isNull())
                return;
        }
        png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
        image.setColorCount(num_palette);
        int i = 0;
        if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_alpha) {
            while (i < num_trans) {
                image.setColor(i, qRgba(
                    palette[i].red,
                    palette[i].green,
                    palette[i].blue,
                    trans_alpha[i]
                   )
               );
                i++;
            }
        }
        while (i < num_palette) {
            image.setColor(i, qRgba(
                palette[i].red,
                palette[i].green,
                palette[i].blue,
                0xff
               )
           );
            i++;
        }
    } else {
        // 32-bit
        if (bit_depth == 16)
            png_set_strip_16(png_ptr);

        png_set_expand(png_ptr);

        if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
            png_set_gray_to_rgb(png_ptr);

        QImage::Format format = QImage::Format_ARGB32;
        // Only add filler if no alpha, or we can get 5 channel data.
        if (!(color_type & PNG_COLOR_MASK_ALPHA)
            && !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
            png_set_filler(png_ptr, 0xff, QSysInfo::ByteOrder == QSysInfo::BigEndian ?
                           PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
            // We want 4 bytes, but it isn't an alpha channel
            format = QImage::Format_RGB32;
        }
        QSize outSize(width,height);
        if (!scaledSize.isEmpty() && quint32(scaledSize.width()) <= width &&
            quint32(scaledSize.height()) <= height && interlace_method == PNG_INTERLACE_NONE) {
            // Do inline downscaling
            outSize = scaledSize;
            if (doScaledRead)
                *doScaledRead = true;
        }
        if (image.size() != outSize || image.format() != format) {
            image = QImage(outSize, format);
            if (image.isNull())
                return;
        }

        if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
            png_set_swap_alpha(png_ptr);

        png_read_update_info(png_ptr, info_ptr);
    }

    // Qt==ARGB==Big(ARGB)==Little(BGRA)
    if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) {
        png_set_bgr(png_ptr);
    }
}
Пример #4
0
 QRgb map(QRgb pixel, QPoint) const {
     return qRgb(colorBound((int) qRed(pixel) * (m_avg[0] / m_avg[1])),
                 colorBound((int) qGreen(pixel) * (m_avg[0] / m_avg[2])),
                 colorBound((int) qBlue(pixel) * (m_avg[0] / m_avg[3])));
 }
Пример #5
0
                                                             << "performer"
                                                             << "grouping"
                                                             << "lyrics"
                                                             << "originalyear";

// From http://en.wikipedia.org/wiki/8.3_filename#Directory_table
const char OrganiseFormat::kInvalidFatCharacters[] = "\"*/\\:<>?|";
const int OrganiseFormat::kInvalidFatCharactersCount =
    arraysize(OrganiseFormat::kInvalidFatCharacters) - 1;

const char OrganiseFormat::kInvalidPrefixCharacters[] = ".";
const int OrganiseFormat::kInvalidPrefixCharactersCount =
    arraysize(OrganiseFormat::kInvalidPrefixCharacters) - 1;

const QRgb OrganiseFormat::SyntaxHighlighter::kValidTagColorLight =
    qRgb(64, 64, 255);
const QRgb OrganiseFormat::SyntaxHighlighter::kInvalidTagColorLight =
    qRgb(255, 64, 64);
const QRgb OrganiseFormat::SyntaxHighlighter::kBlockColorLight =
    qRgb(230, 230, 230);

const QRgb OrganiseFormat::SyntaxHighlighter::kValidTagColorDark =
    qRgb(128, 128, 255);
const QRgb OrganiseFormat::SyntaxHighlighter::kInvalidTagColorDark =
    qRgb(255, 128, 128);
const QRgb OrganiseFormat::SyntaxHighlighter::kBlockColorDark =
    qRgb(64, 64, 64);

OrganiseFormat::OrganiseFormat(const QString& format)
    : format_(format),
      replace_non_ascii_(false),
#include "qicnshandler_p.h"

#include <QtCore/qmath.h>
#include <QtCore/qendian.h>
#include <QtCore/qregularexpression.h>
#include <QtCore/qbuffer.h>
#include <QtGui/qimage.h>

#ifndef QT_NO_DATASTREAM

QT_BEGIN_NAMESPACE

static const quint8 ICNSBlockHeaderSize = 8;

static const QRgb ICNSColorTableMono[] = {
    qRgb(0xFF, 0xFF, 0xFF),
    qRgb(0x00, 0x00, 0x00)
};
Q_STATIC_ASSERT(sizeof(ICNSColorTableMono) / sizeof(ICNSColorTableMono[0]) == (1 << ICNSEntry::DepthMono));

static const QRgb ICNSColorTable4bit[] = {
    qRgb(0xFF, 0xFF, 0xFF),
    qRgb(0xFC, 0xF3, 0x05),
    qRgb(0xFF, 0x64, 0x02),
    qRgb(0xDD, 0x08, 0x06),
    qRgb(0xF2, 0x08, 0x84),
    qRgb(0x46, 0x00, 0xA5),
    qRgb(0x00, 0x00, 0xD4),
    qRgb(0x02, 0xAB, 0xEA),
    qRgb(0x1F, 0xB7, 0x14),
    qRgb(0x00, 0x64, 0x11),
Пример #7
0
void Image::resizeImage(const int rate) {
	float r = rate / 100.;
	float w = tempImg->width() * r;
	float h = tempImg->height() * r;
	float x, y;
	float ax, ay, bx, by, cx, cy, dx, dy;
	float ar, ag, ab, br, bg, bb, cr, cg, cb, dr, dg, db;
	float er, eg, eb, fr, fg, fb;
	QRgb rgb;

	QImage* newImage = new QImage(w, h, tempImg->format());
	for (int i = 0; i < (int)w; ++i)
		for (int j = 0; j < (int)h; ++j) {
			x = (float)i / r;
			y = (float)j / r;

			// to avoid that x and y excceed the range of the 
			// two-dimension vector.
			if ((float)tempImg->width() - x < 2)
				x = tempImg->width() - 2;
			if ((float)tempImg->height() - y < 2)
				y = tempImg->height() - 2;

			ax = x, ay = y;
			bx = x + 1; by = y;
			cx = x, cy = y + 1;
			dx = x + 1, dy = y + 1;
			
			rgb = tempImg->pixel(ax, ay);
			ar = qRed(rgb);	
			ag = qGreen(rgb);	
			ab = qBlue(rgb);	
	
			rgb = tempImg->pixel(bx, by);
			br = qRed(rgb);	  	
			bg = qGreen(rgb);	 	
			bb = qBlue(rgb);	 	

			rgb = tempImg->pixel(cx, cy);
			cr = qRed(rgb);	  	
			cg = qGreen(rgb);	 	
			cb = qBlue(rgb);	 	
	
			rgb = tempImg->pixel(dx, dy);
			dr = qRed(rgb);	  	
			dg = qGreen(rgb);	 	
			db = qBlue(rgb);	 	

			er = ar + (br - ar) * (x - ax);
			fr = cr + (dr - cr) * (x - cx);
			int R = (int)(er + (fr - er) * (y - ay));

			eg = ag + (bg - ag) * (x - ax);
			fg = cg + (dg - cg) * (x - cx);
			int G = (int)(eg + (fg - eg) * (y - ay));

			eb = ab + (bb - ab) * (x - ax);
			fb = cb + (db - cb) * (x - cx);
			int B = (int)(eb + (fb - eb) * (y - ay));

			newImage->setPixel(i, j, qRgb(R, G, B));
		}
	img = newImage;
	getHistogram();
	update();
}
void tst_QColor::setRgb()
{
    QColor color;

    for (int A = 0; A <= USHRT_MAX; ++A) {
        {
            // 0-255
            int a = A >> 8;
            QRgb rgb = qRgba(0, 0, 0, a);

            color.setRgb(0, 0, 0, a);
            QCOMPARE(color.alpha(), a);
            QCOMPARE(color.rgb(),  qRgb(0, 0, 0));

            color.setRgb(rgb);
            QCOMPARE(color.alpha(), 255);
            QCOMPARE(color.rgb(),   qRgb(0, 0, 0));

            int r, g, b, a2;
            color.setRgb(0, 0, 0, a);
            color.getRgb(&r, &g, &b, &a2);
            QCOMPARE(a2, a);

            QColor c(0, 0, 0);
            c.setAlpha(a);
            QCOMPARE(c.alpha(), a);
        }

        {
            // 0.0-1.0
            qreal a = A / qreal(USHRT_MAX);
            color.setRgbF(0.0, 0.0, 0.0, a);
            QCOMPARE(color.alphaF(), a);

            qreal r, g, b, a2;
            color.getRgbF(&r, &g, &b, &a2);
            QCOMPARE(a2, a);

            QColor c(0, 0, 0);
            c.setAlphaF(a);

            QCOMPARE(c.alphaF(), a);
        }
    }

    for (int R = 0; R <= USHRT_MAX; ++R) {
        {
            // 0-255
            int r = R >> 8;
            QRgb rgb = qRgb(r, 0, 0);

            color.setRgb(r, 0, 0);
            QCOMPARE(color.red(), r);
            QCOMPARE(color.rgb(), rgb);

            color.setRgb(rgb);
            QCOMPARE(color.red(), r);
            QCOMPARE(color.rgb(), rgb);

            int r2, g, b, a;
            color.getRgb(&r2, &g, &b, &a);
            QCOMPARE(r2, r);
        }

        {
            // 0.0-1.0
            qreal r = R / qreal(USHRT_MAX);
            color.setRgbF(r, 0.0, 0.0);
            QCOMPARE(color.redF(), r);

            qreal r2, g, b, a;
            color.getRgbF(&r2, &g, &b, &a);
            QCOMPARE(r2, r);
        }
    }

    for (int G = 0; G <= USHRT_MAX; ++G) {
        {
            // 0-255
            int g = G >> 8;
            QRgb rgb = qRgb(0, g, 0);

            color.setRgb(0, g, 0);
            QCOMPARE(color.green(), g);
            QCOMPARE(color.rgb(),   rgb);

            color.setRgb(rgb);
            QCOMPARE(color.green(), g);
            QCOMPARE(color.rgb(),   rgb);

            int r, g2, b, a;
            color.getRgb(&r, &g2, &b, &a);
            QCOMPARE(g2, g);
        }

        {
            // 0.0-1.0
            qreal g = G / qreal(USHRT_MAX);
            color.setRgbF(0.0, g, 0.0);
            QCOMPARE(color.greenF(), g);

            qreal r, g2, b, a;
            color.getRgbF(&r, &g2, &b, &a);
            QCOMPARE(g2, g);
        }
    }

    for (int B = 0; B <= USHRT_MAX; ++B) {
        {
            // 0-255
            int b = B >> 8;
            QRgb rgb = qRgb(0, 0, b);

            color.setRgb(0, 0, b);
            QCOMPARE(color.blue(),  b);
            QCOMPARE(color.rgb(),   rgb);

            color.setRgb(rgb);
            QCOMPARE(color.blue(),  b);
            QCOMPARE(color.rgb(),   rgb);

            int r, g, b2, a;
            color.getRgb(&r, &g, &b2, &a);
            QCOMPARE(b2, b);
        }

        {
            // 0.0-1.0
            qreal b = B / qreal(USHRT_MAX);
            color.setRgbF(0.0, 0.0, b);
            QCOMPARE(color.blueF(), b);

            qreal r, g, b2, a;
            color.getRgbF(&r, &g, &b2, &a);
            QCOMPARE(b2, b);
        }
    }
}
Пример #9
0
ScanLinesElement::ScanLinesElement(): AkElement()
{
    this->m_showSize = 1;
    this->m_hideSize = 4;
    this->m_hideColor = qRgb(0, 0, 0);
}
// Testing get/set functions
void tst_QColor::getSetCheck()
{
    QColor obj1;
    // int QColor::alpha()
    // void QColor::setAlpha(int)
    obj1.setAlpha(0);
    QCOMPARE(obj1.alpha(), 0);
    obj1.setAlpha(-1);
    QCOMPARE(obj1.alpha(), 0); // range<0, 255>
    obj1.setAlpha(INT_MIN);
    QCOMPARE(obj1.alpha(), 0); // range<0, 255>
    obj1.setAlpha(255);
    QCOMPARE(obj1.alpha(), 255); // range<0, 255>
    obj1.setAlpha(INT_MAX);
    QCOMPARE(obj1.alpha(), 255); // range<0, 255>

    // qreal QColor::alphaF()
    // void QColor::setAlphaF(qreal)
    obj1.setAlphaF(0.0);
    QCOMPARE(obj1.alphaF(), qreal(0.0)); // range<0.0, 1.0>
    obj1.setAlphaF(-0.2);
    QCOMPARE(obj1.alphaF(), qreal(0.0)); // range<0.0, 1.0>
    obj1.setAlphaF(1.0);
    QCOMPARE(obj1.alphaF(), qreal(1.0)); // range<0.0, 1.0>
    obj1.setAlphaF(1.1);
    QCOMPARE(obj1.alphaF(), qreal(1.0)); // range<0.0, 1.0>

    // int QColor::red()
    // void QColor::setRed(int)
    obj1.setRed(0);
    QCOMPARE(obj1.red(), 0);
    obj1.setRed(-1);
    QCOMPARE(obj1.red(), 0); // range<0, 255>
    obj1.setRed(INT_MIN);
    QCOMPARE(obj1.red(), 0); // range<0, 255>
    obj1.setRed(255);
    QCOMPARE(obj1.red(), 255); // range<0, 255>
    obj1.setRed(INT_MAX);
    QCOMPARE(obj1.red(), 255); // range<0, 255>

    // int QColor::green()
    // void QColor::setGreen(int)
    obj1.setGreen(0);
    QCOMPARE(obj1.green(), 0);
    obj1.setGreen(-1);
    QCOMPARE(obj1.green(), 0); // range<0, 255>
    obj1.setGreen(INT_MIN);
    QCOMPARE(obj1.green(), 0); // range<0, 255>
    obj1.setGreen(255);
    QCOMPARE(obj1.green(), 255); // range<0, 255>
    obj1.setGreen(INT_MAX);
    QCOMPARE(obj1.green(), 255); // range<0, 255>

    // int QColor::blue()
    // void QColor::setBlue(int)
    obj1.setBlue(0);
    QCOMPARE(obj1.blue(), 0);
    obj1.setBlue(-1);
    QCOMPARE(obj1.blue(), 0); // range<0, 255>
    obj1.setBlue(INT_MIN);
    QCOMPARE(obj1.blue(), 0); // range<0, 255>
    obj1.setBlue(255);
    QCOMPARE(obj1.blue(), 255); // range<0, 255>
    obj1.setBlue(INT_MAX);
    QCOMPARE(obj1.blue(), 255); // range<0, 255>

    // qreal QColor::redF()
    // void QColor::setRedF(qreal)
    obj1.setRedF(0.0);
    QCOMPARE(obj1.redF(), qreal(0.0));
    obj1.setRedF(-0.2);
    QCOMPARE(obj1.redF(), qreal(0.0)); // range<0.0, 1.0
    obj1.setRedF(1.1);
    QCOMPARE(obj1.redF(), qreal(1.0)); // range<0.0, 1.0

    // qreal QColor::greenF()
    // void QColor::setGreenF(qreal)
    obj1.setGreenF(0.0);
    QCOMPARE(obj1.greenF(), qreal(0.0));
    obj1.setGreenF(-0.2);
    QCOMPARE(obj1.greenF(), qreal(0.0)); // range<0.0, 1.0
    obj1.setGreenF(1.1);
    QCOMPARE(obj1.greenF(), qreal(1.0)); // range<0.0, 1.0

    // qreal QColor::blueF()
    // void QColor::setBlueF(qreal)
    obj1.setBlueF(0.0);
    QCOMPARE(obj1.blueF(), qreal(0.0));
    obj1.setBlueF(-0.2);
    QCOMPARE(obj1.blueF(), qreal(0.0)); // range<0.0, 1.0
    obj1.setBlueF(1.1);
    QCOMPARE(obj1.blueF(), qreal(1.0)); // range<0.0, 1.0

    // QRgb QColor::rgba()
    // void QColor::setRgba(QRgb)
    QRgb var9(qRgba(10, 20, 30, 40));
    obj1.setRgba(var9);
    QCOMPARE(obj1.rgba(), var9);
    obj1.setRgba(QRgb(0));
    QCOMPARE(obj1.rgba(), QRgb(0));

    // QRgb QColor::rgb()
    // void QColor::setRgb(QRgb)
    QRgb var10(qRgb(10, 20, 30));
    obj1.setRgb(var10);
    QCOMPARE(obj1.rgb(), var10);
    obj1.setRgb(QRgb(0));
    QCOMPARE(obj1.rgb(), qRgb(0, 0, 0));
}
void tst_QColor::setallowX11ColorNames()
{
#if defined(Q_OS_IRIX)
    QSKIP("This fails due to the gamma settings in the SGI X server");
#endif
    RGBData x11RgbTbl[] = {
        // a few standard X11 color names
        { "DodgerBlue1", qRgb(30, 144, 255) },
        { "DodgerBlue2", qRgb(28, 134, 238) },
        { "DodgerBlue3", qRgb(24, 116, 205) },
        { "DodgerBlue4", qRgb(16, 78, 139) },
        { "SteelBlue1", qRgb(99, 184, 255) },
        { "SteelBlue2", qRgb(92, 172, 238) },
        { "SteelBlue3", qRgb(79, 148, 205) },
        { "SteelBlue4", qRgb(54, 100, 139) },
        { "DeepSkyBlue1", qRgb(0, 191, 255) },
        { "DeepSkyBlue2", qRgb(0, 178, 238) },
        { "DeepSkyBlue3", qRgb(0, 154, 205) },
        { "DeepSkyBlue4", qRgb(0, 104, 139) },
        { "SkyBlue1", qRgb(135, 206, 255) },
        { "SkyBlue2", qRgb(126, 192, 238) },
        { "SkyBlue3", qRgb(108, 166, 205) },
        { "SkyBlue4", qRgb(74, 112, 139) }
    };
    static const int x11RgbTblSize = sizeof(x11RgbTbl) / sizeof(RGBData);

    // X11 color names should not work by default
    QVERIFY(!QColor::allowX11ColorNames());
    for (int i = 0; i < x11RgbTblSize; ++i) {
        QString colorName = QLatin1String(x11RgbTbl[i].name);
        QColor color;
        color.setNamedColor(colorName);
        QVERIFY(!color.isValid());
    }

    // enable X11 color names
    QColor::setAllowX11ColorNames(true);
    QVERIFY(QColor::allowX11ColorNames());
    for (int i = 0; i < x11RgbTblSize; ++i) {
        QString colorName = QLatin1String(x11RgbTbl[i].name);
        QColor color;
        color.setNamedColor(colorName);
        QColor expected(x11RgbTbl[i].value);
        QCOMPARE(color, expected);
    }

    // should be able to turn off X11 color names
    QColor::setAllowX11ColorNames(false);
    QVERIFY(!QColor::allowX11ColorNames());
    for (int i = 0; i < x11RgbTblSize; ++i) {
        QString colorName = QLatin1String(x11RgbTbl[i].name);
        QColor color;
        color.setNamedColor(colorName);
        QVERIFY(!color.isValid());
    }
}
Пример #12
0
bool QgsRenderChecker::compareImages( QString theTestName,
                                      unsigned int theMismatchCount,
                                      QString theRenderedImageFile )
{
  if ( mExpectedImageFile.isEmpty() )
  {
    qDebug( "QgsRenderChecker::runTest failed - Expected Image (control) File not set." );
    mReport = "<table>"
              "<tr><td>Test Result:</td><td>Expected Result:</td></tr>\n"
              "<tr><td>Nothing rendered</td>\n<td>Failed because Expected "
              "Image File not set.</td></tr></table>\n";
    return false;
  }
  if ( ! theRenderedImageFile.isEmpty() )
  {
    mRenderedImageFile = theRenderedImageFile;
  }
  if ( mRenderedImageFile.isEmpty() )
  {
    qDebug( "QgsRenderChecker::runTest failed - Rendered Image File not set." );
    mReport = "<table>"
              "<tr><td>Test Result:</td><td>Expected Result:</td></tr>\n"
              "<tr><td>Nothing rendered</td>\n<td>Failed because Rendered "
              "Image File not set.</td></tr></table>\n";
    return false;
  }
  //
  // Load /create the images
  //
  QImage myExpectedImage( mExpectedImageFile );
  QImage myResultImage( mRenderedImageFile );
  QImage myDifferenceImage( myExpectedImage.width(),
                            myExpectedImage.height(),
                            QImage::Format_RGB32 );
  QString myDiffImageFile = QDir::tempPath() + QDir::separator() +
                            QDir::separator()  +
                            theTestName + "_result_diff.png";
  myDifferenceImage.fill( qRgb( 152, 219, 249 ) );

  //
  // Set pixel count score and target
  //
  mMatchTarget = myExpectedImage.width() * myExpectedImage.height();
  unsigned int myPixelCount = myResultImage.width() * myResultImage.height();
  //
  // Set the report with the result
  //
  mReport = "<table>";
  mReport += "<tr><td colspan=2>";
  mReport += "Test image and result image for " + theTestName + "<br>"
             "Expected size: " + QString::number( myExpectedImage.width() ).toLocal8Bit() + "w x " +
             QString::number( myExpectedImage.height() ).toLocal8Bit() + "h (" +
             QString::number( mMatchTarget ).toLocal8Bit() + " pixels)<br>"
             "Actual   size: " + QString::number( myResultImage.width() ).toLocal8Bit() + "w x " +
             QString::number( myResultImage.height() ).toLocal8Bit() + "h (" +
             QString::number( myPixelCount ).toLocal8Bit() + " pixels)";
  mReport += "</td></tr>";
  mReport += "<tr><td colspan = 2>\n";
  mReport += "Expected Duration : <= " + QString::number( mElapsedTimeTarget ) +
             "ms (0 indicates not specified)<br>";
  mReport += "Actual Duration :  " + QString::number( mElapsedTime ) + "ms<br>";

  // limit image size in page to something reasonable
  int imgWidth = 420;
  int imgHeight = 280;
  if ( ! myExpectedImage.isNull() )
  {
    imgWidth = qMin( myExpectedImage.width(), imgWidth );
    imgHeight = myExpectedImage.height() * imgWidth / myExpectedImage.width();
  }
  QString myImagesString = "</td></tr>"
                           "<tr><td>Test Result:</td><td>Expected Result:</td><td>Difference (all blue is good, any red is bad)</td></tr>\n"
                           "<tr><td><img width=" + QString::number( imgWidth ) +
                           " height=" + QString::number( imgHeight ) +
                           " src=\"file://" +
                           mRenderedImageFile +
                           "\"></td>\n<td><img width=" + QString::number( imgWidth ) +
                           " height=" + QString::number( imgHeight ) +
                           " src=\"file://" +
                           mExpectedImageFile +
                           "\"></td>\n<td><img width=" + QString::number( imgWidth ) +
                           " height=" + QString::number( imgHeight ) +
                           " src=\"file://" +
                           myDiffImageFile  +
                           "\"></td>\n</tr>\n</table>";
  //
  // To get the images into CDash
  //
  QString myDashMessage = "<DartMeasurementFile name=\"Rendered Image " + theTestName + "\""
                          " type=\"image/png\">" + mRenderedImageFile +
                          "</DartMeasurementFile>\n"
                          "<DartMeasurementFile name=\"Expected Image " + theTestName + "\" type=\"image/png\">" +
                          mExpectedImageFile + "</DartMeasurementFile>\n"
                          "<DartMeasurementFile name=\"Difference Image " + theTestName + "\" type=\"image/png\">" +
                          myDiffImageFile + "</DartMeasurementFile>\n";
  qDebug( ) << myDashMessage;

  //
  // Put the same info to debug too
  //

  qDebug( "Expected size: %dw x %dh", myExpectedImage.width(), myExpectedImage.height() );
  qDebug( "Actual   size: %dw x %dh", myResultImage.width(), myResultImage.height() );

  if ( mMatchTarget != myPixelCount )
  {
    qDebug( "Test image and result image for %s are different - FAILING!", theTestName.toLocal8Bit().constData() );
    mReport += "<tr><td colspan=3>";
    mReport += "<font color=red>Expected image and result image for " + theTestName + " are different dimensions - FAILING!</font>";
    mReport += "</td></tr>";
    mReport += myImagesString;
    return false;
  }

  //
  // Now iterate through them counting how many
  // dissimilar pixel values there are
  //

  mMismatchCount = 0;
  int colorTolerance = ( int ) mColorTolerance;
  for ( int x = 0; x < myExpectedImage.width(); ++x )
  {
    for ( int y = 0; y < myExpectedImage.height(); ++y )
    {
      QRgb myExpectedPixel = myExpectedImage.pixel( x, y );
      QRgb myActualPixel = myResultImage.pixel( x, y );
      if ( mColorTolerance == 0 )
      {
        if ( myExpectedPixel != myActualPixel )
        {
          ++mMismatchCount;
          myDifferenceImage.setPixel( x, y, qRgb( 255, 0, 0 ) );
        }
      }
      else
      {
        if ( qAbs( qRed( myExpectedPixel ) - qRed( myActualPixel ) ) > colorTolerance ||
             qAbs( qGreen( myExpectedPixel ) - qGreen( myActualPixel ) ) > colorTolerance ||
             qAbs( qBlue( myExpectedPixel ) - qBlue( myActualPixel ) ) > colorTolerance ||
             qAbs( qAlpha( myExpectedPixel ) - qAlpha( myActualPixel ) ) > colorTolerance )
        {
          ++mMismatchCount;
          myDifferenceImage.setPixel( x, y, qRgb( 255, 0, 0 ) );
        }
      }
    }
  }
  //
  //save the diff image to disk
  //
  myDifferenceImage.save( myDiffImageFile );

  //
  // Send match result to debug
  //
  qDebug( "%d/%d pixels mismatched (%d allowed)", mMismatchCount, mMatchTarget, theMismatchCount );

  //
  // Send match result to report
  //
  mReport += "<tr><td colspan=3>" +
             QString::number( mMismatchCount ) + "/" +
             QString::number( mMatchTarget ) +
             " pixels mismatched (allowed threshold: " +
             QString::number( theMismatchCount ) +
             ", allowed color component tolerance: " +
             QString::number( mColorTolerance ) + ")";
  mReport += "</td></tr>";

  //
  // And send it to CDash
  //
  myDashMessage = "<DartMeasurement name=\"Mismatch Count "
                  "\" type=\"numeric/integer\">" +
                  QString::number( mMismatchCount ) + "/" +
                  QString::number( mMatchTarget ) +
                  "</DartMeasurement>";
  qDebug( ) << myDashMessage;

  bool myAnomalyMatchFlag = isKnownAnomaly( myDiffImageFile );

  if ( myAnomalyMatchFlag )
  {
    mReport += "<tr><td colspan=3>"
               "Difference image matched a known anomaly - passing test! "
               "</td></tr>";
    return true;
  }
  else
  {
    QString myMessage = "Difference image did not match any known anomaly.";
    mReport += "<tr><td colspan=3>"
               "</td></tr>";
    QString myMeasureMessage = "<DartMeasurement name=\"No Anomalies Match"
                               "\" type=\"text/text\">" +  myMessage +
                               " If you feel the difference image should be considered an anomaly "
                               "you can do something like this\n"
                               "cp " + myDiffImageFile  + " ../tests/testdata/control_images/" + theTestName +
                               "/<imagename>.{wld,png}"
                               "</DartMeasurement>";
    qDebug() << myMeasureMessage;
  }

  if ( mMismatchCount <= theMismatchCount )
  {
    mReport += "<tr><td colspan = 3>\n";
    mReport += "Test image and result image for " + theTestName + " are matched<br>";
    mReport += "</td></tr>";
    if ( mElapsedTimeTarget != 0 && mElapsedTimeTarget < mElapsedTime )
    {
      //test failed because it took too long...
      qDebug( "Test failed because render step took too long" );
      mReport += "<tr><td colspan = 3>\n";
      mReport += "<font color=red>Test failed because render step took too long</font>";
      mReport += "</td></tr>";
      mReport += myImagesString;
      return false;
    }
    else
    {
      mReport += myImagesString;
      return true;
    }
  }
  else
  {
    mReport += "<tr><td colspan = 3>\n";
    mReport += "<font color=red>Test image and result image for " + theTestName + " are mismatched</font><br>";
    mReport += "</td></tr>";
    mReport += myImagesString;
    return false;
  }
}
Пример #13
0
bool QgsRenderChecker::runTest( QString theTestName,
                                unsigned int theMismatchCount )
{
  if ( mExpectedImageFile.isEmpty() )
  {
    qDebug( "QgsRenderChecker::runTest failed - Expected Image File not set." );
    mReport = "<table>"
              "<tr><td>Test Result:</td><td>Expected Result:</td></tr>\n"
              "<tr><td>Nothing rendered</td>\n<td>Failed because Expected "
              "Image File not set.</td></tr></table>\n";
    return false;
  }
  //
  // Load the expected result pixmap
  //
  QImage myExpectedImage( mExpectedImageFile );
  mMatchTarget = myExpectedImage.width() * myExpectedImage.height();
  //
  // Now render our layers onto a pixmap
  //
  mMapSettings.setBackgroundColor( qRgb( 152, 219, 249 ) );
  mMapSettings.setFlag( QgsMapSettings::Antialiasing );
  mMapSettings.setOutputSize( QSize( myExpectedImage.width(), myExpectedImage.height() ) );

  QTime myTime;
  myTime.start();

  QgsMapRendererSequentialJob job( mMapSettings );
  job.start();
  job.waitForFinished();

  mElapsedTime = myTime.elapsed();

  QImage myImage = job.renderedImage();

  //
  // Save the pixmap to disk so the user can make a
  // visual assessment if needed
  //
  mRenderedImageFile = QDir::tempPath() + QDir::separator() +
                       theTestName + "_result.png";

  myImage.setDotsPerMeterX( myExpectedImage.dotsPerMeterX() );
  myImage.setDotsPerMeterY( myExpectedImage.dotsPerMeterY() );
  myImage.save( mRenderedImageFile, "PNG", 100 );

  //create a world file to go with the image...

  QFile wldFile( QDir::tempPath() + QDir::separator() + theTestName + "_result.wld" );
  if ( wldFile.open( QIODevice::WriteOnly ) )
  {
    QgsRectangle r = mMapSettings.extent();

    QTextStream stream( &wldFile );
    stream << QString( "%1\r\n0 \r\n0 \r\n%2\r\n%3\r\n%4\r\n" )
    .arg( qgsDoubleToString( mMapSettings.mapUnitsPerPixel() ) )
    .arg( qgsDoubleToString( -mMapSettings.mapUnitsPerPixel() ) )
    .arg( qgsDoubleToString( r.xMinimum() + mMapSettings.mapUnitsPerPixel() / 2.0 ) )
    .arg( qgsDoubleToString( r.yMaximum() - mMapSettings.mapUnitsPerPixel() / 2.0 ) );
  }

  return compareImages( theTestName, theMismatchCount );
}
Пример #14
0
bool QLinuxFbIntegration::connect(const QString &displaySpec)
{
    const QStringList args = displaySpec.split(QLatin1Char(':'));

    if (args.contains(QLatin1String("nographicsmodeswitch")))
        d_ptr->doGraphicsMode = false;

#ifdef QT_QWS_DEPTH_GENERIC
    if (args.contains(QLatin1String("genericcolors")))
        d_ptr->doGenericColors = true;
#endif

    QRegExp ttyRegExp(QLatin1String("tty=(.*)"));
    if (args.indexOf(ttyRegExp) != -1)
        d_ptr->ttyDevice = ttyRegExp.cap(1);

#if 0
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
#ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN
    if (args.contains(QLatin1String("littleendian")))
#endif
        QScreen::setFrameBufferLittleEndian(true);
#endif
#endif

    // Check for explicitly specified device
    const int len = 8; // "/dev/fbx"
    int m = displaySpec.indexOf(QLatin1String("/dev/fb"));

    QString dev;
    if (m > 0)
        dev = displaySpec.mid(m, len);
    else
        dev = QLatin1String("/dev/fb0");

    if (access(dev.toLatin1().constData(), R_OK|W_OK) == 0)
        d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDWR);
    if (d_ptr->fd == -1) {
        if (access(dev.toLatin1().constData(), R_OK) == 0)
            d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDONLY);
        if (d_ptr->fd == 1) {
            qWarning("Error opening framebuffer device %s", qPrintable(dev));
            return false;
        }
    }

    fb_fix_screeninfo finfo;
    fb_var_screeninfo vinfo;
    //#######################
    // Shut up Valgrind
    memset(&vinfo, 0, sizeof(vinfo));
    memset(&finfo, 0, sizeof(finfo));
    //#######################

    /* Get fixed screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_FSCREENINFO, &finfo)) {
        perror("QLinuxFbIntegration::connect");
        qWarning("Error reading fixed information");
        return false;
    }

    if (finfo.type == FB_TYPE_VGA_PLANES) {
        qWarning("VGA16 video mode not supported");
        return false;
    }

    /* Get variable screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_VSCREENINFO, &vinfo)) {
        perror("QLinuxFbIntegration::connect");
        qWarning("Error reading variable information");
        return false;
    }

    grayscale = vinfo.grayscale;
    d = vinfo.bits_per_pixel;
    if (d == 24) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 24; // reset if color component lengths are not reported
    } else if (d == 16) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 16;
    }
    lstep = finfo.line_length;

    int xoff = vinfo.xoffset;
    int yoff = vinfo.yoffset;
    const char* qwssize;
    if((qwssize=::getenv("QWS_SIZE")) && sscanf(qwssize,"%dx%d",&w,&h)==2) {
        if (d_ptr->fd != -1) {
            if ((uint)w > vinfo.xres) w = vinfo.xres;
            if ((uint)h > vinfo.yres) h = vinfo.yres;
        }
        dw=w;
        dh=h;
        int xxoff, yyoff;
        if (sscanf(qwssize, "%*dx%*d+%d+%d", &xxoff, &yyoff) == 2) {
            if (xxoff < 0 || xxoff + w > (int)(vinfo.xres))
                xxoff = vinfo.xres - w;
            if (yyoff < 0 || yyoff + h > (int)(vinfo.yres))
                yyoff = vinfo.yres - h;
            xoff += xxoff;
            yoff += yyoff;
        } else {
            xoff += (vinfo.xres - w)/2;
            yoff += (vinfo.yres - h)/2;
        }
    } else {
        dw=w=vinfo.xres;
        dh=h=vinfo.yres;
    }

    if (w == 0 || h == 0) {
        qWarning("QLinuxFbIntegration::connect(): Unable to find screen geometry, "
                 "will use 320x240.");
        dw = w = 320;
        dh = h = 240;
    }

    setPixelFormat(vinfo);

    // Handle display physical size spec.
    QStringList displayArgs = displaySpec.split(QLatin1Char(':'));
    QRegExp mmWidthRx(QLatin1String("mmWidth=?(\\d+)"));
    int dimIdxW = displayArgs.indexOf(mmWidthRx);
    QRegExp mmHeightRx(QLatin1String("mmHeight=?(\\d+)"));
    int dimIdxH = displayArgs.indexOf(mmHeightRx);
    if (dimIdxW >= 0) {
        mmWidthRx.exactMatch(displayArgs.at(dimIdxW));
        physWidth = mmWidthRx.cap(1).toInt();
        if (dimIdxH < 0)
            physHeight = dh*physWidth/dw;
    }
    if (dimIdxH >= 0) {
        mmHeightRx.exactMatch(displayArgs.at(dimIdxH));
        physHeight = mmHeightRx.cap(1).toInt();
        if (dimIdxW < 0)
            physWidth = dw*physHeight/dh;
    }
    if (dimIdxW < 0 && dimIdxH < 0) {
        if (vinfo.width != 0 && vinfo.height != 0
            && vinfo.width != UINT_MAX && vinfo.height != UINT_MAX) {
            physWidth = vinfo.width;
            physHeight = vinfo.height;
        } else {
            const int dpi = 72;
            physWidth = qRound(dw * 25.4 / dpi);
            physHeight = qRound(dh * 25.4 / dpi);
        }
    }

    dataoffset = yoff * lstep + xoff * d / 8;
    //qDebug("Using %dx%dx%d screen",w,h,d);

    /* Figure out the size of the screen in bytes */
    size = h * lstep;

    mapsize = finfo.smem_len;

    data = (unsigned char *)-1;
    if (d_ptr->fd != -1)
        data = (unsigned char *)mmap(0, mapsize, PROT_READ | PROT_WRITE,
                                     MAP_SHARED, d_ptr->fd, 0);

    if ((long)data == -1) {
        perror("QLinuxFbIntegration::connect");
        qWarning("Error: failed to map framebuffer device to memory.");
        return false;
    } else {
        data += dataoffset;
    }

#if 0
    canaccel = useOffscreen();
    if(canaccel)
        setupOffScreen();
#endif
    canaccel = false;

    // Now read in palette
    if((vinfo.bits_per_pixel==8) || (vinfo.bits_per_pixel==4)) {
        screencols= (vinfo.bits_per_pixel==8) ? 256 : 16;
        int loopc;
        fb_cmap startcmap;
        startcmap.start=0;
        startcmap.len=screencols;
        startcmap.red=(unsigned short int *)
                 malloc(sizeof(unsigned short int)*screencols);
        startcmap.green=(unsigned short int *)
                   malloc(sizeof(unsigned short int)*screencols);
        startcmap.blue=(unsigned short int *)
                  malloc(sizeof(unsigned short int)*screencols);
        startcmap.transp=(unsigned short int *)
                    malloc(sizeof(unsigned short int)*screencols);
        if (d_ptr->fd == -1 || ioctl(d_ptr->fd, FBIOGETCMAP, &startcmap)) {
            perror("QLinuxFbIntegration::connect");
            qWarning("Error reading palette from framebuffer, using default palette");
            createPalette(startcmap, vinfo, finfo);
        }
        int bits_used = 0;
        for(loopc=0;loopc<screencols;loopc++) {
            screenclut[loopc]=qRgb(startcmap.red[loopc] >> 8,
                                   startcmap.green[loopc] >> 8,
                                   startcmap.blue[loopc] >> 8);
            bits_used |= startcmap.red[loopc]
                         | startcmap.green[loopc]
                         | startcmap.blue[loopc];
        }
        // WORKAROUND: Some framebuffer drivers only return 8 bit
        // color values, so we need to not bit shift them..
        if ((bits_used & 0x00ff) && !(bits_used & 0xff00)) {
            for(loopc=0;loopc<screencols;loopc++) {
                screenclut[loopc] = qRgb(startcmap.red[loopc],
                                         startcmap.green[loopc],
                                         startcmap.blue[loopc]);
            }
            qWarning("8 bits cmap returned due to faulty FB driver, colors corrected");
        }
        free(startcmap.red);
        free(startcmap.green);
        free(startcmap.blue);
        free(startcmap.transp);
    } else {
Пример #15
0
void Interpolate_sV::newTwowayFlow(const QImage &left, const QImage &right,
                                   const FlowField_sV *flowLeftRight, const FlowField_sV *flowRightLeft,
                                   float pos, QImage &output)
{
    const int W = left.width();
    const int H = left.height();


    SourceField_sV leftSourcePixel(flowLeftRight, pos);
    leftSourcePixel.inpaint();
    SourceField_sV rightSourcePixel(flowRightLeft, 1-pos);
    rightSourcePixel.inpaint();

    float aspect = 1 - (.5 + std::cos(M_PI*pos)/2);

#if defined(FIX_FLOW)
    FlowField_sV diffField(flowLeftRight->width(), flowLeftRight->height());
    FlowTools_sV::difference(*flowLeftRight, *flowRightLeft, diffField);
    float diffSum;
    float tmpAspect;
#endif

#ifdef FIX_BORDERS
    bool leftOk;
    bool rightOk;
#endif


    float fx, fy;
    QColor colLeft, colRight;
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {

#ifdef FIX_BORDERS
            fx = leftSourcePixel.at(x,y).fromX;
            fy = leftSourcePixel.at(x,y).fromY;
            if (fx >= 0 && fx < W-1
                    && fy >= 0 && fy < H-1) {
                colLeft = interpolate(left, fx, fy);
                leftOk = true;
            } else {
                fx = leftSourcePixel.at(x,y).fromX;
                fy = leftSourcePixel.at(x,y).fromY;
                fx = CLAMP(fx, 0, W-1.01);
                fy = CLAMP(fy, 0, H-1.01);
                colLeft = interpolate(left, fx, fy);
                leftOk = false;
            }

            fx = rightSourcePixel.at(x,y).fromX;
            fy = rightSourcePixel.at(x,y).fromY;
            if (fx >= 0 && fx < W-1
                    && fy >= 0 && fy < H-1) {
                colRight = interpolate(right, fx, fy);
                rightOk = true;
            } else {
                colRight = qRgb(0,255,0);
                rightOk = false;
            }

            if (leftOk && rightOk) {
                output.setPixel(x,y, blend(colLeft, colRight, aspect).rgba());
            } else if (rightOk) {
                output.setPixel(x,y, colRight.rgba());
//                output.setPixel(x,y, qRgb(255, 0, 0));
            } else if (leftOk) {
                output.setPixel(x,y, colLeft.rgba());
//                output.setPixel(x,y, qRgb(0, 255, 0));
            } else {
                output.setPixel(x,y, colLeft.rgba());
            }
#else
            fx = leftSourcePixel.at(x,y).fromX;
            fy = leftSourcePixel.at(x,y).fromY;
            fx = CLAMP(fx, 0, W-1.01);
            fy = CLAMP(fy, 0, H-1.01);
            colLeft = interpolate(left, fx, fy);

#ifdef FIX_FLOW
            diffSum = diffField.x(fx, fy)+diffField.y(fx, fy);
            if (diffSum > 5) {
                tmpAspect = 0;
            } else if (diffSum < -5) {
                tmpAspect = 1;
            } else {
                tmpAspect = aspect;
            }
#endif

            fx = rightSourcePixel.at(x,y).fromX;
            fy = rightSourcePixel.at(x,y).fromY;
            fx = CLAMP(fx, 0, W-1.01);
            fy = CLAMP(fy, 0, H-1.01);
            colRight = interpolate(right, fx, fy);

#ifdef FIX_FLOW
            diffSum = diffField.x(fx, fy)+diffField.y(fx, fy);
            if (diffSum < 5) {
                tmpAspect = 0;
            } else if (diffSum > -5) {
                tmpAspect = 1;
            }
#endif

#ifdef FIX_FLOW
            output.setPixel(x,y, blend(colLeft, colRight, tmpAspect).rgba());
#else
            output.setPixel(x,y, blend(colLeft, colRight, aspect).rgba());
#endif

#endif
        }
    }
}
Пример #16
0
#include "queue.h"
#include "core/logging.h"
#include "core/player.h"
#include "core/utilities.h"
#include "library/librarybackend.h"
#include "widgets/trackslider.h"
#include "ui/iconloader.h"

#ifdef Q_OS_DARWIN
#include "core/mac_utilities.h"
#endif  // Q_OS_DARWIN

const int QueuedItemDelegate::kQueueBoxBorder = 1;
const int QueuedItemDelegate::kQueueBoxCornerRadius = 3;
const int QueuedItemDelegate::kQueueBoxLength = 30;
const QRgb QueuedItemDelegate::kQueueBoxGradientColor1 = qRgb(102, 150, 227);
const QRgb QueuedItemDelegate::kQueueBoxGradientColor2 = qRgb(77, 121, 200);
const int QueuedItemDelegate::kQueueOpacitySteps = 10;
const float QueuedItemDelegate::kQueueOpacityLowerBound = 0.4;

const int PlaylistDelegateBase::kMinHeight = 19;

QueuedItemDelegate::QueuedItemDelegate(QObject* parent, int indicator_column)
    : QStyledItemDelegate(parent), indicator_column_(indicator_column) {}

void QueuedItemDelegate::paint(QPainter* painter,
                               const QStyleOptionViewItem& option,
                               const QModelIndex& index) const {
  QStyledItemDelegate::paint(painter, option, index);

  if (index.column() == indicator_column_) {
/*!
    This function decodes some data into image changes.

    Returns the number of bytes consumed.
*/
int QGIFFormat::decode(QImage *image, const uchar *buffer, int length,
                       int *nextFrameDelay, int *loopCount)
{
    // We are required to state that
    //    "The Graphics Interchange Format(c) is the Copyright property of
    //    CompuServe Incorporated. GIF(sm) is a Service Mark property of
    //    CompuServe Incorporated."

    image->detach();
    int bpl = image->bytesPerLine();
    unsigned char *bits = image->bits();

#define LM(l, m) (((m)<<8)|l)
    digress = false;
    const int initial = length;
    while (!digress && length) {
        length--;
        unsigned char ch=*buffer++;
        switch (state) {
          case Header:
            hold[count++]=ch;
            if (count==6) {
                // Header
                gif89=(hold[3]!='8' || hold[4]!='7');
                state=LogicalScreenDescriptor;
                count=0;
            }
            break;
          case LogicalScreenDescriptor:
            hold[count++]=ch;
            if (count==7) {
                // Logical Screen Descriptor
                swidth=LM(hold[0], hold[1]);
                sheight=LM(hold[2], hold[3]);
                gcmap=!!(hold[4]&0x80);
                //UNUSED: bpchan=(((hold[4]&0x70)>>3)+1);
                //UNUSED: gcmsortflag=!!(hold[4]&0x08);
                gncols=2<<(hold[4]&0x7);
                bgcol=(gcmap) ? hold[5] : -1;
                //aspect=hold[6] ? double(hold[6]+15)/64.0 : 1.0;

                trans_index = -1;
                count=0;
                ncols=gncols;
                if (gcmap) {
                    ccount=0;
                    state=GlobalColorMap;
                    globalcmap = new QRgb[gncols+1]; // +1 for trans_index
                    globalcmap[gncols] = Q_TRANSPARENT;
                } else {
                    state=Introducer;
                }
            }
            break;
          case GlobalColorMap: case LocalColorMap:
            hold[count++]=ch;
            if (count==3) {
                QRgb rgb = qRgb(hold[0], hold[1], hold[2]);
                if (state == LocalColorMap) {
                    if (ccount < lncols)
                        localcmap[ccount] =  rgb;
                } else {
                    globalcmap[ccount] = rgb;
                }
                if (++ccount >= ncols) {
                    if (state == LocalColorMap)
                        state=TableImageLZWSize;
                    else
                        state=Introducer;
                }
                count=0;
            }
            break;
          case Introducer:
            hold[count++]=ch;
            switch (ch) {
              case ',':
                state=ImageDescriptor;
                break;
              case '!':
                state=ExtensionLabel;
                break;
              case ';':
                  // ### Changed: QRect(0, 0, swidth, sheight)
                state=Done;
                break;
              default:
                digress=true;
                // Unexpected Introducer - ignore block
                state=Error;
            }
            break;
          case ImageDescriptor:
            hold[count++]=ch;
            if (count==10) {
                int newleft=LM(hold[1], hold[2]);
                int newtop=LM(hold[3], hold[4]);
                int newwidth=LM(hold[5], hold[6]);
                int newheight=LM(hold[7], hold[8]);

                // disbelieve ridiculous logical screen sizes,
                // unless the image frames are also large.
                if (swidth/10 > qMax(newwidth,200))
                    swidth = -1;
                if (sheight/10 > qMax(newheight,200))
                    sheight = -1;

                if (swidth <= 0)
                    swidth = newleft + newwidth;
                if (sheight <= 0)
                    sheight = newtop + newheight;

                QImage::Format format = trans_index >= 0 ? QImage::Format_ARGB32 : QImage::Format_RGB32;
                if (image->isNull()) {
                    (*image) = QImage(swidth, sheight, format);
                    bpl = image->bytesPerLine();
                    bits = image->bits();
                    memset(bits, 0, image->byteCount());
                }

                disposePrevious(image);
                disposed = false;

                left = newleft;
                top = newtop;
                width = newwidth;
                height = newheight;

                right=qMax(0, qMin(left+width, swidth)-1);
                bottom=qMax(0, qMin(top+height, sheight)-1);
                lcmap=!!(hold[9]&0x80);
                interlace=!!(hold[9]&0x40);
                //bool lcmsortflag=!!(hold[9]&0x20);
                lncols=lcmap ? (2<<(hold[9]&0x7)) : 0;
                if (lncols) {
                    if (localcmap)
                        delete [] localcmap;
                    localcmap = new QRgb[lncols+1];
                    localcmap[lncols] = Q_TRANSPARENT;
                    ncols = lncols;
                } else {
                    ncols = gncols;
                }
                frame++;
                if (frame == 0) {
                    if (left || top || width<swidth || height<sheight) {
                        // Not full-size image - erase with bg or transparent
                        if (trans_index >= 0) {
                            fillRect(image, 0, 0, swidth, sheight, color(trans_index));
                            // ### Changed: QRect(0, 0, swidth, sheight)
                        } else if (bgcol>=0) {
                            fillRect(image, 0, 0, swidth, sheight, color(bgcol));
                            // ### Changed: QRect(0, 0, swidth, sheight)
                        }
                    }
                }

                if (disposal == RestoreImage) {
                    int l = qMin(swidth-1,left);
                    int r = qMin(swidth-1,right);
                    int t = qMin(sheight-1,top);
                    int b = qMin(sheight-1,bottom);
                    int w = r-l+1;
                    int h = b-t+1;

                    if (backingstore.width() < w
                        || backingstore.height() < h) {
                        // We just use the backing store as a byte array
                        backingstore = QImage(qMax(backingstore.width(), w),
                                              qMax(backingstore.height(), h),
                                              QImage::Format_RGB32);
                        memset(bits, 0, image->byteCount());
                    }
                    const int dest_bpl = backingstore.bytesPerLine();
                    unsigned char *dest_data = backingstore.bits();
                    for (int ln=0; ln<h; ln++) {
                        memcpy(FAST_SCAN_LINE(dest_data, dest_bpl, ln),
                               FAST_SCAN_LINE(bits, bpl, t+ln) + l, w*sizeof(QRgb));
                    }
                }

                count=0;
                if (lcmap) {
                    ccount=0;
                    state=LocalColorMap;
                } else {
                    state=TableImageLZWSize;
                }
                x = left;
                y = top;
                accum = 0;
                bitcount = 0;
                sp = stack;
                firstcode = oldcode = 0;
                needfirst = true;
                out_of_bounds = left>=swidth || y>=sheight;
            }
            break;
          case TableImageLZWSize: {
            lzwsize=ch;
            if (lzwsize > max_lzw_bits) {
                state=Error;
            } else {
                code_size=lzwsize+1;
                clear_code=1<<lzwsize;
                end_code=clear_code+1;
                max_code_size=2*clear_code;
                max_code=clear_code+2;
                int i;
                for (i=0; i<clear_code; i++) {
                    table[0][i]=0;
                    table[1][i]=i;
                }
                state=ImageDataBlockSize;
            }
            count=0;
            break;
          } case ImageDataBlockSize:
            expectcount=ch;
            if (expectcount) {
                state=ImageDataBlock;
            } else {
                state=Introducer;
                digress = true;
                newFrame = true;
            }
            break;
          case ImageDataBlock:
            count++;
            accum|=(ch<<bitcount);
            bitcount+=8;
            while (bitcount>=code_size && state==ImageDataBlock) {
                int code=accum&((1<<code_size)-1);
                bitcount-=code_size;
                accum>>=code_size;

                if (code==clear_code) {
                    if (!needfirst) {
                        code_size=lzwsize+1;
                        max_code_size=2*clear_code;
                        max_code=clear_code+2;
                    }
                    needfirst=true;
                } else if (code==end_code) {
                    bitcount = -32768;
                    // Left the block end arrive
                } else {
                    if (needfirst) {
                        firstcode=oldcode=code;
                        if (!out_of_bounds && image->height() > y && firstcode!=trans_index)
                            ((QRgb*)FAST_SCAN_LINE(bits, bpl, y))[x] = color(firstcode);
                        x++;
                        if (x>=swidth) out_of_bounds = true;
                        needfirst=false;
                        if (x>=left+width) {
                            x=left;
                            out_of_bounds = left>=swidth || y>=sheight;
                            nextY(bits, bpl);
                        }
                    } else {
                        incode=code;
                        if (code>=max_code) {
                            *sp++=firstcode;
                            code=oldcode;
                        }
                        while (code>=clear_code+2) {
                            *sp++=table[1][code];
                            if (code==table[0][code]) {
                                state=Error;
                                break;
                            }
                            if (sp-stack>=(1<<(max_lzw_bits))*2) {
                                state=Error;
                                break;
                            }
                            code=table[0][code];
                        }
                        *sp++=firstcode=table[1][code];
                        code=max_code;
                        if (code<(1<<max_lzw_bits)) {
                            table[0][code]=oldcode;
                            table[1][code]=firstcode;
                            max_code++;
                            if ((max_code>=max_code_size)
                             && (max_code_size<(1<<max_lzw_bits)))
                            {
                                max_code_size*=2;
                                code_size++;
                            }
                        }
                        oldcode=incode;
                        const int h = image->height();
                        const QRgb *map = lcmap ? localcmap : globalcmap;
                        QRgb *line = 0;
                        if (!out_of_bounds && h > y)
                            line = (QRgb*)FAST_SCAN_LINE(bits, bpl, y);
                        while (sp>stack) {
                            const uchar index = *(--sp);
                            if (!out_of_bounds && h > y && index!=trans_index) {
                                if (index > ncols)
                                    line[x] = Q_TRANSPARENT;
                                else
                                    line[x] = map ? map[index] : 0;
                            }
                            x++;
                            if (x>=swidth) out_of_bounds = true;
                            if (x>=left+width) {
                                x=left;
                                out_of_bounds = left>=swidth || y>=sheight;
                                nextY(bits, bpl);
                                if (!out_of_bounds && h > y)
                                    line = (QRgb*)FAST_SCAN_LINE(bits, bpl, y);
                            }
                        }
                    }
                }
            }
            partialNewFrame = true;
            if (count==expectcount) {
                count=0;
                state=ImageDataBlockSize;
            }
            break;
          case ExtensionLabel:
            switch (ch) {
            case 0xf9:
                state=GraphicControlExtension;
                break;
            case 0xff:
                state=ApplicationExtension;
                break;
#if 0
            case 0xfe:
                state=CommentExtension;
                break;
            case 0x01:
                break;
#endif
            default:
                state=SkipBlockSize;
            }
            count=0;
            break;
          case ApplicationExtension:
            if (count<11) hold[count]=ch;
            count++;
            if (count==hold[0]+1) {
                if (qstrncmp((char*)(hold+1), "NETSCAPE", 8)==0) {
                    // Looping extension
                    state=NetscapeExtensionBlockSize;
                } else {
                    state=SkipBlockSize;
                }
                count=0;
            }
            break;
          case NetscapeExtensionBlockSize:
            expectcount=ch;
            count=0;
            if (expectcount) state=NetscapeExtensionBlock;
            else state=Introducer;
            break;
          case NetscapeExtensionBlock:
            if (count<3) hold[count]=ch;
            count++;
            if (count==expectcount) {
                *loopCount = hold[1]+hold[2]*256;
                state=SkipBlockSize; // Ignore further blocks
            }
            break;
          case GraphicControlExtension:
            if (count<5) hold[count]=ch;
            count++;
            if (count==hold[0]+1) {
                disposePrevious(image);
                disposal=Disposal((hold[1]>>2)&0x7);
                //UNUSED: waitforuser=!!((hold[1]>>1)&0x1);
                int delay=count>3 ? LM(hold[2], hold[3]) : 1;
                // IE and mozilla use a minimum delay of 10. With the minimum delay of 10
                // we are compatible to them and avoid huge loads on the app and xserver.
                *nextFrameDelay = (delay < 2 ? 10 : delay) * 10;

                bool havetrans=hold[1]&0x1;
                trans_index = havetrans ? hold[4] : -1;

                count=0;
                state=SkipBlockSize;
            }
            break;
          case SkipBlockSize:
            expectcount=ch;
            count=0;
            if (expectcount) state=SkipBlock;
            else state=Introducer;
            break;
          case SkipBlock:
            count++;
            if (count==expectcount) state=SkipBlockSize;
            break;
          case Done:
            digress=true;
            /* Netscape ignores the junk, so we do too.
            length++; // Unget
            state=Error; // More calls to this is an error
            */
            break;
          case Error:
            return -1; // Called again after done.
        }
    }
Пример #18
0
void MainWindow::reset_view()
{
	m_fgcolor=qRgb(0,0,0);
	m_bgcolor=qRgb(0xff,0xff,0xff);
	update_preview();
}
Пример #19
0
    void render() {

        // setup the screen surface
        if (buffer.size() != bufferSize)
            buffer = QImage(bufferSize, QImage::Format_ARGB32);
        int bufw = buffer.width();
        int bufh = buffer.height();
        if (bufw <= 0 || bufh <= 0)
            return;

        // we intentionally cheat here, to avoid detach
        const uchar *ptr = buffer.bits();
        QRgb *start = (QRgb*)(ptr);
        QRgb stride = buffer.bytesPerLine() / 4;
        QRgb *finish = start + stride * bufh;

        // prepare the texture pointer
        const uchar *src = textureImg.bits();
        const QRgb *texsrc = reinterpret_cast<const QRgb*>(src);

        // cast all rays here
        qreal sina = sin(angle);
        qreal cosa = cos(angle);
        qreal u = cosa - sina;
        qreal v = sina + cosa;
        qreal du = 2 * sina / bufw;
        qreal dv = -2 * cosa / bufw;

        for (int ray = 0; ray < bufw; ++ray, u += du, v += dv) {
            // every time this ray advances 'u' units in x direction,
            // it also advanced 'v' units in y direction
            qreal uu = (u < 0) ? -u : u;
            qreal vv = (v < 0) ? -v : v;
            qreal duu = 1 / uu;
            qreal dvv = 1 / vv;
            int stepx = (u < 0) ? -1 : 1;
            int stepy = (v < 0) ? -1 : 1;

            // the cell in the map that we need to check
            qreal px = playerPos.x();
            qreal py = playerPos.y();
            int mapx = static_cast<int>(px);
            int mapy = static_cast<int>(py);

            // the position and texture for the hit
            int texture = 0;
            qreal hitdist = 0.1;
            qreal texofs = 0;
            bool dark = false;

            // first hit at constant x and constant y lines
            qreal distx = (u > 0) ? (mapx + 1 - px) * duu : (px - mapx) * duu;
            qreal disty = (v > 0) ? (mapy + 1 - py) * dvv : (py - mapy) * dvv;

            // loop until we hit something
            while (texture <= 0) {
                if (distx > disty) {
                    // shorter distance to a hit in constant y line
                    hitdist = disty;
                    disty += dvv;
                    mapy += stepy;
                    texture = world_map[mapy][mapx];
                    if (texture > 0) {
                        dark = true;
                        if (stepy > 0) {
                            qreal ofs = px + u * (mapy - py) / v;
                            texofs = ofs - floor(ofs);
                        } else {
                            qreal ofs = px + u * (mapy + 1 - py) / v;
                            texofs = ofs - floor(ofs);
                        }
                    }
                } else {
                    // shorter distance to a hit in constant x line
                    hitdist = distx;
                    distx += duu;
                    mapx += stepx;
                    texture = world_map[mapy][mapx];
                    if (texture > 0) {
                        if (stepx > 0) {
                            qreal ofs = py + v * (mapx - px) / u;
                            texofs = ofs - floor(ofs);
                        } else {
                            qreal ofs = py + v * (mapx + 1 - px) / u;
                            texofs = ceil(ofs) - ofs;
                        }
                    }
                }
            }

            // get the texture, note that the texture image
            // has two textures horizontally, "normal" vs "dark"
            int col = static_cast<int>(texofs * TEXTURE_SIZE);
            col = qBound(0, col, TEXTURE_SIZE - 1);
            texture = (texture - 1) % textureCount;
            const QRgb *tex = texsrc + TEXTURE_BLOCK * texture * 2 +
                              (TEXTURE_SIZE * 2 * col);
            if (dark)
                tex += TEXTURE_SIZE;

            // start from the texture center (horizontally)
            int h = static_cast<int>(bufw / hitdist / 2);
            int dy = (TEXTURE_SIZE << 12) / h;
            int p1 = ((TEXTURE_SIZE / 2) << 12) - dy;
            int p2 = p1 + dy;

            // start from the screen center (vertically)
            // y1 will go up (decrease), y2 will go down (increase)
            int y1 = bufh / 2;
            int y2 = y1 + 1;
            QRgb *pixel1 = start + y1 * stride + ray;
            QRgb *pixel2 = pixel1 + stride;

            // map the texture to the sliver
            while (y1 >= 0 && y2 < bufh && p1 >= 0) {
                *pixel1 = tex[p1 >> 12];
                *pixel2 = tex[p2 >> 12];
                p1 -= dy;
                p2 += dy;
                --y1;
                ++y2;
                pixel1 -= stride;
                pixel2 += stride;
            }

            // ceiling and floor
            for (; pixel1 > start; pixel1 -= stride)
                *pixel1 = qRgb(0, 0, 0);
            for (; pixel2 < finish; pixel2 += stride)
                *pixel2 = qRgb(96, 96, 96);
        }

        update(QRect(QPoint(0, 0), bufferSize));
    }
Пример #20
0
MainWindow::MainWindow(QWidget* parent, Qt::WFlags fl)
		: QWidget(parent, fl),m_optionWidget(0)
{

	char bstyle_text[][50] = {
		"Australia Post Redirect Code",
		"Australia Post Reply-Paid",
		"Australia Post Routing Code",
		"Australia Post Standard Customer",
		"Aztec Code (ISO 24778)",
		"Aztec Runes",
		"Channel Code",
		"Codabar",
		"Code 11",
		"Code 128 (ISO 15417)",
		"Code 16k",
		"Code 2 of 5 Data Logic",
		"Code 2 of 5 IATA",
		"Code 2 of 5 Industrial",
		"Code 2 of 5 Interleaved",
		"Code 2 of 5 Matrix",
		"Code 32 (Italian Pharmacode)",
		"Code 39 (ISO 16388)",
		"Code 39 Extended",
		"Code 49",
		"Code 93", 
		"Code One",
		"Databar",
		"Databar Expanded",
		"Databar Expanded Stacked",
		"Databar Limited",
		"Databar Stacked",
		"Databar Stacked Omnidirectional",
		"Data Matrix (ISO 16022)",
		"Deutsche Post Identcode",
		"Deutsche Post Leitcode",
		"Dutch Post KIX",
		"EAN-14",
		"European Article Number (EAN)",
		"Facing Identification Mark (FIM)",
		"Flattermarken",
		"Grid Matrix",
		"ITF-14",
		"International Standard Book Number (ISBN)",
		"Japanese Postal Barcode",
		"Korean Postal Barcode",
		"LOGMARS",
		"Maxicode (ISO 16023)",
		"MicroPDF417 (ISO 24728)",
		"Micro QR Code",
		"MSI Plessey",
		"NVE-18",
		"PDF417 (ISO 15438)",
		"Pharmacode",
		"Pharmacode 2-track",
		"Pharma Zentralnummer (PZN)",
		"PLANET",
		"Postnet",
		"QR Code (ISO 18004)",
		"Royal Mail 4-state Barcode",
		"Telepen",
		"Telepen Numeric",
		"UK Plessey",
		"Universal Product Code (UPC-A)",
		"Universal Product Code (UPC-E)",
		"USPS Intelligent Mail"
	};
		
	/* createActions();
	createMenus();	*/
	
	setupUi(this);
	view->setScene(new QGraphicsScene);
	
	m_fgcolor=qRgb(0,0,0);
	m_bgcolor=qRgb(0xff,0xff,0xff);
	for (int i=0;i<metaObject()->enumerator(0).keyCount();i++) {
		bstyle->addItem(metaObject()->enumerator(0).key(i));
		bstyle->setItemText(i,bstyle_text[i]);
	}
	bstyle->setCurrentIndex(9);
	change_options();
	update_preview();
	view->scene()->addItem(&m_bc);
	connect(bstyle, SIGNAL(currentIndexChanged( int )), SLOT(change_options()));
	connect(bstyle, SIGNAL(currentIndexChanged( int )), SLOT(update_preview()));
	connect(heightb, SIGNAL(valueChanged( int )), SLOT(update_preview()));
	connect(bwidth,  SIGNAL(valueChanged( int )), SLOT(update_preview()));
	connect(btype, SIGNAL(currentIndexChanged( int )), SLOT(update_preview()));
	connect(txtData, SIGNAL(textChanged( const QString& )), SLOT(update_preview()));
	connect(txtComposite, SIGNAL(textChanged()), SLOT(update_preview()));
	connect(chkComposite, SIGNAL(stateChanged( int )), SLOT(composite_enable()));
	connect(chkComposite, SIGNAL(stateChanged( int )), SLOT(update_preview()));
	connect(cmbCompType, SIGNAL(currentIndexChanged( int )), SLOT(update_preview()));
	connect(spnWhitespace, SIGNAL(valueChanged( int )), SLOT(update_preview()));
	connect(btnAbout, SIGNAL(clicked( bool )), SLOT(about()));
	connect(btnSave, SIGNAL(clicked( bool )), SLOT(save()));
	connect(spnScale, SIGNAL(valueChanged( double )), SLOT(change_print_scale()));
	connect(btnExit, SIGNAL(clicked( bool )), SLOT(quit_now()));
	connect(btnReset, SIGNAL(clicked( bool )), SLOT(reset_view()));
	connect(btnMoreData, SIGNAL(clicked( bool )), SLOT(open_data_dialog()));
	connect(btnSequence, SIGNAL(clicked( bool )), SLOT(open_sequence_dialog()));
	connect(chkHRTHide, SIGNAL(stateChanged( int )), SLOT(update_preview()));
}
Пример #21
0
 QRgb map(QRgb pixel, QPoint) const {
     return qRgb(qRed(pixel), qGreen(pixel), m_corrector(qBlue(pixel)));
 }
QImage Triangledetection::detect(const QImage &source, const QImage &imageBase)
{
    //QImage binary = detectionContour(extraireRouge(source));
    QImage binary = detectionContour(source);
    QImage detection = binary.convertToFormat(QImage::Format_RGB888);

    QVector<QPoint> ligne = hough(detection);
    std::cout << "-> Nombre de ligne detecté : " << ligne.size() << std::endl;

    QVector<QPoint> ligne_angle0,ligne_angle60,ligne_angle120;
    QPoint inter1,inter2,inter3;
    int l1,l2,l3;



    //Avoir les lignes avec des angles pouvant appartenir à un panneau (+ ou - 1°)
    avoirLigneAngle(ligne,ligne_angle0,90,1);
    avoirLigneAngle(ligne,ligne_angle0,270,1);

    avoirLigneAngle(ligne,ligne_angle60,150,1);
    avoirLigneAngle(ligne,ligne_angle60,330,1);

    avoirLigneAngle(ligne,ligne_angle120,210,1);
    avoirLigneAngle(ligne,ligne_angle120,30,1);

    //On determine les intersections et les longueurs des segments
    for(int i=0;i<ligne_angle0.size();i++)
    {
        for(int j=0;j<ligne_angle60.size();j++)
        {
            for(int k=0;k<ligne_angle120.size();k++)
            {

                inter1 = intersection(ligne_angle0[i],ligne_angle60[j]);
                inter2 = intersection(ligne_angle60[j],ligne_angle120[k]);
                inter3 = intersection(ligne_angle120[k],ligne_angle0[i]);

                l1 = distance(inter1,inter2);
                l2 = distance(inter2,inter3);
                l3 = distance(inter3,inter1);

                //Si les distance sont les mêmes et que tous les points sont dans l'image => on a un triangle
                if(l1 == l2 && l2 == l3 && l1 > 30 && l1 < 100 && estPointImage(detection,inter1) && estPointImage(detection,inter2) && estPointImage(detection,inter3))
                {
                    Triangle a;
                    a.p1 = inter1;
                    a.p2 = inter2;
                    a.p3 = inter3;
                    liste_triangle.push_back(a);
                }
            }
        }
    }

    std::cout<<"-> Nombre de triangle detectés avant élimination des doublons : " << liste_triangle.size() << std::endl;

    //On supprime les triangle doublons
    supprimerDoublon();

    //Dessiner les triangles à l'écran
    for(int i=0;i<liste_triangle.size();i++)
        dessiner(detection,liste_triangle[i],qRgb(0,255,127));


    //Generer les images avec les cercles reconnus
    for(int i=0;i<liste_triangle.size();i++)
    {
        int minX = liste_triangle[i].p1.x();
        int minY = liste_triangle[i].p1.y();
        int maxX = liste_triangle[i].p1.x();
        int maxY = liste_triangle[i].p1.y();
        if (liste_triangle[i].p2.x()<minX) minX = liste_triangle[i].p2.x();
        if (liste_triangle[i].p2.y()<minY) minY = liste_triangle[i].p2.y();
        if (liste_triangle[i].p2.x()>maxX) maxX = liste_triangle[i].p2.x();
        if (liste_triangle[i].p2.y()>maxY) maxY = liste_triangle[i].p2.y();
        if (liste_triangle[i].p3.x()<minX) minX = liste_triangle[i].p3.x();
        if (liste_triangle[i].p3.y()<minY) minY = liste_triangle[i].p3.y();
        if (liste_triangle[i].p3.x()>maxX) maxX = liste_triangle[i].p3.x();
        if (liste_triangle[i].p3.y()>maxY) maxY = liste_triangle[i].p3.y();


        QImage BlueRoadSigns = QImage(maxX-minX, maxY-minY, QImage::Format_RGB32);

        for(int row = 0;row<maxY-minY;row++)
        {
            for (int col=0;col<maxX-minX;col++)
            {
                QColor clrCurrent(imageBase.pixel(col+minX,row+minY));

                int red = clrCurrent.red();
                int green = clrCurrent.green();
                int blue = clrCurrent.blue();

                BlueRoadSigns.setPixel(col, row, qRgb(red,green,blue));
            }
        }

        liste_TrianglesReconnu.push_back(BlueRoadSigns);
    }

    std::cout<<"-> Nombre de triangle detectés : " << liste_triangle.size() << std::endl;

    return detection;
}
Пример #23
0
void Controller::ComputeSteerableViewMap()
{
#if 0  //soc
    if ((!_Canvas) || (!_ViewMap))
        return;

    // Build 4 nodes containing the edges in the 4 directions
    NodeGroup *ng[Canvas::NB_STEERABLE_VIEWMAP];
    unsigned i;
    real c = 32.0f/255.0f; // see SteerableViewMap::readSteerableViewMapPixel() for information about this 32.
    for (i = 0; i < Canvas::NB_STEERABLE_VIEWMAP; ++i) {
        ng[i] = new NodeGroup;
    }
    NodeShape *completeNS = new NodeShape;
    completeNS->material().setDiffuse(c,c,c,1);
    ng[Canvas::NB_STEERABLE_VIEWMAP-1]->AddChild(completeNS);
    SteerableViewMap * svm = _Canvas->getSteerableViewMap();
    svm->Reset();

    ViewMap::fedges_container& fedges = _ViewMap->FEdges();
    LineRep * fRep;
    NodeShape *ns;
    for (ViewMap::fedges_container::iterator f = fedges.begin(), fend = fedges.end();
            f != fend;
            ++f)
    {
        if ((*f)->viewedge()->qi() != 0)
            continue;
        fRep = new LineRep((*f)->vertexA()->point2d(), (*f)->vertexB()->point2d());
        completeNS->AddRep(fRep); // add to the complete map anyway
        double *oweights = svm->AddFEdge(*f);
        for (i = 0; i < (Canvas::NB_STEERABLE_VIEWMAP - 1); ++i) {
            ns = new NodeShape;
            double wc = oweights[i]*c;
            if (oweights[i] == 0)
                continue;
            ns->material().setDiffuse(wc, wc, wc, 1);
            ns->AddRep(fRep);
            ng[i]->AddChild(ns);
        }
    }

    GrayImage *img[Canvas::NB_STEERABLE_VIEWMAP];
    //#ifdef WIN32
    QGLBasicWidget offscreenBuffer(_pView, "SteerableViewMap", _pView->width(), _pView->height());
    QPixmap pm;
    QImage qimg;
    for (i = 0; i < Canvas::NB_STEERABLE_VIEWMAP; ++i) {
        offscreenBuffer.AddNode(ng[i]);
#if 0
        img[i] = new GrayImage(_pView->width(), _pView->height());
        offscreenBuffer.readPixels(0,0,_pView->width(), _pView->height(), img[i]->getArray());
#endif
        pm = offscreenBuffer.renderPixmap(_pView->width(), _pView->height());

        if (pm.isNull()) {
            if (G.debug & G_DEBUG_FREESTYLE) {
                cout << "BuildViewMap Warning: couldn't render the steerable ViewMap" << endl;
            }
        }
        //pm.save(QString("steerable") + QString::number(i) + QString(".bmp"), "BMP");
        // FIXME!! Lost of time !
        qimg = pm.toImage();
        // FIXME !! again!
        img[i] = new GrayImage(_pView->width(), _pView->height());
        for (unsigned int y = 0; y < img[i]->height(); ++y) {
            for (unsigned int x = 0; x < img[i]->width(); ++x) {
                //img[i]->setPixel(x, y, (float)qGray(qimg.pixel(x, y)) / 255.0f);
                img[i]->setPixel(x, y, (float)qGray(qimg.pixel(x, y)));
                //float c = qGray(qimg.pixel(x, y));
                //img[i]->setPixel(x, y, qGray(qimg.pixel(x, y)));
            }
        }
        offscreenBuffer.DetachNode(ng[i]);
        ng[i]->destroy();
        delete ng[i];
        // check
#if 0
        qimg = QImage(_pView->width(), _pView->height(), 32);
        for (unsigned int y = 0; y < img[i]->height(); ++y) {
            for (unsigned int x = 0; x < img[i]->width(); ++x) {
                float v = img[i]->pixel(x, y);
                qimg.setPixel(x, y, qRgb(v, v, v));
            }
        }
        qimg.save(QString("newsteerable") + QString::number(i) + QString(".bmp"), "BMP");
#endif
    }


    svm->buildImagesPyramids(img, false, 0, 1.0f);
#endif
}
Пример #24
0
void ConvDistThread :: run (void)
{
    if (!convParameters)
        return;
    QTime * fftTime = new QTime;
    fftTime->start();
    mFile.lock ();
    int ndn = convParameters->getNRChannels();
    int nd = FFT_Transform::pow2roundup (ndn);
    int nd2 = 2*ndn;
    CalcOpor1 * cop = new CalcOpor1 (nd);
    complex<double> * opor = cop->calc();//new complex<double> [nd];
    int N1 = convParameters->getImpNumb();
    qDebug () << __PRETTY_FUNCTION__ << N1;
    QFile fContData (QString ("stc4.dat"));
    fContData.open (QIODevice::WriteOnly);
    QTextStream stCont (&fContData);
    FFT_Transform fft;// = new FFT_Transform;
    emit sendData (opor, N1);
    //radDataWidget * wOpFFT = new radDataWidget (opor, N1);
    //emit sendWidget (wOpFFT, this);
/*    QMdiSubWindow * subWopFFT = m_mdiArea->addSubWindow (wOpFFT);
    wOpFFT->show ();
    subWopFFT->setAttribute (Qt::WA_DeleteOnClose);
*/
    QFile contOp ("opor_after_FFT.dat");
    contOp.open (QIODevice::WriteOnly);
    QTextStream stOp (&contOp);
    for (int i=0; i<N1; i++)
    {
        double re = real (opor[i])*nd;
        double im = imag (opor[i])*nd;
        stOp << re << " " << im << "i" << endl;
    }
    contOp.close ();

    QString fileName = convParameters->getInputFileName();
    QFile fData (fileName);
    quint8 * st = new quint8 [nd2];
    for (int i=0; i<nd2; i++)
    {
        st [i] = 0;
    }
    complex<double> * stc = new complex<double>[nd];
    complex<double> * stc1 = new complex<double>[nd];
    for (int i=0; i<nd; i++)
    {
        stc[i] = complex<double> (0.0, 0.0);
        stc1[i] = complex<double> (0.0, 0.0);
    }
    int a = 0;
    Q_UNUSED (a);

    FILE * fid5 = fopen (fileName.toAscii().constData(), "rb");
    qDebug () << __PRETTY_FUNCTION__ << fileName.toAscii().constData() << fid5;
    if (!fData.open (fid5, QIODevice::ReadOnly | QIODevice::Unbuffered))
    {
        mFile.unlock();
        return;
    }

    QString fileConvName = convParameters->getConvFileName();//QFileDialog::getSaveFileName (this, tr("Save 1st data"), QDir::currentPath(), tr("All files (*)"));

    FILE * fid6 = fileConvName.isEmpty() ? 0 : fopen (fileConvName.toAscii().constData(), "w+");

    int na = convParameters->getChannelsNumb ();
    qDebug () << __PRETTY_FUNCTION__ << (int)na;
    QAbstractItemModel * radModel = new QStandardItemModel (nd2, 1, 0);// (nd2, na);
    Q_UNUSED (radModel);

    int nr (0);
    Q_UNUSED (nr);
    QFile fContStData (QString ("stc.dat"));
    fContStData.open (QIODevice::WriteOnly);
    QTextStream stContSt (&fContStData);
    QSize imSize (nd, FFT_Transform::pow2roundup(na/50));
    QImage * convImage = new QImage (imSize, QImage::Format_RGB32);//QImage::Format_Mono);
    if (!convImage || convImage->size().isNull())
    {
        if (convImage)
            delete convImage;
        mFile.unlock();
        return;
    }
    convImage->fill (0);
    double maxval = 0.0;
//    stc2MatrAbs = new double (na*nd);
    qDebug () << __PRETTY_FUNCTION__ << fftTime->elapsed ();
    int nThr = convParameters->getNumThreads();
    fftw_init_threads ();
    fftw_plan_with_nthreads (nThr);
    for (int i0=0; i0<na; i0++)
    {
//        qDebug () << __PRETTY_FUNCTION__ << QString("Read new data");
/*        ConvDistColumnThread * thrCol = new ConvDistColumnThread (convParameters, fid5, fid6, i0, 0);
        connect (thrCol, SIGNAL (terminated()), this, SLOT (columnTerminated()) );
        connect (thrCol, SIGNAL (finished()), this, SLOT (columnFinished()) );
        thrCol->start();
        //while (!thrCol->isFinished())
        //    ;
        thrCol->wait();
        //thrCol->deleteLater();
*/
        int cr = fread (st, sizeof (quint8), nd2, fid5);
        if (cr <= 0)
            return;
        for (int ii=0; ii< nd2; ii++)
        {
            if (i0<1)
            {
                QModelIndex wcIndex = radModel->index (nr, 0);
                radModel->setData (wcIndex, QString::number (st[ii]), Qt::DisplayRole);
                nr++;
            }
        }

        for (int ii=0; ii<128; ii++)
            st[ii] = 0.0;

        for (int ii=0; ii<ndn; ii++)
        {
            double re = st[2*ii+1];
            double im = st[2*ii];
            if (re > 128)
                re -= 256;
            if (im > 128)
                im -= 256;
            if (i0==0)
                stContSt << re << " " << im << endl;
            stc[ii] = complex<double> (re, im);//st[2*ii], st[2*ii+1]);
        }
        complex<double> * stc4 = 0;//new complex<double> [nd];
        stc4 = fft (stc, nd, nd, FFTW_FORWARD, FFTW_ESTIMATE);
        //qDebug () << __PRETTY_FUNCTION__ << tr ("FFT of data, elapsed time %1").arg (fftTime->elapsed ()/1.0e3);
        for (int ii=0; ii<nd; ii++)
        {
            double re = real (stc4[ii])*nd;
            double im = imag (stc4[ii])*nd;
            stc4[ii] = complex<double> (re, im);
            if (i0==0)
                stCont << re << (im >= 0 ? "+" : " ") << im << "i" << endl;
        }

        for (int ii=0; ii<nd; ii++)
        {
            double rstc4 = real (stc4[ii])/nd;
            double imstc4 = imag (stc4[ii])/nd;
            double ropor = real (opor[ii]);
            double imopor = imag (opor[ii]);
            complex<double> res = complex<double> ((rstc4 * ropor - imstc4*imopor), (rstc4*imopor+imstc4*ropor));
            stc1[ii] = res;//stc4[i]*opor[i];///(nd*nd);
        }
        delete [] stc4;

        complex<double> * xfft = 0;//new complex<double> [nd];
        //qDebug () << __PRETTY_FUNCTION__ << QString ("Reverse fft");
        xfft = fft (stc1, nd, nd, FFTW_BACKWARD, FFTW_ESTIMATE );//| FFTW_MEASURE);
        //delete [] xConv;
        double * stc2 = new double [2*nd];
        //double * stc2abs = new double [nd];
        for (int ii=0; ii<nd; ii++)
        {
            int ind = ii;//(ii==0 ? nd-1 : ii-1);
            stc2[2*ii] = real (xfft[ind])/nd;//stc3[i]);
            stc2[2*ii+1] = imag (xfft[ind])/nd;
            double vmod = sqrt (stc2[2*ii]*stc2[2*ii] + stc2[2*ii+1]*stc2[2*ii+1]);
            maxval = qMax (maxval, vmod);
        }
        if (fid6)
        {
            //qDebug () << __PRETTY_FUNCTION__ << QString ("Write data");
            size_t h = fwrite (stc2, sizeof (double)/2, 2*nd, fid6);
            int ier = ferror (fid6);
            //qDebug () << __PRETTY_FUNCTION__ << QString ("Data were written %1 bytes, error indicator =%2 ").arg (h).arg(ier);
            if (h ==0 || ier)
            {
                qDebug () << __PRETTY_FUNCTION__ << tr ("Write error, code=%1").arg (ier);
                return;
            }
        }
        delete [] xfft;

        //delete [] stc2abs;
        delete [] stc2;
    }
    delete cop;
    if (fid6)
        fclose (fid6);
    mFile.unlock();
    fid6 = fileConvName.isEmpty() ? 0 : fopen (fileConvName.toAscii().constData(), "r+");
    qDebug () << __PRETTY_FUNCTION__ << maxval;
    if (fid6)
    {
        double * vals = new double [nd];
        int * nums = new int [nd];
        for (int i=0; i<nd; i++)
        {
            vals[i] = 0.0;
            nums[i] = 0;
        }

        for (int i0 = 0; i0 < FFT_Transform::pow2roundup(na/50); i0++)
        {
            for (int i=0; i<50; i++)
            {
                double * stc2c = new double [2*nd];
                size_t h = fread (stc2c, sizeof (double)/2, 2*nd, fid6);
                //qDebug () << __PRETTY_FUNCTION__ << h;
                if (h > 0)
                {
                    for (int ii=0; ii<nd; ii++)
                    {
                        vals [ii] += sqrt (stc2c[2*ii]*stc2c[2*ii] + stc2c[2*ii+1]*stc2c[2*ii+1]);
                        nums[ii]++;
                    }
                }
                delete [] stc2c;
            }
            for (int ii=0; ii<nd; ii++)
            {
                double vmod = vals[ii]/nums[ii];//sqrt (stc2c[2*ii]*stc2c[2*ii] + stc2c[2*ii+1]*stc2c[2*ii+1]);
                
                double gray = (vmod/maxval)*convParameters->getNCalibration();
                //vals [(i0+1)%50+ii] = gray;
                //if ((i0+1)/50*50 == i0+1)
                //{
                //    double gray_ave (0.0);
                //    for (int iii=0; iii<50; iii++)
                //        gray_ave += vals [iii];
                uint val = (uint)(256*(gray));

                QRgb v = qRgb (val, val, val);
                convImage->setPixel (ii, i0, v);//qRgb(val, val, val));
                //}
            }
        }
        delete [] vals;
    }
    fftw_cleanup_threads ();
    //delete [] vals;
    qDebug () << __PRETTY_FUNCTION__ << QString ("Data were read and processed");
    fContData.close();
//    double * stc2abs = new double [nd];
    qDebug () << __PRETTY_FUNCTION__ << convImage->size () << imSize;
    QString fileImageName = QString ("rgg.png");
    convImage->save (fileImageName, "PNG");
    //rggImageWidget * imW = new rggImageWidget;
    //imW->setImage (*convImage);
    //emit sendWidget (imW, this);
    emit sendImage (convImage);
    int msecs = fftTime->elapsed ();
    emit sendTime (msecs);
    delete fftTime;

    delete [] stc1;
    delete [] st;
//    exec();
}
Пример #25
0
void B9Projector::blankProjector()
{
	mImage.fill(qRgb(0,0,0));
}
Пример #26
0
static bool read_jpeg_image(QImage *outImage,
                            QSize scaledSize, QRect scaledClipRect,
                            QRect clipRect, volatile int inQuality, j_decompress_ptr info, struct my_error_mgr* err  )
{
    if (!setjmp(err->setjmp_buffer)) {
        // -1 means default quality.
        int quality = inQuality;
        if (quality < 0)
            quality = 75;

        // If possible, merge the scaledClipRect into either scaledSize
        // or clipRect to avoid doing a separate scaled clipping pass.
        // Best results are achieved by clipping before scaling, not after.
        if (!scaledClipRect.isEmpty()) {
            if (scaledSize.isEmpty() && clipRect.isEmpty()) {
                // No clipping or scaling before final clip.
                clipRect = scaledClipRect;
                scaledClipRect = QRect();
            } else if (scaledSize.isEmpty()) {
                // Clipping, but no scaling: combine the clip regions.
                scaledClipRect.translate(clipRect.topLeft());
                clipRect = scaledClipRect.intersected(clipRect);
                scaledClipRect = QRect();
            } else if (clipRect.isEmpty()) {
                // No clipping, but scaling: if we can map back to an
                // integer pixel boundary, then clip before scaling.
                if ((info->image_width % scaledSize.width()) == 0 &&
                        (info->image_height % scaledSize.height()) == 0) {
                    int x = scaledClipRect.x() * info->image_width /
                            scaledSize.width();
                    int y = scaledClipRect.y() * info->image_height /
                            scaledSize.height();
                    int width = (scaledClipRect.right() + 1) *
                                info->image_width / scaledSize.width() - x;
                    int height = (scaledClipRect.bottom() + 1) *
                                 info->image_height / scaledSize.height() - y;
                    clipRect = QRect(x, y, width, height);
                    scaledSize = scaledClipRect.size();
                    scaledClipRect = QRect();
                }
            } else {
                // Clipping and scaling: too difficult to figure out,
                // and not a likely use case, so do it the long way.
            }
        }

        // Determine the scale factor to pass to libjpeg for quick downscaling.
        if (!scaledSize.isEmpty() && info->image_width && info->image_height) {
            if (clipRect.isEmpty()) {
                double f = qMin(double(info->image_width) / scaledSize.width(),
                                double(info->image_height) / scaledSize.height());

                // libjpeg supports M/8 scaling with M=[1,16]. All downscaling factors
                // are a speed improvement, but upscaling during decode is slower.
                info->scale_num   = qBound(1, qCeil(8/f), 8);
                info->scale_denom = 8;
            } else {
                info->scale_denom = qMin(clipRect.width() / scaledSize.width(),
                                         clipRect.height() / scaledSize.height());

                // Only scale by powers of two when clipping so we can
                // keep the exact pixel boundaries
                if (info->scale_denom < 2)
                    info->scale_denom = 1;
                else if (info->scale_denom < 4)
                    info->scale_denom = 2;
                else if (info->scale_denom < 8)
                    info->scale_denom = 4;
                else
                    info->scale_denom = 8;
                info->scale_num = 1;

                // Correct the scale factor so that we clip accurately.
                // It is recommended that the clip rectangle be aligned
                // on an 8-pixel boundary for best performance.
                while (info->scale_denom > 1 &&
                       ((clipRect.x() % info->scale_denom) != 0 ||
                        (clipRect.y() % info->scale_denom) != 0 ||
                        (clipRect.width() % info->scale_denom) != 0 ||
                        (clipRect.height() % info->scale_denom) != 0)) {
                    info->scale_denom /= 2;
                }
            }
        }

        // If high quality not required, use fast decompression
        if( quality < HIGH_QUALITY_THRESHOLD ) {
            info->dct_method = JDCT_IFAST;
            info->do_fancy_upsampling = false;
        }

        (void) jpeg_calc_output_dimensions(info);

        // Determine the clip region to extract.
        QRect imageRect(0, 0, info->output_width, info->output_height);
        QRect clip;
        if (clipRect.isEmpty()) {
            clip = imageRect;
        } else if (info->scale_denom == info->scale_num) {
            clip = clipRect.intersected(imageRect);
        } else {
            // The scale factor was corrected above to ensure that
            // we don't miss pixels when we scale the clip rectangle.
            clip = QRect(clipRect.x() / int(info->scale_denom),
                         clipRect.y() / int(info->scale_denom),
                         clipRect.width() / int(info->scale_denom),
                         clipRect.height() / int(info->scale_denom));
            clip = clip.intersected(imageRect);
        }

        // Allocate memory for the clipped QImage.
        if (!ensureValidImage(outImage, info, clip.size()))
            longjmp(err->setjmp_buffer, 1);

        // Avoid memcpy() overhead if grayscale with no clipping.
        bool quickGray = (info->output_components == 1 &&
                          clip == imageRect);
        if (!quickGray) {
            // Ask the jpeg library to allocate a temporary row.
            // The library will automatically delete it for us later.
            // The libjpeg docs say we should do this before calling
            // jpeg_start_decompress().  We can't use "new" here
            // because we are inside the setjmp() block and an error
            // in the jpeg input stream would cause a memory leak.
            JSAMPARRAY rows = (info->mem->alloc_sarray)
                              ((j_common_ptr)info, JPOOL_IMAGE,
                               info->output_width * info->output_components, 1);

            (void) jpeg_start_decompress(info);

            while (info->output_scanline < info->output_height) {
                int y = int(info->output_scanline) - clip.y();
                if (y >= clip.height())
                    break;      // We've read the entire clip region, so abort.

                (void) jpeg_read_scanlines(info, rows, 1);

                if (y < 0)
                    continue;   // Haven't reached the starting line yet.

                if (info->output_components == 3) {
                    uchar *in = rows[0] + clip.x() * 3;
                    QRgb *out = (QRgb*)outImage->scanLine(y);
                    rgb888ToRgb32ConverterPtr(out, in, clip.width());
                } else if (info->out_color_space == JCS_CMYK) {
                    // Convert CMYK->RGB.
                    uchar *in = rows[0] + clip.x() * 4;
                    QRgb *out = (QRgb*)outImage->scanLine(y);
                    for (int i = 0; i < clip.width(); ++i) {
                        int k = in[3];
                        *out++ = qRgb(k * in[0] / 255, k * in[1] / 255,
                                      k * in[2] / 255);
                        in += 4;
                    }
                } else if (info->output_components == 1) {
                    // Grayscale.
                    memcpy(outImage->scanLine(y),
                           rows[0] + clip.x(), clip.width());
                }
            }
        } else {
            // Load unclipped grayscale data directly into the QImage.
            (void) jpeg_start_decompress(info);
            while (info->output_scanline < info->output_height) {
                uchar *row = outImage->scanLine(info->output_scanline);
                (void) jpeg_read_scanlines(info, &row, 1);
            }
        }

        if (info->output_scanline == info->output_height)
            (void) jpeg_finish_decompress(info);

        if (info->density_unit == 1) {
            outImage->setDotsPerMeterX(int(100. * info->X_density / 2.54));
            outImage->setDotsPerMeterY(int(100. * info->Y_density / 2.54));
        } else if (info->density_unit == 2) {
            outImage->setDotsPerMeterX(int(100. * info->X_density));
            outImage->setDotsPerMeterY(int(100. * info->Y_density));
        }

        if (scaledSize.isValid() && scaledSize != clip.size()) {
            *outImage = outImage->scaled(scaledSize, Qt::IgnoreAspectRatio, quality >= HIGH_QUALITY_THRESHOLD ? Qt::SmoothTransformation : Qt::FastTransformation);
        }

        if (!scaledClipRect.isEmpty())
            *outImage = outImage->copy(scaledClipRect);
        return !outImage->isNull();
    }
    else
        return false;
}
void Light::processRgb(const QByteArray &data)
{
    if (data.size() >= 3)
        m_color = qRgb(uchar(data[0]), uchar(data[1]), uchar(data[2]));
    emit colorChanged();
}
Пример #28
0
/*******************************************************************************
Stitch together two images using the homography transformation

    image1: first input image
    image2: second input image
    hom: homography transformation (image1 -> image2)
    homInv: inverse homography transformation (image2 -> image1)
    stitchedImage: returned stitched image
*******************************************************************************/
void MainWindow::Stitch(QImage image1, QImage image2, double hom[3][3], double homInv[3][3], QImage &stitchedImage)
{
    // Width and height of stitchedImage
    int sWidth, sHeight;

	// To compute the width and height of stitchedImage, let's first get the corners of image2
	
	// Corners are like so (image2):
	//
	//    A           B
	//
	//
	//
	//    C           D
	//
	// (x, y) is for the original coordinates in image2's corners, while
	// (x_proj, y_proj) is the projected coordinates of image2's corners projected into image1

	double image2CornerA_x = 0.0;
	double image2CornerA_y = 0.0;
	double image2CornerB_x = image2.width();
	double image2CornerB_y = 0.0;
	double image2CornerC_x = 0.0;
	double image2CornerC_y = image2.height();
	double image2CornerD_x = image2.width();
	double image2CornerD_y = image2.height();

	double image2CornerA_x_proj, image2CornerA_y_proj,
		image2CornerB_x_proj, image2CornerB_y_proj,
		image2CornerC_x_proj, image2CornerC_y_proj,
		image2CornerD_x_proj, image2CornerD_y_proj;

	// Project points into image1
	Project(image2CornerA_x, image2CornerA_y, image2CornerA_x_proj, image2CornerA_y_proj, homInv);
	Project(image2CornerB_x, image2CornerB_y, image2CornerB_x_proj, image2CornerB_y_proj, homInv);
	Project(image2CornerC_x, image2CornerC_y, image2CornerC_x_proj, image2CornerC_y_proj, homInv);
	Project(image2CornerD_x, image2CornerD_y, image2CornerD_x_proj, image2CornerD_y_proj, homInv);

	// See how large we'll need to make the combined image
	sWidth = (int) ceil(max((double) image1.width(), max(image2CornerB_x_proj, image2CornerD_x_proj))
		- min(0.0, min(image2CornerA_x_proj, image2CornerC_x_proj)));
	sHeight = (int) ceil(max((double) image1.height(), max(image2CornerC_y_proj, image2CornerD_y_proj))
		- min(0.0, min(image2CornerA_y_proj, image2CornerB_y_proj)));

    stitchedImage = QImage(sWidth, sHeight, QImage::Format_RGB32);
    stitchedImage.fill(qRgb(0,0,0));

    // Copy image 1 into stitched image at offset determined by difference of dimensions
	// between it and the stitched image if image1 is to the right/below image2;
	// if image1 is to the left/above image2, then place it at 0 for the x-/y-axis
	
	int x_offset, y_offset;

	// If image2's farthest left corner is to the left of image1, give image1 an x offset
	if(min(image2CornerA_x_proj, image2CornerC_x_proj) < 0.0)
	{
		x_offset = stitchedImage.width() - image1.width();
	}
	else
	{
		x_offset = 0;
	}

	// If image2's farthest top corner is above image1, give image1 a y offset
	if(min(image2CornerA_y_proj, image2CornerB_y_proj) < 0.0)
	{
		y_offset = stitchedImage.height() - image1.height();
	}
	else
	{
		y_offset = 0;
	}
	
	for(int row = y_offset; row < image1.height() + y_offset; row++)
	{
		for(int col = x_offset; col < image1.width() + x_offset; col++)
		{
			stitchedImage.setPixel(col, row, image1.pixel(col - x_offset, row - y_offset));
		}
	}

	double stitchedImage_x_proj, stitchedImage_y_proj;

	// Place image 2 into stitched image
	for(int row = 0; row < stitchedImage.height(); row++)
	{
		for(int col = 0; col < stitchedImage.width(); col++)
		{
			// Project this point onto image2
			Project(col - x_offset, row - y_offset, stitchedImage_x_proj, stitchedImage_y_proj, hom);
			
			// If the projected point is within image2's boundaries,
			// add the pixel value to the stitched image
			if( (0.0 < stitchedImage_x_proj) &&
				(stitchedImage_x_proj < image2.width()) &&
				(0.0 < stitchedImage_y_proj) &&
				(stitchedImage_y_proj < image2.height()))
			{
				double color[3];
				BilinearInterpolation(&image2, stitchedImage_x_proj, stitchedImage_y_proj, color);
				// Modify colors to blend edges, if image1 is already drawn here
				if(stitchedImage.pixel(col, row) != qRgb(0, 0, 0))
				{
					// Weight each image equally
					color[0] = 0.5 * color[0] + 0.5 * qRed(stitchedImage.pixel(col, row));
					color[1] = 0.5 * color[1] + 0.5 * qGreen(stitchedImage.pixel(col, row));
					color[2] = 0.5 * color[2] + 0.5 * qBlue(stitchedImage.pixel(col, row));
				}
				else
				{
					// Just use the image2 colors as-is
				}
				stitchedImage.setPixel(col, row, qRgb((int) color[0], (int) color[1], (int) color[2]));
			}
		}
	}
}
Пример #29
0
QRgb QColorDialogOptions::customColor(int index)
{
    if (uint(index) >= uint(QColorDialogStaticData::CustomColorCount))
        return qRgb(255, 255, 255);
    return qColorDialogStaticData()->customRgb[index];
}
Пример #30
0
QImage Display::draw(QImage image,int li,int co){

    QRgb value;

    float resolucao_tela_linhas = li;
    float resolucao_tela_colunas = co;

    float resolucao_imagen_linhas = li;
    float resolucao_imagen_colunas = co;

    int var = resolucao_imagen_linhas*resolucao_imagen_colunas;

    cam.ampixel(resolucao_tela_linhas,resolucao_tela_colunas,resolucao_imagen_linhas,resolucao_imagen_colunas);
    cam.map(resolucao_tela_linhas,resolucao_tela_colunas,resolucao_imagen_linhas,resolucao_imagen_colunas);

    //cam.coordcamera(0.0,0.0,0.0);//0.0,0.0,1.0

    /*
    vect at,up,eye;
    at.set(0.0,0.0,0.0,1.0);
    eye.set(0.0,4.0,5.0,1.0);
    up.set(0.0,2.0,5.0,1.0);
    */


    //vect at,up,eye;
    //at.set(0.0,0.0,0.0,1.0);
    //eye.set(0.0,5.0,-5.0,1.0);
    //up.set(0.0,6.0,-5.0,1.0);



    vect at,up,eye;
    at.set(0.0,0.0,0.0,1.0);
    eye.set(0.0,0.0,7.0,1.0);
    up.set(0.0,0.0,1.0,1.0);
    //cam.sistemaCamera(at,up,eye);
    //cam.hortoProjection(false);
    //cam.perspectiva(5.0,5.0,0.01,120000.0);
    //cam.frustum(-50,50,-50,50,-50,50);

//------------------------------------------------------------------------------------------------------------------------------------
    //define iluminação

    light fonte;
    fonte.state(false);
    fonte.coord(-2.0,2.0,3.0);                          //-0.2,0.2,1.0
    fonte.comp_ambiente(1.0,1.0,1.0);
    fonte.comp_difusa(1.0,1.0,1.0);
    fonte.comp_specular(1.0,1.0,1.0);

    light fonte2;
    fonte2.state(false);
    fonte2.coord(2.0,5.0,0.0);                         //0.2,0.5,0.0
    fonte2.comp_ambiente(1.0,1.0,1.0);
    fonte2.comp_difusa(1.0,1.0,1.0);
    fonte2.comp_specular(1.0,1.0,1.0);

    cam.addlight(fonte);
    cam.addlight(fonte2);


    cam.atenuacao(false);
    cam.enableshadow(true);
//-----------------------------------------------------------------------------------------------------------------------------------
//define objetos

    _matrix.resetmatrix();
    _matrix.translate(0.2,-0.2,-0.5);
    objeto esfera;
    esfera.tipo("esfera");
    esfera.setraio(0.02);                               //esfera.raio = 0.02;
    esfera.refracao(true);
    esfera.reflexao(false);
    esfera.indrefracao(20.0);                           //20.8//esfera.centro(0.2,-0.2,-0.5);//0.2,-0.2,-0.5
    esfera.comp_ambiente(0.01,0.01,0.01);               //0.05,0.06,0.01   0.04,0.04,0.04
    esfera.comp_difusa(0.03,0.03,0.03);                 //0.5,0.6,0.1    0.08,0.08,0.08
    esfera.comp_specular(1.0,1.0,1.0,1000.0);           //1.0,1.0,1.0,100.0    1.0,1.0,1.0,1000
    esfera.setmatrix(_matrix.getmatrix());
    esfera.setinvmatrix(_matrix.getinvmatrix());
                                                        //_matrix.translate(0.2,0.0,0.0);//_matrix.rotate_xaxis(80.0);//_matrix.escala(1.0,1.0,1.0);
    _matrix.resetmatrix();
    //_matrix.escala(1.0,2.0,1.0);
    //_matrix.rotate_xaxis(45.0);
    _matrix.translate(0.1,0.3,-0.5);//0.1,0.3,-0.5
    objeto esfera2;                                     //esfera2.centro(0.0,0.0,-1.0);
    esfera2.tipo("esfera");
    //esfera2.centro(0.1,0.3,-0.5);
    esfera2.setraio(0.02);                              //esfera2.raio = 0.02;//esfera2.centro(0.2,0.0,0.0);//0.1,0.3,-0.5
    esfera2.comp_ambiente(0.05,0.06,0.01);              //0.03,0.02,0.01  0.05,0.06,0.01
    esfera2.comp_difusa(0.5,0.6,0.1);                   //0.3,0.2,0.1
    esfera2.comp_specular(1.0,1.0,1.0,100.0);           //1.0,1.0,1.0,100
    esfera2.setmatrix(_matrix.getmatrix());
    esfera2.setinvmatrix(_matrix.getinvmatrix());


    //_matrix.resetmatrix();

    /*
    objeto esfera2;
    esfera2.tipo("esfera");
    //esfera2.setraio(0.02);
    esfera2.comp_ambiente(0.05,0.06,0.01);
    esfera2.comp_difusa(0.5,0.6,0.1);
    esfera2.comp_specular(1.0,1.0,1.0,100.0);
    //esfera2.translate(0.5,0.0,0.0);
    //esfera2.scale(1.0,2.0,1.0);
    //esfera2.rotate_Z(90.0);
    //esfera2.rotate_X(90.0);
    //esfera2.rotate_Y(90.0);
    */


    objeto plano;
    plano.tipo("plano");
    plano.reflexao(true);
    plano.vet_normal(0.0,0.0,1.0);                      //0.0,0.0,1.0
    plano.pontop(0.0,0.0,-1.0);
    plano.comp_ambiente(0.04,0.04,0.04);                //0.05,0.05,0.05    0.04,0.04,0.04
    plano.comp_difusa(0.0,0.0,0.0);                  //0.7,0.7,0.7         0.08,0.08,0.08
    plano.comp_specular(1.0,1.0,1.0,1000.0);            //0.0,0.0,0.0
    plano.ponto_se(-0.5,0.5,-1.0);
    plano.ponto_id(0.5,-0.5,-1.0);

    objeto plano2;
    plano2.tipo("plano");
    plano2.vet_normal(-1.0,0.0,0.0);
    plano2.pontop(0.5,0.0,0.0);
    plano2.comp_ambiente(0.05,0.01,0.01);               //0.1,0.02,0.02
    plano2.comp_difusa(0.3,0.1,0.1);                    //0.3,0.1,0.1
    plano2.comp_specular(0.0,0.0,0.0,5.0);              //1.0,1.0,1.0,50
    plano2.ponto_se(0.5,0.5,-1.0);
    plano2.ponto_id(0.5,-0.5,1.0);

    objeto plano3;
    plano3.tipo("plano");
    plano3.vet_normal(0.0,1.0,0.0);
    plano3.pontop(0.0,-0.5,0.0);
    plano3.comp_ambiente(0.01,0.01,0.05);               //0.02,0.02,0.1
    plano3.comp_difusa(0.1,0.1,0.3);                    //0.1,0.1,0.3
    plano3.comp_specular(0.0,0.0,0.0,5.0);              //0.1,0.1,0.3
    plano3.ponto_se(-0.5,-0.5,-1.0);
    plano3.ponto_id(0.5,-0.5,1.0);

    objeto plano4;
    plano4.tipo("plano");
    plano4.vet_normal(1.0,0.0,0.0);                     //1.0,0.0,0.0
    plano4.pontop(-0.5,0.0,0.0);                        //-0.5,0.0,0.0
    plano4.comp_ambiente(0.01,0.05,0.01);               //0.02,0.1,0.02
    plano4.comp_difusa(0.1,0.3,0.1);                    //0.1,0.3,0.1
    plano4.comp_specular(0.0,0.0,0.0,5.0);              //0.1,0.3,0.1
    plano4.ponto_se(-0.5,0.5,-1.0);                     //-0.5,0.5,-1.0
    plano4.ponto_id(-0.5,-0.5,1.0);                     //-0.5,-0.5,1.0


    _matrix.resetmatrix();
    _matrix.translate(-0.2,-0.5,-0.5);                   //_matrix.escala(0.01,0.01,0.01);
    objeto cilindro;
    cilindro.tipo("cilindro");
    cilindro.raio = 0.01;
    cilindro.altura = 0.7;
    cilindro.indrefracao(20.0);
    cilindro.refracao(false);
    cilindro.reflexao(false);                           //cilindro.centro(-0.2,0.0,-0.5);//-0.2,0.0,-0.5
    cilindro.comp_ambiente(0.1,0.08,0.08);              //0.1,0.08,0.08
    cilindro.comp_difusa(0.5,0.4,0.4);
    cilindro.comp_specular(1.0,1.0,1.0,1000.0);
    cilindro.setmatrix(_matrix.getmatrix());
    cilindro.setinvmatrix(_matrix.getinvmatrix());

/*
    _matrix.resetmatrix();
    //_matrix.escala(1.0,2.0,1.0);
    _matrix.translate(0.0,-0.4,-0.2);                   //_matrix.rotate_xaxis(90.0);//_matrix.translate(0.0,-0.4,-0.2);//_matrix.escala(1.0,0.1,1.0);
    objeto cubo;
    cubo.tipo("cubo");                                  //cubo.centro(0.0,-0.4,-0.2);
    cubo.reflexao(false);
    cubo.dimencao = 0.2;                                //cubo.centro(0.0,-0.4,-0.2);   //0.0,-0.4,-0.2
    cubo.comp_ambiente(0.01,0.0027,0.0);                //0.01,0.0027,0.0               //0.1,0.0027,0.0    //0.01,0.0027,0.0
    cubo.comp_difusa(0.7,0.27,0.0);                     //0.7,0.27,0.0                  //1.0,0.27,0.0
    cubo.comp_specular(0.0,0.0,0.0,100.0);              //1.0,1.0,1.0,100.0
    cubo.setmatrix(_matrix.getmatrix());
    cubo.setinvmatrix(_matrix.getinvmatrix());
*/

    objeto cubo;
    cubo.tipo("cubo");
    //cubo.dimencao = 0.5;
    cubo.comp_ambiente(0.1,0.0027,0.0);
    cubo.comp_difusa(0.7,0.27,0.0);
    cubo.comp_specular(0.0,0.0,0.0,100.0);
    //cubo.translate(0.5,0.0,0.0);
    //cubo.scale(1.0,0.2,1.0);
    //cubo.rotate_X(45.0);
    //cubo.rotate_Y(45.0);
    //cubo.rotate_Z(45.0);

    //cubo._translate.printMatrix();
    //cubo.rotateX.printMatrix();
    //cubo.rotateY.printMatrix();
    //cubo.rotateZ.printMatrix();
    //cubo._escale.printMatrix();



    //cam.addObj(plano2);
    //cam.addObj(plano3);
    //cam.addObj(plano4);
    //cam.addObj(cilindro);
    //cam.addObj(esfera);
    //cam.addObj(esfera2);
    //cam.addObj(plano);
    //cam.addObj(cubo);

    QString nome;
    nome.append("teste");

    cam.loadSceneXML(nome);//--------------------------------

/*
    _matrix.resetmatrix();
    _matrix.translate(0.0,-0.2,0.5);
    _matrix.rotate_xaxis(90.0);
    _matrix.escala(0.7,0.01,0.7);
    objeto parede0;
    parede0.tipo("cubo");
    parede0.reflexao(false);
    parede0.dimencao = 1.0;
    parede0.comp_ambiente(0.04,0.04,0.04);
    parede0.comp_difusa(0.07,0.07,0.07);
    parede0.comp_specular(0.0,0.0,0.0,5.0);
    parede0.setmatrix(_matrix.getmatrix());
    parede0.setinvmatrix(_matrix.getinvmatrix());



    _matrix.resetmatrix();
    _matrix.translate(0.0,-0.5,0.0);
    _matrix.escala(0.7,0.01,0.7);
    objeto parede1;
    parede1.tipo("cubo");
    parede1.reflexao(false);
    parede1.dimencao = 1.0;
    parede1.comp_ambiente(0.01,0.01,0.05);
    parede1.comp_difusa(0.1,0.1,0.3);
    parede1.comp_specular(0.0,0.0,0.0,5.0);
    parede1.setmatrix(_matrix.getmatrix());
    parede1.setinvmatrix(_matrix.getinvmatrix());
*/

    //cam.addObj(parede0);
    //cam.addObj(parede1);


//----------------------------------------------------------------------------------------------------------------------------------



    cam.intersect();


    int r,g,b;
    for(int i=1;i<=var;i++){

        r = (int)(cam.film[i-1].cor[0]*255);
        g = (int)(cam.film[i-1].cor[1]*255);
        b = (int)(cam.film[i-1].cor[2]*255);

        if(r > 255){
            r = 255;
        }
        if(g > 255){
            g = 255;
        }
        if(b > 255){
            b = 255;
        }

        value = qRgb(r,g,b);
        image.setPixel(cam.film[i-1].x_tela,cam.film[i-1].y_tela,value);
    }

    free(cam.film);

    image.save("teste.png",0,100);
    return image;
}