示例#1
0
QSettings::SettingsMap jsonDocumentToVariantMap(const QJsonDocument& document) {
    if (!document.isObject()) {
        qWarning() << "Settings file does not contain a JSON object";
        return QSettings::SettingsMap();
    }
    auto object = document.object();
    QSettings::SettingsMap map;

    for (auto it = object.begin(); it != object.end(); ++it) {

        QVariant result;

        if (!it->isString()) {
            result = it->toVariant();
        } else {
            auto string = it->toString();

            if (string.startsWith(QLatin1String("@@"))) { // Standard string starting with '@'
                result = QVariant(string.mid(1));

            } else if (string.startsWith(QLatin1Char('@'))) { // Custom type to string

                if (string.endsWith(QLatin1Char(')'))) {

                    if (string.startsWith(QLatin1String("@ByteArray("))) {
                        result = QVariant(string.toLatin1().mid(11, string.size() - 12));

                    } else if (string.startsWith(QLatin1String("@Variant("))) {
                        QByteArray a(string.toLatin1().mid(9));
                        QDataStream stream(&a, QIODevice::ReadOnly);
                        stream.setVersion(QDataStream::Qt_4_0);
                        stream >> result;

                    } else if (string.startsWith(QLatin1String("@Rect("))) {
                        QStringList args = splitArgs(string, 5);
                        if (args.size() == 4) {
                            result = QRect(args[0].toInt(), args[1].toInt(),
                                           args[2].toInt(), args[3].toInt());
                        }

                    } else if (string.startsWith(QLatin1String("@Size("))) {
                        QStringList args = splitArgs(string, 5);
                        if (args.size() == 2) {
                            result = QSize(args[0].toInt(), args[1].toInt());
                        }

                    } else if (string.startsWith(QLatin1String("@Point("))) {
                        QStringList args = splitArgs(string, 6);
                        if (args.size() == 2) {
                            result = QPoint(args[0].toInt(), args[1].toInt());
                        }
                    }
                }
            } else { // Standard string
示例#2
0
static int
id3_tag(lame_global_flags* gfp, int type, TextEncoding enc, char* str)
{
    void* x = 0;
    int result;
    switch (enc) 
    {
        default:
        case TENC_RAW:    x = strdup(str);   break;
#ifdef HAVE_ICONV
        case TENC_LATIN1: x = toLatin1(str); break;
        case TENC_UCS2:   x = toUcs2(str);   break;
#endif
    }
    switch (enc)
    {
        default:
        case TENC_RAW:
        case TENC_LATIN1: result = set_id3tag(gfp, type, x);   break;
#ifdef HAVE_ICONV
        case TENC_UCS2:   result = set_id3v2tag(gfp, type, x); break;
#endif
    }
    free(x);
    return result;
}
示例#3
0
Object* OgrFileImport::importPointGeometry(MapPart* map_part, OGRFeatureH feature, OGRGeometryH geometry)
{
	auto style = OGR_F_GetStyleString(feature);
	auto symbol = getSymbol(Symbol::Point, style);
	if (symbol->getType() == Symbol::Point)
	{
		auto object = new PointObject(symbol);
		object->setPosition(toMapCoord(OGR_G_GetX(geometry, 0), OGR_G_GetY(geometry, 0)));
		map_part->addObject(object);
		return object;
	}
	else if (symbol->getType() == Symbol::Text)
	{
		const auto& description = symbol->getDescription();
		auto length = description.length();
		auto split = description.indexOf(QLatin1Char(' '));
		Q_ASSERT(split > 0);
		Q_ASSERT(split < length);
		
		auto label = description.right(length - split - 1);
		if (label.startsWith('{') && label.endsWith('}'))
		{
			label.remove(0,1);
			label.chop(1);
			int index = OGR_F_GetFieldIndex(feature, label.toLatin1());
			if (index >= 0)
			{
				label = QString(OGR_F_GetFieldAsString(feature, index));
			}
		}
		if (!label.isEmpty())
		{
			auto object = new TextObject(symbol);
			object->setAnchorPosition(toMapCoord(OGR_G_GetX(geometry, 0), OGR_G_GetY(geometry, 0)));
			// DXF observation
			label.replace(QRegularExpression("(\\\\[^;]*;)*", QRegularExpression::MultilineOption), QString::null);
			label.replace(QLatin1String("^I"), "\t");
			object->setText(label);
			
			bool ok;
			auto anchor = QStringRef(&description, 1, 2).toInt(&ok);
			if (ok)
			{
				applyLabelAnchor(anchor, object);
			}
				
			auto angle = QStringRef(&description, 3, split-3).toFloat(&ok);
			if (ok)
			{
				object->setRotation(qDegreesToRadians(angle));
			}
			
			map_part->addObject(object);
			return object;
		}
	}
	
	return nullptr;
}
void FindLineEdit::addMenuActions(const QHash<QString, QString> &actionList)
{
    auto menu = new QMenu(this);
    QHash<QString, QString>::const_iterator it;
    for (it = actionList.constBegin(); it != actionList.constEnd(); ++it) {
        auto actionName = it.key();
        auto propertyName = it.value();
        auto action = menu->addAction(actionName);
        action->setCheckable(true);
        setProperty(propertyName.toLatin1().constData(), false);
        actionMap.insert(propertyName, action);
        connect(action, &QAction::triggered, [this, propertyName](bool ck) {
            setProperty(propertyName.toLatin1().constData(), QVariant(ck));
            emit menuActionClicked(propertyName, ck);
        });
    }
    optionsButton->setMenu(menu);
}
示例#5
0
	void update() const
	{
		QSettings settings;
		
		/// \todo Build from driver list in GDAL/OGR >= 2.0
		static const std::vector<QByteArray> default_extensions = { "shp", "shx" };
		enabled_vector_extensions.reserve(default_extensions.size() + 3);
		enabled_vector_extensions = default_extensions;
		
		settings.beginGroup(gdal_manager_group);
		if (settings.value(gdal_dxf_key).toBool())
			enabled_vector_extensions.push_back("dxf");
		if (settings.value(gdal_gpx_key).toBool())
			enabled_vector_extensions.push_back("gpx");
		if (settings.value(gdal_osm_key).toBool())
			enabled_vector_extensions.push_back("osm");
		settings.endGroup();
		
		auto gdal_data = MapperResource::locate(MapperResource::GDAL_DATA);
		if (!gdal_data.isEmpty())
		{
			// The user may overwrite this default in the settings.
			CPLSetConfigOption("GDAL_DATA", gdal_data.toLatin1().constData());
		}
		
		settings.beginGroup(gdal_configuration_group);
		QStringList new_parameters = settings.childKeys();
		if (new_parameters.isEmpty())
		{
			// Default options for debugging and for some drivers
			settings.setValue(QString::fromLatin1("CPL_DEBUG"), QVariant{QLatin1String("OFF")});
			settings.setValue(QString::fromLatin1("USE_PROJ_480_FEATURES"), QVariant{QLatin1String("YES")});
			settings.setValue(QString::fromLatin1("OSM_USE_CUSTOM_INDEXING"), QVariant{QLatin1String("NO")});
			new_parameters = settings.childKeys();
		}
		
		new_parameters.sort();
		for (auto parameter : new_parameters)
		{
			CPLSetConfigOption(parameter.toLatin1().constData(), settings.value(parameter).toByteArray().constData());
		}
		for (auto parameter : static_cast<const QStringList&>(applied_parameters))
		{
			if (!new_parameters.contains(parameter)
			    && parameter != QLatin1String{ "GDAL_DATA" })
			{
				CPLSetConfigOption(parameter.toLatin1().constData(), nullptr);
			}
		}
		applied_parameters.swap(new_parameters);
		
		dirty = false;
	}
bool RS_Graphic::saveAs(const QString &filename, RS2::FormatType type, bool force)
{
	RS_DEBUG->print("RS_Graphic::saveAs: Entering...");

	// Set to "failed" by default.
	bool ret	= false;

	// Check/memorize if file name we want to use as new file
	// name is the same as the actual file name.
	bool fn_is_same	= filename == this->filename;
	auto const filenameSaved=this->filename;
	auto const autosaveFilenameSaved=this->autosaveFilename;
	auto const formatTypeSaved=this->formatType;

	this->filename = filename;
	this->formatType	= type;

	// QString	const oldAutosaveName = this->autosaveFilename;
	QFileInfo	finfo(filename);

	// Construct new autosave filename by prepending # to the filename
	// part, using the same directory as the destination file.
	this->autosaveFilename = finfo.path() + "/#" + finfo.fileName();

	// When drawing is saved using a different name than the actual
	// drawing file name, make LibreCAD think that drawing file
	// has been modified, to make sure the drawing file saved.
	if (!fn_is_same || force)
		setModified(true);

	ret	= save();		//	Save file.

	if (ret) {
		// Save was successful, remove old autosave file.
		QFile	qf_file(autosaveFilenameSaved);

		if (qf_file.exists()) {
			RS_DEBUG->print("RS_Graphic::saveAs: Removing old autosave file %s",
							autosaveFilenameSaved.toLatin1().data());
			qf_file.remove();
		}

	}else{
		//do not modify filenames:
		this->filename=filenameSaved;
		this->autosaveFilename=autosaveFilenameSaved;
		this->formatType=formatTypeSaved;
	}

	return ret;
}
示例#7
0
KeeShareSettings::Reference KeeShare::referenceOf(const Group* group)
{
    static const KeeShareSettings::Reference s_emptyReference;
    const CustomData* customData = group->customData();
    if (!customData->contains(KeeShare_Reference)) {
        return s_emptyReference;
    }
    const auto encoded = customData->value(KeeShare_Reference);
    const auto serialized = QString::fromUtf8(QByteArray::fromBase64(encoded.toLatin1()));
    KeeShareSettings::Reference reference = KeeShareSettings::Reference::deserialize(serialized);
    if (reference.isNull()) {
        qWarning("Invalid sharing reference detected - sharing disabled");
        return s_emptyReference;
    }
    return reference;
}
示例#8
0
void SpecialConfigRequest::dnsFinished() {
	if (!_dnsReply) {
		return;
	}
	auto result = _dnsReply->readAll();
	_dnsReply.release()->deleteLater();

	// Read and store to "entries" map all the data bytes from this response:
	// { .., "Answer": [ { .., "data": "bytes1", .. }, { .., "data": "bytes2", .. } ], .. }
	auto entries = QMap<int, QString>();
	auto error = QJsonParseError { 0, QJsonParseError::NoError };
	auto document = QJsonDocument::fromJson(result, &error);
	if (error.error != QJsonParseError::NoError) {
		LOG(("Config Error: Failed to parse dns response JSON, error: %1").arg(error.errorString()));
	} else if (!document.isObject()) {
		LOG(("Config Error: Not an object received in dns response JSON."));
	} else {
		auto response = document.object();
		auto answerIt = response.find(qsl("Answer"));
		if (answerIt == response.constEnd()) {
			LOG(("Config Error: Could not find Answer in dns response JSON."));
		} else if (!(*answerIt).isArray()) {
			LOG(("Config Error: Not an array received in Answer in dns response JSON."));
		} else {
			for (auto elem : (*answerIt).toArray()) {
				if (!elem.isObject()) {
					LOG(("Config Error: Not an object found in Answer array in dns response JSON."));
				} else {
					auto object = elem.toObject();
					auto dataIt = object.find(qsl("data"));
					if (dataIt == object.constEnd()) {
						LOG(("Config Error: Could not find data in Answer array entry in dns response JSON."));
					} else if (!(*dataIt).isString()) {
						LOG(("Config Error: Not a string data found in Answer array entry in dns response JSON."));
					} else {
						auto data = (*dataIt).toString();
						entries.insertMulti(INT_MAX - data.size(), data);
					}
				}
			}
		}
	}
	auto text = QStringList(entries.values()).join(QString());
	handleResponse(text.toLatin1());
}
示例#9
0
QIcon QmitkStyleManager::ThemeIcon(const QByteArray &originalSVG)
{
  auto styleSheet = qApp->styleSheet();

  if (styleSheet.isEmpty())
    return QPixmap::fromImage(QImage::fromData(originalSVG));

  auto iconColor = ParseColor(styleSheet,
    QStringLiteral("iconColor\\s*[=:]\\s*(#[0-9a-f]{6})"),
    QStringLiteral("#000000"));

  auto iconAccentColor = ParseColor(styleSheet,
    QStringLiteral("iconAccentColor\\s*[=:]\\s*(#[0-9a-f]{6})"),
    QStringLiteral("#ffffff"));

  auto themedSVG = QString(originalSVG).replace(QStringLiteral("#00ff00"), iconColor, Qt::CaseInsensitive);
  themedSVG = themedSVG.replace(QStringLiteral("#ff00ff"), iconAccentColor, Qt::CaseInsensitive);

  return QPixmap::fromImage(QImage::fromData(themedSVG.toLatin1()));
}
示例#10
0
MainWindow::MainWindow(QWidget* _parent)
  :QMainWindow(_parent),
    m_settings(new Settings()),
    m_ui(new Ui::MainWindow()),
    m_copterCtrl(),
    m_tcpServer(),
    m_tcpConnection(),
    m_accelerometerInputFd(-1),
    m_accelerometerInputNotifier(0),
    m_lastTiltX(0),
    m_lastTiltY(0)
{
  m_ui->setupUi(this);
  const auto s_ctrl_path = m_settings->getControlPath();
  QSharedPointer<CopterMotor> mx1(new CopterMotor(m_settings, s_ctrl_path+"ehrpwm.0/pwm/ehrpwm.0:0/duty_percent", m_ui->motor_x1));
  QSharedPointer<CopterMotor> mx2(new CopterMotor(m_settings, s_ctrl_path+"ehrpwm.0/pwm/ehrpwm.0:1/duty_percent", m_ui->motor_x2));
  QSharedPointer<CopterMotor> my1(new CopterMotor(m_settings, s_ctrl_path+"ehrpwm.1/pwm/ehrpwm.1:0/duty_percent", m_ui->motor_y1));
  QSharedPointer<CopterMotor> my2(new CopterMotor(m_settings, s_ctrl_path+"ehrpwm.1/pwm/ehrpwm.1:1/duty_percent", m_ui->motor_y2));
  QSharedPointer<CopterAxis>  m_axisX(new CopterAxis(mx1, mx2));
  QSharedPointer<CopterAxis>  m_axisY(new CopterAxis(my1, my2));
  m_copterCtrl = new CopterCtrl(m_settings, m_axisX, m_axisY, m_ui->motor_all);

  m_tcpServer.listen(QHostAddress::Any, m_settings->getTcpPort());
  connect(&m_tcpServer, SIGNAL(newConnection()), this, SLOT(onConnection()));

  auto const s_accel_input_path = m_settings->getAccelInputPath();
  m_accelerometerInputFd = ::open(s_accel_input_path.toLatin1().data(), O_SYNC, O_RDONLY);
  if (m_accelerometerInputFd == -1)
    qDebug() << "Cannot open accelerometer input file " << s_accel_input_path << ", reason: " << errno;

  m_accelerometerInputNotifier = new QSocketNotifier(m_accelerometerInputFd, QSocketNotifier::Read, this);
  connect(m_accelerometerInputNotifier, SIGNAL(activated(int)), this, SLOT(onAccelerometerRead()));
  m_accelerometerInputNotifier->setEnabled(true);

  m_copterCtrl->adjustPower(0);

  showFullScreen();
  showMaximized();
}
示例#11
0
/* get const char * array function */
const char * rfc::String::data() const {
	return toLatin1().data();
} /* end of 'String::data' function */
示例#12
0
void OgrFileImport::import(bool load_symbols_only)
{
	auto file = qobject_cast<QFile*>(stream);
	if (!file)
	{
		throw FileFormatException("Internal error"); /// \todo Review design and/or message
	}
	
	auto filename = file->fileName();
	// GDAL 2.0: ... = GDALOpenEx(template_path.toLatin1(), GDAL_OF_VECTOR, nullptr, nullptr, nullptr);
	auto data_source = ogr::unique_datasource(OGROpen(filename.toLatin1(), 0, nullptr));
	if (data_source == nullptr)
	{
		throw FileFormatException(Importer::tr("Could not read '%1'")
		                          .arg(filename));
	}
	
	empty_geometries = 0;
	no_transformation = 0;
	failed_transformation = 0;
	unsupported_geometry_type = 0;
	too_few_coordinates = 0;
	
	importStyles(data_source.get());

	if (!load_symbols_only)
	{
		auto num_layers = OGR_DS_GetLayerCount(data_source.get());
		for (int i = 0; i < num_layers; ++i)
		{
			auto layer = OGR_DS_GetLayer(data_source.get(), i);
			if (!layer)
			{
				addWarning(tr("Unable to load layer %1.").arg(i));
				continue;
			}
			
			auto part = map->getCurrentPart();
			if (option(QLatin1String("Separate layers")).toBool())
			{
				if (num_layers > 0)
				{
					if (part->getNumObjects() == 0)
					{
						part->setName(OGR_L_GetName(layer));
					}
					else
					{
						part = new MapPart(OGR_L_GetName(layer), map);
						auto index = map->getNumParts();
						map->addPart(part, index);
						map->setCurrentPartIndex(index);
					}
				}
			}
				
			importLayer(part, layer);
		}
	}
	
	if (empty_geometries)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, empty_geometries)
		           .arg(tr("Empty geometry.")));
	}
	if (no_transformation)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, no_transformation)
		           .arg(tr("Can't determine the coordinate transformation: %1").arg(CPLGetLastErrorMsg())));
	}
	if (failed_transformation)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, failed_transformation)
		           .arg(tr("Failed to transform the coordinates.")));
	}
	if (unsupported_geometry_type)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, unsupported_geometry_type)
		           .arg(tr("Unknown or unsupported geometry type.")));
	}
	if (too_few_coordinates)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, too_few_coordinates)
		           .arg(tr("Not enough coordinates.")));
	}
}
示例#13
0
PlayEngine::PlayEngine()
: d(new Data(this)) {
    Q_ASSERT(d->confDir.isValid());

    _Debug("Create audio/video plugins");
    d->audio = new AudioController(this);
    d->video = new VideoOutput(this);
    d->filter = new VideoFilter;

    d->chapterInfo = new ChapterInfoObject(this, this);
    d->updateMediaName();

    _Debug("Make registrations and connections");

    connect(d->video, &VideoOutput::formatChanged,
            this, &PlayEngine::updateVideoFormat);
    connect(d->video, &VideoOutput::droppedFramesChanged,
            this, &PlayEngine::droppedFramesChanged);

    d->handle = mpv_create();
    auto verbose = qgetenv("CMPLAYER_MPV_VERBOSE").toLower().trimmed();
    const QVector<QByteArray> lvs = {"no", "fatal", "error", "warn", "info",
                                     "status", "v", "debug", "trace"};
    if (lvs.indexOf(verbose) < lvs.indexOf("info"))
        verbose = "info";
    mpv_request_log_messages(d->handle, verbose.constData());

    d->observe();
    connect(this, &PlayEngine::beginChanged, this, &PlayEngine::endChanged);
    connect(this, &PlayEngine::durationChanged, this, &PlayEngine::endChanged);
    connect(this, &PlayEngine::videoStreamsChanged, this, [=] () {
        if (_Change(d->hasVideo, !d->streams[StreamVideo].tracks.isEmpty()))
            emit hasVideoChanged();
        d->videoInfo.setTracks(d->streams[StreamVideo].tracks);
    });
    connect(this, &PlayEngine::audioStreamsChanged, this, [=] ()
        { d->audioInfo.setTracks(d->streams[StreamAudio].tracks); });
    connect(this, &PlayEngine::subtitleStreamsChanged, this, [=] ()
        { d->subInfo.setTracks(d->streams[StreamSubtitle].tracks); });
    connect(this, &PlayEngine::currentVideoStreamChanged, this, [=] (int id)
        { d->videoInfo.setTrack(d->streams[StreamVideo].tracks.value(id)); });
    connect(this, &PlayEngine::currentAudioStreamChanged, this, [=] (int id)
        { d->audioInfo.setTrack(d->streams[StreamAudio].tracks.value(id)); });
    connect(this, &PlayEngine::currentSubtitleStreamChanged, this, [=] ()
        { d->subInfo.setTracks(d->streams[StreamSubtitle].tracks); });
    auto checkDeint = [=] () {
        auto act = Unavailable;
        if (d->filter->isInputInterlaced())
            act = d->filter->isOutputInterlaced() ? Deactivated : Activated;
        d->videoInfo.setDeinterlacer(act);
    };
    connect(d->filter, &VideoFilter::inputInterlacedChanged,
            this, checkDeint, Qt::QueuedConnection);
    connect(d->filter, &VideoFilter::outputInterlacedChanged,
            this, checkDeint, Qt::QueuedConnection);
    connect(d->audio, &AudioController::inputFormatChanged, this, [=] () {
        d->audioInfo.output()->setFormat(d->audio->inputFormat());
    }, Qt::QueuedConnection);
    connect(d->audio, &AudioController::outputFormatChanged, this, [=] () {
        d->audioInfo.renderer()->setFormat(d->audio->outputFormat());
    }, Qt::QueuedConnection);
    connect(d->audio, &AudioController::samplerateChanged, this, [=] (int sr) {
        d->audioInfo.renderer()->setSampleRate(sr, true);
    }, Qt::QueuedConnection);
    connect(d->audio, &AudioController::gainChanged,
            &d->audioInfo, &AudioInfoObject::setNormalizer);
    auto setOption = [this] (const char *name, const char *data) {
        const auto err = mpv_set_option_string(d->handle, name, data);
        d->fatal(err, "Couldn't set option %%=%%.", name, data);
    };
    setOption("fs", "no");
    setOption("input-cursor", "yes");
    setOption("softvol", "yes");
    setOption("softvol-max", "1000.0");
    setOption("sub-auto", "no");
    setOption("osd-level", "0");
    setOption("quiet", "yes");
    setOption("input-terminal", "no");
    setOption("ad-lavc-downmix", "no");
    setOption("title", "\"\"");
    setOption("vo", d->vo().constData());
    setOption("fixed-vo", "yes");

    auto overrides = qgetenv("CMPLAYER_MPV_OPTIONS").trimmed();
    if (!overrides.isEmpty()) {
        const auto opts = QString::fromLocal8Bit(overrides);
        const auto args = opts.split(QRegEx(uR"([\s\t]+)"_q),
                                     QString::SkipEmptyParts);
        for (int i=0; i<args.size(); ++i) {
            if (!args[i].startsWith("--"_a)) {
                _Error("Cannot parse option %%.", args[i]);
                continue;
            }
            const auto arg = args[i].midRef(2);
            const int index = arg.indexOf('='_q);
            if (index < 0) {
                if (arg.startsWith("no-"_a))
                    setOption(arg.mid(3).toLatin1(), "no");
                else
                    setOption(arg.toLatin1(), "yes");
            } else {
                const auto key = arg.left(index).toLatin1();
                const auto value = arg.mid(index+1).toLatin1();
                setOption(key, value);
            }
        }
    }
    d->fatal(mpv_initialize(d->handle), "Couldn't initialize mpv.");
    _Debug("Initialized");
    d->initialized = true;
}
VolumeRenderWidget::VolumeRenderWidget(QWidget *parent)
	:m_renderMode(0), QWidget(parent)
{
	
	m_openGLWidget = new QVTKOpenGLWidget(this);
	vtkNew<vtkGenericOpenGLRenderWindow> renderWindow;
	m_openGLWidget->SetRenderWindow(renderWindow);
	m_renderer = vtkSmartPointer<vtkOpenGLRenderer>::New();
	m_renderer->BackingStoreOn();
	renderWindow->AddRenderer(m_renderer);
	renderWindow->Render(); // making opengl context

	vtkSmartPointer<vtkVolumeProperty> volumeProperty = vtkSmartPointer<vtkVolumeProperty>::New();
	vtkSmartPointer<vtkColorTransferFunction> colorFun = vtkSmartPointer<vtkColorTransferFunction>::New();
	vtkSmartPointer<vtkPiecewiseFunction> opacityFun = vtkSmartPointer<vtkPiecewiseFunction>::New();
	vtkSmartPointer<vtkPiecewiseFunction> gradientFun = vtkSmartPointer<vtkPiecewiseFunction>::New();
	volumeProperty->SetColor(colorFun);
	volumeProperty->SetScalarOpacity(opacityFun);
	volumeProperty->SetGradientOpacity(gradientFun);
	volumeProperty->ShadeOn();
	volumeProperty->SetInterpolationTypeToLinear();
	volumeProperty->SetAmbient(0.6);
	volumeProperty->SetDiffuse(0.9);
	volumeProperty->SetSpecular(0.5);
	volumeProperty->SetSpecularPower(10.0);
	//volumeProperty->IndependentComponentsOff();

	m_settingsWidget = new VolumeRenderSettingsWidget(volumeProperty, this);
	connect(this, &VolumeRenderWidget::imageDataChanged, m_settingsWidget, &VolumeRenderSettingsWidget::setImage);
	connect(m_settingsWidget, &VolumeRenderSettingsWidget::propertyChanged, this, &VolumeRenderWidget::updateRendering);
	connect(m_settingsWidget, &VolumeRenderSettingsWidget::renderModeChanged, this, &VolumeRenderWidget::setRenderMode);
	connect(m_settingsWidget, &VolumeRenderSettingsWidget::cropPlanesChanged, this, &VolumeRenderWidget::setCropPlanes);

	auto layout = new QVBoxLayout;
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(m_openGLWidget);
	this->setLayout(layout);


	//adding orientation prop
	m_orientationProp = std::make_shared<OrientationActorContainer>();
	auto orientationPropPtr = std::static_pointer_cast<VolumeActorContainer>(m_orientationProp).get();
	m_volumeProps.push_back(orientationPropPtr);
	m_renderer->AddActor(m_orientationProp->getActor());	


	//window settings
	m_renderer->SetBackground(0, 0, 0);
	auto menuIcon = QIcon(QString("resources/icons/settings.svg"));
	auto menuButton = new QPushButton(menuIcon, QString(), m_openGLWidget);
	menuButton->setIconSize(QSize(24, 24));
	menuButton->setStyleSheet("QPushButton {background-color:transparent;}");
	auto menu = new QMenu(menuButton);
	menuButton->setMenu(menu);


	auto showAdvancedAction = menu->addAction(tr("Advanced"));
	connect(showAdvancedAction, &QAction::triggered, m_settingsWidget, &VolumeRenderSettingsWidget::toggleVisibility);


	auto showGrapicsAction = menu->addAction(tr("Show graphics"));
	showGrapicsAction->setCheckable(true);
	showGrapicsAction->setChecked(true);
	connect(showGrapicsAction, &QAction::toggled, this, &VolumeRenderWidget::setActorsVisible);

	menu->addAction(QString(tr("Set background color")), [=]() {
		auto color = QColorDialog::getColor(Qt::black, this);
		if (color.isValid())
			m_renderer->SetBackground(color.redF(), color.greenF(), color.blueF());
		updateRendering();
	});
	menu->addAction(QString(tr("Save image to file")), [=]() {
		auto filename = QFileDialog::getSaveFileName(this, tr("Save File"), "untitled.png", tr("Images (*.png)"));
		if (!filename.isEmpty())
		{
			auto renderWindow = m_openGLWidget->GetRenderWindow();
			vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
				vtkSmartPointer<vtkWindowToImageFilter>::New();
			windowToImageFilter->SetInput(renderWindow);
			windowToImageFilter->SetScale(3, 3); //set the resolution of the output image (3 times the current resolution of vtk render window)
			windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel
			windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer
			windowToImageFilter->Update();
			vtkSmartPointer<vtkPNGWriter> writer =
				vtkSmartPointer<vtkPNGWriter>::New();
			writer->SetFileName(filename.toLatin1().data());
			writer->SetInputConnection(windowToImageFilter->GetOutputPort());
			writer->Write();
		}
	});


}
void EntityModel::addFileProperty(Node& child,
								  Lumix::IPropertyDescriptor* desc,
								  Lumix::ComponentUID cmp,
								  bool is_array,
								  bool is_resource)
{
	child.m_setter = [is_array, &child, desc, cmp, this](const QVariant& value)
	{
		this->set(cmp.entity,
				  cmp.type,
				  is_array ? child.m_parent->getIndex() : -1,
				  desc,
				  value);
	};
	child.onSetModelData = [is_array, &child, desc, cmp, this](QWidget* editor)
	{
		const auto& children = editor->children();
		auto value = qobject_cast<QLineEdit*>(children[1])->text();
		this->set(cmp.entity,
				  cmp.type,
				  is_array ? child.m_parent->getIndex() : -1,
				  desc,
				  value);
	};
	child.onDrop = [is_array, &child, desc, cmp, this](const QMimeData* data,
													   Qt::DropAction)
	{
		QList<QUrl> urls = data->urls();
		Q_ASSERT(urls.size() < 2);
		if (urls.size() == 1)
		{
			char rel_path[Lumix::MAX_PATH_LENGTH];
			Lumix::Path path(urls[0].toLocalFile().toLatin1().data());
			m_editor.getRelativePath(rel_path, Lumix::MAX_PATH_LENGTH, path);
			this->set(cmp.entity,
					  cmp.type,
					  is_array ? child.m_parent->getIndex() : -1,
					  desc,
					  rel_path);
			return true;
		}
		return false;
	};
	child.onCreateEditor = [is_array, &child, is_resource, desc, cmp, this](
		QWidget* parent, const QStyleOptionViewItem&) -> QWidget*
	{
		QWidget* widget = new QWidget(parent);
		QHBoxLayout* layout = new QHBoxLayout(widget);
		QLineEdit* edit = new QLineEdit(widget);
		layout->addWidget(edit);
		QPushButton* button = new QPushButton("Browse", widget);
		connect(button,
				&QPushButton::clicked,
				[edit, parent, this]()
				{
					auto value = QFileDialog::getOpenFileName();
					if (!value.isEmpty())
					{
						char rel_path[Lumix::MAX_PATH_LENGTH];
						Lumix::Path path(value.toLatin1().data());
						m_editor.getRelativePath(
							rel_path, Lumix::MAX_PATH_LENGTH, path);
						edit->setText(rel_path);
					}
				});
		layout->addWidget(button);
		if (is_resource)
		{
			QPushButton* go_button = new QPushButton("->", widget);
			connect(go_button,
					&QPushButton::clicked,
					[edit, this]()
					{
						m_view.setSelectedResourceFilename(
							edit->text().toLatin1().data());
					});
			layout->addWidget(go_button);
		}
		layout->setContentsMargins(0, 0, 0, 0);
		edit->setText(this->get(cmp.entity,
								cmp.type,
								is_array ? child.m_parent->getIndex() : -1,
								desc)
						  .toString());
		return widget;
	};
}
示例#16
0
void BakerCLI::bakeFile(QUrl inputUrl, const QString& outputPath, const QString& type) {

    // if the URL doesn't have a scheme, assume it is a local file
    if (inputUrl.scheme() != "http" && inputUrl.scheme() != "https" && inputUrl.scheme() != "ftp" && inputUrl.scheme() != "file") {
        inputUrl = QUrl::fromLocalFile(inputUrl.toString());
    }

    qDebug() << "Baking file type: " << type;

    static const QString MODEL_EXTENSION { "fbx" };
    static const QString SCRIPT_EXTENSION { "js" };

    // check what kind of baker we should be creating
    bool isFBX = type == MODEL_EXTENSION;
    bool isScript = type == SCRIPT_EXTENSION;

    // If the type doesn't match the above, we assume we have a texture, and the type specified is the
    // texture usage type (albedo, cubemap, normals, etc.)
    auto url = inputUrl.toDisplayString();
    auto idx = url.lastIndexOf('.');
    auto extension = idx >= 0 ? url.mid(idx + 1).toLower() : "";
    bool isSupportedImage = QImageReader::supportedImageFormats().contains(extension.toLatin1());

    _outputPath = outputPath;

    // create our appropiate baker
    if (isFBX) {
        _baker = std::unique_ptr<Baker> {
            new FBXBaker(inputUrl,
                         []() -> QThread* { return Oven::instance().getNextWorkerThread(); },
                         outputPath)
        };
        _baker->moveToThread(Oven::instance().getNextWorkerThread());
    } else if (isScript) {
        _baker = std::unique_ptr<Baker> { new JSBaker(inputUrl, outputPath) };
        _baker->moveToThread(Oven::instance().getNextWorkerThread());
    } else if (isSupportedImage) {
        static const std::unordered_map<QString, image::TextureUsage::Type> STRING_TO_TEXTURE_USAGE_TYPE_MAP {
            { "default", image::TextureUsage::DEFAULT_TEXTURE },
            { "strict", image::TextureUsage::STRICT_TEXTURE },
            { "albedo", image::TextureUsage::ALBEDO_TEXTURE },
            { "normal", image::TextureUsage::NORMAL_TEXTURE },
            { "bump", image::TextureUsage::BUMP_TEXTURE },
            { "specular", image::TextureUsage::SPECULAR_TEXTURE },
            { "metallic", image::TextureUsage::METALLIC_TEXTURE },
            { "roughness", image::TextureUsage::ROUGHNESS_TEXTURE },
            { "gloss", image::TextureUsage::GLOSS_TEXTURE },
            { "emissive", image::TextureUsage::EMISSIVE_TEXTURE },
            { "cube", image::TextureUsage::CUBE_TEXTURE },
            { "occlusion", image::TextureUsage::OCCLUSION_TEXTURE },
            { "scattering", image::TextureUsage::SCATTERING_TEXTURE },
            { "lightmap", image::TextureUsage::LIGHTMAP_TEXTURE },
        };

        auto it = STRING_TO_TEXTURE_USAGE_TYPE_MAP.find(type);
        if (it == STRING_TO_TEXTURE_USAGE_TYPE_MAP.end()) {
            qCDebug(model_baking) << "Unknown texture usage type:" << type;
            QCoreApplication::exit(OVEN_STATUS_CODE_FAIL);
        }
        _baker = std::unique_ptr<Baker> { new TextureBaker(inputUrl, it->second, outputPath) };
        _baker->moveToThread(Oven::instance().getNextWorkerThread());
    } else {
        qCDebug(model_baking) << "Failed to determine baker type for file" << inputUrl;
        QCoreApplication::exit(OVEN_STATUS_CODE_FAIL);
        return;
    }

    // invoke the bake method on the baker thread
    QMetaObject::invokeMethod(_baker.get(), "bake");

    // make sure we hear about the results of this baker when it is done
    connect(_baker.get(), &Baker::finished, this, &BakerCLI::handleFinishedBaker);
}