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,536,924
Statistics.hpp
lgottwald_PaPILO/src/papilo/core/Statistics.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_CORE_STATISTICS_HPP_ #define _PAPILO_CORE_STATISTICS_HPP_ namespace papilo { struct Statistics { double presolvetime; int ntsxapplied; int ntsxconflicts; int nboundchgs; int nsidechgs; int ncoefchgs; int nrounds; int ndeletedcols; int ndeletedrows; Statistics( double presolvetime, int ntsxapplied, int ntsxconflicts, int nboundchgs, int nsidechgs, int ncoefchgs, int nrounds, int ndeletedcols, int ndeletedrows ) : presolvetime( presolvetime ), ntsxapplied( ntsxapplied ), ntsxconflicts( ntsxconflicts ), nboundchgs( nboundchgs ), nsidechgs( nsidechgs ), ncoefchgs( ncoefchgs ), nrounds( nrounds ), ndeletedcols( ndeletedcols ), ndeletedrows( ndeletedrows ) { } Statistics() : presolvetime( 0.0 ), ntsxapplied( 0 ), ntsxconflicts( 0 ), nboundchgs( 0 ), nsidechgs( 0 ), ncoefchgs( 0 ), nrounds( 0 ), ndeletedcols( 0 ), ndeletedrows( 0 ) { } }; inline Statistics operator-( const Statistics& a, const Statistics& b ) { return Statistics( 0.0, a.ntsxapplied - b.ntsxapplied, a.ntsxconflicts - b.ntsxconflicts, a.nboundchgs - b.nboundchgs, a.nsidechgs - b.nsidechgs, a.ncoefchgs - b.ncoefchgs, a.nrounds - b.nrounds, a.ndeletedcols - b.ndeletedcols, a.ndeletedrows - b.ndeletedrows ); } } // namespace papilo #endif
3,161
C++
.h
64
45.703125
79
0.512621
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,925
VariableDomains.hpp
lgottwald_PaPILO/src/papilo/core/VariableDomains.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_CORE_VARIABLE_DOMAINS_HPP_ #define _PAPILO_CORE_VARIABLE_DOMAINS_HPP_ #include "papilo/misc/Flags.hpp" #include "papilo/misc/MultiPrecision.hpp" #include "papilo/misc/Vec.hpp" #include "papilo/misc/compress_vector.hpp" #include "papilo/misc/tbb.hpp" namespace papilo { enum class ColFlag : uint8_t { kNone = 0, kLbInf = 1 << 0, kLbHuge = 1 << 1, kUbInf = 1 << 2, kUbHuge = 1 << 3, kIntegral = 1 << 4, kFixed = 1 << 5, kSubstituted = 1 << 6, kImplInt = 1 << 7, kUnbounded = static_cast<uint8_t>( ColFlag::kLbInf ) | static_cast<uint8_t>( ColFlag::kUbInf ), kInactive = static_cast<uint8_t>( ColFlag::kFixed ) | static_cast<uint8_t>( ColFlag::kSubstituted ), kLbUseless = static_cast<uint8_t>( ColFlag::kLbInf ) | static_cast<uint8_t>( ColFlag::kLbHuge ), kUbUseless = static_cast<uint8_t>( ColFlag::kUbInf ) | static_cast<uint8_t>( ColFlag::kUbHuge ), }; using ColFlags = Flags<ColFlag>; /// Type to store the domains for the variables in a problem. /// This includes the lower and upper bounds, and whether the /// variable is constraint to integral values. template <typename REAL> struct VariableDomains { Vec<REAL> lower_bounds; Vec<REAL> upper_bounds; Vec<ColFlags> flags; void compress( const Vec<int>& colmapping, bool full = false ); bool isBinary( int col ) const { return flags[col].test( ColFlag::kIntegral ) && !flags[col].test( ColFlag::kLbUseless, ColFlag::kUbUseless, ColFlag::kInactive ) && lower_bounds[col] == 0 && upper_bounds[col] == 1; } template <typename Archive> void serialize( Archive& ar, const unsigned int version ) { ar& lower_bounds; ar& upper_bounds; ar& flags; } }; #ifdef PAPILO_USE_EXTERN_TEMPLATES extern template struct VariableDomains<double>; extern template struct VariableDomains<Quad>; extern template struct VariableDomains<Rational>; #endif template <typename REAL> void VariableDomains<REAL>::compress( const Vec<int>& colmapping, bool full ) { tbb::parallel_invoke( [this, &colmapping, full]() { compress_vector( colmapping, lower_bounds ); if( full ) lower_bounds.shrink_to_fit(); }, [this, &colmapping, full]() { compress_vector( colmapping, upper_bounds ); if( full ) upper_bounds.shrink_to_fit(); }, [this, &colmapping, full]() { compress_vector( colmapping, flags ); if( full ) flags.shrink_to_fit(); } ); } } // namespace papilo #endif
4,444
C++
.h
108
36.62037
79
0.533765
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,926
PresolveOptions.hpp
lgottwald_PaPILO/src/papilo/core/PresolveOptions.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_CORE_PRESOLVE_OPTIONS_HPP_ #define _PAPILO_CORE_PRESOLVE_OPTIONS_HPP_ #include "papilo/misc/ParameterSet.hpp" #include <type_traits> namespace papilo { struct PresolveOptions { // add the parameters with their default values int maxfillinpersubstitution = 10; double markowitz_tolerance = 0.01; int maxshiftperrow = 10; bool substitutebinarieswithints = true; int dualreds = 2; double abortfac = 8e-4; double lpabortfac = 1e-2; bool boundrelax = false; int componentsmaxint = 0; double compressfac = 0.85; double tlim = std::numeric_limits<double>::max(); double minabscoeff = 1e-10; double feastol = 1e-6; double epsilon = 1e-9; double hugeval = 1e8; bool removeslackvars = true; int weakenlpvarbounds = 0; int detectlindep = 1; int threads = 0; unsigned int randomseed = 0; void addParameters( ParameterSet& paramSet ) { paramSet.addParameter( "presolve.dualreds", "0: disable dual reductions, 1: allow dual reductions that never cut " "off optimal solutions, 2: allow all dual reductions", dualreds, 0, 2 ); paramSet.addParameter( "substitution.markowitz_tolerance", "markowitz tolerance value for allowing a substitution", markowitz_tolerance, 0.0, 1.0 ); paramSet.addParameter( "presolve.abortfac", "abort factor of weighted number of reductions for presolving", abortfac, 0.0, 1.0 ); paramSet.addParameter( "presolve.lpabortfac", "abort factor of weighted number of reductions for presolving LPs", lpabortfac, 0.0, 1.0 ); paramSet.addParameter( "substitution.maxfillin", "maximum estimated fillin for variable substitutions", maxfillinpersubstitution, 0 ); paramSet.addParameter( "presolve.randomseed", "random seed value", randomseed ); paramSet.addParameter( "substitution.maxshiftperrow", "maximum amount of nonzeros being moved to make " "space for fillin from substitutions within a row", maxshiftperrow, 0 ); paramSet.addParameter( "substitution.binarieswithints", "should substitution of binary variables with " "general integers be allowd", substitutebinarieswithints ); paramSet.addParameter( "presolve.boundrelax", "relax bounds of implied free variables after presolving", boundrelax ); paramSet.addParameter( "presolve.removeslackvars", "remove slack variables in equations", removeslackvars ); paramSet.addParameter( "presolve.componentsmaxint", "maximum number of integral variables for trying to solve " "disconnected components of the problem in presolving (-1: disabled)", componentsmaxint, -1 ); paramSet.addParameter( "presolve.compressfac", "compress the problem if fewer than compressfac " "times the number of rows or columns are active", compressfac, 0.0, 1.0 ); paramSet.addParameter( "presolve.tlim", "time limit for presolve", tlim, 0.0 ); paramSet.addParameter( "presolve.minabscoeff", "minimum absolute coefficient value allowed in " "matrix, before it is set to zero", minabscoeff, 0.0, 1e-1 ); paramSet.addParameter( "numerics.feastol", "the feasibility tolerance", feastol, 0.0, 1e-1 ); paramSet.addParameter( "numerics.epsilon", "epsilon tolerance to consider two values equal", epsilon, 0.0, 1e-1 ); paramSet.addParameter( "numerics.hugeval", "absolute bound value that is considered too huge " "for activitity based calculations", hugeval, 0.0 ); paramSet.addParameter( "presolve.weakenlpvarbounds", "weaken bounds obtained by constraint propagation by this factor of " "the feasibility tolerance if the problem is an LP", weakenlpvarbounds ); paramSet.addParameter( "presolve.detectlindep", "detect and remove linearly dependent equations " "and free columns (0: off, 1: for LPs, 2: always)", detectlindep, 0, 2 ); paramSet.addParameter( "presolve.threads", "maximal number of threads to use (0: automatic)", threads, 0 ); } }; } // namespace papilo #endif
6,748
C++
.h
132
40.469697
80
0.536115
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,927
PresolveMethod.hpp
lgottwald_PaPILO/src/papilo/core/PresolveMethod.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_CORE_PRESOLVE_METHOD_HPP_ #define _PAPILO_CORE_PRESOLVE_METHOD_HPP_ #include "papilo/core/PresolveOptions.hpp" #include "papilo/core/Reductions.hpp" #include "papilo/core/RowFlags.hpp" #include "papilo/core/VariableDomains.hpp" #include "papilo/io/Message.hpp" #include "papilo/misc/Num.hpp" #include "papilo/misc/Vec.hpp" #include "papilo/misc/fmt.hpp" #include "papilo/misc/tbb.hpp" #include <bitset> namespace papilo { // forward declaration of problem and reduction template <typename REAL> class Presolve; template <typename REAL> class Problem; template <typename REAL> class ProblemUpdate; /// result codes of a presolving routine enum class PresolveStatus : int { /// problem was not changed kUnchanged = 0, /// problem was reduced kReduced = 1, /// problem was detected to be unbounded or infeasible kUnbndOrInfeas = 2, /// problem was detected to be unbounded kUnbounded = 3, /// problem was detected to be infeasible kInfeasible = 4, }; enum class PresolverTiming : int { kFast = 0, kMedium = 1, kExhaustive = 2, }; enum class PresolverType { kAllCols, kIntegralCols, kContinuousCols, kMixedCols, }; template <typename REAL> class PresolveMethod { public: PresolveMethod() { ncalls = 0; nsuccessCall = 0; name = "unnamed"; type = PresolverType::kAllCols; timing = PresolverTiming::kExhaustive; delayed = false; execTime = 0.0; enabled = true; skip = 0; nconsecutiveUnsuccessCall = 0; } virtual ~PresolveMethod() {} virtual void compress( const Vec<int>& rowmap, const Vec<int>& colmap ) { } virtual bool initialize( const Problem<REAL>& problem, const PresolveOptions& presolveOptions ) { return false; } virtual void addPresolverParams( ParameterSet& paramSet ) { } void addParameters( ParameterSet& paramSet ) { paramSet.addParameter( fmt::format( "{}.enabled", this->name ).c_str(), fmt::format( "is presolver {} enabled", this->name ).c_str(), this->enabled ); addPresolverParams( paramSet ); } PresolveStatus run( const Problem<REAL>& problem, const ProblemUpdate<REAL>& problemUpdate, const Num<REAL>& num, Reductions<REAL>& reductions ) { if( !enabled || delayed ) return PresolveStatus::kUnchanged; if( skip != 0 ) { --skip; return PresolveStatus::kUnchanged; } if( problem.getNumIntegralCols() == 0 && ( type == PresolverType::kIntegralCols || type == PresolverType::kMixedCols ) ) return PresolveStatus::kUnchanged; if( problem.getNumContinuousCols() == 0 && ( type == PresolverType::kContinuousCols || type == PresolverType::kMixedCols ) ) return PresolveStatus::kUnchanged; ++ncalls; auto start = tbb::tick_count::now(); PresolveStatus result = execute( problem, problemUpdate, num, reductions ); auto end = tbb::tick_count::now(); auto duration = end - start; execTime = execTime + duration.seconds(); switch( result ) { case PresolveStatus::kUnbounded: case PresolveStatus::kUnbndOrInfeas: case PresolveStatus::kInfeasible: Message::debug( &problemUpdate, "[{}:{}] {} detected unboundedness or infeasibility\n", __FILE__, __LINE__, this->name ); case PresolveStatus::kReduced: ++nsuccessCall; nconsecutiveUnsuccessCall = 0; break; case PresolveStatus::kUnchanged: ++nconsecutiveUnsuccessCall; if( timing != PresolverTiming::kFast ) skip += nconsecutiveUnsuccessCall; break; } return result; } void printStats( const Message& message, std::pair<int, int> stats ) { double success = ncalls == 0 ? 0.0 : ( double( nsuccessCall ) / double( ncalls ) ) * 100.0; double applied = stats.first == 0 ? 0.0 : ( double( stats.second ) / double( stats.first ) ) * 100.0; message.info( " {:>18} {:>12} {:>18.1f} {:>18} {:>18.1f} {:>18.3f}\n", name, ncalls, success, stats.first, applied, execTime ); } PresolverType getType() const { return this->type; } PresolverTiming getTiming() const { return this->timing; } bool isEnabled() const { return this->enabled; } bool isDelayed() const { return this->delayed; } const std::string& getName() const { return this->name; } bool runInRound( int roundCounter ) { assert( roundCounter < 4 ); if( ( roundCounter == 0 && timing == PresolverTiming::kFast ) || ( roundCounter == 1 && timing == PresolverTiming::kMedium ) || ( roundCounter == 2 && timing == PresolverTiming::kExhaustive ) ) return true; // always finish with a fast round if( roundCounter == 3 && timing == PresolverTiming::kFast ) return true; return false; } /// todo interface for certificate function and flag to indicate whther /// presolver writes certificates virtual void getCertificate() { } unsigned int getNCalls() const { return ncalls; } void setDelayed( bool delayed ) { this->delayed = delayed; } void setEnabled( bool enabled ) { this->enabled = enabled; } protected: /// execute member function for a presolve method gets the constant problem /// and can communicate reductions via the given reductions object virtual PresolveStatus execute( const Problem<REAL>& problem, const ProblemUpdate<REAL>& problemUpdate, const Num<REAL>& num, Reductions<REAL>& reductions ) = 0; void setName( const std::string& name ) { this->name = name; } void setTiming( PresolverTiming timing ) { this->timing = timing; } void setType( PresolverType type ) { this->type = type; } void skipRounds( unsigned int nrounds ) { this->skip += nrounds; } private: std::string name; double execTime; bool enabled; bool delayed; PresolverTiming timing; PresolverType type; unsigned int ncalls; // number of times execute returns REDUCED unsigned int nsuccessCall; unsigned int nconsecutiveUnsuccessCall; unsigned int skip; }; } // namespace papilo #endif
8,397
C++
.h
271
25.701107
80
0.57969
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,929
NumericalStatistics.hpp
lgottwald_PaPILO/src/papilo/misc/NumericalStatistics.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_NUMERICALSTATISTICS_HPP_ #define _PAPILO_MISC_NUMERICALSTATISTICS_HPP_ #include "papilo/core/ConstraintMatrix.hpp" #include "papilo/core/Problem.hpp" #include "papilo/misc/fmt.hpp" #include <cmath> namespace papilo { template <typename REAL> struct Num_stats { REAL matrixMin; REAL matrixMax; REAL objMin; REAL objMax; REAL boundsMin; REAL boundsMax; REAL rhsMin; REAL rhsMax; REAL dynamism; REAL rowDynamism; REAL colDynamism; }; template <typename REAL> class NumericalStatistics { public: NumericalStatistics( const Problem<REAL>& p ) : stats( Num_stats<REAL>() ), prob( p ) { // Set all values in Num_stats const ConstraintMatrix<REAL>& cm = prob.getConstraintMatrix(); const VariableDomains<REAL>& vd = prob.getVariableDomains(); const Vec<RowFlags>& rf = cm.getRowFlags(); const Vec<REAL>& lhs = cm.getLeftHandSides(); const Vec<REAL>& rhs = cm.getRightHandSides(); int nrows = cm.getNRows(); int ncols = cm.getNCols(); stats.matrixMin = 0.0; stats.matrixMax = 0.0; stats.rowDynamism = 0.0; stats.rhsMin = 0.0; stats.rhsMax = 0.0; bool rhsMinSet = false; // Row dynamism, matrixMin/Max, RHS for( int r = 0; r < nrows; ++r ) { // matrixMin/Max const SparseVectorView<REAL>& row = cm.getRowCoefficients( r ); std::pair<REAL, REAL> minmax = row.getMinMaxAbsValue(); stats.matrixMax = std::max( minmax.second, stats.matrixMax ); if( r == 0 ) stats.matrixMin = stats.matrixMax; else stats.matrixMin = std::min( minmax.first, stats.matrixMin ); // Row dynamism REAL dyn = minmax.second / minmax.first; stats.rowDynamism = std::max( dyn, stats.rowDynamism ); // RHS min/max // Handle case where RHS/LHS is inf if( !rhsMinSet ) { rhsMinSet = true; if( !rf[r].test( RowFlag::kLhsInf ) && !rf[r].test( RowFlag::kRhsInf ) && lhs[r] != 0 && rhs[r] != 0 ) stats.rhsMin = std::min( abs( lhs[r] ), abs( rhs[r] ) ); else if( !rf[r].test( RowFlag::kLhsInf ) && lhs[r] != 0 ) stats.rhsMin = abs( lhs[r] ); else if( !rf[r].test( RowFlag::kRhsInf ) && rhs[r] != 0 ) stats.rhsMin = abs( rhs[r] ); else rhsMinSet = false; } else { if( !rf[r].test( RowFlag::kLhsInf ) && !rf[r].test( RowFlag::kRhsInf ) && lhs[r] != 0 && rhs[r] != 0 ) stats.rhsMin = std::min( stats.rhsMin, REAL( std::min( abs( lhs[r] ), abs( rhs[r] ) ) ) ); else if( !rf[r].test( RowFlag::kLhsInf ) && lhs[r] != 0 ) stats.rhsMin = std::min( stats.rhsMin, REAL( abs( lhs[r] ) ) ); else if( !rf[r].test( RowFlag::kRhsInf ) && rhs[r] != 0 ) stats.rhsMin = std::min( stats.rhsMin, REAL( abs( rhs[r] ) ) ); } if( !rf[r].test( RowFlag::kLhsInf ) && !rf[r].test( RowFlag::kRhsInf ) ) stats.rhsMax = std::max( stats.rhsMax, REAL( std::max( abs( lhs[r] ), abs( rhs[r] ) ) ) ); else if( !rf[r].test( RowFlag::kLhsInf ) ) stats.rhsMax = std::max( stats.rhsMax, REAL( abs( lhs[r] ) ) ); else if( !rf[r].test( RowFlag::kRhsInf ) ) stats.rhsMax = std::max( stats.rhsMax, REAL( abs( rhs[r] ) ) ); } stats.colDynamism = 0.0; stats.boundsMin = 0.0; stats.boundsMax = 0.0; bool boundsMinSet = false; // Column dynamism, Variable Bounds for( int c = 0; c < ncols; ++c ) { // Column dynamism const SparseVectorView<REAL>& col = cm.getColumnCoefficients( c ); std::pair<REAL, REAL> minmax = col.getMinMaxAbsValue(); REAL dyn = minmax.second / minmax.first; stats.colDynamism = std::max( dyn, stats.colDynamism ); // Bounds // Handle case where first variables are unbounded if( !boundsMinSet ) { boundsMinSet = true; if( !vd.flags[c].test( ColFlag::kLbInf ) && !vd.flags[c].test( ColFlag::kUbInf ) && vd.lower_bounds[c] != 0 && vd.upper_bounds[c] != 0 ) stats.boundsMin = std::min( abs( vd.lower_bounds[c] ), abs( vd.upper_bounds[c] ) ); else if( !vd.flags[c].test( ColFlag::kLbInf ) && vd.lower_bounds[c] != 0 ) stats.boundsMin = abs( vd.lower_bounds[c] ); else if( !vd.flags[c].test( ColFlag::kUbInf ) && vd.upper_bounds[c] != 0 ) stats.boundsMin = abs( vd.upper_bounds[c] ); else boundsMinSet = false; } else { if( !vd.flags[c].test( ColFlag::kLbInf ) && !vd.flags[c].test( ColFlag::kUbInf ) && vd.lower_bounds[c] != 0 && vd.upper_bounds[c] != 0 ) stats.boundsMin = std::min( stats.boundsMin, REAL( std::min( abs( vd.lower_bounds[c] ), abs( vd.upper_bounds[c] ) ) ) ); else if( !vd.flags[c].test( ColFlag::kLbInf ) && vd.lower_bounds[c] != 0 ) stats.boundsMin = std::min( stats.boundsMin, REAL( abs( vd.lower_bounds[c] ) ) ); else if( !vd.flags[c].test( ColFlag::kUbInf ) && vd.upper_bounds[c] != 0 ) stats.boundsMin = std::min( stats.boundsMin, REAL( abs( vd.upper_bounds[c] ) ) ); } if( !vd.flags[c].test( ColFlag::kLbInf ) && !vd.flags[c].test( ColFlag::kUbInf ) ) stats.boundsMax = std::max( stats.boundsMax, REAL( std::max( abs( vd.lower_bounds[c] ), abs( vd.upper_bounds[c] ) ) ) ); else if( !vd.flags[c].test( ColFlag::kLbInf ) ) stats.boundsMax = std::max( stats.boundsMax, REAL( abs( vd.lower_bounds[c] ) ) ); else if( !vd.flags[c].test( ColFlag::kUbInf ) ) stats.boundsMax = std::max( stats.boundsMax, REAL( abs( vd.upper_bounds[c] ) ) ); } stats.dynamism = stats.matrixMax / stats.matrixMin; // Objective const Objective<REAL>& obj = prob.getObjective(); stats.objMax = 0.0; stats.objMin = 0.0; bool objMinSet = false; for( int i = 0; i < obj.coefficients.size(); ++i ) { if( obj.coefficients[i] != 0 ) { stats.objMax = std::max( stats.objMax, REAL( abs( obj.coefficients[i] ) ) ); if( !objMinSet ) { stats.objMin = abs( obj.coefficients[i] ); objMinSet = true; } else stats.objMin = std::min( stats.objMin, REAL( abs( obj.coefficients[i] ) ) ); } } } void printStatistics() { fmt::print( "Numerical Statistics:\n Matrix range [{:.0e},{:.0e}]\n " "Objective range [{:.0e},{:.0e}]\n Bounds range " "[{:.0e},{:.0e}]\n RHS range [{:.0e},{:.0e}]\n " "Dynamism Variables: {:.0e}\n Dynamism Rows : {:.0e}\n", double( stats.matrixMin ), double( stats.matrixMax ), double( stats.objMin ), double( stats.objMax ), double( stats.boundsMin ), double( stats.boundsMax ), double( stats.rhsMin ), double( stats.rhsMax ), double( stats.colDynamism ), double( stats.rowDynamism ) ); } const Num_stats<REAL>& getNum_stats() { return stats; } private: Num_stats<REAL> stats; const Problem<REAL>& prob; }; } // namespace papilo #endif
9,956
C++
.h
226
33.765487
80
0.483352
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,932
Timer.hpp
lgottwald_PaPILO/src/papilo/misc/Timer.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_TIMER_HPP_ #define _PAPILO_MISC_TIMER_HPP_ #include "papilo/misc/tbb.hpp" namespace papilo { class Timer { public: Timer( double& time ) : time( time ) { start = tbb::tick_count::now(); } double getTime() const { return ( tbb::tick_count::now() - start ).seconds(); } ~Timer() { time += ( tbb::tick_count::now() - start ).seconds(); } private: tbb::tick_count start; double& time; }; } // namespace papilo #endif
2,235
C++
.h
43
50.023256
79
0.4306
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,933
Alloc.hpp
lgottwald_PaPILO/src/papilo/misc/Alloc.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_ALLOC_HPP_ #define _PAPILO_MISC_ALLOC_HPP_ #include <memory> namespace papilo { template <typename T, int = 0> struct AllocatorTraits { using type = std::allocator<T>; }; template <typename T> using Allocator = typename AllocatorTraits<T>::type; } // namespace papilo #endif
2,066
C++
.h
36
56.111111
79
0.431537
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,934
VectorUtils.hpp
lgottwald_PaPILO/src/papilo/misc/VectorUtils.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_VECTOR_UTILS_HPP_ #define _PAPILO_MISC_VECTOR_UTILS_HPP_ #include "papilo/core/Problem.hpp" #include "papilo/core/RowFlags.hpp" #include "papilo/core/Solution.hpp" #include "papilo/core/SparseStorage.hpp" #include "papilo/io/Message.hpp" #include "papilo/misc/Num.hpp" #include "papilo/misc/Vec.hpp" #include "papilo/misc/fmt.hpp" #include <cassert> namespace papilo { template <typename REAL> bool compareVectors( const Vec<REAL>& first, const Vec<REAL>& second, const Num<REAL>& num ) { bool result = std::equal( first.begin(), first.end(), second.begin(), [&num]( const REAL& left, const REAL& right ) { return num.isEq( left, right ); } ); return result; } template <typename REAL> bool compareVariableDomains( const VariableDomains<REAL>& first, const VariableDomains<REAL>& second, const Num<REAL>& num ) { bool result = std::equal( first.begin(), first.end(), second.begin(), [&num]( const REAL& left, const REAL& right ) { return num.isEq( left, right ); } ); return result; } template <typename REAL> bool compareColBounds( const Vec<REAL>& first_values, const Vec<REAL>& second_values, const Vec<ColFlags>& first_flags, const Vec<ColFlags>& second_flags, const Num<REAL>& num ) { int size = first_values.size(); if( size != first_flags.size() ) return false; if( size != second_values.size() ) return false; if( size != second_flags.size() ) return false; for( int i = 0; i < size; i++ ) { if( ( first_flags[i].test( ColFlag::kLbInf ) && second_flags[i].test( ColFlag::kLbInf ) ) || ( first_flags[i].test( ColFlag::kUbInf ) && second_flags[i].test( ColFlag::kUbInf ) ) ) return false; if( !num.isEq( first_values[i], second_values[i] ) ) return false; } return true; } template <typename REAL> bool compareRowBounds( const Vec<REAL>& first_values, const Vec<REAL>& second_values, const Vec<RowFlags>& first_flags, const Vec<RowFlags>& second_flags, const Num<REAL>& num ) { int size = first_values.size(); if( size != first_flags.size() ) return false; if( size != second_values.size() ) return false; if( size != second_flags.size() ) return false; for( int i = 0; i < size; i++ ) { if( ( first_flags[i].test( RowFlag::kLhsInf ) && second_flags[i].test( RowFlag::kLhsInf ) ) || ( first_flags[i].test( RowFlag::kRhsInf ) && second_flags[i].test( RowFlag::kRhsInf ) ) ) return false; if( !num.isEq( first_values[i], second_values[i] ) ) return false; } return true; } // compare index range template <typename IndexRange> bool compareIndexRanges( const Vec<IndexRange>& first, const Vec<IndexRange>& second ) { bool result = std::equal( first.begin(), first.end(), second.begin(), []( const IndexRange& left, const IndexRange& right ) { return ( left.start == right.start && left.end == right.end ); } ); return result; } // compare matrix values template <typename REAL> bool compareMatrices( const SparseStorage<REAL>& first, const SparseStorage<REAL>& second, const Num<REAL>& num ) { if( first.getNRows() != second.getNRows() ) return false; if( first.getNCols() != second.getNCols() ) return false; if( first.getNnz() != second.getNnz() ) return false; // ranges if( !compareIndexRanges( first.getRowRangesVec(), second.getRowRangesVec() ) ) return false; // columns, values if( !std::equal( first.getColumnsVec().begin(), first.getColumnsVec().end(), second.getColumnsVec().begin() ) ) return false; if( !compareVectors( first.getValuesVec(), second.getValuesVec(), num ) ) return false; return true; } template <typename REAL> bool compareMatrixToTranspose( const SparseStorage<REAL>& first, const SparseStorage<REAL>& second, const Num<REAL>& num ) { const SparseStorage<REAL> transpose = first.getTranspose(); bool result = compareMatrices( second, transpose, num ); return result; } template <typename REAL> bool compareMatrixToTranspose( const ConstraintMatrix<REAL>& constarint_matrix, const Num<REAL>& num ) { const SparseStorage<REAL>& matrix = constarint_matrix.getConstraintMatrix(); const SparseStorage<REAL>& transpose = constarint_matrix.getMatrixTranspose(); return compareMatrixToTranspose( matrix, transpose, num ); } template <typename REAL> bool compareProblems( const Problem<REAL>& first, const Problem<REAL>& second, const Num<REAL>& num ) { // ncols, nrows int nRows1 = first.getNRows(); int nRows2 = second.getNRows(); const int nCols1 = first.getNCols(); const int nCols2 = second.getNCols(); if( nRows1 != nRows2 ) return false; if( nCols1 != nCols2 ) return false; // objective const Vec<REAL>& objective1 = first.getObjective().coefficients; const Vec<REAL>& objective2 = second.getObjective().coefficients; bool result = compareVectors( objective1, objective2, num ); if( !result ) return false; // lhs, rhs result = compareColBounds( first.getLowerBounds(), second.getLowerBounds(), first.getColFlags(), second.getColFlags(), num ); if( !result ) return false; result = compareColBounds( first.getUpperBounds(), second.getUpperBounds(), first.getColFlags(), second.getColFlags(), num ); if( !result ) return false; result = compareRowBounds( first.getConstraintMatrix().getLeftHandSides(), second.getConstraintMatrix().getLeftHandSides(), first.getConstraintMatrix().getRowFlags(), second.getConstraintMatrix().getRowFlags(), num ); if( !result ) return false; // matrix rowwise result = compareMatrices( first.getConstraintMatrix().getConstraintMatrix(), second.getConstraintMatrix().getConstraintMatrix(), num ); if( !result ) return false; // matrix colwise (transpose) result = compareMatrices( first.getConstraintMatrix().getMatrixTranspose(), second.getConstraintMatrix().getMatrixTranspose(), num ); if( !result ) return false; // matrix to its own transpose result = compareMatrixToTranspose( first.getConstraintMatrix().getConstraintMatrix(), second.getConstraintMatrix().getMatrixTranspose(), num ); // objective offset if( first.getObjective().offset != second.getObjective().offset ) return false; return true; } } // namespace papilo #endif
8,982
C++
.h
223
33.434978
80
0.571232
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,935
String.hpp
lgottwald_PaPILO/src/papilo/misc/String.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_STRING_HPP_ #define _PAPILO_MISC_STRING_HPP_ #include "papilo/misc/Alloc.hpp" #include <string> namespace papilo { using String = std::basic_string<char, std::char_traits<char>, Allocator<char>>; } #endif
1,991
C++
.h
31
63.064516
80
0.419949
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,936
OptionsParser.hpp
lgottwald_PaPILO/src/papilo/misc/OptionsParser.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_OPTIONS_PARSER_HPP_ #define _PAPILO_MISC_OPTIONS_PARSER_HPP_ #include "papilo/misc/fmt.hpp" #include <boost/program_options.hpp> #include <fstream> #include <initializer_list> #include <string> #include <utility> #include <vector> namespace papilo { using namespace boost::program_options; enum class Command { kNone, kPresolve, kSolve, kPostsolve }; struct ArithmeticType { enum { kDouble = 'd', kQuad = 'q', kRational = 'r' }; }; struct OptionsInfo { Command command = Command::kNone; std::string instance_file; std::string reduced_problem_file; std::string postsolve_archive_file; std::string reduced_solution_file; std::string orig_solution_file; std::string scip_settings_file; std::string soplex_settings_file; std::string param_settings_file; std::string objective_reference; std::vector<std::string> unparsed_options; double tlim = std::numeric_limits<double>::max(); char arithmetic_type = ArithmeticType::kDouble; int nthreads; bool print_stats; bool print_params; bool is_complete; bool checkFiles() { if( !instance_file.empty() && !std::ifstream( instance_file ) ) { fmt::print( "file {} is not valid\n", instance_file ); return false; } if( command == Command::kPostsolve && !postsolve_archive_file.empty() && !std::ifstream( postsolve_archive_file ) ) { fmt::print( "file {} is not valid\n", postsolve_archive_file ); return false; } if( command == Command::kPostsolve && !reduced_solution_file.empty() && !std::ifstream( reduced_solution_file ) ) { fmt::print( "file {} is not valid\n", reduced_solution_file ); return false; } if( !scip_settings_file.empty() && !std::ifstream( scip_settings_file ) ) { fmt::print( "file {} is not valid\n", scip_settings_file ); return false; } if( !soplex_settings_file.empty() && !std::ifstream( soplex_settings_file ) ) { fmt::print( "file {} is not valid\n", soplex_settings_file ); return false; } if( !param_settings_file.empty() && !print_params && !std::ifstream( param_settings_file ) ) { fmt::print( "file {} is not valid\n", param_settings_file ); return false; } return true; } void parse( const std::string& commandString, const std::vector<std::string>& opts = std::vector<std::string>() ) { is_complete = false; if( commandString == "presolve" ) command = Command::kPresolve; else if( commandString == "solve" ) command = Command::kSolve; else if( commandString == "postsolve" ) command = Command::kPostsolve; else { fmt::print( "unknown command: {}\n", commandString ); return; } std::string arithmetic_type_message = fmt::format( "'{}' for double precision, '{}' for quad precision, and '{}' " "for exact rational arithmetic", (char)ArithmeticType::kDouble, (char)ArithmeticType::kQuad, (char)ArithmeticType::kRational ); options_description desc( fmt::format( "{} command", commandString ) ); desc.add_options()( "file,f", value( &instance_file ), "instance file" ); desc.add_options()( "arithmetic-type,a", value( &arithmetic_type )->default_value( ArithmeticType::kDouble ), arithmetic_type_message.c_str() ); desc.add_options()( "postsolve-archive,v", value( &postsolve_archive_file ), "filename for postsolve archive" ); if( command != Command::kPostsolve ) { desc.add_options()( "reduced-problem,r", value( &reduced_problem_file ), "filename for reduced problem" ); desc.add_options()( "parameter-settings,p", value( &param_settings_file ), "filename for presolve parameter settings" ); desc.add_options()( "print-params", bool_switch( &print_params )->default_value( false ), "print possible parameters presolving" ); desc.add_options()( "threads,t", value( &nthreads )->default_value( 0 ) ); } if( command != Command::kPresolve ) { desc.add_options()( "reduced-solution,u", value( &reduced_solution_file ), "filename for solution of reduced problem" ); desc.add_options()( "solution,l", value( &orig_solution_file ), "filename for solution" ); desc.add_options()( "reference-objective,o", value( &objective_reference ), "correct objective value for validation" ); } if( command == Command::kSolve ) { desc.add_options()( "scip-settings,s", value( &scip_settings_file ), "SCIP settings file" ); desc.add_options()( "soplex-settings,x", value( &soplex_settings_file ), "SoPlex settings file" ); desc.add_options()( "tlim", value( &tlim )->default_value( tlim ), "time limit for solver (including presolve time)" ); desc.add_options()( "print-stats", bool_switch( &print_stats )->default_value( false ), "print detailed solver statistics" ); } if( opts.empty() ) { fmt::print( "\n{}\n", desc ); return; } variables_map vm; parsed_options parsed = command_line_parser( opts ) .options( desc ) .allow_unregistered() .run(); store( parsed, vm ); notify( vm ); if( !checkFiles() ) return; if( arithmetic_type != ArithmeticType::kDouble && arithmetic_type != ArithmeticType::kQuad && arithmetic_type != ArithmeticType::kRational ) fmt::print( "invalid arithmetic type '{}'\nvalid options are {}\n", (char)arithmetic_type, arithmetic_type_message ); switch( command ) { case Command::kSolve: case Command::kPresolve: if( instance_file.empty() ) { fmt::print( "{} requires an instance file\n", commandString ); return; } break; case Command::kPostsolve: if( postsolve_archive_file.empty() || reduced_solution_file.empty() ) { fmt::print( "{} requires a postsolve archive and a reduced solution\n", commandString ); return; } case Command::kNone: assert( false ); } unparsed_options = collect_unrecognized( parsed.options, exclude_positional ); is_complete = true; } }; OptionsInfo parseOptions( int argc, char* argv[] ) { OptionsInfo optionsInfo; using namespace boost::program_options; using boost::none; using boost::optional; std::string usage = fmt::format( "usage:\n {} [COMMAND] [ARGUMENTS]\n", argv[0] ); // global description. // will capture the command and arguments as unrecognised options_description global{}; global.add_options()( "help,h", "produce help message" ); global.add_options()( "command", value<std::string>(), "command: {presolve, solve, postsolve}." ); global.add_options()( "args", value<std::vector<std::string>>(), "arguments for the command" ); positional_options_description pos; pos.add( "command", 1 ); pos.add( "args", -1 ); parsed_options parsed = command_line_parser( argc, argv ) .options( global ) .positional( pos ) .allow_unregistered() .run(); variables_map vm; store( parsed, vm ); if( vm.count( "help" ) || vm.empty() ) { fmt::print( "{}\n{}", usage, global ); optionsInfo.parse( "presolve" ); optionsInfo.parse( "solve" ); optionsInfo.parse( "postsolve" ); return optionsInfo; } // we branch on each command // and parse the arguments passed with the command if( vm.count( "command" ) ) { auto command = vm["command"].as<std::string>(); std::vector<std::string> opts = collect_unrecognized( parsed.options, include_positional ); opts.erase( opts.begin() ); optionsInfo.parse( command, opts ); } return optionsInfo; } } // namespace papilo #endif
10,700
C++
.h
272
30.753676
80
0.532023
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,938
Wrappers.hpp
lgottwald_PaPILO/src/papilo/misc/Wrappers.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_WRAPPERS_HPP_ #define _PAPILO_MISC_WRAPPERS_HPP_ #include "papilo/core/Postsolve.hpp" #include "papilo/core/Presolve.hpp" #include "papilo/io/MpsParser.hpp" #include "papilo/io/MpsWriter.hpp" #include "papilo/io/SolParser.hpp" #include "papilo/io/SolWriter.hpp" #include "papilo/misc/NumericalStatistics.hpp" #include "papilo/misc/OptionsParser.hpp" #include "papilo/misc/tbb.hpp" #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/lexical_cast.hpp> #include <fstream> #include <string> #include <utility> namespace papilo { enum class ResultStatus { kOk = 0, kUnbndOrInfeas, kError }; template <typename REAL> ResultStatus presolve_and_solve( const OptionsInfo& opts, std::unique_ptr<SolverFactory<REAL>> lpSolverFactory = nullptr, std::unique_ptr<SolverFactory<REAL>> mipSolverFactory = nullptr ) { double readtime = 0; Problem<REAL> problem; boost::optional<Problem<REAL>> prob; { Timer t( readtime ); prob = MpsParser<REAL>::loadProblem( opts.instance_file ); } // Check wether reading was successfull or not if( !prob ) { fmt::print( "error loading problem {}\n", opts.instance_file ); return ResultStatus::kError; } problem = *prob; fmt::print( "reading took {:.3} seconds\n", readtime ); NumericalStatistics<REAL> nstats( problem ); nstats.printStatistics(); Presolve<REAL> presolve; presolve.addDefaultPresolvers(); presolve.getPresolveOptions().threads = std::max( 0, opts.nthreads ); if( !opts.param_settings_file.empty() || !opts.unparsed_options.empty() || opts.print_params ) { ParameterSet paramSet = presolve.getParameters(); if( !opts.param_settings_file.empty() && !opts.print_params ) { std::ifstream input( opts.param_settings_file ); if( input ) { String theoptionstr; String thevaluestr; for( String line; getline( input, line ); ) { std::size_t pos = line.find_first_of( '#' ); if( pos != String::npos ) line = line.substr( 0, pos ); pos = line.find_first_of( '=' ); if( pos == String::npos ) continue; theoptionstr = line.substr( 0, pos - 1 ); thevaluestr = line.substr( pos + 1 ); boost::algorithm::trim( theoptionstr ); boost::algorithm::trim( thevaluestr ); try { paramSet.parseParameter( theoptionstr.c_str(), thevaluestr.c_str() ); fmt::print( "set {} = {}\n", theoptionstr, thevaluestr ); } catch( const std::exception& e ) { fmt::print( "parameter '{}' could not be set: {}\n", line, e.what() ); } } } else { fmt::print( "could not read parameter file '{}'\n", opts.param_settings_file ); } } if( !opts.unparsed_options.empty() ) { String theoptionstr; String thevaluestr; for( const auto& option : opts.unparsed_options ) { std::size_t pos = option.find_first_of( '=' ); if( pos != String::npos && pos > 2 ) { theoptionstr = option.substr( 2, pos - 2 ); thevaluestr = option.substr( pos + 1 ); try { paramSet.parseParameter( theoptionstr.c_str(), thevaluestr.c_str() ); fmt::print( "set {} = {}\n", theoptionstr, thevaluestr ); } catch( const std::exception& e ) { fmt::print( "parameter '{}' could not be set: {}\n", option, e.what() ); } } else { fmt::print( "parameter '{}' could not be set: value expected\n", option ); } } } if( opts.print_params ) { if( !opts.param_settings_file.empty() ) { std::ofstream outfile( opts.param_settings_file ); if( outfile ) { std::ostream_iterator<char> out_it( outfile ); paramSet.printParams( out_it ); } else { fmt::print( "could not write to parameter file '{}'\n", opts.param_settings_file ); } } else { String paramDesc; paramSet.printParams( std::back_inserter( paramDesc ) ); puts( paramDesc.c_str() ); } } } presolve.setLPSolverFactory( std::move( lpSolverFactory ) ); presolve.setMIPSolverFactory( std::move( mipSolverFactory ) ); presolve.getPresolveOptions().tlim = opts.tlim; auto result = presolve.apply( problem ); switch( result.status ) { case PresolveStatus::kInfeasible: fmt::print( "presolve detected infeasible problem\n" ); return ResultStatus::kUnbndOrInfeas; case PresolveStatus::kUnbndOrInfeas: fmt::print( "presolve detected unbounded or infeasible problem\n" ); return ResultStatus::kUnbndOrInfeas; case PresolveStatus::kUnbounded: fmt::print( "presolve detected unbounded problem\n" ); return ResultStatus::kUnbndOrInfeas; case PresolveStatus::kUnchanged: case PresolveStatus::kReduced: break; } fmt::print( "\npresolving finished after {:.3f} seconds\n\n", presolve.getStatistics().presolvetime ); double writetime = 0; if( !opts.reduced_problem_file.empty() ) { Timer t( writetime ); const auto t0 = tbb::tick_count::now(); MpsWriter<REAL>::writeProb( opts.reduced_problem_file, problem, result.postsolve.origrow_mapping, result.postsolve.origcol_mapping ); const auto t1 = tbb::tick_count::now(); fmt::print( "reduced problem written to {} in {:.3f} seconds\n\n", opts.reduced_problem_file, t.getTime() ); } if( !opts.postsolve_archive_file.empty() ) { Timer t( writetime ); std::ofstream ofs( opts.postsolve_archive_file, std::ios_base::binary ); boost::archive::binary_oarchive oa( ofs ); // write class instance to archive oa << result.postsolve; fmt::print( "postsolve archive written to {} in {:.3f} seconds\n\n", opts.postsolve_archive_file, t.getTime() ); } if( opts.command == Command::kPresolve ) return ResultStatus::kOk; double solvetime = 0; { Timer t( solvetime ); std::unique_ptr<SolverInterface<REAL>> solver; if( result.postsolve.getOriginalProblem().getNumIntegralCols() == 0 && presolve.getLPSolverFactory() ) solver = presolve.getLPSolverFactory()->newSolver( presolve.getVerbosityLevel() ); else if( presolve.getMIPSolverFactory() ) solver = presolve.getMIPSolverFactory()->newSolver( presolve.getVerbosityLevel() ); else { fmt::print( "no solver available for solving\n" ); return ResultStatus::kError; } solver->setUp( problem, result.postsolve.origrow_mapping, result.postsolve.origcol_mapping ); if( opts.tlim != std::numeric_limits<double>::max() ) { double tlim = opts.tlim - presolve.getStatistics().presolvetime - writetime; if( tlim <= 0 ) { fmt::print( "time limit reached in presolving\n" ); return ResultStatus::kOk; } solver->setTimeLimit( tlim ); } solver->solve(); SolverStatus status = solver->getStatus(); if( opts.print_stats ) solver->printDetails(); Solution<REAL> solution; solution.type = SolutionType::kPrimal; if( result.postsolve.getOriginalProblem().getNumIntegralCols() == 0 ) solution.type = SolutionType::kPrimalDual; if( ( status == SolverStatus::kOptimal || status == SolverStatus::kInterrupted ) && solver->getSolution( solution ) ) postsolve( result.postsolve, solution, opts.objective_reference, opts.orig_solution_file ); } fmt::print( "\nsolving finished after {:.3f} seconds\n", presolve.getStatistics().presolvetime + solvetime + writetime ); return ResultStatus::kOk; } template <typename REAL> void postsolve( Postsolve<REAL>& postsolve, const Solution<REAL>& reduced_sol, const std::string& objective_reference = "", const std::string& solution_output = "" ) { Solution<REAL> original_sol; auto t0 = tbb::tick_count::now(); PostsolveStatus status = postsolve.undo( reduced_sol, original_sol ); auto t1 = tbb::tick_count::now(); fmt::print( "\npostsolve finished after {:.3f} seconds\n", ( t1 - t0 ).seconds() ); const Problem<REAL>& origprob = postsolve.getOriginalProblem(); REAL origobj = origprob.computeSolObjective( original_sol.primal ); REAL boundviol; REAL intviol; REAL rowviol; bool origfeas = origprob.computeSolViolations( postsolve.getNum(), original_sol.primal, boundviol, rowviol, intviol ); fmt::print( "feasible: {}\nobjective value: {:.15}\n", origfeas, double( origobj ) ); fmt::print( "\nviolations:\n" ); fmt::print( " bounds: {:.15}\n", double( boundviol ) ); fmt::print( " constraints: {:.15}\n", double( rowviol ) ); fmt::print( " integrality: {:.15}\n\n", double( intviol ) ); if( !solution_output.empty() ) { auto t0 = tbb::tick_count::now(); SolWriter<REAL>::writeSol( solution_output, original_sol.primal, origprob.getObjective().coefficients, origobj, origprob.getVariableNames() ); auto t1 = tbb::tick_count::now(); fmt::print( "solution written to file {} in {:.3} seconds\n", solution_output, ( t1 - t0 ).seconds() ); } if( !objective_reference.empty() ) { if( origfeas && postsolve.num.isFeasEq( boost::lexical_cast<double>( objective_reference ), origobj ) ) fmt::print( "validation: SUCCESS\n" ); else fmt::print( "validation: FAILURE\n" ); } } template <typename REAL> void postsolve( const OptionsInfo& opts ) { Postsolve<REAL> ps; std::ifstream inArchiveFile( opts.postsolve_archive_file, std::ios_base::binary ); boost::archive::binary_iarchive inputArchive( inArchiveFile ); inputArchive >> ps; inArchiveFile.close(); SolParser<REAL> parser; std::ifstream solFile( opts.reduced_solution_file ); Solution<REAL> reduced_solution = parser.read( solFile, ps.origcol_mapping, ps.getOriginalProblem().getVariableNames() ); solFile.close(); postsolve( ps, reduced_solution, opts.objective_reference, opts.orig_solution_file ); } } // namespace papilo #endif
13,192
C++
.h
328
31.612805
79
0.556007
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,939
Vec.hpp
lgottwald_PaPILO/src/papilo/misc/Vec.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_VEC_HPP_ #define _PAPILO_MISC_VEC_HPP_ #include "papilo/misc/Alloc.hpp" #include <boost/container/small_vector.hpp> #include <vector> namespace papilo { template <typename T> using Vec = std::vector<T, Allocator<T>>; template <typename T, int N> using SmallVec = boost::container::small_vector<T, N, Allocator<T>>; } // namespace papilo #endif
2,130
C++
.h
35
59.714286
79
0.441148
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,940
fmt.hpp
lgottwald_PaPILO/src/papilo/misc/fmt.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_FMT_HPP_ #define _PAPILO_MISC_FMT_HPP_ #ifndef FMT_HEADER_ONLY #define FMT_HEADER_ONLY #endif /* if those macros are not defined and fmt includes windows.h * then many macros are defined that can interfere with standard C++ code */ #ifndef NOMINMAX #define NOMINMAX #define PAPILO_DEFINED_NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define PAPILO_DEFINED_WIN32_LEAN_AND_MEAN #endif #ifndef NOGDI #define NOGDI #define PAPILO_DEFINED_NOGDI #endif #include "fmt/format.h" #include "fmt/ostream.h" #ifdef PAPILO_DEFINED_NOGDI #undef NOGDI #undef PAPILO_DEFINED_NOGDI #endif #ifdef PAPILO_DEFINED_NOMINMAX #undef NOMINMAX #undef PAPILO_DEFINED_NOMINMAX #endif #ifdef PAPILO_DEFINED_WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #undef PAPILO_DEFINED_WIN32_LEAN_AND_MEAN #endif #endif
2,602
C++
.h
57
44.45614
79
0.514984
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,941
Signature.hpp
lgottwald_PaPILO/src/papilo/misc/Signature.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_SIGNATURE_HPP_ #define _PAPILO_MISC_SIGNATURE_HPP_ #include "papilo/misc/Hash.hpp" #include <cmath> #include <cstdint> #include <type_traits> namespace papilo { template <typename T> class Signature { public: Signature() : state( 0 ) {} template <typename U> void add( U elem ) { state |= 1 << ( ( uint32_t( elem ) * HashHelpers<uint32_t>::fibonacci_muliplier() ) >> ( 32 - static_cast<int>( std::log2( 8 * sizeof( T ) ) ) ) ); } // template <typename U> // void // add( U elem ) //{ // state |= 1 << ( uint32_t( elem ) % ( sizeof( T ) * 8 ) ); //} bool isSubset( Signature other ) { return ( state & ~other.state ) == 0; } bool isSuperset( Signature other ) { return ( other.state & ~state ) == 0; } bool isEqual( Signature other ) { return state == other.state; } private: T state; }; using Signature32 = Signature<uint32_t>; using Signature64 = Signature<uint64_t>; } // namespace papilo #endif
2,841
C++
.h
72
36.236111
79
0.453919
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,942
Flags.hpp
lgottwald_PaPILO/src/papilo/misc/Flags.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_FLAGS_HPP_ #define _PAPILO_MISC_FLAGS_HPP_ #include <cstdint> #include <type_traits> namespace papilo { template <typename BaseType> class Flags { public: Flags( BaseType t ) : state( static_cast<UnderlyingType>( t ) ) {} Flags() : state( 0 ) {} template <typename... Args> void set( Args... flags ) { state |= joinFlags( flags... ); } void clear() { state = 0; } template <typename... Args> void unset( Args... flags ) { state &= ~joinFlags( flags... ); } template <typename... Args> bool test( Args... flags ) const { return state & joinFlags( flags... ); } template <typename... Args> bool equal( Args... flags ) const { return state == joinFlags( flags... ); } template <typename Archive> void serialize( Archive& ar, const unsigned int version ) { ar& state; } private: using UnderlyingType = typename std::underlying_type<BaseType>::type; static UnderlyingType joinFlags( BaseType f1 ) { return static_cast<UnderlyingType>( f1 ); } template <typename... Args> static UnderlyingType joinFlags( BaseType f1, Args... other ) { return static_cast<UnderlyingType>( f1 ) | joinFlags( other... ); } UnderlyingType state; }; } // namespace papilo #endif
3,126
C++
.h
86
33.104651
79
0.48528
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,943
compress_vector.hpp
lgottwald_PaPILO/src/papilo/misc/compress_vector.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_COMPRESS_VECTOR_HPP_ #define _PAPILO_MISC_COMPRESS_VECTOR_HPP_ #include "papilo/misc/Vec.hpp" #include <cassert> namespace papilo { /// helper function to compress a vector-like container using the given mapping template <typename VEC> void compress_vector( const Vec<int>& mapping, VEC& vec ) { assert( vec.size() == mapping.size() ); int newSize = 0; for( int i = 0; i != static_cast<int>( vec.size() ); ++i ) { assert( mapping[i] <= i ); if( mapping[i] != -1 ) { vec[mapping[i]] = vec[i]; newSize++; } } vec.resize( newSize ); } /// helper function to compress a vector-like container of indicies using the /// given mapping template <typename VEC> void compress_index_vector( const Vec<int>& mapping, VEC& vec ) { int offset = 0; for( std::size_t i = 0; i < vec.size(); ++i ) { int newindex = mapping[vec[i]]; if( newindex != -1 ) vec[i - offset] = newindex; else ++offset; } vec.resize( vec.size() - offset ); } } // namespace papilo #endif
2,847
C++
.h
65
40.953846
79
0.469167
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,944
StableSum.hpp
lgottwald_PaPILO/src/papilo/misc/StableSum.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_STABLE_SUM_HPP_ #define _PAPILO_MISC_STABLE_SUM_HPP_ #include "papilo/misc/Num.hpp" namespace papilo { template <typename REAL, bool isfp = num_traits<REAL>::is_floating_point> class StableSum; template <typename REAL> class StableSum<REAL, true> { REAL sum = 0; REAL c = 0; public: StableSum() = default; StableSum( const REAL& init ) : sum( init ), c( 0 ) {} void add( const REAL& input ) { REAL t = sum + input; REAL z = t - sum; REAL y = ( sum - ( t - z ) ) + ( input - z ); c += y; sum = t; } REAL get() const { return sum + c; } }; template <typename REAL> class StableSum<REAL, false> { REAL sum = 0; public: StableSum() = default; StableSum( const REAL& init ) : sum( init ) {} void add( const REAL& input ) { sum += input; } REAL get() const { return sum; } }; } // namespace papilo #endif
2,714
C++
.h
72
34.833333
79
0.451466
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,945
KktCheckHelper.hpp
lgottwald_PaPILO/src/papilo/misc/KktCheckHelper.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_KKT_CHECK_HELPER_HPP_ #define _PAPILO_MISC_KKT_CHECK_HELPER_HPP_ #include <iostream> #include "papilo/core/Problem.hpp" namespace papilo { template <typename REAL> void addRow( Problem<REAL>& problem, const int row, const int length, const REAL* values, const int* coeffs, const REAL lhs, const REAL rhs, const bool lb_inf, const bool ub_inf ) { // Assuming problem is expanded and row will be added at the preacllocated // space. // Modify lhs, rhs. // Modify rowFlags and colFlags. // Modify matrix. } // todo: template <typename REAL> void addColToProblem() { } } // namespace papilo #endif
2,416
C++
.h
48
48.479167
79
0.46989
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,946
KktChecker.hpp
lgottwald_PaPILO/src/papilo/misc/KktChecker.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_KKT_CHECKER_HPP_ #define _PAPILO_MISC_KKT_CHECKER_HPP_ #include <iostream> #include "papilo/core/Problem.hpp" #include "papilo/core/RowFlags.hpp" #include "papilo/core/Solution.hpp" #include "papilo/core/SparseStorage.hpp" #include "papilo/io/Message.hpp" #include "papilo/misc/KktCheckHelper.hpp" #include "papilo/misc/VectorUtils.hpp" #include "papilo/misc/fmt.hpp" namespace papilo { enum kkt_status { OK, Fail_Length, Fail_Primal_Bound, Fail_Primal_Feasibility, Fail_Dual_Feasibility, Fail_Complementary_Slackness, Fail_Stationarity_Lagrangian }; enum CheckLevel { No_check, Check, Primal_feasibility_only, Solver_and_primal_feas, // expects dual values from solver Postsolved_problem_full, // expects dual values from solver After_each_postsolve_step // expects dual values from solver }; /// class to hold all the data needed for the checks. The other class /// KktChecker only holds copies of the original and reduced problem data template <typename REAL> class KktState { private: // problem and solution data. rowValues is not a reference because it is // calculated internally here. The other three point to the corresponding // values in postsolve const Problem<REAL>& problem; const Vec<REAL>& colValues; const Vec<REAL>& colDuals; const Vec<REAL>& rowDuals; Vec<REAL> rowValues; const Vec<uint8_t>& solSetCol; const Vec<uint8_t>& solSetRow; // references to problem, for easier checking const SparseStorage<REAL>& matrixRW; const Objective<REAL>& objective; const Vec<REAL>& rowLower; const Vec<REAL>& rowUpper; const Vec<REAL>& colLower; const Vec<REAL>& colUpper; // zero tolerance todo set on init REAL tol = 10e-8; public: KktState( CheckLevel checker_level, const Problem<REAL>& prob, const Solution<REAL>& solution, const Vec<uint8_t>& solSetColumns, const Vec<uint8_t>& solSetRows ) : problem( prob ), colValues( solution.primal ), colDuals( solution.col_dual ), rowDuals( solution.row_dual ), solSetCol( solSetColumns ), solSetRow( solSetRows ), matrixRW( problem.getConstraintMatrix().getConstraintMatrix() ), objective( problem.getObjective() ), rowLower( problem.getConstraintMatrix().getLeftHandSides() ), rowUpper( problem.getConstraintMatrix().getRightHandSides() ), colLower( problem.getVariableDomains().lower_bounds ), colUpper( problem.getVariableDomains().upper_bounds ), level( checker_level ) { const int nRows = problem.getNRows(); const int nCols = problem.getNCols(); // We can have a problem with no rows and columns. if( nRows == 0 && nCols == 0 ) return; assert( rowLower.size() == nRows ); assert( rowUpper.size() == nRows ); assert( colLower.size() == nCols ); assert( colLower.size() == nCols ); assert( solSetCol.size() == colValues.size() ); assert( solSetCol.size() == colDuals.size() || 0 == colDuals.size() ); assert( solSetRow.size() == rowDuals.size() || 0 == rowDuals.size() ); assert( solSetRow.size() == rowValues.size() || 0 == rowValues.size() ); } KktState( CheckLevel checker_level, const Problem<REAL>& prob, const Solution<REAL>& solution, const Vec<uint8_t>& solSetColumns, const Vec<uint8_t>& solSetRows, const Vec<REAL>& rowLower_, const Vec<REAL>& rowUpper_, const Vec<REAL>& colLower_, const Vec<REAL>& colUpper_ ) : problem( prob ), colValues( solution.primal ), colDuals( solution.col_dual ), rowDuals( solution.row_dual ), solSetCol( solSetColumns ), solSetRow( solSetRows ), matrixRW( problem.getConstraintMatrix().getConstraintMatrix() ), objective( problem.getObjective() ), rowLower( rowLower_ ), rowUpper( rowUpper_ ), colLower( colLower_ ), colUpper( colUpper_ ), level( checker_level ) { const int nRows = problem.getNRows(); const int nCols = problem.getNCols(); // We can have a problem with no rows and columns. if( nRows == 0 && nCols == 0 ) return; assert( solSetCol.size() == colValues.size() ); assert( solSetCol.size() == colDuals.size() || 0 == colDuals.size() ); assert( solSetRow.size() == rowDuals.size() || 0 == rowDuals.size() ); assert( solSetRow.size() == rowValues.size() || 0 == rowValues.size() ); } int getCurrentNRows() { return std::count_if( solSetRow.begin(), solSetRow.end(), []( uint8_t isset ) { return isset; } ); } int getCurrentNCols() { return std::count_if( solSetCol.begin(), solSetCol.end(), []( uint8_t isset ) { return isset; } ); } kkt_status checkPrimalBounds() { kkt_status status = kkt_status::OK; int reduced_index = 0; for( unsigned int col = 0; col < solSetCol.size(); col++ ) { if( !solSetCol[col] ) continue; if( !colLBInf( problem, reduced_index ) && colLower[col] - colValues[col] > tol ) { message.info( "Column {:<3} violates lower column bound.\n", col ); status = kkt_status::Fail_Primal_Bound; } if( !colUBInf( problem, reduced_index ) && colValues[col] - colUpper[col] > tol ) { message.info( "Column {:<3} violates upper column bound.\n", col ); status = kkt_status::Fail_Primal_Bound; } reduced_index++; } return status; } // called when dual values are being checked too kkt_status checkLength() { const int nCols = solSetCol.size(); if( colLower.size() != nCols || colUpper.size() != nCols || colValues.size() != nCols || colDuals.size() != nCols ) return kkt_status::Fail_Length; const int nRows = solSetRow.size(); if( rowLower.size() != nRows || rowUpper.size() != nRows || rowValues.size() != nRows || rowDuals.size() != nRows ) return kkt_status::Fail_Length; return kkt_status::OK; } // performs the check with respect to the (postsolved) reduced problem. // For the check of primal feasibility of the original problem see // CheckPrimalFeasibilityOriginal() kkt_status checkPrimalFeasibility() { kkt_status status = checkPrimalBounds(); if( status != kkt_status::OK ) return status; int reduced_index = 0; for( int row = 0; row < solSetRow.size(); row++ ) { if( !solSetRow[row] ) continue; if( !rowLHSInf( problem, reduced_index ) && rowLower[row] - rowValues[row] > tol ) { message.info( "Row {:<3} violates row bounds.\n", row ); status = kkt_status::Fail_Primal_Feasibility; } if( !rowRHSInf( problem, reduced_index ) && rowValues[row] - rowUpper[row] > tol ) { message.info( "Row {:<3} violates row bounds.\n", row ); status = kkt_status::Fail_Primal_Feasibility; } reduced_index++; } return status; } kkt_status checkDualFeasibility() { const Vec<REAL>& colLower = problem.getVariableDomains().lower_bounds; const Vec<REAL>& colUpper = problem.getVariableDomains().upper_bounds; // check values of z_j are dual feasible int reduced_index = 0; for( int col = 0; col < solSetCol.size(); col++ ) { if( !solSetCol[col] ) continue; // no lower or upper bound on column if( colLBInf( problem, reduced_index ) && colUBInf( problem, reduced_index ) ) { if( abs( colDuals[col] ) > tol ) return kkt_status::Fail_Dual_Feasibility; } // column at lower bound: x=l and l<u else if( abs( colValues[col] - colLower[col] ) < tol && colLower[col] < colUpper[col] ) { if( colDuals[col] < 0 && abs( colDuals[col] ) > tol ) return kkt_status::Fail_Dual_Feasibility; } // column at upper bound: x=u and l<u else if( abs( colValues[col] - colUpper[col] ) < tol && colLower[col] < colUpper[col] ) { if( colDuals[col] > tol ) return kkt_status::Fail_Dual_Feasibility; } reduced_index++; } // check values of y_i are dual feasible const Vec<REAL>& rowLower = problem.getConstraintMatrix().getLeftHandSides(); const Vec<REAL>& rowUpper = problem.getConstraintMatrix().getRightHandSides(); std::vector<int> orig_col_index( matrixRW.getNCols(), 0 ); int reduced_col_index = 0; for( int col = 0; col < solSetCol.size(); col++ ) { if( !solSetCol[col] ) continue; orig_col_index[reduced_col_index] = col; reduced_col_index++; } assert( matrixRW.getNCols() == reduced_col_index ); for( int row = 0; row < solSetRow.size(); row++ ) { if( !solSetRow[row] ) continue; // L = Ax = U can be any sign if( abs( rowLower[row] - rowValues[row] ) < tol && abs( rowUpper[row] - rowValues[row] ) < tol ) continue; // L = Ax < U else if( abs( rowLower[row] - rowValues[row] ) < tol && rowValues[row] < rowUpper[row] ) { if( rowDuals[row] < -tol ) return kkt_status::Fail_Dual_Feasibility; } // L < Ax = U else if( rowLower[row] < rowValues[row] && abs( rowValues[row] - rowUpper[row] ) < tol ) { if( rowDuals[row] > tol ) return kkt_status::Fail_Dual_Feasibility; } // L < Ax < U else if( rowLower[row] < ( rowValues[row] + tol ) && rowValues[row] < ( rowUpper[row] + tol ) ) { if( abs( rowDuals[row] ) > tol ) return kkt_status::Fail_Dual_Feasibility; } } return kkt_status::OK; } kkt_status checkComplementarySlackness() { int reduced_index = 0; for( int col = 0; col < solSetCol.size(); col++ ) { if( !solSetCol[col] ) continue; if( !colLBInf( problem, reduced_index ) ) if( abs( ( colValues[col] - colLower[col] ) * ( colDuals[col] ) ) > tol && colValues[col] != colUpper[col] && abs( colDuals[col] ) > tol ) return kkt_status::Fail_Complementary_Slackness; if( !colUBInf( problem, reduced_index ) ) if( abs( ( colUpper[col] - colValues[col] ) * ( colDuals[col] ) ) > tol && colValues[col] != colLower[col] && abs( colDuals[col] ) > tol ) return kkt_status::Fail_Complementary_Slackness; } reduced_index++; return kkt_status::OK; } kkt_status checkStOfLagrangian() { // A'y + z = c REAL lagrV; // getMatrixTranspose() doesn't work because sometimes the matrix of the // reduced problem has not been transposed previously. Edit when KKT // check is done at each step, rather than just the start and the end of // postsolve. const SparseStorage<REAL>& matrixCW = problem.getConstraintMatrix().getMatrixTranspose(); // const SparseStorage<REAL>& matrixCW = // problem.getConstraintMatrix().getConstraintMatrix().getTranspose(); std::vector<int> orig_row_index( matrixCW.getNCols(), 0 ); int reduced_row_index = 0; for( int row = 0; row < solSetRow.size(); row++ ) { if( !solSetRow[row] ) continue; orig_row_index[reduced_row_index] = row; reduced_row_index++; } // Below is used getNCols() because matrixCW is the transpose. assert( matrixCW.getNCols() == reduced_row_index ); int reduced_index = 0; for( int col = 0; col < solSetCol.size(); col++ ) { if( !solSetCol[col] ) continue; lagrV = 0; auto index_range = matrixCW.getRowRanges()[reduced_index]; for( int k = index_range.start; k < index_range.end; k++ ) { int row = matrixCW.getColumns()[k]; lagrV += rowDuals[orig_row_index[row]] * matrixCW.getValues()[k]; } lagrV = lagrV + colDuals[col] - objective.coefficients[reduced_index]; if( abs( lagrV ) > tol ) return kkt_status::Fail_Stationarity_Lagrangian; reduced_index++; } return kkt_status::OK; } void getRowValues() { const int nRows = problem.getNRows(); const int nCols = problem.getNCols(); rowValues.resize( solSetRow.size() ); REAL rowValue; int reduced_row_index = 0; auto values = matrixRW.getValues(); std::vector<int> orig_col_index; orig_col_index.reserve( nCols ); for( int i = 0; i < solSetCol.size(); i++ ) if( solSetCol[i] ) orig_col_index.push_back( i ); assert( orig_col_index.size() == nCols ); for( int i = 0; i < solSetRow.size(); i++ ) { if( !solSetRow[i] ) continue; rowValue = 0; auto index_range = matrixRW.getRowRanges()[reduced_row_index]; for( int j = index_range.start; j < index_range.end; j++ ) { int col = matrixRW.getColumns()[j]; assert( col >= 0 ); assert( col < (int)nCols ); // col is index of the column in reduced problem and colValues is // expanded. rowValue += values[j] * colValues[orig_col_index[col]]; } rowValues[i] = rowValue; reduced_row_index++; } } Message message; CheckLevel level; }; enum class ProblemType { kOriginal, kReduced, kPostsolved }; template <typename REAL, CheckLevel CHECK_LEVEL> class KktChecker; template <typename REAL> class KktChecker<REAL, CheckLevel::No_check> { public: CheckLevel level = CheckLevel::No_check; using State = int; State initState( ProblemType type, Solution<REAL>& solution, CheckLevel checker_level ) { return 0; } State initState( ProblemType type, Solution<REAL>& solution, const Vec<uint8_t>& solSetColumns, const Vec<uint8_t>& solSetRows, CheckLevel checker_level ) { return 0; } State initState( ProblemType type, Solution<REAL>& solution, const Vec<int>& origcol_map, const Vec<int>& origrow_map, CheckLevel checker_level ) { return 0; } KktChecker() {} KktChecker( Problem<REAL> prob ) {} void checkSolution( State& ) const { } void checkIntermediate( State& ) const { } kkt_status checkKKT( State& ) const { return kkt_status::OK; } void setLevel( State& state, CheckLevel type_of_check ) const { } void setOriginalProblem( const Problem<REAL>& ) const { } void setReducedProblem( const Problem<REAL>& ) const { } void addRowToProblem( const int row, const int length, const REAL* values, const int* coeffs, const REAL lhs, const REAL rhs, const bool lb_inf, const bool ub_inf ) { } }; /// class for checking the optimality conditions of the problem during and /// at end of postsolve. Only contains the original and reduced /// problem. Any other data required for the check that comes from postsolve is /// contained in the KktState class template <typename REAL> class KktChecker<REAL, CheckLevel::Check> { private: Vec<REAL> rowLower_reduced; Vec<REAL> rowUpper_reduced; Vec<REAL> colLower_reduced; Vec<REAL> colUpper_reduced; Num<REAL> num; public: CheckLevel level = CheckLevel::Primal_feasibility_only; using State = KktState<REAL>; State initState( ProblemType type, Solution<REAL>& solution, CheckLevel checker_level ) { int ncols = original_problem.getNCols(); int nrows = original_problem.getNRows(); Vec<uint8_t> solSetColumns( ncols, 1 ); Vec<uint8_t> solSetRows( nrows, 1 ); return initState( type, solution, solSetColumns, solSetRows, checker_level ); } State initState( ProblemType type, Solution<REAL>& solution, const Vec<int>& origcol_map, const Vec<int>& origrow_map, CheckLevel checker_level ) { int ncols = original_problem.getNCols(); int nrows = original_problem.getNRows(); Vec<uint8_t> solSetColumns( ncols, 0 ); Vec<uint8_t> solSetRows( nrows, 0 ); for( int k = 0; k < origcol_map.size(); ++k ) { int origcol = origcol_map[k]; solSetCol[origcol] = true; } for( int k = 0; k < origrow_map.size(); ++k ) { int origrow = origrow_map[k]; solSetRow[origrow] = true; } return initState( type, solution, solSetCol, solSetRow, checker_level ); } State initState( ProblemType type, Solution<REAL>& solution, const Vec<uint8_t>& solSetColumns, const Vec<uint8_t>& solSetRows, CheckLevel checker_level ) { level = checker_level; // todo: make sure constraint matrix transpose is valid since // ...getMatrixTranspose() is used for checking KKT in KktState. if( type == ProblemType::kPostsolved ) { compareMatrixToTranspose( problem.getConstraintMatrix(), num ); message.info( "Initializing check of postsolved solution\n" ); return State( level, problem, solution, solSetColumns, solSetRows ); } if( type == ProblemType::kOriginal ) { // compares transposes too so no need to call other checks. if( level == CheckLevel::After_each_postsolve_step ) { bool problems_are_same = compareProblems( original_problem, problem, num ); assert( problems_are_same ); } message.info( "Initializing check of original solution\n" ); // todo: assert solSetRows and SolSetColumns are all set. return State( level, original_problem, solution, solSetColumns, solSetRows ); } // matrix type is ProblemType::kReduced. compareMatrixToTranspose( reduced_problem.getConstraintMatrix(), num ); // if problem type is REDUCED expand row / column bound vectors since // original_solution is already padded. const int nRows = reduced_problem.getNRows(); const int nCols = reduced_problem.getNCols(); if( solSetRows.size() > nRows ) { const Vec<REAL> tmp_upper = reduced_problem.getConstraintMatrix().getRightHandSides(); const Vec<REAL> tmp_lower = reduced_problem.getConstraintMatrix().getLeftHandSides(); assert( tmp_upper.size() == nRows ); assert( tmp_lower.size() == nRows ); rowUpper_reduced.clear(); rowLower_reduced.clear(); rowUpper_reduced.resize( solSetRows.size(), 0 ); rowLower_reduced.resize( solSetRows.size(), 0 ); int index = 0; for( int k = 0; k < solSetRows.size(); ++k ) { if( solSetRows[k] ) { rowUpper_reduced[k] = tmp_upper[index]; rowLower_reduced[k] = tmp_lower[index]; index++; } } } else { assert( solSetRows.size() == nRows ); rowUpper_reduced = reduced_problem.getConstraintMatrix().getRightHandSides(); rowLower_reduced = reduced_problem.getConstraintMatrix().getLeftHandSides(); } if( solSetColumns.size() > nCols ) { Vec<REAL> tmp_upper = reduced_problem.getVariableDomains().upper_bounds; Vec<REAL> tmp_lower = reduced_problem.getVariableDomains().lower_bounds; assert( tmp_upper.size() == nCols ); assert( tmp_lower.size() == nCols ); colUpper_reduced.clear(); colLower_reduced.clear(); colUpper_reduced.resize( solSetColumns.size(), 0 ); colLower_reduced.resize( solSetColumns.size(), 0 ); int index = 0; for( int k = 0; k < solSetColumns.size(); ++k ) { if( solSetColumns[k] ) { colUpper_reduced[k] = tmp_upper[index]; colLower_reduced[k] = tmp_lower[index]; index++; } } } else { assert( solSetColumns.size() == nCols ); colUpper_reduced = reduced_problem.getVariableDomains().upper_bounds; colLower_reduced = reduced_problem.getVariableDomains().lower_bounds; } message.info( "Initializing check of reduced solution\n" ); return State( level, reduced_problem, solution, solSetColumns, solSetRows, rowLower_reduced, rowUpper_reduced, colLower_reduced, colUpper_reduced ); } void setLevel( CheckLevel type_of_check ) { level = type_of_check; } void checkSolution( State& state ) const { state.getRowValues(); kkt_status status = kkt_status::OK; if( state.level == CheckLevel::Primal_feasibility_only ) status = state.checkPrimalFeasibility(); else status = checkKKT( state ); if( status ) { message.info( "Check solution: FAIL, status: " ); message.info( std::to_string( status ) ); message.info( "\n" ); } else { message.info( "Check solution: OK\n" ); } } void checkIntermediate( State& state ) const { if( state.level != CheckLevel::After_each_postsolve_step ) return; kkt_status status = checkKKT( state ); if( status ) { message.info( "KKT intermediate FAIL, status: " ); message.info( std::to_string( status ) ); message.info( "\n" ); } return; } kkt_status checkKKT( State& state ) const { kkt_status status; kkt_status return_status = kkt_status::OK; status = state.checkLength(); if( status != kkt_status::OK ) { message.info( "Solution vector length check failed.\n" ); return status; } state.getRowValues(); status = state.checkPrimalFeasibility(); if( status != kkt_status::OK ) { return_status = status; message.info( "Primal feasibility failed.\n" ); } status = state.checkDualFeasibility(); if( status != kkt_status::OK ) { return_status = status; message.info( "Dual feasibility check failed.\n" ); } status = state.checkComplementarySlackness(); if( status != kkt_status::OK ) { return_status = status; message.info( "Complementary slackness check failed.\n" ); } status = state.checkStOfLagrangian(); if( status != kkt_status::OK ) { return_status = status; message.info( "Stationarity of Lagrangian check failed.\n" ); } return return_status; } void setOriginalProblem( const Problem<REAL>& prob ) { original_problem = prob; }; void setReducedProblem( const Problem<REAL>& problem ) { reduced_problem = problem; // todo: // assert original_problem is set // allocate memory for reduced. for now for each row / col take // max of row/col in original and reduced problem. } void addRowToProblem( const int row, const int length, const REAL* values, const int* coeffs, const REAL lhs, const REAL rhs, const bool lb_inf, const bool ub_inf ) { addRow( problem, row, length, values, coeffs, lhs, rhs, lb_inf, ub_inf ); } Message message; private: // set to false if kkt do not hold bool kktHold; Problem<REAL> original_problem; Problem<REAL> reduced_problem; Problem<REAL> problem; Vec<uint8_t> solSetRow; Vec<uint8_t> solSetCol; }; template <typename REAL> bool rowLHSInf( const Problem<REAL>& problem, const int row ) { return problem.getRowFlags()[row].test( RowFlag::kLhsInf ); } template <typename REAL> bool rowRHSInf( const Problem<REAL>& problem, const int row ) { return problem.getRowFlags()[row].test( RowFlag::kRhsInf ); } template <typename REAL> bool colLBInf( const Problem<REAL>& problem, const int col ) { return problem.getColFlags()[col].test( ColFlag::kLbInf ); } template <typename REAL> bool colUBInf( const Problem<REAL>& problem, const int col ) { return problem.getColFlags()[col].test( ColFlag::kUbInf ); } // for testing template <typename REAL> bool check_solution_feasibility( const Problem<REAL>& prob, Solution<REAL>& sol ) { KktChecker<REAL, CheckLevel::Check> chk( prob ); Vec<uint8_t> colsSet( prob.getNCols(), true ); Vec<uint8_t> rowsSet( prob.getNRows(), true ); auto state = chk.initState( true, sol, colsSet, rowsSet, chk.level ); kkt_status status = state.checkSolution( prob ); if( status == kkt_status::OK ) return true; return false; } } // namespace papilo #endif
27,425
C++
.h
758
28.736148
80
0.586486
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,948
tbb.hpp
lgottwald_PaPILO/src/papilo/misc/tbb.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_TBB_HPP_ #define _PAPILO_MISC_TBB_HPP_ /* if those macros are not defined and tbb includes windows.h * then many macros are defined that can interfere with standard C++ code */ #ifndef NOMINMAX #define NOMINMAX #define PAPILO_DEFINED_NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define PAPILO_DEFINED_WIN32_LEAN_AND_MEAN #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define PAPILO_DEFINED_WIN32_LEAN_AND_MEAN #endif #ifndef NOGDI #define NOGDI #define PAPILO_DEFINED_NOGDI #endif #ifdef _MSC_VER #pragma push_macro( "__TBB_NO_IMPLICIT_LINKAGE" ) #define __TBB_NO_IMPLICIT_LINKAGE 1 #endif #include "tbb/blocked_range.h" #include "tbb/combinable.h" #include "tbb/concurrent_hash_map.h" #include "tbb/concurrent_vector.h" #include "tbb/parallel_for.h" #include "tbb/parallel_invoke.h" #include "tbb/partitioner.h" #include "tbb/task_arena.h" #include "tbb/tick_count.h" #ifdef _MSC_VER #pragma pop_macro( "__TBB_NO_IMPLICIT_LINKAGE" ) #endif #ifdef PAPILO_DEFINED_NOGDI #undef NOGDI #undef PAPILO_DEFINED_NOGDI #endif #ifdef PAPILO_DEFINED_NOMINMAX #undef NOMINMAX #undef PAPILO_DEFINED_NOMINMAX #endif #ifdef PAPILO_DEFINED_WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #undef PAPILO_DEFINED_WIN32_LEAN_AND_MEAN #endif #endif
3,066
C++
.h
72
41.402778
79
0.552464
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,949
Hash.hpp
lgottwald_PaPILO/src/papilo/misc/Hash.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_HASH_HPP_ #define _PAPILO_MISC_HASH_HPP_ #include "papilo/Config.hpp" #ifndef PAPILO_USE_STANDARD_HASHMAP #include "ska/bytell_hash_map.hpp" #else #include <unordered_map> #include <unordered_set> #endif #include <cstdint> #include <type_traits> namespace papilo { template <typename T, int TWidth = sizeof( T )> struct HashHelpers; template <typename T> struct HashHelpers<T, 4> { static uint32_t fibonacci_muliplier() { return uint32_t( 0x9e3779b9 ); } static uint32_t rotate_left( uint32_t x, int n ) { return ( x << n ) | ( x >> ( 32 - n ) ); } }; template <typename T> struct HashHelpers<T, 8> { static uint64_t fibonacci_muliplier() { return uint64_t( 0x9e3779b97f4a7c15 ); } static uint64_t rotate_left( uint64_t x, int n ) { return ( x << n ) | ( x >> ( 64 - n ) ); } }; template <typename T, typename U = typename std::make_unsigned<T>::type> struct Hasher; // only add specialization for unsigned result types template <typename T> struct Hasher<T, T> { T state; Hasher( T init = 0 ) : state( init ) {} template <typename U, typename std::enable_if<std::is_integral<U>::value, int>::type = 0> void addValue( U val ) { state = ( HashHelpers<T>::rotate_left( state, 5 ) ^ T( val ) ) * HashHelpers<T>::fibonacci_muliplier(); } T getHash() const { return state; } }; #ifndef PAPILO_USE_STANDARD_HASHMAP template <typename K, typename V, typename H = std::hash<K>, typename E = std::equal_to<K>> using HashMap = ska::bytell_hash_map<K, V, H, E, Allocator<std::pair<const K, V>>>; template <typename T, typename H = std::hash<T>, typename E = std::equal_to<T>> using HashSet = ska::bytell_hash_set<T, H, E, Allocator<T>>; #else template <typename K, typename V, typename H = std::hash<K>, typename E = std::equal_to<K>> using HashMap = std::unordered_map<K, V, H, E, Allocator<std::pair<const K, V>>>; template <typename T, typename H = std::hash<T>, typename E = std::equal_to<T>> using HashSet = std::unordered_set<T, H, E, Allocator<T>>; #endif } // namespace papilo #endif
3,958
C++
.h
104
35.173077
80
0.528198
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,950
MultiPrecision.hpp
lgottwald_PaPILO/src/papilo/misc/MultiPrecision.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_MISC_MULTIPRECISION_HPP_ #define _PAPILO_MISC_MULTIPRECISION_HPP_ #include "papilo/Config.hpp" #include <boost/serialization/split_free.hpp> #ifdef PAPILO_HAVE_FLOAT128 #include <boost/multiprecision/float128.hpp> namespace papilo { using Quad = boost::multiprecision::float128; } // namespace papilo #elif defined( PAPILO_HAVE_GMP ) #include <boost/multiprecision/gmp.hpp> namespace papilo { using Quad = boost::multiprecision::number<boost::multiprecision::gmp_float<35>>; } // namespace papilo BOOST_SERIALIZATION_SPLIT_FREE( papilo::Quad ) #else #include <boost/multiprecision/cpp_bin_float.hpp> #include <boost/serialization/nvp.hpp> namespace papilo { using Quad = boost::multiprecision::cpp_bin_float_quad; } // namespace papilo #endif #ifdef PAPILO_HAVE_GMP #include <boost/multiprecision/cpp_bin_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <boost/serialization/nvp.hpp> // unfortunately the multiprecision gmp types do not provide an overload for // serialization namespace papilo { using Rational = boost::multiprecision::mpq_rational; using Float100 = boost::multiprecision::mpf_float_100; using Float500 = boost::multiprecision::mpf_float_500; using Float1000 = boost::multiprecision::mpf_float_1000; } // namespace papilo BOOST_SERIALIZATION_SPLIT_FREE( papilo::Rational ) BOOST_SERIALIZATION_SPLIT_FREE( papilo::Float100 ) BOOST_SERIALIZATION_SPLIT_FREE( papilo::Float500 ) BOOST_SERIALIZATION_SPLIT_FREE( papilo::Float1000 ) namespace boost { namespace serialization { template <class Archive> void save( Archive& ar, const papilo::Rational& num, const unsigned int version ) { boost::multiprecision::cpp_rational t( num ); ar& t; } template <class Archive> void load( Archive& ar, papilo::Rational& num, const unsigned int version ) { boost::multiprecision::cpp_rational t; ar& t; num = papilo::Rational( t ); } template <class Archive, unsigned M> void save( Archive& ar, const boost::multiprecision::number<boost::multiprecision::gmp_float<M>>& num, const unsigned int version ) { boost::multiprecision::number<boost::multiprecision::cpp_bin_float<M>> t( num ); ar& t; } template <class Archive, unsigned M> void load( Archive& ar, boost::multiprecision::number<boost::multiprecision::gmp_float<M>>& num, const unsigned int version ) { boost::multiprecision::number<boost::multiprecision::cpp_bin_float<M>> t; ar& t; num = boost::multiprecision::number<boost::multiprecision::gmp_float<M>>( t ); } } // namespace serialization } // namespace boost #else #include <boost/multiprecision/cpp_bin_float.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/serialization/nvp.hpp> namespace papilo { using Rational = boost::multiprecision::cpp_rational; using Float100 = boost::multiprecision::number<boost::multiprecision::cpp_bin_float<100>>; using Float500 = boost::multiprecision::number<boost::multiprecision::cpp_bin_float<500>>; using Float1000 = boost::multiprecision::number<boost::multiprecision::cpp_bin_float<1000>>; } // namespace papilo #endif #endif
4,893
C++
.h
124
37.556452
79
0.625763
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,951
SoplexInterface.hpp
lgottwald_PaPILO/src/papilo/interfaces/SoplexInterface.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_INTERFACES_SOPLEX_INTERFACE_HPP_ #define _PAPILO_INTERFACES_SOPLEX_INTERFACE_HPP_ #include "papilo/misc/String.hpp" #include "papilo/misc/Vec.hpp" #include <cassert> #include <stdexcept> #include <type_traits> #include "papilo/core/Problem.hpp" #include "papilo/interfaces/SolverInterface.hpp" #include "soplex.h" namespace papilo { template <typename REAL> class SoplexInterface : public SolverInterface<REAL> { private: soplex::SoPlex spx; public: void readSettings( const String& file ) override { if( !spx.loadSettingsFile( file.c_str() ) ) this->status = SolverStatus::kError; } soplex::SoPlex& getSoPlex() { return spx; } void setTimeLimit( double tlim ) override { using namespace soplex; spx.setIntParam( SoPlex::TIMER, SoPlex::TIMER_WALLCLOCK ); spx.setRealParam( SoPlex::TIMELIMIT, Real( tlim ) ); } void setUp( const Problem<REAL>& problem, const Vec<int>& row_maps, const Vec<int>& col_maps ) override { using namespace soplex; int ncols = problem.getNCols(); int nrows = problem.getNRows(); const Vec<String>& varNames = problem.getVariableNames(); const Vec<String>& consNames = problem.getConstraintNames(); const VariableDomains<REAL>& domains = problem.getVariableDomains(); const Objective<REAL>& obj = problem.getObjective(); const auto& consMatrix = problem.getConstraintMatrix(); const auto& lhs_values = consMatrix.getLeftHandSides(); const auto& rhs_values = consMatrix.getRightHandSides(); const auto& rflags = problem.getRowFlags(); /* set the objective sense and offset */ spx.setIntParam( SoPlex::OBJSENSE, SoPlex::OBJSENSE_MINIMIZE ); if( obj.offset != 0 ) spx.setRealParam( SoPlex::OBJ_OFFSET, Real( obj.offset ) ); LPRowSet rows( nrows ); LPColSet cols( ncols ); DSVector vec( ncols ); for( int i = 0; i < nrows; ++i ) { Real lhs = rflags[i].test( RowFlag::kLhsInf ) ? -infinity : Real( lhs_values[i] ); Real rhs = rflags[i].test( RowFlag::kRhsInf ) ? infinity : Real( rhs_values[i] ); rows.add( lhs, vec, rhs ); } spx.addRowsReal( rows ); for( int i = 0; i < ncols; ++i ) { assert( !domains.flags[i].test( ColFlag::kInactive ) ); Real lb = domains.flags[i].test( ColFlag::kLbInf ) ? -infinity : Real( domains.lower_bounds[i] ); Real ub = domains.flags[i].test( ColFlag::kUbInf ) ? infinity : Real( domains.upper_bounds[i] ); auto colvec = consMatrix.getColumnCoefficients( i ); int collen = colvec.getLength(); const int* colrows = colvec.getIndices(); const REAL* colvals = colvec.getValues(); vec.clear(); if( std::is_same<REAL, Real>::value ) { vec.add( collen, colrows, (const Real*)colvals ); } else { for( int i = 0; i != collen; ++i ) vec.add( colrows[i], Real( colvals[i] ) ); } cols.add( Real( obj.coefficients[i] ), lb, vec, ub ); } spx.addColsReal( cols ); } void setUp( const Problem<REAL>& problem, const Vec<int>& row_maps, const Vec<int>& col_maps, const Components& components, const ComponentInfo& component ) override { using namespace soplex; int ncols = problem.getNCols(); int nrows = problem.getNRows(); const Vec<String>& varNames = problem.getVariableNames(); const Vec<String>& consNames = problem.getConstraintNames(); const VariableDomains<REAL>& domains = problem.getVariableDomains(); const Objective<REAL>& obj = problem.getObjective(); const auto& consMatrix = problem.getConstraintMatrix(); const auto& lhs_values = consMatrix.getLeftHandSides(); const auto& rhs_values = consMatrix.getRightHandSides(); const auto& rflags = problem.getRowFlags(); const int* rowset = components.getComponentsRows( component.componentid ); const int* colset = components.getComponentsCols( component.componentid ); int numrows = components.getComponentsNumRows( component.componentid ); int numcols = components.getComponentsNumCols( component.componentid ); /* set the objective sense and offset */ spx.setIntParam( SoPlex::OBJSENSE, SoPlex::OBJSENSE_MINIMIZE ); LPRowSet rows( numrows ); LPColSet cols( numcols ); DSVector vec( numcols ); for( int i = 0; i != numrows; ++i ) { int row = rowset[i]; assert( components.getRowComponentIdx( row ) == i ); Real lhs = rflags[row].test( RowFlag::kLhsInf ) ? -infinity : Real( lhs_values[row] ); Real rhs = rflags[row].test( RowFlag::kRhsInf ) ? infinity : Real( rhs_values[row] ); rows.add( lhs, vec, rhs ); } spx.addRowsReal( rows ); for( int i = 0; i != numcols; ++i ) { int col = colset[i]; assert( components.getColComponentIdx( col ) == i ); assert( !domains.flags[col].test( ColFlag::kInactive ) ); Real lb = domains.flags[col].test( ColFlag::kLbInf ) ? -infinity : Real( domains.lower_bounds[col] ); Real ub = domains.flags[col].test( ColFlag::kUbInf ) ? infinity : Real( domains.upper_bounds[col] ); auto colvec = consMatrix.getColumnCoefficients( col ); int collen = colvec.getLength(); const int* colrows = colvec.getIndices(); const REAL* colvals = colvec.getValues(); vec.clear(); for( int j = 0; j != collen; ++j ) vec.add( components.getRowComponentIdx( colrows[j] ), Real( colvals[j] ) ); cols.add( Real( obj.coefficients[col] ), lb, vec, ub ); } spx.addColsReal( cols ); } void solve() override { using namespace soplex; assert( this->status != SolverStatus::kError ); spx.setSettings( spx.settings() ); SPxSolver::Status stat = spx.optimize(); switch( stat ) { default: this->status = SolverStatus::kError; return; case SPxSolver::Status::INForUNBD: this->status = SolverStatus::kUnbndOrInfeas; return; case SPxSolver::Status::INFEASIBLE: this->status = SolverStatus::kInfeasible; return; case SPxSolver::Status::UNBOUNDED: this->status = SolverStatus::kUnbounded; return; case SPxSolver::Status::ABORT_CYCLING: this->status = SolverStatus::kInterrupted; return; case SPxSolver::Status::OPTIMAL_UNSCALED_VIOLATIONS: case SPxSolver::Status::OPTIMAL: this->status = SolverStatus::kOptimal; } } void setVerbosity( VerbosityLevel verbosity ) override { using namespace soplex; switch( verbosity ) { case VerbosityLevel::kQuiet: case VerbosityLevel::kError: spx.setIntParam( SoPlex::VERBOSITY, SoPlex::VERBOSITY_ERROR ); break; case VerbosityLevel::kWarning: spx.setIntParam( SoPlex::VERBOSITY, SoPlex::VERBOSITY_WARNING ); break; case VerbosityLevel::kInfo: spx.setIntParam( SoPlex::VERBOSITY, SoPlex::VERBOSITY_NORMAL ); break; case VerbosityLevel::kExtra: spx.setIntParam( SoPlex::VERBOSITY, SoPlex::VERBOSITY_HIGH ); } } REAL getDualBound() override { if( spx.hasPrimal() ) return spx.objValueReal(); else return -soplex::infinity; } bool getSolution( Solution<REAL>& sol ) override { Vec<soplex::Real> buffer; int numcols = spx.numColsReal(); buffer.resize( numcols ); if( !spx.getPrimalReal( buffer.data(), numcols ) ) return false; sol.primal.resize( numcols ); for( int i = 0; i != numcols; ++i ) sol.primal[i] = REAL( buffer[i] ); if( sol.type == SolutionType::kPrimal ) return true; if( !spx.getRedCostReal( buffer.data(), numcols ) ) return false; sol.col_dual.resize( numcols ); for( int i = 0; i != numcols; ++i ) sol.col_dual[i] = REAL( buffer[i] ); int numrows = spx.numRowsReal(); buffer.resize( numrows ); if( !spx.getDualReal( buffer.data(), numrows ) ) return false; sol.row_dual.resize( numrows ); for( int i = 0; i != numrows; ++i ) sol.row_dual[i] = REAL( buffer[i] ); return true; } bool getSolution( const Components& components, int component, Solution<REAL>& sol ) override { Vec<soplex::Real> buffer; int numcols = spx.numColsReal(); assert( components.getComponentsNumCols( component ) == spx.numColsReal() ); buffer.resize( numcols ); if( !spx.getPrimalReal( buffer.data(), numcols ) ) return false; const int* compcols = components.getComponentsCols( component ); for( int i = 0; i != numcols; ++i ) sol.primal[compcols[i]] = REAL( buffer[i] ); if( sol.type == SolutionType::kPrimal ) return true; if( !spx.getRedCostReal( buffer.data(), numcols ) ) return false; for( int i = 0; i != numcols; ++i ) sol.col_dual[compcols[i]] = REAL( buffer[i] ); int numrows = spx.numRowsReal(); buffer.resize( numrows ); const int* comprows = components.getComponentsRows( component ); if( !spx.getDualReal( buffer.data(), numrows ) ) return false; for( int i = 0; i != numrows; ++i ) sol.row_dual[comprows[i]] = REAL( buffer[i] ); return true; } void addParameters( ParameterSet& paramSet ) override { using namespace soplex; SoPlex::Settings& settings = const_cast<SoPlex::Settings&>( spx.settings() ); for( int i = 0; i != SoPlex::BOOLPARAM_COUNT; ++i ) { paramSet.addParameter( settings.boolParam.name[i].c_str(), settings.boolParam.description[i].c_str(), settings._boolParamValues[i] ); } for( int i = 0; i != SoPlex::INTPARAM_COUNT; ++i ) { paramSet.addParameter( settings.intParam.name[i].c_str(), settings.intParam.description[i].c_str(), settings._intParamValues[i], settings.intParam.lower[i], settings.intParam.upper[i] ); } for( int i = 0; i != SoPlex::REALPARAM_COUNT; ++i ) { paramSet.addParameter( settings.realParam.name[i].c_str(), settings.realParam.description[i].c_str(), settings._realParamValues[i], settings.realParam.lower[i], settings.realParam.upper[i] ); } } SolverType getType() override { return SolverType::LP; } String getName() override { return "SoPlex"; } void printDetails() override { spx.printStatistics( std::cout ); } }; template <typename REAL> class SoplexFactory : public SolverFactory<REAL> { void ( *soplexsetup )( soplex::SoPlex& soplex, void* usrdata ); void* soplexsetup_usrdata; SoplexFactory( void ( *soplexsetup )( soplex::SoPlex& soplex, void* usrdata ), void* soplexsetup_usrdata ) : soplexsetup( soplexsetup ), soplexsetup_usrdata( soplexsetup_usrdata ) { } public: virtual std::unique_ptr<SolverInterface<REAL>> newSolver( VerbosityLevel verbosity ) const override { auto soplex = std::unique_ptr<SolverInterface<REAL>>( new SoplexInterface<REAL>() ); // set verbosity already before the setup function call soplex->setVerbosity( verbosity ); if( soplexsetup != nullptr ) soplexsetup( static_cast<SoplexInterface<REAL>*>( soplex.get() )->getSoPlex(), soplexsetup_usrdata ); // set verbosity again in case the setup function altered it soplex->setVerbosity( verbosity ); return std::move( soplex ); } static std::unique_ptr<SolverFactory<REAL>> create( void ( *soplexsetup )( soplex::SoPlex& soplex, void* usrdata ) = nullptr, void* soplexsetup_usrdata = nullptr ) { return std::unique_ptr<SolverFactory<REAL>>( new SoplexFactory<REAL>( soplexsetup, soplexsetup_usrdata ) ); } }; } // namespace papilo #endif
14,865
C++
.h
373
31.324397
80
0.564188
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,953
HighsInterface.hpp
lgottwald_PaPILO/src/papilo/interfaces/HighsInterface.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_INTERFACES_HIGHS_INTERFACE_HPP_ #define _PAPILO_INTERFACES_HIGHS_INTERFACE_HPP_ #include "papilo/misc/String.hpp" #include "papilo/misc/Vec.hpp" #include <cassert> #include <stdexcept> #include <type_traits> #include "Highs.h" #include "papilo/core/Problem.hpp" #include "papilo/interfaces/SolverInterface.hpp" namespace papilo { template <typename REAL> class HighsInterface : public SolverInterface<REAL> { private: Highs solver; HighsOptions opts; static constexpr double inf = 1e+25; public: HighsInterface() { opts.infinite_bound = inf; opts.infinite_cost = inf; opts.presolve = "off"; opts.simplex_scale_strategy = 2; } void setTimeLimit( double tlim ) override { opts.time_limit = tlim; } void setUp( const Problem<REAL>& problem, const Vec<int>& row_maps, const Vec<int>& col_maps ) override { int ncols = problem.getNCols(); int nrows = problem.getNRows(); const Vec<String>& varNames = problem.getVariableNames(); const Vec<String>& consNames = problem.getConstraintNames(); const VariableDomains<REAL>& domains = problem.getVariableDomains(); const Objective<REAL>& obj = problem.getObjective(); const ConstraintMatrix<REAL>& consMatrix = problem.getConstraintMatrix(); const auto& lhs_values = consMatrix.getLeftHandSides(); const auto& rhs_values = consMatrix.getRightHandSides(); const auto& rflags = problem.getRowFlags(); opts.simplex_strategy = 3; opts.highs_min_threads = 4; opts.highs_max_threads = 4; opts.simplex_update_limit = 500; HighsLp model; /* set the objective sense and offset */ model.sense_ = OBJSENSE_MINIMIZE; model.offset_ = double( -obj.offset ); model.numRow_ = nrows; model.numCol_ = ncols; model.nnz_ = consMatrix.getNnz(); model.numInt_ = 0; // model.col_names_.resize( ncols ); model.colCost_.resize( ncols ); model.colLower_.resize( ncols ); model.colUpper_.resize( ncols ); // model.row_names_.resize( numrows ); model.rowLower_.resize( nrows ); model.rowUpper_.resize( nrows ); for( int i = 0; i != nrows; ++i ) { model.rowLower_[i] = rflags[i].test( RowFlag::kLhsInf ) ? -inf : double( lhs_values[i] ); model.rowUpper_[i] = rflags[i].test( RowFlag::kRhsInf ) ? inf : double( rhs_values[i] ); } model.integrality_.resize( ncols ); model.Aindex_.resize( model.nnz_ ); model.Avalue_.resize( model.nnz_ ); model.Astart_.resize( ncols + 1 ); model.Astart_[ncols] = model.nnz_; int start = 0; for( int i = 0; i < ncols; ++i ) { assert( !domains.flags[i].test( ColFlag::kInactive ) ); model.colLower_[i] = domains.flags[i].test( ColFlag::kLbInf ) ? -inf : double( domains.lower_bounds[i] ); model.colUpper_[i] = domains.flags[i].test( ColFlag::kUbInf ) ? inf : double( domains.upper_bounds[i] ); model.colCost_[i] = double( obj.coefficients[i] ); auto colvec = consMatrix.getColumnCoefficients( i ); int collen = colvec.getLength(); const int* colrows = colvec.getIndices(); const REAL* colvals = colvec.getValues(); model.Astart_[i] = start; for( int k = 0; k != collen; ++k ) { model.Avalue_[start + k] = double( colvals[k] ); model.Aindex_[start + k] = double( colrows[k] ); } start += collen; } solver.passModel( model ); } void setUp( const Problem<REAL>& problem, const Vec<int>& row_maps, const Vec<int>& col_maps, const Components& components, const ComponentInfo& component ) override { int ncols = problem.getNCols(); int nrows = problem.getNRows(); const Vec<String>& varNames = problem.getVariableNames(); const Vec<String>& consNames = problem.getConstraintNames(); const VariableDomains<REAL>& domains = problem.getVariableDomains(); const Objective<REAL>& obj = problem.getObjective(); const auto& consMatrix = problem.getConstraintMatrix(); const auto& lhs_values = consMatrix.getLeftHandSides(); const auto& rhs_values = consMatrix.getRightHandSides(); const auto& rflags = problem.getRowFlags(); const int* rowset = components.getComponentsRows( component.componentid ); const int* colset = components.getComponentsCols( component.componentid ); int numrows = components.getComponentsNumRows( component.componentid ); int numcols = components.getComponentsNumCols( component.componentid ); HighsLp model; /* set the objective sense and offset */ model.sense_ = OBJSENSE_MINIMIZE; model.offset_ = 0; model.numRow_ = numrows; model.numCol_ = numcols; model.nnz_ = component.nnonz; model.numInt_ = 0; model.colCost_.resize( numcols ); model.colLower_.resize( numcols ); model.colUpper_.resize( numcols ); model.rowLower_.resize( numrows ); model.rowUpper_.resize( numrows ); for( int i = 0; i != numrows; ++i ) { int row = rowset[i]; assert( components.getRowComponentIdx( row ) == i ); model.rowLower_[i] = rflags[row].test( RowFlag::kLhsInf ) ? -inf : double( lhs_values[row] ); model.rowUpper_[i] = rflags[row].test( RowFlag::kRhsInf ) ? inf : double( rhs_values[row] ); } model.Aindex_.resize( model.nnz_ ); model.Avalue_.resize( model.nnz_ ); model.Astart_.resize( numcols + 1 ); model.Astart_[numcols] = model.nnz_; int start = 0; for( int i = 0; i != numcols; ++i ) { int col = colset[i]; assert( components.getColComponentIdx( col ) == i ); assert( !domains.flags[col].test( ColFlag::kInactive ) ); model.colLower_[i] = domains.flags[col].test( ColFlag::kLbInf ) ? -inf : double( domains.lower_bounds[col] ); model.colUpper_[i] = domains.flags[col].test( ColFlag::kUbInf ) ? inf : double( domains.upper_bounds[col] ); model.colCost_[i] = double( obj.coefficients[col] ); auto colvec = consMatrix.getColumnCoefficients( col ); int collen = colvec.getLength(); const int* colrows = colvec.getIndices(); const REAL* colvals = colvec.getValues(); model.Astart_[i] = start; for( int k = 0; k != collen; ++k ) { model.Avalue_[start + k] = double( colvals[k] ); model.Aindex_[start + k] = components.getRowComponentIdx( colrows[k] ); } start += collen; } solver.passModel( model ); } void solve() override { solver.passHighsOptions( opts ); if( solver.run() == HighsStatus::Error ) { this->status = SolverStatus::kError; return; } HighsModelStatus stat = solver.getModelStatus( true ); switch( stat ) { default: this->status = SolverStatus::kError; return; case HighsModelStatus::PRIMAL_INFEASIBLE: this->status = SolverStatus::kInfeasible; return; case HighsModelStatus::PRIMAL_UNBOUNDED: this->status = SolverStatus::kUnbounded; return; case HighsModelStatus::REACHED_TIME_LIMIT: case HighsModelStatus::REACHED_ITERATION_LIMIT: this->status = SolverStatus::kInterrupted; return; case HighsModelStatus::OPTIMAL: this->status = SolverStatus::kOptimal; } } void setVerbosity( VerbosityLevel verbosity ) override { switch( verbosity ) { case VerbosityLevel::kQuiet: opts.message_level = ML_NONE; opts.logfile = nullptr; opts.output = nullptr; solver.setHighsOutput( nullptr ); solver.setHighsLogfile( nullptr ); break; case VerbosityLevel::kError: case VerbosityLevel::kWarning: case VerbosityLevel::kInfo: case VerbosityLevel::kExtra: opts.message_level = ML_MINIMAL; } } REAL getDualBound() override { if( this->status == SolverStatus::kOptimal ) return -inf; // todo return -inf; } bool getSolution( Solution<REAL>& sol ) override { const HighsSolution& highsSol = solver.getSolution(); int numcols = solver.getNumCols(); int numrows = solver.getNumRows(); if( highsSol.col_value.size() != numcols || highsSol.col_dual.size() != numcols || highsSol.row_dual.size() != numrows || highsSol.row_value.size() != numrows ) return false; // skip objoffset var --numcols; // get primal values sol.primal.resize( numcols ); for( int i = 0; i != numcols; ++i ) sol.primal[i] = highsSol.col_value[i]; // return if no dual requested if( sol.type == SolutionType::kPrimal ) return true; // get reduced costs sol.col_dual.resize( numcols ); for( int i = 0; i != numcols; ++i ) sol.col_dual[i] = REAL( highsSol.col_dual[i] ); // get row duals sol.row_dual.resize( numrows ); for( int i = 0; i != numrows; ++i ) sol.row_dual[i] = REAL( highsSol.row_dual[i] ); return true; } bool getSolution( const Components& components, int component, Solution<REAL>& sol ) override { if( this->status != SolverStatus::kOptimal ) return false; int numcols = solver.getNumCols(); int numrows = solver.getNumRows(); const HighsSolution& highsSol = solver.getSolution(); if( highsSol.col_value.size() != numcols || highsSol.col_dual.size() != numcols || highsSol.row_dual.size() != numrows || highsSol.row_value.size() != numrows ) return false; assert( components.getComponentsNumCols( component ) == numcols ); const int* compcols = components.getComponentsCols( component ); for( int i = 0; i != numcols; ++i ) sol.primal[compcols[i]] = REAL( highsSol.col_value[i] ); if( sol.type == SolutionType::kPrimal ) return true; for( int i = 0; i != numcols; ++i ) sol.col_dual[compcols[i]] = REAL( highsSol.col_dual[i] ); const int* comprows = components.getComponentsRows( component ); for( int i = 0; i != numrows; ++i ) sol.row_dual[comprows[i]] = REAL( highsSol.row_dual[i] ); return true; } void addParameters( ParameterSet& paramSet ) override { } SolverType getType() override { return SolverType::LP; } String getName() override { return "HiGHS"; } void printDetails() override { } }; template <typename REAL> class HighsFactory : public SolverFactory<REAL> { HighsFactory() {} public: virtual std::unique_ptr<SolverInterface<REAL>> newSolver( VerbosityLevel verbosity ) const override { auto highs = std::unique_ptr<SolverInterface<REAL>>( new HighsInterface<REAL>() ); highs->setVerbosity( verbosity ); return std::move( highs ); } static std::unique_ptr<SolverFactory<REAL>> create() { return std::unique_ptr<SolverFactory<REAL>>( new HighsFactory<REAL>() ); } }; } // namespace papilo #endif
13,698
C++
.h
352
31.099432
80
0.568069
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,954
SolverInterface.hpp
lgottwald_PaPILO/src/papilo/interfaces/SolverInterface.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_INTERFACES_SOLVER_INTERFACE_HPP_ #define _PAPILO_INTERFACES_SOLVER_INTERFACE_HPP_ #include "papilo/core/Components.hpp" #include "papilo/io/Message.hpp" #include "papilo/misc/ParameterSet.hpp" #include "papilo/misc/String.hpp" #include "papilo/misc/Vec.hpp" #include <memory> #include <string> namespace papilo { enum class SolverType : int { LP, MIP }; enum class SolverStatus : int { kInit, kOptimal, kInfeasible, kUnbounded, kUnbndOrInfeas, kInterrupted, kError }; template <typename REAL> class SolverInterface { protected: SolverStatus status; public: SolverInterface() : status( SolverStatus::kInit ) {} virtual void setUp( const Problem<REAL>& prob, const Vec<int>& row_maps, const Vec<int>& col_maps ) = 0; virtual void setUp( const Problem<REAL>& prob, const Vec<int>& row_maps, const Vec<int>& col_maps, const Components& components, const ComponentInfo& component ) = 0; virtual void solve() = 0; virtual SolverType getType() = 0; virtual String getName() = 0; virtual void printDetails() { } virtual void readSettings( const String& file ) { } SolverStatus getStatus() { return status; } virtual void setNodeLimit( int num ) { } virtual void setGapLimit( const REAL& gaplim ) { } virtual void setSoftTimeLimit( double tlim ) { } virtual void setTimeLimit( double tlim ) = 0; virtual void setVerbosity( VerbosityLevel verbosity ) = 0; virtual bool getSolution( Solution<REAL>& sol ) = 0; virtual bool getSolution( const Components& components, int component, Solution<REAL>& sol ) = 0; virtual REAL getDualBound() = 0; virtual void addParameters( ParameterSet& paramSet ) { } virtual ~SolverInterface() {} }; template <typename REAL> class SolverFactory { public: virtual std::unique_ptr<SolverInterface<REAL>> newSolver( VerbosityLevel verbosity = VerbosityLevel::kQuiet ) const = 0; virtual ~SolverFactory() {} }; } // namespace papilo #endif
3,904
C++
.h
120
29.266667
79
0.548722
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,958
SolWriter.hpp
lgottwald_PaPILO/src/papilo/io/SolWriter.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_IO_SOL_WRITER_HPP_ #define _PAPILO_IO_SOL_WRITER_HPP_ #include "papilo/Config.hpp" #include "papilo/misc/Vec.hpp" #include "papilo/misc/fmt.hpp" #include <boost/iostreams/filtering_stream.hpp> #include <cmath> #include <fstream> #include <iostream> #ifdef PAPILO_USE_BOOST_IOSTREAMS_WITH_BZIP2 #include <boost/iostreams/filter/bzip2.hpp> #endif #ifdef PAPILO_USE_BOOST_IOSTREAMS_WITH_ZLIB #include <boost/iostreams/filter/gzip.hpp> #endif namespace papilo { /// Writer to write problem structures into an mps file template <typename REAL> struct SolWriter { static void writeSol( const std::string& filename, const Vec<REAL>& sol, const Vec<REAL>& objective, const REAL& solobj, const Vec<std::string>& colnames ) { std::ofstream file( filename, std::ofstream::out ); boost::iostreams::filtering_ostream out; #ifdef PAPILO_USE_BOOST_IOSTREAMS_WITH_ZLIB if( boost::algorithm::ends_with( filename, ".gz" ) ) out.push( boost::iostreams::gzip_compressor() ); #endif #ifdef PAPILO_USE_BOOST_IOSTREAMS_WITH_BZIP2 if( boost::algorithm::ends_with( filename, ".bz2" ) ) out.push( boost::iostreams::bzip2_compressor() ); #endif out.push( file ); fmt::print( out, "{: <50} {: <18.15}\n", "=obj=", double( solobj ) ); for( int i = 0; i != sol.size(); ++i ) { if( sol[i] != 0.0 ) { fmt::print( out, "{: <50} {: <18.15} obj({:.15})\n", colnames[i], double( sol[i] ), double( objective[i] ) ); } } } }; } // namespace papilo #endif
3,378
C++
.h
72
43.375
79
0.502124
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,970
SimpleProbing.hpp
lgottwald_PaPILO/src/papilo/presolvers/SimpleProbing.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_PRESOLVERS_SIMPLE_PROBING_HPP_ #define _PAPILO_PRESOLVERS_SIMPLE_PROBING_HPP_ #include "papilo/core/PresolveMethod.hpp" #include "papilo/core/Problem.hpp" #include "papilo/core/ProblemUpdate.hpp" #include "papilo/io/Message.hpp" namespace papilo { template <typename REAL> class SimpleProbing : public PresolveMethod<REAL> { public: SimpleProbing() : PresolveMethod<REAL>() { this->setName( "simpleprobing" ); this->setType( PresolverType::kIntegralCols ); this->setTiming( PresolverTiming::kMedium ); } virtual PresolveStatus execute( const Problem<REAL>& problem, const ProblemUpdate<REAL>& problemUpdate, const Num<REAL>& num, Reductions<REAL>& reductions ) override; }; #ifdef PAPILO_USE_EXTERN_TEMPLATES extern template class SimpleProbing<double>; extern template class SimpleProbing<Quad>; extern template class SimpleProbing<Rational>; #endif template <typename REAL> PresolveStatus SimpleProbing<REAL>::execute( const Problem<REAL>& problem, const ProblemUpdate<REAL>& problemUpdate, const Num<REAL>& num, Reductions<REAL>& reductions ) { assert( problem.getNumIntegralCols() != 0 ); const auto& domains = problem.getVariableDomains(); const auto& cflags = domains.flags; const auto& activities = problem.getRowActivities(); const auto& changedactivities = problemUpdate.getChangedActivities(); const auto& rowsize = problem.getRowSizes(); const auto& constMatrix = problem.getConstraintMatrix(); const auto& lhs_values = constMatrix.getLeftHandSides(); const auto& rhs_values = constMatrix.getRightHandSides(); const auto& rflags = constMatrix.getRowFlags(); PresolveStatus result = PresolveStatus::kUnchanged; int nrows = problem.getNRows(); for( int i = 0; i != nrows; ++i ) { if( !rflags[i].test( RowFlag::kEquation ) || rowsize[i] <= 2 || activities[i].ninfmin != 0 || activities[i].ninfmax != 0 || !num.isEq( activities[i].min + activities[i].max, 2 * rhs_values[i] ) ) continue; assert( rflags[i].test( RowFlag::kEquation ) ); assert( activities[i].ninfmin == 0 && activities[i].ninfmax == 0 ); assert( num.isEq( activities[i].min + activities[i].max, 2 * rhs_values[i] ) ); auto rowvec = constMatrix.getRowCoefficients( i ); const REAL* rowvals = rowvec.getValues(); const int* rowcols = rowvec.getIndices(); const int rowlen = rowvec.getLength(); REAL bincoef = activities[i].max - rhs_values[i]; int bincol = -1; for( int k = 0; k != rowlen; ++k ) { int col = rowcols[k]; assert( !cflags[col].test( ColFlag::kUnbounded ) ); if( !cflags[col].test( ColFlag::kIntegral ) || domains.lower_bounds[col] != 0 || domains.upper_bounds[col] != 1 || !num.isEq( abs( rowvals[k] ), bincoef ) ) continue; bincol = col; // could be negative bincoef = rowvals[k]; break; } if( bincol != -1 ) { assert( num.isEq( abs( bincoef ), activities[i].max - rhs_values[i] ) ); assert( domains.lower_bounds[bincol] == 0 ); assert( domains.upper_bounds[bincol] == 1 ); assert( cflags[bincol].test( ColFlag::kIntegral ) ); Message::debug( this, "probing on simple equation detected {} subsitutions\n", rowlen - 1 ); result = PresolveStatus::kReduced; for( int k = 0; k != rowlen; ++k ) { int col = rowcols[k]; if( col == bincol ) continue; REAL factor; REAL offset; if( bincoef * rowvals[k] > 0 ) { factor = -( domains.upper_bounds[col] - domains.lower_bounds[col] ); offset = domains.upper_bounds[col]; } else { factor = domains.upper_bounds[col] - domains.lower_bounds[col]; offset = domains.lower_bounds[col]; } reductions.replaceCol( col, bincol, factor, offset ); } } } return result; } } // namespace papilo #endif
6,124
C++
.h
136
37.875
80
0.537223
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,976
ImplIntDetection.hpp
lgottwald_PaPILO/src/papilo/presolvers/ImplIntDetection.hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* PaPILO --- Parallel Presolve for Integer and Linear Optimization */ /* */ /* Copyright (C) 2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* This program 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. */ /* */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _PAPILO_PRESOLVERS_IMPL_INT_DETECTION_HPP_ #define _PAPILO_PRESOLVERS_IMPL_INT_DETECTION_HPP_ #include "papilo/core/PresolveMethod.hpp" #include "papilo/core/Problem.hpp" #include "papilo/core/ProblemUpdate.hpp" #include "papilo/misc/Num.hpp" #include "papilo/misc/fmt.hpp" namespace papilo { template <typename REAL> class ImplIntDetection : public PresolveMethod<REAL> { public: ImplIntDetection() : PresolveMethod<REAL>() { this->setName( "implint" ); this->setTiming( PresolverTiming::kExhaustive ); this->setType( PresolverType::kMixedCols ); } virtual PresolveStatus execute( const Problem<REAL>& problem, const ProblemUpdate<REAL>& problemUpdate, const Num<REAL>& num, Reductions<REAL>& reductions ) override; }; #ifdef PAPILO_USE_EXTERN_TEMPLATES extern template class ImplIntDetection<double>; extern template class ImplIntDetection<Quad>; extern template class ImplIntDetection<Rational>; #endif template <typename REAL> PresolveStatus ImplIntDetection<REAL>::execute( const Problem<REAL>& problem, const ProblemUpdate<REAL>& problemUpdate, const Num<REAL>& num, Reductions<REAL>& reductions ) { const auto& domains = problem.getVariableDomains(); const auto& lower_bounds = domains.lower_bounds; const auto& upper_bounds = domains.upper_bounds; const auto& cflags = domains.flags; const auto& domainFlags = domains.flags; const auto& activities = problem.getRowActivities(); const auto& consmatrix = problem.getConstraintMatrix(); const auto& lhs_values = consmatrix.getLeftHandSides(); const auto& rhs_values = consmatrix.getRightHandSides(); const auto& rflags = consmatrix.getRowFlags(); const auto& nrows = consmatrix.getNRows(); const auto& ncols = consmatrix.getNCols(); PresolveStatus result = PresolveStatus::kUnchanged; for( int col = 0; col != ncols; ++col ) { if( cflags[col].test( ColFlag::kIntegral, ColFlag::kImplInt, ColFlag::kInactive ) ) continue; bool testinequalities = problemUpdate.getPresolveOptions().dualreds == 2 ? true : false; bool impliedint = false; auto colvec = consmatrix.getColumnCoefficients( col ); int collen = colvec.getLength(); const int* colrows = colvec.getIndices(); const REAL* colvals = colvec.getValues(); for( int i = 0; i != collen; ++i ) { int row = colrows[i]; if( rflags[row].test( RowFlag::kRedundant ) || !rflags[row].test( RowFlag::kEquation ) ) continue; testinequalities = false; REAL scale = 1 / colvals[i]; if( !num.isIntegral( scale * rhs_values[row] ) ) continue; auto rowvec = consmatrix.getRowCoefficients( row ); int rowlen = rowvec.getLength(); const int* rowcols = rowvec.getIndices(); const REAL* rowvals = rowvec.getValues(); impliedint = true; for( int j = 0; j != rowlen; ++j ) { int rowcol = rowcols[j]; if( rowcol == col ) continue; if( !cflags[rowcol].test( ColFlag::kIntegral, ColFlag::kImplInt ) || !num.isIntegral( scale * rowvals[j] ) ) { impliedint = false; break; } } if( impliedint ) break; } if( impliedint ) { // add reduction reductions.impliedInteger( col ); result = PresolveStatus::kReduced; continue; } if( !testinequalities ) continue; if( !cflags[col].test( ColFlag::kLbInf ) && !num.isIntegral( lower_bounds[col] ) ) continue; if( !cflags[col].test( ColFlag::kUbInf ) && !num.isIntegral( upper_bounds[col] ) ) continue; impliedint = true; for( int i = 0; i != collen; ++i ) { int row = colrows[i]; if( rflags[row].test( RowFlag::kRedundant ) ) continue; REAL scale = 1 / colvals[i]; if( !rflags[row].test( RowFlag::kRhsInf ) && !num.isIntegral( scale * rhs_values[row] ) ) { impliedint = false; break; } if( !rflags[row].test( RowFlag::kLhsInf ) && !num.isIntegral( scale * lhs_values[row] ) ) { impliedint = false; break; } auto rowvec = consmatrix.getRowCoefficients( row ); int rowlen = rowvec.getLength(); const int* rowcols = rowvec.getIndices(); const REAL* rowvals = rowvec.getValues(); for( int j = 0; j != rowlen; ++j ) { int rowcol = rowcols[j]; if( rowcol == col ) continue; if( !cflags[rowcol].test( ColFlag::kIntegral, ColFlag::kImplInt ) || !num.isIntegral( scale * rowvals[j] ) ) { impliedint = false; break; } } if( !impliedint ) break; } if( impliedint ) { // add reduction reductions.impliedInteger( col ); result = PresolveStatus::kReduced; } } return result; } } // namespace papilo #endif
7,189
C++
.h
177
32.768362
80
0.534213
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,977
examples-common.inc
lgottwald_PaPILO/external/tbb/examples/common/examples-common.inc
# Copyright (c) 2005-2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # detect if a compiler can support C++11 # If CXX0XFLAGS already set, do not change it ifneq (,$(findstring icc, $(CXX))$(findstring icpc, $(CXX))$(findstring clang++, $(CXX))) # every supported icc or clang is OK CXX0XFLAGS ?= -std=c++11 else ifneq (,$(findstring g++, $(CXX))$(findstring gcc, $(CXX))) ifneq (, $(strip $(shell $(CXX) -v 2>&1 | grep "clang-"))) # This is clang actually, # every supported clang is OK CXX0XFLAGS ?= -std=c++11 else # support of lambda started GCC 4.5 ifneq (, $(strip $(shell g++ -dumpfullversion -dumpversion | egrep "^(4\.[5-9]|[5-9]|1[0-9])"))) CXX0XFLAGS ?= -std=c++11 endif endif endif endif
1,350
C++
.inc
32
37.15625
108
0.656535
lgottwald/PaPILO
39
2
2
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,978
gui_error.cpp
HookedBehemoth_ShareNX-Overlay/source/gui_error.cpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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 "gui_error.hpp" static char result_buffer[10]; ErrorGui::ErrorGui(const char *msg) : m_msg(msg), m_result() {} ErrorGui::ErrorGui(Result rc) { this->m_result = nullptr; if (R_MODULE(rc) == 206) { if ( R_DESCRIPTION(rc) == 23) { this->m_msg = "File not found."; this->m_result = "Was it deleted?"; } else { this->m_msg = "Unknown Album error."; } } else { this->m_msg = "Unknown error occured."; } if (this->m_result == nullptr) { std::snprintf(result_buffer, 10, "2%03d-%04d", R_MODULE(rc), R_DESCRIPTION(rc)); this->m_result = result_buffer; } } tsl::elm::Element *ErrorGui::createUI() { auto rootFrame = new tsl::elm::OverlayFrame("ShareNX \uE134", VERSION); auto *custom = new tsl::elm::CustomDrawer([&](tsl::gfx::Renderer *drawer, u16 x, u16 y, u16 w, u16 h) { static s32 msg_width = 0; static s32 result_width = 0; if (msg_width == 0) { auto [width, height] = drawer->drawString(this->m_msg, false, 0, 0, 25, tsl::style::color::ColorTransparent); msg_width = width; if (this->m_result) { auto [width, height] = drawer->drawString(this->m_msg, false, 0, 0, 25, tsl::style::color::ColorTransparent); result_width = width; } } drawer->drawString("\uE150", false, x + ((w - 90) / 2), 300, 90, 0xffff); drawer->drawString(this->m_msg, false, x + ((w - msg_width) / 2), 380, 25, 0xffff); if (this->m_result) { drawer->drawString(this->m_result, false, x + ((w - result_width) / 2), 430, 25, 0xffff); } }); rootFrame->setContent(custom); return rootFrame; }
2,431
C++
.cpp
60
34.316667
125
0.613627
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,979
main.cpp
HookedBehemoth_ShareNX-Overlay/source/main.cpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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/>. */ #define TESLA_INIT_IMPL #include "gui_error.hpp" #include "gui_main.hpp" #include "image_item.hpp" #define R_INIT(cmd, message) \ rc = cmd; \ if (R_FAILED(rc)) { \ msg = message; \ return; \ } constexpr const SocketInitConfig sockConf = { .bsdsockets_version = 1, .tcp_tx_buf_size = 0x800, .tcp_rx_buf_size = 0x800, .tcp_tx_buf_max_size = 0x25000, .tcp_rx_buf_max_size = 0x25000, .udp_tx_buf_size = 0, .udp_rx_buf_size = 0, .sb_efficiency = 1, .num_bsd_sessions = 0, .bsd_service_type = BsdServiceType_Auto, }; static u8 img[THUMB_SIZE]; class ShareOverlay : public tsl::Overlay { private: Result rc = 0; const char *msg = nullptr; CapsAlbumFileId fileId; public: virtual void initServices() override { R_INIT(socketInitialize(&sockConf), "Failed to init socket!") R_INIT(capsaInitialize(), "Failed to init capture service!"); u64 size; rc = capsaGetLastOverlayScreenShotThumbnail(&this->fileId, &size, img, THUMB_SIZE); if (R_FAILED(rc) || size == 0 || this->fileId.application_id == 0) { msg = "No screenshot taken!"; return; } u8 *work = new (std::nothrow) u8[WORK_SIZE]; if (work == nullptr) { msg = "Out of memory!"; return; } tsl::hlp::ScopeGuard work_guard([work] { delete[] work; }); u64 w, h; rc = capsaLoadAlbumScreenShotThumbnailImage(&w, &h, &this->fileId, img, THUMB_SIZE, work, WORK_SIZE); if (R_FAILED(rc) || w != THUMB_WIDTH || h != THUMB_HEIGHT) { msg = "CapSrv error!"; return; } } virtual void exitServices() override { capsaExit(); socketExit(); } virtual void onShow() override {} virtual void onHide() override {} virtual std::unique_ptr<tsl::Gui> loadInitialGui() override { if (R_FAILED(rc)) { return std::make_unique<ErrorGui>(rc); } else if (msg != nullptr) { return std::make_unique<ErrorGui>(msg); } else { return std::make_unique<MainGui>(this->fileId, img); } } }; int main(int argc, char **argv) { return tsl::loop<ShareOverlay>(argc, argv); }
2,987
C++
.cpp
87
28.517241
109
0.618371
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,980
gui_main.cpp
HookedBehemoth_ShareNX-Overlay/source/gui_main.cpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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 "gui_main.hpp" #include <string> #include "gui_error.hpp" #include "upload.hpp" MainGui::MainGui(const CapsAlbumFileId &file_id, const u8 *rgba_buffer) : fileId(file_id) { img = new ImageItem(file_id, rgba_buffer); } MainGui::~MainGui() {} tsl::elm::Element *MainGui::createUI() { auto rootFrame = new tsl::elm::OverlayFrame("ShareNX \uE134", VERSION); auto *list = new tsl::elm::List(); list->addItem(this->img); auto *button = new tsl::elm::ListItem("Upload"); button->setClickListener([&](u64 keys) { if (keys & HidNpadButton_A && !this->uploaded) { std::string url = web::UploadImage(this->fileId); this->uploaded = true; this->img->setUrl(url); return true; } return false; }); list->addItem(button); rootFrame->setContent(list); return rootFrame; }
1,560
C++
.cpp
44
31.227273
76
0.683267
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,981
upload.cpp
HookedBehemoth_ShareNX-Overlay/source/upload.cpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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 "upload.hpp" #include <sys/select.h> #include <curl/curl.h> #include <tesla.hpp> namespace web { size_t StringWrite(const char *contents, size_t size, size_t nmemb, std::string *userp) { userp->append(contents, size * nmemb); return size * nmemb; } std::string UploadImage(const CapsAlbumFileId &fileId) { u64 size = 0; Result rc = capsaGetAlbumFileSize(&fileId, &size); if (R_FAILED(rc)) return "Can't get Filesize"; char *imgBuffer = new (std::nothrow) char[size]; if (imgBuffer == nullptr) return "Memory allocation failed"; tsl::hlp::ScopeGuard buffer_guard([imgBuffer] { delete[] imgBuffer; }); u64 actualSize = 0; rc = capsaLoadAlbumFile(&fileId, &actualSize, imgBuffer, size); if (R_FAILED(rc)) { return "Failed to load Image"; } CURL *curl = curl_easy_init(); if (curl == nullptr) return "Failed to init curl"; curl_mime *mime = curl_mime_init(curl); curl_mimepart *file_part = curl_mime_addpart(mime); curl_mime_filename(file_part, "switch.jpg"); curl_mime_name(file_part, "fileToUpload"); curl_mime_data(file_part, imgBuffer, actualSize); curl_mimepart *part = curl_mime_addpart(mime); curl_mime_name(part, "curl"); curl_mime_data(part, "1", CURL_ZERO_TERMINATED); std::string urlresponse = std::string(); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, StringWrite); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&urlresponse); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); curl_easy_setopt(curl, CURLOPT_URL, "https://lewd.pics/p/index.php"); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); CURLcode res = CURLE_OK; tsl::hlp::doWithSmSession([&] { res = curl_easy_perform(curl); }); long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (res != CURLE_OK) { urlresponse = "Curl failed " + std::to_string(res); } else if (http_code != 200) { urlresponse = "Failed with " + std::to_string(http_code); } else if (urlresponse.size() > 0x30) { urlresponse = "Result too long"; } curl_mime_free(mime); curl_easy_cleanup(curl); return urlresponse; } }
3,188
C++
.cpp
76
34.684211
93
0.636805
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,982
gui_main.hpp
HookedBehemoth_ShareNX-Overlay/source/gui_main.hpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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/>. */ #pragma once #include <tesla.hpp> #include "image_item.hpp" class MainGui : public tsl::Gui { private: ImageItem *img; bool uploaded = false; CapsAlbumFileId fileId; public: MainGui(const CapsAlbumFileId &fileId, const u8 *rgba_buffer); ~MainGui(); virtual tsl::elm::Element *createUI() override; virtual void update() override {} };
1,041
C++
.h
31
30.870968
76
0.738308
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,983
upload.hpp
HookedBehemoth_ShareNX-Overlay/source/upload.hpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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/>. */ #pragma once #include <switch.h> #include <string> namespace web { std::string UploadImage(const CapsAlbumFileId &fileId); }
804
C++
.h
23
32.869565
76
0.757732
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,984
gui_error.hpp
HookedBehemoth_ShareNX-Overlay/source/gui_error.hpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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/>. */ #pragma once #include <tesla.hpp> class ErrorGui : public tsl::Gui { private: const char *m_msg; const char *m_result; public: ErrorGui(const char *msg); ErrorGui(Result rc); virtual tsl::elm::Element *createUI() override; };
924
C++
.h
28
30.428571
76
0.736547
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,985
image_item.hpp
HookedBehemoth_ShareNX-Overlay/source/image_item.hpp
/* * Copyright (c) 2020 Behemoth * * This file is part of ShareNX. * * 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/>. */ #pragma once #include <tesla.hpp> constexpr size_t THUMB_WIDTH = 320, THUMB_HEIGHT = 180; constexpr size_t THUMB_SIZE = THUMB_WIDTH * THUMB_HEIGHT * 4; constexpr size_t WORK_SIZE = 0x10000; class ImageItem : public tsl::elm::ListItem { private: CapsAlbumFileId fileId; const u8 *buffer; s32 img_x, img_y; char appId[0x11]; char date[0x20]; std::string url; public: ImageItem(const CapsAlbumFileId &file_id, const u8 *image) : ListItem(""), fileId(file_id), buffer(image), img_x(), img_y(), url() { std::snprintf(this->appId, 0x11, "%016lX", this->fileId.application_id); std::snprintf(this->date, 0x20, "%4d:%02d:%02d %02d:%02d:%02d", this->fileId.datetime.year, this->fileId.datetime.month, this->fileId.datetime.day, this->fileId.datetime.hour, this->fileId.datetime.minute, this->fileId.datetime.second); } virtual void draw(tsl::gfx::Renderer *renderer) override { u32 img_x = this->getX() + ((this->getWidth() - THUMB_WIDTH) / 2); renderer->drawRect(img_x, this->getY(), THUMB_WIDTH, THUMB_HEIGHT, 0xf000); renderer->drawBitmap(img_x, this->getY(), THUMB_WIDTH, THUMB_HEIGHT, this->buffer); renderer->drawString(this->appId, false, this->getX() + 15, this->getY() + THUMB_HEIGHT + 25, 20, tsl::style::color::ColorText); renderer->drawString(this->date, false, this->getX() + 15, this->getY() + THUMB_HEIGHT + 55, 20, tsl::style::color::ColorText); if (!url.empty()) renderer->drawString(this->url.c_str(), false, this->getX() + 15, this->getY() + THUMB_HEIGHT + 85, 20, tsl::style::color::ColorText); } virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { this->setBoundaries(this->getX(), this->getY(), this->getWidth(), THUMB_HEIGHT + 100); } virtual tsl::elm::Element *requestFocus(tsl::elm::Element *, tsl::FocusDirection) { return nullptr; } public: void setUrl(const std::string &url) { this->url = url; } };
2,851
C++
.h
62
39.532258
146
0.648542
HookedBehemoth/ShareNX-Overlay
37
7
10
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,986
PluginEditor.cpp
unevens_Curvessor/Source/PluginEditor.cpp
/* Copyright 2020 Dario Mambro This file is part of Curvessor. Curvessor 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 3 of the License, or (at your option) any later version. Curvessor 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 Curvessor. If not, see <https://www.gnu.org/licenses/>. */ #include "PluginEditor.h" #include "PluginProcessor.h" CurvessorAudioProcessorEditor::CurvessorAudioProcessorEditor( CurvessorAudioProcessor& p) : AudioProcessorEditor(&p) , processor(p) , spline(*p.getCurvessorParameters().spline, *p.getCurvessorParameters().apvts) , selectedKnot(*p.getCurvessorParameters().spline, *p.getCurvessorParameters().apvts) , gammaEnv(*p.getCurvessorParameters().apvts, p.getCurvessorParameters().envelopeFollower) , midSide(*this, *p.getCurvessorParameters().apvts, "Mid-Side") , sideChain(*this, *p.getCurvessorParameters().apvts, "SideChain") , vuMeter({ { &processor.gainVuMeterResults[0], &processor.gainVuMeterResults[1] } }, 36.f) , inputGain(*p.getCurvessorParameters().apvts, "Input Gain", p.getCurvessorParameters().inputGain) , outputGain(*p.getCurvessorParameters().apvts, "Output Gain", p.getCurvessorParameters().outputGain) , wet(*p.getCurvessorParameters().apvts, "Wet", p.getCurvessorParameters().wet) , feedbackAmount(*p.getCurvessorParameters().apvts, "Feedback", p.getCurvessorParameters().feedbackAmount) , highPassCutoff(*p.getCurvessorParameters().apvts, "Cutoff", p.getCurvessorParameters().highPassCutoff) , highPassOrder(*this, *p.getCurvessorParameters().apvts, "High-Pass-Order", { "Disabled", "6dB/Oct", "12db/Oct", "18dB/Oct" }) , stereoLink(*this, *p.getCurvessorParameters().apvts, "Stereo-Link") , ioGainLabels(*p.getCurvessorParameters().apvts, "Mid-Side") , highPassCutoffLabels(*p.getCurvessorParameters().apvts, "Mid-Side") , oversampling(*this, *p.getCurvessorParameters().apvts, "Oversampling", { "1x", "2x", "4x", "8x", "16x", "32x" }) , linearPhase(*this, *p.getCurvessorParameters().apvts, "Linear-Phase-Oversampling") , smoothing(*this, *p.getCurvessorParameters().apvts, "Smoothing-Time") , background(ImageCache::getFromMemory(BinaryData::background_png, BinaryData::background_pngSize)) { addAndMakeVisible(spline); addAndMakeVisible(selectedKnot); addAndMakeVisible(inputGain); addAndMakeVisible(outputGain); addAndMakeVisible(wet); addAndMakeVisible(feedbackAmount); addAndMakeVisible(gammaEnv); addAndMakeVisible(vuMeter); addAndMakeVisible(stereoLinkLabel); addAndMakeVisible(oversamplingLabel); addAndMakeVisible(ioGainLabels); addAndMakeVisible(highPassCutoffLabels); addAndMakeVisible(smoothingLabel); addAndMakeVisible(highPassCutoff); addAndMakeVisible(highPassLabelFirsLine); addAndMakeVisible(highPassLabelSecondLine); addAndMakeVisible(url); spline.xSuffix = "dB"; spline.ySuffix = "dB"; attachAndInitializeSplineEditors(spline, selectedKnot, 3); oversamplingLabel.setFont(Font(20._p, Font::bold)); stereoLinkLabel.setFont(Font(20._p, Font::bold)); midSide.getControl().setButtonText("Mid Side"); sideChain.getControl().setButtonText("SideChain"); oversamplingLabel.setJustificationType(Justification::centred); stereoLinkLabel.setJustificationType(Justification::centred); smoothingLabel.setJustificationType(Justification::centred); highPassLabelFirsLine.setJustificationType(Justification::centred); highPassLabelSecondLine.setJustificationType(Justification::centred); smoothing.getControl().setTextValueSuffix("ms"); for (int c = 0; c < 2; ++c) { spline.vuMeter[c] = &processor.levelVuMeterResults[c]; feedbackAmount.getControl(c).setTextValueSuffix("%"); highPassCutoff.getControl(c).setTextValueSuffix("hz"); } linearPhase.getControl().setButtonText("Linear Phase"); stereoLink.getControl().setTextValueSuffix("%"); lineColour = p.looks.frontColour.darker(1.f); vuMeter.internalColour = backgroundColour; auto tableSettings = LinkableControlTable(); tableSettings.lineColour = lineColour; tableSettings.backgroundColour = backgroundColour; gammaEnv.setTableSettings(tableSettings); selectedKnot.setTableSettings(tableSettings); auto const applyTableSettings = [&](auto& linkedControls) { linkedControls.tableSettings.lineColour = lineColour; linkedControls.tableSettings.backgroundColour = backgroundColour; }; applyTableSettings(inputGain); applyTableSettings(outputGain); applyTableSettings(ioGainLabels); applyTableSettings(highPassCutoffLabels); applyTableSettings(feedbackAmount); applyTableSettings(highPassCutoff); applyTableSettings(wet); for (int c = 0; c < 2; ++c) { outputGain.getControl(c).setTextValueSuffix("dB"); inputGain.getControl(c).setTextValueSuffix("dB"); wet.getControl(c).setTextValueSuffix("%"); wet.getControl(c).setTextValueSuffix("%"); } url.setFont({ 14._p, Font::bold }); url.setJustification(Justification::centred); url.setReadOnly(true); url.setColour(TextEditor::ColourIds::focusedOutlineColourId, Colours::white); url.setColour(TextEditor::ColourIds::backgroundColourId, Colours::transparentBlack); url.setColour(TextEditor::ColourIds::outlineColourId, Colours::transparentBlack); url.setColour(TextEditor::ColourIds::textColourId, Colours::white.withAlpha(0.2f)); url.setColour(TextEditor::ColourIds::highlightedTextColourId, Colours::white); url.setColour(TextEditor::ColourIds::highlightColourId, Colours::black); url.setText("www.unevens.net", dontSendNotification); url.setJustification(Justification::left); setSize(1022._p, 966._p); } CurvessorAudioProcessorEditor::~CurvessorAudioProcessorEditor() {} constexpr auto offset = 10._p; constexpr auto rowHeight = 40._p; constexpr auto splineEditorSide = 572._p; constexpr auto vuMeterWidth = 89._p; constexpr auto knotEditorHeight = 160._p; constexpr auto gainLeft = 3 * offset + splineEditorSide + vuMeterWidth; constexpr auto ioGainTop = splineEditorSide + 2 * offset; constexpr auto highPassTop = splineEditorSide + offset - rowHeight * 4; constexpr auto offsetFromRight = 241._p; constexpr auto channelLabelsWidth = 55._p; void CurvessorAudioProcessorEditor::paint(Graphics& g) { g.drawImage(background, getLocalBounds().toFloat()); auto const left = getRight() - offsetFromRight - 5._p; g.setColour(backgroundColour); g.fillRect(juce::Rectangle<float>(left, 10._p, 160._p, 400._p)); g.fillRect(juce::Rectangle<float>(gainLeft, highPassTop, 136._p, 160._p)); g.setColour(lineColour); g.drawRect(left, 10._p, 160._p, 45._p, 1); g.drawRect(left, 10._p, 160._p, 90._p, 1); g.drawRect(left, 10._p, 160._p, 180._p, 1); g.drawRect(left, 10._p, 160._p, 270._p, 1); g.drawRect(left, 10._p, 160._p, 400._p, 1); g.drawRect(spline.getBounds().expanded(1, 1), 1); g.drawRect(gainLeft, highPassTop, 136._p, 160._p, 1); g.drawRect(gainLeft + 10._p, highPassTop + 10._p, 116._p, 60._p, 1); g.drawLine(gainLeft + 30._p, highPassTop + 80._p, gainLeft + 106._p, highPassTop + 80._p, 1); } void CurvessorAudioProcessorEditor::resized() { spline.setTopLeftPosition(offset + 1, offset + 1); spline.setSize(splineEditorSide - 2, splineEditorSide - 2); vuMeter.setTopLeftPosition(splineEditorSide + 2 * offset, offset); vuMeter.setSize(vuMeterWidth, splineEditorSide); selectedKnot.setTopLeftPosition(offset, splineEditorSide + 2 * offset); selectedKnot.setSize(splineEditorSide + offset + vuMeterWidth + 2, 160._p); constexpr auto gammaEnvEditorY = splineEditorSide + knotEditorHeight + 3 * offset; gammaEnv.setTopLeftPosition(offset, gammaEnvEditorY); gammaEnv.setSize(gammaEnv.fullSizeWidth * uiGlobalScaleFactor, rowHeight * 4); highPassLabelFirsLine.setTopLeftPosition(gainLeft, highPassTop + 10._p); highPassLabelFirsLine.setSize(136._p, rowHeight); highPassLabelSecondLine.setTopLeftPosition(gainLeft, highPassTop + 30._p); highPassLabelSecondLine.setSize(136._p, rowHeight); highPassOrder.getControl().setTopLeftPosition(gainLeft + 10._p, highPassTop + 2.5 * rowHeight); highPassOrder.getControl().setSize(116._p, rowHeight); highPassCutoffLabels.setTopLeftPosition(gainLeft + 136._p - 2, highPassTop); highPassCutoffLabels.setSize(channelLabelsWidth, rowHeight * 4); highPassCutoff.setTopLeftPosition(highPassCutoffLabels.getRight() - 2, highPassTop); highPassCutoff.setSize(136._p, rowHeight * 4); ioGainLabels.setTopLeftPosition(gainLeft, ioGainTop); ioGainLabels.setSize(channelLabelsWidth, rowHeight * 4); inputGain.setTopLeftPosition(gainLeft + channelLabelsWidth - 1, ioGainTop); inputGain.setSize(136._p, rowHeight * 4); outputGain.setTopLeftPosition(inputGain.getRight() - 2, ioGainTop); outputGain.setSize(136._p, rowHeight * 4); feedbackAmount.setTopLeftPosition(inputGain.getPosition().getX(), gammaEnvEditorY); feedbackAmount.setSize(136._p, rowHeight * 4); wet.setTopLeftPosition(feedbackAmount.getRight() - 2, gammaEnvEditorY); wet.setSize(136._p + 1, rowHeight * 4); Grid grid; using Track = Grid::TrackInfo; grid.templateRows = { Track(Grid::Px(44._p)), Track(Grid::Px(44._p)), Track(Grid::Px(44._p)), Track(Grid::Px(44._p)), Track(Grid::Px(44._p)), Track(Grid::Px(44._p)), Track(Grid::Px(48._p)), Track(Grid::Px(40._p)), Track(Grid::Px(40._p)) }; grid.templateColumns = { Track(1_fr) }; grid.items = { GridItem(sideChain.getControl()) .withWidth(120._p) .withAlignSelf(GridItem::AlignSelf::center) .withJustifySelf(GridItem::JustifySelf::center), GridItem(midSide.getControl()) .withWidth(120._p) .withAlignSelf(GridItem::AlignSelf::center) .withJustifySelf(GridItem::JustifySelf::center), GridItem(stereoLinkLabel) .withAlignSelf(GridItem::AlignSelf::start) .withJustifySelf(GridItem::JustifySelf::center), GridItem(stereoLink.getControl()) .withWidth(135._p) .withAlignSelf(GridItem::AlignSelf::center) .withJustifySelf(GridItem::JustifySelf::center), GridItem(smoothingLabel) .withAlignSelf(GridItem::AlignSelf::start) .withJustifySelf(GridItem::JustifySelf::center), GridItem(smoothing.getControl()) .withWidth(135._p) .withAlignSelf(GridItem::AlignSelf::start) .withJustifySelf(GridItem::JustifySelf::center), GridItem(oversamplingLabel).withAlignSelf(GridItem::AlignSelf::start), GridItem(oversampling.getControl()) .withWidth(std::max(60.0L, 70._p)) .withHeight(30._p) .withAlignSelf(GridItem::AlignSelf::start) .withJustifySelf(GridItem::JustifySelf::center), GridItem(linearPhase.getControl()) .withWidth(130._p) .withAlignSelf(GridItem::AlignSelf::start) .withJustifySelf(GridItem::JustifySelf::center) }; grid.justifyContent = Grid::JustifyContent::center; grid.alignContent = Grid::AlignContent::center; grid.performLayout(juce::Rectangle<int>( getRight() - offsetFromRight, offset - 2._p, 150._p, 400._p)); url.setTopLeftPosition(10._p, getHeight() - 18._p); url.setSize(160._p, 16._p); spline.areaInWhichToDrawKnots = juce::Rectangle<int>(spline.getPosition().x, spline.getPosition().y, jmax(spline.getWidth(), selectedKnot.getWidth()), selectedKnot.getBottom() - spline.getPosition().y); }
12,432
C++
.cpp
265
40.74717
80
0.716093
unevens/Curvessor
36
3
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,987
Processing.cpp
unevens_Curvessor/Source/Processing.cpp
/* Copyright 2020-2021 Dario Mambro This file is part of Curvessor. Curvessor 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 3 of the License, or (at your option) any later version. Curvessor 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 Curvessor. If not, see <https://www.gnu.org/licenses/>. */ #include "PluginProcessor.h" static void leftRightToMidSide(double** io, int const n) { for (int i = 0; i < n; ++i) { double m = 0.5 * (io[0][i] + io[1][i]); double s = 0.5 * (io[0][i] - io[1][i]); io[0][i] = m; io[1][i] = s; } } static void midSideToLeftRight(double** io, int const n) { for (int i = 0; i < n; ++i) { double l = io[0][i] + io[1][i]; double r = io[0][i] - io[1][i]; io[0][i] = l; io[1][i] = r; } } static void applyGain(double** io, double* gain_target, double* gain_state, double const alpha, int const n) { for (int c = 0; c < 2; ++c) { for (int i = 0; i < n; ++i) { gain_state[c] = gain_target[c] + alpha * (gain_state[c] - gain_target[c]); io[c][i] *= gain_state[c]; } } } static inline Vec2d applyStereoLink(Vec2d in, Vec2d& stereo_link, Vec2d& stereo_link_target, Vec2d alpha) { auto const mean = 0.5 * (in + permute2<1, 0>(in)); stereo_link = stereo_link_target + alpha * (stereo_link - stereo_link_target); return in + stereo_link * (mean - in); } Vec2d toVumeter(Vec2d vumeter_state, Vec2d env, Vec2d alpha) { return env + alpha * (vumeter_state - env); } Vec2d applyHighPassFilter(Vec2d input, Vec2d& state, Vec2d g) { auto const v = g * (input - state); auto const low = v + state; state = low + v; return input - low; } constexpr double ln10 = 2.30258509299404568402; constexpr double db_to_lin = ln10 / 20.0; template<int highPassOrder> void CurvessorAudioProcessor::Dsp::forwardProcess(VecBuffer<Vec2d>& io, int const numActiveKnots) { auto spline = autoSpline.spline.getVecSpline<maxNumKnots>(); auto automation = autoSpline.automator.getVecAutomator<maxNumKnots>(); auto envelope = envelopeFollower.getVecData(); auto stereo_link_target = Vec2d(stereoLinkTarget); auto automation_alpha = Vec2d(automationAlpha); auto stereo_link = Vec2d().load(stereoLink); auto gain_vumeter = Vec2d().load(gainVuMeterBuffer); auto level_vumeter = Vec2d().load(levelVuMeterBuffer); auto high_pass_state = Vec2d().load(highPassState); auto high_pass_coef = Vec2d().load(highPassCoef); auto high_pass_state_2 = Vec2d().load(highPassState2); auto high_pass_state_3 = Vec2d().load(highPassState3); int const numSamples = io.getNumSamples(); for (int i = 0; i < numSamples; ++i) { Vec2d in = io[i]; Vec2d env_in = in; if constexpr (highPassOrder >= 1) { env_in = applyHighPassFilter(in, high_pass_state, high_pass_coef); } if constexpr (highPassOrder >= 2) { env_in = applyHighPassFilter(env_in, high_pass_state_2, high_pass_coef); } if constexpr (highPassOrder >= 3) { env_in = applyHighPassFilter(env_in, high_pass_state_3, high_pass_coef); } Vec2d env_out = envelope.processDB(env_in); env_out = applyStereoLink( env_out, stereo_link, stereo_link_target, automation_alpha); level_vumeter = toVumeter(level_vumeter, env_out, automation_alpha); Vec2d gc = spline.process<SplineAutomator::VecAutomator>( env_out, automation, numActiveKnots); gc -= env_out; gain_vumeter = toVumeter(gain_vumeter, gc, automation_alpha); gc = exp(db_to_lin * gc); io[i] = in * gc; } autoSpline.spline.update(spline, numActiveKnots); envelope.update(envelopeFollower); _mm_store_pd(stereoLink, stereo_link); _mm_store_pd(gainVuMeterBuffer, gain_vumeter); _mm_store_pd(levelVuMeterBuffer, level_vumeter); _mm_store_pd(highPassState, high_pass_state); _mm_store_pd(highPassState2, high_pass_state_2); _mm_store_pd(highPassState3, high_pass_state_3); } template<int highPassOrder> void CurvessorAudioProcessor::Dsp::feedbackProcess(VecBuffer<Vec2d>& io, int const numActiveKnots) { auto spline = autoSpline.spline.getVecSpline<maxNumKnots>(); auto automation = autoSpline.automator.getVecAutomator<maxNumKnots>(); auto envelope = envelopeFollower.getVecData(); auto stereo_link_target = Vec2d(stereoLinkTarget); auto automation_alpha = Vec2d(automationAlpha); auto stereo_link = Vec2d().load(stereoLink); auto gain_vumeter = Vec2d().load(gainVuMeterBuffer); auto level_vumeter = Vec2d().load(levelVuMeterBuffer); auto feedback_amount_target = Vec2d().load(feedbackAmountTarget); auto feedback_amount = Vec2d().load(feedbackAmount); auto env_in = Vec2d().load(feedbackBuffer); auto high_pass_state = Vec2d().load(highPassState); auto high_pass_coef = Vec2d().load(highPassCoef); auto high_pass_state_2 = Vec2d().load(highPassState2); auto high_pass_state_3 = Vec2d().load(highPassState3); int const numSamples = io.getNumSamples(); for (int s = 0; s < numSamples; ++s) { Vec2d in = io[s]; feedback_amount = feedback_amount + automation_alpha * (feedback_amount_target - feedback_amount); env_in = in + feedback_amount * (env_in - in); if constexpr (highPassOrder >= 1) { env_in = applyHighPassFilter(env_in, high_pass_state, high_pass_coef); } if constexpr (highPassOrder >= 2) { env_in = applyHighPassFilter(env_in, high_pass_state_2, high_pass_coef); } Vec2d env_out = envelope.processDB(env_in); env_out = applyStereoLink( env_out, stereo_link, stereo_link_target, automation_alpha); level_vumeter = toVumeter(level_vumeter, env_out, automation_alpha); Vec2d gc = spline.process<SplineAutomator::VecAutomator>( env_out, automation, numActiveKnots); gc -= env_out; gain_vumeter = toVumeter(gain_vumeter, gc, automation_alpha); gc = exp(db_to_lin * gc); io[s] = env_in = in * gc; } autoSpline.spline.update(spline, numActiveKnots); envelope.update(envelopeFollower); stereo_link.store(stereoLink); gain_vumeter.store(gainVuMeterBuffer); level_vumeter.store(levelVuMeterBuffer); env_in.store(feedbackBuffer); feedback_amount.store(feedbackAmount); high_pass_state.store(highPassState); high_pass_state_2.store(highPassState2); } template<int highPassOrder> void CurvessorAudioProcessor::Dsp::sidechainProcess(VecBuffer<Vec2d>& io, VecBuffer<Vec2d>& sidechain, int const numActiveKnots) { auto spline = autoSpline.spline.getVecSpline<maxNumKnots>(); auto automation = autoSpline.automator.getVecAutomator<maxNumKnots>(); auto envelope = envelopeFollower.getVecData(); auto automation_alpha = Vec2d(automationAlpha); auto stereo_link_target = Vec2d(stereoLinkTarget); auto stereo_link = Vec2d().load(stereoLink); auto gain_vumeter = Vec2d().load(gainVuMeterBuffer); auto level_vumeter = Vec2d().load(levelVuMeterBuffer); auto high_pass_state = Vec2d().load(highPassState); auto high_pass_coef = Vec2d().load(highPassCoef); auto high_pass_state_2 = Vec2d().load(highPassState2); auto high_pass_state_3 = Vec2d().load(highPassState3); int const numSamples = io.getNumSamples(); for (int s = 0; s < numSamples; ++s) { Vec2d in = io[s]; Vec2d env_in = sidechain[s]; if constexpr (highPassOrder >= 1) { env_in = applyHighPassFilter(env_in, high_pass_state, high_pass_coef); } if constexpr (highPassOrder >= 2) { env_in = applyHighPassFilter(env_in, high_pass_state_2, high_pass_coef); } if constexpr (highPassOrder >= 3) { env_in = applyHighPassFilter(env_in, high_pass_state_3, high_pass_coef); } Vec2d env_out = envelope.processDB(env_in); env_out = applyStereoLink( env_out, stereo_link, stereo_link_target, automation_alpha); level_vumeter = toVumeter(level_vumeter, env_out, automation_alpha); Vec2d gc = spline.process<SplineAutomator::VecAutomator>( env_out, automation, numActiveKnots); gc -= env_out; gain_vumeter = toVumeter(gain_vumeter, gc, automation_alpha); gc = exp(db_to_lin * gc); io[s] = in * gc; } autoSpline.spline.update(spline, numActiveKnots); envelope.update(envelopeFollower); stereo_link.store(stereoLink); gain_vumeter.store(gainVuMeterBuffer); level_vumeter.store(levelVuMeterBuffer); high_pass_state.store(highPassState); high_pass_state_2.store(highPassState2); high_pass_state_3.store(highPassState3); } void CurvessorAudioProcessor::processBlock(AudioBuffer<double>& buffer, MidiBuffer& midi) { ScopedNoDenormals noDenormals; auto const totalNumInputChannels = getTotalNumInputChannels(); auto const totalNumOutputChannels = getTotalNumOutputChannels(); auto const numSamples = buffer.getNumSamples(); double* ioAudio[2] = { buffer.getWritePointer(0), buffer.getWritePointer(1) }; // update settings from parameters bool const isMidSideEnabled = parameters.midSide->get(); bool const isSideChainAvailable = totalNumInputChannels == 4; bool const isSideChainRequested = parameters.sideChain->get(); bool const isUsingSideChain = isSideChainRequested && isSideChainAvailable; dsp->stereoLinkTarget = 0.01 * parameters.stereoLink->get(); double const invUpsampledSampleRate = 1.0 / (getSampleRate() * oversampling->getRate()); double const bltFrequencyCoef = MathConstants<double>::pi * invUpsampledSampleRate; double const upsampledAngularFrequencyCoef = 1000.0 * MathConstants<double>::twoPi * invUpsampledSampleRate; float const smoothingTime = parameters.smoothingTime->get(); double const automationAlpha = smoothingTime == 0.f ? 0.f : exp(-upsampledAngularFrequencyCoef / smoothingTime); double const upsampledAutomationAlpha = smoothingTime == 0.f ? 0.f : exp(-upsampledAngularFrequencyCoef / smoothingTime); dsp->automationAlpha = upsampledAutomationAlpha; double inputGainTarget[2]; double outputGainTarget[2]; double wetAmountTarget[2]; for (int c = 0; c < 2; ++c) { outputGainTarget[c] = exp(db_to_lin * parameters.outputGain.get(c)->get()); inputGainTarget[c] = exp(db_to_lin * parameters.inputGain.get(c)->get()); wetAmountTarget[c] = 0.01 * parameters.wet.get(c)->get(); dsp->feedbackAmountTarget[c] = 0.01 * parameters.feedbackAmount.get(c)->get(); dsp->highPassCoef[c] = [&] { double const g = tan(bltFrequencyCoef * parameters.highPassCutoff.get(c)->get()); return g / (1.0 + g); }(); // evenlope follower settings float const rmsTime = parameters.envelopeFollower.rmsTime.get(c)->get(); bool const rmsAlpha = rmsTime == 0.f ? 0.f : exp(-upsampledAngularFrequencyCoef / rmsTime); double const attackFrequency = parameters.envelopeFollower.attack.get(c)->get(); double const releaseFrequency = upsampledAngularFrequencyCoef / parameters.envelopeFollower.release.get(c)->get(); double const attackDelay = 0.01 * parameters.envelopeFollower.attackDelay.get(c)->get(); double const releaseDelay = 0.01 * parameters.envelopeFollower.releaseDelay.get(c)->get(); envelopeFollowerSettings.setup(c, rmsAlpha, attackFrequency, releaseFrequency, attackDelay, releaseDelay); } dsp->autoSpline.automator.setSmoothingAlpha(upsampledAutomationAlpha); int numActiveKnots = parameters.spline->updateSpline(dsp->autoSpline); bool const isWetPassNeeded = [&] { double m = wetAmountTarget[0] * wetAmountTarget[1] * dsp->wetAmount[0] * dsp->wetAmount[1]; if (m == 1.0) { return false; } if (m == 0.0) { return !(wetAmountTarget[0] == 0.0 && wetAmountTarget[1] == 0.0 && dsp->wetAmount[0] == 0.0 && dsp->wetAmount[1] == 0.0); } return true; }(); bool const isBypassing = (!isWetPassNeeded && (dsp->wetAmount[0] == 0.0)) || (numActiveKnots == 0); int const highPassOrder = parameters.highPassOrder->getIndex(); // ready to process // mid side if (isMidSideEnabled) { leftRightToMidSide(ioAudio, numSamples); } // copy the dry signal dryBuffer.setNumSamples(numSamples); for (int c = 0; c < 2; ++c) { std::copy(ioAudio[c], ioAudio[c] + numSamples, dryBuffer.get()[c]); } // input gain applyGain( ioAudio, inputGainTarget, dsp->inputGain, automationAlpha, numSamples); // oversampling oversampling->prepareBuffers(numSamples); // extra safety measure int const numUpsampledSamples = oversampling->scalarToVecUpsamplers[0]->processBlock( ioAudio, 2, numSamples); oversampling->scalarToVecUpsamplers[1]->processBlock( dryBuffer.get(), 2, numSamples); if (numUpsampledSamples == 0) { for (auto i = 0; i < totalNumOutputChannels; ++i) { buffer.clear(i, 0, numSamples); } return; } auto& upsampledBuffer = oversampling->scalarToVecUpsamplers[0]->getOutput(); auto& upsampledIo = upsampledBuffer.getBuffer2(0); auto& upsampledDryBuffer = oversampling->scalarToVecUpsamplers[1]->getOutput(); // sidechain double* envelopeInput[2] = { buffer.getWritePointer(isUsingSideChain ? 2 : 0), buffer.getWritePointer(isUsingSideChain ? 3 : 1) }; if (isUsingSideChain) { if (isMidSideEnabled) { leftRightToMidSide(envelopeInput, numSamples); } applyGain(envelopeInput, inputGainTarget, dsp->sidechainInputGain, automationAlpha, numSamples); } oversampling->scalarToVecUpsamplers[2]->processBlock( envelopeInput, 2, numSamples); auto& upsampledSideChainInput = oversampling->scalarToVecUpsamplers[2]->getOutput().getBuffer2(0); // processing const bool isFeedbackNeeded = [&] { for (int c = 0; c < 2; ++c) { if (dsp->feedbackAmountTarget[c] > 0.f) { return true; } if (dsp->feedbackAmount[c] > 0.f) { return true; } } return false; }(); if (!isBypassing) { if (isSideChainRequested) { if (isSideChainAvailable) { switch (highPassOrder) { case 0: dsp->sidechainProcess<0>( upsampledIo, upsampledSideChainInput, numActiveKnots); break; case 1: dsp->sidechainProcess<1>( upsampledIo, upsampledSideChainInput, numActiveKnots); break; case 2: dsp->sidechainProcess<2>( upsampledIo, upsampledSideChainInput, numActiveKnots); break; case 3: dsp->sidechainProcess<3>( upsampledIo, upsampledSideChainInput, numActiveKnots); break; default: assert(false); break; } } } else if (isFeedbackNeeded) { switch (highPassOrder) { case 0: dsp->feedbackProcess<0>(upsampledIo, numActiveKnots); break; case 1: dsp->feedbackProcess<1>(upsampledIo, numActiveKnots); break; case 2: dsp->feedbackProcess<2>(upsampledIo, numActiveKnots); break; case 3: dsp->feedbackProcess<3>(upsampledIo, numActiveKnots); break; default: assert(false); break; } } else { switch (highPassOrder) { case 0: dsp->forwardProcess<0>(upsampledIo, numActiveKnots); break; case 1: dsp->forwardProcess<1>(upsampledIo, numActiveKnots); break; case 2: dsp->forwardProcess<2>(upsampledIo, numActiveKnots); break; case 3: dsp->forwardProcess<3>(upsampledIo, numActiveKnots); break; default: assert(false); break; } } } // downsampling oversampling->vecToVecDownsamplers[0]->processBlock( upsampledBuffer, 2, numUpsampledSamples, numSamples); oversampling->vecToVecDownsamplers[1]->processBlock( upsampledDryBuffer, 2, numUpsampledSamples, numSamples); // dry-wet and output gain auto& wetOutput = oversampling->vecToVecDownsamplers[0]->getOutput(); auto& dryOutput = oversampling->vecToVecDownsamplers[1]->getOutput(); if (isWetPassNeeded) { auto& dryBuffer = dryOutput.getBuffer2(0); auto& wetBuffer = wetOutput.getBuffer2(0); Vec2d alpha = automationAlpha; Vec2d amount = Vec2d().load_a(dsp->wetAmount); Vec2d amountTarget = Vec2d().load(wetAmountTarget); Vec2d gain = Vec2d().load_a(dsp->outputGain); Vec2d gainTarget = Vec2d().load(outputGainTarget); for (int i = 0; i < numSamples; ++i) { amount = alpha * (amountTarget - amount) + amountTarget; gain = alpha * (gainTarget - gain) + gainTarget; Vec2d wet = gain * wetBuffer[i]; Vec2d dry = dryBuffer[i]; wetBuffer[i] = amount * (wet - dry) + dry; } amount.store(dsp->wetAmount); gain.store(dsp->outputGain); } else { if (!isBypassing) { auto& wetBuffer = wetOutput.getBuffer2(0); Vec2d alpha = automationAlpha; Vec2d gain = Vec2d().load(dsp->outputGain); Vec2d gainTarget = Vec2d().load(outputGainTarget); for (int i = 0; i < numSamples; ++i) { gain = alpha * (gainTarget - gain) + gainTarget; wetBuffer[i] = gain * wetBuffer[i]; } gain.store(dsp->outputGain); } } if (isBypassing) { dryOutput.deinterleave(ioAudio, 2, numSamples); } else { wetOutput.deinterleave(ioAudio, 2, numSamples); } // mid side if (isMidSideEnabled) { midSideToLeftRight(ioAudio, numSamples); } // update vu meters for (int i = 0; i < 2; ++i) { levelVuMeterResults[i].store((float)dsp->levelVuMeterBuffer[i]); gainVuMeterResults[i].store((float)dsp->gainVuMeterBuffer[i]); } }
18,707
C++
.cpp
489
31.940695
80
0.666925
unevens/Curvessor
36
3
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,988
PluginProcessor.cpp
unevens_Curvessor/Source/PluginProcessor.cpp
/* Copyright 2020 Dario Mambro This file is part of Curvessor. Curvessor 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 3 of the License, or (at your option) any later version. Curvessor 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 Curvessor. If not, see <https://www.gnu.org/licenses/>. */ #include "PluginProcessor.h" #include "PluginEditor.h" CurvessorAudioProcessor::Parameters::Parameters( CurvessorAudioProcessor& processor) { AudioProcessorValueTreeState::ParameterLayout layout; auto const createFloatParameter = [&](String name, float value, float min, float max, float step = 0.01f, float skewFactor = 1.f, bool symmetricSkew = false) { auto p = new AudioParameterFloat( name, name, { min, max, step, skewFactor, symmetricSkew }, value); layout.add(std::unique_ptr<RangedAudioParameter>(p)); return static_cast<AudioParameterFloat*>(p); }; auto const createWrappedBoolParameter = [&](String name, bool value) { WrappedBoolParameter wrapper; layout.add(wrapper.createParameter(name, value)); return wrapper; }; auto const createBoolParameter = [&](String name, bool value) { auto p = new AudioParameterBool(name, name, value); layout.add(std::unique_ptr<RangedAudioParameter>(p)); return static_cast<AudioParameterBool*>(p); }; auto const createChoiceParameter = [&](String name, StringArray choices, int defaultIndex = 0) { auto p = new AudioParameterChoice(name, name, choices, defaultIndex); layout.add(std::unique_ptr<RangedAudioParameter>(p)); return static_cast<AudioParameterChoice*>(p); }; String const ch0Suffix = "_ch0"; String const ch1Suffix = "_ch1"; String const linkSuffix = "_is_linked"; auto const createLinkableFloatParameters = [&](String name, float value, float min, float max, float step = 0.01f, float skewFactor = 1.f, bool symmetricSkew = false) { return LinkableParameter<AudioParameterFloat>{ createWrappedBoolParameter(name + linkSuffix, true), { createFloatParameter( name + ch0Suffix, value, min, max, step, skewFactor, symmetricSkew), createFloatParameter( name + ch1Suffix, value, min, max, step, skewFactor, symmetricSkew) } }; }; auto const createLinkableChoiceParameters = [&](String name, StringArray choices, int defaultIndex = 0) { return LinkableParameter<AudioParameterChoice>{ createWrappedBoolParameter(name + linkSuffix, true), { createChoiceParameter(name + ch0Suffix, choices, defaultIndex), createChoiceParameter(name + ch1Suffix, choices, defaultIndex) } }; }; midSide = createBoolParameter("Mid-Side", false); smoothingTime = createFloatParameter("Smoothing-Time", 50.f, 0.f, 500.f, 1.f); sideChain = createBoolParameter("SideChain", false); oversampling = { static_cast<RangedAudioParameter*>(createChoiceParameter( "Oversampling", { "1x", "2x", "4x", "8x", "16x", "32x" })), createWrappedBoolParameter("Linear-Phase-Oversampling", false) }; inputGain = createLinkableFloatParameters( "Input-Gain", 0.f, -48.f, 48.f, 0.01f, 0.25f, true); outputGain = createLinkableFloatParameters( "Output-Gain", 0.f, -48.f, 48.f, 0.01f, 0.25f, true); wet = createLinkableFloatParameters("Wet", 100.f, 0.f, 100.f, 1.f); feedbackAmount = createLinkableFloatParameters("Feedback-Amount", 0.f, 0.f, 100.f, 1.f); envelopeFollower.attack = createLinkableFloatParameters("Attack", 20.f, 0.05f, 2000.f, 0.01f, 0.25f); envelopeFollower.release = createLinkableFloatParameters("Release", 200.f, 1.f, 2000.f, 0.01f, 0.25f); envelopeFollower.attackDelay = createLinkableFloatParameters("Attack-Delay", 0.f, 0.f, 25.f); envelopeFollower.releaseDelay = createLinkableFloatParameters("Release-Delay", 0.f, 0.f, 25.f); envelopeFollower.rmsTime = createLinkableFloatParameters("RMS-Time", 0.f, 0.f, 1000.f, 0.01f, 0.25f); stereoLink = createFloatParameter("Stereo-Link", 50.f, 0.f, 100.f, 1.f); highPassCutoff = createLinkableFloatParameters("High-Pass-Cutoff", 100.f, 10.f, 250.f); highPassOrder = createChoiceParameter( "High-Pass-Order", { "Disabled", "6dB/Oct", "12db/Oct", "18dB/Oct" }); auto const isKnotActive = [](int knotIndex) { return knotIndex >= 3 && knotIndex <= 6; }; spline = std::unique_ptr<SplineParameters>( new SplineParameters("", layout, CurvessorAudioProcessor::maxEditableKnots, { -96.f, 6.f, 0.01f }, { -96.f, 6.f, 0.01f }, { -20.f, 20.f, 0.01f }, isKnotActive, { { -96.f, -96.f, 1.f, 1.f } })); apvts = std::unique_ptr<AudioProcessorValueTreeState>( new AudioProcessorValueTreeState( processor, nullptr, "CURVESSOR2-PARAMETERS", std::move(layout))); } CurvessorAudioProcessor::CurvessorAudioProcessor() #ifndef JucePlugin_PreferredChannelConfigurations : AudioProcessor(BusesProperties() .withInput("Input", AudioChannelSet::stereo(), true) .withOutput("Output", AudioChannelSet::stereo(), true) .withInput("Sidechain", AudioChannelSet::stereo())) #endif , parameters(*this) , dsp(Aligned<Dsp>::make()) , envelopeFollowerSettings(dsp->envelopeFollower) , oversamplingSettings([this] { auto oversamplingSettings = OversamplingSettings{}; oversamplingSettings.numScalarToVecUpsamplers = 3; oversamplingSettings.numVecToVecDownsamplers = 2; oversamplingSettings.numChannels = 2; oversamplingSettings.updateLatency = [this](int latency) { setLatencySamples(latency); }; return oversamplingSettings; }()) , oversampling(std::make_unique<Oversampling>(oversamplingSettings)) , oversamplingAttachments(parameters.oversampling, *parameters.apvts, this, &oversampling, &oversamplingSettings, &oversamplingMutex) { levelVuMeterResults[0].store(-500.f); levelVuMeterResults[1].store(-500.f); gainVuMeterResults[0].store(0.f); gainVuMeterResults[1].store(0.f); looks.simpleFontSize *= uiGlobalScaleFactor; looks.simpleSliderLabelFontSize *= uiGlobalScaleFactor; looks.simpleRotarySliderOffset *= uiGlobalScaleFactor; LookAndFeel::setDefaultLookAndFeel(&looks); } void CurvessorAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { dryBuffer.setNumSamples(samplesPerBlock); floatToDouble = AudioBuffer<double>(4, samplesPerBlock); if (oversamplingSettings.numSamplesPerBlock != samplesPerBlock) { auto const guard = std::lock_guard<std::recursive_mutex>(oversamplingMutex); oversamplingSettings.numSamplesPerBlock = samplesPerBlock; oversampling = std::make_unique<Oversampling>(oversamplingSettings); } reset(); } #ifndef JucePlugin_PreferredChannelConfigurations bool CurvessorAudioProcessor::isBusesLayoutSupported( const BusesLayout& layouts) const { if (layouts.getMainOutputChannels() != 2) { return false; } if (layouts.getMainInputChannels() != 2) { return false; } int const sidechainChannels = layouts.getNumChannels(true, 1); if (sidechainChannels == 2 || sidechainChannels == 0) { return true; } return false; } #endif void CurvessorAudioProcessor::processBlock(AudioBuffer<float>& buffer, MidiBuffer& midiMessages) { auto const totalNumInputChannels = getTotalNumInputChannels(); auto const numSamples = buffer.getNumSamples(); floatToDouble.setSize(4, numSamples, false, false, true); for (int c = 0; c < totalNumInputChannels; ++c) { std::copy(buffer.getReadPointer(c), buffer.getReadPointer(c) + numSamples, floatToDouble.getWritePointer(c)); } for (int c = totalNumInputChannels; c < 4; ++c) { floatToDouble.clear(c, 0, numSamples); } processBlock(floatToDouble, midiMessages); for (int c = 0; c < totalNumInputChannels; ++c) { std::copy(floatToDouble.getReadPointer(c), floatToDouble.getReadPointer(c) + numSamples, buffer.getWritePointer(c)); } } void CurvessorAudioProcessor::getStateInformation(MemoryBlock& destData) { auto state = parameters.apvts->copyState(); std::unique_ptr<XmlElement> xml(state.createXml()); copyXmlToBinary(*xml, destData); } void CurvessorAudioProcessor::setStateInformation(const void* data, int sizeInBytes) { std::unique_ptr<XmlElement> xmlState(getXmlFromBinary(data, sizeInBytes)); if (xmlState.get() != nullptr) { if (xmlState->hasTagName(parameters.apvts->state.getType())) { parameters.apvts->replaceState(ValueTree::fromXml(*xmlState)); } } } void CurvessorAudioProcessor::releaseResources() { floatToDouble = AudioBuffer<double>(0, 0); } //============================================================================== CurvessorAudioProcessor::~CurvessorAudioProcessor() {} const String CurvessorAudioProcessor::getName() const { return JucePlugin_Name; } bool CurvessorAudioProcessor::acceptsMidi() const { #if JucePlugin_WantsMidiInput return true; #else return false; #endif } bool CurvessorAudioProcessor::producesMidi() const { #if JucePlugin_ProducesMidiOutput return true; #else return false; #endif } bool CurvessorAudioProcessor::isMidiEffect() const { #if JucePlugin_IsMidiEffect return true; #else return false; #endif } double CurvessorAudioProcessor::getTailLengthSeconds() const { return 0.0; } int CurvessorAudioProcessor::getNumPrograms() { return 1; // NB: some hosts don't cope very well if you tell them there are 0 // programs, so this should be at least 1, even if you're not really // implementing programs. } int CurvessorAudioProcessor::getCurrentProgram() { return 0; } void CurvessorAudioProcessor::setCurrentProgram(int index) {} const String CurvessorAudioProcessor::getProgramName(int index) { return {}; } void CurvessorAudioProcessor::changeProgramName(int index, const String& newName) {} bool CurvessorAudioProcessor::hasEditor() const { return true; } AudioProcessorEditor* CurvessorAudioProcessor::createEditor() { return new CurvessorAudioProcessorEditor(*this); } AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new CurvessorAudioProcessor(); } void CurvessorAudioProcessor::Dsp::reset(Parameters& parameters) { parameters.spline->updateSpline(autoSpline); envelopeFollower.reset(); autoSpline.reset(); constexpr double ln10 = 2.30258509299404568402; constexpr double db_to_lin = ln10 / 20.0; double const stereoLinkTarget = 0.01 * parameters.stereoLink->get(); for (int c = 0; c < 2; ++c) { gainVuMeterBuffer[c] = 0.f; levelVuMeterBuffer[c] = -200.0; stereoLink[c] = stereoLinkTarget; inputGain[c] = exp(db_to_lin * parameters.inputGain.get(c)->get()); outputGain[c] = exp(db_to_lin * parameters.outputGain.get(c)->get()); wetAmount[c] = 0.01 * parameters.wet.get(c)->get(); sidechainInputGain[c] = inputGain[c]; feedbackAmount[c] = feedbackAmountTarget[c] = parameters.feedbackAmount.get(c)->get(); } }
12,287
C++
.cpp
328
31.14939
80
0.6803
unevens/Curvessor
36
3
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,989
AppConfig.h
unevens_Curvessor/JuceLibraryCode/AppConfig.h
/* IMPORTANT! This file is auto-generated each time you save your project - if you alter its contents, your changes may be overwritten! There's a section below where you can add your own custom code safely, and the Projucer will preserve the contents of that block, but the best way to change any of these definitions is by using the Projucer's project settings. Any commented-out settings will assume their default values. */ #pragma once //============================================================================== // [BEGIN_USER_CODE_SECTION] // (You can add your own code in this section, and the Projucer will not overwrite it) #define JUCE_REPORT_APP_USAGE 0 #define JUCE_DISPLAY_SPLASH_SCREEN 0 // [END_USER_CODE_SECTION] #include "JucePluginDefines.h" /* ============================================================================== In accordance with the terms of the JUCE 6 End-Use License Agreement, the JUCE Code in SECTION A cannot be removed, changed or otherwise rendered ineffective unless you have a JUCE Indie or Pro license, or are using JUCE under the GPL v3 license. End User License Agreement: www.juce.com/juce-6-licence ============================================================================== */ // BEGIN SECTION A #ifndef JUCE_DISPLAY_SPLASH_SCREEN #define JUCE_DISPLAY_SPLASH_SCREEN 0 #endif // END SECTION A #define JUCE_USE_DARK_SPLASH_SCREEN 1 #define JUCE_PROJUCER_VERSION 0x60008 //============================================================================== #define JUCE_MODULE_AVAILABLE_juce_audio_basics 1 #define JUCE_MODULE_AVAILABLE_juce_audio_devices 1 #define JUCE_MODULE_AVAILABLE_juce_audio_formats 1 #define JUCE_MODULE_AVAILABLE_juce_audio_plugin_client 1 #define JUCE_MODULE_AVAILABLE_juce_audio_processors 1 #define JUCE_MODULE_AVAILABLE_juce_audio_utils 1 #define JUCE_MODULE_AVAILABLE_juce_core 1 #define JUCE_MODULE_AVAILABLE_juce_cryptography 1 #define JUCE_MODULE_AVAILABLE_juce_data_structures 1 #define JUCE_MODULE_AVAILABLE_juce_events 1 #define JUCE_MODULE_AVAILABLE_juce_graphics 1 #define JUCE_MODULE_AVAILABLE_juce_gui_basics 1 #define JUCE_MODULE_AVAILABLE_juce_gui_extra 1 #define JUCE_MODULE_AVAILABLE_juce_opengl 1 #define JUCE_GLOBAL_MODULE_SETTINGS_INCLUDED 1 //============================================================================== // juce_audio_devices flags: #ifndef JUCE_USE_WINRT_MIDI //#define JUCE_USE_WINRT_MIDI 0 #endif #ifndef JUCE_ASIO //#define JUCE_ASIO 0 #endif #ifndef JUCE_WASAPI //#define JUCE_WASAPI 1 #endif #ifndef JUCE_DIRECTSOUND //#define JUCE_DIRECTSOUND 1 #endif #ifndef JUCE_ALSA //#define JUCE_ALSA 1 #endif #ifndef JUCE_JACK //#define JUCE_JACK 0 #endif #ifndef JUCE_BELA //#define JUCE_BELA 0 #endif #ifndef JUCE_USE_ANDROID_OBOE //#define JUCE_USE_ANDROID_OBOE 1 #endif #ifndef JUCE_USE_OBOE_STABILIZED_CALLBACK //#define JUCE_USE_OBOE_STABILIZED_CALLBACK 0 #endif #ifndef JUCE_USE_ANDROID_OPENSLES //#define JUCE_USE_ANDROID_OPENSLES 0 #endif #ifndef JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS //#define JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS 0 #endif //============================================================================== // juce_audio_formats flags: #ifndef JUCE_USE_FLAC //#define JUCE_USE_FLAC 1 #endif #ifndef JUCE_USE_OGGVORBIS //#define JUCE_USE_OGGVORBIS 1 #endif #ifndef JUCE_USE_MP3AUDIOFORMAT //#define JUCE_USE_MP3AUDIOFORMAT 0 #endif #ifndef JUCE_USE_LAME_AUDIO_FORMAT //#define JUCE_USE_LAME_AUDIO_FORMAT 0 #endif #ifndef JUCE_USE_WINDOWS_MEDIA_FORMAT //#define JUCE_USE_WINDOWS_MEDIA_FORMAT 1 #endif //============================================================================== // juce_audio_plugin_client flags: #ifndef JUCE_VST3_CAN_REPLACE_VST2 #define JUCE_VST3_CAN_REPLACE_VST2 0 #endif #ifndef JUCE_FORCE_USE_LEGACY_PARAM_IDS //#define JUCE_FORCE_USE_LEGACY_PARAM_IDS 0 #endif #ifndef JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE //#define JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE 0 #endif #ifndef JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS //#define JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS 1 #endif #ifndef JUCE_AU_WRAPPERS_SAVE_PROGRAM_STATES //#define JUCE_AU_WRAPPERS_SAVE_PROGRAM_STATES 0 #endif #ifndef JUCE_STANDALONE_FILTER_WINDOW_USE_KIOSK_MODE //#define JUCE_STANDALONE_FILTER_WINDOW_USE_KIOSK_MODE 0 #endif //============================================================================== // juce_audio_processors flags: #ifndef JUCE_PLUGINHOST_VST //#define JUCE_PLUGINHOST_VST 0 #endif #ifndef JUCE_PLUGINHOST_VST3 //#define JUCE_PLUGINHOST_VST3 0 #endif #ifndef JUCE_PLUGINHOST_AU //#define JUCE_PLUGINHOST_AU 0 #endif #ifndef JUCE_PLUGINHOST_LADSPA //#define JUCE_PLUGINHOST_LADSPA 0 #endif #ifndef JUCE_CUSTOM_VST3_SDK //#define JUCE_CUSTOM_VST3_SDK 0 #endif //============================================================================== // juce_audio_utils flags: #ifndef JUCE_USE_CDREADER //#define JUCE_USE_CDREADER 0 #endif #ifndef JUCE_USE_CDBURNER //#define JUCE_USE_CDBURNER 0 #endif //============================================================================== // juce_core flags: #ifndef JUCE_FORCE_DEBUG //#define JUCE_FORCE_DEBUG 0 #endif #ifndef JUCE_LOG_ASSERTIONS //#define JUCE_LOG_ASSERTIONS 0 #endif #ifndef JUCE_CHECK_MEMORY_LEAKS //#define JUCE_CHECK_MEMORY_LEAKS 1 #endif #ifndef JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES //#define JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES 0 #endif #ifndef JUCE_INCLUDE_ZLIB_CODE //#define JUCE_INCLUDE_ZLIB_CODE 1 #endif #ifndef JUCE_USE_CURL //#define JUCE_USE_CURL 1 #endif #ifndef JUCE_LOAD_CURL_SYMBOLS_LAZILY //#define JUCE_LOAD_CURL_SYMBOLS_LAZILY 0 #endif #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS //#define JUCE_CATCH_UNHANDLED_EXCEPTIONS 0 #endif #ifndef JUCE_ALLOW_STATIC_NULL_VARIABLES //#define JUCE_ALLOW_STATIC_NULL_VARIABLES 0 #endif #ifndef JUCE_STRICT_REFCOUNTEDPOINTER #define JUCE_STRICT_REFCOUNTEDPOINTER 1 #endif #ifndef JUCE_ENABLE_ALLOCATION_HOOKS //#define JUCE_ENABLE_ALLOCATION_HOOKS 0 #endif //============================================================================== // juce_events flags: #ifndef JUCE_EXECUTE_APP_SUSPEND_ON_BACKGROUND_TASK //#define JUCE_EXECUTE_APP_SUSPEND_ON_BACKGROUND_TASK 0 #endif //============================================================================== // juce_graphics flags: #ifndef JUCE_USE_COREIMAGE_LOADER //#define JUCE_USE_COREIMAGE_LOADER 1 #endif #ifndef JUCE_USE_DIRECTWRITE //#define JUCE_USE_DIRECTWRITE 1 #endif #ifndef JUCE_DISABLE_COREGRAPHICS_FONT_SMOOTHING //#define JUCE_DISABLE_COREGRAPHICS_FONT_SMOOTHING 0 #endif //============================================================================== // juce_gui_basics flags: #ifndef JUCE_ENABLE_REPAINT_DEBUGGING //#define JUCE_ENABLE_REPAINT_DEBUGGING 0 #endif #ifndef JUCE_USE_XRANDR //#define JUCE_USE_XRANDR 1 #endif #ifndef JUCE_USE_XINERAMA //#define JUCE_USE_XINERAMA 1 #endif #ifndef JUCE_USE_XSHM //#define JUCE_USE_XSHM 1 #endif #ifndef JUCE_USE_XRENDER //#define JUCE_USE_XRENDER 0 #endif #ifndef JUCE_USE_XCURSOR //#define JUCE_USE_XCURSOR 1 #endif #ifndef JUCE_WIN_PER_MONITOR_DPI_AWARE //#define JUCE_WIN_PER_MONITOR_DPI_AWARE 1 #endif //============================================================================== // juce_gui_extra flags: #ifndef JUCE_WEB_BROWSER #define JUCE_WEB_BROWSER 0 #endif #ifndef JUCE_USE_WIN_WEBVIEW2 //#define JUCE_USE_WIN_WEBVIEW2 0 #endif #ifndef JUCE_ENABLE_LIVE_CONSTANT_EDITOR //#define JUCE_ENABLE_LIVE_CONSTANT_EDITOR 0 #endif //============================================================================== #ifndef JUCE_STANDALONE_APPLICATION #if defined(JucePlugin_Name) && defined(JucePlugin_Build_Standalone) #define JUCE_STANDALONE_APPLICATION JucePlugin_Build_Standalone #else #define JUCE_STANDALONE_APPLICATION 0 #endif #endif
8,605
C++
.h
238
33
87
0.624009
unevens/Curvessor
36
3
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,536,990
PluginEditor.h
unevens_Curvessor/Source/PluginEditor.h
/* Copyright 2020 Dario Mambro This file is part of Curvessor. Curvessor 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 3 of the License, or (at your option) any later version. Curvessor 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 Curvessor. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "GainVuMeter.h" #include "GammaEnvEditor.h" #include "PluginProcessor.h" #include "SplineEditor.h" #include <JuceHeader.h> class CurvessorAudioProcessorEditor : public AudioProcessorEditor { public: CurvessorAudioProcessorEditor(CurvessorAudioProcessor&); ~CurvessorAudioProcessorEditor(); void paint(Graphics&) override; void resized() override; private: CurvessorAudioProcessor& processor; SplineEditor spline; SplineKnotEditor selectedKnot; GammaEnvEditor gammaEnv; GainVuMeter vuMeter; AttachedToggle midSide; AttachedToggle sideChain; AttachedComboBox oversampling; AttachedToggle linearPhase; Label oversamplingLabel{ {}, "Oversampling" }; AttachedSlider stereoLink; Label stereoLinkLabel{ {}, "Stereo Link" }; AttachedSlider smoothing; Label smoothingLabel{ {}, "Smoothing Time" }; LinkableControl<AttachedSlider> inputGain; LinkableControl<AttachedSlider> outputGain; LinkableControl<AttachedSlider> wet; LinkableControl<AttachedSlider> feedbackAmount; LinkableControl<AttachedSlider> highPassCutoff; AttachedComboBox highPassOrder; ChannelLabels ioGainLabels; ChannelLabels highPassCutoffLabels; Label highPassLabelFirsLine{ {}, "Detector" }; Label highPassLabelSecondLine{ {}, "High Pass" }; TextEditor url; Colour lineColour = Colours::white; Colour backgroundColour = Colours::black.withAlpha(0.6f); Image background; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CurvessorAudioProcessorEditor) };
2,179
C++
.h
58
35.189655
77
0.815852
unevens/Curvessor
36
3
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,991
PluginProcessor.h
unevens_Curvessor/Source/PluginProcessor.h
/* Copyright 2020 Dario Mambro This file is part of Curvessor. Curvessor 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 3 of the License, or (at your option) any later version. Curvessor 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 Curvessor. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "GammaEnvEditor.h" #include "Linkables.h" #include "OversamplingParameters.h" #include "SimpleLookAndFeel.h" #include "SplineParameters.h" #include "adsp/GammaEnv.hpp" #include "adsp/Spline.hpp" #include <JuceHeader.h> #ifndef CURVESSOR_UI_SCALE #define CURVESSOR_UI_SCALE 0.8f #endif static constexpr float uiGlobalScaleFactor = CURVESSOR_UI_SCALE; constexpr static long double operator"" _p(long double px) { return px * uiGlobalScaleFactor; } class CurvessorAudioProcessor : public AudioProcessor { public: static constexpr int maxNumKnots = 9; static constexpr int maxEditableKnots = maxNumKnots - 1; private: struct Parameters { AudioParameterBool* midSide; AudioParameterBool* sideChain; LinkableParameter<AudioParameterFloat> inputGain; LinkableParameter<AudioParameterFloat> outputGain; LinkableParameter<AudioParameterFloat> wet; LinkableParameter<AudioParameterFloat> feedbackAmount; LinkableParameter<AudioParameterFloat> rmsTime; GammaEnvParameters envelopeFollower; AudioParameterFloat* stereoLink; AudioParameterFloat* smoothingTime; OversamplingParameters oversampling; LinkableParameter<AudioParameterFloat> highPassCutoff; AudioParameterChoice* highPassOrder; std::unique_ptr<SplineParameters> spline; std::unique_ptr<AudioProcessorValueTreeState> apvts; Parameters(CurvessorAudioProcessor& processor); }; Parameters parameters; using Spline = adsp::Spline<Vec2d, maxNumKnots>; using AutoSpline = adsp::AutoSpline<Vec2d, maxNumKnots>; using SplineAutomator = adsp::Spline<Vec2d, maxNumKnots>::SmoothingAutomator; struct Dsp { AutoSpline autoSpline; adsp::GammaEnv<Vec2d> envelopeFollower; double stereoLink[2]; double wetAmount[2]; double inputGain[2]; double outputGain[2]; double sidechainInputGain[2]; double feedbackBuffer[2]; double feedbackAmount[2]; double feedbackAmountTarget[2]; double rmsAlpha[2]; double levelVuMeterBuffer[2]; double gainVuMeterBuffer[2]; double highPassCoef[2]; double highPassState[2]; double highPassState2[2]; double highPassState3[2]; double automationAlpha; double stereoLinkTarget; Dsp() { AVEC_ASSERT_ALIGNMENT(this, Vec2d); std::fill_n(stereoLink, 2 * 15, 0.0); } void reset(Parameters& parameters); template<int highPassOrder> void forwardProcess(VecBuffer<Vec2d>& io, int const numActiveKnots); template<int highPassOrder> void feedbackProcess(VecBuffer<Vec2d>& io, int const numActiveKnots); template<int highPassOrder> void sidechainProcess(VecBuffer<Vec2d>& io, VecBuffer<Vec2d>& sidechain, int const numActiveKnots); }; aligned_ptr<Dsp> dsp; adsp::GammaEnvSettings<Vec2d> envelopeFollowerSettings; ScalarBuffer<double> dryBuffer{ 2 }; // buffer for single precision processing call AudioBuffer<double> floatToDouble; // oversampling using Oversampling = oversimple::Oversampling<double>; using OversamplingSettings = oversimple::OversamplingSettings; OversamplingSettings oversamplingSettings; std::unique_ptr<Oversampling> oversampling; std::recursive_mutex oversamplingMutex; OversamplingAttachments<double, std::recursive_mutex> oversamplingAttachments; public: // for gui SimpleLookAndFeel looks; Parameters& getCurvessorParameters() { return parameters; } std::array<std::atomic<float>, 2> levelVuMeterResults; std::array<std::atomic<float>, 2> gainVuMeterResults; // AudioProcessor interface //============================================================================== CurvessorAudioProcessor(); ~CurvessorAudioProcessor(); //============================================================================== void prepareToPlay(double sampleRate, int samplesPerBlock) override; void releaseResources() override; void reset() override { dsp->reset(parameters); } #ifndef JucePlugin_PreferredChannelConfigurations bool isBusesLayoutSupported(const BusesLayout& layouts) const override; #endif void processBlock(AudioBuffer<float>&, MidiBuffer&) override; bool supportsDoublePrecisionProcessing() const override { return true; } void processBlock(AudioBuffer<double>& buffer, MidiBuffer& midi) override; //============================================================================== AudioProcessorEditor* createEditor() override; bool hasEditor() const override; //============================================================================== const String getName() const override; bool acceptsMidi() const override; bool producesMidi() const override; bool isMidiEffect() const override; double getTailLengthSeconds() const override; //============================================================================== int getNumPrograms() override; int getCurrentProgram() override; void setCurrentProgram(int index) override; const String getProgramName(int index) override; void changeProgramName(int index, const String& newName) override; //============================================================================== void getStateInformation(MemoryBlock& destData) override; void setStateInformation(const void* data, int sizeInBytes) override; private: //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CurvessorAudioProcessor) };
6,234
C++
.h
152
36.960526
82
0.705882
unevens/Curvessor
36
3
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,992
Benchmarker.cpp
nlbucki_RAPPIDS/test/Benchmarker.cpp
/*! * Rectangular Pyramid Partitioning using Integrated Depth Sensors * * Copyright 2020 by Junseok Lee <junseok_lee@berkeley.edu> * and Nathan Bucki <nathan_bucki@berkeley.edu> * * This code 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 3 of the License, or (at your option) any later version. * * This code 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 the code. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <boost/program_options.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <ctime> #include <fstream> #include <iostream> #include <opencv2/opencv.hpp> #include <random> #include <string> #include "RectangularPyramidPlanner/DepthImagePlanner.hpp" #include "RapidQuadcopterTrajectories/RapidTrajectoryGenerator.hpp" using namespace CommonMath; using namespace RapidQuadrocopterTrajectoryGenerator; using namespace RectangularPyramidPlanner; enum testType { CONSERVATIVENESS = 0, COLLISION_CHECKING_TIME = 1, TRAJECTORY_COVERAGE = 2, }; typedef struct { int w; int h; double depth_scale; double f; double cx; double cy; } camera_intrinsics_t; typedef struct { double physical_vehicle_radius; double vehicle_radius_for_planning; double minimum_collision_distance; } planner_specs_t; typedef struct { uint num_scenes; // [1] uint num_obstacles; // [1] double obstacles_width_min; // [m] double obstacles_width_max; // [m] double obstacles_depth_min; // [m] double obstacles_depth_max; // [m] uint random_seed; } synthesis_specs_t; typedef struct { bool display; double display_range_min; // [m] double display_range_max; // [m] bool png_output; double vx_min; double vx_max; double vy_min; double vy_max; double vz_min; double vz_max; double ay_min; double ay_max; uint random_seed; int test_type; } benchmark_options_t; typedef struct { std::vector<int> max_num_pyramids; int num_traj; } conservative_test_options_t; typedef struct { double pyramid_gen_time; int num_traj; } collision_time_options_t; typedef struct { double min_comp_time; double max_comp_time; int num_comp_times; } traj_coverage_options_t; typedef struct { int count; double min; double max; double median; double mean; } benchmark_stats_t; template<class T> static benchmark_stats_t calculate_stats(std::vector<T>& q) { benchmark_stats_t stats; const auto median_it = q.begin() + q.size() / 2; std::nth_element(q.begin(), median_it, q.end()); // nth_element is a partial sorting algorithm that rearranges elements. stats.count = q.size(); stats.min = *std::min_element(q.begin(), q.end()); stats.max = *std::max_element(q.begin(), q.end()); stats.mean = std::accumulate(std::begin(q), std::end(q), 0.0) / q.size(); // ! 0.0 double 0.0f float 0 integer stats.median = *median_it; return stats; } static void print_stats(std::ostream& os, const std::string& stats_name, benchmark_stats_t& stats) { os << std::left << std::endl << std::setw(60) << "Samples:" << stats.count << std::endl << std::setw(60) << stats_name + ".min: " << stats.min << std::endl << std::setw(60) << stats_name + ".max: " << stats.max << std::endl << std::setw(60) << stats_name + ".mean: " << stats.mean << std::endl << std::setw(60) << stats_name + ".median: " << stats.median << std::endl; } static void display_image(const cv::Mat& depth_image, double pixelMin, double pixelMax) { cv::Mat displayable_image; double alpha = 255.0 / (pixelMax - pixelMin); double beta = -alpha * pixelMin; depth_image.convertTo(displayable_image, CV_8UC1, alpha, beta); // BLUE = FAR // RED = CLOSE cv::applyColorMap(displayable_image, displayable_image, cv::COLORMAP_HOT); cv::imshow("display", displayable_image); cv::waitKey(1); } // Include center point of your rectangle, size of your rectangle and the degrees of rotation static void draw_rotated_rectangle(cv::Mat& image, const uint obstacle_depth, const cv::Point centerPoint, const cv::Size rectangleSize, const double rotationDegrees) { cv::Scalar color = cv::Scalar(obstacle_depth); // Create the rotated rectangle cv::RotatedRect rotatedRectangle(centerPoint, rectangleSize, rotationDegrees); // We take the edges that OpenCV calculated for us cv::Point2f vertices2f[4]; rotatedRectangle.points(vertices2f); // Convert them so we can use them in a fillConvexPoly cv::Point vertices[4]; for (int i = 0; i < 4; ++i) { vertices[i] = vertices2f[i]; } // Now we can fill the rotated rectangle with our specified color cv::fillConvexPoly(image, vertices, 4, color); } static void make_image(const camera_intrinsics_t& camera_intrinsics, const synthesis_specs_t& synthesis_specs, std::mt19937& gen, cv::Mat& out_depth_frame) { // output // * Produces random floating-point values i, uniformly distributed on the interval [a, b). std::uniform_real_distribution<> random_angle(0, 180); std::uniform_real_distribution<> random_w_SI( synthesis_specs.obstacles_width_min, synthesis_specs.obstacles_width_max); // [m] std::uniform_real_distribution<> random_depth_SI( synthesis_specs.obstacles_depth_min, synthesis_specs.obstacles_depth_max); // [m] // * Produces random integer values i, uniformly distributed on the closed interval [a, b]. std::uniform_int_distribution<> random_x_px(0, camera_intrinsics.w - 1); const uint RECT_HEIGHT = 0xFFFF; const uint DEPTH_MAX = 0xFFFF; // represent infinity in 16 bit image cv::Mat depth_mat(camera_intrinsics.h, camera_intrinsics.w, CV_16UC1, cv::Scalar(DEPTH_MAX)); for (int j = 0; j < synthesis_specs.num_obstacles; j++) { int center_x = random_x_px(gen); int center_y = static_cast<float>(camera_intrinsics.h) / static_cast<float>(camera_intrinsics.w) * center_x; // pixelValues = depth / depth_scale // e.g. 1 meter = 1000 pixel value for depth_scale = 0.001 double depth_SI = random_depth_SI(gen); int depth_px = depth_SI / camera_intrinsics.depth_scale; // double to int implicit conversion draw_rotated_rectangle( depth_mat, depth_px, cv::Point2f(center_x, center_y), cv::Size2f(RECT_HEIGHT, camera_intrinsics.f * random_w_SI(gen) / depth_SI), random_angle(gen)); } // Output: depth frame out_depth_frame = depth_mat; } static void run_conservativeness_benchmark( const camera_intrinsics_t& camera_intrinsics, const planner_specs_t& planner_specs, const synthesis_specs_t& synthesis_specs, const benchmark_options_t& benchmark_options, const conservative_test_options_t& conservative_test_options, boost::property_tree::ptree& root) { if (benchmark_options.display) { cv::namedWindow("display", cv::WINDOW_AUTOSIZE); cv::moveWindow("display", 500,500); } // Set up the random number generators std::mt19937 image_rdgen(synthesis_specs.random_seed); std::mt19937 state_rdgen(benchmark_options.random_seed); std::uniform_real_distribution<> random_vx(benchmark_options.vx_min, benchmark_options.vx_max); std::uniform_real_distribution<> random_vy(benchmark_options.vy_min, benchmark_options.vy_max); std::uniform_real_distribution<> random_vz(benchmark_options.vz_min, benchmark_options.vz_max); std::uniform_real_distribution<> random_ay(benchmark_options.ay_min, benchmark_options.ay_max); // For saving the results boost::property_tree::ptree max_num_pyramids_ptree; // Run the test for each given pyramid limit for (int max_allowed_pyramids : conservative_test_options.max_num_pyramids) { int total_incorrect_in_collision = 0; int total_correct_in_collision = 0; std::vector<int> num_pyramids_generated; boost::property_tree::ptree conservativenesss_ptree; for (int i = 0; i < synthesis_specs.num_scenes; i++) { if (i % 20 == 0) { printf("Processed %d frames so far.\n", i); } // Set up the test cv::Mat depth_mat; make_image(camera_intrinsics, synthesis_specs, image_rdgen, depth_mat); DepthImagePlanner planner(depth_mat, camera_intrinsics.depth_scale, camera_intrinsics.f, camera_intrinsics.cx, camera_intrinsics.cy, planner_specs.physical_vehicle_radius, planner_specs.vehicle_radius_for_planning, planner_specs.minimum_collision_distance); RapidTrajectoryGenerator traj( Vec3(0, 0, 0), Vec3(random_vx(state_rdgen), random_vy(state_rdgen), random_vz(state_rdgen)), Vec3(0, -random_ay(state_rdgen), 0), Vec3(0, 9.81, 0)); // Run the test int incorrect_in_collision, correct_in_collision; planner.MeasureConservativeness(conservative_test_options.num_traj, max_allowed_pyramids, traj, incorrect_in_collision, correct_in_collision); // Store the results total_incorrect_in_collision += incorrect_in_collision; total_correct_in_collision += correct_in_collision; num_pyramids_generated.push_back(planner.GetPyramids().size()); boost::property_tree::ptree convervativeness_node; convervativeness_node.put_value( double(incorrect_in_collision) / double(incorrect_in_collision + correct_in_collision)); conservativenesss_ptree.push_back( std::make_pair("", convervativeness_node)); if (benchmark_options.png_output) { std::string filename = std::to_string(i) + ".png"; imwrite(filename, depth_mat); } if (benchmark_options.display) { display_image( depth_mat, benchmark_options.display_range_min / camera_intrinsics.depth_scale, benchmark_options.display_range_max / camera_intrinsics.depth_scale); } } benchmark_stats_t stats_pyramids = calculate_stats<int>( num_pyramids_generated); double conservativeness = double(total_incorrect_in_collision) / (total_incorrect_in_collision + total_correct_in_collision); printf("\nConservativeness = %f (%d max pyramids)\n", conservativeness, max_allowed_pyramids); print_stats(std::cout, "AvgPyramids", stats_pyramids); boost::property_tree::ptree maxPyramidNode; maxPyramidNode.put_value(max_allowed_pyramids); max_num_pyramids_ptree.push_back( std::make_pair("numPyramids", maxPyramidNode)); max_num_pyramids_ptree.add_child( "Conservativeness" + std::to_string(max_allowed_pyramids), conservativenesss_ptree); root.put_child("MaxNumPyramids", max_num_pyramids_ptree); // put_child overwrites, unlike add_child. std::ofstream json_out("./data/conservativenessTest.json"); write_json(json_out, root); json_out.close(); } } static void run_collision_checking_time_benchmark( const camera_intrinsics_t& camera_intrinsics, const planner_specs_t& planner_specs, const synthesis_specs_t& synthesis_specs, const benchmark_options_t& benchmark_options, const collision_time_options_t& collision_time_options, boost::property_tree::ptree& root) { if (benchmark_options.display) { cv::namedWindow("display", cv::WINDOW_AUTOSIZE); cv::moveWindow("display", 500,500); } std::mt19937 image_rdgen(synthesis_specs.random_seed); std::mt19937 state_rdgen(benchmark_options.random_seed); std::uniform_real_distribution<> random_vx(benchmark_options.vx_min, benchmark_options.vx_max); std::uniform_real_distribution<> random_vy(benchmark_options.vy_min, benchmark_options.vy_max); std::uniform_real_distribution<> random_vz(benchmark_options.vz_min, benchmark_options.vz_max); std::uniform_real_distribution<> random_ay(benchmark_options.ay_min, benchmark_options.ay_max); std::vector<double> collision_check_time; std::vector<double> percent_collision_free_vec; std::vector<int> num_pyramids; for (int i = 0; i < synthesis_specs.num_scenes; i++) { if (i % 20 == 0) { printf("Processed %d frames so far.\n", i); } cv::Mat depth_mat; make_image(camera_intrinsics, synthesis_specs, image_rdgen, depth_mat); DepthImagePlanner planner(depth_mat, camera_intrinsics.depth_scale, camera_intrinsics.f, camera_intrinsics.cx, camera_intrinsics.cy, planner_specs.physical_vehicle_radius, planner_specs.vehicle_radius_for_planning, planner_specs.minimum_collision_distance); RapidTrajectoryGenerator traj( Vec3(0, 0, 0), Vec3(random_vx(state_rdgen), random_vy(state_rdgen), random_vz(state_rdgen)), Vec3(0, -random_ay(state_rdgen), 0), Vec3(0, 9.81, 0)); double total_check_time; double percent_collision_free; planner.MeasureCollisionCheckingSpeed( collision_time_options.num_traj, collision_time_options.pyramid_gen_time, traj, total_check_time, percent_collision_free); collision_check_time.push_back( total_check_time / collision_time_options.num_traj); percent_collision_free_vec.push_back(percent_collision_free); num_pyramids.push_back(planner.GetPyramids().size()); if (benchmark_options.png_output) { std::string filename = std::to_string(i) + ".png"; imwrite(filename, depth_mat); } if (benchmark_options.display) { display_image( depth_mat, benchmark_options.display_range_min / camera_intrinsics.depth_scale, benchmark_options.display_range_max / camera_intrinsics.depth_scale); } } benchmark_stats_t stats_coll_check_time = calculate_stats<double>( collision_check_time); root.put("AvgCollCheckTimePerTrajNs", stats_coll_check_time.mean); benchmark_stats_t stats_num_pyramids = calculate_stats<int>(num_pyramids); root.put("AvgPyramidsGen", stats_num_pyramids.mean); benchmark_stats_t percent_collision_free_stats = calculate_stats<double>( percent_collision_free_vec); printf("Avg. Collision checking time per traj. = %f ns\n", stats_coll_check_time.mean); printf("Avg. pyramids per frame = %f\n", stats_num_pyramids.mean); print_stats(std::cout, "AvgCollCheckTimePerTrajNs", stats_coll_check_time); print_stats(std::cout, "AvgPyramidsGen", stats_num_pyramids); print_stats(std::cout, "percent_collision_free_stats", percent_collision_free_stats); std::ofstream json_out("./data/collisionCheckingTime.json"); write_json(json_out, root); json_out.close(); } static void run_trajectory_coverage_benchmark( const camera_intrinsics_t& camera_intrinsics, const planner_specs_t& planner_specs, const synthesis_specs_t& synthesis_specs, const benchmark_options_t& benchmark_options, const traj_coverage_options_t& traj_coverage_options, boost::property_tree::ptree& root) { if (benchmark_options.display) { cv::namedWindow("display", cv::WINDOW_AUTOSIZE); cv::moveWindow("display", 500,500); } std::mt19937 image_rdgen(synthesis_specs.random_seed); std::mt19937 state_rdgen(benchmark_options.random_seed); std::uniform_real_distribution<> random_vx(benchmark_options.vx_min, benchmark_options.vx_max); std::uniform_real_distribution<> random_vy(benchmark_options.vy_min, benchmark_options.vy_max); std::uniform_real_distribution<> random_vz(benchmark_options.vz_min, benchmark_options.vz_max); std::uniform_real_distribution<> random_ay(benchmark_options.ay_min, benchmark_options.ay_max); boost::property_tree::ptree comp_time_ptree, avg_traj_gen_ptree; for (int k = 0; k < traj_coverage_options.num_comp_times; k++) { double a = traj_coverage_options.min_comp_time; double b = traj_coverage_options.max_comp_time; double n = traj_coverage_options.num_comp_times; double base = pow(b / a, 1 / (n - 1)); // This increasing computation time geometrically, so we have more resolution at smaller computation times double comp_time = a * pow(base, k); // When k == n-1, compTime = b std::vector<int> num_traj_gen; for (int i = 0; i < synthesis_specs.num_scenes; i++) { if (i % 20 == 0) { printf("Processed %d frames so far.\n", i); } cv::Mat depth_mat; make_image(camera_intrinsics, synthesis_specs, image_rdgen, depth_mat); DepthImagePlanner planner(depth_mat, camera_intrinsics.depth_scale, camera_intrinsics.f, camera_intrinsics.cx, camera_intrinsics.cy, planner_specs.physical_vehicle_radius, planner_specs.vehicle_radius_for_planning, planner_specs.minimum_collision_distance); RapidTrajectoryGenerator traj( Vec3(0, 0, 0), Vec3(random_vx(state_rdgen), random_vy(state_rdgen), random_vz(state_rdgen)), Vec3(0, -random_ay(state_rdgen), 0), Vec3(0, 9.81, 0)); Vec3 exploration_direction(0, 0, 1); planner.FindFastestTrajRandomCandidates(traj, comp_time, exploration_direction); num_traj_gen.push_back(planner.GetNumTrajectoriesGenerated()); if (benchmark_options.png_output) { std::string filename = std::to_string(i) + ".png"; imwrite(filename, depth_mat); } if (benchmark_options.display) { display_image( depth_mat, benchmark_options.display_range_min / camera_intrinsics.depth_scale, benchmark_options.display_range_max / camera_intrinsics.depth_scale); } } benchmark_stats_t stats_num_traj_gen = calculate_stats<int>(num_traj_gen); printf("Stats for %f s of computation time:", comp_time); print_stats(std::cout, "numTrajGen", stats_num_traj_gen); boost::property_tree::ptree comp_time_node; comp_time_node.put_value(comp_time); comp_time_ptree.push_back(std::make_pair("", comp_time_node)); boost::property_tree::ptree avg_traj_gen_node; avg_traj_gen_node.put_value(stats_num_traj_gen.mean); avg_traj_gen_ptree.push_back(std::make_pair("", avg_traj_gen_node)); root.put_child("CompTime", comp_time_ptree); // * put_child replaces the node, instead of adding a node like add_child. root.put_child("AvgTrajGen", avg_traj_gen_ptree); std::ofstream json_out("./data/avgTrajGen.json"); write_json(json_out, root); json_out.close(); } } int main(int argc, const char* argv[]) { using namespace boost::program_options; using namespace boost::property_tree; try { camera_intrinsics_t camera_intrinsics { }; planner_specs_t planner_specs { }; synthesis_specs_t synthesis_specs { }; benchmark_options_t benchmark_options { }; conservative_test_options_t conservative_test_options { }; collision_time_options_t collision_time_options { }; traj_coverage_options_t traj_coverage_options { }; options_description desc { "Options" }; options_description_easy_init opt = desc.add_options(); opt("help,h", "Help screen"); opt("test_type", value<int>(&benchmark_options.test_type)->default_value( TRAJECTORY_COVERAGE), "test to be run (CONSERVATIVENESS = 0, COLLISION_CHECKING_TIME = 1, TRAJECTORY_COVERAGE = 2)"); opt("image-count,n", value<uint>(&synthesis_specs.num_scenes)->default_value(500), "number of scenes for synthetic depth images"); opt("w", value<int>(&camera_intrinsics.w)->default_value(160), "synthesized image width"); opt("h", value<int>(&camera_intrinsics.h)->default_value(120), "synthesized image height"); opt("depth-scale", value<double>(&camera_intrinsics.depth_scale)->default_value(0.001), "depth scale"); opt("f", value<double>(&camera_intrinsics.f)->default_value(386.643 / 4.0), "synthesized image focal length"); // This has to be scaled when images scaled down. opt("cx", value<double>(&camera_intrinsics.cx)->default_value(160.0 / 2.0), "synthesized image cx"); opt("cy", value<double>(&camera_intrinsics.cy)->default_value(120.0 / 2.0), "synthesized image cy"); opt("vehicleRadius", value<double>(&planner_specs.physical_vehicle_radius)->default_value( 0.26), "The true physical radius of the vehicle (ignore depth values closer than this) [meters]"); opt("planningRadius", value<double>(&planner_specs.vehicle_radius_for_planning)->default_value( 0.46), "The radius of the vehicle used for planning [meters]"); opt("minimumCollisionDistance", value<double>(&planner_specs.minimum_collision_distance)->default_value( 1.0), "We assume on obstacle is just outside the field of view this distance away [meters]"); opt("obs-num", value<uint>(&synthesis_specs.num_obstacles)->default_value(2), "number of obstacles for synthetic depth images"); opt("obs-w-min", value<double>(&synthesis_specs.obstacles_width_min)->default_value( 0.20), "min width of obstacles in [m]"); opt("obs-w-max", value<double>(&synthesis_specs.obstacles_width_max)->default_value( 0.20), "max width of obstacles in [m]"); opt("obs-d-min", value<double>(&synthesis_specs.obstacles_depth_min)->default_value(1.5), "min depth of obstacles in [m]"); opt("obs-d-max", value<double>(&synthesis_specs.obstacles_depth_max)->default_value(3.0), "max depth of obstacles in [m]"); opt("obs-seed", value<uint>(&synthesis_specs.random_seed)->default_value(0), "random seed for generating images"); opt("dispaly,d", bool_switch(&benchmark_options.display)->default_value(false), "display each frame"); opt("display-min", value<double>(&benchmark_options.display_range_min)->default_value(0.0), "min of depth range for display"); opt("display-max", value<double>(&benchmark_options.display_range_max)->default_value(4.0), "max of depth range for display"); opt("png-output,o", bool_switch(&benchmark_options.png_output)->default_value(false), "output png files"); opt("vx-min", value<double>(&benchmark_options.vx_min)->default_value(-1), "min vx [m/s]"); opt("vx-max", value<double>(&benchmark_options.vx_max)->default_value(1), "max vx [m/s]"); opt("vy-min", value<double>(&benchmark_options.vy_min)->default_value(-1), "min vy [m/s]"); opt("vy-max", value<double>(&benchmark_options.vy_max)->default_value(1), "max vy [m/s]"); opt("vz-min", value<double>(&benchmark_options.vz_min)->default_value(0), "min vz [m/s]"); opt("vz-max", value<double>(&benchmark_options.vz_max)->default_value(4), "max vz [m/s]"); opt("ay-min", value<double>(&benchmark_options.ay_min)->default_value(-5), "min ax [m/s]"); opt("ay-max", value<double>(&benchmark_options.ay_max)->default_value(5), "max ay [m/s]"); opt("bc-seed", value<uint>(&benchmark_options.random_seed)->default_value(0), "random seed for initial states"); opt("maxNumPyramidForConservativenessTest", value<std::vector<int>>(&conservative_test_options.max_num_pyramids) ->multitoken()->default_value(std::vector<int> { 1, 2, 4, 8 }, "1 2 4 8"), "List of the maximum allowed number of pyramids (for use with CONSERVATIVENESS only)"); opt("numTrajForConservativenessTest", value<int>(&conservative_test_options.num_traj)->default_value(1000), "Number of trajectories to use to compute conservativeness (for use with CONSERVATIVENESS only)"); opt("pyramidGenTimeForCCTest", value<double>(&collision_time_options.pyramid_gen_time)->default_value( 0.00181), "Time allocated for generating pyramids (for use with COLLISION_CHECKING_TIME only)"); opt("numTrajForCCTest", value<int>(&collision_time_options.num_traj)->default_value(10000), "Number of trajectories to use to time collision checker (for use with COLLISION_CHECKING_TIME only)"); opt("minCompTimeForTCTest", value<double>(&traj_coverage_options.min_comp_time)->default_value( 0.0001), "Minimum computation time allocated to planner (for use with TRAJECTORY_COVERAGE only)"); opt("maxCompTimeForTCTest", value<double>(&traj_coverage_options.max_comp_time)->default_value( 0.05), "Maximum computation time allocated to planner (for use with TRAJECTORY_COVERAGE only)"); opt("numCompTimesForTCTest", value<int>(&traj_coverage_options.num_comp_times)->default_value(10), "Number of computation times to test between min and max (for use with TRAJECTORY_COVERAGE only)"); variables_map vm; store(parse_command_line(argc, argv, desc), vm); notify(vm); if (vm.count("help")) { std::cout << "\n" << desc << "\n"; return 0; } std::cout << std::left << std::endl << "* please make sure the executable is compiled with optimization." << std::endl << "* please make sure the CPU governor is performance." << std::endl; // std::vector<cv::Mat> qDepthFrames; ptree root; // * each item will be structured as per dot's root.put("synthesis_specs.camera_intrinsics.w", camera_intrinsics.w); root.put("synthesis_specs.camera_intrinsics.h", camera_intrinsics.h); root.put("synthesis_specs.camera_intrinsics.depth_scale", camera_intrinsics.depth_scale); root.put("synthesis_specs.camera_intrinsics.f", camera_intrinsics.f); root.put("synthesis_specs.camera_intrinsics.cx", camera_intrinsics.cx); root.put("synthesis_specs.camera_intrinsics.cy", camera_intrinsics.cy); root.put("synthesis_specs.num_scenes", synthesis_specs.num_scenes); root.put("synthesis_specs.num_obstacles", synthesis_specs.num_obstacles); root.put("synthesis_specs.obstacles_width_min", synthesis_specs.obstacles_width_min); root.put("synthesis_specs.obstacles_width_max", synthesis_specs.obstacles_width_max); root.put("synthesis_specs.obstacles_depth_min", synthesis_specs.obstacles_depth_min); root.put("synthesis_specs.obstacles_depth_max", synthesis_specs.obstacles_depth_max); root.put("synthesis_specs.random_seed", synthesis_specs.random_seed); root.put("benchmark_options.display", benchmark_options.display); root.put("benchmark_options.display_range_min", benchmark_options.display_range_min); root.put("benchmark_options.display_range_max", benchmark_options.display_range_max); root.put("benchmark_options.png_output", benchmark_options.png_output); root.put("benchmark_options.vx_min", benchmark_options.vx_min); root.put("benchmark_options.vx_max", benchmark_options.vx_max); root.put("benchmark_options.vy_min", benchmark_options.vy_min); root.put("benchmark_options.vy_max", benchmark_options.vy_max); root.put("benchmark_options.vz_min", benchmark_options.vz_min); root.put("benchmark_options.vz_max", benchmark_options.vz_max); root.put("benchmark_options.ax_min", benchmark_options.ay_min); root.put("benchmark_options.ax_max", benchmark_options.ay_max); root.put("benchmark_options.random_seed", benchmark_options.random_seed); // Run benchmark and save data try { if (benchmark_options.test_type == CONSERVATIVENESS) { // const properties saved first ptree child; for (auto &x : conservative_test_options.max_num_pyramids) { ptree node; node.put_value(x); child.push_back(std::make_pair("", node)); } root.add_child("conservative_test_options.max_num_pyramids", child); root.put("conservative_test_options.num_traj", conservative_test_options.num_traj); run_conservativeness_benchmark(camera_intrinsics, planner_specs, synthesis_specs, benchmark_options, conservative_test_options, root); } else if (benchmark_options.test_type == COLLISION_CHECKING_TIME) { // const properties saved first root.put("collision_time_options.pyramid_gen_time", collision_time_options.pyramid_gen_time); root.put("collision_time_options.num_traj", collision_time_options.num_traj); run_collision_checking_time_benchmark(camera_intrinsics, planner_specs, synthesis_specs, benchmark_options, collision_time_options, root); } else if (benchmark_options.test_type == TRAJECTORY_COVERAGE) { // const properties saved first root.put("traj_coverage_options.min_comp_time", traj_coverage_options.min_comp_time); root.put("traj_coverage_options.max_comp_time", traj_coverage_options.max_comp_time); root.put("traj_coverage_options.num_comp_times", traj_coverage_options.num_comp_times); run_trajectory_coverage_benchmark(camera_intrinsics, planner_specs, synthesis_specs, benchmark_options, traj_coverage_options, root); } else { printf("Invalid choice of benchmarking test to run. Aborting.\n"); } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } } catch (const error& ex) { std::cerr << ex.what() << '\n'; } return 0; }
31,315
C++
.cpp
654
39.735474
150
0.654037
nlbucki/RAPPIDS
35
13
1
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,001
Rotation.hpp
nlbucki_RAPPIDS/include/CommonMath/Rotation.hpp
/*! * Rapid Collision Detection for Multicopter Trajectories * * Copyright 2019 by High Performance Robotics Lab, UC Berkeley * * This code 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 3 of the License, or (at your option) any later version. * * This code 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 the code. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <stdio.h> #include <math.h> #include <limits> #include "CommonMath/Vec3.hpp" namespace CommonMath { //! A way of representing attitudes, based on the Euler-Rodriguez symmetric parameters (ERSP) a.k.a. "quaternion of rotation". /*!Note that you should call Normalise() every once in a while, so that you're rotations remain * orthonormal. * * BEWARE: Everyone defines rotations differently, take care when interpreting the internals, or * using it. Construct some test cases and make sure the numbers make sense. */ class Rotation { double static constexpr half = double(0.5); double static constexpr MIN_ANGLE = double(4.84813681e-6); //less than one arc second. public: Rotation(void) { } //! Constructor given a unit quaternion. Rotation(double a, double b, double c, double d) { _v[0] = a; _v[1] = b; _v[2] = c; _v[3] = d; } //! Copy constructor. Rotation(Rotation const &in) { _v[0] = double(in[0]); _v[1] = double(in[1]); _v[2] = double(in[2]); _v[3] = double(in[3]); } static inline Rotation Identity(void) { return Rotation(1, 0, 0, 0); } Rotation Inverse(void) const { return Rotation(_v[0], -_v[1], -_v[2], -_v[3]); } //! This makes sure the quaternion is a unit quaternion. void Normalise(void) { double n = sqrt( _v[0] * _v[0] + _v[1] * _v[1] + _v[2] * _v[2] + _v[3] * _v[3]); if (n < 1.0e-6) { (*this) = Identity(); } else { for (int i = 0; i < 4; i++) _v[i] /= n; } } /*! Returns a Rotation object given a vector, where the direction of the vector * is the rotation axis and the magnitude of the vector is the angle of rotation in radians. */ static Rotation FromRotationVector(const Vec3 rotVec) { const double theta = rotVec.GetNorm2(); if (theta < MIN_ANGLE) return Identity(); //less than one arc second :) return FromAxisAngle(rotVec / theta, theta); } /*! Returns a Rotation object given a unit vector and angle. The unit vector * is the rotation axis and the angle is the angle of rotation in radians. */ static inline Rotation FromAxisAngle(const Vec3 &unitVector, const double &angle) { return Rotation(cos(angle * half), sin(angle * half) * unitVector.x, sin(angle * half) * unitVector.y, sin(angle * half) * unitVector.z); } //! Returns a Rotation object given Euler angles yaw, pitch, and roll. static Rotation FromEulerYPR(const double& y, const double& p, const double& r) { //NB! rotation: 3-2-1 yaw,pitch,roll Rotation rot; rot[0] = cos(half * y) * cos(half * p) * cos(half * r) + sin(half * y) * sin(half * p) * sin(half * r); rot[1] = cos(half * y) * cos(half * p) * sin(half * r) - sin(half * y) * sin(half * p) * cos(half * r); rot[2] = cos(half * y) * sin(half * p) * cos(half * r) + sin(half * y) * cos(half * p) * sin(half * r); rot[3] = sin(half * y) * cos(half * p) * cos(half * r) - cos(half * y) * sin(half * p) * sin(half * r); return rot; } //! Returns a Rotation object given the three elements of the vector part of a unit quaternion. static Rotation FromVectorPartOfQuaternion(const Vec3 in) { double tmp = in.GetNorm2Squared(); if (tmp > 1.0f) return Rotation::Identity(); double a0 = sqrt(1 - tmp); return Rotation(a0, in.x, in.y, in.z); } //! Rotation multiplication: r2*r1, corresponds to a rotation r1 followed by rotation r2 Rotation operator*(const Rotation& r1) const { double c0 = r1[0] * _v[0] - r1[1] * _v[1] - r1[2] * _v[2] - r1[3] * _v[3]; double c1 = r1[1] * _v[0] + r1[0] * _v[1] + r1[3] * _v[2] - r1[2] * _v[3]; double c2 = r1[2] * _v[0] - r1[3] * _v[1] + r1[0] * _v[2] + r1[1] * _v[3]; double c3 = r1[3] * _v[0] + r1[2] * _v[1] - r1[1] * _v[2] + r1[0] * _v[3]; return Rotation(c0, c1, c2, c3); } //! Rotate a vector forward Vec3 operator*(const Vec3& vec) const { return Rotate(vec); } /*! Returns the rotation vector corresponding to this rotation, where * the returned vector is the rotation axis and its magnitude is the * rotation angle. */ Vec3 ToRotationVector(void) const { const Vec3 n = ToVectorPartOfQuaternion(); const double norm = n.GetNorm2(); const double angle = asin(norm) * 2; if (angle < MIN_ANGLE) { return Vec3(0, 0, 0); //less than one arc second } return n * (angle / norm); } //! Returns the vector part of the quaternion representing this rotation Vec3 ToVectorPartOfQuaternion(void) const { //makes first component positive if (_v[0] > 0) return Vec3(_v[1], _v[2], _v[3]); else return Vec3(-_v[1], -_v[2], -_v[3]); } //! Returns the Euler angles yaw, pitch, and roll representing this rotation void ToEulerYPR(double &y, double &p, double &r) const { y = atan2(double(2.0) * _v[1] * _v[2] + double(2.0) * _v[0] * _v[3], _v[1] * _v[1] + _v[0] * _v[0] - _v[3] * _v[3] - _v[2] * _v[2]); p = -asin(double(2.0) * _v[1] * _v[3] - double(2.0) * _v[0] * _v[2]); r = atan2(double(2.0) * _v[2] * _v[3] + double(2.0) * _v[0] * _v[1], _v[3] * _v[3] - _v[2] * _v[2] - _v[1] * _v[1] + _v[0] * _v[0]); } //! Returns the Euler angles yaw, pitch, and roll representing this rotation Vec3 ToEulerYPR(void) const { Vec3 out; ToEulerYPR(out.x, out.y, out.z); return out; } //! For debugging void PrintRotationMatrix(void) { double R[9]; GetRotationMatrix(R); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%.3f\t", (double) R[i * 3 + j]); } printf("\n"); } } double& operator[](unsigned const i) { return _v[i]; } const double& operator[](unsigned const i) const { return _v[i]; } /*! Returns the rotation matrix corresponding to this rotation where * Matrix = * [[R[0], R[1], R[2]], * [R[3], R[4], R[5]], * [R[6], R[7], R[8]]] */ void GetRotationMatrix(double R[9]) const { const double r0 = _v[0] * _v[0]; const double r1 = _v[1] * _v[1]; const double r2 = _v[2] * _v[2]; const double r3 = _v[3] * _v[3]; R[0] = r0 + r1 - r2 - r3; R[1] = 2 * _v[1] * _v[2] - 2 * _v[0] * _v[3]; R[2] = 2 * _v[1] * _v[3] + 2 * _v[0] * _v[2]; R[3] = 2 * _v[1] * _v[2] + 2 * _v[0] * _v[3]; R[4] = r0 - r1 + r2 - r3; R[5] = 2 * _v[2] * _v[3] - 2 * _v[0] * _v[1]; R[6] = 2 * _v[1] * _v[3] - 2 * _v[0] * _v[2]; R[7] = 2 * _v[2] * _v[3] + 2 * _v[0] * _v[1]; R[8] = r0 - r1 - r2 + r3; } private: Vec3 Rotate(const Vec3& in) const { double R[9]; GetRotationMatrix(R); Vec3 ret(R[0] * in.x + R[1] * in.y + R[2] * in.z, R[3] * in.x + R[4] * in.y + R[5] * in.z, R[6] * in.x + R[7] * in.y + R[8] * in.z); return ret; } Vec3 RotateBackwards(const Vec3& in) const { double R[9]; Inverse().GetRotationMatrix(R); Vec3 ret(R[0] * in.x + R[1] * in.y + R[2] * in.z, R[3] * in.x + R[4] * in.y + R[5] * in.z, R[6] * in.x + R[7] * in.y + R[8] * in.z); return ret; } double _v[4]; }; }
8,304
C++
.h
213
32.929577
127
0.5619
nlbucki/RAPPIDS
35
13
1
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,006
py_common_types.cpp
zeldamods_oead/py/py_common_types.cpp
/** * Copyright (C) 2020 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #include <type_traits> #include <pybind11/operators.h> #include <pybind11/pybind11.h> #include <oead/errors.h> #include <oead/types.h> #include <oead/util/swap.h> #include "main.h" namespace oead::bind { namespace detail { template <typename T, typename PyT> void BindNumber(py::module& m, const char* name) { py::class_<T> cl(m, name); cl.def(py::init([](PyT v) { return T(v); }), "value"_a = 0) .def(py::self == py::self) .def(py::self < py::self) .def(py::self <= py::self) .def(py::self > py::self) .def(py::self >= py::self) .def_property( "v", [](const T& self) { return self.value; }, [](T& self, PyT vnew) { self = vnew; }, "Value") .def("__int__", [](const T& self) { if constexpr (std::is_floating_point<decltype(T::value)>()) return s64(self.value); else return self.value; }) .def("__float__", [](const T& self) { return double(self.value); }) .def("__str__", [](const T& self) { return std::to_string(self.value); }) .def("__repr__", [name](const T& self) { return "{}({})"_s.format(name, self.value); }); if constexpr (std::is_integral<decltype(T::value)>()) { cl.def("__index__", [](const T& self) { return self.value; }); } } template <size_t N> void BindFixedSafeString(py::module& m, const char* name) { py::class_<FixedSafeString<N>>(m, name) .def(py::init<>()) .def(py::init<std::string_view>()) .def("__str__", [](const FixedSafeString<N>& s) { return Str(s); }) .def("__repr__", [name](const FixedSafeString<N>& s) { return "{}({})"_s.format(name, Str(s)); }) .def(py::self == py::self) .def("__eq__", [](const FixedSafeString<N>& lhs, std::string_view rhs) { return Str(lhs) == rhs; }); } } // namespace detail void BindCommonTypes(py::module& m) { BindVector<std::vector<u8>>( m, "Bytes", py::buffer_protocol(), "Mutable bytes-like object. This is used to avoid possibly expensive data copies."); py::implicitly_convertible<py::bytes, std::vector<u8>>(); BindVector<std::vector<int>>(m, "BufferInt", py::buffer_protocol(), "Mutable list-like object that stores signed 32-bit integers."); BindVector<std::vector<f32>>(m, "BufferF32", py::buffer_protocol(), "Mutable list-like object that stores binary32 floats."); BindVector<std::vector<u32>>(m, "BufferU32", py::buffer_protocol(), "Mutable list-like object that stores unsigned 32-bit integers."); BindVector<std::vector<bool>>(m, "BufferBool", "Mutable list-like object that stores booleans."); BindVector<std::vector<std::string>>(m, "BufferString", "Mutable list-like object that stores strings."); detail::BindNumber<U8, py::int_>(m, "U8"); detail::BindNumber<U16, py::int_>(m, "U16"); detail::BindNumber<U32, py::int_>(m, "U32"); detail::BindNumber<U64, py::int_>(m, "U64"); detail::BindNumber<S8, py::int_>(m, "S8"); detail::BindNumber<S16, py::int_>(m, "S16"); detail::BindNumber<S32, py::int_>(m, "S32"); detail::BindNumber<S64, py::int_>(m, "S64"); detail::BindNumber<F32, py::float_>(m, "F32"); detail::BindNumber<F64, py::float_>(m, "F64"); py::class_<Vector2f>(m, "Vector2f") .def(py::init<>()) .def(py::self == py::self) .def_readwrite("x", &Vector2f::x) .def_readwrite("y", &Vector2f::y); py::class_<Vector3f>(m, "Vector3f") .def(py::init<>()) .def(py::self == py::self) .def_readwrite("x", &Vector3f::x) .def_readwrite("y", &Vector3f::y) .def_readwrite("z", &Vector3f::z); py::class_<Vector4f>(m, "Vector4f") .def(py::init<>()) .def(py::self == py::self) .def_readwrite("x", &Vector4f::x) .def_readwrite("y", &Vector4f::y) .def_readwrite("z", &Vector4f::z) .def_readwrite("t", &Vector4f::t); py::class_<Quatf>(m, "Quatf") .def(py::init<>()) .def(py::self == py::self) .def_readwrite("a", &Quatf::a) .def_readwrite("b", &Quatf::b) .def_readwrite("c", &Quatf::c) .def_readwrite("d", &Quatf::d); py::class_<Color4f>(m, "Color4f") .def(py::init<>()) .def(py::self == py::self) .def_readwrite("r", &Color4f::r) .def_readwrite("g", &Color4f::g) .def_readwrite("b", &Color4f::b) .def_readwrite("a", &Color4f::a); py::class_<Curve>(m, "Curve") .def(py::init<>()) .def(py::self == py::self) .def_readwrite("a", &Curve::a) .def_readwrite("b", &Curve::b) .def_readwrite("floats", &Curve::floats); detail::BindFixedSafeString<16>(m, "FixedSafeString16"); detail::BindFixedSafeString<32>(m, "FixedSafeString32"); detail::BindFixedSafeString<48>(m, "FixedSafeString48"); detail::BindFixedSafeString<64>(m, "FixedSafeString64"); detail::BindFixedSafeString<128>(m, "FixedSafeString128"); detail::BindFixedSafeString<256>(m, "FixedSafeString256"); py::register_exception<TypeError>(m, "TypeError"); py::register_exception<InvalidDataError>(m, "InvalidDataError"); py::enum_<util::Endianness>(m, "Endianness") .value("Big", util::Endianness::Big) .value("Little", util::Endianness::Little); } } // namespace oead::bind
6,073
C++
.cpp
141
37.262411
99
0.608659
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,007
py_aamp.cpp
zeldamods_oead/py/py_aamp.cpp
/** * Copyright (C) 2019 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #include <map> #include <nonstd/span.h> #include <type_traits> #include <vector> #include <pybind11/operators.h> #include <pybind11/pybind11.h> #include <oead/aamp.h> #include "main.h" OEAD_MAKE_VARIANT_CASTER(oead::aamp::Parameter::Value); OEAD_MAKE_OPAQUE("aamp.ParameterMap", oead::aamp::ParameterMap); OEAD_MAKE_OPAQUE("aamp.ParameterObjectMap", oead::aamp::ParameterObjectMap); OEAD_MAKE_OPAQUE("aamp.ParameterListMap", oead::aamp::ParameterListMap); namespace oead::bind { static void BindAampParameter(py::module& m) { py::class_<aamp::Parameter> clas(m, "Parameter"); py::enum_<aamp::Parameter::Type>(clas, "Type") .value("Bool", aamp::Parameter::Type::Bool) .value("F32", aamp::Parameter::Type::F32) .value("Int", aamp::Parameter::Type::Int) .value("Vec2", aamp::Parameter::Type::Vec2) .value("Vec3", aamp::Parameter::Type::Vec3) .value("Vec4", aamp::Parameter::Type::Vec4) .value("Color", aamp::Parameter::Type::Color) .value("String32", aamp::Parameter::Type::String32) .value("String64", aamp::Parameter::Type::String64) .value("Curve1", aamp::Parameter::Type::Curve1) .value("Curve2", aamp::Parameter::Type::Curve2) .value("Curve3", aamp::Parameter::Type::Curve3) .value("Curve4", aamp::Parameter::Type::Curve4) .value("BufferInt", aamp::Parameter::Type::BufferInt) .value("BufferF32", aamp::Parameter::Type::BufferF32) .value("String256", aamp::Parameter::Type::String256) .value("Quat", aamp::Parameter::Type::Quat) .value("U32", aamp::Parameter::Type::U32) .value("BufferU32", aamp::Parameter::Type::BufferU32) .value("BufferBinary", aamp::Parameter::Type::BufferBinary) .value("StringRef", aamp::Parameter::Type::StringRef); clas // This is required to support conversions from F32 to float. // Without this constructor, oead.F32(1.7) is turned into an integer. .def(py::init<F32>()) .def(py::init<aamp::Parameter::Value>()) .def(py::self == py::self) .def("__copy__", [](const aamp::Parameter::Value& o) { return aamp::Parameter::Value(o); }) .def("__deepcopy__", [](const aamp::Parameter::Value& o, py::dict) { return aamp::Parameter::Value(o); }); clas.def("type", &aamp::Parameter::GetType) .def("__repr__", [](aamp::Parameter& i) { return "aamp.Parameter({!r})"_s.format(i.GetVariant()); }) .def("__str__", [](aamp::Parameter& i) { return "{!s}"_s.format(i.GetVariant()); }); clas.def_property( "v", [](aamp::Parameter& i) -> aamp::Parameter::Value& { return i.GetVariant(); }, [](aamp::Parameter& i, aamp::Parameter::Value& v) { i.GetVariant() = std::move(v); }, "Value"); py::implicitly_convertible<aamp::Parameter::Value, aamp::Parameter>(); } void BindAamp(py::module& parent) { py::module m = parent.def_submodule("aamp"); py::class_<aamp::Name>(m, "Name") .def(py::init<u32>(), "name_crc32"_a) .def(py::init<std::string_view>(), "name"_a) .def(py::self == py::self) .def_readonly("hash", &aamp::Name::hash) .def( "__hash__", [](aamp::Name n) { return n.hash; }, py::is_operator()) .def("__str__", [](aamp::Name n) { return "{}"_s.format(n.hash); }) .def("__repr__", [](aamp::Name n) { return "aamp.Name({})"_s.format(n.hash); }); py::implicitly_convertible<u32, aamp::Name>(); py::implicitly_convertible<std::string_view, aamp::Name>(); BindAampParameter(m); py::class_<aamp::ParameterObject>(m, "ParameterObject") .def(py::init<>()) .def(py::self == py::self) .def("__copy__", [](const aamp::ParameterObject& o) { return aamp::ParameterObject(o); }) .def("__deepcopy__", [](const aamp::ParameterObject& o, py::dict) { return aamp::ParameterObject(o); }) .def_readwrite("params", &aamp::ParameterObject::params); py::class_<aamp::ParameterList>(m, "ParameterList") .def(py::init<>()) .def(py::self == py::self) .def("__copy__", [](const aamp::ParameterList& o) { return aamp::ParameterList(o); }) .def("__deepcopy__", [](const aamp::ParameterList& o, py::dict) { return aamp::ParameterList(o); }) .def_readwrite("objects", &aamp::ParameterList::objects) .def_readwrite("lists", &aamp::ParameterList::lists); py::class_<aamp::ParameterIO, aamp::ParameterList>(m, "ParameterIO") .def(py::init<>()) .def(py::self == py::self) .def("__copy__", [](const aamp::ParameterIO& o) { return aamp::ParameterIO(o); }) .def("__deepcopy__", [](const aamp::ParameterIO& o, py::dict) { return aamp::ParameterIO(o); }) .def_readwrite("version", &aamp::ParameterIO::version) .def_readwrite("type", &aamp::ParameterIO::type) .def_static("from_binary", &aamp::ParameterIO::FromBinary, "buffer"_a) .def_static("from_text", &aamp::ParameterIO::FromText, "yml_text"_a) .def("to_binary", &aamp::ParameterIO::ToBinary) .def("to_text", &aamp::ParameterIO::ToText); BindMap<aamp::ParameterMap>(m, "ParameterMap"); BindMap<aamp::ParameterObjectMap>(m, "ParameterObjectMap"); BindMap<aamp::ParameterListMap>(m, "ParameterListMap"); py::class_<aamp::NameTable>(m, "NameTable") .def(py::init<bool>(), "with_botw_strings"_a) .def("__copy__", [](const aamp::NameTable& o) { return aamp::NameTable(o); }) .def("__deepcopy__", [](const aamp::NameTable& o, py::dict) { return aamp::NameTable(o); }) .def("get_name", &aamp::NameTable::GetName, "hash"_a, "index"_a, "parent_name_hash"_a) .def("add_name", py::overload_cast<std::string>(&aamp::NameTable::AddName), "name"_a); m.def("get_default_name_table", &aamp::GetDefaultNameTable, py::return_value_policy::reference, "Just like in C++, this returns the default instance of the name table. It is modifiable."); } } // namespace oead::bind
6,625
C++
.cpp
128
46.523438
100
0.642846
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,008
main.cpp
zeldamods_oead/py/main.cpp
/** * Copyright (C) 2019 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #include <pybind11/pybind11.h> #include "main.h" PYBIND11_MODULE(oead, m) { oead::bind::BindCommonTypes(m); oead::bind::BindAamp(m); oead::bind::BindByml(m); oead::bind::BindGsheet(m); oead::bind::BindSarc(m); oead::bind::BindYaz0(m); }
970
C++
.cpp
28
32.5
71
0.733759
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,009
py_gsheet.cpp
zeldamods_oead/py/py_gsheet.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <oead/gsheet.h> #include <vector> #include "main.h" OEAD_MAKE_OPAQUE("oead.gsheet.FieldArray", std::vector<oead::gsheet::Field>) OEAD_MAKE_OPAQUE("oead.gsheet.Struct", oead::gsheet::Data::Struct) OEAD_MAKE_OPAQUE("oead.gsheet.StructArray", std::vector<oead::gsheet::Data::Struct>) OEAD_MAKE_VARIANT_CASTER(oead::gsheet::Data::Variant) namespace pybind11::detail { struct oead_gsheet_data_caster { using value_conv = make_caster<oead::gsheet::Data::Variant>; template <typename T_> static handle cast(T_&& src, return_value_policy policy, handle parent) { return value_conv::cast(src.v, policy, parent); } bool load(handle src, bool convert) { value_conv inner_caster; if (!inner_caster.load(src, convert)) return false; value.v = std::move(cast_op<oead::gsheet::Data::Variant&&>(std::move(inner_caster))); return true; } PYBIND11_TYPE_CASTER(oead::gsheet::Data, value_conv::name); }; template <> struct type_caster<oead::gsheet::Data> : oead_gsheet_data_caster {}; } // namespace pybind11::detail namespace oead::bind { void BindGsheet(py::module& parent) { py::module m = parent.def_submodule("gsheet"); auto Field = py::class_<gsheet::Field>(m, "Field", "Grezzo datasheet field."); BindVector<std::vector<gsheet::Field>>(m, "FieldArray"); py::enum_<gsheet::Field::Type>(Field, "Type") .value("Struct", gsheet::Field::Type::Struct, "C/C++ style structure.") .value("Bool", gsheet::Field::Type::Bool, "Boolean.") .value("Int", gsheet::Field::Type::Int, "Signed 32-bit integer.") .value("Float", gsheet::Field::Type::Float, "Single-precision floating point number (binary32)..") .value("String", gsheet::Field::Type::String, "Null-terminated string."); py::enum_<gsheet::Field::Flag>(Field, "Flag") .value("IsNullable", gsheet::Field::Flag::IsNullable) .value("IsArray", gsheet::Field::Flag::IsArray) .value("IsKey", gsheet::Field::Flag::IsKey) .value("Unknown3", gsheet::Field::Flag::Unknown3) .value("IsEnum", gsheet::Field::Flag::IsEnum) .value("Unknown5", gsheet::Field::Flag::Unknown5); Field.def(py::init<>()) .def_readwrite("name", &gsheet::Field::name, "Name (must not be empty).") .def_readwrite("type_name", &gsheet::Field::type_name, "Type name.") .def_readwrite("type", &gsheet::Field::type, "Field type.") .def_readwrite("x11", &gsheet::Field::x11, "Unknown; depth level?") .def_property( "flags", [](gsheet::Field& self) { return self.flags.m_hex; }, [](gsheet::Field& self, u32 flags) { self.flags.m_hex = flags; }, "Flags.") .def_readwrite("offset_in_value", &gsheet::Field::offset_in_value, "Offset of this field in the value structure.") .def_readwrite( "inline_size", &gsheet::Field::inline_size, "Size of this field in the value structure. For strings and arrays, this is always 0x10.") .def_readwrite("data_size", &gsheet::Field::data_size, "Size of the field data. For strings and inline types (inline structs, ints, " "floats, bools,), this is the same as the inline size.") .def_readwrite("fields", &gsheet::Field::fields, "[For structs] Fields") .def("__repr__", [](const gsheet::Field& self) { return "<Field: {} {}>"_s.format(self.type_name, self.name); }); BindMap<gsheet::Data::Struct>(m, "Struct", "Grezzo datasheet struct. In this API, a Struct is represented as " "a dict-like object, with the field names as keys."); BindVector<std::vector<gsheet::Data::Struct>>(m, "StructArray", "A list of Struct elements."); m.attr("BoolArray") = parent.attr("BufferBool"); m.attr("IntArray") = parent.attr("BufferInt"); m.attr("FloatArray") = parent.attr("BufferF32"); m.attr("StringArray") = parent.attr("BufferString"); auto Sheet = py::class_<gsheet::SheetRw>(m, "Sheet", "Grezzo datasheet."); Sheet.def(py::init<>()) .def_readwrite("alignment", &gsheet::SheetRw::alignment) .def_readwrite("hash", &gsheet::SheetRw::hash) .def_readwrite("name", &gsheet::SheetRw::name) .def_readwrite("root_fields", &gsheet::SheetRw::root_fields) .def_readwrite("values", &gsheet::SheetRw::values) .def("__repr__", [](const gsheet::SheetRw& self) { return "<Datasheet: {}>"_s.format(self.name); }) .def("to_binary", &gsheet::SheetRw::ToBinary, "Convert the sheet to a binary datasheet."); m.def( "parse", [](std::vector<u8> data) { return gsheet::Sheet{data}.MakeRw(); }, "data"_a, "Parse a binary datasheet."); m.def( "test_roundtrip", [](std::vector<u8> data) { gsheet::Sheet sheet{data}; return sheet.MakeRw().ToBinary(); }, "data"_a, "Parse a binary datasheet and immediately dump it back for testing purposes."); } } // namespace oead::bind
5,679
C++
.cpp
113
44.522124
100
0.653381
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,010
py_yaz0.cpp
zeldamods_oead/py/py_yaz0.cpp
/** * Copyright (C) 2019 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #include <nonstd/span.h> #include <vector> #include <oead/errors.h> #include <oead/types.h> #include <oead/yaz0.h> #include "main.h" namespace oead::bind { void BindYaz0(py::module& parent) { auto m = parent.def_submodule("yaz0"); py::class_<yaz0::Header>(m, "Header") .def_readwrite("magic", &yaz0::Header::magic) .def_readwrite("uncompressed_size", &yaz0::Header::uncompressed_size) .def_readwrite("data_alignment", &yaz0::Header::data_alignment) .def_readwrite("reserved", &yaz0::Header::reserved); m.def("get_header", &yaz0::GetHeader, "data"_a); m.def( "decompress", [](tcb::span<const u8> src) { const auto header = yaz0::GetHeader(src); if (!header) throw InvalidDataError("Invalid Yaz0 header"); py::bytes dst_py{nullptr, header->uncompressed_size}; yaz0::Decompress(src, PyBytesToSpan(dst_py)); return dst_py; }, "data"_a); m.def( "decompress_unsafe", [](tcb::span<const u8> src) { py::bytes dst_py{nullptr, yaz0::GetHeader(src)->uncompressed_size}; yaz0::DecompressUnsafe(src, PyBytesToSpan(dst_py)); return dst_py; }, "data"_a); m.def("compress", &yaz0::Compress, "data"_a, "data_alignment"_a = 0, "level"_a = 7); } } // namespace oead::bind
2,040
C++
.cpp
55
32.727273
86
0.671899
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,011
py_sarc.cpp
zeldamods_oead/py/py_sarc.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <oead/sarc.h> #include "main.h" OEAD_MAKE_OPAQUE("FileMap", oead::SarcWriter::FileMap); namespace oead::bind { void BindSarc(py::module& m) { py::class_<Sarc> cl(m, "Sarc"); py::class_<Sarc::File> file_cl(m, "File"); cl.def(py::init<tcb::span<const u8>>(), "data"_a, py::keep_alive<1, 2>()) .def(py::self == py::self) .def("are_files_equal", &Sarc::AreFilesEqual) .def("get_num_files", &Sarc::GetNumFiles) .def("get_data_offset", &Sarc::GetDataOffset) .def("get_endianness", &Sarc::GetEndianness) .def("get_file", py::overload_cast<std::string_view>(&Sarc::GetFile, py::const_), "name"_a, py::keep_alive<0, 1>()) .def("get_file", py::overload_cast<u16>(&Sarc::GetFile, py::const_), "index"_a, py::keep_alive<0, 1>()) .def( "get_files", [](const Sarc& s) { return py::make_iterator(s.GetFiles().begin(), s.GetFiles().end()); }, py::keep_alive<0, 1>()) .def("guess_min_alignment", &Sarc::GuessMinAlignment); file_cl.def_readonly("name", &Sarc::File::name) .def_readonly("data", &Sarc::File::data) .def("__repr__", [](const Sarc::File& file) { return "Sarc.File({})"_s.format(file.name); }) .def("__str__", [](const Sarc::File& file) { return file.name; }); py::class_<SarcWriter> writer_cl(m, "SarcWriter"); py::enum_<SarcWriter::Mode>(writer_cl, "Mode") .value("Legacy", SarcWriter::Mode::Legacy) .value("New", SarcWriter::Mode::New); BindMap<SarcWriter::FileMap>(writer_cl, "FileMap"); writer_cl .def(py::init<util::Endianness, SarcWriter::Mode>(), "endian"_a = util::Endianness::Little, "mode"_a = SarcWriter::Mode::New) .def("write", &SarcWriter::Write, py::return_value_policy::move) .def("set_endianness", &SarcWriter::SetEndianness, "endian"_a) .def("set_min_alignment", &SarcWriter::SetMinAlignment, "alignment"_a) .def("add_alignment_requirement", &SarcWriter::AddAlignmentRequirement, "extension_without_dot"_a, "alignment"_a) .def("set_mode", &SarcWriter::SetMode, "mode"_a) .def_readwrite("files", &SarcWriter::m_files) .def_static("from_sarc", &SarcWriter::FromSarc, "archive"_a, py::return_value_policy::move); } } // namespace oead::bind
2,992
C++
.cpp
62
43.225806
100
0.64851
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,012
py_byml.cpp
zeldamods_oead/py/py_byml.cpp
/** * Copyright (C) 2019 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #include <functional> #include <map> #include <nonstd/span.h> #include <type_traits> #include <vector> #include <pybind11/operators.h> #include <pybind11/pybind11.h> #include <oead/byml.h> #include <oead/util/scope_guard.h> #include "main.h" OEAD_MAKE_OPAQUE("Array", oead::Byml::Array); OEAD_MAKE_OPAQUE("Hash", oead::Byml::Hash); OEAD_MAKE_VARIANT_CASTER(oead::Byml::Value); namespace pybind11::detail { template <> struct type_caster<oead::Byml> { using value_conv = make_caster<oead::Byml::Value>; template <typename T_> static handle cast(T_&& src, return_value_policy policy, handle parent) { return value_conv::cast(src.GetVariant(), policy, parent); } bool load(handle src, bool convert) { value_conv inner_caster; if (!inner_caster.load(src, convert)) return false; value.GetVariant() = std::move(cast_op<oead::Byml::Value&&>(std::move(inner_caster))); return true; } PYBIND11_TYPE_CASTER(oead::Byml, make_caster<oead::Byml::Value::Storage>::name); }; } // namespace pybind11::detail namespace oead::bind { /// Wraps a callable to avoid expensive conversions to Byml; instead, we detect /// whether the first parameter is a Byml::Array or a Byml::Hash and if so we /// borrow the value and move-construct a temporary Byml in order to avoid copies. template <typename... Ts, typename Callable> static auto BorrowByml(Callable&& callable) { return [&, callable](py::handle handle, Ts&&... args) { Byml obj; const auto invoke = [&, callable](auto&& value) { obj = std::move(value); return std::invoke(callable, obj, std::forward<Ts>(args)...); }; if (py::isinstance<Byml::Array>(handle)) { auto& ref = handle.cast<Byml::Array&>(); util::ScopeGuard guard{[&] { ref = std::move(obj.Get<Byml::Type::Array>()); }}; return invoke(std::move(ref)); } if (py::isinstance<Byml::Hash>(handle)) { auto& ref = handle.cast<Byml::Hash&>(); util::ScopeGuard guard{[&] { ref = std::move(obj.Get<Byml::Type::Hash>()); }}; return invoke(std::move(ref)); } return invoke(handle.cast<Byml>()); }; } void BindByml(py::module& parent) { auto m = parent.def_submodule("byml"); m.def("from_binary", &Byml::FromBinary, "buffer"_a, py::return_value_policy::move, ":return: An Array or a Hash."); m.def("from_text", &Byml::FromText, "yml_text"_a, py::return_value_policy::move, ":return: An Array or a Hash."); m.def("to_binary", BorrowByml<bool, int>(&Byml::ToBinary), "data"_a, "big_endian"_a, "version"_a = 2); m.def("to_text", BorrowByml(&Byml::ToText), "data"_a); m.def("get_bool", BorrowByml(&Byml::GetBool), "data"_a); m.def("get_double", BorrowByml(&Byml::GetDouble), "data"_a); m.def("get_float", BorrowByml(&Byml::GetFloat), "data"_a); m.def("get_int", BorrowByml(&Byml::GetInt), "data"_a); m.def("get_int64", BorrowByml(&Byml::GetInt64), "data"_a); m.def("get_string", BorrowByml(py::overload_cast<>(&Byml::GetString, py::const_)), "data"_a); m.def("get_uint", BorrowByml(&Byml::GetUInt), "data"_a); m.def("get_uint64", BorrowByml(&Byml::GetUInt64), "data"_a); BindVector<Byml::Array>(m, "Array"); BindMap<Byml::Hash>(m, "Hash"); } } // namespace oead::bind
3,958
C++
.cpp
95
38.484211
95
0.678785
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,013
aamp.cpp
zeldamods_oead/src/aamp.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <oead/aamp.h> #include <absl/container/inlined_vector.h> #include <absl/strings/str_format.h> #include <algorithm> #include <array> #include <limits> #include <queue> #include "absl/container/flat_hash_set.h" #include <oead/errors.h> #include <oead/util/binary_reader.h> #include <oead/util/bit_utils.h> #include <oead/util/iterator_utils.h> #include <oead/util/type_utils.h> namespace oead::aamp { constexpr std::array<char, 4> HeaderMagic = {'A', 'A', 'M', 'P'}; enum class HeaderFlag : u32 { LittleEndian = 1 << 0, Utf8 = 1 << 1, }; struct ResHeader { std::array<char, 4> magic; util::LeInt<u32> version; util::Flags<HeaderFlag> flags; util::LeInt<u32> file_size; util::LeInt<u32> pio_version; /// Offset to parameter IO (relative to 0x30) util::LeInt<u32> offset_to_pio; /// Number of lists (including parameter IO) util::LeInt<u32> num_lists; util::LeInt<u32> num_objects; util::LeInt<u32> num_parameters; util::LeInt<u32> data_section_size; util::LeInt<u32> string_section_size; util::LeInt<u32> unk_section_size; }; static_assert(sizeof(ResHeader) == 0x30); template <typename T, size_t Factor = 4> struct CompactOffset { static constexpr size_t MaxDistance = [] { if constexpr (util::IsAnyOfType<T, U24<false>, U24<true>>()) return Factor * (1 << 24); else return Factor * std::numeric_limits<typename NumberType<T>::type>::max(); }(); constexpr CompactOffset() = default; constexpr CompactOffset(size_t value) { Set(value); } constexpr size_t Get() const { return size_t(raw_value) * Factor; } constexpr void Set(size_t x) { if (x % Factor != 0 || x > MaxDistance) throw std::invalid_argument("Offset is not representable"); raw_value = x / Factor; } private: T raw_value; }; struct ResParameter { util::LeInt<u32> name_crc32; CompactOffset<U24<false>> data_rel_offset; Parameter::Type type; }; static_assert(sizeof(ResParameter) == 8); struct ResParameterObj { util::LeInt<u32> name_crc32; CompactOffset<util::LeInt<u16>> parameters_rel_offset; util::LeInt<u16> num_parameters; }; static_assert(sizeof(ResParameterObj) == 8); struct ResParameterList { util::LeInt<u32> name_crc32; CompactOffset<util::LeInt<u16>> lists_rel_offset; util::LeInt<u16> num_lists; CompactOffset<util::LeInt<u16>> objects_rel_offset; util::LeInt<u16> num_objects; }; static_assert(sizeof(ResParameterList) == 0xc); class Parser { public: Parser(tcb::span<const u8> data) : m_reader{data, util::Endianness::Little} { if (data.size() < sizeof(ResHeader)) throw InvalidDataError("Invalid header"); if (m_reader.Read<decltype(ResHeader::magic)>() != HeaderMagic) throw InvalidDataError("Invalid magic"); const auto version = *m_reader.Read<u32>(offsetof(ResHeader, version)); if (version != 2) throw InvalidDataError("Only version 2 parameter archives are supported"); auto flags = *m_reader.Read<util::Flags<HeaderFlag>>(offsetof(ResHeader, flags)); if (!flags[HeaderFlag::LittleEndian]) throw InvalidDataError("Only little endian parameter archives are supported"); if (!flags[HeaderFlag::Utf8]) throw InvalidDataError("Only UTF-8 parameter archives are supported"); } ParameterIO Parse() { const auto offset_to_pio = *m_reader.Read<u32>(offsetof(ResHeader, offset_to_pio)); auto&& [root_name, root] = ParseList(sizeof(ResHeader) + offset_to_pio); if (root_name != ParameterIO::ParamRootKey.hash) throw InvalidDataError("No param_root"); ParameterIO pio; pio.version = *m_reader.Read<u32>(offsetof(ResHeader, pio_version)); pio.type = m_reader.ReadString(sizeof(ResHeader)); pio.objects = std::move(root.objects); pio.lists = std::move(root.lists); return pio; } private: std::pair<u32, Parameter> ParseParameter(u32 offset) { const auto info = m_reader.Read<ResParameter>(offset).value(); const auto crc32 = info.name_crc32; const auto data_offset = offset + info.data_rel_offset.Get(); switch (info.type) { case Parameter::Type::Bool: return {crc32, m_reader.Read<u32>(data_offset).value() != 0}; case Parameter::Type::F32: // There's some trickery going on in the parse function -- floats can // in some cases get multiplied by some factor. // That is currently ignored and the data is loaded as is. return {crc32, m_reader.Read<f32>(data_offset).value()}; case Parameter::Type::Int: return {crc32, m_reader.Read<int>(data_offset).value()}; case Parameter::Type::Vec2: return {crc32, m_reader.Read<Vector2f>(data_offset).value()}; case Parameter::Type::Vec3: return {crc32, m_reader.Read<Vector3f>(data_offset).value()}; case Parameter::Type::Vec4: return {crc32, m_reader.Read<Vector4f>(data_offset).value()}; case Parameter::Type::Color: return {crc32, m_reader.Read<Color4f>(data_offset).value()}; case Parameter::Type::String32: return {crc32, FixedSafeString<32>(m_reader.ReadString(data_offset, 32))}; case Parameter::Type::String64: return {crc32, FixedSafeString<64>(m_reader.ReadString(data_offset, 64))}; case Parameter::Type::Curve1: return {crc32, m_reader.Read<std::array<Curve, 1>>(data_offset).value()}; case Parameter::Type::Curve2: return {crc32, m_reader.Read<std::array<Curve, 2>>(data_offset).value()}; case Parameter::Type::Curve3: return {crc32, m_reader.Read<std::array<Curve, 3>>(data_offset).value()}; case Parameter::Type::Curve4: return {crc32, m_reader.Read<std::array<Curve, 4>>(data_offset).value()}; case Parameter::Type::BufferInt: return {crc32, ParseBuffer<int>(data_offset)}; case Parameter::Type::BufferF32: return {crc32, ParseBuffer<f32>(data_offset)}; case Parameter::Type::String256: return {crc32, FixedSafeString<256>(m_reader.ReadString(data_offset, 256))}; case Parameter::Type::Quat: // Quat parameters receive additional processing after being loaded: // depending on what parameters are passed to the apply function, // there may be linear interpolation going on. // That is also being ignored by this implementation. return {crc32, m_reader.Read<Quatf>(data_offset).value()}; case Parameter::Type::U32: return {crc32, m_reader.Read<U32>(data_offset).value()}; case Parameter::Type::BufferU32: return {crc32, ParseBuffer<u32>(data_offset)}; case Parameter::Type::BufferBinary: return {crc32, ParseBuffer<u8>(data_offset)}; case Parameter::Type::StringRef: return {crc32, m_reader.ReadString(data_offset)}; default: throw InvalidDataError("Unexpected parameter type"); } } template <typename T> std::vector<T> ParseBuffer(u32 data_offset) { const size_t size = m_reader.Read<u32>(data_offset - 4).value(); std::vector<T> buffer; buffer.reserve(size); for (size_t i = 0; i < size; ++i) buffer.emplace_back(m_reader.Read<T>().value()); return buffer; } std::pair<u32, ParameterObject> ParseObject(u32 offset) { const auto info = m_reader.Read<ResParameterObj>(offset).value(); const auto offset_to_params = offset + info.parameters_rel_offset.Get(); ParameterObject object; object.params.reserve(info.num_parameters); for (size_t i = 0; i < info.num_parameters; ++i) object.params.emplace(ParseParameter(offset_to_params + sizeof(ResParameter) * i)); return {info.name_crc32, std::move(object)}; } std::pair<u32, ParameterList> ParseList(u32 offset) { const auto info = m_reader.Read<ResParameterList>(offset).value(); const auto offset_to_lists = offset + info.lists_rel_offset.Get(); const auto offset_to_objects = offset + info.objects_rel_offset.Get(); ParameterList list; list.lists.reserve(info.num_lists); list.objects.reserve(info.num_objects); for (size_t i = 0; i < info.num_lists; ++i) list.lists.emplace(ParseList(offset_to_lists + sizeof(ResParameterList) * i)); for (size_t i = 0; i < info.num_objects; ++i) list.objects.emplace(ParseObject(offset_to_objects + sizeof(ResParameterObj) * i)); return {info.name_crc32, std::move(list)}; } util::BinaryReader m_reader; }; template <typename T, typename T2> static void WriteBuffer(util::BinaryWriterBase<T2>& writer, const std::vector<T>& v) { writer.Write(u32(v.size())); for (const auto& x : v) writer.Write(x); } struct WriteContext { public: void WriteLists(const ParameterIO& pio) { const auto write = [&](auto self, const ParameterList& list) -> void { WriteOffsetForParent(list, offsetof(ResParameterList, lists_rel_offset)); for (const auto& pair : list.lists) WriteList(pair.first, pair.second); for (const auto& pair : list.lists) self(self, pair.second); }; WriteList(ParameterIO::ParamRootKey, pio); write(write, pio); } void WriteObjects(const ParameterList& list) { // Perform a DFS on the parameter tree. Objects are handled before lists. WriteOffsetForParent(list, offsetof(ResParameterList, objects_rel_offset)); for (const auto& [object_name, object] : list.objects) WriteObject(object_name, object); for (const auto& [child_list_name, child_list] : list.lists) WriteObjects(child_list); } void WriteParameters(const ParameterList& list) { // Perform a DFS on the parameter tree. Objects are handled after lists. for (const auto& [child_list_name, child_list] : list.lists) WriteParameters(child_list); for (const auto& [object_name, object] : list.objects) { WriteOffsetForParent(object, offsetof(ResParameterObj, parameters_rel_offset)); for (const auto& [name, param] : object.params) { WriteParameter(name, param); } } } void CollectParameters(const ParameterIO& pio) { // For some reason, the order in which parameter data is serialized is not the order // of parameter objects or even parameters... Rather, for the majority of binary // parameter archives the order is determined with a rather convoluted algorithm: // // * First, process all of the parameter IO's objects (i.e. add all their parameters // to the parameter queue). // * Recursively collect all objects for child lists. For lists, object processing // happens after recursively processing child lists; however every 2 lists one // object from the parent list is processed. // const auto do_collect = [this](auto next, const ParameterList& list, bool process_top_objects_first) -> void { auto object_it = list.objects.begin(); const auto process_one_object = [this, &object_it] { for (const auto& [name, param] : object_it->second.params) { if (IsStringType(param.GetType())) string_parameters_to_write.emplace_back(param); else parameters_to_write.emplace_back(param); } ++object_it; }; // If the parameter IO is a Breath of the Wild AIProgram, then it appears that // even the parameter IO's objects are processed after child lists. // This is likely a hack, but it does match observations... const bool is_botw_aiprog = !list.objects.empty() && list.objects.begin()->first == Name("DemoAIActionIdx"); if (process_top_objects_first && !is_botw_aiprog) { // Again this is probably a hack but it is required for matching BoneControl documents... for (size_t i = 0; i < 7 && object_it != list.objects.end(); ++i) process_one_object(); } size_t i = 0; for (const auto& [child_list_name, child_list] : list.lists) { if (!is_botw_aiprog && i % 2 == 0 && object_it != list.objects.end()) process_one_object(); next(next, child_list, false); ++i; } // Process all remaining objects. while (object_it != list.objects.end()) process_one_object(); }; do_collect(do_collect, pio, true); } void WriteDataSection() { const size_t lookup_start_offset = writer.Tell(); for (const Parameter& param : parameters_to_write) WriteParameterData(param, lookup_start_offset); writer.AlignUp(4); } void WriteStringSection() { for (const Parameter& param : string_parameters_to_write) WriteString(param); writer.AlignUp(4); } void WriteParameterData(const Parameter& param, size_t lookup_start_offset) { if (IsStringType(param.GetType())) throw std::logic_error("WriteParameterData called with string parameter"); // Write to a temporary buffer first to try to reuse existing data. util::BinaryWriterBase<absl::InlinedVector<u8, 0x200>> temp_writer{writer.Endian()}; util::Match( param.GetVariant().v, // [&](bool v) { temp_writer.Write<u32>(v); }, [&](const std::vector<int>& v) { WriteBuffer(temp_writer, v); }, [&](const std::vector<f32>& v) { WriteBuffer(temp_writer, v); }, [&](const std::vector<u32>& v) { WriteBuffer(temp_writer, v); }, [&](const std::vector<u8>& v) { WriteBuffer(temp_writer, v); }, [&](const auto& v) { temp_writer.Write(v); }); const size_t parent_offset = offsets.at(&param); size_t data_offset = writer.Tell() + (IsBufferType(param.GetType()) ? 4 : 0); bool found = false; for (size_t offset = lookup_start_offset; offset + temp_writer.Buffer().size() <= writer.Buffer().size() && offset - parent_offset < (1 << 24) * 4; offset += 4) { if (std::equal(temp_writer.Buffer().begin(), temp_writer.Buffer().end(), writer.Buffer().begin() + offset)) { data_offset = offset; found = true; break; } } // Write the data offset in the parent parameter structure. writer.RunAt(parent_offset + offsetof(ResParameter, data_rel_offset), [&](size_t) { writer.Write( static_cast<decltype(ResParameter::data_rel_offset)>(data_offset - parent_offset)); }); // Write the parameter data if it hasn't already been written. if (!found) { writer.WriteBytes(temp_writer.Buffer()); writer.AlignUp(4); } } void WriteString(const Parameter& param) { const size_t parent_offset = offsets.at(&param); const std::string_view string = param.GetStringView(); const auto pair = string_offsets.emplace(string, u32(writer.Tell())); // Write the data offset in the parent parameter structure. writer.RunAt(parent_offset + offsetof(ResParameter, data_rel_offset), [&](size_t) { writer.Write( static_cast<decltype(ResParameter::data_rel_offset)>(pair.first->second - parent_offset)); }); // Write the parameter data if it hasn't already been written. if (pair.second) { writer.WriteCStr(string); writer.AlignUp(4); } } void WriteList(Name name, const ParameterList& list) { offsets.emplace(&list, u32(writer.Tell())); ++num_lists; ResParameterList data; data.name_crc32 = name.hash; data.num_lists = u16(list.lists.size()); data.num_objects = u16(list.objects.size()); writer.Write(data); } void WriteObject(Name name, const ParameterObject& object) { offsets.emplace(&object, u32(writer.Tell())); ++num_objects; ResParameterObj data; data.name_crc32 = name.hash; data.num_parameters = u16(object.params.size()); writer.Write(data); } void WriteParameter(Name name, const Parameter& parameter) { offsets.emplace(&parameter, u32(writer.Tell())); ++num_parameters; ResParameter data; data.name_crc32 = name.hash; data.type = parameter.GetType(); writer.Write(data); } template <typename T> void WriteOffsetForParent(const T& parent, size_t offset_in_parent_struct) { const u32 parent_offset = offsets.at(&parent); writer.WriteCurrentOffsetAt<CompactOffset<util::LeInt<u16>>>( parent_offset + offset_in_parent_struct, parent_offset); } util::BinaryWriter writer{util::Endianness::Little}; u32 num_lists = 0; u32 num_objects = 0; u32 num_parameters = 0; /// Parameters in serialization order. std::vector<std::reference_wrapper<const Parameter>> parameters_to_write; std::vector<std::reference_wrapper<const Parameter>> string_parameters_to_write; /// Used to find where a structure (ResParameter...) is located in the buffer. absl::flat_hash_map<const void*, u32> offsets; absl::flat_hash_map<std::string_view, u32> string_offsets; }; ParameterIO ParameterIO::FromBinary(tcb::span<const u8> data) { Parser parser{data}; return parser.Parse(); } std::vector<u8> ParameterIO::ToBinary() const { WriteContext ctx; ctx.writer.Seek(sizeof(ResHeader)); ctx.writer.WriteCStr(type); ctx.writer.AlignUp(4); const size_t offset_to_pio = ctx.writer.Tell(); ctx.WriteLists(*this); ctx.WriteObjects(*this); ctx.CollectParameters(*this); ctx.WriteParameters(*this); const size_t data_section_begin = ctx.writer.Tell(); ctx.WriteDataSection(); const size_t string_section_begin = ctx.writer.Tell(); ctx.WriteStringSection(); const size_t unk_section_begin = ctx.writer.Tell(); ctx.writer.AlignUp(4); ctx.writer.GrowBuffer(); ResHeader header{}; header.magic = HeaderMagic; header.version = 2; header.flags[HeaderFlag::LittleEndian] = true; header.flags[HeaderFlag::Utf8] = true; header.file_size = ctx.writer.Tell(); header.pio_version = version; header.offset_to_pio = u32(offset_to_pio - sizeof(ResHeader)); header.num_lists = ctx.num_lists; header.num_objects = ctx.num_objects; header.num_parameters = ctx.num_parameters; header.data_section_size = string_section_begin - data_section_begin; header.string_section_size = unk_section_begin - string_section_begin; header.unk_section_size = 0; ctx.writer.Seek(0); ctx.writer.Write(header); return ctx.writer.Finalize(); } std::string_view Parameter::GetStringView() const { if (!IsStringType(GetType())) throw TypeError("GetStringView called with non-string parameter"); return util::Match(GetVariant().v, [](const auto& v) -> std::string_view { if constexpr (std::is_convertible<decltype(v), std::string_view>()) return Str(v); else std::terminate(); }); } } // namespace oead::aamp
19,105
C++
.cpp
453
37.333333
100
0.685799
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,014
yaz0.cpp
zeldamods_oead/src/yaz0.cpp
/** * Copyright (C) 2019 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <bitset> #include <cstring> #include <zlib-ng.h> #include <oead/util/binary_reader.h> #include <oead/yaz0.h> namespace oead::yaz0 { constexpr std::array<char, 4> Magic = {'Y', 'a', 'z', '0'}; constexpr size_t ChunksPerGroup = 8; constexpr size_t MaximumMatchLength = 0xFF + 0x12; static std::optional<Header> GetHeader(util::BinaryReader& reader) { const auto header = reader.Read<Header>(); if (!header) return std::nullopt; if (header->magic != Magic) return std::nullopt; return header; } std::optional<Header> GetHeader(tcb::span<const u8> data) { util::BinaryReader reader{data, util::Endianness::Big}; return GetHeader(reader); } namespace { class GroupWriter { public: GroupWriter(std::vector<u8>& result) : m_result{result} { Reset(); } void HandleZlibMatch(u32 dist, u32 lc) { if (dist == 0) { // Literal. m_group_header.set(7 - m_pending_chunks); m_result.push_back(u8(lc)); } else { // Back reference. constexpr u32 ZlibMinMatch = 3; WriteMatch(dist - 1, lc + ZlibMinMatch); } ++m_pending_chunks; if (m_pending_chunks == ChunksPerGroup) { m_result[m_group_header_offset] = u8(m_group_header.to_ulong()); Reset(); } } // Must be called after zlib has completed to ensure the last group is written. void Finalise() { if (m_pending_chunks != 0) m_result[m_group_header_offset] = u8(m_group_header.to_ulong()); } private: void Reset() { m_pending_chunks = 0; m_group_header.reset(); m_group_header_offset = m_result.size(); m_result.push_back(0xFF); } void WriteMatch(u32 distance, u32 length) { if (length < 18) { m_result.push_back(((length - 2) << 4) | u8(distance >> 8)); m_result.push_back(u8(distance)); } else { // If the match is longer than 18 bytes, 3 bytes are needed to write the match. const size_t actual_length = std::min<size_t>(MaximumMatchLength, length); m_result.push_back(u8(distance >> 8)); m_result.push_back(u8(distance)); m_result.push_back(u8(actual_length - 0x12)); } } std::vector<u8>& m_result; size_t m_pending_chunks; std::bitset<8> m_group_header; std::size_t m_group_header_offset; }; } // namespace std::vector<u8> Compress(tcb::span<const u8> src, u32 data_alignment, int level) { util::BinaryWriter writer{util::Endianness::Big}; writer.Buffer().reserve(src.size()); // Write the header. Header header; header.magic = Magic; header.uncompressed_size = u32(src.size()); header.data_alignment = data_alignment; header.reserved.fill(0); writer.Write(header); GroupWriter group_writer{writer.Buffer()}; // Let zlib do the heavy lifting. std::array<u8, 8> dummy{}; size_t dummy_size = dummy.size(); const int ret = zng_compress2( dummy.data(), &dummy_size, src.data(), src.size(), std::clamp<int>(level, 6, 9), [](void* w, u32 dist, u32 lc) { static_cast<GroupWriter*>(w)->HandleZlibMatch(dist, lc); }, &group_writer); if (ret != Z_OK) throw std::runtime_error("zng_compress failed"); group_writer.Finalise(); return writer.Finalize(); } std::vector<u8> Decompress(tcb::span<const u8> src) { const auto header = GetHeader(src); if (!header) return {}; std::vector<u8> result(header->uncompressed_size); Decompress(src, result); return result; } template <bool Safe> static void Decompress(tcb::span<const u8> src, tcb::span<u8> dst) { util::BinaryReader reader{src, util::Endianness::Big}; reader.Seek(sizeof(Header)); u8 group_header = 0; size_t remaining_chunks = 0; for (auto dst_it = dst.begin(); dst_it < dst.end();) { if (remaining_chunks == 0) { group_header = reader.Read<u8, Safe>().value(); remaining_chunks = ChunksPerGroup; } if (group_header & 0x80) { *dst_it++ = reader.Read<u8, Safe>().value(); } else { const u16 pair = reader.Read<u16, Safe>().value(); const size_t distance = (pair & 0x0FFF) + 1; const size_t length = ((pair >> 12) ? (pair >> 12) : (reader.Read<u8, Safe>().value() + 16)) + 2; const u8* base = dst_it - distance; if (base < dst.begin() || dst_it + length > dst.end()) { throw std::invalid_argument("Copy is out of bounds"); } for (size_t i = 0; i < length; ++i) *dst_it++ = base[i]; } group_header <<= 1; remaining_chunks -= 1; } } void Decompress(tcb::span<const u8> src, tcb::span<u8> dst) { Decompress<true>(src, dst); } void DecompressUnsafe(tcb::span<const u8> src, tcb::span<u8> dst) { Decompress<false>(src, dst); } } // namespace oead::yaz0
5,401
C++
.cpp
157
30.566879
97
0.662002
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,015
byml_text.cpp
zeldamods_oead/src/byml_text.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <absl/algorithm/container.h> #include <absl/strings/escaping.h> #include <absl/strings/str_format.h> #include <c4/std/string.hpp> #include <ryml.hpp> #include "../lib/libyaml/include/yaml.h" #include <oead/byml.h> #include <oead/util/iterator_utils.h> #include <oead/util/type_utils.h> #include <oead/util/variant_utils.h> #include "yaml.h" namespace oead { namespace byml { static bool IsBinaryTag(std::string_view tag) { return util::IsAnyOf(tag, "tag:yaml.org,2002:binary", "!!binary"); } static std::optional<yml::TagBasedType> RecognizeTag(const std::string_view tag) { if (util::IsAnyOf(tag, "!f64")) return yml::TagBasedType::Float; if (util::IsAnyOf(tag, "!u", "!l", "!ul")) return yml::TagBasedType::Int; if (IsBinaryTag(tag)) return yml::TagBasedType::Str; return std::nullopt; } static Byml ScalarToValue(std::string_view tag, yml::Scalar&& scalar) { return util::Match( std::move(scalar), [](std::nullptr_t) -> Byml { return Byml::Null{}; }, [](bool value) -> Byml { return value; }, [&](std::string&& value) -> Byml { if (IsBinaryTag(tag)) { std::string decoded; if (!absl::Base64Unescape(value, &decoded)) throw InvalidDataError("Invalid base64-encoded data"); return Byml{std::vector<u8>(decoded.begin(), decoded.end())}; } return Byml{std::move(value)}; }, [&](u64 value) -> Byml { if (tag == "!u") return U32(value); if (tag == "!l") return S64(value); if (tag == "!ul") return U64(value); return S32(value); }, [&](f64 value) -> Byml { if (tag == "!f64") return F64(value); return F32(value); }); } static bool ShouldUseInlineYamlStyle(const Byml& container) { const auto is_simple = [](const Byml& item) { return !util::IsAnyOf(item.GetType(), Byml::Type::Array, Byml::Type::Hash); }; switch (container.GetType()) { case Byml::Type::Array: return container.GetArray().size() <= 10 && absl::c_all_of(container.GetArray(), is_simple); case Byml::Type::Hash: return container.GetHash().size() <= 10 && absl::c_all_of(container.GetHash(), [&](const auto& p) { return is_simple(p.second); }); default: return false; } } Byml ParseYamlNode(const c4::yml::NodeRef& node) { if (!node.valid()) throw InvalidDataError("Invalid YAML node"); if (node.is_seq()) { auto array = Byml::Array{}; array.reserve(node.num_children()); for (const auto& child : node) { array.emplace_back(ParseYamlNode(child)); } return Byml{std::move(array)}; } if (node.is_map()) { auto hash = Byml::Hash{}; for (const auto& child : node) { std::string key{yml::RymlSubstrToStrView(child.key())}; Byml value = ParseYamlNode(child); hash.emplace(std::move(key), std::move(value)); } return Byml{std::move(hash)}; } if (node.has_val()) { return byml::ScalarToValue(yml::RymlGetValTag(node), yml::ParseScalar(node, byml::RecognizeTag)); } throw InvalidDataError("Failed to parse YAML node"); } } // namespace byml Byml Byml::FromText(std::string_view yml_text) { yml::InitRymlIfNeeded(); ryml::Tree tree = ryml::parse(yml::StrViewToRymlSubstr(yml_text)); return byml::ParseYamlNode(tree.rootref()); } std::string Byml::ToText() const { yml::LibyamlEmitterWithStorage<std::string> emitter; yaml_event_t event; yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING); emitter.Emit(event); yaml_document_start_event_initialize(&event, nullptr, nullptr, nullptr, 1); emitter.Emit(event); const auto emit = [&](auto self, const Byml& node) -> void { util::Match( node.GetVariant().v, [&](Null) { emitter.EmitNull(); }, [&](const String& v) { emitter.EmitString(v); }, [&](const std::vector<u8>& v) { const std::string encoded = absl::Base64Escape(std::string_view((const char*)v.data(), v.size())); emitter.EmitString(encoded, "tag:yaml.org,2002:binary"); }, [&](const Array& v) { yaml_event_t event; const auto style = byml::ShouldUseInlineYamlStyle(v) ? YAML_FLOW_SEQUENCE_STYLE : YAML_BLOCK_SEQUENCE_STYLE; yaml_sequence_start_event_initialize(&event, nullptr, nullptr, 1, style); emitter.Emit(event); for (const Byml& item : v) self(self, item); yaml_sequence_end_event_initialize(&event); emitter.Emit(event); }, [&](const Hash& v) { const auto style = byml::ShouldUseInlineYamlStyle(v) ? YAML_FLOW_MAPPING_STYLE : YAML_BLOCK_MAPPING_STYLE; yml::LibyamlEmitter::MappingScope scope{emitter, {}, style}; for (const auto& [k, v] : v) { emitter.EmitString(k); self(self, v); } }, [&](bool v) { emitter.EmitBool(v); }, // [&](S32 v) { emitter.EmitInt(v); }, // [&](F32 v) { emitter.EmitFloat(v); }, // [&](U32 v) { emitter.EmitScalar(absl::StrFormat("0x%08x", v), false, false, "!u"); }, [&](S64 v) { emitter.EmitInt(v, "!l"); }, // [&](U64 v) { emitter.EmitInt(v, "!ul"); }, // [&](F64 v) { emitter.EmitDouble(v, "!f64"); }); }; emit(emit, *this); yaml_document_end_event_initialize(&event, 1); emitter.Emit(event); yaml_stream_end_event_initialize(&event); emitter.Emit(event); return std::move(emitter.GetOutput()); } } // namespace oead
6,414
C++
.cpp
169
31.680473
99
0.614531
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,016
yaml.cpp
zeldamods_oead/src/yaml.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include "yaml.h" #include <absl/strings/match.h> #include <absl/strings/numbers.h> #include <absl/strings/str_format.h> #include <mutex> #include <c4/error.hpp> #include <ryml.hpp> #include <oead/errors.h> #include <oead/util/iterator_utils.h> namespace oead::yml { using namespace std::string_view_literals; std::string FormatFloat(float value) { std::string repr = absl::StrFormat("%.9g", value); if (!absl::StrContains(repr, ".") && !absl::StrContains(repr, "e")) repr += ".0"sv; return repr; } std::string FormatDouble(double value) { std::string repr = absl::StrFormat("%.17g", value); if (!absl::StrContains(repr, ".") && !absl::StrContains(repr, "e")) repr += ".0"sv; return repr; } static bool IsInfinity(std::string_view input) { return util::IsAnyOf(input, ".inf", ".Inf", ".INF") || util::IsAnyOf(input, "+.inf", "+.Inf", "+.INF"); } static bool IsNegativeInfinity(std::string_view input) { return util::IsAnyOf(input, "-.inf", "-.Inf", "-.INF"); } static bool IsNaN(std::string_view input) { return util::IsAnyOf(input, ".nan", ".NaN", ".NAN"); } static std::optional<TagBasedType> GetTagBasedType(const std::string_view tag, TagRecognizer recognizer) { if (tag.empty()) return std::nullopt; if (tag == "tag:yaml.org,2002:str") return TagBasedType::Str; if (tag == "tag:yaml.org,2002:float") return TagBasedType::Float; if (tag == "tag:yaml.org,2002:int") return TagBasedType::Int; if (tag == "tag:yaml.org,2002:bool") return TagBasedType::Bool; if (tag == "tag:yaml.org,2002:null") return TagBasedType::Null; if (const auto type = recognizer(tag)) return type; return std::nullopt; } // Deliberately not compliant to the YAML 1.2 standard to get rid of unused features // that harm performance. Scalar ParseScalar(const std::string_view tag, const std::string_view value, bool is_quoted, TagRecognizer recognizer) { const auto tag_type = GetTagBasedType(tag, recognizer); if (tag_type == TagBasedType::Bool || util::IsAnyOf(value, "true", "false")) return value[0] == 't'; // Floating-point conversions. const bool is_possible_double = absl::StrContains(value, "."); if (tag_type == TagBasedType::Float || (!tag_type && is_possible_double && !is_quoted)) { if (IsInfinity(value)) return std::numeric_limits<double>::infinity(); if (IsNegativeInfinity(value)) return -std::numeric_limits<double>::infinity(); if (IsNaN(value)) return std::numeric_limits<double>::quiet_NaN(); double maybe_double; if (absl::SimpleAtod(value, &maybe_double)) return maybe_double; if (tag_type == TagBasedType::Float) throw ParseError("Failed to parse value that was explicitly marked as float"); } // Integer conversions. Not YAML 1.2 compliant: base 8 is not supported as it's not useful. if (tag_type == TagBasedType::Int || (!tag_type && !value.empty() && !is_quoted)) { char* int_str_end = nullptr; const u64 maybe_u64 = std::strtoull(value.data(), &int_str_end, 0); if (value.data() + value.size() == int_str_end) return maybe_u64; if (tag_type == TagBasedType::Int) throw ParseError("Failed to parse value that was explicitly marked as integer"); } if (tag_type == TagBasedType::Null || value == "null") return nullptr; // Fall back to treating the value as a string. return std::string(value); } bool StringNeedsQuotes(const std::string_view value) { if (util::IsAnyOf(value, "true", "false")) return true; const bool is_possible_double = absl::StrContains(value, "."); if (is_possible_double) { if (IsInfinity(value) || IsNegativeInfinity(value) || IsNaN(value)) return true; double maybe_double; if (absl::SimpleAtod(value, &maybe_double)) return true; } if (!value.empty()) { char* int_str_end = nullptr; std::strtoull(value.data(), &int_str_end, 0); if (value.data() + value.size() == int_str_end) return true; } if (value == "null") return true; return false; } Scalar ParseScalar(const ryml::NodeRef& node, TagRecognizer recognizer) { if (!node.valid()) throw InvalidDataError("Invalid YAML node for ParseScalar"); const std::string_view tag = RymlGetValTag(node); const std::string_view value = RymlSubstrToStrView(node.val()); const char* arena_start = node.tree()->arena().data(); bool is_quoted = false; const char* raw_string = node.val().data(); if (raw_string != nullptr && raw_string != arena_start) is_quoted = util::IsAnyOf(raw_string[-1], '\'', '"'); return ParseScalar(tag, value, is_quoted, recognizer); } Scalar ParseScalarKey(const ryml::NodeRef& node, TagRecognizer recognizer) { if (!node.valid()) throw InvalidDataError("Invalid YAML node for ParseScalarKey"); const std::string_view tag = RymlGetKeyTag(node); const std::string_view value = RymlSubstrToStrView(node.key()); const char* arena_start = node.tree()->arena().data(); bool is_quoted = false; const char* raw_string = node.key().data(); if (raw_string != nullptr && raw_string != arena_start) is_quoted = util::IsAnyOf(raw_string[-1], '\'', '"'); return ParseScalar(tag, value, is_quoted, recognizer); } void InitRymlIfNeeded() { static std::once_flag s_flag; std::call_once(s_flag, [] { ryml::Callbacks callbacks = ryml::get_callbacks(); callbacks.m_error = [](const char* msg, size_t msg_len, ryml::Location, void*) { throw RymlError("RymlError: " + std::string(msg, msg_len)); }; ryml::set_callbacks(callbacks); c4::set_error_callback([](const char* msg, size_t msg_size) { throw RymlError("RymlError (c4): " + std::string(msg, msg_size)); }); }); } LibyamlEmitter::LibyamlEmitter() { yaml_emitter_initialize(&m_emitter); yaml_emitter_set_unicode(&m_emitter, 1); yaml_emitter_set_width(&m_emitter, 120); } LibyamlEmitter::~LibyamlEmitter() { yaml_emitter_delete(&m_emitter); } void LibyamlEmitter::Emit(yaml_event_t& event, bool ignore_errors) { if (!yaml_emitter_emit(&m_emitter, &event) && !ignore_errors) { throw std::runtime_error("Emit failed: " + std::string(m_emitter.problem ? m_emitter.problem : "unknown")); } } } // namespace oead::yml
7,032
C++
.cpp
178
35.623596
93
0.677074
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,017
aamp_text.cpp
zeldamods_oead/src/aamp_text.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <absl/algorithm/container.h> #include <absl/strings/match.h> #include <absl/strings/str_format.h> #include <array> #include <tuple> #include <c4/std/string.hpp> #include <ryml.hpp> #include "../lib/libyaml/include/yaml.h" #include <cmrc/cmrc.hpp> #include <oead/aamp.h> #include <oead/errors.h> #include <oead/util/iterator_utils.h> #include <oead/util/string_utils.h> #include <oead/util/variant_utils.h> #include "yaml.h" CMRC_DECLARE(oead::res); namespace oead::aamp { NameTable::NameTable(bool with_botw_strings) { if (!with_botw_strings) return; const auto fs = cmrc::oead::res::get_filesystem(); const auto hashed_names_f = fs.open("data/botw_hashed_names.txt"); util::SplitStringByLine({hashed_names_f.begin(), hashed_names_f.size()}, [&](std::string_view name) { // No need to copy the string data since it is in the constant data // section of the executable. names.emplace(util::crc32(name), name); }); const auto numbered_names_f = fs.open("data/botw_numbered_names.txt"); util::SplitStringByLine({numbered_names_f.begin(), numbered_names_f.size()}, [&](std::string_view name) { numbered_names.emplace_back(name); }); } std::optional<std::string_view> NameTable::GetName(u32 hash, int index, u32 parent_name_hash) { using namespace std::string_view_literals; if (const auto it = names.find(hash); it != names.end()) return it->second; if (const auto it = owned_names.find(hash); it != owned_names.end()) return it->second; // Try to guess the name from the parent structure if possible. if (const auto it = names.find(parent_name_hash); it != names.end()) { const auto test_names = [&](std::string_view prefix) -> std::optional<std::string_view> { static const std::array formats{ absl::ParsedFormat<'s', 'd'>{"%s%d"}, absl::ParsedFormat<'s', 'd'>{"%s_%d"}, absl::ParsedFormat<'s', 'd'>{"%s%02d"}, absl::ParsedFormat<'s', 'd'>{"%s_%02d"}, absl::ParsedFormat<'s', 'd'>{"%s%03d"}, absl::ParsedFormat<'s', 'd'>{"%s_%03d"}, }; for (int i : {index, index + 1}) { for (const auto format : formats) { auto candidate = absl::StrFormat(format, prefix, i); if (util::crc32(candidate) == hash) return AddName(hash, std::move(candidate)); } } return std::nullopt; }; const std::string_view parent_name = it->second; if (const auto match = test_names(parent_name)) return *match; // Sometimes the parent name is plural and the object names are singular. if (const auto match = test_names("Children"sv)) return *match; if (const auto match = test_names("Child"sv)) return *match; for (std::string_view suffix : {"s"sv, "es"sv, "List"sv}) { if (!absl::EndsWith(parent_name, suffix)) continue; if (const auto match = test_names(parent_name.substr(0, parent_name.size() - suffix.size()))) return *match; } } // Last resort: test all numbered names. for (std::string_view name : numbered_names) { for (int i = 0; i < index + 2; ++i) { auto format = absl::ParsedFormat<'d'>::New(name); if (!format) break; auto candidate = absl::StrFormat(*format, i); if (util::crc32(candidate) == hash) return AddName(hash, std::move(candidate)); } } return std::nullopt; } std::string_view NameTable::AddName(u32 hash, std::string name) { const auto& [it, added] = owned_names.emplace(hash, std::move(name)); return it->second; } void NameTable::AddNameReference(std::string_view name) { names.emplace(util::crc32(name), name); } NameTable& GetDefaultNameTable() { static NameTable s_table{true}; return s_table; } static std::optional<oead::yml::TagBasedType> RecognizeTag(const std::string_view tag) { if (util::IsAnyOf(tag, "!str32", "!str64", "!str256")) return yml::TagBasedType::Str; if (util::IsAnyOf(tag, "!u")) return yml::TagBasedType::Int; return std::nullopt; } static Parameter ScalarToValue(std::string_view tag, yml::Scalar&& scalar) { return util::Match( std::move(scalar), [](bool value) -> Parameter { return value; }, [&](std::string&& value) -> Parameter { if (tag == "!str32") return FixedSafeString<32>(value); if (tag == "!str64") return FixedSafeString<64>(value); if (tag == "!str256") return FixedSafeString<256>(value); return Parameter{std::move(value)}; }, [&](u64 value) -> Parameter { if (tag == "!u") return U32(value); return int(value); }, [&](f64 value) -> Parameter { return float(value); }, [](std::nullptr_t) -> Parameter { throw InvalidDataError("Unexpected scalar type"); }); } template <typename T> static T ParseIntOrFloat(const ryml::NodeRef& node) { using YmlType = std::conditional_t<std::is_integral_v<T>, u64, f64>; return T(std::get<YmlType>(yml::ParseScalar(node, RecognizeTag))); } template <typename T> static T ReadSequenceForNumericalStruct(const ryml::NodeRef& node) { T value; auto fields = value.fields(); if (node.num_children() != std::tuple_size<decltype(fields)>()) throw InvalidDataError("Unexpected number of children"); auto child = node.children().begin(); std::apply( [&](auto&&... x) { ((x = ParseIntOrFloat<std::decay_t<decltype(x)>>(*child), ++child), ...); }, fields); return value; } template <typename T> static std::vector<T> ReadSequenceForBuffer(const ryml::NodeRef& node) { std::vector<T> vector; vector.reserve(node.num_children()); for (const auto& child : node) vector.emplace_back(ParseIntOrFloat<T>(child)); return vector; } template <size_t N> static std::array<oead::Curve, N> ReadSequenceForCurve(const ryml::NodeRef& node) { std::array<Curve, N> curves; size_t i = 0; for (Curve& curve : curves) { curve.a = ParseIntOrFloat<u32>(node[i++]); curve.b = ParseIntOrFloat<u32>(node[i++]); for (float& x : curve.floats) x = ParseIntOrFloat<f32>(node[i++]); } return curves; } Parameter ReadParameter(const ryml::NodeRef& node) { if (!node.valid()) throw InvalidDataError("Invalid YAML node for Parameter"); if (node.is_seq()) { const auto tag = yml::RymlSubstrToStrView(node.val_tag()); if (tag == "!vec2") return ReadSequenceForNumericalStruct<Vector2f>(node); if (tag == "!vec3") return ReadSequenceForNumericalStruct<Vector3f>(node); if (tag == "!vec4") return ReadSequenceForNumericalStruct<Vector4f>(node); if (tag == "!color") return ReadSequenceForNumericalStruct<Color4f>(node); if (tag == "!curve") { constexpr size_t NumElementsPerCurve = 32; switch (node.num_children()) { case 1 * NumElementsPerCurve: return ReadSequenceForCurve<1>(node); case 2 * NumElementsPerCurve: return ReadSequenceForCurve<2>(node); case 3 * NumElementsPerCurve: return ReadSequenceForCurve<3>(node); case 4 * NumElementsPerCurve: return ReadSequenceForCurve<4>(node); default: throw InvalidDataError("Invalid curve: unexpected number of children"); } } if (tag == "!buffer_int") return ReadSequenceForBuffer<int>(node); if (tag == "!buffer_f32") return ReadSequenceForBuffer<f32>(node); if (tag == "!buffer_u32") return ReadSequenceForBuffer<u32>(node); if (tag == "!buffer_binary") return ReadSequenceForBuffer<u8>(node); if (tag == "!quat") return ReadSequenceForNumericalStruct<Quatf>(node); throw InvalidDataError(absl::StrFormat("Unexpected sequence tag (or no tag): %s", tag)); } if (node.has_val()) return ScalarToValue(yml::RymlGetValTag(node), yml::ParseScalar(node, RecognizeTag)); throw InvalidDataError("Invalid parameter node"); } template <typename Fn, typename Map> static void ReadMap(const ryml::NodeRef& node, Map& map, Fn read_fn) { if (!node.valid()) throw InvalidDataError("Invalid YAML node for Map"); if (!node.is_map()) throw InvalidDataError("Expected map node"); for (const auto& child : node) { const auto key = yml::ParseScalarKey(child, RecognizeTag); auto structure = read_fn(child); if (const auto* hash = std::get_if<u64>(&key)) map.emplace(static_cast<u32>(*hash), std::move(structure)); else if (const auto* str = std::get_if<std::string>(&key)) map.emplace(*str, std::move(structure)); else throw InvalidDataError("Unexpected key scalar type"); } } ParameterObject ReadParameterObject(const ryml::NodeRef& node) { if (!node.valid()) throw InvalidDataError("Invalid YAML node for ParameterObject"); ParameterObject object; ReadMap(node, object.params, ReadParameter); return object; } ParameterList ReadParameterList(const ryml::NodeRef& node) { if (!node.valid()) throw InvalidDataError("Invalid YAML node for ParameterList"); ParameterList list; ReadMap(yml::RymlGetMapItem(node, "objects"), list.objects, ReadParameterObject); ReadMap(yml::RymlGetMapItem(node, "lists"), list.lists, ReadParameterList); return list; } ParameterIO ReadParameterIO(const ryml::NodeRef& node) { if (!node.valid()) throw InvalidDataError("Invalid YAML node for ParameterIO"); ParameterIO pio; pio.version = ParseIntOrFloat<u32>(yml::RymlGetMapItem(node, "version")); pio.type = std::move( std::get<std::string>(yml::ParseScalar(yml::RymlGetMapItem(node, "type"), RecognizeTag))); ParameterList param_root = ReadParameterList(yml::RymlGetMapItem(node, "param_root")); pio.objects = std::move(param_root.objects); pio.lists = std::move(param_root.lists); return pio; } ParameterIO ParameterIO::FromText(std::string_view yml_text) { yml::InitRymlIfNeeded(); ryml::Tree tree = ryml::parse(yml::StrViewToRymlSubstr(yml_text)); return ReadParameterIO(tree.rootref()); } class TextEmitter { public: std::string Emit(const ParameterIO& pio) { m_extra_name_table = {}; BuildExtraNameTable(pio); yaml_event_t event; yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING); emitter.Emit(event); yaml_document_start_event_initialize(&event, nullptr, nullptr, nullptr, 1); emitter.Emit(event); EmitParameterIO(pio); yaml_document_end_event_initialize(&event, 1); emitter.Emit(event); yaml_stream_end_event_initialize(&event); emitter.Emit(event); return std::move(emitter.GetOutput()); } private: /// Populates the extra name table with strings from the given parameter IO. void BuildExtraNameTable(const ParameterList& list) { for (const auto& [obj_name, obj] : list.objects) { for (const auto& [param_name, param] : obj.params) { if (IsStringType(param.GetType())) m_extra_name_table.AddNameReference(param.GetStringView()); } } for (const auto& [sub_list_name, sub_list] : list.lists) BuildExtraNameTable(sub_list); } void EmitName(Name name, int index, Name parent_name) { NameTable& table = GetDefaultNameTable(); if (const auto name_str = m_extra_name_table.GetName(name, index, parent_name)) emitter.EmitString(*name_str); else if (const auto name_str = table.GetName(name, index, parent_name)) emitter.EmitString(*name_str); else emitter.EmitInt(name); } void EmitParameter(const Parameter& param) { util::Match( param.GetVariant().v, // [&](bool v) { emitter.EmitBool(v); }, // [&](float v) { emitter.EmitFloat(v); }, // [&](int v) { emitter.EmitInt(v); }, // [&](const Vector2f& v) { emitter.EmitSimpleSequence(v.fields(), "!vec2"); }, [&](const Vector3f& v) { emitter.EmitSimpleSequence(v.fields(), "!vec3"); }, [&](const Vector4f& v) { emitter.EmitSimpleSequence(v.fields(), "!vec4"); }, [&](const Color4f& v) { emitter.EmitSimpleSequence(v.fields(), "!color"); }, [&](const FixedSafeString<32>& v) { emitter.EmitString(v, "!str32"); }, [&](const FixedSafeString<64>& v) { emitter.EmitString(v, "!str64"); }, [&](const std::array<Curve, 1>& v) { EmitCurves(v); }, [&](const std::array<Curve, 2>& v) { EmitCurves(v); }, [&](const std::array<Curve, 3>& v) { EmitCurves(v); }, [&](const std::array<Curve, 4>& v) { EmitCurves(v); }, [&](const std::vector<int>& v) { emitter.EmitSimpleSequence<int>(v, "!buffer_int"); }, [&](const std::vector<f32>& v) { emitter.EmitSimpleSequence<f32>(v, "!buffer_f32"); }, [&](const FixedSafeString<256>& v) { emitter.EmitString(v, "!str256"); }, [&](const Quatf& v) { emitter.EmitSimpleSequence(v.fields(), "!quat"); }, [&](U32 v) { emitter.EmitInt(v, "!u"); }, [&](const std::vector<u32>& v) { emitter.EmitSimpleSequence<u32>(v, "!buffer_u32"); }, [&](const std::vector<u8>& v) { emitter.EmitSimpleSequence<u8>(v, "!buffer_binary"); }, [&](const std::string& v) { emitter.EmitString(v); }); } void EmitParameterObject(const ParameterObject& pobject, Name parent_name) { yml::LibyamlEmitter::MappingScope scope{emitter, "!obj", YAML_BLOCK_MAPPING_STYLE}; size_t i = 0; for (const auto& [name, param] : pobject.params) { EmitName(name, i++, parent_name); EmitParameter(param); } } void EmitParameterList(const ParameterList& plist, Name parent_name) { yml::LibyamlEmitter::MappingScope scope{emitter, "!list", YAML_BLOCK_MAPPING_STYLE}; emitter.EmitString("objects"); { yml::LibyamlEmitter::MappingScope subscope{emitter, {}, YAML_BLOCK_MAPPING_STYLE}; size_t i = 0; for (const auto& [name, object] : plist.objects) { EmitName(name, i++, parent_name); EmitParameterObject(object, name); } } emitter.EmitString("lists"); { yml::LibyamlEmitter::MappingScope subscope{emitter, {}, YAML_BLOCK_MAPPING_STYLE}; size_t i = 0; for (const auto& [name, list] : plist.lists) { EmitName(name, i++, parent_name); EmitParameterList(list, name); } } } void EmitParameterIO(const ParameterIO& pio) { yml::LibyamlEmitter::MappingScope scope{emitter, "!io", YAML_BLOCK_MAPPING_STYLE}; emitter.EmitString("version"); emitter.EmitInt(pio.version); emitter.EmitString("type"); emitter.EmitString(pio.type); emitter.EmitString("param_root"); EmitParameterList(pio, ParameterIO::ParamRootKey); } void EmitCurves(tcb::span<const Curve> curves) { yaml_event_t event; yaml_sequence_start_event_initialize(&event, nullptr, (const u8*)"!curve", 0, YAML_FLOW_SEQUENCE_STYLE); emitter.Emit(event); for (const Curve& curve : curves) { emitter.EmitInt(curve.a); emitter.EmitInt(curve.b); for (float v : curve.floats) emitter.EmitFloat(v); } yaml_sequence_end_event_initialize(&event); emitter.Emit(event); } NameTable m_extra_name_table{false}; yml::LibyamlEmitterWithStorage<std::string> emitter; }; std::string ParameterIO::ToText() const { TextEmitter emitter; return emitter.Emit(*this); } } // namespace oead::aamp
16,114
C++
.cpp
394
35.560914
99
0.657318
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,018
byml.cpp
zeldamods_oead/src/byml.cpp
/** * Copyright (C) 2020 leoetlino <leo@leolam.fr> * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <absl/container/flat_hash_map.h> #include <absl/hash/hash.h> #include <algorithm> #include <array> #include <cstring> #include <map> #include <string_view> #include <oead/byml.h> #include <oead/util/align.h> #include <oead/util/binary_reader.h> #include <oead/util/bit_utils.h> #include <oead/util/iterator_utils.h> #include <oead/util/variant_utils.h> namespace oead { namespace byml { struct ResHeader { /// “BY” (big endian) or “YB” (little endian). std::array<char, 2> magic; /// Format version (1-4). u16 version; /// Offset to the hash key table, relative to start (usually 0x010) /// May be 0 if no hash nodes are used. Must be a string table node (0xc2). u32 hash_key_table_offset; /// Offset to the string table, relative to start. May be 0 if no strings are used. /// Must be a string table node (0xc2). u32 string_table_offset; /// Offset to the root node, relative to start. May be 0 if the document is totally empty. /// Must be either an array node (0xc0) or a hash node (0xc1). u32 root_node_offset; }; static_assert(sizeof(ResHeader) == 0x10); enum class NodeType : u8 { String = 0xa0, Binary = 0xa1, Array = 0xc0, Hash = 0xc1, StringTable = 0xc2, PathTable = 0xc3, // Unsupported Bool = 0xd0, Int = 0xd1, Float = 0xd2, UInt = 0xd3, Int64 = 0xd4, UInt64 = 0xd5, Double = 0xd6, Null = 0xff, }; constexpr NodeType GetNodeType(Byml::Type type) { constexpr std::array map{ NodeType::Null, NodeType::String, NodeType::Binary, NodeType::Array, NodeType::Hash, NodeType::Bool, NodeType::Int, NodeType::Float, NodeType::UInt, NodeType::Int64, NodeType::UInt64, NodeType::Double, }; return map[u8(type)]; } template <typename T = NodeType> constexpr bool IsContainerType(T type) { return type == T::Array || type == T::Hash; } template <typename T = NodeType> constexpr bool IsLongType(T type) { return type == T::Int64 || type == T::UInt64 || type == T::Double; } template <typename T = NodeType> constexpr bool IsNonInlineType(T type) { return IsContainerType(type) || IsLongType(type) || type == T::Binary; } constexpr bool IsValidVersion(int version) { return 1 <= version && version <= 4; } class StringTableParser { public: StringTableParser() = default; StringTableParser(util::BinaryReader& reader, u32 offset) : m_offset{offset} { if (offset == 0) return; const auto type = reader.Read<NodeType>(offset); const auto num_entries = reader.ReadU24(); if (!type || *type != NodeType::StringTable || !num_entries) throw InvalidDataError("Invalid string table"); m_size = *num_entries; } std::string GetString(util::BinaryReader& reader, u32 idx) const { if (idx >= m_size) throw std::out_of_range("Invalid string table entry index"); const auto rel_offset = reader.Read<u32>(m_offset + 4 + 4 * idx); // This is safe even for idx = N - 1 since the offset array has N+1 elements. const auto next_rel_offset = reader.Read<u32>(); if (!rel_offset || !next_rel_offset) throw InvalidDataError("Invalid string table: failed to read offsets"); if (*next_rel_offset < *rel_offset) throw InvalidDataError("Invalid string table: inconsistent offsets"); const size_t max_len = *next_rel_offset - *rel_offset; return reader.ReadString(m_offset + *rel_offset, max_len); } private: u32 m_offset = 0; u32 m_size = 0; }; class Parser { public: Parser(tcb::span<const u8> data) { if (data.size() < sizeof(ResHeader)) throw InvalidDataError("Invalid header"); const bool is_big_endian = data[0] == 'B' && data[1] == 'Y'; const bool is_little_endian = data[0] == 'Y' && data[1] == 'B'; const auto endianness = is_big_endian ? util::Endianness::Big : util::Endianness::Little; if (!is_big_endian && !is_little_endian) throw InvalidDataError("Invalid magic"); m_reader = {data, endianness}; const u16 version = *m_reader.Read<u16>(offsetof(ResHeader, version)); if (!IsValidVersion(version)) throw InvalidDataError("Unexpected version"); m_hash_key_table = StringTableParser( m_reader, *m_reader.Read<u32>(offsetof(ResHeader, hash_key_table_offset))); m_string_table = StringTableParser(m_reader, *m_reader.Read<u32>(offsetof(ResHeader, string_table_offset))); // In MK8 byamls, there is an extra offset to a path table here u32 root_node_offset = *m_reader.Read<u32>(offsetof(ResHeader, root_node_offset)); size_t header_end = m_reader.Tell(); if (root_node_offset != 0) { const auto type = m_reader.Read<NodeType>(root_node_offset); if (type == NodeType::PathTable) throw UnsupportedError("Path nodes unsupported"); } m_root_node_offset = root_node_offset; m_reader.Seek(header_end); } Byml Parse() { if (m_root_node_offset == 0) return Byml::Null(); return ParseContainerNode(m_root_node_offset); } private: Byml ParseValueNode(u32 offset, NodeType type) { const auto raw = m_reader.Read<u32>(offset); if (!raw) throw InvalidDataError("Invalid value node"); const auto read_long_value = [this, raw] { const auto long_value = m_reader.Read<u64>(*raw); if (!long_value) throw InvalidDataError("Invalid value node: failed to read long value"); return *long_value; }; switch (type) { case NodeType::String: return Byml{m_string_table.GetString(m_reader, *raw)}; case NodeType::Binary: { const u32 data_offset = *raw; const u32 size = m_reader.Read<u32>(data_offset).value(); return Byml{std::vector<u8>(m_reader.span().begin() + data_offset + 4, m_reader.span().begin() + data_offset + 4 + size)}; } case NodeType::Bool: return *raw != 0; case NodeType::Int: return S32(*raw); case NodeType::Float: return F32(util::BitCast<f32>(*raw)); case NodeType::UInt: return U32(*raw); case NodeType::Int64: return S64(read_long_value()); case NodeType::UInt64: return U64(read_long_value()); case NodeType::Double: return F64(util::BitCast<f64>(read_long_value())); case NodeType::Null: return Byml::Null(); default: throw InvalidDataError("Invalid value node: unexpected type"); } } Byml ParseContainerChildNode(u32 offset, NodeType type) { if (IsContainerType(type)) return ParseContainerNode(m_reader.Read<u32>(offset).value()); return ParseValueNode(offset, type); } Byml ParseArrayNode(u32 offset, u32 size) { Byml::Array result; result.reserve(size); const u32 values_offset = offset + 4 + util::AlignUp(size, 4); for (u32 i = 0; i < size; ++i) { const auto type = m_reader.Read<NodeType>(offset + 4 + i); result.emplace_back(ParseContainerChildNode(values_offset + 4 * i, type.value())); } return Byml{std::move(result)}; } Byml ParseHashNode(u32 offset, u32 size) { Byml::Hash result; for (u32 i = 0; i < size; ++i) { const u32 entry_offset = offset + 4 + 8 * i; const auto name_idx = m_reader.ReadU24(entry_offset); const auto type = m_reader.Read<NodeType>(entry_offset + 3); result.emplace(m_hash_key_table.GetString(m_reader, name_idx.value()), ParseContainerChildNode(entry_offset + 4, type.value())); } return Byml{std::move(result)}; } Byml ParseContainerNode(u32 offset) { const auto type = m_reader.Read<NodeType>(offset); const auto num_entries = m_reader.ReadU24(); if (!type || !num_entries) throw InvalidDataError("Invalid container node"); switch (*type) { case NodeType::Array: return ParseArrayNode(offset, *num_entries); case NodeType::Hash: return ParseHashNode(offset, *num_entries); default: throw InvalidDataError("Invalid container node: must be array or hash"); } } util::BinaryReader m_reader; StringTableParser m_hash_key_table; StringTableParser m_string_table; u32 m_root_node_offset; }; template <typename Value, typename T> std::vector<Value> SortMapKeys(const T& map) { std::vector<Value> keys; keys.reserve(map.size()); for (const auto& [key, value] : map) keys.emplace_back(key); std::sort(keys.begin(), keys.end()); return keys; } struct WriteContext { WriteContext(const Byml& root, util::Endianness endianness) : writer{endianness} { size_t num_non_inline_nodes = 0; const auto traverse = [&](auto self, const Byml& data) -> void { const Byml::Type type = data.GetType(); if (IsNonInlineType(type)) ++num_non_inline_nodes; switch (type) { case Byml::Type::String: string_table.Add(data.GetString()); break; case Byml::Type::Array: for (const auto& value : data.GetArray()) self(self, value); break; case Byml::Type::Hash: for (const auto& [key, value] : data.GetHash()) { hash_key_table.Add(key); self(self, value); } break; default: break; } }; traverse(traverse, root); non_inline_node_data.reserve(num_non_inline_nodes); hash_key_table.Build(); string_table.Build(); } void WriteValueNode(const Byml& data) { switch (data.GetType()) { case Byml::Type::Null: return writer.Write<u32>(0); case Byml::Type::String: return writer.Write<u32>(string_table.GetIndex(data.GetString())); case Byml::Type::Binary: writer.Write(static_cast<u32>(data.GetBinary().size())); writer.WriteBytes(data.GetBinary()); return; case Byml::Type::Bool: return writer.Write<u32>(data.GetBool()); case Byml::Type::Int: return writer.Write(data.GetInt()); case Byml::Type::Float: return writer.Write(data.GetFloat()); case Byml::Type::UInt: return writer.Write(data.GetUInt()); case Byml::Type::Int64: return writer.Write(data.GetInt64()); case Byml::Type::UInt64: return writer.Write(data.GetUInt64()); case Byml::Type::Double: return writer.Write(data.GetDouble()); default: throw std::logic_error("Unexpected value node type"); } } struct NonInlineNode { size_t offset_in_container; const Byml* data; }; void WriteContainerNode(const Byml& data) { std::vector<NonInlineNode> non_inline_nodes; const auto write_container_item = [&](const Byml& item) { if (IsNonInlineType(item.GetType())) { non_inline_nodes.push_back({writer.Tell(), &item}); writer.Write<u32>(0); } else { WriteValueNode(item); } }; switch (data.GetType()) { case Byml::Type::Array: { const auto& array = data.GetArray(); writer.Write(NodeType::Array); writer.WriteU24(array.size()); for (const auto& item : array) writer.Write(GetNodeType(item.GetType())); writer.AlignUp(4); for (const auto& item : array) write_container_item(item); break; } case Byml::Type::Hash: { const auto& hash = data.GetHash(); writer.Write(NodeType::Hash); writer.WriteU24(hash.size()); for (const auto& [key, value] : hash) { const auto type = GetNodeType(value.GetType()); writer.WriteU24(hash_key_table.GetIndex(key)); writer.Write(type); write_container_item(value); } break; } default: throw std::invalid_argument("Invalid container node type"); } for (const NonInlineNode& node : non_inline_nodes) { const auto it = non_inline_node_data.find(*node.data); if (it != non_inline_node_data.end()) { // This node has already been written. Reuse its data. writer.RunAt(node.offset_in_container, [&](size_t) { writer.Write<u32>(it->second); }); } else { const size_t offset = writer.Tell(); writer.RunAt(node.offset_in_container, [&](size_t) { writer.Write<u32>(offset); }); non_inline_node_data.emplace(*node.data, offset); if (IsContainerType(node.data->GetType())) WriteContainerNode(*node.data); else WriteValueNode(*node.data); } } } struct StringTable { explicit operator bool() const { return !sorted_strings.empty(); } size_t Size() const { return sorted_strings.size(); } void Add(std::string_view string) { map.emplace(string, 0); } u32 GetIndex(std::string_view string) const { return map.at(string); } /// Build the sorted vector of strings and sets indices in the map. void Build() { sorted_strings = SortMapKeys<std::string_view>(map); for (const auto& [i, key] : util::Enumerate(sorted_strings)) map[key] = i; } // We use a hash map here to get fast insertions and fast lookups in hot paths, // and because we only need a sorted list of strings for two operations. absl::flat_hash_map<std::string_view, u32> map; std::vector<std::string_view> sorted_strings; }; void WriteStringTable(const StringTable& table) { const size_t base = writer.Tell(); writer.Write(NodeType::StringTable); writer.WriteU24(table.Size()); // String offsets. const size_t offset_table_offset = writer.Tell(); writer.Seek(writer.Tell() + sizeof(u32) * (table.Size() + 1)); for (const auto& [i, string] : util::Enumerate(table.sorted_strings)) { writer.WriteCurrentOffsetAt<u32>(offset_table_offset + sizeof(u32) * i, base); writer.WriteCStr(string); } writer.WriteCurrentOffsetAt<u32>(offset_table_offset + sizeof(u32) * table.Size(), base); writer.AlignUp(4); } util::BinaryWriter writer; StringTable hash_key_table; StringTable string_table; absl::flat_hash_map<std::reference_wrapper<const Byml>, u32> non_inline_node_data; }; } // namespace byml Byml Byml::FromBinary(tcb::span<const u8> data) { byml::Parser parser{data}; return parser.Parse(); } std::vector<u8> Byml::ToBinary(bool big_endian, int version) const { if (!byml::IsValidVersion(version)) throw std::invalid_argument("Invalid version"); byml::WriteContext ctx{*this, big_endian ? util::Endianness::Big : util::Endianness::Little}; // Header ctx.writer.Write(ctx.writer.Endian() == util::Endianness::Big ? "BY" : "YB"); ctx.writer.Write<u16>(version); ctx.writer.Write<u32>(0); // Hash key table offset. ctx.writer.Write<u32>(0); // String table offset. ctx.writer.Write<u32>(0); // Root node offset. if (GetType() == Byml::Type::Null) return ctx.writer.Finalize(); if (ctx.hash_key_table) { ctx.writer.WriteCurrentOffsetAt<u32>(offsetof(byml::ResHeader, hash_key_table_offset)); ctx.WriteStringTable(ctx.hash_key_table); } if (ctx.string_table) { ctx.writer.WriteCurrentOffsetAt<u32>(offsetof(byml::ResHeader, string_table_offset)); ctx.WriteStringTable(ctx.string_table); } ctx.writer.WriteCurrentOffsetAt<u32>(offsetof(byml::ResHeader, root_node_offset)); ctx.writer.AlignUp(4); ctx.WriteContainerNode(*this); ctx.writer.AlignUp(4); return ctx.writer.Finalize(); } Byml::Hash& Byml::GetHash() { return Get<Type::Hash>(); } Byml::Array& Byml::GetArray() { return Get<Type::Array>(); } Byml::String& Byml::GetString() { return Get<Type::String>(); } std::vector<u8>& Byml::GetBinary() { return Get<Type::Binary>(); } const Byml::Hash& Byml::GetHash() const { return Get<Type::Hash>(); } const Byml::Array& Byml::GetArray() const { return Get<Type::Array>(); } const Byml::String& Byml::GetString() const { return Get<Type::String>(); } const std::vector<u8>& Byml::GetBinary() const { return Get<Type::Binary>(); } bool Byml::GetBool() const { return Get<Type::Bool>(); } s32 Byml::GetInt() const { switch (GetType()) { case Type::Int: return Get<Type::Int>(); case Type::UInt: return s32(Get<Type::UInt>()); default: throw TypeError("GetInt: expected Int or UInt"); } } template <typename T> static inline T CheckPositiveAndReturn(T value) { if (value >= 0) return value; throw TypeError("expected positive integer value"); } u32 Byml::GetUInt() const { switch (GetType()) { case Type::UInt: return Get<Type::UInt>(); case Type::Int: return CheckPositiveAndReturn(Get<Type::Int>()); default: throw TypeError("GetUInt: expected Int or UInt value"); } } f32 Byml::GetFloat() const { return Get<Type::Float>(); } s64 Byml::GetInt64() const { switch (GetType()) { case Type::Int: return Get<Type::Int>(); case Type::UInt: return s64(Get<Type::UInt>()); case Type::Int64: return Get<Type::Int64>(); default: throw TypeError("GetInt64: expected Int, UInt or Int64"); } } u64 Byml::GetUInt64() const { switch (GetType()) { case Type::Int: return CheckPositiveAndReturn(Get<Type::Int>()); case Type::UInt: return Get<Type::UInt>(); case Type::UInt64: return Get<Type::UInt64>(); case Type::Int64: return CheckPositiveAndReturn(Get<Type::Int64>()); default: throw TypeError("GetUInt64: expected UInt or UInt64"); } } f64 Byml::GetDouble() const { return Get<Type::Double>(); } } // namespace oead
17,957
C++
.cpp
513
30.39961
99
0.666801
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,019
sarc.cpp
zeldamods_oead/src/sarc.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <absl/algorithm/container.h> #include <absl/container/flat_hash_set.h> #include <absl/strings/numbers.h> #include <array> #include <numeric> #include <cmrc/cmrc.hpp> #include <ryml.hpp> #include <oead/errors.h> #include <oead/sarc.h> #include <oead/util/align.h> #include <oead/util/magic_utils.h> #include <oead/util/string_utils.h> #include "yaml.h" CMRC_DECLARE(oead::res); namespace oead { namespace sarc { constexpr auto SarcMagic = util::MakeMagic("SARC"); constexpr auto SfatMagic = util::MakeMagic("SFAT"); constexpr auto SfntMagic = util::MakeMagic("SFNT"); struct ResHeader { std::array<char, 4> magic; u16 header_size; u16 bom; u32 file_size; u32 data_offset; u16 version; u16 reserved; OEAD_DEFINE_FIELDS(ResHeader, magic, header_size, bom, file_size, data_offset, version, reserved); }; static_assert(sizeof(ResHeader) == 0x14); struct ResFatHeader { std::array<char, 4> magic; u16 header_size; u16 num_files; u32 hash_multiplier; OEAD_DEFINE_FIELDS(ResFatHeader, magic, header_size, num_files, hash_multiplier); }; static_assert(sizeof(ResFatHeader) == 0xC); struct ResFatEntry { u32 name_hash; u32 rel_name_optional_offset; /// Relative to the data offset. u32 data_begin; /// Relative to the data offset. u32 data_end; OEAD_DEFINE_FIELDS(ResFatEntry, name_hash, rel_name_optional_offset, data_begin, data_end); }; struct ResFntHeader { std::array<char, 4> magic; u16 header_size; u16 reserved; OEAD_DEFINE_FIELDS(ResFntHeader, magic, header_size, reserved); }; static_assert(sizeof(ResFntHeader) == 0x8); constexpr u32 HashName(u32 multiplier, std::string_view name) { u32 hash = 0; for (const char c : name) hash = hash * multiplier + c; return hash; } } // namespace sarc // Note: This mirrors what sead::SharcArchiveRes::prepareArchive_ does. Sarc::Sarc(tcb::span<const u8> data) : m_reader{data, util::Endianness::Big} { m_reader = {data, util::ByteOrderMarkToEndianness(m_reader.Read<sarc::ResHeader>().value().bom)}; const auto header = *m_reader.Read<sarc::ResHeader>(); if (header.magic != sarc::SarcMagic) throw InvalidDataError("Invalid SARC magic"); if (header.version != 0x0100) throw InvalidDataError("Unknown SARC version"); if (header.header_size != sizeof(sarc::ResHeader)) throw InvalidDataError("Invalid SARC header size"); const auto fat_header = m_reader.Read<sarc::ResFatHeader>().value(); if (fat_header.magic != sarc::SfatMagic) throw InvalidDataError("Invalid SFAT magic"); if (fat_header.header_size != sizeof(sarc::ResFatHeader)) throw InvalidDataError("Invalid SFAT header size"); if (fat_header.num_files >> 0xE) throw InvalidDataError("Too many files"); m_num_files = fat_header.num_files; m_entries_offset = m_reader.Tell(); m_hash_multiplier = fat_header.hash_multiplier; m_data_offset = header.data_offset; const auto fnt_header_offset = m_entries_offset + sizeof(sarc::ResFatEntry) * m_num_files; const auto fnt_header = m_reader.Read<sarc::ResFntHeader>(fnt_header_offset).value(); if (fnt_header.magic != sarc::SfntMagic) throw InvalidDataError("Invalid SFNT magic"); if (fnt_header.header_size != sizeof(sarc::ResFntHeader)) throw InvalidDataError("Invalid SFNT header size"); m_names_offset = m_reader.Tell(); if (m_data_offset < m_names_offset) throw InvalidDataError("File data should not be stored before the name table"); } Sarc::File Sarc::GetFile(u16 index) const { if (index > m_num_files) throw std::out_of_range("Sarc::GetFile: out of range: " + std::to_string(index)); const auto entry_offset = m_entries_offset + sizeof(sarc::ResFatEntry) * index; const auto entry = m_reader.Read<sarc::ResFatEntry>(entry_offset).value(); File file{}; if (entry.rel_name_optional_offset) { const auto name_offset = m_names_offset + (entry.rel_name_optional_offset & 0xFFFFFF) * 4; file.name = m_reader.ReadString<std::string_view>(name_offset); } file.data = m_reader.span().subspan(m_data_offset + entry.data_begin, entry.data_end - entry.data_begin); return file; } std::optional<Sarc::File> Sarc::GetFile(std::string_view name) const { if (m_num_files == 0) return std::nullopt; const auto wanted_hash = sarc::HashName(m_hash_multiplier, name); // Perform a binary search. u32 a = 0; u32 b = m_num_files - 1; while (a <= b) { const u32 m = (a + b) / 2; const auto hash = m_reader.Read<u32>(m_entries_offset + sizeof(sarc::ResFatEntry) * m); if (wanted_hash < hash) b = m - 1; else if (wanted_hash > hash) a = m + 1; else return GetFile(m); } return std::nullopt; } bool Sarc::operator==(const Sarc& other) const { return absl::c_equal(m_reader.span(), other.m_reader.span()); } bool Sarc::AreFilesEqual(const Sarc& other) const { if (GetNumFiles() != other.GetNumFiles()) return false; for (const auto& [file1, file2] : easy_iterator::zip(GetFiles(), other.GetFiles())) { if (file1 != file2) return false; } return true; } static constexpr bool IsValidAlignment(size_t alignment) { return alignment != 0 && (alignment & (alignment - 1)) == 0; } size_t Sarc::GuessMinAlignment() const { static constexpr size_t MinAlignment = 4; size_t gcd = MinAlignment; for (size_t i = 0; i < m_num_files; ++i) { const u32 entry_offset = m_entries_offset + sizeof(sarc::ResFatEntry) * i; const u32 data_begin = m_reader.Read<sarc::ResFatEntry>(entry_offset).value().data_begin; gcd = std::gcd(gcd, m_data_offset + data_begin); } // If the GCD is not a power of 2, the files are most likely not aligned. if (!IsValidAlignment(gcd)) return MinAlignment; return gcd; } static auto& GetBotwFactoryNames() { static auto names = [] { absl::flat_hash_set<std::string_view> names; const auto fs = cmrc::oead::res::get_filesystem(); const auto info_tsv_file = fs.open("data/botw_resource_factory_info.tsv"); util::SplitStringByLine({info_tsv_file.begin(), info_tsv_file.size()}, [&names](std::string_view line) { const auto tab_pos = line.find('\t'); names.emplace(line.substr(0, tab_pos)); }); return names; }(); return names; } static const auto& GetAglEnvAlignmentRequirements() { static auto requirements = [] { std::vector<std::pair<std::string, u32>> requirements; const auto fs = cmrc::oead::res::get_filesystem(); const auto info_tsv_file = fs.open("data/aglenv_file_info.json"); yml::InitRymlIfNeeded(); const auto tree = ryml::parse(yml::StrViewToRymlSubstr({info_tsv_file.begin(), info_tsv_file.size()})); for (const ryml::NodeRef& entry : tree.rootref()) { int alignment = 1; if (absl::SimpleAtoi(yml::RymlSubstrToStrView(entry["align"].val()), &alignment)) { requirements.emplace_back(std::string(yml::RymlSubstrToStrView(entry["ext"].val())), std::abs(alignment)); requirements.emplace_back(std::string(yml::RymlSubstrToStrView(entry["bext"].val())), std::abs(alignment)); } } return requirements; }(); return requirements; } void SarcWriter::AddDefaultAlignmentRequirements() { for (const auto& [type, alignment] : GetAglEnvAlignmentRequirements()) AddAlignmentRequirement(type, alignment); // BotW: Pack/Bootup.pack/Env/env.sgenvb/postfx/*.bksky (AAMP) AddAlignmentRequirement("ksky", 8); AddAlignmentRequirement("bksky", 8); // BotW: Pack/TitleBG.pack/Terrain/System/tera_resource.Nin_NX_NVN.release.ssarc AddAlignmentRequirement("gtx", 0x2000); AddAlignmentRequirement("sharcb", 0x1000); AddAlignmentRequirement("sharc", 0x1000); // BotW: Pack/Bootup.pack/Layout/MultiFilter.ssarc/*.baglmf (AAMP) AddAlignmentRequirement("baglmf", 0x80); // BotW: Font/*.bfarc/.bffnt AddAlignmentRequirement("bffnt", m_endian == util::Endianness::Big ? 0x2000 : 0x1000); } std::pair<u32, std::vector<u8>> SarcWriter::Write() { util::BinaryWriter writer{m_endian}; writer.Seek(sizeof(sarc::ResHeader)); // Sort the files by name hash to make binary searches possible. std::vector<std::reference_wrapper<FileMap::value_type>> files{m_files.begin(), m_files.end()}; absl::c_sort(files, [this](const FileMap::value_type& a, const FileMap::value_type& b) { return sarc::HashName(m_hash_multiplier, a.first) < sarc::HashName(m_hash_multiplier, b.first); }); // Try to avoid unnecessary reallocations by making the buffer large enough to fit the whole SARC. size_t estimated_size = sizeof(sarc::ResHeader) + sizeof(sarc::ResFatHeader) + sizeof(sarc::ResFntHeader); for (const FileMap::value_type& pair : files) { const auto& [name, data] = pair; estimated_size += sizeof(sarc::ResFatEntry); estimated_size += util::AlignUp(name.size() + 1, 4); estimated_size += data.size(); } writer.Buffer().reserve(1.5f * estimated_size); // SFAT sarc::ResFatHeader fat_header{}; fat_header.magic = sarc::SfatMagic; fat_header.header_size = sizeof(fat_header); fat_header.num_files = u16(m_files.size()); fat_header.hash_multiplier = m_hash_multiplier; writer.Write(fat_header); AddDefaultAlignmentRequirements(); std::vector<u32> alignments; alignments.reserve(files.size()); { u32 rel_string_offset = 0; u32 rel_data_offset = 0; for (const FileMap::value_type& pair : files) { const auto& [name, data] = pair; const u32 alignment = GetAlignmentForFile(name, data); alignments.emplace_back(alignment); sarc::ResFatEntry entry{}; entry.name_hash = sarc::HashName(m_hash_multiplier, name); entry.rel_name_optional_offset = 1 << 24 | (rel_string_offset / 4); entry.data_begin = util::AlignUp(rel_data_offset, alignment); entry.data_end = entry.data_begin + data.size(); writer.Write(entry); rel_data_offset = entry.data_end; rel_string_offset += util::AlignUp(name.size() + 1, 4); } } // SFNT sarc::ResFntHeader fnt_header{}; fnt_header.magic = sarc::SfntMagic; fnt_header.header_size = sizeof(fnt_header); writer.Write(fnt_header); for (const FileMap::value_type& pair : files) { writer.WriteCStr(pair.first); writer.AlignUp(4); } // File data const u32 required_alignment = absl::c_accumulate(alignments, 1u, std::lcm<u32, u32>); writer.AlignUp(required_alignment); const u32 data_offset_begin = u32(writer.Tell()); for (const auto& [pair, alignment] : easy_iterator::zip(files, alignments)) { writer.AlignUp(alignment); writer.WriteBytes(pair.second); } sarc::ResHeader header{}; header.magic = sarc::SarcMagic; header.header_size = sizeof(header); header.bom = 0xFEFF; header.file_size = writer.Tell(); header.data_offset = data_offset_begin; header.version = 0x0100; writer.Seek(0); writer.Write(header); return {required_alignment, writer.Finalize()}; } void SarcWriter::SetMinAlignment(size_t alignment) { if (!IsValidAlignment(alignment)) throw std::invalid_argument("Invalid alignment"); m_min_alignment = alignment; } void SarcWriter::AddAlignmentRequirement(std::string extension, size_t alignment) { if (!IsValidAlignment(alignment)) throw std::invalid_argument("Invalid alignment"); m_alignment_map.insert_or_assign(std::move(extension), alignment); } static bool IsSarc(tcb::span<const u8> data) { return data.size() >= 0x20 && (std::memcmp(data.data(), "SARC", 4) == 0 || (std::memcmp(data.data(), "Yaz0", 4) == 0 && std::memcmp(data.data() + 0x11, "SARC", 4) == 0)); } /// Detects alignment requirements for binary files that use nn::util::BinaryFileHeader. static u32 GetAlignmentForNewBinaryFile(tcb::span<const u8> data) { util::BinaryReader reader{data, util::Endianness::Big}; if (data.size() <= 0x20) return 1; const auto bom = *reader.Read<u16>(0xC); if (bom != 0xFEFF && bom != 0xFFFE) return 1; reader.SetEndian(util::ByteOrderMarkToEndianness(bom)); // If the file size doesn't match, then the file likely does not contain a // nn::util::BinaryFileHeader const auto file_size = *reader.Read<u32>(0x1C); if (file_size != data.size()) return 1; return 1 << data[0xE]; } static u32 GetAlignmentForCafeBflim(tcb::span<const u8> data) { if (data.size() <= 0x28 || std::memcmp(data.data() + data.size() - 0x28, "FLIM", 4) != 0) return 1; return util::SwapIfNeeded(u16(util::BitCastPtr<u16>(data.data() + data.size() - 0x8)), util::Endianness::Big); } u32 SarcWriter::GetAlignmentForFile(std::string_view name, tcb::span<const u8> data) const { const std::string_view::size_type dot_pos = name.rfind('.'); const std::string_view ext = dot_pos + 1 < name.size() ? name.substr(dot_pos + 1) : ""; u32 alignment = m_min_alignment; if (const auto it = m_alignment_map.find(ext); it != m_alignment_map.end()) { alignment = std::lcm(alignment, it->second); } // In some archives (SMO's for example), Nintendo seems to use a somewhat arbitrary // alignment requirement (0x2000) for nested SARCs. if (m_mode == Mode::Legacy && IsSarc(data)) { alignment = std::lcm(alignment, 0x2000u); } // For resources that are unhandled by a BotW-style resource system, or for resources // from games that do not have such a system, try to detect the alignment. if (m_mode == Mode::Legacy || !GetBotwFactoryNames().contains(ext)) { alignment = std::lcm(alignment, GetAlignmentForNewBinaryFile(data)); if (m_endian == util::Endianness::Big) alignment = std::lcm(alignment, GetAlignmentForCafeBflim(data)); } return alignment; } SarcWriter SarcWriter::FromSarc(const Sarc& archive) { SarcWriter writer; writer.SetEndianness(archive.GetEndianness()); writer.SetMinAlignment(archive.GuessMinAlignment()); writer.m_files.reserve(archive.GetNumFiles()); for (const Sarc::File& file : archive.GetFiles()) { writer.m_files.emplace(std::string(file.name), std::vector<u8>(file.data.begin(), file.data.end())); } return writer; } } // namespace oead
14,982
C++
.cpp
364
37.002747
100
0.692123
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,020
gsheet.cpp
zeldamods_oead/src/gsheet.cpp
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #include <absl/strings/str_format.h> #include <algorithm> #include <any> #include <oead/errors.h> #include <oead/gsheet.h> #include <oead/util/align.h> #include <oead/util/magic_utils.h> namespace oead::gsheet { FieldMap MakeFieldMap(tcb::span<ResField> fields) { FieldMap map; for (ResField& field : fields) map.emplace(field.name, &field); return map; } namespace { struct OpaqueArray { auto Items(size_t item_size) const { return easy_iterator::MakeIterable<OpaqueIterator>( data, reinterpret_cast<void*>((uintptr_t)data + item_size * size), item_size); } void* data = nullptr; u32 size = 0; private: [[maybe_unused]] u32 padding = 0; }; static_assert(sizeof(OpaqueArray) == 0x10); u32 GetValueSize(const SheetRw& sheet) { if (sheet.root_fields.empty()) return 0; const Field& last_field = sheet.root_fields.back(); return util::AlignUp<u32>(last_field.offset_in_value + last_field.inline_size, sheet.alignment); } u32 GetNumFields(const SheetRw& sheet) { u32 count = 0; const auto traverse = [&count](auto self, const Field& field) -> void { ++count; for (const auto& subfield : field.fields) self(self, subfield); }; for (const auto& field : sheet.root_fields) traverse(traverse, field); return count; } struct Writer { std::vector<u8> Write(const SheetRw& sheet) { // Header ResHeader header{}; header.alignment = sheet.alignment; header.hash = sheet.hash; header.num_root_fields = u32(sheet.root_fields.size()); header.num_fields = GetNumFields(sheet); header.num_values = u32(sheet.values.size()); header.value_size = GetValueSize(sheet); writer.Write(header); field_strings.push_back({offsetof(ResHeader, name), sheet.name}); writer.RunAt(offsetof(ResHeader, values), [&](auto) { RegisterAndWriteObjectPtr(sheet.values, "sheet.values"); }); // Fields WriteFields(sheet.root_fields, true); // Values RegisterObject(sheet.values); for (const auto& value : sheet.values) { WriteStruct(value, sheet.root_fields); writer.AlignUp(sheet.alignment); } // Document name and field strings writer.AlignUp(0x10); for (const auto& [ptr_offset, string] : field_strings) { writer.WriteCurrentOffsetAt<u64>(ptr_offset); writer.WriteCStr(string); } // Value data for (const auto& value : sheet.values) WriteStructData(value, sheet.root_fields); writer.AlignUp(0x10); writer.GrowBuffer(); // Pointers WriteObjectPointers(); return writer.Finalize(); } private: void WriteField(const Field& field) { const auto offset = writer.Tell(); ResField res{}; res.type = field.type; res.x11 = field.x11; res.flags = field.flags; res.offset_in_value = field.offset_in_value; res.inline_size = field.inline_size; res.data_size = field.data_size; res.num_fields = u16(field.fields.size()); res.parent = (ResField*)0xdeadbeefdeadbeef; writer.Write(res); field_strings.push_back({offset + offsetof(ResField, name), field.name}); field_strings.push_back({offset + offsetof(ResField, type_name), field.type_name}); if (!field.fields.empty()) { writer.RunAt(offset + offsetof(ResField, fields), [&](auto) { RegisterAndWriteObjectPtr(field.fields, "field.fields"); }); } } void WriteFields(const std::vector<Field>& fields, bool is_root = false) { if (!is_root && !fields.empty()) RegisterObject(fields); for (const auto& field : fields) WriteField(field); for (const auto& field : fields) WriteFields(field.fields); } void WriteDataInline(const Data& data, const Field& field) { util::Match( data.v.v, [&](const Data::Struct& v) { if (field.type != Field::Type::Struct) throw std::invalid_argument("Mismatched field type and data type (expected Struct)"); WriteStruct(v, field.fields); }, [&](bool v) { if (field.type != Field::Type::Bool) throw std::invalid_argument("Mismatched field type and data type (expected Bool)"); writer.Write<u8>(v); }, [&](int v) { if (field.type != Field::Type::Int) throw std::invalid_argument("Mismatched field type and data type (expected Int)"); writer.Write(v); }, [&](float v) { if (field.type != Field::Type::Float) throw std::invalid_argument("Mismatched field type and data type (expected Float)"); writer.Write(v); }, [&](const std::string& v) { if (field.type != Field::Type::String) throw std::invalid_argument("Mismatched field type and data type (expected String)"); writer.WriteCStr(v); }, [](const auto&) { throw std::logic_error("Unexpected type"); }); } void WriteStringPtr(const std::string& string, const Field& field) { if (!string.empty() || !field.flags[Field::Flag::IsNullable]) RegisterAndWriteObjectPtr(string, "string ptr"); else writer.Write<u64>(0); writer.Write(u32(string.size())); writer.Write<u32>(0); } void WriteStruct(const Data::Struct& struct_, const std::vector<Field>& fields) { const auto base_offset = writer.Tell(); for (const Field& field : fields) { writer.Seek(base_offset + field.offset_in_value); const auto& data = struct_.at(field.name); // Arrays. if (field.flags[Field::Flag::IsArray]) { RegisterAndWriteObjectPtr(data, "struct: array"); writer.Write(u32(data.VisitArray([](const auto& v) { return v.size(); }))); writer.Write<u32>(0); } // Strings (including Nullables that are strings). else if (field.type == Field::Type::String) { WriteStringPtr(data.v.Get<Data::Type::String>(), field); } // Nullables that are not strings. else if (field.flags[Field::Flag::IsNullable]) { if (data.IsNull()) writer.Write<u64>(0); else RegisterAndWriteObjectPtr(data, "struct: nullable"); } // Other types. else { WriteDataInline(data, field); } } } void WriteStructData(const Data::Struct& struct_, const std::vector<Field>& fields) { for (const Field& field : fields) { const auto& data = struct_.at(field.name); // Arrays. if (field.flags[Field::Flag::IsArray]) { switch (field.type) { case Field::Type::Struct: { const auto& structs = data.v.Get<Data::Type::StructArray>(); for (const auto& struct_ : structs) WriteStructData(struct_, field.fields); writer.AlignUp(8); RegisterObject(data); for (const auto& struct_ : structs) { WriteStruct(struct_, field.fields); writer.AlignUp(8); } break; } case Field::Type::String: { const auto& strings = data.v.Get<Data::Type::StringArray>(); for (const auto& string : strings) { RegisterObject(string); writer.WriteCStr(string); } writer.AlignUp(8); RegisterObject(data); for (const auto& string : strings) WriteStringPtr(string, field); break; } default: { // XXX: how are bool arrays written? if (field.type != Field::Type::Bool) writer.AlignUp(4); RegisterObject(data); data.VisitArray([&](const auto& v) { using T = typename std::decay_t<decltype(v)>::value_type; if constexpr (util::IsAnyOfType<T, bool, int, float>()) { for (const T item : v) { writer.Write(item); writer.AlignUp(4); } } }); } } } // Strings. else if (field.type == Field::Type::String) { const auto& string = data.v.Get<Data::Type::String>(); if (!string.empty() || !field.flags[Field::Flag::IsNullable]) { RegisterObject(string); writer.WriteCStr(string); } } // Nullables. else if (field.flags[Field::Flag::IsNullable]) { if (!data.IsNull()) { if (field.type == Field::Type::Struct) { const auto& struct_ = data.v.Get<Data::Type::Struct>(); WriteStructData(struct_, field.fields); writer.AlignUp(8); RegisterObject(data); WriteStruct(struct_, field.fields); } else { RegisterObject(data); WriteDataInline(data, field); } } } // Structs. else if (field.type == Field::Type::Struct) { WriteStructData(data.v.Get<Data::Type::Struct>(), field.fields); } // Nothing to do for the other inline types (bool/int/float). } } template <typename T> void RegisterObject(const T& obj) { static_assert(!std::is_pointer_v<std::decay_t<T>>); ObjectEntry& entry = objects[&obj]; if (entry.obj_offset) throw std::logic_error("Attempted to register an object twice"); entry.obj_offset = writer.Tell(); } template <typename T> void RegisterAndWriteObjectPtr(const T& obj, [[maybe_unused]] const char* description) { static_assert(!std::is_pointer_v<std::decay_t<T>>); ObjectEntry& entry = objects[&obj]; if (entry.ptr_offset) throw std::logic_error("Attempted to register a pointer twice"); entry.ptr_offset = writer.Tell(); #ifdef OEAD_GSHEET_DEBUG entry.object = obj; entry.description = description; #endif writer.Write<u64>(0xFFFFFFFFFFFFFFFF); } void WriteObjectPointers() { for (const auto& [obj, entry] : objects) { if (!entry.ptr_offset && !entry.obj_offset) throw std::logic_error("Invalid object entry"); if (!entry.ptr_offset) { throw std::logic_error(absl::StrFormat( "Inaccessible object: no pointer was written for object %#x", entry.obj_offset)); } if (!entry.obj_offset) { throw std::logic_error(absl::StrFormat( "Missing object: no object was written for pointer %#x", entry.ptr_offset)); } writer.RunAt(entry.ptr_offset, [this, offset = entry.obj_offset](auto) { writer.Write<u64>(offset); }); } } util::BinaryWriter writer{util::Endianness::Little}; /// List of field-related strings and their corresponding offsets. std::vector<std::pair<u32, std::string_view>> field_strings; struct ObjectEntry { /// Offset of the pointer that is to point to the object. u32 ptr_offset = 0; /// Offset of the object itself. u32 obj_offset = 0; #ifdef OEAD_GSHEET_DEBUG std::any object; const char* description = nullptr; #endif }; absl::flat_hash_map<const void*, ObjectEntry> objects; }; } // namespace std::vector<u8> SheetRw::ToBinary() const { return Writer{}.Write(*this); } namespace { void RelocateField(ResField& field, ResField* parent, tcb::span<u8> buffer) { if (!field.name || !field.type_name) throw InvalidDataError("Missing field name or field type name"); util::Relocate(buffer, field.name); util::Relocate(buffer, field.type_name); const auto fields_offset = reinterpret_cast<uintptr_t>(field.fields); if (fields_offset) { if (fields_offset < sizeof(ResHeader)) throw InvalidDataError("Invalid field offset"); if (fields_offset % sizeof(ResField) != 0) throw InvalidDataError("Invalid field alignment"); util::Relocate(buffer, field.fields, field.num_fields); field.parent = parent; for (size_t i = 0; i < field.num_fields; ++i) { RelocateField(field.fields[i], &field, buffer); } } else if (field.num_fields) { throw InvalidDataError("Missing sub-fields"); } } void RelocateFieldData(void* data, const ResField& field, tcb::span<u8> buffer, bool ignore_array_flag = false, bool ignore_nullable_flag = false) { if (field.flags[Field::Flag::IsArray] && !ignore_array_flag) { auto* array = static_cast<OpaqueArray*>(data); util::RelocateWithSize(buffer, array->data, field.data_size * array->size); for (void* item : array->Items(field.data_size)) RelocateFieldData(item, field, buffer, true, ignore_nullable_flag); } else if (field.type == Field::Type::String) { auto* string = static_cast<String*>(data); if ((string->size || !field.flags[Field::Flag::IsNullable]) && !string->data) throw InvalidDataError("Missing string data"); if (string->data) { util::Relocate(buffer, string->data, string->size); if (util::ReadString(buffer, string->data).size() != string->size) throw InvalidDataError("Invalid string size"); } } else if (field.flags[Field::Flag::IsNullable] && !ignore_nullable_flag) { auto* nullable = static_cast<Nullable<void>*>(data); if (nullable->data) { util::RelocateWithSize(buffer, nullable->data, field.data_size); RelocateFieldData(nullable->data, field, buffer, ignore_array_flag, true); } } else if (field.type == Field::Type::Struct) { for (const ResField& subfield : field.GetFields()) { RelocateFieldData(reinterpret_cast<void*>(uintptr_t(data) + subfield.offset_in_value), subfield, buffer); } } } } // namespace Sheet::Sheet(tcb::span<u8> data) : m_data{data} { if (data.size() < sizeof(ResHeader)) throw InvalidDataError("Invalid header"); ResHeader& header = GetHeader(); if (header.magic != util::MakeMagic("gsht")) throw InvalidDataError("Invalid magic"); if (header.version != 1) throw InvalidDataError("Invalid version (expected 1)"); if (header.bool_size != 1) throw InvalidDataError("Invalid bool size"); if (header.pointer_size != 8) throw InvalidDataError("Invalid pointer size"); if (!header.name) throw InvalidDataError("Missing name"); // Relocate all pointers. util::Relocate(data, header.name); util::RelocateWithSize(data, header.values, header.num_values * header.value_size); if (data.data() + data.size() < (u8*)&GetAllFieldsRaw()[header.num_fields]) throw std::out_of_range("Fields are out of bounds"); for (ResField& field : GetRootFields()) RelocateField(field, nullptr, data); for (void* value : GetValues()) { for (const ResField& field : GetRootFields()) { RelocateFieldData(reinterpret_cast<void*>(uintptr_t(value) + field.offset_in_value), field, data); } } // Build the int or string map. const auto key_field = std::find_if(GetRootFields().begin(), GetRootFields().end(), [](const ResField& field) { return field.flags[Field::Flag::IsKey]; }); if (key_field != GetRootFields().end()) { m_key_field = &*key_field; if (key_field->flags[Field::Flag::IsArray] || key_field->flags[Field::Flag::IsNullable]) throw InvalidDataError("Key fields cannot be Arrays or Nullables"); switch (key_field->type) { case Field::Type::Int: for (void* value : GetValues()) { m_int_map.emplace(*reinterpret_cast<int*>(uintptr_t(value) + key_field->offset_in_value), value); } break; case Field::Type::String: for (void* value : GetValues()) { m_string_map.emplace( *reinterpret_cast<const char**>(uintptr_t(value) + key_field->offset_in_value), value); } break; default: throw InvalidDataError("Key fields must be of type Int or String"); } } } tcb::span<ResField> Sheet::GetRootFields() const { return {GetAllFieldsRaw(), GetHeader().num_root_fields}; } tcb::span<ResField> Sheet::GetAllFields() const { return {GetAllFieldsRaw(), GetHeader().num_fields}; } FieldMap Sheet::MakeFieldMap() const { return gsheet::MakeFieldMap(GetRootFields()); } ResField::ResField() { // Older versions of GCC appear not to initialize padding bits in this structure // even when zero initialization is supposed to be done. // So let's memset the structure manually to be sure. std::memset(this, 0, sizeof(*this)); } Field::Field(const ResField& raw) { name = raw.name; type_name = raw.type_name; type = raw.type; x11 = raw.x11; flags = raw.flags; offset_in_value = raw.offset_in_value; inline_size = raw.inline_size; data_size = raw.data_size; fields.reserve(raw.num_fields); fields.assign(raw.GetFields().begin(), raw.GetFields().end()); } template <typename T, bool IsUniquePtr = false> static std::vector<T> ParseValueArray(const OpaqueArray* array, const Field& field, bool ignore_nullable_flag) { std::vector<T> vector; vector.reserve(array->size); for (void* item : array->Items(field.data_size)) { if constexpr (IsUniquePtr) { auto ptr = std::get<std::unique_ptr<T>>( std::move(Data{item, field, true, ignore_nullable_flag}.v.v)); vector.emplace_back(std::move(*ptr)); } else { vector.emplace_back( std::get<T>(std::move(Data{item, field, true, ignore_nullable_flag}.v.v))); } } return vector; } Data::Data(const void* data, const Field& field, bool ignore_array_flag, bool ignore_nullable_flag) { if (field.flags[Field::Flag::IsArray] && !ignore_array_flag) { auto* array = static_cast<const OpaqueArray*>(data); switch (field.type) { case Field::Type::Struct: v = ParseValueArray<Struct, true>(array, field, ignore_nullable_flag); break; case Field::Type::Bool: v = ParseValueArray<bool>(array, field, ignore_nullable_flag); break; case Field::Type::Int: v = ParseValueArray<int>(array, field, ignore_nullable_flag); break; case Field::Type::Float: v = ParseValueArray<float>(array, field, ignore_nullable_flag); break; case Field::Type::String: v = ParseValueArray<std::string, true>(array, field, ignore_nullable_flag); break; default: throw InvalidDataError("Unexpected field type"); } } else if (field.type == Field::Type::String) { auto* string = static_cast<const String*>(data); v = string->data ? std::string(string->data) : ""; } else if (field.flags[Field::Flag::IsNullable] && !ignore_nullable_flag) { auto* nullable = static_cast<const Nullable<void>*>(data); if (nullable->data) *this = Data(nullable->data, field, ignore_array_flag, true); else v = Null{}; } else if (field.type == Field::Type::Struct) { Struct struct_; struct_.reserve(field.fields.size()); for (const Field& subfield : field.fields) { const auto* ptr = reinterpret_cast<const void*>(uintptr_t(data) + subfield.offset_in_value); struct_.emplace(subfield.name, Data{ptr, subfield, false, false}); } v = std::move(struct_); } else if (field.type == Field::Type::Bool) { v = *static_cast<const bool*>(data); } else if (field.type == Field::Type::Int) { v = *static_cast<const int*>(data); } else if (field.type == Field::Type::Float) { v = *static_cast<const float*>(data); } } SheetRw Sheet::MakeRw() const { SheetRw sheet; sheet.alignment = GetHeader().alignment; sheet.hash = GetHeader().hash; sheet.name = GetName(); sheet.root_fields.reserve(GetRootFields().size()); sheet.root_fields.assign(GetRootFields().begin(), GetRootFields().end()); sheet.values.reserve(GetHeader().num_values); for (const void* value : GetValues()) { Data::Struct struct_; struct_.reserve(sheet.root_fields.size()); for (const Field& field : sheet.root_fields) { const auto* ptr = reinterpret_cast<const void*>(uintptr_t(value) + field.offset_in_value); struct_.emplace(field.name, Data{ptr, field}); } sheet.values.emplace_back(std::move(struct_)); } return sheet; } } // namespace oead::gsheet
20,667
C++
.cpp
547
31.786106
99
0.643171
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,022
pybind11_common.h
zeldamods_oead/py/pybind11_common.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ // To be included in every translation unit. #pragma once #include <nonstd/span.h> #include <optional> #include <vector> #include <pybind11/operators.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <oead/types.h> #include <oead/util/scope_guard.h> #include "pybind11_variant_caster.h" namespace py = pybind11; using namespace py::literals; #define OEAD_MAKE_OPAQUE(NAME, ...) \ namespace pybind11::detail { \ template <> \ class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { \ public: \ static constexpr auto name = _(NAME); \ }; \ } #define OEAD_MAKE_VARIANT_CASTER(...) \ namespace pybind11::detail { \ template <> \ struct type_caster<__VA_ARGS__::Storage> : oead_variant_caster<__VA_ARGS__::Storage> {}; \ template <> \ struct type_caster<__VA_ARGS__> : oead_variant_wrapper_caster<__VA_ARGS__> {}; \ } namespace pybind11::detail { template <typename T> constexpr auto OeadGetSpanCasterName() { if constexpr (std::is_same_v<std::decay_t<T>, u8>) return _("BytesLike"); return _("Span[") + detail::concat(make_caster<T>::name) + _("]"); } template <typename T> struct type_caster<tcb::span<T>> { static handle cast(tcb::span<T> span, return_value_policy, handle) { return py::memoryview::from_memory(span.data(), ssize_t(span.size_bytes())).release(); } bool load(handle src, bool) { const py::buffer_info buffer = src.cast<py::buffer>().request(!std::is_const_v<T>); if (buffer.itemsize != sizeof(T) || buffer.ndim != 1) return false; value = {static_cast<T*>(buffer.ptr), size_t(buffer.size)}; return true; } PYBIND11_TYPE_CASTER(tcb::span<T>, OeadGetSpanCasterName<T>()); }; } // namespace pybind11::detail namespace oead::bind { inline tcb::span<u8> PyBytesToSpan(py::bytes b) { return {reinterpret_cast<u8*>(PYBIND11_BYTES_AS_STRING(b.ptr())), size_t(PYBIND11_BYTES_SIZE(b.ptr()))}; } template <typename Vector, typename holder_type = std::unique_ptr<Vector>, typename... Args> py::class_<Vector, holder_type> BindVector(py::handle scope, const std::string& name, Args&&... args) { using Value = typename Vector::value_type; auto cl = py::bind_vector<Vector, holder_type>(scope, name, std::forward<Args>(args)...); cl.def(py::self == py::self); py::implicitly_convertible<py::list, Vector>(); return cl; } template <typename Map, typename Key, typename CastFn> static Map MapFromIter(py::iterator it, CastFn cast_value) { Map map; while (it != py::iterator::sentinel()) { auto pair = py::cast<std::pair<py::handle, py::handle>>(*it); map.emplace(pair.first.cast<Key>(), cast_value(pair.second)); ++it; } return map; } template <typename Map, typename Key, typename CastFn> static Map MapFromDict(py::dict dict, CastFn cast_value) { Map map; for (std::pair<py::handle, py::handle> pair : dict) map.emplace(pair.first.cast<Key>(), cast_value(pair.second)); return map; } template <typename Map, typename Key, typename Value> static Value MapCastValue(py::handle handle) { if constexpr (std::is_convertible<Map, Value>()) { if (py::isinstance<py::dict>(handle)) return MapFromDict<Map, Key>(handle.cast<py::dict>(), MapCastValue<Map, Key, Value>); if (py::isinstance<py::iterator>(handle)) return MapFromIter<Map, Key>(handle.cast<py::iterator>(), MapCastValue<Map, Key, Value>); } return handle.cast<Value>(); } template <typename Map, typename holder_type = std::unique_ptr<Map>, typename... Args> py::class_<Map, holder_type> BindMap(py::handle scope, const std::string& name, Args&&... args) { using Key = typename Map::key_type; using Value = typename Map::mapped_type; auto cl = py::bind_map<Map, holder_type>(scope, name, std::forward<Args>(args)...) .def(py::init([&](py::iterator it) { return MapFromIter<Map, Key>(it, MapCastValue<Map, Key, Value>); }), "iterator"_a) .def(py::init([&](py::dict dict) { return MapFromDict<Map, Key>(dict, MapCastValue<Map, Key, Value>); }), "dictionary"_a) .def(py::self == py::self) .def( "__contains__", [](const Map& map, const py::object& arg) { try { auto key = py::cast<Key>(arg); return map.find(key) != map.end(); } catch (const py::cast_error&) { return false; } }, py::prepend{}) .def("clear", &Map::clear) .def( "get", [](const Map& map, const Key& key, std::optional<py::object> default_value) -> std::variant<py::object, Value> { const auto it = map.find(key); if (it == map.cend()) { if (default_value) return *default_value; throw py::key_error(); } return it->second; }, "key"_a, "default"_a = std::nullopt, py::keep_alive<0, 1>()); py::implicitly_convertible<py::dict, Map>(); return cl; } } // namespace oead::bind OEAD_MAKE_OPAQUE("oead.Bytes", std::vector<u8>); OEAD_MAKE_OPAQUE("oead.BufferInt", std::vector<int>); OEAD_MAKE_OPAQUE("oead.BufferF32", std::vector<f32>); OEAD_MAKE_OPAQUE("oead.BufferU32", std::vector<u32>); OEAD_MAKE_OPAQUE("oead.BufferBool", std::vector<bool>); OEAD_MAKE_OPAQUE("oead.BufferString", std::vector<std::string>);
7,322
C++
.h
159
39.08805
100
0.542693
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,023
pybind11_variant_caster.h
zeldamods_oead/py/pybind11_variant_caster.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <memory> #include <nonstd/visit.h> #include <type_traits> #include <variant> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <oead/types.h> #include <oead/util/type_utils.h> namespace oead::detail { template <class T> struct RemoveUniquePtr { using type = T; }; template <class T, class D> struct RemoveUniquePtr<std::unique_ptr<T, D>> { using type = T; }; } // namespace oead::detail namespace pybind11::detail { struct oead_caster_visitor { return_value_policy policy; handle parent; using result_type = handle; // required by boost::variant in C++11 template <typename U> result_type operator()(U& src) const { if constexpr (!oead::util::IsUniquePtr<std::decay_t<U>>()) { return make_caster<U>::cast(src, policy, parent); } else { using T = typename std::decay_t<U>::element_type; return make_caster<T>::cast(*src, policy, parent); } } }; template <typename Variant> struct oead_variant_caster; /// Variant of pybind11::detail::variant_caster /// which supports std::unique_ptr members. /// Also disables implicit conversions to bool. template <template <typename...> class V, typename... Ts> struct oead_variant_caster<V<Ts...>> { template <typename T, bool ptr> bool do_load(handle src, bool convert) { if constexpr (oead::util::IsAnyOfType<T, bool, u32, s32, f32, oead::U32, oead::S32, oead::F32>()) { convert = false; } auto caster = make_caster<T>(); if (caster.load(src, convert)) { if constexpr (ptr) { this->value = std::make_unique<T>(cast_op<T>(caster)); } else { this->value = cast_op<T>(caster); } return true; } return false; } template <typename U, typename... Us> bool load_alternative(handle src, bool convert, type_list<U, Us...>) { bool ok; if constexpr (oead::util::IsUniquePtr<std::decay_t<U>>()) ok = do_load<typename std::decay_t<U>::element_type, true>(src, convert); else ok = do_load<U, false>(src, convert); return ok || load_alternative(src, convert, type_list<Us...>{}); } bool load_alternative(handle, bool, type_list<>) { return false; } template <typename T> bool load_with_no_conversion(handle src) { if constexpr (oead::util::IsAnyOfType<T, Ts...>()) return load_alternative<T>(src, false, {}); else return false; } bool load(handle src, bool convert) { // Try to load the strongly typed number types first to avoid undesired conversions. if (load_with_no_conversion<oead::U8>(src)) return true; if (load_with_no_conversion<oead::U16>(src)) return true; if (load_with_no_conversion<oead::U32>(src)) return true; if (load_with_no_conversion<oead::U64>(src)) return true; if (load_with_no_conversion<oead::S8>(src)) return true; if (load_with_no_conversion<oead::S16>(src)) return true; if (load_with_no_conversion<oead::S32>(src)) return true; if (load_with_no_conversion<oead::S64>(src)) return true; if (load_with_no_conversion<oead::F32>(src)) return true; if (load_with_no_conversion<oead::F64>(src)) return true; if (convert && load_alternative(src, false, type_list<Ts...>{})) return true; return load_alternative(src, convert, type_list<Ts...>{}); } template <typename T> static handle cast(T&& src, return_value_policy policy, handle parent) { return rollbear::visit(oead_caster_visitor{policy, parent}, std::forward<T>(src)); } using Type = V<Ts...>; PYBIND11_TYPE_CASTER( Type, _("Union[") + detail::concat(make_caster< typename oead::detail::RemoveUniquePtr<std::decay_t<Ts>>::type>::name...) + _("]")); }; template <typename T> struct oead_variant_wrapper_caster { using value_conv = make_caster<typename T::Storage>; template <typename T_> static handle cast(T_&& src, return_value_policy policy, handle parent) { return value_conv::cast(src.v, policy, parent); } bool load(handle src, bool convert) { value_conv inner_caster; if (!inner_caster.load(src, convert)) return false; value.v = std::move(cast_op<typename T::Storage&&>(std::move(inner_caster))); return true; } PYBIND11_TYPE_CASTER(T, value_conv::name); }; } // namespace pybind11::detail
5,154
C++
.h
149
30.228188
100
0.667068
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,024
main.h
zeldamods_oead/py/main.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <pybind11/pybind11.h> #include "pybind11_common.h" namespace py = pybind11; namespace oead::bind { void BindAamp(py::module& m); void BindByml(py::module& m); void BindCommonTypes(py::module& m); void BindGsheet(py::module& m); void BindSarc(py::module& m); void BindYaz0(py::module& m); } // namespace oead::bind
1,042
C++
.h
30
32.933333
71
0.748259
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,025
yaml.h
zeldamods_oead/src/yaml.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <nonstd/span.h> #include <optional> #include <stdexcept> #include <string> #include <string_view> #include <tuple> #include <variant> #include <c4/std/string.hpp> #include <ryml.hpp> #include "../lib/libyaml/include/yaml.h" #include <oead/types.h> #include <oead/util/type_utils.h> namespace oead::yml { std::string FormatFloat(float value); std::string FormatDouble(double value); using Scalar = std::variant<std::nullptr_t, bool, u64, double, std::string>; bool StringNeedsQuotes(std::string_view value); enum class TagBasedType { Bool, Str, Int, Float, Null, }; using TagRecognizer = std::optional<TagBasedType> (*)(std::string_view tag); Scalar ParseScalar(std::string_view tag, std::string_view value, bool is_quoted, TagRecognizer recognizer); Scalar ParseScalar(const ryml::NodeRef& node, TagRecognizer recognizer); Scalar ParseScalarKey(const ryml::NodeRef& node, TagRecognizer recognizer); void InitRymlIfNeeded(); inline std::string_view RymlSubstrToStrView(c4::csubstr str) { return {str.data(), str.size()}; } inline c4::csubstr StrViewToRymlSubstr(std::string_view str) { return {str.data(), str.size()}; } inline std::string_view RymlGetValTag(const ryml::NodeRef& n) { return n.has_val_tag() ? RymlSubstrToStrView(n.val_tag()) : std::string_view{}; } inline std::string_view RymlGetKeyTag(const ryml::NodeRef& n) { return n.has_key_tag() ? RymlSubstrToStrView(n.key_tag()) : std::string_view{}; } inline ryml::NodeRef RymlGetMapItem(const ryml::NodeRef& n, std::string_view key) { auto child = n.is_map() ? n.find_child(StrViewToRymlSubstr(key)) : ryml::NodeRef{}; if (n.valid()) return child; throw std::out_of_range("No such key: " + std::string(key)); } class ParseError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class RymlError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class LibyamlParser { public: LibyamlParser(tcb::span<const u8> data) { yaml_parser_initialize(&m_parser); yaml_parser_set_input_string(&m_parser, data.data(), data.size()); } ~LibyamlParser() { yaml_parser_delete(&m_parser); } LibyamlParser(const LibyamlParser&) = delete; LibyamlParser& operator=(const LibyamlParser&) = delete; operator yaml_parser_t*() { return &m_parser; } template <typename Callable> void Parse(Callable event_handler) { yaml_event_t event; bool done = false; while (!done) { if (!yaml_parser_parse(&m_parser, &event)) throw ParseError("yaml_parser_parse failed"); event_handler(event); done = event.type == YAML_STREAM_END_EVENT; yaml_event_delete(&event); } } private: yaml_parser_t m_parser; }; class LibyamlEmitter { public: LibyamlEmitter(); ~LibyamlEmitter(); LibyamlEmitter(const LibyamlEmitter&) = delete; LibyamlEmitter& operator=(const LibyamlEmitter&) = delete; operator yaml_emitter_t*() { return &m_emitter; } void Emit(yaml_event_t& event, bool ignore_errors = false); void EmitScalar(std::string_view value, bool plain_implicit, bool quoted_implicit, std::string_view tag = {}) { yaml_event_t event; const auto style = value.empty() ? YAML_SINGLE_QUOTED_SCALAR_STYLE : YAML_ANY_SCALAR_STYLE; yaml_scalar_event_initialize(&event, nullptr, tag.empty() ? nullptr : (const u8*)tag.data(), (const u8*)value.data(), value.size(), plain_implicit, quoted_implicit, style); Emit(event); } void EmitNull() { EmitScalar("null", true, false); } void EmitBool(bool v, std::string_view tag = "!!bool") { EmitScalar(v ? "true" : "false", true, false, tag); } void EmitFloat(float v, std::string_view tag = "!!float") { EmitScalar(FormatFloat(v), true, false, tag); } void EmitDouble(double v, std::string_view tag = "!f64") { EmitScalar(FormatDouble(v), false, false, tag); } template <typename T = int> void EmitInt(T v, std::string_view tag = "!!int") { EmitScalar(std::to_string(v), tag == "!!int", false, tag); } void EmitString(std::string_view v, std::string_view tag) { EmitScalar(v, false, false, tag); } void EmitString(std::string_view v) { EmitScalar(v, !StringNeedsQuotes(v), true); } /// Emits an inline sequence of bools, ints or floats. template <typename T> void EmitSimpleSequence(tcb::span<const T> sequence, std::string_view sequence_tag = {}) { yaml_event_t event; yaml_sequence_start_event_initialize(&event, nullptr, (const u8*)sequence_tag.data(), sequence_tag.empty(), YAML_FLOW_SEQUENCE_STYLE); Emit(event); for (const T& v : sequence) { if constexpr (std::is_same_v<T, bool>) EmitBool(v); else if constexpr (std::is_same_v<typename NumberType<T>::type, double>) EmitDouble(v); else if constexpr (std::is_same_v<typename NumberType<T>::type, float>) EmitFloat(v); else if constexpr (std::is_integral_v<typename NumberType<T>::type>) EmitInt(v); else static_assert(util::AlwaysFalse<T>(), "Unsupported type!"); } yaml_sequence_end_event_initialize(&event); Emit(event); } template <typename T> void EmitSimpleSequence(std::initializer_list<T> l, std::string_view tag = {}) { EmitSimpleSequence(tcb::span<const T>(l.begin(), l.end()), tag); } template <typename... Ts> void EmitSimpleSequence(const std::tuple<Ts...>& tuple, std::string_view tag = {}) { std::apply([&](auto&&... args) { EmitSimpleSequence({args...}, tag); }, tuple); } struct MappingScope { MappingScope(LibyamlEmitter& emitter_, std::string_view tag, yaml_mapping_style_t style) : emitter{emitter_} { yaml_event_t event; yaml_mapping_start_event_initialize(&event, nullptr, (const u8*)tag.data(), tag.empty() ? 1 : 0, style); emitter.Emit(event); } ~MappingScope() { yaml_event_t event; yaml_mapping_end_event_initialize(&event); // Ignore errors here because this shouldn't throw... emitter.Emit(event, true); } private: LibyamlEmitter& emitter; }; protected: yaml_emitter_t m_emitter; }; template <typename Container> class LibyamlEmitterWithStorage : public LibyamlEmitter { public: LibyamlEmitterWithStorage() : LibyamlEmitter{} { const auto write_handler = [](void* userdata, u8* buffer, size_t size) { auto* self = static_cast<LibyamlEmitterWithStorage*>(userdata); self->m_output.insert(self->m_output.end(), (char*)buffer, (char*)buffer + size); return 1; }; yaml_emitter_set_output(&m_emitter, write_handler, this); } ~LibyamlEmitterWithStorage() = default; Container& GetOutput() { return m_output; } const Container& GetOutput() const { return m_output; } private: Container m_output; }; } // namespace oead::yml
7,676
C++
.h
201
33.885572
97
0.684543
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,026
gsheet.h
zeldamods_oead/src/include/oead/gsheet.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <absl/container/flat_hash_map.h> #include <memory> #include <nonstd/span.h> #include <string> #include <string_view> #include <vector> #include <easy_iterator.h> #include <oead/types.h> #include <oead/util/binary_reader.h> #include <oead/util/bit_utils.h> #include <oead/util/magic_utils.h> #include <oead/util/variant_utils.h> namespace oead::gsheet { constexpr auto Magic = util::MakeMagic("gsht"); struct ResHeader { std::array<char, 4> magic = Magic; int version = 1; /// Unknown - probably some kind of hash or ID? u32 hash = 0; u8 bool_size = 1; u8 pointer_size = 8; u8 alignment = 8; const char* name; u32 num_root_fields; u32 num_fields; void* values; u32 num_values; u32 value_size; }; static_assert(sizeof(ResHeader) == 0x30); struct ResField; /// Grezzo datasheet field. struct Field { enum class Type : u8 { /// C/C++ style structure. Struct = 0, /// Boolean. Bool = 1, /// Signed 32-bit integer. Int = 2, /// Single-precision floating point number (binary32). Float = 3, /// Null-terminated string. String = 4, }; enum class Flag : u16 { IsNullable = 1 << 0, IsArray = 1 << 1, IsKey = 1 << 2, Unknown3 = 1 << 3, IsEnum = 1 << 4, Unknown5 = 1 << 5, }; Field() = default; Field(const ResField& raw); /// Name (must not be empty). std::string name; /// Type name. std::string type_name; /// Field type. Type type; /// Unknown; depth level? u8 x11; /// Flags. util::Flags<Flag> flags; /// Offset of this field in the value structure. u16 offset_in_value; /// Size of this field in the value structure. /// For strings and arrays, this is always 0x10. u16 inline_size; /// Size of the field data. /// For strings and inline types (inline structs, ints, floats, bools), this is the same as the /// size in the value structure. u16 data_size; /// [For structs] Fields std::vector<Field> fields; constexpr auto ReflectionFields() const { return std::tie(name, type_name, type, x11, flags, offset_in_value, inline_size, data_size, fields); } friend bool operator==(const Field& a, const Field& b) { return a.ReflectionFields() == b.ReflectionFields(); } }; /// Grezzo datasheet field (serialized). struct ResField { using Type = Field::Type; using Flag = Field::Flag; ResField(); tcb::span<ResField> GetFields() const { return {fields, num_fields}; } /// Name (guaranteed to be non-null). const char* name; /// Type name. const char* type_name; /// Field type. Type type; /// Unknown; depth level? u8 x11; /// Flags. util::Flags<Flag> flags; /// Offset of this field in the value structure. u16 offset_in_value; /// Size of this field in the value structure. /// For strings and arrays, this is always 0x10. u16 inline_size; /// Size of the field data. /// For strings and inline types (inline structs, ints, floats, bools), this is the same as the /// size in the value structure. u16 data_size; /// [For structs] Number of fields u16 num_fields; /// [For structs] Fields ResField* fields; /// [For structs] Parent field (filled in during parsing; always 0xdeadbeefdeadbeef when /// serialized) ResField* parent; }; static_assert(sizeof(ResField) == 0x30); /// For defining datasheet structures. template <typename T> struct Nullable { /// Nullptr if no value. T* data = nullptr; }; /// For defining datasheet structures. template <typename T> struct Array { tcb::span<T> Span() const { return {data, size}; } operator tcb::span<T>() const { return Span(); } T* data = nullptr; u32 size = 0; private: [[maybe_unused]] u32 padding = 0; }; /// For defining datasheet structures. struct String { std::string_view Str() const { return {data, size}; } operator std::string_view() const { return Str(); } const char* data = nullptr; u32 size = 0; private: [[maybe_unused]] u32 padding = 0; }; using FieldMap = absl::flat_hash_map<std::string_view, ResField*>; FieldMap MakeFieldMap(tcb::span<ResField> fields); /// Represents a piece of field data in a datasheet. struct Data { enum class Type { Struct, Bool, Int, Float, String, StructArray, BoolArray, IntArray, FloatArray, StringArray, Null, }; using Null = std::nullptr_t; /// A struct is represented as a string to Value map, with the field names as keys. #ifdef OEAD_GSHEET_DEBUG using Struct = std::unordered_map<std::string, Data>; #else using Struct = absl::flat_hash_map<std::string, Data>; #endif using Variant = util::Variant<Type, // std::unique_ptr<Struct>, // bool, // int, // float, // std::unique_ptr<std::string>, // std::unique_ptr<std::vector<Struct>>, // std::unique_ptr<std::vector<bool>>, // std::unique_ptr<std::vector<int>>, // std::unique_ptr<std::vector<float>>, // std::unique_ptr<std::vector<std::string>>, // Null // >; Data() : v{Null{}} {} Data(const void* raw, const Field& field, bool ignore_array_flag = false, bool ignore_nullable_flag = false); template <typename T, std::enable_if_t<std::is_constructible_v<Variant, T>>* = nullptr> Data(T value) : v{std::move(value)} {} Data(const Data& other) { *this = other; } Data(Data&& other) noexcept { *this = std::move(other); } Data& operator=(const Data& other) = default; Data& operator=(Data&& other) noexcept = default; constexpr bool IsNull() const { return std::holds_alternative<Null>(v.v); } constexpr bool IsArray() const { return Type::StructArray <= v.GetType() && v.GetType() <= Type::StringArray; } template <typename Callable> auto VisitArray(Callable&& fn) const { if (auto* x = std::get_if<std::unique_ptr<std::vector<Struct>>>(&v.v)) return fn(*x->get()); if (auto* x = std::get_if<std::unique_ptr<std::vector<bool>>>(&v.v)) return fn(*x->get()); if (auto* x = std::get_if<std::unique_ptr<std::vector<int>>>(&v.v)) return fn(*x->get()); if (auto* x = std::get_if<std::unique_ptr<std::vector<float>>>(&v.v)) return fn(*x->get()); if (auto* x = std::get_if<std::unique_ptr<std::vector<std::string>>>(&v.v)) return fn(*x->get()); throw std::logic_error("Not an array"); } OEAD_DEFINE_FIELDS(Data, v) Variant v; }; static_assert(sizeof(Data) == 0x10); /// An iterator for opaque blobs for which only the element size is known. class OpaqueIterator : public easy_iterator::InitializedIterable { public: OpaqueIterator(void* begin, void* end, size_t item_size) : m_current{begin}, m_end{end}, m_item_size{item_size} {} bool advance() { m_current = reinterpret_cast<void*>(uintptr_t(m_current) + m_item_size); return m_current != m_end; } bool init() { return m_current != m_end; } void* value() { return m_current; } private: void* m_current; void* m_end; size_t m_item_size; }; /// Grezzo datasheet. /// /// This allows reading and writing binary datasheets and data modifications. /// For a readonly parser, see the Sheet class. struct SheetRw { /// Serialize the datasheet to the v1 binary format. std::vector<u8> ToBinary() const; u8 alignment = 8; u32 hash = 0; std::string name; std::vector<Field> root_fields; std::vector<Data::Struct> values; }; /// Grezzo datasheet. /// /// To actually access values that are stored in a binary datasheet, users are intended to define /// C++ structures and cast value pointers to the appropriate structure type. /// /// See also SheetRw for a version of this class that allows for reflection and modifications. class Sheet { public: Sheet(tcb::span<u8> data); ResHeader& GetHeader() const { return *reinterpret_cast<ResHeader*>(m_data.data()); } std::string_view GetName() const { return GetHeader().name; } /// Get the datasheet root fields. tcb::span<ResField> GetRootFields() const; /// Get every single datasheet field (including nested fields). tcb::span<ResField> GetAllFields() const; /// Get the datasheet values (as an iterable). auto GetValues() const { const auto& header = GetHeader(); return easy_iterator::MakeIterable<OpaqueIterator>( header.values, reinterpret_cast<void*>((uintptr_t)header.values + header.value_size * header.num_values), header.value_size); } using IntMap = absl::flat_hash_map<int, void*>; using StringMap = absl::flat_hash_map<std::string_view, void*>; const IntMap& GetIntMap() const { return m_int_map; } const StringMap& GetStringMap() const { return m_string_map; } FieldMap MakeFieldMap() const; SheetRw MakeRw() const; private: ResField* GetAllFieldsRaw() const { return reinterpret_cast<ResField*>(&GetHeader() + 1); } tcb::span<u8> m_data; /// Key field. Nullptr if there is no key field. ResField* m_key_field = nullptr; /// Only valid if there is a valid key field and the key field type is Int. IntMap m_int_map; /// Only valid if there is a valid key field and the key field type is String. StringMap m_string_map; }; } // namespace oead::gsheet
10,434
C++
.h
299
30.571906
98
0.639564
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,027
aamp.h
zeldamods_oead/src/include/oead/aamp.h
/** * Copyright (C) 2020 leoetlino <leo@leolam.fr> * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <absl/container/flat_hash_map.h> #include <absl/hash/hash.h> #include <array> #include <memory> #include <nonstd/span.h> #include <string> #include <string_view> #include <tsl/ordered_map.h> #include <variant> #include <vector> #include <oead/types.h> #include <oead/util/hash.h> #include <oead/util/variant_utils.h> namespace oead::aamp { /// A table of names that is used to recover original names in binary parameter archives /// which store only name hashes. struct NameTable { NameTable(bool with_botw_strings = false); /// Tries to guess the name that is associated with the given hash and index /// (of the parameter / object / list in its parent). /// /// The table is automatically updated with any newly found names if an indice-based guess /// was necessary. std::optional<std::string_view> GetName(u32 hash, int index, u32 parent_name_hash); /// Add a known string to the name table. /// \return a view to the added string. std::string_view AddName(std::string name) { const u32 hash = util::crc32(name); return AddName(hash, std::move(name)); } /// Add a known string to the name table. This should be used if the string's hash /// has already been computed in order to avoid recomputing it. /// \return a view to the added string. std::string_view AddName(u32 hash, std::string name); /// Add a known string to the name table. /// \warning Since this is taking a string view, the actual string data must outlive this table. void AddNameReference(std::string_view name); /// Hash to name map. The strings are only references. absl::flat_hash_map<u32, std::string_view> names; /// Hash to name map. The strings are owned. absl::flat_hash_map<u32, std::string> owned_names; /// List of numbered names (i.e. names that contain a printf specifier for the index). std::vector<std::string_view> numbered_names; }; /// Returns the default instance of the name table, which is automatically populated with /// Breath of the Wild strings. /// Initialised on first use. NameTable& GetDefaultNameTable(); /// Parameter structure name. This is a wrapper around a CRC32 hash. struct Name { constexpr Name(std::string_view name) : hash{util::crc32(name)} {} constexpr Name(const char* name) : hash{util::crc32(name)} {} constexpr Name(u32 name_crc32) : hash{name_crc32} {} operator u32() const { return hash; } /// The CRC32 hash of the name. u32 hash; OEAD_DEFINE_FIELDS(Name, hash); }; /// Parameter. /// /// Note that unlike agl::utl::Parameter the name is not stored as part of the parameter class /// in order to make the parameter logic simpler and more efficient. class Parameter { public: enum class Type : u8 { Bool = 0, F32, Int, Vec2, Vec3, Vec4, Color, String32, String64, Curve1, Curve2, Curve3, Curve4, BufferInt, BufferF32, String256, Quat, U32, BufferU32, BufferBinary, StringRef, }; using Value = util::Variant<Type, bool, float, int, Vector2f, Vector3f, Vector4f, Color4f, std::unique_ptr<FixedSafeString<32>>, std::unique_ptr<FixedSafeString<64>>, std::unique_ptr<std::array<Curve, 1>>, std::unique_ptr<std::array<Curve, 2>>, std::unique_ptr<std::array<Curve, 3>>, std::unique_ptr<std::array<Curve, 4>>, std::unique_ptr<std::vector<int>>, std::unique_ptr<std::vector<float>>, std::unique_ptr<FixedSafeString<256>>, Quatf, U32, std::unique_ptr<std::vector<u32>>, std::unique_ptr<std::vector<u8>>, std::unique_ptr<std::string>>; Parameter() = default; Parameter(const Parameter& other) { *this = other; } Parameter(Parameter&& other) noexcept { *this = std::move(other); } template <typename T, std::enable_if_t<std::is_constructible_v<Value, T>>* = nullptr> Parameter(T value) : m_value{std::move(value)} {} Parameter(F32 value) : m_value{static_cast<f32>(value)} {} Parameter& operator=(const Parameter& other) = default; Parameter& operator=(Parameter&& other) noexcept = default; OEAD_DEFINE_FIELDS(Parameter, m_value); Type GetType() const { return m_value.GetType(); } template <Type type> const auto& Get() const { return m_value.Get<type>(); } template <Type type> auto& Get() { return m_value.Get<type>(); } /// Get the value as a string view. Throws a TypeError if the parameter is not a string. std::string_view GetStringView() const; auto& GetVariant() { return m_value; } const auto& GetVariant() const { return m_value; } private: Value m_value; }; static_assert(sizeof(Parameter) <= 0x18); constexpr bool IsStringType(Parameter::Type type) { return type == Parameter::Type::String32 || type == Parameter::Type::String64 || type == Parameter::Type::String256 || type == Parameter::Type::StringRef; } constexpr bool IsBufferType(Parameter::Type type) { return type == Parameter::Type::BufferInt || type == Parameter::Type::BufferU32 || type == Parameter::Type::BufferF32 || type == Parameter::Type::BufferBinary; } using ParameterMap = tsl::ordered_map<Name, Parameter, absl::Hash<Name>, std::equal_to<Name>, std::allocator<std::pair<Name, Parameter>>, std::vector<std::pair<Name, Parameter>>>; /// Parameter object. This is essentially a dictionary of parameters. struct ParameterObject { ParameterMap params; OEAD_DEFINE_FIELDS(ParameterObject, params); }; using ParameterObjectMap = tsl::ordered_map<Name, ParameterObject, absl::Hash<Name>, std::equal_to<Name>, std::allocator<std::pair<Name, ParameterObject>>, std::vector<std::pair<Name, ParameterObject>>>; /// Parameter list. This is essentially a dictionary of parameter objects /// and a dictionary of parameter lists. struct ParameterList { ParameterObjectMap objects; tsl::ordered_map<Name, ParameterList, absl::Hash<Name>, std::equal_to<Name>, std::allocator<std::pair<Name, ParameterList>>, std::vector<std::pair<Name, ParameterList>>> lists; OEAD_DEFINE_FIELDS(ParameterList, objects, lists); }; using ParameterListMap = tsl::ordered_map<Name, ParameterList, absl::Hash<Name>, std::equal_to<Name>, std::allocator<std::pair<Name, ParameterList>>, std::vector<std::pair<Name, ParameterList>>>; /// Parameter IO. This is the root parameter list and the only structure that can be serialized to /// or deserialized from a binary parameter archive. struct ParameterIO : ParameterList { static constexpr Name ParamRootKey = Name("param_root"); /// Data version (not the AAMP format version). Typically 0. u32 version = 0; /// Data type identifier. Typically "xml". std::string type; OEAD_DEFINE_FIELDS(ParameterIO, objects, lists, version, type); /// Load a ParameterIO from a binary parameter archive. static ParameterIO FromBinary(tcb::span<const u8> data); /// Load a ParameterIO from a YAML representation. static ParameterIO FromText(std::string_view yml_text); /// Serialize the ParameterIO to a binary parameter archive. std::vector<u8> ToBinary() const; /// Serialize the ParameterIO to a YAML representation. std::string ToText() const; }; } // namespace oead::aamp
8,158
C++
.h
194
37.56701
98
0.69255
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,028
types.h
zeldamods_oead/src/include/oead/types.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <algorithm> #include <array> #include <cstddef> #include <cstdint> #include <string_view> #include <tuple> #include <utility> using u8 = std::uint8_t; using u16 = std::uint16_t; using u32 = std::uint32_t; using u64 = std::uint64_t; using s8 = std::int8_t; using s16 = std::int16_t; using s32 = std::int32_t; using s64 = std::int64_t; using size_t = std::size_t; using f32 = float; using f64 = double; namespace oead { #define OEAD_DEFINE_FIELDS(TYPE, ...) \ constexpr auto fields() { return std::tie(__VA_ARGS__); } \ constexpr auto fields() const { return std::tie(__VA_ARGS__); } \ constexpr friend bool operator==(const TYPE& lhs, const TYPE& rhs) { \ return lhs.fields() == rhs.fields(); \ } \ constexpr friend bool operator!=(const TYPE& lhs, const TYPE& rhs) { return !(lhs == rhs); } \ template <typename H> \ friend H AbslHashValue(H h, const TYPE& self) { \ return H::combine(std::move(h), self.fields()); \ } /// Strongly typed wrapper around arithmetic types /// to make types clear especially for Python bindings. template <typename T> struct Number { static_assert(std::is_arithmetic<T>(), "T must be an arithmetic type"); constexpr Number() = default; constexpr explicit Number(T v) : value{v} {} constexpr operator T() const { return value; } constexpr Number& operator=(T v) { return value = v, *this; } constexpr Number& operator++(int) { return ++value, *this; } constexpr Number& operator--(int) { return --value, *this; } constexpr Number& operator++() { return value++, *this; } constexpr Number& operator--() { return value--, *this; } constexpr Number& operator+=(T rhs) { return value += rhs, *this; } constexpr Number& operator-=(T rhs) { return value -= rhs, *this; } constexpr Number& operator*=(T rhs) { return value *= rhs, *this; } constexpr Number& operator/=(T rhs) { return value /= rhs, *this; } constexpr Number& operator%=(T rhs) { return value %= rhs, *this; } constexpr Number& operator&=(T rhs) { return value &= rhs, *this; } constexpr Number& operator|=(T rhs) { return value |= rhs, *this; } constexpr Number& operator<<=(T rhs) { return value <<= rhs, *this; } constexpr Number& operator>>=(T rhs) { return value >>= rhs, *this; } OEAD_DEFINE_FIELDS(Number, value); T value; }; using U8 = Number<std::uint8_t>; using U16 = Number<std::uint16_t>; using U32 = Number<std::uint32_t>; using U64 = Number<std::uint64_t>; using S8 = Number<std::int8_t>; using S16 = Number<std::int16_t>; using S32 = Number<std::int32_t>; using S64 = Number<std::int64_t>; using F32 = Number<float>; using F64 = Number<double>; /// Unsigned 24-bit integer. template <bool BigEndian> struct U24 { constexpr U24() = default; constexpr U24(u32 v) { Set(v); } constexpr operator u32() const { return Get(); } constexpr U24& operator=(u32 v) { return Set(v), *this; } private: constexpr u32 Get() const { if constexpr (BigEndian) return data[0] << 16 | data[1] << 8 | data[2]; else return data[2] << 16 | data[1] << 8 | data[0]; } constexpr void Set(u32 v) { if constexpr (BigEndian) { data[0] = (v >> 16) & 0xFF; data[1] = (v >> 8) & 0xFF; data[2] = v & 0xFF; } else { data[2] = (v >> 16) & 0xFF; data[1] = (v >> 8) & 0xFF; data[0] = v & 0xFF; } } std::array<u8, 3> data; }; static_assert(sizeof(U24<false>) == 3); /// Underlying type for an arithmetic type. template <typename T> struct NumberType { static_assert(std::is_arithmetic<T>(), "Only sane for arithmetic types!"); using type = T; }; /// Underlying type for an arithmetic type. template <typename T> struct NumberType<Number<T>> { using type = T; }; /// 2D vector. template <typename T> struct Vector2 { T x, y; OEAD_DEFINE_FIELDS(Vector2, x, y); }; /// 3D vector. template <typename T> struct Vector3 { T x, y, z; OEAD_DEFINE_FIELDS(Vector3, x, y, z); }; /// 4D vector. template <typename T> struct Vector4 { T x, y, z, t; OEAD_DEFINE_FIELDS(Vector4, x, y, z, t); }; using Vector2f = Vector2<float>; using Vector3f = Vector3<float>; using Vector4f = Vector4<float>; /// Quaternion. template <typename T> struct Quat { T a, b, c, d; OEAD_DEFINE_FIELDS(Quat, a, b, c, d); }; using Quatf = Quat<float>; /// RGBA color (Red/Green/Blue/Alpha). struct Color4f { float r, g, b, a; OEAD_DEFINE_FIELDS(Color4f, r, g, b, a); }; /// Curve (sead::hostio::curve*) struct Curve { u32 a, b; std::array<float, 30> floats; OEAD_DEFINE_FIELDS(Curve, a, b, floats); }; static_assert(sizeof(Curve) == 0x80); /// A string class with its own inline, fixed-size storage. template <size_t N> struct FixedSafeString { FixedSafeString() = default; FixedSafeString(std::string_view str) { *this = str; } auto& operator=(const FixedSafeString& other) { length = other.length; data = other.data; return *this; } auto& operator=(std::string_view str) { data.fill(0); length = std::min(str.size(), N); std::copy_n(str.begin(), length, data.begin()); return *this; } operator std::string_view() const { return {data.data(), length}; } bool operator==(const FixedSafeString& other) const { return Str(*this) == Str(other); } bool operator!=(const FixedSafeString& other) const { return !(*this == other); } private: size_t length = 0; std::array<char, N> data{}; }; /// Casts a string-like object to a string view. template <typename T> std::string_view Str(const T& str_like) { return static_cast<std::string_view>(str_like); } } // namespace oead
6,770
C++
.h
192
32.786458
100
0.622059
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,029
byml.h
zeldamods_oead/src/include/oead/byml.h
/** * Copyright (C) 2020 leoetlino <leo@leolam.fr> * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <absl/container/btree_map.h> #include <absl/container/flat_hash_map.h> #include <functional> #include <memory> #include <nonstd/span.h> #include <string> #include <string_view> #include <type_traits> #include <variant> #include <vector> #include <oead/errors.h> #include <oead/types.h> #include <oead/util/type_utils.h> #include <oead/util/variant_utils.h> namespace oead { /// BYML value class. This represents a generic value (array, dict, bool, float, u32, etc.) class Byml { public: enum class Type { Null = 0, String, Binary, Array, Hash, Bool, Int, Float, UInt, Int64, UInt64, Double, }; using Null = std::nullptr_t; using String = std::string; using Array = std::vector<Byml>; using Hash = absl::btree_map<std::string, Byml>; using Value = util::Variant<Type, Null, std::unique_ptr<String>, std::unique_ptr<std::vector<u8>>, std::unique_ptr<Array>, std::unique_ptr<Hash>, bool, S32, F32, U32, S64, U64, F64>; Byml() = default; Byml(const Byml& other) { *this = other; } Byml(Byml&& other) noexcept { *this = std::move(other); } template <typename T, std::enable_if_t<std::is_constructible_v<Value, T>>* = nullptr> Byml(T value) : m_value{std::move(value)} {} Byml& operator=(const Byml& other) = default; Byml& operator=(Byml&& other) noexcept = default; OEAD_DEFINE_FIELDS(Byml, m_value); Type GetType() const { return m_value.GetType(); } template <Type type> const auto& Get() const { return m_value.Get<type>(); } template <Type type> auto& Get() { return m_value.Get<type>(); } auto& GetVariant() { return m_value; } const auto& GetVariant() const { return m_value; } /// Get an item from a map/hash. template <typename T> struct Reference { Reference(T value) : m_storage{std::move(value)} {} Reference(std::reference_wrapper<T> value) : m_storage{std::move(value)} {} T* operator->() const { if (auto ptr = std::get_if<0>(&m_storage)) return ptr; if (auto ptr = std::get_if<1>(&m_storage)) return &ptr->get(); return nullptr; } T& operator*() const { return *operator->(); } private: using Storage = std::variant<T, std::reference_wrapper<T>>; Storage m_storage; }; template <Type Type, typename T> Reference<const T> Get(std::string_view key, T default_) const { auto it = GetHash().find(key); if (it == GetHash().end()) return default_; return std::cref(it->second.Get<Type>()); } template <Type Type, typename T> Reference<T> Get(std::string_view key, T default_) { auto it = GetHash().find(key); if (it == GetHash().end()) return default_; return std::ref(it->second.Get<Type>()); } /// Load a document from binary data. static Byml FromBinary(tcb::span<const u8> data); /// Load a document from YAML text. static Byml FromText(std::string_view yml_text); /// Serialize the document to BYML with the specified endianness and version number. /// This can only be done for Null, Array or Hash nodes. std::vector<u8> ToBinary(bool big_endian, int version = 2) const; /// Serialize the document to YAML. /// This can only be done for Null, Array or Hash nodes. std::string ToText() const; // These getters mirror the behaviour of Nintendo's BYML library. // Some of them will perform type conversions automatically. // If value types are incorrect, an exception is thrown. Hash& GetHash(); Array& GetArray(); String& GetString(); std::vector<u8>& GetBinary(); const Hash& GetHash() const; const Array& GetArray() const; const String& GetString() const; const std::vector<u8>& GetBinary() const; bool GetBool() const; s32 GetInt() const; u32 GetUInt() const; f32 GetFloat() const; s64 GetInt64() const; u64 GetUInt64() const; f64 GetDouble() const; private: Value m_value; }; } // namespace oead
4,707
C++
.h
140
29.921429
100
0.674802
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,030
errors.h
zeldamods_oead/src/include/oead/errors.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <stdexcept> namespace oead { /// Thrown when an operation is applied to an object of the wrong type. struct TypeError : std::runtime_error { using std::runtime_error::runtime_error; }; /// Thrown when the data that is passed to a function is invalid or otherwise unusable. struct InvalidDataError : std::runtime_error { using std::runtime_error::runtime_error; }; /// Thrown when unsupported feature is detected. struct UnsupportedError : std::runtime_error { using std::runtime_error::runtime_error; }; } // namespace oead
1,258
C++
.h
34
35.117647
87
0.755957
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,031
yaz0.h
zeldamods_oead/src/include/oead/yaz0.h
/** * Copyright (C) 2019 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <array> #include <nonstd/span.h> #include <optional> #include <vector> #include <oead/types.h> #include <oead/util/swap.h> namespace oead::yaz0 { struct Header { /// 'Yaz0' std::array<char, 4> magic; /// Size of uncompressed data u32 uncompressed_size; /// [Newer files only] Required buffer alignment u32 data_alignment; /// Unused (as of December 2019) std::array<u8, 4> reserved; OEAD_DEFINE_FIELDS(Header, magic, uncompressed_size, data_alignment, reserved); }; static_assert(sizeof(Header) == 0x10); std::optional<Header> GetHeader(tcb::span<const u8> data); /// @param src Source data /// @param data_alignment Required buffer alignment hint for decompression /// @param level Compression level (6 to 9; 6 is fastest and 9 is slowest) std::vector<u8> Compress(tcb::span<const u8> src, u32 data_alignment = 0, int level = 7); std::vector<u8> Decompress(tcb::span<const u8> src); /// For increased flexibility, allocating the destination buffer can be done manually. /// In that case, the header is assumed to be valid, and the buffer size /// must be equal to the uncompressed data size. void Decompress(tcb::span<const u8> src, tcb::span<u8> dst); /// Same, but additionally assumes that the source is well-formed. /// DO NOT USE THIS FOR UNTRUSTED SOURCES. void DecompressUnsafe(tcb::span<const u8> src, tcb::span<u8> dst); } // namespace oead::yaz0
2,129
C++
.h
52
39.076923
89
0.741171
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,032
sarc.h
zeldamods_oead/src/include/oead/sarc.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <absl/algorithm/container.h> #include <absl/container/btree_map.h> #include <absl/container/flat_hash_map.h> #include <easy_iterator.h> #include <nonstd/span.h> #include <optional> #include <string> #include <string_view> #include <oead/types.h> #include <oead/util/binary_reader.h> namespace oead { /// A simple SARC archive reader. class Sarc { public: /// A file that is stored in a SARC archive. struct File { /// File name. May be empty for file entries that do not use the file name table. std::string_view name; /// File data (as a view). tcb::span<const u8> data; bool operator==(const File& other) const { return name == other.name && absl::c_equal(data, other.data); } bool operator!=(const File& other) const { return !(*this == other); } }; /// File iterator. class FileIterator : public easy_iterator::InitializedIterable { public: FileIterator(u16 index, const Sarc& parent) : m_index{index}, m_parent{parent} {} File value() { return m_parent.GetFile(m_index); } bool advance() { return ++m_index < m_parent.GetNumFiles(); } bool init() { return m_index != m_parent.GetNumFiles(); } private: u16 m_index; const Sarc& m_parent; }; Sarc(tcb::span<const u8> data); /// Get the number of files that are stored in the archive. u16 GetNumFiles() const { return m_num_files; } /// Get the offset to the beginning of file data. u32 GetDataOffset() const { return m_data_offset; } /// Get the archive endianness. util::Endianness GetEndianness() const { return m_reader.Endian(); } /// Get a file by name. std::optional<File> GetFile(std::string_view name) const; /// Get a file by index. Throws if index >= m_num_files. File GetFile(u16 index) const; /// Returns an iterator over the contained files. auto GetFiles() const { return easy_iterator::MakeIterable<FileIterator>(0, *this); } /// Guess the minimum data alignment for files that are stored in the archive. size_t GuessMinAlignment() const; /// Returns true if and only if the raw archive data is identical. bool operator==(const Sarc& other) const; bool operator!=(const Sarc& other) const { return !(*this == other); } bool AreFilesEqual(const Sarc& other) const; private: u16 m_num_files; u16 m_entries_offset; u32 m_hash_multiplier; u32 m_data_offset; u32 m_names_offset; mutable util::BinaryReader m_reader; }; class SarcWriter { public: enum class Mode { /// Used for games with an old-style resource system that requires aligning nested SARCs /// and manual alignment of file data in archives. Legacy, /// Used for games with a new-style resource system that automatically takes care of data /// alignment and does not require manual alignment nor nested SARC alignment. New, }; SarcWriter(util::Endianness endian = util::Endianness::Little, Mode mode = Mode::New) : m_endian{endian}, m_mode{mode} {} /// Make a SarcWriter from a SARC archive. The endianness, data alignment and file content will be /// copied from the SARC. /// @param archive Source archive static SarcWriter FromSarc(const Sarc& archive); /// Write a SARC archive using the specified endianness. /// Default alignment requirements may be automatically added. /// \returns the required data alignment and the data. std::pair<u32, std::vector<u8>> Write(); /// Set the endianness. void SetEndianness(util::Endianness endian) { m_endian = endian; } /// Set the minimum data alignment. /// @param alignment Data alignment (must be a power of 2) void SetMinAlignment(size_t alignment); /// Add or modify a data alignment requirement for a file type. /// Set the alignment to 1 to revert. /// @param extension_without_dot File extension without the dot (e.g. "bgparamlist") /// @param alignment Data alignment (must be a power of 2) void AddAlignmentRequirement(std::string extension_without_dot, size_t alignment); void SetMode(Mode mode) { m_mode = mode; } /// \warning The map type is an implementation detail. using FileMap = absl::flat_hash_map<std::string, std::vector<u8>>; /// Files to be written. FileMap m_files; private: void AddDefaultAlignmentRequirements(); u32 GetAlignmentForFile(std::string_view name, tcb::span<const u8> data) const; util::Endianness m_endian = util::Endianness::Little; Mode m_mode = Mode::New; /// Multiplier to use for calculating name hashes. u32 m_hash_multiplier = 0x65; size_t m_min_alignment = 4; /// Required data alignment for specific extensions. absl::flat_hash_map<std::string, size_t> m_alignment_map; }; } // namespace oead
5,383
C++
.h
129
38.651163
100
0.719533
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,034
bit_utils.h
zeldamods_oead/src/include/oead/util/bit_utils.h
// Copyright 2017 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #pragma once #include <array> #include <climits> #include <cstddef> #include <cstring> #include <initializer_list> #include <type_traits> namespace oead::util { /// /// Retrieves the size of a type in bits. /// /// @tparam T Type to get the size of. /// /// @return the size of the type in bits. /// template <typename T> constexpr size_t BitSize() noexcept { return sizeof(T) * CHAR_BIT; } /// /// Extracts a bit from a value. /// /// @param src The value to extract a bit from. /// @param bit The bit to extract. /// /// @tparam T The type of the value. /// /// @return The extracted bit. /// template <typename T> constexpr T ExtractBit(const T src, const size_t bit) noexcept { return (src >> bit) & static_cast<T>(1); } /// /// Extracts a bit from a value. /// /// @param src The value to extract a bit from. /// /// @tparam bit The bit to extract. /// @tparam T The type of the value. /// /// @return The extracted bit. /// template <size_t bit, typename T> constexpr T ExtractBit(const T src) noexcept { static_assert(bit < BitSize<T>(), "Specified bit must be within T's bit width."); return ExtractBit(src, bit); } /// /// Extracts a range of bits from a value. /// /// @param src The value to extract the bits from. /// @param begin The beginning of the bit range. This is inclusive. /// @param end The ending of the bit range. This is inclusive. /// /// @tparam T The type of the value. /// @tparam Result The returned result type. This is the unsigned analog /// of a signed type if a signed type is passed as T. /// /// @return The extracted bits. /// template <typename T, typename Result = std::make_unsigned_t<T>> constexpr Result ExtractBits(const T src, const size_t begin, const size_t end) noexcept { return static_cast<Result>(((static_cast<Result>(src) << ((BitSize<T>() - 1) - end)) >> (BitSize<T>() - end + begin - 1))); } /// /// Extracts a range of bits from a value. /// /// @param src The value to extract the bits from. /// /// @tparam begin The beginning of the bit range. This is inclusive. /// @tparam end The ending of the bit range. This is inclusive. /// @tparam T The type of the value. /// @tparam Result The returned result type. This is the unsigned analog /// of a signed type if a signed type is passed as T. /// /// @return The extracted bits. /// template <size_t begin, size_t end, typename T, typename Result = std::make_unsigned_t<T>> constexpr Result ExtractBits(const T src) noexcept { static_assert(begin < end, "Beginning bit must be less than the ending bit."); static_assert(begin < BitSize<T>(), "Beginning bit is larger than T's bit width."); static_assert(end < BitSize<T>(), "Ending bit is larger than T's bit width."); return ExtractBits<T, Result>(src, begin, end); } /// /// Rotates a value left (ROL). /// /// @param value The value to rotate. /// @param amount The number of bits to rotate the value. /// @tparam T An unsigned type. /// /// @return The rotated value. /// template <typename T> constexpr T RotateLeft(const T value, size_t amount) noexcept { static_assert(std::is_unsigned<T>(), "Can only rotate unsigned types left."); amount %= BitSize<T>(); if (amount == 0) return value; return static_cast<T>((value << amount) | (value >> (BitSize<T>() - amount))); } /// /// Rotates a value right (ROR). /// /// @param value The value to rotate. /// @param amount The number of bits to rotate the value. /// @tparam T An unsigned type. /// /// @return The rotated value. /// template <typename T> constexpr T RotateRight(const T value, size_t amount) noexcept { static_assert(std::is_unsigned<T>(), "Can only rotate unsigned types right."); amount %= BitSize<T>(); if (amount == 0) return value; return static_cast<T>((value >> amount) | (value << (BitSize<T>() - amount))); } /// /// Verifies whether the supplied value is a valid bit mask of the form 0b00...0011...11. /// Both edge cases of all zeros and all ones are considered valid masks, too. /// /// @param mask The mask value to test for validity. /// /// @tparam T The type of the value. /// /// @return A bool indicating whether the mask is valid. /// template <typename T> constexpr bool IsValidLowMask(const T mask) noexcept { static_assert(std::is_integral<T>::value, "Mask must be an integral type."); static_assert(std::is_unsigned<T>::value, "Signed masks can introduce hard to find bugs."); // Can be efficiently determined without looping or bit counting. It's the counterpart // to https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 // and doesn't require special casing either edge case. return (mask & (mask + 1)) == 0; } /// /// Reinterpret objects of one type as another by bit-casting between object representations. /// /// @remark This is the example implementation of std::bit_cast which is to be included /// in C++2a. See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0476r2.html /// for more details. The only difference is this variant is not constexpr, /// as the mechanism for bit_cast requires a compiler built-in to have that quality. /// /// @param source The source object to convert to another representation. /// /// @tparam To The type to reinterpret source as. /// @tparam From The initial type representation of source. /// /// @return The representation of type From as type To. /// /// @pre Both To and From types must be the same size /// @pre Both To and From types must satisfy the TriviallyCopyable concept. /// template <typename To, typename From> inline To BitCast(const From& source) noexcept { static_assert(sizeof(From) == sizeof(To), "BitCast source and destination types must be equal in size."); static_assert(std::is_trivially_copyable<From>(), "BitCast source type must be trivially copyable."); static_assert(std::is_trivially_copyable<To>(), "BitCast destination type must be trivially copyable."); std::aligned_storage_t<sizeof(To), alignof(To)> storage; std::memcpy(&storage, &source, sizeof(storage)); return reinterpret_cast<To&>(storage); } template <typename T, typename PtrType> class BitCastPtrType { public: static_assert(std::is_trivially_copyable<PtrType>(), "BitCastPtr source type must be trivially copyable."); static_assert(std::is_trivially_copyable<T>(), "BitCastPtr destination type must be trivially copyable."); explicit BitCastPtrType(PtrType* ptr) : m_ptr(ptr) {} // Enable operator= only for pointers to non-const data template <typename S> inline typename std::enable_if<std::is_same<S, T>() && !std::is_const<PtrType>()>::type operator=(const S& source) { std::memcpy(m_ptr, &source, sizeof(source)); } inline operator T() const { T result; std::memcpy(&result, m_ptr, sizeof(result)); return result; } private: PtrType* m_ptr; }; // Provides an aliasing-safe alternative to reinterpret_cast'ing pointers to structs // Conversion constructor and operator= provided for a convenient syntax. // Usage: MyStruct s = BitCastPtr<MyStruct>(some_ptr); // BitCastPtr<MyStruct>(some_ptr) = s; template <typename T, typename PtrType> inline auto BitCastPtr(PtrType* ptr) noexcept -> BitCastPtrType<T, PtrType> { return BitCastPtrType<T, PtrType>{ptr}; } // Similar to BitCastPtr, but specifically for aliasing structs to arrays. template <typename ArrayType, typename T, typename Container = std::array<ArrayType, sizeof(T) / sizeof(ArrayType)>> inline auto BitCastToArray(const T& obj) noexcept -> Container { static_assert(sizeof(T) % sizeof(ArrayType) == 0, "Size of array type must be a factor of size of source type."); static_assert(std::is_trivially_copyable<T>(), "BitCastToArray source type must be trivially copyable."); static_assert(std::is_trivially_copyable<Container>(), "BitCastToArray array type must be trivially copyable."); Container result; std::memcpy(result.data(), &obj, sizeof(T)); return result; } template <typename ArrayType, typename T, typename Container = std::array<ArrayType, sizeof(T) / sizeof(ArrayType)>> inline void BitCastFromArray(const Container& array, T& obj) noexcept { static_assert(sizeof(T) % sizeof(ArrayType) == 0, "Size of array type must be a factor of size of destination type."); static_assert(std::is_trivially_copyable<Container>(), "BitCastFromArray array type must be trivially copyable."); static_assert(std::is_trivially_copyable<T>(), "BitCastFromArray destination type must be trivially copyable."); std::memcpy(&obj, array.data(), sizeof(T)); } template <typename ArrayType, typename T, typename Container = std::array<ArrayType, sizeof(T) / sizeof(ArrayType)>> inline auto BitCastFromArray(const Container& array) noexcept -> T { static_assert(sizeof(T) % sizeof(ArrayType) == 0, "Size of array type must be a factor of size of destination type."); static_assert(std::is_trivially_copyable<Container>(), "BitCastFromArray array type must be trivially copyable."); static_assert(std::is_trivially_copyable<T>(), "BitCastFromArray destination type must be trivially copyable."); T obj; std::memcpy(&obj, array.data(), sizeof(T)); return obj; } template <typename T> void SetBit(T& value, size_t bit_number, bool bit_value) { static_assert(std::is_unsigned<T>(), "SetBit is only sane on unsigned types."); if (bit_value) value |= (T{1} << bit_number); else value &= ~(T{1} << bit_number); } template <typename T> class FlagBit { public: FlagBit(std::underlying_type_t<T>& bits, T bit) : m_bits(bits), m_bit(bit) {} explicit operator bool() const { return (m_bits & static_cast<std::underlying_type_t<T>>(m_bit)) != 0; } FlagBit& operator=(const bool rhs) { if (rhs) m_bits |= static_cast<std::underlying_type_t<T>>(m_bit); else m_bits &= ~static_cast<std::underlying_type_t<T>>(m_bit); return *this; } private: std::underlying_type_t<T>& m_bits; T m_bit; }; template <typename T> class Flags { public: constexpr Flags() = default; constexpr Flags(std::initializer_list<T> bits) { for (auto bit : bits) { m_hex |= static_cast<std::underlying_type_t<T>>(bit); } } FlagBit<T> operator[](T bit) { return FlagBit(m_hex, bit); } constexpr bool operator[](T bit) const { return (m_hex & static_cast<std::underlying_type_t<T>>(bit)) != 0; } constexpr friend bool operator==(Flags a, Flags b) { return a.m_hex == b.m_hex; } std::underlying_type_t<T> m_hex = 0; }; } // namespace oead::util
10,941
C++
.h
283
35.710247
94
0.687135
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,036
binary_reader.h
zeldamods_oead/src/include/oead/util/binary_reader.h
/** * Copyright (C) 2019 leoetlino <leo@leolam.fr> * * This file is part of syaz0. * * syaz0 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. * * syaz0 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 syaz0. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <array> #include <cstring> #include <nonstd/span.h> #include <optional> #include <type_traits> #include <vector> #include <oead/types.h> #include <oead/util/align.h> #include <oead/util/bit_utils.h> #include <oead/util/swap.h> namespace oead::util { /// A simple binary data reader that automatically byteswaps and avoids undefined behaviour. class BinaryReader final { public: BinaryReader() = default; BinaryReader(tcb::span<const u8> data, Endianness endian) : m_data{data}, m_endian{endian} {} const auto& span() const { return m_data; } size_t Tell() const { return m_offset; } void Seek(size_t offset) { m_offset = offset; } Endianness Endian() const { return m_endian; } void SetEndian(Endianness endian) { m_endian = endian; } template <typename T, bool Safe = true> std::optional<T> Read(std::optional<size_t> offset = std::nullopt) { if (offset) Seek(*offset); static_assert(std::is_standard_layout<T>()); if constexpr (Safe) { if (m_offset + sizeof(T) > m_data.size()) return std::nullopt; } T value = util::BitCastPtr<T>(&m_data[m_offset]); util::SwapIfNeededInPlace(value, m_endian); m_offset += sizeof(T); return value; } template <bool Safe = true> std::optional<u32> ReadU24(std::optional<size_t> read_offset = std::nullopt) { if (read_offset) Seek(*read_offset); if constexpr (Safe) { if (m_offset + 3 > m_data.size()) return std::nullopt; } const size_t offset = m_offset; m_offset += 3; if (m_endian == Endianness::Big) return m_data[offset] << 16 | m_data[offset + 1] << 8 | m_data[offset + 2]; return m_data[offset + 2] << 16 | m_data[offset + 1] << 8 | m_data[offset]; } template <typename StringType = std::string> StringType ReadString(size_t offset, std::optional<size_t> max_len = std::nullopt) const { if (offset > m_data.size()) throw std::out_of_range("Out of bounds string read"); // Ensure strnlen doesn't go out of bounds. if (!max_len || *max_len > m_data.size() - offset) max_len = m_data.size() - offset; const char* ptr = reinterpret_cast<const char*>(&m_data[offset]); return {ptr, strnlen(ptr, *max_len)}; } private: tcb::span<const u8> m_data{}; size_t m_offset = 0; Endianness m_endian = Endianness::Big; }; template <typename T> inline void RelocateWithSize(tcb::span<u8> buffer, T*& ptr, size_t size) { const u64 offset = reinterpret_cast<u64>(ptr); if (buffer.size() < offset || buffer.size() < offset + size) throw std::out_of_range("RelocateWithSize: out of bounds"); ptr = reinterpret_cast<T*>(buffer.data() + offset); } template <typename T> inline void Relocate(tcb::span<u8> buffer, T*& ptr, size_t num_objects = 1) { RelocateWithSize(buffer, ptr, sizeof(T) * num_objects); } inline std::string_view ReadString(tcb::span<u8> buffer, const char* ptr_) { const u8* ptr = reinterpret_cast<const u8*>(ptr_); if (ptr < buffer.data() || buffer.data() + buffer.size() <= ptr) throw std::out_of_range("ReadString: out of bounds"); const size_t max_len = buffer.data() + buffer.size() - ptr; const size_t length = strnlen(ptr_, max_len); if (length == max_len) throw std::out_of_range("String is not null-terminated"); return {ptr_, length}; } template <typename Storage> class BinaryWriterBase { public: BinaryWriterBase(Endianness endian) : m_endian{endian} {} /// Returns a std::vector<u8> with everything written so far, and resets the buffer. std::vector<u8> Finalize() { return std::move(m_data); } const auto& Buffer() const { return m_data; } auto& Buffer() { return m_data; } size_t Tell() const { return m_offset; } void Seek(size_t offset) { m_offset = offset; } Endianness Endian() const { return m_endian; } BinaryReader Reader() const { return {m_data, m_endian}; } void WriteBytes(tcb::span<const u8> bytes) { if (m_offset + bytes.size() > m_data.size()) m_data.resize(m_offset + bytes.size()); std::memcpy(&m_data[m_offset], bytes.data(), bytes.size()); m_offset += bytes.size(); } template <typename T, typename std::enable_if_t<!std::is_pointer_v<T> && std::is_trivially_copyable_v<T>>* = nullptr> void Write(T value) { SwapIfNeededInPlace(value, m_endian); WriteBytes({reinterpret_cast<const u8*>(&value), sizeof(value)}); } void Write(std::string_view str) { WriteBytes({reinterpret_cast<const u8*>(str.data()), str.size()}); } void WriteCStr(std::string_view str) { Write(str); WriteNul(); } void WriteU24(u32 value) { if (m_endian == Endianness::Big) Write<U24<true>>(value); else Write<U24<false>>(value); } void WriteNul() { Write<u8>(0); } template <typename Callable> void RunAt(size_t offset, Callable fn) { const size_t current_offset = Tell(); Seek(offset); fn(current_offset); Seek(current_offset); } template <typename T> void WriteCurrentOffsetAt(size_t offset, size_t base = 0) { RunAt(offset, [this, base](size_t current_offset) { Write(T(current_offset - base)); }); } void AlignUp(size_t n) { Seek(util::AlignUp(Tell(), n)); } void GrowBuffer() { if (m_offset > m_data.size()) m_data.resize(m_offset); } private: Storage m_data; size_t m_offset = 0; Endianness m_endian; }; using BinaryWriter = BinaryWriterBase<std::vector<u8>>; } // namespace oead::util
6,217
C++
.h
165
33.884848
95
0.669934
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,037
string_utils.h
zeldamods_oead/src/include/oead/util/string_utils.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <string_view> namespace oead::util { template <typename Callback> inline void SplitStringByLine(std::string_view data, Callback cb) { size_t line_start_pos = 0; while (line_start_pos < data.size()) { const auto line_end_pos = data.find('\n', line_start_pos); if (line_start_pos != line_end_pos) { auto line = data.substr(line_start_pos, line_end_pos - line_start_pos); if (!line.empty() && line.back() == '\r') line.remove_suffix(1); cb(line); } if (line_end_pos == std::string_view::npos) break; line_start_pos = line_end_pos + 1; } } } // namespace oead::util
1,347
C++
.h
38
32.315789
77
0.695318
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,038
magic_utils.h
zeldamods_oead/src/include/oead/util/magic_utils.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <array> namespace oead::util { template <size_t N> constexpr auto MakeMagic(const char (&magic)[N]) { std::array<char, N - 1> data{}; for (size_t i = 0; i < N - 1; ++i) data[i] = magic[i]; return data; } }
941
C++
.h
29
30.344828
71
0.717751
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,039
variant_utils.h
zeldamods_oead/src/include/oead/util/variant_utils.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <nonstd/visit.h> #include <type_traits> #include <oead/util/type_utils.h> namespace oead::util { template <class... Ts> struct Overloaded : Ts... { using Ts::operator()...; }; template <class... Ts> Overloaded(Ts...)->Overloaded<Ts...>; /// Helper function to visit a std::variant efficiently. template <typename Visitor, typename... Variants> constexpr auto Visit(Visitor&& visitor, Variants&&... variants) { static_assert((rollbear::detail::is_variant_v<Variants> && ...), "need variants"); return rollbear::visit( [&visitor](auto&& value) { using T = decltype(value); if constexpr (util::IsUniquePtr<std::decay_t<T>>()) return visitor(std::forward<typename std::decay_t<T>::element_type>(*value)); else return visitor(std::forward<T>(value)); }, std::forward<Variants>(variants)...); } /// Helper function to visit a std::variant efficiently. More convenient to use in most cases. template <typename Variant, typename... Ts> constexpr auto Match(Variant&& variant, Ts&&... lambdas) { return Visit(Overloaded{std::forward<Ts>(lambdas)...}, std::forward<Variant>(variant)); } /// A std::variant wrapper that transparently dereferences unique_ptrs. This is intended for be /// used for variants that can contain possibly large values. template <typename EnumType, typename... Types> struct Variant { using Storage = std::variant<Types...>; Variant() = default; Variant(const Variant& other) { *this = other; } Variant(Variant&& other) noexcept { *this = std::move(other); } template <typename T, std::enable_if_t<IsAnyOfType<std::decay_t<T>, Types...>() || IsAnyOfType<std::unique_ptr<std::decay_t<T>>, Types...>()>* = nullptr> Variant(const T& value) { if constexpr (IsAnyOfType<std::unique_ptr<std::decay_t<T>>, Types...>()) v = std::make_unique<T>(value); else v = value; } template <typename T, std::enable_if_t<IsAnyOfType<std::decay_t<T>, Types...>() || IsAnyOfType<std::unique_ptr<std::decay_t<T>>, Types...>()>* = nullptr> Variant(T&& value) noexcept { if constexpr (IsAnyOfType<std::unique_ptr<std::decay_t<T>>, Types...>()) v = std::make_unique<T>(std::move(value)); else v = std::move(value); } Variant& operator=(const Variant& other) { Visit([this](const auto& value) { *this = value; }, other.v); return *this; } Variant& operator=(Variant&& other) noexcept { v = std::move(other.v); return *this; } template <typename H> friend H AbslHashValue(H h, const Variant& self) { return Visit([&](const auto& value) { return H::combine(std::move(h), self.v.index(), value); }, self.v); } constexpr EnumType GetType() const { return EnumType(v.index()); } template <EnumType type> const auto& Get() const { using T = std::variant_alternative_t<static_cast<size_t>(type), Storage>; if constexpr (util::IsUniquePtr<T>()) return *std::get<T>(v); else return std::get<T>(v); } template <EnumType type> auto& Get() { using T = std::variant_alternative_t<static_cast<size_t>(type), Storage>; if constexpr (util::IsUniquePtr<T>()) return *std::get<T>(v); else return std::get<T>(v); } Storage v; }; template <typename... Types> inline bool operator==(const Variant<Types...>& lhs, const Variant<Types...>& rhs) { if (lhs.v.index() != rhs.v.index()) return false; return rollbear::visit( [&](const auto& value) { using T = std::decay_t<decltype(value)>; if constexpr (util::IsUniquePtr<T>()) { const auto& other = std::get<T>(lhs.v); return other == value || *other == *value; } else { return std::get<T>(lhs.v) == value; } }, rhs.v); } } // namespace oead::util
4,617
C++
.h
123
32.861789
100
0.646401
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,040
type_utils.h
zeldamods_oead/src/include/oead/util/type_utils.h
/** * Copyright (C) 2020 leoetlino * * This file is part of oead. * * oead 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. * * oead 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 oead. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <memory> #include <type_traits> namespace oead::util { template <class... T> struct AlwaysFalse : std::false_type {}; template <class T> struct IsUniquePtr : std::false_type {}; template <class T, class D> struct IsUniquePtr<std::unique_ptr<T, D>> : std::true_type {}; template <class T, class...> struct IsAnyOfType : std::false_type {}; template <class T, class Head, class... Tail> struct IsAnyOfType<T, Head, Tail...> : std::conditional_t<std::is_same_v<T, Head>, std::true_type, IsAnyOfType<T, Tail...>> {}; template <typename T> constexpr T& AsMutable(T const& value) noexcept { return const_cast<T&>(value); } template <typename T> constexpr T* AsMutable(T const* value) noexcept { return const_cast<T*>(value); } template <typename T> constexpr T* AsMutable(T* value) noexcept { return value; } template <typename T> void AsMutable(T const&&) = delete; template <typename, template <typename> class, typename = std::void_t<>> struct Detect : std::false_type {}; template <typename T, template <typename> class Op> struct Detect<T, Op, std::void_t<Op<T>>> : std::true_type {}; template <typename T> using ExposesFieldsImpl = decltype(std::declval<T>().fields()); template <typename T> using ExposesFields = Detect<T, ExposesFieldsImpl>; } // namespace oead::util
2,012
C++
.h
56
34.25
94
0.732648
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,041
scope_guard.h
zeldamods_oead/src/include/oead/util/scope_guard.h
// Copyright 2015 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #pragma once #include <optional> namespace oead::util { template <typename Callable> class ScopeGuard final { public: ScopeGuard(Callable&& finalizer) : m_finalizer(std::forward<Callable>(finalizer)) {} ScopeGuard(ScopeGuard&& other) : m_finalizer(std::move(other.m_finalizer)) { other.m_finalizer = nullptr; } ~ScopeGuard() { Exit(); } void Dismiss() { m_finalizer.reset(); } void Exit() { if (m_finalizer) { (*m_finalizer)(); // must not throw m_finalizer.reset(); } } ScopeGuard(const ScopeGuard&) = delete; void operator=(const ScopeGuard&) = delete; private: std::optional<Callable> m_finalizer; }; } // namespace oead::util
797
C++
.h
27
26.518519
86
0.702632
zeldamods/oead
33
18
4
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,044
main.cpp
qiayuanl_rm_suspension/main.cpp
// // Created by qiayuan on 2/15/20. // #include "Simulation.h" void selectSimType(Simulation *sim); bool selectSimTime(Simulation *sim); bool selectPlaySpeed(Simulation *sim); bool selectFlyRampSpeed(Simulation *sim); int main(int argc, char **argv) { ros::init(argc, argv, "sim"); Simulation simulation; printf("\n\r\n\r RM Suspension Simulation\n\r"); printf("\n\r Author: Qiayuan Liao(liaoqiayuan@gmail.com)\n\r\n\r"); while (ros::ok()) { simulation.clearCollision(); simulation.resetSimTime(); selectSimType(&simulation); if (selectSimTime(&simulation) && ros::ok()) { while (selectPlaySpeed(&simulation) && ros::ok()) { } } } } void selectSimType(Simulation *sim) { //prepare init robot state sim->addCollisionPlane(0.7, 0, 0.); char input; while (ros::ok()) { //loop until legal input sim->setupState_.bodyPosition.setZero(); sim->setupState_.bodyVelocity.setZero(); sim->setupState_.bodyPosition[2] = 0.15; printf(" Simulation Type:\n\r"); printf(" a - Drop from 0.5 meter height\n\r"); printf(" b - Run down the stairs\n\r"); printf(" c - Brake in maximum X speed\n\r"); printf(" d - Brake in maximum Y speed\n\r"); printf(" e - Diagonally across the ramp\n\r"); printf(" f - Fly the ramp\n\r"); std::cin >> input; double stairs_height = 0.2; switch (input) { case 'a': { sim->setupState_.bodyPosition[2] = 0.5; //Reconfigure z to 0.5 meter sim->setSpeed(0.); break; } case 'b': { sim->setupState_.bodyPosition[2] = stairs_height + 0.15; //Reconfigure z sim->addCollisionBox(0.7, 0., 3., 1., stairs_height, Vec3<double>(0., 0., stairs_height / 2.), coordinateRotation<double>(CoordinateAxis::Z, 0.));//turn 0 degree sim->setSpeed(3.); sim->setupState_.bodyVelocity[3] = 3.; //[3] mean x axis break; } case 'c': { sim->setSpeed(0.); sim->setupState_.bodyVelocity[3] = 3.; break; } case 'd': { sim->setSpeed(0.); sim->setupState_.bodyVelocity[4] = 3.; break; } case 'e': { sim->addCollisionBox(0.7, 0., 2., 3., 0.1, Vec3<double>(1.6, .5, 1. * sin(0.072222 * M_PI) - 0.05), rpyToRotMat(Vec3<double>(0., -0.072222 * M_PI, M_PI_4))//turn 13 degree ); sim->setSpeed(1.); sim->setupState_.bodyVelocity[3] = 1.; break; } case 'f': { sim->setupState_.bodyPosition[2] = stairs_height + 0.15; sim->addCollisionBox(0.7, 0., (1. + 1.145) * 2, 1., stairs_height, Vec3<double>(0., 0., stairs_height / 2.), coordinateRotation<double>(CoordinateAxis::Z, 0.)); sim->addCollisionBox(0.7, 0, 1.197323, 1., 0.1, Vec3<double>(1. + 1.145 / 2. + 0.05, 0., 1.145 * tan(0.094444 * M_PI) / 2. + stairs_height - 0.05), coordinateRotation<double>(CoordinateAxis::Y, -0.094444 * M_PI)); //turn 17 degree sim->addCollisionBox(0.7, 0., 2., 1., stairs_height, Vec3<double>(3.795, 0., stairs_height / 2.), coordinateRotation<double>(CoordinateAxis::Z, 0.)); if (selectFlyRampSpeed(sim) && ros::ok()) { sim->setSpeed(sim->getFlyRampSpeed()); sim->setupState_.bodyVelocity[3] = sim->getFlyRampSpeed(); } break; } default: { printf("\n\r Illegal Input! Check and try again.\n\r"); continue; } } break; //get out on loop } sim->setRobotState(sim->setupState_); } bool selectSimTime(Simulation *sim) { char input; while (ros::ok()) { printf("\n\r Simulation Time:\n\r"); printf(" a - 0.5 s\n\r"); printf(" b - 1.0 s\n\r"); printf(" c - 2.0 s\n\r"); printf(" d - 3.0 s\n\r"); printf(" q - quit \n\r"); std::cin >> input; switch (input) { case 'a':sim->runForTime(.5); break; case 'b':sim->runForTime(1.); break; case 'c':sim->runForTime(2.); break; case 'd':sim->runForTime(3.); break; case 'q':return false; default: { printf("\n\r Illegal Input! Check and try again.\n\r"); continue; } } break; } return true; } bool selectPlaySpeed(Simulation *sim) { char input; printf("\n\r Play Speed:\n\r"); printf(" a - x1\n\r"); printf(" b - x3\n\r"); printf(" c - x5\n\r"); printf(" d - x10\n\r"); printf(" q - quit \n\r"); std::cin >> input; switch (input) { case 'a':sim->play(1); break; case 'b':sim->play(3); break; case 'c':sim->play(5); break; case 'd':sim->play(10); break; case 'q':return false; default:printf("\n\r Illegal Input! Check and try again.\n\r"); break; } return true; } bool selectFlyRampSpeed(Simulation *sim) { char input; printf("\n\rFly speed: \n\r"); printf(" a - 2.5\n\r"); printf(" b - 2.8\n\r"); printf(" c - 3.0\n\r"); printf(" d - 3.4\n\r"); printf(" e - 3.8\n\r"); std::cin >> input; while (ros::ok()) { switch (input) { case 'a' : sim->setFlyRampSpeed(2.5); break; case 'b' : sim->setFlyRampSpeed(2.8); break; case 'c' : sim->setFlyRampSpeed(3.0); break; case 'd' : sim->setFlyRampSpeed(3.4); break; case 'e' : sim->setFlyRampSpeed(3.8); break; default: { printf("\n\rIllegal Input! Check and try again.\n\r"); continue; } } break; } return true; }
5,789
C++
.cpp
184
24.244565
116
0.541101
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,045
Simulation.cpp
qiayuanl_rm_suspension/src/Simulation.cpp
// // Created by qiayuan on 2/14/20. // #include "Simulation.h" /*! * Initialize the simulator here. It is _not_ okay to block here waiting for * the robot to connect. Use firstRun() instead! */ Simulation::Simulation() : tau_(8) { // init ROS printf("[Simulation] Init ROS...\n"); markerPub_ = nh_.advertise<visualization_msgs::Marker>("visualization_marker", 10); marker_.header.frame_id = "/map"; marker_.header.stamp = ros::Time::now(); marker_.ns = "basic_shapes"; while (markerPub_.getNumSubscribers() < 1 && ros::ok()) { ROS_INFO_ONCE("[Simulation] Wait for subscriber to the marker\n"); sleep(1); } twistPub_ = nh_.advertise<geometry_msgs::Twist>("base_twist", 100); suspePub_ = nh_.advertise<rm_suspension::SuspeData>("suspe_data", 100); // init parameters printf("[Simulation] Load parameters...\n"); simParams_.getParam(&nh_); fakeSuspe_.setParams(&nh_); chassis_._params.getParam(&nh_); // init chassis info printf("[Simulation] Build chassis...\n"); printf("[Simulation] Build actuator model...\n"); actuatorModels_ = chassis_.buildActuatorModels(); // init rigid body dynamics printf("[Simulation] Build rigid body model...\n"); model_ = chassis_.buildModel(); simulator_ = new DynamicsSimulator<double>(model_, simParams_.use_spring_damper_); DVec<double> zero8(8); for (u32 i = 0; i < 8; i++) { zero8[i] = 0.; } // set some sane defaults: setupState_.q = zero8; setupState_.qd = zero8; setupState_.bodyOrientation = rotationMatrixToQuaternion( ori::coordinateRotation(CoordinateAxis::Z, 0.0)); setupState_.q = zero8; setupState_.qd = zero8; for (int wheelID = 0; wheelID < 4; ++wheelID) { setupState_.q[wheelID * 2] = fakeSuspe_.getSetupAngle(wheelID); } tau_ = zero8; printf("[Simulation] Ready!\n"); } void Simulation::step(double dt, double dtControl) { //Fake suspension for (int wheel = 0; wheel < 4; ++wheel) { suspeData_.q_[wheel] = simulator_->getState().q[wheel * 2]; suspeData_.qd_[wheel] = simulator_->getState().qd[wheel * 2]; } fakeSuspe_.update(suspeData_); for (int wheel = 0; wheel < 4; ++wheel) { tau_[wheel * 2] = fakeSuspe_.torque_out_[wheel]; } // Low level control if (currentSimTime_ >= timeOfNextLControl_) { double qd[4] = {simulator_->getState().qd[1], simulator_->getState().qd[3], simulator_->getState().qd[5], simulator_->getState().qd[7]}; controller_.update(qd); timeOfNextLControl_ = timeOfNextLControl_ + dtControl; } // actuator model: only for wheel actuator for (int wheelID = 0; wheelID < 4; wheelID++) { tau_[wheelID * 2 + 1] = actuatorModels_[0].getTorque( controller_.torque_out_[wheelID], simulator_->getState().qd[wheelID * 2 + 1]); } // dynamics currentSimTime_ += dt; // Set Homing Information RobotHomingInfo<double> homing; homing.active_flag = simParams_.go_home_; homing.position = simParams_.home_pos_; homing.rpy = simParams_.home_rpy_; homing.kp_lin = simParams_.home_kp_lin_; homing.kd_lin = simParams_.home_kd_lin_; homing.kp_ang = simParams_.home_kp_ang_; homing.kd_ang = simParams_.home_kd_ang_; simulator_->setHoming(homing); simulator_->step(dt, tau_, simParams_.floor_kp_, simParams_.floor_kd_); } /*! * Add an infinite collision plane to the simulator * @param mu : friction of the plane * @param resti : restitution coefficient * @param height : height of plane * @param addToWindow : if true, also adds graphics for the plane */ void Simulation::addCollisionPlane(double mu, double resti, double height, double sizeX, double sizeY) { simulator_->addCollisionPlane(mu, resti, height); marker_.id = 0; marker_.type = visualization_msgs::Marker::CUBE; marker_.action = visualization_msgs::Marker::ADD; marker_.pose.position.z = -0.001; marker_.pose.orientation.x = 0.0; marker_.pose.orientation.y = 0.0; marker_.pose.orientation.z = 0.0; marker_.pose.orientation.w = 1.0; // Set the scale of the marker -- 1x1x1 here means 1m on a side marker_.scale.x = sizeX; marker_.scale.y = sizeY; marker_.scale.z = 0.001; // Set the color -- be sure to set alpha to something non-zero! marker_.color.r = 1.0f; marker_.color.g = 1.0f; marker_.color.b = 1.0f; marker_.color.a = .8f; marker_.lifetime = ros::Duration(0); markerPub_.publish(marker_); } /*! * Add an box collision to the simulator * @param mu : friction of the mu * @param resti : restitution coefficient * @param depth : depth (x) of box * @param width : width (y) of box * @param height : height (z) of box * @param pos : position of box * @param ori : orientation of box * @param addToWindow : if true, also adds graphics for the plane */ void Simulation::addCollisionBox(double mu, double resti, double depth, double width, double height, const Vec3<double> &pos, const Mat3<double> &ori) { simulator_->addCollisionBox(mu, resti, depth, width, height, pos, ori); marker_.id = ++markerId_; marker_.type = visualization_msgs::Marker::CUBE; marker_.action = visualization_msgs::Marker::ADD; marker_.pose.position.x = pos.x(); marker_.pose.position.y = pos.y(); marker_.pose.position.z = pos.z(); Quat<double> quat = rotationMatrixToQuaternion(ori); marker_.pose.orientation.x = quat[1]; marker_.pose.orientation.y = quat[2]; marker_.pose.orientation.z = quat[3]; marker_.pose.orientation.w = quat[0]; // Set the scale of the marker -- 1x1x1 here means 1m on a side marker_.scale.x = depth; marker_.scale.y = width; marker_.scale.z = height; // Set the color -- be sure to set alpha to something non-zero! marker_.color.r = 1.0f; marker_.color.g = 1.0f; marker_.color.b = 1.0f; marker_.color.a = 1.0; marker_.lifetime = ros::Duration(0); markerPub_.publish(marker_); } void Simulation::addCollisionMesh(double mu, double resti, double grid_size, const Vec3<double> &left_corner_loc, const DMat<double> &height_map, bool addToWindow, bool transparent) { simulator_->addCollisionMesh(mu, resti, grid_size, left_corner_loc, height_map); } /*! * Runs the simulator for time xxx * @param */ void Simulation::runForTime(double time) { visData_.clear(); resetSimTime(); while (currentSimTime_ < time && ros::ok()) { step(simParams_.dynamics_dt_, simParams_.control_dt_); if (currentSimTime_ >= timeOfRecord_) { record(); timeOfRecord_ = currentSimTime_ + 1. / simParams_.vis_fps_; } if (ros::Time::now().toSec() >= timeOfPrint_) { printf("\r[Simulation] Computing... %.3lf%%", currentSimTime_ / time * 100.); fflush(stdout); //for console in clion timeOfPrint_ = ros::Time::now().toSec() + .2; } } } void Simulation::setSpeed(double speed) { controller_.setSpeed(speed / chassis_._params._wheelRadius); } void Simulation::record() { VisData vis_data; /////////////////////////////////record TF Data/////////////////////////////////// vis_data.tfPos[0] = simulator_->getState().bodyPosition; vis_data.tfQuat[0] = rotationMatrixToQuaternion(model_.getOrientation(5).transpose()); for (int wheelID = 0; wheelID < 4; ++wheelID) { vis_data.tfQuat[wheelID * 2 + 1] = rotationMatrixToQuaternion(model_.getOrientation(wheelID * 2 + 6).transpose()); // note!! need tranpose!!! vis_data.tfPos[wheelID * 2 + 1] = model_.getPosition(wheelID * 2 + 6); vis_data.tfQuat[wheelID * 2 + 2] = rotationMatrixToQuaternion(model_.getOrientation(wheelID * 2 + 7).transpose());// note!! need tranpose!!! vis_data.tfPos[wheelID * 2 + 2] = model_.getPosition(wheelID * 2 + 7); } //////////////////////////record contact force data/////////////////////////////// int _nTotalGC = simulator_->getTotalNumGC(); int count = 0; for (int i = 0; i < _nTotalGC; ++i) { Vec3<double> f = simulator_->getContactForce(i); if (f.norm() > .0001 && f.norm() < 1000.) { vis_data.cpForce.push_back(f); vis_data.cpPos.push_back(simulator_->getModel()._pGC[i]); count++; if (count < 4) { vis_data.suspeData.cp_force[count] = f.norm(); } } } ///////////////////////////////record base twist and suspe data for plot////////////////////////// vis_data.baseMsg.linear.x = vis_data.tfPos[0].x(); vis_data.baseMsg.linear.y = vis_data.tfPos[0].y(); vis_data.baseMsg.linear.z = vis_data.tfPos[0].z(); Vec3<double> rpy = quatToRPY(simulator_->getState().bodyOrientation); vis_data.baseMsg.angular.x = rpy.x(); vis_data.baseMsg.angular.y = rpy.y(); vis_data.baseMsg.angular.z = rpy.z(); for (int wheelID = 0; wheelID < 4; ++wheelID) { vis_data.suspeData.spring_length[wheelID] = fakeSuspe_.getSpringLength(wheelID); vis_data.suspeData.tau_suspe[wheelID] = tau_[wheelID * 2]; vis_data.suspeData.qd_wheel[wheelID] = simulator_->getState().qd[wheelID * 2 + 1]; } visData_.push_back(vis_data); } void Simulation::play(double scale) { printf("\n[Simulation] Start play!\n"); auto iter = visData_.begin(); ros::Rate loop_rate(simParams_.vis_fps_ / scale); while (ros::ok() && iter != visData_.end()) { sendTf(iter); sendCP(iter, scale); sendMsg(iter); ++iter; loop_rate.sleep(); } } void Simulation::sendTf(const vector<VisData>::iterator &iter) { tf::Quaternion quat_tf; tf::Transform tf; std::string frame; ros::Time now = ros::Time::now(); quat_tf.setValue(iter->tfQuat[0][1], iter->tfQuat[0][2], iter->tfQuat[0][3], iter->tfQuat[0][0]); tf.setRotation(quat_tf); tf.setOrigin(tf::Vector3(iter->tfPos[0].x(), iter->tfPos[0].y(), iter->tfPos[0].z())); br_.sendTransform(tf::StampedTransform(tf, now, "map", "base_link")); for (int wheelID = 0; wheelID < 4; ++wheelID) { quat_tf.setValue(iter->tfQuat[wheelID * 2 + 1][1], iter->tfQuat[wheelID * 2 + 1][2], iter->tfQuat[wheelID * 2 + 1][3], iter->tfQuat[wheelID * 2 + 1][0]); tf.setRotation(quat_tf); tf.setOrigin(tf::Vector3(iter->tfPos[wheelID * 2 + 1].x(), iter->tfPos[wheelID * 2 + 1].y(), iter->tfPos[wheelID * 2 + 1].z())); frame = "suspension_"; frame += std::to_string(wheelID); br_.sendTransform(tf::StampedTransform(tf, now, "map", frame)); quat_tf.setValue(iter->tfQuat[wheelID * 2 + 2][1], iter->tfQuat[wheelID * 2 + 2][2], iter->tfQuat[wheelID * 2 + 2][3], iter->tfQuat[wheelID * 2 + 2][0]); tf.setRotation(quat_tf); tf.setOrigin(tf::Vector3(iter->tfPos[wheelID * 2 + 2].x(), iter->tfPos[wheelID * 2 + 2].y(), iter->tfPos[wheelID * 2 + 2].z())); frame = "wheel_"; frame += std::to_string(wheelID); br_.sendTransform(tf::StampedTransform(tf, now, "map", frame)); } } void Simulation::sendCP(const vector<VisData>::iterator &iter, double scale) { visualization_msgs::Marker marker; marker.header.frame_id = "map"; marker.header.stamp = ros::Time::now(); marker.ns = "my_namespace"; marker.color.a = 1.0; // Don't forget to set the alpha! marker.color.g = 1.0; marker.scale.x = .01; marker.pose.orientation.w = 1; marker.id = 5; //large enough to avoid cover marker create at set up marker.type = visualization_msgs::Marker::LINE_LIST; marker.action = visualization_msgs::Marker::ADD; marker.lifetime = ros::Duration(1. / (simParams_.vis_fps_ / scale)); auto cpP = iter->cpPos.begin(); auto cpF = iter->cpForce.begin(); while (cpP != iter->cpPos.end()) { geometry_msgs::Point p; p.x = cpP->x(); p.y = cpP->y(); p.z = cpP->z(); marker.points.push_back(p); p.x = cpP->x() + 0.005 * cpF->x(); p.y = cpP->y() + 0.005 * cpF->y(); p.z = cpP->z() + 0.005 * cpF->z(); marker.points.push_back(p); markerPub_.publish(marker); cpP++; cpF++; marker.points.clear(); marker.id++; } } void Simulation::sendMsg(const vector<VisData>::iterator &iter) { twistPub_.publish(iter->baseMsg); suspePub_.publish(iter->suspeData); } void Simulation::clearCollision() { visualization_msgs::Marker marker; marker.action = visualization_msgs::Marker::DELETEALL; markerPub_.publish(marker); markerId_ = 0; simulator_->deleteAllCollision(); }
12,760
C++
.cpp
325
34.064615
114
0.621251
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,052
Controller.cpp
qiayuanl_rm_suspension/src/Utilities/Controller.cpp
// // Created by qiayuan on 2/17/20. // #include <Utilities/Controller.h> void Controller::update(const double *qd) { for (int wheelID = 0; wheelID < 4; ++wheelID) { torque_out_[wheelID] = .5 * (qd_des_ - qd[wheelID]); } } void Controller::setSpeed(double speed) { qd_des_ = -speed; }
296
C++
.cpp
12
22.75
56
0.657244
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,053
FakeSuspe.cpp
qiayuanl_rm_suspension/src/Utilities/FakeSuspe.cpp
// // Created by qiayuan on 2/16/20. // #include "Utilities/FakeSuspe.h" void FakeSuspe::setParams(ros::NodeHandle *nh) { params.getParam(nh); suspe0ForceAngle_ = acos(( //law of cosines params.suspe_length0_ * params.suspe_length0_ + params.suspe_length1_ * params.suspe_length1_ - params.spring_length_ * params.spring_length_) / (2. * params.suspe_length0_ * params.suspe_length1_)); } double FakeSuspe::getSetupAngle(int id) { return signTable[id] * params.suspe_q_offset_; } void FakeSuspe::update(SuspeData &data) { double q[4], qd[4]{}; for (int wheelID = 0; wheelID < 4; ++wheelID) { //Flip input according sign table q[wheelID] = signTable[wheelID] * data.q_[wheelID]; qd[wheelID] = signTable[wheelID] * data.qd_[wheelID]; //Calculate moment of suspension double suspeAngle = -q[wheelID] + suspe0ForceAngle_ + params.suspe_q_offset_; springLength_[wheelID] = sqrt(params.suspe_length0_ * params.suspe_length0_ + //law of cosines params.suspe_length1_ * params.suspe_length1_ - 2. * params.suspe_length0_ * params.suspe_length1_ * cos(suspeAngle)); double springVel = params.suspe_length0_ * params.suspe_length1_ * sin(suspeAngle) / springLength_[wheelID] * qd[wheelID]; double springForce; //Check if out of range. Use large kp and kd to simulate collision //Note that we defines the positive direction of the spring is compress direction double delta_length = params.spring_length_ - springLength_[wheelID]; if (delta_length < 0.) { springForce = 10000. * (delta_length - 0.01) - 50000. * (0 - springVel); //minus 0.001 to avoid stack on critical point } else if (delta_length > params.spring_range_) { springForce = 50000. * (delta_length - params.spring_range_ + 0.01) - 100000. * (0 - springVel); //plus 0.001 to avoid stack on critical point } else { springForce = params.spring_kp_ * delta_length - params.spring_kd_ * (0 - springVel) + params.spring_preload_[wheelID]; } double sinTheta = sin(suspeAngle) / springLength_[wheelID] * params.suspe_length0_;//law of sines torque_out_[wheelID] = -springForce * params.suspe_length1_ * sinTheta; //flip output according sign table torque_out_[wheelID] = signTable[wheelID] * torque_out_[wheelID]; } } double FakeSuspe::getSpringLength(int id) { return springLength_[id]; }
2,551
C++
.cpp
52
42.019231
115
0.649017
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,059
Chassis.cpp
qiayuanl_rm_suspension/src/Dynamics/Chassis.cpp
// // Created by qiayuan on 2/13/20. // #include "Dynamics/Chassis.h" #include "Dynamics/spatial.h" #include "Math/orientation_tools.h" using namespace ori; using namespace spatial; /*! * Build a FloatingBaseModel of the chassis */ template<typename T> FloatingBaseModel<T> Chassis<T>::buildModel() { FloatingBaseModel<T> model; // we assume the Chassis's body can be modeled as a uniformly distributed box. Vec3<T> bodyDims(_params._bodyLength, _params._bodyWidth, _params._bodyHeight); model.addBase(_params._bodyInertia); // add contact for the chassis's body model.addGroundContactBoxPoints(5, bodyDims); const int baseID = 5; int bodyID = baseID; T ySideSign[4] = {1, -1, -1, 1}; T xSideSign[4] = {1, 1, -1, -1}; Mat3<T> I3 = Mat3<T>::Identity(); // loop over 4 wheel for (int wheelID = 0; wheelID < 4; wheelID++) { // Suspe Joint bodyID++; Mat6<T> xtreeSuspe = createSXform(coordinateRotation<T>(CoordinateAxis::Z, T(M_PI)), withWheelSigns<T>(_params._suspeLocation, wheelID)); Mat6<T> xtreeSuspeRotor = createSXform(coordinateRotation<T>(CoordinateAxis::Z, T(M_PI)), withWheelSigns<T>(_params._suspeLocation, wheelID)); if (ySideSign[wheelID] < 0.) { if (xSideSign[wheelID] < 0.) { model.addBody(_params._suspeInertia.flipAlongAxis(CoordinateAxis::Y).flipAlongAxis(CoordinateAxis::X), _params._suspeRotorInertia.flipAlongAxis(CoordinateAxis::Y).flipAlongAxis(CoordinateAxis::X), 1., baseID, JointType::Revolute, CoordinateAxis::Y, xtreeSuspe, xtreeSuspeRotor); } else { model.addBody(_params._suspeInertia.flipAlongAxis(CoordinateAxis::Y), _params._suspeRotorInertia.flipAlongAxis(CoordinateAxis::Y), 1., baseID, JointType::Revolute, CoordinateAxis::Y, xtreeSuspe, xtreeSuspeRotor); } } else { if (xSideSign[wheelID] < 0.) { model.addBody(_params._suspeInertia.flipAlongAxis(CoordinateAxis::X), _params._suspeRotorInertia.flipAlongAxis(CoordinateAxis::X), 1., baseID, JointType::Revolute, CoordinateAxis::Y, xtreeSuspe, xtreeSuspeRotor); } else { model.addBody(_params._suspeInertia, _params._suspeRotorInertia, 1., baseID, JointType::Revolute, CoordinateAxis::Y, xtreeSuspe, xtreeSuspeRotor); } } // Wheel Joint bodyID++; Mat6<T> xtreeKnee = createSXform(I3, withWheelSigns<T>(_params._wheelLocation, wheelID)); Mat6<T> xtreeKneeRotor = createSXform(I3, withWheelSigns<T>(_params._wheelRotorLocation, wheelID)); if (ySideSign[wheelID] < 0) { model.addBody(_params._wheelInertia.flipAlongAxis(CoordinateAxis::Y), _params._wheelRotorInertia.flipAlongAxis(CoordinateAxis::Y), _params._wheelGearRatio, bodyID - 1, JointType::Revolute, CoordinateAxis::Y, xtreeKnee, xtreeKneeRotor); } else { model.addBody(_params._wheelInertia, _params._wheelRotorInertia, _params._wheelGearRatio, bodyID - 1, JointType::Revolute, CoordinateAxis::Y, xtreeKnee, xtreeKneeRotor); } //add "foot" of wheel for (int i = 0; i < 16; ++i) { double angle = 2. * M_PI / 16. * i; model.addGroundContactPoint (bodyID, Vec3<T>(_params._wheelRadius * sin(angle), 0, _params._wheelRadius * cos(angle)), false); } //TODO add rfid contact point } Vec3<T> g(0, 0, -9.81); model.setGravity(g); return model; } /*! * Flip signs of elements of a vector V depending on which leg it belongs to */ template<typename T, typename T2> Vec3<T> withWheelSigns(const Eigen::MatrixBase<T2> &v, int wheelID) { static_assert(T2::ColsAtCompileTime == 1 && T2::RowsAtCompileTime == 3, "Must have 3x1 matrix"); switch (wheelID) { case 0:return Vec3<T>(v[0], v[1], v[2]); case 1:return Vec3<T>(v[0], -v[1], v[2]); case 2:return Vec3<T>(-v[0], -v[1], v[2]); case 3:return Vec3<T>(-v[0], v[1], v[2]); default:throw std::runtime_error("Invalid wheel id!"); } } template<typename T> std::vector<ActuatorModel<T>> Chassis<T>::buildActuatorModels() { std::vector<ActuatorModel<T>> models; models.emplace_back(_params._wheelGearRatio, _params._motorKT, _params._motorR, _params._batteryV, _params._jointDamping, _params._jointDryFriction, _params._motorTauMax); return models; } template class Chassis<double>; template class Chassis<float>;
4,703
C++
.cpp
112
34.580357
115
0.640594
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,060
Simulation.h
qiayuanl_rm_suspension/include/Simulation.h
// // Created by qiayuan on 2/14/20. // #ifndef SUSPENSION_SIM_INCLUDE_SIMULATION_H_ #define SUSPENSION_SIM_INCLUDE_SIMULATION_H_ #include "Dynamics/Chassis.h" #include "Dynamics/DynamicsSimulator.h" #include "Utilities/FakeSuspe.h" #include "Utilities/Controller.h" #include "config.h" #include <visualization_msgs/Marker.h> #include <tf/transform_broadcaster.h> #include <rosbag/bag.h> #include <geometry_msgs/Twist.h> #include <rm_suspension/SuspeData.h> struct VisData { Quat<double> tfQuat[9]; Vec3<double> tfPos[9]; vector<Vec3<double >> cpPos; vector<Vec3<double>> cpForce; geometry_msgs::Twist baseMsg; rm_suspension::SuspeData suspeData; }; /*! * Top-level control of a simulation. * It does not include the graphics window */ class Simulation { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW explicit Simulation(); /*! * Explicitly set the state of the robot */ void setRobotState(FBModelState<double> &state) { simulator_->setState(state); } void step(double dt, double dtControl); void addCollisionPlane(double mu, double resti, double height, double sizeX = 20, double sizeY = 20); void addCollisionBox(double mu, double resti, double depth, double width, double height, const Vec3<double> &pos, const Mat3<double> &ori); void addCollisionMesh(double mu, double resti, double grid_size, const Vec3<double> &left_corner_loc, const DMat<double> &height_map, bool addToWindow = true, bool transparent = true); void clearCollision(); void setSpeed(double speed); void runForTime(double time); void play(double scale); void resetSimTime() { currentSimTime_ = 0.; timeOfNextLControl_ = 0.; timeOfPrint_ = 0; timeOfRecord_ = 0; } ~Simulation() { delete simulator_; } inline void setFlyRampSpeed(double speed) { flyRampSpeed_ = speed; } inline double getFlyRampSpeed() { return flyRampSpeed_; } FBModelState<double> setupState_; private: ros::NodeHandle nh_; ros::Publisher markerPub_; ros::Publisher twistPub_; ros::Publisher suspePub_; visualization_msgs::Marker marker_; tf::TransformBroadcaster br_; Chassis<double> chassis_; FloatingBaseModel<double> model_; DVec<double> tau_; DynamicsSimulator<double> *simulator_ = nullptr; std::vector<ActuatorModel<double>> actuatorModels_; SimParameters simParams_; FakeSuspe fakeSuspe_; SuspeData suspeData_{}; Controller controller_; vector<VisData> visData_; size_t markerId_{}; double currentSimTime_{}; double timeOfNextLControl_{}; double timeOfRecord_{}; double timeOfPrint_{}; double flyRampSpeed_{}; void record(); void sendTf(const vector<VisData>::iterator &iter); void sendCP(const vector<VisData>::iterator &iter, double scale); void sendMsg(const vector<VisData>::iterator &iter); }; #endif //SUSPENSION_SIM_INCLUDE_SIMULATION_H_
2,982
C++
.h
92
28.195652
80
0.712796
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,063
config.h
qiayuanl_rm_suspension/include/config.h
// // Created by qiayuan on 2/14/20. // #ifndef SUSPENSION_SIM_INCLUDE_CONFIG_H_ #define SUSPENSION_SIM_INCLUDE_CONFIG_H_ #include "cTypes.h" #include "cppTypes.h" #include "Math/orientation_tools.h" #include "Dynamics/SpatialInertia.h" #include <ros/ros.h> class SimParameters { public: double dynamics_dt_; double control_dt_; double vis_fps_; double floor_kp_; double floor_kd_; bool use_spring_damper_; bool go_home_; Vec3<double> home_pos_; Vec3<double> home_rpy_; double home_kp_lin_; double home_kd_lin_; double home_kp_ang_; double home_kd_ang_; void getParam(ros::NodeHandle *nh) { XmlRpc::XmlRpcValue param; nh->param<double>("dynamics_dt", dynamics_dt_, 0.00001); nh->param<double>("control_dt", control_dt_, 0.001); nh->param<double>("vis_fps", vis_fps_, 1000); nh->param<double>("floor_kp", floor_kp_, 5000); nh->param<double>("floor_kd", floor_kd_, 500000); nh->param<double>("home_kp_lin", home_kp_lin_, 2500); nh->param<double>("home_kd_lin", home_kd_lin_, 300); nh->param<double>("home_kp_ang", home_kp_ang_, 250); nh->param<double>("home_kd_ang", home_kd_ang_, 60); nh->param<bool>("use_spring_damper", use_spring_damper_, false); nh->param<bool>("go_home", go_home_, false); if (nh->getParam("home_pos", param)) home_pos_ << param[0], param[1], param[2]; if (nh->getParam("home_rpy", param)) home_rpy_ << param[0], param[1], param[2]; }; }; class SuspeParameters { public: double spring_length_; double spring_kp_; double spring_kd_; double spring_range_; double suspe_length0_; double suspe_length1_; double suspe_q_offset_; double spring_preload_[4]; void getParam(ros::NodeHandle *nh) { XmlRpc::XmlRpcValue param; nh->param<double>("spring_length", spring_length_, 0.100); nh->param<double>("spring_kp", spring_kp_, 5000.); nh->param<double>("spring_kd", spring_kd_, 200.); nh->param<double>("spring_range", spring_range_, 0.03); nh->param<double>("suspe_length0", suspe_length0_, 0.05168); nh->param<double>("suspe_length1", suspe_length1_, 0.10233); nh->param<double>("suspe_q_offset", suspe_q_offset_, -0.32); if (nh->getParam("spring_preload", param)) for (int wheelID = 0; wheelID < 4; ++wheelID) spring_preload_[wheelID] = param[wheelID]; }; }; template<typename T> class ChassisParameters { public: T _bodyMass; T _suspeMass; T _wheelMass; T _rotorMass; T _bodyLength; T _bodyWidth; T _bodyHeight; T _wheelRadius; T _wheelGearRatio; T _motorTauMax; T _batteryV; T _motorKT; // this is flux linkage * pole pairs T _motorR; T _jointDamping; T _jointDryFriction; SpatialInertia<T> _bodyInertia, _suspeInertia, _wheelInertia; SpatialInertia<T> _wheelRotorInertia, _suspeRotorInertia; Vec3<T> _suspeLocation, _wheelLocation, _wheelRotorLocation, _rfidLocation; void getParam(ros::NodeHandle *nh) { XmlRpc::XmlRpcValue param; nh->param<T>("bodyMass", _bodyMass, 12.); nh->param<T>("suspeMass", _suspeMass, .900); nh->param<T>("wheelMass", _wheelMass, .660); nh->param<T>("rotorMass", _rotorMass, .146); nh->param<T>("bodyLength", _bodyLength, .58); nh->param<T>("bodyWidth", _bodyWidth, .52); nh->param<T>("bodyHeight", _bodyHeight, 0.015); nh->param<T>("wheelRadius", _wheelRadius, 0.10233); nh->param<T>("wheelGearRatio", _wheelGearRatio, 19.); nh->param<T>("motorTauMax", _motorTauMax, .15789); nh->param<T>("batteryV", _batteryV, 24.); nh->param<T>("motorKT", _motorKT, .0059333); nh->param<T>("motorR", _motorR, .194); nh->param<T>("jointDamping", _jointDamping, .01); nh->param<T>("jointDryFriction", _jointDryFriction, .05); Mat3<T> bodyRotationalInertia; if (nh->getParam("bodyRotationalInertia", param)) bodyRotationalInertia << param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], param[8]; Mat3<T> suspeRotationalInertia; if (nh->getParam("suspeRotationalInertia", param)) suspeRotationalInertia << param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], param[8]; Mat3<T> wheelRotationalInertia; if (nh->getParam("wheelRotationalInertia", param)) wheelRotationalInertia << param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], param[8]; Mat3<T> rotorRotationalInertiaZ; if (nh->getParam("rotorRotationalInertiaZ", param)) rotorRotationalInertiaZ << param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], param[8]; Vec3<T> bodyCOM; if (nh->getParam("bodyCOM", param)) bodyCOM << param[0], param[1], param[2]; Vec3<T> suspeCOM; if (nh->getParam("suspeCOM", param)) suspeCOM << param[0], param[1], param[2]; Vec3<T> wheelCOM; if (nh->getParam("wheelCOM", param)) wheelCOM << param[0], param[1], param[2]; Vec3<T> rotorCOM(0., 0., 0.); _bodyInertia = SpatialInertia<T>(_bodyMass, bodyCOM, bodyRotationalInertia); _suspeInertia = SpatialInertia<T>(_suspeMass, suspeCOM, suspeRotationalInertia); _wheelInertia = SpatialInertia<T>(_wheelMass, wheelCOM, wheelRotationalInertia); Mat3<T> RX = coordinateRotation<T>(CoordinateAxis::X, M_PI / 2); Mat3<T> rotorRotationalInertiaY = RX * rotorRotationalInertiaZ * RX.transpose(); _suspeRotorInertia = SpatialInertia<T>(_rotorMass, rotorCOM, rotorRotationalInertiaY); _wheelRotorInertia = SpatialInertia<T>(_rotorMass, rotorCOM, rotorRotationalInertiaY); if (nh->getParam("suspeLocation", param)) _suspeLocation << param[0], param[1], param[2]; if (nh->getParam("wheelLocation", param)) _wheelLocation << param[0], param[1], param[2]; if (nh->getParam("wheelRotorLocation", param)) _wheelRotorLocation << param[0], param[1], param[2]; if (nh->getParam("rfidLocation", param)) _rfidLocation << param[0], param[1], param[2]; }; }; #endif //SUSPENSION_SIM_INCLUDE_CONFIG_H_
6,106
C++
.h
155
34.774194
90
0.661489
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,071
Controller.h
qiayuanl_rm_suspension/include/Utilities/Controller.h
// // Created by qiayuan on 2/17/20. // #ifndef SRC_RM_SUSPENSION_INCLUDE_UTILITIES_CONTROLLER_H_ #define SRC_RM_SUSPENSION_INCLUDE_UTILITIES_CONTROLLER_H_ class Controller { public: double torque_out_[4]; Controller() = default; ~Controller() = default; void setSpeed(double speed); void update(const double *qd); private: double qd_des_{}; }; #endif //SRC_RM_SUSPENSION_INCLUDE_UTILITIES_CONTROLLER_H_
420
C++
.h
16
24.25
58
0.748756
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,075
FakeSuspe.h
qiayuanl_rm_suspension/include/Utilities/FakeSuspe.h
// // Created by qiayuan on 2/16/20. // #ifndef SRC_RM_SUSPENSION_INCLUDE_UTILITIES_FAKESUSPE_H_ #define SRC_RM_SUSPENSION_INCLUDE_UTILITIES_FAKESUSPE_H_ #include <config.h> struct SuspeData { double q_[4]; double qd_[4]; }; class FakeSuspe { public: FakeSuspe() = default; ~FakeSuspe() = default; void update(SuspeData &data); void setParams(ros::NodeHandle *nh); double getSetupAngle(int id); double getSpringLength(int id); float torque_out_[4]{}; private: SuspeParameters params; double signTable[4] = {1., 1., -1., -1.}; double suspe0ForceAngle_; double springLength_[4]; }; #endif //SRC_RM_SUSPENSION_INCLUDE_UTILITIES_FAKESUSPE_H_
670
C++
.h
26
23.538462
57
0.728125
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,078
Chassis.h
qiayuanl_rm_suspension/include/Dynamics/Chassis.h
// // Created by qiayuan on 2/13/20. // #ifndef SUSPENSION_SIM_INCLUDE_DYNAMICS_CHASSIS_H_ #define SUSPENSION_SIM_INCLUDE_DYNAMICS_CHASSIS_H_ #include "Dynamics/ActuatorModel.h" #include "Dynamics/FloatingBaseModel.h" #include "Dynamics/SpatialInertia.h" #include "config.h" #include <eigen3/Eigen/StdVector> #include <vector> using std::vector; /*! * Representation of a chassis robot's physical properties. * * When viewed from the top, the chassis's wheel are: * * FRONT * 2 1 RIGHT * 3 4 * BACK * */ template<typename T> class Chassis { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW ChassisType _chassisType; FloatingBaseModel<T> buildModel(); std::vector<ActuatorModel<T>> buildActuatorModels(); ChassisParameters<T> _params; }; template<typename T, typename T2> Vec3<T> withWheelSigns(const Eigen::MatrixBase<T2> &v, int legID); #endif //SUSPENSION_SIM_INCLUDE_DYNAMICS_CHASSIS_H_
910
C++
.h
35
24.228571
66
0.7687
qiayuanl/rm_suspension
33
7
0
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,088
main.cpp
qlwz_esp_cover/src/main.cpp
#include <Arduino.h> #include <ESP8266httpUpdate.h> #include <ESP8266HTTPUpdateServer.h> #include <ESP8266WiFi.h> #include "Framework.h" #include "Cover.h" #ifdef USE_HOMEKIT #include "homekit.h" #endif void setup() { Framework::one(115200); module = new Cover(); Framework::setup(); #ifdef USE_HOMEKIT homekit_init(); #endif } void loop() { #ifdef USE_HOMEKIT homekit_loop(); #else Framework::loop(); #endif }
441
C++
.cpp
26
14.807692
36
0.726161
qlwz/esp_cover
33
24
0
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,089
Cover.cpp
qlwz_esp_cover/src/Cover.cpp
#include "Cover.h" #include "DOOYACommand.h" #ifdef USE_HOMEKIT #include "HomeKit.h" #endif #pragma region 继承 void Cover::init() { if (config.weak_switch == 126) { config.weak_switch = 127; } if (config.power_switch == 126) { config.power_switch = 127; } if (config.direction == 126) { config.direction = 127; } if (config.hand_pull == 126) { config.hand_pull = 127; } softwareSerial = new SoftwareSerial(config.pin_rx, config.pin_tx); // RX, TX softwareSerial->begin(9600); if (config.pin_led != 99) { Led::init(config.pin_led > 30 ? config.pin_led - 30 : config.pin_led, config.pin_led > 30 ? HIGH : LOW); } if (config.pin_btn != 99) { pinMode(config.pin_btn, INPUT_PULLUP); } strcpy(positionStatTopic, Mqtt::getStatTopic(F("position")).c_str()); } bool Cover::moduleLed() { if (WiFi.status() == WL_CONNECTED && Mqtt::mqttClient.connected()) { if (config.led == 0) { Led::on(); return true; } else if (config.led == 1) { Led::off(); return true; } } return false; } void Cover::loop() { readSoftwareSerialTick(); checkButton(); if (bitRead(operationFlag, 0)) { bitClear(operationFlag, 0); if (getPositionState || perSecond == 5 || perSecond % 60 == 0) { getPositionTask(); } if (config.report_interval > 0 && (perSecond % config.report_interval) == 0) { reportPosition(); } } } void Cover::perSecondDo() { bitSet(operationFlag, 0); } void Cover::checkButton() { bool buttonState = digitalRead(config.pin_btn); if (buttonState == 0) { // 按下按钮 if (buttonTiming == false) { buttonTiming = true; buttonTimingStart = millis(); } else { // buttonTiming = true if (millis() >= (buttonTimingStart + buttonDebounceTime)) { buttonAction = 1; } if (millis() >= (buttonTimingStart + buttonLongPressTime)) { buttonAction = 2; } } } else { // buttonState == 1, 释放按钮 buttonTiming = false; if (buttonAction != 0) { if (buttonAction == 1) // 执行短按动作 { Debug::AddInfo(PSTR("buttonShortPressAction")); } else if (buttonAction == 2) // 执行长按动作 { Debug::AddInfo(PSTR("buttonLongPressAction")); Wifi::setupWifiManager(false); } buttonAction = 0; } } } #pragma endregion #pragma region 配置 void Cover::readConfig() { Config::moduleReadConfig(MODULE_CFG_VERSION, sizeof(CoverConfigMessage), CoverConfigMessage_fields, &config); } void Cover::resetConfig() { Debug::AddInfo(PSTR("moduleResetConfig . . . OK")); memset(&config, 0, sizeof(CoverConfigMessage)); config.position = 127; config.direction = 127; config.hand_pull = 127; config.weak_switch = 127; config.power_switch = 127; config.pin_rx = 14; config.pin_tx = 12; config.pin_led = 34; config.pin_btn = 13; config.autoStroke = 1; } void Cover::saveConfig(bool isEverySecond) { Config::moduleSaveConfig(MODULE_CFG_VERSION, CoverConfigMessage_size, CoverConfigMessage_fields, &config); } #pragma endregion #pragma region MQTT void Cover::mqttCallback(char *topic, char *payload, char *cmnd) { uint8_t tmp[10]; uint8_t len = 0; if (strcmp(cmnd, "set_position") == 0) { uint8_t n = getInt(payload, 0, 100); len = DOOYACommand::setPosition(tmp, 0xFEFE, 0, n); getPositionState = true; } else if (strcmp(cmnd, "get_position") == 0) { len = DOOYACommand::getPosition(tmp, 0xFEFE, 0); } else if (strcmp(cmnd, "set") == 0) { if (strcmp(payload, "open") == 0) { len = DOOYACommand::open(tmp, 0xFEFE, 0); getPositionState = true; } else if (strcmp(payload, "close") == 0) { len = DOOYACommand::close(tmp, 0xFEFE, 0); getPositionState = true; } else if (strcmp(payload, "stop") == 0) { len = DOOYACommand::stop(tmp, 0xFEFE, 0); getPositionState = false; } else if (strcmp(payload, "position") == 0) { len = DOOYACommand::getPosition(tmp, 0xFEFE, 0); } } else if (strcmp(cmnd, "get") == 0) { if (strcmp(payload, "position") == 0) { len = DOOYACommand::getPosition(tmp, 0xFEFE, 0); } else if (strcmp(payload, "direction") == 0) { len = DOOYACommand::getDirectionStatus(tmp, 0xFEFE, 0); } else if (strcmp(payload, "hand_pull") == 0) { len = DOOYACommand::getHandPullStatus(tmp, 0xFEFE, 0); } else if (strcmp(payload, "motor") == 0) { len = DOOYACommand::getMotorStatus(tmp, 0xFEFE, 0); } else if (strcmp(payload, "weak_switch_type") == 0) { len = DOOYACommand::getWeakSwitchType(tmp, 0xFEFE, 0); } else if (strcmp(payload, "power_switch_type") == 0) { len = DOOYACommand::getPowerSwitchType(tmp, 0xFEFE, 0); } else if (strcmp(payload, "protocol_version") == 0) { len = DOOYACommand::getProtocolVersion(tmp, 0xFEFE, 0); } } else if (strcmp(cmnd, "delete_trip") == 0) { len = DOOYACommand::deleteTrip(tmp, 0xFEFE, 0); } else if (strcmp(cmnd, "reset") == 0) { len = DOOYACommand::reset(tmp, 0xFEFE, 0); } else if (strcmp(cmnd, "set_scene") == 0) { uint8_t n = getInt(payload, 1, 254); len = DOOYACommand::setScene(tmp, 0xFEFE, 0, n); } else if (strcmp(cmnd, "run_scene") == 0) { uint8_t n = getInt(payload, 1, 254); len = DOOYACommand::runScene(tmp, 0xFEFE, 0, n); } else if (strcmp(cmnd, "delete_scene") == 0) { uint8_t n = getInt(payload, 1, 254); len = DOOYACommand::deleteScene(tmp, 0xFEFE, 0, n); } else if (strcmp(cmnd, "open_close") == 0) { len = DOOYACommand::openOrClose(tmp, 0xFEFE, 0); } if (len > 0) { softwareSerial->write(tmp, len); } } void Cover::mqttDiscovery(bool isEnable) { char topic[50]; sprintf(topic, PSTR("%s/cover/%s/config"), globalConfig.mqtt.discovery_prefix, UID); if (isEnable) { char message[500]; sprintf(message, PSTR("{\"name\":\"%s\"," "\"cmd_t\":\"%s\"," "\"pl_open\":\"open\"," "\"pl_cls\":\"close\"," "\"pl_stop\":\"stop\"," "\"pos_t\":\"%s\"," "\"set_pos_t\":\"%s\"," "\"position_open\":100," "\"position_closed\":0," "\"avty_t\":\"%s\"," "\"pl_avail\":\"online\"," "\"pl_not_avail\":\"offline\"}"), UID, Mqtt::getCmndTopic(F("set")).c_str(), positionStatTopic, Mqtt::getCmndTopic(F("set_position")).c_str(), Mqtt::getTeleTopic(F("availability")).c_str()); //Debug::AddInfo(PSTR("discovery: %s - %s"), topic, message); Mqtt::publish(topic, message, true); Mqtt::availability(); } else { Mqtt::publish(topic, "", true); } } void Cover::mqttConnected() { if (globalConfig.mqtt.discovery) { mqttDiscovery(true); } getPositionTask(); } #pragma endregion #pragma region HTTP void Cover::httpAdd(ESP8266WebServer *server) { server->on(F("/cover_position"), std::bind(&Cover::httpPosition, this, server)); server->on(F("/cover_set"), std::bind(&Cover::httpDo, this, server)); server->on(F("/cover_setting"), std::bind(&Cover::httpSetting, this, server)); server->on(F("/cover_reset"), std::bind(&Cover::httpReset, this, server)); server->on(F("/ha"), std::bind(&Cover::httpHa, this, server)); #ifdef USE_HOMEKIT server->on(F("/homekit"), std::bind(&homekit_http, server)); #endif } String Cover::httpGetStatus(ESP8266WebServer *server) { String data = F("\"position\":"); data += config.position; return data; } void Cover::httpHtml(ESP8266WebServer *server) { server->sendContent_P( PSTR("<table class='gridtable'><thead><tr><th colspan='2'>控制窗帘</th></tr></thead><tbody>" "<tr><td>操作</td><td><button type='button' class='btn-success' style='width:50px' id='cover_open' onclick=\"coverSet('open')\">开</button> " "<button type='button' class='btn-success' style='width:50px' onclick=\"coverSet('stop')\">停</button> " "<button type='button' class='btn-success' style='width:50px' id='cover_close' onclick=\"coverSet('close')\">关</button></td></tr>")); snprintf_P(tmpData, sizeof(tmpData), PSTR("<tr><td>当前位置</td><td><input type='range' min='0' max='100' id='position' name='position' value='%d' onchange='rangOnChange(this)'/>&nbsp;<span>%d%%</span></td></tr>"), config.position, config.position); server->sendContent_P(tmpData); server->sendContent_P( PSTR("<form method='post' action='/cover_setting' onsubmit='postform(this);return false'>" "<table class='gridtable'><thead><tr><th colspan='2'>窗帘设置</th></tr></thead><tbody>" "<tr><td>电机方向</td><td>" "<label class='bui-radios-label'><input type='radio' name='direction' value='0'/><i class='bui-radios'></i> 默认方向</label>&nbsp;&nbsp;&nbsp;&nbsp;" "<label class='bui-radios-label'><input type='radio' name='direction' value='1'/><i class='bui-radios'></i> 反方向</label>" "</td></tr>" "<tr><td>手拉使能</td><td>" "<label class='bui-radios-label'><input type='radio' name='hand_pull' value='0'/><i class='bui-radios'></i> 开启</label>&nbsp;&nbsp;&nbsp;&nbsp;" "<label class='bui-radios-label'><input type='radio' name='hand_pull' value='1'/><i class='bui-radios'></i> 关闭</label>" "</td></tr>" "<tr><td>弱点开关</td><td>" "<label class='bui-radios-label'><input type='radio' name='weak_switch' value='1'/><i class='bui-radios'></i> 双反弹开关</label><br/>" "<label class='bui-radios-label'><input type='radio' name='weak_switch' value='2'/><i class='bui-radios'></i> 双不反弹开关</label><br/>" "<label class='bui-radios-label'><input type='radio' name='weak_switch' value='3'/><i class='bui-radios'></i> DC246电子开关</label><br/>" "<label class='bui-radios-label'><input type='radio' name='weak_switch' value='4'/><i class='bui-radios'></i> 单键循环开关</label>" "</td></tr>" "<tr><td>强电开关</td><td>" "<label class='bui-radios-label'><input type='radio' name='power_switch' value='0'/><i class='bui-radios'></i> 强电双键不反弹模式</label><br/>" "<label class='bui-radios-label'><input type='radio' name='power_switch' value='1'/><i class='bui-radios'></i> 酒店模式</label><br/>" "<label class='bui-radios-label'><input type='radio' name='power_switch' value='2'/><i class='bui-radios'></i> 强电双键可反弹模式</label>" "</td></tr>" "<tr><td>LED</td><td>" "<label class='bui-radios-label'><input type='radio' name='led' value='0'/><i class='bui-radios'></i> 常亮</label>&nbsp;&nbsp;&nbsp;&nbsp;" "<label class='bui-radios-label'><input type='radio' name='led' value='1'/><i class='bui-radios'></i> 常灭</label>&nbsp;&nbsp;&nbsp;&nbsp;" "<label class='bui-radios-label'><input type='radio' name='led' value='2'/><i class='bui-radios'></i> 闪烁</label><br>未连接WIFI或者MQTT时为快闪" "</td></tr>")); snprintf_P(tmpData, sizeof(tmpData), PSTR("<tr><td>主动上报间隔</td><td><input type='number' min='0' max='3600' name='report_interval' required value='%d'>&nbsp;秒,0关闭</td></tr>"), config.report_interval); server->sendContent_P(tmpData); server->sendContent_P( PSTR("<tr><td>自动行程</td><td>" "<label class='bui-radios-label'><input type='radio' name='autoStroke' value='0'/><i class='bui-radios'></i> 否</label>&nbsp;&nbsp;&nbsp;&nbsp;" "<label class='bui-radios-label'><input type='radio' name='autoStroke' value='1'/><i class='bui-radios'></i> 是</label>" "</td></tr>")); server->sendContent_P( PSTR("<tr><td colspan='2'><button type='submit' class='btn-info'>设置</button><br>" "<button type='button' class='btn-success' style='margin-top:10px' onclick='window.location.href=\"/ha\"'>下载HA配置文件</button><br>" "<button type='button' class='btn-danger' style='margin-top: 10px' onclick=\"javascript:if(confirm('确定要电机恢复出厂设置?')){ajaxPost('/cover_reset');}\">电机恢复出厂</button>" "</td></tr>" "</tbody></table></form>")); #ifdef USE_HOMEKIT homekit_html(server); #endif server->sendContent_P( PSTR("<script type='text/javascript'>" "var iscover=0;function setDataSub(data,key){if(key=='position'){var t=id(key);var v=data[key];if(iscover>0&&v==t.value&&iscover++>5){iscover=0;intervalTime=defIntervalTime}t.value=v;t.nextSibling.nextSibling.innerHTML=v+'%';id('cover_open').disabled=v==100;id('cover_close').disabled=v==0;return true}return false}" "function coverSet(t){ajaxPost('/cover_set','do='+t);iscover=1;intervalTime=1000}function rangOnChange(the){the.nextSibling.nextSibling.innerHTML=the.value+'%';ajaxPost('/cover_position', 'position=' + the.value);iscover=1;intervalTime=1000}")); snprintf_P(tmpData, sizeof(tmpData), PSTR("setRadioValue('direction', '%d');" "setRadioValue('hand_pull', '%d');" "setRadioValue('weak_switch', '%d');" "setRadioValue('power_switch', '%d');" "setRadioValue('led', '%d');" "setRadioValue('autoStroke', '%d');"), config.direction, config.hand_pull, config.weak_switch, config.power_switch, config.led, config.autoStroke); server->sendContent_P(tmpData); server->sendContent_P(PSTR("</script>")); } uint8_t Cover::getInt(char *str, uint8_t min, uint8_t max) { uint8_t n = atoi(str); if (n > max) n = max; if (n < min) n = min; return n; } void Cover::httpPosition(ESP8266WebServer *server) { int position = server->arg(F("position")).toInt(); if (position > 100) position = 100; if (position < 0) position = 0; uint8_t tmp[10]; int len = DOOYACommand::setPosition(tmp, 0xFEFE, 0, position); softwareSerial->write(tmp, len); delay(100); getPositionState = true; server->setContentLength(CONTENT_LENGTH_UNKNOWN); server->send_P(200, PSTR("application/json"), PSTR("{\"code\":1,\"msg\":\"已设置窗帘位置。\",\"data\":{")); server->sendContent(httpGetStatus(server)); server->sendContent_P(PSTR("}}")); } void Cover::httpDo(ESP8266WebServer *server) { String str = server->arg(F("do")); uint8_t tmp[10]; int len; if (str.equals(F("open"))) { len = DOOYACommand::open(tmp, 0xFEFE, 0); getPositionState = true; } else if (str.equals(F("close"))) { len = DOOYACommand::close(tmp, 0xFEFE, 0); getPositionState = true; } else if (str.equals(F("stop"))) { len = DOOYACommand::stop(tmp, 0xFEFE, 0); getPositionState = false; } else { server->send_P(200, PSTR("application/json"), PSTR("{\"code\":0,\"msg\":\"没有该操作。\"}")); return; } softwareSerial->write(tmp, len); delay(100); server->send_P(200, PSTR("application/json"), PSTR("{\"code\":1,\"msg\":\"已执行窗帘操作。\"}")); } void Cover::httpSetting(ESP8266WebServer *server) { uint8_t tmp[10]; int len; config.led = server->arg(F("led")).toInt(); if (server->hasArg(F("report_interval"))) { config.report_interval = server->arg(F("report_interval")).toInt(); } if (server->hasArg(F("direction"))) { uint8_t direction = server->arg(F("direction")).toInt(); if (direction != config.direction) { len = DOOYACommand::setDirection(tmp, 0xFEFE, 0, direction != 1); softwareSerial->write(tmp, len); delay(100); len = DOOYACommand::getDirectionStatus(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); len = DOOYACommand::getPosition(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); } } if (server->hasArg(F("hand_pull"))) { uint8_t handPull = server->arg(F("hand_pull")).toInt(); if (handPull != config.hand_pull) { len = DOOYACommand::setHandPull(tmp, 0xFEFE, 0, handPull != 1); softwareSerial->write(tmp, len); delay(100); len = DOOYACommand::getHandPullStatus(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); } } if (server->hasArg(F("weak_switch"))) { config.weak_switch == 127; String weakSwitch = server->arg(F("weak_switch")); len = DOOYACommand::setWeakSwitchType(tmp, 0xFEFE, 0, weakSwitch.equals(F("2")) ? 0x02 : (weakSwitch.equals(F("3")) ? 0x03 : (weakSwitch.equals(F("4")) ? 0x04 : 0x01))); softwareSerial->write(tmp, len); delay(100); } if (server->hasArg(F("power_switch"))) { config.power_switch == 127; String powerSwitch = server->arg(F("power_switch")); len = DOOYACommand::setPowerSwitchType(tmp, 0xFEFE, 0, powerSwitch.equals(F("1")) ? 0x01 : (powerSwitch.equals(F("2")) ? 0x02 : 0x00)); softwareSerial->write(tmp, len); } server->send_P(200, PSTR("application/json"), PSTR("{\"code\":1,\"msg\":\"已经设置。\"}")); } void Cover::httpReset(ESP8266WebServer *server) { server->send_P(200, PSTR("application/json"), PSTR("{\"code\":1,\"msg\":\"正在重置电机 . . . 设备将会重启。\"}")); delay(200); Led::blinkLED(400, 4); uint8_t tmp[10]; int len; DOOYACommand::reset(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); config.position = 127; config.direction = 127; config.hand_pull = 127; config.weak_switch = 127; config.power_switch = 127; Config::saveConfig(); ESP.restart(); } void Cover::httpHa(ESP8266WebServer *server) { char attachment[100]; snprintf_P(attachment, sizeof(attachment), PSTR("attachment; filename=%s.yaml"), UID); server->setContentLength(CONTENT_LENGTH_UNKNOWN); server->sendHeader(F("Content-Disposition"), attachment); server->send_P(200, PSTR("Content-Type: application/octet-stream"), ""); snprintf_P(tmpData, sizeof(tmpData), PSTR("cover:\r\n" " - platform: mqtt\r\n" " name: \"%s\"\r\n" " command_topic: \"%s\"\r\n" " position_topic: \"%s\"\r\n" " set_position_topic: \"%s\"\r\n" " payload_open: \"open\"\r\n" " payload_close: \"close\"\r\n" " payload_stop: \"stop\"\r\n" " position_open: 100\r\n" " position_closed: 0\r\n" " availability_topic: \"%s\"\r\n" " payload_available: \"online\"\r\n" " payload_not_available: \"offline\"\r\n\r\n"), UID, Mqtt::getCmndTopic(F("set")).c_str(), positionStatTopic, Mqtt::getCmndTopic(F("set_position")).c_str(), Mqtt::getTeleTopic(F("availability")).c_str()); server->sendContent_P(tmpData); } #pragma endregion void Cover::doPosition(uint8_t position, uint8_t command) { if (position == 255) { if (!config.autoStroke) { return; } // 自动设置行程 Debug::AddInfo(PSTR("AutoStroke: %d"), autoStroke ? 1 : 0); if (!autoStroke) { autoStroke = true; delay(100); uint8_t tmp[10]; uint8_t len2 = DOOYACommand::open(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len2); getPositionState = true; if (config.position > 127) { config.position = 100; } Debug::AddInfo(PSTR("Start Auto Stroke: Last %d"), config.position); } return; } if (autoStroke && (position == 100 || position == 0)) // 设置完行程回到原来的位置 { config.weak_switch = 127; config.power_switch = 127; autoStroke = false; delay(100); Debug::AddInfo(PSTR("Stop Auto Stroke: Last %d"), config.position); uint8_t tmp[10]; uint8_t len2 = DOOYACommand::setPosition(tmp, 0xFEFE, 0, config.position); softwareSerial->write(tmp, len2); getPositionState = true; } else if (config.position != position) { Debug::AddInfo(PSTR("Position: %d"), position); config.position = position; Mqtt::publish(positionStatTopic, String(config.position).c_str(), globalConfig.mqtt.retain); } } void Cover::doSoftwareSerialTick(uint8_t *buf, int len) { DOOYACommand::Command command = DOOYACommand::parserReplyCommand(buf, len); //char strHex[50]; //DOOYACommand::hex2Str(buf, len, strHex, true); //Debug::AddInfo(PSTR("%s: %s"), (command.command == 0x01 ? "Read" : (command.command == 0x02 ? "Write" : (command.command == 0x03 ? "Control" : (command.command == 0x04 ? "Request" : "??")))), strHex); if (command.command == 0x01) { String topic; if (command.address == 0x02) { if (getPositionState && (command.data[0] == 0 || command.data[0] == 100)) { getPositionState = false; } doPosition(command.data[0], command.command); return; } switch (command.address) { case 0x02: break; case 0x03: topic = Mqtt::getStatTopic(F("direction")); config.direction = command.data[0]; break; case 0x04: topic = Mqtt::getStatTopic(F("hand_pull")); config.hand_pull = command.data[0]; break; case 0x05: topic = Mqtt::getStatTopic(F("motor")); break; case 0x27: config.weak_switch = command.data[0]; topic = Mqtt::getStatTopic(F("weak_switch_type")); break; case 0x28: config.power_switch = command.data[0]; topic = Mqtt::getStatTopic(F("power_switch_type")); break; case 0xFE: topic = Mqtt::getStatTopic(F("protocol_version")); break; default: break; } if (topic.length() > 0) { Mqtt::publish(topic.c_str(), command.data, command.dataLen, globalConfig.mqtt.retain); } } else if (command.command == 0x02) { } else if (command.command == 0x03) { } else if (command.command == 0x04) { if (command.address == 0x02 && command.dataLen == 8) { // 0 : 百分比 // 1 :电机方向 0默认 1反向 // 2 :手拉使能 0开启 1关闭 // 3 : 0电机停止 1开 2关 4电机卡停 // 7 : 行程 0未设置行程 1已设置行程 config.direction = command.data[1]; config.hand_pull = command.data[2]; if (command.data[3] == 0 || command.data[3] == 4) // 0电机停止 1 开 2 关 4 电机卡停 { isRun = false; if (autoStroke && command.data[0] == 0xFF) { uint8_t tmp[10]; uint8_t len2 = DOOYACommand::close(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len2); getPositionState = true; delay(100); } else { getPositionState = false; } } else { isRun = true; getPositionState = true; } doPosition(command.data[0], command.command); } } } /* 软串串口数据接受进程 */ void Cover::readSoftwareSerialTick() { while (softwareSerial->available()) { uint8_t c = softwareSerial->read(); Serial.printf("%02X ", c); if (softwareSerialPos == 0 && c != 0x55) { // 第一个字节不是0x55 抛弃 Serial.print(F("\nBuff NO 0x55\n")); continue; } if (softwareSerialPos == 0) { // 记录0x55时间 softwareSerialTime = millis(); } softwareSerialBuff[softwareSerialPos++] = c; if (softwareSerialPos >= 6 && softwareSerialBuff[softwareSerialPos - 1] * 256 + softwareSerialBuff[softwareSerialPos - 2] == DOOYACommand::crc16(softwareSerialBuff, softwareSerialPos - 2)) // crc 正确 { Serial.println(); softwareSerialBuff[softwareSerialPos] = 0x00; doSoftwareSerialTick(softwareSerialBuff, softwareSerialPos); //Led::led(200); softwareSerialPos = 0; } else if (softwareSerialPos > 15) { Debug::AddInfo(PSTR("\nBuff Len Error")); softwareSerialPos = 0; } } if (softwareSerialPos > 0 && (millis() - softwareSerialTime >= 100)) { // 距离0x55 超过100ms则抛弃指令 softwareSerialPos = 0; } } void Cover::getPositionTask() { uint8_t tmp[10]; uint8_t len; if (config.weak_switch == 127) { config.weak_switch = 126; len = DOOYACommand::getWeakSwitchType(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); } if (config.power_switch == 127) { config.power_switch = 126; len = DOOYACommand::getPowerSwitchType(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); } if (config.hand_pull == 127) { config.hand_pull = 126; len = DOOYACommand::getHandPullStatus(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); } if (config.direction == 127) { config.direction = 126; len = DOOYACommand::getDirectionStatus(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); delay(100); } len = DOOYACommand::getPosition(tmp, 0xFEFE, 0); softwareSerial->write(tmp, len); } void Cover::reportPosition() { Mqtt::publish(positionStatTopic, String(config.position).c_str(), globalConfig.mqtt.retain); }
27,734
C++
.cpp
738
28.158537
329
0.556591
qlwz/esp_cover
33
24
0
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,092
Cover.h
qlwz_esp_cover/include/Cover.h
// Cover.h #ifndef _COVER_h #define _COVER_h #include <SoftwareSerial.h> #include "Module.h" #include "CoverConfig.pb.h" #define MODULE_CFG_VERSION 1502 //1501 - 2000 class Cover : public Module { public: uint8_t operationFlag = 0; // 0每秒 bool isRun = false; CoverConfigMessage config; char positionStatTopic[80]; bool getPositionState = false; SoftwareSerial *softwareSerial; // RX, TX uint8_t softwareSerialBuff[20]; // 定义缓冲buff uint8_t softwareSerialPos = 0; // 收到的字节实际长度 unsigned long softwareSerialTime = 0; // 记录读取最后一个字节的时间点 bool autoStroke = false; // 是否自动设置行程 // 按键 int buttonDebounceTime = 50; int buttonLongPressTime = 2000; // 2000 = 2s bool buttonTiming = false; unsigned long buttonTimingStart = 0; int buttonAction = 0; // 0 = 没有要执行的动作, 1 = 执行短按动作, 2 = 执行长按动作 uint8_t getInt(char *str, uint8_t min, uint8_t max); void httpPosition(ESP8266WebServer *server); void httpDo(ESP8266WebServer *server); void httpSetting(ESP8266WebServer *server); void httpReset(ESP8266WebServer *server); void httpHa(ESP8266WebServer *server); void doPosition(uint8_t position, uint8_t command); void doSoftwareSerialTick(uint8_t *buf, int len); void readSoftwareSerialTick(); void getPositionTask(); void checkButton(); void reportPosition(); void init(); String getModuleName() { return F("cover"); } String getModuleCNName() { return F("杜亚KT82TV/W窗帘电机"); } String getModuleVersion() { return F("2020.08.14.2300"); } String getModuleAuthor() { return F("情留メ蚊子"); } bool moduleLed(); void loop(); void perSecondDo(); void readConfig(); void resetConfig(); void saveConfig(bool isEverySecond); void mqttCallback(char *topic, char *payload, char *cmnd); void mqttConnected(); void mqttDiscovery(bool isEnable = true); void httpAdd(ESP8266WebServer *server); void httpHtml(ESP8266WebServer *server); String httpGetStatus(ESP8266WebServer *server); }; #endif
2,213
C++
.h
57
31.929825
65
0.701
qlwz/esp_cover
33
24
0
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,093
CoverConfig.pb.h
qlwz_esp_cover/include/CoverConfig.pb.h
/* Automatically generated nanopb header */ /* Generated by nanopb-0.3.9.4 at Fri Aug 14 23:36:46 2020. */ #ifndef PB_COVERCONFIG_PB_H_INCLUDED #define PB_COVERCONFIG_PB_H_INCLUDED #include <pb.h> /* @@protoc_insertion_point(includes) */ #if PB_PROTO_HEADER_VERSION != 30 #error Regenerate this file with the current version of nanopb generator. #endif #ifdef __cplusplus extern "C" { #endif /* Struct definitions */ typedef struct _CoverConfigMessage { uint8_t position; uint8_t direction; uint8_t hand_pull; uint8_t weak_switch; uint8_t power_switch; uint16_t report_interval; uint8_t led; bool autoStroke; uint8_t pin_rx; uint8_t pin_tx; uint8_t pin_led; uint8_t pin_btn; /* @@protoc_insertion_point(struct:CoverConfigMessage) */ } CoverConfigMessage; /* Default values for struct fields */ /* Initializer values for message structs */ #define CoverConfigMessage_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #define CoverConfigMessage_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} /* Field tags (for use in manual encoding/decoding) */ #define CoverConfigMessage_position_tag 1 #define CoverConfigMessage_direction_tag 2 #define CoverConfigMessage_hand_pull_tag 3 #define CoverConfigMessage_weak_switch_tag 4 #define CoverConfigMessage_power_switch_tag 5 #define CoverConfigMessage_report_interval_tag 6 #define CoverConfigMessage_led_tag 7 #define CoverConfigMessage_autoStroke_tag 9 #define CoverConfigMessage_pin_rx_tag 20 #define CoverConfigMessage_pin_tx_tag 21 #define CoverConfigMessage_pin_led_tag 22 #define CoverConfigMessage_pin_btn_tag 23 /* Struct field encoding specification for nanopb */ extern const pb_field_t CoverConfigMessage_fields[13]; /* Maximum encoded size of messages (where known) */ #define CoverConfigMessage_size 72 /* Message IDs (where set with "msgid" option) */ #ifdef PB_MSGID #define COVERCONFIG_MESSAGES \ #endif #ifdef __cplusplus } /* extern "C" */ #endif /* @@protoc_insertion_point(eof) */ #endif
2,150
C++
.h
58
34.982759
85
0.710159
qlwz/esp_cover
33
24
0
GPL-2.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,095
advection.cc
hyperdeal_hyperdeal/examples/advection/advection.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- #include <hyper.deal/base/config.h> #include <deal.II/base/mpi.h> #include <hyper.deal/base/dynamic_convergence_table.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include "include/application.h" #ifndef DIM_X # define DIM_X 2 #endif #ifndef DIM_V # define DIM_V 2 #endif #ifndef DEGREE # define DEGREE 3 #endif #ifndef N_POINTS # define N_POINTS DEGREE + 1 #endif const MPI_Comm comm = MPI_COMM_WORLD; using Number = double; using VectorizedArrayType = dealii::VectorizedArray<Number>; using Problem = hyperdeal::advection:: Application<DIM_X, DIM_V, DEGREE, N_POINTS, Number, VectorizedArrayType>; struct ParametersDriver { ParametersDriver() {} ParametersDriver(const std::string & file_name, const dealii::ConditionalOStream &pcout) { dealii::ParameterHandler prm; std::ifstream file; file.open(file_name); add_parameters(prm); prm.parse_input_from_json(file, true); if (print_parameter && pcout.is_active()) prm.print_parameters(pcout.get_stream(), dealii::ParameterHandler::OutputStyle::PRM); file.close(); } void add_parameters(dealii::ParameterHandler &prm) { prm.enter_subsection("General"); prm.add_parameter("DimX", dim_x, "Number of dimension in x-space."); prm.add_parameter("DimV", dim_v, "Number of dimension in v-space."); prm.add_parameter("DegreeX", degree_x, "Polynomial degree in x-space."); prm.add_parameter("DegreeV", degree_v, "Polynomial degree in v-space."); prm.add_parameter("PartitionX", partition_x, "Number of partitions of the x-triangulation."); prm.add_parameter("PartitionV", partition_v, "Number of partitions of the v-triangulation."); prm.add_parameter("UseVirtualTopology", use_virtual_topology, "Renumber processes along a blocked z-curve."); prm.add_parameter( "UseSharedMemory", use_shared_memory, "Explicitly use MPI-3.0 shared-memory features during ghost-values-update and compression steps."); prm.add_parameter("Verbose", print_parameter, "Print the parameter after parsing."); prm.leave_subsection(); } unsigned int dim_x = DIM_X; unsigned int dim_v = DIM_V; unsigned int degree_x = DEGREE; unsigned int degree_v = DEGREE; unsigned int partition_x = 1; unsigned int partition_v = 1; bool use_virtual_topology = true; bool use_shared_memory = true; bool print_parameter = true; }; void run(hyperdeal::DynamicConvergenceTable &table, const std::string file_name) { // read input parameter file const ParametersDriver param( file_name, dealii::ConditionalOStream(std::cout, dealii::Utilities::MPI::this_mpi_process(comm) == 0)); // check input parameters (TODO: at the moment, degree and dimension are // fixed at compile time) // clang-format off AssertThrow(DIM_X == param.dim_x, dealii::ExcDimensionMismatch(DIM_X, param.dim_x)); AssertThrow(DIM_V == param.dim_v, dealii::ExcDimensionMismatch(DIM_V, param.dim_v)); AssertThrow(DEGREE == param.degree_x, dealii::ExcDimensionMismatch(DEGREE, param.degree_x)); AssertThrow(DEGREE == param.degree_v, dealii::ExcDimensionMismatch(DEGREE, param.degree_v)); // clang-format on // partitions of x- and v-space const unsigned int size_x = param.partition_x; const unsigned int size_v = param.partition_v; // create rectangular communicator MPI_Comm comm_global = hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v); // only proceed if process part of new communicator if (comm_global != MPI_COMM_NULL) { // create communicator for shared memory (only create once since // expensive) MPI_Comm comm_sm = hyperdeal::mpi::create_sm(comm_global); // optionally create virtual topology (blocked Morton order) MPI_Comm comm_z = param.use_virtual_topology ? hyperdeal::mpi::create_z_order_comm( comm_global, {size_x, size_v}, hyperdeal::Utilities::decompose( hyperdeal::mpi::n_procs_of_sm(comm_global, comm_sm))) : comm_global; #ifdef DEBUG if (param.print_parameter) { hyperdeal::mpi::print_sm(comm_z, comm_sm); hyperdeal::mpi::print_new_order(comm, comm_z); } #endif // process problem Problem problem(comm_z, param.use_shared_memory ? comm_sm : MPI_COMM_SELF, size_x, size_v, table); problem.reinit(file_name); problem.solve(); // free communicators if (param.use_virtual_topology) MPI_Comm_free(&comm_z); MPI_Comm_free(&comm_sm); MPI_Comm_free(&comm_global); // print results table.add_new_row(); table.print(false); } else { #ifdef DEBUG if (param.print_parameter) hyperdeal::mpi::print_new_order(comm, MPI_COMM_NULL); #endif } } void print_parameters(const bool print_details, const std::string &label) { dealii::ParameterHandler prm; ParametersDriver prm_driver; prm_driver.add_parameters(prm); hyperdeal::advection::Parameters<Number> prm_advection; prm_advection.add_parameters(prm); hyperdeal::advection::cases::Parameters prm_cases(label); prm_cases.add_parameters(prm); const auto initializer = hyperdeal::advection::cases::get<DIM_X, DIM_V, DEGREE, Number>(label); initializer->add_parameters(prm); prm.print_parameters( std::cout, print_details ? dealii::ParameterHandler::OutputStyle::JSON : dealii::ParameterHandler::OutputStyle::ShortJSON | dealii::ParameterHandler::OutputStyle::KeepDeclarationOrder); } int main(int argc, char **argv) { try { dealii::Utilities::MPI::MPI_InitFinalize mpi(argc, argv, 1); dealii::ConditionalOStream pcout( std::cout, dealii::Utilities::MPI::this_mpi_process(comm) == 0); hyperdeal::Utilities::print_version(pcout); if (argc == 1) { if (pcout.is_active()) printf("ERROR: No .json parameter files has been provided!\n"); return 1; } else if (argc == 3 && (std::string(argv[1]) == "--help" || std::string(argv[1]) == "--help-detail")) { if (pcout.is_active()) print_parameters(std::string(argv[1]) == "--help-detail", argv[2]); return 0; } dealii::deallog.depth_console(0); hyperdeal::DynamicConvergenceTable table; for (int i = 1; i < argc; i++) { if (dealii::Utilities::MPI::this_mpi_process(comm) == 0) std::cout << std::string(argv[i]) << std::endl; run(table, std::string(argv[i])); } table.print(false); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; }
8,609
C++
.cc
239
29.066946
105
0.595072
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,096
vlasov_poisson.cc
hyperdeal_hyperdeal/examples/vlasov_poisson/vlasov_poisson.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- #include <hyper.deal/base/config.h> #include <deal.II/base/mpi.h> #include <deal.II/base/revision.h> #include <hyper.deal/base/dynamic_convergence_table.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include "include/application.h" #ifndef DIM_X # define DIM_X 2 #endif #ifndef DIM_V # define DIM_V 2 #endif #ifndef DEGREE # define DEGREE 3 #endif #ifndef N_POINTS # define N_POINTS DEGREE + 1 #endif const MPI_Comm comm = MPI_COMM_WORLD; using Number = double; using VectorizedArrayType = dealii::VectorizedArray<Number>; using Problem = hyperdeal::vp:: Application<DIM_X, DIM_V, DEGREE, N_POINTS, Number, VectorizedArrayType>; struct ParametersDriver { ParametersDriver() {} ParametersDriver(const std::string & file_name, const dealii::ConditionalOStream &pcout) { dealii::ParameterHandler prm; std::ifstream file; file.open(file_name); add_parameters(prm); prm.parse_input_from_json(file, true); if (print_parameter && pcout.is_active()) prm.print_parameters(pcout.get_stream(), dealii::ParameterHandler::OutputStyle::PRM); file.close(); } void add_parameters(dealii::ParameterHandler &prm) { prm.enter_subsection("General"); prm.add_parameter("DimX", dim_x); prm.add_parameter("DimV", dim_v); prm.add_parameter("DegreeX", degree_x); prm.add_parameter("DegreeV", degree_v); prm.add_parameter("PartitionX", partition_x); prm.add_parameter("PartitionV", partition_v); prm.add_parameter("UseVirtualTopology", use_virtual_topology); prm.add_parameter("Verbose", print_parameter); prm.leave_subsection(); } unsigned int dim_x = DIM_X; unsigned int dim_v = DIM_V; unsigned int degree_x = DEGREE; unsigned int degree_v = DEGREE; unsigned int partition_x = 1; unsigned int partition_v = 1; bool use_virtual_topology = true; bool print_parameter = true; }; void run(hyperdeal::DynamicConvergenceTable &table, const std::string file_name) { // read input parameter file const ParametersDriver param( file_name, dealii::ConditionalOStream(std::cout, dealii::Utilities::MPI::this_mpi_process(comm) == 0)); // check input parameters (TODO: at the moment, degree and dimension are // fixed at compile time) // clang-format off AssertThrow(DIM_X == param.dim_x, dealii::ExcDimensionMismatch(DIM_X, param.dim_x)); AssertThrow(DIM_V == param.dim_v, dealii::ExcDimensionMismatch(DIM_V, param.dim_v)); AssertThrow(DEGREE == param.degree_x, dealii::ExcDimensionMismatch(DEGREE, param.degree_x)); AssertThrow(DEGREE == param.degree_v, dealii::ExcDimensionMismatch(DEGREE, param.degree_v)); // clang-format on // partitions of x- and v-space const unsigned int size_x = param.partition_x; const unsigned int size_v = param.partition_v; // create rectangular communicator MPI_Comm comm_global = hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v); // only proceed if process part of new communicator if (comm_global != MPI_COMM_NULL) { // create communicator for shared memory (only create once since // expensive) MPI_Comm comm_sm = hyperdeal::mpi::create_sm(comm_global); // optionally create virtual topology (blocked Morton order) MPI_Comm comm_z = param.use_virtual_topology ? hyperdeal::mpi::create_z_order_comm( comm_global, {size_x, size_v}, hyperdeal::Utilities::decompose( hyperdeal::mpi::n_procs_of_sm(comm_global, comm_sm))) : comm_global; #ifdef DEBUG if (param.print_parameter) { hyperdeal::mpi::print_sm(comm_z, comm_sm); hyperdeal::mpi::print_new_order(comm, comm_z); } #endif // process problem Problem problem(comm_z, comm_sm, size_x, size_v, table); problem.reinit(file_name); problem.solve(); // free communicators if (param.use_virtual_topology) MPI_Comm_free(&comm_z); MPI_Comm_free(&comm_sm); MPI_Comm_free(&comm_global); // print results table.add_new_row(); table.print(false); } else { #ifdef DEBUG if (param.print_parameter) hyperdeal::mpi::print_new_order(comm, MPI_COMM_NULL); #endif } } void print_parameters(const bool print_details, const std::string &label) { dealii::ParameterHandler prm; ParametersDriver prm_driver; prm_driver.add_parameters(prm); hyperdeal::vp::Parameters<Number> prm_vp; prm_vp.add_parameters(prm); hyperdeal::vp::cases::Parameters prm_cases(label); prm_cases.add_parameters(prm); const auto initializer = hyperdeal::vp::cases::get<DIM_X, DIM_V, DEGREE, Number>(label); initializer->add_parameters(prm); prm.print_parameters( std::cout, print_details ? dealii::ParameterHandler::OutputStyle::JSON : dealii::ParameterHandler::OutputStyle::ShortJSON | dealii::ParameterHandler::OutputStyle::KeepDeclarationOrder); } int main(int argc, char **argv) { try { dealii::Utilities::MPI::MPI_InitFinalize mpi(argc, argv, 1); if (argc == 1) { if (dealii::Utilities::MPI::this_mpi_process(comm) == 0) printf("ERROR: No .json parameter files has been provided!\n"); return 1; } else if (argc == 3 && (std::string(argv[1]) == "--help" || std::string(argv[1]) == "--help-detail")) { if (dealii::Utilities::MPI::this_mpi_process(comm) == 0) print_parameters(std::string(argv[1]) == "--help-detail", argv[2]); return 0; } if (dealii::Utilities::MPI::this_mpi_process(comm) == 0) printf("deal.II git version %s on branch %s\n\n", DEAL_II_GIT_SHORTREV, DEAL_II_GIT_BRANCH); dealii::deallog.depth_console(0); hyperdeal::DynamicConvergenceTable table; for (int i = 1; i < argc; i++) { if (dealii::Utilities::MPI::this_mpi_process(comm) == 0) std::cout << std::string(argv[i]) << std::endl; run(table, std::string(argv[i])); } table.print(false); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; }
7,862
C++
.cc
224
28.928571
94
0.601397
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,097
vector_tools_03.cc
hyperdeal_hyperdeal/tests/vector_tools/vector_tools_03.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- // Update ghost values with the help of LinearAlgebra::distributed::Partitioner. #include <deal.II/base/function.h> #include <deal.II/base/mpi.h> #include <deal.II/lac/la_parallel_vector.h> #include <deal.II/numerics/data_out.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include <hyper.deal/grid/grid_generator.h> #include <hyper.deal/numerics/vector_tools.h> #include "../tests_functions.h" #include "../tests_mf.h" using namespace dealii; template <int dim_x, int dim_v, int degree, int n_points, typename Number, typename VectorizedArrayType, typename VectorType> void test(const MPI_Comm &comm, const unsigned int n_refs) { const auto sizes = hyperdeal::Utilities::decompose( dealii::Utilities::MPI::n_mpi_processes(comm)); const unsigned int size_x = sizes.first; const unsigned int size_v = sizes.second; if (dealii::Utilities::pow<unsigned int>(2, n_refs) < size_x || dealii::Utilities::pow<unsigned int>(2, n_refs) < size_v) { deallog << "Early return, since some processes have no cells!" << std::endl; return; } MPI_Comm comm_global = hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v); if (comm_global != MPI_COMM_NULL) { MPI_Comm comm_sm = MPI_COMM_SELF; hyperdeal::MatrixFreeWrapper<dim_x, dim_v, Number, VectorizedArrayType> matrixfree_wrapper(comm_global, comm_sm, size_x, size_v); hyperdeal::Parameters p; p.triangulation_type = "fullydistributed"; p.degree = degree; p.mapping_degree = 1; p.do_collocation = false; p.do_ghost_faces = true; p.do_buffering = false; p.use_ecl = true; matrixfree_wrapper.init(p, [n_refs](auto &tria_x, auto &tria_v) { hyperdeal::GridGenerator::hyper_cube( tria_x, tria_v, true, n_refs, -1, +1); }); const auto &matrix_free = matrixfree_wrapper.get_matrix_free(); VectorType vec; matrix_free.initialize_dof_vector(vec, 0, false, true); VectorType vec_x; matrix_free.get_matrix_free_x().initialize_dof_vector(vec_x, 0); VectorType vec_v; matrix_free.get_matrix_free_v().initialize_dof_vector(vec_v, 0); static const int dim = dim_x + dim_v; const std::shared_ptr<Function<dim, Number>> solution = std::make_shared<DistanceFunction<dim, Number>>(); hyperdeal::VectorTools::interpolate<degree, n_points>( solution, matrix_free, vec, 0, 0, 2, 2); hyperdeal::VectorTools::velocity_space_integration<degree, n_points>( matrix_free, vec_x, vec, 0, 0, 2); if (dealii::Utilities::MPI::this_mpi_process( matrixfree_wrapper.get_comm_column()) == 0) { vec_x.print(deallog.get_file_stream()); DataOutBase::VtkFlags flags; flags.write_higher_order_cells = true; DataOut<dim_x> data_out; data_out.set_flags(flags); data_out.add_data_vector( matrix_free.get_matrix_free_x().get_dof_handler(), vec_x, "solution_x"); data_out.build_patches(degree + 1); data_out.write_vtu_with_pvtu_record( "./", "result_x", 0, matrixfree_wrapper.get_comm_row()); } hyperdeal::VectorTools::coordinate_space_integration<degree, n_points>( matrix_free, vec_v, vec, 0, 0, 2); if (dealii::Utilities::MPI::this_mpi_process( matrixfree_wrapper.get_comm_row()) == 0) { vec_v.print(deallog.get_file_stream()); DataOutBase::VtkFlags flags; flags.write_higher_order_cells = true; DataOut<dim_v> data_out; data_out.set_flags(flags); data_out.add_data_vector( matrix_free.get_matrix_free_v().get_dof_handler(), vec_v, "solution_v"); data_out.build_patches(degree + 1); data_out.write_vtu_with_pvtu_record( "./", "result_v", 0, matrixfree_wrapper.get_comm_column()); } MPI_Comm_free(&comm_global); } } int main(int argc, char *argv[]) { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); MPILogInitAll all; const MPI_Comm comm = MPI_COMM_WORLD; for (unsigned int refs = 3; refs <= 3; refs++) test<2, 2, 3, 4, double, dealii::VectorizedArray<double>, dealii::LinearAlgebra::distributed::Vector<double>>(comm, refs); }
5,243
C++
.cc
132
32.94697
80
0.613202
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,098
vector_tools_02.cc
hyperdeal_hyperdeal/tests/vector_tools/vector_tools_02.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- // Update ghost values with the help of LinearAlgebra::distributed::Partitioner. #include <deal.II/base/function.h> #include <deal.II/base/mpi.h> #include <deal.II/lac/la_parallel_vector.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include <hyper.deal/grid/grid_generator.h> #include <hyper.deal/numerics/vector_tools.h> #include "../tests_functions.h" #include "../tests_mf.h" using namespace dealii; template <int dim_x, int dim_v, int degree, int n_points, typename Number, typename VectorizedArrayType, typename VectorType> void test(const MPI_Comm &comm, const unsigned int n_refs) { const auto sizes = hyperdeal::Utilities::decompose( dealii::Utilities::MPI::n_mpi_processes(comm)); const unsigned int size_x = sizes.first; const unsigned int size_v = sizes.second; if (dealii::Utilities::pow<unsigned int>(2, n_refs) < size_x || dealii::Utilities::pow<unsigned int>(2, n_refs) < size_v) { deallog << "Early return, since some processes have no cells!" << std::endl; return; } MPI_Comm comm_global = hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v); if (comm_global != MPI_COMM_NULL) { MPI_Comm comm_sm = MPI_COMM_SELF; hyperdeal::MatrixFreeWrapper<dim_x, dim_v, Number, VectorizedArrayType> matrixfree_wrapper(comm_global, comm_sm, size_x, size_v); hyperdeal::Parameters p; p.triangulation_type = "fullydistributed"; p.degree = degree; p.mapping_degree = 1; p.do_collocation = false; p.do_ghost_faces = true; p.do_buffering = false; p.use_ecl = true; matrixfree_wrapper.init(p, [n_refs](auto &tria_x, auto &tria_v) { hyperdeal::GridGenerator::hyper_cube(tria_x, tria_v, true, n_refs); }); const auto &matrix_free = matrixfree_wrapper.get_matrix_free(); VectorType vec; matrix_free.initialize_dof_vector(vec, 0, false, true); VectorType vec_x; matrix_free.get_matrix_free_x().initialize_dof_vector(vec_x, 0); VectorType vec_v; matrix_free.get_matrix_free_v().initialize_dof_vector(vec_v, 0); static const int dim = dim_x + dim_v; std::shared_ptr<dealii::Function<dim, Number>> solution; for (unsigned int i = 0; i < 3; i++) { if (i == 0) solution.reset(new dealii::Functions::ZeroFunction<dim, Number>(1)); else if (i == 1) solution.reset( new dealii::Functions::ConstantFunction<dim, Number>(1.0, 1)); else if (i == 2) solution.reset(new SinusConsinusFunction<dim, Number>); else AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented()); hyperdeal::VectorTools::interpolate<degree, n_points>( solution, matrix_free, vec, 0, 0, 2, 2); hyperdeal::VectorTools::velocity_space_integration<degree, n_points>( matrix_free, vec_x, vec, 0, 0, 2); if (dealii::Utilities::MPI::this_mpi_process( matrixfree_wrapper.get_comm_column()) == 0) vec_x.print(deallog.get_file_stream()); hyperdeal::VectorTools::coordinate_space_integration<degree, n_points>( matrix_free, vec_v, vec, 0, 0, 2); if (dealii::Utilities::MPI::this_mpi_process( matrixfree_wrapper.get_comm_row()) == 0) vec_v.print(deallog.get_file_stream()); } MPI_Comm_free(&comm_global); } } int main(int argc, char *argv[]) { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); MPILogInitAll all; const MPI_Comm comm = MPI_COMM_WORLD; for (unsigned int refs = 2; refs <= 5; refs++) test<1, 1, 3, 4, double, dealii::VectorizedArray<double>, dealii::LinearAlgebra::distributed::Vector<double>>(comm, refs); }
4,742
C++
.cc
116
33.818966
80
0.608402
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,099
vector_tools_01.cc
hyperdeal_hyperdeal/tests/vector_tools/vector_tools_01.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- // Update ghost values with the help of LinearAlgebra::distributed::Partitioner. #include <deal.II/base/function.h> #include <deal.II/base/mpi.h> #include <deal.II/lac/la_parallel_vector.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include <hyper.deal/grid/grid_generator.h> #include <hyper.deal/numerics/vector_tools.h> #include "../tests_functions.h" #include "../tests_mf.h" using namespace dealii; template <int dim_x, int dim_v, int degree, int n_points, typename Number, typename VectorizedArrayType, typename VectorType> void test(const MPI_Comm &comm, const unsigned int n_refs) { const auto sizes = hyperdeal::Utilities::decompose( dealii::Utilities::MPI::n_mpi_processes(comm)); const unsigned int size_x = sizes.first; const unsigned int size_v = sizes.second; if (dealii::Utilities::pow<unsigned int>(2, n_refs) < size_x || dealii::Utilities::pow<unsigned int>(2, n_refs) < size_v) { deallog << "Early return, since some processes have no cells!" << std::endl; return; } MPI_Comm comm_global = hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v); if (comm_global != MPI_COMM_NULL) { MPI_Comm comm_sm = MPI_COMM_SELF; hyperdeal::MatrixFreeWrapper<dim_x, dim_v, Number, VectorizedArrayType> matrixfree_wrapper(comm_global, comm_sm, size_x, size_v); hyperdeal::Parameters p; p.triangulation_type = "fullydistributed"; p.degree = degree; p.mapping_degree = 1; p.do_collocation = false; p.do_ghost_faces = true; p.do_buffering = false; p.use_ecl = true; matrixfree_wrapper.init(p, [n_refs](auto &tria_x, auto &tria_v) { hyperdeal::GridGenerator::hyper_cube(tria_x, tria_v, true, n_refs); }); const auto &matrix_free = matrixfree_wrapper.get_matrix_free(); VectorType vec; matrix_free.initialize_dof_vector(vec, 0, false, true); static const int dim = dim_x + dim_v; std::shared_ptr<dealii::Function<dim, Number>> solution; for (unsigned int i = 0; i < 3; i++) { if (i == 0) solution.reset(new dealii::Functions::ZeroFunction<dim, Number>(1)); else if (i == 1) solution.reset( new dealii::Functions::ConstantFunction<dim, Number>(1.0, 1)); else if (i == 2) solution.reset(new SinusConsinusFunction<dim, Number>); else AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented()); hyperdeal::VectorTools::interpolate<degree, n_points>( solution, matrix_free, vec, 0, 0, 2, 2); const auto result = hyperdeal::VectorTools::norm_and_error<degree, n_points>( solution, matrix_free, vec, 0, 0, 0, 0); deallog << result[0] << " " << result[1] << std::endl; } MPI_Comm_free(&comm_global); } } int main(int argc, char *argv[]) { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); MPILogInitAll all; const MPI_Comm comm = MPI_COMM_WORLD; for (unsigned int refs = 2; refs <= 5; refs++) test<1, 1, 3, 4, double, dealii::VectorizedArray<double>, dealii::LinearAlgebra::distributed::Vector<double>>(comm, refs); }
4,115
C++
.cc
105
33.07619
80
0.613357
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,100
z_order_01.cc
hyperdeal_hyperdeal/tests/mpi/z_order_01.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- // Update ghost values with the help of LinearAlgebra::distributed::Partitioner. #include <deal.II/base/mpi.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include "../tests.h" using namespace dealii; void test(const MPI_Comm &comm, const std::pair<int, int> &group_size) { const auto pair = hyperdeal::Utilities::decompose( dealii::Utilities::MPI::n_mpi_processes(comm)); MPI_Comm comm_z = hyperdeal::mpi::create_z_order_comm(comm, pair, group_size); auto procs = hyperdeal::mpi::procs_of_sm(comm, comm_z); if (dealii::Utilities::MPI::this_mpi_process(comm) != 0) return; for (unsigned int i = 0, c = 0; i < pair.second; i++) { for (unsigned int j = 0; j < pair.first; j++) deallog << std::setw(5) << procs[c++]; deallog << std::endl; } deallog << std::endl; } int main(int argc, char *argv[]) { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); MPILogInitAll all; const MPI_Comm comm = MPI_COMM_WORLD; // 28 = 7 * 4 deallog.push("version1"); test(comm, {1, 1}); deallog.pop(); deallog.push("version2"); test(comm, {2, 2}); deallog.pop(); deallog.push("version3"); test(comm, {3, 2}); deallog.pop(); deallog.push("version4"); test(comm, {2, 3}); deallog.pop(); }
1,970
C++
.cc
57
31.912281
80
0.627172
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,101
cartesian_01.cc
hyperdeal_hyperdeal/tests/mpi/cartesian_01.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- // Test shared memory functionality. #include <deal.II/base/mpi.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include "../tests.h" using namespace dealii; void test(const MPI_Comm &comm, const unsigned int size_x, const unsigned int size_v) { MPI_Comm cart_comm = hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v); if (cart_comm == MPI_COMM_NULL) { deallog << "Not part of Cartesian communicator!" << std::endl; return; } MPI_Comm row_comm = hyperdeal::mpi::create_row_comm(cart_comm, size_x, size_v); MPI_Comm col_comm = hyperdeal::mpi::create_column_comm(cart_comm, size_x, size_v); for (const auto &i : hyperdeal::mpi::procs_of_sm(comm, cart_comm)) deallog << i << " "; deallog << std::endl; for (const auto &i : hyperdeal::mpi::procs_of_sm(comm, row_comm)) deallog << i << " "; deallog << std::endl; for (const auto &i : hyperdeal::mpi::procs_of_sm(comm, col_comm)) deallog << i << " "; deallog << std::endl; MPI_Comm_free(&col_comm); MPI_Comm_free(&row_comm); MPI_Comm_free(&cart_comm); } int main(int argc, char *argv[]) { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); MPILogInitAll all; const MPI_Comm comm = MPI_COMM_WORLD; test(comm, 5, 4); }
1,976
C++
.cc
55
33.218182
80
0.632546
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,102
sm_01.cc
hyperdeal_hyperdeal/tests/mpi/sm_01.cc
// --------------------------------------------------------------------- // // Copyright (C) 2020 by the hyper.deal authors // // This file is part of the hyper.deal library. // // The hyper.deal library is free software; you can use it, 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.0 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.MD at // the top level directory of hyper.deal. // // --------------------------------------------------------------------- // Test shared memory functionality. #include <deal.II/base/mpi.h> #include <hyper.deal/base/mpi.h> #include <hyper.deal/base/utilities.h> #include "../tests.h" using namespace dealii; void test(const MPI_Comm &comm) { const unsigned int rank = dealii::Utilities::MPI::this_mpi_process(comm); MPI_Comm new_comm; MPI_Comm_split(comm, rank < 3, rank, &new_comm); deallog << hyperdeal::mpi::n_procs_of_sm(comm, new_comm) << std::endl; for (const auto &i : hyperdeal::mpi::procs_of_sm(comm, new_comm)) deallog << i << " "; deallog << std::endl; MPI_Comm_free(&new_comm); } int main(int argc, char *argv[]) { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); MPILogInitAll all; const MPI_Comm comm = MPI_COMM_WORLD; test(comm); }
1,449
C++
.cc
40
34.225
75
0.636559
hyperdeal/hyperdeal
32
9
9
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false