Color4 EvolutionGraphWidget::QColor2Col( const QColor& color )
{
	return Color4(color.red(), color.green(), color.blue(), 255); // ignore alpha
}
Ejemplo n.º 2
0
Color::Color(const QColor& c)
    : m_color(makeRGBA(c.red(), c.green(), c.blue(), c.alpha()))
{
    m_valid = c.isValid();
}
Ejemplo n.º 3
0
QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
                                       const int num_samples, const int)
{
    if (
            audioFrame.size() > 63
            && m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0    // <= 0 if widget is too small (resized by user)
    ) {
        if (!m_customFreq) {
            m_freqMax = freq / 2;
        }

        QTime start = QTime::currentTime();


#ifdef DETECT_OVERMODULATION
        bool overmodulated = false;
        int overmodulateCount = 0;

        for (int i = 0; i < audioFrame.size(); i++) {
            if (
                    audioFrame[i] == std::numeric_limits<int16_t>::max()
                    || audioFrame[i] == std::numeric_limits<int16_t>::min()) {
                overmodulateCount++;
                if (overmodulateCount > 3) {
                    overmodulated = true;
                    break;
                }
            }
        }
        if (overmodulated) {
            colorizeFactor = 1;
        } else {
            if (colorizeFactor > 0) {
                colorizeFactor -= .08;
                if (colorizeFactor < 0) {
                    colorizeFactor = 0;
                }
            }
        }
#endif


        // Determine the window size to use. It should be
        // * not bigger than the number of samples actually available
        // * divisible by 2
        int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
        if (fftWindow > num_samples) {
            fftWindow = num_samples;
        }
        if ((fftWindow & 1) == 1) {
            fftWindow--;
        }

        // Show the window size used, for information
        ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());


        // Get the spectral power distribution of the input samples,
        // using the given window size and function
        float freqSpectrum[fftWindow/2];
        FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
        m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);


        // Store the current FFT window (for the HUD) and run the interpolation
        // for easy pixel-based dB value access
        QVector<float> dbMap;
        m_lastFFTLock.acquire();
        m_lastFFT = QVector<float>(fftWindow/2);
        memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));

        uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
        dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180);
        m_lastFFTLock.release();


#ifdef DEBUG_AUDIOSPEC
        QTime drawTime = QTime::currentTime();
#endif

        // Draw the spectrum
        QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
        spectrum.fill(qRgba(0,0,0,0));
        const uint w = m_innerScopeRect.width();
        const uint h = m_innerScopeRect.height();
        const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
        const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
        QColor spectrumColor(AbstractScopeWidget::colDarkWhite);
        int yMax;

#ifdef DETECT_OVERMODULATION
        if (colorizeFactor > 0) {
            QColor col = AbstractScopeWidget::colHighlightDark;
            QColor spec = spectrumColor;
            float f = std::sin(M_PI_2 * colorizeFactor);
            spectrumColor = QColor(
                        (int) (f * col.red() + (1-f) * spec.red()),
                        (int) (f * col.green() + (1-f) * spec.green()),
                        (int) (f * col.blue() + (1-f) * spec.blue()),
                        spec.alpha()
                        );
            // Limit the maximum colorization for non-overmodulated frames to better
            // recognize consecutively overmodulated frames
            if (colorizeFactor > MAX_OVM_COLOR) {
                colorizeFactor = MAX_OVM_COLOR;
            }
        }
#endif

#ifdef AUDIOSPEC_LINES
        QPainter davinci(&spectrum);
        davinci.setPen(QPen(QBrush(spectrumColor.rgba()), 1, Qt::SolidLine));
#endif

        for (uint i = 0; i < w; i++) {
            yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
            if (yMax < 0) {
                yMax = 0;
            } else if (yMax >= (int)h) {
                yMax = h-1;
            }
#ifdef AUDIOSPEC_LINES
            davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax);
#else
            for (int y = 0; y < yMax && y < (int)h; y++) {
                spectrum.setPixel(leftDist + i, topDist + h-y-1, spectrumColor.rgba());
            }
#endif
        }

        // Calculate the peak values. Use the new value if it is bigger, otherwise adapt to lower
        // values using the Moving Average formula
        if (m_aShowMax->isChecked()) {
            davinci.setPen(QPen(QBrush(AbstractScopeWidget::colHighlightLight), 2));
            if (m_peaks.size() != fftWindow/2) {
                m_peaks = QVector<float>(m_lastFFT);
            } else {
                for (int i = 0; i < fftWindow/2; i++) {
                    if (m_lastFFT[i] > m_peaks[i]) {
                        m_peaks[i] = m_lastFFT[i];
                    } else {
                        m_peaks[i] = ALPHA_MOVING_AVG * m_lastFFT[i] + (1-ALPHA_MOVING_AVG) * m_peaks[i];
                    }
                }
            }
            int prev = 0;
            m_peakMap = FFTTools::interpolatePeakPreserving(m_peaks, m_innerScopeRect.width(), 0, right, -180);
            for (uint i = 0; i < w; i++) {
                yMax = (m_peakMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
                if (yMax < 0) {
                    yMax = 0;
                } else if (yMax >= (int)h) {
                    yMax = h-1;
                }

                davinci.drawLine(leftDist + i-1, topDist + h-prev-1, leftDist + i, topDist + h-yMax-1);
                spectrum.setPixel(leftDist + i, topDist + h-yMax-1, AbstractScopeWidget::colHighlightLight.rgba());
                prev = yMax;
            }
        }

#ifdef DEBUG_AUDIOSPEC
        m_showTotal++;
        m_timeTotal += drawTime.elapsed();
        qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ;
#endif

        emit signalScopeRenderingFinished(start.elapsed(), 1);


        return spectrum;
    } else {
        emit signalScopeRenderingFinished(0, 1);
        return QImage();
    }
}
Ejemplo n.º 4
0
string RTFGenParser::parse(const QString &text)
{
    res = "";
    m_res_size = 0;
    m_codec = getContacts()->getCodec(m_contact);
    int charset = 0;
    for (const ENCODING *c = getContacts()->getEncodings(); c->language; c++){
        if (!strcasecmp(c->codec, m_codec->name())){
            charset = c->rtf_code;
            break;
        }
    }
#ifdef WIN32
    if ((charset == 0) && !strcasecmp(m_codec->name(), "system")){
        char buff[256];
        int res = GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTANSICODEPAGE, (char*)&buff, sizeof(buff));
        if (res){
            unsigned codepage = atol(buff);
            if (codepage){
                for (const rtf_cp *c = rtf_cps; c->cp; c++){
                    if (c->cp == codepage)
                        charset = c->charset;
                }
            }
        }
    }
