id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,533,869
qormquerybuilder.h
dpurgin_qtorm/src/orm/qormquerybuilder.h
/* * Copyright (C) 2019 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMQUERYBUILDER_H #define QORMQUERYBUILDER_H #include <QtOrm/qormfilter.h> #include <QtOrm/qormfilterexpression.h> #include <QtOrm/qormglobal.h> #include <QtOrm/qormquery.h> #include <QtOrm/qormqueryresult.h> #include <QtCore/qobject.h> #include <QtCore/qshareddata.h> #include <QtCore/qvector.h> #include <memory> QT_BEGIN_NAMESPACE class QOrmAbstractProvider; class QOrmFilterExpression; class QOrmMetadataCache; class QOrmQueryBuilderPrivate; class QOrmRelation; class QOrmSession; namespace QOrmPrivate { class QueryBuilderHelperPrivate; class Q_ORM_EXPORT QueryBuilderHelper { public: QueryBuilderHelper(QOrmSession* session, const QOrmRelation& relation); QueryBuilderHelper(const QueryBuilderHelper&) = delete; QueryBuilderHelper(QueryBuilderHelper&&); ~QueryBuilderHelper(); QueryBuilderHelper& operator=(const QueryBuilderHelper&) = delete; QueryBuilderHelper& operator=(QueryBuilderHelper&&); void setInstance(const QMetaObject& qMetaObject, QObject* instance); void addFilter(const QOrmFilter& filter); void addOrder(const QOrmClassProperty& classProperty, Qt::SortOrder direction); void setLimit(int limit); void setOffset(int offset); Q_REQUIRED_RESULT QOrmQuery build(QOrm::Operation operation, QOrm::QueryFlags flags) const; Q_REQUIRED_RESULT QOrmQueryResult<QObject> select(QOrm::QueryFlags flags) const; [[nodiscard]] QOrmQueryResult<QObject> remove() const; private: std::unique_ptr<QueryBuilderHelperPrivate> d; }; } // namespace QOrmPrivate template<typename T> class QOrmQueryBuilder { template<typename> friend class QOrmQueryBuilder; public: using Projection = std::decay_t<T>; using UnaryPredicate = std::function<bool(const Projection*)>; explicit QOrmQueryBuilder(QOrmSession* session, const QOrmRelation& relation) : m_helper{session, relation} { } QOrmQueryBuilder(const QOrmQueryBuilder&) = delete; template<typename U, typename = std::enable_if_t<std::is_same_v<U, QObject> || std::is_same_v<U, T>>> QOrmQueryBuilder(QOrmQueryBuilder<U>&& other) : m_helper{std::move(other.m_helper)} { } QOrmQueryBuilder& operator=(const QOrmQueryBuilder&) = delete; QOrmQueryBuilder& operator=(QOrmQueryBuilder&&) = default; QOrmQueryBuilder& filter(QOrmFilterExpression expression) { m_helper.addFilter(QOrmFilter{expression}); return *this; } QOrmQueryBuilder& filter(UnaryPredicate predicate) { m_helper.addFilter(QOrmFilter{[predicate](const QObject* value) { return predicate(qobject_cast<const Projection*>(value)); }}); return *this; } QOrmQueryBuilder& order(const QOrmClassProperty& classProperty, Qt::SortOrder direction = Qt::AscendingOrder) { m_helper.addOrder(classProperty, direction); return *this; } QOrmQueryBuilder& instance(const QMetaObject& qMetaObject, QObject* instance) { m_helper.setInstance(qMetaObject, instance); return *this; } QOrmQueryBuilder& limit(int limit) { m_helper.setLimit(limit); return *this; } QOrmQueryBuilder& offset(int offset) { m_helper.setOffset(offset); return *this; } Q_REQUIRED_RESULT QOrmQueryResult<Projection> select(QOrm::QueryFlags flags = QOrm::QueryFlags::None) const { return m_helper.select(flags); } [[nodiscard]] QOrmQueryResult<Projection> remove() { return m_helper.remove(); } Q_REQUIRED_RESULT QOrmQuery build(QOrm::Operation operation, QOrm::QueryFlags flags = QOrm::QueryFlags::None) const { return m_helper.build(operation, flags); } private: QOrmPrivate::QueryBuilderHelper m_helper; }; QT_END_NAMESPACE #endif // QORMQUERYBUILDER_H
4,807
C++
.h
130
31.738462
146
0.721636
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,870
qormquery.h
dpurgin_qtorm/src/orm/qormquery.h
/* * Copyright (C) 2019 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMQUERY_H #define QORMQUERY_H #include <QtCore/qglobal.h> #include <QtCore/qshareddata.h> #include <QtOrm/qormglobal.h> #include <QtOrm/qormqueryresult.h> #include <vector> #include <optional> QT_BEGIN_NAMESPACE class QOrmFilter; class QOrmOrder; class QOrmQueryPrivate; class QOrmRelation; class QOrmMetadata; class Q_ORM_EXPORT QOrmQuery { public: QOrmQuery(QOrm::Operation operation, const QOrmRelation& relation, const std::optional<QOrmMetadata>& projection, const std::optional<QOrmFilter>& expressionFilter, const std::optional<QOrmFilter>& invokableFilter, const std::vector<QOrmOrder>& order, const QFlags<QOrm::QueryFlags>& flags); QOrmQuery(QOrm::Operation operation, const QOrmMetadata& relation, QObject* entityInstance); QOrmQuery(const QOrmQuery&); QOrmQuery(QOrmQuery&&); ~QOrmQuery(); QOrmQuery& operator=(const QOrmQuery&); QOrmQuery& operator=(QOrmQuery&&); Q_REQUIRED_RESULT QOrm::Operation operation() const; Q_REQUIRED_RESULT const QOrmRelation& relation() const; Q_REQUIRED_RESULT const std::optional<QOrmMetadata>& projection() const; Q_REQUIRED_RESULT const std::optional<QOrmFilter>& expressionFilter() const; Q_REQUIRED_RESULT const std::optional<QOrmFilter>& invokableFilter() const; Q_REQUIRED_RESULT const std::vector<QOrmOrder>& order() const; Q_REQUIRED_RESULT const QObject* entityInstance() const; Q_REQUIRED_RESULT const QFlags<QOrm::QueryFlags>& flags() const; [[nodiscard]] std::optional<int> limit() const; void setLimit(std::optional<int> limit); [[nodiscard]] std::optional<int> offset() const; void setOffset(std::optional<int> offset); private: QSharedDataPointer<QOrmQueryPrivate> d; }; QDebug operator<<(QDebug dbg, const QOrmQuery& query); QT_END_NAMESPACE #endif // QORMQUERY_H
2,798
C++
.h
75
33.16
96
0.736394
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,871
qormclassproperty.h
dpurgin_qtorm/src/orm/qormclassproperty.h
/* * Copyright (C) 2019-2022 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2022 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMCLASSPROPERTY_H #define QORMCLASSPROPERTY_H #include <QtCore/qstring.h> #include <QtOrm/qormglobal.h> QT_BEGIN_NAMESPACE class QOrmFilterExpression; class Q_ORM_EXPORT QOrmClassProperty { public: explicit QOrmClassProperty(const char* descriptor); QString descriptor() const; QOrmFilterExpression contains(const QVariant& value) const; QOrmFilterExpression notContains(const QVariant& value) const; private: QString m_descriptor; }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmClassProperty& classProperty); #define Q_ORM_CLASS_PROPERTY(descriptor) (QOrmClassProperty{#descriptor}) QT_END_NAMESPACE #endif // QORMCLASSPROPERTY_H
1,546
C++
.h
39
37.333333
90
0.785141
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,872
qormmetadata_p.h
dpurgin_qtorm/src/orm/qormmetadata_p.h
/* * Copyright (C) 2019 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMMETADATA_P_H #define QORMMETADATA_P_H #include "QtOrm/qormpropertymapping.h" #include <QtCore/qshareddata.h> #include <vector> class QOrmMetadataPrivate : public QSharedData { public: QOrmMetadataPrivate(const QMetaObject& metaObject) : m_qMetaObject{metaObject} { } const QMetaObject& m_qMetaObject; QString m_className; QString m_tableName; std::vector<QOrmPropertyMapping> m_propertyMappings; int m_objectIdPropertyMappingIdx{-1}; QHash<QString, int> m_classPropertyMappingIndex; QHash<QString, int> m_tableFieldMappingIndex; QOrmUserMetadata m_userMetadata; }; #endif
1,491
C++
.h
41
33.439024
79
0.764747
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,873
qormabstractprovider.h
dpurgin_qtorm/src/orm/qormabstractprovider.h
/* * Copyright (C) 2019 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2022 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMABSTRACTPROVIDER_H #define QORMABSTRACTPROVIDER_H #include <QtOrm/qormglobal.h> #include <QtOrm/qormqueryresult.h> QT_BEGIN_NAMESPACE class QObject; class QOrmEntityInstanceCache; class QOrmError; class QOrmMetadataCache; class QOrmQuery; class Q_ORM_EXPORT QOrmAbstractProvider { public: virtual ~QOrmAbstractProvider(); virtual QOrmError connectToBackend() = 0; virtual QOrmError disconnectFromBackend() = 0; virtual bool isConnectedToBackend() = 0; virtual QOrmError beginTransaction() = 0; virtual QOrmError commitTransaction() = 0; virtual QOrmError rollbackTransaction() = 0; virtual QOrmQueryResult<QObject> execute(const QOrmQuery& query, QOrmEntityInstanceCache& entityInstanceCache) = 0; [[nodiscard]] virtual int capabilities() const = 0; }; QT_END_NAMESPACE #endif // QORMABSTRACTPROVIDER_H
1,766
C++
.h
45
35.622222
95
0.754971
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,874
qormglobal.h
dpurgin_qtorm/src/orm/qormglobal.h
/* * Copyright (C) 2019-2022 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2022 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMGLOBAL_H #define QORMGLOBAL_H #include <algorithm> #include <QtCore/qglobal.h> #include <QtCore/qhashfunctions.h> #include <QtCore/qmetatype.h> #include <QtCore/qobject.h> #include <QtCore/qset.h> #include <QtCore/qvector.h> QT_BEGIN_NAMESPACE #ifndef QT_STATIC #ifdef QT_BUILD_ORM_LIB #define Q_ORM_EXPORT Q_DECL_EXPORT #else #define Q_ORM_EXPORT Q_DECL_IMPORT #endif #else #define Q_ORM_EXPORT #endif class QDebug; namespace QOrm { enum class ErrorType { None, Provider, UnsynchronizedEntity, UnsynchronizedSchema, InvalidMapping, TransactionNotActive, Other }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, QOrm::ErrorType error); enum class TransactionPropagation { Require, Support, DontSupport }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, QOrm::TransactionPropagation propagation); enum class TransactionAction { Commit, Rollback }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, QOrm::TransactionAction action); enum class Comparison { Equal, NotEqual, Less, LessOrEqual, Greater, GreaterOrEqual, InList, NotInList, Contains, NotContains }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, QOrm::Comparison comparison); extern Q_ORM_EXPORT uint qHash(Comparison comparison) Q_DECL_NOTHROW; enum class BinaryLogicalOperator { And, Or }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, QOrm::BinaryLogicalOperator logicalOperator); enum class UnaryLogicalOperator { Not }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, QOrm::UnaryLogicalOperator logicalOperator); enum class Operation { Create, Read, Update, Delete, Merge }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, Operation operation); enum class FilterType { Expression, Invokable }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, FilterType filterType); enum class FilterExpressionType { TerminalPredicate, BinaryPredicate, UnaryPredicate }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, FilterExpressionType expressionType); enum class RemoveMode { PreventRemoveAll, ForceRemoveAll }; enum class RelationType { Query, Mapping }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, QOrm::RelationType relationType); enum class QueryFlags { None = 0x00, OverwriteCachedInstances = 0x01 }; enum class Keyword { Table, Property, Column, Autogenerated, Identity, Transient, Schema }; inline uint qHash(Keyword value) { return ::qHash(static_cast<int>(value)); } } // namespace QOrm namespace QOrmPrivate { template<typename From, typename To, typename ToValueType = typename To::value_type> struct ContainerConverter { static To convert(const From& v) { To result; std::transform(std::begin(v), std::end(v), std::inserter(result, std::end(result)), [](auto o) { return qobject_cast<ToValueType>(o); }); return result; } }; template<typename From, typename ToValueType> struct ContainerConverter<From, QSet<ToValueType>> { static QSet<ToValueType> convert(const From& v) { QSet<ToValueType> result; for (auto o : v) result.insert(qobject_cast<ToValueType>(o)); return result; } }; template<typename EntityContainer, typename Entity = typename EntityContainer::value_type> void registerContainerConverter() { if (!QMetaType::hasRegisteredConverterFunction<EntityContainer, QVector<QObject*>>()) { QMetaType::registerConverter<EntityContainer, QVector<QObject*>>( &ContainerConverter<EntityContainer, QVector<QObject*>>::convert); } if (!QMetaType::hasRegisteredConverterFunction<QVector<QObject*>, EntityContainer>()) { QMetaType::registerConverter<QVector<QObject*>, EntityContainer>( &ContainerConverter<QVector<QObject*>, EntityContainer>::convert); } } template<typename T> inline void qRegisterOrmEntity() { qRegisterMetaType<T*>(); qRegisterMetaType<QVector<T*>>(); qRegisterMetaType<QSet<T*>>(); registerContainerConverter<QVector<T*>>(); registerContainerConverter<QSet<T*>>(); } template<typename T> inline void qRegisterOrmEnum() { QMetaType::registerConverter<T, int>([](T myEnum) -> int { return static_cast<int>(myEnum); }); QMetaType::registerConverter<int, T>([](int myEnum) -> T { return static_cast<T>(myEnum); }); QMetaType::registerConverter<T, QString>( [](T myEnum) -> QString { return QString::number(static_cast<int>(myEnum)); }); QMetaType::registerConverter<QString, T>([](QString myEnum) -> T { return static_cast<T>(myEnum.toInt()); }); } } // namespace QOrmPrivate template<typename... Ts> inline constexpr void qRegisterOrmEntity() { (..., QOrmPrivate::qRegisterOrmEntity<Ts>()); } template<typename... Ts> inline constexpr void qRegisterOrmEnum() { (..., QOrmPrivate::qRegisterOrmEnum<Ts>()); } using QOrmUserMetadata = QHash<QOrm::Keyword, QVariant>; QT_END_NAMESPACE #define Q_ORM_CLASS(arg) Q_CLASSINFO("QtOrmClassInfo", #arg) #define Q_ORM_PROPERTY(arg) Q_CLASSINFO("QtOrmPropertyInfo", #arg) #endif
6,849
C++
.h
218
24.568807
99
0.649682
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,875
qormpropertymapping.h
dpurgin_qtorm/src/orm/qormpropertymapping.h
/* * Copyright (C) 2019-2021 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2021 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMPROPERTYMAPPING_H #define QORMPROPERTYMAPPING_H #include <QtOrm/qormglobal.h> #include <QtCore/qmetaobject.h> #include <QtCore/qshareddata.h> #include <QtCore/qstring.h> #include <QtCore/qvariant.h> QT_BEGIN_NAMESPACE class QOrmMetadata; class QOrmPropertyMappingPrivate; class Q_ORM_EXPORT QOrmPropertyMapping { public: QOrmPropertyMapping(const QOrmMetadata& enclosingEntity, QMetaProperty qMetaProperty, QString classPropertyName, QString tableFieldName, bool isObjectId, bool isAutoGenerated, QVariant::Type dataType, const QOrmMetadata* referencedEntity, bool isTransient, QOrmUserMetadata userMetadata); QOrmPropertyMapping(const QOrmPropertyMapping&); QOrmPropertyMapping(QOrmPropertyMapping&&); ~QOrmPropertyMapping(); QOrmPropertyMapping& operator=(const QOrmPropertyMapping&); QOrmPropertyMapping& operator=(QOrmPropertyMapping&&); [[nodiscard]] const QOrmMetadata& enclosingEntity() const; [[nodiscard]] const QMetaProperty& qMetaProperty() const; [[nodiscard]] QString classPropertyName() const; [[nodiscard]] QString tableFieldName() const; [[nodiscard]] bool isObjectId() const; [[nodiscard]] bool isAutogenerated() const; [[nodiscard]] QVariant::Type dataType() const; [[nodiscard]] QString dataTypeName() const; [[nodiscard]] bool isReference() const; [[nodiscard]] const QOrmMetadata* referencedEntity() const; [[nodiscard]] bool isTransient() const; [[nodiscard]] const QOrmUserMetadata& userMetadata() const; private: QSharedDataPointer<QOrmPropertyMappingPrivate> d; }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmPropertyMapping& propertyMapping); QT_END_NAMESPACE #endif
2,781
C++
.h
65
36.830769
94
0.720414
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,876
qormfilterexpression.h
dpurgin_qtorm/src/orm/qormfilterexpression.h
/* * Copyright (C) 2019-2022 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2022 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMFILTERBUILDER_H #define QORMFILTERBUILDER_H #include <QtOrm/qormglobal.h> #include <QtOrm/qormclassproperty.h> #include <QtOrm/qormpropertymapping.h> #include <QtCore/qshareddata.h> #include <QtCore/qvariant.h> #include <variant> QT_BEGIN_NAMESPACE class QOrmFilterExpressionPrivate; class QVariant; class QOrmFilterTerminalPredicate; class QOrmFilterBinaryPredicate; class QOrmFilterUnaryPredicate; class Q_ORM_EXPORT QOrmFilterExpression { public: QOrmFilterExpression(const QOrmFilterTerminalPredicate& terminalPredicate); QOrmFilterExpression(const QOrmFilterBinaryPredicate& binaryPredicate); QOrmFilterExpression(const QOrmFilterUnaryPredicate& unaryPredicate); QOrmFilterExpression(const QOrmFilterExpression&); QOrmFilterExpression(QOrmFilterExpression&&); ~QOrmFilterExpression(); QOrmFilterExpression& operator=(const QOrmFilterExpression&); QOrmFilterExpression& operator=(QOrmFilterExpression&&); Q_REQUIRED_RESULT QOrm::FilterExpressionType type() const; Q_REQUIRED_RESULT const QOrmFilterTerminalPredicate* terminalPredicate() const; Q_REQUIRED_RESULT const QOrmFilterBinaryPredicate* binaryPredicate() const; Q_REQUIRED_RESULT const QOrmFilterUnaryPredicate* unaryPredicate() const; private: QSharedDataPointer<QOrmFilterExpressionPrivate> d; }; class Q_ORM_EXPORT QOrmFilterTerminalPredicate { public: using FilterProperty = std::variant<QOrmClassProperty, QOrmPropertyMapping>; QOrmFilterTerminalPredicate(FilterProperty filterProperty, QOrm::Comparison comparison, QVariant value); Q_REQUIRED_RESULT bool isResolved() const; Q_REQUIRED_RESULT const QOrmClassProperty* classProperty() const; Q_REQUIRED_RESULT const QOrmPropertyMapping* propertyMapping() const; Q_REQUIRED_RESULT QOrm::Comparison comparison() const; Q_REQUIRED_RESULT QVariant value() const; private: std::variant<QOrmClassProperty, QOrmPropertyMapping> m_filterProperty; QOrm::Comparison m_comparison; QVariant m_value; }; class Q_ORM_EXPORT QOrmFilterBinaryPredicate { public: QOrmFilterBinaryPredicate(QOrmFilterExpression lhs, QOrm::BinaryLogicalOperator logicalOperator, QOrmFilterExpression rhs); Q_REQUIRED_RESULT const QOrmFilterExpression& lhs() const; Q_REQUIRED_RESULT QOrm::BinaryLogicalOperator logicalOperator() const; Q_REQUIRED_RESULT const QOrmFilterExpression& rhs() const; private: QOrmFilterExpression m_lhs; QOrm::BinaryLogicalOperator m_logicalOperator; QOrmFilterExpression m_rhs; }; class Q_ORM_EXPORT QOrmFilterUnaryPredicate { public: QOrmFilterUnaryPredicate(QOrm::UnaryLogicalOperator logicalOperator, QOrmFilterExpression rhs); Q_REQUIRED_RESULT QOrm::UnaryLogicalOperator logicalOperator() const; Q_REQUIRED_RESULT const QOrmFilterExpression& rhs() const; private: QOrm::UnaryLogicalOperator m_logicalOperator; QOrmFilterExpression m_rhs; }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmFilterExpression& expression); extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmFilterTerminalPredicate& predicate); extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmFilterBinaryPredicate& predicate); extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmFilterUnaryPredicate& predicate); namespace QtOrmPrivate { template<typename T> struct IsList : std::false_type { }; template<typename T> struct IsList<QVector<T>> : std::true_type { }; template<typename T> struct IsList<QList<T>> : std::true_type { }; template<typename T> struct IsList<QSet<T>> : std::true_type { }; template<> struct IsList<QStringList> : std::true_type { }; template<typename T, bool Convertible = std::is_convertible_v<std::decay_t<T>, QVariant>> struct ValueConverter; template<typename T> struct ValueConverter<T, false> { static QVariant convert(T&& value) { return QVariant::fromValue(std::forward<T>(value)); } }; template<typename T> struct ValueConverter<T, true> { static QVariant convert(const T& value) { return QVariant{value}; } }; template<typename T, bool ConvertToQVariantList = IsList<std::decay_t<T>>::value> struct FilterTerminalPredicateFactory; template<typename T> struct FilterTerminalPredicateFactory<T, false> { [[nodiscard]] static QOrmFilterTerminalPredicate create( const QOrmFilterTerminalPredicate::FilterProperty& property, QOrm::Comparison comparison, T&& value) { return {property, comparison, ValueConverter<T>::convert(std::forward<T>(value))}; } }; template<typename T> struct FilterTerminalPredicateFactory<T, true> { [[nodiscard]] static QOrmFilterTerminalPredicate create( const QOrmFilterTerminalPredicate::FilterProperty& property, QOrm::Comparison comparison, T&& value) { QVariantList list; using ValueType = typename std::decay_t<T>::value_type; std::transform(std::cbegin(std::forward<T>(value)), std::cend(std::forward<T>(value)), std::back_inserter(list), [](const ValueType& value) { return ValueConverter<ValueType>::convert(value); }); return {property, comparison, list}; } }; template<typename T, bool IsList = IsList<std::decay_t<T>>::value> struct EqualsComparator; template<typename T> struct EqualsComparator<T, false> { [[nodiscard]] static QOrm::Comparison comparator() { return QOrm::Comparison::Equal; } }; template<typename T> struct EqualsComparator<T, true> { [[nodiscard]] static QOrm::Comparison comparator() { return QOrm::Comparison::InList; } }; template<typename T, bool IsList = IsList<std::decay_t<T>>::value> struct NotEqualsComparator; template<typename T> struct NotEqualsComparator<T, false> { [[nodiscard]] static QOrm::Comparison comparator() { return QOrm::Comparison::NotEqual; } }; template<typename T> struct NotEqualsComparator<T, true> { [[nodiscard]] static QOrm::Comparison comparator() { return QOrm::Comparison::NotInList; } }; } // namespace QtOrmPrivate template<typename T> [[nodiscard]] inline QOrmFilterTerminalPredicate operator==(const QOrmFilterTerminalPredicate::FilterProperty& property, T&& value) { return QtOrmPrivate::FilterTerminalPredicateFactory<T>::create( property, QtOrmPrivate::EqualsComparator<T>::comparator(), std::forward<T>(value)); } template<typename T> [[nodiscard]] inline QOrmFilterTerminalPredicate operator!=(const QOrmFilterTerminalPredicate::FilterProperty& property, T&& value) { return QtOrmPrivate::FilterTerminalPredicateFactory<T>::create( property, QtOrmPrivate::NotEqualsComparator<T>::comparator(), std::forward<T>(value)); } template<typename T> [[nodiscard]] inline QOrmFilterTerminalPredicate operator<(const QOrmFilterTerminalPredicate::FilterProperty& property, T&& value) { return QtOrmPrivate::FilterTerminalPredicateFactory<T>::create(property, QOrm::Comparison::Less, std::forward<T>(value)); } template<typename T> [[nodiscard]] inline QOrmFilterTerminalPredicate operator<=(const QOrmFilterTerminalPredicate::FilterProperty& property, T&& value) { return QtOrmPrivate::FilterTerminalPredicateFactory<T>::create(property, QOrm::Comparison::LessOrEqual, std::forward<T>(value)); } template<typename T> [[nodiscard]] inline QOrmFilterTerminalPredicate operator>(const QOrmFilterTerminalPredicate::FilterProperty& property, T&& value) { return QtOrmPrivate::FilterTerminalPredicateFactory<T>::create(property, QOrm::Comparison::Greater, std::forward<T>(value)); } template<typename T> [[nodiscard]] inline QOrmFilterTerminalPredicate operator>=(const QOrmFilterTerminalPredicate::FilterProperty& property, T&& value) { return QtOrmPrivate::FilterTerminalPredicateFactory<T>::create(property, QOrm::Comparison::GreaterOrEqual, std::forward<T>(value)); } Q_REQUIRED_RESULT Q_ORM_EXPORT QOrmFilterUnaryPredicate operator!(const QOrmFilterExpression& operand); Q_REQUIRED_RESULT Q_ORM_EXPORT QOrmFilterBinaryPredicate operator||(const QOrmFilterExpression& lhs, const QOrmFilterExpression& rhs); Q_REQUIRED_RESULT Q_ORM_EXPORT QOrmFilterBinaryPredicate operator&&(const QOrmFilterExpression& lhs, const QOrmFilterExpression& rhs); QT_END_NAMESPACE #endif // QORMFILTERBUILDER_H
10,278
C++
.h
246
34.288618
100
0.697674
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,877
qormmetadata.h
dpurgin_qtorm/src/orm/qormmetadata.h
/* * Copyright (C) 2019-2021 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2021 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMMETADATA_H #define QORMMETADATA_H #include <QtOrm/qormglobal.h> #include <QtOrm/qormpropertymapping.h> #include <QtCore/qstring.h> #include <memory> #include <vector> QT_BEGIN_NAMESPACE class QDebug; class QOrmMetadataPrivate; class Q_ORM_EXPORT QOrmMetadata { public: explicit QOrmMetadata(const QOrmMetadataPrivate* data); QOrmMetadata(const QOrmMetadata&); QOrmMetadata(QOrmMetadata&&); ~QOrmMetadata(); QOrmMetadata& operator=(const QOrmMetadata&); QOrmMetadata& operator=(QOrmMetadata&&); [[nodiscard]] const QMetaObject& qMetaObject() const; [[nodiscard]] QString className() const; [[nodiscard]] QString tableName() const; [[nodiscard]] const std::vector<QOrmPropertyMapping>& propertyMappings() const; [[nodiscard]] const QOrmPropertyMapping* tableFieldMapping(const QString& fieldName) const; [[nodiscard]] const QOrmPropertyMapping* classPropertyMapping( const QString& classProperty) const; [[nodiscard]] const QOrmPropertyMapping* objectIdMapping() const; [[nodiscard]] const QOrmUserMetadata& userMetadata() const; private: QSharedDataPointer<const QOrmMetadataPrivate> d; }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmMetadata& metadata); QT_END_NAMESPACE #endif // QORMMETADATA_H
2,164
C++
.h
53
37.90566
95
0.768496
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,878
qormsqlitestatementgenerator_p.h
dpurgin_qtorm/src/orm/qormsqlitestatementgenerator_p.h
/* * Copyright (C) 2021 Dmitriy Purgin <dpurgin@gmail.com> * Copyright (C) 2019-2021 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2021 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMSQLITESTATEMENTGENERATOR_H #define QORMSQLITESTATEMENTGENERATOR_H #include <QtOrm/qormglobal.h> #include <QtCore/qshareddata.h> #include <QtCore/qstring.h> #include <QtCore/qvariant.h> #include <optional> #include <utility> #include <vector> QT_BEGIN_NAMESPACE class QOrmFilter; class QOrmFilterBinaryPredicate; class QOrmFilterExpression; class QOrmFilterTerminalPredicate; class QOrmFilterUnaryPredicate; class QOrmMetadata; class QOrmOrder; class QOrmPropertyMapping; class QOrmQuery; class QOrmRelation; class Q_ORM_EXPORT QOrmSqliteStatementGenerator { public: enum Option { NoOptions = 0x00, WithReturningClause = 0x01 }; Q_DECLARE_FLAGS(Options, Option); explicit QOrmSqliteStatementGenerator(); explicit QOrmSqliteStatementGenerator(Options options); [[nodiscard]] std::pair<QString, QVariantMap> generate(const QOrmQuery& query); [[nodiscard]] QString generate(const QOrmQuery& query, QVariantMap& boundParameters); [[nodiscard]] QString generateInsertStatement(const QOrmMetadata& relation, const QObject* instance, QVariantMap& boundParameters); [[nodiscard]] QString generateInsertIntoStatement(const QString& destinationTableName, const QStringList& destionationColumns, const QString& sourceTableName, const QStringList& sourceColumns); [[nodiscard]] QString generateUpdateStatement(const QOrmMetadata& relation, const QObject* instance, QVariantMap& boundParameters); [[nodiscard]] QString generateSelectStatement(const QOrmQuery& query, QVariantMap& boundParameters); [[nodiscard]] QString generateDeleteStatement(const QOrmMetadata& relation, const QOrmFilter& filter, QVariantMap& boundParameters); [[nodiscard]] QString generateDeleteStatement(const QOrmMetadata& relation, const QObject* instance, QVariantMap& boundParameters); [[nodiscard]] QString generateFromClause(const QOrmRelation& relation, QVariantMap& boundParameters); [[nodiscard]] QString generateWhereClause(const QOrmFilter& filter, QVariantMap& boundParameters); [[nodiscard]] QString generateOrderClause(const std::vector<QOrmOrder>& order); [[nodiscard]] QString generateReturningIdClause(const QOrmMetadata& relation); [[nodiscard]] QString generateCondition(const QOrmFilterExpression& expression, QVariantMap& boundParameters); [[nodiscard]] QString generateCondition(const QOrmFilterTerminalPredicate& predicate, QVariantMap& boundParameters); [[nodiscard]] QString generateCondition(const QOrmFilterBinaryPredicate& predicate, QVariantMap& boundParameters); [[nodiscard]] QString generateCondition(const QOrmFilterUnaryPredicate& predicate, QVariantMap& boundParameters); [[nodiscard]] QString generateCreateTableStatement( const QOrmMetadata& entity, std::optional<QString> overrideTableName = std::nullopt); [[nodiscard]] QString generateAlterTableAddColumnStatement( const QOrmMetadata& relation, const QOrmPropertyMapping& propertyMapping); [[nodiscard]] QString generateDropTableStatement(const QOrmMetadata& entity); [[nodiscard]] QString generateRenameTableStatement(const QString& oldName, const QString& newName); [[nodiscard]] QString generateLimitOffsetClause(std::optional<int> limit, std::optional<int> offset, QVariantMap& boundParameters); [[nodiscard]] QString toSqliteType(QVariant::Type type); [[nodiscard]] QString escapeIdentifier(const QString& identifier); void setOptions(Options options) { m_options = options; } [[nodiscard]] Options options() const { return m_options; } private: Options m_options{NoOptions}; }; QT_END_NAMESPACE #endif
5,628
C++
.h
106
40.160377
93
0.644809
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,879
qormmetadatacache.h
dpurgin_qtorm/src/orm/qormmetadatacache.h
/* * Copyright (C) 2019 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMMETADATACACHE_H #define QORMMETADATACACHE_H #include <QtOrm/qormglobal.h> #include <QtOrm/qormmetadata.h> #include <memory> QT_BEGIN_NAMESPACE class QOrmMetadata; class QOrmMetadataCachePrivate; class QMetaObject; class Q_ORM_EXPORT QOrmMetadataCache { Q_DISABLE_COPY(QOrmMetadataCache) public: QOrmMetadataCache(); QOrmMetadataCache(QOrmMetadataCache&&); ~QOrmMetadataCache(); QOrmMetadataCache& operator=(QOrmMetadataCache&&); Q_REQUIRED_RESULT const QOrmMetadata& operator[](const QMetaObject& qMetaObject); template<typename T> Q_REQUIRED_RESULT const QOrmMetadata& get() { return operator[](T::staticMetaObject); } Q_REQUIRED_RESULT const QOrmMetadata& get(const QMetaObject& qMetaObject) { return operator[](qMetaObject); } private: std::unique_ptr<QOrmMetadataCachePrivate> d; }; QT_END_NAMESPACE #endif // QORMMETADATACACHE_H
1,778
C++
.h
51
31.823529
95
0.764156
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,880
qormerror.h
dpurgin_qtorm/src/orm/qormerror.h
/* * Copyright (C) 2019-2021 Dmitriy Purgin <dmitriy.purgin@sequality.at> * Copyright (C) 2019-2021 sequality software engineering e.U. <office@sequality.at> * * This file is part of QtOrm library. * * QtOrm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QtOrm is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with QtOrm. If not, see <https://www.gnu.org/licenses/>. */ #ifndef QORMERROR_H #define QORMERROR_H #include <QtOrm/qormglobal.h> #include <QtCore/qstring.h> QT_BEGIN_NAMESPACE class QDebug; class Q_ORM_EXPORT QOrmError { public: QOrmError(); QOrmError(QOrm::ErrorType type, const QString& text); [[nodiscard]] QOrm::ErrorType type() const; [[nodiscard]] QString text() const; [[nodiscard]] bool operator==(QOrm::ErrorType errorType) const { return m_type == errorType; } [[nodiscard]] bool operator!=(QOrm::ErrorType errorType) const { return !operator==(errorType); } private: QOrm::ErrorType m_type{QOrm::ErrorType::None}; QString m_text; }; extern Q_ORM_EXPORT QDebug operator<<(QDebug dbg, const QOrmError& error); QT_END_NAMESPACE #endif // QORMERROR_H
1,616
C++
.h
44
33.931818
98
0.74086
dpurgin/qtorm
35
11
2
LGPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,881
fluidsynthvst.cpp
AZSlow3_FluidSynthVST/source/fluidsynthvst.cpp
/* * FluidSynth VST * * Wrapper part (this file): Copyright (C) 2019 AZ (www.azslow.com) * * FluidSynth: Copyright (C) 2003-2019 Peter Hanappe and others. * VST API: (c) 2019, Steinberg Media Technologies GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include "public.sdk/source/main/pluginfactory.h" #include "base/source/fstreamer.h" #include "base/source/fbuffer.h" #include "pluginterfaces/base/ibstream.h" #include "pluginterfaces/base/ustring.h" #include "../include/fluidsynthvst.h" #include "pluginterfaces/vst/ivstevents.h" #include "pluginterfaces/vst/ivstmidicontrollers.h" #include "pluginterfaces/vst/ivstparameterchanges.h" #include "pluginterfaces/vst/vsttypes.h" #include "pluginterfaces/vst/ivstattributes.h" namespace FluidSynthVST { using namespace Steinberg; #ifdef WIN32 #else /* Linux */ #include <time.h> class PerfMeter { private: struct timespec start_ts; struct timespec end_ts; unsigned long long md; char *pfx; public: PerfMeter(const char *prefix = "Perf", unsigned long long min_diff = 1) : md(min_diff){ clock_gettime(CLOCK_REALTIME, &start_ts); pfx = strdup(prefix); } ~PerfMeter(){ clock_gettime(CLOCK_REALTIME, &end_ts); unsigned long long td = (end_ts.tv_sec - start_ts.tv_sec)*1000000 + (end_ts.tv_nsec - start_ts.tv_nsec)/1000; if(td >= md) printf("%s: %llu uSec\n", pfx, td); } }; #endif /* platform */ // CC Names static const char *szCCName[Vst::kCountCtrlNumber] = { // MSB "Bank (MSB)", //= 0x00 "Modulation (MSB)", //= 0x01, "Breath (MSB)", //= 0x02, "", "Foot (MSB)", //= 0x04 "Portamento time (MSB)", //= 0x05, "Data entry (MSB)", //= 0x06, "Volume (MSB)", //= 0x07, "Balance (MSB)", //= 0x08, "", "Pan (MSB)", //= 0x0A, "Expression (MSB)", //= 0x0B, "Effect Control 1 (MSB)", //= 0x0C, "Effect Control 2 (MSM)", //= 0x0D, "", "", "General 1 (MSB)", //= 0x10, "General 2 (MSB)", //= 0x11, "General 3 (MSB)", //= 0x12, "General 4 (MSB)", //= 0x13, "", "", "", "", "", "", "", "", "", "", "", "", // 12x // LSB "Bank (LSB)", //= 0x20 "Modulation (LSB)", //= 0x21, "Breath (LSB)", //= 0x22, "", "Foot (LSB)", //= 0x24 "Portamento time (LSB)", //= 0x25, "Data entry (LSB)", //= 0x26, "Volume (LSB)", //= 0x27, "Balance (LSB)", //= 0x28, "", "Pan (LSB)", //= 0x2A, "Expression (LSB)", //= 0x2B, "Effect Control 1 (LSB)", //= 0x2C, "Effect Control 2 (LSm)", //= 0x2D, "", "", "General 1 (LSB)", //= 0x30, "General 2 (LSB)", //= 0x31, "General 3 (LSB)", //= 0x32, "General 4 (LSB)", //= 0x33, "", "", "", "", "", "", "", "", "", "", "", "", // 12x // Switches "Sustain", //= 0x40 "Portamento", //= 0x41 "Sostenuto", //= 0x42 "Soft pedal", //= 0x43 "Legato", //= 0x44 "Hold 2 ", //= 0x45 // 7bit controllers "Sound controller 1", //=0x46 "Sound controller 2", //=0x47 "Sound controller 3", //=0x48 "Sound controller 4", //=0x49 "Sound controller 5", //=0x4a "Sound controller 6", //=0x4b "Sound controller 7", //=0x4c "Sound controller 8", //=0x4d "Sound controller 9", //=0x4e "Sound controller 10", //=0x4f "General 5", //= 0x50 "General 6", //= 0x51 "General 7", //= 0x52 "General 8", //= 0x53 "Portamento control", //= 0x54 "", "", "", "", "", "", // 6x "Effects depth 1 (Reverb)", //= 0x5B "Effects depth 2", //= 0x5C "Effects depth 3 (Chorus)", //= 0x5D "Effects depth 4", //= 0x5E "Effects depth 5", //= 0x5F // System "Increment", //=0x60 "Decrement", //=0x61 "NRPN (LSB)", //=0x62 "NRPN (MSB)", //= 0x63 "RPN (LSB)", //=0x64 "RPN (MSB)", //= 0x65 "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // 18x "All sound off", //= 0x78 "Reset controllers", //= 0x79 "Local control", //= 0x7A "All notes off", //= 0x7B "Omni off", //= 0x7C "Onmi on", //= 0x7D "Mono mode on", //= 0x7E "Poly mode on", //= 0x7F // VST extra "AT", //= 0x80 "PB", //= 0x81 }; // Processor Processor::Processor() : mSynth(NULL), mChangeSoundFont(false), mLoadingThread(0) /*, mAudioBufsSize(0) */ { setControllerClass(ControllerUID); mSynthSettings = new_fluid_settings(); mSynth = new_fluid_synth(mSynthSettings); scanSoundFonts(); /* mAudioBufs[0] = NULL; mAudioBufs[1] = NULL; */ } void Processor::syncedLoadSoundFont() { char fileName[FILENAME_MAX]; GetPath(fileName, FILENAME_MAX); PathAppend(fileName, FILENAME_MAX, mLoadedFile.text8()); fluid_synth_all_notes_off(mSynth, -1); fluid_synth_all_sounds_off(mSynth, -1); if(fluid_synth_sfcount(mSynth) > 0){ // unload old one int id = fluid_sfont_get_id(fluid_synth_get_sfont(mSynth, 0)); fluid_synth_sfunload(mSynth, id, 1); } if((mSoundFontID = fluid_synth_sfload(mSynth, fileName, 1)) == FLUID_FAILED){ printf("Failed '%s'...\n", fileName); } mLoadingComplete = true; } Processor::~Processor() { checkSoundFont(true); // to stop the thread, if any if(mSynth){ delete_fluid_synth(mSynth); mSynth = NULL; } if(mSynthSettings){ delete_fluid_settings(mSynthSettings); mSynthSettings = NULL; } /* if(mAudioBufs[0]) delete [] mAudioBufs[0]; if(mAudioBufs[1]) delete [] mAudioBufs[1]; */ } tresult PLUGIN_API Processor::initialize(FUnknown* context){ tresult result = AudioEffect::initialize(context); if(result == kResultTrue){ addAudioInput(STR16("AudioInput"), Vst::SpeakerArr::kStereo); addAudioOutput(STR16("AudioOutput"), Vst::SpeakerArr::kStereo); addEventInput(STR16("MIDIInput"), 16); } return result; } tresult PLUGIN_API Processor::setBusArrangements(Vst::SpeakerArrangement* inputs, int32 numIns, Vst::SpeakerArrangement* outputs, int32 numOuts){ if((numIns == 1) && (numOuts == 1) && (inputs[0] == outputs[0])){ return AudioEffect::setBusArrangements(inputs, numIns, outputs, numOuts); } return kResultFalse; } tresult PLUGIN_API Processor::canProcessSampleSize(int32 symbolicSampleSize){ if(symbolicSampleSize == Vst::kSample32) return kResultTrue; // printf("64bit (%d) audio is not supported by now\n", symbolicSampleSize); // Well, FluidSynth has compile time fixed precision. And it is default to 64bit... But // fluid_synth_write_float unconditionally writes "float", so 32bit... return kResultFalse; } tresult PLUGIN_API Processor::setupProcessing(Vst::ProcessSetup& setup){ tresult result = AudioEffect::setupProcessing(setup); if(result == kResultTrue){ //printf("Processor: SetupProcessing\n"); // TODO: set block size, etc. if(fluid_settings_setnum(mSynthSettings, "synth.sample-rate", setup.sampleRate) == FLUID_FAILED){ printf("Could not set sample rate to %f\n", setup.sampleRate); } // BAD SDK: // from common sense, we should not load any sound font till we know which one should be loaded // but reality is different. REAPER calls setupProcessing before setState, even in case it is // called later (the plug-in is instantiated from a project, from saved state). // In case last getState returns the same as default getState, setState is not called at all. // Finally, if plug-in is just instantiated, setState should not be called. And so, // we have no way to check the user wants not default font in this instance, we are forced // to always load default first. if(!mSoundFontFile.text8()[0]){ mSoundFontFile = mSoundFontFiles.at(getCurrentSoundFontIdx()); // we know the list is not emply mChangeSoundFont = true; } checkSoundFont(true); /* if((setup.sampleRate == Vst::kSample64) && (mAudioBufsSize < setup.maxSamplesPerBlock)){ // we should be called with real time stopped if(mAudioBufs[0]) delete [] mAudioBufs[0]; if(mAudioBufs[1]) delete [] mAudioBufs[1]; mAudioBufs[0] = new float[setup.maxSamplesPerBlock + 1]; mAudioBufs[1] = new float[setup.maxSamplesPerBlock + 1]; if(mAudioBufs[0] && mAudioBufs[1]) mAudioBufsSize = setup.maxSamplesPerBlock; else mAudioBufsSize = 0; } */ } return result; } tresult PLUGIN_API Processor::setActive(TBool state){ tresult result = AudioEffect::setActive(state); if(result == kResultTrue){ if(state){ //printf("Processor: activated\n"); } else { //printf("Processor: deactivated\n"); } } return result; } void Processor::writeAudio(Vst::ProcessData& data, int32 start_sample, int32 end_sample){ // end_sample is exclusive if((data.numSamples < end_sample) || (start_sample >= end_sample) || (data.numOutputs < 1) || (data.outputs[0].numChannels < 2)) return; if(data.symbolicSampleSize == Vst::kSample32){ if(!checkSoundFont(false)){ // the synth is not ready memset(data.outputs[0].channelBuffers32[0] + start_sample, 0, sizeof(float) * (end_sample - start_sample)); memset(data.outputs[0].channelBuffers32[1] + start_sample, 0, sizeof(float) * (end_sample - start_sample)); } else { if(fluid_synth_write_float(mSynth, end_sample - start_sample, data.outputs[0].channelBuffers32[0] + start_sample, 0, 1, data.outputs[0].channelBuffers32[1] + start_sample, 0, 1) == FLUID_FAILED){ //printf("Generation failed\n"); } } } else { // MAYBE TODO: handle 64bit audio case // fluid_synth_write_double does not exist (yet) // I have started to add tmp buffer, but I think hosts can handle that limitation automatically } } // A bit not optimal... // return earliest change/event sample offset after (strict) curSample (which can be -1) // return -1 in case there is no changes/event after curSample // Can it return offset greater or equal data.numSamples? I try to process that correctly, just in case... int32 Processor::nextOffset(Vst::ProcessData& data, int32 curSample){ int32 minSampleOffset = -1; if(data.inputParameterChanges){ int32 numParamsChanged = data.inputParameterChanges->getParameterCount(); for(int32 index = 0; index < numParamsChanged; index++){ Vst::IParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(index); if(paramQueue){ Vst::ParamValue value; int32 sampleOffset; int32 numPoints = paramQueue->getPointCount(); for(int32 point = 0; point < numPoints; ++point){ if(paramQueue->getPoint(point, sampleOffset, value) == kResultTrue){ if((minSampleOffset >= 0) && (sampleOffset > minSampleOffset)) break; // assume they are time ordered if(sampleOffset > curSample) minSampleOffset = sampleOffset; } } } } } Vst::Event e; int32 evcount = data.inputEvents ? data.inputEvents->getEventCount() : 0; for(int32 index = 0; index < evcount; ++index){ if(data.inputEvents->getEvent(index, e) == kResultTrue){ if((minSampleOffset >= 0) && (e.sampleOffset > minSampleOffset)) break; // assume they are time ordered if(e.sampleOffset > curSample) minSampleOffset = e.sampleOffset; } } return minSampleOffset; } void Processor::playParChanges(Vst::ProcessData& data, int32 curSample, int32 endSample){ // endSample inclusive if(!data.inputParameterChanges) return; int32 numParamsChanged = data.inputParameterChanges->getParameterCount(); for(int32 index = 0; index < numParamsChanged; index++){ Vst::IParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(index); if(paramQueue){ Vst::ParamValue value; int32 sampleOffset; Vst::ParamID id = paramQueue->getParameterId(); int32 numPoints = paramQueue->getPointCount(); for(int32 point = 0; point < numPoints; ++point){ if(paramQueue->getPoint(point, sampleOffset, value) == kResultTrue){ if(sampleOffset < curSample) continue; // already played if(sampleOffset > endSample) break; // assume they are time ordered switch(id){ case FluidSynthVSTParams::kBypassId: mBypass = (value > 0.5f); break; case FluidSynthVSTParams::kRootPrgId: // we can not change here, but we schedule the change on restart if(mSoundFontFiles.size()){ int32 soundFontIdx = (value*(mSoundFontFiles.size()-1) + 0.5); //printf("Processor: font change request\n"); if(mSoundFontFile != mSoundFontFiles.at(soundFontIdx)){ mSoundFontFile = mSoundFontFiles.at(soundFontIdx); mChangeSoundFont = true; //printf("Processor: will change font to %s\n", mSoundFontFile.text8()); checkSoundFont(false); } } break; default: if(!checkSoundFont(false)){ // the synth is not ready break; } if(id >= 1024){ int32 ch = id / 1024 - 1; int32 ctrlNumber = id%1024; if(ctrlNumber < Vst::kAfterTouch){ // CC fluid_synth_cc(mSynth, ch, ctrlNumber, value*127.+0.5); //printf("Ch:%d CC%d = %d\n", ch, ctrlNumber, (int)(value*127. + 0.5)); } else if(ctrlNumber == Vst::kAfterTouch){ fluid_synth_channel_pressure(mSynth, ch, value*127.+0.5); //printf("Ch:%d AT = %d\n", ch, (int)(value*127. + 0.5)); } else if(ctrlNumber == Vst::kPitchBend){ fluid_synth_pitch_bend(mSynth, ch, value*16383.+0.5); //printf("Ch:%d PB = %d\n", ch, ((int)(value*16383. + 0.5)) - 8192); } else { printf("Hmm... unknown control %d\n", ctrlNumber); } } else if((id >= kChPrgId) && (id <= kLastChPrgId)){ // PC fluid_synth_program_change(mSynth, id - kChPrgId, value*127.+0.5); } else { printf("Unknown param change ID: %d\n", id); } // TODO: also send as "legacy MIDI events" } } } } } } void Processor::playEvents(Vst::ProcessData& data, int32 curSample, int32 endSample){ // endSample inclusive Vst::Event e; int32 evcount = data.inputEvents ? data.inputEvents->getEventCount() : 0; for(int32 index = 0; index < evcount; ++index){ if(data.inputEvents->getEvent(index, e) == kResultTrue){ if(e.sampleOffset < curSample) continue; // already played if(e.sampleOffset > endSample) break; // assume they are time ordered switch(e.type){ case Vst::Event::kNoteOnEvent: if(fluid_synth_noteon(mSynth, e.noteOn.channel, e.noteOn.pitch, e.noteOn.velocity*127. + 0.5) == FLUID_FAILED){ //printf("NoteOn failed\n"); } break; case Vst::Event::kNoteOffEvent: fluid_synth_noteoff(mSynth, e.noteOff.channel, e.noteOff.pitch); break; default: // TODO: at least SysEx printf("Unprocessed Event type: %d\n", e.type); } if(data.outputEvents) data.outputEvents->addEvent(e); } } } tresult PLUGIN_API Processor::process(Vst::ProcessData& data){ //PerfMeter pm("Process", 8000); //printf("*\n"); if((data.numOutputs <= 0) || (data.numSamples <= 0)) return kResultOk; int32 curSample = -1; while(true){ int32 offset = nextOffset(data, curSample); int32 sample = (curSample < 0 ? 0 : curSample); int32 endSample = data.numSamples; if((offset >= 0) && (offset < endSample)){ // write before offset, which is withing the block endSample = offset; } if(endSample > sample) writeAudio(data, sample, endSample); if(offset >= 0){ playParChanges(data, curSample, endSample); playEvents(data, curSample, endSample); } curSample = endSample; if((curSample >= data.numSamples) && (offset < 0)) break; } return kResultOk; } tresult PLUGIN_API Processor::setProcessing (TBool state){ if(state){ //printf("Processor: started\n"); } else { //printf("Processor: ended\n"); } return kResultTrue; } int Processor::getCurrentSoundFontIdx(){ if(mSoundFontFiles.size() < 2) return 0; auto it = std::find(mSoundFontFiles.begin(), mSoundFontFiles.end(), mSoundFontFile); if(it == mSoundFontFiles.end()){ // can be if not set or not exist, return default auto dit = std::find(mSoundFontFiles.begin(), mSoundFontFiles.end(), "default.sf2"); if(dit == mSoundFontFiles.end()) return 0.; // the first return dit - mSoundFontFiles.begin(); } return it - mSoundFontFiles.begin(); } float Processor::getCurrentSoundFontNormalized(){ return (float)(getCurrentSoundFontIdx()) / (mSoundFontFiles.size() - 1); } tresult PLUGIN_API Processor::setState(IBStream* state){ if(!state) return kResultFalse; //printf("Processor: setState\n"); IBStreamer streamer(state, kLittleEndian); int32 savedBypass = 0; if(streamer.readInt32(savedBypass) == false) return kResultFalse; mBypass = savedBypass > 0; String newSoundFontFile; char *soundFontFileCStr; if(!(soundFontFileCStr = streamer.readStr8())){ // can be, the first version was not saving it newSoundFontFile = ""; //printf("Processor: using default font\n"); } else { newSoundFontFile = soundFontFileCStr; delete soundFontFileCStr; //printf("Processor: State font: %s\n", mSoundFontFile.text8()); } if(!newSoundFontFile.text8()[0]) newSoundFontFile = mSoundFontFiles.at(getCurrentSoundFontIdx()); // the list is not empty after scanning if(newSoundFontFile != mSoundFontFile){ mSoundFontFile = newSoundFontFile; auto it = std::find(mSoundFontFiles.begin(), mSoundFontFiles.end(), mSoundFontFile); if(it == mSoundFontFiles.end()){ mSoundFontFiles.push_back( mSoundFontFile ); // some not existing sound font, add it std::sort(mSoundFontFiles.begin(), mSoundFontFiles.end()); sendProgramList(); } mChangeSoundFont = true; sendCurrentProgram(); } return kResultOk; } tresult PLUGIN_API Processor::getState(IBStream* state){ int32 toSaveBypass = mBypass ? 1 : 0; //printf("Processor: getState\n"); IBStreamer streamer(state, kLittleEndian); streamer.writeInt32(toSaveBypass); streamer.writeStr8(mSoundFontFile.text8()); // can be empty //printf(" Current sound font: %s\n", mSoundFontFile.text8()); // in case there will be no future setState, controller will be called with this state // but "empty" font effectively means "default.sf2", in case it exist. And it can be not the first one. sendCurrentProgram(); return kResultOk; } void Processor::sendProgramList(){ Steinberg::Buffer buf; for(auto const& fileName : mSoundFontFiles){ String name; fileName.extract(name, 0, fileName.length() - 4); // remove ".sfX" buf.appendString8(name); // UTF-8 buf.endString8(); } Vst::IMessage* message = allocateMessage(); FReleaser msgReleaser(message); if(message){ message->setMessageID("SoundFontFiles"); message->getAttributes()->setBinary("List", buf, buf.getFillSize()); //printf(" sending %d, first: %s\n", buf.getFillSize(), buf.str8()); sendMessage(message); } } tresult PLUGIN_API Processor::connect (IConnectionPoint* other){ if(Vst::AudioEffect::connect(other) == kResultOk){ //printf("Processor: connected\n"); sendProgramList(); } return kResultFalse; } void Processor::sendCurrentProgram(){ float cSoundFontNorm = getCurrentSoundFontNormalized(); Vst::IMessage* message = allocateMessage(); FReleaser msgReleaser(message); if(message){ message->setMessageID("CurrentSoundFont"); message->getAttributes()->setBinary("Value", &cSoundFontNorm, sizeof(float)); sendMessage(message); } } // Controller tresult PLUGIN_API Controller::initialize(FUnknown* context){ tresult result = EditController::initialize(context); if(result != kResultOk){ return result; } parameters.addParameter(STR16("Bypass"), nullptr, 1, 0, Vst::ParameterInfo::kCanAutomate | Vst::ParameterInfo::kIsBypass, FluidSynthVSTParams::kBypassId); addUnit(new Vst::Unit(String("Root"), Vst::kRootUnitId, Vst::kNoParentUnitId, kRootPrgId /* Vst::kNoProgramListId */)); // register so far empty Sound Font list and its parameter Vst::ProgramList* prgList = new Vst::ProgramList(String("Sound Font"), kRootPrgId, Vst::kRootUnitId); addProgramList(prgList); prgList->addProgram(String("default")); // something crash otherwise... mCurrentProgram = 0.; // we will be informed about real one Vst::Parameter* prgParam = prgList->getParameter(); prgParam->getInfo().flags &= ~Vst::ParameterInfo::kCanAutomate; parameters.addParameter(prgParam); for(int32 ch = 0; ch < 16; ++ch){ Vst::UnitID unitId = ch + 1; Vst::ProgramListID prgListId = kChPrgId + ch; String unitName; // Unit unitName.printf("Ch%d", ch + 1); addUnit(new Vst::Unit(unitName, unitId, Vst::kRootUnitId, prgListId /* Vst::kNoProgramListId */)); // ProgramList String listName; listName.printf("Ch%d", ch + 1); Vst::ProgramList* prgList = new Vst::ProgramList(listName, prgListId, unitId); addProgramList(prgList); for(int32 i = 0; i < 128; i++){ String title; title.printf("Prog %d", i); prgList->addProgram(title); } // ProgramList parameter Vst::Parameter* prgParam = prgList->getParameter(); prgParam->getInfo().flags &= ~Vst::ParameterInfo::kCanAutomate; parameters.addParameter(prgParam); /* unitName.printf("Prg Ch%d", ch + 1); parameters.addParameter(unitName, nullptr, 127, 0, Vst::ParameterInfo::kIsProgramChange | Vst::ParameterInfo::kIsList, prgListId, unitId); */ // CC, (Channel) AfterTouch, PitchBend for(int midiCtrlNumber = 0; midiCtrlNumber < Vst::kCountCtrlNumber; ++midiCtrlNumber){ String parName; int nSteps; if(!szCCName[midiCtrlNumber][0]) continue; parName.printf("Ch:%d %s", ch + 1, szCCName[midiCtrlNumber]); if(midiCtrlNumber ==Vst::kPitchBend){ nSteps = 128*128 - 1; // 16383 } else { nSteps = 127; } parameters.addParameter(parName, nullptr, nSteps, 0, Vst::ParameterInfo::kNoFlags, 1024 + 1024*ch + midiCtrlNumber); } } return kResultOk; } tresult PLUGIN_API Controller::notify (Vst::IMessage* message){ if(!message) return kInvalidArgument; //printf("Controller: Notify\n"); FIDString messageID = message->getMessageID(); uint32 messageSize = 0; const char *messageData = NULL; if(!strcmp(messageID, "SoundFontFiles")){ //printf(" SoundFontFiles\n"); if(message->getAttributes()->getBinary("List", (const void *&)messageData, messageSize) == kResultOk){ // that should be an array of UTF8 strings if(messageData && messageSize && !messageData[messageSize - 1]){ auto prgList = getProgramList(kRootPrgId); auto prgPar = dynamic_cast<Vst::StringListParameter *>(prgList->getParameter()); if(prgList && prgPar){ const char *messageEnd = messageData + messageSize; // BAD SDK: there is no call to clear the list, so we can only replace... int32 currentProgramCount = prgList->getCount(); int idx = 0; // printf(" Controller: font list\n"); while(messageData < messageEnd){ String soundFont; soundFont.fromUTF8(messageData); // printf(" %s\n", soundFont.text8()); if(idx >= currentProgramCount){ prgList->addProgram(soundFont); prgPar->appendString(soundFont); } else { prgList->setProgramName(idx, soundFont); prgPar->replaceString(idx, soundFont); } messageData += strlen(messageData) + 1; ++idx; } // TODO: set current value for parameter if(componentHandler) componentHandler->restartComponent(Vst::kParamValuesChanged); notifyProgramListChange(kRootPrgId); // Ask host to redraw possible "build-in presets" return kResultTrue; } } } } else if(!strcmp(messageID, "CurrentSoundFont")){ //printf(" CurrentSoundFont\n"); if(message->getAttributes()->getBinary("Value", (const void *&)messageData, messageSize) == kResultOk){ // that should be an array of UTF8 strings if(messageData && (messageSize == sizeof(float))){ memcpy(&mCurrentProgram, messageData, sizeof(float)); // processor has precalculate correct value for us, but we do not setNormalized here // it can be just initial value and there will be more return kResultTrue; } } } return kResultFalse; } tresult PLUGIN_API Controller::setComponentState(IBStream* state){ if(!state) return kResultFalse; //printf("Controller: setComponentState\n"); IBStreamer streamer(state, kLittleEndian); int32 bypassState; if(streamer.readInt32(bypassState) == false) return kResultFalse; setParamNormalized(kBypassId, bypassState ? 1 : 0); char *soundFontFileName; if(soundFontFileName = streamer.readStr8()){ delete soundFontFileName; } setParamNormalized(kRootPrgId, mCurrentProgram); // BAD SDK: it is goot time now, we used messege to transfer it // It is unclear will host call GetState or SetState for processor in case of this one // REAPER called GetState first (so "empty"), but then it can call SetState and setComponentState // with the same (externally saved) state. So processor has no chance ot fix the state itself, effectively // we can not use saved file name for that reason. return kResultOk; } tresult PLUGIN_API Controller::getMidiControllerAssignment(int32 busIndex, int16 channel, Vst::CtrlNumber midiControllerNumber, Vst::ParamID& id/*out*/){ if((midiControllerNumber >= Vst::kCountCtrlNumber) || !szCCName[midiControllerNumber][0]) return kResultFalse; if(busIndex == 0){ id = 1024 + channel*1024 + midiControllerNumber; // printf("ID = %d %d -> %d\n", channel, midiControllerNumber, id); return kResultOk; } // printf("Asked %d %d %d\n", busIndex, channel, midiControllerNumber); return kResultFalse; } tresult PLUGIN_API Controller::getUnitByBus(Vst::MediaType type, Vst::BusDirection dir, int32 busIndex, int32 channel, Vst::UnitID& unitId /*out*/){ if(type == Vst::kEvent && dir == Vst::kInput && busIndex == 0){ if((channel >= 0) && (channel < 16)){ unitId = channel + 1; // printf("OK: %d %d %d %d\n", type, dir, busIndex, channel); return kResultTrue; } } else { // printf("Hmm: %d %d %d %d\n", type, dir, busIndex, channel); } return kResultFalse; } tresult PLUGIN_API Controller::setParamNormalized (Vst::ParamID tag, Vst::ParamValue value){ tresult result = EditControllerEx1::setParamNormalized(tag, value); if(result == kResultOk){ if(tag == kRootPrgId){ //printf("Controller: SoundFont set to %f\n", value); } } return result; } } // FluidSynthVST // Factory BEGIN_FACTORY_DEF(stringCompanyName, stringCompanyWeb, stringCompanyEmail) DEF_CLASS2 (INLINE_UID_FROM_FUID(FluidSynthVST::ProcessorUID), PClassInfo::kManyInstances, kVstAudioEffectClass, stringPluginName, Vst::kDistributable, stringSubCategory, FULL_VERSION_STR, kVstVersionString, FluidSynthVST::Processor::createInstance) DEF_CLASS2 (INLINE_UID_FROM_FUID(FluidSynthVST::ControllerUID), PClassInfo::kManyInstances, kVstComponentControllerClass, stringPluginName "Controller", 0, "", FULL_VERSION_STR, kVstVersionString, FluidSynthVST::Controller::createInstance) END_FACTORY extern void *moduleHandle; #ifdef WIN32 #include <windows.h> #include <glib.h> extern "C" { void g_thread_win32_process_detach (void); void g_thread_win32_thread_detach (void); void g_thread_win32_init (void); void g_console_win32_init (void); void g_clock_win32_init (void); void g_crash_handler_win32_init (void); void g_crash_handler_win32_deinit (void); extern HMODULE glib_dll; void glib_init(void); }; // AZ: assume glib is build with Windows native threads #define THREADS_WIN32 1 void glib_DllMain(void *moduleHandle, DWORD fdwReason, LPVOID lpvReserved){ switch (fdwReason) { case DLL_PROCESS_ATTACH: glib_dll = (HMODULE)moduleHandle; g_crash_handler_win32_init (); g_clock_win32_init (); #ifdef THREADS_WIN32 g_thread_win32_init (); #endif glib_init (); /* must go after glib_init */ g_console_win32_init (); // from gobject DllMain // gobject_init(); break; case DLL_THREAD_DETACH: #ifdef THREADS_WIN32 g_thread_win32_thread_detach (); #endif break; case DLL_PROCESS_DETACH: #ifdef THREADS_WIN32 if (lpvReserved == NULL) g_thread_win32_process_detach (); #endif g_crash_handler_win32_deinit (); break; default: /* do nothing */ ; } } void FluidSynthVST::GetPath(char *szPath /* Out */, int32 size){ WCHAR wszPath[MAX_PATH]; if(GetModuleFileName((HMODULE)moduleHandle, wszPath, MAX_PATH) > 0){ wszPath[MAX_PATH - 1] = 0; if(WideCharToMultiByte(CP_UTF8, 0, wszPath, -1, szPath, size, NULL, NULL) > 0){ szPath[size - 1] = 0; char *slash = strrchr(szPath, '\\'); if(slash) *slash = 0; return; } } *szPath = 0; } void FluidSynthVST::PathAppend(char *szPath /* Out */, int32 size, const char *szName){ if(size <= (strlen(szPath) + strlen(szName) + 1)) return; strcat(szPath, "\\"); strcat(szPath, szName); } void FluidSynthVST::Processor::scanSoundFonts(){ WCHAR szName[MAX_PATH]; if(GetModuleFileNameW((HMODULE)moduleHandle, szName, MAX_PATH) <= 0) return; szName[MAX_PATH - 1] = 0; WCHAR *slash = wcsrchr(szName, L'\\'); if(slash) *slash = 0; wcscat(szName, L"\\*.sf?"); HANDLE hFind; WIN32_FIND_DATA FindData; if((hFind = FindFirstFileW(szName, &FindData)) != INVALID_HANDLE_VALUE){ do { slash = wcsrchr(FindData.cFileName, L'\\'); if(slash) ++slash; else slash = FindData.cFileName; String s(slash); s.toMultiByte(kCP_Utf8); const char *cstr = s.text8(); // used pattern is translated using DOS wildcards, f.e. it will match name.sfpack if((strlen(cstr) > 3) && !memcmp(cstr + strlen(cstr) - 4, ".sf", 3)) mSoundFontFiles.push_back( s ); } while(FindNextFileW(hFind, &FindData)); FindClose(hFind); std::sort(mSoundFontFiles.begin(), mSoundFontFiles.end()); } if(mSoundFontFiles.size() == 0) mSoundFontFiles.push_back( "default.sf2" ); } static DWORD WINAPI Processor_LoadingThread(void *par){ auto processor = static_cast<FluidSynthVST::Processor *>(par); processor->syncedLoadSoundFont(); return NULL; } /* * Returns true in case the synth can be used. * Initiate font loading, synced or asynced as specified in case that was requested. * Also finish loading in specified mode * * It is not thread safe, but it can be called from * destructor, setProcessing or process only. Host should never * parallelize any of them. */ bool FluidSynthVST::Processor::checkSoundFont(bool synced){ //PerfMeter pm("Check", 8000); if(mLoadingThread){ if(mLoadingComplete || synced){ CloseHandle(mLoadingThread); mLoadingThread = 0; //printf("Processor: loading font complete\n"); } else return false; } if(!mChangeSoundFont) return true; //printf("Processor: changing sound font %s\n", synced ? "synced" : "asynced"); mLoadedFile = mSoundFontFile; mChangeSoundFont = false; if(!synced){ mLoadingComplete = false; if((mLoadingThread = CreateThread(NULL, 0, Processor_LoadingThread, this, 0, NULL))) return false; printf("Could not create loading thread, continue in synced mode\n"); } syncedLoadSoundFont(); return true; } #else /* Linux */ #define glib_DllMain(x,y,z) #include <dlfcn.h> void FluidSynthVST::GetPath(char *szPath /* Out */, int32 size){ Dl_info info; if(!dladdr(&moduleHandle, &info) || (strlen(info.dli_fname) > (size - 1))){ *szPath = 0; } else { strcpy(szPath, info.dli_fname); char *slash = strrchr(szPath, '/'); if(slash) *slash = 0; } } void FluidSynthVST::PathAppend(char *szPath /* Out */, int32 size, const char *szName){ if(size <= (strlen(szPath) + strlen(szName) + 1)) return; strcat(szPath, "/"); strcat(szPath, szName); } #include <sys/types.h> #include <dirent.h> void FluidSynthVST::Processor::scanSoundFonts(){ char szDirName[FILENAME_MAX]; GetPath(szDirName, FILENAME_MAX); DIR *dir = opendir(szDirName); if(dir){ struct dirent *de; while((de = readdir(dir))){ if((strlen(de->d_name) > 4) && !memcmp(de->d_name + strlen(de->d_name) - 4, ".sf", 3)){ mSoundFontFiles.push_back( de->d_name ); // will be in file system encoding, hope it is UTF8 } } closedir(dir); std::sort(mSoundFontFiles.begin(), mSoundFontFiles.end()); } if(mSoundFontFiles.size() == 0) mSoundFontFiles.push_back( "default.sf2" ); } #include <pthread.h> static void *Processor_LoadingThread(void *par){ auto processor = static_cast<FluidSynthVST::Processor *>(par); processor->syncedLoadSoundFont(); return NULL; } /* * Returns true in case the synth can be used. * Initiate font loading, synced or asynced as specified in case that was requested. * Also finish loading in specified mode * * It is not thread safe, but it can be called from * destructor, setProcessing or process only. Host should never * parallelize any of them. */ bool FluidSynthVST::Processor::checkSoundFont(bool synced){ //PerfMeter pm("Check", 8000); if(mLoadingThread){ if(mLoadingComplete || synced){ pthread_join(mLoadingThread, NULL); mLoadingThread = 0; //printf("Processor: loading font complete\n"); } else return false; } if(!mChangeSoundFont) return true; //printf("Processor: changing sound font %s\n", synced ? "synced" : "asynced"); mLoadedFile = mSoundFontFile; mChangeSoundFont = false; if(!synced){ mLoadingComplete = false; if(!pthread_create(&mLoadingThread, NULL, Processor_LoadingThread, this)){ return false; } printf("Could not create loading thread, continue in synced mode\n"); } syncedLoadSoundFont(); return true; } #endif // Module bool InitModule(){ glib_DllMain(moduleHandle, DLL_PROCESS_ATTACH, NULL); return true; } bool DeinitModule(){ glib_DllMain(moduleHandle, DLL_PROCESS_DETACH, NULL); return true; }
34,654
C++
.cpp
971
31.584964
153
0.679943
AZSlow3/FluidSynthVST
35
1
5
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,882
fluidsynthvst.h
AZSlow3_FluidSynthVST/include/fluidsynthvst.h
/* * FluidSynth VST * * Wrapper part (this file): Copyright (C) 2019 AZ (www.azslow.com) * * FluidSynth: Copyright (C) 2003-2019 Peter Hanappe and others. * VST API: (c) 2019, Steinberg Media Technologies GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "pluginterfaces/base/fplatform.h" #include "public.sdk/source/vst/vstaudioeffect.h" #include "public.sdk/source/vst/vsteditcontroller.h" #include "pluginterfaces/vst/ivstmidicontrollers.h" #include "pluginterfaces/vst/ivstmessage.h" #include "fluidsynth.h" #ifdef WIN32 #include <windows.h> #else /* Linux */ #include <pthread.h> #endif /* Platform */ #define MAJOR_VERSION_STR "0" #define MAJOR_VERSION_INT 0 #define SUB_VERSION_STR "0" #define SUB_VERSION_INT 0 #define RELEASE_NUMBER_STR "0" #define RELEASE_NUMBER_INT 0 #define BUILD_NUMBER_STR "3" #define BUILD_NUMBER_INT 3 #define FULL_VERSION_STR MAJOR_VERSION_STR "." SUB_VERSION_STR "." RELEASE_NUMBER_STR "." BUILD_NUMBER_STR #define VERSION_STR MAJOR_VERSION_STR "." SUB_VERSION_STR "." RELEASE_NUMBER_STR #define stringPluginName "FluidSynth" #define stringSubCategory "Instrument|Sampler" #define stringOriginalFilename "fluidsynthvst.vst3" #define stringFileDescription stringPluginName #define stringCompanyName "AZ" #define stringCompanyWeb "http://www.azslow.com" #define stringCompanyEmail "mailto:admin@azslow.com" #define stringLegalCopyright "© 2019 AZ" #define stringLegalTrademarks "VST is a trademark of Steinberg Media Technologies GmbH" namespace FluidSynthVST { using namespace Steinberg; static const FUID ProcessorUID(0xe42276cd, 0x074c42e5, 0xb68a740f, 0x8565fc6f); static const FUID ControllerUID(0x43d1bc05, 0xf0f847a0, 0x85153e69, 0xe59c7455); enum FluidSynthVSTParams : Vst::ParamID { kBypassId = 0, // Vst::ProgramListID, but they are used as program change ParamID... kRootPrgId, kChPrgId, kLastChPrgId = kChPrgId + 15, }; class Controller : public Vst::EditControllerEx1, public Vst::IMidiMapping { public: tresult PLUGIN_API initialize(FUnknown* context) SMTG_OVERRIDE; tresult PLUGIN_API setComponentState(IBStream* state) SMTG_OVERRIDE; tresult PLUGIN_API setParamNormalized (Vst::ParamID tag, Vst::ParamValue value) SMTG_OVERRIDE; tresult PLUGIN_API getMidiControllerAssignment (int32 busIndex, int16 channel, Vst::CtrlNumber midiControllerNumber, Vst::ParamID& id/*out*/) SMTG_OVERRIDE; tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, int32 busIndex, int32 channel, Vst::UnitID& unitId /*out*/) SMTG_OVERRIDE; tresult PLUGIN_API notify (Vst::IMessage* message) SMTG_OVERRIDE; static FUnknown* createInstance (void*){ return (IEditController*)new Controller(); } //static FUID cid; OBJ_METHODS (Controller, Vst::EditControllerEx1) DEFINE_INTERFACES DEF_INTERFACE(Vst::IMidiMapping) END_DEFINE_INTERFACES(Vst::EditControllerEx1) REFCOUNT_METHODS(Vst::EditControllerEx1) private: float mCurrentProgram; }; class Processor : public Vst::AudioEffect { public: Processor(); ~Processor(); tresult PLUGIN_API initialize(FUnknown* context) SMTG_OVERRIDE; tresult PLUGIN_API setBusArrangements(Vst::SpeakerArrangement* inputs, int32 numIns, Vst::SpeakerArrangement* outputs, int32 numOuts) SMTG_OVERRIDE; tresult PLUGIN_API canProcessSampleSize (int32 symbolicSampleSize) SMTG_OVERRIDE; tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& setup) SMTG_OVERRIDE; tresult PLUGIN_API setActive (TBool state) SMTG_OVERRIDE; tresult PLUGIN_API setProcessing (TBool state) SMTG_OVERRIDE; tresult PLUGIN_API process(Vst::ProcessData& data) SMTG_OVERRIDE; tresult PLUGIN_API setState (IBStream* state) SMTG_OVERRIDE; tresult PLUGIN_API getState (IBStream* state) SMTG_OVERRIDE; tresult PLUGIN_API connect (IConnectionPoint* other) SMTG_OVERRIDE; static FUnknown* createInstance(void*){ return (Vst::IAudioProcessor*)new Processor (); } void syncedLoadSoundFont(); // public for thread function protected: bool mBypass = false; fluid_settings_t* mSynthSettings; fluid_synth_t* mSynth; int32 mSoundFontID; // -1 when failed to load using StringVector = std::vector<String>; StringVector mSoundFontFiles; // in UTF-8 String mSoundFontFile; bool mChangeSoundFont; float *mAudioBufs[2]; int32 mAudioBufsSize; void writeAudio(Vst::ProcessData& data, int32 start_sample, int32 end_samle); int32 nextOffset(Vst::ProcessData& data, int32 curSample); void playParChanges(Vst::ProcessData& data, int32 curSample, int32 endSample); void playEvents(Vst::ProcessData& data, int32 curSample, int32 endSample); void scanSoundFonts(); bool checkSoundFont(bool synced); int getCurrentSoundFontIdx(); float getCurrentSoundFontNormalized(); void sendCurrentProgram(); void sendProgramList(); private: #ifdef WIN32 HANDLE mLoadingThread; #else /* Linux */ pthread_t mLoadingThread; #endif /* platform */ String mLoadedFile; bool mLoadingComplete; }; void GetPath(char *szPath /* Out */, int32 size); void PathAppend(char *szPath /* Out */, int32 size, const char *szName); }
5,878
C++
.h
134
40.402985
160
0.757193
AZSlow3/FluidSynthVST
35
1
5
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,883
config.h
shajra_shajra-keyboards/keymaps/moonlander/shajra/config.h
#define MOONLANDER_USER_LEDS #define ONESHOT_TIMEOUT 1500 #define ORYX_CONFIGURATOR #define PERMISSIVE_HOLD #define QUICK_TAP_TERM 0 #define RGBLIGHT_SLEEP
156
C++
.h
6
25
28
0.853333
shajra/shajra-keyboards
34
5
0
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,884
config.h
shajra_shajra-keyboards/keymaps/ergodox_ez/shajra/config.h
#define ONESHOT_TIMEOUT 1500 #define ORYX_CONFIGURATOR #define PERMISSIVE_HOLD #define QUICK_TAP_TERM 0
104
C++
.h
4
25
28
0.85
shajra/shajra-keyboards
34
5
0
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,885
util.cpp
zetaPRIME_MultiBound2/multibound2/util.cpp
#include "util.h" #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QJSEngine> #include <QDebug> std::function<void(QString)> MultiBound::Util::updateStatus; QJsonDocument MultiBound::Util::loadJson(const QString& path) { QFile f(path); f.open(QFile::ReadOnly); return parseJson(f.readAll()); } QJsonDocument MultiBound::Util::parseJson(const QByteArray data) { QJsonParseError err; QJsonDocument json = QJsonDocument::fromJson(data, &err); // if it fails, try stripping comments via javascript if (err.error != QJsonParseError::NoError) { QJSEngine js; auto v = js.evaluate(qs("js=%1;").arg(QString(data))); auto func = js.evaluate(qs("JSON.stringify")); QJSValueList args; args.append(v); auto v2 = func.call(args); if (v2.isString()) json = QJsonDocument::fromJson(v2.toString().toUtf8(), &err); } if (err.error != QJsonParseError::NoError) qDebug() << err.errorString(); return json; }
1,024
C++
.cpp
28
31.857143
88
0.687247
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,886
workshop.cpp
zetaPRIME_MultiBound2/multibound2/workshop.cpp
#include "util.h" // part of utility header #include "data/config.h" #include "data/instance.h" #include <deque> #include <QSet> #include <QHash> #include <QJsonDocument> #include <QJsonArray> #include <QRegularExpression> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QHttpMultiPart> #include <QEventLoop> namespace { // utilities QHttpPart formPart(QString id, QString val) { QHttpPart pt; pt.setHeader(QNetworkRequest::ContentDispositionHeader, qs("form-data; name=\"%1\"").arg(id)); pt.setBody(val.toUtf8()); return pt; } } void MultiBound::Util::updateFromWorkshop(MultiBound::Instance* inst, bool save) { updateStatus(qs("Fetching collection details...")); auto wsId = inst->workshopId(); if (wsId.isEmpty()) return; // no workshop id attached auto& json = inst->json; auto info = json["info"].toObject(); info["workshopId"] = wsId; // make sure id tag is present QHash<QString, QString> wsMods; std::deque<QString> modInfoQueue; std::deque<QString> wsQueue; QSet<QString> wsVisited; QNetworkAccessManager net; QEventLoop ev; auto getCollectionDetails = [&](QStringList ids) { QNetworkRequest req(QUrl("https://api.steampowered.com/ISteamRemoteStorage/GetCollectionDetails/v1/")); req.setRawHeader("Accept", "application/json"); QHttpMultiPart form(QHttpMultiPart::FormDataType); form.append(formPart(qs("collectioncount"), QString::number(ids.count()))); for (auto i = 0; i < ids.count(); ++i) form.append(formPart(qs("publishedfileids[%1]").arg(i), ids[i])); req.setHeader(QNetworkRequest::ContentTypeHeader, qs("multipart/form-data; boundary=%1").arg(QString::fromUtf8(form.boundary()))); auto reply = net.post(req, &form); QObject::connect(reply, &QNetworkReply::finished, &ev, &QEventLoop::quit); ev.exec(); // wait for things reply->deleteLater(); // queue deletion on event loop, *after we're done* return QJsonDocument::fromJson(reply->readAll()).object()[qs("response")].toObject(); }; auto getItemDetails = [&](QStringList ids) { QNetworkRequest req(qs("https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/")); req.setRawHeader("Accept", "application/json"); QHttpMultiPart form(QHttpMultiPart::FormDataType); form.append(formPart(qs("itemcount"), QString::number(ids.count()))); for (auto i = 0; i < ids.count(); ++i) form.append(formPart(qs("publishedfileids[%1]").arg(i), ids[i])); req.setHeader(QNetworkRequest::ContentTypeHeader, qs("multipart/form-data; boundary=%1").arg(QString::fromUtf8(form.boundary()))); auto reply = net.post(req, &form); QObject::connect(reply, &QNetworkReply::finished, &ev, &QEventLoop::quit); ev.exec(); // wait for things reply->deleteLater(); // queue deletion on event loop, *after we're done* return QJsonDocument::fromJson(reply->readAll()).object()[qs("response")].toObject(); }; bool needsInfo = !info["lockInfo"].toBool(); bool needsExtCfg = true; wsQueue.push_back(wsId); // it starts with one while (!wsQueue.empty()) { QString cId = wsQueue.front(); wsQueue.pop_front(); if (cId.isEmpty() || wsVisited.contains(cId)) continue; wsVisited.insert(cId); auto obj = getCollectionDetails(QStringList() << cId); if (needsInfo || needsExtCfg) { auto inf = getItemDetails(QStringList() << cId)["publishedfiledetails"].toArray()[0].toObject(); if (needsInfo) { // update display name and title from html needsInfo = false; auto name = inf["title"].toString(); info["name"] = name; info["windowTitle"] = qs("Starbound - %1").arg(name); } if (needsExtCfg) { // find extcfg block auto desc = inf["description"].toString(); static QRegularExpression xcm("\\[code\\]\\[noparse\\]([\\S\\s]*)\\[\\/noparse\\]\\[\\/code\\]"); xcm.setPatternOptions(QRegularExpression::CaseInsensitiveOption); auto xc = xcm.match(desc).captured(1); if (!xc.isEmpty()) { needsExtCfg = false; json["extCfg"] = Util::parseJson(xc.toUtf8()).object(); } } } auto children = obj["collectiondetails"].toArray()[0].toObject()["children"].toArray(); for (auto ch : children) { auto c = ch.toObject(); auto id = c["publishedfileid"].toString(); auto ft = c["filetype"].toInt(-1); if (id.isEmpty()) continue; if (ft == 2) { // subcollection wsQueue.push_back(id); } else if (ft == 0) { // mod modInfoQueue.push_back(id); } } } if (modInfoQueue.size() > 0) { QStringList ids; for (auto& id : modInfoQueue) ids << id; //modInfoQueue.clear(); auto r = getItemDetails(ids)["publishedfiledetails"].toArray(); for (auto pfi : r) { auto inf = pfi.toObject(); auto id = inf["publishedfileid"].toString(); auto title = inf["title"].toString(); if (id.isEmpty()) continue; wsMods[id] = title; } } json["info"] = info; // update info in json body // rebuild assetSources with new contents auto oldSrc = json["assetSources"].toArray(); QJsonArray src; // carry over old entries that aren't workshopAuto for (auto s : oldSrc) if (s.isString() || s.toObject()["type"].toString() != "workshopAuto") src << s; // and add mod entries for (auto i = wsMods.keyValueBegin(); i != wsMods.keyValueEnd(); i++) { QJsonObject s; s["type"] = "workshopAuto"; s["id"] = (*i).first; s["friendlyName"] = (*i).second; src << s; } json["assetSources"] = src; // commit if (save) inst->save(); if (Config::steamcmdEnabled) Util::updateMods(inst); updateStatus(""); }
6,225
C++
.cpp
136
37.183824
138
0.608696
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,887
steamcmd.cpp
zetaPRIME_MultiBound2/multibound2/steamcmd.cpp
#include "util.h" // part of utility header #include "data/config.h" #include "data/instance.h" #include <QJsonDocument> #include <QJsonArray> #include <QDialog> #include <QDialogButtonBox> #include <QTextEdit> #include <QLineEdit> #include <QBoxLayout> #include <QLabel> #include <QMessageBox> #include <QMetaObject> #include <QProcess> #include <QFile> #include <QStandardPaths> #include <QEventLoop> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QDataStream> #include <QSet> namespace { // clazy:excludeall=non-pod-global-static const auto updMsg = qs("Updating mods..."); QProcess* scp; QEventLoop ev; bool scFail = true; QString scConfigPath; // these are only saved for the session QString triedUserName; QString triedPassword; } bool MultiBound::Util::initSteamCmd() { if (!Config::steamcmdEnabled) return false; // don't bother if it's disabled if (scp) { if (scFail) return false; // could not init steamcmd return true; // already initialized } scp = new QProcess(); QObject::connect(scp, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), &ev, &QEventLoop::quit); #if defined(Q_OS_WIN) QDir scd(Config::configPath); scd.mkpath("steamcmd"); // make sure it exists scd.cd("steamcmd"); if (!scd.exists("steamcmd.exe")) { // download and install if not present updateStatus(qs("Downloading steamcmd...")); scp->start("powershell", QStringList() << "curl -o"<< scd.absoluteFilePath("steamcmd.zip") << "https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip"); auto scz = scd.absoluteFilePath("steamcmd.zip"); ev.exec(); scp->start("powershell", QStringList() << "Expand-Archive"<< "-DestinationPath" << scd.absolutePath() << "-LiteralPath" << scz); ev.exec(); if (scp->exitCode() != 0) return false; // extraction failed for some reason or another, abort // finish installing updateStatus(qs("Installing steamcmd...")); scp->setWorkingDirectory(scd.absolutePath()); scp->start(scd.absoluteFilePath("steamcmd.exe"), QStringList() << "+exit"); ev.exec(); scp->readAll(); // and clean up buffer } scp->setProgram(scd.absoluteFilePath("steamcmd.exe")); scp->setWorkingDirectory(scd.absolutePath()); scConfigPath = Util::splicePath(scd.absolutePath(), "/config/"); #else // test with standard "which" command on linux and mac if (scp->execute("which", QStringList() << "steamcmd") == 0) { // use system steamcmd if present scp->readAll(); // clear buffer scp->setProgram("steamcmd"); QDir home(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); scConfigPath = Util::splicePath(home, "/.steam/steam/config/"); } else { // use our own copy, and install automatically if necessary scp->readAll(); // clear buffer QDir scd(Config::configPath); scd.mkpath("steamcmd"); // make sure it exists scd.cd("steamcmd"); if (!scd.exists("steamcmd.sh")) { // install local copy updateStatus(qs("Downloading steamcmd...")); #if defined(Q_OS_MACOS) auto scUrl = qs("https://steamcdn-a.akamaihd.net/client/installer/steamcmd_osx.tar.gz"); #else auto scUrl = qs("https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz"); #endif scp->setWorkingDirectory(scd.absolutePath()); scp->start("bash", QStringList() << "-c" << qs("curl -sqL \"%1\" | tar -xzvf -").arg(scUrl)); ev.exec(); if (scp->exitCode() != 0) return false; // something went wrong, abort // finish installing updateStatus(qs("Installing steamcmd...")); scp->setWorkingDirectory(scd.absolutePath()); scp->start(scd.absoluteFilePath("steamcmd.sh"), QStringList() << "+exit"); ev.exec(); scp->readAll(); // and clean up buffer } scp->setProgram(scd.absoluteFilePath("steamcmd.sh")); scp->setWorkingDirectory(scd.absolutePath()); scConfigPath = Util::splicePath(scd.absolutePath(), "/config/"); } #endif scFail = false; return true; } void MultiBound::Util::updateMods(MultiBound::Instance* inst) { if (!initSteamCmd()) return; updateStatus(updMsg); auto& json = inst->json; QSet<QString> workshop; QSet<QString> workshopExclude; auto sources = json["assetSources"].toArray(); for (auto s : sources) { if (s.isObject()) { auto src = s.toObject(); auto type = src["type"].toString(); if (type == "mod") { if (auto id = src["workshopId"]; id.isString()) workshop.insert(id.toString()); } else if (type == "workshopAuto") { if (auto id = src["id"]; id.isString()) workshop.insert(id.toString()); } else if (type == "workshopExclude") { if (auto id = src["id"]; id.isString()) workshopExclude.insert(id.toString()); } } } int wsc = 0; bool ws = !Config::workshopRoot.isEmpty(); // workshop active; valid workshop root? bool wsUpd = Config::steamcmdUpdateSteamMods; // should update workshop-subscribed mods? QString wsScript, dlScript; QTextStream wss(&wsScript), dls(&dlScript); if (ws) { // if valid workshop, force proper root in case steamcmd defaults are incorrect QDir wsr(Config::workshopRoot); for (int i = 0; i < 4; i++) wsr.cdUp(); wss << qs("force_install_dir \"") << wsr.absolutePath() << qs("\"\n"); } wss << qs("login anonymous\n"); // log in after forcing install dir dls << qs("force_install_dir \"") << Config::steamcmdDLRoot << qs("\"\n"); dls << qs("login anonymous\n"); auto eh = qs("workshop_download_item 211820 "); for (auto& id : workshop) { if (!workshopExclude.contains(id)) { if (ws && QDir(Config::workshopRoot).exists(id)) { if (wsUpd) { wss << eh << id << qs("\n"); wsc++; } } else {dls << eh << id << qs("\n"); wsc++; } } } QString endcap = qs("_dummy\n"); // force last download attempt to fully print wss << endcap; wss.flush(); dls << endcap; dls.flush(); QString scriptPath = QDir(Config::steamcmdDLRoot).filePath("steamcmd.txt"); { QFile sf(scriptPath); sf.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text); (QTextStream(&sf)) << wsScript; sf.close(); } QString scriptPath2 = QDir(Config::steamcmdDLRoot).filePath("steamcmd2.txt"); { QFile sf(scriptPath2); sf.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text); (QTextStream(&sf)) << dlScript; sf.close(); } std::unique_ptr<QObject> ctx(new QObject()); int wsp = 0; updateStatus(qs("%1 (%2/%3)").arg(updMsg).arg(wsp).arg(wsc)); QObject::connect(scp, &QProcess::readyRead, ctx.get(), [wsc, &wsp, &ctx] { // clazy:exclude=lambda-in-connect while (scp->canReadLine()) { QString l = scp->readLine(); //qDebug() << l; if (l.startsWith(qs("Success. Downloaded item"))) { wsp++; updateStatus(qs("%1 (%2/%3)").arg(updMsg).arg(wsp).arg(wsc)); } else if (l.contains("Missing decryption key") || l.contains("failed (Failure).")) { ctx.reset(); scp->close(); // abort return; } } }); /* / run workshop-update script */ { QStringList args; args << "+runscript" << scriptPath << "+quit"; scp->setArguments(args); scp->start(); ev.exec(); } /* and then the custom-download one */ if (ctx) { QStringList args; args << "+runscript" << scriptPath2 << "+quit"; scp->setArguments(args); scp->start(); ev.exec(); } if (!ctx) { // download failure occurred QMessageBox::critical(nullptr, " ", "Failed to download one or more mods. This may be due to Steam maintenance, or due to a network or steamcmd error. Please try again in a few minutes."); } } //
8,295
C++
.cpp
194
35.35567
196
0.612265
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,889
mainwindow.cpp
zetaPRIME_MultiBound2/multibound2/mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "settingswindow.h" #include "data/config.h" #include "data/instance.h" #include "util.h" #include "uitools.h" #include <memory> #include <QDebug> #include <QTimer> #include <QDir> #include <QFile> #include <QFileInfo> #include <QJsonDocument> #include <QMenu> #include <QShortcut> #include <QClipboard> #include <QMessageBox> #include <QInputDialog> #include <QFileDialog> #include <QDesktopServices> #include <QUrl> using MultiBound::MainWindow; using MultiBound::Instance; QPointer<MainWindow> MainWindow::instance; namespace { // clazy:excludeall=non-pod-global-static inline Instance* instanceFromItem(QListWidgetItem* itm) { return static_cast<Instance*>(itm->data(Qt::UserRole).value<void*>()); } auto checkableEventFilter = new MultiBound::CheckableEventFilter(); void bindConfig(QAction* a, bool& f) { a->setChecked(f); QObject::connect(a, &QAction::triggered, a, [&f](bool b) { f = b; MultiBound::Config::save(); }); QObject::connect(MultiBound::MainWindow::instance, &MultiBound::MainWindow::refreshSettings, a, [a, &f] { a->setChecked(f); }); } bool firstShow = true; } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); instance = this; connect(ui->launchButton, &QPushButton::pressed, this, [this] { launch(); }); connect(ui->instanceList, &QListWidget::doubleClicked, this, [this](const QModelIndex& ind) { if (ind.isValid()) launch(); }); connect(new QShortcut(QKeySequence("Return"), ui->instanceList), &QShortcut::activated, this, [this] { launch(); }); // hook up menus for (auto m : ui->menuBar->children()) if (qobject_cast<QMenu*>(m)) m->installEventFilter(checkableEventFilter); ui->actionRefresh->shortcuts() << QKeySequence("F5"); connect(ui->actionRefresh, &QAction::triggered, this, [this] { refresh(); }); connect(ui->actionExit, &QAction::triggered, this, [this] { close(); }); connect(ui->actionFromCollection, &QAction::triggered, this, [this] { newFromWorkshop(); }); // settings bindConfig(ui->actionUpdateSteamMods, Config::steamcmdUpdateSteamMods); connect(ui->actionSettings, &QAction::triggered, this, [ ] { if (SettingsWindow::instance) { SettingsWindow::instance->show(); SettingsWindow::instance->raise(); SettingsWindow::instance->activateWindow(); } else (new SettingsWindow)->show(); }); // and context menu connect(ui->instanceList, &QListWidget::customContextMenuRequested, this, [this](const QPoint& pt) { auto m = new QMenu(this); if (auto i = ui->instanceList->itemAt(pt); i) { auto inst = instanceFromItem(i); m->addAction(qs("&Launch instance"), this, [this, inst] { launch(inst); }); if (auto id = inst->workshopId(); !id.isEmpty()) { m->addAction(qs("&Update from Workshop collection"), m, [this, inst] { updateFromWorkshop(inst); }); m->addAction(qs("Open &Workshop link..."), m, [id] { QDesktopServices::openUrl(QUrl(Util::workshopLinkFromId(id))); }); } m->addAction(qs("&Open instance directory..."), m, [inst] { QDesktopServices::openUrl(QUrl::fromLocalFile(inst->path)); }); m->addSeparator(); } // carry over options from menu bar m->addMenu(ui->menuNewInstance); m->addSeparator(); m->addAction(ui->actionRefresh); m->setAttribute(Qt::WA_DeleteOnClose); m->popup(ui->instanceList->mapToGlobal(pt)); }); connect(new QShortcut(QKeySequence(QKeySequence::Paste), this), &QShortcut::activated, this, [this] { auto txt = QApplication::clipboard()->text(); auto id = Util::workshopIdFromLink(txt); if (id.isEmpty()) return; newFromWorkshop(id); }); if (auto fi = QFileInfo(Config::starboundPath); !fi.isFile() || !fi.isExecutable()) { // prompt for working file path if executable missing auto d = fi.dir(); if (!d.exists()) { // walk up until dir exists auto cd = qs(".."); while (!d.cd(cd)) cd.append(qs("/..")); } auto fn = QFileDialog::getOpenFileName(this, qs("Locate Starbound executable..."), d.absolutePath()); if (fn.isEmpty()) { QMetaObject::invokeMethod(this, [this] { close(); QApplication::quit(); }, Qt::ConnectionType::QueuedConnection); } else { // set new path and refresh Config::starboundPath = fn; Config::save(); Config::load(); } } refresh(); Util::updateStatus = [this] (QString msg) { ui->statusBar->setVisible(!msg.isEmpty()); // only show status bar when a message is shown ui->statusBar->showMessage(msg); }; Util::updateStatus(""); // add version to title setWindowTitle(QString("%1 %2").arg(windowTitle(), Util::version)); } MainWindow::~MainWindow() { delete ui; if (SettingsWindow::instance) SettingsWindow::instance->close(); } void MainWindow::showEvent(QShowEvent* e) { QMainWindow::showEvent(e); if (firstShow) { // only check for updates and such on launch, not on return from game firstShow = false; // execute the rest after showing QTimer::singleShot(0, this, [this] { if (!Config::openSBOffered) { auto res = QMessageBox::question(this, "OpenStarbound integration", "Would you like to enable OpenStarbound support? OpenStarbound contains various performance and quality-of-life improvements over the vanilla client, and enables mod features which are simply not possible otherwise.\n\n(MultiBound will handle installing and updating its own copy of OpenStarbound.)", QMessageBox::Yes, QMessageBox::No); Config::openSBEnabled = res == QMessageBox::Yes; Config::openSBOffered = true; Config::save(); } // then check updates checkUpdates(); }); } } bool MainWindow::isInteractive() { return ui->centralWidget->isEnabled(); } void MainWindow::setInteractive(bool b) { ui->menuBar->setEnabled(b); ui->centralWidget->setEnabled(b); if (b) unsetCursor(); else setCursor(Qt::WaitCursor); } void MainWindow::checkUpdates(bool osbOnly) { if (!osbOnly) { // TODO figure out update check on windows setInteractive(false); Util::checkForUpdates(); setInteractive(true); } // OpenStarbound update check if (Config::openSBEnabled) { setInteractive(false); Util::openSBCheckForUpdates(); setInteractive(true); } } void MainWindow::updateCIBuild() { setInteractive(false); Util::openSBUpdateCI(); setInteractive(true); } void MainWindow::refresh(const QString& focusPath) { QString selPath; if (!focusPath.isEmpty()) selPath = focusPath; else if (auto sel = ui->instanceList->selectedItems(); sel.count() > 0) selPath = instanceFromItem(sel[0])->path; ui->instanceList->clear(); QListWidgetItem* selItm = nullptr; // load instances instances.clear(); QDir d(Config::instanceRoot); auto lst = d.entryList(QDir::Dirs); instances.reserve(static_cast<size_t>(lst.count())); for (auto& idir : lst) { auto inst = Instance::loadFrom(idir); if (!inst) continue; instances.push_back(inst); auto itm = new QListWidgetItem(inst->displayName(), ui->instanceList); itm->setData(Qt::UserRole, QVariant::fromValue(static_cast<void*>(inst.get())));//reinterpret_cast<qintptr>(inst.get())); if (inst->path == selPath) selItm = itm; } if (selItm) { ui->instanceList->setCurrentRow(ui->instanceList->row(selItm)); ui->instanceList->scrollToItem(selItm); } } void MainWindow::launch(Instance* inst) { if (!inst) { inst = selectedInstance(); if (!inst) return; } hide(); inst->launch(); show(); } void MainWindow::updateFromWorkshop(Instance* inst) { if (!inst) { inst = selectedInstance(); if (!inst) return; } setInteractive(false); Util::updateFromWorkshop(inst); setInteractive(true); refresh(inst->path); } void MainWindow::newFromWorkshop(const QString& id_) { auto id = id_; if (id.isEmpty()) { // prompt bool ok = false; auto link = QInputDialog::getText(this, qs("Enter collection link"), qs("Enter a link to a Steam Workshop collection:"), QLineEdit::Normal, QString(), &ok); id = Util::workshopIdFromLink(link); if (!ok || id.isEmpty()) return; } setInteractive(false); auto inst = findWorkshopId(id); if (inst) { return updateFromWorkshop(inst); } else { auto ni = std::make_shared<Instance>(); ni->json = QJsonDocument::fromJson(qs("{\"info\" : { \"workshopId\" : \"%1\" }, \"savePath\" : \"inst:/storage/\", \"assetSources\" : [ \"inst:/mods/\" ] }").arg(id).toUtf8()).object(); Util::updateFromWorkshop(ni.get(), false); if (!ni->displayName().isEmpty()) { bool ok = false; auto name = QInputDialog::getText(this, qs("Directory name?"), qs("Enter a directory name for your new instance:"), QLineEdit::Normal, ni->displayName(), &ok); if (ok && !name.isEmpty()) { auto path = Util::splicePath(Config::instanceRoot, name); if (QDir(path).exists()) { QMessageBox::warning(this, qs("Error creating instance"), qs("Directory already exists.")); } else { ni->path = path; ni->save(); refresh(ni->path); } } } } setInteractive(true); } Instance* MainWindow::selectedInstance() { if (auto sel = ui->instanceList->selectedItems(); sel.count() > 0) return instanceFromItem(sel[0]); return nullptr; } Instance* MainWindow::findWorkshopId(const QString& id) { if (id.isEmpty()) return nullptr; for (auto& i : instances) if (i->workshopId() == id) return i.get(); return nullptr; } //
10,338
C++
.cpp
243
35.452675
420
0.632439
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,890
update.cpp
zetaPRIME_MultiBound2/multibound2/update.cpp
#include "util.h" // part of utility header // version tracking and update checking #include <QCoreApplication> #include <QDir> #include <QDateTime> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QHttpMultiPart> #include <QEventLoop> #include <QMessageBox> #include <QDesktopServices> #include <QVersionNumber> const QString MultiBound::Util::version = qs("v0.6.3"); namespace { // clazy:excludeall=non-pod-global-static const auto releasesUrl = qs("https://api.github.com/repos/zetaPRIME/MultiBound2/releases"); } QVersionNumber getVer(QString a) { if (a.at(0) == 'v') a = a.mid(1); int suf = -1; auto v = QVersionNumber::fromString(a, &suf); if (suf > 0 && suf < a.length()) { auto c = a.at(suf).toLower(); if (c.isLetter()) { auto vr = v.segments(); vr.append(c.toLatin1() - ('a'-1)); v = QVersionNumber(vr); } } return v; } // a > b bool compareVersions(const QString& a, const QString& b = MultiBound::Util::version) { return getVer(a) > getVer(b); } // somewhat naive github version checking for Windows only void MultiBound::Util::checkForUpdates() { updateStatus("Checking for updates..."); // fetch release info QNetworkAccessManager net; QEventLoop ev; QNetworkRequest req(releasesUrl); auto reply = net.get(req); QObject::connect(reply, &QNetworkReply::finished, &ev, &QEventLoop::quit); ev.exec(); // wait for things reply->deleteLater(); auto releaseInfo = QJsonDocument::fromJson(reply->readAll()); auto ra = releaseInfo.array(); QJsonObject rel; // for now we assume releases are listed newest to oldest foreach (const auto& rv, ra) { auto r = rv.toObject(); // loop through assets to find the one we want foreach (const auto& av, r[qs("assets")].toArray()) { auto a = av.toObject(); if (a[qs("name")].toString().contains("-windows.zip")) { rel = r; break; } } if (!rel.isEmpty()) break; } if (!rel.isEmpty()) { // we found a release, check if it's eligible auto ver = rel["tag_name"].toString(); if (compareVersions(ver)) { // prompt auto res = QMessageBox::information(nullptr, "Update Notice", QString("A new version of MultiBound (%1) is available. Would you like to visit the release page?").arg(ver), QMessageBox::Yes, QMessageBox::No); if (res == QMessageBox::Yes) { QDesktopServices::openUrl(rel["html_url"].toString()); } } } updateStatus(""); }
2,730
C++
.cpp
75
30.48
219
0.635915
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,891
settingswindow.cpp
zetaPRIME_MultiBound2/multibound2/settingswindow.cpp
#include "settingswindow.h" #include "ui_settingswindow.h" #include "mainwindow.h" #include "data/config.h" #include <QTimer> using MultiBound::SettingsWindow; QPointer<SettingsWindow> SettingsWindow::instance; SettingsWindow::SettingsWindow(QWidget *parent) : QDialog(parent), ui(new Ui::SettingsWindow) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); if (instance) instance->close(); instance = this; connect(this, &QDialog::accepted, this, &SettingsWindow::apply); // set up initial values ui->openSBEnabled->setChecked(Config::openSBEnabled); ui->openSBUseCIBuild->setChecked(Config::openSBUseCIBuild); ui->openSBUseDevBranch->setChecked(Config::openSBUseDevBranch); ui->steamcmdEnabled->setChecked(Config::steamcmdEnabled); ui->steamcmdUpdateSteamMods->setChecked(Config::steamcmdUpdateSteamMods); // and some interactions ui->steamcmdUpdateSteamMods->setEnabled(ui->steamcmdEnabled->isChecked()); connect(ui->steamcmdEnabled, &QCheckBox::stateChanged, this, [this] { ui->steamcmdUpdateSteamMods->setEnabled(ui->steamcmdEnabled->isChecked()); }); connect(ui->btnUpdateCI, &QPushButton::clicked, this, [this] { if (!MainWindow::instance->isInteractive()) return; // guard QPointer<QPushButton> btn = ui->btnUpdateCI; btn->setEnabled(false); MainWindow::instance->updateCIBuild(); if (btn) btn->setEnabled(true); }); } SettingsWindow::~SettingsWindow() { delete ui; } void SettingsWindow::apply() { bool enablingOSB = ui->openSBEnabled->isChecked() && !Config::openSBEnabled; Config::openSBEnabled = ui->openSBEnabled->isChecked(); Config::openSBUseCIBuild = ui->openSBUseCIBuild->isChecked(); Config::openSBUseDevBranch = ui->openSBUseDevBranch->isChecked(); Config::steamcmdEnabled = ui->steamcmdEnabled->isChecked(); Config::steamcmdUpdateSteamMods = ui->steamcmdUpdateSteamMods->isChecked(); Config::save(); emit MainWindow::instance->refreshSettings(); if (enablingOSB) QTimer::singleShot(0, MainWindow::instance, [] { MainWindow::instance->checkUpdates(true); }); }
2,178
C++
.cpp
50
38.68
82
0.72891
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,892
opensb.cpp
zetaPRIME_MultiBound2/multibound2/opensb.cpp
#include "util.h" // part of utility header // functions for OpenStarbound installation and update management #include "data/config.h" #include <cmath> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QHttpMultiPart> #include <QEventLoop> #include <QMessageBox> #include <QProcess> // QDateTime::fromString(str, Qt::ISODate) namespace { // clazy:excludeall=non-pod-global-static const auto releasesUrl = qs("https://api.github.com/repos/OpenStarbound/OpenStarbound/releases"); // QJsonDocument releaseInfo; QJsonObject eligibleRelease; QString eligibleReleaseUrl; QJsonObject currentRelease; const auto ciUrl = qs("https://api.github.com/repos/OpenStarbound/OpenStarbound/actions/runs"); // os-specific things #if defined(Q_OS_WIN) const auto pkgAssetName = qs("win_opensb.zip"); const auto ciPlatform = qs("Windows"); const auto ciArtifact = qs("OpenStarbound-Windows-Client"); #elif defined (Q_OS_MACOS) const auto pkgAssetName = qs("osx_opensb.zip except not because we don't have code for this"); // it just won't find an eligible release const auto ciPlatform = qs("macOS"); const auto ciArtifact = qs("and now we have a problem"); #else // linux const auto pkgAssetName = qs("linux_opensb.zip"); const auto ciPlatform = qs("Ubuntu Linux"); const auto ciArtifact = qs("OpenStarbound-Linux-Client"); #endif // some utility stuff QEventLoop ev; void await(QNetworkReply* reply) { QObject::connect(reply, &QNetworkReply::finished, &ev, &QEventLoop::quit); ev.exec(); // wait for things reply->deleteLater(); } } QJsonDocument& getReleaseInfo(bool forceRefresh = false) { if (!forceRefresh && !releaseInfo.isEmpty()) return releaseInfo; QNetworkAccessManager net; QNetworkRequest req(releasesUrl); auto reply = net.get(req); await(reply); releaseInfo = QJsonDocument::fromJson(reply->readAll()); return releaseInfo; } QJsonObject& findEligibleRelease(bool forceRefresh = false) { if (!forceRefresh && !eligibleRelease.isEmpty()) return eligibleRelease; getReleaseInfo(forceRefresh); auto ra = releaseInfo.array(); // for now we assume releases are listed newest to oldest foreach (const auto& rv, ra) { auto r = rv.toObject(); // loop through assets to find the one we want foreach (const auto& av, r[qs("assets")].toArray()) { auto a = av.toObject(); if (a[qs("name")] == pkgAssetName) { eligibleRelease = r; eligibleReleaseUrl = a[qs("browser_download_url")].toString(); return eligibleRelease; } } } return eligibleRelease; } void MultiBound::Util::openSBCheckForUpdates() { if (currentRelease.isEmpty()) { if (QFile f(Util::splicePath(Config::openSBRoot, "/release.json")); f.exists()) { f.open(QFile::ReadOnly); currentRelease = QJsonDocument::fromJson(f.readAll()).object(); } } // if still empty, assume none and... prompt? if (currentRelease.isEmpty()) { // TODO } findEligibleRelease(true); if (eligibleRelease.isEmpty()) return; // nothing to show auto ed = QDateTime::fromString(eligibleRelease["published_at"].toString(), Qt::ISODate); auto cd = QDateTime::fromString(currentRelease["published_at"].toString(), Qt::ISODate); if (ed > cd) { // eligible is newer (or more extant) than current, prompt to update auto ver = eligibleRelease["name"].toString(); if (ver.isEmpty()) ver = eligibleRelease["tag_name"].toString(); if (ver.isEmpty()) ver = "unknown"; auto res = QMessageBox::information(nullptr, "OpenStarbound update", QString("A new version of OpenStarbound (%1) is available. Would you like to install it?").arg(ver), QMessageBox::Yes, QMessageBox::No); if (res == QMessageBox::Yes) { openSBUpdate(); } // } } void MultiBound::Util::openSBUpdate() { findEligibleRelease(); if (eligibleRelease.isEmpty()) return; // nothing // set up directory structure QDir osbd(Config::openSBRoot); if (osbd.exists()) { // nuke old installation files if they exist osbd.removeRecursively(); } osbd.mkpath("."); // make the directory exist (again) // download time! QNetworkAccessManager net; QEventLoop ev; const auto fn = qs("_download.zip"); QFile f(osbd.absoluteFilePath(fn)); f.open(QFile::WriteOnly); QNetworkRequest req(eligibleReleaseUrl); req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); // allow redirects auto reply = net.get(req); QObject::connect(reply, &QNetworkReply::downloadProgress, &ev, [](auto c, auto t) { updateStatus(QString("Downloading... %1\%").arg(std::floor((double)c/(double)t*100 + 0.5))); }); QObject::connect(reply, &QNetworkReply::readyRead, &f, [&f, reply] {f.write(reply->readAll());}); await(reply); f.flush(); f.close(); // now we unzip this fucker updateStatus("Extracting package..."); QProcess ps; QObject::connect(&ps, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), &ev, &QEventLoop::quit); #if defined(Q_OS_WIN) // powershell is weird but guaranteed to be there ps.start("powershell", QStringList() << "Expand-Archive" << "-DestinationPath" << osbd.absolutePath() << "-LiteralPath" << f.fileName()); ev.exec(); #else // if you're running a desktop without unzip, huh??? ps.start("unzip", QStringList() << f.fileName() << "-d" << osbd.absolutePath()); ev.exec(); foreach (auto fi, osbd.entryInfoList(QDir::Files)) { // fix permissions auto ext = fi.suffix(); QFile ff(fi.absoluteFilePath()); if (ext == "" or ext == "sh") { // assume no extension is executable ff.setPermissions(ff.permissions() | QFile::ExeOwner | QFile::ExeGroup | QFile::ExeOther); } } #endif osbd.remove(fn); // clean up the zip after we're done if (auto f = QFile(osbd.absoluteFilePath("steam_appid.txt")); true) { // ensure appid file f.open(QFile::WriteOnly); f.write("211820"); f.flush(); f.close(); } updateStatus(""); // finally, write out the release info QFile rf(osbd.absoluteFilePath("release.json")); rf.open(QFile::WriteOnly); rf.write(QJsonDocument(eligibleRelease).toJson(QJsonDocument::Indented)); rf.flush(); rf.close(); currentRelease = eligibleRelease; } void MultiBound::Util::openSBUpdateCI() { QNetworkAccessManager net; auto reply = net.get(QNetworkRequest(ciUrl)); await(reply); auto runs = QJsonDocument::fromJson(reply->readAll()).object()["workflow_runs"].toArray(); QJsonObject ri; foreach (const auto& rv, runs) { auto r = rv.toObject(); qDebug() << "run entry" << r["name"].toString(); if (r["name"] == ciPlatform && r["head_branch"] == "main") { ri = r; break; } } if (ri.isEmpty()) { QMessageBox::critical(nullptr, "", "No matching artifacts found."); return; } qDebug() << "fetching artifacts"; reply = net.get(QNetworkRequest(ri["artifacts_url"].toString())); await(reply); qDebug() << "fetch complete"; auto afx = QJsonDocument::fromJson(reply->readAll()).object()["artifacts"].toArray(); QJsonObject ai; foreach (const auto& av, afx) { auto a = av.toObject(); qDebug() << "artifact entry" << a["name"].toString(); if (a["name"] == ciArtifact) { ai = a; break; } } if (ai.isEmpty()) { QMessageBox::critical(nullptr, "", "No matching artifacts found."); return; } else { auto res = QMessageBox::question(nullptr, "", QString("Build #%1 (%2): %3").arg(ri["run_number"].toVariant().toString(), ri["head_sha"].toString().left(7), ri["display_title"].toString()), "Install", "Cancel"); qDebug() << "prompt returned" << res; if (res != 0) return; } qDebug() << "after prompt"; QDir cid(Config::openSBCIRoot); if (cid.exists()) { // nuke old installation files if they exist cid.removeRecursively(); } cid.mkpath("."); // make the directory exist (again) const auto fn = qs("_download.zip"); QFile f(cid.absoluteFilePath(fn)); f.open(QFile::WriteOnly); // we need to take a slight detour here; assemble our download url auto lnk = QString("https://nightly.link/OpenStarbound/OpenStarbound/suites/%1/artifacts/%2").arg(ri["check_suite_id"].toVariant().toString(), ai["id"].toVariant().toString()); QNetworkRequest req(lnk); // prepare for actual download req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); // allow redirects reply = net.get(req); QObject::connect(reply, &QNetworkReply::downloadProgress, &ev, [](auto c, auto t) { updateStatus(QString("Downloading... %1\%").arg(std::floor((double)c/(double)t*100 + 0.5))); }); QObject::connect(reply, &QNetworkReply::readyRead, &f, [&f, reply] {f.write(reply->readAll());}); await(reply); f.flush(); f.close(); // now we unzip this fucker updateStatus("Extracting package..."); QProcess ps; QObject::connect(&ps, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), &ev, &QEventLoop::quit); // windows: unzip > assets, win // linux: unzip, client.tar, client_distribution/[assets, linux] // why. QDir wd(cid.absolutePath()); // working dir #if defined(Q_OS_WIN) // oh boy, platform implementation time // extract using powershell, move everything in /win/ to /, remove /win/ ps.start("powershell", QStringList() << "Expand-Archive" << "-DestinationPath" << cid.absolutePath() << "-LiteralPath" << f.fileName()); ev.exec(); updateStatus(""); cid.rename("assets", "data"); // match release layout wd.cd("win"); foreach (auto fn, wd.entryList(QDir::Files)) { wd.rename(fn, cid.absoluteFilePath(fn)); } cid.rmdir("win"); // super easy #else // unix, probably linux // extract with unzip, untar, move assets out, move everything in linux to root, then nuke client_distribution // kind of annoying ps.start("unzip", QStringList() << f.fileName() << "-d" << cid.absolutePath()); ev.exec(); ps.start("tar", QStringList() << "-xf" << cid.absoluteFilePath("client.tar") << "-C" << cid.absolutePath()); ev.exec(); updateStatus(""); if (!wd.cd("client_distribution")) return; // download failed for some reason or another wd.rename("assets", cid.absoluteFilePath("data")); wd.cd("linux"); foreach (auto fi, wd.entryInfoList(QDir::Files)) { auto fn = fi.fileName(); auto ext = fi.suffix(); QFile ff(fi.absoluteFilePath()); if (ext == "" or ext == "sh") { // assume no extension is executable ff.setPermissions(ff.permissions() | QFile::ExeOwner | QFile::ExeGroup | QFile::ExeOther); } ff.rename(cid.absoluteFilePath(fn)); } // nuke leftovers wd.setPath(cid.absoluteFilePath("client_distribution")); if (wd.exists()) wd.removeRecursively(); cid.remove("client.tar"); // clean up internal subarchive #endif f.remove(); // clean up downloaded archive if (auto f = QFile(cid.absoluteFilePath("steam_appid.txt")); true) { // ensure appid file f.open(QFile::WriteOnly); f.write("211820"); f.flush(); f.close(); } // }
11,780
C++
.cpp
274
36.981752
218
0.650608
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,893
uitools.cpp
zetaPRIME_MultiBound2/multibound2/uitools.cpp
#include "uitools.h" #include <QEvent> #include <QMenu> using MultiBound::CheckableEventFilter; bool CheckableEventFilter::eventFilter(QObject* obj, QEvent* e) { if (e->type() == QEvent::MouseButtonRelease) { if (auto m = qobject_cast<QMenu*>(obj); m) { if (auto a = m->activeAction(); a && a->isCheckable()) { a->trigger(); return true; } } } return QObject::eventFilter(obj, e); }
471
C++
.cpp
15
24.533333
68
0.584071
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,894
config.cpp
zetaPRIME_MultiBound2/multibound2/data/config.cpp
#include "config.h" #include "util.h" #include <QDir> #include <QStandardPaths> #include <QCoreApplication> #include <QSettings> #include <QJsonDocument> #include <QJsonObject> #include <QCryptographicHash> #include <QDebug> QString MultiBound::Config::configPath; QString MultiBound::Config::instanceRoot; QString MultiBound::Config::workshopRoot; QString MultiBound::Config::steamcmdDLRoot; QString MultiBound::Config::steamcmdWorkshopRoot; QString MultiBound::Config::starboundPath; QString MultiBound::Config::starboundRoot; bool MultiBound::Config::steamcmdEnabled = true; bool MultiBound::Config::steamcmdUpdateSteamMods = true; bool MultiBound::Config::openSBEnabled = true; bool MultiBound::Config::openSBUseCIBuild = false; bool MultiBound::Config::openSBUseDevBranch = false; bool MultiBound::Config::openSBOffered = false; QString MultiBound::Config::openSBRoot; QString MultiBound::Config::openSBCIRoot; QString MultiBound::Config::openSBDevRoot; namespace { [[maybe_unused]] inline bool isX64() { return QSysInfo::currentCpuArchitecture().contains(QLatin1String("64")); } } void MultiBound::Config::load() { // defaults configPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation); // already has "multibound" attached #if defined(Q_OS_WIN) // same place as the exe on windows, like mb1 if (QDir(QCoreApplication::applicationDirPath()).exists("config.json")) configPath = QCoreApplication::applicationDirPath(); // find Steam path #if defined(Q_PROCESSOR_X86_64) QSettings sreg(R"(HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Valve\Steam)", QSettings::NativeFormat); QString steamPath = QDir::cleanPath(qs("C:/Program Files (x86)/Steam")); #else QSettings sreg(R"(HKEY_LOCAL_MACHINE\SOFTWARE\Valve\Steam)", QSettings::NativeFormat); QString steamPath = QDir::cleanPath(qs("C:/Program Files/Steam")); #endif if (auto ip = sreg.value("InstallPath"); ip.type() == QVariant::String && !ip.isNull()) steamPath = QDir::cleanPath(ip.toString()); if (isX64()) starboundPath = Util::splicePath(steamPath, "/SteamApps/common/Starbound/win64/starbound.exe"); else starboundPath = Util::splicePath(steamPath, "/SteamApps/common/Starbound/win32/starbound.exe"); #elif defined(Q_OS_MACOS) QDir home(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); starboundPath = Util::splicePath(home, "/Library/Application Support/Steam/steamapps/common/Starbound/osx/Starbound.app/Contents/MacOS/starbound"); #else QDir home(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); starboundPath = Util::splicePath(home, "/.steam/steam/steamapps/common/Starbound/linux/run-client.sh"); #endif if (auto d = QDir(configPath); !d.exists()) d.mkpath("."); instanceRoot = Util::splicePath(configPath, "/instances/"); openSBRoot = Util::splicePath(configPath, "/opensb/"); openSBCIRoot = Util::splicePath(configPath, "/opensb-ci/"); openSBDevRoot = Util::splicePath(configPath, "/opensb-dev/"); steamcmdDLRoot = configPath; QJsonObject cfg; if (QFile f(Util::splicePath(configPath, "/config.json")); f.exists()) { f.open(QFile::ReadOnly); cfg = QJsonDocument::fromJson(f.readAll()).object(); starboundPath = cfg["starboundPath"].toString(starboundPath); instanceRoot = cfg["instanceRoot"].toString(instanceRoot); steamcmdDLRoot = cfg["steamcmdRoot"].toString(steamcmdDLRoot); steamcmdUpdateSteamMods = cfg["steamcmdUpdateSteamMods"].toBool(steamcmdUpdateSteamMods); openSBEnabled = cfg["openSBEnabled"].toBool(openSBEnabled); openSBUseCIBuild = cfg["openSBUseCIBuild"].toBool(openSBUseCIBuild); openSBUseDevBranch = cfg["openSBUseDevBranch"].toBool(openSBUseDevBranch); openSBOffered = cfg["openSBOffered"].toBool(openSBOffered); } if (auto d = QDir(instanceRoot); !d.exists()) d.mkpath("."); QDir r(starboundPath); while (r.dirName().toLower() != "starbound" || !r.exists()) { auto old = r; r.cdUp(); if (r == old) break; } starboundRoot = QDir::cleanPath(r.absolutePath()); while (r.dirName().toLower() != "steamapps") { auto old = r; r.cdUp(); if (r == old) break; } if (auto rr = r.absolutePath(); rr.length() >= 10) workshopRoot = Util::splicePath(rr, "/workshop/content/211820/"); steamcmdWorkshopRoot = Util::splicePath(QDir(steamcmdDLRoot).absolutePath(), "/steamapps/workshop/content/211820/"); verify(); } void MultiBound::Config::verify() { // stub } void MultiBound::Config::save() { verify(); QJsonObject cfg; cfg["starboundPath"] = starboundPath; cfg["instanceRoot"] = instanceRoot; cfg["steamcmdRoot"] = steamcmdDLRoot; cfg["steamcmdUpdateSteamMods"] = steamcmdUpdateSteamMods; cfg["openSBEnabled"] = openSBEnabled; cfg["openSBUseCIBuild"] = openSBUseCIBuild; cfg["openSBUseDevBranch"] = openSBUseDevBranch; cfg["openSBOffered"] = openSBOffered; QFile f(Util::splicePath(configPath, "/config.json")); f.open(QFile::WriteOnly); f.write(QJsonDocument(cfg).toJson()); }
5,105
C++
.cpp
100
46.96
151
0.735932
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,895
instance.cpp
zetaPRIME_MultiBound2/multibound2/data/instance.cpp
#include "instance.h" using MultiBound::Instance; #include "data/config.h" #include "util.h" #include <QDebug> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QDir> #include <QFile> #include <QSet> #include <QProcess> QString Instance::displayName() { return json["info"].toObject()["name"].toString(path); } QString Instance::workshopId() { auto info = json["info"].toObject(); auto id = info["workshopId"].toString(); if (id.isEmpty()) id = Util::workshopIdFromLink(info["workshopLink"].toString()); return id; } QString Instance::evaluatePath(const QString& p) { auto f = QString::SectionSkipEmpty; auto pfx = p.section(':', 0, 0, f); auto body = p.section(':', 1, -1, f); if (pfx == "sb") return Util::splicePath(Config::starboundRoot, body); else if (pfx == "ws" || pfx == "workshop") { if (auto s = Util::splicePath(Config::workshopRoot, body); QDir(s).exists()) return s; return Util::splicePath(Config::steamcmdWorkshopRoot, body); } else if (pfx == "inst") return Util::splicePath(path, body); return QDir::cleanPath(p); } bool Instance::load() { QDir d(path); if (!d.exists("instance.json")) return false; json = Util::loadJson(d.absoluteFilePath("instance.json")).object(); return true; } bool Instance::save() { QDir(path).mkpath("."); QFile f(QDir(path).absoluteFilePath("instance.json")); f.open(QFile::WriteOnly); f.write(QJsonDocument(json).toJson()); return true; } bool Instance::launch() { // determine path ahead of time QString sbinitPath = Util::splicePath(Config::configPath, "_init.config"); // and some logic for switching to OpenSB #if defined(Q_OS_WIN) const auto osbBinary = qs("starbound.exe"); #else const auto osbBinary = qs("starbound"); #endif bool useOSB = Config::openSBEnabled; auto osbRoot = Config::openSBRoot; if (Config::openSBUseCIBuild && QDir(Config::openSBCIRoot).exists(osbBinary)) osbRoot = Config::openSBCIRoot; if (Config::openSBUseDevBranch && QDir(Config::openSBDevRoot).exists(osbBinary)) osbRoot = Config::openSBDevRoot; if (!QDir(osbRoot).exists(osbBinary)) useOSB = false; { // construct sbinit QJsonObject sbinit; auto extCfg = json["extCfg"].toObject(); // extra config from steam workshop collections // assemble default configuration QJsonObject defaultCfg; defaultCfg["gameServerBind"] = "*"; defaultCfg["queryServerBind"] = "*"; defaultCfg["rconServerBind"] = "*"; defaultCfg["allowAssetsMismatch"] = true; defaultCfg["maxTeamSize"] = 64; // more than you'll ever need, because why is there even a limit!? if (auto server = extCfg["defaultServer"].toString(); !server.isEmpty()) { QJsonObject ts; constexpr auto f = QString::SectionSkipEmpty; ts["multiPlayerAddress"] = server.section(':', 0, 0, f); ts["multiPlayerPort"] = server.section(':', 1, 1, f); defaultCfg["title"] = ts; } sbinit["defaultConfiguration"] = defaultCfg; sbinit["includeUGC"] = false; // openSB: don't pull in everything from Steam // storage directory if (auto s = json["savePath"]; s.isString()) sbinit["storageDirectory"] = evaluatePath(s.toString()); else sbinit["storageDirectory"] = evaluatePath("inst:/storage/"); // and put together asset list QJsonArray assets; assets.append(evaluatePath("sb:/assets/")); if (useOSB) { assets.append(Util::splicePath(osbRoot, "/data/")); } QSet<QString> workshop; QSet<QString> workshopExclude; auto sources = json["assetSources"].toArray(); for (auto s : sources) { if (s.isString()) assets.append(evaluatePath(s.toString())); else if (s.isObject()) { auto src = s.toObject(); auto type = src["type"].toString(); if (type == "mod") { if (auto p = src["path"]; p.isString()) assets.append(evaluatePath(p.toString())); else if (auto id = src["workshopId"]; id.isString()) workshop.insert(id.toString()); } else if (type == "workshopAuto") { if (auto id = src["id"]; id.isString()) workshop.insert(id.toString()); } else if (type == "workshopExclude") { if (auto id = src["id"]; id.isString()) workshopExclude.insert(id.toString()); } } } for (auto& id : workshop) if (!workshopExclude.contains(id)) assets.append(evaluatePath(qs("workshop:/") + id)); sbinit["assetDirectories"] = assets; // write to disk QFile f(sbinitPath); f.open(QFile::WriteOnly); f.write(QJsonDocument(sbinit).toJson()); } // then launch... QStringList param; param << "-bootconfig" << QDir::toNativeSeparators(sbinitPath); QProcess sb; QDir wp(Config::starboundPath); wp.cdUp(); sb.setWorkingDirectory(wp.absolutePath()); auto exec = Config::starboundPath; if (useOSB) { QDir d(osbRoot); sb.setWorkingDirectory(d.absolutePath()); exec = d.absoluteFilePath(osbBinary); } sb.start(exec, param); sb.waitForFinished(-1); qDebug() << sb.errorString(); return true; } std::shared_ptr<Instance> Instance::loadFrom(const QString& path) { QString ipath; if (QDir(path).isAbsolute()) ipath = path; else ipath = Util::splicePath(Config::instanceRoot, path); if (!QDir(ipath).exists("instance.json")) return nullptr; auto inst = std::make_shared<Instance>(); inst->path = ipath; if (!inst->load()) return nullptr; return inst; }
5,838
C++
.cpp
141
34.432624
120
0.628995
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,896
util.h
zetaPRIME_MultiBound2/multibound2/util.h
#pragma once #include <functional> #include <QString> #include <QDir> #define qs QStringLiteral class QJsonDocument; namespace MultiBound { class Instance; namespace Util { const extern QString version; inline QString splicePath(const QString& p1, const QString& p2) { return QDir::cleanPath(qs("%1/%2").arg(p1, p2)); } inline QString splicePath(const QDir& d, const QString& p) { return splicePath(d.absolutePath(), p); } QJsonDocument loadJson(const QString& path); QJsonDocument parseJson(const QByteArray data); inline QString workshopLinkFromId(const QString& id) { return qs("https://steamcommunity.com/sharedfiles/filedetails/?id=%1").arg(id); } inline QString workshopIdFromLink(const QString& link) { constexpr auto f = QString::SectionSkipEmpty; return link.section("id=", 1, 1, f).section('&', 0, 0, f); // extract only id parameter } void updateFromWorkshop(Instance*, bool save = true); bool initSteamCmd(); void updateMods(Instance*); extern std::function<void(QString)> updateStatus; // update checking for MultiBound itself void checkForUpdates(); // OpenStarbound integration void openSBCheckForUpdates(); void openSBUpdate(); void openSBUpdateCI(); } }
1,363
C++
.h
31
36.774194
144
0.67803
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,897
mainwindow.h
zetaPRIME_MultiBound2/multibound2/mainwindow.h
#pragma once #include <QMainWindow> #include <QPointer> #include <memory> #include <vector> class QListWidgetItem; namespace MultiBound { namespace Ui { class MainWindow; } class Instance; class MainWindow : public QMainWindow { Q_OBJECT public: static QPointer<MainWindow> instance; std::vector<std::shared_ptr<Instance>> instances; explicit MainWindow(QWidget* parent = nullptr); ~MainWindow(); void showEvent(QShowEvent*) override; bool isInteractive(); void setInteractive(bool); void checkUpdates(bool osbOnly = false); void updateCIBuild(); void refresh(const QString& focusPath = { }); void launch(Instance* inst = nullptr); void updateFromWorkshop(Instance* inst = nullptr); void newFromWorkshop(const QString& = { }); Instance* selectedInstance(); Instance* findWorkshopId(const QString&); private: Ui::MainWindow *ui; signals: void refreshSettings(); }; }
1,054
C++
.h
33
25.242424
58
0.663682
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,898
settingswindow.h
zetaPRIME_MultiBound2/multibound2/settingswindow.h
#pragma once #include <QDialog> #include <QPointer> namespace MultiBound { namespace Ui { class SettingsWindow; } class SettingsWindow : public QDialog { Q_OBJECT public: static QPointer<SettingsWindow> instance; explicit SettingsWindow(QWidget *parent = nullptr); ~SettingsWindow(); private: Ui::SettingsWindow *ui; void apply(); }; }
412
C++
.h
16
20
59
0.667526
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,900
instance.h
zetaPRIME_MultiBound2/multibound2/data/instance.h
#pragma once #include <memory> #include <QJsonObject> namespace MultiBound { class Instance { // public: QString path; QJsonObject json; Instance() = default; ~Instance() = default; QString displayName(); QString workshopId(); QString evaluatePath(const QString&); bool load(); bool save(); bool launch(); // statics static std::shared_ptr<Instance> loadFrom(const QString& path); }; }
511
C++
.h
21
17.380952
71
0.590437
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,901
config.h
zetaPRIME_MultiBound2/multibound2/data/config.h
#pragma once #include <QString> namespace MultiBound { namespace Config { extern QString configPath; extern QString instanceRoot; extern QString starboundPath; extern QString starboundRoot; extern QString workshopRoot; extern QString steamcmdDLRoot; extern QString steamcmdWorkshopRoot; extern bool steamcmdEnabled; extern bool steamcmdUpdateSteamMods; extern bool openSBEnabled; extern bool openSBUseCIBuild; extern bool openSBUseDevBranch; extern bool openSBOffered; extern QString openSBRoot; extern QString openSBCIRoot; extern QString openSBDevRoot; // void load(); void verify(); void save(); } }
779
C++
.h
26
22.192308
44
0.672483
zetaPRIME/MultiBound2
33
3
6
LGPL-2.1
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,902
MetricAddS.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/MetricAddS.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <MetricAddS.h> #include <PointCloudAdaptor.h> #include <kdTree.h> #include <memory> using namespace Eigen; using namespace nanoflann; MetricAddS::MetricAddS() { } MetricAddS::~MetricAddS() { } VectorXd MetricAddS::evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) { VectorXd values(1); if (((estimate.translation()(0) == std::numeric_limits<double>::infinity()) && (estimate.translation()(1) == std::numeric_limits<double>::infinity()) && (estimate.translation()(2) == std::numeric_limits<double>::infinity())) || ((estimate.translation()(0) == 0.0) && (estimate.translation()(1) == 0.0) && (estimate.translation()(2) == 0.0))) { // Warning: this check is required since some DenseFusion frames might be missing. // When missing, they are identified as having an infinite estimate or all zeros // In such cases, they are assigned with an infinite error as per the code // that can be found here https://github.com/j96w/DenseFusion/blob/master/replace_ycb_toolbox/evaluate_poses_keyframe.m values(0) = std::numeric_limits<double>::infinity(); return values; } /* Evaluate model in estimated pose. */ MatrixXd estimated_model = estimate * model.colwise().homogeneous(); /* Evaluate model in ground truth pose. */ MatrixXd ground_truth_model = ground_truth * model.colwise().homogeneous(); /* Evaluate ADD-S metric. */ MatrixXd estimated_model_symmetric(estimated_model.rows(), estimated_model.cols()); std::unique_ptr<PointCloudAdaptor> adapted_cloud = std::unique_ptr<PointCloudAdaptor>(new PointCloudAdaptor(estimated_model)); std::unique_ptr<kdTree> tree = std::unique_ptr<kdTree>(new kdTree(3 /* dim */, *adapted_cloud, KDTreeSingleIndexAdaptorParams(10 /* max leaf */))); tree->buildIndex(); /* Evaluate closest points using a kdtree. */ for (std::size_t i = 0; i < ground_truth_model.cols(); i++) { const Ref<const Vector3d> gt_i = ground_truth_model.col(i); std::size_t ret_index; double out_dist_sqr; KNNResultSet<double> resultSet(1); resultSet.init(&ret_index, &out_dist_sqr); tree->findNeighbors(resultSet, gt_i.data(), nanoflann::SearchParams(10)); estimated_model_symmetric.col(i) = estimated_model.col(ret_index); } MatrixXd difference = ground_truth_model - estimated_model_symmetric; values(0) = difference.colwise().norm().sum() / difference.cols(); return values; }
2,861
C++
.cpp
57
44.736842
183
0.687028
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,903
main.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/main.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <ObjectResults.h> #include <Eigen/Dense> #include <fstream> #include <iostream> #include <memory> #include <string> #include <vector> using namespace Eigen; std::pair<bool, std::unordered_map<std::string, std::vector<std::size_t>>> loadKeyframes(const std::string& filename); int main(int argc, char** argv) { if ((argc != 5) && (argc != 6)) { std::cout << "Synopsis: validation <metric> <results_path> <models_path> <use_key_frames> <keyframes_path>" << std::endl; exit(EXIT_FAILURE); } const std::string metric = std::string(argv[1]); const std::string result_path = std::string(argv[2]); const std::string models_path = std::string(argv[3]); const bool use_keyframes = (std::string(argv[4]) == "true"); std::string keyframes_path; if (use_keyframes) keyframes_path = std::string(argv[5]); const double max_error = 0.02; /* Metrics. */ const std::vector<std::string> metrics {metric}; /* Keyframes. */ bool valid_keyframes = false; std::unordered_map<std::string, std::vector<std::size_t>> keyframes; if (use_keyframes) std::tie(valid_keyframes, keyframes) = loadKeyframes(keyframes_path); if (use_keyframes && (!valid_keyframes)) { std::cout << "Cannot load keyframes file." << std::endl; exit(EXIT_FAILURE); } std::unordered_map<std::string, std::pair<std::size_t, std::size_t>> skipped_frames_placeholder; /* Dictionary. */ std::vector<std::string> keys = {"002_master_chef_can", "003_cracker_box", "004_sugar_box", "005_tomato_soup_can", "006_mustard_bottle", "007_tuna_fish_can", "008_pudding_box", "009_gelatin_box", "010_potted_meat_can", "011_banana", "019_pitcher_base", "021_bleach_cleanser", "024_bowl", "025_mug", "035_power_drill", "036_wood_block", "037_scissors", "040_large_marker", "051_large_clamp", "052_extra_large_clamp", "061_foam_brick"}; std::unordered_map<std::string, std::vector<std::string>> objects_videos; objects_videos["002_master_chef_can"] = std::vector<std::string>({"0048", "0051", "0055", "0056"}); objects_videos["003_cracker_box"] = std::vector<std::string>({"0050", "0054", "0059"}); objects_videos["004_sugar_box"] = std::vector<std::string>({"0049", "0051", "0054", "0055", "0058"}); objects_videos["005_tomato_soup_can"] = std::vector<std::string>({"0050", "0051", "0053", "0055", "0057", "0059"}); objects_videos["006_mustard_bottle"] = std::vector<std::string>({"0050", "0052"}); objects_videos["007_tuna_fish_can"] = std::vector<std::string>({"0048", "0049", "0052", "0059"}); objects_videos["008_pudding_box"] = std::vector<std::string>({"0058"}); objects_videos["009_gelatin_box"] = std::vector<std::string>({"0058"}); objects_videos["010_potted_meat_can"] = std::vector<std::string>({"0049", "0053", "0059"}); objects_videos["011_banana"] = std::vector<std::string>({"0050", "0056"}); objects_videos["019_pitcher_base"] = std::vector<std::string>({"0052", "0056", "0058"}); objects_videos["021_bleach_cleanser"] = std::vector<std::string>({"0051", "0054", "0055", "0057"}); objects_videos["024_bowl"] = std::vector<std::string>({"0049", "0053"}); objects_videos["025_mug"] = std::vector<std::string>({"0048", "0055"}); objects_videos["035_power_drill"] = std::vector<std::string>({"0050", "0054", "0056", "0059"}); objects_videos["036_wood_block"] = std::vector<std::string>({"0055"}); objects_videos["037_scissors"] = std::vector<std::string>({"0051"}); objects_videos["040_large_marker"] = std::vector<std::string>({"0057", "0059"}); objects_videos["051_large_clamp"] = std::vector<std::string>({"0048", "0054"}); objects_videos["052_extra_large_clamp"] = std::vector<std::string>({"0048", "0057"}); objects_videos["061_foam_brick"] = std::vector<std::string>({"0057"}); std::unordered_map<std::string, bool> objects_symmetry; objects_symmetry["002_master_chef_can"] = true; objects_symmetry["003_cracker_box"] = false; objects_symmetry["004_sugar_box"] = false; objects_symmetry["005_tomato_soup_can"] = true; objects_symmetry["006_mustard_bottle"] = false; objects_symmetry["007_tuna_fish_can"] = true; objects_symmetry["008_pudding_box"] = false; objects_symmetry["009_gelatin_box"] = false; objects_symmetry["010_potted_meat_can"] = false; objects_symmetry["011_banana"] = false; objects_symmetry["019_pitcher_base"] = false; objects_symmetry["021_bleach_cleanser"] = false; objects_symmetry["024_bowl"] = true; objects_symmetry["025_mug"] = false; objects_symmetry["035_power_drill"] = false; objects_symmetry["036_wood_block"] = true; objects_symmetry["037_scissors"] = false; objects_symmetry["040_large_marker"] = true; objects_symmetry["051_large_clamp"] = true; objects_symmetry["052_extra_large_clamp"] = true; objects_symmetry["061_foam_brick"] = false; std::unordered_map<std::string, Eigen::Vector3d> objects_symmetry_axes; objects_symmetry_axes["002_master_chef_can"] = Vector3d::UnitZ(); objects_symmetry_axes["003_cracker_box"] = Vector3d::Zero(); objects_symmetry_axes["004_sugar_box"] = Vector3d::Zero(); objects_symmetry_axes["005_tomato_soup_can"] = Vector3d::UnitZ(); objects_symmetry_axes["006_mustard_bottle"] = Vector3d::Zero(); objects_symmetry_axes["007_tuna_fish_can"] = Vector3d::UnitZ(); objects_symmetry_axes["008_pudding_box"] = Vector3d::Zero(); objects_symmetry_axes["009_gelatin_box"] = Vector3d::Zero(); objects_symmetry_axes["010_potted_meat_can"] = Vector3d::Zero(); objects_symmetry_axes["011_banana"] = Vector3d::Zero(); objects_symmetry_axes["019_pitcher_base"] = Vector3d::Zero(); objects_symmetry_axes["021_bleach_cleanser"] = Vector3d::Zero(); objects_symmetry_axes["024_bowl"] = Vector3d::UnitZ(); objects_symmetry_axes["025_mug"] = Vector3d::Zero(); objects_symmetry_axes["035_power_drill"] = Vector3d::Zero(); objects_symmetry_axes["036_wood_block"] = Vector3d::UnitZ(); objects_symmetry_axes["037_scissors"] = Vector3d::Zero(); objects_symmetry_axes["040_large_marker"] = Vector3d::UnitY(); objects_symmetry_axes["051_large_clamp"] = Vector3d::UnitY(); objects_symmetry_axes["052_extra_large_clamp"] = Vector3d::UnitX(); objects_symmetry_axes["061_foam_brick"] = Vector3d::Zero(); std::vector<std::unique_ptr<const ObjectResults>> objects_results(keys.size()); if (use_keyframes) for (std::size_t i = 0; i < keys.size(); i++) objects_results[i] = std::unique_ptr<ObjectResults>(new ObjectResults(keys[i], objects_symmetry[keys[i]], objects_symmetry_axes[keys[i]], models_path, result_path, objects_videos[keys[i]], keyframes, skipped_frames_placeholder, metrics, max_error)); else for (std::size_t i = 0; i < keys.size(); i++) objects_results[i] = std::unique_ptr<ObjectResults>(new ObjectResults(keys[i], objects_symmetry[keys[i]], objects_symmetry_axes[keys[i]], models_path, result_path, objects_videos[keys[i]], 1, metrics, max_error)); ObjectResults (objects_results, metrics, max_error); return EXIT_SUCCESS; } std::pair<bool, std::unordered_map<std::string, std::vector<std::size_t>>> loadKeyframes(const std::string& filename) { std::unordered_map<std::string, std::vector<std::size_t>> keyframes; std::ifstream in(filename); if (!in.is_open()) { std::cout << "loadKeyframes. Failed to open " << filename << '\n'; return std::make_pair(false, keyframes); } std::string line; while (std::getline(in, line)) { std::istringstream line_stream(line); std::vector<std::string> split; std::string item; while (getline(line_stream, item, '/')) split.push_back(item); std::stringstream sstream(split.at(1)); size_t frame_number; sstream >> frame_number; keyframes[split.at(0)].push_back(frame_number); } return std::make_pair(true, keyframes); }
9,065
C++
.cpp
155
51.064516
261
0.602004
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,904
MetricRMSSymmetry.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/MetricRMSSymmetry.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <MetricRMSSymmetry.h> #include <limits> using namespace Eigen; MetricRMSSymmetry::MetricRMSSymmetry(const Eigen::VectorXd& symmetry_axis) : symmetry_axis_(symmetry_axis) { } MetricRMSSymmetry::~MetricRMSSymmetry() { } VectorXd MetricRMSSymmetry::evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) { VectorXd errors(2); if (((estimate.translation()(0) == std::numeric_limits<double>::infinity()) && (estimate.translation()(1) == std::numeric_limits<double>::infinity()) && (estimate.translation()(2) == std::numeric_limits<double>::infinity())) || ((estimate.translation()(0) == 0.0) && (estimate.translation()(1) == 0.0) && (estimate.translation()(2) == 0.0))) { // Warning: this check is required since some DenseFusion frames might be missing. // When missing, they are identified as having an infinite estimate or all zeros // In such cases, we decided to assign a null error for the evaluation of the RMSE errors(0) = 0.0; errors(1) = 0.0; return errors; } errors(0) = (estimate.translation() - ground_truth.translation()).squaredNorm(); // Use twist-swing decomposition to extract the relevant rotation taking into account the symmetry axis AngleAxisd twist; AngleAxisd swing; std::tie(twist, swing) = twistSwingDecomposition(AngleAxisd((estimate.rotation().transpose() * ground_truth.rotation())), symmetry_axis_); errors(1) = std::pow(swing.angle(), 2); return errors; } std::pair<Eigen::AngleAxisd, Eigen::AngleAxisd> MetricRMSSymmetry::twistSwingDecomposition(const Eigen::AngleAxisd& rotation, const Vector3d& twist_axis) { // Find twist-swing decomposition according to // https://www.gamedev.net/forums/topic/696882-swing-twist-interpolation-sterp-an-alternative-to-slerp/ // Convert rotation to a quaternion Quaterniond q(rotation); // Resulting rotations AngleAxisd swing; AngleAxisd twist; // Handle singularity (rotation by 180 degree) Vector3d q_vector(q.x(), q.y(), q.z()); if (q_vector.squaredNorm() < std::numeric_limits<double>::min()) { // Vector3 rotatedTwistAxis = q * twistAxis; Vector3d rotated_twist_axis = q.toRotationMatrix() * twist_axis; Vector3d swing_axis = twist_axis.cross(rotated_twist_axis); if (swing_axis.squaredNorm() > std::numeric_limits<double>::min()) { double swing_angle = std::acos(twist_axis.normalized().dot(swing_axis.normalized())); swing = AngleAxisd(swing_angle, swing_axis); } else { // More singularity: rotation axis parallel to twist axis swing = AngleAxisd(Transform<double, 3, Affine>::Identity().rotation()); } // always twist 180 degree on singularity twist = AngleAxisd(M_PI, twist_axis); return std::make_pair(twist, swing); } // General case Vector3d projection = twist_axis * q_vector.dot(twist_axis); Quaterniond twist_q(q.w(), projection(0), projection(1), projection(2)); twist_q.normalize(); Quaterniond swing_q = q * twist_q.inverse(); return std::make_pair(AngleAxisd(twist_q), AngleAxisd(swing_q)); }
3,581
C++
.cpp
76
41.065789
190
0.679782
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,905
Metric.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/Metric.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <Metric.h> using namespace Eigen; Metric::Metric() { } Metric::~Metric() { } Eigen::VectorXd Metric::evaluate(const Eigen::VectorXd& estimate, const Eigen::VectorXd& ground_truth, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth_pose) { return VectorXd(); }
501
C++
.cpp
16
29.25
171
0.748428
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,906
MetricEmpty.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/MetricEmpty.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <MetricEmpty.h> using namespace Eigen; MetricEmpty::MetricEmpty() { } MetricEmpty::~MetricEmpty() { } VectorXd MetricEmpty::evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) { return VectorXd(); }
539
C++
.cpp
16
31.625
184
0.759223
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,907
MetricRMS.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/MetricRMS.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <MetricRMS.h> using namespace Eigen; MetricRMS::MetricRMS() { } MetricRMS::~MetricRMS() { } VectorXd MetricRMS::evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) { VectorXd errors(2); if (((estimate.translation()(0) == std::numeric_limits<double>::infinity()) && (estimate.translation()(1) == std::numeric_limits<double>::infinity()) && (estimate.translation()(2) == std::numeric_limits<double>::infinity())) || ((estimate.translation()(0) == 0.0) && (estimate.translation()(1) == 0.0) && (estimate.translation()(2) == 0.0))) { // Warning: this check is required since some DenseFusion frames might be missing. // When missing, they are identified as having an infinite estimate or all zeros // In such cases, we decided to assign a null error for the evaluation of the RMSE errors(0) = 0.0; errors(1) = 0.0; return errors; } errors(0) = (estimate.translation() - ground_truth.translation()).squaredNorm(); errors(1) = std::pow(AngleAxisd((estimate.rotation().transpose() * ground_truth.rotation())).angle(), 2); return errors; }
1,492
C++
.cpp
33
40.060606
182
0.666897
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,908
ObjectResults.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/ObjectResults.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <MetricAddS.h> #include <MetricEmpty.h> #include <MetricRMS.h> #include <MetricRMSSymmetry.h> #include <ObjectResults.h> #include <fstream> #include <iostream> #include <iomanip> #include <fstream> using namespace Eigen; ObjectResults::ObjectResults ( const std::string& object_name, const bool& object_has_symmetry, const Eigen::Vector3d& object_symmetry_axis, const std::string& model_path, const std::string& result_path, const std::vector<std::string>& test_set, const std::unordered_map<std::string, std::vector<std::size_t>>& keyframes, const std::unordered_map<std::string, std::pair<std::size_t, std::size_t>>& excluded_keyframes, const std::vector<std::string>& metrics, const double& max_error ) { MatrixXd model; bool valid_model = false; std::tie(valid_model, model) = loadPointCloudFromFile(model_path + "/" + object_name); if (!valid_model) throw(std::runtime_error("[main] Cannot load model of object " + object_name)); for (auto name : metrics) { std::string metric_name = name; if ((metric_name == "RMSSymmetry") && (!object_has_symmetry)) metric_name = "RMS"; if (metric_name == "ADD-S") metric_.emplace(metric_name, std::unique_ptr<MetricAddS>(new MetricAddS())); else if (metric_name == "RMS") metric_.emplace(metric_name, std::unique_ptr<MetricRMS>(new MetricRMS())); else if (metric_name == "RMSSymmetry") metric_.emplace(metric_name, std::unique_ptr<MetricRMSSymmetry>(new MetricRMSSymmetry(object_symmetry_axis))); else if (metric_name == "FPS") metric_.emplace(metric_name, std::unique_ptr<MetricEmpty>(new MetricEmpty())); else throw(std::runtime_error(log_ID_ + "::ctor. Error: cannot load requested metric " + name + ".")); } for (auto video_name : test_set) results_.emplace(video_name, SingleVideoResult(object_name, video_name, result_path)); std::cout << log_ID_ << "::ctor. Object name: " << object_name << std::endl; for (auto& metric_item : metric_) { counter_ = 0; std::size_t counter_good = 0; rmse_position_ = 0; rmse_orientation_ = 0; fps_ = 0; std::unordered_map<std::string, double> partials_ratio; std::unordered_map<std::string, double> partials_auc; std::unordered_map<std::string, double> partials_rmse_position; std::unordered_map<std::string, double> partials_rmse_orientation; std::unordered_map<std::string, double> partials_fps; for (auto video_name : test_set) { std::size_t counter_part = 0; std::size_t counter_good_part = 0; std::vector<double> errors_part; double rmse_position_part = 0; double rmse_orientation_part = 0; double fps_part = 0; SingleVideoResult& video_results = results_.at(video_name); for (auto keyframe : keyframes.at(video_name)) { std::size_t excluded_keyframes_range_left = 0; std::size_t excluded_keyframes_range_right = 0; if (excluded_keyframes.find(video_name) != excluded_keyframes.end()) { excluded_keyframes_range_left = excluded_keyframes.at(video_name).first; excluded_keyframes_range_right = excluded_keyframes.at(video_name).second; } if (excluded_keyframes_range_left <= keyframe && keyframe <= excluded_keyframes_range_right) continue; Transform<double, 3, Affine> gt_pose = video_results.getGroundTruthPose(keyframe); Transform<double, 3, Affine> est_pose = video_results.getObjectPose(keyframe); VectorXd error = metric_item.second->evaluate(est_pose, gt_pose, model); if (metric_item.first == "ADD-S") { // Storage for evaluation of AUC errors_.push_back(error(0)); errors_part.push_back(error(0)); // // Evaluation of the percentage of metric, i.e. ADD, ADD-S, smaller than max error if (error(0) < max_error) { counter_good++; counter_good_part++; } // } else if((metric_item.first == "RMS") || (metric_item.first == "RMSSymmetry")) { // RMSE rmse_position_ += error(0); rmse_orientation_ += error(1); rmse_position_part += error(0); rmse_orientation_part += error(1); // } else if (metric_item.first == "FPS") { fps_ += video_results.getFPS(keyframe); fps_part += video_results.getFPS(keyframe); } counter_++; counter_part++; } if (metric_item.first == "ADD-S") { partials_ratio[video_name] = double(counter_good_part) / double(counter_part); partials_auc[video_name] = evaluateAUC(errors_part, 0.1); } else if((metric_item.first == "RMS") || (metric_item.first == "RMSSymmetry")) { partials_rmse_position[video_name] = std::sqrt(rmse_position_part / double(counter_part)); partials_rmse_orientation[video_name] = std::sqrt(rmse_orientation_part / double(counter_part)); } else if(metric_item.first == "FPS") { partials_fps[video_name] = fps_part / double(counter_part); } } if (metric_item.first == "ADD-S") { // Print percentage < max_error std::cout << "% < " << max_error << "(" << metric_item.first << ") : " << double(counter_good) / double(counter_) * 100.0 << " "; map_add_s_less_[object_name] = double(counter_good) / double(counter_) * 100.0; std::cout << "{"; for (auto partial : partials_ratio) std::cout << partial.first << ": " << partial.second * 100.0 << " "; std::cout << "}" << std::endl; // Print AUC (0.1 m) double auc = evaluateAUC(errors_, 0.1) * 100.0; std::cout << "AUC (0.1 m) (" << metric_item.first << ") : " << auc << " "; map_add_s_auc_[object_name] = auc; std::cout << "{"; for (auto partial : partials_auc) std::cout << partial.first << ": " << partial.second * 100.0 << " "; std::cout << "}" << std::endl; } else if((metric_item.first == "RMS") || (metric_item.first == "RMSSymmetry")) { std::cout << "RMSE (position): " << std::setprecision(3) << std::sqrt(rmse_position_ / double(counter_)) * 100.0 << " "; map_rmse_position_[object_name] = std::sqrt(rmse_position_ / double(counter_)) * 100.0; std::cout << "{"; for (auto partial : partials_rmse_position) std::cout << partial.first << ": " << std::setprecision(3) << partial.second * 100.0 << " "; std::cout << "}" << std::endl; std::cout << "RMSE (orientation): " << std::setprecision(3) << std::sqrt(rmse_orientation_ / double(counter_)) * 180.0 / M_PI << " "; map_rmse_orientation_[object_name] = std::sqrt(rmse_orientation_ / double(counter_)) * 180.0 / M_PI; std::cout << "{"; for (auto partial : partials_rmse_orientation) std::cout << partial.first << ": " << std::setprecision(3) << partial.second * 180.0 / M_PI << " "; std::cout << "}" << std::endl; } else if(metric_item.first == "FPS") { std::cout << "FPS: " << std::setprecision(3) << fps_ / double(counter_) << " "; std::cout << "{"; for (auto partial : partials_fps) std::cout << partial.first << ": " << std::setprecision(3) << partial.second << " "; std::cout << "}" << std::endl; } std::cout << std::endl; } } ObjectResults::ObjectResults ( const std::string& object_name, const bool& object_has_symmetry, const Eigen::Vector3d& object_symmetry_axis, const std::string& model_path, const std::string& result_path, const std::vector<std::string>& test_set, const std::size_t skip_frames, const std::vector<std::string>& metrics, const double& max_error ) { MatrixXd model; bool valid_model = false; std::tie(valid_model, model) = loadPointCloudFromFile(model_path + object_name); if (!valid_model) throw(std::runtime_error("[main] Cannot load model of object " + object_name)); for (auto name : metrics) { std::string metric_name = name; if ((metric_name == "RMSSymmetry") && (!object_has_symmetry)) metric_name = "RMS"; if (metric_name == "ADD-S") metric_.emplace(metric_name, std::unique_ptr<MetricAddS>(new MetricAddS())); else if (metric_name == "RMS") metric_.emplace(metric_name, std::unique_ptr<MetricRMS>(new MetricRMS())); else if (metric_name == "RMSSymmetry") metric_.emplace(metric_name, std::unique_ptr<MetricRMSSymmetry>(new MetricRMSSymmetry(object_symmetry_axis))); else if (metric_name == "FPS") metric_.emplace(metric_name, std::unique_ptr<MetricEmpty>(new MetricEmpty())); else throw(std::runtime_error(log_ID_ + "::ctor. Error: cannot load requested metric " + name + ".")); } for (auto video_name : test_set) results_.emplace(video_name, SingleVideoResult(object_name, video_name, result_path)); std::cout << log_ID_ << "::ctor. Object name: " << object_name << std::endl; for (auto& metric_item : metric_) { counter_ = 0; std::size_t counter_good = 0; rmse_position_ = 0; rmse_orientation_ = 0; fps_ = 0; std::unordered_map<std::string, double> partials_ratio; std::unordered_map<std::string, double> partials_auc; std::unordered_map<std::string, double> partials_rmse_position; std::unordered_map<std::string, double> partials_rmse_orientation; std::unordered_map<std::string, double> partials_fps; for (auto video_name : test_set) { std::size_t counter_part = 0; std::size_t counter_good_part = 0; std::vector<double> errors_part; double rmse_position_part = 0; double rmse_orientation_part = 0; double fps_part = 0; SingleVideoResult& video_results = results_.at(video_name); for (std::size_t frame = 1 + skip_frames; frame <= video_results.getNumberFrames(); frame++) { Transform<double, 3, Affine> gt_pose = video_results.getGroundTruthPose(frame); Transform<double, 3, Affine> est_pose = video_results.getObjectPose(frame); VectorXd error; error = metric_item.second->evaluate(est_pose, gt_pose, model); if (metric_item.first == "ADD-S") { // Storage for evaluation of AUC errors_.push_back(error(0)); errors_part.push_back(error(0)); // // Evaluation of the percentage of metric, i.e. ADD, ADD-S, smaller than max error if (error(0) < max_error) { counter_good++; counter_good_part++; } // } else if((metric_item.first == "RMS") || (metric_item.first == "RMSSymmetry")) { // RMSE rmse_position_ += error(0); rmse_orientation_ += error(1); rmse_position_part += error(0); rmse_orientation_part += error(1); // } else if(metric_item.first == "FPS") { fps_ += video_results.getFPS(frame); fps_part += video_results.getFPS(frame); } counter_++; counter_part++; } if ((metric_item.first == "ADD") || (metric_item.first == "ADD-S")) { partials_ratio[video_name] = double(counter_good_part) / double(counter_part); partials_auc[video_name] = evaluateAUC(errors_part, 0.1); } else if((metric_item.first == "RMS") || (metric_item.first == "RMSSymmetry")) { partials_rmse_position[video_name] = std::sqrt(rmse_position_part / double(counter_part)); partials_rmse_orientation[video_name] = std::sqrt(rmse_orientation_part / double(counter_part)); } else if(metric_item.first == "FPS") { partials_fps[video_name] = fps_part / double(counter_part); } } if (metric_item.first == "ADD-S") { // Print percentage < max_error std::cout << "% < " << max_error << "(" << metric_item.first << ") : " << double(counter_good) / double(counter_) * 100.0 << " "; map_add_s_less_[object_name] = double(counter_good) / double(counter_) * 100.0; std::cout << "{"; for (auto partial : partials_ratio) std::cout << partial.first << ": " << partial.second * 100.0 << " "; std::cout << "}" << std::endl; // Print AUC (0.1 m) double auc = evaluateAUC(errors_, 0.1) * 100.0; std::cout << "AUC (0.1 m) (" << metric_item.first << ") : " << auc << " "; map_add_s_auc_[object_name] = auc; std::cout << "{"; for (auto partial : partials_auc) std::cout << partial.first << ": " << partial.second * 100.0 << " "; std::cout << "}" << std::endl; } else if((metric_item.first == "RMS") || (metric_item.first == "RMSSymmetry")) { std::cout << "RMSE (position): " << std::setprecision(3) << std::sqrt(rmse_position_ / double(counter_)) * 100.0 << " "; map_rmse_position_[object_name] = std::sqrt(rmse_position_ / double(counter_)) * 100.0; std::cout << "{"; for (auto partial : partials_rmse_position) std::cout << partial.first << ": " << std::setprecision(3) << partial.second * 100.0 << " "; std::cout << "}" << std::endl; std::cout << "RMSE (orientation): " << std::setprecision(3) << std::sqrt(rmse_orientation_ / double(counter_)) * 180.0 / M_PI << " "; map_rmse_orientation_[object_name] = std::sqrt(rmse_orientation_ / double(counter_)) * 180.0 / M_PI; std::cout << "{"; for (auto partial : partials_rmse_orientation) std::cout << partial.first << ": " << std::setprecision(3) << partial.second * 180.0 / M_PI << " "; std::cout << "}" << std::endl; } else if(metric_item.first == "FPS") { std::cout << "FPS: " << std::setprecision(3) << fps_ / double(counter_) << " "; std::cout << "{"; for (auto partial : partials_fps) std::cout << partial.first << ": " << std::setprecision(3) << partial.second << " "; std::cout << "}" << std::endl; } std::cout << std::endl; } } ObjectResults::ObjectResults(const std::vector<std::unique_ptr<const ObjectResults>>& results_set, const std::vector<std::string>& metrics, const double& max_error) { std::cout << log_ID_ << "::ctor. MEAN" << std::endl; for (const std::string& metric_name : metrics) { if (metric_name == "ADD-S") { std::size_t counter = 0; std::size_t counter_good = 0; std::vector<double> total_errors; for (auto& result : results_set) { std::vector<double> errors; std::tie(std::ignore, errors) = result->getErrors(); counter += errors.size(); for (std::size_t i = 0; i < errors.size(); i++) { total_errors.push_back(errors[i]); if (errors[i] < max_error) counter_good++; } } std::cout << "% < " << max_error << "(" << metric_name << ") : " << double(counter_good) / double(counter) * 100.0 << " " << std::endl; double auc = evaluateAUC(total_errors, 0.1) * 100.0; std::cout << "AUC (0.1 m) (" << metric_name << ") : " << auc << std::endl; map_add_s_auc_["all"] = auc; map_add_s_less_["all"] = double(counter_good) / double(counter) * 100.0; } else if((metric_name == "RMS") || (metric_name == "RMSSymmetry")) { std::size_t counter = 0; double total_rmse_position = 0; double total_rmse_orientation = 0; for (auto& result : results_set) { double rmse_position; double rmse_orientation; std::size_t number_samples; std::tie(number_samples, rmse_position, rmse_orientation) = result->getRMSE(); counter += number_samples; total_rmse_position += rmse_position; total_rmse_orientation += rmse_orientation; } std::cout << "RMSE (position): " << std::setprecision(3) << std::sqrt(total_rmse_position / double(counter)) * 100.0 << std::endl; std::cout << "RMSE (orientation): " << std::setprecision(3) << std::sqrt(total_rmse_orientation / double(counter)) * 180.0 / M_PI << std::endl; map_rmse_position_["all"] = std::sqrt(total_rmse_position / double(counter)) * 100.0; map_rmse_orientation_["all"] = std::sqrt(total_rmse_orientation / double(counter)) * 180.0 / M_PI; } else if(metric_name == "FPS") { std::size_t counter = 0; double total_fps = 0; for (auto& result : results_set) { double fps; std::size_t number_samples; std::tie(number_samples, fps) = result->getFPS(); counter += number_samples; total_fps += fps; } map_fps_["all"] = total_fps / double(counter); std::cout << "FPS: " << std::setprecision(3) << total_fps / double(counter) << std::endl; } } } std::tuple<std::size_t, std::vector<double>> ObjectResults::getErrors() const { return std::make_tuple(counter_, errors_); } std::tuple<std::size_t, double, double> ObjectResults::getRMSE() const { return std::make_tuple(counter_, rmse_position_, rmse_orientation_); } std::tuple<std::size_t, double> ObjectResults::getFPS() const { return std::make_tuple(counter_, fps_); } double ObjectResults::evaluateAUC(const std::vector<double>& errors, const double& max_threshold) { /* Adapted from https://github.com/yuxng/YCB_Video_toolbox/blob/d08b645d406b93a988087fea42a5f6ac7330933c/plot_accuracy_keyframe.m#L143. */ std::vector<double> metrics = errors; for (std::size_t i = 0; i < metrics.size(); i++) if (metrics[i] > max_threshold) metrics[i] = std::numeric_limits<double>::infinity(); std::sort(metrics.begin(), metrics.end()); VectorXd accuracy_classes(metrics.size()); for (std::size_t i = 0; i < metrics.size(); i++) accuracy_classes(i) = double(i + 1) / double(metrics.size()); std::size_t counter = 0; for (std::size_t i = 0; i < metrics.size(); i++) if (metrics[i] != std::numeric_limits<double>::infinity()) counter++; VectorXd accuracy_classes_modified(counter + 2); accuracy_classes_modified(0) = 0.0; accuracy_classes_modified.segment(1, counter) = accuracy_classes.segment(0, counter); accuracy_classes_modified(accuracy_classes_modified.size() - 1) = accuracy_classes(counter - 1); VectorXd metrics_modified(counter + 2); Map<const VectorXd> metrics_eigen(metrics.data(), metrics.size()); metrics_modified(0) = 0.0; metrics_modified.segment(1, counter) = metrics_eigen.segment(0, counter); metrics_modified(metrics_modified.size() - 1) = 0.1; for (std::size_t i = 1; i < accuracy_classes_modified.size(); i++) accuracy_classes_modified(i) = std::max(accuracy_classes_modified(i), accuracy_classes_modified(i - 1)); std::vector<std::size_t> indexes; for (std::size_t i = 1; i < metrics_modified.size(); i++) if (metrics_modified(i) != metrics_modified(i - 1)) indexes.push_back(i); double sum = 0; for (std::size_t i = 0; i < indexes.size(); i++) sum += (metrics_modified(indexes[i]) - metrics_modified(indexes[i] - 1)) * accuracy_classes_modified(indexes[i]); sum *= 10; return sum; } std::pair<bool, MatrixXd> ObjectResults::loadPointCloudFromFile(const std::string& filename) { MatrixXd data; std::ifstream istrm(filename); if (!istrm.is_open()) { istrm.close(); return std::make_pair(false, MatrixXd(0,0)); } std::vector<std::string> istrm_strings; std::string line; while (std::getline(istrm, line)) istrm_strings.push_back(line); data.resize(3, istrm_strings.size()); std::size_t found_lines = 0; for (auto line : istrm_strings) { std::size_t found_fields = 0; std::string number_str; std::istringstream iss(line); while (iss >> number_str) { std::size_t index = (3 * found_lines) + found_fields; *(data.data() + index) = std::stod(number_str); found_fields++; } if (found_fields != 3) return std::make_pair(false, MatrixXd(0,0)); found_lines++; } istrm.close(); return std::make_pair(true, data); }
22,686
C++
.cpp
479
36.127349
164
0.542085
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,909
SingleVideoResult.cpp
hsp-iit_mask-ukf/src/mask-ukf-evaluator/src/SingleVideoResult.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <SingleVideoResult.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include <unsupported/Eigen/MatrixFunctions> using namespace Eigen; SingleVideoResult::SingleVideoResult(const std::string& object_name, const std::string& video_name, const std::string& result_path) : video_name_(video_name) { /* Compose path. */ std::string root_result = result_path; if (root_result.back() != '/') root_result += '/'; /* Compose estimate file name. */ std::string estimate_file_name = root_result + object_name + "/" + video_name + "/object-tracking_estimate.txt"; /* Compose ground truth file name. */ std::string ground_truth_file_name; ground_truth_file_name = root_result + object_name + "/" + video_name + "/object-tracking_ground_truth.txt"; /* Compose fps file name. */ std::string fps_file_name = root_result + object_name + "/" + video_name + "/object-tracking_fps.txt"; /* Load estimate. */ bool valid_estimate = false; std::tie(valid_estimate, estimate_) = readDataFromFile(estimate_file_name, 14); if (!valid_estimate) { std::string error = log_ID_ + "::ctor. Error: cannot load results from file " + estimate_file_name; throw(std::runtime_error(error)); } /* Load ground truth. */ bool valid_ground_truth = false; std::tie(valid_ground_truth, ground_truth_) = readDataFromFile(ground_truth_file_name, 9); if (!valid_ground_truth) { std::string error = log_ID_ + "::ctor. Error: cannot load ground truth from file " + ground_truth_file_name; throw(std::runtime_error(error)); } /* Load fps. */ bool valid_fps = false; std::tie(valid_fps, fps_) = readDataFromFile(fps_file_name, 1); if (!valid_fps) { std::string error = log_ID_ + "::ctor. Error: cannot load fps from file " + fps_file_name; throw(std::runtime_error(error)); } if ((ground_truth_.cols() - estimate_.cols()) > 1) { /* Handle validation sets having missing frames such as DenseFusion. */ std::cout << "Padding missing frames" << std::endl; estimate_ = padMissingFrames(estimate_, ground_truth_.cols()); if (ground_truth_.cols() != estimate_.cols()) { std::string error = log_ID_ + "::ctor. Error: unable to pad missing frames (" + object_name + ", " + video_name + ", #GT: " + std::to_string(ground_truth_.cols()) + ", #EST: " + std::to_string(estimate_.cols()) + ")"; throw(std::runtime_error(error)); } } } Transform<double, 3, Affine> SingleVideoResult::getObjectPose(const std::size_t& frame_id) const { // frame_id starts from 1 in YCB Video dataset VectorXd vector = estimate_.col(frame_id - 1); return makeTransform(vector.segment<7>(0)); } Transform<double, 3, Affine> SingleVideoResult::getGroundTruthPose(const std::size_t& frame_id) const { // frame_id starts from 1 in YCB Video dataset VectorXd vector = ground_truth_.col(frame_id - 1); return makeTransform(vector.segment<7>(2)); } double SingleVideoResult::getFPS(const std::size_t& frame_id) const { return fps_.col(frame_id -1)(0); } std::size_t SingleVideoResult::getNumberFrames() const { return ground_truth_.cols(); } std::string SingleVideoResult::getVideoName() const { return video_name_; } std::pair<bool, MatrixXd> SingleVideoResult::readDataFromFile(const std::string& filename, const std::size_t num_fields) { MatrixXd data; std::ifstream istrm(filename); if (!istrm.is_open()) { std::cout << log_ID_ + "::readDataFromFile. Error: failed to open " << filename << '\n'; istrm.close(); return std::make_pair(false, MatrixXd(0,0)); } std::vector<std::string> istrm_strings; std::string line; while (std::getline(istrm, line)) { istrm_strings.push_back(line); } data.resize(num_fields, istrm_strings.size()); std::size_t found_lines = 0; for (auto line : istrm_strings) { std::size_t found_fields = 0; std::string number_str; std::istringstream iss(line); while (iss >> number_str) { std::size_t index = (num_fields * found_lines) + found_fields; *(data.data() + index) = std::stod(number_str); found_fields++; } if (num_fields != found_fields) { std::cout << log_ID_ + "::readDataFromFile. Error: malformed input file " << filename << '\n'; return std::make_pair(false, MatrixXd(0,0)); } found_lines++; } istrm.close(); return std::make_pair(true, data); } Eigen::MatrixXd SingleVideoResult::padMissingFrames(const Eigen::MatrixXd& data, const std::size_t& expected_length) { MatrixXd padded_data(data.rows(), expected_length); std::size_t index_key = data.rows() - 1; for (std::size_t i = 0, j = 0; i < padded_data.cols(); i++) { if (data.col(j)(index_key) == (i + 1)) { padded_data.col(i) = data.col(j); j++; } else { // DenseFusion might have missing frames due to missing detection in PoseCNN // When missing, they are identified as having an infinite error as per the code // that can be found here https://github.com/j96w/DenseFusion/blob/master/replace_ycb_toolbox/evaluate_poses_keyframe.m VectorXd padded_col = VectorXd::Ones(data.rows()) * std::numeric_limits<double>::infinity(); padded_col(index_key) = i; padded_data.col(i) = padded_col; } } return padded_data; } Transform<double, 3, Affine> SingleVideoResult::makeTransform(const VectorXd pose) const { /** * pose expected to be a 7-dimensional vector containing * x - y - z - axis vector - angle */ Transform<double, 3, Affine> transform; /* Compose translational part. */ transform = Translation<double, 3>(pose.head<3>()); /* Compose rotational part. */ AngleAxisd rotation(pose(6), pose.segment<3>(3)); transform.rotate(rotation); return transform; }
6,399
C++
.cpp
163
33.355828
229
0.636613
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,910
CorrectionICP.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/CorrectionICP.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <CorrectionICP.h> #include <Eigen/Dense> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/registration/icp.h> using namespace bfl; using namespace Eigen; CorrectionICP::CorrectionICP(std::unique_ptr<bfl::AdditiveMeasurementModel> measurement_model, const std::string& point_cloud_filename) : measurement_model_(std::move(measurement_model)) { /* Load model point cloud from file. */ bool valid_cloud = false; std::tie(valid_cloud, model_) = loadPointCloudFromFile(point_cloud_filename); if (!valid_cloud) { std::string err = log_ID_ + "::ctor. Error: cannot load point cloud from file " + point_cloud_filename; throw(std::runtime_error(err)); } } CorrectionICP::~CorrectionICP() { } void CorrectionICP::correctStep(const bfl::GaussianMixture& pred_state, bfl::GaussianMixture& corr_state) { pcl::console::setVerbosityLevel(pcl::console::L_ALWAYS); /* Get the current measurement if available. */ bool valid_measurement; Data measurement; std::tie(valid_measurement, measurement) = measurement_model_->measure(); if (!valid_measurement) { corr_state = pred_state; return; } MatrixXd meas_vector = any::any_cast<MatrixXd&&>(std::move(measurement)).col(0); MatrixXd meas = Map<MatrixXd>(meas_vector.data(), 3, meas_vector.size() / 3); /* Transform the model in the current pose. */ VectorXd state = pred_state.mean(0); Transform<double, 3, Affine> pose; pose = Translation<double, 3>(state.head<3>()); pose.rotate(AngleAxisd(state(9), Vector3d::UnitZ()) * AngleAxisd(state(10), Vector3d::UnitY()) * AngleAxisd(state(11), Vector3d::UnitX())); MatrixXd model_transformed = pose * model_.topRows<3>().colwise().homogeneous(); /* Do ICP. */ pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_target (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_source (new pcl::PointCloud<pcl::PointXYZ>); /* Fill in source cloud */ cloud_source->width = meas.size() / 3.0; cloud_source->height = 1; cloud_source->is_dense = false; cloud_source->points.resize (meas.size() / 3.0); for (size_t i = 0; i < cloud_source->points.size(); ++i) { cloud_source->points[i].x = meas.col(i)(0); cloud_source->points[i].y = meas.col(i)(1); cloud_source->points[i].z = meas.col(i)(2); } /* Fill in pcl cloud. */ cloud_target->width = model_transformed.cols(); cloud_target->height = 1; cloud_target->is_dense = false; cloud_target->points.resize (model_transformed.cols()); for (size_t i = 0; i < cloud_target->points.size(); ++i) { cloud_target->points[i].x = model_transformed.col(i)(0); cloud_target->points[i].y = model_transformed.col(i)(1); cloud_target->points[i].z = model_transformed.col(i)(2); } pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp; icp.setInputSource(cloud_source); icp.setInputTarget(cloud_target); // Set the max correspondence distance (e.g., correspondences with higher distances will be ignored) icp.setMaxCorrespondenceDistance (0.05); pcl::PointCloud<pcl::PointXYZ> aligned; icp.align(aligned); if (icp.hasConverged()) { Matrix4f transformation = icp.getFinalTransformation(); Matrix4d transformation_double = transformation.cast<double>(); Transform<double, 3, Affine> pose_delta(transformation_double); pose = pose_delta.inverse() * pose; corr_state.mean(0).head<3>() = pose.translation(); corr_state.mean(0).tail<3>() = pose.rotation().eulerAngles(2, 1, 0); } else // If not convergence, the predicted state is used as corrected state // Warning: in the ICP implementation the predicted state corresponds to // the corrected state at the previous step since there is no motion model involved // (see class StaticPrediction for more details) corr_state = pred_state; } MeasurementModel& CorrectionICP::getMeasurementModel() { return *measurement_model_; } std::pair<bool, MatrixXd> CorrectionICP::loadPointCloudFromFile(const std::string& filename) { MatrixXd data; std::ifstream istrm(filename); if (!istrm.is_open()) { istrm.close(); return std::make_pair(false, MatrixXd(0,0)); } std::vector<std::string> istrm_strings; std::string line; while (std::getline(istrm, line)) istrm_strings.push_back(line); data.resize(3, istrm_strings.size()); std::size_t found_lines = 0; for (auto line : istrm_strings) { std::size_t found_fields = 0; std::string number_str; std::istringstream iss(line); while (iss >> number_str) { std::size_t index = (3 * found_lines) + found_fields; *(data.data() + index) = std::stod(number_str); found_fields++; } if (found_fields != 3) return std::make_pair(false, MatrixXd(0,0)); found_lines++; } istrm.close(); return std::make_pair(true, data); }
5,396
C++
.cpp
134
34.395522
137
0.65863
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,911
ConfigParser.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/ConfigParser.cpp
#include <ConfigParser.h> #include <regex> #include <sstream> #include <vector> ConfigParser::ConfigParser ( const int& argc, char** argv, const std::string& file_path ) : allowed_booleans_(allowed_booleans_string_), default_path_(file_path) { std::string cfg_path = get_cfg_file_path(argc, argv); try { cfg_.readFile(cfg_path.c_str()); const libconfig::Setting& root = cfg_.getRoot(); std::vector<ParameterInfo> list; get_parameters_list(root, list); TCLAP::CmdLine cli(""); add_cli_arg_from(cli); for (const auto& parameter : list) add_cli_argument(parameter, cli); cli.parse(argc, argv); process_cli_args_bool(cli_args_bool_); process_cli_args(cli_args_double_); process_cli_args(cli_args_int_); process_cli_args(cli_args_string_); process_cli_args_array<double>(cli_args_double_array_); process_cli_args_array<int>(cli_args_int_array_); } catch(const libconfig::FileIOException& e) { throw(std::runtime_error("ConfigParser::ctor. I/O error while reading " + cfg_path + ".")); } catch(const libconfig::ParseException& e) { const std::string file_name(e.getFile()); const std::string file_line(std::to_string(e.getLine())); const std::string file_error(e.getError()); throw(std::runtime_error("ConfigParser::ctor. Parse error at " + file_name + ":" + file_line + " - " + file_error)); } } void ConfigParser::add_cli_argument(const ConfigParser::ParameterInfo& parameter_info, TCLAP::CmdLine& cli) { if (parameter_info.type == libconfig::Setting::TypeArray) { std::string description{"Specify the array as \"x_1, ..., x_" + std::to_string(parameter_info.array_length) + "\"."}; std::string type_description{"array"}; if (parameter_info.array_type == libconfig::Setting::TypeInt) { type_description += " of int"; cli_args_int_array_[parameter_info.name] = std::make_unique<TCLAP::ValueArg<std::string>>("", parameter_info.name, description, false, "", type_description); cli.add(*cli_args_int_array_.at(parameter_info.name)); } else if (parameter_info.array_type == libconfig::Setting::TypeFloat) { type_description += " of double"; cli_args_double_array_[parameter_info.name] = std::make_unique<TCLAP::ValueArg<std::string>>("", parameter_info.name, description, false, "", type_description); cli.add(*cli_args_double_array_.at(parameter_info.name)); } } else if (parameter_info.type == libconfig::Setting::TypeBoolean) { cli_args_bool_[parameter_info.name] = std::make_unique<TCLAP::ValueArg<std::string>>("", parameter_info.name, "", false, "", &allowed_booleans_); cli.add(*cli_args_bool_.at(parameter_info.name)); } else if (parameter_info.type == libconfig::Setting::TypeFloat) { cli_args_double_[parameter_info.name] = std::make_unique<TCLAP::ValueArg<double>>("", parameter_info.name, "", false, 0.0, "double"); cli.add(*cli_args_double_.at(parameter_info.name)); } else if (parameter_info.type == libconfig::Setting::TypeInt) { cli_args_int_[parameter_info.name] = std::make_unique<TCLAP::ValueArg<int>>("", parameter_info.name, "", false, 0, "int"); cli.add(*cli_args_int_.at(parameter_info.name)); } else if (parameter_info.type == libconfig::Setting::TypeString) { cli_args_string_[parameter_info.name] = std::make_unique<TCLAP::ValueArg<std::string>>("", parameter_info.name, "", false, "", "string"); cli.add(*cli_args_string_.at(parameter_info.name)); } } void ConfigParser::add_cli_arg_from(TCLAP::CmdLine& cli) { cli_arg_from_ = std::make_unique<TCLAP::ValueArg<std::string>>("", "from", "Path to the configuration file. It overrides the path provided to the ConfigParser constructor.", false, "", "string"); cli.add(*cli_arg_from_); } void ConfigParser::get_parameters_list(const libconfig::Setting& parent, std::vector<ConfigParser::ParameterInfo>& list, const std::string& parent_name) { for (const libconfig::Setting& item : parent) { std::string name = parent_name; if (!name.empty()) name += "::"; name += item.getName(); if ((item.getLength() > 0) && (item.getType() != libconfig::Setting::TypeArray)) get_parameters_list(item, list, name); else { if (item.getType() == libconfig::Setting::TypeArray) { libconfig::Setting& array_child = item[0]; list.push_back(ConfigParser::ParameterInfo{name, item.getType(), array_child.getType(), item.getLength()}); } else list.push_back(ConfigParser::ParameterInfo{name, item.getType()}); } } } std::string ConfigParser::get_cfg_file_path(const int& argc, char** argv) { std::string file_path = default_path_; TCLAP::CmdLine cli(" ", ' ', " ", false); TCLAP::ValueArg<std::string> arg("", "from", "Path to the configuration file. It overrides the path provided to the ConfigParser constructor.", false, "", "string"); cli.add(arg); cli.setExceptionHandling(false); try { cli.parse(argc, argv); } catch (TCLAP::CmdLineParseException) {} if (arg.isSet()) file_path = arg.getValue(); return file_path; } void ConfigParser::process_cli_args_bool(const std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>>& list) { for (const auto& pair : list) { std::string libconfig_path = std::regex_replace(pair.first, std::regex("::"), "."); if(pair.second->isSet()) { cfg_.lookup(libconfig_path) = (pair.second->getValue() == "true"); } } }
5,943
C++
.cpp
139
35.798561
199
0.625519
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,912
ObjectPointCloudPrediction.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/ObjectPointCloudPrediction.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <ObjectPointCloudPrediction.h> #include <fstream> using namespace Eigen; using namespace nanoflann; ObjectPointCloudPrediction::ObjectPointCloudPrediction(const std::string& point_cloud_filename) { // Load the point cloud from file bool valid_cloud = false; std::tie(valid_cloud, cloud_) = loadPointCloudFromFile(point_cloud_filename); if (!valid_cloud) { std::string err = log_ID_ + "::ctor. Error: cannot load point cloud from file " + point_cloud_filename; throw(std::runtime_error(err)); } } ObjectPointCloudPrediction::~ObjectPointCloudPrediction() { } std::pair<bool, MatrixXd> ObjectPointCloudPrediction::predictPointCloud(ConstMatrixXdRef state, ConstVectorXdRef meas) { // Check if meas size is multiple of 3 if ((meas.size() % 3) != 0) return std::make_pair(false, MatrixXd(0, 0)); // Reshape measurement as a matrix Map<const MatrixXd> meas_matrix(meas.data(), 3, meas.size() / 3); // Move sampled point cloud to robot frame according to states stored in state std::vector<MatrixXd> clouds(state.cols()); std::vector<std::unique_ptr<PointCloudAdaptor>> adapted_clouds(state.cols()); std::vector<std::unique_ptr<kdTree>> trees(state.cols()); for (std::size_t i = 0; i < state.cols(); i++) { // Compose translation Transform<double, 3, Eigen::Affine> pose; pose = Translation<double, 3>(state.col(i).segment(0, 3)); // Compose rotation AngleAxisd rotation(AngleAxis<double>(state(9, i), Vector3d::UnitZ()) * AngleAxis<double>(state(10, i), Vector3d::UnitY()) * AngleAxis<double>(state(11, i), Vector3d::UnitX())); pose.rotate(rotation); // Express point cloud sampled on the model in robot frame clouds[i] = pose * cloud_.topRows<3>().colwise().homogeneous(); // Initialize tree adapted_clouds[i] = std::unique_ptr<PointCloudAdaptor>(new PointCloudAdaptor(clouds.at(i))); trees[i] = std::unique_ptr<kdTree>(new kdTree(3 /* dim */, *adapted_clouds.at(i), KDTreeSingleIndexAdaptorParams(10 /* max leaf */))); trees[i]->buildIndex(); } // Predict measurement MatrixXd predictions(meas.size(), state.cols()); for (std::size_t i = 0; i < state.cols(); i++) { for (std::size_t j = 0; j < meas.size() / 3; j++) { const Ref<const Vector3d> meas_j = meas_matrix.col(j); std::size_t ret_index; double out_dist_sqr; KNNResultSet<double> resultSet(1); resultSet.init(&ret_index, &out_dist_sqr); // Querying tree_ is thread safe as per this issue // https://github.com/jlblancoc/nanoflann/issues/54 trees.at(i)->findNeighbors(resultSet, meas_j.data(), nanoflann::SearchParams(10)); predictions.col(i).segment<3>(j * 3) = clouds.at(i).col(ret_index); } } return std::make_pair(true, predictions); } std::pair<bool, MatrixXd> ObjectPointCloudPrediction::evaluateDistances(ConstMatrixXdRef state, ConstVectorXdRef meas) { // Check if meas size is multiple of 3 if ((meas.size() % 3) != 0) return std::make_pair(false, MatrixXd(0, 0)); MatrixXd squared_distances(state.cols(), meas.size() / 3); // Reshape measurement as a matrix Map<const MatrixXd> meas_matrix(meas.data(), 3, meas.size() / 3); // Move sampled point cloud to robot frame according to states stored in state std::vector<MatrixXd> clouds(state.cols()); std::vector<std::unique_ptr<PointCloudAdaptor>> adapted_clouds(state.cols()); std::vector<std::unique_ptr<kdTree>> trees(state.cols()); for (std::size_t i = 0; i < state.cols(); i++) { // Compose translation Transform<double, 3, Eigen::Affine> pose; pose = Translation<double, 3>(state.col(i).segment(0, 3)); // Compose rotation AngleAxisd rotation(AngleAxis<double>(state(9, i), Vector3d::UnitZ()) * AngleAxis<double>(state(10, i), Vector3d::UnitY()) * AngleAxis<double>(state(11, i), Vector3d::UnitX())); pose.rotate(rotation); // Express point cloud sampled on the model in robot frame clouds[i] = pose * cloud_.topRows<3>().colwise().homogeneous(); // Initialize tree adapted_clouds[i] = std::unique_ptr<PointCloudAdaptor>(new PointCloudAdaptor(clouds.at(i))); trees[i] = std::unique_ptr<kdTree>(new kdTree(3 /* dim */, *adapted_clouds.at(i), KDTreeSingleIndexAdaptorParams(10 /* max leaf */))); trees[i]->buildIndex(); } // Eval distances for (std::size_t i = 0; i < state.cols(); i++) { for (std::size_t j = 0; j < meas.size() / 3; j++) { const Ref<const Vector3d> meas_j = meas_matrix.col(j); std::size_t ret_index; double out_dist_sqr; KNNResultSet<double> resultSet(1); resultSet.init(&ret_index, &out_dist_sqr); // Querying tree_ is thread safe as per this issue // https://github.com/jlblancoc/nanoflann/issues/54 trees.at(i)->findNeighbors(resultSet, meas_j.data(), nanoflann::SearchParams(10)); squared_distances(i, j) = out_dist_sqr; } } return std::make_pair(true, squared_distances); } Eigen::MatrixXd ObjectPointCloudPrediction::evaluateModel(const Transform<double, 3, Affine>& object_pose) { return object_pose * cloud_.colwise().homogeneous(); } std::pair<bool, MatrixXd> ObjectPointCloudPrediction::loadPointCloudFromFile(const std::string& filename) { MatrixXd data; std::ifstream istrm(filename); if (!istrm.is_open()) { istrm.close(); return std::make_pair(false, MatrixXd(0,0)); } std::vector<std::string> istrm_strings; std::string line; while (std::getline(istrm, line)) istrm_strings.push_back(line); data.resize(3, istrm_strings.size()); std::size_t found_lines = 0; for (auto line : istrm_strings) { std::size_t found_fields = 0; std::string number_str; std::istringstream iss(line); while (iss >> number_str) { std::size_t index = (3 * found_lines) + found_fields; *(data.data() + index) = std::stod(number_str); found_fields++; } if (found_fields != 3) return std::make_pair(false, MatrixXd(0,0)); found_lines++; } istrm.close(); return std::make_pair(true, data); }
6,836
C++
.cpp
154
36.818182
142
0.630143
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,913
StaticPrediction.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/StaticPrediction.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <StaticPrediction.h> using namespace bfl; StaticPrediction::StaticPrediction() : model_placeholder_(std::unique_ptr<StaticModel>(new StaticModel())) { } StaticPrediction::~StaticPrediction() { } StateModel& StaticPrediction::getStateModel() noexcept { return *model_placeholder_; } void StaticPrediction::predictStep(const GaussianMixture& prev_state, GaussianMixture& pred_state) { // The predicted state corresponds to the corrected state at the previous step. // This is used for the implementation of ICP. pred_state = prev_state; }
784
C++
.cpp
23
31.565217
98
0.772304
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,914
main.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/main.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <Camera.h> #include <ConfigParser.h> #include <Correction.h> #include <CorrectionICP.h> #include <DiscretizedKinematicModel.h> #include <InitGroundTruth.h> #include <MaskSegmentation.h> #include <ObjectPointCloudPrediction.h> #include <PointCloudSegmentation.h> #include <StaticPrediction.h> #include <UKFFilter.h> #include <YCBVideoCamera.h> #include <BayesFilters/AdditiveMeasurementModel.h> #include <BayesFilters/FilteringAlgorithm.h> #include <BayesFilters/GaussianCorrection.h> #include <BayesFilters/GaussianPrediction.h> #include <BayesFilters/KFPrediction.h> #include <Eigen/Dense> #include <cstdlib> #include <string> #include <sstream> using namespace bfl; using namespace Eigen; int main(int argc, char** argv) { const std::string log_ID = "[Main] "; std::cout << log_ID << "Configuring and starting module..." << std::endl; ConfigParser conf(argc, argv); /* Get algorithm name. */ std::string algorithm; conf("algorithm", algorithm); /* Get autostart flag. */ bool autostart; conf("autostart", autostart); /* Get initial conditions. */ VectorXd cov_x_0; conf("initial_condition::cov_x_0", cov_x_0); VectorXd cov_v_0; conf("initial_condition::cov_v_0", cov_v_0); VectorXd cov_eul_0; conf("initial_condition::cov_eul_0", cov_eul_0); VectorXd cov_eul_dot_0; conf("initial_condition::cov_eul_dot_0", cov_eul_dot_0); /* Camera parameters. */ std::string camera_name; conf("camera::name", camera_name); /* Kinematic model. */ VectorXd kin_q_x; conf("kinematic_model::q_x", kin_q_x); VectorXd kin_q_eul; conf("kinematic_model::q_eul", kin_q_eul); double kin_rate; conf("kinematic_model::rate", kin_rate); bool kin_est_period; conf("kinematic_model::estimate_period", kin_est_period); /* Measurement model. */ VectorXd visual_covariance; conf("measurement_model::visual_covariance", visual_covariance); MatrixXd visual_covariance_diagonal = visual_covariance.asDiagonal(); /* Unscented transform. */ double ut_alpha; conf("unscented_transform::alpha", ut_alpha); double ut_beta; conf("unscented_transform::beta", ut_beta); double ut_kappa; conf("unscented_transform::kappa", ut_kappa); /* Point cloud filtering. */ bool pc_outlier_rejection; conf("point_cloud_filtering::outlier_rejection", pc_outlier_rejection); /* Depth. */ std::string depth_fetch_mode; conf("depth::fetch_mode", depth_fetch_mode); int depth_stride; conf("depth::stride", depth_stride); /* Mesh parameters. */ std::string object_name; conf("object::object_name", object_name); std::string object_point_cloud_path = "./models/" + object_name; std::string object_data_path; conf("object::path", object_data_path); /* Segmentation parameters. */ std::string segmentation_set; conf("segmentation::masks_set", segmentation_set); bool segmentation_enforce_fps; conf("segmentation::enforce_fps", segmentation_enforce_fps); double segmentation_fps; conf("segmentation::fps", segmentation_fps); /* Logging parameters. */ bool enable_log; conf("log::enable_log", enable_log); std::string log_path; conf("log::absolute_log_path", log_path); if (enable_log && log_path == "") { std::cout << "Invalid log path. Disabling log..." << std::endl; enable_log = false; } /* Log parameters. */ auto eigen_to_string = [](const Ref<const VectorXd>& v) { std::stringstream ss; ss << v.transpose(); return ss.str(); }; std::cout << log_ID << "Algorithm: " << algorithm << std::endl; std::cout << log_ID << "Initial conditions:" << std::endl; std::cout << log_ID << "- cov_x_0: " << eigen_to_string(cov_x_0) << std::endl; std::cout << log_ID << "- cov_v_0: " << eigen_to_string(cov_v_0) << std::endl; std::cout << log_ID << "- cov_eul_0: " << eigen_to_string(cov_eul_0) << std::endl; std::cout << log_ID << "- cov_eul_dot_0: " << eigen_to_string(cov_eul_dot_0) << std::endl; std::cout << log_ID << "Camera:" << std::endl; std::cout << log_ID << "- name: " << camera_name << std::endl; std::cout << log_ID << "Kinematic model:" << std::endl; std::cout << log_ID << "- q_x: " << eigen_to_string(kin_q_x) << std::endl; std::cout << log_ID << "- q_eul: " << eigen_to_string(kin_q_eul) << std::endl; std::cout << log_ID << "- rate: " << kin_rate << std::endl; std::cout << log_ID << "- estimate_period: " << kin_est_period << std::endl; std::cout << log_ID << "Measurement model:" << std::endl; std::cout << log_ID << "- visual_covariance: " << eigen_to_string(visual_covariance) << std::endl; std::cout << log_ID << "Unscented transform:" << std::endl; std::cout << log_ID << "- alpha: " << ut_alpha << std::endl; std::cout << log_ID << "- beta: " << ut_beta << std::endl; std::cout << log_ID << "- kappa: " << ut_kappa << std::endl; std::cout << log_ID << "Point cloud filtering:" << std::endl; std::cout << log_ID << "- outlier_rejection: " << pc_outlier_rejection << std::endl; std::cout << log_ID << "Depth:" << std::endl; std::cout << log_ID << "- fetch_mode: " << depth_fetch_mode << std::endl; std::cout << log_ID << "- stride: " << depth_stride << std::endl; std::cout << log_ID << "Object:" << std::endl; std::cout << log_ID << "- object_name: " << object_name << std::endl; std::cout << log_ID << "- object_data_path: " << object_data_path << std::endl; std::cout << log_ID << "- point cloud path is: " << object_point_cloud_path << std::endl; std::cout << log_ID << "Segmentation:" << std::endl; std::cout << log_ID << "- masks_set: " << segmentation_set << std::endl; std::cout << log_ID << "- enforce_fps: " << segmentation_enforce_fps << std::endl; if (segmentation_enforce_fps) std::cout << log_ID << "- fps: " << segmentation_fps << std::endl; std::cout << log_ID << "Logging:" << std::endl; std::cout << log_ID << "- enable_log: " << enable_log << std::endl; std::cout << log_ID << "- absolute_log_path: " << log_path << std::endl; /** * Initialize camera */ std::unique_ptr<Camera> camera; if (camera_name == "YCBVideoCamera") { camera = std::unique_ptr<YcbVideoCamera> ( new YcbVideoCamera(object_data_path) ); } else { std::cerr << log_ID << "The requested camera is not available. Requested camera is" << camera_name << std::endl;; std::exit(EXIT_FAILURE); } camera->initialize(); /** * Initialize object segmentation. */ std::unique_ptr<PointCloudSegmentation> segmentation; if (segmentation_enforce_fps) { segmentation = std::unique_ptr<MaskSegmentation> ( new MaskSegmentation(object_data_path, object_name, depth_stride, segmentation_set, segmentation_fps) ); } else { segmentation = std::unique_ptr<MaskSegmentation> ( new MaskSegmentation(object_data_path, object_name, depth_stride, segmentation_set) ); } /** * Initialize point cloud prediction. */ std::shared_ptr<PointCloudPrediction> point_cloud_prediction = std::make_shared<ObjectPointCloudPrediction>(object_point_cloud_path); /** * Initialize measurement model. */ std::unique_ptr<AdditiveMeasurementModel> measurement_model; std::unique_ptr<ObjectMeasurements> obj_meas = std::unique_ptr<ObjectMeasurements> ( new ObjectMeasurements(std::move(camera), std::move(segmentation), point_cloud_prediction, visual_covariance_diagonal, depth_fetch_mode) ); obj_meas->enableOutlierRejection(pc_outlier_rejection); // if (enable_log) // obj_meas->enable_log(log_path, "object-tracking"); measurement_model = std::move(obj_meas); /** * Filter construction. */ /** * StateModel */ std::unique_ptr<LinearStateModel> kinematic_model = std::unique_ptr<DiscretizedKinematicModel> ( new DiscretizedKinematicModel(kin_q_x(0), kin_q_x(1), kin_q_x(2), kin_q_eul(0), kin_q_eul(1), kin_q_eul(2), 1.0 / kin_rate, kin_est_period) ); /** * Initial condition. */ VectorXd initial_covariance(12); initial_covariance.head<3>() = cov_x_0; initial_covariance.segment<3>(3) = cov_v_0; initial_covariance.segment<3>(6) = cov_eul_dot_0; initial_covariance.tail<3>() = cov_eul_0; std::unique_ptr<InitGroundTruth> initialization = std::unique_ptr<InitGroundTruth> ( new InitGroundTruth(object_data_path, object_name, 0, initial_covariance.asDiagonal()) ); /** * Prediction step. */ std::unique_ptr<GaussianPrediction> prediction; if (algorithm == "UKF") { prediction = std::unique_ptr<KFPrediction> ( new KFPrediction(std::move(kinematic_model)) ); } else { // Used for ICP prediction = std::unique_ptr<StaticPrediction> ( new StaticPrediction() ); } /** * Correction step. */ std::unique_ptr<GaussianCorrection> correction; if (algorithm == "UKF") { // A measurement is made of 3 * N scalars, N being the number of points std::size_t measurement_sub_size = 3; correction = std::unique_ptr<Correction> ( new Correction(std::move(measurement_model), ut_alpha, ut_beta, ut_kappa, measurement_sub_size) ); } else { correction = std::unique_ptr<CorrectionICP> ( new CorrectionICP(std::move(measurement_model), object_point_cloud_path) ); } /** * Filter. */ std::cout << "Initializing filter..." << std::flush; std::unique_ptr<UKFFilter> filter = std::unique_ptr<UKFFilter> ( new UKFFilter(std::move(initialization), std::move(prediction), std::move(correction)) ); if (enable_log) filter->enable_log(log_path, "object-tracking"); std::cout << "done." << std::endl; std::cout << "Booting filter..." << std::flush; filter->boot(); std::cout << "done." << std::endl; std::cout << "Running filter..." << std::endl; if (autostart) filter->run(); if (!filter->wait()) return EXIT_FAILURE; std::cout << log_ID << "Application closed succesfully." << std::endl; return EXIT_SUCCESS; }
10,759
C++
.cpp
255
36.552941
147
0.622679
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,915
MaskSegmentation.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/MaskSegmentation.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <MaskSegmentation.h> #include <fstream> #include <iostream> using namespace Eigen; MaskSegmentation::MaskSegmentation(const std::string& path, const std::string& mask_name, const std::size_t& depth_stride, const std::string& masks_set) : mask_name_(mask_name), depth_stride_(depth_stride) { /* Compose root path. */ std::string root = path; if (root.back() != '/') root += '/'; /* Compose path containing mask images. */ path_mask_images_ = root + "masks/" + masks_set + "/"; } MaskSegmentation::MaskSegmentation(const std::string& path, const std::string& mask_name, const std::size_t& depth_stride, const std::string& masks_set, const double& simulated_fps) : mask_name_(mask_name), depth_stride_(depth_stride), simulated_fps_(true), fps_(simulated_fps) { /* Compose root path. */ std::string root = path; if (root.back() != '/') root += '/'; /* Compose path containing mask images. */ path_mask_images_ = root + "masks/" + masks_set + "/"; } MaskSegmentation::~MaskSegmentation() {} bool MaskSegmentation::freezeSegmentation(Camera& camera) { // Get camera parameters bool valid_parameters = false; CameraParameters camera_parameters; std::tie(valid_parameters, camera_parameters) = camera.getIntrinsicParameters(); if (!valid_parameters) return false; // Get binary mask bool received_mask = false; bool valid_mask = false; cv::Mat mask; std::tie(received_mask, valid_mask, mask) = getMask(camera); // A binary mask has been received and it is valid if (received_mask) { if (valid_mask) { mask_initialized_ = true; mask_ = mask.clone(); } // A binary mask has been received but it is empty (i.e. no detection) else { mask_initialized_ = false; coordinates_.clear(); } } // As soon as a mask has been received the coordinates are extracted // If a mask has not been received but the last one was valid, // 'mask_initialized_' will be true and old coordinates are used // If an empty mask was received 'mask_initialized_' will be false // and coordinates_ will be empty // The variable coordinates_ is used in method extractPointCloud() if(mask_initialized_) { // Find non zero coordinates cv::Mat non_zero_coordinates; cv::findNonZero(mask_, non_zero_coordinates); // Fill coordinates vector coordinates_.clear(); for (std::size_t i = 0; i < non_zero_coordinates.total(); i+= depth_stride_) { cv::Point& p = non_zero_coordinates.at<cv::Point>(i); coordinates_.push_back(std::make_pair(p.x, p.y)); } } return true; } std::tuple<bool, std::size_t, MatrixXd> MaskSegmentation::extractPointCloud(Camera& camera, const Ref<const MatrixXf>& depth, const double& max_depth) { // Find valid points according to depth VectorXi valid_points(coordinates_.size()); for (std::size_t i = 0; i < valid_points.size(); i++) { valid_points(i) = 0; float depth_u_v = depth(coordinates_[i].second, coordinates_[i].first); if ((depth_u_v > 0) && (depth_u_v < max_depth)) valid_points(i) = 1; } // Check if there are valid points std::size_t num_valids = valid_points.sum(); // Get camera parameters bool valid_parameters = false; CameraParameters camera_parameters; std::tie(valid_parameters, camera_parameters) = camera.getIntrinsicParameters(); if (!valid_parameters) return std::make_tuple(false, 0, MatrixXd()); // Get deprojection matrix bool valid_deprojection_matrix = false; MatrixXd deprojection_matrix; std::tie(valid_deprojection_matrix, deprojection_matrix) = camera.getDeprojectionMatrix(); if (!valid_deprojection_matrix) return std::make_tuple(false, 0, MatrixXd()); // Store only valid points MatrixXd points(3, num_valids); for (int i = 0, j = 0; i < coordinates_.size(); i++) { if(valid_points(i) == 1) { const int& u = coordinates_[i].first; const int& v = coordinates_[i].second; points.col(j) = deprojection_matrix.col(u * camera_parameters.height + v) * depth(v, u); j++; } } // When coordinates_ is empty the resulting point cloud will be empty too return std::make_tuple(true, coordinates_.size(), points); } bool MaskSegmentation::setProperty(const std::string& property) { bool valid = PointCloudSegmentation::setProperty(property); if (property == "reset") head_ = 1; return valid; } std::tuple<bool, bool, cv::Mat> MaskSegmentation::getMask(Camera& camera) { cv::Mat mask; head_++; // Move head to the next frame if (simulated_fps_) { if ((head_ -1) % static_cast<int>(original_fps_ / fps_) == 0) effective_head_ = head_; } else effective_head_ = head_; std::string file_name = path_mask_images_ + mask_name_ + "_" + composeFileName(effective_head_, number_of_digits_) + ".png"; mask = cv::imread(file_name, cv::IMREAD_COLOR); if (mask.empty()) { // Detection not available for this frame return std::make_tuple(true, false, cv::Mat()); } cv::cvtColor(mask, mask, cv::COLOR_BGR2GRAY); CameraParameters parameters; std::tie(std::ignore, parameters) = camera.getIntrinsicParameters(); cv::resize(mask, mask, cv::Size(parameters.width, parameters.height)); cv::Mat non_zero_coordinates; cv::findNonZero(mask, non_zero_coordinates); if (non_zero_coordinates.total() == 0) // Mask available but empty return std::make_tuple(true, false, cv::Mat()); // Mask available and non-empty return std::make_tuple(true, true, mask); } std::string MaskSegmentation::composeFileName(const std::size_t& index, const std::size_t& number_digits) { std::ostringstream ss; ss << std::setw(number_digits) << std::setfill('0') << index; return ss.str(); }
6,380
C++
.cpp
169
31.863905
183
0.644596
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,916
Camera.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/Camera.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <Camera.h> #include <iostream> using namespace Eigen; Camera::~Camera() { } bool Camera::initialize() { bool ok = true; // Cache the deprojection matrix once for all ok &= evalDeprojectionMatrix(); return ok; } bool Camera::freeze() { return true; } bool Camera::reset() { return false; } bool Camera::setFrame(const std::size_t& number) { return false; } std::pair<bool, MatrixXd> Camera::getDeprojectionMatrix() { if (!deprojection_matrix_initialized_) return std::make_pair(false, MatrixXd()); return std::make_pair(true, deprojection_matrix_); } bool Camera::evalDeprojectionMatrix() { if (!parameters_.initialized) { std::cout << log_ID_base_ << "::evalDeprojectionMatrix. Camera parameters not initialized. Did you initialize the class member 'parameters_' in the derived class?"; return false; } // Allocate storage deprojection_matrix_.resize(3, parameters_.width * parameters_.height); // Evaluate deprojection matrix int i = 0; for (std::size_t u = 0; u < parameters_.width; u++) { for (std::size_t v = 0; v < parameters_.height; v++) { deprojection_matrix_(0, i) = (u - parameters_.cx) / parameters_.fx; deprojection_matrix_(1, i) = (v - parameters_.cy) / parameters_.fy; deprojection_matrix_(2, i) = 1.0; i++; } } deprojection_matrix_initialized_ = true; return true; } std::pair<bool, CameraParameters> Camera::getIntrinsicParameters() const { if (!parameters_.initialized) return std::make_pair(false, CameraParameters()); return std::make_pair(true, parameters_); }
1,924
C++
.cpp
66
24.651515
172
0.666302
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,917
ObjectMeasurements.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/ObjectMeasurements.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <ObjectMeasurements.h> #include <BayesFilters/Gaussian.h> #include <mlpack/methods/approx_kfn/drusilla_select.hpp> #include <armadillo> #include <vector> using namespace bfl; using namespace Eigen; using namespace mlpack::neighbor; using MatrixXu = Matrix<std::size_t, Dynamic, Dynamic>; ObjectMeasurements::ObjectMeasurements ( std::unique_ptr<Camera> camera, std::shared_ptr<PointCloudSegmentation> segmentation, std::shared_ptr<PointCloudPrediction> prediction, const Eigen::Ref<const Eigen::Matrix3d>& visual_noise_covariance, const std::string& depth_fetch_mode ) : camera_(std::move(camera)), segmentation_(segmentation), prediction_(prediction), visual_noise_covariance_(visual_noise_covariance), depth_fetch_mode_(depth_fetch_mode) { } ObjectMeasurements::~ObjectMeasurements() { disable_log(); } std::pair<bool, Data> ObjectMeasurements::measure(const Data& data) const { return std::make_pair(true, measurement_); } bool ObjectMeasurements::freeze(const Data& data) { // Freeze camera measurements_available_ = camera_->freeze(); if (!measurements_available_) return false; // Get depth image if(!getDepth()) return false; // Freeze segmentation if (!segmentation_->freezeSegmentation(*camera_)) return false; // Get 3D point cloud. bool blocking_call = false; bool valid_point_cloud; MatrixXd point_cloud; std::size_t expected_num_points; std::tie(valid_point_cloud, expected_num_points, point_cloud) = segmentation_->extractPointCloud(*camera_, depth_, 10.0); if (!valid_point_cloud) return false; // Extract last belief available about object pose Gaussian last_belief = any::any_cast<Gaussian>(data); if (outlier_rejection_) { double ratio = double(point_cloud.cols()) / double(expected_num_points) * 100.0; if ((point_cloud.cols() == 0) || (ratio < 20.0)) { // If too few measurements than expected, or no measurements at all, // use virtual measurements sampled on the last belief as described in 3.6 Transform<double, 3, Affine> pose; pose = Translation<double, 3>(last_belief.mean().head<3>()); pose.rotate(AngleAxisd(AngleAxisd(last_belief.mean(9), Vector3d::UnitZ()) * AngleAxisd(last_belief.mean(10), Vector3d::UnitY()) * AngleAxisd(last_belief.mean(11), Vector3d::UnitX()))); point_cloud = prediction_->evaluateModel(pose); } else if (outlier_rejection_) { // If using real measurements, perform outlier rejection as described in 3.4 // Temporary storage MatrixXd point_cloud_tmp; MatrixXd prediction_tmp; VectorXi excluded_points = VectorXi::Zero(point_cloud.cols()); point_cloud_tmp.swap(point_cloud); do { // Move inliers to temporary storage if (excluded_points.sum() != 0) { point_cloud_tmp.resize(point_cloud.rows(), point_cloud.cols() - excluded_points.sum()); for (std::size_t i = 0, j = 0; i < point_cloud.cols(); i++) { if (excluded_points(i) == 0) { point_cloud_tmp.col(j).swap(point_cloud.col(i)); j++; } } excluded_points = VectorXi::Zero(point_cloud_tmp.cols()); } // Predict point cloud using current object pose MatrixXd prediction_tmp; MatrixXd prediction_vector; std::tie(std::ignore, prediction_vector) = prediction_->predictPointCloud(last_belief.mean(), Map<MatrixXd>(point_cloud_tmp.data(), point_cloud_tmp.size(), 1)); prediction_tmp = Map<MatrixXd>(prediction_vector.col(0).data(), 3, prediction_vector.col(0).size() / 3); // Initialize DrusillaSelect bool use_drusilla = true; arma::mat point_cloud_reference = arma::mat(point_cloud_tmp.data(), point_cloud_tmp.rows(), point_cloud_tmp.cols(), false, false); std::unique_ptr<DrusillaSelect<>> akfn; try { std::size_t drusilla_l = 5; std::size_t drusilla_m = 5; akfn = std::unique_ptr<DrusillaSelect<>>(new DrusillaSelect<>(point_cloud_reference, drusilla_l, drusilla_m)); } catch (std::invalid_argument) { // If drusilla_l * drusilla_m > point_cloud_tmp.cols() DrusillaSelect cannot be used use_drusilla = false; } // Search for outliers std::size_t k = 5; for (std::size_t i = 0; i < point_cloud_tmp.cols(); i++) { // Query point Vector3d q = point_cloud_tmp.col(i); MatrixXu neighbors; if (use_drusilla) { arma::Mat<size_t> neighbors_arma; arma::mat distances; arma::mat query_arma(q.data(), 3, 1, false, false); akfn->Search(query_arma, k, neighbors_arma, distances); neighbors = Map<MatrixXu>(neighbors_arma.memptr(), neighbors_arma.n_rows, neighbors_arma.n_cols); } else { // Since DrusillaSelect is not available, a brute force approach with k = 1 is used std::size_t max_index; (point_cloud_tmp.colwise() - q).colwise().norm().maxCoeff(&max_index); neighbors.resize(1, 1); neighbors(0, 0) = max_index; } // Projected point Vector3d q_p = prediction_tmp.col(i); for (std::size_t j = 0; j < neighbors.rows(); j++) { // Furthest point to q Vector3d f = point_cloud_tmp.col(neighbors.col(0)(j)); // Projected point Vector3d f_p = prediction_tmp.col(neighbors.col(0)(j)); // Distance in real point cloud double dist_real = (q - f).norm(); // Distance in projection double dist_proj = (q_p - f_p).norm(); if (abs(dist_proj - dist_real) > 0.01) { // Distance of outlier candidates to their projections double dist_1 = (q - q_p).norm(); double dist_2 = (f - f_p).norm(); if (dist_1 > dist_2) { excluded_points(i) = 1; } else { excluded_points(neighbors.col(0)(j)) = 1; } } } } point_cloud.swap(point_cloud_tmp); } while(excluded_points.sum() != 0); } } // Resize measurements to be a column vector. measurement_.resize(3 * point_cloud.cols(), 1); measurement_.swap(Map<MatrixXd>(point_cloud.data(), point_cloud.size(), 1)); // Log measurements logger(measurement_.transpose()); return true; } VectorDescription ObjectMeasurements::getInputDescription() const { // 9 linear components (x, y, z, x_dot, y_dot, z_dot, yaw_dot, pitch_dot, roll_dot) // 3 angular components (yaw, pitch, roll) // 12 noise components return VectorDescription(9, 3, 12, VectorDescription::CircularType::Euler); } VectorDescription ObjectMeasurements::getMeasurementDescription() const { // measurement_.size() linear components return VectorDescription(measurement_.size()); } std::pair<bool, bfl::Data> ObjectMeasurements::predictedMeasure(const Eigen::Ref<const Eigen::MatrixXd>& cur_states) const { bool valid_measure; bfl::Data measurement; std::tie(valid_measure, measurement) = measure(); if (!valid_measure) return std::make_pair(false, Data()); bool valid_prediction; MatrixXd prediction; std::tie(valid_prediction, prediction) = prediction_->predictPointCloud(cur_states, any::any_cast<MatrixXd>(measurement).col(0)); if (!valid_prediction) return std::make_pair(false, Data()); return std::make_pair(true, prediction); } std::pair<bool, bfl::Data> ObjectMeasurements::innovation(const bfl::Data& predicted_measurements, const bfl::Data& measurements) const { MatrixXd innovation = -(any::any_cast<MatrixXd>(predicted_measurements).colwise() - any::any_cast<MatrixXd>(measurements).col(0)); return std::make_pair(true, std::move(innovation)); } std::pair<bool, Eigen::MatrixXd> ObjectMeasurements::getNoiseCovarianceMatrix() const { return std::make_pair(true, visual_noise_covariance_); } bool ObjectMeasurements::setProperty(const std::string& property) { if (property == "reset") { reset(); return true; } else if (property == "measurements_available") { return measurements_available_; } else if (property == "disable_log") { disable_log(); return true; } return false; } void ObjectMeasurements::enableOutlierRejection(const bool& enable) { outlier_rejection_ = enable; } bool ObjectMeasurements::getDepth() { std::string mode = depth_fetch_mode_; if (!depth_initialized_) { // in case a depth was never received // it is required to wait at least for the first image in blocking mode mode = "new_image"; } bool valid_depth; MatrixXf tmp_depth; std::tie(valid_depth, tmp_depth) = camera_->getDepthImage(mode == "new_image"); if (valid_depth) { depth_ = std::move(tmp_depth); depth_initialized_ = true; } if (mode == "skip") return depth_initialized_ && valid_depth; else return depth_initialized_; } void ObjectMeasurements::reset() { depth_initialized_ = false; measurements_available_ = true; camera_->reset(); segmentation_->setProperty("reset"); }
10,927
C++
.cpp
265
30.132075
176
0.568045
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,918
YCBVideoCamera.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/YCBVideoCamera.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <YCBVideoCamera.h> #include <Eigen/Dense> #include <fstream> #include <sstream> using namespace Eigen; YcbVideoCamera::YcbVideoCamera(const std::string& path) { // Camera parameters parameters_.width = 320; parameters_.height = 240; parameters_.fx = 533.4; parameters_.fy = 535.75; parameters_.cx = 156.495; parameters_.cy = 120.655; parameters_.initialized = true; /* Compose root path. */ std::string root = path; if (root.back() != '/') root += '/'; /* Compose path containing rgb images. */ path_rgb_images_ = root + "rgb/"; /* Compose path containing depth images. */ path_depth_images_ = root + "depth/"; /* Determine the structure of the file names by trying several alternatives. */ std::ifstream in; number_of_digits_ = 1; bool found_frame_0 = false; while(!found_frame_0) { std::string file_path = path_rgb_images_ + composeFileName(1, number_of_digits_) + ".png"; in.open(file_path); if(in.is_open()) { found_frame_0 = true; std::cout << log_ID_ + "::ctor. Found keyframe " << file_path << std::endl; } else number_of_digits_++; in.close(); } } YcbVideoCamera::~YcbVideoCamera() { } bool YcbVideoCamera::freeze() { head_++; // Test for the next frame being available return checkImage(head_); } bool YcbVideoCamera::reset() { head_ = 0; return true; } bool YcbVideoCamera::setFrame(const std::size_t& number) { head_ = number; return true; } std::pair<bool, cv::Mat> YcbVideoCamera::getRgbImage(const bool& blocking) { std::string file_name = path_rgb_images_ + composeFileName(head_, number_of_digits_) + ".png"; cv::Mat image = cv::imread(file_name, cv::IMREAD_COLOR); if (image.empty()) { std::cout << log_ID_ << "::getRgbImage. Warning: frame " << file_name << " is empty!" << std::endl; return std::make_pair(false, cv::Mat()); } cv::resize(image, image, cv::Size(parameters_.width, parameters_.height)); return std::make_pair(true, image); } std::pair<bool, MatrixXf> YcbVideoCamera::getDepthImage(const bool& blocking) { std::FILE* in; std::string file_name = path_depth_images_ + composeFileName(head_, number_of_digits_) + ".float"; if ((in = std::fopen(file_name.c_str(), "rb")) == nullptr) { std::cout << log_ID_ << "::ctor. Error: cannot load depth frame " + file_name; return std::make_pair(true, MatrixXf()); } /* Load image size .*/ std::size_t dims[2]; std::fread(dims, sizeof(dims), 1, in); /* Load image. */ float float_image_raw[dims[0] * dims[1]]; std::fread(float_image_raw, sizeof(float), dims[0] * dims[1], in); /* Store image. */ MatrixXf float_image(dims[1], dims[0]); float_image = Map<Matrix<float, -1, -1, RowMajor>>(float_image_raw, dims[1], dims[0]); /* Handle resize if required (downscaling from 640x480 to 320x240 is the only one supported). */ MatrixXf depth; if ((float_image.cols() != parameters_.width) && (float_image.rows() != parameters_.height)) { if ((float_image.cols() == 640) && (float_image.rows() == 480) && (parameters_.width == 320) && (parameters_.height == 240)) { depth.resize(parameters_.height, parameters_.width); for (std::size_t i = 0; i < float_image.rows(); i += 2) for (std::size_t j = 0; j < float_image.cols(); j += 2) depth(i / 2, j / 2) = float_image(i, j); } } else depth = float_image; std::fclose(in); return std::make_pair(true, depth); } std::pair<bool, Transform<double, 3, Affine>> YcbVideoCamera::getCameraPose(const bool& blocking) { return std::make_pair(true, Transform<double, 3, Affine>::Identity()); } std::string YcbVideoCamera::composeFileName(const std::size_t& index, const std::size_t& number_digits) { std::ostringstream ss; ss << std::setw(number_digits) << std::setfill('0') << index; return ss.str(); } bool YcbVideoCamera::checkImage(const std::size_t& index) { std::ifstream in; std::string file_name = path_rgb_images_ + composeFileName(index, number_of_digits_) + ".png"; in.open(file_name); bool outcome = in.is_open(); if (!outcome) { std::cout << log_ID_ << "::checkImage. Warning: cannot open file " << file_name << std::endl; } in.close(); return outcome; }
4,745
C++
.cpp
135
29.940741
132
0.620863
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,919
InitGroundTruth.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/InitGroundTruth.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <InitGroundTruth.h> #include <fstream> #include <iostream> #include <vector> using namespace Eigen; InitGroundTruth::InitGroundTruth ( const std::string& path, const std::string& object_name, const std::size_t& frame_index, const MatrixXd& initial_covariance ) : index_(frame_index) { /* Compose root path. */ std::string root = path; if (root.back() != '/') root += '/'; /* Compose path containing ground truth data. */ std::string file_name = root + "gt_" + object_name.substr(object_name.find("_") + 1) + "/data.log"; /* Load data. */ bool valid_data = false; data_shift_ = 0; std::tie(valid_data, data_) = readStateFromFile(file_name, 9); if (!valid_data) { // Try with a different format file_name = root + "gt/data.log"; std::tie(valid_data, data_) = readStateFromFile(file_name, 10); data_shift_ = 1; if (!valid_data) { std::string error = log_ID_ + "::ctor. Error: cannot open ground truth data (" + file_name + ")"; throw(std::runtime_error(error)); } } /* Extract initial pose and convert to x-y-z-Euler(Z, Y, X). */ initial_pose_ = VectorXd::Zero(12); initial_pose_.head<3>() = data_.col(frame_index).segment<3>(2 + data_shift_); AngleAxisd angle_axis(data_.col(frame_index)(8 + data_shift_), data_.col(frame_index).segment<3>(5 + data_shift_)); initial_pose_.tail<3>() = angle_axis.toRotationMatrix().eulerAngles(2, 1, 0); initial_covariance_ = initial_covariance; initial_pose_.head<3>()(0) += 0.05; initial_pose_.head<3>()(1) += 0.05; initial_pose_.head<3>()(2) += 0.05; initial_pose_.tail<3>()(0) += 10.0 * M_PI / 180; initial_pose_.tail<3>()(1) += 10.0 * M_PI / 180; initial_pose_.tail<3>()(2) += 10.0 * M_PI / 180; } InitGroundTruth::~InitGroundTruth() noexcept { } Eigen::VectorXd InitGroundTruth::getInitialPose() { return initial_pose_; } Eigen::MatrixXd InitGroundTruth::getInitialCovariance() { return initial_covariance_; } std::pair<bool, MatrixXd> InitGroundTruth::readStateFromFile(const std::string& filename, const std::size_t num_fields) { MatrixXd data; std::ifstream istrm(filename); if (!istrm.is_open()) { return std::make_pair(false, MatrixXd(0,0)); } std::vector<std::string> istrm_strings; std::string line; while (std::getline(istrm, line)) { istrm_strings.push_back(line); } data.resize(num_fields, istrm_strings.size()); std::size_t found_lines = 0; for (auto line : istrm_strings) { std::size_t found_fields = 0; std::string number_str; std::istringstream iss(line); while (iss >> number_str) { std::size_t index = (num_fields * found_lines) + found_fields; *(data.data() + index) = std::stod(number_str); found_fields++; } if (num_fields != found_fields) { return std::make_pair(false, MatrixXd(0,0)); } found_lines++; } return std::make_pair(true, data); }
3,362
C++
.cpp
100
28.11
119
0.616502
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,920
DiscretizedKinematicModel.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/DiscretizedKinematicModel.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <DiscretizedKinematicModel.h> #include <Eigen/Dense> using namespace Eigen; using namespace bfl; DiscretizedKinematicModel::DiscretizedKinematicModel ( const double sigma_x, const double sigma_y, const double sigma_z, const double sigma_yaw, const double sigma_pitch, const double sigma_roll, const double period, const bool estimate_period ) { estimate_period_ = estimate_period; sigma_position_.resize(3); sigma_position_ << sigma_x, sigma_y, sigma_z; sigma_orientation_.resize(3); sigma_orientation_ << sigma_yaw, sigma_pitch, sigma_roll; F_.resize(12, 12); F_ = MatrixXd::Zero(12, 12); Q_.resize(12, 12); Q_ = MatrixXd::Zero(12, 12); // Evaluate F and Q matrices using a default // sampling time to be updated online evaluateStateTransitionMatrix(period); evaluateNoiseCovarianceMatrix(period); } DiscretizedKinematicModel::~DiscretizedKinematicModel() { } void DiscretizedKinematicModel::evaluateStateTransitionMatrix(const double T) { // Compute the state transition matrix F_.block<3, 3>(0, 0) = Matrix3d::Identity(); F_.block<3, 3>(0, 3) = T * Matrix3d::Identity(); F_.block<3, 3>(3, 3) = Matrix3d::Identity(); F_.block<3, 3>(6, 6) = Matrix3d::Identity(); F_.block<3, 3>(9, 6) = T * Matrix3d::Identity(); F_.block<3, 3>(9, 9) = Matrix3d::Identity(); } void DiscretizedKinematicModel::evaluateNoiseCovarianceMatrix(const double T) { // Compose noise covariance matrix for the linear acceleration part MatrixXd Q_pos(6, 6); Q_pos.block<3, 3>(0, 0) = sigma_position_.asDiagonal() * (std::pow(T, 3.0) / 3.0); Q_pos.block<3, 3>(0, 3) = sigma_position_.asDiagonal() * (std::pow(T, 2.0) / 2.0); Q_pos.block<3, 3>(3, 0) = sigma_position_.asDiagonal() * (std::pow(T, 2.0) / 2.0); Q_pos.block<3, 3>(3, 3) = sigma_position_.asDiagonal() * T; // Compose noise covariance matrix for the euler angle rates part MatrixXd Q_ang(6, 6); Q_ang.block<3, 3>(0, 0) = sigma_orientation_.asDiagonal() * T; Q_ang.block<3, 3>(0, 3) = sigma_orientation_.asDiagonal() * (std::pow(T, 2.0) / 2.0); Q_ang.block<3, 3>(3, 0) = sigma_orientation_.asDiagonal() * (std::pow(T, 2.0) / 2.0); Q_ang.block<3, 3>(3, 3) = sigma_orientation_.asDiagonal() * (std::pow(T, 3.0) / 3.0); Q_.block<6, 6>(0, 0) = Q_pos; Q_.block<6, 6>(6, 6) = Q_ang; } VectorDescription DiscretizedKinematicModel::getInputDescription() { // 9 linear components (x, y, z, x_dot, y_dot, z_dot, yaw_dot, pitch_dot, roll_dot) // 3 angular components (yaw, pitch, roll) // 12 noise components return VectorDescription(9, 3, 12, VectorDescription::CircularType::Euler); } VectorDescription DiscretizedKinematicModel::getStateDescription() { // 9 linear components (x, y, z, x_dot, y_dot, z_dot, yaw_dot, pitch_dot, roll_dot) // 3 angular components (yaw, pitch, roll) // 0 noise components return VectorDescription(9, 3, 0, VectorDescription::CircularType::Euler); } Eigen::MatrixXd DiscretizedKinematicModel::getStateTransitionMatrix() { return F_; } Eigen::MatrixXd DiscretizedKinematicModel::getNoiseCovarianceMatrix() { return Q_; } bool DiscretizedKinematicModel::setProperty(const std::string& property) { if (property == "tick") { if (estimate_period_) { // Evaluate elapsed time and reset matrices F_ and Q_ std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); if (last_time_set_) { std::chrono::duration<double, std::milli> delta_chrono = now - last_time_; double delta = delta_chrono.count() / 1000.0; evaluateStateTransitionMatrix(delta); evaluateNoiseCovarianceMatrix(delta); } last_time_ = now; last_time_set_ = true; } return true; } else if (property == "reset") { last_time_set_ = false; } return false; }
4,241
C++
.cpp
108
34.148148
90
0.658376
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,921
UKFFilter.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/UKFFilter.cpp
/* f * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <UKFFilter.h> #include <BayesFilters/utils.h> using namespace bfl; using namespace Eigen; UKFFilter::UKFFilter ( std::unique_ptr<InitGroundTruth> initialization, std::unique_ptr<GaussianPrediction> prediction, std::unique_ptr<GaussianCorrection> correction ) : GaussianFilter(std::move(prediction), std::move(correction)), initialization_(std::move(initialization)) { } UKFFilter::~UKFFilter() { disable_log(); } bool UKFFilter::run_condition() { return true; } bool UKFFilter::initialization_step() { pred_belief_.resize(12); corr_belief_.resize(12); pred_belief_.mean() = initialization_->getInitialPose(); pred_belief_.covariance() = initialization_->getInitialCovariance(); return true; } std::vector<std::string> UKFFilter::log_file_names(const std::string& prefix_path, const std::string& prefix_name) { return {prefix_path + "/" + prefix_name + "_estimate", prefix_path + "/" + prefix_name + "_ground_truth", prefix_path + "/" + prefix_name + "_fps"}; } void UKFFilter::filtering_step() { // When there are no more images in the dataset, teardown() is invoked if(!correction().getMeasurementModel().setProperty("measurements_available")) { teardown(); return; } startTimeCount(); if (step_number() == 0) correction().freeze_measurements(pred_belief_); else correction().freeze_measurements(corr_belief_); if (step_number() != 0) prediction().predict(corr_belief_, pred_belief_); correction().correct(pred_belief_, corr_belief_); // Tick the state model prediction().getStateModel().setProperty("tick"); // Evaluate fps double execution_time = stopTimeCount(); double fps = (execution_time != 0) ? (1 / execution_time) : -1; // Send data VectorXd estimate(14); estimate.head<3>() = corr_belief_.mean().head<3>(); AngleAxisd angle_axis(AngleAxisd(corr_belief_.mean(9), Vector3d::UnitZ()) * AngleAxisd(corr_belief_.mean(10), Vector3d::UnitY()) * AngleAxisd(corr_belief_.mean(11), Vector3d::UnitX())); estimate.segment<3>(3) = angle_axis.axis(); estimate(6) = angle_axis.angle(); estimate.segment<3>(7) = corr_belief_.mean().segment<3>(3); estimate.segment<3>(10) = corr_belief_.mean().segment<3>(6); estimate(13) = keyframe_counter_; logger(estimate.transpose(), last_ground_truth_.transpose(), fps); // Increase keyframe counter keyframe_counter_++; } void UKFFilter::startTimeCount() { std_time_0_ = std::chrono::steady_clock::now(); } double UKFFilter::stopTimeCount() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - std_time_0_).count() / 1000.0; }
3,037
C++
.cpp
86
30.651163
130
0.672485
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,922
PointCloudModel.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/PointCloudModel.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <PointCloudModel.h> using namespace bfl; using namespace Eigen; PointCloudModel::PointCloudModel ( std::unique_ptr<PointCloudPrediction> prediction, const Eigen::Ref<const Eigen::Matrix3d>& noise_covariance_matrix, const Eigen::Ref<const Eigen::Matrix3d>& tactile_noise_covariance_matrix ) : prediction_(std::move(prediction)), model_noise_covariance_(noise_covariance_matrix), tactile_model_noise_covariance_(tactile_noise_covariance_matrix) { } std::pair<bool, bfl::Data> PointCloudModel::predictedMeasure(const Eigen::Ref<const Eigen::MatrixXd>& cur_states) const { bool valid_measure; bfl::Data measurement; std::tie(valid_measure, measurement) = measure(); if (!valid_measure) return std::make_pair(false, Data()); bool valid_prediction; MatrixXd prediction; std::tie(valid_prediction, prediction) = prediction_->predictPointCloud(cur_states, any::any_cast<MatrixXd>(measurement).col(0)); if (!valid_prediction) return std::make_pair(false, Data()); return std::make_pair(true, prediction); } std::pair<bool, bfl::Data> PointCloudModel::innovation(const bfl::Data& predicted_measurements, const bfl::Data& measurements) const { MatrixXd innovation = -(any::any_cast<MatrixXd>(predicted_measurements).colwise() - any::any_cast<MatrixXd>(measurements).col(0)); return std::make_pair(true, std::move(innovation)); } std::pair<bool, MatrixXd> PointCloudModel::getNoiseCovarianceMatrix() const { return std::make_pair(true, model_noise_covariance_); } std::pair<bool, MatrixXd> PointCloudModel::getTactileNoiseCovarianceMatrix() const { return std::make_pair(true, tactile_model_noise_covariance_); }
1,930
C++
.cpp
46
38.413043
134
0.746788
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,923
PointCloudSegmentation.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/PointCloudSegmentation.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <PointCloudSegmentation.h> PointCloudSegmentation::PointCloudSegmentation() { } PointCloudSegmentation::~PointCloudSegmentation() { } bool PointCloudSegmentation::getProperty(const std::string& property) const { return true; } bool PointCloudSegmentation::setProperty(const std::string& property) { return true; }
548
C++
.cpp
19
26.684211
75
0.794231
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,924
Correction.cpp
hsp-iit_mask-ukf/src/mask-ukf-tracker/src/Correction.cpp
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <Correction.h> #include <cmath> using namespace bfl; using namespace Eigen; Correction::Correction ( std::unique_ptr<AdditiveMeasurementModel> meas_model, /** * Unscented transform parameters */ const double alpha, const double beta, const double kappa, /** * Subsize, J, of measurement vector y in R^M such that * M = k * J for some positive integer k */ const std::size_t meas_sub_size ) noexcept : SUKFCorrection(std::move(meas_model), alpha, beta, kappa, meas_sub_size, true) { } void Correction::correctStep(const GaussianMixture& pred_state, GaussianMixture& corr_state) { SUKFCorrection::correctStep(pred_state, corr_state); // Handle angular components of the state corr_state.mean().bottomRows(3) = (std::complex<double>(0.0,1.0) * corr_state.mean().bottomRows(3)).array().exp().arg(); }
1,106
C++
.cpp
33
30.030303
124
0.702347
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,925
MetricAddS.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/MetricAddS.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef METRICADDS_H #define METRICADDS_H #include <Eigen/Dense> #include <Metric.h> class MetricAddS : public Metric { public: MetricAddS(); ~MetricAddS(); Eigen::VectorXd evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) override; }; #endif /* METRICADDS_H */
603
C++
.h
18
31.111111
192
0.746967
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,926
ResultsPoseRBPFADDS.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/ResultsPoseRBPFADDS.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <Results.h> #include <map> class ResultsPoseRBPFADDS : public Results { public: ResultsPoseRBPFADDS() { map_add_s_auc_ = { {"002_master_chef_can", 95.1}, {"003_cracker_box", 93.0}, {"004_sugar_box", 95.5}, {"005_tomato_soup_can", 93.8}, {"006_mustard_bottle", 96.3}, {"007_tuna_fish_can", 95.3}, {"008_pudding_box", 92.0}, {"009_gelatin_box", 97.5}, {"010_potted_meat_can", 77.9}, {"011_banana", 86.9}, {"019_pitcher_base", 94.2}, {"021_bleach_cleanser", 93.0}, {"024_bowl", 94.2}, {"025_mug", 97.1}, {"035_power_drill", 96.1}, {"036_wood_block", 89.1}, {"037_scissors", 85.6}, {"040_large_marker", 97.1}, {"051_large_clamp", 94.8}, {"052_extra_large_clamp", 90.1}, {"061_foam_brick", 95.7}, {"all", 93.3} }; } };
1,234
C++
.h
40
22.15
71
0.497061
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,927
ObjectResults.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/ObjectResults.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef OBJECTRESULTS_H #define OBJECTRESULTS_H #include <Eigen/Dense> #include <Metric.h> #include <Results.h> #include <SingleVideoResult.h> #include <memory> #include <string> #include <unordered_map> #include <vector> class ObjectResults : public Results { public: ObjectResults ( const std::string& object_name, const bool& object_has_symmetry, const Eigen::Vector3d& object_symmetry_axis, const std::string& model_path, const std::string& result_path, const std::vector<std::string>& test_set, const std::unordered_map<std::string, std::vector<std::size_t>>& keyframes, const std::unordered_map<std::string, std::pair<std::size_t, std::size_t>>& excluded_keyframes, const std::vector<std::string>& metrics, const double& max_error ); ObjectResults ( const std::string& object_name, const bool& object_has_symmetry, const Eigen::Vector3d& object_symmetry_axis, const std::string& model_path, const std::string& result_path, const std::vector<std::string>& test_set, const std::size_t skip_frames, const std::vector<std::string>& metrics, const double& max_error ); ObjectResults(const std::vector<std::unique_ptr<const ObjectResults>>& results_set, const std::vector<std::string>& metrics, const double& max_error); std::tuple<std::size_t, std::vector<double>> getErrors() const; std::tuple<std::size_t, double, double> getRMSE() const; std::tuple<std::size_t, double, double> getRMSEV() const; std::tuple<std::size_t, double> getFPS() const; private: double evaluateAUC(const std::vector<double>& errors, const double& max_threshold); std::pair<bool, Eigen::MatrixXd> loadPointCloudFromFile(const std::string& filename); std::unordered_map<std::string, SingleVideoResult> results_; std::unordered_map<std::string, std::unique_ptr<Metric>> metric_; std::vector<double> errors_; double rmse_position_; double rmse_orientation_; double fps_; std::size_t counter_; const std::string log_ID_ = "[ObjectResults]"; }; #endif /* OBJECTRESULTS_H */
2,418
C++
.h
62
33.66129
154
0.68667
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,928
Metric.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/Metric.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef METRIC_H #define METRIC_H #include <Eigen/Dense> class Metric { public: Metric(); virtual ~Metric(); virtual Eigen::VectorXd evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) = 0; virtual Eigen::VectorXd evaluate(const Eigen::VectorXd& estimate, const Eigen::VectorXd& ground_truth, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth_pose); }; #endif /* METRIC_H */
731
C++
.h
18
38
195
0.741844
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,929
PointCloudAdaptor.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/PointCloudAdaptor.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef POINTCLOUDADAPTOR_H #define POINTCLOUDADAPTOR_H struct PointCloudAdaptor { const Eigen::Ref<const Eigen::MatrixXd> data; PointCloudAdaptor(const Eigen::Ref<const Eigen::MatrixXd>& data_) : data(data_) { } /// CRTP helper method inline Eigen::Ref<const Eigen::MatrixXd> derived() const { return data; } // Must return the number of data points inline std::size_t kdtree_get_point_count() const { return data.cols(); } // Returns the dim'th component of the idx'th point in the class: inline double kdtree_get_pt(const size_t idx, const size_t dim) const { return derived()(dim, idx); } // Optional bounding-box computation: return false to default to a standard bbox computation loop. // Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again. // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX& /*bb*/) const { return false; } }; #endif
1,284
C++
.h
28
41.964286
126
0.713942
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,930
MetricEmpty.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/MetricEmpty.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef METRICEMPTY_H #define METRICEMPTY_H #include <Eigen/Dense> #include <Metric.h> class MetricEmpty : public Metric { public: MetricEmpty(); virtual ~MetricEmpty(); Eigen::VectorXd evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model); }; #endif /* METRICEMPTY_H */
608
C++
.h
18
31.388889
183
0.749141
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,931
Results.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/Results.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef RESULTS_H #define RESULTS_H #include <map> class Results { public: std::map<std::string, double> map_rmse_position_; std::map<std::string, double> map_rmse_orientation_; std::map<std::string, double> map_add_s_auc_; std::map<std::string, double> map_add_s_less_; std::map<std::string, double> map_fps_; }; #endif
557
C++
.h
19
26.578947
71
0.713208
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,932
MetricRMS.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/MetricRMS.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef METRICRMS_H #define METRICRMS_H #include <Eigen/Dense> #include <Metric.h> class MetricRMS : public Metric { public: MetricRMS(); ~MetricRMS(); Eigen::VectorXd evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) override; }; #endif /* METRICRMS_H */
597
C++
.h
18
30.777778
192
0.744308
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,933
MetricRMSSymmetry.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/MetricRMSSymmetry.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef METRICRMSSYMMETRY_H #define METRICRMSSYMMETRY_H #include <Eigen/Dense> #include <Metric.h> class MetricRMSSymmetry : public Metric { public: MetricRMSSymmetry(const Eigen::VectorXd& symmetry_axis); ~MetricRMSSymmetry(); Eigen::VectorXd evaluate(const Eigen::Transform<double, 3, Eigen::Affine>& estimate, const Eigen::Transform<double, 3, Eigen::Affine>& ground_truth, const Eigen::MatrixXd& model) override; std::pair<Eigen::AngleAxisd, Eigen::AngleAxisd> twistSwingDecomposition(const Eigen::AngleAxisd& rotation, const Eigen::Vector3d& twist_axis); private: Eigen::VectorXd symmetry_axis_; }; #endif /* METRICRMSSYMMETRY_H */
875
C++
.h
21
39
192
0.770142
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,934
kdTree.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/kdTree.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef KDTREE_H #define KDTREE_H #include <PointCloudAdaptor.h> #include <nanoflann.hpp> using kdTree = nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloudAdaptor >, PointCloudAdaptor, 3 /* dimension, since using point clouds */>; #endif
585
C++
.h
14
32.857143
108
0.645503
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,935
ResultsDenseFusionADDS.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/ResultsDenseFusionADDS.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #include <Results.h> #include <map> class ResultsDenseFusionADDS : public Results { public: ResultsDenseFusionADDS() { map_add_s_auc_ = { {"002_master_chef_can", 96.4}, {"003_cracker_box", 95.5}, {"004_sugar_box", 97.5}, {"005_tomato_soup_can", 94.6}, {"006_mustard_bottle", 97.2}, {"007_tuna_fish_can", 96.6}, {"008_pudding_box", 96.5}, {"009_gelatin_box", 98.1}, {"010_potted_meat_can", 91.3}, {"011_banana", 96.6}, {"019_pitcher_base", 97.1}, {"021_bleach_cleanser", 95.8}, {"024_bowl", 88.2}, {"025_mug", 97.1}, {"035_power_drill", 96.0}, {"036_wood_block", 89.7}, {"037_scissors", 95.2}, {"040_large_marker", 97.5}, {"051_large_clamp", 72.9}, {"052_extra_large_clamp", 69.8}, {"061_foam_brick", 92.5}, {"all", 93.1} }; map_add_s_less_ = { {"002_master_chef_can", 100.0}, {"003_cracker_box", 99.5}, {"004_sugar_box", 100.0}, {"005_tomato_soup_can", 96.9}, {"006_mustard_bottle", 100.0}, {"007_tuna_fish_can", 100.0}, {"008_pudding_box", 100.0}, {"009_gelatin_box", 100.0}, {"010_potted_meat_can", 93.1}, {"011_banana", 100.0}, {"019_pitcher_base", 100.0}, {"021_bleach_cleanser", 100.0}, {"024_bowl", 98.8}, {"025_mug", 100.0}, {"035_power_drill", 98.7}, {"036_wood_block", 94.6}, {"037_scissors", 100.0}, {"040_large_marker", 100.0}, {"051_large_clamp", 79.2}, {"052_extra_large_clamp", 76.3}, {"061_foam_brick", 100.0}, {"all", 96.8} }; } };
2,148
C++
.h
65
22.861538
71
0.464165
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,936
SingleVideoResult.h
hsp-iit_mask-ukf/src/mask-ukf-evaluator/include/SingleVideoResult.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef SINGLEVIDEORESULT_H #define SINGLEVIDEORESULT_H #include <Eigen/Dense> class SingleVideoResult { public: SingleVideoResult(const std::string& object_name, const std::string& video_name, const std::string& result_path); Eigen::Transform<double, 3, Eigen::Affine> getObjectPose(const std::size_t& frame_id) const; Eigen::Transform<double, 3, Eigen::Affine> getGroundTruthPose(const std::size_t& frame_id) const; Eigen::VectorXd getObjectVelocity(const std::size_t& frame_id) const; Eigen::VectorXd getGroundTruthVelocity(const std::size_t& frame_id, const std::size_t& frame_id_0); double getFPS(const std::size_t& frame_id) const; std::string getVideoName() const; std::size_t getNumberFrames() const; private: std::pair<bool, Eigen::MatrixXd> readDataFromFile(const std::string& filename, const std::size_t num_fields); Eigen::MatrixXd padMissingFrames(const Eigen::MatrixXd& data, const std::size_t& expected_length); Eigen::Transform<double, 3, Eigen::Affine> makeTransform(const Eigen::VectorXd pose) const; Eigen::MatrixXd estimate_; Eigen::MatrixXd ground_truth_; Eigen::MatrixXd fps_; Eigen::VectorXd last_v_; const std::string video_name_; const std::string log_ID_ = "[SingleVideoResult]"; }; #endif /* SINGLEVIDEORESULT_H */
1,538
C++
.h
32
44.15625
117
0.741588
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,937
ObjectPointCloudPrediction.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/ObjectPointCloudPrediction.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef OBJECTPOINTCLOUDPREDICTION_H #define OBJECTPOINTCLOUDPREDICTION_H #include <Eigen/Dense> #include <PointCloudPrediction.h> #include <kdTree.h> #include <BayesFilters/ParticleSet.h> #include <BayesFilters/ParticleSetInitialization.h> #include <memory> #include <string> class ObjectPointCloudPrediction : public PointCloudPrediction { public: ObjectPointCloudPrediction(const std::string& point_cloud_filename); ~ObjectPointCloudPrediction(); std::pair<bool, Eigen::MatrixXd> predictPointCloud(ConstMatrixXdRef state, ConstVectorXdRef meas) override; std::pair<bool, Eigen::MatrixXd> evaluateDistances(ConstMatrixXdRef state, ConstVectorXdRef meas) override; Eigen::MatrixXd evaluateModel(const Eigen::Transform<double, 3, Eigen::Affine>& object_pose); private: std::pair<bool, Eigen::MatrixXd> loadPointCloudFromFile(const std::string& filename); Eigen::MatrixXd cloud_; const std::string log_ID_ = "ObjectPointCloudPrediction"; }; #endif
1,202
C++
.h
29
38.655172
111
0.7962
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,938
StaticPrediction.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/StaticPrediction.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef STATICPREDICTION_H #define STATICPREDICTION_H #include <BayesFilters/GaussianMixture.h> #include <BayesFilters/GaussianPrediction.h> #include <BayesFilters/StateModel.h> #include <BayesFilters/VectorDescription.h> #include <memory> class StaticModel : public bfl::StateModel { public: StaticModel() { }; virtual ~StaticModel() { }; void propagate(const Eigen::Ref<const Eigen::MatrixXd>& cur_states, Eigen::Ref<Eigen::MatrixXd> prop_states) override { }; void motion(const Eigen::Ref<const Eigen::MatrixXd>& cur_states, Eigen::Ref<Eigen::MatrixXd> mot_states) override { }; bool setProperty(const std::string& property) override { return false; }; bfl::VectorDescription getInputDescription() override { // 9 linear components (x, y, z, x_dot, y_dot, z_dot, yaw_dot, pitch_dot, roll_dot) // 3 angular components (yaw, pitch, roll) // 12 noise components return bfl::VectorDescription(9, 3, 12, bfl::VectorDescription::CircularType::Euler); }; bfl::VectorDescription getStateDescription() override { // 9 linear components (x, y, z, x_dot, y_dot, z_dot, yaw_dot, pitch_dot, roll_dot) // 3 angular components (yaw, pitch, roll) // 0 noise components return bfl::VectorDescription(9, 3, 0, bfl::VectorDescription::CircularType::Euler); }; }; class StaticPrediction : public bfl::GaussianPrediction { public: StaticPrediction(); virtual ~StaticPrediction(); bfl::StateModel& getStateModel() noexcept override; protected: void predictStep(const bfl::GaussianMixture& prev_state, bfl::GaussianMixture& pred_state) override; private: std::unique_ptr<StaticModel> model_placeholder_; }; #endif /* STATICPREDICTION_H */
2,005
C++
.h
55
32.127273
121
0.712733
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,939
Correction.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/Correction.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef CORRECTION_H #define CORRECTION_H #include <BayesFilters/AdditiveMeasurementModel.h> #include <BayesFilters/SUKFCorrection.h> #include <ObjectMeasurements.h> class Correction : public bfl::SUKFCorrection { public: Correction ( std::unique_ptr<bfl::AdditiveMeasurementModel> meas_model, /** * Unscented transform parameters */ const double alpha, const double beta, const double kappa, /** * Subsize, J, of measurement vector y in R^M such that * M = k * J for some positive integer k */ const std::size_t meas_sub_size ) noexcept; void correctStep(const bfl::GaussianMixture& pred_state, bfl::GaussianMixture& corr_state) override; }; #endif /* CORRECTION_H */
1,017
C++
.h
32
26.71875
104
0.677914
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,940
CorrectionICP.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/CorrectionICP.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef CORRECTIONICP_H #define CORRECTIONICP_H #include <BayesFilters/AdditiveMeasurementModel.h> #include <BayesFilters/GaussianCorrection.h> #include <Eigen/Dense> #include <ObjectMeasurements.h> class CorrectionICP : public bfl::GaussianCorrection { public: CorrectionICP(std::unique_ptr<bfl::AdditiveMeasurementModel> measurement_model, const std::string& point_cloud_filename); virtual ~CorrectionICP(); void correctStep(const bfl::GaussianMixture& pred_state, bfl::GaussianMixture& corr_state) override; bfl::MeasurementModel& getMeasurementModel() override; private: std::pair<bool, Eigen::MatrixXd> loadPointCloudFromFile(const std::string& filename); std::unique_ptr<bfl::AdditiveMeasurementModel> measurement_model_; Eigen::MatrixXd model_; const std::string log_ID_ = "CorrectionICP"; }; #endif /* CORRECTIONICP_H */
1,083
C++
.h
26
38.692308
125
0.7814
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,941
ObjectMeasurements.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/ObjectMeasurements.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef OBJECTMEASUREMENTS_H #define OBJECTMEASUREMENTS_H #include <BayesFilters/AdditiveMeasurementModel.h> #include <BayesFilters/Data.h> #include <BayesFilters/VectorDescription.h> #include <Camera.h> #include <PointCloudPrediction.h> #include <PointCloudSegmentation.h> #include <Eigen/Dense> #include <memory> class ObjectMeasurements : public bfl::AdditiveMeasurementModel { public: ObjectMeasurements(std::unique_ptr<Camera> camera, std::shared_ptr<PointCloudSegmentation> segmentation, std::shared_ptr<PointCloudPrediction> prediction, const Eigen::Ref<const Eigen::Matrix3d>& visual_noise_covariance, const std::string& depth_fetch_mode); ~ObjectMeasurements(); std::pair<bool, bfl::Data> measure(const bfl::Data& data = bfl::Data()) const; bool freeze(const bfl::Data& data = bfl::Data()) override; bfl::VectorDescription getInputDescription() const override; bfl::VectorDescription getMeasurementDescription() const override; std::pair<bool, bfl::Data> predictedMeasure(const Eigen::Ref<const Eigen::MatrixXd>& current_states) const override; std::pair<bool, bfl::Data> innovation(const bfl::Data& predicted_measurements, const bfl::Data& measurements) const override; std::pair<bool, Eigen::MatrixXd> getNoiseCovarianceMatrix() const override; bool setProperty(const std::string& property) override; void enableOutlierRejection(const bool& enable); protected: bool getDepth(); virtual void reset(); /** * Local copy of depht image. */ Eigen::MatrixXf depth_; std::string depth_fetch_mode_; bool depth_initialized_ = false; /** * Local copy of measurements. * A vector of size 3 * L with L the number of points in set. */ Eigen::MatrixXd measurement_; std::unique_ptr<Camera> camera_; std::shared_ptr<PointCloudSegmentation> segmentation_; std::shared_ptr<PointCloudPrediction> prediction_; Eigen::Matrix3d visual_noise_covariance_; bool measurements_available_ = true; bool outlier_rejection_ = false; std::vector<std::string> log_file_names(const std::string& prefix_path, const std::string& prefix_name) override { return {prefix_path + "/" + prefix_name + "_measurements"}; } }; #endif /* OBJECTMEASUREMENTS_H */
2,513
C++
.h
56
40.625
262
0.742268
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,942
InitGroundTruth.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/InitGroundTruth.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef INITGROUNDTRUTH_H #define INITGROUNDTRUTH_H #include <Eigen/Dense> class InitGroundTruth { public: InitGroundTruth(const std::string& path, const std::string& object_name, const std::size_t& frame_index, const Eigen::MatrixXd& initial_covariance); virtual ~InitGroundTruth() noexcept; Eigen::VectorXd getInitialPose(); Eigen::MatrixXd getInitialCovariance(); protected: std::pair<bool, Eigen::MatrixXd> readStateFromFile(const std::string& filename, const std::size_t num_fields); Eigen::MatrixXd data_; std::size_t data_shift_; Eigen::VectorXd initial_pose_; Eigen::MatrixXd initial_covariance_; std::size_t index_ = 0; std::string log_ID_ = "InitGroundTruth"; }; #endif /* INITGROUNDTRUTH_H */
971
C++
.h
26
33.884615
152
0.741935
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,943
MaskSegmentation.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/MaskSegmentation.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef MASKSEGMENTATION_H #define MASKSEGMENTATION_H #include <Eigen/Dense> #include <Camera.h> #include <PointCloudSegmentation.h> class MaskSegmentation : public PointCloudSegmentation { public: MaskSegmentation(const std::string& path, const std::string& mask_name, const std::size_t& depth_stride, const std::string& masks_set); MaskSegmentation(const std::string& path, const std::string& mask_name, const std::size_t& depth_stride, const std::string& masks_set, const double& simulated_fps); ~MaskSegmentation(); bool freezeSegmentation(Camera& camera) override; std::tuple<bool, std::size_t, Eigen::MatrixXd> extractPointCloud(Camera& camera, const Eigen::Ref<const Eigen::MatrixXf>& depth, const double& max_depth) override; bool setProperty(const std::string& property) override; protected: std::string composeFileName(const std::size_t& index, const std::size_t& number_digits); std::tuple<bool, bool, cv::Mat> getMask(Camera& camera); std::size_t depth_stride_; std::string mask_name_; std::vector<std::pair<int, int>> coordinates_; cv::Mat mask_; bool mask_initialized_ = false; /** * Required for simulated fps. */ double fps_; const bool simulated_fps_ = false; double original_fps_ = 30.0; /** * Required for offline execution. */ std::string path_mask_images_; std::size_t number_of_digits_ = 6; int head_ = 0; int effective_head_; const std::string log_ID_ = "MaskSegmentation"; }; #endif /* MASKSEGMENTATION_H */
1,781
C++
.h
44
36.159091
168
0.7137
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,944
ConfigParser.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/ConfigParser.h
#ifndef CONFIG_PARSER_H #define CONFIG_PARSER_H #include <iostream> #include <regex> #include <unordered_map> #include <Eigen/Dense> #include <libconfig.h++> #include <tclap/CmdLine.h> class ConfigParser { public: ConfigParser(const int& argc, char** argv, const std::string& file_path = ""); template <class T> void operator()(const std::string& path, T& value) { std::string libconfig_path = std::regex_replace(path, std::regex("::"), "."); try { cfg_.lookupValue(libconfig_path, value); } catch(libconfig::SettingNotFoundException &e) { throw(std::runtime_error("ConfigParser::operator(). Error: cannot find the setting with name " + std::string(e.getPath()))); } } template <class T> void operator()(const std::string& path, std::vector<T>& array) { std::string libconfig_path = std::regex_replace(path, std::regex("::"), "."); try { libconfig::Setting& parameters = cfg_.lookup(libconfig_path); if ((parameters.getType() == libconfig::Setting::TypeArray)) { for (std::size_t i = 0; i < parameters.getLength(); i++) { T value = parameters[i]; array.push_back(value); } } else throw(std::runtime_error("ConfigParser::operator(). Error: cannot find an array setting with name " + libconfig_path)); } catch(libconfig::SettingNotFoundException &e) { throw(std::runtime_error("ConfigParser::operator(). Error: cannot find the setting with name " + std::string(e.getPath()))); } } template <class T> void operator()(const std::string& path, Eigen::Matrix<T, Eigen::Dynamic, 1>& array) { std::vector<T> array_std; operator()<T>(path, array_std); Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> map(array_std.data(), array_std.size()); array = map; } struct ParameterInfo { std::string name; libconfig::Setting::Type type; libconfig::Setting::Type array_type; int array_length; }; private: void add_cli_argument(const ConfigParser::ParameterInfo& parameter_info, TCLAP::CmdLine& cli); void add_cli_arg_from(TCLAP::CmdLine& cli); void get_parameters_list(const libconfig::Setting& parent, std::vector<ParameterInfo>& list, const std::string& parent_name = ""); std::string get_cfg_file_path(const int& argc, char** argv); void process_cli_args_bool(const std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>>& list); void process_cli_args_array(const std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>>& list, const libconfig::Setting::Type& type); template <class T> void process_cli_args(const std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<T>>>& list) { for (const auto& pair : list) { std::string libconfig_path = std::regex_replace(pair.first, std::regex("::"), "."); if(pair.second->isSet()) { cfg_.lookup(libconfig_path) = pair.second->getValue(); } } } template <class T> void process_cli_args_array(const std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>>& list) { std::regex exp; std::string type_description; if (std::is_same<T, int>::value) { type_description = "int"; exp = std::regex("^([+-]?([0-9]*))+(,[ ]{0,}([+-]?([0-9]*))+)*$"); } else if (std::is_same<T, double>::value) { type_description = "double"; exp = std::regex("^([+-]?([0-9]*[.])?[0-9])+(,[ ]{0,}([+-]?([0-9]*[.])?[0-9])+)*$"); } for (const auto& pair : list) { std::string libconfig_path = std::regex_replace(pair.first, std::regex("::"), "."); if(pair.second->isSet()) { std::smatch match; if(!std::regex_search(pair.second->getValue(), match, exp)) throw(std::runtime_error("Provided values for " + pair.first + " are not valid " + type_description + " numbers.")); std::stringstream ss(pair.second->getValue()); std::vector<T> array; T number; while(ss >> number) { array.push_back(number); if (ss.peek() == ',') ss.ignore(); } std::string libconfig_path = std::regex_replace(pair.first, std::regex("::"), "."); libconfig::Setting& parameters = cfg_.lookup(libconfig_path); if (array.size() != parameters.getLength()) throw(std::runtime_error("Expected " + std::to_string(parameters.getLength()) + " values for " + pair.first + ".")); for (std::size_t i = 0; i < array.size(); i++) parameters[i] = array.at(i); } } } libconfig::Config cfg_; std::vector<std::string> allowed_booleans_string_ = {"true", "false"}; TCLAP::ValuesConstraint<std::string> allowed_booleans_; std::unique_ptr<TCLAP::ValueArg<std::string>> cli_arg_from_; const std::string default_path_; /* Plain types. */ std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>> cli_args_bool_; std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<double>>> cli_args_double_; std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<int>>> cli_args_int_; std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>> cli_args_string_; /* Arrays. */ std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>> cli_args_int_array_; std::unordered_map<std::string, std::unique_ptr<TCLAP::ValueArg<std::string>>> cli_args_double_array_; }; #endif /* CONFIG_PARSER_H */
6,160
C++
.h
138
35.050725
162
0.571739
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,945
Camera.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/Camera.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef CAMERA_H #define CAMERA_H #include <CameraParameters.h> #include <Eigen/Dense> #include <opencv2/opencv.hpp> #include <string> class Camera { public: virtual ~Camera(); virtual bool initialize(); virtual bool freeze(); virtual bool reset(); virtual bool setFrame(const std::size_t& number); virtual std::pair<bool, Eigen::Transform<double, 3, Eigen::Affine>> getCameraPose(const bool& blocking) = 0; virtual std::pair<bool, cv::Mat> getRgbImage(const bool& blocking) = 0; virtual std::pair<bool, Eigen::MatrixXf> getDepthImage(const bool& blocking) = 0; virtual std::pair<bool, CameraParameters> getIntrinsicParameters() const; virtual std::pair<bool, Eigen::MatrixXd> getDeprojectionMatrix(); protected: virtual bool evalDeprojectionMatrix(); CameraParameters parameters_; Eigen::MatrixXd deprojection_matrix_; bool deprojection_matrix_initialized_ = false; const std::string log_ID_base_ = "Camera"; }; #endif /* CAMERA_H */
1,225
C++
.h
33
33.484848
112
0.737607
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,946
UKFFilter.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/UKFFilter.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef UKFFILTER_H #define UKFFILTER_H #include <BayesFilters/Gaussian.h> #include <BayesFilters/GaussianCorrection.h> #include <BayesFilters/GaussianFilter.h> #include <BayesFilters/GaussianPrediction.h> #include <BayesFilters/MeasurementModel.h> #include <InitGroundTruth.h> #include <ObjectMeasurements.h> #include <chrono> #include <memory> class UKFFilter : public bfl::GaussianFilter { public: UKFFilter ( std::unique_ptr<InitGroundTruth> initialization, std::unique_ptr<bfl::GaussianPrediction> prediction, std::unique_ptr<bfl::GaussianCorrection> correction ); virtual ~UKFFilter(); bool run_condition() override; bool initialization_step() override; protected: std::vector<std::string> log_file_names(const std::string& prefix_path, const std::string& prefix_name) override; void filtering_step() override; private: void startTimeCount(); double stopTimeCount(); std::chrono::steady_clock::time_point std_time_0_; bfl::Gaussian pred_belief_; bfl::Gaussian corr_belief_; Eigen::VectorXd last_ground_truth_; std::unique_ptr<InitGroundTruth> initialization_; std::size_t keyframe_counter_ = 1; bool pause_ = false; const std::string log_ID_ = "UKFFilter"; }; #endif /* UKFFILTER_H */
1,517
C++
.h
45
29.977778
117
0.741379
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,947
PointCloudModel.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/PointCloudModel.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef POINTCLOUDMODEL_H #define POINTCLOUDMODEL_H #include <BayesFilters/AdditiveMeasurementModel.h> #include <PointCloudPrediction.h> #include <Eigen/Dense> #include <memory> class PointCloudModel : public bfl::AdditiveMeasurementModel { public: PointCloudModel(std::unique_ptr<PointCloudPrediction> prediction, const Eigen::Ref<const Eigen::Matrix3d>& noise_covariance_matrix, const Eigen::Ref<const Eigen::Matrix3d>& tactile_noise_covariance_matrix); std::pair<bool, bfl::Data> predictedMeasure(const Eigen::Ref<const Eigen::MatrixXd>& current_states) const override; std::pair<bool, bfl::Data> innovation(const bfl::Data& predicted_measurements, const bfl::Data& measurements) const override; std::pair<bool, Eigen::MatrixXd> getNoiseCovarianceMatrix() const override; std::pair<bool, Eigen::MatrixXd> getTactileNoiseCovarianceMatrix() const; protected: std::unique_ptr<PointCloudPrediction> prediction_; Eigen::Matrix3d model_noise_covariance_; Eigen::Matrix3d tactile_model_noise_covariance_; std::vector<std::string> log_file_names(const std::string& prefix_path, const std::string& prefix_name) override { return {prefix_path + "/" + prefix_name + "_measurements"}; } }; #endif /* POINTCLOUDMODEL_H */
1,488
C++
.h
30
46.166667
210
0.765603
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,948
DiscretizedKinematicModel.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/DiscretizedKinematicModel.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef DISCRETIZEDKINEMATICMODEL_H #define DISCRETIZEDKINEMATICMODEL_H #include <BayesFilters/LinearStateModel.h> #include <BayesFilters/VectorDescription.h> #include <Eigen/Dense> #include <chrono> class DiscretizedKinematicModel : public bfl::LinearStateModel { public: DiscretizedKinematicModel ( const double sigma_x, const double sigma_y, const double sigma_z, const double sigma_phi, const double sigma_theta, const double sigma_psi, const double period, const bool estimate_period ); virtual ~DiscretizedKinematicModel(); Eigen::MatrixXd getStateTransitionMatrix() override; bool setProperty(const std::string& property) override; Eigen::MatrixXd getNoiseCovarianceMatrix(); bfl::VectorDescription getInputDescription() override; bfl::VectorDescription getStateDescription() override; protected: void evaluateStateTransitionMatrix(const double T); void evaluateNoiseCovarianceMatrix(const double T); /** * State transition matrix. */ Eigen::MatrixXd F_; /** * Noise covariance matrix. */ Eigen::MatrixXd Q_; /** * Squared power spectral densities */ Eigen::VectorXd sigma_position_; Eigen::VectorXd sigma_orientation_; std::chrono::steady_clock::time_point last_time_; bool last_time_set_ = false; bool estimate_period_ = false; }; #endif /* DISCRETIZEDKINEMATICMODEL_H */
1,689
C++
.h
53
27
71
0.726146
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,949
PointCloudPrediction.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/PointCloudPrediction.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef POINTCLOUDPREDICTION_H #define POINTCLOUDPREDICTION_H #include <Eigen/Dense> using ConstMatrixXdRef = const Eigen::Ref<const Eigen::MatrixXd>&; using ConstVectorXdRef = const Eigen::Ref<const Eigen::VectorXd>&; class PointCloudPrediction { public: virtual std::pair<bool, Eigen::MatrixXd> predictPointCloud(ConstMatrixXdRef state, ConstVectorXdRef meas) = 0; virtual std::pair<bool, Eigen::MatrixXd> evaluateDistances(ConstMatrixXdRef state, ConstVectorXdRef meas) = 0; virtual Eigen::MatrixXd evaluateModel(const Eigen::Transform<double, 3, Eigen::Affine>& object_pose) = 0; }; #endif /* POINTCLOUDPREDICTION_H */
851
C++
.h
19
42.473684
114
0.782767
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,950
PointCloudSegmentation.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/PointCloudSegmentation.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef POINTCLOUDSEGMENTATION_H #define POINTCLOUDSEGMENTATION_H #include <Camera.h> #include <Eigen/Dense> class PointCloudSegmentation { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW PointCloudSegmentation(); virtual ~PointCloudSegmentation(); virtual bool freezeSegmentation(Camera& camera) = 0; virtual std::tuple<bool, std::size_t, Eigen::MatrixXd> extractPointCloud(Camera& camera, const Eigen::Ref<const Eigen::MatrixXf>& depth, const double& max_depth) = 0; virtual bool getProperty(const std::string& property) const; virtual bool setProperty(const std::string& property); }; #endif /* POINTCLOUDSEGMENTATION_H */
866
C++
.h
22
36.318182
170
0.769231
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,951
YCBVideoCamera.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/YCBVideoCamera.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef YCBVIDEOCAMERA_H #define YCBVIDEOCAMERA_H #include <Camera.h> #include <Eigen/Dense> class YcbVideoCamera : public Camera { public: YcbVideoCamera(const std::string& path); ~YcbVideoCamera(); bool freeze() override; bool reset() override; bool setFrame(const std::size_t& number) override; std::pair<bool, Eigen::Transform<double, 3, Eigen::Affine>> getCameraPose(const bool& blocking) override; std::pair<bool, cv::Mat> getRgbImage(const bool& blocking) override; std::pair<bool, Eigen::MatrixXf> getDepthImage(const bool& blocking) override; private: std::string composeFileName(const std::size_t& index, const std::size_t& number_digits); bool checkImage(const std::size_t& index); int head_ = 0; std::string path_rgb_images_; std::string path_depth_images_; std::size_t number_of_digits_; const std::string log_ID_ = "YcbVideoCamera"; }; #endif /* YCBVIDEOCAMERANRT_H */
1,172
C++
.h
31
34.032258
109
0.727679
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,952
CameraParameters.h
hsp-iit_mask-ukf/src/mask-ukf-tracker/include/CameraParameters.h
/* * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * GPL-2+ license. See the accompanying LICENSE file for details. */ #ifndef CAMERAPARAMETERS_H #define CAMERAPARAMETERS_H struct CameraParameters { public: int width; int height; double cx; double cy; double fx; double fy; bool initialized = false; }; #endif /* CAMERAPARAMETERS_H */
458
C++
.h
20
19.95
71
0.733796
hsp-iit/mask-ukf
32
9
0
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,953
Main.cpp
bemardev_HekateBrew/Source/Main.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui_MainApplication.hpp> #include <Types.hpp> #include <sys/stat.h> #include <cstdlib> #include <ctime> extern char *fake_heap_end; void *new_heap_addr = NULL; static constexpr u64 HeapSize = 0x10000000; void Initialize() { if ((GetLaunchMode() == LaunchMode::Applet) && R_SUCCEEDED(svcSetHeapSize(&new_heap_addr, HeapSize))) fake_heap_end = (char*) new_heap_addr + HeapSize; splInitialize(); setsysInitialize(); } void Finalize() { if (GetLaunchMode() == LaunchMode::Applet) svcSetHeapSize(&new_heap_addr, ((u8*) envGetHeapOverrideAddr() + envGetHeapOverrideSize()) - (u8*) new_heap_addr); splExit(); setsysExit(); } namespace ui { MainApplication::Ref mainapp; } int main() { Initialize(); ui::mainapp = ui::MainApplication::New(); ui::mainapp->ShowWithFadeIn(); Finalize(); return 0; }
1,682
C++
.cpp
51
29.098039
123
0.70031
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,954
PayloadReboot.cpp
bemardev_HekateBrew/Source/PayloadReboot.cpp
/* * Copyright (c) 2018-2019 Atmosphère-NX * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <cstring> #include <cstdio> #include <cstdbool> #include <switch.h> #include <unistd.h> #include <PayloadReboot.hpp> #include <Utils.hpp> static u8 g_reboot_payload[IRAM_PAYLOAD_MAX_SIZE] alignas(0x1000); static u8 g_ff_page[0x1000] alignas(0x1000); static u8 g_work_page[0x1000] alignas(0x1000); boot_cfg_t *b_cfg = NULL; void do_iram_dram_copy(void *buf, uintptr_t iram_addr, size_t size, int option) { std::memcpy(g_work_page, buf, size); SecmonArgs args = {0}; args.X[0] = 0xF0000201; /* smcAmsIramCopy */ args.X[1] = (uintptr_t) g_work_page; /* DRAM Address */ args.X[2] = iram_addr; /* IRAM Address */ args.X[3] = size; /* Copy size */ args.X[4] = option; /* 0 = Read, 1 = Write */ svcCallSecureMonitor(&args); std::memcpy(buf, g_work_page, size); } void copy_to_iram(uintptr_t iram_addr, void *buf, size_t size) { do_iram_dram_copy(buf, iram_addr, size, 1); } void copy_from_iram(void *buf, uintptr_t iram_addr, size_t size) { do_iram_dram_copy(buf, iram_addr, size, 0); } static void clear_iram(void) { std::memset(g_ff_page, 0xFF, sizeof (g_ff_page)); for (size_t i = 0; i < IRAM_PAYLOAD_MAX_SIZE; i += sizeof (g_ff_page)) { copy_to_iram(IRAM_PAYLOAD_BASE + i, g_ff_page, sizeof (g_ff_page)); } } void PayloadReboot::Reboot() { splInitialize(); clear_iram(); for (size_t i = 0; i < IRAM_PAYLOAD_MAX_SIZE; i += 0x1000) { copy_to_iram(IRAM_PAYLOAD_BASE + i, &g_reboot_payload[i], 0x1000); } splSetConfig((SplConfigItem) 65001, 2); splExit(); } void PayloadReboot::RebootRCM() { splInitialize(); clear_iram(); splSetConfig((SplConfigItem) 65001, 1); splExit(); } void PayloadReboot::RebootHekate(std::string hbPath) { PayloadReboot::AlterPayload("0", "0", hbPath, true, true); } void PayloadReboot::Shutdown() { splInitialize(); clear_iram(); splSetConfig((SplConfigItem) 65002, 1); splExit(); } bool PayloadReboot::Init(std::string payloadPath) { splInitialize(); FILE *f = std::fopen(payloadPath.c_str(), "rb"); if (!f) return false; std::fread(g_reboot_payload, sizeof (g_reboot_payload), 1, f); std::fclose(f); return true; } bool PayloadReboot::AlterPayload(std::string autoboot, std::string autobootl, std::string hbPath, bool launch, bool nocfg) { std::string binFile = hbPath + "payload.bin"; std::string bakFile = hbPath + "payload.bak"; /*if (isFile(bakFile)) { if(isFile(binFile)) removeFile(binFile); //renameFile(bakFile, binFile); if(!copyFile(bakFile, binFile)) return false; }*/ if (isFile(binFile)) { //if (copyFile(binFile, bakFile)) //{ b_cfg = new boot_cfg_t; b_cfg->boot_cfg = (nocfg) ? 0 : BOOT_CFG_AUTOBOOT_EN; b_cfg->autoboot = std::stoi(autoboot); b_cfg->autoboot_list = std::stoi(autobootl); b_cfg->extra_cfg = 0; std::memset(b_cfg->id, 0, sizeof (b_cfg->id)); std::memset(b_cfg->xt_str, 0, sizeof (b_cfg->xt_str)); std::FILE* fp = std::fopen(binFile.c_str(), "r+b"); if (fp != NULL) { std::fseek(fp, PATCHED_RELOC_SZ, SEEK_SET); std::fwrite(b_cfg, sizeof (boot_cfg_t), 1, fp); std::fclose(fp); } else { std::fclose(fp); delete b_cfg; return false; } delete b_cfg; usleep(100); if (launch) { if (Init(binFile)) Reboot(); else return false; } return true; //} } return false; }
4,567
C++
.cpp
145
25.165517
123
0.602011
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,955
Types.cpp
bemardev_HekateBrew/Source/Types.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <Types.hpp> LaunchMode GetLaunchMode() { LaunchMode mode = LaunchMode::Unknown; AppletType type = appletGetAppletType(); switch (type) { case AppletType_SystemApplication: case AppletType_Application: mode = LaunchMode::Application; break; // Shall I add other applet types? Don't think this will run over qlaunch or overlay... case AppletType_LibraryApplet: mode = LaunchMode::Applet; default: break; } return mode; }
1,297
C++
.cpp
36
31.361111
96
0.705556
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,956
elm_TextIcon.cpp
bemardev_HekateBrew/Source/elm/elm_TextIcon.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <elm/elm_TextIcon.hpp> namespace elm { TextIcon::TextIcon(s32 X, s32 Y, pu::String Text, Icons IconType, pu::ui::Color Color, TextIconAlign Align, s32 FontSize) : Element::Element() { this->x = X; this->y = Y; this->text = Text; this->iconType = IconType; this->align = Align; this->clr = Color; this->fsize = FontSize; this->padding = 12; this->fnt = pu::ui::render::LoadDefaultFont(FontSize); this->icofnt = pu::ui::render::LoadSharedIconFont(pu::ui::render::SharedFont::NintendoExtended, 25); this->ntex = NULL; this->itex = NULL; this->ReloadTextures(); } TextIcon::~TextIcon() { if (this->ntex != NULL) { pu::ui::render::DeleteTexture(this->ntex); this->ntex = NULL; } if (this->itex != NULL) { pu::ui::render::DeleteTexture(this->itex); this->itex = NULL; } } s32 TextIcon::GetX() { return this->x; } void TextIcon::SetX(s32 X) { this->x = X; } s32 TextIcon::GetY() { return this->y; } void TextIcon::SetY(s32 Y) { this->y = Y; } s32 TextIcon::GetWidth() { return this->GetTextWidth(); } s32 TextIcon::GetHeight() { return this->GetTextHeight(); } s32 TextIcon::GetTextWidth() { return pu::ui::render::GetTextWidth(this->fnt, this->text) + 30 /*harcoded*/ + this->padding; } s32 TextIcon::GetTextHeight() { return pu::ui::render::GetTextHeight(this->fnt, this->text); } pu::String TextIcon::GetText() { return this->text; } void TextIcon::SetText(pu::String Text, Icons IconType) { this->text = Text; this->iconType = IconType; this->ReloadTextures(); } pu::ui::Color TextIcon::GetColor() { return this->clr; } void TextIcon::SetColor(pu::ui::Color Color) { this->clr = Color; this->ReloadTextures(); } void TextIcon::OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y) { s32 rdx = X; s32 rdy = Y; Drawer->RenderTexture(this->itex, rdx, rdy); Drawer->RenderTexture(this->ntex, rdx + 30 /*harcoded*/ + this->padding, rdy); } void TextIcon::OnInput(u64 Down, u64 Up, u64 Held, bool Touch) { } void TextIcon::ReloadTextures() { if (this->ntex != NULL) pu::ui::render::DeleteTexture(this->ntex); if (this->itex != NULL) pu::ui::render::DeleteTexture(this->itex); this->ntex = pu::ui::render::RenderText(this->fnt, this->text, this->clr); this->itex = pu::ui::render::RenderIcon(this->icofnt, this->iconType, this->clr); switch (this->align) { case(TextIconAlign::Right): this->x -= this->GetTextWidth(); break; default: break; } } }
3,812
C++
.cpp
128
23.148438
146
0.590128
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,957
elm_NinMenu.cpp
bemardev_HekateBrew/Source/elm/elm_NinMenu.cpp
#include <elm/elm_NinMenu.hpp> namespace elm { NinMenuItem::NinMenuItem(pu::String Name) { this->clr = {10, 10, 10, 255}; this->name = Name; this->hasicon = false; } pu::String NinMenuItem::GetName() { return this->name; } void NinMenuItem::SetName(pu::String Name) { this->name = Name; } pu::ui::Color NinMenuItem::GetColor() { return this->clr; } void NinMenuItem::SetColor(pu::ui::Color Color) { this->clr = Color; } void NinMenuItem::AddOnClick(std::function<void() > Callback, u64 Key) { this->cbs.push_back(Callback); this->cbipts.push_back(Key); } s32 NinMenuItem::GetCallbackCount() { return this->cbs.size(); } std::function<void() > NinMenuItem::GetCallback(s32 Index) { if (this->cbs.empty()) return [&]() { }; return this->cbs[Index]; } u64 NinMenuItem::GetCallbackKey(s32 Index) { return this->cbipts[Index]; } std::string NinMenuItem::GetIcon() { return this->icon; } void NinMenuItem::SetIcon(std::string Icon) { std::ifstream ifs(Icon); if (ifs.good()) { this->icon = Icon; this->hasicon = true; } ifs.close(); } bool NinMenuItem::HasIcon() { return this->hasicon; } NinMenu::NinMenu(s32 X, s32 Y, s32 Width, pu::ui::Color OptionColor, s32 ItemSize, s32 ItemsToShow) : Element::Element() { this->x = X; this->y = Y; this->w = Width; this->clr = OptionColor; this->scb = {110, 110, 110, 255}; this->isize = ItemSize; this->ishow = ItemsToShow; this->previsel = 0; this->isel = 0; this->fisel = 0; this->onselch = [&]() { }; this->icdown = false; this->dtouch = false; this->basestatus = 0; this->font = pu::ui::render::LoadDefaultFont(25); this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->_txtclr = {255, 255, 255, 255}; this->_borderclr = {18, 187, 254, 255}; this->_altclr = {115, 223, 235, 255}; this->_baseclr = {61, 61, 61, 255}; this->_innerclr = {28, 33, 37, 255}; this->_lineclr = {45, 79, 238, 255}; } s32 NinMenu::GetX() { return this->x; } void NinMenu::SetX(s32 X) { this->x = X; } s32 NinMenu::GetY() { return this->y; } void NinMenu::SetY(s32 Y) { this->y = Y; } s32 NinMenu::GetWidth() { return this->w; } void NinMenu::SetWidth(s32 Width) { this->w = Width; } s32 NinMenu::GetHeight() { return (this->isize * this->ishow); } s32 NinMenu::GetItemSize() { return this->isize; } void NinMenu::SetItemSize(s32 ItemSize) { this->isize = ItemSize; } s32 NinMenu::GetNumberOfItemsToShow() { return this->ishow; } void NinMenu::SetNumberOfItemsToShow(s32 ItemsToShow) { this->ishow = ItemsToShow; } pu::ui::Color NinMenu::GetColor() { return this->clr; } void NinMenu::SetColor(pu::ui::Color Color) { this->clr = Color; } void NinMenu::SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor) { this->_txtclr = TextColor; this->_borderclr = BorderColor; this->_altclr = AltBorderColor; this->_innerclr = InnerBorderColor; this->_baseclr = BaseColor; this->_lineclr = LineColor; } void NinMenu::SetIsFocused(bool isFocus) { this->_isfocus = isFocus; } pu::ui::Color NinMenu::GetScrollbarColor() { return this->scb; } void NinMenu::SetScrollbarColor(pu::ui::Color Color) { this->scb = Color; } void NinMenu::SetOnSelectionChanged(std::function<void() > Callback) { this->onselch = Callback; } void NinMenu::AddItem(NinMenuItem::Ref &Item) { this->itms.push_back(Item); } void NinMenu::ClearItems() { this->itms.clear(); for(auto &name : this->loadednames) pu::ui::render::DeleteTexture(name); this->loadednames.clear(); for(auto &icon : this->loadedicons) if(icon != NULL) pu::ui::render::DeleteTexture(icon); this->loadedicons.clear(); } void NinMenu::SetCooldownEnabled(bool Cooldown) { this->icdown = Cooldown; } NinMenuItem::Ref &NinMenu::GetSelectedItem() { return this->itms[this->isel]; } std::vector<NinMenuItem::Ref> &NinMenu::GetItems() { return this->itms; } s32 NinMenu::GetSelectedIndex() { return this->isel; } void NinMenu::SetSelectedIndex(s32 Index) { if (this->itms.size() > Index) { this->isel = Index; this->fisel = 0; if (this->isel >= (this->itms.size() - this->ishow)) this->fisel = this->itms.size() - this->ishow; else if (this->isel < this->ishow) this->fisel = 0; else this->fisel = this->isel; ReloadItemRenders(); } } void NinMenu::OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y) { if (!this->itms.empty()) { s32 cx = X; s32 cy = Y; s32 cw = this->w; s32 ch = this->isize; s32 its = this->ishow; if (its > this->itms.size()) its = this->itms.size(); if ((its + this->fisel) > this->itms.size()) its = this->itms.size() - this->fisel; if (this->loadednames.empty()) ReloadItemRenders(); for (s32 i = this->fisel; i < (its + this->fisel); i++) { s32 clrr = this->clr.R; s32 clrg = this->clr.G; s32 clrb = this->clr.B; s32 nr = clrr - 70; if (nr < 0) nr = 0; s32 ng = clrg - 70; if (ng < 0) ng = 0; s32 nb = clrb - 70; if (nb < 0) nb = 0; pu::ui::Color nclr(nr, ng, nb, this->clr.A); auto loadedidx = i - this->fisel; auto curname = GetTextContent(this->itms[i]->GetName().AsUTF8(), (this->isel == i)); auto curicon = this->loadedicons[loadedidx]; if (this->isel == i) { if(this->_isfocus) { auto curtime = std::chrono::steady_clock::now(); //cy = cy-20; auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - this->blinktime).count(); if (diff >= 500) { this->_blink = !this->_blink; this->blinktime = std::chrono::steady_clock::now(); } if (this->_blink) { Drawer->RenderRoundedRectangleFill(this->_borderclr, cx - 5, cy - 5, cw + 10, ch + 10, 4); } else { Drawer->RenderRoundedRectangleFill(this->_altclr, cx - 5, cy - 5, cw + 10, ch + 10, 4); } Drawer->RenderRectangleFill(this->_innerclr, cx, cy, cw, ch); } Drawer->RenderRectangleFill(this->_lineclr, cx+8, cy+10, 3, ch-20); } //else Drawer->RenderRectangleFill(this->clr, cx, cy, cw, ch); auto itm = this->itms[i]; s32 xh = pu::ui::render::GetTextHeight(this->font, itm->GetName()); s32 tx = (cx + 25); s32 ty = ((ch - xh) / 2) + cy; if (itm->HasIcon()) { float factor = (float) pu::ui::render::GetTextureHeight(curicon) / (float) pu::ui::render::GetTextureWidth(curicon); s32 icw = (this->isize - 10); s32 ich = icw; s32 icx = (cx + 25); s32 icy = (cy + 5); tx = (icx + icw + 25); if (factor < 1) { ich = ich*factor; icy = icy + ((this->isize - ich) / 2); } else { icw = icw / factor; icx = icx + ((this->isize - icw) / 2); } Drawer->RenderTextureScaled(curicon, icx, icy, icw, ich); } Drawer->RenderTexture(curname, tx, ty); cy += ch; } if (this->ishow < this->itms.size()) { s32 sccr = this->scb.R; s32 sccg = this->scb.G; s32 sccb = this->scb.B; s32 snr = sccr - 30; if (snr < 0) snr = 0; s32 sng = sccg - 30; if (sng < 0) sng = 0; s32 snb = sccb - 30; if (snb < 0) snb = 0; pu::ui::Color sclr(snr, sng, snb, this->scb.A); s32 scx = X + (this->w - 20); s32 scy = Y; s32 scw = 20; s32 sch = (this->ishow * this->isize); Drawer->RenderRectangleFill(this->scb, scx, scy, scw, sch); s32 fch = ((this->ishow * sch) / this->itms.size()); s32 fcy = scy + (this->fisel * (sch / this->itms.size())); Drawer->RenderRectangleFill(sclr, scx, fcy, scw, fch); } Drawer->RenderShadowSimple(cx, cy, cw, 5, 160); } } void NinMenu::OnInput(u64 Down, u64 Up, u64 Held, bool Touch) { if (itms.empty() || !this->_isfocus) return; if (basestatus == 1) { auto curtime = std::chrono::steady_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - basetime).count(); if (diff >= 150) { basestatus = 2; } } if (Touch) { touchPosition tch; hidTouchRead(&tch, 0); s32 cx = this->GetProcessedX(); s32 cy = this->GetProcessedY(); s32 cw = this->w; s32 ch = this->isize; s32 its = this->ishow; if (its > this->itms.size()) its = this->itms.size(); if ((its + this->fisel) > this->itms.size()) its = this->itms.size() - this->fisel; for (s32 i = this->fisel; i < (this->fisel + its); i++) { if (((cx + cw) > tch.px) && (tch.px > cx) && ((cy + ch) > tch.py) && (tch.py > cy)) { this->dtouch = true; this->previsel = this->isel; this->isel = i; (this->onselch)(); break; } cy += this->isize; } } else if (this->dtouch) { if (this->icdown) this->icdown = false; else (this->itms[this->isel]->GetCallback(0))(); this->dtouch = false; } else { if ((Down & KEY_DDOWN) || (Down & KEY_LSTICK_DOWN) || (Held & KEY_RSTICK_DOWN)) { bool move = true; if (Held & KEY_RSTICK_DOWN) { move = false; if (basestatus == 0) { basetime = std::chrono::steady_clock::now(); basestatus = 1; } else if (basestatus == 2) { basestatus = 0; move = true; } } if (move) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; if (this->isel < (this->itms.size() - 1)) { if ((this->isel - this->fisel) == (this->ishow - 1)) { this->fisel++; this->isel++; (this->onselch)(); ReloadItemRenders(); } else { this->previsel = this->isel; this->isel++; (this->onselch)(); } } else { this->isel = 0; this->fisel = 0; if (this->itms.size() >= this->ishow) { ReloadItemRenders(); } } } } else if ((Down & KEY_DUP) || (Down & KEY_LSTICK_UP) || (Held & KEY_RSTICK_UP)) { bool move = true; if (Held & KEY_RSTICK_UP) { move = false; if (basestatus == 0) { basetime = std::chrono::steady_clock::now(); basestatus = 1; } else if (basestatus == 2) { basestatus = 0; move = true; } } if (move) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; if (this->isel > 0) { if (this->isel == this->fisel) { this->fisel--; this->isel--; (this->onselch)(); ReloadItemRenders(); } else { this->previsel = this->isel; this->isel--; (this->onselch)(); } } else { this->isel = this->itms.size() - 1; this->fisel = 0; if (this->itms.size() >= this->ishow) { this->fisel = this->itms.size() - this->ishow; ReloadItemRenders(); } } } } else { s32 ipc = this->itms[this->isel]->GetCallbackCount(); if (ipc > 0) for (s32 i = 0; i < ipc; i++) { if (Down & this->itms[this->isel]->GetCallbackKey(i)) { if (this->icdown) this->icdown = false; else (this->itms[this->isel]->GetCallback(i))(); } } } } } pu::ui::render::NativeTexture NinMenu::GetTextContent(std::string text, bool selected) { std::string indexText = (selected) ? text + "_select" : text; if (_contents.count(indexText) == 0 || _contents[indexText] == NULL) { if(selected) { _contents[indexText] = pu::ui::render::RenderText(this->font, text, this->_lineclr); } else _contents[indexText] = pu::ui::render::RenderText(this->font, text, this->_txtclr); } return _contents[indexText]; } void NinMenu::ReloadItemRenders() { for (u32 i = 0; i < this->loadednames.size(); i++) pu::ui::render::DeleteTexture(this->loadednames[i]); for (u32 i = 0; i < this->loadedicons.size(); i++) pu::ui::render::DeleteTexture(this->loadedicons[i]); this->loadednames.clear(); this->loadedicons.clear(); s32 its = this->ishow; if (its > this->itms.size()) its = this->itms.size(); if ((its + this->fisel) > this->itms.size()) its = this->itms.size() - this->fisel; for (s32 i = this->fisel; i < (its + this->fisel); i++) { auto strname = this->itms[i]->GetName(); auto tex = pu::ui::render::RenderText(this->font, strname, this->itms[i]->GetColor()); this->loadednames.push_back(tex); if (this->itms[i]->HasIcon()) { auto stricon = this->itms[i]->GetIcon(); auto icontex = pu::ui::render::LoadImage(stricon); this->loadedicons.push_back(icontex); } else this->loadedicons.push_back(NULL); } } }
17,538
C++
.cpp
507
21.108481
196
0.427974
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,958
elm_TextScroll.cpp
bemardev_HekateBrew/Source/elm/elm_TextScroll.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <elm/elm_TextScroll.hpp> #include <Utils.hpp> namespace elm { TextScroll::TextScroll(s32 X, s32 Y, s32 Width, pu::String Text, s32 FontSize) : Element::Element() { this->outputW = Width; this->x = X; this->y = Y; this->text = Text; this->currentText = this->text.AsUTF8(); this->clr = {0, 0, 0, 255}; this->fnt = pu::ui::render::LoadDefaultFont(FontSize); this->fsize = FontSize; if (pu::ui::render::GetTextWidth(this->fnt, this->currentText) > Width) this->currentText += "\t"; this->ntex = pu::ui::render::RenderText(this->fnt, currentText, this->clr); this->start_time = std::chrono::high_resolution_clock::now(); this->newLength = floor(((float) Width / pu::ui::render::GetTextWidth(this->fnt, this->currentText)) * Text.length()); } TextScroll::~TextScroll() { if (this->ntex != NULL) { pu::ui::render::DeleteTexture(this->ntex); this->ntex = NULL; } } s32 TextScroll::GetX() { return this->x; } void TextScroll::SetX(s32 X) { this->x = X; } s32 TextScroll::GetY() { return this->y; } void TextScroll::SetY(s32 Y) { this->y = Y; } s32 TextScroll::GetWidth() { return this->GetTextWidth(); } s32 TextScroll::GetHeight() { return this->GetTextHeight(); } s32 TextScroll::GetTextWidth() { return pu::ui::render::GetTextWidth(this->fnt, this->text); } s32 TextScroll::GetTextHeight() { return pu::ui::render::GetTextHeight(this->fnt, this->text); } pu::String TextScroll::GetText() { return this->text; } void TextScroll::SetText(pu::String Text) { this->text = Text; pu::ui::render::DeleteTexture(this->ntex); this->ntex = pu::ui::render::RenderText(this->fnt, Text, this->clr); } void TextScroll::SetFont(pu::ui::render::NativeFont Font) { this->fnt = Font; pu::ui::render::DeleteTexture(this->ntex); this->ntex = pu::ui::render::RenderText(Font, this->text, this->clr); } pu::ui::Color TextScroll::GetColor() { return this->clr; } void TextScroll::SetColor(pu::ui::Color Color) { this->clr = Color; pu::ui::render::DeleteTexture(this->ntex); this->ntex = pu::ui::render::RenderText(this->fnt, this->text, Color); } void TextScroll::OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y) { s32 rdx = X; s32 rdy = Y; this->current_time = std::chrono::high_resolution_clock::now(); this->Elapsed = current_time - start_time; if (pu::ui::render::GetTextWidth(this->fnt, this->currentText) > this->outputW) { pu::ui::render::DeleteTexture(this->ntex); this->ntex = pu::ui::render::RenderText(this->fnt, this->currentText.substr(0, this->newLength), this->clr); if (this->Elapsed.count() >= 150) { stringShift(this->currentText); this->start_time = std::chrono::high_resolution_clock::now(); } } rdx = rdx + ((this->outputW - pu::ui::render::GetTextWidth(this->fnt, this->currentText.substr(0, this->newLength))) / 2); Drawer->RenderTexture(this->ntex, rdx, rdy); } void TextScroll::OnInput(u64 Down, u64 Up, u64 Held, bool Touch) { } }
4,298
C++
.cpp
126
27.47619
130
0.604959
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,959
elm_SimpleGrid.cpp
bemardev_HekateBrew/Source/elm/elm_SimpleGrid.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <elm/elm_SimpleGrid.hpp> #include <ui/ui_MainApplication.hpp> #include <Utils.hpp> namespace elm { SimpleGridItem::SimpleGridItem(pu::String Image, pu::String Name) { this->clr = {58, 168, 182, 255}; this->name = Name; this->img = Image; this->hasicon = true; this->icdown = true; } pu::String SimpleGridItem::GetName() { return this->name; } pu::String SimpleGridItem::GetImage() { return this->img; } void SimpleGridItem::SetName(pu::String Name) { this->name = Name; } pu::ui::Color SimpleGridItem::GetColor() { return this->clr; } void SimpleGridItem::SetColor(pu::ui::Color Color) { this->clr = Color; } bool SimpleGridItem::GetCoolDown() { return this->icdown; } void SimpleGridItem::SetCoolDown(bool CoolDown) { this->icdown = CoolDown; } void SimpleGridItem::AddOnClick(std::function<void() > Callback, u64 Key) { this->cbs.push_back(Callback); this->cbipts.push_back(Key); } s32 SimpleGridItem::GetCallbackCount() { return this->cbs.size(); } std::function<void() > SimpleGridItem::GetCallback(s32 Index) { if (this->cbs.empty()) return [&]() { }; return this->cbs[Index]; } u64 SimpleGridItem::GetCallbackKey(s32 Index) { return this->cbipts[Index]; } std::string SimpleGridItem::GetIcon() { return this->icon; } void SimpleGridItem::SetIcon(std::string Icon) { std::ifstream ifs(Icon); if (ifs.good()) { this->icon = Icon; this->hasicon = true; } ifs.close(); } bool SimpleGridItem::HasIcon() { return this->hasicon; } SimpleGrid::SimpleGrid(s32 X, s32 Y, bool rounded) : Element::Element() { this->x = X; this->y = Y; this->w = 1280; this->clr = pu::ui::Color::FromHex("#ffffff"); this->scb = {110, 110, 110, 255}; this->isize = 256; // icon size this->ishow = 4; // number per rows this->rshow = 2; this->previsel = 0; this->isel = 0; this->fisel = 0; this->hspace = 15; this->vspace = 15; this->onselch = [&]() { }; this->icdown = true; this->dtouch = false; this->fcs = {40, 40, 40, 255}; this->basestatus = 0; this->_fontsize = 25; this->font = pu::ui::render::LoadDefaultFont(this->_fontsize); this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->_rounded = rounded; this->_txtonsel = false; this->_txtunder = false; this->_txtclr = {255, 255, 255, 255}; this->_borderclr = {18, 187, 254, 255}; this->_altclr = {115, 223, 235, 255}; this->_baseclr = {61, 61, 61, 255}; this->_innerclr = {28, 33, 37, 255}; } s32 SimpleGrid::GetX() { return this->x; } void SimpleGrid::SetX(s32 X) { this->x = X; } s32 SimpleGrid::GetY() { return this->y; } void SimpleGrid::SetY(s32 Y) { this->y = Y; } s32 SimpleGrid::GetWidth() { return this->w; } void SimpleGrid::SetWidth(s32 Width) { this->w = Width; } s32 SimpleGrid::GetHeight() { return (this->isize * this->ishow); } s32 SimpleGrid::GetItemSize() { return this->isize; } void SimpleGrid::SetItemSize(s32 ItemSize) { this->isize = ItemSize; } s32 SimpleGrid::GetNumberOfItemsToShow() { return this->ishow; } void SimpleGrid::SetNumberOfItemsToShow(s32 ItemsToShow) { this->ishow = ItemsToShow; } void SimpleGrid::SetHorizontalPadding(s32 HorizontalPadding) { this->hspace = HorizontalPadding; } void SimpleGrid::SetVerticalPadding(s32 VerticalPadding) { this->vspace = VerticalPadding; } void SimpleGrid::SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor) { this->_txtclr = TextColor; this->_borderclr = BorderColor; this->_altclr = AltBorderColor; this->_innerclr = InnerBorderColor; this->_baseclr = BaseColor; } pu::ui::Color SimpleGrid::GetColor() { return this->clr; } void SimpleGrid::SetColor(pu::ui::Color Color) { this->clr = Color; } pu::ui::Color SimpleGrid::GetOnFocusColor() { return this->fcs; } void SimpleGrid::SetOnFocusColor(pu::ui::Color Color) { this->fcs = Color; } pu::ui::Color SimpleGrid::GetScrollbarColor() { return this->scb; } void SimpleGrid::SetScrollbarColor(pu::ui::Color Color) { this->scb = Color; } void SimpleGrid::SetOnSelectionChanged(std::function<void() > Callback) { this->onselch = Callback; } void SimpleGrid::SetDisplayNameOnSelected(bool txtonsel) { this->_txtonsel = txtonsel; } void SimpleGrid::SetTextUnderIcon(bool txtunder) { this->_txtunder = txtunder; } void SimpleGrid::SetFontSize(s32 fontsize) { this->_fontsize = fontsize; this->font = pu::ui::render::LoadDefaultFont(this->_fontsize); } void SimpleGrid::AddItem(SimpleGridItem::Ref &Item) { this->itms.push_back(Item); } void SimpleGrid::ClearItems() { this->itms.clear(); } void SimpleGrid::SetCooldownEnabled(bool Cooldown) { this->icdown = Cooldown; } SimpleGridItem::Ref &SimpleGrid::GetSelectedItem() { return this->itms[this->isel]; } std::vector<SimpleGridItem::Ref> &SimpleGrid::GetItems() { return this->itms; } s32 SimpleGrid::GetSelectedIndex() { return this->isel; } void SimpleGrid::SetSelectedIndex(s32 Index) { if (this->itms.size() > Index) { this->itms[this->previsel]->SetCoolDown(true); this->isel = Index; this->itms[this->isel]->SetCoolDown(false); this->previsel = Index; this->fisel = 0; if (this->isel >= (this->itms.size() - this->ishow)) this->fisel = this->itms.size() - this->ishow; else if (this->isel < this->ishow) this->fisel = 0; else this->fisel = this->isel; } } void SimpleGrid::OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y) { if (!this->itms.empty()) { s32 cx = X; s32 cy = Y; s32 cw = this->w; s32 ch = this->isize; s32 th = 40; s32 finInc = (this->fisel + (this->rshow * this->ishow)) > this->itms.size() ? this->itms.size() : this->fisel + (this->rshow * this->ishow); for (s32 i = this->fisel; i < finInc; i++) { s32 xcoeff = i - this->fisel; while (xcoeff >= this->ishow) xcoeff -= this->ishow; s32 ycoeff = (i - this->fisel) / this->ishow; cx = X + (this->isize + this->hspace) * (xcoeff); cy = Y + (this->isize + this->vspace) * (ycoeff); if (cx >= 1280) break; std::string strDisplay = ""; s32 currentTextLength = pu::ui::render::GetTextWidth(this->font, this->itms[i]->GetName()); if (currentTextLength > this->isize) { s32 newLength = floor(((float) this->isize / currentTextLength) * this->itms[i]->GetName().length()); strDisplay = this->itms[i]->GetName().AsUTF8().substr(0, newLength); } else { strDisplay = this->itms[i]->GetName().AsUTF8(); } s32 rdx = cx; s32 rdy = cy; rdx = rdx + ((this->isize - pu::ui::render::GetTextWidth(this->font, strDisplay)) / 2); if (this->_txtunder) rdy += this->isize + 20; else rdy += this->isize - 50 + ((th - pu::ui::render::GetTextHeight(this->font, strDisplay)) / 2); if (this->isel == i) { auto curtime = std::chrono::steady_clock::now(); //cy = cy-20; auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - this->blinktime).count(); if (diff >= 500) { this->_blink = !this->_blink; this->blinktime = std::chrono::steady_clock::now(); } if (this->_rounded) { if (this->_blink) { Drawer->RenderRoundedRectangleFill(this->_borderclr, cx - 10, cy - 10, ch + 20, ch + 20, 4); } else { Drawer->RenderRoundedRectangleFill(this->_altclr, cx - 10, cy - 10, ch + 20, ch + 20, 4); } Drawer->RenderRoundedRectangleFill(this->_innerclr, cx - 5, cy - 5, ch + 10, ch + 10, 4); } else { if (this->_blink) Drawer->RenderTexture(GetBorder(this->_borderclr), cx - 10, cy - 10, ch + 20, ch + 20); else Drawer->RenderTexture(GetBorder(this->_altclr), cx - 10, cy - 10, ch + 20, ch + 20); Drawer->RenderTexture(GetBorder(this->_innerclr), cx - 5, cy - 5, ch + 10, ch + 10); } Drawer->RenderTexture(GetBorder(this->_baseclr), cx, cy, ch, ch); Drawer->RenderTexture(GetImageContent(this->itms[i]->GetImage().AsUTF8()), cx, cy, ch, ch); if (!this->_txtunder) Drawer->RenderTexture(GetBorder(this->_baseclr), cx, cy + this->isize - 50, this->isize, th); Drawer->RenderTexture(GetTextContent(strDisplay), rdx, rdy); } else { Drawer->RenderTexture(GetBorder(this->_baseclr), cx, cy, ch, ch); Drawer->RenderTextureScaled(GetImageContent(this->itms[i]->GetImage().AsUTF8()), cx, cy, ch, ch); if (!this->_txtunder) Drawer->RenderTexture(GetBorder(this->_baseclr), cx, rdy, this->isize, th); if (!this->_txtonsel) Drawer->RenderTexture(GetTextContent(strDisplay), rdx, rdy); } } if ((this->rshow * this->ishow) < this->itms.size()) { s32 scx = this->w - 30; s32 scy = Y; s32 scw = 5; s32 sch = (this->isize + this->vspace) / this->rshow; s32 ycoeff = this->isel / this->ishow; s32 fcy = scy + (ycoeff * sch); Drawer->RenderRectangleFill(this->scb, scx, fcy, scw, sch); } } } void SimpleGrid::OnInput(u64 Down, u64 Up, u64 Held, bool Touch) { if (itms.empty()) return; if (Touch) { touchPosition tch; hidTouchRead(&tch, 0); s32 cx = this->GetProcessedX(); s32 cy = this->GetProcessedY(); s32 cw = this->w; s32 ch = this->isize; s32 its = this->rshow * this->ishow; if (its > this->itms.size()) its = this->itms.size(); if ((its + this->fisel) > this->itms.size()) its = this->itms.size() - this->fisel; for (s32 i = this->fisel; i < (this->fisel + its); i++) { s32 xcoeff = i - this->fisel; while (xcoeff >= this->ishow) xcoeff -= this->ishow; s32 ycoeff = (i - this->fisel) / this->ishow; s32 rdx = cx + (this->isize + this->hspace) * xcoeff; s32 rdy = cy + (this->isize + this->vspace) * ycoeff; if ((tch.px >= rdx) && (tch.py >= rdy) && (tch.px < (rdx + this->isize)) && (tch.py < (rdy + this->isize))) { this->previsel = this->isel; this->dtouch = true; this->isel = i; (this->onselch)(); break; } } } else if (this->dtouch) { if (this->itms[this->isel]->GetCoolDown()) { this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } else (this->itms[this->isel]->GetCallback(0))(); this->dtouch = false; } else { if ((Down & KEY_DUP) || (Down & KEY_LSTICK_UP) || (Held & KEY_RSTICK_UP)) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->previsel = this->isel; if (this->isel >= this->ishow) { if ((this->isel - this->ishow) < (this->fisel)) { this->fisel -= (this->rshow * this->ishow); } this->isel -= this->ishow; (this->onselch)(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } else if ((Down & KEY_DDOWN) || (Down & KEY_LSTICK_DOWN) || (Held & KEY_RSTICK_DOWN)) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->previsel = this->isel; if ((this->isel + this->ishow) < this->itms.size()) { if ((this->isel + this->ishow) >= (this->fisel + (this->rshow * this->ishow))) { this->fisel += (this->rshow * this->ishow); } this->isel += this->ishow; (this->onselch)(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } else { int idxElm = 0; while(idxElm + this->ishow < this->itms.size() -1) idxElm += this->ishow; if(this->isel < idxElm) { this->isel = this->itms.size() - 1; this->fisel = idxElm; (this->onselch)(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } } else if ((Down & KEY_DRIGHT) || (Down & KEY_LSTICK_RIGHT) || (Held & KEY_RSTICK_RIGHT)) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->previsel = this->isel; if (((this->isel + 1) % (this->ishow) != 0) && (this->isel < this->itms.size() - 1)) { this->isel++; (this->onselch)(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } else if ((Down & KEY_DLEFT) || (Down & KEY_LSTICK_LEFT) || (Held & KEY_RSTICK_LEFT)) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->previsel = this->isel; if ((this->isel % this->ishow != 0) && (this->isel < (this->fisel + (this->rshow * this->ishow)))) { this->isel--; (this->onselch)(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } else { s32 ipc = this->itms[this->isel]->GetCallbackCount(); if (ipc > 0) for (s32 i = 0; i < ipc; i++) { if (Down & this->itms[this->isel]->GetCallbackKey(i)) { if (this->itms[this->isel]->GetCoolDown()) { this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } else (this->itms[this->isel]->GetCallback(i))(); } } } } } pu::ui::render::NativeTexture SimpleGrid::GetTextContent(std::string text) { if (_contents.count(text) == 0 || _contents[text] == NULL) _contents[text] = pu::ui::render::RenderText(this->font, text, this->_txtclr); return _contents[text]; } pu::ui::render::NativeTexture SimpleGrid::GetImageContent(std::string imagePath) { if (_contents.count(imagePath) == 0 || _contents[imagePath] == NULL) _contents[imagePath] = pu::ui::render::LoadImage(imagePath); return _contents[imagePath]; } pu::ui::render::NativeTexture SimpleGrid::GetBorder(pu::ui::Color color) { std::string currentKey = std::to_string(color.R) + "_" + std::to_string(color.G) + "_" + std::to_string(color.B) + "_" + std::to_string(color.A); if (_contents.count(currentKey) == 0 || _contents[currentKey] == NULL) { _contents[currentKey] = pu::ui::render::GetColorTexture(color); } return _contents[currentKey]; } }
19,227
C++
.cpp
524
24.956107
174
0.490321
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,960
elm_RotatableImage.cpp
bemardev_HekateBrew/Source/elm/elm_RotatableImage.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <elm/elm_RotatableImage.hpp> namespace elm { RotatableImage::RotatableImage(s32 X, s32 Y, pu::String Image, s32 angledelta, s32 delay) : Image::Image(X, Y, Image) { this->_angle = 0; this->_delay = delay; this->_delta = angledelta; this->delaytime = std::chrono::steady_clock::now(); } void RotatableImage::OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y) { s32 rdx = X; s32 rdy = Y; auto curtime = std::chrono::steady_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - this->delaytime).count(); if (diff >= this->_delay) { this->_angle += this->_delta; this->delaytime = std::chrono::steady_clock::now(); } Drawer->RenderTextureRotate(this->ntex, rdx, rdy, this->GetWidth(), this->GetHeight(), this->_angle); //Drawer->RenderTextureScaled(this->ntex, rdx, rdy, this->GetWidth(), this->GetHeight()); } }
1,772
C++
.cpp
42
37.142857
121
0.668403
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,961
elm_SeparatorLine.cpp
bemardev_HekateBrew/Source/elm/elm_SeparatorLine.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <elm/elm_SeparatorLine.hpp> namespace elm { SeparatorLine::SeparatorLine(s32 X1, s32 Y1, s32 X2, s32 Y2, pu::ui::Color LineColor) : Element::Element() { this->x1 = X1; this->x2 = X2; this->y1 = Y1; this->y2 = Y2; this->clr = LineColor; } s32 SeparatorLine::GetX() { return this->x1; } s32 SeparatorLine::GetY() { return this->y1; } s32 SeparatorLine::GetWidth() { return this->x2 - this->x1; } s32 SeparatorLine::GetHeight() { return this->y2 - this->y1; } void SeparatorLine::OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y) { Drawer->RenderLine(this->clr, this->x1, this->y1, this->x2, this->y2); } void SeparatorLine::OnInput(u64 Down, u64 Up, u64 Held, bool Touch) { } }
1,622
C++
.cpp
52
26.576923
110
0.660691
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,962
elm_NinContentMenu.cpp
bemardev_HekateBrew/Source/elm/elm_NinContentMenu.cpp
#include <elm/elm_NinContentMenu.hpp> namespace elm { NinContentMenuItem::NinContentMenuItem(pu::String Name, pu::String Value) { this->clr = {10, 10, 10, 255}; this->vclr = this->clr; this->name = Name; this->value = Value; this->hasicon = false; this->icdown = true; this->disabled = false; } pu::String NinContentMenuItem::GetName() { return this->name; } void NinContentMenuItem::SetName(pu::String Name) { this->name = Name; } pu::String NinContentMenuItem::GetValue() { return this->value; } void NinContentMenuItem::SetValue(pu::String Value) { this->value = Value; } pu::ui::Color NinContentMenuItem::GetColor() { return this->clr; } void NinContentMenuItem::SetColor(pu::ui::Color Color) { this->clr = Color; } pu::ui::Color NinContentMenuItem::GetValueColor() { return this->vclr; } void NinContentMenuItem::SetValueColor(pu::ui::Color Color) { this->vclr = Color; } bool NinContentMenuItem::GetCoolDown() { return this->icdown; } void NinContentMenuItem::SetCoolDown(bool CoolDown) { this->icdown = CoolDown; } void NinContentMenuItem::AddOnClick(std::function<void() > Callback, u64 Key) { this->cbs.push_back(Callback); this->cbipts.push_back(Key); } s32 NinContentMenuItem::GetCallbackCount() { return this->cbs.size(); } std::function<void() > NinContentMenuItem::GetCallback(s32 Index) { if (this->cbs.empty()) return [&]() { }; return this->cbs[Index]; } u64 NinContentMenuItem::GetCallbackKey(s32 Index) { return this->cbipts[Index]; } std::string NinContentMenuItem::GetIcon() { return this->icon; } void NinContentMenuItem::SetIcon(std::string Icon) { std::ifstream ifs(Icon); if (ifs.good()) { this->icon = Icon; this->hasicon = true; } ifs.close(); } bool NinContentMenuItem::HasIcon() { return this->hasicon; } bool NinContentMenuItem::IsDisabled() { return this->disabled; } void NinContentMenuItem::SetIsDisabled(bool Disabled) { this->disabled = Disabled; } NinContentMenu::NinContentMenu(s32 X, s32 Y, s32 Width, pu::ui::Color OptionColor, s32 ItemSize, s32 ItemsToShow) : Element::Element() { this->x = X; this->y = Y; this->w = Width; this->clr = OptionColor; this->scb = {110, 110, 110, 255}; this->isize = ItemSize; this->ishow = ItemsToShow; this->previsel = 0; this->isel = 0; this->fisel = 0; this->onselch = [&]() { }; this->icdown = false; this->dtouch = false; this->fcs = {40, 40, 40, 255}; this->basestatus = 0; this->font = pu::ui::render::LoadDefaultFont(25); this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->_txtclr = {255, 255, 255, 255}; this->_borderclr = {18, 187, 254, 255}; this->_altclr = {115, 223, 235, 255}; this->_baseclr = {61, 61, 61, 255}; this->_innerclr = {28, 33, 37, 255}; } s32 NinContentMenu::GetX() { return this->x; } void NinContentMenu::SetX(s32 X) { this->x = X; } s32 NinContentMenu::GetY() { return this->y; } void NinContentMenu::SetY(s32 Y) { this->y = Y; } s32 NinContentMenu::GetWidth() { return this->w; } void NinContentMenu::SetWidth(s32 Width) { this->w = Width; } s32 NinContentMenu::GetHeight() { return (this->isize * this->ishow); } s32 NinContentMenu::GetItemSize() { return this->isize; } void NinContentMenu::SetItemSize(s32 ItemSize) { this->isize = ItemSize; } s32 NinContentMenu::GetNumberOfItemsToShow() { return this->ishow; } void NinContentMenu::SetNumberOfItemsToShow(s32 ItemsToShow) { this->ishow = ItemsToShow; } pu::ui::Color NinContentMenu::GetColor() { return this->clr; } void NinContentMenu::SetColor(pu::ui::Color Color) { this->clr = Color; } void NinContentMenu::SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor) { this->_txtclr = TextColor; this->_borderclr = BorderColor; this->_altclr = AltBorderColor; this->_innerclr = InnerBorderColor; this->_baseclr = BaseColor; } pu::ui::Color NinContentMenu::GetOnFocusColor() { return this->fcs; } void NinContentMenu::SetOnFocusColor(pu::ui::Color Color) { this->fcs = Color; } void NinContentMenu::SetIsFocused(bool isFocus) { this->_isfocus = isFocus; } pu::ui::Color NinContentMenu::GetScrollbarColor() { return this->scb; } void NinContentMenu::SetScrollbarColor(pu::ui::Color Color) { this->scb = Color; } void NinContentMenu::SetOnSelectionChanged(std::function<void() > Callback) { this->onselch = Callback; } void NinContentMenu::AddItem(NinContentMenuItem::Ref &Item) { this->itms.push_back(Item); } void NinContentMenu::ClearItems() { this->itms.clear(); for(auto &name : this->loadednames) pu::ui::render::DeleteTexture(name); this->loadednames.clear(); for(auto &icon : this->loadedicons) if(icon != NULL) pu::ui::render::DeleteTexture(icon); this->loadedicons.clear(); for(auto &value : this->loadedvalues) pu::ui::render::DeleteTexture(value); this->loadedvalues.clear(); } void NinContentMenu::SetCooldownEnabled(bool Cooldown) { this->icdown = Cooldown; } NinContentMenuItem::Ref &NinContentMenu::GetSelectedItem() { return this->itms[this->isel]; } std::vector<NinContentMenuItem::Ref> &NinContentMenu::GetItems() { return this->itms; } s32 NinContentMenu::GetSelectedIndex() { return this->isel; } void NinContentMenu::SetSelectedIndex(s32 Index) { if (this->itms.size() > Index) { this->itms[this->previsel]->SetCoolDown(true); this->isel = Index; this->itms[this->isel]->SetCoolDown(false); this->previsel = Index; this->fisel = 0; if (this->isel >= (this->itms.size() - this->ishow)) this->fisel = this->itms.size() - this->ishow; else if (this->isel < this->ishow) this->fisel = 0; else this->fisel = this->isel; ReloadItemRenders(); } } void NinContentMenu::OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y) { if (!this->itms.empty()) { s32 cx = X; s32 cy = Y; s32 cw = this->w; s32 ch = this->isize; s32 its = this->ishow; if (its > this->itms.size()) its = this->itms.size(); if ((its + this->fisel) > this->itms.size()) its = this->itms.size() - this->fisel; if (this->loadednames.empty()) ReloadItemRenders(); for (s32 i = this->fisel; i < (its + this->fisel); i++) { s32 clrr = this->clr.R; s32 clrg = this->clr.G; s32 clrb = this->clr.B; s32 nr = clrr - 70; if (nr < 0) nr = 0; s32 ng = clrg - 70; if (ng < 0) ng = 0; s32 nb = clrb - 70; if (nb < 0) nb = 0; pu::ui::Color nclr(nr, ng, nb, this->clr.A); auto loadedidx = i - this->fisel; auto curname = loadednames[loadedidx]; auto curvalue = loadedvalues[loadedidx]; auto curicon = this->loadedicons[loadedidx]; if (this->isel == i && this->_isfocus) { auto curtime = std::chrono::steady_clock::now(); //cy = cy-20; auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - this->blinktime).count(); if (diff >= 500) { this->_blink = !this->_blink; this->blinktime = std::chrono::steady_clock::now(); } if (this->_blink) { Drawer->RenderRoundedRectangleFill(this->_borderclr, cx - 5, cy - 5, cw + 10, ch + 10, 4); } else { Drawer->RenderRoundedRectangleFill(this->_altclr, cx - 5, cy - 5, cw + 10, ch + 10, 4); } Drawer->RenderRectangleFill(this->_innerclr, cx, cy, cw, ch); } //else Drawer->RenderRectangleFill(this->_innerclr, cx, cy, cw, ch); auto itm = this->itms[i]; s32 xh = pu::ui::render::GetTextHeight(this->font, itm->GetName()); s32 tx = (cx + 25); s32 ty = ((ch - xh) / 2) + cy; s32 vx = cx - 25 + cw - pu::ui::render::GetTextureWidth(curvalue); if (itm->HasIcon()) { float factor = (float) pu::ui::render::GetTextureHeight(curicon) / (float) pu::ui::render::GetTextureWidth(curicon); s32 icw = (this->isize - 10); s32 ich = icw; s32 icx = (cx + 25); s32 icy = (cy + 5); tx = (icx + icw + 25); if (factor < 1) { ich = ich*factor; icy = icy + ((this->isize - ich) / 2); } else { icw = icw / factor; icx = icx + ((this->isize - icw) / 2); } Drawer->RenderTextureScaled(curicon, icx, icy, icw, ich); } Drawer->RenderTexture(curvalue, vx, ty); Drawer->RenderTexture(curname, tx, ty); if(itm->IsDisabled()) { pu::ui::Color dsclr = pu::ui::Color({this->_baseclr.R, this->_baseclr.G, this->_baseclr.B, 140}); Drawer->RenderRoundedRectangleFill(dsclr, cx, cy, cw, ch, 4); } cy += ch; } if (this->ishow < this->itms.size()) { s32 sccr = this->scb.R; s32 sccg = this->scb.G; s32 sccb = this->scb.B; s32 snr = sccr - 30; if (snr < 0) snr = 0; s32 sng = sccg - 30; if (sng < 0) sng = 0; s32 snb = sccb - 30; if (snb < 0) snb = 0; pu::ui::Color sclr(snr, sng, snb, this->scb.A); s32 scx = X + (this->w - 20); s32 scy = Y; s32 scw = 20; s32 sch = (this->ishow * this->isize); Drawer->RenderRectangleFill(this->scb, scx, scy, scw, sch); s32 fch = ((this->ishow * sch) / this->itms.size()); s32 fcy = scy + (this->fisel * (sch / this->itms.size())); Drawer->RenderRectangleFill(sclr, scx, fcy, scw, fch); } Drawer->RenderShadowSimple(cx, cy, cw, 5, 160); } } void NinContentMenu::OnInput(u64 Down, u64 Up, u64 Held, bool Touch) { if (itms.empty() || !this->_isfocus) return; if (basestatus == 1) { auto curtime = std::chrono::steady_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - basetime).count(); if (diff >= 150) { basestatus = 2; } } if (Touch) { touchPosition tch; hidTouchRead(&tch, 0); s32 cx = this->GetProcessedX(); s32 cy = this->GetProcessedY(); s32 cw = this->w; s32 ch = this->isize; s32 its = this->ishow; if (its > this->itms.size()) its = this->itms.size(); if ((its + this->fisel) > this->itms.size()) its = this->itms.size() - this->fisel; for (s32 i = this->fisel; i < (this->fisel + its); i++) { if (((cx + cw) > tch.px) && (tch.px > cx) && ((cy + ch) > tch.py) && (tch.py > cy)) { this->dtouch = true; this->previsel = this->isel; this->isel = i; (this->onselch)(); break; } cy += this->isize; } } else if (this->dtouch) { if (this->itms[this->isel]->GetCoolDown()) { this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } else (this->itms[this->isel]->GetCallback(0))(); this->dtouch = false; } else { if ((Down & KEY_DDOWN) || (Down & KEY_LSTICK_DOWN) || (Held & KEY_RSTICK_DOWN)) { bool move = true; if (Held & KEY_RSTICK_DOWN) { move = false; if (basestatus == 0) { basetime = std::chrono::steady_clock::now(); basestatus = 1; } else if (basestatus == 2) { basestatus = 0; move = true; } } if (move) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->previsel = this->isel; if (this->isel < (this->itms.size() - 1)) { if ((this->isel - this->fisel) == (this->ishow - 1)) { this->fisel++; this->isel++; (this->onselch)(); ReloadItemRenders(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } else { this->isel++; (this->onselch)(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } else { this->isel = 0; this->fisel = 0; if (this->itms.size() >= this->ishow) { ReloadItemRenders(); } this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } } else if ((Down & KEY_DUP) || (Down & KEY_LSTICK_UP) || (Held & KEY_RSTICK_UP)) { bool move = true; if (Held & KEY_RSTICK_UP) { move = false; if (basestatus == 0) { basetime = std::chrono::steady_clock::now(); basestatus = 1; } else if (basestatus == 2) { basestatus = 0; move = true; } } if (move) { this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->previsel = this->isel; if (this->isel > 0) { if (this->isel == this->fisel) { this->fisel--; this->isel--; (this->onselch)(); ReloadItemRenders(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } else { this->isel--; (this->onselch)(); this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } else { this->isel = this->itms.size() - 1; this->fisel = 0; if (this->itms.size() >= this->ishow) { this->fisel = this->itms.size() - this->ishow; ReloadItemRenders(); } this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } } } else { s32 ipc = this->itms[this->isel]->GetCallbackCount(); if (ipc > 0) for (s32 i = 0; i < ipc; i++) { if (Down & this->itms[this->isel]->GetCallbackKey(i)) { if (this->itms[this->isel]->GetCoolDown()) { this->itms[this->previsel]->SetCoolDown(true); this->itms[this->isel]->SetCoolDown(false); } else (this->itms[this->isel]->GetCallback(i))(); } } } } } void NinContentMenu::ReloadItemRenders() { for (u32 i = 0; i < this->loadednames.size(); i++) pu::ui::render::DeleteTexture(this->loadednames[i]); for (u32 i = 0; i < this->loadedvalues.size(); i++) pu::ui::render::DeleteTexture(this->loadedvalues[i]); for (u32 i = 0; i < this->loadedicons.size(); i++) pu::ui::render::DeleteTexture(this->loadedicons[i]); this->loadednames.clear(); this->loadedvalues.clear(); this->loadedicons.clear(); s32 its = this->ishow; if (its > this->itms.size()) its = this->itms.size(); if ((its + this->fisel) > this->itms.size()) its = this->itms.size() - this->fisel; for (s32 i = this->fisel; i < (its + this->fisel); i++) { auto strname = this->itms[i]->GetName(); auto tex = pu::ui::render::RenderText(this->font, strname, this->itms[i]->GetColor()); this->loadednames.push_back(tex); auto strvalue = this->itms[i]->GetValue(); auto vtex = pu::ui::render::RenderText(this->font, strvalue, this->itms[i]->GetValueColor()); this->loadedvalues.push_back(vtex); if (this->itms[i]->HasIcon()) { auto stricon = this->itms[i]->GetIcon(); auto icontex = pu::ui::render::LoadImage(stricon); this->loadedicons.push_back(icontex); } else this->loadedicons.push_back(NULL); } } }
20,431
C++
.cpp
571
22.471103
203
0.453025
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,963
set_Settings.cpp
bemardev_HekateBrew/Source/set/set_Settings.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <set/set_Settings.hpp> #include <ui/ui_MainApplication.hpp> namespace set { Settings ProcessSettings() { Settings gset; LoadHekateBrewConfig(gset.hbConfig); // Blink delay for borders gset.blinkDelay = 500; // Theme defined ColorSetId csid = ColorSetId_Light; setsysGetColorSetId(&csid); if (csid == ColorSetId_Dark) gset.CustomScheme = ui::DefaultDark; else gset.CustomScheme = ui::DefaultLight; LoadHekateConfig(gset.hConfig); LoadHekateInfos(gset.hekateItems); LoadAllPayloads(gset.payloadItems, gset.hbConfig); return gset; } void ReloadList(Settings &gset) { gset.hekateItems.clear(); LoadHekateInfos(gset.hekateItems); gset.payloadItems.clear(); LoadAllPayloads(gset.payloadItems, gset.hbConfig); } void SaveSettings(Settings &gset) { SaveHekateBrewConfig(gset.hbConfig); SaveHekateConfig(gset.hConfig); } }
1,884
C++
.cpp
52
29
79
0.676734
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,964
ui_MainApplication.cpp
bemardev_HekateBrew/Source/ui/ui_MainApplication.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_MainApplication.hpp> #include <ui/ui_FileDialog.hpp> #include <ui/ui_SliderDialog.hpp> #include <ui/ui_TimeDialog.hpp> #include <cfw/cfw_Helper.hpp> #include <set/set_Settings.hpp> #include <PayloadReboot.hpp> set::Settings gsets; namespace ui { MainApplication::MainApplication() : pu::ui::Application() { gsets = set::ProcessSettings(); pu::ui::render::SetDefaultFontFromShared(pu::ui::render::SharedFont::Standard); this->loader = ui::LoadingOverlay::New(gsets.CustomScheme.loaderImage, pu::ui::Color(40, 40, 40, 255)); this->toast = pu::ui::extras::Toast::New(":", 20, pu::ui::Color(225, 225, 225, 255), pu::ui::Color(40, 40, 40, 255)); this->topSeparator = elm::SeparatorLine::New(30, 73, 1250, 73, gsets.CustomScheme.Text); this->bottomSeparator = elm::SeparatorLine::New(30, 647, 1250, 647, gsets.CustomScheme.Text); this->mainPage = MainPageLayout::New(); this->mainPage->Add(this->topSeparator); this->mainPage->Add(this->bottomSeparator); this->SetOnInput(std::bind(&MainApplication::OnInput, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); this->LoadLayout(this->mainPage); this->mainPage->Load(); this->configPage = HkConfigLayout::New(); this->configPage->Add(this->topSeparator); this->configPage->Add(this->bottomSeparator); this->payloadPage = PayloadLayout::New(); this->payloadPage->Add(this->topSeparator); this->payloadPage->Add(this->bottomSeparator); this->optionsPage = OptionsLayout::New(); this->optionsPage->Add(this->topSeparator); this->optionsPage->Add(this->bottomSeparator); if(gsets.hbConfig.autoboot != "0") { if(gsets.hbConfig.autoboot == "1" && gsets.hbConfig.autoboot_payload != "" && stoi(gsets.hbConfig.autoboot_payload) < gsets.payloadItems.size()) { std::string payloadPath = gsets.payloadItems[stoi(gsets.hbConfig.autoboot_payload)].payloadPath; int returnVal = this->CreateTimeDialog(payloadPath, 3000); if(returnVal != -1) { if (PayloadReboot::Init(payloadPath)) PayloadReboot::Reboot(); else this->showNotification("Error booting payload"); } } else if(gsets.hbConfig.autoboot == "2" && gsets.hbConfig.autoboot_config != "" && stoi(gsets.hbConfig.autoboot_config) < gsets.hekateItems.size()) { int returnVal = this->CreateTimeDialog(gsets.hekateItems[stoi(gsets.hbConfig.autoboot_config)].entryName, 3000); if(returnVal != -1) { if (!PayloadReboot::AlterPayload(gsets.hekateItems[stoi(gsets.hbConfig.autoboot_config)].entryIndex, gsets.hekateItems[stoi(gsets.hbConfig.autoboot_config)].entryInList, gsets.hbConfig.path, true)) { this->showNotification("Error sending config to hekate payload"); } } } } } MainPageLayout::Ref &MainApplication::GetMainPageLayout() { return this->mainPage; } HkConfigLayout::Ref &MainApplication::GetHkConfigLayout() { return this->configPage; } PayloadLayout::Ref &MainApplication::GetPayloadLayout() { return this->payloadPage; } OptionsLayout::Ref &MainApplication::GetOptionsLayout() { return this->optionsPage; } void MainApplication::OnInput(u64 Down, u64 Up, u64 Held) { } void MainApplication::showNotification(std::string text, int delay) { this->EndOverlay(); this->toast->SetText(text); this->StartOverlayWithTimeout(this->toast, delay); } int MainApplication::CreateShowDialog(pu::String Title, pu::String Content, std::vector<pu::String> Options, bool UseLastOptionAsCancel, std::string Icon) { pu::ui::Dialog dlg(Title, Content); dlg.SetColor(gsets.CustomScheme.Base); dlg.SetTitleColor(gsets.CustomScheme.Text); dlg.SetContentColor(gsets.CustomScheme.Text); dlg.SetButtonColor(gsets.CustomScheme.BaseFocus); for (s32 i = 0; i < Options.size(); i++) { if (UseLastOptionAsCancel && (i == Options.size() - 1)) dlg.SetCancelOption(Options[i]); else dlg.AddOption(Options[i]); } if (!Icon.empty()) dlg.SetIcon(Icon); int opt = dlg.Show(this->rend, this); if (dlg.UserCancelled()) opt = -1; else if (!dlg.IsOk()) opt = -2; return opt; } std::string MainApplication::CreateFileDialog(std::string title, std::string BeginPath) { ui::FileDialog* fdlg = new ui::FileDialog(BeginPath); fdlg->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base, gsets.CustomScheme.LineSep, gsets.CustomScheme.BaseFocus); std::string selectedPath = fdlg->Show(this->rend, this); if(fdlg->UserCancelled()) selectedPath = std::string(); delete fdlg; return selectedPath; } int MainApplication::CreateListDialog(std::string title, std::vector<ListDialogItem::Ref> &listItems) { ui::ListDialog* ldlg = new ui::ListDialog(title); ldlg->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base, gsets.CustomScheme.LineSep, gsets.CustomScheme.BaseFocus); for(auto &entry : listItems) ldlg->AddItem(entry); int idxSelected = ldlg->Show(this->rend, this); if(ldlg->UserCancelled()) idxSelected = -1; delete ldlg; return idxSelected; } int MainApplication::CreateSliderDialog(std::string title, int minValue, int maxValue, int step, int currentValue) { ui::SliderDialog* sdlg = new ui::SliderDialog(title, minValue, maxValue, step, currentValue); sdlg->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base, gsets.CustomScheme.LineSep, gsets.CustomScheme.BaseFocus); int value = sdlg->Show(this->rend, this); if(sdlg->UserCancelled()) value = -1; delete sdlg; return value; } int MainApplication::CreateTimeDialog(std::string dialogText, int delay) { ui::TimeDialog* tdlg = new ui::TimeDialog(dialogText, delay); tdlg->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.Base, gsets.CustomScheme.BaseFocus); int value = tdlg->Show(this->rend, this); if(tdlg->UserCancelled()) value = -1; delete tdlg; return value; } void MainApplication::mainClose() { int opt = this->CreateShowDialog("Exit", "Exit HekateBrew ?",{"Yes", "No", "Cancel"}, true); if (opt == 0) { this->CloseWithFadeOut(); } } void MainApplication::endWithErrorMessage(std::string errMessage) { int sopt = this->CreateShowDialog("Error", errMessage, {"OK"}, false, gsets.CustomScheme.warnImage); if (sopt == 0) { this->CloseWithFadeOut(); } } void MainApplication::ShowLoading(bool close) { this->EndOverlay(); if (!close) this->StartOverlay(this->loader); } }
8,613
C++
.cpp
181
38.005525
225
0.638356
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,965
ui_SliderDialog.cpp
bemardev_HekateBrew/Source/ui/ui_SliderDialog.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_SliderDialog.hpp> #include <IconTypes.hpp> #include <Utils.hpp> namespace ui { SliderDialog::SliderDialog(std::string Title, int MinValue, int MaxValue, int Step, int CurrentValue) { // Slider width : 600px // Slider height : 6px // Diametre : 42px // Border : 5px this->blinktime = std::chrono::steady_clock::now(); this->_blink = true; this->_txtclr = {255, 255, 255, 255}; this->_borderclr = {18, 187, 254, 255}; this->_altclr = {115, 223, 235, 255}; this->_baseclr = {70, 70, 70, 255}; this->_lineclr = {106, 106, 106, 255}; this->_innerclr = {58, 61, 66, 255}; this->x = 340; this->y = 0; this->w = 600; this->h = 21; this->minValue = MinValue; this->maxValue = MaxValue; this->currentValue = CurrentValue; this->step = Step; this->currentXpos = 0; this->previsel = 0; this->isel = 0; this->fisel = 0; this->selfact = 255; this->pselfact = 0; this->onselch = [&](){}; this->icdown = false; this->dtouch = false; this->font = pu::ui::render::LoadDefaultFont(25); this->icofont = pu::ui::render::LoadSharedIconFont(pu::ui::render::SharedFont::NintendoExtended, 25); this->title = Title; this->cancel = false; this->vtex = pu::ui::render::RenderText(this->font, std::to_string(this->currentValue), this->_bfocus); this->iconLaunch = elm::TextIcon::New(1220, 670, "Ok", Icons::Icon_A, this->_txtclr, elm::TextIconAlign::Right); this->iconMove = elm::TextIcon::New(this->iconLaunch->GetX() - 40, 670, "Move", Icons::Icon_JoystickR, this->_txtclr, elm::TextIconAlign::Right); this->iconCancel = elm::TextIcon::New(this->iconMove->GetX() - 40, 670, "Cancel", Icons::Icon_B, this->_txtclr, elm::TextIconAlign::Right); } SliderDialog::~SliderDialog() { pu::ui::render::DeleteTexture(this->vtex); } s32 SliderDialog::GetX() { return this->x; } void SliderDialog::SetX(s32 X) { this->x = X; } s32 SliderDialog::GetY() { return this->y; } void SliderDialog::SetY(s32 Y) { this->y = Y; } void SliderDialog::SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor, pu::ui::Color BaseFocus) { this->_txtclr = TextColor; this->_borderclr = BorderColor; this->_altclr = AltBorderColor; this->_innerclr = InnerBorderColor; this->_baseclr = BaseColor; this->_lineclr = LineColor; this->_bfocus = BaseFocus; this->iconLaunch->SetColor(this->_txtclr); this->iconMove->SetColor(this->_txtclr); this->iconCancel->SetColor(this->_txtclr); pu::ui::render::DeleteTexture(this->vtex); this->vtex = pu::ui::render::RenderText(this->font, std::to_string(this->currentValue), this->_bfocus); } void SliderDialog::SetOnSelectionChanged(std::function<void()> Callback) { this->onselch = Callback; } int SliderDialog::Show(pu::ui::render::Renderer::Ref &Drawer, void *App) { pu::ui::Color ovclr({this->_baseclr.R, this->_baseclr.G, this->_baseclr.B, 140}); this->SetY(720 - (73 /*bottom buttons*/ + 10*2 /*padding before/after elements*/ + 72 /*top text title*/ + 60)); auto titletex = pu::ui::render::RenderText(this->font, this->title, this->_txtclr); s32 tth = pu::ui::render::GetTextHeight(this->font, this->title); s32 telmy = this->GetY()+11 + ((60 - tth) / 2); bool end = false; while(true) { bool ok = ((pu::ui::Application*)App)->CallForRenderWithRenderOver([&](pu::ui::render::Renderer::Ref &Drawer) -> bool { pu::ui::render::DeleteTexture(this->vtex); this->currentXpos = ((float)this->w/this->maxValue)*this->currentValue; this->vtex = pu::ui::render::RenderText(this->font, std::to_string(this->currentValue), this->_bfocus); s32 ytex = this->GetY() + 72 + ((60 - pu::ui::render::GetTextHeight(this->font, std::to_string(this->currentValue))) / 2); //Global overlay Drawer->RenderRectangleFill(ovclr, 0, 0, 1280, 720); //Popup back color Drawer->RenderRectangleFill(this->_baseclr, 0, this->GetY(), 1280, 720-this->GetY()); //Top Separator Line Drawer->RenderLine(this->_txtclr, 30, this->GetY() + 71, 1250, this->GetY() + 71); //Bottom Separator Line Drawer->RenderLine(this->_txtclr, 30, 647, 1250, 647); //Title Text Drawer->RenderTexture(titletex, 72, telmy); // Top element separator Drawer->RenderRectangleFill(this->_bfocus, this->GetX(), 604, this->currentXpos, 6); Drawer->RenderRectangleFill(this->_lineclr, this->GetX() + this->currentXpos, 604, 600 - this->currentXpos, 6); auto curtime = std::chrono::steady_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - this->blinktime).count(); if (diff >= 500) { this->_blink = !this->_blink; this->blinktime = std::chrono::steady_clock::now(); } if (this->_blink) { Drawer->RenderCircleFill(this->_borderclr, this->GetX() + this->currentXpos, 607, 26); } else { Drawer->RenderCircleFill(this->_altclr, this->GetX() + this->currentXpos, 607, 26); } Drawer->RenderCircleFill(this->_innerclr, this->GetX() + this->currentXpos, 607, 21); Drawer->RenderTexture(this->vtex, this->GetX()+625, ytex); u64 d = hidKeysDown(CONTROLLER_P1_AUTO); u64 h = hidKeysHeld(CONTROLLER_P1_AUTO); if((d & KEY_DRIGHT) || (h & KEY_RSTICK_RIGHT)) { end = false; this->cancel = false; if(this->currentValue<this->maxValue) this->currentValue+=this->step; } else if((d & KEY_DLEFT) || (h & KEY_RSTICK_LEFT)) { end = false; this->cancel = false; if(this->currentValue>this->minValue) this->currentValue-=this->step; } else if(d & KEY_A) { end = true; this->cancel = false; } else if(d & KEY_B) { end = true; this->cancel = true; } u64 th = hidKeysDown(CONTROLLER_HANDHELD); this->iconLaunch->OnRender(Drawer, this->iconLaunch->GetX(), this->iconLaunch->GetY()); this->iconMove->OnRender(Drawer, this->iconMove->GetX(), this->iconMove->GetY()); this->iconCancel->OnRender(Drawer, this->iconCancel->GetX(), this->iconCancel->GetY()); if(end) return false; return true; }); if(!ok) { ((pu::ui::Application*)App)->CallForRenderWithRenderOver([&](pu::ui::render::Renderer::Ref &Drawer) -> bool {}); break; } } return this->currentValue; } bool SliderDialog::UserCancelled() { return this->cancel; } }
8,671
C++
.cpp
194
33.649485
226
0.554398
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,966
ui_HkConfigLayout.cpp
bemardev_HekateBrew/Source/ui/ui_HkConfigLayout.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_HkConfigLayout.hpp> #include <ui/ui_MainApplication.hpp> #include <PayloadReboot.hpp> namespace ui { HkConfigLayout::HkConfigLayout() : pu::ui::Layout() { this->SetBackgroundColor(gsets.CustomScheme.Background); //ActionIcons this->iconLaunch = elm::TextIcon::New(1220, 670, "Launch", Icons::Icon_A, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconLaunch); this->iconClose = elm::TextIcon::New(this->iconLaunch->GetX() - 40, 670, "Back", Icons::Icon_B, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconClose); this->pageName = pu::ui::elm::TextBlock::New(60, 20, "", 25); this->pageName->SetColor(gsets.CustomScheme.Text); this->Add(this->pageName); this->buttonGrid = elm::SimpleGrid::New(60, 112, true); this->buttonGrid->SetItemSize(192); this->buttonGrid->SetVerticalPadding(65); this->buttonGrid->SetHorizontalPadding(128); this->buttonGrid->SetTextUnderIcon(true); this->buttonGrid->SetFontSize(20); this->buttonGrid->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base); this->Add(this->buttonGrid); this->SetOnInput(std::bind(&HkConfigLayout::OnInput, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } void HkConfigLayout::Load() { this->pageName->SetText("Launch"); for (auto const& item : gsets.hekateItems) { std::string image = item.entryImage.empty() ? gsets.CustomScheme.defaultImage : item.entryImage; elm::SimpleGridItem::Ref launchItem = elm::SimpleGridItem::New(image, item.entryName); launchItem->AddOnClick([this, item] { this->buttonGrid_OnClick(item.entryIndex, item.entryInList); }); this->buttonGrid->AddItem(launchItem); } if (this->buttonGrid->GetItems().size() > 0) this->buttonGrid->SetSelectedIndex(0); } void HkConfigLayout::Unload() { this->buttonGrid->ClearItems(); } void HkConfigLayout::buttonGrid_OnClick(std::string autoboot, std::string autobootl) { if (!PayloadReboot::AlterPayload(autoboot, autobootl, gsets.hbConfig.path, true)) { mainapp->showNotification("Error sending config to hekate payload"); } } void HkConfigLayout::OnInput(u64 Down, u64 Up, u64 Held) { if ((Down & KEY_B)) { this->Unload(); mainapp->LoadLayout(mainapp->GetMainPageLayout()); mainapp->GetMainPageLayout()->Load(); } } }
3,545
C++
.cpp
80
37.325
178
0.668406
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,968
ui_PayloadLayout.cpp
bemardev_HekateBrew/Source/ui/ui_PayloadLayout.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_PayloadLayout.hpp> #include <ui/ui_MainApplication.hpp> #include <PayloadReboot.hpp> #include <Utils.hpp> #include <vector> namespace ui { PayloadLayout::PayloadLayout() : pu::ui::Layout() { this->SetBackgroundColor(gsets.CustomScheme.Background); //ActionIcons this->iconLaunch = elm::TextIcon::New(1220, 670, "Launch", Icons::Icon_A, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconLaunch); this->iconClose = elm::TextIcon::New(this->iconLaunch->GetX() - 40, 670, "Back", Icons::Icon_B, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconClose); this->pageName = pu::ui::elm::TextBlock::New(60, 20, "", 25); this->pageName->SetColor(gsets.CustomScheme.Text); this->Add(this->pageName); this->buttonGrid = elm::SimpleGrid::New(60, 112, true); this->buttonGrid->SetItemSize(192); this->buttonGrid->SetVerticalPadding(65); this->buttonGrid->SetHorizontalPadding(128); this->buttonGrid->SetTextUnderIcon(true); this->buttonGrid->SetFontSize(20); this->buttonGrid->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base); this->Add(this->buttonGrid); this->SetOnInput(std::bind(&PayloadLayout::OnInput, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } void PayloadLayout::Load() { this->pageName->SetText("Payloads"); for (auto const& item : gsets.payloadItems) { std::string image = item.payloadImage.empty() ? gsets.CustomScheme.defaultImage : item.payloadImage; elm::SimpleGridItem::Ref launchItem = elm::SimpleGridItem::New(image, item.payloadName); launchItem->AddOnClick([this, item] { this->buttonGrid_OnClick(item.payloadPath); }); this->buttonGrid->AddItem(launchItem); } if (this->buttonGrid->GetItems().size() > 0) this->buttonGrid->SetSelectedIndex(0); } void PayloadLayout::Unload() { this->buttonGrid->ClearItems(); } void PayloadLayout::buttonGrid_OnClick(std::string payloadPath) { if (PayloadReboot::Init(payloadPath)) PayloadReboot::Reboot(); } void PayloadLayout::OnInput(u64 Down, u64 Up, u64 Held) { if ((Down & KEY_B)) { this->Unload(); mainapp->LoadLayout(mainapp->GetMainPageLayout()); mainapp->GetMainPageLayout()->Load(); } } }
3,529
C++
.cpp
80
36.2125
179
0.652263
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,969
ui_OptionsLayout.cpp
bemardev_HekateBrew/Source/ui/ui_OptionsLayout.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_OptionsLayout.hpp> #include <ui/ui_MainApplication.hpp> #include <set/set_Settings.hpp> #include <Utils.hpp> #include <vector> namespace ui { OptionsLayout::OptionsLayout() : pu::ui::Layout() { this->SetBackgroundColor(gsets.CustomScheme.Background); this->optionSeparator = elm::SeparatorLine::New(320, 112, 320, 608, gsets.CustomScheme.Text); this->Add(this->optionSeparator); //ActionIcons this->iconLaunch = elm::TextIcon::New(1220, 670, "Ok", Icons::Icon_A, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconLaunch); this->iconSave = elm::TextIcon::New(this->iconLaunch->GetX() - 40, 670, "Save", Icons::Icon_Y, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconSave); this->iconHint = elm::TextIcon::New(this->iconSave->GetX() - 40, 670, "Infos", Icons::Icon_Minus, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconHint); this->iconClose = elm::TextIcon::New(this->iconHint->GetX() - 40, 670, "Back", Icons::Icon_B, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconClose); this->pageName = pu::ui::elm::TextBlock::New(60, 20, "", 25); this->pageName->SetColor(gsets.CustomScheme.Text); this->Add(this->pageName); this->optionsMenu = elm::NinMenu::New(30, 112, 280, gsets.CustomScheme.Background, 65, 6); this->optionsMenu->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base, gsets.CustomScheme.BaseFocus); this->optionsMenu->SetOnSelectionChanged([this] { this->contentsMenu->ClearItems(); }); this->optionsMenu->SetIsFocused(true); this->Add(this->optionsMenu); this->contentsMenu = elm::NinContentMenu::New(330, 112, 920, gsets.CustomScheme.Background, 65, 6); this->contentsMenu->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base, gsets.CustomScheme.BaseFocus); this->contentsMenu->SetIsFocused(false); this->Add(this->contentsMenu); this->SetOnInput(std::bind(&OptionsLayout::OnInput, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } void OptionsLayout::Load() { this->pageName->SetText("Options"); elm::NinMenuItem::Ref hekateBrewOptions = elm::NinMenuItem::New("HekateBrew"); hekateBrewOptions->SetColor(gsets.CustomScheme.Text); hekateBrewOptions->AddOnClick([this] { this->LoadHekateBrewOptionsItems(true); }); hekateBrewOptions->AddOnClick([this] { this->LoadHekateBrewOptionsItems(true); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }, KEY_RIGHT); this->optionsMenu->AddItem(hekateBrewOptions); elm::NinMenuItem::Ref payloadOptions = elm::NinMenuItem::New("Payloads"); payloadOptions->SetColor(gsets.CustomScheme.Text); payloadOptions->AddOnClick([this] { this->LoadPayloadOptionsItems(true); }); payloadOptions->AddOnClick([this] { this->LoadPayloadOptionsItems(true); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }, KEY_RIGHT); this->optionsMenu->AddItem(payloadOptions); if(gsets.hbConfig.hasHekate) { elm::NinMenuItem::Ref hekateOptions = elm::NinMenuItem::New("Hekate config"); hekateOptions->SetColor(gsets.CustomScheme.Text); hekateOptions->AddOnClick([this] { this->LoadHekateOptionsItems(true); }); hekateOptions->AddOnClick([this] { this->LoadHekateOptionsItems(true); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }, KEY_RIGHT); this->optionsMenu->AddItem(hekateOptions); } this->optionsMenu->SetIsFocused(true); this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetSelectedIndex(0); } void OptionsLayout::LoadPayloadOptionsItems(bool isFocused) { this->contentsMenu->ClearItems(); // Show Hekate payloads elm::NinContentMenuItem::Ref showHekate = elm::NinContentMenuItem::New("Show Hekate payloads", gsets.hbConfig.showHekate=="1" ? "Yes" : "No"); showHekate->SetColor(gsets.CustomScheme.Text); showHekate->SetValueColor(gsets.hbConfig.showHekate=="1" ? gsets.CustomScheme.BaseFocus : gsets.CustomScheme.LineSep); showHekate->AddOnClick([this, isFocused] { gsets.hbConfig.showHekate = (gsets.hbConfig.showHekate=="1") ? "0" : "1"; this->LoadPayloadOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); showHekate->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); showHekate->AddOnClick([] { mainapp->showNotification("Show existing payloads from sdmc:/bootloader/payloads/", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(showHekate); // Show Argon payloads elm::NinContentMenuItem::Ref showArgon = elm::NinContentMenuItem::New("Show Argon payloads", gsets.hbConfig.showArgon=="1" ? "Yes" : "No"); showArgon->SetColor(gsets.CustomScheme.Text); showArgon->SetValueColor(gsets.hbConfig.showArgon=="1" ? gsets.CustomScheme.BaseFocus : gsets.CustomScheme.LineSep); showArgon->AddOnClick([this, isFocused] { gsets.hbConfig.showArgon = (gsets.hbConfig.showArgon=="1") ? "0" : "1"; this->LoadPayloadOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); showArgon->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); showArgon->AddOnClick([] { mainapp->showNotification("Show existing payloads from sdmc:/argon/payloads/", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(showArgon); // Show root payload dir elm::NinContentMenuItem::Ref showRootDir = elm::NinContentMenuItem::New("Show payloads from sdmc:/payloads", gsets.hbConfig.showRootDir=="1" ? "Yes" : "No"); showRootDir->SetColor(gsets.CustomScheme.Text); showRootDir->SetValueColor(gsets.hbConfig.showRootDir=="1" ? gsets.CustomScheme.BaseFocus : gsets.CustomScheme.LineSep); showRootDir->AddOnClick([this, isFocused] { gsets.hbConfig.showRootDir = (gsets.hbConfig.showRootDir=="1") ? "0" : "1"; this->LoadPayloadOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); showRootDir->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); showRootDir->AddOnClick([] { mainapp->showNotification("Show existing payloads from sdmc:/payloads/", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(showRootDir); // Show Custom path payloads elm::NinContentMenuItem::Ref showCustomPath = elm::NinContentMenuItem::New("Show custom path payloads", gsets.hbConfig.showCustomPath=="1" ? "Yes" : "No"); showCustomPath->SetColor(gsets.CustomScheme.Text); showCustomPath->SetValueColor(gsets.hbConfig.showCustomPath=="1" ? gsets.CustomScheme.BaseFocus : gsets.CustomScheme.LineSep); showCustomPath->AddOnClick([this, isFocused] { gsets.hbConfig.showCustomPath = (gsets.hbConfig.showCustomPath=="1") ? "0" : "1"; this->LoadPayloadOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); showCustomPath->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); showCustomPath->AddOnClick([] { mainapp->showNotification("Show existing payloads from defined custom path", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(showCustomPath); // Custom payload path if(gsets.hbConfig.showCustomPath == "1") { elm::NinContentMenuItem::Ref customPath = elm::NinContentMenuItem::New("Custom path", gsets.hbConfig.customPath); customPath->SetColor(gsets.CustomScheme.Text); customPath->SetValueColor(gsets.CustomScheme.BaseFocus); customPath->AddOnClick([this, isFocused] { std::string returnVal = mainapp->CreateFileDialog("Custom path", "sdmc:/"); if(returnVal != std::string()) { removeDblSlash(returnVal); gsets.hbConfig.customPath = returnVal; } this->LoadPayloadOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); customPath->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); customPath->AddOnClick([] { mainapp->showNotification("Custom path definition", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(customPath); } this->optionsMenu->SetIsFocused(!isFocused); this->contentsMenu->SetIsFocused(isFocused); } void OptionsLayout::LoadHekateOptionsItems(bool isFocused) { this->contentsMenu->ClearItems(); // autoboot/autoboot_List elm::NinContentMenuItem::Ref autoboot = elm::NinContentMenuItem::New("autoboot / autoboot_list", gsets.hConfig.autoboot + " / " + gsets.hConfig.autoboot_list); autoboot->SetColor(gsets.CustomScheme.Text); autoboot->SetValueColor(gsets.CustomScheme.BaseFocus); autoboot->AddOnClick([this, isFocused] { std::vector<ListDialogItem::Ref> listItems; ListDialogItem::Ref disabledItem = ListDialogItem::New("Disabled"); if(gsets.hConfig.autoboot == "0" && gsets.hConfig.autoboot_list == "0") disabledItem->SetSelected(true); listItems.push_back(disabledItem); for(auto &config : gsets.hekateItems) { ListDialogItem::Ref configItem = ListDialogItem::New(config.entryName); configItem->SetIcon(config.entryImage); if(gsets.hConfig.autoboot == config.entryIndex && gsets.hConfig.autoboot_list == config.entryInList) configItem->SetSelected(true); listItems.push_back(configItem); } int returnVal = mainapp->CreateListDialog("autoboot", listItems); if(returnVal != -1) { if(returnVal == 0) { gsets.hConfig.autoboot = std::to_string(returnVal); gsets.hConfig.autoboot_list = std::to_string(returnVal); } else { gsets.hConfig.autoboot = gsets.hekateItems[returnVal-1].entryIndex; gsets.hConfig.autoboot_list = gsets.hekateItems[returnVal-1].entryInList; } } this->LoadHekateOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); autoboot->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); autoboot->AddOnClick([] { mainapp->showNotification("0: Disable, #: Boot entry number to auto boot / \n0: Read autoboot boot entry from hekate_ipl.ini, 1: Read from ini folder (ini files are ASCII ordered)", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(autoboot); // bootwait elm::NinContentMenuItem::Ref bootwait = elm::NinContentMenuItem::New("bootwait", gsets.hConfig.bootwait); bootwait->SetColor(gsets.CustomScheme.Text); bootwait->SetValueColor(gsets.hConfig.bootwait == "0" ? gsets.CustomScheme.LineSep : gsets.CustomScheme.BaseFocus); bootwait->AddOnClick([this, isFocused] { int returnVal = mainapp->CreateSliderDialog("Bootwait", 0, 10, 1, std::stoi(gsets.hConfig.bootwait)); if(returnVal != -1) gsets.hConfig.bootwait = std::to_string(returnVal); this->LoadHekateOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); bootwait->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); bootwait->AddOnClick([] { mainapp->showNotification("0: Disable (It also disables bootlogo. Having VOL- pressed since injection goes to menu.)\n#: Time to wait for VOL- to enter menu", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(bootwait); // verification elm::NinContentMenuItem::Ref verification = elm::NinContentMenuItem::New("verification", gsets.hConfig.verification); verification->SetColor(gsets.CustomScheme.Text); verification->SetValueColor(gsets.hConfig.verification == "0" ? gsets.CustomScheme.LineSep : gsets.CustomScheme.BaseFocus); verification->AddOnClick([this, isFocused] { std::vector<ListDialogItem::Ref> listItems; for(auto &verif : {"0","1","2"}) { ListDialogItem::Ref valueItem = ListDialogItem::New(verif); if(gsets.hConfig.verification == verif) valueItem->SetSelected(true); listItems.push_back(valueItem); } int returnVal = mainapp->CreateListDialog("verification", listItems); if(returnVal != -1) gsets.hConfig.verification = std::to_string(returnVal); this->LoadHekateOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); verification->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); verification->AddOnClick([] { mainapp->showNotification("0: Disable Backup/Restore verification\n1: Sparse (block based, fast and not 100% reliable)\n2: Full (sha256 based, slow and 100% reliable).", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(verification); // backlight elm::NinContentMenuItem::Ref backlight = elm::NinContentMenuItem::New("backlight", gsets.hConfig.backlight); backlight->SetColor(gsets.CustomScheme.Text); backlight->SetValueColor(gsets.hConfig.backlight == "0" ? gsets.CustomScheme.LineSep : gsets.CustomScheme.BaseFocus); backlight->AddOnClick([this, isFocused] { int returnVal = mainapp->CreateSliderDialog("Backlight", 0, 255, 5, std::stoi(gsets.hConfig.backlight)); if(returnVal != -1) gsets.hConfig.backlight = std::to_string(returnVal); this->LoadHekateOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); backlight->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); backlight->AddOnClick([] { mainapp->showNotification("Screen backlight level from 0 to 255", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(backlight); // autohosoff elm::NinContentMenuItem::Ref autohosoff = elm::NinContentMenuItem::New("autohosoff", gsets.hConfig.autohosoff); autohosoff->SetColor(gsets.CustomScheme.Text); autohosoff->SetValueColor(gsets.hConfig.autohosoff == "0" ? gsets.CustomScheme.LineSep : gsets.CustomScheme.BaseFocus); autohosoff->AddOnClick([this, isFocused] { std::vector<ListDialogItem::Ref> listItems; for(auto &autohosoff : {"0","1","2"}) { ListDialogItem::Ref valueItem = ListDialogItem::New(autohosoff); if(gsets.hConfig.autohosoff == autohosoff) valueItem->SetSelected(true); listItems.push_back(valueItem); } int returnVal = mainapp->CreateListDialog("autohosoff", listItems); if(returnVal != -1) gsets.hConfig.autohosoff = std::to_string(returnVal); this->LoadHekateOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); autohosoff->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); autohosoff->AddOnClick([] { mainapp->showNotification("0: Disable\n1: If woke up from HOS via an RTC alarm, shows logo, then powers off completely\n2: No logo, immediately powers off", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(autohosoff); // autonogc elm::NinContentMenuItem::Ref autonogc = elm::NinContentMenuItem::New("autonogc", gsets.hConfig.autonogc); autonogc->SetColor(gsets.CustomScheme.Text); autonogc->SetValueColor(gsets.hConfig.autonogc == "0" ? gsets.CustomScheme.LineSep : gsets.CustomScheme.BaseFocus); autonogc->AddOnClick([this, isFocused] { //Load popup or ui element to modify gsets.hConfig.autonogc = (gsets.hConfig.autonogc == "0") ? "1" : "0"; this->LoadHekateOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); autonogc->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); autonogc->AddOnClick([] { mainapp->showNotification("0: Disable\n1: Automatically applies nogc patch if unburnt fuses found and a >= 4.0.0 HOS is booted", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(autonogc); this->optionsMenu->SetIsFocused(!isFocused); this->contentsMenu->SetIsFocused(isFocused); } void OptionsLayout::LoadHekateBrewOptionsItems(bool isFocused) { this->contentsMenu->ClearItems(); // Autoboot option elm::NinContentMenuItem::Ref autoboot = elm::NinContentMenuItem::New("Autoboot", gsets.hbConfig.autoboot=="0" ? "Disabled" : (gsets.hbConfig.autoboot == "1" ? "Payload" : "Hekate config")); autoboot->SetColor(gsets.CustomScheme.Text); autoboot->SetValueColor(gsets.hbConfig.autoboot=="0" ? gsets.CustomScheme.LineSep : gsets.CustomScheme.BaseFocus); autoboot->AddOnClick([this, isFocused] { std::vector<ListDialogItem::Ref> listItems; int index=0; for(auto &hbautoboot : {"Disabled", "Payload", "Hekate config"}) { ListDialogItem::Ref valueItem = ListDialogItem::New(hbautoboot); if(gsets.hbConfig.autoboot == std::to_string(index)) valueItem->SetSelected(true); listItems.push_back(valueItem); index+=1; } int returnVal = mainapp->CreateListDialog("autoboot", listItems); if(returnVal != -1) gsets.hbConfig.autoboot = std::to_string(returnVal); this->LoadHekateBrewOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); autoboot->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); autoboot->AddOnClick([] { mainapp->showNotification("Autoboot payload or hekate config", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(autoboot); if(gsets.hbConfig.autoboot == "1") { if(gsets.payloadItems.size() > 0) { elm::NinContentMenuItem::Ref autoboot_payload = elm::NinContentMenuItem::New("Autoboot payload", (gsets.hbConfig.autoboot_payload=="" || std::stoi(gsets.hbConfig.autoboot_payload) > gsets.payloadItems.size() -1) ? "" : gsets.payloadItems[stoi(gsets.hbConfig.autoboot_payload)].payloadName); autoboot_payload->SetColor(gsets.CustomScheme.Text); autoboot_payload->SetValueColor(gsets.CustomScheme.BaseFocus); autoboot_payload->AddOnClick([this, isFocused] { std::vector<ListDialogItem::Ref> listItems; int index=0; for(auto &payload : gsets.payloadItems) { ListDialogItem::Ref payloadItem = ListDialogItem::New(payload.payloadPath); payloadItem->SetIcon(payload.payloadImage); if(gsets.hbConfig.autoboot_payload == std::to_string(index)) payloadItem->SetSelected(true); listItems.push_back(payloadItem); index+=1; } int returnVal = mainapp->CreateListDialog("Autoboot payload", listItems); if(returnVal != -1) gsets.hbConfig.autoboot_payload = std::to_string(returnVal); this->LoadHekateBrewOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); autoboot_payload->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); autoboot_payload->AddOnClick([] { mainapp->showNotification("Payload to autoboot", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(autoboot_payload); } else { elm::NinContentMenuItem::Ref autoboot_payload = elm::NinContentMenuItem::New("Autoboot payload", "No payload found !"); autoboot_payload->SetColor(gsets.CustomScheme.Text); autoboot_payload->SetValueColor(pu::ui::Color(218, 11, 11,255)); this->contentsMenu->AddItem(autoboot_payload); } } else if(gsets.hbConfig.autoboot == "2") { if(gsets.hekateItems.size() > 0) { elm::NinContentMenuItem::Ref autoboot_config = elm::NinContentMenuItem::New("Autoboot config", (gsets.hbConfig.autoboot_config=="" || std::stoi(gsets.hbConfig.autoboot_config) > gsets.hekateItems.size() -1) ? "" : gsets.hekateItems[stoi(gsets.hbConfig.autoboot_config)].entryName); autoboot_config->SetColor(gsets.CustomScheme.Text); autoboot_config->SetValueColor(gsets.CustomScheme.BaseFocus); autoboot_config->AddOnClick([this, isFocused] { std::vector<ListDialogItem::Ref> listItems; int index=0; for(auto &config : gsets.hekateItems) { ListDialogItem::Ref configItem = ListDialogItem::New(config.entryName); configItem->SetIcon(config.entryImage); if(gsets.hbConfig.autoboot_config == std::to_string(index)) configItem->SetSelected(true); listItems.push_back(configItem); index+=1; } int returnVal = mainapp->CreateListDialog("Autoboot config", listItems); if(returnVal != -1) gsets.hbConfig.autoboot_config = std::to_string(returnVal); this->LoadHekateBrewOptionsItems(isFocused); this->contentsMenu->SetSelectedIndex(this->contentsMenu->GetSelectedIndex()); }); autoboot_config->AddOnClick([this] { this->contentsMenu->SetIsFocused(false); this->optionsMenu->SetIsFocused(true); }, KEY_LEFT); autoboot_config->AddOnClick([] { mainapp->showNotification("Hekate config to autoboot", 3000); }, KEY_MINUS); this->contentsMenu->AddItem(autoboot_config); } else { elm::NinContentMenuItem::Ref autoboot_config = elm::NinContentMenuItem::New("Autoboot config", "No Hekate config found !"); autoboot_config->SetColor(gsets.CustomScheme.Text); autoboot_config->SetValueColor(pu::ui::Color(218, 11, 11,255)); this->contentsMenu->AddItem(autoboot_config); } } this->optionsMenu->SetIsFocused(!isFocused); this->contentsMenu->SetIsFocused(isFocused); } void OptionsLayout::Unload() { this->optionsMenu->ClearItems(); this->contentsMenu->ClearItems(); } void OptionsLayout::OnInput(u64 Down, u64 Up, u64 Held) { if ((Down & KEY_B)) { this->Unload(); gsets = set::ProcessSettings(); mainapp->LoadLayout(mainapp->GetMainPageLayout()); mainapp->GetMainPageLayout()->Load(); } else if ((Down & KEY_Y)) { mainapp->ShowLoading(); set::SaveSettings(gsets); this->Unload(); set::ReloadList(gsets); mainapp->ShowLoading(true); mainapp->LoadLayout(mainapp->GetMainPageLayout()); mainapp->GetMainPageLayout()->Load(); mainapp->showNotification("Settings saved"); } } }
28,095
C++
.cpp
547
38.892139
306
0.611932
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,970
ui_LoadingOverlay.cpp
bemardev_HekateBrew/Source/ui/ui_LoadingOverlay.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_LoadingOverlay.hpp> namespace ui { LoadingOverlay::LoadingOverlay(pu::String imagePath, pu::ui::Color BaseColor) : Overlay(0, 0, 1280, 720, BaseColor) { this->Loader = elm::RotatableImage::New(550, 270, imagePath, 10, 50); this->Add(this->Loader); } void LoadingOverlay::OnPreRender(pu::ui::render::Renderer::Ref &Drawer) { Drawer->SetBaseRenderAlpha(200); } void LoadingOverlay::OnPostRender(pu::ui::render::Renderer::Ref &Drawer) { Drawer->UnsetBaseRenderAlpha(); } }
1,310
C++
.cpp
34
34.970588
119
0.71956
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,972
ui_TimeDialog.cpp
bemardev_HekateBrew/Source/ui/ui_TimeDialog.cpp
/* * Copyright (C) 2019 bemar * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_TimeDialog.hpp> #include <IconTypes.hpp> #include <Utils.hpp> namespace ui { TimeDialog::TimeDialog(std::string DialogText, s32 Delay) { this->dialogText = DialogText; this->initialDelay = Delay; this->txtcounter = std::to_string(this->initialDelay / 1000); this->delaytime = std::chrono::steady_clock::now(); this->_txtclr = {255, 255, 255, 255}; this->x = 0; this->y = 129; this->w = 1280; this->h = 0; this->dtouch = false; this->font = pu::ui::render::LoadDefaultFont(25); this->cancel = false; } TimeDialog::~TimeDialog() { if(this->texdialog != NULL) pu::ui::render::DeleteTexture(this->texdialog); } s32 TimeDialog::GetX() { return this->x; } void TimeDialog::SetX(s32 X) { this->x = X; } s32 TimeDialog::GetY() { return this->y; } void TimeDialog::SetY(s32 Y) { this->y = Y; } s32 TimeDialog::GetWidth() { return this->w; } void TimeDialog::SetWidth(s32 Width) { this->w = Width; } s32 TimeDialog::GetHeight() { return this->h; } void TimeDialog::SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BaseColor, pu::ui::Color BaseFocus) { this->_txtclr = TextColor; this->_bfocus = BaseFocus; this->_baseclr = BaseColor; if(this->texdialog != NULL) pu::ui::render::DeleteTexture(this->texdialog); this->texdialog = pu::ui::render::RenderText(this->font, this->dialogText, this->_bfocus); } s32 TimeDialog::Show(pu::ui::render::Renderer::Ref &Drawer, void *App) { pu::ui::Color ovclr({this->_baseclr.R, this->_baseclr.G, this->_baseclr.B, 210}); std::string preText = "Autobooting:"; std::string infoText = "Press any key or touch screen to cancel."; pu::ui::render::NativeTexture pretex = NULL; pretex = pu::ui::render::RenderText(this->font, preText, this->_txtclr); s32 ptx = (1280 - pu::ui::render::GetTextWidth(this->font, preText)) /2; pu::ui::render::NativeTexture infotex = NULL; infotex = pu::ui::render::RenderText(this->font, infoText, pu::ui::Color(218, 11, 11,255)); s32 itx = (1280 - pu::ui::render::GetTextWidth(this->font, infoText)) /2; pu::ui::render::NativeTexture delaytex = NULL; s32 dtx = (1280 - pu::ui::render::GetTextWidth(this->font, this->dialogText)) /2; s32 dty = (720 - pu::ui::render::GetTextHeight(this->font, this->dialogText)) /2; bool end = false; while (true) { bool ok = ((pu::ui::Application*)App)->CallForRenderWithRenderOver([&](pu::ui::render::Renderer::Ref & Drawer) -> bool { //Global overlay Drawer->RenderRectangleFill(ovclr, 0, 0, 1280, 720); Drawer->RenderTexture(pretex, ptx, dty - 40); Drawer->RenderTexture(texdialog, dtx, dty); Drawer->RenderTexture(infotex, itx, dty + 40); if(delaytex != NULL) pu::ui::render::DeleteTexture(delaytex); delaytex = pu::ui::render::RenderText(this->font, this->txtcounter, this->_bfocus); s32 ctx = (1280 - pu::ui::render::GetTextWidth(this->font, this->txtcounter)) /2; s32 cty = dty + 80; Drawer->RenderTexture(delaytex, ctx, cty); u64 d = hidKeysDown(CONTROLLER_P1_AUTO); u64 u = hidKeysUp(CONTROLLER_P1_AUTO); u64 h = hidKeysHeld(CONTROLLER_P1_AUTO); u64 th = hidKeysDown(CONTROLLER_HANDHELD); auto curtime = std::chrono::steady_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(curtime - this->delaytime).count(); if ((d) || (u) || (h) || (th)) { end = true; this->cancel = true; } else if(diff >= this->initialDelay) { end = true; this->cancel = false; } else { this->txtcounter = std::to_string((this->initialDelay - diff) / 1000); } if (end) return false; return true; }); if (!ok) { ((pu::ui::Application*)App)->CallForRenderWithRenderOver([&](pu::ui::render::Renderer::Ref & Drawer) -> bool { }); break; } } return 0; } bool TimeDialog::UserCancelled() { return this->cancel; } }
5,623
C++
.cpp
146
28.883562
130
0.56318
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false