#endif
    unsigned ansicpg = 0;
    const char *send_encoding = 0;
    m_codec = NULL;
    if (charset){
        for (const ENCODING *c = getContacts()->getEncodings(); c->language; c++){
            if ((c->rtf_code == charset) && c->bMain){
                send_encoding = c->codec;
                m_codec = getContacts()->getCodecByName(send_encoding);
                ansicpg = c->cp_code;
                break;
            }
        }
    }

    // Add defaults to the tables
    m_fontFaces.push_back("MS Sans Serif");
    m_colors.push_back(m_foreColor);
    // Create a "fake" tag which'll serve as the default style
    CharStyle style;
    style.faceIdx = 0;
    style.colorIdx = 1; // colors are 1-based (0 = default)
    style.sizePt = 12; // default according to Microsoft
    Tag& tag = *(m_tags.pushNew());
    tag.setCharStyle(style);

    // Assume we go immediately after a tag.
    m_bSpace = true;
    HTMLParser::parse(text);

    string s;
    s = "{\\rtf1\\ansi";
    if (ansicpg){
        s += "\\ansicpg";
        s += number(ansicpg);
    }
    s += "\\deff0\r\n";
    s += "{\\fonttbl";
    unsigned n = 0;
    for (list<QString>::iterator it_face = m_fontFaces.begin(); it_face != m_fontFaces.end(); it_face++, n++){
        s += "{\\f";
        s += number(n);
        QString face = (*it_face);
        if (face.find("Times") >= 0){
            s += "\\froman";
        }else if (face.find("Courier") >= 0){
            s += "\\fmodern";
        }else{
            s += "\\fswiss";
        }
        if (charset){
            s += "\\fcharset";
            s += number(charset);
        }
        s += " ";
        int pos = face.find(QRegExp(" +["));
        if (pos > 0)
            face = face.left(pos);
        s += face.latin1();
        s += ";}";
    }
    s += "}\r\n";
    s += "{\\colortbl ;";
    for (list<QColor>::iterator it_colors = m_colors.begin(); it_colors != m_colors.end(); ++it_colors){
        QColor c = *it_colors;
        s += "\\red";
        s += number(c.red());
        s += "\\green";
        s += number(c.green());
        s += "\\blue";
        s += number(c.blue());
        s += ";";
    }
    s += "}\r\n";
    s += "\\viewkind4\\pard";
    s += style.getDiffRTF(CharStyle()).utf8();
    s += res;
    s += "\r\n}\r\n";

    log(L_DEBUG, "Resulting RTF: %s", s.c_str());

    return s;
}
Ejemplo n.º 5
0
void KisRainDropsFilter::process(KisConstProcessingInformation srcInfo,
                                 KisProcessingInformation dstInfo,
                                 const QSize& size,
                                 const KisFilterConfiguration* config,
                                 KoUpdater* progressUpdater
                                ) const
{

    const KisPaintDeviceSP src = srcInfo.paintDevice();
    KisPaintDeviceSP dst = dstInfo.paintDevice();
    QPoint dstTopLeft = dstInfo.topLeft();
    QPoint srcTopLeft = srcInfo.topLeft();
    Q_UNUSED(config);
    Q_ASSERT(!src.isNull());
    Q_ASSERT(!dst.isNull());

    //read the filter configuration values from the KisFilterConfiguration object
    quint32 DropSize = config->getInt("dropSize", 80);
    quint32 number = config->getInt("number", 80);
    quint32 fishEyes = config->getInt("fishEyes", 30);

    if (progressUpdater) {
        progressUpdater->setRange(0, size.width() * size.height());
    }
    int count = 0;

    if (fishEyes <= 0) fishEyes = 1;

    if (fishEyes > 100) fishEyes = 100;

    int Width = size.width();
    int Height = size.height();

    bool** BoolMatrix = CreateBoolArray(Width, Height);

    int       i, j, k, l, m, n;                 // loop variables
    int       Bright;                           // Bright value for shadows and highlights
    int       x, y;                             // center coordinates
    int       Counter = 0;                      // Counter (duh !)
    int       NewSize;                          // Size of current raindrop
    int       halfSize;                         // Half of the current raindrop
    int       Radius;                           // Maximum radius for raindrop
    int       BlurRadius;                       // Blur Radius
    int       BlurPixels;

    double    r, a;                             // polar coordinates
    double    OldRadius;                        // Radius before processing
    double    NewfishEyes = (double)fishEyes * 0.01;  // FishEye fishEyesicients
    double    s;
    double    R, G, B;

    bool      FindAnother = false;              // To search for good coordinates

    const KoColorSpace * cs = src->colorSpace();


    // XXX: move the seed to the config, so the filter can be used as
    // and adjustment filter (boud).
    // And use a thread-safe random number generator
    QDateTime dt = QDateTime::currentDateTime();
    QDateTime Y2000(QDate(2000, 1, 1), QTime(0, 0, 0));

    srand((uint) dt.secsTo(Y2000));

    // Init booleen Matrix.

    for (i = 0 ; (i < Width) && !(progressUpdater && progressUpdater->interrupted()) ; ++i) {
        for (j = 0 ; (j < Height) && !(progressUpdater && progressUpdater->interrupted()); ++j) {
            BoolMatrix[i][j] = false;
        }
    }

    KisRandomAccessorSP dstAccessor = dst->createRandomAccessorNG(dstTopLeft.x(), dstTopLeft.y());
    KisRandomConstAccessorSP srcAccessor = src->createRandomConstAccessorNG(dstTopLeft.x(), dstTopLeft.y());
    
    for (uint NumBlurs = 0; (NumBlurs <= number) && !(progressUpdater && progressUpdater->interrupted()); ++NumBlurs) {
        NewSize = (int)(rand() * ((double)(DropSize - 5) / RAND_MAX) + 5);
        halfSize = NewSize / 2;
        Radius = halfSize;
        s = Radius / log(NewfishEyes * Radius + 1);

        Counter = 0;

        do {
            FindAnother = false;
            y = (int)(rand() * ((double)(Width - 1) / RAND_MAX));
            x = (int)(rand() * ((double)(Height - 1) / RAND_MAX));

            if (BoolMatrix[y][x])
                FindAnother = true;
            else
                for (i = x - halfSize ; (i <= x + halfSize) && !(progressUpdater && progressUpdater->interrupted()); i++)
                    for (j = y - halfSize ; (j <= y + halfSize) && !(progressUpdater && progressUpdater->interrupted()); j++)
                        if ((i >= 0) && (i < Height) && (j >= 0) && (j < Width))
                            if (BoolMatrix[j][i])
                                FindAnother = true;

            Counter++;
        } while ((FindAnother && (Counter < 10000) && !(progressUpdater && progressUpdater->interrupted())));

        if (Counter >= 10000) {
            NumBlurs = number;
            break;
        }

        for (i = -1 * halfSize ; (i < NewSize - halfSize) && !(progressUpdater && progressUpdater->interrupted()); i++) {
            for (j = -1 * halfSize ; (j < NewSize - halfSize) && !(progressUpdater && progressUpdater->interrupted()); j++) {
                r = sqrt(i * i + j * j);
                a = atan2(static_cast<double>(i), static_cast<double>(j));

                if (r <= Radius) {
                    OldRadius = r;
                    r = (exp(r / s) - 1) / NewfishEyes;

                    k = x + (int)(r * sin(a));
                    l = y + (int)(r * cos(a));

                    m = x + i;
                    n = y + j;

                    if ((k >= 0) && (k < Height) && (l >= 0) && (l < Width)) {
                        if ((m >= 0) && (m < Height) && (n >= 0) && (n < Width)) {
                            Bright = 0;

                            if (OldRadius >= 0.9 * Radius) {
                                if ((a <= 0) && (a > -2.25))
                                    Bright = -80;
                                else if ((a <= -2.25) && (a > -2.5))
                                    Bright = -40;
                                else if ((a <= 0.25) && (a > 0))
                                    Bright = -40;
                            }

                            else if (OldRadius >= 0.8 * Radius) {
                                if ((a <= -0.75) && (a > -1.50))
                                    Bright = -40;
                                else if ((a <= 0.10) && (a > -0.75))
                                    Bright = -30;
                                else if ((a <= -1.50) && (a > -2.35))
                                    Bright = -30;
                            }

                            else if (OldRadius >= 0.7 * Radius) {
                                if ((a <= -0.10) && (a > -2.0))
                                    Bright = -20;
                                else if ((a <= 2.50) && (a > 1.90))
                                    Bright = 60;
                            }

                            else if (OldRadius >= 0.6 * Radius) {
                                if ((a <= -0.50) && (a > -1.75))
                                    Bright = -20;
                                else if ((a <= 0) && (a > -0.25))
                                    Bright = 20;
                                else if ((a <= -2.0) && (a > -2.25))
                                    Bright = 20;
                            }

                            else if (OldRadius >= 0.5 * Radius) {
                                if ((a <= -0.25) && (a > -0.50))
                                    Bright = 30;
                                else if ((a <= -1.75) && (a > -2.0))
                                    Bright = 30;
                            }

                            else if (OldRadius >= 0.4 * Radius) {
                                if ((a <= -0.5) && (a > -1.75))
                                    Bright = 40;
                            }

                            else if (OldRadius >= 0.3 * Radius) {
                                if ((a <= 0) && (a > -2.25))
                                    Bright = 30;
                            }

                            else if (OldRadius >= 0.2 * Radius) {
                                if ((a <= -0.5) && (a > -1.75))
                                    Bright = 20;
                            }

                            BoolMatrix[n][m] = true;

                            QColor originalColor;

                            srcAccessor->moveTo(srcTopLeft.x() + l, srcTopLeft.y() + k);
                            cs->toQColor(srcAccessor->oldRawData(), &originalColor);

                            int newRed = CLAMP(originalColor.red() + Bright, 0, quint8_MAX);
                            int newGreen = CLAMP(originalColor.green() + Bright, 0, quint8_MAX);
                            int newBlue = CLAMP(originalColor.blue() + Bright, 0, quint8_MAX);

                            QColor newColor;
                            newColor.setRgb(newRed, newGreen, newBlue);

                            dstAccessor->moveTo(dstTopLeft.x() + n, dstTopLeft.y() + m);
                            cs->fromQColor(newColor, dstAccessor->rawData());
                        }
                    }
                }
            }
        }

        BlurRadius = NewSize / 25 + 1;

        for (i = -1 * halfSize - BlurRadius ; (i < NewSize - halfSize + BlurRadius) && !(progressUpdater && progressUpdater->interrupted()) ; i++) {
            for (j = -1 * halfSize - BlurRadius;
                    ((j < NewSize - halfSize + BlurRadius) && !(progressUpdater && progressUpdater->interrupted()));
                    ++j) {
                r = sqrt(i * i + j * j);

                if (r <= Radius * 1.1) {
                    R = G = B = 0;
                    BlurPixels = 0;

                    for (k = -1 * BlurRadius; k < BlurRadius + 1; k++)
                        for (l = -1 * BlurRadius; l < BlurRadius + 1; l++) {
                            m = x + i + k;
                            n = y + j + l;

                            if ((m >= 0) && (m < Height) && (n >= 0) && (n < Width)) {
                                QColor color;
                                dstAccessor->moveTo(dstTopLeft.x() + n, dstTopLeft.y() + m);
                                cs->toQColor(dstAccessor->rawData(), &color);

                                R += color.red();
                                G += color.green();
                                B += color.blue();
                                BlurPixels++;
                            }
                        }

                    m = x + i;
                    n = y + j;

                    if ((m >= 0) && (m < Height) && (n >= 0) && (n < Width)) {
                        QColor color;

                        color.setRgb((int)(R / BlurPixels), (int)(G / BlurPixels), (int)(B / BlurPixels));
                        dstAccessor->moveTo(dstTopLeft.x() + n, dstTopLeft.y() + m);
                        cs->fromQColor(color, dstAccessor->rawData());
                    }
                }
            }
        }

        if (progressUpdater) progressUpdater->setValue(++count);
    }

    FreeBoolArray(BoolMatrix, Width);
}
Ejemplo n.º 6
0
void SciDoc::applySettings() {
//	LOGGER;

	setShowLineNumbers(EditorSettings::get(EditorSettings::ShowLineNumbers));

	QFont font = EditorSettings::font();
	LexerStorage::instance()->updateLexers(font);
	QColor textColor = EditorSettings::get(EditorSettings::DefaultFontColor);
	QColor bgColor = EditorSettings::get(EditorSettings::DefaultBgColor);

	QsciScintilla* edits[] = { int_->edit1_, int_->edit2_, NULL };
	for (int i = 0; edits[i] != NULL; ++i ) {
		QsciScintilla* edit = edits[i];

		// indents
		//edit->setTabWidth(EditorSettings::get(EditorSettings::TabWidth));
		//edit->setIndentationsUseTabs(EditorSettings::get(EditorSettings::UseTabs));
		edit->setBackspaceUnindents(EditorSettings::get(EditorSettings::BackspaceUnindents));

		// colors
		edit->setIndentationGuides(QSciSettings::get(QSciSettings::ShowIndents));
		edit->setIndentationGuidesForegroundColor(QSciSettings::get(QSciSettings::IndentsColor));
		edit->setIndentationGuidesBackgroundColor(bgColor);

		QColor selBgColor = EditorSettings::get(EditorSettings::SelectionBgColor);
		edit->setSelectionBackgroundColor(selBgColor);
		if ( selBgColor.red() + selBgColor.green() + selBgColor.blue() < 3 * 255 / 2)
			edit->setSelectionForegroundColor(QColor(255, 255, 255));
		else
			edit->setSelectionForegroundColor(QColor(0, 0, 0));

		if ( QSciSettings::get(QSciSettings::HighlightMatchingBrace) ) {
			edit->setMatchedBraceBackgroundColor(QSciSettings::get(QSciSettings::MatchingBraceBgColor));
			edit->setMatchedBraceForegroundColor(QSciSettings::get(QSciSettings::MatchingBraceFgColor));
		}
		else {
			edit->setMatchedBraceBackgroundColor(bgColor);
			edit->setMatchedBraceForegroundColor(textColor);
		}

		edit->setCaretLineBackgroundColor(LexerStorage::instance()->curLineColor(syntax()));
		edit->setMarkerBackgroundColor(QSciSettings::get(QSciSettings::MarkersColor));
		edit->setCaretForegroundColor(textColor);

		QColor marginsBgColor = QSciSettings::get(QSciSettings::MarginsBgColor);
		edit->setMarginsBackgroundColor(marginsBgColor);
		edit->setMarginsForegroundColor(textColor);
		edit->setFoldMarginColors(marginsBgColor, bgColor);

		// markers
		edit->markerDefine(markerPixmap(QSciSettings::get(QSciSettings::MarkersColor), marginsBgColor), -1);
		edit->setCaretLineVisible(QSciSettings::get(QSciSettings::HighlightCurLine));


		// line length indicator
		int lInd = EditorSettings::get(EditorSettings::LineLengthIndicator);
		if ( lInd > 0 ) {
			edit->setEdgeMode(QsciScintilla::EdgeLine);
			edit->setEdgeColumn(lInd);
		}
		else {
			edit->setEdgeMode(QsciScintilla::EdgeNone);
		}

		edit->SendScintilla(QsciScintillaBase::SCI_SETWHITESPACEFORE, 1, QSciSettings::get(QSciSettings::WhiteSpaceColor));

		// selection
/*		QColor selBgColor = TextDocSettings::selectionBgColor();
		edit->setSelectionBackgroundColor(selBgColor);
		if ( selBgColor.red() + selBgColor.green() + selBgColor.blue() < 3 * 255 / 2)
			edit->setSelectionForegroundColor(QColor(255, 255, 255));
		else
			edit->setSelectionForegroundColor(QColor(0, 0, 0));
*/
		//	autocompletion
		edit->setAutoCompletionThreshold(AutocompleteSettings::get(AutocompleteSettings::Threshold));
		edit->setAutoCompletionReplaceWord(AutocompleteSettings::get(AutocompleteSettings::ReplaceWord));
//		edit->setAutoCompletionCaseSensitivity(AutocompleteSettings::get(AutocompleteSettings::CaseSensitive));
		if ( AutocompleteSettings::get(AutocompleteSettings::UseDocument) ) {
			if ( AutocompleteSettings::get(AutocompleteSettings::UseApis) )
				edit->setAutoCompletionSource(QsciScintilla::AcsAll);
			else
				edit->setAutoCompletionSource(QsciScintilla::AcsDocument);
		}
		else {
			if ( AutocompleteSettings::get(AutocompleteSettings::UseApis) )
				edit->setAutoCompletionSource(QsciScintilla::AcsAPIs);
			else
				edit->setAutoCompletionSource(QsciScintilla::AcsNone);
		}
		edit->setAutoCompletionCaseSensitivity(false);
	}
}
Ejemplo n.º 7
0
void BlockIdentifier::parseDefinition(JSONObject *b, BlockInfo *parent,
                                      int pack) {
  int id;
  if (parent == NULL) {
    id = b->at("id")->asNumber();
  } else {
    id = parent->id;
    int data = b->at("data")->asNumber();
    id |= data << 12;
  }
  BlockInfo *block = new BlockInfo();
  block->id = id;

  if (b->has("name"))
    block->setName(b->at("name")->asString());
  else if (parent != NULL)
    block->setName(parent->getName());
  else
    block->setName("Unknown");
  block->enabled = true;

  if (b->has("transparent")) {
    block->transparent = b->at("transparent")->asBool();
    block->rendernormal = false;  // for most cases except the following
    if (b->has("rendercube"))
      block->rendernormal = b->at("rendercube")->asBool();
    block->spawninside = false;  // for most cases except the following
    if (b->has("spawninside"))
      block->spawninside = b->at("spawninside")->asBool();
  } else if (parent != NULL) {
    block->transparent = parent->transparent;
    block->rendernormal = parent->rendernormal;
    block->spawninside = parent->spawninside;
  } else {
    block->transparent = false;
    block->rendernormal = true;
    block->spawninside = false;
  }

  if (b->has("liquid"))
    block->liquid = b->at("liquid")->asBool();
  else if (parent != NULL)
    block->liquid = parent->liquid;
  else
    block->liquid = false;

  if (b->has("canProvidePower"))
    block->providepower = b->at("canProvidePower")->asBool();
  else if (parent != NULL)
    block->providepower = parent->providepower;
  else
    block->providepower = false;

  if (b->has("alpha"))
    block->alpha = b->at("alpha")->asNumber();
  else if (parent != NULL)
    block->alpha = parent->alpha;
  else
    block->alpha = 1.0;

  QColor blockcolor;
  if (b->has("color")) {
    QString colorname = b->at("color")->asString();
    if (colorname.length() == 6) {
      // check if this is an old color definition with missing '#'
      bool ok;
      colorname.toInt(&ok,16);
      if (ok)
        colorname.push_front('#');
    }
    blockcolor.setNamedColor(colorname);
    assert(blockcolor.isValid());
  } else if (parent != NULL) {
    // copy brightest color from parent
    blockcolor = parent->colors[15];
  } else {
    // use hashed by name instead
    quint32 hue = qHash(block->getName());
    blockcolor.setHsv(hue % 360, 255, 255);
  }

  // pre-calculate light spectrum
  for (int i = 0; i < 16; i++) {
    // calculate light attenuation similar to Minecraft
    // except base 90% here, were Minecraft is using 80% per level
    double light_factor = pow(0.90,15-i);
    block->colors[i].setRgb(light_factor*blockcolor.red(),
                            light_factor*blockcolor.green(),
                            light_factor*blockcolor.blue(),
                            255*block->alpha );
  }

  if (b->has("mask"))
    block->mask = b->at("mask")->asNumber();
  else if (b->has("variants"))
    block->mask = 0x0f;
  else
    block->mask = 0x00;

  if (b->has("variants")) {
    JSONArray *variants = dynamic_cast<JSONArray *>(b->at("variants"));
    int vlen = variants->length();
    for (int j = 0; j < vlen; j++)
      parseDefinition(dynamic_cast<JSONObject *>(variants->at(j)), block, pack);
  }

  blocks[id].append(block);
  packs[pack].append(block);
}
Ejemplo n.º 8
0
void
TagColorEditor::askGradientChoice()
{
  QString homePath = QDir::homePath();
  QFileInfo sfi(homePath, ".drishtigradients.xml");
  QString stopsflnm = sfi.absoluteFilePath();
  if (!sfi.exists())
    copyGradientFile(stopsflnm);

  QDomDocument document;
  QFile f(stopsflnm);
  if (f.open(QIODevice::ReadOnly))
    {
      document.setContent(&f);
      f.close();
    }

  QStringList glist;

  QDomElement main = document.documentElement();
  QDomNodeList dlist = main.childNodes();
  for(int i=0; i<dlist.count(); i++)
    {
      if (dlist.at(i).nodeName() == "gradient")
	{
	  QDomNodeList cnode = dlist.at(i).childNodes();
	  for(int j=0; j<cnode.count(); j++)
	    {
	      QDomElement dnode = cnode.at(j).toElement();
	      if (dnode.nodeName() == "name")
		glist << dnode.text();
	    }
	}
    }

  bool ok;
  QString gstr = QInputDialog::getItem(0,
				       "Color Gradient",
				       "Color Gradient",
				       glist, 0, false,
				       &ok);
  if (!ok)
    return;

  int cno = -1;
  for(int i=0; i<dlist.count(); i++)
    {
      if (dlist.at(i).nodeName() == "gradient")
	{
	  QDomNodeList cnode = dlist.at(i).childNodes();
	  for(int j=0; j<cnode.count(); j++)
	    {
	      QDomElement dnode = cnode.at(j).toElement();
	      if (dnode.tagName() == "name" && dnode.text() == gstr)
		{
		  cno = i;
		  break;
		}
	    }
	}
    }
	
  if (cno < 0)
    return;

  QGradientStops stops;
  QDomNodeList cnode = dlist.at(cno).childNodes();
  for(int j=0; j<cnode.count(); j++)
    {
      QDomElement de = cnode.at(j).toElement();
      if (de.tagName() == "gradientstops")
	{
	  QString str = de.text();
	  QStringList strlist = str.split(" ", QString::SkipEmptyParts);
	  for(int j=0; j<strlist.count()/5; j++)
	    {
	      float pos, r,g,b,a;
	      pos = strlist[5*j].toFloat();
	      r = strlist[5*j+1].toInt();
	      g = strlist[5*j+2].toInt();
	      b = strlist[5*j+3].toInt();
	      a = strlist[5*j+4].toInt();
	      stops << QGradientStop(pos, QColor(r,g,b,a));
	    }
	}
    }

  int mapSize = QInputDialog::getInt(0,
				     "Number of Colors",
				     "Number of Colors",
				     50, 2, 255, 1, &ok);
  if (!ok)
    mapSize = 50;

  QGradientStops gstops;
  gstops = StaticFunctions::resampleGradientStops(stops, mapSize);

  uchar *colors = Global::tagColors();  
  for(int i=0; i<gstops.size(); i++)
    {
      float pos = gstops[i].first;
      QColor color = gstops[i].second;
      int r = color.red();
      int g = color.green();
      int b = color.blue();
      colors[4*i+0] = r;
      colors[4*i+1] = g;
      colors[4*i+2] = b;
    }
  
  setColors();
}
Ejemplo n.º 9
0
void DialogSun::diffuseColorChange(const QColor &color)
{
    light->sun.setDiffuse(color.red()/255.0,color.green()/255.0,color.blue()/255.0);
    ui->pushChoose_Diffuse->setPalette(QPalette(color));
}
Ejemplo n.º 10
0
void ValueMap::writeEntry(const QString& k, const QColor& v )
{
   m_map[k] = numStr(v.red()) + "," + numStr(v.green()) + "," + numStr(v.blue());
}
Ejemplo n.º 11
0
void PaletteEditor::stopsChangedAction()
{
	static const int GradientBufferLastIdx = GradientBufferSize - 1;
	static const qreal dx  = 1.0 / GradientBufferSize;
	QSize s( m_gradientLabel->maximumSize() );
	QRect r( QPoint(0, 0), QSize(s.width(), (s.height() / 2.0 ) ) );
	QImage palette_image(s, QImage::Format_RGB32);
	QPainter painter(&palette_image);
	GradientStops stops(m_gradientStops->getStops());
	qStableSort(stops.begin(), stops.end(), GradientStop::lessThanGradientStopComparison);

	// now apply the ends and update the palette
	GradientStops ends( m_gradientEnds->getStops() );
	QGradient::Spread spread((QGradient::Spread)m_gradientSpreadGroup->checkedId());

	GradientStop n_stop(stops.first());
	QRgb ccolor = n_stop.second.rgba();
	for (int n = 0, fpos = n_stop.first * GradientBufferSize  ; n < fpos ; n++)
		m_gradient[qMin(n, GradientBufferLastIdx)] = ccolor;

	int last_stop_idx = stops.size() - 1;
	for (int begin_idx = 0; begin_idx < last_stop_idx ; begin_idx++)
	{
		GradientStop a = stops.at(begin_idx);
		GradientStop b = stops.at(begin_idx + 1);
		QColor ac = a.second;
		QColor bc = b.second;
		qreal d = ( b.first - a.first );
		qreal rdx, gdx, bdx, adx;
		if (b.colorspace == 0)
		{
			rdx = ( (bc.red()   - ac.red() )   / d ) * dx;
			gdx = ( (bc.green() - ac.green() ) / d ) * dx;
			bdx = ( (bc.blue()  - ac.blue() )  / d ) * dx;
			adx = ( (bc.alpha() - ac.alpha() ) / d ) * dx;
		}
		else
		{
			rdx = ( (bc.hue()        - ac.hue() )        / d ) * dx;
			gdx = ( (bc.saturation() - ac.saturation() ) / d ) * dx;
			bdx = ( (bc.value()      - ac.value() )      / d ) * dx;
			adx = ( (bc.alpha()      - ac.alpha() )      / d ) * dx;

			if (b.colorspace == 1)
			{
				if (rdx == 0.0)
					rdx = 180.0 / d * dx;
				else if (rdx < 0)
					rdx *= -1;
			}
			else
			{
				if (rdx == 0.0)
					rdx = -180.0 / d * dx;
				else if (rdx > 0)
					rdx *= -1;
			}
		}
		int n  = a.first * GradientBufferSize ;
		int nb = (int)(b.first * GradientBufferSize );
		for (int i = 0 ; n < nb ; i++, n++)
		{
			if (b.colorspace == 0)
			{
				m_gradient[n] = qRgba(
						qBound(0, (int)( ac.red()   + rdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.green() + gdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.blue()  + bdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.alpha() + adx * i + 0.5 ), 255));
			}
			else
			{
				int h = (int)( ac.hue() + rdx * i + 0.5 );
				if (h < 0)
					h += 360;
				m_gradient[n] = QColor::fromHsv(h % 360,
						qBound(0, (int)( ac.saturation() + gdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.value()  + bdx * i + 0.5 ), 255),
						qBound(0, (int)( ac.alpha() + adx * i + 0.5 ), 255)).rgba();
			}
		}
	}

	n_stop = stops.last();
	ccolor = n_stop.second.rgba();
	for (int n = n_stop.first * GradientBufferSize ; n < GradientBufferSize ; n++)
		m_gradient[n] = ccolor;

	qreal start(ends.at(0).first);
	qreal end(ends.at(1).first);
	int begin_idx = start * 256 ;
	int end_idx   = end   * 256 ;
	int ibuf_size = end_idx - begin_idx;
	flam3_palette_entry* ibuf = new flam3_palette_entry[ibuf_size]();

	// a very acute filter
	qreal c2 = 0.01;
	qreal c3 = 1.0;
	qreal c4 = 0.01;
	qreal norm = c2 + c3 + c4;
	qreal k = 0.0;
	qreal skip( (GradientBufferSize / 256.0) / qMax(qreal(1.0/GradientBufferSize), end - start) );
	for (int n = 0 ; n < ibuf_size ; n++, k += skip)
	{
		int j = k;
		QRgb a2( m_gradient[qBound(0, j + 0, GradientBufferLastIdx)] );
		QRgb a3( m_gradient[qMin(j + 1, GradientBufferLastIdx)] );
		QRgb a4( m_gradient[qMin(j + 2, GradientBufferLastIdx)] );

		ibuf[n].color[0] = (qRed(a2)*c2   + qRed(a3)*c3   + qRed(a4)*c4 )   / (norm * 255.);
		ibuf[n].color[1] = (qGreen(a2)*c2 + qGreen(a3)*c3 + qGreen(a4)*c4 ) / (norm * 255.);
		ibuf[n].color[2] = (qBlue(a2)*c2  + qBlue(a3)*c3  + qBlue(a4)*c4 )  / (norm * 255.);
		ibuf[n].color[3] = (qAlpha(a2)*c2 + qAlpha(a3)*c3 + qAlpha(a4)*c4 ) / (norm * 255.);
	}

	// update the gradient editor label
	painter.fillRect(QRect(QPoint(0,0), s), checkers);
	if (ibuf_size == 256)
	{
		for (int n = 0, h = s.height() ; n < 256 ; n++)
		{
			painter.setPen(QColor::fromRgbF(ibuf[n].color[0], ibuf[n].color[1], ibuf[n].color[2], ibuf[n].color[3]));
			painter.drawLine(n, 0, n, h);
		}
	}
	else
	{
		for (int n = 0, h = s.height(), j = 0 ; n < 256 ; n++, j += 4)
		{
			QRgb a2( m_gradient[qBound(0, j + 0, GradientBufferLastIdx)] );
			QRgb a3( m_gradient[qMin(j + 1, GradientBufferLastIdx)] );
			QRgb a4( m_gradient[qMin(j + 2, GradientBufferLastIdx)] );
			QRgb r((qRed(a2)*c2   + qRed(a3)*c3   + qRed(a4)*c4 )   / norm );
			QRgb g((qGreen(a2)*c2 + qGreen(a3)*c3 + qGreen(a4)*c4 ) / norm );
			QRgb b((qBlue(a2)*c2  + qBlue(a3)*c3  + qBlue(a4)*c4 )  / norm );
			QRgb a((qAlpha(a2)*c2 + qAlpha(a3)*c3 + qAlpha(a4)*c4 ) / norm );
			QColor c(r, g, b, a);
			painter.setPen(c);
			painter.drawLine(n, 0, n, h);
		}
	}
	m_gradientLabel->setPixmap(QPixmap::fromImage(palette_image));

	// Rescale the gradient colors into the palette with a simple filter
	if (spread == QGradient::PadSpread)
	{
		QRgb fc(m_gradient[0]);
		flam3_palette_entry e = { 0., { qRed(fc)/255., qGreen(fc)/255., qBlue(fc)/255., qAlpha(fc)/255. }};
		for (int n = 0 ; n < begin_idx ; n++)
			p[n] = e;

		for (int n = begin_idx, j = 0 ; n < end_idx ; n++, j++)
			p[n] = ibuf[j];

		fc = m_gradient[GradientBufferLastIdx];
		e = (flam3_palette_entry){ 1., { qRed(fc)/255., qGreen(fc)/ 255., qBlue(fc)/255., qAlpha(fc)/255. }};
		for (int n = end_idx ; n < 256 ; n++)
			p[n] = e;
	}
	else if (spread == QGradient::RepeatSpread)
	{
		for (int n = begin_idx, j = 0 ; n < 256 ; n++, j++)
			p[n] = ibuf[j % ibuf_size];
		for (int n = begin_idx - 1, j = ibuf_size * 4096 - 1 ; n >= 0 ; n--, j--)
			p[n] = ibuf[j % ibuf_size];
	}
	else if (spread == QGradient::ReflectSpread)
	{
		for (int n = begin_idx, j = 0, h = 4096*ibuf_size -1 ; n < begin_idx + ibuf_size ; n++, j++, h--)
		{
			for (int k = n, q = n + ibuf_size ; k < 256 ; k += 2*ibuf_size, q += 2*ibuf_size )
			{
				p[k] = ibuf[j % ibuf_size];
				if (q < 256)
					p[q] = ibuf[h % ibuf_size];
			}
		}
		for (int n = begin_idx - 1, j = ibuf_size * 4096 - 1, h = 0 ; n >= begin_idx - ibuf_size ; n--, j--, h++)
		{
			for (int k = n, q = n - ibuf_size ; k >= 0 ; k -= 2*ibuf_size, q -= 2*ibuf_size )
			{
				p[k] = ibuf[h % ibuf_size];
				if (q >= 0)
					p[q] = ibuf[j % ibuf_size];
			}
		}
	}
	delete[] ibuf;

	setPaletteView();
	emit paletteChanged();
}
Ejemplo n.º 12
0
void toSqlText::setHighlighter(HighlighterTypeEnum h)
{
    using namespace ToConfiguration;

    // TODO handle bgthread working here
    QsciLexer *lexer = super::lexer();
    highlighterType = h;
    switch (highlighterType)
    {
        case None:
            if (m_analyzerNL == NULL)
                m_analyzerNL = new toSyntaxAnalyzerNL(this);
            m_currentAnalyzer = m_analyzerNL;
            m_worker->setAnalyzer(m_currentAnalyzer);
            setLexer(NULL);
            break;
        case QsciSql:
            if (m_analyzerNL == NULL)
                m_analyzerNL = new toSyntaxAnalyzerNL(this);
            m_currentAnalyzer = m_analyzerNL;
            m_worker->setAnalyzer(m_currentAnalyzer);
            setLexer(m_currentAnalyzer ? m_currentAnalyzer->createLexer(this) : NULL);
            break;
        case Oracle:
            if ( m_analyzerOracle == NULL)
                m_analyzerOracle = new toSyntaxAnalyzerOracle(this);
            m_currentAnalyzer = m_analyzerOracle;
            m_worker->setAnalyzer(m_currentAnalyzer);
            setLexer(m_currentAnalyzer ? m_currentAnalyzer->createLexer(this) : NULL);
            break;
#ifdef TORA_EXPERIMENTAL
        case MySQL:
            if ( m_analyzerMySQL == NULL)
            	m_analyzerMySQL = new toSyntaxAnalyzerMysql(this);
            m_currentAnalyzer = m_analyzerMySQL;
            m_worker->setAnalyzer(m_analyzerMySQL);
            setLexer(m_currentAnalyzer ? m_currentAnalyzer->createLexer(this) : NULL);
            break;
        case PostgreSQL:
            if ( m_analyzerPostgreSQL == NULL)
            	m_analyzerPostgreSQL = new toSyntaxAnalyzerPostgreSQL(this);
        	m_currentAnalyzer = m_analyzerPostgreSQL;
        	m_worker->setAnalyzer(m_analyzerPostgreSQL);
            setLexer(m_currentAnalyzer ? m_currentAnalyzer->createLexer(this) : NULL);
            break;
#endif
    }
#ifdef QT_DEBUG
	if (super::lexer())
	{
		QString txt = QLatin1String(ENUM_NAME(toSqlText, HighlighterTypeEnum, highlighterType));
		TLOG(8, toDecorator, __HERE__) << " Lexer: " << txt << std::endl;

		QMetaEnum m_enum = toSyntaxAnalyzer::staticMetaObject.enumerator(toSyntaxAnalyzer::staticMetaObject.indexOfEnumerator("WordClassEnum"));
		QString fontName = super::lexer()->font(0).toString();
		for (int idx = 0; idx < m_enum.keyCount(); idx++)
		{
			unsigned ival = m_enum.value(idx);
			QString  sval = m_enum.key(idx);
			TLOG(8, toNoDecorator, __HERE__) << "  Analyzer:" << sval << '(' << ival << ')' << std::endl;
			if (super::lexer() == NULL)
				break;
			QColor c = super::lexer()->color(ival);
			QColor p = super::lexer()->paper(ival);
			QFont  f = super::lexer()->font(ival);
			TLOG(8, toNoDecorator, __HERE__) << "  Style:" << sval << std::endl
				<< "   Fore:" << c.name() << '(' << c.red() << ' ' << c.green() << ' ' << c.blue() << ' ' << c.alpha() << ')' << std::endl
				<< "   Back:" << p.name() << '(' << p.red() << ' ' << p.green() << ' ' << p.blue() << ' ' << p.alpha() << ')' << std::endl
				<< "   Font:" << f.toString() << std::endl;
		}
	}
#endif

    if (lexer) // delete the "old" lexer - if any
        delete lexer;

    if (super::lexer())
    {
    	QPalette const& palette = QApplication::palette();
        declareStyle(Default,
                     QColor(Qt::black),
                     palette.color(QPalette::AlternateBase),
                     mono);
    	declareStyle(OneLine,
                     QColor(Qt::black),
                     QColor(toSqlText::lightCyan),
                     mono);
        declareStyle(OneLineAlt,
                     QColor(Qt::black),
                     QColor(toSqlText::lightMagenta),
                     mono);
    }

    setFont(Utils::toStringToFont(toConfigurationNewSingle::Instance().option(Editor::ConfCodeFont).toString()));
    //update(); gets called by setFont
}
	void ColorPositionParameterDefinition::setDefaultValues(ActionInstance *actionInstance)
	{
		actionInstance->setSubParameter(name().original(), "position", defaultPosition());

        QColor localDefaultColor = defaultColor();
        actionInstance->setSubParameter(name().original(), "color", QString("%1:%2:%3").arg(localDefaultColor.red()).arg(localDefaultColor.green()).arg(localDefaultColor.blue()));
	}
Ejemplo n.º 14
0
JointItem::JointItem(int index,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::JointItem)
{
    ui->setupUi(this);
    internalState = StateStarting;
    internalInteraction = InteractionStarting;
    jointIndex = index;
    sliderPositionPressed = false;
    sliderTorquePressed = false;
    sliderOpenloopPressed = false;
    sliderVelocityPressed = false;
    speed = 10;
    enableCalib = true;
    speedVisible = false;
    lastVelocity = 0;
    velocityModeEnabled = false;

    IDLE            = 0;
    POSITION        = 1;
    POSITION_DIR    = 2;
    MIXED           = 3;
    VELOCITY        = 4;
    TORQUE          = 5;
    OPENLOOP        = 6;



    connect(ui->comboMode,SIGNAL(currentIndexChanged(int)),this,SLOT(onModeChanged(int)));
    connect(ui->comboInteraction,SIGNAL(currentIndexChanged(int)),this,SLOT(onInteractionChanged(int)));

    ui->sliderPositionPosition->installEventFilter(this);
    connect(ui->sliderPositionPosition,SIGNAL(sliderPressed()),this,SLOT(onSliderPositionPressed()));
    connect(ui->sliderPositionPosition,SIGNAL(sliderReleased()),this,SLOT(onSliderPositionReleased()));
    connect(ui->sliderPositionPosition,SIGNAL(actionTriggered(int)),this,SLOT(onSliderPositionActionTriggered(int)));

    ui->sliderTorqueTorque->installEventFilter(this);
    connect(ui->sliderTorqueTorque,SIGNAL(sliderPressed()),this,SLOT(onSliderTorquePressed()));
    connect(ui->sliderTorqueTorque,SIGNAL(sliderReleased()),this,SLOT(onSliderTorqueReleased()));

    ui->sliderOpenloopOutput->installEventFilter(this);
    connect(ui->sliderOpenloopOutput,SIGNAL(sliderPressed()),this,SLOT(onSliderOpenloopPressed()));
    connect(ui->sliderOpenloopOutput,SIGNAL(sliderReleased()),this,SLOT(onSliderOpenloopReleased()));

    ui->sliderPositionDirect->installEventFilter(this);
    connect(ui->sliderPositionDirect,SIGNAL(sliderPressed()),this,SLOT(onSliderPositionPressed()));
    connect(ui->sliderPositionDirect,SIGNAL(sliderReleased()),this,SLOT(onSliderPositionReleased()));

    ui->sliderMixedPosition->installEventFilter(this);
    connect(ui->sliderMixedPosition,SIGNAL(sliderPressed()),this,SLOT(onSliderPositionPressed()));
    connect(ui->sliderMixedPosition,SIGNAL(sliderReleased()),this,SLOT(onSliderPositionReleased()));

    ui->sliderVelocityVelocity->installEventFilter(this);
    connect(ui->sliderVelocityVelocity,SIGNAL(sliderPressed()),this,SLOT(onSliderVelocityPressed()));
    connect(ui->sliderVelocityVelocity,SIGNAL(sliderReleased()),this,SLOT(onSliderVelocityReleased()));

    ui->sliderPositionVelocity->installEventFilter(this);
    connect(ui->sliderPositionVelocity,SIGNAL(sliderMoved(int)),this,SLOT(onSliderVelocityMoved(int)));

    ui->sliderMixedVelocity->installEventFilter(this);
    connect(ui->sliderMixedVelocity,SIGNAL(sliderMoved(int)),this,SLOT(onSliderVelocityMoved(int)));


    connect(ui->buttonHome,SIGNAL(clicked()),this,SLOT(onHomeClicked()));
    connect(ui->buttonIdle,SIGNAL(clicked()),this,SLOT(onIdleClicked()));
    connect(ui->buttonRun,SIGNAL(clicked()),this,SLOT(onRunClicked()));
    connect(ui->buttonPid,SIGNAL(clicked()),this,SLOT(onPidClicked()));
    connect(ui->buttonCalib,SIGNAL(clicked()),this,SLOT(onCalibClicked()));

    ui->groupBox->setTitle(QString("JOINT %1 (%2)").arg(index).arg(jointName));
    // ui->groupBox->setAlignment(Qt::AlignHCenter);




    movingSliderStyle = "QSlider::groove:horizontal:enabled {"
                        "border: 1px solid #999999;"
                        "height: 8px;"
                        "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #FF2E2E, stop:1 #FDA6A6);"
                        "margin: 2px 0;}"
                        "QSlider::groove:horizontal:disabled {"
                        "border: 1px solid #c8c8c8;"
                        "height: 8px;"
                        "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #f0f0f0, stop:1 #dcdcdc);"
                        "margin: 2px 0;}"
                        "QSlider::handle:horizontal:enabled {"
                        "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);"
                        "border: 1px solid #5c5c5c;"
                        "width: 30px;"
                        "margin: -2px 0;"
                        "border-radius: 3px;}"
                        "QSlider::handle:horizontal:disabled {"
                        "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #e6e6e6, stop:1 #c8c8c8);"
                        "border: 1px solid #c8c8c8;"
                        "width: 30px;"
                        "margin: -2px 0;"
                        "border-radius: 3px;}";



    comboStyle1 = "QComboBox {"
                  "border: 1px solid gray;"
                  "border-radius: 3px;"
                  "padding: 1px 18px 1px 3px;"
                  "min-width: 6em;}"
                  "QComboBox:editable {"
                  "background: white;}"
                  "QComboBox::down-arrow {"
                  "image: url(:/images/downArrow.png);}";


    comboStyle2 = "QComboBox:on { "
                  "padding-top: 3px;"
                  "padding-left: 4px;}"
                  "QComboBox::drop-down {"
                  "subcontrol-origin: padding;"
                  "subcontrol-position: top right;"
                  "width: 15px;"
                  "border-left-width: 1px;"
                  "border-left-color: darkgray;"
                  "border-left-style: solid; "
                  "border-top-right-radius: 3px; "
                  "border-bottom-right-radius: 3px;"
                  "background-color: darkgray;}";



    installFilter();

    ui->comboInteraction->setItemData(0,QColor(Qt::darkGray),Qt::BackgroundRole);
    ui->comboInteraction->setItemData(1,QColor(0,80,255),Qt::BackgroundRole);


//    idleColor           = QColor( 249,236,141);
//    positionColor       = QColor( 149,221,186);
//    positionDirectColor = QColor( 119,206,111);
//    mixedColor          = QColor( 150,(221+190)/2,(186+255)/2);
//    velocityColor       = QColor( 150,190,255);
//    torqueColor         = QColor( 219,166,171);
//    openLoopColor       = QColor( 250,250,250);
//    errorColor          = QColor(255,0,0);
//    disconnectColor     = QColor(190,190,190);
//    hwFaultColor        = QColor(255,0,0);
//    calibratingColor    = QColor(220,220,220);

    ui->comboMode->setItemData( IDLE,           idleColor, Qt::BackgroundRole );
    ui->comboMode->setItemData( POSITION,       positionColor, Qt::BackgroundRole );
    ui->comboMode->setItemData( POSITION_DIR,   positionDirectColor, Qt::BackgroundRole );
    ui->comboMode->setItemData( MIXED,          mixedColor, Qt::BackgroundRole );
    ui->comboMode->setItemData( VELOCITY,       velocityColor, Qt::BackgroundRole );
    ui->comboMode->setItemData( TORQUE,         torqueColor, Qt::BackgroundRole );
    ui->comboMode->setItemData( OPENLOOP,       openLoopColor, Qt::BackgroundRole );

    ui->comboMode->setItemData( IDLE,           Idle, Qt::UserRole);
    ui->comboMode->setItemData( POSITION,       Position, Qt::UserRole );
    ui->comboMode->setItemData( POSITION_DIR,   PositionDirect, Qt::UserRole );
    ui->comboMode->setItemData( MIXED,          Mixed, Qt::UserRole );
    ui->comboMode->setItemData( VELOCITY,       Velocity, Qt::UserRole );
    ui->comboMode->setItemData( TORQUE,         Torque, Qt::UserRole );
    ui->comboMode->setItemData( OPENLOOP,       OpenLoop, Qt::UserRole );

    QString styleSheet = QString("%1 QComboBox:!editable, QComboBox::drop-down:editable {background-color: rgb(149,221,186);} %2").arg(comboStyle1).arg(comboStyle2);
    ui->comboMode->setStyleSheet(styleSheet);

    setJointInternalState(IDLE);

    QVariant variant = ui->comboInteraction->itemData(0,Qt::BackgroundRole);
    QColor c = variant.value<QColor>();

    styleSheet = QString("%1 QComboBox:!editable, QComboBox::drop-down:editable {background-color: rgb(%2,%3,%4);} %5").arg(comboStyle1).arg(c.red()).arg(c.green()).arg(c.blue()).arg(comboStyle2);
    ui->comboInteraction->setStyleSheet(styleSheet);


    ui->stackedWidget->widget(VELOCITY)->setEnabled(false);
    velocityTimer.setInterval(50);
    velocityTimer.setSingleShot(false);
    connect(&velocityTimer,SIGNAL(timeout()),this,SLOT(onVelocityTimer()));
}
WColor transform(const QColor& color)
{
	return WColor(color.red(), color.green(), color.blue(), color.alpha());
}
Ejemplo n.º 16
0
void DialogSun::specularColorChange(const QColor &color)
{
    light->sun.setSpecular(color.red()/255.0,color.green()/255.0,color.blue()/255.0);
    ui->pushChoose_Specular->setPalette(QPalette(color));
}
Ejemplo n.º 17
0
QPixmap
KTreemapTile::renderCushion()
{
    QRect rect = QCanvasRectangle::rect();

    if ( rect.width() < 1 || rect.height() < 1 )
	return QPixmap();

    // kdDebug() << k_funcinfo << endl;

    double 	nx;
    double 	ny;
    double 	cosa;
    int		x, y;
    int		red, green, blue;


    // Cache some values. They are used for each loop iteration, so let's try
    // to keep multiple indirect references down.

    int		ambientLight	= parentView()->ambientLight();
    double 	lightX		= parentView()->lightX();
    double 	lightY		= parentView()->lightY();
    double 	lightZ		= parentView()->lightZ();

    double	xx2		= cushionSurface().xx2();
    double	xx1		= cushionSurface().xx1();
    double	yy2		= cushionSurface().yy2();
    double	yy1		= cushionSurface().yy1();

    int		x0 		= rect.x();
    int		y0 		= rect.y();

    QColor	color		= parentView()->tileColor( _orig );
    int		maxRed		= max( 0, color.red()   - ambientLight );
    int		maxGreen	= max( 0, color.green() - ambientLight );
    int		maxBlue		= max( 0, color.blue()  - ambientLight );

    QImage image( rect.width(), rect.height(), 32 );

    for ( y = 0; y < rect.height(); y++ )
    {
	for ( x = 0; x < rect.width(); x++ )
	{
	    nx = 2.0 * xx2 * (x+x0) + xx1;
	    ny = 2.0 * yy2 * (y+y0) + yy1;
	    cosa  = ( nx * lightX + ny * lightY + lightZ ) / sqrt( nx*nx + ny*ny + 1.0 );

	    red	  = (int) ( maxRed   * cosa + 0.5 );
	    green = (int) ( maxGreen * cosa + 0.5 );
	    blue  = (int) ( maxBlue  * cosa + 0.5 );

	    if ( red   < 0 )	red   = 0;
	    if ( green < 0 )	green = 0;
	    if ( blue  < 0 )	blue  = 0;

	    red   += ambientLight;
	    green += ambientLight;
	    blue  += ambientLight;

	    image.setPixel( x, y, qRgb( red, green, blue) );
	}
    }

    if ( _parentView->ensureContrast() )
	ensureContrast( image );

    return QPixmap( image );
}
Ejemplo n.º 18
0
void DialogSun::ambientColorChange(const QColor &color)
{
    light->setAmbient(color.red()/255.0,color.green()/255.0,color.blue()/255.0);
    ui->pushChoose_Ambient->setPalette(QPalette(color));
}
Ejemplo n.º 19
0
QPixmap markerPixmap(const QColor& color, const QColor& bgColor) {
	// create unique string-name for color combinations
	QString cacheName(color.name()+bgColor.name());
	QPixmap px(16, 16);

	// The method signature was changed: it's
	// bool QPixmapCache::find ( const QString & key, QPixmap & pm ) in Qt <= 4.5
	// and
	// bool QPixmapCache::find ( const QString & key, QPixmap * pm ) in Qt >= 4.6
#if QT_VERSION >= 0x040600
	if ( QPixmapCache::find(cacheName, &px) ) {
#else
	if ( QPixmapCache::find(cacheName, px) ) {
#endif
		return px;
	}

	px.fill(bgColor);

	QPainter p(&px);
	// As we are using pixmap cache for most pixmap access
	// we can use more resource and time consuming rendering
	// to get better results (smooth rounded bullet in this case).
	// Remember: painting is performed only once per running juffed
	//           in the ideal case.
	p.setRenderHint(QPainter::Antialiasing);

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

	QColor light(red + (255 - red) / 2, green + (255 - green) / 2, blue + (255 - blue) / 2);
	QColor dark(red / 2, green / 2, blue / 2);

	QRadialGradient gr(0.4, 0.4, 0.5, 0.4, 0.4);
	gr.setCoordinateMode(QGradient::ObjectBoundingMode);
	gr.setColorAt(0, light);
	gr.setColorAt(1, dark);
	p.setPen(dark);
	p.setBrush(gr);
	p.drawEllipse(1, 1, 14, 14);

	p.end();

	QPixmapCache::insert(cacheName, px);
	return px;
}

class SciDoc::Interior {
public:
	Interior(QWidget* w) {
//		LOGGER;

		curEdit_ = NULL;

		spl_ = new QSplitter(Qt::Vertical);
		QVBoxLayout* vBox = new QVBoxLayout();
		vBox->setContentsMargins(0, 0, 0, 0);
		vBox->addWidget(spl_);
		w->setLayout(vBox);

		edit1_ = createEdit();
		edit2_ = createEdit();
		spl_->addWidget(edit1_);
		spl_->addWidget(edit2_);
		edit1_->setDocument(edit2_->document());
		w->setFocusProxy(spl_);
		spl_->setSizes(QList<int>() << 0 << spl_->height());
		
		hlTimer_ = new QTimer( w );
		hlTimer_->setSingleShot( true );
		connect(hlTimer_, SIGNAL(timeout()), w, SLOT(highlightWord()));
	}

	JuffScintilla* createEdit() {
//		LOGGER;
		JuffScintilla* edit = new JuffScintilla();
		edit->setFocusPolicy(Qt::ClickFocus);
		edit->setUtf8(true);
		edit->setFolding(QsciScintilla::BoxedTreeFoldStyle);
		edit->setAutoIndent(true);
		edit->setBraceMatching(QsciScintilla::SloppyBraceMatch);

		// margins
		edit->setMarginLineNumbers(0, false);
		edit->setMarginLineNumbers(1, true);
		edit->setMarginSensitivity(0, true);
		edit->setMarginWidth(0, 20);
		edit->setMarginWidth(2, 12);

		// markers
		edit->markerDefine(QsciScintilla::Background, 2);
		//	Set the 0th margin accept markers numbered 1 and 2
		//	Binary mask for markers 1 and 2 is 00000110 ( == 6 )
		edit->setMarginMarkerMask(0, 6);
		edit->setMarginMarkerMask(1, 0);

		return edit;
	}

	void setCurrentEdit(JuffScintilla* edit) {
//		LOGGER;

		curEdit_ = edit;
		spl_->setFocusProxy(edit);
	}

	JuffScintilla* edit1_;
	JuffScintilla* edit2_;
	JuffScintilla* curEdit_;
	QString syntax_;
	QSplitter* spl_;
	QTimer* hlTimer_;
};

SciDoc::SciDoc(const QString& fileName) : Juff::Document(fileName) {
//	LOGGER;

	int_ = new Interior(this);

	JuffScintilla* edits[] = { int_->edit1_, int_->edit2_ };
	for ( int i = 0; i < 2; ++i) {
		JuffScintilla* edit = edits[i];
		connect(edit, SIGNAL(cursorPositionChanged(int, int)), this, SLOT(onCursorMoved(int, int)));
	//	connect(int_->edit1_, SIGNAL(contextMenuCalled(int, int)), this, SIGNAL(contextMenuCalled(int, int)));
		connect(edit, SIGNAL(marginClicked(int, int, Qt::KeyboardModifiers)), SLOT(onMarginClicked(int, int, Qt::KeyboardModifiers)));
		connect(edit, SIGNAL(focusReceived()), SLOT(onEditFocused()));
		connect(edit, SIGNAL(markersMenuRequested(const QPoint&)), SIGNAL(markersMenuRequested(const QPoint&)));
		connect(edit, SIGNAL(escapePressed()), SIGNAL(escapePressed()));
	}
	connect(int_->edit1_, SIGNAL(modificationChanged(bool)), this, SIGNAL(modified(bool)));
	connect(int_->edit1_, SIGNAL(linesChanged()), SLOT(onLineCountChanged()));
	connect(int_->edit1_, SIGNAL(textChanged()), this, SIGNAL(textChanged()));

	QString lexName = "none";
	SciDoc::Eol eol = guessEol(fileName);
	std::pair<bool,int> indentation = guessIndentation(fileName);
	if ( !fileName.isEmpty() && !isNoname() ) {
		QString codecName = Document::guessCharset(fileName);
		if ( !codecName.isEmpty() )
			setCharset(codecName);
		readFile();
		setEol(eol);
		setIndentationsUseTabs(indentation.first);
		setTabWidth(indentation.second);
		int_->edit1_->setModified(false);

		//	syntax highlighting
		lexName = LexerStorage::instance()->lexerName(fileName);
	}
	else {
		setEol(eol);
		setIndentationsUseTabs(indentation.first);
		setTabWidth(indentation.second);
	}
	
	
	
	
	setLexer(lexName);

	applySettings();

	QAction* hlWordAct = new QAction("", this);
	hlWordAct->setShortcut(QKeySequence("Ctrl+H"));
	connect(hlWordAct, SIGNAL(triggered()), SLOT(highlightWord()));
	addAction(hlWordAct);
}

/*SciDoc::SciDoc(Juff::Document* doc) : Juff::Document(doc) {
	SciDoc* d = qobject_cast<SciDoc*>(doc);
	if ( d != 0 ) {
		int_->edit1_->setDocument(d->int_->edit1_->document());
		int_->edit2_->setDocument(d->int_->edit2_->document());
	}
}*/

SciDoc::~SciDoc() {
	delete int_;
}

QString SciDoc::type() const {
	return "QSci";
}

bool SciDoc::supportsAction(Juff::ActionID id) const {
	switch (id) {
		case Juff::FileClone : return true;
		default :              return Juff::Document::supportsAction(id);
	}
}

/*Juff::Document* SciDoc::createClone() {
	if ( hasClone() )
		return NULL;
	else
		return new SciDoc(this);
}

void SciDoc::updateClone() {
	LOGGER;

//	SciDoc* cln = qobject_cast<SciDoc*>(clone());
//	if ( cln != 0 ) {
//		if ( cln->int_->syntax_ != int_->syntax_ ) {
//			cln->int_->syntax_ = int_->syntax_;
//			QsciLexer* lexer = LexerStorage::instance()->lexer(int_->syntax_);
//			cln->int_->edit1_->setLexer(lexer);
//			cln->int_->edit2_->setLexer(lexer);
//		}
//	}

	Juff::Document::updateClone();
}*/

void SciDoc::init() {
	int_->setCurrentEdit(int_->edit2_);
}
Ejemplo n.º 20
0
void MythRenderD3D9::DrawRect(const QRect &rect, const QColor &color, int alpha)
{
    D3D9Locker locker(this);
    IDirect3DDevice9* dev = locker.Acquire();
    if (!dev)
        return;

    if (!m_rect_vertexbuffer)
    {
        HRESULT hr = dev->CreateVertexBuffer(
                sizeof(VERTEX)*4,     D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
                D3DFVF_VERTEX,        D3DPOOL_DEFAULT,
                &m_rect_vertexbuffer, NULL);

        if (FAILED(hr))
        {
            VERBOSE(VB_IMPORTANT, D3DERR + "Failed to create vertex buffer");
            return;
        }
    }

    EnableBlending(dev, true);
    SetTextureVertices(dev, false);
    MultiTexturing(dev, false);
    SetTexture(dev, NULL, 0);

    int alphamod = (int)(color.alpha() * (alpha / 255.0));
    D3DCOLOR clr = D3DCOLOR_ARGB(alphamod, color.red(),
                                 color.green(), color.blue());
    VERTEX *p_vertices;
    HRESULT hr = m_rect_vertexbuffer->Lock(0, 0, (VOID **)(&p_vertices),
                                           D3DLOCK_DISCARD);
    if (FAILED(hr))
    {
        VERBOSE(VB_IMPORTANT, D3DERR + "Failed to lock vertex buffer.");
        return;
    }

    p_vertices[0].x       = (float)rect.left();
    p_vertices[0].y       = (float)rect.top();
    p_vertices[0].z       = 0.0f;
    p_vertices[0].diffuse = clr;
    p_vertices[0].rhw     = 1.0f;
    p_vertices[1].x       = (float)(rect.left() + rect.width());
    p_vertices[1].y       = (float)rect.top();
    p_vertices[1].z       = 0.0f;
    p_vertices[1].diffuse = clr;
    p_vertices[1].rhw     = 1.0f;
    p_vertices[2].x       = (float)(rect.left() + rect.width());
    p_vertices[2].y       = (float)(rect.top() + rect.height());
    p_vertices[2].z       = 0.0f;
    p_vertices[2].diffuse = clr;
    p_vertices[2].rhw     = 1.0f;
    p_vertices[3].x       = (float)rect.left();
    p_vertices[3].y       = (float)(rect.top() + rect.height());
    p_vertices[3].z       = 0.0f;
    p_vertices[3].diffuse = clr;
    p_vertices[3].rhw     = 1.0f;

    hr = m_rect_vertexbuffer->Unlock();
    if (FAILED(hr))
    {
        VERBOSE(VB_IMPORTANT, D3DERR + "Failed to unlock vertex buffer");
        return;
    }

    hr = dev->SetStreamSource(0, m_rect_vertexbuffer,
                                      0, sizeof(VERTEX));
    if (FAILED(hr))
    {
        VERBOSE(VB_IMPORTANT, D3DERR + "SetStreamSource() failed");
        return;
    }

    hr = dev->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2);
    if (FAILED(hr))
    {
        VERBOSE(VB_IMPORTANT, D3DERR + "DrawPrimitive() failed");
        return;
    }
}
Ejemplo n.º 21
0
void MapView::renderChunk(Chunk *chunk) {
  int offset = 0;
  uchar *bits = chunk->image;
  uchar *depthbits = chunk->depth;
  for (int z = 0; z < 16; z++) {  // n->s
    int lasty = -1;
    for (int x = 0; x < 16; x++, offset++) {  // e->w
      // initialize color
      uchar r = 0, g = 0, b = 0;
      double alpha = 0.0;
      // get Biome
      auto &biome = biomes->getBiome(chunk->biomes[offset]);
      int top = depth;
      if (top > chunk->highest)
        top = chunk->highest;
      int highest = 0;
      for (int y = top; y >= 0; y--) {  // top->down
        int sec = y >> 4;
        ChunkSection *section = chunk->sections[sec];
        if (!section) {
          y = (sec << 4) - 1;  // skip whole section
          continue;
        }

        // get data value
        int data = section->getData(offset, y);

        // get BlockInfo from block value
        BlockInfo &block = blocks->getBlock(section->getBlock(offset, y),
                                            data);
        if (block.alpha == 0.0) continue;

        // get light value from one block above
        int light = 0;
        ChunkSection *section1 = NULL;
        if (y < 255)
          section1 = chunk->sections[(y+1) >> 4];
        if (section1)
          light = section1->getLight(offset, y+1);
        int light1 = light;
        if (!(flags & flgLighting))
          light = 13;
        if (alpha == 0.0 && lasty != -1) {
          if (lasty < y)
            light += 2;
          else if (lasty > y)
            light -= 2;
        }
//        if (light < 0) light = 0;
//        if (light > 15) light = 15;

        // get current block color
        QColor blockcolor = block.colors[15];  // get the color from Block definition
        if (block.biomeWater()) {
          blockcolor = biome.getBiomeWaterColor(blockcolor);
        }
        else if (block.biomeGrass()) {
          blockcolor = biome.getBiomeGrassColor(blockcolor, y-64);
        }
        else if (block.biomeFoliage()) {
          blockcolor = biome.getBiomeFoliageColor(blockcolor, y-64);
        }

        // shade color based on light value
        double light_factor = pow(0.90,15-light);
        quint32 colr = std::clamp( int(light_factor*blockcolor.red()),   0, 255 );
        quint32 colg = std::clamp( int(light_factor*blockcolor.green()), 0, 255 );
        quint32 colb = std::clamp( int(light_factor*blockcolor.blue()),  0, 255 );

        // process flags
        if (flags & flgDepthShading) {
          // Use a table to define depth-relative shade:
          static const quint32 shadeTable[] = {
            0, 12, 18, 22, 24, 26, 28, 29, 30, 31, 32};
          size_t idx = qMin(static_cast<size_t>(depth - y),
                            sizeof(shadeTable) / sizeof(*shadeTable) - 1);
          quint32 shade = shadeTable[idx];
          colr = colr - qMin(shade, colr);
          colg = colg - qMin(shade, colg);
          colb = colb - qMin(shade, colb);
        }
        if (flags & flgMobSpawn) {
          // get block info from 1 and 2 above and 1 below
          quint16 blid1(0), blid2(0), blidB(0);  // default to air
          int data1(0), data2(0), dataB(0);  // default variant
          ChunkSection *section2 = NULL;
          ChunkSection *sectionB = NULL;
          if (y < 254)
            section2 = chunk->sections[(y+2) >> 4];
          if (y > 0)
            sectionB = chunk->sections[(y-1) >> 4];
          if (section1) {
            blid1 = section1->getBlock(offset, y+1);
            data1 = section1->getData(offset, y+1);
          }
          if (section2) {
            blid2 = section2->getBlock(offset, y+2);
            data2 = section2->getData(offset, y+2);
          }
          if (sectionB) {
            blidB = sectionB->getBlock(offset, y-1);
            dataB = sectionB->getData(offset, y-1);
          }
          BlockInfo &block2 = blocks->getBlock(blid2, data2);
          BlockInfo &block1 = blocks->getBlock(blid1, data1);
          BlockInfo &block0 = block;
          BlockInfo &blockB = blocks->getBlock(blidB, dataB);
          int light0 = section->getLight(offset, y);

          // spawn check #1: on top of solid block
          if (block0.doesBlockHaveSolidTopSurface(data) &&
              !block0.isBedrock() && light1 < 8 &&
              !block1.isBlockNormalCube() && block1.spawninside &&
              !block1.isLiquid() &&
              !block2.isBlockNormalCube() && block2.spawninside) {
            colr = (colr + 256) / 2;
            colg = (colg + 0) / 2;
            colb = (colb + 192) / 2;
          }
          // spawn check #2: current block is transparent,
          // but mob can spawn through (e.g. snow)
          if (blockB.doesBlockHaveSolidTopSurface(dataB) &&
              !blockB.isBedrock() && light0 < 8 &&
              !block0.isBlockNormalCube() && block0.spawninside &&
              !block0.isLiquid() &&
              !block1.isBlockNormalCube() && block1.spawninside) {
            colr = (colr + 192) / 2;
            colg = (colg + 0) / 2;
            colb = (colb + 256) / 2;
          }
        }
        if (flags & flgBiomeColors) {
          colr = biome.colors[light].red();
          colg = biome.colors[light].green();
          colb = biome.colors[light].blue();
          alpha = 0;
        }

        // combine current block to final color
        if (alpha == 0.0) {
          // first color sample
          alpha = block.alpha;
          r = colr;
          g = colg;
          b = colb;
          highest = y;
        } else {
          // combine further color samples with blending
          r = (quint8)(alpha * r + (1.0 - alpha) * colr);
          g = (quint8)(alpha * g + (1.0 - alpha) * colg);
          b = (quint8)(alpha * b + (1.0 - alpha) * colb);
          alpha += block.alpha * (1.0 - alpha);
        }

        // finish depth (Y) scanning when color is saturated enough
        if (block.alpha == 1.0 || alpha > 0.9)
          break;
      }
      *depthbits++ = lasty = highest;
      *bits++ = b;
      *bits++ = g;
      *bits++ = r;
      *bits++ = 0xff;
    }
  }
Ejemplo n.º 22
0
HairObject::HairObject(
        ObjMesh *mesh,
        float hairsPerUnitArea,
        float maxHairLength,
        QImage &hairGrowthMap,
        QImage &hairGroomingMap,
        Simulation *simulation,
        HairObject *oldObject)
{    
    if (hairGrowthMap.width() == 0)
    {
        std::cout << "Hair growth map does not appear to be a valid image." << std::endl;
        exit(1);
    }

    m_hairGrowthMap = hairGrowthMap;
    m_hairGroomingMap = hairGroomingMap;

    // Initialize blurred hair growth map texture.
    QImage blurredImage;
    Blurrer::blur(hairGrowthMap, blurredImage);
    m_blurredHairGrowthMapTexture = new Texture();
    m_blurredHairGrowthMapTexture->createColorTexture(blurredImage, GL_LINEAR, GL_LINEAR);

    
    int _failures = 0;
    int _emptyPoints = 0;
    for (unsigned int i = 0; i < mesh->triangles.size(); i++)
    {
        Triangle t = mesh->triangles[i];

        // Number of guide hairs to generate on this triangle.
        int numHairs = (int) (hairsPerUnitArea * t.area() + rand() / (float)RAND_MAX);
        for (int hair = 0; hair < numHairs; hair++)
        {
            // Generate random point on triangle.
            glm::vec3 pos; glm::vec2 uv; glm::vec3 normal;
            t.randPoint(pos, uv, normal);
            uv = glm::vec2(MIN(uv.x, 0.999), MIN(uv.y, 0.999)); // Make UV in range [0,1) instead of [0,1]

            QPoint p = QPoint(uv.x * hairGrowthMap.width(), (1 - uv.y) * hairGrowthMap.height());
            if (!hairGrowthMap.valid(p)){
                _failures++;
                continue; // Don't put hair on neck......
            }

            // If hair growth map is black, skip this hair.
            QColor hairGrowth = QColor(hairGrowthMap.pixel(p));
            if (hairGrowth.valueF() < 0.05){
                _emptyPoints++;
                continue;
            }
            
            glm::vec3 u = glm::normalize(glm::cross(normal, glm::vec3(0, 1, 0)));
            glm::vec3 v = glm::normalize(glm::cross(u, normal));
            QColor groomingColor = QColor(m_hairGroomingMap.pixel(p));
            float a = 10.0 * (groomingColor.red() - 128.0) / 255.0;
            float b = 10.0 * (groomingColor.green() - 128.0) / 255.0;
            glm::vec3 x = glm::vec3(a, b, 1.0);
            glm::mat3 m = glm::mat3(u, v, normal);
            glm::vec3 dir = glm::normalize(m * x);
            
            m_guideHairs.append(new Hair(20, maxHairLength * hairGrowth.valueF(), pos, dir, normal));
        }
    }
    
    setAttributes(oldObject);

    m_simulation = simulation;    
}
Ejemplo n.º 23
0
void VisPrefsDialog::on_bgColorButton_colorPicked( QColor color )
{
	QColor bgColor(color.red(), color.green(), color.blue());
	_vtkVisPipeline->setBGColor(bgColor);
}
Ejemplo n.º 24
0
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e)
{
  bool ok = true;

  clearAttributes(e);

  switch (v.type())
  {
  case QVariant::String:
    e.setTagName("string");
    e.setAttribute("value", v.toString().utf8());
    break;
  case QVariant::CString:
    e.setTagName("string");
    e.setAttribute("value", v.toCString());
    break;
  case QVariant::Int:
    e.setTagName("int");
    e.setAttribute("value", v.toInt());
    break;
  case QVariant::UInt:
    e.setTagName("uint");
    e.setAttribute("value", v.toUInt());
    break;
  case QVariant::Double:
    e.setTagName("double");
    e.setAttribute("value", v.toDouble());
    break;
  case QVariant::Bool:
    e.setTagName("bool");
    e.setAttribute("value", boolString(v.toBool()));
    break;
  case QVariant::Color:
    {
      e.setTagName("color");
      QColor color = v.toColor();
      e.setAttribute("red", color.red());
      e.setAttribute("green", color.green());
      e.setAttribute("blue", color.blue());
    }
    break;
  case QVariant::Pen:
    {
      e.setTagName("pen");
      QPen pen = v.toPen();
      e.setAttribute("red", pen.color().red());
      e.setAttribute("green", pen.color().green());
      e.setAttribute("blue", pen.color().blue());
      e.setAttribute("style", pen.style());
      e.setAttribute("cap", pen.capStyle());
      e.setAttribute("join", pen.joinStyle());
    }
    break;
  case QVariant::Brush:
    {
      e.setTagName("brush");
      QBrush brush = v.toBrush();
      e.setAttribute("red", brush.color().red());
      e.setAttribute("green", brush.color().green());
      e.setAttribute("blue", brush.color().blue());
      e.setAttribute("style", brush.style());
    }
    break;
  case QVariant::Point:
    {
      e.setTagName("point");
      QPoint point = v.toPoint();
      e.setAttribute("x", point.x());
      e.setAttribute("y", point.y());
    }
    break;
  case QVariant::Rect:
    {
      e.setTagName("rect");
      QRect rect = v.toRect();
      e.setAttribute("x", rect.x());
      e.setAttribute("y", rect.y());
      e.setAttribute("width", rect.width());
      e.setAttribute("height", rect.height());
    }
    break;
  case QVariant::Size:
    {
      e.setTagName("size");
      QSize qsize = v.toSize();
      e.setAttribute("width", qsize.width());
      e.setAttribute("height", qsize.height());
    }
    break;
  case QVariant::Font:
    {
      e.setTagName("font");
      QFont f(v.toFont());
      e.setAttribute("family", f.family());
      e.setAttribute("pointsize", f.pointSize());
      e.setAttribute("bold", boolString(f.bold()));
      e.setAttribute("italic", boolString(f.italic()));
      e.setAttribute("underline", boolString(f.underline()));
      e.setAttribute("strikeout", boolString(f.strikeOut()));
    }
    break;
  case QVariant::SizePolicy:
    {
      e.setTagName("sizepolicy");
      QSizePolicy sp(v.toSizePolicy());
      e.setAttribute("hsizetype", sp.horData());
      e.setAttribute("vsizetype", sp.verData());
#if (QT_VERSION >= 300)
      e.setAttribute("horstretch", sp.horStretch());
      e.setAttribute("verstretch", sp.verStretch());
#endif
    }
    break;
  case QVariant::Cursor:
    e.setTagName("cursor");
    e.setAttribute("shape", v.toCursor().shape());
    break;

  case QVariant::StringList:
    {
      e.setTagName("stringlist");
      uint j;
      
      QDomNode n;
      QDomNodeList stringNodeList = e.elementsByTagName("string");
      QDomElement stringElem;
      QStringList stringList = v.toStringList();
      QStringList::Iterator it = stringList.begin();

      for (j = 0; 
	   ((j < stringNodeList.length()) && (it != stringList.end()));
	   j++)
      {
	// get the current string element
	stringElem = stringNodeList.item(j).toElement();

	// set it to the current string
	variantToElement(QVariant(*it), stringElem);

	// iterate to the next string
	++it;
      }
      
      // more nodes in previous stringlist then current, remove excess nodes
      if (stringNodeList.count() > stringList.count())
      {
	while (j < stringNodeList.count())
	  e.removeChild(stringNodeList.item(j).toElement());
      }
      else if (j <stringList.count())
      {
	while (it != stringList.end())
	{
	  // create a new element
	  stringElem = m_doc.createElement("string");
	
	  // set it to the currentstring
	  variantToElement(QVariant(*it), stringElem);

	  // append it to the current element
	  e.appendChild(stringElem);

	  // iterate to the next string
	  ++it;
	}
      }
    }
    break;

#if QT_VERSION >= 300
  case QVariant::KeySequence:
    e.setTagName("key");
    e.setAttribute("sequence", (QString)v.toKeySequence());
    break;
#endif

  case QVariant::ByteArray: // this is only for [u]int64_t
    {
      e.setTagName("uint64");
      QByteArray ba = v.toByteArray();

      // make sure this only handles [u]int64_t's
      if (ba.size() != sizeof(uint64_t))
      {
	qWarning("Don't know how to persist variant of type: %s (%d) (size=%d)!",
		 v.typeName(), v.type(), ba.size());
	ok = false;
	break;
      }

      // convert the data back into a uint64_t
      uint64_t num = *(uint64_t*)ba.data();
      
      QChar buff[33];
      QChar* p = &buff[32];
      const char* digitSet = "0123456789abcdef";
      int len = 0;

      // construct the string
      do 
      {
        *--p = digitSet[((int)(num%16))];
        num = num >> 4; // divide by 16
        len++;
      } while ( num );

      // store it in a QString
      QString storage;
      storage.setUnicode(p, len);
      
      // set the value
      e.setAttribute("value", storage);
    }
    break;

#if 0
  case QVariant::List:
  case QVaraint::Map:
#endif
  default:
    qWarning("Don't know how to persist variant of type: %s (%d)!",
	     v.typeName(), v.type());
    ok = false;
    break;
  }

  return ok;
}
Ejemplo n.º 25
0
std::vector<Vector3f> ShapeEstimation::gradientField(ImageReader mask, std::vector<float> &pixelLuminances, std::vector<float> &gradientX, std::vector<float> &gradientY){
    int rows = mask.getImageHeight();
    int cols = mask.getImageWidth();

    float gxNormalize = 0.0f;
    float gyNormalize = 0.0f;

    for(int row = 0; row < rows; row++){
        for(int col = 0; col < cols; col++){
           int index = mask.indexAt(row, col);
           if(row + 1 < rows){
               int indexUp = mask.indexAt(row + 1, col);
               float dY = pixelLuminances[indexUp] - pixelLuminances[index];
               gradientY.push_back(dY);
               if(fabs(dY) > gyNormalize){
                   gyNormalize = fabs(dY);
               }

           } else {
               gradientY.push_back(0.0f);
           }

           if(col + 1 < cols){
               int indexRight = mask.indexAt(row, col+1);
               float dX = pixelLuminances[indexRight] - pixelLuminances[index];
               gradientX.push_back(dX);
               if(fabs(dX) > gxNormalize){
                   gxNormalize = fabs(dX);
               }
           } else {
               gradientX.push_back(0.0f);
           }

        }
    }
    assert(gradientX.size() == gradientY.size());

    for(int i = 0; i < gradientX.size(); i++){
        gradientX[i] = gradientReshapeRecursive(gradientX[i]/gxNormalize, m_curvature) * gxNormalize;

    }
    for(int i = 0; i < gradientY.size(); i++){
        gradientY[i] = gradientReshapeRecursive(gradientY[i]/gyNormalize, m_curvature) * gyNormalize;
    }

    std::vector<Vector3f> normals;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            QColor maskColor = QColor(mask.pixelAt(i,j));
            if(maskColor.red() > 150){
                Eigen::Vector3f gx = Vector3f(1.0f, 0.0f, gradientX[mask.indexAt(i,j)]);
                Eigen::Vector3f gy = Vector3f(0.0f, 1.0f, gradientY[mask.indexAt(i,j)]);


                Eigen::Vector3f normal = (gx.cross(gy));

                normal = normal.normalized();
                normals.push_back(normal);
            } else {
                normals.push_back(Vector3f(0.0,0.0,0.0));
            }
        }
    }
    //pixelLuminances = gradientX;
    return normals;
}
void RealTimeMultiSampleArrayWidget::onTableViewBackgroundColorChanged(const QColor& backgroundColor)
{
    m_pTableView->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(backgroundColor.red()).arg(backgroundColor.green()).arg(backgroundColor.blue()));
}
Ejemplo n.º 27
0
void Document::loadTheme(const Theme& theme)
{
	m_text->document()->blockSignals(true);

	// Update colors
	QString contrast = (qGray(theme.textColor().rgb()) > 127) ? "black" : "white";
	QColor color = theme.foregroundColor();
	color.setAlpha(theme.foregroundOpacity() * 2.55f);
	m_text->setStyleSheet(
		QString("QTextEdit { background: rgba(%1, %2, %3, %4); color: %5; selection-background-color: %6; selection-color: %7; padding: %8px; border-radius: %9px; }")
			.arg(color.red())
			.arg(color.green())
			.arg(color.blue())
			.arg(color.alpha())
			.arg(theme.textColor().name())
			.arg(theme.textColor().name())
			.arg(contrast)
			.arg(theme.foregroundPadding())
			.arg(theme.foregroundRounding())
	);
	if (m_highlighter->misspelledColor() != theme.misspelledColor()) {
		m_highlighter->setMisspelledColor(theme.misspelledColor());
	}

	// Update text
	QFont font = theme.textFont();
	font.setStyleStrategy(m_text->font().styleStrategy());
	if (m_text->font() != font) {
		m_text->setFont(font);
	}
	m_text->setCursorWidth(!m_block_cursor ? 1 : m_text->fontMetrics().averageCharWidth());

	int margin = theme.foregroundMargin();
	m_layout->setColumnMinimumWidth(0, margin);
	m_layout->setColumnMinimumWidth(2, margin);
	if (theme.foregroundPosition() < 3) {
		m_text->setFixedWidth(theme.foregroundWidth());

		switch (theme.foregroundPosition()) {
		case 0:
			m_layout->setColumnStretch(0, 0);
			m_layout->setColumnStretch(2, 1);
			break;

		case 2:
			m_layout->setColumnStretch(0, 1);
			m_layout->setColumnStretch(2, 0);
			break;

		case 1:
		default:
			m_layout->setColumnStretch(0, 1);
			m_layout->setColumnStretch(2, 1);
			break;
		};
	} else {
		m_text->setMinimumWidth(theme.foregroundWidth());
		m_text->setMaximumWidth(maximumSize().height());

		m_layout->setColumnStretch(0, 0);
		m_layout->setColumnStretch(2, 0);
	}

	centerCursor(true);
	m_text->document()->blockSignals(false);
}
Ejemplo n.º 28
0
bool QgsComposerItem::_writeXML( QDomElement& itemElem, QDomDocument& doc ) const
{
    if ( itemElem.isNull() )
    {
        return false;
    }

    QDomElement composerItemElem = doc.createElement( "ComposerItem" );

    //frame
    if ( mFrame )
    {
        composerItemElem.setAttribute( "frame", "true" );
    }
    else
    {
        composerItemElem.setAttribute( "frame", "false" );
    }

    //scene rect
    composerItemElem.setAttribute( "x", transform().dx() );
    composerItemElem.setAttribute( "y", transform().dy() );
    composerItemElem.setAttribute( "width", rect().width() );
    composerItemElem.setAttribute( "height", rect().height() );
    composerItemElem.setAttribute( "zValue", QString::number( zValue() ) );
    composerItemElem.setAttribute( "outlineWidth", QString::number( pen().widthF() ) );
    composerItemElem.setAttribute( "rotation", mRotation );
    composerItemElem.setAttribute( "id", mId );
    //position lock for mouse moves/resizes
    if ( mItemPositionLocked )
    {
        composerItemElem.setAttribute( "positionLock", "true" );
    }
    else
    {
        composerItemElem.setAttribute( "positionLock", "false" );
    }

    composerItemElem.setAttribute( "lastValidViewScaleFactor", mLastValidViewScaleFactor );


    //frame color
    QDomElement frameColorElem = doc.createElement( "FrameColor" );
    QColor frameColor = pen().color();
    frameColorElem.setAttribute( "red", QString::number( frameColor.red() ) );
    frameColorElem.setAttribute( "green", QString::number( frameColor.green() ) );
    frameColorElem.setAttribute( "blue", QString::number( frameColor.blue() ) );
    frameColorElem.setAttribute( "alpha", QString::number( frameColor.alpha() ) );
    composerItemElem.appendChild( frameColorElem );

    //background color
    QDomElement bgColorElem = doc.createElement( "BackgroundColor" );
    QColor bgColor = brush().color();
    bgColorElem.setAttribute( "red", QString::number( bgColor.red() ) );
    bgColorElem.setAttribute( "green", QString::number( bgColor.green() ) );
    bgColorElem.setAttribute( "blue", QString::number( bgColor.blue() ) );
    bgColorElem.setAttribute( "alpha", QString::number( bgColor.alpha() ) );
    composerItemElem.appendChild( bgColorElem );

    itemElem.appendChild( composerItemElem );

    return true;
}
Ejemplo n.º 29
0
void SpotLight::setAmbientColor(QColor color)
{
    ambient_light =new Vec4((float)color.red()/255.0,(float)color.green()/255.0,(float)color.blue()/255.0);
}
Ejemplo n.º 30
0
void PatternView::paintEvent( QPaintEvent * )
{
	if( m_needsUpdate == false )
	{
		QPainter p( this );
		p.drawPixmap( 0, 0, m_paintPixmap );
		return;
	}

	QPainter _p( this );
	const QColor styleColor = _p.pen().brush().color();

	m_pat->changeLength( m_pat->length() );

	m_needsUpdate = false;

	if( m_paintPixmap.isNull() == true || m_paintPixmap.size() != size() )
	{
		m_paintPixmap = QPixmap( size() );
	}

	QPainter p( &m_paintPixmap );

	QLinearGradient lingrad( 0, 0, 0, height() );

	QColor c;
	if(( m_pat->m_patternType != Pattern::BeatPattern ) &&
		!( m_pat->getTrack()->isMuted() || m_pat->isMuted() ))
	{
		c = styleColor;
	}
	else
	{
		c = QColor( 80, 80, 80 );
	}

	if( isSelected() == true )
	{
		c.setRgb( qMax( c.red() - 128, 0 ), qMax( c.green() - 128, 0 ), 255 );
	}

	if( m_pat->m_patternType != Pattern::BeatPattern )
	{
		lingrad.setColorAt( 1, c.darker( 300 ) );
		lingrad.setColorAt( 0, c );
	}
	else
	{
		lingrad.setColorAt( 0, c.darker( 300 ) );
		lingrad.setColorAt( 1, c );
	}

	p.setBrush( lingrad );
	if( gui->pianoRoll()->currentPattern() == m_pat && m_pat->m_patternType != Pattern::BeatPattern )
		p.setPen( c.lighter( 130 ) );
	else
		p.setPen( c.darker( 300 ) );
	p.drawRect( QRect( 0, 0, width() - 1, height() - 1 ) );

	p.setBrush( QBrush() );
	if( m_pat->m_patternType != Pattern::BeatPattern )
	{
		if( gui->pianoRoll()->currentPattern() == m_pat )
			p.setPen( c.lighter( 160 ) );
		else
			p.setPen( c.lighter( 130 ) );
		p.drawRect( QRect( 1, 1, width() - 3, height() - 3 ) );
	}

	const float ppt = fixedTCOs() ?
			( parentWidget()->width() - 2 * TCO_BORDER_WIDTH )
					/ (float) m_pat->length().getTact() :
				( width() - 2 * TCO_BORDER_WIDTH )
					/ (float) m_pat->length().getTact();


	const int x_base = TCO_BORDER_WIDTH;
	p.setPen( c.darker( 300 ) );

	for( tact_t t = 1; t < m_pat->length().getTact(); ++t )
	{
		p.drawLine( x_base + static_cast<int>( ppt * t ) - 1,
				TCO_BORDER_WIDTH, x_base + static_cast<int>(
						ppt * t ) - 1, 5 );
		p.drawLine( x_base + static_cast<int>( ppt * t ) - 1,
				height() - ( 4 + 2 * TCO_BORDER_WIDTH ),
				x_base + static_cast<int>( ppt * t ) - 1,
				height() - 2 * TCO_BORDER_WIDTH );
	}

// melody pattern paint event

	if( m_pat->m_patternType == Pattern::MelodyPattern )
	{
		if( m_pat->m_notes.size() > 0 )
		{
			// first determine the central tone so that we can
			// display the area where most of the m_notes are
			// also calculate min/max tones so the tonal range can be
			// properly stretched accross the pattern vertically

			int central_key = 0;
			int max_key = 0;
			int min_key = 9999999;
			int total_notes = 0;

			for( NoteVector::Iterator it = m_pat->m_notes.begin();
					it != m_pat->m_notes.end(); ++it )
			{
				if( ( *it )->length() > 0 )
				{
					max_key = qMax( max_key, ( *it )->key() );
					min_key = qMin( min_key, ( *it )->key() );
					central_key += ( *it )->key();
					++total_notes;
				}
			}

			if( total_notes > 0 )
			{
				central_key = central_key / total_notes;
				const int keyrange = qMax( qMax( max_key - central_key, central_key - min_key ), 1 );

				// debug code
				// qDebug( "keyrange: %d", keyrange );

				// determine height of the pattern view, sans borders
				const int ht = (height() - 1 - TCO_BORDER_WIDTH * 2) -1;

				// determine maximum height value for drawing bounds checking
				const int max_ht = height() - 1 - TCO_BORDER_WIDTH;

				// set colour based on mute status
				if( m_pat->getTrack()->isMuted() ||
							m_pat->isMuted() )
				{
					p.setPen( QColor( 160, 160, 160 ) );
				}
				else
				{
					p.setPen( fgColor() );	
				}

				// scan through all the notes and draw them on the pattern
				for( NoteVector::Iterator it =
							m_pat->m_notes.begin();
					it != m_pat->m_notes.end(); ++it )
				{
					// calculate relative y-position
					const float y_key =
						( float( central_key - ( *it )->key() ) / keyrange + 1.0f ) / 2;
					// multiply that by pattern height
					const int y_pos = static_cast<int>( TCO_BORDER_WIDTH + y_key * ht ) + 1;

					// debug code
					// if( ( *it )->length() > 0 ) qDebug( "key %d, central_key %d, y_key %f, y_pos %d", ( *it )->key(), central_key, y_key, y_pos );

					// check that note isn't out of bounds, and has a length
					if( ( *it )->length() > 0 &&
							y_pos >= TCO_BORDER_WIDTH &&
							y_pos <= max_ht )
					{
						// calculate start and end x-coords of the line to be drawn
						const int x1 = x_base +
							static_cast<int>
							( ( *it )->pos() * ( ppt  / MidiTime::ticksPerTact() ) );
						const int x2 = x_base +
							static_cast<int>
							( ( ( *it )->pos() + ( *it )->length() ) * ( ppt  / MidiTime::ticksPerTact() ) );

						// check bounds, draw line
						if( x1 < width() - TCO_BORDER_WIDTH )
							p.drawLine( x1, y_pos,
										qMin( x2, width() - TCO_BORDER_WIDTH ), y_pos );
					}
				}
			}
		}
	}

// beat pattern paint event

	else if( m_pat->m_patternType == Pattern::BeatPattern &&
		( fixedTCOs() || ppt >= 96
			|| m_pat->m_steps != MidiTime::stepsPerTact() ) )
	{
		QPixmap stepon;
		QPixmap stepoverlay;
		QPixmap stepoff;
		QPixmap stepoffl;
		const int steps = qMax( 1,
					m_pat->m_steps );
		const int w = width() - 2 * TCO_BORDER_WIDTH;

		// scale step graphics to fit the beat pattern length
		stepon = s_stepBtnOn->scaled( w / steps,
					      s_stepBtnOn->height(),
					      Qt::IgnoreAspectRatio,
					      Qt::SmoothTransformation );
		stepoverlay = s_stepBtnOverlay->scaled( w / steps,
					      s_stepBtnOn->height(),
					      Qt::IgnoreAspectRatio,
					      Qt::SmoothTransformation );
		stepoff = s_stepBtnOff->scaled( w / steps,
						s_stepBtnOff->height(),
						Qt::IgnoreAspectRatio,
						Qt::SmoothTransformation );
		stepoffl = s_stepBtnOffLight->scaled( w / steps,
						s_stepBtnOffLight->height(),
						Qt::IgnoreAspectRatio,
						Qt::SmoothTransformation );

		for( int it = 0; it < steps; it++ )	// go through all the steps in the beat pattern
		{
			Note * n = m_pat->noteAtStep( it );

			// figure out x and y coordinates for step graphic
			const int x = TCO_BORDER_WIDTH + static_cast<int>( it * w / steps );
			const int y = height() - s_stepBtnOff->height() - 1;

			// get volume and length of note, if noteAtStep returned null
			// (meaning, note at step doesn't exist for some reason)
			// then set both at zero, ie. treat as an off step
			const int vol = ( n != NULL ? n->getVolume() : 0 );
			const int len = ( n != NULL ? int( n->length() ) : 0 );

			if( len < 0 )
			{
				p.drawPixmap( x, y, stepoff );
				for( int i = 0; i < vol / 5 + 1; ++i )
				{
					p.drawPixmap( x, y, stepon );
				}
				for( int i = 0; i < ( 25 + ( vol - 75 ) ) / 5;
									++i )
				{
					p.drawPixmap( x, y, stepoverlay );
				}
			}
			else if( ( it / 4 ) % 2 )
			{
				p.drawPixmap( x, y, stepoffl );
			}
			else
			{
				p.drawPixmap( x, y, stepoff );
			}
		} // end for loop
	}

	p.setFont( pointSize<8>( p.font() ) );

	QColor text_color = ( m_pat->isMuted() || m_pat->getTrack()->isMuted() )
		? QColor( 30, 30, 30 )
		: textColor();

	if( m_pat->name() != m_pat->instrumentTrack()->name() )
	{
		p.setPen( QColor( 0, 0, 0 ) );
		p.drawText( 4, p.fontMetrics().height()+1, m_pat->name() );
		p.setPen( text_color );
		p.drawText( 3, p.fontMetrics().height(), m_pat->name() );
	}

	if( m_pat->isMuted() )
	{
		p.drawPixmap( 3, p.fontMetrics().height() + 1,
				embed::getIconPixmap( "muted", 16, 16 ) );
	}

	p.end();

	_p.drawPixmap( 0, 0, m_paintPixmap );

}