diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..94be386 --- /dev/null +++ b/.clang-format @@ -0,0 +1,225 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: true +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAfterAttributes: Never +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: false +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: CurrentLine +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 1000 +PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Left +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Always +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: true +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: Always +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: true + AfterFunctionDeclarationName: true + AfterIfMacros: true + AfterOverloadedOperator: true + AfterRequiresInClause: true + AfterRequiresInExpression: true + BeforeNonEmptyParentheses: true +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +... + diff --git a/src/External/Android/fft.cpp b/src/External/Android/fft.cpp index 960bee7..3121192 100644 --- a/src/External/Android/fft.cpp +++ b/src/External/Android/fft.cpp @@ -1,7 +1,6 @@ #include "fft.h" -namespace External::Android -{ +namespace External::Android { /* * Copyright (C) 2010 The Android Open Source Project * @@ -31,155 +30,133 @@ namespace External::Android #endif #define LOG_FFT_SIZE 10 #define MAX_FFT_SIZE (1 << LOG_FFT_SIZE) - static const int32_t twiddle[MAX_FFT_SIZE / 4] = { - 0x00008000, 0xff378001, 0xfe6e8002, 0xfda58006, 0xfcdc800a, 0xfc13800f, - 0xfb4a8016, 0xfa81801e, 0xf9b88027, 0xf8ef8032, 0xf827803e, 0xf75e804b, - 0xf6958059, 0xf5cd8068, 0xf5058079, 0xf43c808b, 0xf374809e, 0xf2ac80b2, - 0xf1e480c8, 0xf11c80de, 0xf05580f6, 0xef8d8110, 0xeec6812a, 0xedff8146, - 0xed388163, 0xec718181, 0xebab81a0, 0xeae481c1, 0xea1e81e2, 0xe9588205, - 0xe892822a, 0xe7cd824f, 0xe7078276, 0xe642829d, 0xe57d82c6, 0xe4b982f1, - 0xe3f4831c, 0xe3308349, 0xe26d8377, 0xe1a983a6, 0xe0e683d6, 0xe0238407, - 0xdf61843a, 0xde9e846e, 0xdddc84a3, 0xdd1b84d9, 0xdc598511, 0xdb998549, - 0xdad88583, 0xda1885be, 0xd95885fa, 0xd8988637, 0xd7d98676, 0xd71b86b6, - 0xd65c86f6, 0xd59e8738, 0xd4e1877b, 0xd42487c0, 0xd3678805, 0xd2ab884c, - 0xd1ef8894, 0xd13488dd, 0xd0798927, 0xcfbe8972, 0xcf0489be, 0xce4b8a0c, - 0xcd928a5a, 0xccd98aaa, 0xcc218afb, 0xcb698b4d, 0xcab28ba0, 0xc9fc8bf5, - 0xc9468c4a, 0xc8908ca1, 0xc7db8cf8, 0xc7278d51, 0xc6738dab, 0xc5c08e06, - 0xc50d8e62, 0xc45b8ebf, 0xc3a98f1d, 0xc2f88f7d, 0xc2488fdd, 0xc198903e, - 0xc0e990a1, 0xc03a9105, 0xbf8c9169, 0xbedf91cf, 0xbe329236, 0xbd86929e, - 0xbcda9307, 0xbc2f9371, 0xbb8593dc, 0xbadc9448, 0xba3394b5, 0xb98b9523, - 0xb8e39592, 0xb83c9603, 0xb7969674, 0xb6f196e6, 0xb64c9759, 0xb5a897ce, - 0xb5059843, 0xb46298b9, 0xb3c09930, 0xb31f99a9, 0xb27f9a22, 0xb1df9a9c, - 0xb1409b17, 0xb0a29b94, 0xb0059c11, 0xaf689c8f, 0xaecc9d0e, 0xae319d8e, - 0xad979e0f, 0xacfd9e91, 0xac659f14, 0xabcd9f98, 0xab36a01c, 0xaaa0a0a2, - 0xaa0aa129, 0xa976a1b0, 0xa8e2a238, 0xa84fa2c2, 0xa7bda34c, 0xa72ca3d7, - 0xa69ca463, 0xa60ca4f0, 0xa57ea57e, 0xa4f0a60c, 0xa463a69c, 0xa3d7a72c, - 0xa34ca7bd, 0xa2c2a84f, 0xa238a8e2, 0xa1b0a976, 0xa129aa0a, 0xa0a2aaa0, - 0xa01cab36, 0x9f98abcd, 0x9f14ac65, 0x9e91acfd, 0x9e0fad97, 0x9d8eae31, - 0x9d0eaecc, 0x9c8faf68, 0x9c11b005, 0x9b94b0a2, 0x9b17b140, 0x9a9cb1df, - 0x9a22b27f, 0x99a9b31f, 0x9930b3c0, 0x98b9b462, 0x9843b505, 0x97ceb5a8, - 0x9759b64c, 0x96e6b6f1, 0x9674b796, 0x9603b83c, 0x9592b8e3, 0x9523b98b, - 0x94b5ba33, 0x9448badc, 0x93dcbb85, 0x9371bc2f, 0x9307bcda, 0x929ebd86, - 0x9236be32, 0x91cfbedf, 0x9169bf8c, 0x9105c03a, 0x90a1c0e9, 0x903ec198, - 0x8fddc248, 0x8f7dc2f8, 0x8f1dc3a9, 0x8ebfc45b, 0x8e62c50d, 0x8e06c5c0, - 0x8dabc673, 0x8d51c727, 0x8cf8c7db, 0x8ca1c890, 0x8c4ac946, 0x8bf5c9fc, - 0x8ba0cab2, 0x8b4dcb69, 0x8afbcc21, 0x8aaaccd9, 0x8a5acd92, 0x8a0cce4b, - 0x89becf04, 0x8972cfbe, 0x8927d079, 0x88ddd134, 0x8894d1ef, 0x884cd2ab, - 0x8805d367, 0x87c0d424, 0x877bd4e1, 0x8738d59e, 0x86f6d65c, 0x86b6d71b, - 0x8676d7d9, 0x8637d898, 0x85fad958, 0x85beda18, 0x8583dad8, 0x8549db99, - 0x8511dc59, 0x84d9dd1b, 0x84a3dddc, 0x846ede9e, 0x843adf61, 0x8407e023, - 0x83d6e0e6, 0x83a6e1a9, 0x8377e26d, 0x8349e330, 0x831ce3f4, 0x82f1e4b9, - 0x82c6e57d, 0x829de642, 0x8276e707, 0x824fe7cd, 0x822ae892, 0x8205e958, - 0x81e2ea1e, 0x81c1eae4, 0x81a0ebab, 0x8181ec71, 0x8163ed38, 0x8146edff, - 0x812aeec6, 0x8110ef8d, 0x80f6f055, 0x80def11c, 0x80c8f1e4, 0x80b2f2ac, - 0x809ef374, 0x808bf43c, 0x8079f505, 0x8068f5cd, 0x8059f695, 0x804bf75e, - 0x803ef827, 0x8032f8ef, 0x8027f9b8, 0x801efa81, 0x8016fb4a, 0x800ffc13, - 0x800afcdc, 0x8006fda5, 0x8002fe6e, 0x8001ff37, - }; +static const int32_t twiddle [MAX_FFT_SIZE / 4] = { + 0x00008000, 0xff378001, 0xfe6e8002, 0xfda58006, 0xfcdc800a, 0xfc13800f, 0xfb4a8016, 0xfa81801e, 0xf9b88027, + 0xf8ef8032, 0xf827803e, 0xf75e804b, 0xf6958059, 0xf5cd8068, 0xf5058079, 0xf43c808b, 0xf374809e, 0xf2ac80b2, + 0xf1e480c8, 0xf11c80de, 0xf05580f6, 0xef8d8110, 0xeec6812a, 0xedff8146, 0xed388163, 0xec718181, 0xebab81a0, + 0xeae481c1, 0xea1e81e2, 0xe9588205, 0xe892822a, 0xe7cd824f, 0xe7078276, 0xe642829d, 0xe57d82c6, 0xe4b982f1, + 0xe3f4831c, 0xe3308349, 0xe26d8377, 0xe1a983a6, 0xe0e683d6, 0xe0238407, 0xdf61843a, 0xde9e846e, 0xdddc84a3, + 0xdd1b84d9, 0xdc598511, 0xdb998549, 0xdad88583, 0xda1885be, 0xd95885fa, 0xd8988637, 0xd7d98676, 0xd71b86b6, + 0xd65c86f6, 0xd59e8738, 0xd4e1877b, 0xd42487c0, 0xd3678805, 0xd2ab884c, 0xd1ef8894, 0xd13488dd, 0xd0798927, + 0xcfbe8972, 0xcf0489be, 0xce4b8a0c, 0xcd928a5a, 0xccd98aaa, 0xcc218afb, 0xcb698b4d, 0xcab28ba0, 0xc9fc8bf5, + 0xc9468c4a, 0xc8908ca1, 0xc7db8cf8, 0xc7278d51, 0xc6738dab, 0xc5c08e06, 0xc50d8e62, 0xc45b8ebf, 0xc3a98f1d, + 0xc2f88f7d, 0xc2488fdd, 0xc198903e, 0xc0e990a1, 0xc03a9105, 0xbf8c9169, 0xbedf91cf, 0xbe329236, 0xbd86929e, + 0xbcda9307, 0xbc2f9371, 0xbb8593dc, 0xbadc9448, 0xba3394b5, 0xb98b9523, 0xb8e39592, 0xb83c9603, 0xb7969674, + 0xb6f196e6, 0xb64c9759, 0xb5a897ce, 0xb5059843, 0xb46298b9, 0xb3c09930, 0xb31f99a9, 0xb27f9a22, 0xb1df9a9c, + 0xb1409b17, 0xb0a29b94, 0xb0059c11, 0xaf689c8f, 0xaecc9d0e, 0xae319d8e, 0xad979e0f, 0xacfd9e91, 0xac659f14, + 0xabcd9f98, 0xab36a01c, 0xaaa0a0a2, 0xaa0aa129, 0xa976a1b0, 0xa8e2a238, 0xa84fa2c2, 0xa7bda34c, 0xa72ca3d7, + 0xa69ca463, 0xa60ca4f0, 0xa57ea57e, 0xa4f0a60c, 0xa463a69c, 0xa3d7a72c, 0xa34ca7bd, 0xa2c2a84f, 0xa238a8e2, + 0xa1b0a976, 0xa129aa0a, 0xa0a2aaa0, 0xa01cab36, 0x9f98abcd, 0x9f14ac65, 0x9e91acfd, 0x9e0fad97, 0x9d8eae31, + 0x9d0eaecc, 0x9c8faf68, 0x9c11b005, 0x9b94b0a2, 0x9b17b140, 0x9a9cb1df, 0x9a22b27f, 0x99a9b31f, 0x9930b3c0, + 0x98b9b462, 0x9843b505, 0x97ceb5a8, 0x9759b64c, 0x96e6b6f1, 0x9674b796, 0x9603b83c, 0x9592b8e3, 0x9523b98b, + 0x94b5ba33, 0x9448badc, 0x93dcbb85, 0x9371bc2f, 0x9307bcda, 0x929ebd86, 0x9236be32, 0x91cfbedf, 0x9169bf8c, + 0x9105c03a, 0x90a1c0e9, 0x903ec198, 0x8fddc248, 0x8f7dc2f8, 0x8f1dc3a9, 0x8ebfc45b, 0x8e62c50d, 0x8e06c5c0, + 0x8dabc673, 0x8d51c727, 0x8cf8c7db, 0x8ca1c890, 0x8c4ac946, 0x8bf5c9fc, 0x8ba0cab2, 0x8b4dcb69, 0x8afbcc21, + 0x8aaaccd9, 0x8a5acd92, 0x8a0cce4b, 0x89becf04, 0x8972cfbe, 0x8927d079, 0x88ddd134, 0x8894d1ef, 0x884cd2ab, + 0x8805d367, 0x87c0d424, 0x877bd4e1, 0x8738d59e, 0x86f6d65c, 0x86b6d71b, 0x8676d7d9, 0x8637d898, 0x85fad958, + 0x85beda18, 0x8583dad8, 0x8549db99, 0x8511dc59, 0x84d9dd1b, 0x84a3dddc, 0x846ede9e, 0x843adf61, 0x8407e023, + 0x83d6e0e6, 0x83a6e1a9, 0x8377e26d, 0x8349e330, 0x831ce3f4, 0x82f1e4b9, 0x82c6e57d, 0x829de642, 0x8276e707, + 0x824fe7cd, 0x822ae892, 0x8205e958, 0x81e2ea1e, 0x81c1eae4, 0x81a0ebab, 0x8181ec71, 0x8163ed38, 0x8146edff, + 0x812aeec6, 0x8110ef8d, 0x80f6f055, 0x80def11c, 0x80c8f1e4, 0x80b2f2ac, 0x809ef374, 0x808bf43c, 0x8079f505, + 0x8068f5cd, 0x8059f695, 0x804bf75e, 0x803ef827, 0x8032f8ef, 0x8027f9b8, 0x801efa81, 0x8016fb4a, 0x800ffc13, + 0x800afcdc, 0x8006fda5, 0x8002fe6e, 0x8001ff37, +}; + /* Returns the multiplication of \conj{a} and {b}. */ - static inline int32_t mult (int32_t a, int32_t b) - { +static inline int32_t mult (int32_t a, int32_t b) { #if __ARM_ARCH__ >= 6 - int32_t t = b; - __asm__("smuad %0, %0, %1" : "+r" (t) : "r" (a)); - __asm__("smusdx %0, %0, %1" : "+r" (b) : "r" (a)); - __asm__("pkhtb %0, %0, %1, ASR #16" : "+r" (t) : "r" (b)); + int32_t t = b; + __asm__ ("smuad %0, %0, %1" : "+r"(t) : "r"(a)); + __asm__ ("smusdx %0, %0, %1" : "+r"(b) : "r"(a)); + __asm__ ("pkhtb %0, %0, %1, ASR #16" : "+r"(t) : "r"(b)); return t; #else - return (((a >> 16) * (b >> 16) + (int16_t) a * (int16_t) b) & ~0xFFFF) | - ((((a >> 16) * (int16_t) b - (int16_t) a * (b >> 16)) >> 16) & 0xFFFF); + return (((a >> 16) * (b >> 16) + static_cast (a) * static_cast (b)) & ~0xFFFF) | + ((((a >> 16) * static_cast (b) - static_cast (a) * (b >> 16)) >> 16) & 0xFFFF); #endif - } - static inline int32_t half (int32_t a) - { +} + +static inline int32_t half (int32_t a) { #if __ARM_ARCH__ >= 6 - __asm__("shadd16 %0, %0, %1" : "+r" (a) : "r" (0)); + __asm__ ("shadd16 %0, %0, %1" : "+r"(a) : "r"(0)); return a; #else - return ((a >> 1) & ~0x8000) | (a & 0x8000); + return ((a >> 1) & ~0x8000) | (a & 0x8000); #endif - } - void fixed_fft (int n, int32_t* v) - { - int scale = LOG_FFT_SIZE, i, p, r; - for (r = 0, i = 1; i < n; ++i) - { - for (p = n; !(p & r); p >>= 1, r ^= p); - if (i < r) - { - int32_t t = v[i]; - v[i] = v[r]; - v[r] = t; - } - } - for (p = 1; p < n; p <<= 1) - { - --scale; - for (i = 0; i < n; i += p << 1) - { - int32_t x = half (v[i]); - int32_t y = half (v[i + p]); - v[i] = x + y; - v[i + p] = x - y; - } - for (r = 1; r < p; ++r) - { - int32_t w = MAX_FFT_SIZE / 4 - (r << scale); - i = w >> 31; - w = twiddle[(w ^ i) - i] ^ (i << 16); - for (i = r; i < n; i += p << 1) - { - int32_t x = half (v[i]); - int32_t y = mult (w, v[i + p]); - v[i] = x - y; - v[i + p] = x + y; - } - } - } - } - void fixed_fft_real (int n, int32_t* v) - { - int scale = LOG_FFT_SIZE, m = n >> 1, i; - fixed_fft (n, v); - for (i = 1; i <= n; i <<= 1, --scale); - v[0] = mult (~v[0], 0x80008000); - v[m] = half (v[m]); - for (i = 1; i < n >> 1; ++i) - { - int32_t x = half (v[i]); - int32_t z = half (v[n - i]); - int32_t y = z - (x ^ 0xFFFF); - x = half (x + (z ^ 0xFFFF)); - y = mult (y, twiddle[i << scale]); - v[i] = x - y; - v[n - i] = (x + y) ^ 0xFFFF; - } - } +} - bool doFft (uint8_t* fft, uint8_t* waveform) - { - int32_t workspace[WAVE_BUFFER_SIZE >> 1]; - int32_t nonzero = 0; - for (uint32_t i = 0; i < WAVE_BUFFER_SIZE; i += 2) - { - workspace[i >> 1] = - ((waveform[i] ^ 0x80) << 24) | ((waveform[i + 1] ^ 0x80) << 8); - nonzero |= workspace[i >> 1]; +void fixed_fft (int n, int32_t* v) { + int scale = LOG_FFT_SIZE, i, p, r; + for (r = 0, i = 1; i < n; ++i) { + for (p = n; !(p & r); p >>= 1, r ^= p) + ; + if (i < r) { + int32_t t = v [i]; + v [i] = v [r]; + v [r] = t; } - if (nonzero) - { - fixed_fft_real (WAVE_BUFFER_SIZE >> 1, workspace); - } - for (uint32_t i = 0; i < WAVE_BUFFER_SIZE; i += 2) - { - short tmp = workspace[i >> 1] >> 21; - while (tmp > 127 || tmp < -128) tmp >>= 1; - fft[i] = tmp; - tmp = workspace[i >> 1]; - tmp >>= 5; - while (tmp > 127 || tmp < -128) tmp >>= 1; - fft[i + 1] = tmp; - } - return true; } -} \ No newline at end of file + for (p = 1; p < n; p <<= 1) { + --scale; + for (i = 0; i < n; i += p << 1) { + int32_t x = half (v [i]); + int32_t y = half (v [i + p]); + v [i] = x + y; + v [i + p] = x - y; + } + for (r = 1; r < p; ++r) { + int32_t w = MAX_FFT_SIZE / 4 - (r << scale); + i = w >> 31; + w = twiddle [(w ^ i) - i] ^ (i << 16); + for (i = r; i < n; i += p << 1) { + int32_t x = half (v [i]); + int32_t y = mult (w, v [i + p]); + v [i] = x - y; + v [i + p] = x + y; + } + } + } +} + +void fixed_fft_real (int n, int32_t* v) { + int scale = LOG_FFT_SIZE, m = n >> 1, i; + fixed_fft (n, v); + for (i = 1; i <= n; i <<= 1, --scale) + ; + v [0] = mult (~v [0], 0x80008000); + v [m] = half (v [m]); + for (i = 1; i < n >> 1; ++i) { + int32_t x = half (v [i]); + int32_t z = half (v [n - i]); + int32_t y = z - (x ^ 0xFFFF); + x = half (x + (z ^ 0xFFFF)); + y = mult (y, twiddle [i << scale]); + v [i] = x - y; + v [n - i] = (x + y) ^ 0xFFFF; + } +} + +bool doFft (uint8_t* fft, uint8_t* waveform) { + int32_t workspace [WAVE_BUFFER_SIZE >> 1]; + int32_t nonzero = 0; + for (uint32_t i = 0; i < WAVE_BUFFER_SIZE; i += 2) { + workspace [i >> 1] = ((waveform [i] ^ 0x80) << 24) | ((waveform [i + 1] ^ 0x80) << 8); + nonzero |= workspace [i >> 1]; + } + if (nonzero) { + fixed_fft_real (WAVE_BUFFER_SIZE >> 1, workspace); + } + for (uint32_t i = 0; i < WAVE_BUFFER_SIZE; i += 2) { + short tmp = workspace [i >> 1] >> 21; + while (tmp > 127 || tmp < -128) + tmp >>= 1; + fft [i] = tmp; + tmp = workspace [i >> 1]; + tmp >>= 5; + while (tmp > 127 || tmp < -128) + tmp >>= 1; + fft [i + 1] = tmp; + } + return true; +} +} // namespace External::Android \ No newline at end of file diff --git a/src/External/Android/fft.h b/src/External/Android/fft.h index dcc5281..5f450eb 100644 --- a/src/External/Android/fft.h +++ b/src/External/Android/fft.h @@ -1,12 +1,11 @@ #pragma once -#include -#include #include +#include +#include #define WAVE_BUFFER_SIZE 1024 -namespace External::Android -{ - bool doFft (uint8_t* fft, uint8_t* waveform); +namespace External::Android { +bool doFft (uint8_t* fft, uint8_t* waveform); } \ No newline at end of file diff --git a/src/Steam/FileSystem/FileSystem.cpp b/src/Steam/FileSystem/FileSystem.cpp index 5d1101d..62c1cfe 100644 --- a/src/Steam/FileSystem/FileSystem.cpp +++ b/src/Steam/FileSystem/FileSystem.cpp @@ -2,34 +2,26 @@ #include "WallpaperEngine/Logging/CLog.h" #include #include -#include #include +#include #include -const char* assets_default_paths [] = { - ".steam/steam/steamapps/common", - ".local/share/Steam/steamapps/common", - ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/common", - "snap/steam/common/.local/share/Steam/steamapps/common", - nullptr -}; +const char* assets_default_paths [] = {".steam/steam/steamapps/common", ".local/share/Steam/steamapps/common", + ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/common", + "snap/steam/common/.local/share/Steam/steamapps/common", nullptr}; const char* workshop_content_default_paths [] = { - ".local/share/Steam/steamapps/workshop/content", - ".steam/steam/steamapps/workshop/content", + ".local/share/Steam/steamapps/workshop/content", ".steam/steam/steamapps/workshop/content", ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/workshop/content", - "snap/steam/common/.local/share/Steam/steamapps/workshop/content", - nullptr -}; + "snap/steam/common/.local/share/Steam/steamapps/workshop/content", nullptr}; -std::filesystem::path detectHomepath () -{ +std::filesystem::path detectHomepath () { char* home = getenv ("HOME"); if (home == nullptr) sLog.exception ("Cannot find home directory for the current user"); - std::filesystem::path path = home; + const std::filesystem::path path = home; if (!std::filesystem::is_directory (path)) sLog.exception ("Cannot find home directory for current user, ", home, " is not a directory"); @@ -37,12 +29,10 @@ std::filesystem::path detectHomepath () return home; } -std::filesystem::path Steam::FileSystem::workshopDirectory (int appID, const std::string& contentID) -{ +std::filesystem::path Steam::FileSystem::workshopDirectory (int appID, const std::string& contentID) { auto homepath = detectHomepath (); - for (const char** current = workshop_content_default_paths; *current != nullptr; current ++) - { + for (const char** current = workshop_content_default_paths; *current != nullptr; current++) { auto currentpath = std::filesystem::path (homepath) / *current / std::to_string (appID) / contentID; if (!std::filesystem::exists (currentpath) || !std::filesystem::is_directory (currentpath)) @@ -54,12 +44,10 @@ std::filesystem::path Steam::FileSystem::workshopDirectory (int appID, const std sLog.exception ("Cannot find workshop directory for steam app ", appID, " and content ", contentID); } -std::filesystem::path Steam::FileSystem::appDirectory (const std::string& appDirectory, const std::string& path) -{ +std::filesystem::path Steam::FileSystem::appDirectory (const std::string& appDirectory, const std::string& path) { auto homepath = detectHomepath (); - for (const char** current = assets_default_paths; *current != nullptr; current ++) - { + for (const char** current = assets_default_paths; *current != nullptr; current++) { auto currentpath = std::filesystem::path (homepath) / *current / appDirectory / path; if (!std::filesystem::exists (currentpath) || !std::filesystem::is_directory (currentpath)) diff --git a/src/Steam/FileSystem/FileSystem.h b/src/Steam/FileSystem/FileSystem.h index 5f39cd0..daf7e74 100644 --- a/src/Steam/FileSystem/FileSystem.h +++ b/src/Steam/FileSystem/FileSystem.h @@ -1,9 +1,9 @@ #pragma once -#include #include -namespace Steam::FileSystem -{ - std::filesystem::path workshopDirectory (int appID, const std::string& contentID); - std::filesystem::path appDirectory (const std::string& appDirectory, const std::string& path); -} \ No newline at end of file +#include + +namespace Steam::FileSystem { +std::filesystem::path workshopDirectory (int appID, const std::string& contentID); +std::filesystem::path appDirectory (const std::string& appDirectory, const std::string& path); +} // namespace Steam::FileSystem \ No newline at end of file diff --git a/src/WallpaperEngine/Application/CApplicationContext.cpp b/src/WallpaperEngine/Application/CApplicationContext.cpp index 7798add..d0624c2 100644 --- a/src/WallpaperEngine/Application/CApplicationContext.cpp +++ b/src/WallpaperEngine/Application/CApplicationContext.cpp @@ -12,112 +12,100 @@ using namespace WallpaperEngine::Application; -struct option long_options[] = { - { "screen-root", required_argument, nullptr, 'r' }, - { "bg", required_argument, nullptr, 'b' }, - { "window", required_argument, nullptr, 'w' }, - { "pkg", required_argument, nullptr, 'p' }, - { "dir", required_argument, nullptr, 'd' }, - { "silent", no_argument, nullptr, 's' }, - { "volume", required_argument, nullptr, 'v' }, - { "help", no_argument, nullptr, 'h' }, - { "fps", required_argument, nullptr, 'f' }, - { "assets-dir", required_argument, nullptr, 'a' }, - { "screenshot", required_argument, nullptr, 'c' }, - { "list-properties", no_argument, nullptr, 'l' }, - { "set-property", required_argument, nullptr, 'o' }, - { "noautomute", no_argument, nullptr, 'm' }, - { "no-fullscreen-pause", no_argument, nullptr, 'n' }, - { "disable-mouse", no_argument, nullptr, 'e' }, - { "scaling", required_argument, nullptr, 't' }, - { "clamping", required_argument, nullptr, 't' }, - { nullptr, 0, nullptr, 0 } -}; +struct option long_options [] = {{"screen-root", required_argument, nullptr, 'r'}, + {"bg", required_argument, nullptr, 'b'}, + {"window", required_argument, nullptr, 'w'}, + {"pkg", required_argument, nullptr, 'p'}, + {"dir", required_argument, nullptr, 'd'}, + {"silent", no_argument, nullptr, 's'}, + {"volume", required_argument, nullptr, 'v'}, + {"help", no_argument, nullptr, 'h'}, + {"fps", required_argument, nullptr, 'f'}, + {"assets-dir", required_argument, nullptr, 'a'}, + {"screenshot", required_argument, nullptr, 'c'}, + {"list-properties", no_argument, nullptr, 'l'}, + {"set-property", required_argument, nullptr, 'o'}, + {"noautomute", no_argument, nullptr, 'm'}, + {"no-fullscreen-pause", no_argument, nullptr, 'n'}, + {"disable-mouse", no_argument, nullptr, 'e'}, + {"scaling", required_argument, nullptr, 't'}, + {"clamping", required_argument, nullptr, 't'}, + {nullptr, 0, nullptr, 0}}; /* std::hash::operator() isn't constexpr, so it can't be used to get hash values as compile-time constants - * So here is customHash. It skips all spaces, so hashes for " find " and "fi nd" are the same + * So here is customHash. It skips all spaces, so hashes for " find " and "fi nd" are the same * Basicly got it from here: https://stackoverflow.com/questions/8317508/hash-function-for-a-string -*/ -constexpr size_t customHash(const char* str) { - constexpr size_t A = 54059; /* a prime */ - constexpr size_t B = 76963; /* another prime */ - constexpr size_t C = 86969; /* yet another prime */ + */ +constexpr size_t customHash (const char* str) { + constexpr size_t A = 54059; /* a prime */ + constexpr size_t B = 76963; /* another prime */ + constexpr size_t C = 86969; /* yet another prime */ constexpr size_t FIRSTH = 37; /* also prime */ size_t hash = FIRSTH; while (*str) { - if(*str != ' ') // Skip spaces + if (*str != ' ') // Skip spaces hash = (hash * A) ^ (*str * B); ++str; } return hash % C; } -std::string stringPathFixes (const std::string& s) -{ +std::string stringPathFixes (const std::string& s) { if (s.empty ()) return s; std::string str (s); // remove single-quotes from the arguments - if (str[0] == '\'' && str[str.size () - 1] == '\'') - str - .erase (str.size () - 1, 1) - .erase (0, 1); + if (str [0] == '\'' && str [str.size () - 1] == '\'') + str.erase (str.size () - 1, 1).erase (0, 1); return std::move (str); } -CApplicationContext::CApplicationContext (int argc, char* argv[]) -{ +CApplicationContext::CApplicationContext (int argc, char* argv []) { // setup structs with sane default values for now - this->settings = - { + this->settings = { .general = - { - .onlyListProperties = false, - .assets = "", - .defaultBackground = "", - .screenBackgrounds = {}, - .properties = {}, - }, + { + .onlyListProperties = false, + .assets = "", + .defaultBackground = "", + .screenBackgrounds = {}, + .properties = {}, + }, .render = - { - .mode = NORMAL_WINDOW, - .maximumFPS = 30, - .pauseOnFullscreen = true, - .window = { .geometry = {}, .clamp = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVs, - .scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs, }, - }, - .audio = - { - .enabled = true, - .volume = 15, - .automute = true - }, + { + .mode = NORMAL_WINDOW, + .maximumFPS = 30, + .pauseOnFullscreen = true, + .window = + { + .geometry = {}, + .clamp = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVs, + .scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs, + }, + }, + .audio = {.enabled = true, .volume = 15, .automute = true}, .mouse = - { - .enabled = true, - }, + { + .enabled = true, + }, .screenshot = - { - .take = false, - .path = "", - .format = FIF_UNKNOWN, - }, + { + .take = false, + .path = "", + .format = FIF_UNKNOWN, + }, }; int c; std::string lastScreen; - while ((c = getopt_long (argc, argv, "b:r:p:d:shf:a:w:mnt:", long_options, nullptr)) != -1) - { - switch (c) - { - case 'n': - this->settings.render.pauseOnFullscreen = false; - break; + while ((c = getopt_long (argc, argv, "b:r:p:d:shf:a:w:mnt:", long_options, nullptr)) != -1) { + switch (c) { + case 'n': this->settings.render.pauseOnFullscreen = false; break; case 'b': if (lastScreen.empty ()) @@ -125,45 +113,41 @@ CApplicationContext::CApplicationContext (int argc, char* argv[]) // no need to check for previous screen being in the list, as it's the only way for this variable // to have any value - this->settings.general.screenBackgrounds[lastScreen] = translateBackground (optarg); - this->settings.general.screenScalings[lastScreen] = this->settings.render.window.scalingMode; + this->settings.general.screenBackgrounds [lastScreen] = translateBackground (optarg); + this->settings.general.screenScalings [lastScreen] = this->settings.render.window.scalingMode; break; - case 'o': - { - std::string value = optarg; - std::string::size_type equals = value.find ('='); + case 'o': { + std::string value = optarg; + const std::string::size_type equals = value.find ('='); - // properties without value are treated as booleans for now - if (equals == std::string::npos) - this->settings.general.properties[value] = "1"; - else - this->settings.general.properties[value.substr (0, equals)] = value.substr (equals + 1); - } - break; + // properties without value are treated as booleans for now + if (equals == std::string::npos) + this->settings.general.properties [value] = "1"; + else + this->settings.general.properties [value.substr (0, equals)] = value.substr (equals + 1); + } break; - case 'l': - this->settings.general.onlyListProperties = true; - break; + case 'l': this->settings.general.onlyListProperties = true; break; case 'r': - if (this->settings.general.screenBackgrounds.find (optarg) != this->settings.general.screenBackgrounds.end ()) + if (this->settings.general.screenBackgrounds.find (optarg) != + this->settings.general.screenBackgrounds.end ()) sLog.exception ("Cannot specify the same screen more than once: ", optarg); if (this->settings.render.mode == EXPLICIT_WINDOW) sLog.exception ("Cannot run in both background and window mode"); this->settings.render.mode = DESKTOP_BACKGROUND; lastScreen = optarg; - this->settings.general.screenBackgrounds[lastScreen] = ""; - this->settings.general.screenScalings[lastScreen] = this->settings.render.window.scalingMode; + this->settings.general.screenBackgrounds [lastScreen] = ""; + this->settings.general.screenScalings [lastScreen] = this->settings.render.window.scalingMode; break; case 'w': if (this->settings.render.mode == DESKTOP_BACKGROUND) sLog.exception ("Cannot run in both background and window mode"); - if (optarg != nullptr) - { + if (optarg != nullptr) { this->settings.render.mode = EXPLICIT_WINDOW; // read window geometry char* pos = optarg; @@ -185,92 +169,77 @@ CApplicationContext::CApplicationContext (int argc, char* argv[]) this->settings.general.defaultBackground = translateBackground (stringPathFixes (optarg)); break; - case 's': - this->settings.audio.enabled = false; - break; + case 's': this->settings.audio.enabled = false; break; case 'h': - printHelp (argv[0]); - std::exit(0); + printHelp (argv [0]); + std::exit (0); break; - case 'f': - this->settings.render.maximumFPS = atoi (optarg); - break; + case 'f': this->settings.render.maximumFPS = atoi (optarg); break; - case 'a': - this->settings.general.assets = stringPathFixes (optarg); - break; + case 'a': this->settings.general.assets = stringPathFixes (optarg); break; - case 'v': - this->settings.audio.volume = std::max (atoi (optarg), 128); - break; + case 'v': this->settings.audio.volume = std::max (atoi (optarg), 128); break; case 'c': this->settings.screenshot.take = true; this->settings.screenshot.path = stringPathFixes (optarg); break; - case 'm': - this->settings.audio.automute = false; - break; + case 'm': this->settings.audio.automute = false; break; - case 'e': - this->settings.mouse.enabled = false; - break; + case 'e': this->settings.mouse.enabled = false; break; - case 't': - { - size_t hash = customHash(optarg); + case 't': { + size_t hash = customHash (optarg); // Use a switch statement with the hash switch (hash) { // --scale options - case customHash("stretch"): - this->settings.render.window.scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::StretchUVs; + case customHash ("stretch"): + this->settings.render.window.scalingMode = + WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::StretchUVs; break; - case customHash("fit"): - this->settings.render.window.scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFitUVs; + case customHash ("fit"): + this->settings.render.window.scalingMode = + WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFitUVs; break; - case customHash("fill"): - this->settings.render.window.scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFillUVs; + case customHash ("fill"): + this->settings.render.window.scalingMode = + WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFillUVs; break; - case customHash("default"): - this->settings.render.window.scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs; + case customHash ("default"): + this->settings.render.window.scalingMode = + WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs; break; // --clamp options - case customHash("clamp"): + case customHash ("clamp"): this->settings.render.window.clamp = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVs; break; - case customHash("border"): - this->settings.render.window.clamp = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVsBorder; + case customHash ("border"): + this->settings.render.window.clamp = + WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVsBorder; break; - case customHash("repeat"): + case customHash ("repeat"): this->settings.render.window.clamp = WallpaperEngine::Assets::ITexture::TextureFlags::NoFlags; break; default: - sLog.error("Wrong argument:"); - sLog.error(optarg); - sLog.exception("Wrong argument provided for --scale or --clamp option."); + sLog.error ("Wrong argument:"); + sLog.error (optarg); + sLog.exception ("Wrong argument provided for --scale or --clamp option."); break; } - } - break; - default: - sLog.out ("Default on path parsing: ", optarg); - break; + } break; + default: sLog.out ("Default on path parsing: ", optarg); break; } } - if (this->settings.general.defaultBackground.empty ()) - { - if (optind < argc && strlen (argv[optind]) > 0) - { - this->settings.general.defaultBackground = translateBackground (argv[optind]); - } - else - { - printHelp (argv[0]); - std::exit(0); + if (this->settings.general.defaultBackground.empty ()) { + if (optind < argc && strlen (argv [optind]) > 0) { + this->settings.general.defaultBackground = translateBackground (argv [optind]); + } else { + printHelp (argv [0]); + std::exit (0); } } @@ -284,42 +253,36 @@ CApplicationContext::CApplicationContext (int argc, char* argv[]) this->state.audio.volume = this->settings.audio.volume; } -std::filesystem::path CApplicationContext::translateBackground (const std::string& bgIdOrPath) -{ +std::filesystem::path CApplicationContext::translateBackground (const std::string& bgIdOrPath) { if (bgIdOrPath.find ('/') == std::string::npos) return Steam::FileSystem::workshopDirectory (WORKSHOP_APP_ID, bgIdOrPath); return bgIdOrPath; } -void CApplicationContext::validateAssets () -{ - if (!this->settings.general.assets.empty ()) - { - sLog.out ("Using wallpaper engine's assets at ", this->settings.general.assets, " based on --assets-dir parameter"); +void CApplicationContext::validateAssets () { + if (!this->settings.general.assets.empty ()) { + sLog.out ("Using wallpaper engine's assets at ", this->settings.general.assets, + " based on --assets-dir parameter"); return; } - try - { + try { this->settings.general.assets = Steam::FileSystem::appDirectory (APP_DIRECTORY, "assets"); - } - catch (std::runtime_error&) - { + } catch (std::runtime_error&) { // set current path as assets' folder std::filesystem::path directory = std::filesystem::canonical ("/proc/self/exe").parent_path () / "assets"; } } -void CApplicationContext::validateScreenshot () -{ +void CApplicationContext::validateScreenshot () { if (!this->settings.screenshot.take) return; if (!this->settings.screenshot.path.has_extension ()) sLog.exception ("Cannot determine screenshot format"); - std::string extension = this->settings.screenshot.path.extension (); + const std::string extension = this->settings.screenshot.path.extension (); if (extension == ".bmp") this->settings.screenshot.format = FIF_BMP; @@ -331,8 +294,7 @@ void CApplicationContext::validateScreenshot () sLog.exception ("Cannot determine screenshot format, unknown extension ", extension); } -void CApplicationContext::printHelp (const char* route) -{ +void CApplicationContext::printHelp (const char* route) { sLog.out ("Usage: ", route, " [options] background_path/background_id"); sLog.out (""); sLog.out ("where background_path/background_id can be:"); @@ -344,7 +306,8 @@ void CApplicationContext::printHelp (const char* route) sLog.out ("\t--volume \t\t\tSets the volume for all the sounds in the background"); sLog.out ("\t--noautomute\t\t\t\tDisables the automute when an app is playing sound"); sLog.out ("\t--screen-root \tDisplay as screen's background"); - sLog.out ("\t--window \tRuns in window mode, geometry has to be XxYxWxH and sets the position and size of the window"); + sLog.out ( + "\t--window \tRuns in window mode, geometry has to be XxYxWxH and sets the position and size of the window"); sLog.out ("\t--fps \t\t\tLimits the FPS to the given number, useful to keep battery consumption low"); sLog.out ("\t--assets-dir \t\t\tFolder where the assets are stored"); sLog.out ("\t--screenshot\t\t\t\tTakes a screenshot of the background"); @@ -352,8 +315,10 @@ void CApplicationContext::printHelp (const char* route) sLog.out ("\t--set-property \tOverrides the default value of the given property"); sLog.out ("\t--no-fullscreen-pause\tPrevents the background pausing when an app is fullscreen"); sLog.out ("\t--disable-mouse\tDisables mouse interactions"); - sLog.out ("\t--scaling \t Scaling mode for wallpaper. Can be stretch, fit, fill, default. Must be used before wallpaper provided.\n\ + sLog.out ( + "\t--scaling \t Scaling mode for wallpaper. Can be stretch, fit, fill, default. Must be used before wallpaper provided.\n\ \t\t For default wallpaper last specified value will be used.\n\ \t\t Example: ./wallengine --scaling stretch --screen-root eDP-1 --bg 2667198601 --scaling fill --screen-root eDP-2 2667198602"); - sLog.out ("\t--clamping \t Clamping mode for all wallpapers. Can be clamp, border, repeat. Enables GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, GL_REPEAT accordingly. Default is clamp."); + sLog.out ( + "\t--clamping \t Clamping mode for all wallpapers. Can be clamp, border, repeat. Enables GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, GL_REPEAT accordingly. Default is clamp."); } diff --git a/src/WallpaperEngine/Application/CApplicationContext.h b/src/WallpaperEngine/Application/CApplicationContext.h index 864b19f..06e8be1 100644 --- a/src/WallpaperEngine/Application/CApplicationContext.h +++ b/src/WallpaperEngine/Application/CApplicationContext.h @@ -14,130 +14,120 @@ #include "WallpaperEngine/Assets/ITexture.h" #include "WallpaperEngine/Render/CWallpaperState.h" -namespace WallpaperEngine::Application -{ - /** - * Application information as parsed off the command line arguments - */ - class CApplicationContext - { - public: - CApplicationContext (int argc, char* argv[]); +namespace WallpaperEngine::Application { +/** + * Application information as parsed off the command line arguments + */ +class CApplicationContext { + public: + CApplicationContext (int argc, char* argv []); - enum WINDOW_MODE - { - /** Default window mode */ - NORMAL_WINDOW = 0, - /** Draw to the window server desktop */ - DESKTOP_BACKGROUND = 1, - /** Explicit window mode with specified geometry */ - EXPLICIT_WINDOW = 2, - }; + enum WINDOW_MODE { + /** Default window mode */ + NORMAL_WINDOW = 0, + /** Draw to the window server desktop */ + DESKTOP_BACKGROUND = 1, + /** Explicit window mode with specified geometry */ + EXPLICIT_WINDOW = 2, + }; - struct - { - /** - * General settings - */ - struct - { - /** If the user requested a list of properties for the given background */ - bool onlyListProperties; + struct { + /** + * General settings + */ + struct { + /** If the user requested a list of properties for the given background */ + bool onlyListProperties; - /** The path to the assets folder */ - std::filesystem::path assets; - /** Background to load (provided as the final argument) as fallback for multi-screen setups */ - std::filesystem::path defaultBackground; + /** The path to the assets folder */ + std::filesystem::path assets; + /** Background to load (provided as the final argument) as fallback for multi-screen setups */ + std::filesystem::path defaultBackground; - /** The backgrounds specified for different screens */ - std::map screenBackgrounds; - /** Properties to change values for */ - std::map properties; - /** The scaling mode for different screens */ - std::map screenScalings; - } general; + /** The backgrounds specified for different screens */ + std::map screenBackgrounds; + /** Properties to change values for */ + std::map properties; + /** The scaling mode for different screens */ + std::map screenScalings; + } general; - /** - * Render settings - */ - struct - { - /** The mode to run the background in */ - WINDOW_MODE mode; - /** Maximum FPS */ - int maximumFPS; - /** Indicates if pausing should happen when something goes fullscreen */ - bool pauseOnFullscreen; + /** + * Render settings + */ + struct { + /** The mode to run the background in */ + WINDOW_MODE mode; + /** Maximum FPS */ + int maximumFPS; + /** Indicates if pausing should happen when something goes fullscreen */ + bool pauseOnFullscreen; - struct - { - /** The window size used in explicit window */ - glm::ivec4 geometry; - WallpaperEngine::Assets::ITexture::TextureFlags clamp; - WallpaperEngine::Render::CWallpaperState::TextureUVsScaling scalingMode; - } window; - } render; + struct { + /** The window size used in explicit window */ + glm::ivec4 geometry; + WallpaperEngine::Assets::ITexture::TextureFlags clamp; + WallpaperEngine::Render::CWallpaperState::TextureUVsScaling scalingMode; + } window; + } render; - /** - * Audio settings - */ - struct - { - /** If the audio system is enabled */ - bool enabled; - /** Sound volume (0-128) */ - int volume; - /** If the audio must be muted if something else is playing sound */ - bool automute; - } audio; + /** + * Audio settings + */ + struct { + /** If the audio system is enabled */ + bool enabled; + /** Sound volume (0-128) */ + int volume; + /** If the audio must be muted if something else is playing sound */ + bool automute; + } audio; - /** - * Mouse input settings - */ - struct - { - /** If the mouse movement is enabled */ - bool enabled; - } mouse; + /** + * Mouse input settings + */ + struct { + /** If the mouse movement is enabled */ + bool enabled; + } mouse; - /** - * Screenshot settings - */ - struct - { - /** If an screenshot should be taken */ - bool take; - /** The path to where the screenshot must be saved */ - std::filesystem::path path; - /** The image format */ - FREE_IMAGE_FORMAT format; - } screenshot; - } settings; + /** + * Screenshot settings + */ + struct { + /** If an screenshot should be taken */ + bool take; + /** The path to where the screenshot must be saved */ + std::filesystem::path path; + /** The image format */ + FREE_IMAGE_FORMAT format; + } screenshot; + } settings; - CApplicationState state; + CApplicationState state; - private: - /** - * Validates the assets folder and ensures a valid one is present - */ - void validateAssets (); + private: + /** + * Validates the assets folder and ensures a valid one is present + */ + void validateAssets (); - /** - * Validates the screenshot settings - */ - void validateScreenshot (); + /** + * Validates the screenshot settings + */ + void validateScreenshot (); - /** - * Validates a background parameter and returns the real bgIdOrPath to it - * - * @param bgIdOrPath - * @return - */ - static std::filesystem::path translateBackground (const std::string& bgIdOrPath); + /** + * Validates a background parameter and returns the real bgIdOrPath to it + * + * @param bgIdOrPath + * @return + */ + static std::filesystem::path translateBackground (const std::string& bgIdOrPath); - /** - * Prints the normal help message - */ - static void printHelp (const char* route); - }; -} \ No newline at end of file + /** + * Prints the normal help message + */ + static void printHelp (const char* route); +}; +} // namespace WallpaperEngine::Application \ No newline at end of file diff --git a/src/WallpaperEngine/Application/CApplicationState.h b/src/WallpaperEngine/Application/CApplicationState.h index 014e9c9..697f0bf 100644 --- a/src/WallpaperEngine/Application/CApplicationState.h +++ b/src/WallpaperEngine/Application/CApplicationState.h @@ -2,28 +2,23 @@ #include "CApplicationContext.h" -namespace WallpaperEngine::Application -{ - /** - * Represents current application state - */ - class CApplicationState - { - public: - struct - { - bool keepRunning; - } general{}; +namespace WallpaperEngine::Application { +/** + * Represents current application state + */ +class CApplicationState { + public: + struct { + bool keepRunning; + } general {}; - struct - { - bool enabled; - int volume; - } audio{}; + struct { + bool enabled; + int volume; + } audio {}; - struct - { - bool enabled; - } mouse{}; - }; -} \ No newline at end of file + struct { + bool enabled; + } mouse {}; +}; +} // namespace WallpaperEngine::Application \ No newline at end of file diff --git a/src/WallpaperEngine/Application/CWallpaperApplication.cpp b/src/WallpaperEngine/Application/CWallpaperApplication.cpp index e86d517..b4d5cd7 100644 --- a/src/WallpaperEngine/Application/CWallpaperApplication.cpp +++ b/src/WallpaperEngine/Application/CWallpaperApplication.cpp @@ -1,15 +1,15 @@ #include "CWallpaperApplication.h" #include "Steam/FileSystem/FileSystem.h" -#include "WallpaperEngine/Assets/CDirectory.h" -#include "WallpaperEngine/Assets/CVirtualContainer.h" -#include "WallpaperEngine/Core/CVideo.h" -#include "WallpaperEngine/Logging/CLog.h" -#include "WallpaperEngine/Render/CRenderContext.h" #include "WallpaperEngine/Application/CApplicationState.h" #include "WallpaperEngine/Assets/CAssetLoadException.h" +#include "WallpaperEngine/Assets/CDirectory.h" +#include "WallpaperEngine/Assets/CVirtualContainer.h" #include "WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h" +#include "WallpaperEngine/Core/CVideo.h" #include "WallpaperEngine/Input/Drivers/CGLFWMouseInput.h" +#include "WallpaperEngine/Logging/CLog.h" +#include "WallpaperEngine/Render/CRenderContext.h" #include "WallpaperEngine/Input/Drivers/CWaylandMouseInput.h" #include "WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" @@ -18,379 +18,344 @@ float g_Time; float g_TimeLast; float g_Daytime; -namespace WallpaperEngine::Application -{ - CWallpaperApplication::CWallpaperApplication (CApplicationContext& context) : - m_context (context), - m_defaultBackground (nullptr) - { - this->loadBackgrounds (); - this->setupProperties (); +namespace WallpaperEngine::Application { +CWallpaperApplication::CWallpaperApplication (CApplicationContext& context) : + m_context (context), + m_defaultBackground (nullptr) { + this->loadBackgrounds (); + this->setupProperties (); +} + +CWallpaperApplication::~CWallpaperApplication () { + delete context; + delete videoDriver; + delete audioContext; + delete audioDriver; + delete inputContext; +} + +void CWallpaperApplication::setupContainer (CCombinedContainer& container, const std::string& bg) const { + const std::filesystem::path basepath = bg; + + container.add (new CDirectory (basepath)); + container.addPkg (basepath / "scene.pkg"); + container.addPkg (basepath / "gifscene.pkg"); + container.add (new CDirectory (this->m_context.settings.general.assets)); + + // add two possible patches directories to the container + // hopefully one sticks + bool relative = true; + bool absolute = true; + + try { + container.add (new CDirectory ("../share/")); + } catch (CAssetLoadException&) { + relative = false; } - CWallpaperApplication::~CWallpaperApplication () - { - delete context; - delete videoDriver; - delete audioContext; - delete audioDriver; - delete inputContext; + try { + container.add (new CDirectory (DATADIR)); + } catch (CAssetLoadException&) { + absolute = false; } - void CWallpaperApplication::setupContainer (CCombinedContainer& container, const std::string& bg) const - { - std::filesystem::path basepath = bg; + if (!relative && !absolute) + sLog.error ("WARNING: Shader patches directory cannot be found, this might make some backgrounds not work " + "properly"); - container.add (new CDirectory (basepath)); - container.addPkg (basepath / "scene.pkg"); - container.addPkg (basepath / "gifscene.pkg"); - container.add (new CDirectory (this->m_context.settings.general.assets)); + // TODO: move this somewhere else? + auto* virtualContainer = new CVirtualContainer (); - // add two possible patches directories to the container - // hopefully one sticks - bool relative = true; - bool absolute = true; + // + // Had to get a little creative with the effects to achieve the same bloom effect without any custom code + // these virtual files are loaded by an image in the scene that takes current _rt_FullFrameBuffer and + // applies the bloom effect to render it out to the screen + // - try - { - container.add (new CDirectory ("../share/")); - } - catch (CAssetLoadException& ex) - { - relative = false; - } + // add the effect file for screen bloom - try - { - container.add (new CDirectory (DATADIR)); - } - catch (CAssetLoadException& ex) - { - absolute = false; - } + // add some model for the image element even if it's going to waste rendering cycles + virtualContainer->add ("effects/wpenginelinux/bloomeffect.json", + "{" + "\t\"name\":\"camerabloom_wpengine_linux\"," + "\t\"group\":\"wpengine_linux_camera\"," + "\t\"dependencies\":[]," + "\t\"passes\":" + "\t[" + "\t\t{" + "\t\t\t\"material\": \"materials/util/downsample_quarter_bloom.json\"," + "\t\t\t\"target\": \"_rt_4FrameBuffer\"," + "\t\t\t\"bind\":" + "\t\t\t[" + "\t\t\t\t{" + "\t\t\t\t\t\"name\": \"_rt_FullFrameBuffer\"," + "\t\t\t\t\t\"index\": 0" + "\t\t\t\t}" + "\t\t\t]" + "\t\t}," + "\t\t{" + "\t\t\t\"material\": \"materials/util/downsample_eighth_blur_v.json\"," + "\t\t\t\"target\": \"_rt_8FrameBuffer\"," + "\t\t\t\"bind\":" + "\t\t\t[" + "\t\t\t\t{" + "\t\t\t\t\t\"name\": \"_rt_4FrameBuffer\"," + "\t\t\t\t\t\"index\": 0" + "\t\t\t\t}" + "\t\t\t]" + "\t\t}," + "\t\t{" + "\t\t\t\"material\": \"materials/util/blur_h_bloom.json\"," + "\t\t\t\"target\": \"_rt_Bloom\"," + "\t\t\t\"bind\":" + "\t\t\t[" + "\t\t\t\t{" + "\t\t\t\t\t\"name\": \"_rt_8FrameBuffer\"," + "\t\t\t\t\t\"index\": 0" + "\t\t\t\t}" + "\t\t\t]" + "\t\t}," + "\t\t{" + "\t\t\t\"material\": \"materials/util/combine.json\"," + "\t\t\t\"target\": \"_rt_FullFrameBuffer\"," + "\t\t\t\"bind\":" + "\t\t\t[" + "\t\t\t\t{" + "\t\t\t\t\t\"name\": \"_rt_imageLayerComposite_-1_a\"," + "\t\t\t\t\t\"index\": 0" + "\t\t\t\t}," + "\t\t\t\t{" + "\t\t\t\t\t\"name\": \"_rt_Bloom\"," + "\t\t\t\t\t\"index\": 1" + "\t\t\t\t}" + "\t\t\t]" + "\t\t}" + "\t]" + "}"); - if (!relative && !absolute) - sLog.error ( - "WARNING: Shader patches directory cannot be found, this might make some backgrounds not work " - "properly" - ); + virtualContainer->add ("models/wpenginelinux.json", "{" + "\t\"material\":\"materials/wpenginelinux.json\"" + "}"); - // TODO: move this somewhere else? - auto* virtualContainer = new CVirtualContainer (); + // models require materials, so add that too + virtualContainer->add ("materials/wpenginelinux.json", "{" + "\t\"passes\":" + "\t\t[" + "\t\t\t{" + "\t\t\t\t\"blending\": \"normal\"," + "\t\t\t\t\"cullmode\": \"nocull\"," + "\t\t\t\t\"depthtest\": \"disabled\"," + "\t\t\t\t\"depthwrite\": \"disabled\"," + "\t\t\t\t\"shader\": \"genericimage2\"," + "\t\t\t\t\"textures\": [\"_rt_FullFrameBuffer\"]" + "\t\t\t}" + "\t\t]" + "}"); - // - // Had to get a little creative with the effects to achieve the same bloom effect without any custom code - // these virtual files are loaded by an image in the scene that takes current _rt_FullFrameBuffer and - // applies the bloom effect to render it out to the screen - // + container.add (virtualContainer); +} - // add the effect file for screen bloom +void CWallpaperApplication::loadBackgrounds () { + for (const auto& [background, path] : this->m_context.settings.general.screenBackgrounds) { + // ignore the screen settings if there was no background specified + // the default will be used + if (path.empty ()) + continue; - // add some model for the image element even if it's going to waste rendering cycles - virtualContainer->add ( - "effects/wpenginelinux/bloomeffect.json", - "{" - "\t\"name\":\"camerabloom_wpengine_linux\"," - "\t\"group\":\"wpengine_linux_camera\"," - "\t\"dependencies\":[]," - "\t\"passes\":" - "\t[" - "\t\t{" - "\t\t\t\"material\": \"materials/util/downsample_quarter_bloom.json\"," - "\t\t\t\"target\": \"_rt_4FrameBuffer\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_FullFrameBuffer\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}," - "\t\t{" - "\t\t\t\"material\": \"materials/util/downsample_eighth_blur_v.json\"," - "\t\t\t\"target\": \"_rt_8FrameBuffer\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_4FrameBuffer\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}," - "\t\t{" - "\t\t\t\"material\": \"materials/util/blur_h_bloom.json\"," - "\t\t\t\"target\": \"_rt_Bloom\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_8FrameBuffer\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}," - "\t\t{" - "\t\t\t\"material\": \"materials/util/combine.json\"," - "\t\t\t\"target\": \"_rt_FullFrameBuffer\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_imageLayerComposite_-1_a\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}," - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_Bloom\"," - "\t\t\t\t\t\"index\": 1" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}" - "\t]" - "}" - ); - - virtualContainer->add ( - "models/wpenginelinux.json", - "{" - "\t\"material\":\"materials/wpenginelinux.json\"" - "}" - ); - - // models require materials, so add that too - virtualContainer->add ( - "materials/wpenginelinux.json", - "{" - "\t\"passes\":" - "\t\t[" - "\t\t\t{" - "\t\t\t\t\"blending\": \"normal\"," - "\t\t\t\t\"cullmode\": \"nocull\"," - "\t\t\t\t\"depthtest\": \"disabled\"," - "\t\t\t\t\"depthwrite\": \"disabled\"," - "\t\t\t\t\"shader\": \"genericimage2\"," - "\t\t\t\t\"textures\": [\"_rt_FullFrameBuffer\"]" - "\t\t\t}" - "\t\t]" - "}" - ); - - container.add (virtualContainer); + this->m_backgrounds [background] = this->loadBackground (path); } - void CWallpaperApplication::loadBackgrounds () - { - for (const auto& it : this->m_context.settings.general.screenBackgrounds) - { - // ignore the screen settings if there was no background specified - // the default will be used - if (it.second.empty ()) - continue; + // load the default project if required + if (!this->m_context.settings.general.defaultBackground.empty ()) + this->m_defaultBackground = this->loadBackground (this->m_context.settings.general.defaultBackground); +} - this->m_backgrounds[it.first] = this->loadBackground (it.second); +Core::CProject* CWallpaperApplication::loadBackground (const std::string& bg) { + auto* container = new CCombinedContainer (); + + this->setupContainer (*container, bg); + + return Core::CProject::fromFile ("project.json", container); +} + +void CWallpaperApplication::setupPropertiesForProject (const Core::CProject* project) { + // show properties if required + for (const auto cur : project->getProperties ()) { + // update the value of the property + auto override = this->m_context.settings.general.properties.find (cur->getName ()); + + if (override != this->m_context.settings.general.properties.end ()) { + sLog.out ("Applying override value for ", cur->getName ()); + + cur->update (override->second); } - // load the default project if required - if (!this->m_context.settings.general.defaultBackground.empty ()) - this->m_defaultBackground = this->loadBackground (this->m_context.settings.general.defaultBackground); + if (this->m_context.settings.general.onlyListProperties) + sLog.out (cur->dump ()); } +} - Core::CProject* CWallpaperApplication::loadBackground (const std::string& bg) - { - auto* container = new CCombinedContainer (); +void CWallpaperApplication::setupProperties () { + for (const auto& [backgrounc, info] : this->m_backgrounds) + this->setupPropertiesForProject (info); - this->setupContainer (*container, bg); + if (this->m_defaultBackground != nullptr) + this->setupPropertiesForProject (this->m_defaultBackground); +} - return Core::CProject::fromFile ("project.json", container); - } +void CWallpaperApplication::takeScreenshot (const Render::CRenderContext& context, + const std::filesystem::path& filename, FREE_IMAGE_FORMAT format) { + // this should be getting called at the end of the frame, so the right thing should be bound already + const int width = context.getOutput ().getFullWidth (); + const int height = context.getOutput ().getFullHeight (); - void CWallpaperApplication::setupPropertiesForProject (Core::CProject* project) - { - // show properties if required - for (auto cur : project->getProperties ()) - { - // update the value of the property - auto override = this->m_context.settings.general.properties.find (cur->getName ()); + // build the output file with FreeImage + static FIBITMAP* bitmap = FreeImage_Allocate (width, height, 24); + RGBQUAD color; + int xoffset = 0; - if (override != this->m_context.settings.general.properties.end ()) - { - sLog.out ("Applying override value for ", cur->getName ()); + for (const auto& [screen, viewport] : context.getOutput ().getViewports ()) { + // activate opengl context so we can read from the framebuffer + viewport->makeCurrent (); + // make room for storing the pixel of this viewport + auto* buffer = new uint8_t [viewport->viewport.z * viewport->viewport.w * sizeof (uint8_t) * 3]; + const uint8_t* pixel = buffer; - cur->update (override->second); + // read the viewport data into the pixel buffer + glReadPixels (viewport->viewport.x, viewport->viewport.y, viewport->viewport.z, viewport->viewport.w, GL_RGB, + GL_UNSIGNED_BYTE, buffer); + + // now get access to the pixels + for (int y = viewport->viewport.w; y > 0; y--) { + for (int x = 0; x < viewport->viewport.z; x++) { + color.rgbRed = *pixel++; + color.rgbGreen = *pixel++; + color.rgbBlue = *pixel++; + + // set the pixel in the destination + FreeImage_SetPixelColor (bitmap, x + xoffset, + context.getOutput ().renderVFlip () ? (viewport->viewport.w - y) : y, &color); } - - if (this->m_context.settings.general.onlyListProperties) - sLog.out (cur->dump ()); - } - } - - void CWallpaperApplication::setupProperties () - { - for (const auto& it : this->m_backgrounds) - this->setupPropertiesForProject (it.second); - - if (this->m_defaultBackground != nullptr) - this->setupPropertiesForProject (this->m_defaultBackground); - } - - void CWallpaperApplication::takeScreenshot ( - const Render::CRenderContext& context, const std::filesystem::path& filename, FREE_IMAGE_FORMAT format - ) - { - // this should be getting called at the end of the frame, so the right thing should be bound already - int width = context.getOutput ().getFullWidth (); - int height = context.getOutput ().getFullHeight (); - - // build the output file with FreeImage - static FIBITMAP* bitmap = FreeImage_Allocate (width, height, 24); - RGBQUAD color; - int xoffset = 0; - - for (const auto& viewport : context.getOutput ().getViewports ()) - { - // activate opengl context so we can read from the framebuffer - viewport.second->makeCurrent (); - // make room for storing the pixel of this viewport - uint8_t* buffer = new uint8_t[viewport.second->viewport.z * viewport.second->viewport.w * sizeof (uint8_t) * 3]; - uint8_t* pixel = buffer; - - // read the viewport data into the pixel buffer - glReadPixels ( - viewport.second->viewport.x, viewport.second->viewport.y, - viewport.second->viewport.z, viewport.second->viewport.w, - GL_RGB, GL_UNSIGNED_BYTE, buffer - ); - - // now get access to the pixels - for (int y = viewport.second->viewport.w; y > 0; y--) - { - for (int x = 0; x < viewport.second->viewport.z; x++) - { - color.rgbRed = *pixel++; - color.rgbGreen = *pixel++; - color.rgbBlue = *pixel++; - - // set the pixel in the destination - FreeImage_SetPixelColor (bitmap, x + xoffset, context.getOutput ().renderVFlip() ? (viewport.second->viewport.w - y) : y, &color); - } - } - - if (viewport.second->single) - xoffset += viewport.second->viewport.z; - - // free the buffer allocated for the viewport - delete[] buffer; } - // finally save the file - FreeImage_Save (format, bitmap, filename.c_str (), 0); + if (viewport->single) + xoffset += viewport->viewport.z; - FreeImage_Unload (bitmap); + // free the buffer allocated for the viewport + delete [] buffer; } - void CWallpaperApplication::show () - { + // finally save the file + FreeImage_Save (format, bitmap, filename.c_str (), 0); + + FreeImage_Unload (bitmap); +} + +void CWallpaperApplication::show () { #ifdef ENABLE_WAYLAND - const bool WAYLAND_DISPLAY = getenv ("WAYLAND_DISPLAY"); + const bool WAYLAND_DISPLAY = getenv ("WAYLAND_DISPLAY"); - // setup the right video driver based on the environment and the startup mode requested - if (WAYLAND_DISPLAY && this->m_context.settings.render.mode == CApplicationContext::DESKTOP_BACKGROUND) - { - auto waylandDriver = new WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver (this->m_context, *this); - inputContext = new WallpaperEngine::Input::CInputContext (new WallpaperEngine::Input::Drivers::CWaylandMouseInput (waylandDriver)); + // setup the right video driver based on the environment and the startup mode requested + if (WAYLAND_DISPLAY && this->m_context.settings.render.mode == CApplicationContext::DESKTOP_BACKGROUND) { + const auto waylandDriver = new WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver (this->m_context, *this); + inputContext = new WallpaperEngine::Input::CInputContext ( + new WallpaperEngine::Input::Drivers::CWaylandMouseInput (waylandDriver)); - videoDriver = waylandDriver; - } - else + videoDriver = waylandDriver; + } else #endif - { - auto x11Driver = new WallpaperEngine::Render::Drivers::CX11OpenGLDriver ("wallpaperengine", this->m_context, *this); - // no wayland detected, try the old X11 method - inputContext = new WallpaperEngine::Input::CInputContext (new WallpaperEngine::Input::Drivers::CGLFWMouseInput (x11Driver)); - - videoDriver = x11Driver; - } - - // stereo mix recorder for audio processing - WallpaperEngine::Audio::Drivers::Recorders::CPulseAudioPlaybackRecorder audioRecorder; - // audio playing detector - WallpaperEngine::Audio::Drivers::Detectors::CPulseAudioPlayingDetector audioDetector (this->m_context, videoDriver->getFullscreenDetector ()); - // initialize sdl audio driver - audioDriver = new WallpaperEngine::Audio::Drivers::CSDLAudioDriver (this->m_context, audioDetector, audioRecorder); - // initialize audio context - audioContext = new WallpaperEngine::Audio::CAudioContext (*audioDriver); - // initialize render context - context = new WallpaperEngine::Render::CRenderContext (*videoDriver, *inputContext, *this); - - // set all the specific wallpapers required - for (const auto& it : this->m_backgrounds) - context->setWallpaper ( - it.first, - WallpaperEngine::Render::CWallpaper::fromWallpaper (it.second->getWallpaper (), *context, *audioContext, this->m_context.settings.general.screenScalings[it.first]) - ); - - // set the default rendering wallpaper if available - if (this->m_defaultBackground != nullptr) - context->setDefaultWallpaper (WallpaperEngine::Render::CWallpaper::fromWallpaper ( - this->m_defaultBackground->getWallpaper (), *context, *audioContext, this->m_context.settings.render.window.scalingMode - )); - - static time_t seconds; - static struct tm* timeinfo; - - while (this->m_context.state.general.keepRunning && !videoDriver->closeRequested ()) - { - // update g_Daytime - time (&seconds); - timeinfo = localtime(&seconds); - g_Daytime = ((timeinfo->tm_hour * 60) + timeinfo->tm_min) / (24.0 * 60.0); - - // keep track of the previous frame's time - g_TimeLast = g_Time; - // calculate the current time value - g_Time = videoDriver->getRenderTime (); - // update audio recorder - audioDriver->update (); - // update input information - inputContext->update (); - // process driver events - videoDriver->dispatchEventQueue (); - - if (!this->m_context.settings.screenshot.take || videoDriver->getFrameCounter () < 5) - continue; - - this->takeScreenshot (*context, this->m_context.settings.screenshot.path, this->m_context.settings.screenshot.format); - this->m_context.settings.screenshot.take = false; - } - - // ensure this is updated as sometimes it might not come from a signal - this->m_context.state.general.keepRunning = false; - - sLog.out ("Stop requested"); - - SDL_Quit (); - } - - void CWallpaperApplication::update(Render::Drivers::Output::COutputViewport* viewport) { - // render the scene - context->render (viewport); + const auto x11Driver = + new WallpaperEngine::Render::Drivers::CX11OpenGLDriver ("wallpaperengine", this->m_context, *this); + // no wayland detected, try the old X11 method + inputContext = new WallpaperEngine::Input::CInputContext ( + new WallpaperEngine::Input::Drivers::CGLFWMouseInput (x11Driver)); + + videoDriver = x11Driver; } - void CWallpaperApplication::signal (int signal) - { - this->m_context.state.general.keepRunning = false; + // stereo mix recorder for audio processing + WallpaperEngine::Audio::Drivers::Recorders::CPulseAudioPlaybackRecorder audioRecorder; + // audio playing detector + WallpaperEngine::Audio::Drivers::Detectors::CPulseAudioPlayingDetector audioDetector ( + this->m_context, videoDriver->getFullscreenDetector ()); + // initialize sdl audio driver + audioDriver = new WallpaperEngine::Audio::Drivers::CSDLAudioDriver (this->m_context, audioDetector, audioRecorder); + // initialize audio context + audioContext = new WallpaperEngine::Audio::CAudioContext (*audioDriver); + // initialize render context + context = new WallpaperEngine::Render::CRenderContext (*videoDriver, *inputContext, *this); + + // set all the specific wallpapers required + for (const auto& [background, info] : this->m_backgrounds) + context->setWallpaper (background, WallpaperEngine::Render::CWallpaper::fromWallpaper ( + info->getWallpaper (), *context, *audioContext, + this->m_context.settings.general.screenScalings [background])); + + // set the default rendering wallpaper if available + if (this->m_defaultBackground != nullptr) + context->setDefaultWallpaper (WallpaperEngine::Render::CWallpaper::fromWallpaper ( + this->m_defaultBackground->getWallpaper (), *context, *audioContext, + this->m_context.settings.render.window.scalingMode)); + + static time_t seconds; + static struct tm* timeinfo; + + while (this->m_context.state.general.keepRunning && !videoDriver->closeRequested ()) { + // update g_Daytime + time (&seconds); + timeinfo = localtime (&seconds); + g_Daytime = ((timeinfo->tm_hour * 60) + timeinfo->tm_min) / (24.0 * 60.0); + + // keep track of the previous frame's time + g_TimeLast = g_Time; + // calculate the current time value + g_Time = videoDriver->getRenderTime (); + // update audio recorder + audioDriver->update (); + // update input information + inputContext->update (); + // process driver events + videoDriver->dispatchEventQueue (); + + if (!this->m_context.settings.screenshot.take || videoDriver->getFrameCounter () < 5) + continue; + + this->takeScreenshot (*context, this->m_context.settings.screenshot.path, + this->m_context.settings.screenshot.format); + this->m_context.settings.screenshot.take = false; } - const std::map& CWallpaperApplication::getBackgrounds () const - { - return this->m_backgrounds; - } + // ensure this is updated as sometimes it might not come from a signal + this->m_context.state.general.keepRunning = false; - Core::CProject* CWallpaperApplication::getDefaultBackground () const - { - return this->m_defaultBackground; - } + sLog.out ("Stop requested"); - CApplicationContext& CWallpaperApplication::getContext () const - { - return this->m_context; - } -} \ No newline at end of file + SDL_Quit (); +} + +void CWallpaperApplication::update (Render::Drivers::Output::COutputViewport* viewport) { + // render the scene + context->render (viewport); +} + +void CWallpaperApplication::signal (int signal) { + this->m_context.state.general.keepRunning = false; +} + +const std::map& CWallpaperApplication::getBackgrounds () const { + return this->m_backgrounds; +} + +Core::CProject* CWallpaperApplication::getDefaultBackground () const { + return this->m_defaultBackground; +} + +CApplicationContext& CWallpaperApplication::getContext () const { + return this->m_context; +} + +const WallpaperEngine::Render::Drivers::Output::COutput& CWallpaperApplication::getOutput () const { + return this->context->getOutput (); +} +} // namespace WallpaperEngine::Application \ No newline at end of file diff --git a/src/WallpaperEngine/Application/CWallpaperApplication.h b/src/WallpaperEngine/Application/CWallpaperApplication.h index 70ffacf..9e6b4ee 100644 --- a/src/WallpaperEngine/Application/CWallpaperApplication.h +++ b/src/WallpaperEngine/Application/CWallpaperApplication.h @@ -6,8 +6,8 @@ #include "WallpaperEngine/Core/CProject.h" -#include "WallpaperEngine/Render/CWallpaper.h" #include "WallpaperEngine/Render/CRenderContext.h" +#include "WallpaperEngine/Render/CWallpaper.h" #include "WallpaperEngine/Render/Drivers/CX11OpenGLDriver.h" #ifdef ENABLE_WAYLAND #include "WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" @@ -28,99 +28,98 @@ #include "WallpaperEngine/Input/CInputContext.h" -namespace WallpaperEngine::Application -{ +namespace WallpaperEngine::Application { +/** + * Small wrapper class over the actual wallpaper's main application skeleton + * + * @author Alexis Maiquez + */ +class CWallpaperApplication { + public: + explicit CWallpaperApplication (CApplicationContext& context); + ~CWallpaperApplication (); + /** - * Small wrapper class over the actual wallpaper's main application skeleton - * - * @author Alexis Maiquez + * Shows the application until it's closed */ - class CWallpaperApplication - { - public: - explicit CWallpaperApplication (CApplicationContext& context); - ~CWallpaperApplication (); + void show (); + /** + * Handles a OS signal sent to this PID + * + * @param signal + */ + void signal (int signal); + /** + * @return Maps screens to loaded backgrounds + */ + [[nodiscard]] const std::map& getBackgrounds () const; + /** + * @return The default background to use if no specific project is loaded + */ + [[nodiscard]] Core::CProject* getDefaultBackground () const; + /** + * @return The current application context + */ + [[nodiscard]] CApplicationContext& getContext () const; + /** + * Renders a frame + */ + void update (Render::Drivers::Output::COutputViewport* viewport); + /** + * Gets the output + */ + [[nodiscard]] const WallpaperEngine::Render::Drivers::Output::COutput& getOutput () const; - /** - * Shows the application until it's closed - */ - void show (); - /** - * Handles a OS signal sent to this PID - * - * @param signal - */ - void signal (int signal); - /** - * @return Maps screens to loaded backgrounds - */ - [[nodiscard]] const std::map & getBackgrounds () const; - /** - * @return The default background to use if no specific project is loaded - */ - [[nodiscard]] Core::CProject* getDefaultBackground () const; - /** - * @return The current application context - */ - [[nodiscard]] CApplicationContext& getContext () const; - /** - * Renders a frame - */ - void update(Render::Drivers::Output::COutputViewport* viewport); - /** - * Gets the output - */ - WallpaperEngine::Render::Drivers::Output::COutput* getOutput() const; + private: + /** + * Sets up a combined container for the given background, adding default files and directories to the list + * + * @param container + * @param bg + */ + void setupContainer (CCombinedContainer& container, const std::string& bg) const; + /** + * Loads projects based off the settings + */ + void loadBackgrounds (); + /** + * Loads the given project + * + * @param bg + * @return + */ + Core::CProject* loadBackground (const std::string& bg); + /** + * Prepares all background's values and updates their properties if required + */ + void setupProperties (); + /** + * Updates the properties for the given background based on the current context + * + * @param project + */ + void setupPropertiesForProject (const Core::CProject* project); + /** + * Takes an screenshot of the background and saves it to the specified path + * + * @param context + * @param filename + * @param format + */ + static void takeScreenshot (const Render::CRenderContext& context, const std::filesystem::path& filename, + FREE_IMAGE_FORMAT format); - private: - /** - * Sets up a combined container for the given background, adding default files and directories to the list - * - * @param container - * @param bg - */ - void setupContainer (CCombinedContainer& container, const std::string& bg) const; - /** - * Loads projects based off the settings - */ - void loadBackgrounds (); - /** - * Loads the given project - * - * @param bg - * @return - */ - Core::CProject* loadBackground (const std::string& bg); - /** - * Prepares all background's values and updates their properties if required - */ - void setupProperties (); - /** - * Updates the properties for the given background based on the current context - * - * @param project - */ - void setupPropertiesForProject (Core::CProject* project); - /** - * Takes an screenshot of the background and saves it to the specified path - * - * @param context - * @param filename - * @param format - */ - static void takeScreenshot (const Render::CRenderContext& context, const std::filesystem::path& filename, FREE_IMAGE_FORMAT format); + /** The default background to display if no specific background was loaded */ + Core::CProject* m_defaultBackground; + /** The application context that contains the current app settings */ + CApplicationContext& m_context; + /** Maps screens to backgrounds */ + std::map m_backgrounds; - /** The default background to display if no specific background was loaded */ - Core::CProject* m_defaultBackground; - /** The application context that contains the current app settings */ - CApplicationContext& m_context; - /** Maps screens to backgrounds */ - std::map m_backgrounds; - - WallpaperEngine::Render::Drivers::CVideoDriver* videoDriver; - WallpaperEngine::Input::CInputContext* inputContext; - WallpaperEngine::Audio::Drivers::CSDLAudioDriver* audioDriver; - WallpaperEngine::Render::CRenderContext* context; - WallpaperEngine::Audio::CAudioContext* audioContext; - }; -} + WallpaperEngine::Render::Drivers::CVideoDriver* videoDriver; + WallpaperEngine::Input::CInputContext* inputContext; + WallpaperEngine::Audio::Drivers::CSDLAudioDriver* audioDriver; + WallpaperEngine::Render::CRenderContext* context; + WallpaperEngine::Audio::CAudioContext* audioContext; +}; +} // namespace WallpaperEngine::Application diff --git a/src/WallpaperEngine/Assets/CAssetLoadException.cpp b/src/WallpaperEngine/Assets/CAssetLoadException.cpp index 1f7cbc4..3b8eb2e 100644 --- a/src/WallpaperEngine/Assets/CAssetLoadException.cpp +++ b/src/WallpaperEngine/Assets/CAssetLoadException.cpp @@ -2,12 +2,9 @@ using namespace WallpaperEngine::Assets; -CAssetLoadException::CAssetLoadException(const std::string& filename, const std::string& extrainfo) - : m_message("Cannot find file " + filename + ": " + extrainfo) -{ -} +CAssetLoadException::CAssetLoadException (const std::string& filename, const std::string& extrainfo) : + m_message ("Cannot find file " + filename + ": " + extrainfo) {} -const char *CAssetLoadException::what() const noexcept -{ +const char* CAssetLoadException::what () const noexcept { return this->m_message.c_str (); } diff --git a/src/WallpaperEngine/Assets/CAssetLoadException.h b/src/WallpaperEngine/Assets/CAssetLoadException.h index 43a9c81..7c61856 100644 --- a/src/WallpaperEngine/Assets/CAssetLoadException.h +++ b/src/WallpaperEngine/Assets/CAssetLoadException.h @@ -3,15 +3,13 @@ #include #include -namespace WallpaperEngine::Assets -{ - class CAssetLoadException : public std::exception - { - public: - explicit CAssetLoadException (const std::string& filename, const std::string& extrainfo = ""); - [[nodiscard]] const char* what () const noexcept override; +namespace WallpaperEngine::Assets { +class CAssetLoadException final : public std::exception { + public: + explicit CAssetLoadException (const std::string& filename, const std::string& extrainfo = ""); + [[nodiscard]] const char* what () const noexcept override; - private: - std::string m_message; - }; -} \ No newline at end of file + private: + std::string m_message; +}; +} // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CCombinedContainer.cpp b/src/WallpaperEngine/Assets/CCombinedContainer.cpp index 2063627..5b8854c 100644 --- a/src/WallpaperEngine/Assets/CCombinedContainer.cpp +++ b/src/WallpaperEngine/Assets/CCombinedContainer.cpp @@ -6,50 +6,33 @@ using namespace WallpaperEngine::Assets; -CCombinedContainer::CCombinedContainer () : - CContainer (), - m_containers () -{ -} +CCombinedContainer::CCombinedContainer () : CContainer () {} -void CCombinedContainer::add (CContainer* container) -{ +void CCombinedContainer::add (CContainer* container) { this->m_containers.emplace_back (container); } -void CCombinedContainer::addPkg (const std::filesystem::path& path) -{ - try - { +void CCombinedContainer::addPkg (const std::filesystem::path& path) { + try { // add the package to the list this->add (new CPackage (path)); sLog.out ("Detected ", path.filename (), " file at ", path, ". Adding to list of searchable paths"); - } - catch (CPackageLoadException& ex) - { + } catch (CPackageLoadException&) { // ignore this error, the package file was not found sLog.out ("No ", path.filename (), " file found at ", path, ". Defaulting to normal folder storage"); - } - catch (std::runtime_error& ex) - { + } catch (std::runtime_error& ex) { // the package was found but there was an error loading it (wrong header or something) - sLog.exception ("Failed to load scene.pkg file: ", ex.what()); + sLog.exception ("Failed to load scene.pkg file: ", ex.what ()); } } - -std::filesystem::path CCombinedContainer::resolveRealFile (const std::string& filename) const -{ - for (auto cur : this->m_containers) - { - try - { +std::filesystem::path CCombinedContainer::resolveRealFile (const std::string& filename) const { + for (const auto cur : this->m_containers) { + try { // try to read the file on the current container, if the file doesn't exists // an exception will be thrown return cur->resolveRealFile (filename); - } - catch (CAssetLoadException& ex) - { + } catch (CAssetLoadException&) { // not found in this container, next try } } @@ -58,18 +41,13 @@ std::filesystem::path CCombinedContainer::resolveRealFile (const std::string& fi throw CAssetLoadException (filename, "Cannot resolve file in any of the containers"); } -const void* CCombinedContainer::readFile (const std::string& filename, uint32_t* length) const -{ - for (auto cur : this->m_containers) - { - try - { +const void* CCombinedContainer::readFile (const std::string& filename, uint32_t* length) const { + for (const auto cur : this->m_containers) { + try { // try to read the file on the current container, if the file doesn't exists // an exception will be thrown return cur->readFile (filename, length); - } - catch (CAssetLoadException& ex) - { + } catch (CAssetLoadException&) { // not found in this container, next try } } diff --git a/src/WallpaperEngine/Assets/CCombinedContainer.h b/src/WallpaperEngine/Assets/CCombinedContainer.h index e5e00b8..b2dbf4c 100644 --- a/src/WallpaperEngine/Assets/CCombinedContainer.h +++ b/src/WallpaperEngine/Assets/CCombinedContainer.h @@ -6,36 +6,34 @@ #include #include -namespace WallpaperEngine::Assets -{ +namespace WallpaperEngine::Assets { +/** + * A meta-container that allows backgrounds to have files spread across different containers + */ +class CCombinedContainer final : public CContainer { + public: + CCombinedContainer (); + /** - * A meta-container that allows backgrounds to have files spread across different containers + * Adds a container to the list + * + * @param container */ - class CCombinedContainer : public CContainer - { - public: - CCombinedContainer (); + void add (CContainer* container); + /** + * Adds the given package to the list + * + * @param path + */ + void addPkg (const std::filesystem::path& path); - /** - * Adds a container to the list - * - * @param container - */ - void add (CContainer* container); - /** - * Adds the given package to the list - * - * @param path - */ - void addPkg (const std::filesystem::path& path); + /** @inheritdoc */ + [[nodiscard]] std::filesystem::path resolveRealFile (const std::string& filename) const override; + /** @inheritdoc */ + [[nodiscard]] const void* readFile (const std::string& filename, uint32_t* length) const override; - /** @inheritdoc */ - [[nodiscard]] std::filesystem::path resolveRealFile (const std::string& filename) const override; - /** @inheritdoc */ - [[nodiscard]] const void* readFile (const std::string& filename, uint32_t* length) const override; - - private: - /** The list of containers to search files off from */ - std::vector m_containers; - }; -}; \ No newline at end of file + private: + /** The list of containers to search files off from */ + std::vector m_containers; +}; +}; // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CContainer.cpp b/src/WallpaperEngine/Assets/CContainer.cpp index 0c632c0..0e84db3 100644 --- a/src/WallpaperEngine/Assets/CContainer.cpp +++ b/src/WallpaperEngine/Assets/CContainer.cpp @@ -1,27 +1,25 @@ #include "CContainer.h" +#include "CAssetLoadException.h" #include "CTexture.h" #include "WallpaperEngine/Logging/CLog.h" -#include "CAssetLoadException.h" #include -#include #include +#include using namespace WallpaperEngine::Assets; -std::filesystem::path CContainer::resolveRealFile (const std::string& filename) const -{ +std::filesystem::path CContainer::resolveRealFile (const std::string& filename) const { throw CAssetLoadException (filename, "Cannot resolve physical file in this container"); } -const ITexture* CContainer::readTexture (const std::string& filename) const -{ +const ITexture* CContainer::readTexture (const std::string& filename) const { // get the texture's filename (usually .tex) - std::string texture = "materials/" + filename + ".tex"; + const std::string texture = "materials/" + filename + ".tex"; const void* textureContents = this->readFile (texture, nullptr); - ITexture* result = new CTexture (textureContents); + const ITexture* result = new CTexture (textureContents); #if !NDEBUG glObjectLabel (GL_TEXTURE, result->getTextureID (), -1, texture.c_str ()); @@ -29,22 +27,19 @@ const ITexture* CContainer::readTexture (const std::string& filename) const return result; } -std::string CContainer::readShader (const std::string& filename) const -{ + +std::string CContainer::readShader (const std::string& filename) const { std::filesystem::path shader = filename; auto it = shader.begin (); // detect workshop shaders and check if there's a - if (*it++ == "workshop") - { - std::filesystem::path workshopId = *it++; + if (*it++ == "workshop") { + const std::filesystem::path workshopId = *it++; - if (++it != shader.end ()) - { - std::filesystem::path shaderfile = *it; + if (++it != shader.end ()) { + const std::filesystem::path shaderfile = *it; - try - { + try { shader = std::filesystem::path ("zcompat") / "scene" / "shaders" / workshopId / shaderfile; // replace the old path with the new one std::string contents = this->readFileAsString (shader); @@ -52,34 +47,26 @@ std::string CContainer::readShader (const std::string& filename) const sLog.out ("Replaced ", filename, " with compat ", shader); return contents; - } - catch (CAssetLoadException&) - { - - } + } catch (CAssetLoadException&) {} } } return this->readFileAsString ("shaders/" + filename); } -std::string CContainer::readVertexShader (const std::string& filename) const -{ +std::string CContainer::readVertexShader (const std::string& filename) const { return this->readShader (filename + ".vert"); } -std::string CContainer::readFragmentShader (const std::string& filename) const -{ +std::string CContainer::readFragmentShader (const std::string& filename) const { return this->readShader (filename + ".frag"); } -std::string CContainer::readIncludeShader (const std::string& filename) const -{ +std::string CContainer::readIncludeShader (const std::string& filename) const { return this->readFileAsString ("shaders/" + filename); } -std::string CContainer::readFileAsString (const std::string& filename) const -{ +std::string CContainer::readFileAsString (const std::string& filename) const { uint32_t length = 0; // read file contents and allocate a buffer for a string @@ -94,7 +81,7 @@ std::string CContainer::readFileAsString (const std::string& filename) const std::string result = buffer; // free the intermediate buffer used to generate the std::string - delete[] buffer; + delete [] buffer; return result; } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CContainer.h b/src/WallpaperEngine/Assets/CContainer.h index dde5f7b..61c5a7b 100644 --- a/src/WallpaperEngine/Assets/CContainer.h +++ b/src/WallpaperEngine/Assets/CContainer.h @@ -5,85 +5,85 @@ #include #include -namespace WallpaperEngine::Assets -{ +namespace WallpaperEngine::Assets { +/** + * File container, provides access to files for backgrounds + */ +class CContainer { + public: + virtual ~CContainer () = default; + /** - * File container, provides access to files for backgrounds + * Resolves the full path to the specified file in the filesystem + * + * @param filename + * @return */ - class CContainer - { - public: - /** - * Resolves the full path to the specified file in the filesystem - * - * @param filename - * @return - */ - [[nodiscard]] virtual std::filesystem::path resolveRealFile (const std::string& filename) const; + [[nodiscard]] virtual std::filesystem::path resolveRealFile (const std::string& filename) const; - /** - * Reads the given file from the container and returns it's data - * Additionally sets a length parameter to return back the file's length - * - * @param filename The file to read - * @param length The file's length after it's been read, null for not getting anything back - * - * @return - */ - [[nodiscard]] virtual const void* readFile (const std::string& filename, uint32_t* length) const = 0; + /** + * Reads the given file from the container and returns it's data + * Additionally sets a length parameter to return back the file's length + * + * @param filename The file to read + * @param length The file's length after it's been read, null for not getting anything back + * + * @return + */ + [[nodiscard]] virtual const void* readFile (const std::string& filename, uint32_t* length) const = 0; - /** - * Wrapper for readFile, appends the texture extension at the end of the filename - * - * @param filename The texture name (without the .tex) - * - * @return - */ - [[nodiscard]] const ITexture* readTexture (const std::string& filename) const; + /** + * Wrapper for readFile, appends the texture extension at the end of the filename + * + * @param filename The texture name (without the .tex) + * + * @return + */ + [[nodiscard]] const ITexture* readTexture (const std::string& filename) const; - /** - * Wrapper for readFile, checks for compat versions of the given shader file - * - * @param filename - * - * @return The shader code as an string to be used - */ - [[nodiscard]] std::string readShader (const std::string& filename) const; + /** + * Wrapper for readFile, checks for compat versions of the given shader file + * + * @param filename + * + * @return The shader code as an string to be used + */ + [[nodiscard]] std::string readShader (const std::string& filename) const; - /** - * Wrapper for readFile, appends the .vert extension at the end and opens the given shader file - * - * @param filename - * - * @return The shader code as an string to be used - */ - [[nodiscard]] std::string readVertexShader (const std::string& filename) const; + /** + * Wrapper for readFile, appends the .vert extension at the end and opens the given shader file + * + * @param filename + * + * @return The shader code as an string to be used + */ + [[nodiscard]] std::string readVertexShader (const std::string& filename) const; - /** - * Wrapper for readFile, appends the .frag extension at the end and opens the given shader file - * - * @param filename - * - * @return The shader code as an string to be used - */ - [[nodiscard]] std::string readFragmentShader (const std::string& filename) const; + /** + * Wrapper for readFile, appends the .frag extension at the end and opens the given shader file + * + * @param filename + * + * @return The shader code as an string to be used + */ + [[nodiscard]] std::string readFragmentShader (const std::string& filename) const; - /** - * Wrapper for readFile, appends the .h extension at the end and opens the given shader file - * - * @param filename - * - * @return The shader code as an string to be used - */ - [[nodiscard]] std::string readIncludeShader (const std::string& filename) const; + /** + * Wrapper for readFile, appends the .h extension at the end and opens the given shader file + * + * @param filename + * + * @return The shader code as an string to be used + */ + [[nodiscard]] std::string readIncludeShader (const std::string& filename) const; - /** - * Reads a file as string - * - * @param filename - * - * @return The file's contents as string - */ - [[nodiscard]] std::string readFileAsString (const std::string& filename) const; - }; -} \ No newline at end of file + /** + * Reads a file as string + * + * @param filename + * + * @return The file's contents as string + */ + [[nodiscard]] std::string readFileAsString (const std::string& filename) const; +}; +} // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CDirectory.cpp b/src/WallpaperEngine/Assets/CDirectory.cpp index f80181a..dab7526 100644 --- a/src/WallpaperEngine/Assets/CDirectory.cpp +++ b/src/WallpaperEngine/Assets/CDirectory.cpp @@ -3,63 +3,54 @@ #include -#include "CDirectory.h" #include "CAssetLoadException.h" +#include "CDirectory.h" using namespace WallpaperEngine::Assets; -CDirectory::CDirectory (std::filesystem::path basepath) : - m_basepath (std::move(basepath)) -{ +CDirectory::CDirectory (std::filesystem::path basepath) : m_basepath (std::move (basepath)) { // ensure the specified path exists struct stat buffer {}; if (stat (this->m_basepath.c_str (), &buffer) != 0) throw CAssetLoadException (this->m_basepath, "Cannot find directory"); - if (!S_ISDIR(buffer.st_mode)) + if (!S_ISDIR (buffer.st_mode)) throw CAssetLoadException (this->m_basepath, "Expected directory but found a file"); } -CDirectory::~CDirectory () -= default; - -std::filesystem::path CDirectory::resolveRealFile (const std::string& filename) const -{ +std::filesystem::path CDirectory::resolveRealFile (const std::string& filename) const { return std::filesystem::path (this->m_basepath) / filename; } -const void* CDirectory::readFile (const std::string& filename, uint32_t* length) const -{ - std::filesystem::path final = std::filesystem::path (this->m_basepath) / filename; +const void* CDirectory::readFile (const std::string& filename, uint32_t* length) const { + const std::filesystem::path final = std::filesystem::path (this->m_basepath) / filename; // first check the cache, if the file is there already just return the data in there - auto it = this->m_cache.find (final); + const auto it = this->m_cache.find (final); - if (it != this->m_cache.end ()) - { + if (it != this->m_cache.end ()) { if (length != nullptr) - *length = (*it).second.length; + *length = it->second.length; - return (*it).second.address; + return it->second.address; } FILE* fp = fopen (final.c_str (), "rb"); if (fp == nullptr) - throw CAssetLoadException(filename, "Cannot find file"); + throw CAssetLoadException (filename, "Cannot find file"); // go to the end, get the position and return to the beginning fseek (fp, 0, SEEK_END); - long size = ftell (fp); + const long size = ftell (fp); fseek (fp, 0, SEEK_SET); // now read the whole file - char* contents = new char[size]; + auto* contents = new char [size]; - if (fread (contents, size, 1, fp) != 1) - { - delete[] contents; + if (fread (contents, size, 1, fp) != 1) { + delete [] contents; throw CAssetLoadException (filename, "Unexpected error when reading the file"); } diff --git a/src/WallpaperEngine/Assets/CDirectory.h b/src/WallpaperEngine/Assets/CDirectory.h index 514218c..4bb584b 100644 --- a/src/WallpaperEngine/Assets/CDirectory.h +++ b/src/WallpaperEngine/Assets/CDirectory.h @@ -1,33 +1,30 @@ #pragma once -#include -#include -#include #include +#include +#include +#include #include "CContainer.h" #include "CFileEntry.h" -namespace WallpaperEngine::Assets -{ - /** - * Directory container implementation, provides access to background files under a specific directory - */ - class CDirectory : public CContainer - { - public: - explicit CDirectory (std::filesystem::path basepath); - ~CDirectory (); +namespace WallpaperEngine::Assets { +/** + * Directory container implementation, provides access to background files under a specific directory + */ +class CDirectory final : public CContainer { + public: + explicit CDirectory (std::filesystem::path basepath); - /** @inheritdoc */ - [[nodiscard]] std::filesystem::path resolveRealFile (const std::string& filename) const override; - /** @inheritdoc */ - [[nodiscard]] const void* readFile (const std::string& filename, uint32_t* length) const override; + /** @inheritdoc */ + [[nodiscard]] std::filesystem::path resolveRealFile (const std::string& filename) const override; + /** @inheritdoc */ + [[nodiscard]] const void* readFile (const std::string& filename, uint32_t* length) const override; - private: - /** The basepath for the directory */ - std::filesystem::path m_basepath; - /** File cache to simplify access to data */ - std::map m_cache; - }; -} \ No newline at end of file + private: + /** The basepath for the directory */ + std::filesystem::path m_basepath; + /** File cache to simplify access to data */ + std::map m_cache; +}; +} // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CFileEntry.h b/src/WallpaperEngine/Assets/CFileEntry.h index e73112a..6f3ca00 100644 --- a/src/WallpaperEngine/Assets/CFileEntry.h +++ b/src/WallpaperEngine/Assets/CFileEntry.h @@ -2,21 +2,21 @@ #include -namespace WallpaperEngine::Assets -{ - /** - * File cache entry to prevent hit the disk when loading the same file multiple times - */ - class CFileEntry - { - public: - CFileEntry (const void* address, uint32_t length) : - address (address), - length (length) { } +namespace WallpaperEngine::Assets { +/** + * File cache entry to prevent hit the disk when loading the same file multiple times + */ +class CFileEntry { + public: + CFileEntry (const char* address, uint32_t length) : address (address), length (length) {} - /** File contents */ - const void* address; - /** File length */ - uint32_t length; - }; -} + ~CFileEntry () { + delete [] address; + } + + /** File contents */ + const char* address; + /** File length */ + uint32_t length; +}; +} // namespace WallpaperEngine::Assets diff --git a/src/WallpaperEngine/Assets/CPackage.cpp b/src/WallpaperEngine/Assets/CPackage.cpp index 59eaa12..d5a81db 100644 --- a/src/WallpaperEngine/Assets/CPackage.cpp +++ b/src/WallpaperEngine/Assets/CPackage.cpp @@ -1,53 +1,48 @@ -#include "common.h" #include "CPackage.h" #include "CAssetLoadException.h" #include "CPackageLoadException.h" +#include "common.h" -#include #include +#include using namespace WallpaperEngine::Assets; -class CPackageEntry -{ -public: +class CPackageEntry { + public: CPackageEntry (std::string filename, uint32_t offset, uint32_t length) : - filename (std::move(filename)), + filename (std::move (filename)), offset (offset), - length (length) { } + length (length) {} std::string filename; uint32_t offset; uint32_t length; }; -CPackage::CPackage (std::filesystem::path path) : - m_path (std::move(path)), - m_contents () -{ +CPackage::CPackage (std::filesystem::path path) : m_path (std::move (path)) { this->init (); } -CPackage::~CPackage() -= default; - - -const void* CPackage::readFile (const std::string& filename, uint32_t* length) const -{ - auto it = this->m_contents.find (filename); +const void* CPackage::readFile (const std::string& filename, uint32_t* length) const { + const auto it = this->m_contents.find (filename); if (it == this->m_contents.end ()) - throw CAssetLoadException(filename, "Cannot find the file in the package"); + throw CAssetLoadException (filename, "Cannot find the file in the package"); // set file length if required if (length != nullptr) - *length = (*it).second.length; + *length = it->second->length; - return (*it).second.address; + // clone original first + auto* result = new char [it->second->length]; + + memcpy (result, it->second->address, it->second->length); + + return result; } -void CPackage::init () -{ +void CPackage::init () { FILE* fp = fopen (this->m_path.c_str (), "rb+"); if (fp == nullptr) @@ -61,21 +56,20 @@ void CPackage::init () fclose (fp); } -char* CPackage::readSizedString (FILE* fp) -{ +char* CPackage::readSizedString (FILE* fp) { unsigned int length = 0; if (fread (&length, sizeof (unsigned int), 1, fp) != 1) sLog.exception ("Cannot read sized string length on file ", this->m_path); // account for 0 termination of the string - length ++; + length++; char* pointer = new char [length]; memset (pointer, 0, length); // read only the string bytes so the last one in the memory is 0 - length --; + length--; // read data from file if (fread (pointer, sizeof (char), length, fp) != length) @@ -84,8 +78,7 @@ char* CPackage::readSizedString (FILE* fp) return pointer; } -uint32_t CPackage::readInteger (FILE* fp) -{ +uint32_t CPackage::readInteger (FILE* fp) { uint32_t output; if (fread (&output, sizeof (uint32_t), 1, fp) != 1) @@ -94,46 +87,41 @@ uint32_t CPackage::readInteger (FILE* fp) return output; } -void CPackage::validateHeader (FILE* fp) -{ - char* pointer = this->readSizedString (fp); +void CPackage::validateHeader (FILE* fp) { + const char* pointer = this->readSizedString (fp); - if (strncmp ("PKGV", pointer, 4) != 0) - { + if (strncmp ("PKGV", pointer, 4) != 0) { std::stringstream msg; msg << "Expected PKGV indicator, found " << pointer; - delete[] pointer; - throw std::runtime_error(msg.str()); + delete [] pointer; + throw std::runtime_error (msg.str ()); } // free memory - delete[] pointer; + delete [] pointer; } -void CPackage::loadFiles (FILE* fp) -{ - uint32_t count = this->readInteger (fp); +void CPackage::loadFiles (FILE* fp) { + const uint32_t count = this->readInteger (fp); std::vector list; - for (uint32_t index = 0; index < count; index ++) - { + for (uint32_t index = 0; index < count; index++) { // first read the filename char* filename = this->readSizedString (fp); uint32_t offset = this->readInteger (fp); uint32_t length = this->readInteger (fp); // add the file to the list - list.emplace_back(filename, offset, length); + list.emplace_back (filename, offset, length); // only free filename, the file's contents are stored in a map for a later use - delete[] filename; + delete [] filename; } // get current baseOffset, this is where the files start - long baseOffset = ftell (fp); + const long baseOffset = ftell (fp); - for (const auto& cur : list) - { - long offset = cur.offset + baseOffset; + for (const auto& cur : list) { + const long offset = cur.offset + baseOffset; // with all the data we can jump to the offset and read the content if (fseek (fp, offset, SEEK_SET) != 0) @@ -142,14 +130,13 @@ void CPackage::loadFiles (FILE* fp) // allocate memory for the file's contents and read it from the file char* fileContents = new char [cur.length]; - if (fread (fileContents, cur.length, 1, fp) != 1) - { - delete[] fileContents; + if (fread (fileContents, cur.length, 1, fp) != 1) { + delete [] fileContents; sLog.exception ("Cannot read file ", cur.filename, " contents from package ", this->m_path); } // add the file to the map - this->m_contents.insert_or_assign (cur.filename, CFileEntry (fileContents, cur.length)); + this->m_contents.insert_or_assign (cur.filename, new CFileEntry (fileContents, cur.length)); } } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CPackage.h b/src/WallpaperEngine/Assets/CPackage.h index a8be5c2..70e6aef 100644 --- a/src/WallpaperEngine/Assets/CPackage.h +++ b/src/WallpaperEngine/Assets/CPackage.h @@ -1,71 +1,68 @@ #pragma once +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include #include "CContainer.h" #include "CFileEntry.h" -namespace WallpaperEngine::Assets -{ +namespace WallpaperEngine::Assets { +/** + * Package container implementation, provides access to background files that are stored + * inside the WallpaperEngine's pkg format + */ +class CPackage final : public CContainer { + public: + explicit CPackage (std::filesystem::path path); + + [[nodiscard]] const void* readFile (const std::string& filename, uint32_t* length) const override; + + protected: /** - * Package container implementation, provides access to background files that are stored - * inside the WallpaperEngine's pkg format + * Loads the current package file and loads all it's contents to memory */ - class CPackage : public CContainer - { - public: - explicit CPackage (std::filesystem::path path); - ~CPackage (); + void init (); - [[nodiscard]] const void* readFile (const std::string& filename, uint32_t* length) const override; + /** + * Reads the header from the current position and ensures it's a compatible version + * + * @param fp The file where to read from + */ + void validateHeader (FILE* fp); - protected: - /** - * Loads the current package file and loads all it's contents to memory - */ - void init (); + /** + * Loads the files in the package into memory + * + * @param fp The file where to read from + */ + void loadFiles (FILE* fp); - /** - * Reads the header from the current position and ensures it's a compatible version - * - * @param fp The file where to read from - */ - void validateHeader (FILE* fp); + /** + * Reads a size-prefixed string + * + * @param fp File to read from + * + * @return The read data, important to free it + */ + char* readSizedString (FILE* fp); + /** + * Reads a simple unsigned of 32 bits + * + * @param fp File to read from + * + * @return The read value + */ + uint32_t readInteger (FILE* fp); - /** - * Loads the files in the package into memory - * - * @param fp The file where to read from - */ - void loadFiles (FILE* fp); - - /** - * Reads a size-prefixed string - * - * @param fp File to read from - * - * @return The read data, important to free it - */ - char* readSizedString (FILE* fp); - /** - * Reads a simple unsigned of 32 bits - * - * @param fp File to read from - * - * @return The read value - */ - uint32_t readInteger (FILE* fp); - - private: - /** The path to the package file */ - std::filesystem::path m_path; - /** Contents of the package file */ - std::map m_contents; - }; -} + private: + /** The path to the package file */ + std::filesystem::path m_path; + /** Contents of the package file */ + std::map m_contents; +}; +} // namespace WallpaperEngine::Assets diff --git a/src/WallpaperEngine/Assets/CPackageLoadException.cpp b/src/WallpaperEngine/Assets/CPackageLoadException.cpp index 7ed7eb8..e47b3e7 100644 --- a/src/WallpaperEngine/Assets/CPackageLoadException.cpp +++ b/src/WallpaperEngine/Assets/CPackageLoadException.cpp @@ -3,11 +3,8 @@ using namespace WallpaperEngine::Assets; CPackageLoadException::CPackageLoadException (const std::string& filename, const std::string& extrainfo) : - m_message ("Cannot load package " + filename + ": " + extrainfo) -{ -} + m_message ("Cannot load package " + filename + ": " + extrainfo) {} -const char *CPackageLoadException::what () const noexcept -{ +const char* CPackageLoadException::what () const noexcept { return this->m_message.c_str (); } diff --git a/src/WallpaperEngine/Assets/CPackageLoadException.h b/src/WallpaperEngine/Assets/CPackageLoadException.h index e94c6e5..0be83f3 100644 --- a/src/WallpaperEngine/Assets/CPackageLoadException.h +++ b/src/WallpaperEngine/Assets/CPackageLoadException.h @@ -3,15 +3,13 @@ #include #include -namespace WallpaperEngine::Assets -{ - class CPackageLoadException : public std::exception - { - public: - explicit CPackageLoadException (const std::string& message, const std::string& extrainfo = ""); - [[nodiscard]] const char* what () const noexcept override; +namespace WallpaperEngine::Assets { +class CPackageLoadException final : public std::exception { + public: + explicit CPackageLoadException (const std::string& filename, const std::string& extrainfo = ""); + [[nodiscard]] const char* what () const noexcept override; - private: - std::string m_message; - }; -} \ No newline at end of file + private: + std::string m_message; +}; +} // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CTexture.cpp b/src/WallpaperEngine/Assets/CTexture.cpp index 05db4d4..7d4d307 100644 --- a/src/WallpaperEngine/Assets/CTexture.cpp +++ b/src/WallpaperEngine/Assets/CTexture.cpp @@ -1,53 +1,37 @@ -#include "common.h" #include "CTexture.h" +#include "common.h" -#include #include #include +#include using namespace WallpaperEngine::Assets; -CTexture::CTexture (const void* fileData) : - m_resolution () -{ +CTexture::CTexture (const void* fileData) : m_resolution () { // ensure the header is parsed - this->m_header = parseHeader (static_cast (fileData)); + this->m_header = parseHeader (static_cast (fileData)); GLint internalFormat; - if (this->isAnimated ()) - { - this->m_resolution = { - this->m_header->textureWidth, this->m_header->textureHeight, - this->m_header->gifWidth, this->m_header->gifHeight - }; - } - else - { - if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) - { + if (this->isAnimated ()) { + this->m_resolution = {this->m_header->textureWidth, this->m_header->textureHeight, this->m_header->gifWidth, + this->m_header->gifHeight}; + } else { + if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) { // wpengine-texture format always has one mipmap // get first image size auto element = this->m_header->images.find (0)->second.begin (); // set the texture resolution - this->m_resolution = { - (*element)->width, (*element)->height, - this->m_header->width, this->m_header->height - }; - } - else - { + this->m_resolution = {(*element)->width, (*element)->height, this->m_header->width, this->m_header->height}; + } else { // set the texture resolution - this->m_resolution = { - this->m_header->textureWidth, this->m_header->textureHeight, - this->m_header->width, this->m_header->height - }; + this->m_resolution = {this->m_header->textureWidth, this->m_header->textureHeight, this->m_header->width, + this->m_header->height}; } } - if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) - { + if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) { internalFormat = GL_RGBA8; // set some extra information too as it's used for image sizing // this ensures that a_TexCoord uses the full image instead of just part of it @@ -56,33 +40,16 @@ CTexture::CTexture (const void* fileData) : this->m_header->height = this->m_header->mipmaps [0]->height; this->m_header->textureWidth = this->m_header->mipmaps [0]->width; this->m_header->textureHeight = this->m_header->mipmaps [0]->height;*/ - } - else - { + } else { // detect the image format and hand it to openGL to be used - switch (this->m_header->format) - { - case TextureFormat::DXT5: - internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - break; - case TextureFormat::DXT3: - internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; - break; - case TextureFormat::DXT1: - internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; - break; - case TextureFormat::ARGB8888: - internalFormat = GL_RGBA8; - break; - case TextureFormat::R8: - internalFormat = GL_R8; - break; - case TextureFormat::RG88: - internalFormat = GL_RG8; - break; - default: - delete this->m_header; - sLog.exception ("Cannot determine texture format"); + switch (this->m_header->format) { + case TextureFormat::DXT5: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; + case TextureFormat::DXT3: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; + case TextureFormat::DXT1: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; + case TextureFormat::ARGB8888: internalFormat = GL_RGBA8; break; + case TextureFormat::R8: internalFormat = GL_R8; break; + case TextureFormat::RG88: internalFormat = GL_RG8; break; + default: delete this->m_header; sLog.exception ("Cannot determine texture format"); } } @@ -94,8 +61,7 @@ CTexture::CTexture (const void* fileData) : auto imgCur = this->m_header->images.begin (); auto imgEnd = this->m_header->images.end (); - for (int index = 0; imgCur != imgEnd; imgCur ++, index ++) - { + for (int index = 0; imgCur != imgEnd; ++imgCur, index++) { // bind the texture to assign information to it glBindTexture (GL_TEXTURE_2D, this->m_textureID [index]); @@ -104,35 +70,28 @@ CTexture::CTexture (const void* fileData) : glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, this->m_header->mipmapCount - 1); // setup texture wrapping and filtering - if (this->m_header->flags & TextureFlags::ClampUVs) - { + if (this->m_header->flags & TextureFlags::ClampUVs) { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - } - else - { + } else { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } - if (this->m_header->flags & TextureFlags::NoInterpolation) - { + if (this->m_header->flags & TextureFlags::NoInterpolation) { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); - } - else - { + } else { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY, 8.0f); - auto cur = (*imgCur).second.begin (); - auto end = (*imgCur).second.end (); + auto cur = imgCur->second.begin (); + auto end = imgCur->second.end (); - for (int32_t level = 0; cur != end; cur ++, level ++) - { + for (int32_t level = 0; cur != end; ++cur, level++) { FIBITMAP* bitmap = nullptr; FIBITMAP* converted = nullptr; FIMEMORY* memory = nullptr; @@ -142,9 +101,9 @@ CTexture::CTexture (const void* fileData) : uint32_t bufferSize = (*cur)->uncompressedSize; GLenum textureFormat = GL_RGBA; - if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) - { - memory = FreeImage_OpenMemory (reinterpret_cast ((*cur)->uncompressedData), (*cur)->uncompressedSize); + if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) { + memory = + FreeImage_OpenMemory (reinterpret_cast ((*cur)->uncompressedData), (*cur)->uncompressedSize); // load the image and setup pointers so they can be used bitmap = FreeImage_LoadFromMemory (this->m_header->freeImageFormat, memory); @@ -158,47 +117,33 @@ CTexture::CTexture (const void* fileData) : height = FreeImage_GetHeight (converted); bufferSize = FreeImage_GetMemorySize (converted); textureFormat = GL_BGRA; - } - else - { - if (this->m_header->format == TextureFormat::R8) - { + } else { + if (this->m_header->format == TextureFormat::R8) { // red textures are 1-byte-per-pixel, so it's alignment has to be set manually glPixelStorei (GL_UNPACK_ALIGNMENT, 1); textureFormat = GL_RED; - } - else if (this->m_header->format == TextureFormat::RG88) + } else if (this->m_header->format == TextureFormat::RG88) textureFormat = GL_RG; } - switch (internalFormat) - { - case GL_RGBA8: - case GL_RG8: - case GL_R8: - glTexImage2D ( - GL_TEXTURE_2D, level, internalFormat, - width, height, 0, - textureFormat, GL_UNSIGNED_BYTE, - dataptr - ); - break; - case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: - case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: - case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - glCompressedTexImage2D ( - GL_TEXTURE_2D, level, internalFormat, - width, height, 0, - bufferSize, dataptr - ); - break; - default: - sLog.exception ("Cannot load texture, unknown format", this->m_header->format); + switch (internalFormat) { + case GL_RGBA8: + case GL_RG8: + case GL_R8: + glTexImage2D (GL_TEXTURE_2D, level, internalFormat, width, height, 0, textureFormat, + GL_UNSIGNED_BYTE, dataptr); + break; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: + case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: + glCompressedTexImage2D (GL_TEXTURE_2D, level, internalFormat, width, height, 0, bufferSize, + dataptr); + break; + default: sLog.exception ("Cannot load texture, unknown format", this->m_header->format); } // freeimage buffer won't be used anymore, so free memory - if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) - { + if (this->m_header->freeImageFormat != FREE_IMAGE_FORMAT::FIF_UNKNOWN) { FreeImage_Unload (bitmap); FreeImage_Unload (converted); FreeImage_CloseMemory (memory); @@ -207,8 +152,7 @@ CTexture::CTexture (const void* fileData) : } } -CTexture::~CTexture () -{ +CTexture::~CTexture () { if (this->getHeader () == nullptr) return; @@ -216,8 +160,7 @@ CTexture::~CTexture () delete this->getHeader (); } -const GLuint CTexture::getTextureID (uint32_t imageIndex) const -{ +const GLuint CTexture::getTextureID (uint32_t imageIndex) const { // ensure we do not go out of bounds if (imageIndex > this->m_header->imageCount) return this->m_textureID [0]; @@ -225,87 +168,73 @@ const GLuint CTexture::getTextureID (uint32_t imageIndex) const return this->m_textureID [imageIndex]; } -const uint32_t CTexture::getTextureWidth (uint32_t imageIndex) const -{ +const uint32_t CTexture::getTextureWidth (uint32_t imageIndex) const { if (imageIndex > this->m_header->imageCount) return this->getHeader ()->textureWidth; return (*this->m_header->images [imageIndex].begin ())->width; } -const uint32_t CTexture::getTextureHeight (uint32_t imageIndex) const -{ +const uint32_t CTexture::getTextureHeight (uint32_t imageIndex) const { if (imageIndex > this->m_header->imageCount) return this->getHeader ()->textureHeight; return (*this->m_header->images [imageIndex].begin ())->height; } -const uint32_t CTexture::getRealWidth () const -{ +const uint32_t CTexture::getRealWidth () const { return this->isAnimated () ? this->getHeader ()->gifWidth : this->getHeader ()->width; } -const uint32_t CTexture::getRealHeight () const -{ +const uint32_t CTexture::getRealHeight () const { return this->isAnimated () ? this->getHeader ()->gifHeight : this->getHeader ()->height; } -const ITexture::TextureFormat CTexture::getFormat () const -{ +const ITexture::TextureFormat CTexture::getFormat () const { return this->getHeader ()->format; } -const ITexture::TextureFlags CTexture::getFlags () const -{ +const ITexture::TextureFlags CTexture::getFlags () const { return this->getHeader ()->flags; } -const CTexture::TextureHeader* CTexture::getHeader () const -{ +const CTexture::TextureHeader* CTexture::getHeader () const { return this->m_header; } -const glm::vec4* CTexture::getResolution () const -{ +const glm::vec4* CTexture::getResolution () const { return &this->m_resolution; } -const std::vector& CTexture::getFrames () const -{ +const std::vector& CTexture::getFrames () const { return this->getHeader ()->frames; } -const bool CTexture::isAnimated () const -{ +const bool CTexture::isAnimated () const { return this->getHeader ()->isAnimated (); } -CTexture::TextureMipmap::TextureMipmap () -= default; +CTexture::TextureMipmap::TextureMipmap () = default; -CTexture::TextureMipmap::~TextureMipmap () -{ +CTexture::TextureMipmap::~TextureMipmap () { if (this->compression == 1) delete this->compressedData; delete this->uncompressedData; } -void CTexture::TextureMipmap::decompressData () -{ - if (this->compression == 1) - { - this->uncompressedData = new char [this->uncompressedSize]; - - int result = LZ4_decompress_safe ( - this->compressedData, this->uncompressedData, - this->compressedSize, this->uncompressedSize - ); - - if (!result) - sLog.exception ("Cannot decompress texture data, LZ4_decompress_safe returned an error"); +void CTexture::TextureMipmap::decompressData () { + if (this->compression != 1) { + return; } + + this->uncompressedData = new char [this->uncompressedSize]; + + const int result = LZ4_decompress_safe (this->compressedData, this->uncompressedData, this->compressedSize, + this->uncompressedSize); + + if (!result) + sLog.exception ("Cannot decompress texture data, LZ4_decompress_safe returned an error"); } CTexture::TextureFrame::TextureFrame () : @@ -316,12 +245,7 @@ CTexture::TextureFrame::TextureFrame () : width1 (0), width2 (0), height1 (0), - height2 (0) -{ -} - -CTexture::TextureFrame::~TextureFrame () -= default; + height2 (0) {} CTexture::TextureHeader::TextureHeader () : flags (NoFlags), @@ -333,130 +257,109 @@ CTexture::TextureHeader::TextureHeader () : gifHeight (0), format (TextureFormat::UNKNOWN), imageCount (0), - mipmapCount (0) -{ -} + mipmapCount (0) {} -CTexture::TextureHeader::~TextureHeader () -{ - for (const auto& imgCur : this->images) - for (auto cur : imgCur.second) +CTexture::TextureHeader::~TextureHeader () { + for (const auto& [index, mipmaps] : this->images) + for (const auto cur : mipmaps) delete cur; } -CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) -{ +CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) { // check the magic value on the header first - if (memcmp (fileData, "TEXV0005", 9) != 0) + if (strncmp (fileData, "TEXV0005", 9) != 0) sLog.exception ("unexpected texture container type: ", std::string_view (fileData, 9)); // jump to the next value fileData += 9; // check the sub-magic value on the header - if (memcmp (fileData, "TEXI0001", 9) != 0) + if (strncmp (fileData, "TEXI0001", 9) != 0) sLog.exception ("unexpected texture sub-container type: ", std::string_view (fileData, 9)); // jump through the string again fileData += 9; auto* header = new TextureHeader; - const auto* pointer = reinterpret_cast (fileData); + const auto* pointer = reinterpret_cast (fileData); - header->format = static_cast (*pointer ++); - header->flags = static_cast (*pointer ++); - header->textureWidth = *pointer ++; - header->textureHeight = *pointer ++; - header->width = *pointer ++; - header->height = *pointer ++; - pointer ++; // ignore some more bytes + header->format = static_cast (*pointer++); + header->flags = static_cast (*pointer++); + header->textureWidth = *pointer++; + header->textureHeight = *pointer++; + header->width = *pointer++; + header->height = *pointer++; + pointer++; // ignore some more bytes // now we're going to parse some more data that is string // so get the current position back as string - fileData = reinterpret_cast (pointer); + fileData = reinterpret_cast (pointer); // get the position of what comes after the texture data - pointer = reinterpret_cast (fileData + 9); + pointer = reinterpret_cast (fileData + 9); - if (memcmp (fileData, "TEXB0003", 9) == 0) - { + if (strncmp (fileData, "TEXB0003", 9) == 0) { header->containerVersion = ContainerVersion::TEXB0003; - header->imageCount = *pointer ++; - header->freeImageFormat = static_cast (*pointer++); - } - else if(memcmp (fileData, "TEXB0002", 9) == 0) - { + header->imageCount = *pointer++; + header->freeImageFormat = static_cast (*pointer++); + } else if (strncmp (fileData, "TEXB0002", 9) == 0) { header->containerVersion = ContainerVersion::TEXB0002; - header->imageCount = *pointer ++; - } - else if (memcmp (fileData, "TEXB0001", 9) == 0) - { + header->imageCount = *pointer++; + } else if (strncmp (fileData, "TEXB0001", 9) == 0) { header->containerVersion = ContainerVersion::TEXB0001; - header->imageCount = *pointer ++; - } - else - { + header->imageCount = *pointer++; + } else { delete header; sLog.exception ("unknown texture format type: ", std::string_view (fileData, 9)); } - for (uint32_t image = 0; image < header->imageCount; image ++) - { + for (uint32_t image = 0; image < header->imageCount; image++) { // read the number of mipmaps available for this image - header->mipmapCount = *pointer ++; - std::vector mipmaps; + header->mipmapCount = *pointer++; + std::vector mipmaps; - fileData = reinterpret_cast (pointer); + fileData = reinterpret_cast (pointer); - for (uint32_t i = 0; i < header->mipmapCount; i ++) + for (uint32_t i = 0; i < header->mipmapCount; i++) mipmaps.emplace_back (parseMipmap (header, &fileData)); // add the pixmaps back - header->images.insert (std::pair > (image, mipmaps)); + header->images.insert (std::pair (image, mipmaps)); - pointer = reinterpret_cast (fileData); + pointer = reinterpret_cast (fileData); } // gifs have extra information after the mipmaps - if (header->isAnimated () == true) - { - if (memcmp (fileData, "TEXS0002", 9) == 0) - { + if (header->isAnimated () == true) { + if (strncmp (fileData, "TEXS0002", 9) == 0) { header->animatedVersion = AnimatedVersion::TEXS0002; - } - else if (memcmp (fileData, "TEXS0003", 9) == 0) - { + } else if (strncmp (fileData, "TEXS0003", 9) == 0) { header->animatedVersion = AnimatedVersion::TEXS0003; - } - else - { + } else { delete header; sLog.exception ("found animation information of unknown type: ", std::string_view (fileData, 9)); } // get an integer pointer back to read the frame count - pointer = reinterpret_cast (fileData + 9); + pointer = reinterpret_cast (fileData + 9); uint32_t framecount = *pointer++; - if (header->animatedVersion == AnimatedVersion::TEXS0003) - { + if (header->animatedVersion == AnimatedVersion::TEXS0003) { // ignore two extra integers as those are width and height of the git - header->gifWidth = *pointer ++; - header->gifHeight = *pointer ++; + header->gifWidth = *pointer++; + header->gifHeight = *pointer++; } // get back the pointer into filedata - fileData = reinterpret_cast (pointer); + fileData = reinterpret_cast (pointer); - while (framecount > 0) - { + while (framecount > 0) { // add the frame to the list header->frames.push_back (parseAnimation (&fileData)); - framecount --; + framecount--; } // ensure gif width and height is right for TEXS0002 - if (header->animatedVersion == AnimatedVersion::TEXS0002) - { - TextureFrame* first = *header->frames.begin (); + if (header->animatedVersion == AnimatedVersion::TEXS0002) { + const TextureFrame* first = *header->frames.begin (); header->gifWidth = first->width1; header->gifHeight = first->height1; @@ -466,50 +369,47 @@ CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) return header; } -CTexture::TextureFrame* CTexture::parseAnimation (const char** originalFileData) -{ +CTexture::TextureFrame* CTexture::parseAnimation (const char** originalFileData) { const char* fileData = *originalFileData; // get back the pointer into integer - const auto* pointer = reinterpret_cast (fileData); + const auto* pointer = reinterpret_cast (fileData); // start reading frame information - auto* frame = new TextureFrame(); + auto* frame = new TextureFrame (); frame->frameNumber = *pointer++; // reinterpret the pointer into float - const auto* fPointer = reinterpret_cast (pointer); + const auto* fPointer = reinterpret_cast (pointer); - frame->frametime = *fPointer ++; - frame->x = *fPointer ++; - frame->y = *fPointer ++; - frame->width1 = *fPointer ++; - frame->width2 = *fPointer ++; - frame->height2 = *fPointer ++; - frame->height1 = *fPointer ++; + frame->frametime = *fPointer++; + frame->x = *fPointer++; + frame->y = *fPointer++; + frame->width1 = *fPointer++; + frame->width2 = *fPointer++; + frame->height2 = *fPointer++; + frame->height1 = *fPointer++; // get back the pointer into fileData so it can be reused later - *originalFileData = reinterpret_cast (fPointer); + *originalFileData = reinterpret_cast (fPointer); return frame; } -CTexture::TextureMipmap* CTexture::parseMipmap (TextureHeader* header, const char** originalFileData) -{ +CTexture::TextureMipmap* CTexture::parseMipmap (const TextureHeader* header, const char** originalFileData) { auto* mipmap = new TextureMipmap (); // get the current position const char* fileData = *originalFileData; // get an integer pointer - const auto* pointer = reinterpret_cast (fileData); + const auto* pointer = reinterpret_cast (fileData); mipmap->width = *pointer++; mipmap->height = *pointer++; if (header->containerVersion == ContainerVersion::TEXB0002 || - header->containerVersion == ContainerVersion::TEXB0003) - { + header->containerVersion == ContainerVersion::TEXB0003) { mipmap->compression = *pointer++; mipmap->uncompressedSize = *pointer++; } @@ -517,10 +417,9 @@ CTexture::TextureMipmap* CTexture::parseMipmap (TextureHeader* header, const cha mipmap->compressedSize = *pointer++; // get back a normal char pointer - fileData = reinterpret_cast (pointer); + fileData = reinterpret_cast (pointer); - if (mipmap->compression == 0) - { + if (mipmap->compression == 0) { // this might be better named as mipmap_bytes_size instead of compressedSize // as in uncompressed files this variable actually holds the file length mipmap->uncompressedSize = mipmap->compressedSize; @@ -528,8 +427,7 @@ CTexture::TextureMipmap* CTexture::parseMipmap (TextureHeader* header, const cha mipmap->uncompressedData = new char [mipmap->uncompressedSize]; - if (mipmap->compression == 1) - { + if (mipmap->compression == 1) { mipmap->compressedData = new char [mipmap->compressedSize]; memcpy (mipmap->compressedData, fileData, mipmap->compressedSize); @@ -537,9 +435,7 @@ CTexture::TextureMipmap* CTexture::parseMipmap (TextureHeader* header, const cha mipmap->decompressData (); // advance to the end of the mipmap fileData += mipmap->compressedSize; - } - else - { + } else { memcpy (mipmap->uncompressedData, fileData, mipmap->uncompressedSize); // advance to the end of the mipmap fileData += mipmap->uncompressedSize; @@ -551,7 +447,6 @@ CTexture::TextureMipmap* CTexture::parseMipmap (TextureHeader* header, const cha return mipmap; } -bool CTexture::TextureHeader::isAnimated () const -{ +bool CTexture::TextureHeader::isAnimated () const { return this->flags & TextureFlags::IsGif; } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CTexture.h b/src/WallpaperEngine/Assets/CTexture.h index 7c37df6..fb27c3a 100644 --- a/src/WallpaperEngine/Assets/CTexture.h +++ b/src/WallpaperEngine/Assets/CTexture.h @@ -10,166 +10,159 @@ #include #include -namespace WallpaperEngine::Assets -{ +namespace WallpaperEngine::Assets { +/** + * A normal texture file in WallpaperEngine's format + */ +class CTexture final : public ITexture { /** - * A normal texture file in WallpaperEngine's format + * Different texture container versions supported */ - class CTexture : public ITexture - { - private: - /** - * Different texture container versions supported - */ - enum ContainerVersion : int - { - UNKNOWN = -1, - TEXB0003 = 3, - TEXB0002 = 2, - TEXB0001 = 1 - }; - - /** - * Different texture animation versions supported - */ - enum AnimatedVersion : int - { - TEXSUNKN = -1, - TEXS0002 = 0, - TEXS0003 = 1, - }; - - /** - * Texture mipmap data - */ - class TextureMipmap - { - public: - TextureMipmap (); - ~TextureMipmap (); - - /** Width of the mipmap */ - uint32_t width = 0; - /** Height of the mipmap */ - uint32_t height = 0; - /** If the mipmap data is compressed */ - uint32_t compression = 0; - /** Uncompressed size of the mipmap */ - uint32_t uncompressedSize = 0; - /** Compress size of the mipmap */ - uint32_t compressedSize = 0; - /** Pointer to the compressed data */ - char* compressedData = nullptr; - /** Pointer to the uncompressed data */ - char* uncompressedData = nullptr; - /** - * Performs actual decompression of the compressed data - */ - void decompressData (); - }; - - /** - * Texture header data - */ - class TextureHeader - { - public: - TextureHeader (); - ~TextureHeader (); - - [[nodiscard]] bool isAnimated () const; - - /** The version of the texture container */ - ContainerVersion containerVersion = ContainerVersion::UNKNOWN; - /** The version of the animated data */ - AnimatedVersion animatedVersion = AnimatedVersion::TEXSUNKN; - /** Flags with extra texture information */ - TextureFlags flags; - /** Real width of the texture */ - uint32_t width; - /** Real height of the texture */ - uint32_t height; - /** Texture width in memory (power of 2) */ - uint32_t textureWidth; - /** Texture height in memory (power of 2) */ - uint32_t textureHeight; - /** Gif width */ - uint32_t gifWidth; - /** Gif height */ - uint32_t gifHeight; - /** Texture data format */ - TextureFormat format; - /** Free Image format */ - FREE_IMAGE_FORMAT freeImageFormat = FREE_IMAGE_FORMAT::FIF_UNKNOWN; - /** The amount of images in the texture file */ - uint32_t imageCount; - /** Number of mipmap levels on the texture */ - uint32_t mipmapCount; - /** List of mipmaps */ - std::map> images; - /** List of animation frames */ - std::vector frames; - }; - - public: - explicit CTexture (const void* fileData); - ~CTexture (); - - /** @inheritdoc */ - [[nodiscard]] const GLuint getTextureID (uint32_t imageIndex = 0) const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getTextureWidth (uint32_t imageIndex = 0) const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getTextureHeight (uint32_t imageIndex = 0) const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getRealWidth () const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getRealHeight () const override; - /** @inheritdoc */ - [[nodiscard]] const TextureFormat getFormat () const override; - /** @inheritdoc */ - [[nodiscard]] const TextureFlags getFlags () const override; - /** @inheritdoc */ - [[nodiscard]] const glm::vec4* getResolution () const override; - /** @inheritdoc */ - [[nodiscard]] const std::vector& getFrames () const override; - /** @inheritdoc */ - [[nodiscard]] const bool isAnimated () const override; - - private: - /** - * @return The texture header - */ - [[nodiscard]] const TextureHeader* getHeader () const; - - /** - * Tries to parse a header off the given data pointer - * - * @param fileData The point at which to start reading data off from - * @return - */ - static TextureHeader* parseHeader (const char* fileData); - /** - * Tries to parse an animation frame off the given data pointer - * - * @param originalFileData The point at which to start reading data off from - * @return - */ - static TextureFrame* parseAnimation (const char** originalFileData); - /** - * Tries to parse mipmap information off the given data pointer - * - * @param header The file header - * @param fileData The point at which to start reading data off from - * @return - */ - static TextureMipmap* parseMipmap (TextureHeader* header, const char** fileData); - - /** The texture header */ - TextureHeader* m_header; - /** OpenGL's texture ID */ - GLuint* m_textureID; - /** Resolution vector of the texture */ - glm::vec4 m_resolution; + enum ContainerVersion : int { + UNKNOWN = -1, + TEXB0003 = 3, + TEXB0002 = 2, + TEXB0001 = 1 }; -} \ No newline at end of file + + /** + * Different texture animation versions supported + */ + enum AnimatedVersion : int { + TEXSUNKN = -1, + TEXS0002 = 0, + TEXS0003 = 1, + }; + + /** + * Texture mipmap data + */ + class TextureMipmap { + public: + TextureMipmap (); + ~TextureMipmap (); + + /** Width of the mipmap */ + uint32_t width = 0; + /** Height of the mipmap */ + uint32_t height = 0; + /** If the mipmap data is compressed */ + uint32_t compression = 0; + /** Uncompressed size of the mipmap */ + uint32_t uncompressedSize = 0; + /** Compress size of the mipmap */ + uint32_t compressedSize = 0; + /** Pointer to the compressed data */ + char* compressedData = nullptr; + /** Pointer to the uncompressed data */ + char* uncompressedData = nullptr; + /** + * Performs actual decompression of the compressed data + */ + void decompressData (); + }; + + /** + * Texture header data + */ + class TextureHeader { + public: + TextureHeader (); + ~TextureHeader (); + + [[nodiscard]] bool isAnimated () const; + + /** The version of the texture container */ + ContainerVersion containerVersion = ContainerVersion::UNKNOWN; + /** The version of the animated data */ + AnimatedVersion animatedVersion = AnimatedVersion::TEXSUNKN; + /** Flags with extra texture information */ + TextureFlags flags; + /** Real width of the texture */ + uint32_t width; + /** Real height of the texture */ + uint32_t height; + /** Texture width in memory (power of 2) */ + uint32_t textureWidth; + /** Texture height in memory (power of 2) */ + uint32_t textureHeight; + /** Gif width */ + uint32_t gifWidth; + /** Gif height */ + uint32_t gifHeight; + /** Texture data format */ + TextureFormat format; + /** Free Image format */ + FREE_IMAGE_FORMAT freeImageFormat = FREE_IMAGE_FORMAT::FIF_UNKNOWN; + /** The amount of images in the texture file */ + uint32_t imageCount; + /** Number of mipmap levels on the texture */ + uint32_t mipmapCount; + /** List of mipmaps */ + std::map> images; + /** List of animation frames */ + std::vector frames; + }; + + public: + explicit CTexture (const void* fileData); + ~CTexture () override; + + /** @inheritdoc */ + [[nodiscard]] const GLuint getTextureID (uint32_t imageIndex = 0) const override; + /** @inheritdoc */ + [[nodiscard]] const uint32_t getTextureWidth (uint32_t imageIndex = 0) const override; + /** @inheritdoc */ + [[nodiscard]] const uint32_t getTextureHeight (uint32_t imageIndex = 0) const override; + /** @inheritdoc */ + [[nodiscard]] const uint32_t getRealWidth () const override; + /** @inheritdoc */ + [[nodiscard]] const uint32_t getRealHeight () const override; + /** @inheritdoc */ + [[nodiscard]] const TextureFormat getFormat () const override; + /** @inheritdoc */ + [[nodiscard]] const TextureFlags getFlags () const override; + /** @inheritdoc */ + [[nodiscard]] const glm::vec4* getResolution () const override; + /** @inheritdoc */ + [[nodiscard]] const std::vector& getFrames () const override; + /** @inheritdoc */ + [[nodiscard]] const bool isAnimated () const override; + + private: + /** + * @return The texture header + */ + [[nodiscard]] const TextureHeader* getHeader () const; + + /** + * Tries to parse a header off the given data pointer + * + * @param fileData The point at which to start reading data off from + * @return + */ + static TextureHeader* parseHeader (const char* fileData); + /** + * Tries to parse an animation frame off the given data pointer + * + * @param originalFileData The point at which to start reading data off from + * @return + */ + static TextureFrame* parseAnimation (const char** originalFileData); + /** + * Tries to parse mipmap information off the given data pointer + * + * @param header The file header + * @param fileData The point at which to start reading data off from + * @return + */ + static TextureMipmap* parseMipmap (const TextureHeader* header, const char** fileData); + + /** The texture header */ + TextureHeader* m_header; + /** OpenGL's texture ID */ + GLuint* m_textureID; + /** Resolution vector of the texture */ + glm::vec4 m_resolution; +}; +} // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CVirtualContainer.cpp b/src/WallpaperEngine/Assets/CVirtualContainer.cpp index 2a8d69d..9f0dca9 100644 --- a/src/WallpaperEngine/Assets/CVirtualContainer.cpp +++ b/src/WallpaperEngine/Assets/CVirtualContainer.cpp @@ -1,19 +1,15 @@ #include -#include "CVirtualContainer.h" #include "CAssetLoadException.h" +#include "CVirtualContainer.h" using namespace WallpaperEngine::Assets; -void CVirtualContainer::add (const std::string& filename, void* contents, uint32_t length) -{ - this->m_virtualFiles.insert ( - std::make_pair (filename, CFileEntry (contents, length)) - ); +void CVirtualContainer::add (const std::string& filename, const char* contents, uint32_t length) { + this->m_virtualFiles.insert (std::make_pair (filename, new CFileEntry (contents, length))); } -void CVirtualContainer::add (const std::string& filename, const std::string& contents) -{ +void CVirtualContainer::add (const std::string& filename, const std::string& contents) { char* copy = new char [contents.length () + 1]; // copy the text AND the \0 @@ -23,14 +19,19 @@ void CVirtualContainer::add (const std::string& filename, const std::string& con this->add (filename, copy, contents.length () + 1); } -const void* CVirtualContainer::readFile (const std::string& filename, uint32_t* length) const -{ - auto cur = this->m_virtualFiles.find (filename); +const void* CVirtualContainer::readFile (const std::string& filename, uint32_t* length) const { + const auto cur = this->m_virtualFiles.find (filename); if (cur == this->m_virtualFiles.end ()) throw CAssetLoadException (filename, "Cannot find file in the virtual container"); - *length = (*cur).second.length; + if (length != nullptr) + *length = cur->second->length; - return (*cur).second.address; + // clone original first + char* result = new char [cur->second->length]; + + memcpy (result, cur->second->address, cur->second->length); + + return result; } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CVirtualContainer.h b/src/WallpaperEngine/Assets/CVirtualContainer.h index 9327d65..bf8e760 100644 --- a/src/WallpaperEngine/Assets/CVirtualContainer.h +++ b/src/WallpaperEngine/Assets/CVirtualContainer.h @@ -1,43 +1,38 @@ #pragma once -#include #include +#include -#include "CFileEntry.h" #include "CContainer.h" +#include "CFileEntry.h" -namespace WallpaperEngine::Assets -{ +namespace WallpaperEngine::Assets { +/** + * Virtual container implementation, provides virtual files for the backgrounds to use + */ +class CVirtualContainer final : public CContainer { + public: /** - * Virtual container implementation, provides virtual files for the backgrounds to use + * Adds a new file to the virtual container + * + * @param filename + * @param contents + * @param length */ - class CVirtualContainer : public CContainer - { - public: - CVirtualContainer () = default; - ~CVirtualContainer () = default; + void add (const std::string& filename, const char* contents, uint32_t length); - /** - * Adds a new file to the virtual container - * - * @param filename - * @param contents - * @param length - */ - void add (const std::string& filename, void* contents, uint32_t length); + /** + * Adds a new file to the virtual container + * + * @param filename + * @param contents + */ + void add (const std::string& filename, const std::string& contents); + /** @inheritdoc */ + const void* readFile (const std::string& filename, uint32_t* length) const override; - /** - * Adds a new file to the virtual container - * - * @param filename - * @param contents - */ - void add (const std::string& filename, const std::string& contents); - /** @inheritdoc */ - const void* readFile (const std::string& filename, uint32_t* length) const override; - - private: - /** The recorded files in this virtual container */ - std::map m_virtualFiles; - }; -} \ No newline at end of file + private: + /** The recorded files in this virtual container */ + std::map m_virtualFiles; +}; +} // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/ITexture.h b/src/WallpaperEngine/Assets/ITexture.h index 42037a9..03fa0a4 100644 --- a/src/WallpaperEngine/Assets/ITexture.h +++ b/src/WallpaperEngine/Assets/ITexture.h @@ -4,116 +4,113 @@ #include #include -namespace WallpaperEngine::Assets -{ +namespace WallpaperEngine::Assets { +/** + * Base interface that describes the minimum information required for a texture + * to be displayed by the engine + */ +class ITexture { + public: + virtual ~ITexture () = default; + /** - * Base interface that describes the minimum information required for a texture - * to be displayed by the engine + * Texture frame information for animated textures */ - class ITexture - { - public: - /** - * Texture frame information for animated textures - */ - class TextureFrame - { - public: - TextureFrame(); - ~TextureFrame(); + class TextureFrame final { + public: + TextureFrame (); + virtual ~TextureFrame () = default; - /** The image index of this frame */ - uint32_t frameNumber; - /** The amount of time this frame spends being displayed */ - float frametime; - /** The x position of the frame in the texture */ - float x; - /** The y position of the frame in the texture */ - float y; - /** The width of the frame in the texture */ - float width1; - float width2; - float height2; - /** The height of the frame in the texture */ - float height1; - }; - - /** - * Data formats for textures in memory - */ - enum TextureFormat : uint32_t - { - UNKNOWN = 0xFFFFFFFF, - ARGB8888 = 0, - RGB888 = 1, - RGB565 = 2, - DXT5 = 4, - DXT3 = 6, - DXT1 = 7, - RG88 = 8, - R8 = 9, - RG1616f = 10, - R16f = 11, - BC7 = 12, - RGBa1010102 = 13, - RGBA16161616f = 14, - RGB161616f = 15, - }; - - /** - * Different settings of the textures - */ - enum TextureFlags : uint32_t - { - NoFlags = 0, - NoInterpolation = 1, - ClampUVs = 2, - IsGif = 4, - ClampUVsBorder = 8, - }; - - /** - * @param imageIndex For animated textures, the frame to get the ID of - * @return The OpenGL texture to use when rendering - */ - [[nodiscard]] virtual const GLuint getTextureID (uint32_t imageIndex = 0) const = 0; - /** - * @param imageIndex For animated textures, the frame to get the ID of - * @return The texture's width - */ - [[nodiscard]] virtual const uint32_t getTextureWidth (uint32_t imageIndex = 0) const = 0; - /** - * @param imageIndex For animated textures, the frame to get the ID of - * @return The texture's height - */ - [[nodiscard]] virtual const uint32_t getTextureHeight (uint32_t imageIndex = 0) const = 0; - /** - * @return The textures real width - */ - [[nodiscard]] virtual const uint32_t getRealWidth () const = 0; - /** - * @return The textures real height - */ - [[nodiscard]] virtual const uint32_t getRealHeight () const = 0; - /** - * @return The texture's memory format - */ - [[nodiscard]] virtual const TextureFormat getFormat () const = 0; - /** - * @return The texture's settings - */ - [[nodiscard]] virtual const TextureFlags getFlags () const = 0; - /** - * @return The list of frames this texture has - */ - [[nodiscard]] virtual const std::vector& getFrames () const = 0; - /** - * @return The texture's resolution vector - */ - [[nodiscard]] virtual const glm::vec4* getResolution () const = 0; - /** - * @return If the texture is animated or not - */ - [[nodiscard]] virtual const bool isAnimated () const = 0; + /** The image index of this frame */ + uint32_t frameNumber; + /** The amount of time this frame spends being displayed */ + float frametime; + /** The x position of the frame in the texture */ + float x; + /** The y position of the frame in the texture */ + float y; + /** The width of the frame in the texture */ + float width1; + float width2; + float height2; + /** The height of the frame in the texture */ + float height1; }; -} \ No newline at end of file + + /** + * Data formats for textures in memory + */ + enum TextureFormat : uint32_t { + UNKNOWN = 0xFFFFFFFF, + ARGB8888 = 0, + RGB888 = 1, + RGB565 = 2, + DXT5 = 4, + DXT3 = 6, + DXT1 = 7, + RG88 = 8, + R8 = 9, + RG1616f = 10, + R16f = 11, + BC7 = 12, + RGBa1010102 = 13, + RGBA16161616f = 14, + RGB161616f = 15, + }; + + /** + * Different settings of the textures + */ + enum TextureFlags : uint32_t { + NoFlags = 0, + NoInterpolation = 1, + ClampUVs = 2, + IsGif = 4, + ClampUVsBorder = 8, + }; + + /** + * @param imageIndex For animated textures, the frame to get the ID of + * @return The OpenGL texture to use when rendering + */ + [[nodiscard]] virtual const GLuint getTextureID (uint32_t imageIndex = 0) const = 0; + /** + * @param imageIndex For animated textures, the frame to get the ID of + * @return The texture's width + */ + [[nodiscard]] virtual const uint32_t getTextureWidth (uint32_t imageIndex = 0) const = 0; + /** + * @param imageIndex For animated textures, the frame to get the ID of + * @return The texture's height + */ + [[nodiscard]] virtual const uint32_t getTextureHeight (uint32_t imageIndex = 0) const = 0; + /** + * @return The textures real width + */ + [[nodiscard]] virtual const uint32_t getRealWidth () const = 0; + /** + * @return The textures real height + */ + [[nodiscard]] virtual const uint32_t getRealHeight () const = 0; + /** + * @return The texture's memory format + */ + [[nodiscard]] virtual const TextureFormat getFormat () const = 0; + /** + * @return The texture's settings + */ + [[nodiscard]] virtual const TextureFlags getFlags () const = 0; + /** + * @return The list of frames this texture has + */ + [[nodiscard]] virtual const std::vector& getFrames () const = 0; + /** + * @return The texture's resolution vector + */ + [[nodiscard]] virtual const glm::vec4* getResolution () const = 0; + /** + * @return If the texture is animated or not + */ + [[nodiscard]] virtual const bool isAnimated () const = 0; +}; +} // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/CAudioContext.cpp b/src/WallpaperEngine/Audio/CAudioContext.cpp index 188ab57..9af8103 100644 --- a/src/WallpaperEngine/Audio/CAudioContext.cpp +++ b/src/WallpaperEngine/Audio/CAudioContext.cpp @@ -1,40 +1,30 @@ #include "CAudioContext.h" #include "WallpaperEngine/Audio/Drivers/CAudioDriver.h" -namespace WallpaperEngine::Audio -{ - CAudioContext::CAudioContext (Drivers::CAudioDriver& driver) : - m_driver (driver) - { - } +namespace WallpaperEngine::Audio { +CAudioContext::CAudioContext (Drivers::CAudioDriver& driver) : m_driver (driver) {} - void CAudioContext::addStream (CAudioStream* stream) - { - this->m_driver.addStream (stream); - } +void CAudioContext::addStream (CAudioStream* stream) { + this->m_driver.addStream (stream); +} - AVSampleFormat CAudioContext::getFormat () const - { - return this->m_driver.getFormat (); - } +AVSampleFormat CAudioContext::getFormat () const { + return this->m_driver.getFormat (); +} - int CAudioContext::getSampleRate () const - { - return this->m_driver.getSampleRate (); - } +int CAudioContext::getSampleRate () const { + return this->m_driver.getSampleRate (); +} - int CAudioContext::getChannels () const - { - return this->m_driver.getChannels (); - } +int CAudioContext::getChannels () const { + return this->m_driver.getChannels (); +} - Application::CApplicationContext& CAudioContext::getApplicationContext () - { - return this->m_driver.getApplicationContext (); - } +Application::CApplicationContext& CAudioContext::getApplicationContext () { + return this->m_driver.getApplicationContext (); +} - Drivers::Recorders::CPlaybackRecorder& CAudioContext::getRecorder () - { - return this->m_driver.getRecorder (); - } -} \ No newline at end of file +Drivers::Recorders::CPlaybackRecorder& CAudioContext::getRecorder () { + return this->m_driver.getRecorder (); +} +} // namespace WallpaperEngine::Audio \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/CAudioContext.h b/src/WallpaperEngine/Audio/CAudioContext.h index 16f8f92..26c5eb8 100644 --- a/src/WallpaperEngine/Audio/CAudioContext.h +++ b/src/WallpaperEngine/Audio/CAudioContext.h @@ -3,68 +3,62 @@ #include #include -#include "WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h" #include "WallpaperEngine/Application/CApplicationContext.h" +#include "WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h" -namespace WallpaperEngine -{ - namespace Application - { - class CApplicationContext; - } +namespace WallpaperEngine { +namespace Application { +class CApplicationContext; +} - namespace Audio - { - namespace Drivers - { - class CAudioDriver; +namespace Audio { +namespace Drivers { +class CAudioDriver; - namespace Recorders - { - class CPulseAudioPlaybackRecorder; - } - } +namespace Recorders { +class CPulseAudioPlaybackRecorder; +} +} // namespace Drivers - class CAudioStream; +class CAudioStream; - class CAudioContext - { - public: - explicit CAudioContext (Drivers::CAudioDriver& driver); +class CAudioContext { + public: + explicit CAudioContext (Drivers::CAudioDriver& driver); - /** - * Registers the given stream in the driver for playing - * - * @param stream - */ - void addStream (CAudioStream* stream); + /** + * Registers the given stream in the driver for playing + * + * @param stream + */ + void addStream (CAudioStream* stream); - /** - * TODO: MAYBE THIS SHOULD BE OUR OWN DEFINITIONS INSTEAD OF LIBRARY SPECIFIC ONES? - * - * @return The audio format the driver supports - */ - [[nodiscard]] AVSampleFormat getFormat () const; - /** - * @return The sample rate the driver supports - */ - [[nodiscard]] int getSampleRate () const; - /** - * @return The channels the driver supports - */ - [[nodiscard]] int getChannels () const; - /** - * @return The application context under which the audio driver is initialized - */ - Application::CApplicationContext& getApplicationContext (); - /** - * @return The audio recorder to use to capture stereo mix data - */ - [[nodiscard]] Drivers::Recorders::CPlaybackRecorder& getRecorder (); + /** + * TODO: MAYBE THIS SHOULD BE OUR OWN DEFINITIONS INSTEAD OF LIBRARY SPECIFIC ONES? + * + * @return The audio format the driver supports + */ + [[nodiscard]] AVSampleFormat getFormat () const; + /** + * @return The sample rate the driver supports + */ + [[nodiscard]] int getSampleRate () const; + /** + * @return The channels the driver supports + */ + [[nodiscard]] int getChannels () const; + /** + * @return The application context under which the audio driver is initialized + */ + Application::CApplicationContext& getApplicationContext (); + /** + * @return The audio recorder to use to capture stereo mix data + */ + [[nodiscard]] Drivers::Recorders::CPlaybackRecorder& getRecorder (); - private: - /** The audio driver in use */ - Drivers::CAudioDriver& m_driver; - }; - } -} \ No newline at end of file + private: + /** The audio driver in use */ + Drivers::CAudioDriver& m_driver; +}; +} // namespace Audio +} // namespace WallpaperEngine \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/CAudioStream.cpp b/src/WallpaperEngine/Audio/CAudioStream.cpp index 4e86e96..c4dc725 100644 --- a/src/WallpaperEngine/Audio/CAudioStream.cpp +++ b/src/WallpaperEngine/Audio/CAudioStream.cpp @@ -1,5 +1,5 @@ -#include "common.h" #include "CAudioStream.h" +#include "common.h" #include #include #include @@ -10,25 +10,20 @@ using namespace WallpaperEngine::Audio; -int audio_read_thread (void* arg) -{ +int audio_read_thread (void* arg) { SDL_mutex* waitMutex = SDL_CreateMutex (); - auto* stream = static_cast (arg); + auto* stream = static_cast (arg); AVPacket* packet = av_packet_alloc (); int ret = 0; if (waitMutex == nullptr) sLog.exception ("Cannot create mutex for audio playback waiting"); - while (ret >= 0 && stream->getAudioContext ().getApplicationContext ().state.general.keepRunning) - { + while (ret >= 0 && stream->getAudioContext ().getApplicationContext ().state.general.keepRunning) { // give the cpu some time to play the queued frames if there's enough info there - if ( - stream->getQueueSize () >= MAX_QUEUE_SIZE || - (stream->getQueuePacketCount () > MIN_FRAMES && - (av_q2d (stream->getTimeBase ()) * stream->getQueueDuration () > 1.0)) - ) - { + if (stream->getQueueSize () >= MAX_QUEUE_SIZE || + (stream->getQueuePacketCount () > MIN_FRAMES && + (av_q2d (stream->getTimeBase ()) * stream->getQueueDuration () > 1.0))) { SDL_LockMutex (waitMutex); SDL_CondWaitTimeout (stream->getWaitCondition (), waitMutex, 10); SDL_UnlockMutex (waitMutex); @@ -37,14 +32,13 @@ int audio_read_thread (void* arg) ret = av_read_frame (stream->getFormatContext (), packet); - if (ret == AVERROR_EOF) - { + if (ret == AVERROR_EOF) { // seek to the beginning of the file again avformat_seek_file (stream->getFormatContext (), stream->getAudioStream (), 0, 0, 0, ~AVSEEK_FLAG_FRAME); avcodec_flush_buffers (stream->getContext ()); // ensure the thread is not killed if audio has to be looped - if (stream->isRepeat()) + if (stream->isRepeat ()) ret = 0; continue; @@ -67,36 +61,29 @@ int audio_read_thread (void* arg) return 0; } -static int audio_read_data_callback (void* streamarg, uint8_t* buffer, int buffer_size) -{ - auto stream = static_cast (streamarg); - int left = stream->getLength () - stream->getPosition (); +static int audio_read_data_callback (void* streamarg, uint8_t* buffer, int buffer_size) { + const auto stream = static_cast (streamarg); + const int left = stream->getLength () - stream->getPosition (); buffer_size = FFMIN (buffer_size, left); - memcpy (buffer, (uint8_t*) stream->getBuffer () + stream->getPosition (), buffer_size); + memcpy (buffer, stream->getBuffer () + stream->getPosition (), buffer_size); // update position stream->setPosition (stream->getPosition () + buffer_size); return buffer_size; } -int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) -{ - auto stream = static_cast (streamarg); +int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) { + const auto stream = static_cast (streamarg); if (whence & AVSEEK_SIZE) return stream->getLength (); - switch (whence) - { - case SEEK_CUR: - stream->setPosition (stream->getPosition () + offset); - break; + switch (whence) { + case SEEK_CUR: stream->setPosition (stream->getPosition () + offset); break; - case SEEK_SET: - stream->setPosition (offset); - break; + case SEEK_SET: stream->setPosition (offset); break; } return offset; @@ -104,15 +91,13 @@ int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) CAudioStream::CAudioStream (CAudioContext& context, const std::string& filename) : m_audioContext (context), - m_swrctx (nullptr) -{ + m_swrctx (nullptr) { this->loadCustomContent (filename.c_str ()); } CAudioStream::CAudioStream (CAudioContext& context, const void* buffer, int length) : m_audioContext (context), - m_swrctx (nullptr) -{ + m_swrctx (nullptr) { // setup a custom context first this->m_formatContext = avformat_alloc_context (); @@ -124,15 +109,8 @@ CAudioStream::CAudioStream (CAudioContext& context, const void* buffer, int leng this->m_position = 0; // setup custom io for it - this->m_formatContext->pb = avio_alloc_context ( - static_cast (av_malloc (4096)), - 4096, - 0, - static_cast (this), - &audio_read_data_callback, - nullptr, - &audio_seek_data_callback - ); + this->m_formatContext->pb = avio_alloc_context (static_cast (av_malloc (4096)), 4096, 0, this, + &audio_read_data_callback, nullptr, &audio_seek_data_callback); if (this->m_formatContext->pb == nullptr) sLog.exception ("Cannot create avio context"); @@ -141,17 +119,15 @@ CAudioStream::CAudioStream (CAudioContext& context, const void* buffer, int leng this->loadCustomContent (); } -CAudioStream::CAudioStream(CAudioContext& audioContext, AVCodecContext* context) : +CAudioStream::CAudioStream (CAudioContext& audioContext, AVCodecContext* context) : m_context (context), m_queue (new PacketQueue), m_audioContext (audioContext), - m_swrctx (nullptr) -{ + m_swrctx (nullptr) { this->initialize (); } -CAudioStream::~CAudioStream() -{ +CAudioStream::~CAudioStream () { if (this->m_swrctx != nullptr && swr_is_initialized (this->m_swrctx) == true) swr_close (this->m_swrctx); if (this->m_swrctx != nullptr) @@ -160,19 +136,14 @@ CAudioStream::~CAudioStream() // TODO: FREE EVERYTHING ELSE THAT THIS CLASS HOLDS! } -void CAudioStream::loadCustomContent (const char* filename) -{ - const AVCodec* aCodec; - AVCodecContext* avCodecContext; - +void CAudioStream::loadCustomContent (const char* filename) { if (avformat_open_input (&this->m_formatContext, filename, nullptr, nullptr) != 0) sLog.exception ("Cannot open audio file: ", filename); if (avformat_find_stream_info (this->m_formatContext, nullptr) < 0) sLog.exception ("Cannot determine file format: ", filename); // find the audio stream - for (int i = 0; i< this->m_formatContext->nb_streams; i ++) - { + for (int i = 0; i < this->m_formatContext->nb_streams; i++) { if (this->m_formatContext->streams [i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && this->m_audioStream < 0) this->m_audioStream = i; } @@ -181,15 +152,17 @@ void CAudioStream::loadCustomContent (const char* filename) sLog.exception ("Cannot find an audio stream in file ", filename); // get the decoder for it and alloc the required context - aCodec = avcodec_find_decoder (this->m_formatContext->streams [this->m_audioStream]->codecpar->codec_id); + const AVCodec* aCodec = + avcodec_find_decoder (this->m_formatContext->streams [this->m_audioStream]->codecpar->codec_id); if (aCodec == nullptr) sLog.exception ("Cannot initialize audio decoder for file: ", filename); // alocate context - avCodecContext = avcodec_alloc_context3 (aCodec); + AVCodecContext* avCodecContext = avcodec_alloc_context3 (aCodec); - if (avcodec_parameters_to_context (avCodecContext, this->m_formatContext->streams [this->m_audioStream]->codecpar) != 0) + if (avcodec_parameters_to_context (avCodecContext, + this->m_formatContext->streams [this->m_audioStream]->codecpar) != 0) sLog.exception ("Cannot initialize audio decoder parameters"); // finally open @@ -205,8 +178,7 @@ void CAudioStream::loadCustomContent (const char* filename) SDL_CreateThread (audio_read_thread, filename, this); } -void CAudioStream::initialize () -{ +void CAudioStream::initialize () { #if FF_API_FIFO_OLD_API // allocate the FIFO buffer this->m_queue->packetList = av_fifo_alloc2 (1, sizeof (MyAVPacketList), AV_FIFO_FLAG_AUTO_GROW); @@ -217,8 +189,7 @@ void CAudioStream::initialize () int64_t out_channel_layout; // set output audio channels based on the input audio channels - switch (this->m_audioContext.getChannels ()) - { + switch (this->m_audioContext.getChannels ()) { case 1: out_channel_layout = AV_CH_LAYOUT_MONO; break; case 2: out_channel_layout = AV_CH_LAYOUT_STEREO; break; default: out_channel_layout = AV_CH_LAYOUT_SURROUND; break; @@ -227,37 +198,21 @@ void CAudioStream::initialize () #if FF_API_OLD_CHANNEL_LAYOUT av_channel_layout_from_mask (&this->m_out_channel_layout, out_channel_layout); - swr_alloc_set_opts2 ( - &this->m_swrctx, - &this->m_out_channel_layout, - this->m_audioContext.getFormat (), - this->m_audioContext.getSampleRate (), - &this->m_context->ch_layout, - this->m_context->sample_fmt, - this->m_context->sample_rate, - 0, - nullptr - ); + swr_alloc_set_opts2 (&this->m_swrctx, &this->m_out_channel_layout, this->m_audioContext.getFormat (), + this->m_audioContext.getSampleRate (), &this->m_context->ch_layout, + this->m_context->sample_fmt, this->m_context->sample_rate, 0, nullptr); #else // initialize swrctx - this->m_swrctx = swr_alloc_set_opts ( - nullptr, - out_channel_layout, - this->m_audioContext.getFormat (), - this->m_audioContext.getSampleRate (), - this->getContext ()->channel_layout, - this->getContext ()->sample_fmt, - this->getContext ()->sample_rate, - 0, - nullptr - ); + this->m_swrctx = swr_alloc_set_opts (nullptr, out_channel_layout, this->m_audioContext.getFormat (), + this->m_audioContext.getSampleRate (), this->getContext ()->channel_layout, + this->getContext ()->sample_fmt, this->getContext ()->sample_rate, 0, nullptr); #endif if (this->m_swrctx == nullptr) sLog.exception ("Cannot initialize swrctx for audio resampling"); // initialize the context if (swr_init (this->m_swrctx) < 0) - sLog.exception("Failed to initialize the resampling context."); + sLog.exception ("Failed to initialize the resampling context."); // setup the queue information this->m_queue->mutex = SDL_CreateMutex (); @@ -267,13 +222,11 @@ void CAudioStream::initialize () this->m_initialized = true; } -void CAudioStream::queuePacket(AVPacket *pkt) -{ +void CAudioStream::queuePacket (AVPacket* pkt) { // clone the packet AVPacket* clone = av_packet_alloc (); - if (clone == nullptr) - { + if (clone == nullptr) { av_packet_unref (clone); return; } @@ -281,16 +234,15 @@ void CAudioStream::queuePacket(AVPacket *pkt) av_packet_move_ref (clone, pkt); SDL_LockMutex (this->m_queue->mutex); - bool gotQueued = this->doQueue (clone); + const bool gotQueued = this->doQueue (clone); SDL_UnlockMutex (this->m_queue->mutex); if (!gotQueued) av_packet_free (&pkt); } -bool CAudioStream::doQueue (AVPacket* pkt) -{ - MyAVPacketList entry { pkt }; +bool CAudioStream::doQueue (AVPacket* pkt) { + MyAVPacketList entry {pkt}; #if FF_API_FIFO_OLD_API // write the entry if possible @@ -304,7 +256,7 @@ bool CAudioStream::doQueue (AVPacket* pkt) av_fifo_generic_write (this->m_queue->packetList, &entry, sizeof (entry), nullptr); #endif - this->m_queue->nb_packets ++; + this->m_queue->nb_packets++; this->m_queue->size += entry.packet->size + sizeof (entry); this->m_queue->duration += entry.packet->duration; @@ -313,14 +265,12 @@ bool CAudioStream::doQueue (AVPacket* pkt) return true; } -void CAudioStream::dequeuePacket (AVPacket* output) -{ +void CAudioStream::dequeuePacket (AVPacket* output) { MyAVPacketList entry; SDL_LockMutex (this->m_queue->mutex); - while (this->m_audioContext.getApplicationContext ().state.general.keepRunning) - { + while (this->m_audioContext.getApplicationContext ().state.general.keepRunning) { #if FF_API_FIFO_OLD_API int ret = av_fifo_read (this->m_queue->packetList, &entry, 1); @@ -332,9 +282,8 @@ void CAudioStream::dequeuePacket (AVPacket* output) #endif // enough data available, read it - if (ret >= 0) - { - this->m_queue->nb_packets --; + if (ret >= 0) { + this->m_queue->nb_packets--; this->m_queue->size -= entry.packet->size + sizeof (entry); this->m_queue->duration -= entry.packet->duration; @@ -351,93 +300,75 @@ void CAudioStream::dequeuePacket (AVPacket* output) SDL_UnlockMutex (this->m_queue->mutex); } -AVCodecContext* CAudioStream::getContext () -{ +AVCodecContext* CAudioStream::getContext () { return this->m_context; } -AVFormatContext* CAudioStream::getFormatContext () -{ +AVFormatContext* CAudioStream::getFormatContext () { return this->m_formatContext; } -int CAudioStream::getAudioStream () -{ +int CAudioStream::getAudioStream () { return this->m_audioStream; } -bool CAudioStream::isInitialized () -{ +bool CAudioStream::isInitialized () { return this->m_initialized; } -void CAudioStream::setRepeat (bool newRepeat) -{ +void CAudioStream::setRepeat (bool newRepeat) { this->m_repeat = newRepeat; } -bool CAudioStream::isRepeat () -{ +bool CAudioStream::isRepeat () { return this->m_repeat; } -const void* CAudioStream::getBuffer () -{ +const void* CAudioStream::getBuffer () { return this->m_buffer; } -int CAudioStream::getLength () -{ +int CAudioStream::getLength () { return this->m_length; } -int CAudioStream::getPosition () -{ +int CAudioStream::getPosition () { return this->m_position; } -void CAudioStream::setPosition (int current) -{ +void CAudioStream::setPosition (int current) { this->m_position = current; } -SDL_cond* CAudioStream::getWaitCondition () -{ +SDL_cond* CAudioStream::getWaitCondition () { return this->m_queue->wait; } -int CAudioStream::getQueueSize () -{ +int CAudioStream::getQueueSize () { return this->m_queue->size; } -int CAudioStream::getQueuePacketCount () -{ +int CAudioStream::getQueuePacketCount () { return this->m_queue->nb_packets; } -AVRational CAudioStream::getTimeBase () -{ +AVRational CAudioStream::getTimeBase () { return this->m_formatContext->streams [this->m_audioStream]->time_base; } -int64_t CAudioStream::getQueueDuration () -{ +int64_t CAudioStream::getQueueDuration () { return this->m_queue->duration; } -bool CAudioStream::isQueueEmpty () -{ +bool CAudioStream::isQueueEmpty () { return this->m_queue->nb_packets == 0; } -SDL_mutex* CAudioStream::getMutex () -{ +SDL_mutex* CAudioStream::getMutex () { return this->m_queue->mutex; } -void CAudioStream::stop () -{ +void CAudioStream::stop () { if (!this->isInitialized ()) return; @@ -445,36 +376,27 @@ void CAudioStream::stop () this->m_initialized = false; } -int CAudioStream::resampleAudio (AVFrame * decoded_audio_frame, uint8_t * out_buf) -{ +int CAudioStream::resampleAudio (const AVFrame* decoded_audio_frame, uint8_t* out_buf) { int out_linesize = 0; int ret; int out_nb_channels; - int in_nb_samples; int out_nb_samples; - int max_out_nb_samples; uint8_t** resampled_data = nullptr; int resampled_data_size; // retrieve number of audio samples (per channel) - in_nb_samples = decoded_audio_frame->nb_samples; - if (in_nb_samples <= 0) - { - sLog.error("in_nb_samples error."); + const int in_nb_samples = decoded_audio_frame->nb_samples; + if (in_nb_samples <= 0) { + sLog.error ("in_nb_samples error."); return -1; } - max_out_nb_samples = out_nb_samples = av_rescale_rnd( - in_nb_samples, - this->m_audioContext.getSampleRate (), - this->getContext ()->sample_rate, - AV_ROUND_UP - ); + int max_out_nb_samples = out_nb_samples = av_rescale_rnd (in_nb_samples, this->m_audioContext.getSampleRate (), + this->getContext ()->sample_rate, AV_ROUND_UP); // check rescaling was successful - if (max_out_nb_samples <= 0) - { - sLog.error("av_rescale_rnd error."); + if (max_out_nb_samples <= 0) { + sLog.error ("av_rescale_rnd error."); return -1; } @@ -485,64 +407,44 @@ int CAudioStream::resampleAudio (AVFrame * decoded_audio_frame, uint8_t * out_bu int64_t out_channel_layout; // set output audio channels based on the input audio channels - switch (this->m_audioContext.getChannels ()) - { + switch (this->m_audioContext.getChannels ()) { case 1: out_channel_layout = AV_CH_LAYOUT_MONO; break; case 2: out_channel_layout = AV_CH_LAYOUT_STEREO; break; default: out_channel_layout = AV_CH_LAYOUT_SURROUND; break; } - out_nb_channels = av_get_channel_layout_nb_channels(out_channel_layout); + out_nb_channels = av_get_channel_layout_nb_channels (out_channel_layout); #endif - ret = av_samples_alloc_array_and_samples( - &resampled_data, - &out_linesize, - out_nb_channels, - out_nb_samples, - this->m_audioContext.getFormat (), - 0 - ); + ret = av_samples_alloc_array_and_samples (&resampled_data, &out_linesize, out_nb_channels, out_nb_samples, + this->m_audioContext.getFormat (), 0); - if (ret < 0) - { - sLog.error("av_samples_alloc_array_and_samples() error: Could not allocate destination samples."); + if (ret < 0) { + sLog.error ("av_samples_alloc_array_and_samples() error: Could not allocate destination samples."); return -1; } // retrieve output samples number taking into account the progressive delay - out_nb_samples = av_rescale_rnd( - swr_get_delay(this->m_swrctx, this->getContext ()->sample_rate) + in_nb_samples, - this->m_audioContext.getSampleRate (), - this->getContext ()->sample_rate, - AV_ROUND_UP - ); + out_nb_samples = + av_rescale_rnd (swr_get_delay (this->m_swrctx, this->getContext ()->sample_rate) + in_nb_samples, + this->m_audioContext.getSampleRate (), this->getContext ()->sample_rate, AV_ROUND_UP); // check output samples number was correctly retrieved - if (out_nb_samples <= 0) - { - sLog.error("av_rescale_rnd error"); + if (out_nb_samples <= 0) { + sLog.error ("av_rescale_rnd error"); return -1; } - if (out_nb_samples > max_out_nb_samples) - { + if (out_nb_samples > max_out_nb_samples) { // free memory block and set pointer to NULL - av_free(resampled_data[0]); + av_free (resampled_data [0]); // Allocate a samples buffer for out_nb_samples samples - ret = av_samples_alloc( - resampled_data, - &out_linesize, - out_nb_channels, - out_nb_samples, - this->m_audioContext.getFormat (), - 1 - ); + ret = av_samples_alloc (resampled_data, &out_linesize, out_nb_channels, out_nb_samples, + this->m_audioContext.getFormat (), 1); // check samples buffer correctly allocated - if (ret < 0) - { - sLog.error("av_samples_alloc failed."); + if (ret < 0) { + sLog.error ("av_samples_alloc failed."); return -1; } @@ -550,69 +452,54 @@ int CAudioStream::resampleAudio (AVFrame * decoded_audio_frame, uint8_t * out_bu } // do the actual audio data resampling - ret = swr_convert( - this->m_swrctx, - resampled_data, - max_out_nb_samples, - (const uint8_t **) decoded_audio_frame->data, - decoded_audio_frame->nb_samples - ); + ret = swr_convert (this->m_swrctx, resampled_data, max_out_nb_samples, + const_cast (decoded_audio_frame->data), decoded_audio_frame->nb_samples); // check audio conversion was successful - if (ret < 0) - { - sLog.error("swr_convert_error."); + if (ret < 0) { + sLog.error ("swr_convert_error."); return -1; } // Get the required buffer size for the given audio parameters - resampled_data_size = av_samples_get_buffer_size( - &out_linesize, - out_nb_channels, - ret, - this->m_audioContext.getFormat (), - 1 - ); + resampled_data_size = + av_samples_get_buffer_size (&out_linesize, out_nb_channels, ret, this->m_audioContext.getFormat (), 1); // check audio buffer size - if (resampled_data_size < 0) - { + if (resampled_data_size < 0) { sLog.error ("av_samples_get_buffer_size error."); return -1; } // copy the resampled data to the output buffer - memcpy(out_buf, resampled_data[0], resampled_data_size); + memcpy (out_buf, resampled_data [0], resampled_data_size); /* * Memory Cleanup. */ - if (resampled_data) - { + if (resampled_data) { // free memory block and set pointer to NULL - av_freep(&resampled_data[0]); + av_freep (&resampled_data [0]); } - av_freep(&resampled_data); - resampled_data = NULL; + av_freep (&resampled_data); + resampled_data = nullptr; return resampled_data_size; } -int CAudioStream::decodeFrame (uint8_t* audioBuffer, int bufferSize) -{ - AVPacket *pkt = av_packet_alloc (); - static uint8_t *audio_pkt_data = NULL; +int CAudioStream::decodeFrame (uint8_t* audioBuffer, int bufferSize) { + AVPacket* pkt = av_packet_alloc (); + static uint8_t* audio_pkt_data = nullptr; static int audio_pkt_size = 0; int len1, data_size; // allocate a new frame, used to decode audio packets - static AVFrame * avFrame = NULL; - avFrame = av_frame_alloc(); - if (!avFrame) - { - sLog.error("Could not allocate AVFrame.\n"); + static AVFrame* avFrame = nullptr; + avFrame = av_frame_alloc (); + if (!avFrame) { + sLog.error ("Could not allocate AVFrame.\n"); return -1; } @@ -620,21 +507,20 @@ int CAudioStream::decodeFrame (uint8_t* audioBuffer, int bufferSize) while (this->m_audioContext.getApplicationContext ().state.general.keepRunning) { while (audio_pkt_size > 0) { int got_frame = 0; - int ret = avcodec_receive_frame(this->getContext (), avFrame); + int ret = avcodec_receive_frame (this->getContext (), avFrame); if (ret == 0) got_frame = 1; - if (ret == AVERROR(EAGAIN)) + if (ret == AVERROR (EAGAIN)) ret = 0; if (ret == 0) - ret = avcodec_send_packet(this->getContext (), pkt); + ret = avcodec_send_packet (this->getContext (), pkt); if (ret < 0 && ret != AVERROR (EAGAIN)) return -1; len1 = pkt->size; - if (len1 < 0) - { + if (len1 < 0) { // if error, skip frame audio_pkt_size = 0; break; @@ -647,7 +533,7 @@ int CAudioStream::decodeFrame (uint8_t* audioBuffer, int bufferSize) if (got_frame) { // audio resampling data_size = this->resampleAudio (avFrame, audioBuffer); - assert(data_size <= bufferSize); + assert (data_size <= bufferSize); } if (data_size <= 0) { // no data found, keep waiting @@ -657,7 +543,7 @@ int CAudioStream::decodeFrame (uint8_t* audioBuffer, int bufferSize) return data_size; } if (pkt->data) - av_packet_unref(pkt); + av_packet_unref (pkt); this->dequeuePacket (pkt); @@ -668,7 +554,6 @@ int CAudioStream::decodeFrame (uint8_t* audioBuffer, int bufferSize) return 0; } -CAudioContext& CAudioStream::getAudioContext () const -{ +CAudioContext& CAudioStream::getAudioContext () const { return this->m_audioContext; } \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/CAudioStream.h b/src/WallpaperEngine/Audio/CAudioStream.h index ca379c1..25d732b 100644 --- a/src/WallpaperEngine/Audio/CAudioStream.h +++ b/src/WallpaperEngine/Audio/CAudioStream.h @@ -2,14 +2,13 @@ #include -extern "C" -{ -#include +extern "C" { #include #include -#include -#include +#include #include +#include +#include } #include @@ -17,196 +16,192 @@ extern "C" #include "WallpaperEngine/Audio/CAudioContext.h" -namespace WallpaperEngine::Audio -{ - class CAudioContext; +namespace WallpaperEngine::Audio { +class CAudioContext; + +/** + * Represents a playable audio stream for the audio driver + */ +class CAudioStream { + public: + CAudioStream (CAudioContext& context, const std::string& filename); + CAudioStream (CAudioContext& context, const void* buffer, int length); + CAudioStream (CAudioContext& audioContext, AVCodecContext* context); + ~CAudioStream (); + + void queuePacket (AVPacket* pkt); /** - * Represents a playable audio stream for the audio driver + * Gets the next packet in the queue + * + * WARNING: BLOCKS UNTIL SOME DATA IS READ FROM IT + * + * @return */ - class CAudioStream - { - public: - CAudioStream (CAudioContext& context, const std::string& filename); - CAudioStream (CAudioContext& context, const void* buffer, int length); - CAudioStream (CAudioContext& audioContext, AVCodecContext* context); - ~CAudioStream (); + void dequeuePacket (AVPacket* output); - void queuePacket (AVPacket* pkt); + /** + * @return The audio context in use for this audio stream + */ + [[nodiscard]] CAudioContext& getAudioContext () const; - /** - * Gets the next packet in the queue - * - * WARNING: BLOCKS UNTIL SOME DATA IS READ FROM IT - * - * @return - */ - void dequeuePacket (AVPacket* output); + /** + * @return to the codec context, which provides information on the audio stream's format + */ + AVCodecContext* getContext (); + /** + * @returns the format context, which controls how data is read off the audio stream + */ + AVFormatContext* getFormatContext (); + /** + * @return The audio stream index of the given file + */ + int getAudioStream (); + /** + * @return If the audio stream can be played or not + */ + bool isInitialized (); + /** + * @param newRepeat true = repeat, false = no repeat + */ + void setRepeat (bool newRepeat = true); + /** + * @return If the stream is to be repeated at the end or not + */ + bool isRepeat (); + /** + * Stops decoding and playbak of the stream + */ + void stop (); + /** + * @return The file data buffer + */ + const void* getBuffer (); + /** + * @return The length of the file data buffer + */ + int getLength (); + /** + * @return The read position of the data buffer + */ + int getPosition (); + /** + * Updates the read position of the data buffer + * + * @param current + */ + void setPosition (int current); + /** + * @return The SDL_cond used to signal waiting for data + */ + SDL_cond* getWaitCondition (); + /** + * @return The data queue size + */ + int getQueueSize (); + /** + * @return The amount of packets ready to be converted and played + */ + int getQueuePacketCount (); + /** + * @return The duration (in seconds) of the queued data to be played + */ + int64_t getQueueDuration (); + /** + * @return Time unit used for packet playback + */ + AVRational getTimeBase (); + /** + * @return If the data queue is empty or not + */ + bool isQueueEmpty (); + /** + * @return The SDL_mutex used for thread synchronization + */ + SDL_mutex* getMutex (); - /** - * @return The audio context in use for this audio stream - */ - [[nodiscard]] CAudioContext& getAudioContext () const; + /** + * Reads a frame from the audio stream, resamples it to the driver's settings + * and returns the data ready to be played + * + * @param audioBuffer + * @param bufferSize + * + * @return The amount of bytes available or < 0 for error + */ + int decodeFrame (uint8_t* audioBuffer, int bufferSize); - /** - * @return to the codec context, which provides information on the audio stream's format - */ - AVCodecContext* getContext (); - /** - * @returns the format context, which controls how data is read off the audio stream - */ - AVFormatContext* getFormatContext (); - /** - * @return The audio stream index of the given file - */ - int getAudioStream (); - /** - * @return If the audio stream can be played or not - */ - bool isInitialized (); - /** - * @param newRepeat true = repeat, false = no repeat - */ - void setRepeat (bool newRepeat = true); - /** - * @return If the stream is to be repeated at the end or not - */ - bool isRepeat (); - /** - * Stops decoding and playbak of the stream - */ - void stop (); - /** - * @return The file data buffer - */ - const void* getBuffer (); - /** - * @return The length of the file data buffer - */ - int getLength (); - /** - * @return The read position of the data buffer - */ - int getPosition (); - /** - * Updates the read position of the data buffer - * - * @param current - */ - void setPosition (int current); - /** - * @return The SDL_cond used to signal waiting for data - */ - SDL_cond* getWaitCondition (); - /** - * @return The data queue size - */ - int getQueueSize (); - /** - * @return The amount of packets ready to be converted and played - */ - int getQueuePacketCount (); - /** - * @return The duration (in seconds) of the queued data to be played - */ - int64_t getQueueDuration (); - /** - * @return Time unit used for packet playback - */ - AVRational getTimeBase (); - /** - * @return If the data queue is empty or not - */ - bool isQueueEmpty (); - /** - * @return The SDL_mutex used for thread synchronization - */ - SDL_mutex* getMutex (); - - /** - * Reads a frame from the audio stream, resamples it to the driver's settings - * and returns the data ready to be played - * - * @param audioBuffer - * @param bufferSize - * - * @return The amount of bytes available or < 0 for error - */ - int decodeFrame (uint8_t* audioBuffer, int bufferSize); - - private: - /** - * Initializes ffmpeg to read the given file - * - * @param filename - */ - void loadCustomContent (const char* filename = nullptr); - /** - * Converts the audio frame from the original format to one supported by the audio driver - * - * @param decoded_audio_frame - * @param out_buf - * @return - */ - int resampleAudio (AVFrame* decoded_audio_frame, uint8_t* out_buf); - /** - * Queues a packet into the play queue - * - * @param pkt - * @return - */ - bool doQueue (AVPacket* pkt); - /** - * Initializes queues and ffmpeg resampling - */ - void initialize (); + private: + /** + * Initializes ffmpeg to read the given file + * + * @param filename + */ + void loadCustomContent (const char* filename = nullptr); + /** + * Converts the audio frame from the original format to one supported by the audio driver + * + * @param decoded_audio_frame + * @param out_buf + * @return + */ + int resampleAudio (const AVFrame* decoded_audio_frame, uint8_t* out_buf); + /** + * Queues a packet into the play queue + * + * @param pkt + * @return + */ + bool doQueue (AVPacket* pkt); + /** + * Initializes queues and ffmpeg resampling + */ + void initialize (); #if FF_API_OLD_CHANNEL_LAYOUT - /** Chanel layout needed for old FFMPEG versions */ - AVChannelLayout m_out_channel_layout; + /** Chanel layout needed for old FFMPEG versions */ + AVChannelLayout m_out_channel_layout {}; #endif - /** The SwrContext that handles resampling */ - SwrContext* m_swrctx; - /** The audio context this stream will be played under */ - CAudioContext& m_audioContext; - /** If this stream was properly initialized or not */ - bool m_initialized; - /** Repeat enabled? */ - bool m_repeat; - /** The codec context that contains the original audio format information */ - AVCodecContext* m_context = nullptr; - /** The format context that controls how data is read off the file */ - AVFormatContext* m_formatContext = nullptr; - /** The stream index for the audio being played */ - int m_audioStream = -1; - /** File data pointer */ - const void* m_buffer; - /** The length of the file data pointer */ - int m_length; - /** The read position on the file data pointer */ - int m_position = 0; + /** The SwrContext that handles resampling */ + SwrContext* m_swrctx; + /** The audio context this stream will be played under */ + CAudioContext& m_audioContext; + /** If this stream was properly initialized or not */ + bool m_initialized {}; + /** Repeat enabled? */ + bool m_repeat {}; + /** The codec context that contains the original audio format information */ + AVCodecContext* m_context = nullptr; + /** The format context that controls how data is read off the file */ + AVFormatContext* m_formatContext = nullptr; + /** The stream index for the audio being played */ + int m_audioStream = -1; + /** File data pointer */ + const void* m_buffer {}; + /** The length of the file data pointer */ + int m_length {}; + /** The read position on the file data pointer */ + int m_position = 0; - struct MyAVPacketList - { - AVPacket* packet; - }; - - /** - * Packet queue information - */ - struct PacketQueue - { -#if FF_API_FIFO_OLD_API - AVFifo* packetList; -#else - AVFifoBuffer* packetList; -#endif - int nb_packets; - int size; - int64_t duration; - SDL_mutex* mutex; - SDL_cond* wait; - SDL_cond* cond; - }* m_queue; + struct MyAVPacketList { + AVPacket* packet; }; -} + + /** + * Packet queue information + */ + struct PacketQueue { +#if FF_API_FIFO_OLD_API + AVFifo* packetList; +#else + AVFifoBuffer* packetList; +#endif + int nb_packets; + int size; + int64_t duration; + SDL_mutex* mutex; + SDL_cond* wait; + SDL_cond* cond; + }* m_queue {}; +}; +} // namespace WallpaperEngine::Audio diff --git a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp index cfac41e..a68f9c2 100644 --- a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp +++ b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp @@ -1,31 +1,26 @@ #include "CAudioDriver.h" -namespace WallpaperEngine::Audio::Drivers -{ - CAudioDriver::CAudioDriver (Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder) : - m_applicationContext (applicationContext), - m_detector (detector), - m_recorder (recorder) - { - } +namespace WallpaperEngine::Audio::Drivers { +CAudioDriver::CAudioDriver (Application::CApplicationContext& applicationContext, + Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder) : + m_applicationContext (applicationContext), + m_detector (detector), + m_recorder (recorder) {} - void CAudioDriver::update () - { - this->m_recorder.update (); - this->m_detector.update (); - } - - Application::CApplicationContext& CAudioDriver::getApplicationContext () - { - return this->m_applicationContext; - } - Detectors::CAudioPlayingDetector& CAudioDriver::getAudioDetector () - { - return this->m_detector; - } - - Recorders::CPlaybackRecorder& CAudioDriver::getRecorder () - { - return this->m_recorder; - } +void CAudioDriver::update () { + this->m_recorder.update (); + this->m_detector.update (); } + +Application::CApplicationContext& CAudioDriver::getApplicationContext () { + return this->m_applicationContext; +} + +Detectors::CAudioPlayingDetector& CAudioDriver::getAudioDetector () { + return this->m_detector; +} + +Recorders::CPlaybackRecorder& CAudioDriver::getRecorder () { + return this->m_recorder; +} +} // namespace WallpaperEngine::Audio::Drivers diff --git a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h index 0fa029b..28eab39 100644 --- a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h +++ b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h @@ -2,86 +2,81 @@ #include -#include "WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h" -#include "WallpaperEngine/Audio/Drivers/Recorders/CPlaybackRecorder.h" #include "WallpaperEngine/Application/CApplicationContext.h" #include "WallpaperEngine/Audio/CAudioStream.h" +#include "WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h" +#include "WallpaperEngine/Audio/Drivers/Recorders/CPlaybackRecorder.h" -namespace WallpaperEngine -{ - namespace Application - { - class CApplicationContext; - } +namespace WallpaperEngine { +namespace Application { +class CApplicationContext; +} - namespace Audio - { - class CAudioStream; +namespace Audio { +class CAudioStream; - namespace Drivers - { - namespace Detectors - { - class CAudioPlayingDetector; - } +namespace Drivers { +namespace Detectors { +class CAudioPlayingDetector; +} - namespace Recorders - { - class CPulseAudioPlaybackRecorder; - } +namespace Recorders { +class CPulseAudioPlaybackRecorder; +} - /** - * Base class for audio driver implementations - */ - class CAudioDriver - { - public: - explicit CAudioDriver (Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder); +/** + * Base class for audio driver implementations + */ +class CAudioDriver { + public: + explicit CAudioDriver (Application::CApplicationContext& applicationContext, + Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder); - /** - * Registers the given stream in the driver for playing - * - * @param stream - */ - virtual void addStream (CAudioStream* stream) = 0; + virtual ~CAudioDriver () = default; + /** + * Registers the given stream in the driver for playing + * + * @param stream + */ + virtual void addStream (CAudioStream* stream) = 0; - /** - * Updates status of the different audio settings - */ - virtual void update (); + /** + * Updates status of the different audio settings + */ + virtual void update (); - /** - * TODO: MAYBE THIS SHOULD BE OUR OWN DEFINITIONS INSTEAD OF LIBRARY SPECIFIC ONES? - * - * @return The audio format the driver supports - */ - [[nodiscard]] virtual AVSampleFormat getFormat () const = 0; - /** - * @return The sample rate the driver supports - */ - [[nodiscard]] virtual int getSampleRate () const = 0; - /** - * @return The channels the driver supports - */ - [[nodiscard]] virtual int getChannels () const = 0; - /** - * @return The application context under which the audio driver is initialized - */ - Application::CApplicationContext& getApplicationContext (); - /** - * @return The audio playing detector to use to stop playing sound when something else starts playing - */ - [[nodiscard]] Detectors::CAudioPlayingDetector& getAudioDetector (); - /** - * @return The audio recorder to use to capture stereo mix data - */ - [[nodiscard]] Recorders::CPlaybackRecorder& getRecorder (); + /** + * TODO: MAYBE THIS SHOULD BE OUR OWN DEFINITIONS INSTEAD OF LIBRARY SPECIFIC ONES? + * + * @return The audio format the driver supports + */ + [[nodiscard]] virtual AVSampleFormat getFormat () const = 0; + /** + * @return The sample rate the driver supports + */ + [[nodiscard]] virtual int getSampleRate () const = 0; + /** + * @return The channels the driver supports + */ + [[nodiscard]] virtual int getChannels () const = 0; + /** + * @return The application context under which the audio driver is initialized + */ + Application::CApplicationContext& getApplicationContext (); + /** + * @return The audio playing detector to use to stop playing sound when something else starts playing + */ + [[nodiscard]] Detectors::CAudioPlayingDetector& getAudioDetector (); + /** + * @return The audio recorder to use to capture stereo mix data + */ + [[nodiscard]] Recorders::CPlaybackRecorder& getRecorder (); - private: - Application::CApplicationContext& m_applicationContext; - Detectors::CAudioPlayingDetector& m_detector; - Recorders::CPlaybackRecorder& m_recorder; - }; - } - } -} \ No newline at end of file + private: + Application::CApplicationContext& m_applicationContext; + Detectors::CAudioPlayingDetector& m_detector; + Recorders::CPlaybackRecorder& m_recorder; +}; +} // namespace Drivers +} // namespace Audio +} // namespace WallpaperEngine \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp index 8888009..98d2f9f 100644 --- a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp +++ b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp @@ -1,5 +1,5 @@ -#include "common.h" #include "CSDLAudioDriver.h" +#include "common.h" #define SDL_AUDIO_BUFFER_SIZE 4096 #define MAX_AUDIO_FRAME_SIZE 192000 @@ -7,9 +7,8 @@ using namespace WallpaperEngine::Audio; using namespace WallpaperEngine::Audio::Drivers; -void audio_callback (void* userdata, uint8_t* streamData, int length) -{ - auto* driver = reinterpret_cast (userdata); +void audio_callback (void* userdata, uint8_t* streamData, int length) { + auto* driver = static_cast (userdata); memset (streamData, 0, length); @@ -17,11 +16,9 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) if (driver->getAudioDetector ().anythingPlaying ()) return; - for (const auto& buffer : driver->getStreams ()) - { + for (const auto& buffer : driver->getStreams ()) { uint8_t* streamDataPointer = streamData; int streamLength = length; - int len1, audio_size; // sound is not initialized or stopped and is not in loop mode // ignore mixing it in @@ -29,43 +26,35 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) continue; // check if queue is empty and signal the read thread - if (buffer->stream->isQueueEmpty ()) - { + if (buffer->stream->isQueueEmpty ()) { SDL_CondSignal (buffer->stream->getWaitCondition ()); continue; } - while (streamLength > 0 && driver->getApplicationContext ().state.general.keepRunning) - { - if (buffer->audio_buf_index >= buffer->audio_buf_size) - { + while (streamLength > 0 && driver->getApplicationContext ().state.general.keepRunning) { + if (buffer->audio_buf_index >= buffer->audio_buf_size) { // get more data to fill the buffer - audio_size = buffer->stream->decodeFrame (buffer->audio_buf, sizeof (buffer->audio_buf)); + int audio_size = buffer->stream->decodeFrame (buffer->audio_buf, sizeof (buffer->audio_buf)); - if (audio_size < 0) - { + if (audio_size < 0) { // fallback for errors, silence buffer->audio_buf_size = 1024; - memset(buffer->audio_buf, 0, buffer->audio_buf_size); - } - else - { + memset (buffer->audio_buf, 0, buffer->audio_buf_size); + } else { buffer->audio_buf_size = audio_size; } buffer->audio_buf_index = 0; } - len1 = buffer->audio_buf_size - buffer->audio_buf_index; + int len1 = buffer->audio_buf_size - buffer->audio_buf_index; if (len1 > streamLength) len1 = streamLength; // mix the audio - SDL_MixAudioFormat ( - streamDataPointer, &buffer->audio_buf [buffer->audio_buf_index], - driver->getSpec ().format, len1, driver->getApplicationContext ().state.audio.volume - ); + SDL_MixAudioFormat (streamDataPointer, &buffer->audio_buf [buffer->audio_buf_index], + driver->getSpec ().format, len1, driver->getApplicationContext ().state.audio.volume); streamLength -= len1; streamDataPointer += len1; @@ -74,34 +63,29 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) } } -CSDLAudioDriver::CSDLAudioDriver (Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder) : +CSDLAudioDriver::CSDLAudioDriver (Application::CApplicationContext& applicationContext, + Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder) : CAudioDriver (applicationContext, detector, recorder), m_initialized (false), - m_audioSpec () -{ - if (SDL_InitSubSystem (SDL_INIT_AUDIO) < 0) - { + m_audioSpec () { + if (SDL_InitSubSystem (SDL_INIT_AUDIO) < 0) { sLog.error ("Cannot initialize SDL audio system, SDL_GetError: ", SDL_GetError ()); sLog.error ("Continuing without audio support"); return; } - SDL_AudioSpec requestedSpec; + const SDL_AudioSpec requestedSpec = {.freq = 48000, + .format = AUDIO_F32, + .channels = 2, + .samples = SDL_AUDIO_BUFFER_SIZE, + .callback = audio_callback, + .userdata = this}; - memset (&requestedSpec, 0, sizeof (requestedSpec)); + this->m_deviceID = + SDL_OpenAudioDevice (nullptr, false, &requestedSpec, &this->m_audioSpec, SDL_AUDIO_ALLOW_ANY_CHANGE); - requestedSpec.freq = 48000; - requestedSpec.format = AUDIO_F32; - requestedSpec.channels = 2; - requestedSpec.samples = SDL_AUDIO_BUFFER_SIZE; - requestedSpec.callback = audio_callback; - requestedSpec.userdata = this; - - this->m_deviceID = SDL_OpenAudioDevice (nullptr, false, &requestedSpec, &this->m_audioSpec, SDL_AUDIO_ALLOW_ANY_CHANGE); - - if (this->m_deviceID == 0) - { + if (this->m_deviceID == 0) { sLog.error ("SDL_OpenAudioDevice: ", SDL_GetError ()); return; } @@ -111,8 +95,7 @@ CSDLAudioDriver::CSDLAudioDriver (Application::CApplicationContext& applicationC this->m_initialized = true; } -CSDLAudioDriver::~CSDLAudioDriver () -{ +CSDLAudioDriver::~CSDLAudioDriver () { if (!this->m_initialized) return; @@ -120,39 +103,39 @@ CSDLAudioDriver::~CSDLAudioDriver () SDL_QuitSubSystem (SDL_INIT_AUDIO); } -void CSDLAudioDriver::addStream (CAudioStream* stream) -{ - this->m_streams.push_back (new CSDLAudioBuffer { stream }); +void CSDLAudioDriver::addStream (CAudioStream* stream) { + this->m_streams.push_back (new CSDLAudioBuffer {stream}); } -const std::vector & CSDLAudioDriver::getStreams () -{ +const std::vector& CSDLAudioDriver::getStreams () { return this->m_streams; } -AVSampleFormat CSDLAudioDriver::getFormat () const -{ - switch (this->m_audioSpec.format) - { - case AUDIO_U8: case AUDIO_S8: return AV_SAMPLE_FMT_U8; - case AUDIO_U16MSB: case AUDIO_U16LSB: case AUDIO_S16LSB: case AUDIO_S16MSB: return AV_SAMPLE_FMT_S16; - case AUDIO_S32LSB: case AUDIO_S32MSB: return AV_SAMPLE_FMT_S32; - case AUDIO_F32LSB: case AUDIO_F32MSB: return AV_SAMPLE_FMT_FLT; +AVSampleFormat CSDLAudioDriver::getFormat () const { + switch (this->m_audioSpec.format) { + case AUDIO_U8: + case AUDIO_S8: return AV_SAMPLE_FMT_U8; + case AUDIO_U16MSB: + case AUDIO_U16LSB: + case AUDIO_S16LSB: + case AUDIO_S16MSB: return AV_SAMPLE_FMT_S16; + case AUDIO_S32LSB: + case AUDIO_S32MSB: return AV_SAMPLE_FMT_S32; + case AUDIO_F32LSB: + case AUDIO_F32MSB: return AV_SAMPLE_FMT_FLT; } sLog.exception ("Cannot convert from SDL format to ffmpeg format, aborting..."); } -int CSDLAudioDriver::getSampleRate () const -{ +int CSDLAudioDriver::getSampleRate () const { return this->m_audioSpec.freq; } -int CSDLAudioDriver::getChannels () const -{ +int CSDLAudioDriver::getChannels () const { return this->m_audioSpec.channels; } -const SDL_AudioSpec& CSDLAudioDriver::getSpec () const -{ + +const SDL_AudioSpec& CSDLAudioDriver::getSpec () const { return this->m_audioSpec; } \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h index 2979fa0..2c75716 100644 --- a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h +++ b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include "WallpaperEngine/Audio/CAudioStream.h" #include "WallpaperEngine/Audio/Drivers/CAudioDriver.h" @@ -10,54 +10,52 @@ #define MAX_AUDIO_FRAME_SIZE 192000 -namespace WallpaperEngine::Audio::Drivers -{ +namespace WallpaperEngine::Audio::Drivers { +/** + * Audio output buffers for streams being played under SDL + */ +struct CSDLAudioBuffer { + CAudioStream* stream; + uint8_t audio_buf [(MAX_AUDIO_FRAME_SIZE * 3) / 2] = {0}; + unsigned int audio_buf_size = 0; + unsigned int audio_buf_index = 0; +}; + +/** + * SDL's audio driver implementation + */ +class CSDLAudioDriver final : public CAudioDriver { + public: + CSDLAudioDriver (Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, + Recorders::CPlaybackRecorder& recorder); + ~CSDLAudioDriver () override; + + /** @inheritdoc */ + void addStream (CAudioStream* stream) override; /** - * Audio output buffers for streams being played under SDL + * @return All the registered audio streams */ - struct CSDLAudioBuffer - { - CAudioStream* stream; - uint8_t audio_buf[(MAX_AUDIO_FRAME_SIZE * 3) / 2] = {0}; - unsigned int audio_buf_size = 0; - unsigned int audio_buf_index = 0; - }; + const std::vector& getStreams (); + /** @inheritdoc */ + [[nodiscard]] AVSampleFormat getFormat () const override; + /** @inheritdoc */ + [[nodiscard]] int getSampleRate () const override; + /** @inheritdoc */ + [[nodiscard]] int getChannels () const override; /** - * SDL's audio driver implementation + * @return The SDL's audio driver settings */ - class CSDLAudioDriver : public CAudioDriver - { - public: - CSDLAudioDriver (Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder); - ~CSDLAudioDriver (); + [[nodiscard]] const SDL_AudioSpec& getSpec () const; - /** @inheritdoc */ - void addStream (CAudioStream* stream) override; - /** - * @return All the registered audio streams - */ - const std::vector & getStreams (); - - /** @inheritdoc */ - [[nodiscard]] AVSampleFormat getFormat () const override; - /** @inheritdoc */ - [[nodiscard]] int getSampleRate () const override; - /** @inheritdoc */ - [[nodiscard]] int getChannels () const override; - /** - * @return The SDL's audio driver settings - */ - [[nodiscard]] const SDL_AudioSpec& getSpec () const; - - private: - /** The device's ID */ - SDL_AudioDeviceID m_deviceID; - /** If the driver is initialized or not */ - bool m_initialized; - /** The sound output configuration */ - SDL_AudioSpec m_audioSpec; - /** All the playable steams */ - std::vector m_streams; - }; -} \ No newline at end of file + private: + /** The device's ID */ + SDL_AudioDeviceID m_deviceID; + /** If the driver is initialized or not */ + bool m_initialized; + /** The sound output configuration */ + SDL_AudioSpec m_audioSpec; + /** All the playable steams */ + std::vector m_streams; +}; +} // namespace WallpaperEngine::Audio::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp index ba0962a..acf976c 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp @@ -1,33 +1,26 @@ #include "CAudioPlayingDetector.h" -namespace WallpaperEngine::Audio::Drivers::Detectors -{ - CAudioPlayingDetector::CAudioPlayingDetector ( - Application::CApplicationContext& appContext, - const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector) : - m_applicationContext (appContext), - m_fullscreenDetector (fullscreenDetector), - m_isPlaying (false) - { - } +namespace WallpaperEngine::Audio::Drivers::Detectors { +CAudioPlayingDetector::CAudioPlayingDetector ( + Application::CApplicationContext& appContext, + const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector) : + m_applicationContext (appContext), + m_fullscreenDetector (fullscreenDetector), + m_isPlaying (false) {} - bool CAudioPlayingDetector::anythingPlaying () const - { - return this->m_isPlaying; - } +bool CAudioPlayingDetector::anythingPlaying () const { + return this->m_isPlaying; +} - Application::CApplicationContext& CAudioPlayingDetector::getApplicationContext () - { - return this->m_applicationContext; - } +Application::CApplicationContext& CAudioPlayingDetector::getApplicationContext () { + return this->m_applicationContext; +} - const Render::Drivers::Detectors::CFullScreenDetector& CAudioPlayingDetector::getFullscreenDetector () const - { - return this->m_fullscreenDetector; - } +const Render::Drivers::Detectors::CFullScreenDetector& CAudioPlayingDetector::getFullscreenDetector () const { + return this->m_fullscreenDetector; +} - void CAudioPlayingDetector::setIsPlaying (bool newState) - { - this->m_isPlaying = newState; - } -} \ No newline at end of file +void CAudioPlayingDetector::setIsPlaying (bool newState) { + this->m_isPlaying = newState; +} +} // namespace WallpaperEngine::Audio::Drivers::Detectors \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h index cec3341..e99529e 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h @@ -1,60 +1,58 @@ #pragma once -#include "WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h" #include "WallpaperEngine/Application/CApplicationContext.h" +#include "WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h" -namespace WallpaperEngine -{ - namespace Application - { - class CApplicationContext; - } - - namespace Render::Drivers::Detectors - { - class CFullScreenDetector; - } - - namespace Audio::Drivers::Detectors - { - /** - * Base class for any implementation of audio playing detection - */ - class CAudioPlayingDetector - { - public: - CAudioPlayingDetector (Application::CApplicationContext& appContext, const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector); - - /** - * @return If any kind of sound is currently playing on the default audio device - */ - [[nodiscard]] bool anythingPlaying () const; - - /** - * Updates the playing status to the specified value - * - * @param newState - */ - void setIsPlaying (bool newState); - - /** - * Checks if any audio is playing and updates state accordingly - */ - virtual void update () = 0; - /** - * @return The application context using this detector - */ - [[nodiscard]] Application::CApplicationContext& getApplicationContext (); - /** - * @return The fullscreen detector used - */ - [[nodiscard]] const Render::Drivers::Detectors::CFullScreenDetector& getFullscreenDetector () const; - - private: - bool m_isPlaying; - - Application::CApplicationContext& m_applicationContext; - const Render::Drivers::Detectors::CFullScreenDetector& m_fullscreenDetector; - }; - } +namespace WallpaperEngine { +namespace Application { +class CApplicationContext; } + +namespace Render::Drivers::Detectors { +class CFullScreenDetector; +} + +namespace Audio::Drivers::Detectors { +/** + * Base class for any implementation of audio playing detection + */ +class CAudioPlayingDetector { + public: + CAudioPlayingDetector (Application::CApplicationContext& appContext, + const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector); + + virtual ~CAudioPlayingDetector () = default; + + /** + * @return If any kind of sound is currently playing on the default audio device + */ + [[nodiscard]] bool anythingPlaying () const; + + /** + * Updates the playing status to the specified value + * + * @param newState + */ + void setIsPlaying (bool newState); + + /** + * Checks if any audio is playing and updates state accordingly + */ + virtual void update () = 0; + /** + * @return The application context using this detector + */ + [[nodiscard]] Application::CApplicationContext& getApplicationContext (); + /** + * @return The fullscreen detector used + */ + [[nodiscard]] const Render::Drivers::Detectors::CFullScreenDetector& getFullscreenDetector () const; + + private: + bool m_isPlaying; + + Application::CApplicationContext& m_applicationContext; + const Render::Drivers::Detectors::CFullScreenDetector& m_fullscreenDetector; +}; +} // namespace Audio::Drivers::Detectors +} // namespace WallpaperEngine diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp index 3019e01..3720c0d 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp @@ -3,84 +3,76 @@ #include -namespace WallpaperEngine::Audio::Drivers::Detectors -{ - void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info, int eol, void* userdata) - { - auto* detector = static_cast (userdata); +namespace WallpaperEngine::Audio::Drivers::Detectors { +void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info, int eol, void* userdata) { + auto* detector = static_cast (userdata); - if (info == nullptr) - return; + if (info == nullptr) + return; - if (info->proplist == nullptr) - return; + if (info->proplist == nullptr) + return; - // get processid - const char* value = pa_proplist_gets (info->proplist, PA_PROP_APPLICATION_PROCESS_ID); + // get processid + const char* value = pa_proplist_gets (info->proplist, PA_PROP_APPLICATION_PROCESS_ID); - if (value && atoi (value) != getpid () && pa_cvolume_avg (&info->volume) != PA_VOLUME_MUTED) - detector->setIsPlaying (true); + if (value && atoi (value) != getpid () && pa_cvolume_avg (&info->volume) != PA_VOLUME_MUTED) + detector->setIsPlaying (true); +} + +void defaultSinkInfoCallback (pa_context* context, const pa_server_info* info, void* userdata) { + if (info == nullptr) + return; + + pa_operation* op = pa_context_get_sink_input_info_list (context, sinkInputInfoCallback, userdata); + + pa_operation_unref (op); +} + +CPulseAudioPlayingDetector::CPulseAudioPlayingDetector ( + Application::CApplicationContext& appContext, + const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector) : + CAudioPlayingDetector (appContext, fullscreenDetector), + m_mainloop (nullptr), + m_mainloopApi (nullptr), + m_context (nullptr) { + this->m_mainloop = pa_mainloop_new (); + this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop); + this->m_context = pa_context_new (this->m_mainloopApi, "wallpaperengine"); + + pa_context_connect (this->m_context, nullptr, PA_CONTEXT_NOFLAGS, nullptr); + + // lock until pulseaudio allows connection + while (pa_context_get_state (this->m_context) != PA_CONTEXT_READY) + pa_mainloop_iterate (this->m_mainloop, 1, nullptr); +} + +CPulseAudioPlayingDetector::~CPulseAudioPlayingDetector () { + if (this->m_context) { + pa_context_disconnect (this->m_context); + pa_context_unref (this->m_context); } - void defaultSinkInfoCallback (pa_context* context, const pa_server_info* info, void* userdata) - { - if (info == nullptr) - return; + if (this->m_mainloop) + pa_mainloop_free (this->m_mainloop); +} - pa_operation* op = pa_context_get_sink_input_info_list (context, sinkInputInfoCallback, userdata); +void CPulseAudioPlayingDetector::update () { + if (!this->getApplicationContext ().settings.audio.automute) + return this->setIsPlaying (false); + if (this->getFullscreenDetector ().anythingFullscreen ()) + return this->setIsPlaying (true); - pa_operation_unref (op); - } + // reset playing state + this->setIsPlaying (false); - CPulseAudioPlayingDetector::CPulseAudioPlayingDetector ( - Application::CApplicationContext& appContext, - const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector) : - CAudioPlayingDetector (appContext, fullscreenDetector), - m_mainloop (nullptr), - m_mainloopApi (nullptr), - m_context (nullptr) - { - this->m_mainloop = pa_mainloop_new (); - this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop); - this->m_context = pa_context_new (this->m_mainloopApi, "wallpaperengine"); + // start discovery of sinks + pa_operation* op = pa_context_get_server_info (this->m_context, defaultSinkInfoCallback, this); - pa_context_connect (this->m_context, nullptr, PA_CONTEXT_NOFLAGS, nullptr); + // wait until all the operations are done + while (pa_operation_get_state (op) == PA_OPERATION_RUNNING) + pa_mainloop_iterate (this->m_mainloop, 1, nullptr); - // lock until pulseaudio allows connection - while (pa_context_get_state (this->m_context) != PA_CONTEXT_READY) - pa_mainloop_iterate (this->m_mainloop, 1, nullptr); - } - - CPulseAudioPlayingDetector::~CPulseAudioPlayingDetector () - { - if (this->m_context) - { - pa_context_disconnect (this->m_context); - pa_context_unref (this->m_context); - } - - if (this->m_mainloop) - pa_mainloop_free (this->m_mainloop); - } - - - void CPulseAudioPlayingDetector::update () - { - if (!this->getApplicationContext ().settings.audio.automute) - return this->setIsPlaying (false); - if (this->getFullscreenDetector ().anythingFullscreen ()) - return this->setIsPlaying (true); - - // reset playing state - this->setIsPlaying (false); - - // start discovery of sinks - pa_operation* op = pa_context_get_server_info (this->m_context, defaultSinkInfoCallback, (void*) this); - - // wait until all the operations are done - while (pa_operation_get_state (op) == PA_OPERATION_RUNNING) - pa_mainloop_iterate (this->m_mainloop, 1, nullptr); - - pa_operation_unref (op); - } -} \ No newline at end of file + pa_operation_unref (op); +} +} // namespace WallpaperEngine::Audio::Drivers::Detectors \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h index b4628c2..6527df7 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h @@ -1,23 +1,22 @@ #pragma once +#include "CAudioPlayingDetector.h" #include #include -#include "CAudioPlayingDetector.h" #include -namespace WallpaperEngine::Audio::Drivers::Detectors -{ - class CPulseAudioPlayingDetector : public CAudioPlayingDetector - { - public: - explicit CPulseAudioPlayingDetector (Application::CApplicationContext& appContext, const Render::Drivers::Detectors::CFullScreenDetector&); - ~CPulseAudioPlayingDetector (); +namespace WallpaperEngine::Audio::Drivers::Detectors { +class CPulseAudioPlayingDetector final : public CAudioPlayingDetector { + public: + explicit CPulseAudioPlayingDetector (Application::CApplicationContext& appContext, + const Render::Drivers::Detectors::CFullScreenDetector&); + ~CPulseAudioPlayingDetector () override; - void update () override; + void update () override; - private: - pa_mainloop* m_mainloop; - pa_mainloop_api* m_mainloopApi; - pa_context* m_context; - }; -} + private: + pa_mainloop* m_mainloop; + pa_mainloop_api* m_mainloopApi; + pa_context* m_context; +}; +} // namespace WallpaperEngine::Audio::Drivers::Detectors diff --git a/src/WallpaperEngine/Audio/Drivers/Recorders/CPlaybackRecorder.h b/src/WallpaperEngine/Audio/Drivers/Recorders/CPlaybackRecorder.h index 6210c3e..e66c87f 100644 --- a/src/WallpaperEngine/Audio/Drivers/Recorders/CPlaybackRecorder.h +++ b/src/WallpaperEngine/Audio/Drivers/Recorders/CPlaybackRecorder.h @@ -1,14 +1,14 @@ #pragma once -namespace WallpaperEngine::Audio::Drivers::Recorders -{ - class CPlaybackRecorder - { - public: - virtual void update () = 0; +namespace WallpaperEngine::Audio::Drivers::Recorders { +class CPlaybackRecorder { + public: + virtual ~CPlaybackRecorder () = default; - float audio16[16] = {0}; - float audio32[32] = {0}; - float audio64[64] = {0}; - }; -} \ No newline at end of file + virtual void update () = 0; + + float audio16 [16] = {0}; + float audio32 [32] = {0}; + float audio64 [64] = {0}; +}; +} // namespace WallpaperEngine::Audio::Drivers::Recorders \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp index 24b5d05..acfdd4d 100644 --- a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp +++ b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp @@ -1,223 +1,205 @@ -#include -#include -#include #include "CPulseAudioPlaybackRecorder.h" -#include "WallpaperEngine/Logging/CLog.h" #include "External/Android/fft.h" +#include "WallpaperEngine/Logging/CLog.h" +#include +#include +#include -namespace WallpaperEngine::Audio::Drivers::Recorders -{ - float movetowards(float current, float target, float maxDelta) - { - if (abs(target - current) <= maxDelta) - return target; +namespace WallpaperEngine::Audio::Drivers::Recorders { +float movetowards (float current, float target, float maxDelta) { + if (abs (target - current) <= maxDelta) + return target; - return current + glm::sign(target - current) * maxDelta; + return current + glm::sign (target - current) * maxDelta; +} + +void pa_stream_notify_cb (pa_stream* stream, void* /*userdata*/) { + switch (pa_stream_get_state (stream)) { + case PA_STREAM_FAILED: sLog.error ("Cannot open stream for capture. Audio processing is disabled"); break; + case PA_STREAM_READY: sLog.debug ("Capture stream ready"); break; + } +} + +void pa_stream_read_cb (pa_stream* stream, const size_t /*nbytes*/, void* userdata) { + auto* recorder = static_cast (userdata); + + // Careful when to pa_stream_peek() and pa_stream_drop()! + // c.f. https://www.freedesktop.org/software/pulseaudio/doxygen/stream_8h.html#ac2838c449cde56e169224d7fe3d00824 + const void* data = nullptr; + size_t currentSize; + if (pa_stream_peek (stream, &data, ¤tSize) != 0) { + sLog.error ("Failed to peek at stream data..."); + return; } - void pa_stream_notify_cb(pa_stream *stream, void* /*userdata*/) - { - const pa_stream_state state = pa_stream_get_state(stream); - switch (state) { - case PA_STREAM_FAILED: - sLog.error ("Cannot open stream for capture. Audio processing is disabled"); - break; - case PA_STREAM_READY: - sLog.debug ("Capture stream ready"); - break; - } + if (data == nullptr && currentSize == 0) { + // No data in the buffer, ignore. + return; } - void pa_stream_read_cb(pa_stream *stream, const size_t /*nbytes*/, void* userdata) - { - auto* recorder = reinterpret_cast(userdata); - - // Careful when to pa_stream_peek() and pa_stream_drop()! - // c.f. https://www.freedesktop.org/software/pulseaudio/doxygen/stream_8h.html#ac2838c449cde56e169224d7fe3d00824 - uint8_t *data = nullptr; - size_t currentSize; - if (pa_stream_peek(stream, (const void**)&data, ¤tSize) != 0) { - sLog.error ("Failed to peek at stream data..."); + if (data == nullptr && currentSize > 0) { + // Hole in the buffer. We must drop it. + if (pa_stream_drop (stream) != 0) { + sLog.error ("Failed to drop a hole while capturing!"); return; } + } else if (currentSize > 0 && data) { + size_t dataToCopy = std::min (currentSize, WAVE_BUFFER_SIZE - recorder->currentWritePointer); - if (data == nullptr && currentSize == 0) { - // No data in the buffer, ignore. - return; - } else if (data == nullptr && currentSize > 0) { - // Hole in the buffer. We must drop it. - if (pa_stream_drop(stream) != 0) { - sLog.error ("Failed to drop a hole while capturing!"); - return; - } - } else if (currentSize > 0 && data) { - size_t dataToCopy = std::min (currentSize, WAVE_BUFFER_SIZE - recorder->currentWritePointer); + memcpy (&recorder->audio_buffer_tmp [recorder->currentWritePointer], data, dataToCopy * sizeof (uint8_t)); - memcpy (&recorder->audio_buffer_tmp [recorder->currentWritePointer], data, dataToCopy * sizeof (uint8_t)); + recorder->currentWritePointer += dataToCopy; - recorder->currentWritePointer += dataToCopy; - - if (recorder->currentWritePointer == WAVE_BUFFER_SIZE) { - // copy to the final buffer - memcpy (recorder->audio_buffer, recorder->audio_buffer_tmp, WAVE_BUFFER_SIZE * sizeof (uint8_t)); - // reset the write pointer - recorder->currentWritePointer = 0; - recorder->fullframeReady = true; - } - - // any data read left? - if (dataToCopy < currentSize) { - while ((currentSize - dataToCopy) > WAVE_BUFFER_SIZE) - dataToCopy += WAVE_BUFFER_SIZE; // there's more than one full frame available, skip it entirely - - // data pending, keep it in the buffer - memcpy (recorder->audio_buffer_tmp, data + dataToCopy, (currentSize - dataToCopy) * sizeof (uint8_t)); - - recorder->currentWritePointer = currentSize - dataToCopy; - } + if (recorder->currentWritePointer == WAVE_BUFFER_SIZE) { + // copy to the final buffer + memcpy (recorder->audio_buffer, recorder->audio_buffer_tmp, WAVE_BUFFER_SIZE * sizeof (uint8_t)); + // reset the write pointer + recorder->currentWritePointer = 0; + recorder->fullframeReady = true; } - if (pa_stream_drop(stream) != 0) { - sLog.error ("Failed to drop data after peeking"); + // any data read left? + if (dataToCopy < currentSize) { + while ((currentSize - dataToCopy) > WAVE_BUFFER_SIZE) + dataToCopy += WAVE_BUFFER_SIZE; // there's more than one full frame available, skip it entirely + + // data pending, keep it in the buffer + memcpy (recorder->audio_buffer_tmp, data + dataToCopy, (currentSize - dataToCopy) * sizeof (uint8_t)); + + recorder->currentWritePointer = currentSize - dataToCopy; } } - void pa_server_info_cb(pa_context *ctx, const pa_server_info *info, void* userdata) - { - auto* recorder = reinterpret_cast(userdata); + if (pa_stream_drop (stream) != 0) { + sLog.error ("Failed to drop data after peeking"); + } +} - pa_sample_spec spec; - spec.format = PA_SAMPLE_U8; - spec.rate = 44100; - spec.channels = 1; +void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userdata) { + auto* recorder = static_cast (userdata); - if (recorder->getCaptureStream ()) - { - pa_stream_unref (recorder->getCaptureStream ()); - // get rid of the reference just in case - recorder->setCaptureStream (nullptr); + pa_sample_spec spec; + spec.format = PA_SAMPLE_U8; + spec.rate = 44100; + spec.channels = 1; + + if (recorder->getCaptureStream ()) { + pa_stream_unref (recorder->getCaptureStream ()); + // get rid of the reference just in case + recorder->setCaptureStream (nullptr); + } + + pa_stream* captureStream = pa_stream_new (ctx, "output monitor", &spec, nullptr); + + // store the stream first, if the record start fails there'll still be a reference to it + // so it can be free'd later + recorder->setCaptureStream (captureStream), + + pa_stream_set_state_callback (captureStream, &pa_stream_notify_cb, userdata); + pa_stream_set_read_callback (captureStream, &pa_stream_read_cb, userdata); + + std::string monitor_name (info->default_sink_name); + monitor_name += ".monitor"; + if (pa_stream_connect_record (captureStream, monitor_name.c_str (), nullptr, PA_STREAM_NOFLAGS) != 0) { + sLog.error ("Failed to connect to input for recording"); + } +} + +void pa_context_subscribe_cb (pa_context* ctx, pa_subscription_event_type_t t, uint32_t idx, void* userdata) { + // sink changes mean re-take the stream + pa_context_get_server_info (ctx, &pa_server_info_cb, userdata); +} + +void pa_context_notify_cb (pa_context* ctx, void* userdata) { + switch (pa_context_get_state (ctx)) { + case PA_CONTEXT_READY: { + // set callback + pa_context_set_subscribe_callback (ctx, pa_context_subscribe_cb, userdata); + // set events mask and enable event callback. + pa_operation* o = pa_context_subscribe ( + ctx, static_cast (PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE), + nullptr, nullptr); + + if (o) + pa_operation_unref (o); + + // context being ready means to fetch the sink too + pa_context_get_server_info (ctx, &pa_server_info_cb, userdata); + + break; } + case PA_CONTEXT_FAILED: + sLog.error ("PulseAudio context initialization failed. Audio processing is disabled"); + break; + } +} - pa_stream* captureStream = pa_stream_new(ctx, "output monitor", &spec, nullptr); +CPulseAudioPlaybackRecorder::CPulseAudioPlaybackRecorder () : m_captureStream (nullptr) { + this->m_mainloop = pa_mainloop_new (); + this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop); + this->m_context = pa_context_new (this->m_mainloopApi, "wallpaperengine-audioprocessing"); - // store the stream first, if the record start fails there'll still be a reference to it - // so it can be free'd later - recorder->setCaptureStream (captureStream), + pa_context_set_state_callback (this->m_context, &pa_context_notify_cb, this); - pa_stream_set_state_callback(captureStream, &pa_stream_notify_cb, userdata); - pa_stream_set_read_callback(captureStream, &pa_stream_read_cb, userdata); - - std::string monitor_name(info->default_sink_name); - monitor_name += ".monitor"; - if (pa_stream_connect_record(captureStream, monitor_name.c_str(), nullptr, PA_STREAM_NOFLAGS) != 0) { - sLog.error ("Failed to connect to input for recording"); - return; - } + if (pa_context_connect (this->m_context, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) { + sLog.error ("PulseAudio connection failed! Audio processing is disabled"); + return; } - void pa_context_subscribe_cb (pa_context *ctx, pa_subscription_event_type_t t, uint32_t idx, void *userdata) - { - // sink changes mean re-take the stream - pa_context_get_server_info(ctx, &pa_server_info_cb, userdata); + // wait until the context is ready + while (pa_context_get_state (this->m_context) != PA_CONTEXT_READY) + pa_mainloop_iterate (this->m_mainloop, 1, nullptr); +} + +CPulseAudioPlaybackRecorder::~CPulseAudioPlaybackRecorder () { + pa_context_disconnect (this->m_context); + pa_mainloop_free (this->m_mainloop); +} + +pa_stream* CPulseAudioPlaybackRecorder::getCaptureStream () { + return this->m_captureStream; +} + +void CPulseAudioPlaybackRecorder::setCaptureStream (pa_stream* stream) { + this->m_captureStream = stream; +} + +void CPulseAudioPlaybackRecorder::update () { + pa_mainloop_iterate (this->m_mainloop, 0, nullptr); + + // interpolate current values to the destination + for (int i = 0; i < 64; i++) { + this->audio64 [i] = movetowards (this->audio64 [i], fft_destination64 [i], 0.1f); + if (i >= 32) + continue; + this->audio32 [i] = movetowards (this->audio32 [i], fft_destination32 [i], 0.1f); + if (i >= 16) + continue; + this->audio16 [i] = movetowards (this->audio16 [i], fft_destination16 [i], 0.1f); } - void pa_context_notify_cb(pa_context *ctx, void* userdata) - { - const pa_context_state state = pa_context_get_state(ctx); - switch (state) { - case PA_CONTEXT_READY: - { - //set callback - pa_context_set_subscribe_callback (ctx, pa_context_subscribe_cb, userdata); - //set events mask and enable event callback. - pa_operation* o = pa_context_subscribe ( - ctx, static_cast(PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE), - NULL, NULL - ); + if (!this->fullframeReady) + return; - if (o) - pa_operation_unref (o); + this->fullframeReady = false; - // context being ready means to fetch the sink too - pa_context_get_server_info(ctx, &pa_server_info_cb, userdata); + External::Android::doFft (audio_fft, audio_buffer); - break; - } - case PA_CONTEXT_FAILED: - sLog.error ("PulseAudio context initialization failed. Audio processing is disabled"); - break; - } + for (int i = 0; i < 64; i++) { + const int paramInt = (i + 2) * 2; + float f1 = audio_fft [paramInt]; + float f2 = audio_fft [paramInt + 1]; + f2 = f1 * f1 + f2 * f2; + f1 = 0.0F; + if (f2 > 0.0F) + f1 = 0.35F * static_cast (log10 (f2)); + + this->fft_destination64 [i] = + fmin (1.0F, f1 * static_cast (2.0f - pow (M_E, (1.0F - i / 63.0F) * 1.0f - 0.5f))); + this->fft_destination32 [i >> 1] = + fmin (1.0F, f1 * static_cast (2.0f - pow (M_E, (1.0F - i / 31.0F) * 1.0f - 0.5f))); + this->fft_destination16 [i >> 2] = + fmin (1.0F, f1 * static_cast (2.0f - pow (M_E, (1.0F - i / 15.0F) * 1.0f - 0.5f))); } - - CPulseAudioPlaybackRecorder::CPulseAudioPlaybackRecorder () : - m_captureStream (nullptr) - { - this->m_mainloop = pa_mainloop_new (); - this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop); - this->m_context = pa_context_new (this->m_mainloopApi, "wallpaperengine-audioprocessing"); - - pa_context_set_state_callback (this->m_context, &pa_context_notify_cb, this); - - if (pa_context_connect(this->m_context, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) { - sLog.error ("PulseAudio connection failed! Audio processing is disabled"); - return; - } - - // wait until the context is ready - while (pa_context_get_state (this->m_context) != PA_CONTEXT_READY) - pa_mainloop_iterate (this->m_mainloop, 1, nullptr); - } - - CPulseAudioPlaybackRecorder::~CPulseAudioPlaybackRecorder () - { - pa_context_disconnect(this->m_context); - pa_mainloop_free(this->m_mainloop); - } - - pa_stream* CPulseAudioPlaybackRecorder::getCaptureStream () - { - return this->m_captureStream; - } - - void CPulseAudioPlaybackRecorder::setCaptureStream (pa_stream* stream) - { - this->m_captureStream = stream; - } - - void CPulseAudioPlaybackRecorder::update () - { - pa_mainloop_iterate (this->m_mainloop, 0, nullptr); - - // interpolate current values to the destination - for (int i = 0; i < 64; i ++) { - this->audio64 [i] = movetowards (this->audio64[i], fft_destination64[i], 0.1f); - if (i >= 32) - continue; - this->audio32 [i] = movetowards (this->audio32[i], fft_destination32[i], 0.1f); - if (i >= 16) - continue; - this->audio16 [i] = movetowards (this->audio16[i], fft_destination16[i], 0.1f); - } - - if (!this->fullframeReady) - return; - - this->fullframeReady = false; - - External::Android::doFft (audio_fft, audio_buffer); - - for (int i = 0; i < 64; i ++) { - int paramInt = (i + 2) * 2; - float f1 = audio_fft[paramInt]; - float f2 = audio_fft[paramInt + 1]; - f2 = f1 * f1 + f2 * f2; - f1 = 0.0F; - if (f2 > 0.0F) - f1 = 0.35F * (float)log10(f2); - - this->fft_destination64[i] = fmin(1.0F, f1 * (float)(2.0f - pow(M_E, (1.0F - i / 63.0F) * 1.0f - 0.5f))); - this->fft_destination32[i >> 1] = fmin(1.0F, f1 * (float)(2.0f - pow(M_E, (1.0F - i / 31.0F) * 1.0f - 0.5f))); - this->fft_destination16[i >> 2] = fmin(1.0F, f1 * (float)(2.0f - pow(M_E, (1.0F - i / 15.0F) * 1.0f - 0.5f))); - } - } -} \ No newline at end of file +} +} // namespace WallpaperEngine::Audio::Drivers::Recorders \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h index a50e1db..7c38b08 100644 --- a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h +++ b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h @@ -1,45 +1,43 @@ #pragma once -#include -#include "External/Android/fft.h" #include "CPlaybackRecorder.h" +#include "External/Android/fft.h" +#include -namespace WallpaperEngine::Audio::Drivers::Recorders -{ - class CPlaybackRecorder; +namespace WallpaperEngine::Audio::Drivers::Recorders { +class CPlaybackRecorder; - class CPulseAudioPlaybackRecorder : public CPlaybackRecorder - { - public: - CPulseAudioPlaybackRecorder (); - ~CPulseAudioPlaybackRecorder (); +class CPulseAudioPlaybackRecorder final : public CPlaybackRecorder { + public: + CPulseAudioPlaybackRecorder (); + ~CPulseAudioPlaybackRecorder () override; - void update () override; + void update () override; - /** - * @return The current stream we're capturing from - */ - [[nodiscard]] pa_stream* getCaptureStream (); + /** + * @return The current stream we're capturing from + */ + [[nodiscard]] pa_stream* getCaptureStream (); - /** - * @param stream The new stream to be capturing off from - */ - void setCaptureStream (pa_stream* stream); + /** + * @param stream The new stream to be capturing off from + */ + void setCaptureStream (pa_stream* stream); - uint8_t audio_buffer [WAVE_BUFFER_SIZE] = {0x80}; - uint8_t audio_buffer_tmp [WAVE_BUFFER_SIZE] = {0x80}; - uint8_t audio_fft [WAVE_BUFFER_SIZE] = {0}; - size_t currentWritePointer = 0; - bool fullframeReady = false; + uint8_t audio_buffer [WAVE_BUFFER_SIZE] = {0x80}; + uint8_t audio_buffer_tmp [WAVE_BUFFER_SIZE] = {0x80}; + uint8_t audio_fft [WAVE_BUFFER_SIZE] = {0}; + size_t currentWritePointer = 0; + bool fullframeReady = false; - private: - pa_mainloop* m_mainloop; - pa_mainloop_api* m_mainloopApi; - pa_context* m_context; - pa_stream* m_captureStream; + private: + pa_mainloop* m_mainloop; + pa_mainloop_api* m_mainloopApi; + pa_context* m_context; + pa_stream* m_captureStream; - float fft_destination64[64]; - float fft_destination32[32]; - float fft_destination16[16]; - }; -} + float fft_destination64 [64]; + float fft_destination32 [32]; + float fft_destination16 [16]; +}; +} // namespace WallpaperEngine::Audio::Drivers::Recorders diff --git a/src/WallpaperEngine/Core/CObject.cpp b/src/WallpaperEngine/Core/CObject.cpp index 562c18c..b5e77ef 100644 --- a/src/WallpaperEngine/Core/CObject.cpp +++ b/src/WallpaperEngine/Core/CObject.cpp @@ -1,13 +1,13 @@ -#include "common.h" #include "CObject.h" +#include "common.h" -#include -#include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" -#include "WallpaperEngine/Core/Objects/CImage.h" -#include "WallpaperEngine/Core/Objects/CSound.h" -#include "WallpaperEngine/Core/Objects/CParticle.h" -#include "WallpaperEngine/Core/CScene.h" #include "WallpaperEngine/Core/CProject.h" +#include "WallpaperEngine/Core/CScene.h" +#include "WallpaperEngine/Core/Objects/CImage.h" +#include "WallpaperEngine/Core/Objects/CParticle.h" +#include "WallpaperEngine/Core/Objects/CSound.h" +#include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" +#include #include "WallpaperEngine/Assets/CContainer.h" @@ -15,35 +15,25 @@ using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Core::UserSettings; -CObject::CObject ( - CScene* scene, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - std::string type, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles) : +CObject::CObject (CScene* scene, CUserSettingBoolean* visible, uint32_t id, std::string name, std::string type, + CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles) : m_scene (scene), m_visible (visible), m_id (id), - m_name (std::move(name)), - m_type (std::move(type)), + m_name (std::move (name)), + m_type (std::move (type)), m_origin (origin), m_scale (scale), - m_angles (angles) -{ -} + m_angles (angles) {} -CObject* CObject::fromJSON (json data, CScene* scene, CContainer* container) -{ +CObject* CObject::fromJSON (json data, CScene* scene, CContainer* container) { std::string json = data.dump (); auto id_it = jsonFindRequired (data, "id", "Objects must have id"); - auto visible = jsonFindUserConfig (data, "visible", false); - auto origin = jsonFindUserConfig (data, "origin", {0, 0, 0}); - auto scale = jsonFindUserConfig (data, "scale", {1, 1, 1}); - auto angles_val = jsonFindDefault (data, "angles", "0.0 0.0 0.0"); + auto visible = jsonFindUserConfig (data, "visible", false); + auto origin = jsonFindUserConfig (data, "origin", {0, 0, 0}); + auto scale = jsonFindUserConfig (data, "scale", {1, 1, 1}); + auto angles_val = jsonFindDefault (data, "angles", "0.0 0.0 0.0"); auto name_it = jsonFindRequired (data, "name", "Objects must have name"); auto effects_it = data.find ("effects"); auto dependencies_it = data.find ("dependencies"); @@ -56,142 +46,89 @@ CObject* CObject::fromJSON (json data, CScene* scene, CContainer* container) CObject* object; - if (image_it != data.end () && !(*image_it).is_null ()) - { - object = Objects::CImage::fromJSON ( - scene, - data, - container, - visible, - *id_it, - *name_it, - origin, - scale, - WallpaperEngine::Core::aToVector3 (angles_val) - ); - } - else if (sound_it != data.end () && !(*sound_it).is_null ()) - { - object = Objects::CSound::fromJSON ( - scene, - data, - visible, - *id_it, - *name_it, - origin, - scale, - WallpaperEngine::Core::aToVector3 (angles_val) - ); - } - else if (particle_it != data.end () && !(*particle_it).is_null ()) - { + if (image_it != data.end () && !image_it->is_null ()) { + object = Objects::CImage::fromJSON (scene, data, container, visible, *id_it, *name_it, origin, scale, + WallpaperEngine::Core::aToVector3 (angles_val)); + } else if (sound_it != data.end () && !sound_it->is_null ()) { + object = Objects::CSound::fromJSON (scene, data, visible, *id_it, *name_it, origin, scale, + WallpaperEngine::Core::aToVector3 (angles_val)); + } else if (particle_it != data.end () && !particle_it->is_null ()) { /// TODO: XXXHACK -- TO REMOVE WHEN PARTICLE SUPPORT IS PROPERLY IMPLEMENTED - try - { - object = Objects::CParticle::fromFile ( - scene, - (*particle_it).get (), - container, - visible, - *id_it, - *name_it, - origin, - scale - ); - } - catch (std::runtime_error& ex) - { + try { + object = Objects::CParticle::fromFile (scene, particle_it->get (), container, visible, *id_it, + *name_it, origin, scale); + } catch (std::runtime_error&) { return nullptr; } - } - else if (text_it != data.end () && !(*text_it).is_null ()) - { + } else if (text_it != data.end () && !text_it->is_null ()) { /// TODO: XXXHACK -- TO REMOVE WHEN TEXT SUPPORT IS IMPLEMENTED return nullptr; - } - else if (light_it != data.end () && !(*light_it).is_null ()) - { + } else if (light_it != data.end () && !light_it->is_null ()) { /// TODO: XXXHACK -- TO REMOVE WHEN LIGHT SUPPORT IS IMPLEMENTED return nullptr; - } - else - { + } else { sLog.exception ("Unknown object type detected: ", *name_it); } - if (effects_it != data.end () && (*effects_it).is_array ()) - { - for (auto& cur : *effects_it) - { - auto effectVisible = jsonFindUserConfig (cur, "visible", true); + if (effects_it != data.end () && effects_it->is_array ()) { + for (auto& cur : *effects_it) { + auto effectVisible = jsonFindUserConfig (cur, "visible", true); - if (!effectVisible->processValue (scene->getProject ().getProperties ())) - continue; + if (!effectVisible->processValue (scene->getProject ().getProperties ())) + continue; - object->insertEffect ( - Objects::CEffect::fromJSON (cur, effectVisible, object, container) - ); + object->insertEffect (Objects::CEffect::fromJSON (cur, effectVisible, object, container)); } } - if (dependencies_it != data.end () && (*dependencies_it).is_array ()) + if (dependencies_it != data.end () && dependencies_it->is_array ()) for (const auto& cur : *dependencies_it) object->insertDependency (cur); return object; } -glm::vec3 CObject::getOrigin () const -{ +glm::vec3 CObject::getOrigin () const { return this->m_origin->processValue (this->getScene ()->getProject ().getProperties ()); } -glm::vec3 CObject::getScale () const -{ +glm::vec3 CObject::getScale () const { return this->m_scale->processValue (this->getScene ()->getProject ().getProperties ()); } -const glm::vec3& CObject::getAngles () const -{ +const glm::vec3& CObject::getAngles () const { return this->m_angles; } -const std::string& CObject::getName () const -{ +const std::string& CObject::getName () const { return this->m_name; } -const std::vector& CObject::getEffects () const -{ +const std::vector& CObject::getEffects () const { return this->m_effects; } -const std::vector& CObject::getDependencies () const -{ +const std::vector& CObject::getDependencies () const { return this->m_dependencies; } -bool CObject::isVisible () const -{ +bool CObject::isVisible () const { // TODO: cache this return this->m_visible->processValue (this->getScene ()->getProject ().getProperties ()); } -CScene* CObject::getScene () const -{ +CScene* CObject::getScene () const { return this->m_scene; } -int CObject::getId () const -{ +int CObject::getId () const { return this->m_id; } -void CObject::insertEffect (Objects::CEffect* effect) -{ +void CObject::insertEffect (Objects::CEffect* effect) { this->m_effects.push_back (effect); } -void CObject::insertDependency (uint32_t dependency) -{ + +void CObject::insertDependency (uint32_t dependency) { this->m_dependencies.push_back (dependency); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/CObject.h b/src/WallpaperEngine/Core/CObject.h index 0ad7731..4cc1061 100644 --- a/src/WallpaperEngine/Core/CObject.h +++ b/src/WallpaperEngine/Core/CObject.h @@ -8,76 +8,75 @@ #include "WallpaperEngine/Core/UserSettings/CUserSettingFloat.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingVector3.h" -namespace WallpaperEngine::Core -{ - class CScene; +namespace WallpaperEngine::Core { +class CScene; } -namespace WallpaperEngine::Core::Objects -{ - class CEffect; +namespace WallpaperEngine::Core::Objects { +class CEffect; } -namespace WallpaperEngine::Core::UserSettings -{ - class CUserSettingBoolean; +namespace WallpaperEngine::Core::UserSettings { +class CUserSettingBoolean; } -namespace WallpaperEngine::Core -{ - using json = nlohmann::json; - using namespace WallpaperEngine::Assets; - using namespace WallpaperEngine::Core::UserSettings; +namespace WallpaperEngine::Core { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Core::UserSettings; - class CObject - { - friend class CScene; - public: - static CObject* fromJSON (json data, CScene* scene, CContainer* container); +class CObject { + friend class CScene; - template const T* as () const { assert (is ()); return (const T*) this; } - template T* as () { assert (is ()); return (T*) this; } + public: + static CObject* fromJSON (json data, CScene* scene, CContainer* container); - template bool is () { return this->m_type == T::Type; } + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); + } - const std::vector& getEffects () const; - const std::vector& getDependencies () const; - int getId () const; + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } - glm::vec3 getOrigin () const; - glm::vec3 getScale () const; - const glm::vec3& getAngles () const; - const std::string& getName () const; + template bool is () { + return this->m_type == T::Type; + } - bool isVisible () const; - CScene* getScene () const; - protected: - CObject ( - CScene* scene, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - std::string type, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles - ); + const std::vector& getEffects () const; + const std::vector& getDependencies () const; + int getId () const; - void insertEffect (Objects::CEffect* effect); - void insertDependency (uint32_t dependency); - private: - std::string m_type; + glm::vec3 getOrigin () const; + glm::vec3 getScale () const; + const glm::vec3& getAngles () const; + const std::string& getName () const; - CUserSettingBoolean* m_visible; - uint32_t m_id; - std::string m_name; - CUserSettingVector3* m_origin; - CUserSettingVector3* m_scale; - glm::vec3 m_angles; + bool isVisible () const; + CScene* getScene () const; - std::vector m_effects; - std::vector m_dependencies; + protected: + CObject (CScene* scene, CUserSettingBoolean* visible, uint32_t id, std::string name, std::string type, + CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles); - CScene* m_scene; - }; -} + void insertEffect (Objects::CEffect* effect); + void insertDependency (uint32_t dependency); + + private: + std::string m_type; + + CUserSettingBoolean* m_visible; + uint32_t m_id; + std::string m_name; + CUserSettingVector3* m_origin; + CUserSettingVector3* m_scale; + glm::vec3 m_angles; + + std::vector m_effects; + std::vector m_dependencies; + + CScene* m_scene; +}; +} // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/CProject.cpp b/src/WallpaperEngine/Core/CProject.cpp index 4fc7397..4d81926 100644 --- a/src/WallpaperEngine/Core/CProject.cpp +++ b/src/WallpaperEngine/Core/CProject.cpp @@ -12,18 +12,16 @@ using namespace WallpaperEngine::Assets; CProject::CProject (std::string title, std::string type, CContainer* container) : m_title (std::move (title)), m_type (std::move (type)), - m_container (container) -{ -} + m_wallpaper (nullptr), + m_container (container) {} -CProject* CProject::fromFile (const std::string& filename, CContainer* container) -{ +CProject* CProject::fromFile (const std::string& filename, CContainer* container) { json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)); - std::string title = *jsonFindRequired (content, "title", "Project title missing"); + const std::string title = *jsonFindRequired (content, "title", "Project title missing"); std::string type = *jsonFindRequired (content, "type", "Project type missing"); - std::string file = *jsonFindRequired (content, "file", "Project's main file missing"); - auto general = content.find ("general"); + const std::string file = *jsonFindRequired (content, "file", "Project's main file missing"); + const auto general = content.find ("general"); CWallpaper* wallpaper; std::transform (type.begin (), type.end (), type.begin (), tolower); @@ -33,7 +31,7 @@ CProject* CProject::fromFile (const std::string& filename, CContainer* container if (type == "scene") wallpaper = CScene::fromFile (file, *project, container); else if (type == "video") - wallpaper = new CVideo (file.c_str (), *project); + wallpaper = new CVideo (file, *project); else if (type == "web") sLog.exception ("Web wallpapers are not supported yet"); else @@ -41,14 +39,11 @@ CProject* CProject::fromFile (const std::string& filename, CContainer* container project->setWallpaper (wallpaper); - if (general != content.end ()) - { - auto properties = (*general).find ("properties"); + if (general != content.end ()) { + const auto properties = general->find ("properties"); - if (properties != (*general).end ()) - { - for (const auto& cur : (*properties).items ()) - { + if (properties != general->end ()) { + for (const auto& cur : properties->items ()) { Projects::CProperty* property = Projects::CProperty::fromJSON (cur.value (), cur.key ()); if (property != nullptr) @@ -60,37 +55,30 @@ CProject* CProject::fromFile (const std::string& filename, CContainer* container return project; } -void CProject::setWallpaper (CWallpaper* wallpaper) -{ +void CProject::setWallpaper (CWallpaper* wallpaper) { this->m_wallpaper = wallpaper; } -CWallpaper* CProject::getWallpaper () const -{ +CWallpaper* CProject::getWallpaper () const { return this->m_wallpaper; } -const std::string& CProject::getTitle () const -{ +const std::string& CProject::getTitle () const { return this->m_title; } -const std::string& CProject::getType () const -{ +const std::string& CProject::getType () const { return this->m_type; } -const std::vector& CProject::getProperties () const -{ +const std::vector& CProject::getProperties () const { return this->m_properties; } -CContainer* CProject::getContainer () -{ +CContainer* CProject::getContainer () { return this->m_container; } -void CProject::insertProperty (Projects::CProperty* property) -{ +void CProject::insertProperty (Projects::CProperty* property) { this->m_properties.push_back (property); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/CProject.h b/src/WallpaperEngine/Core/CProject.h index 0dda0cf..7f48677 100644 --- a/src/WallpaperEngine/Core/CProject.h +++ b/src/WallpaperEngine/Core/CProject.h @@ -6,37 +6,36 @@ #include "WallpaperEngine/Assets/CContainer.h" -namespace WallpaperEngine::Core -{ - using json = nlohmann::json; - using namespace WallpaperEngine::Assets; +namespace WallpaperEngine::Core { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; - class CWallpaper; +class CWallpaper; - class CProject - { - public: - static CProject* fromFile (const std::string& filename, CContainer* container); +class CProject { + public: + static CProject* fromFile (const std::string& filename, CContainer* container); - CWallpaper* getWallpaper () const; + CWallpaper* getWallpaper () const; - const std::string& getTitle () const; - const std::string& getType () const; - const std::vector& getProperties () const; + const std::string& getTitle () const; + const std::string& getType () const; + const std::vector& getProperties () const; - CContainer* getContainer (); + CContainer* getContainer (); - protected: - CProject (std::string title, std::string type, CContainer* container); + protected: + CProject (std::string title, std::string type, CContainer* container); - void setWallpaper (CWallpaper* wallpaper); - void insertProperty (Projects::CProperty* property); - private: - std::vector m_properties; + void setWallpaper (CWallpaper* wallpaper); + void insertProperty (Projects::CProperty* property); - std::string m_title; - std::string m_type; - CWallpaper* m_wallpaper; - CContainer* m_container; - }; -} + private: + std::vector m_properties; + + std::string m_title; + std::string m_type; + CWallpaper* m_wallpaper; + CContainer* m_container; +}; +} // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/CScene.cpp b/src/WallpaperEngine/Core/CScene.cpp index 746c8f5..dc9eb9d 100644 --- a/src/WallpaperEngine/Core/CScene.cpp +++ b/src/WallpaperEngine/Core/CScene.cpp @@ -8,27 +8,12 @@ using namespace WallpaperEngine::Core; -CScene::CScene ( - CProject& project, - CContainer* container, - Scenes::CCamera* camera, - glm::vec3 ambientColor, - CUserSettingBoolean* bloom, - CUserSettingFloat* bloomStrength, - CUserSettingFloat* bloomThreshold, - bool cameraFade, - bool cameraParallax, - double cameraParallaxAmount, - double cameraParallaxDelay, - double cameraParallaxMouseInfluence, - bool cameraPreview, - bool cameraShake, - double cameraShakeAmplitude, - double cameraShakeRoughness, - double cameraShakeSpeed, - CUserSettingVector3* clearColor, - Scenes::CProjection* orthogonalProjection, - glm::vec3 skylightColor) : +CScene::CScene (CProject& project, CContainer* container, Scenes::CCamera* camera, glm::vec3 ambientColor, + CUserSettingBoolean* bloom, CUserSettingFloat* bloomStrength, CUserSettingFloat* bloomThreshold, + bool cameraFade, bool cameraParallax, double cameraParallaxAmount, double cameraParallaxDelay, + double cameraParallaxMouseInfluence, bool cameraPreview, bool cameraShake, double cameraShakeAmplitude, + double cameraShakeRoughness, double cameraShakeSpeed, CUserSettingVector3* clearColor, + Scenes::CProjection* orthogonalProjection, glm::vec3 skylightColor) : CWallpaper (Type, project), m_container (container), m_camera (camera), @@ -48,60 +33,44 @@ CScene::CScene ( m_cameraShakeSpeed (cameraShakeSpeed), m_clearColor (clearColor), m_orthogonalProjection (orthogonalProjection), - m_skylightColor (skylightColor) -{ -} + m_skylightColor (skylightColor) {} -CScene* CScene::fromFile (const std::string& filename, CProject& project, CContainer* container) -{ +CScene* CScene::fromFile (const std::string& filename, CProject& project, CContainer* container) { std::string stringContent = WallpaperEngine::FileSystem::loadFullFile (filename, container); json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)); - auto camera_it = jsonFindRequired (content, "camera", "Scenes must have a defined camera"); - auto general_it = jsonFindRequired (content, "general", "Scenes must have a general section"); - auto objects_it = jsonFindRequired (content, "objects", "Scenes must have a list of objects to display"); + const auto camera_it = jsonFindRequired (content, "camera", "Scenes must have a defined camera"); + const auto general_it = jsonFindRequired (content, "general", "Scenes must have a general section"); + const auto objects_it = jsonFindRequired (content, "objects", "Scenes must have a list of objects to display"); - // TODO: FIND IF THESE DEFAULTS ARE SENSIBLE OR NOT AND PERFORM PROPER VALIDATION WHEN CAMERA PREVIEW AND CAMERA PARALLAX ARE PRESENT - auto ambientcolor = jsonFindDefault (*general_it, "ambientcolor", "0 0 0"); - auto bloom = jsonFindUserConfig (*general_it, "bloom", false); - auto bloomstrength = jsonFindUserConfig (*general_it, "bloomstrength", 0.0); - auto bloomthreshold = jsonFindUserConfig (*general_it, "bloomthreshold", 0.0); - auto camerafade = jsonFindDefault (*general_it, "camerafade", false); - auto cameraparallax = jsonFindDefault (*general_it, "cameraparallax", true); - auto cameraparallaxamount = jsonFindDefault (*general_it, "cameraparallaxamount", 1.0f); - auto cameraparallaxdelay = jsonFindDefault (*general_it, "cameraparallaxdelay", 0.0f); - auto cameraparallaxmouseinfluence = jsonFindDefault (*general_it, "cameraparallaxmouseinfluence", 1.0f); - auto camerapreview = jsonFindDefault (*general_it, "camerapreview", false); - auto camerashake = jsonFindDefault (*general_it, "camerashake", false); - auto camerashakeamplitude = jsonFindDefault (*general_it, "camerashakeamplitude", 0.0f); - auto camerashakeroughness = jsonFindDefault (*general_it, "camerashakeroughness", 0.0f); - auto camerashakespeed = jsonFindDefault (*general_it, "camerashakespeed", 0.0f); - auto clearcolor = jsonFindUserConfig (*general_it, "clearcolor", {1, 1, 1}); - auto orthogonalprojection_it = jsonFindRequired (*general_it, "orthogonalprojection", "General section must have orthogonal projection info"); - auto skylightcolor = jsonFindDefault (*general_it, "skylightcolor", "0 0 0"); + // TODO: FIND IF THESE DEFAULTS ARE SENSIBLE OR NOT AND PERFORM PROPER VALIDATION WHEN CAMERA PREVIEW AND CAMERA + // PARALLAX ARE PRESENT + const auto ambientcolor = jsonFindDefault (*general_it, "ambientcolor", "0 0 0"); + const auto bloom = jsonFindUserConfig (*general_it, "bloom", false); + const auto bloomstrength = jsonFindUserConfig (*general_it, "bloomstrength", 0.0); + const auto bloomthreshold = jsonFindUserConfig (*general_it, "bloomthreshold", 0.0); + const auto camerafade = jsonFindDefault (*general_it, "camerafade", false); + const auto cameraparallax = jsonFindDefault (*general_it, "cameraparallax", true); + const auto cameraparallaxamount = jsonFindDefault (*general_it, "cameraparallaxamount", 1.0f); + const auto cameraparallaxdelay = jsonFindDefault (*general_it, "cameraparallaxdelay", 0.0f); + const auto cameraparallaxmouseinfluence = + jsonFindDefault (*general_it, "cameraparallaxmouseinfluence", 1.0f); + const auto camerapreview = jsonFindDefault (*general_it, "camerapreview", false); + const auto camerashake = jsonFindDefault (*general_it, "camerashake", false); + const auto camerashakeamplitude = jsonFindDefault (*general_it, "camerashakeamplitude", 0.0f); + const auto camerashakeroughness = jsonFindDefault (*general_it, "camerashakeroughness", 0.0f); + const auto camerashakespeed = jsonFindDefault (*general_it, "camerashakespeed", 0.0f); + const auto clearcolor = jsonFindUserConfig (*general_it, "clearcolor", {1, 1, 1}); + const auto orthogonalprojection_it = + jsonFindRequired (*general_it, "orthogonalprojection", "General section must have orthogonal projection info"); + const auto skylightcolor = jsonFindDefault (*general_it, "skylightcolor", "0 0 0"); - CScene* scene = new CScene ( - project, - container, - Scenes::CCamera::fromJSON (*camera_it), - WallpaperEngine::Core::aToColorf(ambientcolor), - bloom, - bloomstrength, - bloomthreshold, - camerafade, - cameraparallax, - cameraparallaxamount, - cameraparallaxdelay, - cameraparallaxmouseinfluence, - camerapreview, - camerashake, - camerashakeamplitude, - camerashakeroughness, - camerashakespeed, - clearcolor, - Scenes::CProjection::fromJSON (*orthogonalprojection_it), - WallpaperEngine::Core::aToColorf(skylightcolor) - ); + auto* scene = new CScene ( + project, container, Scenes::CCamera::fromJSON (*camera_it), WallpaperEngine::Core::aToColorf (ambientcolor), + bloom, bloomstrength, bloomthreshold, camerafade, cameraparallax, cameraparallaxamount, cameraparallaxdelay, + cameraparallaxmouseinfluence, camerapreview, camerashake, camerashakeamplitude, camerashakeroughness, + camerashakespeed, clearcolor, Scenes::CProjection::fromJSON (*orthogonalprojection_it), + WallpaperEngine::Core::aToColorf (skylightcolor)); for (const auto& cur : *objects_it) scene->insertObject (CObject::fromJSON (cur, scene, container)); @@ -109,117 +78,95 @@ CScene* CScene::fromFile (const std::string& filename, CProject& project, CConta return scene; } -const std::map& CScene::getObjects () const -{ +const std::map& CScene::getObjects () const { return this->m_objects; } -const std::vector& CScene::getObjectsByRenderOrder () const -{ + +const std::vector& CScene::getObjectsByRenderOrder () const { return this->m_objectsByRenderOrder; } -void CScene::insertObject (CObject* object) -{ +void CScene::insertObject (CObject* object) { /// TODO: XXXHACK -- TO REMOVE WHEN PARTICLE SUPPORT IS PROPERLY IMPLEMENTED - if (object != nullptr) - { + if (object != nullptr) { this->m_objects.insert (std::make_pair (object->getId (), object)); this->m_objectsByRenderOrder.emplace_back (object); } } -CContainer* CScene::getContainer () -{ +CContainer* CScene::getContainer () { return this->m_container; } -const Scenes::CCamera* CScene::getCamera () const -{ +const Scenes::CCamera* CScene::getCamera () const { return this->m_camera; } -const glm::vec3 &CScene::getAmbientColor() const -{ +const glm::vec3& CScene::getAmbientColor () const { return this->m_ambientColor; } -const bool CScene::isBloom () const -{ +const bool CScene::isBloom () const { return this->m_bloom->processValue (this->getProject ().getProperties ()); } -double CScene::getBloomStrength () const -{ +double CScene::getBloomStrength () const { return this->m_bloomStrength->processValue (this->getProject ().getProperties ()); } -double CScene::getBloomThreshold () const -{ +double CScene::getBloomThreshold () const { return this->m_bloomThreshold->processValue (this->getProject ().getProperties ()); } -const bool CScene::isCameraFade () const -{ +const bool CScene::isCameraFade () const { return this->m_cameraFade; } -const bool CScene::isCameraParallax () const -{ +const bool CScene::isCameraParallax () const { return this->m_cameraParallax; } -const double CScene::getCameraParallaxAmount () const -{ +const double CScene::getCameraParallaxAmount () const { return this->m_cameraParallaxAmount; } -const double CScene::getCameraParallaxDelay () const -{ +const double CScene::getCameraParallaxDelay () const { return this->m_cameraParallaxDelay; } -const double CScene::getCameraParallaxMouseInfluence () const -{ +const double CScene::getCameraParallaxMouseInfluence () const { return this->m_cameraParallaxMouseInfluence; } -const bool CScene::isCameraPreview () const -{ +const bool CScene::isCameraPreview () const { return this->m_cameraPreview; } -const bool CScene::isCameraShake () const -{ +const bool CScene::isCameraShake () const { return this->m_cameraShake; } -const double CScene::getCameraShakeAmplitude () const -{ +const double CScene::getCameraShakeAmplitude () const { return this->m_cameraShakeAmplitude; } -const double CScene::getCameraShakeRoughness () const -{ +const double CScene::getCameraShakeRoughness () const { return this->m_cameraShakeRoughness; } -const double CScene::getCameraShakeSpeed () const -{ +const double CScene::getCameraShakeSpeed () const { return this->m_cameraShakeSpeed; } -glm::vec3 CScene::getClearColor () const -{ +glm::vec3 CScene::getClearColor () const { return this->m_clearColor->processValue (this->getProject ().getProperties ()); } -Scenes::CProjection* CScene::getOrthogonalProjection () const -{ +Scenes::CProjection* CScene::getOrthogonalProjection () const { return this->m_orthogonalProjection; } -const glm::vec3& CScene::getSkylightColor () const -{ +const glm::vec3& CScene::getSkylightColor () const { return this->m_skylightColor; } diff --git a/src/WallpaperEngine/Core/CScene.h b/src/WallpaperEngine/Core/CScene.h index 89a191d..05610cd 100644 --- a/src/WallpaperEngine/Core/CScene.h +++ b/src/WallpaperEngine/Core/CScene.h @@ -8,94 +8,77 @@ #include "WallpaperEngine/Core/Scenes/CCamera.h" #include "WallpaperEngine/Core/Scenes/CProjection.h" -namespace WallpaperEngine::Core -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core { +using json = nlohmann::json; - class CObject; +class CObject; - class CScene : public CWallpaper - { - public: - static CScene* fromFile (const std::string& filename, CProject& project, CContainer* container); +class CScene : public CWallpaper { + public: + static CScene* fromFile (const std::string& filename, CProject& project, CContainer* container); - const std::map& getObjects () const; - const std::vector& getObjectsByRenderOrder () const; + const std::map& getObjects () const; + const std::vector& getObjectsByRenderOrder () const; - const glm::vec3& getAmbientColor() const; - const bool isBloom() const; - double getBloomStrength() const; - double getBloomThreshold() const; - const bool isCameraFade() const; - const bool isCameraParallax() const; - const double getCameraParallaxAmount() const; - const double getCameraParallaxDelay() const; - const double getCameraParallaxMouseInfluence() const; - const bool isCameraPreview() const; - const bool isCameraShake() const; - const double getCameraShakeAmplitude() const; - const double getCameraShakeRoughness() const; - const double getCameraShakeSpeed() const; - glm::vec3 getClearColor() const; - Scenes::CProjection* getOrthogonalProjection() const; - const glm::vec3& getSkylightColor() const; - const Scenes::CCamera* getCamera () const; + const glm::vec3& getAmbientColor () const; + const bool isBloom () const; + double getBloomStrength () const; + double getBloomThreshold () const; + const bool isCameraFade () const; + const bool isCameraParallax () const; + const double getCameraParallaxAmount () const; + const double getCameraParallaxDelay () const; + const double getCameraParallaxMouseInfluence () const; + const bool isCameraPreview () const; + const bool isCameraShake () const; + const double getCameraShakeAmplitude () const; + const double getCameraShakeRoughness () const; + const double getCameraShakeSpeed () const; + glm::vec3 getClearColor () const; + Scenes::CProjection* getOrthogonalProjection () const; + const glm::vec3& getSkylightColor () const; + const Scenes::CCamera* getCamera () const; - protected: - friend class CWallpaper; + protected: + friend class CWallpaper; - CScene ( - CProject& project, - CContainer* container, - Scenes::CCamera* camera, - glm::vec3 ambientColor, - CUserSettingBoolean* bloom, - CUserSettingFloat* bloomStrength, - CUserSettingFloat* bloomThreshold, - bool cameraFade, - bool cameraParallax, - double cameraParallaxAmount, - double cameraParallaxDelay, - double cameraParallaxMouseInfluence, - bool cameraPreview, - bool cameraShake, - double cameraShakeAmplitude, - double cameraShakeRoughness, - double cameraShakeSpeed, - CUserSettingVector3* clearColor, - Scenes::CProjection* orthogonalProjection, - glm::vec3 skylightColor - ); + CScene (CProject& project, CContainer* container, Scenes::CCamera* camera, glm::vec3 ambientColor, + CUserSettingBoolean* bloom, CUserSettingFloat* bloomStrength, CUserSettingFloat* bloomThreshold, + bool cameraFade, bool cameraParallax, double cameraParallaxAmount, double cameraParallaxDelay, + double cameraParallaxMouseInfluence, bool cameraPreview, bool cameraShake, double cameraShakeAmplitude, + double cameraShakeRoughness, double cameraShakeSpeed, CUserSettingVector3* clearColor, + Scenes::CProjection* orthogonalProjection, glm::vec3 skylightColor); - static const std::string Type; + static const std::string Type; - void insertObject (CObject* object); + void insertObject (CObject* object); - CContainer* getContainer (); - private: - CContainer* m_container; - Scenes::CCamera* m_camera; + CContainer* getContainer (); - // data from general section on the json - glm::vec3 m_ambientColor; - CUserSettingBoolean* m_bloom; - CUserSettingFloat* m_bloomStrength; - CUserSettingFloat* m_bloomThreshold; - bool m_cameraFade; - bool m_cameraParallax; - double m_cameraParallaxAmount; - double m_cameraParallaxDelay; - double m_cameraParallaxMouseInfluence; - bool m_cameraPreview; - bool m_cameraShake; - double m_cameraShakeAmplitude; - double m_cameraShakeRoughness; - double m_cameraShakeSpeed; - CUserSettingVector3* m_clearColor; - Scenes::CProjection* m_orthogonalProjection; - glm::vec3 m_skylightColor; + private: + CContainer* m_container; + Scenes::CCamera* m_camera; - std::map m_objects; - std::vector m_objectsByRenderOrder; - }; -} + // data from general section on the json + glm::vec3 m_ambientColor; + CUserSettingBoolean* m_bloom; + CUserSettingFloat* m_bloomStrength; + CUserSettingFloat* m_bloomThreshold; + bool m_cameraFade; + bool m_cameraParallax; + double m_cameraParallaxAmount; + double m_cameraParallaxDelay; + double m_cameraParallaxMouseInfluence; + bool m_cameraPreview; + bool m_cameraShake; + double m_cameraShakeAmplitude; + double m_cameraShakeRoughness; + double m_cameraShakeSpeed; + CUserSettingVector3* m_clearColor; + Scenes::CProjection* m_orthogonalProjection; + glm::vec3 m_skylightColor; + + std::map m_objects; + std::vector m_objectsByRenderOrder; +}; +} // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/CVideo.cpp b/src/WallpaperEngine/Core/CVideo.cpp index 9049d46..385f0b3 100644 --- a/src/WallpaperEngine/Core/CVideo.cpp +++ b/src/WallpaperEngine/Core/CVideo.cpp @@ -6,12 +6,9 @@ using namespace WallpaperEngine::Core; CVideo::CVideo (std::string filename, CProject& project) : CWallpaper (Type, project), - m_filename (std::move(filename)) -{ -} + m_filename (std::move (filename)) {} -const std::string& CVideo::getFilename () -{ +const std::string& CVideo::getFilename () { return this->m_filename; } diff --git a/src/WallpaperEngine/Core/CVideo.h b/src/WallpaperEngine/Core/CVideo.h index debe3bd..d217fa6 100644 --- a/src/WallpaperEngine/Core/CVideo.h +++ b/src/WallpaperEngine/Core/CVideo.h @@ -1,32 +1,27 @@ #pragma once -#include "Core.h" #include "CWallpaper.h" +#include "Core.h" -extern "C" -{ +extern "C" { #include #include #include #include } -namespace WallpaperEngine::Core -{ - class CVideo : public CWallpaper - { - public: - explicit CVideo (std::string filename, CProject& project); +namespace WallpaperEngine::Core { +class CVideo : public CWallpaper { + public: + explicit CVideo (std::string filename, CProject& project); - const std::string& getFilename (); + const std::string& getFilename (); - protected: - friend class CWallpaper; + protected: + friend class CWallpaper; - const std::string m_filename; + const std::string m_filename; - static const std::string Type; - - private: - }; -} + static const std::string Type; +}; +} // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/CWallpaper.cpp b/src/WallpaperEngine/Core/CWallpaper.cpp index a162f19..055fbcb 100644 --- a/src/WallpaperEngine/Core/CWallpaper.cpp +++ b/src/WallpaperEngine/Core/CWallpaper.cpp @@ -4,13 +4,8 @@ using namespace WallpaperEngine::Core; -CWallpaper::CWallpaper (std::string type, CProject& project) : - m_type (std::move(type)), - m_project (project) -{ -} +CWallpaper::CWallpaper (std::string type, CProject& project) : m_type (std::move (type)), m_project (project) {} -CProject& CWallpaper::getProject () const -{ +CProject& CWallpaper::getProject () const { return this->m_project; } diff --git a/src/WallpaperEngine/Core/CWallpaper.h b/src/WallpaperEngine/Core/CWallpaper.h index 6bcb51e..5b81a00 100644 --- a/src/WallpaperEngine/Core/CWallpaper.h +++ b/src/WallpaperEngine/Core/CWallpaper.h @@ -4,28 +4,35 @@ #include "CProject.h" -namespace WallpaperEngine::Core -{ - class CProject; +namespace WallpaperEngine::Core { +class CProject; - class CWallpaper - { - public: - template const T* as () const { assert (is ()); return (const T*) this; } - template T* as () { assert (is ()); return (T*) this; } +class CWallpaper { + public: + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); + } - template bool is () { return this->m_type == T::Type; } + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } - CWallpaper (std::string type, CProject& project); + template bool is () { + return this->m_type == T::Type; + } - CProject& getProject () const; + CWallpaper (std::string type, CProject& project); - protected: - friend class CProject; + CProject& getProject () const; - private: - CProject& m_project; + protected: + friend class CProject; - std::string m_type; - }; -} + private: + CProject& m_project; + + std::string m_type; +}; +} // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/Core.cpp b/src/WallpaperEngine/Core/Core.cpp index b095fac..250fd98 100644 --- a/src/WallpaperEngine/Core/Core.cpp +++ b/src/WallpaperEngine/Core/Core.cpp @@ -9,78 +9,87 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Core::UserSettings; -glm::vec4 Core::aToVector4 (const char* str) -{ - float x = strtof (str, const_cast (&str)); while (*str == ' ') str ++; - float y = strtof (str, const_cast (&str)); while (*str == ' ') str ++; - float z = strtof (str, const_cast (&str)); while (*str == ' ') str ++; - float w = strtof (str, const_cast (&str)); +glm::vec4 Core::aToVector4 (const char* str) { + float x = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float y = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float z = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float w = strtof (str, const_cast (&str)); return {x, y, z, w}; } -glm::vec3 Core::aToVector3 (const char* str) -{ - float x = strtof (str, const_cast (&str)); while (*str == ' ') str ++; - float y = strtof (str, const_cast (&str)); while (*str == ' ') str ++; - float z = strtof (str, const_cast (&str)); +glm::vec3 Core::aToVector3 (const char* str) { + float x = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float y = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float z = strtof (str, const_cast (&str)); return {x, y, z}; } -glm::vec2 Core::aToVector2 (const char* str) -{ - float x = strtof (str, const_cast (&str)); while (*str == ' ') str ++; - float y = strtof (str, const_cast (&str)); +glm::vec2 Core::aToVector2 (const char* str) { + float x = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float y = strtof (str, const_cast (&str)); return {x, y}; } -glm::vec4 Core::aToVector4 (const std::string& str) -{ +glm::vec4 Core::aToVector4 (const std::string& str) { return Core::aToVector4 (str.c_str ()); } -glm::vec3 Core::aToVector3 (const std::string& str) -{ +glm::vec3 Core::aToVector3 (const std::string& str) { return Core::aToVector3 (str.c_str ()); } -glm::vec2 Core::aToVector2 (const std::string& str) -{ +glm::vec2 Core::aToVector2 (const std::string& str) { return Core::aToVector2 (str.c_str ()); } -glm::vec3 Core::aToColorf (const char* str) -{ - float r = strtof (str, const_cast(&str)); while (*str == ' ') str ++; - float g = strtof (str, const_cast(&str)); while (*str == ' ') str ++; - float b = strtof (str, const_cast(&str)); +glm::vec3 Core::aToColorf (const char* str) { + float r = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float g = strtof (str, const_cast (&str)); + while (*str == ' ') + str++; + float b = strtof (str, const_cast (&str)); return {r, g, b}; } -glm::vec3 Core::aToColorf (const std::string& str) -{ +glm::vec3 Core::aToColorf (const std::string& str) { return aToColorf (str.c_str ()); } -glm::ivec3 Core::aToColori (const char* str) -{ - auto r = static_cast (strtol (str, const_cast(&str), 10)); while (*str == ' ') str ++; - auto g = static_cast (strtol (str, const_cast(&str), 10)); while (*str == ' ') str ++; - auto b = static_cast (strtol (str, const_cast(&str), 10)); +glm::ivec3 Core::aToColori (const char* str) { + auto r = static_cast (strtol (str, const_cast (&str), 10)); + while (*str == ' ') + str++; + auto g = static_cast (strtol (str, const_cast (&str), 10)); + while (*str == ' ') + str++; + auto b = static_cast (strtol (str, const_cast (&str), 10)); return {r, g, b}; } -glm::ivec3 Core::aToColori (const std::string& str) -{ +glm::ivec3 Core::aToColori (const std::string& str) { return aToColori (str.c_str ()); } -nlohmann::json::iterator Core::jsonFindRequired (nlohmann::json& data, const char *key, const char *notFoundMsg) -{ +nlohmann::json::iterator Core::jsonFindRequired (nlohmann::json& data, const char* key, const char* notFoundMsg) { auto value = data.find (key); if (value == data.end ()) @@ -89,41 +98,34 @@ nlohmann::json::iterator Core::jsonFindRequired (nlohmann::json& data, const cha return value; } -nlohmann::json::iterator Core::jsonFindRequired (nlohmann::json::iterator& data, const char *key, const char *notFoundMsg) -{ - auto value = (*data).find (key); +nlohmann::json::iterator Core::jsonFindRequired (const nlohmann::json::iterator& data, const char* key, + const char* notFoundMsg) { + auto value = data->find (key); - if (value == (*data).end ()) + if (value == data->end ()) sLog.exception ("Cannot find required key (", key, ") in json: ", notFoundMsg); return value; } -template T Core::jsonFindDefault (nlohmann::json& data, const char *key, T defaultValue) -{ - auto value = data.find (key); +template T Core::jsonFindDefault (nlohmann::json& data, const char* key, T defaultValue) { + const auto value = data.find (key); if (value == data.end () || value->type () == nlohmann::detail::value_t::null) return defaultValue; // type checks - if ((std::is_same ::value || std::is_same ::value)) - { + if ((std::is_same_v || std::is_same_v) ) { if (value->type () != nlohmann::detail::value_t::number_float && value->type () != nlohmann::detail::value_t::number_integer && - value->type () != nlohmann::detail::value_t::number_unsigned) - { + value->type () != nlohmann::detail::value_t::number_unsigned) { sLog.error (key, " is not of type double or integer, returning default value"); return defaultValue; } - } - else if (std::is_same ::value && value->type () != nlohmann::detail::value_t::string) - { + } else if (std::is_same_v && value->type () != nlohmann::detail::value_t::string) { sLog.error (key, " is not of type string, returning default value"); return defaultValue; - } - else if (std::is_same ::value && value->type () != nlohmann::detail::value_t::boolean) - { + } else if (std::is_same_v && value->type () != nlohmann::detail::value_t::boolean) { sLog.error (key, " is not of type boolean, returning default value"); return defaultValue; } @@ -133,20 +135,20 @@ template T Core::jsonFindDefault (nlohmann::json& data, const char return *value; } -template bool Core::jsonFindDefault (nlohmann::json& data, const char *key, bool defaultValue); -template std::string Core::jsonFindDefault (nlohmann::json& data, const char *key, std::string defaultValue); -template int16_t Core::jsonFindDefault (nlohmann::json& data, const char *key, int16_t defaultValue); -template uint16_t Core::jsonFindDefault (nlohmann::json& data, const char *key, uint16_t defaultValue); -template int32_t Core::jsonFindDefault (nlohmann::json& data, const char *key, int32_t defaultValue); -template uint32_t Core::jsonFindDefault (nlohmann::json& data, const char *key, uint32_t defaultValue); -template int64_t Core::jsonFindDefault (nlohmann::json& data, const char *key, int64_t defaultValue); -template uint64_t Core::jsonFindDefault (nlohmann::json& data, const char *key, uint64_t defaultValue); -template float Core::jsonFindDefault (nlohmann::json& data, const char *key, float defaultValue); -template double Core::jsonFindDefault (nlohmann::json& data, const char *key, double defaultValue); +template bool Core::jsonFindDefault (nlohmann::json& data, const char* key, bool defaultValue); +template std::string Core::jsonFindDefault (nlohmann::json& data, const char* key, std::string defaultValue); +template int16_t Core::jsonFindDefault (nlohmann::json& data, const char* key, int16_t defaultValue); +template uint16_t Core::jsonFindDefault (nlohmann::json& data, const char* key, uint16_t defaultValue); +template int32_t Core::jsonFindDefault (nlohmann::json& data, const char* key, int32_t defaultValue); +template uint32_t Core::jsonFindDefault (nlohmann::json& data, const char* key, uint32_t defaultValue); +template int64_t Core::jsonFindDefault (nlohmann::json& data, const char* key, int64_t defaultValue); +template uint64_t Core::jsonFindDefault (nlohmann::json& data, const char* key, uint64_t defaultValue); +template float Core::jsonFindDefault (nlohmann::json& data, const char* key, float defaultValue); +template double Core::jsonFindDefault (nlohmann::json& data, const char* key, double defaultValue); -template T* Core::jsonFindUserConfig (nlohmann::json& data, const char *key, typename T::data_type defaultValue) -{ - auto it = data.find (key); +template +T* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, typename T::data_type defaultValue) { + const auto it = data.find (key); if (it == data.end () || it->type () == nlohmann::detail::value_t::null) return T::fromScalar (defaultValue); @@ -154,6 +156,9 @@ template T* Core::jsonFindUserConfig (nlohmann::json& data, const c return T::fromJSON (*it); } -template CUserSettingBoolean* Core::jsonFindUserConfig (nlohmann::json& data, const char *key, CUserSettingBoolean::data_type defaultValue); -template CUserSettingVector3* Core::jsonFindUserConfig (nlohmann::json& data, const char *key, CUserSettingVector3::data_type defaultValue); -template CUserSettingFloat* Core::jsonFindUserConfig (nlohmann::json& data, const char *key, CUserSettingFloat::data_type defaultValue); \ No newline at end of file +template CUserSettingBoolean* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, + CUserSettingBoolean::data_type defaultValue); +template CUserSettingVector3* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, + CUserSettingVector3::data_type defaultValue); +template CUserSettingFloat* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, + CUserSettingFloat::data_type defaultValue); \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Core.h b/src/WallpaperEngine/Core/Core.h index 3f4f6f4..e0c9689 100644 --- a/src/WallpaperEngine/Core/Core.h +++ b/src/WallpaperEngine/Core/Core.h @@ -1,29 +1,29 @@ #pragma once -#include -#include -#include -#include #include +#include +#include +#include +#include -namespace WallpaperEngine::Core -{ - glm::vec4 aToVector4 (const char* str); - glm::vec3 aToVector3 (const char* str); - glm::vec2 aToVector2 (const char* str); +namespace WallpaperEngine::Core { +glm::vec4 aToVector4 (const char* str); +glm::vec3 aToVector3 (const char* str); +glm::vec2 aToVector2 (const char* str); - glm::vec4 aToVector4 (const std::string& str); - glm::vec3 aToVector3 (const std::string& str); - glm::vec2 aToVector2 (const std::string& str); +glm::vec4 aToVector4 (const std::string& str); +glm::vec3 aToVector3 (const std::string& str); +glm::vec2 aToVector2 (const std::string& str); - glm::vec3 aToColorf (const char* str); - glm::vec3 aToColorf (const std::string& str); +glm::vec3 aToColorf (const char* str); +glm::vec3 aToColorf (const std::string& str); - glm::ivec3 aToColori (const char* str); - glm::ivec3 aToColori (const std::string& str); +glm::ivec3 aToColori (const char* str); +glm::ivec3 aToColori (const std::string& str); - nlohmann::json::iterator jsonFindRequired (nlohmann::json& data, const char *key, const char *notFoundMsg); - nlohmann::json::iterator jsonFindRequired (nlohmann::json::iterator& data, const char *key, const char *notFoundMsg); - template T jsonFindDefault (nlohmann::json& data, const char *key, T defaultValue); - template T* jsonFindUserConfig (nlohmann::json& data, const char *key, typename T::data_type defaultValue); -} +nlohmann::json::iterator jsonFindRequired (nlohmann::json& data, const char* key, const char* notFoundMsg); +nlohmann::json::iterator jsonFindRequired (const nlohmann::json::iterator& data, const char* key, + const char* notFoundMsg); +template T jsonFindDefault (nlohmann::json& data, const char* key, T defaultValue); +template T* jsonFindUserConfig (nlohmann::json& data, const char* key, typename T::data_type defaultValue); +} // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/Objects/CEffect.cpp b/src/WallpaperEngine/Core/Objects/CEffect.cpp index 5ad29be..5e2e65d 100644 --- a/src/WallpaperEngine/Core/Objects/CEffect.cpp +++ b/src/WallpaperEngine/Core/Objects/CEffect.cpp @@ -1,16 +1,16 @@ -#include "common.h" #include "CEffect.h" +#include "common.h" -#include #include +#include -#include "WallpaperEngine/Core/CScene.h" #include "WallpaperEngine/Core/CProject.h" +#include "WallpaperEngine/Core/CScene.h" #include "WallpaperEngine/Core/Objects/CImage.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h" -#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" @@ -20,45 +20,30 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Core::Objects; using namespace WallpaperEngine::Core::UserSettings; -CEffect::CEffect ( - std::string name, - std::string description, - std::string group, - std::string preview, - CObject* object, - CUserSettingBoolean* visible): - m_name (std::move(name)), - m_description (std::move(description)), - m_group (std::move(group)), - m_preview (std::move(preview)), +CEffect::CEffect (std::string name, std::string description, std::string group, std::string preview, CObject* object, + CUserSettingBoolean* visible) : + m_name (std::move (name)), + m_description (std::move (description)), + m_group (std::move (group)), + m_preview (std::move (preview)), m_object (object), - m_visible (visible) -{ -} + m_visible (visible) {} -CEffect* CEffect::fromJSON (json data, CUserSettingBoolean* visible, CObject* object, CContainer* container) -{ +CEffect* CEffect::fromJSON (json data, CUserSettingBoolean* visible, CObject* object, CContainer* container) { auto file_it = jsonFindRequired (data, "file", "Object effect must have a file"); auto effectpasses_it = data.find ("passes"); - json content = json::parse (WallpaperEngine::FileSystem::loadFullFile ((*file_it).get (), container)); + json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (file_it->get (), container)); auto name_it = jsonFindRequired (content, "name", "Effect must have a name"); - auto description = jsonFindDefault (content, "description", ""); + auto description = jsonFindDefault (content, "description", ""); auto group_it = jsonFindRequired (content, "group", "Effect must have a group"); - auto preview = jsonFindDefault (content, "preview", ""); + auto preview = jsonFindDefault (content, "preview", ""); auto passes_it = jsonFindRequired (content, "passes", "Effect must have a pass list"); auto dependencies_it = jsonFindRequired (content, "dependencies", ""); auto fbos_it = content.find ("fbos"); - auto* effect = new CEffect ( - *name_it, - description, - *group_it, - preview, - object, - visible - ); + auto* effect = new CEffect (*name_it, description, *group_it, preview, object, visible); CEffect::materialsFromJSON (passes_it, effect, container); CEffect::dependencyFromJSON (dependencies_it, effect); @@ -66,47 +51,36 @@ CEffect* CEffect::fromJSON (json data, CUserSettingBoolean* visible, CObject* ob if (fbos_it != content.end ()) CEffect::fbosFromJSON (fbos_it, effect); - if (effectpasses_it != data.end ()) - { - auto cur = (*effectpasses_it).begin (); - auto end = (*effectpasses_it).end (); + if (effectpasses_it != data.end ()) { + auto cur = effectpasses_it->begin (); + auto end = effectpasses_it->end (); - for (int passNumber = 0; cur != end; cur ++, passNumber ++) - { - auto constants_it = (*cur).find ("constantshadervalues"); - auto combos_it = (*cur).find ("combos"); - auto textures_it = (*cur).find ("textures"); + for (int passNumber = 0; cur != end; ++cur, passNumber++) { + auto constants_it = cur->find ("constantshadervalues"); + auto combos_it = cur->find ("combos"); + auto textures_it = cur->find ("textures"); - if (constants_it == (*cur).end () && combos_it == (*cur).end () && textures_it == (*cur).end ()) + if (constants_it == cur->end () && combos_it == cur->end () && textures_it == cur->end ()) continue; Images::CMaterial* material = effect->getMaterials ().at (passNumber); - for (const auto& passCur : material->getPasses ()) - { - if (textures_it != (*cur).end ()) - { + for (const auto& passCur : material->getPasses ()) { + if (textures_it != cur->end ()) { int textureNumber = 0; - for (const auto& texturesCur : (*textures_it)) - { + for (const auto& texturesCur : (*textures_it)) { std::string texture; - if (texturesCur.is_null ()) - { - if (textureNumber == 0) - { - auto* image = object->as (); + if (texturesCur.is_null ()) { + if (textureNumber == 0) { + auto* image = object->as (); texture = (*(*image->getMaterial ()->getPasses ().begin ())->getTextures ().begin ()); - } - else - { + } else { texture = ""; } - } - else - { + } else { texture = texturesCur; } @@ -117,17 +91,15 @@ CEffect* CEffect::fromJSON (json data, CUserSettingBoolean* visible, CObject* ob else passCur->insertTexture (texture); - textureNumber ++; + textureNumber++; } } - if (combos_it != (*cur).end ()) - { + if (combos_it != cur->end ()) { CEffect::combosFromJSON (combos_it, passCur); } - if (constants_it != (*cur).end ()) - { + if (constants_it != cur->end ()) { CEffect::constantsFromJSON (constants_it, passCur); } } @@ -137,16 +109,14 @@ CEffect* CEffect::fromJSON (json data, CUserSettingBoolean* visible, CObject* ob return effect; } -void CEffect::combosFromJSON (json::const_iterator combos_it, Core::Objects::Images::Materials::CPass* pass) -{ - for (const auto& cur : (*combos_it).items ()) +void CEffect::combosFromJSON (const json::const_iterator& combos_it, Core::Objects::Images::Materials::CPass* pass) { + for (const auto& cur : combos_it->items ()) pass->insertCombo (cur.key (), cur.value ()); } -void CEffect::constantsFromJSON (json::const_iterator constants_it, Core::Objects::Images::Materials::CPass* pass) -{ - for (auto& cur : (*constants_it).items ()) - { +void CEffect::constantsFromJSON (const json::const_iterator& constants_it, + Core::Objects::Images::Materials::CPass* pass) { + for (auto& cur : constants_it->items ()) { auto val = cur.value (); Effects::Constants::CShaderConstant* constant; @@ -155,12 +125,10 @@ void CEffect::constantsFromJSON (json::const_iterator constants_it, Core::Object // for the UI, take the value, which is what we need // TODO: SUPPORT USER SETTINGS HERE - if (cur.value ().is_object ()) - { + if (cur.value ().is_object ()) { auto it = cur.value ().find ("value"); - if (it == cur.value ().end ()) - { + if (it == cur.value ().end ()) { sLog.error ("Found object for shader constant without \"value\" member"); continue; } @@ -168,21 +136,14 @@ void CEffect::constantsFromJSON (json::const_iterator constants_it, Core::Object val = it.value (); } - if (val.is_number_float ()) - { - constant = new Effects::Constants::CShaderConstantFloat (val.get ()); - } - else if (val.is_number_integer ()) - { - constant = new Effects::Constants::CShaderConstantInteger (val.get ()); - } - else if (val.is_string ()) - { + if (val.is_number_float ()) { + constant = new Effects::Constants::CShaderConstantFloat (val.get ()); + } else if (val.is_number_integer ()) { + constant = new Effects::Constants::CShaderConstantInteger (val.get ()); + } else if (val.is_string ()) { // try a vector 4 first, then a vector3 and then a vector 2 constant = new Effects::Constants::CShaderConstantVector4 (WallpaperEngine::Core::aToVector4 (val)); - } - else - { + } else { sLog.exception ("unknown shader constant type ", val); } @@ -190,22 +151,18 @@ void CEffect::constantsFromJSON (json::const_iterator constants_it, Core::Object } } -void CEffect::fbosFromJSON (json::const_iterator fbos_it, CEffect* effect) -{ +void CEffect::fbosFromJSON (const json::const_iterator& fbos_it, CEffect* effect) { for (const auto& cur : (*fbos_it)) effect->insertFBO (Effects::CFBO::fromJSON (cur)); } -void CEffect::dependencyFromJSON (json::const_iterator dependencies_it, CEffect* effect) -{ +void CEffect::dependencyFromJSON (const json::const_iterator& dependencies_it, CEffect* effect) { for (const auto& cur : (*dependencies_it)) effect->insertDependency (cur); } -void CEffect::materialsFromJSON (json::const_iterator passes_it, CEffect* effect, CContainer* container) -{ - for (const auto& cur : (*passes_it)) - { +void CEffect::materialsFromJSON (const json::const_iterator& passes_it, CEffect* effect, CContainer* container) { + for (const auto& cur : (*passes_it)) { auto materialfile = cur.find ("material"); auto target = cur.find ("target"); auto bind = cur.find ("bind"); @@ -216,12 +173,11 @@ void CEffect::materialsFromJSON (json::const_iterator passes_it, CEffect* effect Images::CMaterial* material; if (target == cur.end ()) - material = Images::CMaterial::fromFile ((*materialfile).get (), container); + material = Images::CMaterial::fromFile (materialfile->get (), container); else - material = Images::CMaterial::fromFile ((*materialfile).get (), *target, container); + material = Images::CMaterial::fromFile (materialfile->get (), *target, container); - if (bind != cur.end ()) - { + if (bind != cur.end ()) { for (const auto& bindCur : (*bind)) material->insertTextureBind (Effects::CBind::fromJSON (bindCur)); } @@ -230,28 +186,23 @@ void CEffect::materialsFromJSON (json::const_iterator passes_it, CEffect* effect } } -const std::vector& CEffect::getDependencies () const -{ +const std::vector& CEffect::getDependencies () const { return this->m_dependencies; } -const std::vector& CEffect::getMaterials () const -{ +const std::vector& CEffect::getMaterials () const { return this->m_materials; } -const std::vector& CEffect::getFbos () const -{ +const std::vector& CEffect::getFbos () const { return this->m_fbos; } -bool CEffect::isVisible () const -{ +bool CEffect::isVisible () const { return this->m_visible->processValue (this->m_object->getScene ()->getProject ().getProperties ()); } -Effects::CFBO* CEffect::findFBO (const std::string& name) -{ +Effects::CFBO* CEffect::findFBO (const std::string& name) { for (const auto& cur : this->m_fbos) if (cur->getName () == name) return cur; @@ -259,17 +210,14 @@ Effects::CFBO* CEffect::findFBO (const std::string& name) sLog.exception ("cannot find fbo ", name); } -void CEffect::insertDependency (const std::string& dep) -{ +void CEffect::insertDependency (const std::string& dep) { this->m_dependencies.push_back (dep); } -void CEffect::insertMaterial (Images::CMaterial* material) -{ +void CEffect::insertMaterial (Images::CMaterial* material) { this->m_materials.push_back (material); } -void CEffect::insertFBO (Effects::CFBO* fbo) -{ +void CEffect::insertFBO (Effects::CFBO* fbo) { this->m_fbos.push_back (fbo); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/CEffect.h b/src/WallpaperEngine/Core/Objects/CEffect.h index 9decf01..e9210ff 100644 --- a/src/WallpaperEngine/Core/Objects/CEffect.h +++ b/src/WallpaperEngine/Core/Objects/CEffect.h @@ -1,99 +1,92 @@ #pragma once +#include "WallpaperEngine/Assets/CContainer.h" +#include "WallpaperEngine/Core/CObject.h" #include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/Objects/Effects/CFBO.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" -#include "WallpaperEngine/Core/CObject.h" #include "WallpaperEngine/Core/Objects/Images/CMaterial.h" -#include "WallpaperEngine/Assets/CContainer.h" -namespace WallpaperEngine::Core -{ - class CObject; +namespace WallpaperEngine::Core { +class CObject; } -namespace WallpaperEngine::Core::UserSettings -{ - class CUserSettingBoolean; +namespace WallpaperEngine::Core::UserSettings { +class CUserSettingBoolean; } -namespace WallpaperEngine::Core::Objects -{ - using json = nlohmann::json; - using namespace WallpaperEngine::Assets; - using namespace WallpaperEngine::Core::UserSettings; +namespace WallpaperEngine::Core::Objects { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Core::UserSettings; + +/** + * Represents an effect applied to background objects + */ +class CEffect { + public: + CEffect (std::string name, std::string description, std::string group, std::string preview, CObject* object, + CUserSettingBoolean* visible); + + static CEffect* fromJSON (json data, UserSettings::CUserSettingBoolean* visible, CObject* object, + CContainer* container); /** - * Represents an effect applied to background objects + * @return List of dependencies for the effect to work */ - class CEffect - { - public: - CEffect ( - std::string name, - std::string description, - std::string group, - std::string preview, - CObject* object, - CUserSettingBoolean* visible - ); + [[nodiscard]] const std::vector& getDependencies () const; + /** + * @return List of materials the effect applies + */ + [[nodiscard]] const std::vector& getMaterials () const; + /** + * @return The list of FBOs to be used for this effect + */ + [[nodiscard]] const std::vector& getFbos () const; + /** + * @return If the effect is visible or not + */ + [[nodiscard]] bool isVisible () const; + /** + * Searches the FBOs list for the given FBO + * + * @param name The FBO to search for + * + * @return + */ + Effects::CFBO* findFBO (const std::string& name); - static CEffect* fromJSON (json data, UserSettings::CUserSettingBoolean* visible, CObject* object, CContainer* container); + protected: + static void constantsFromJSON (const json::const_iterator& constants_it, + Core::Objects::Images::Materials::CPass* pass); + static void combosFromJSON (const json::const_iterator& combos_it, Core::Objects::Images::Materials::CPass* pass); + static void fbosFromJSON (const json::const_iterator& fbos_it, CEffect* effect); + static void dependencyFromJSON (const json::const_iterator& dependencies_it, CEffect* effect); + static void materialsFromJSON (const json::const_iterator& passes_it, CEffect* effect, CContainer* container); - /** - * @return List of dependencies for the effect to work - */ - [[nodiscard]] const std::vector& getDependencies () const; - /** - * @return List of materials the effect applies - */ - [[nodiscard]] const std::vector& getMaterials () const; - /** - * @return The list of FBOs to be used for this effect - */ - [[nodiscard]] const std::vector& getFbos () const; - /** - * @return If the effect is visible or not - */ - [[nodiscard]] bool isVisible () const; - /** - * Searches the FBOs list for the given FBO - * - * @param name The FBO to search for - * - * @return - */ - Effects::CFBO* findFBO (const std::string& name); - protected: - static void constantsFromJSON (json::const_iterator constants_it, Core::Objects::Images::Materials::CPass* pass); - static void combosFromJSON (json::const_iterator combos_it, Core::Objects::Images::Materials::CPass* pass); - static void fbosFromJSON (json::const_iterator fbos_it, CEffect* effect); - static void dependencyFromJSON (json::const_iterator dependencies_it, CEffect* effect); - static void materialsFromJSON (json::const_iterator passes_it, CEffect* effect, CContainer* container); + void insertDependency (const std::string& dep); + void insertMaterial (Images::CMaterial* material); + void insertFBO (Effects::CFBO* fbo); - void insertDependency (const std::string& dep); - void insertMaterial (Images::CMaterial* material); - void insertFBO (Effects::CFBO* fbo); + private: + /** Effect's name */ + std::string m_name; + /** Effect's description used in the UI */ + std::string m_description; + /** Effect's group used in the UI */ + std::string m_group; + /** A project that previews the given effect, used in the UI */ + std::string m_preview; + /** The object the effect applies to */ + CObject* m_object; + /** If the effect is visible or not */ + UserSettings::CUserSettingBoolean* m_visible; - private: - /** Effect's name */ - std::string m_name; - /** Effect's description used in the UI */ - std::string m_description; - /** Effect's group used in the UI */ - std::string m_group; - /** A project that previews the given effect, used in the UI */ - std::string m_preview; - /** The object the effect applies to */ - CObject* m_object; - /** If the effect is visible or not */ - UserSettings::CUserSettingBoolean* m_visible; - - /** List of dependencies for the effect */ - std::vector m_dependencies; - /** List of materials the effect applies */ - std::vector m_materials; - /** List of FBOs required for this effect */ - std::vector m_fbos; - }; -} + /** List of dependencies for the effect */ + std::vector m_dependencies; + /** List of materials the effect applies */ + std::vector m_materials; + /** List of FBOs required for this effect */ + std::vector m_fbos; +}; +} // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/CImage.cpp b/src/WallpaperEngine/Core/Objects/CImage.cpp index 1e8b158..4ec48b8 100644 --- a/src/WallpaperEngine/Core/Objects/CImage.cpp +++ b/src/WallpaperEngine/Core/Objects/CImage.cpp @@ -12,143 +12,91 @@ using namespace WallpaperEngine::Core::Objects; using namespace WallpaperEngine::Core::UserSettings; -CImage::CImage ( - CScene* scene, - Images::CMaterial* material, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles, - const glm::vec2& size, - std::string alignment, - CUserSettingVector3* color, - CUserSettingFloat* alpha, - float brightness, - uint32_t colorBlendMode, - const glm::vec2& parallaxDepth, - bool fullscreen, - bool passthrough, - bool autosize -) : - CObject (scene, visible, id, std::move(name), Type, origin, scale, angles), +CImage::CImage (CScene* scene, Images::CMaterial* material, CUserSettingBoolean* visible, uint32_t id, std::string name, + CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles, const glm::vec2& size, + std::string alignment, CUserSettingVector3* color, CUserSettingFloat* alpha, float brightness, + uint32_t colorBlendMode, const glm::vec2& parallaxDepth, bool fullscreen, bool passthrough, + bool autosize) : + CObject (scene, visible, id, std::move (name), Type, origin, scale, angles), m_size (size), m_material (material), - m_alignment (std::move(alignment)), + m_alignment (std::move (alignment)), m_color (color), m_alpha (alpha), m_brightness (brightness), m_colorBlendMode (colorBlendMode), - m_parallaxDepth(parallaxDepth), + m_parallaxDepth (parallaxDepth), m_fullscreen (fullscreen), m_passthrough (passthrough), - m_autosize (autosize) -{ + m_autosize (autosize) {} + +WallpaperEngine::Core::CObject* CImage::fromJSON (CScene* scene, json data, CContainer* container, + CUserSettingBoolean* visible, uint32_t id, std::string name, + CUserSettingVector3* origin, CUserSettingVector3* scale, + const glm::vec3& angles) { + const auto image_it = data.find ("image"); + const auto size_val = jsonFindDefault (data, "size", "0.0 0.0"); // this one might need some adjustment + const auto alignment = jsonFindDefault (data, "alignment", "center"); + const auto alpha = jsonFindUserConfig (data, "alpha", 1.0); + const auto color = jsonFindUserConfig (data, "color", {1, 1, 1}); + const auto brightness_val = jsonFindDefault (data, "brightness", 1.0); + const auto colorBlendMode_val = jsonFindDefault (data, "colorBlendMode", 0); + const auto parallaxDepth_val = jsonFindDefault (data, "parallaxDepth", "0 0"); + + json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (image_it->get (), container)); + + const auto material_it = jsonFindRequired (content, "material", "Image must have a material"); + const auto fullscreen = jsonFindDefault (content, "fullscreen", false); + const auto passthrough = jsonFindDefault (content, "passthrough", false); + const auto autosize = jsonFindDefault (content, "autosize", false); + + return new CImage (scene, Images::CMaterial::fromFile (material_it->get (), container), visible, id, + std::move (name), origin, scale, angles, WallpaperEngine::Core::aToVector2 (size_val), alignment, + color, alpha, brightness_val, colorBlendMode_val, + WallpaperEngine::Core::aToVector2 (parallaxDepth_val), fullscreen, passthrough, autosize); } -WallpaperEngine::Core::CObject* CImage::fromJSON ( - CScene* scene, - json data, - CContainer* container, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles) -{ - auto image_it = data.find ("image"); - auto size_val = jsonFindDefault (data, "size", "0.0 0.0"); // this one might need some adjustment - auto alignment = jsonFindDefault (data, "alignment", "center"); - auto alpha = jsonFindUserConfig (data, "alpha", 1.0); - auto color = jsonFindUserConfig (data, "color", {1, 1, 1}); - auto brightness_val = jsonFindDefault (data, "brightness", 1.0); - auto colorBlendMode_val = jsonFindDefault (data, "colorBlendMode", 0); - auto parallaxDepth_val = jsonFindDefault (data, "parallaxDepth", "0 0"); - - json content = json::parse (WallpaperEngine::FileSystem::loadFullFile ((*image_it).get (), container)); - - auto material_it = jsonFindRequired (content, "material", "Image must have a material"); - auto fullscreen = jsonFindDefault (content, "fullscreen", false); - auto passthrough = jsonFindDefault (content, "passthrough", false); - auto autosize = jsonFindDefault (content, "autosize", false); - - return new CImage ( - scene, - Images::CMaterial::fromFile ((*material_it).get (), container), - visible, - id, - std::move(name), - origin, - scale, - angles, - WallpaperEngine::Core::aToVector2 (size_val), - alignment, - color, - alpha, - brightness_val, - colorBlendMode_val, - WallpaperEngine::Core::aToVector2 (parallaxDepth_val), - fullscreen, - passthrough, - autosize - ); -} - -const Images::CMaterial* CImage::getMaterial () const -{ +const Images::CMaterial* CImage::getMaterial () const { return this->m_material; } -const glm::vec2& CImage::getSize () const -{ +const glm::vec2& CImage::getSize () const { return this->m_size; } -const std::string& CImage::getAlignment () const -{ +const std::string& CImage::getAlignment () const { return this->m_alignment; } -float CImage::getAlpha () const -{ +float CImage::getAlpha () const { return this->m_alpha->processValue (this->getScene ()->getProject ().getProperties ()); } -glm::vec3 CImage::getColor () const -{ +glm::vec3 CImage::getColor () const { return this->m_color->processValue (this->getScene ()->getProject ().getProperties ()); } -float CImage::getBrightness () const -{ +float CImage::getBrightness () const { return this->m_brightness; } -uint32_t CImage::getColorBlendMode () const -{ +uint32_t CImage::getColorBlendMode () const { return this->m_colorBlendMode; } - -const glm::vec2& CImage::getParallaxDepth () const -{ +const glm::vec2& CImage::getParallaxDepth () const { return this->m_parallaxDepth; } -bool CImage::isFullscreen () const -{ +bool CImage::isFullscreen () const { return this->m_fullscreen; } -bool CImage::isPassthrough () const -{ +bool CImage::isPassthrough () const { return this->m_passthrough; } -bool CImage::isAutosize () const -{ +bool CImage::isAutosize () const { return this->m_autosize; } diff --git a/src/WallpaperEngine/Core/Objects/CImage.h b/src/WallpaperEngine/Core/Objects/CImage.h index 199fb0b..a5e72c3 100644 --- a/src/WallpaperEngine/Core/Objects/CImage.h +++ b/src/WallpaperEngine/Core/Objects/CImage.h @@ -2,8 +2,8 @@ #include "WallpaperEngine/Core/Objects/Images/CMaterial.h" -#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/CObject.h" +#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Assets/CContainer.h" @@ -11,109 +11,104 @@ #include "WallpaperEngine/Core/UserSettings/CUserSettingFloat.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingVector3.h" -namespace WallpaperEngine::Core -{ - class CScene; +namespace WallpaperEngine::Core { +class CScene; } -namespace WallpaperEngine::Core::Objects -{ - using json = nlohmann::json; - using namespace WallpaperEngine::Assets; - using namespace WallpaperEngine::Core::UserSettings; +namespace WallpaperEngine::Core::Objects { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Core::UserSettings; + +/** + * Represents an image in a background + */ +class CImage : public CObject { + friend class CObject; + + public: + static CObject* fromJSON (CScene* scene, json data, CContainer* container, CUserSettingBoolean* visible, + uint32_t id, std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale, + const glm::vec3& angles); /** - * Represents an image in a background + * @return The base material to use for the image */ - class CImage : public CObject - { - friend class CObject; - public: - static CObject* fromJSON ( - CScene* scene, json data, CContainer* container, CUserSettingBoolean* visible, uint32_t id, - std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles - ); + [[nodiscard]] const Images::CMaterial* getMaterial () const; + /** + * @return The size of the image + */ + [[nodiscard]] const glm::vec2& getSize () const; + /** + * @return The type of alignment to use for image positioning + */ + [[nodiscard]] const std::string& getAlignment () const; + /** + * @return The alpha value for the image's rendering + */ + [[nodiscard]] float getAlpha () const; + /** + * @return The color to use for the image + */ + [[nodiscard]] glm::vec3 getColor () const; + /** + * @return The brightness to use for the image + */ + [[nodiscard]] float getBrightness () const; + /** + * @return The color blending mode to be used, special value for shaders + */ + [[nodiscard]] uint32_t getColorBlendMode () const; + /** + * @return Parallax depth of the image + */ + [[nodiscard]] const glm::vec2& getParallaxDepth () const; + /** + * @return If the image is fullscreen or not + */ + [[nodiscard]] bool isFullscreen () const; + /** + * @return If the image is passthrough or not + */ + [[nodiscard]] bool isPassthrough () const; + /** + * @return If the image is autosized or not + */ + [[nodiscard]] bool isAutosize () const; - /** - * @return The base material to use for the image - */ - [[nodiscard]] const Images::CMaterial* getMaterial () const; - /** - * @return The size of the image - */ - [[nodiscard]] const glm::vec2& getSize () const; - /** - * @return The type of alignment to use for image positioning - */ - [[nodiscard]] const std::string& getAlignment () const; - /** - * @return The alpha value for the image's rendering - */ - [[nodiscard]] float getAlpha () const; - /** - * @return The color to use for the image - */ - [[nodiscard]] glm::vec3 getColor () const; - /** - * @return The brightness to use for the image - */ - [[nodiscard]] float getBrightness () const; - /** - * @return The color blending mode to be used, special value for shaders - */ - [[nodiscard]] uint32_t getColorBlendMode () const; - /** - * @return Parallax depth of the image - */ - [[nodiscard]] const glm::vec2& getParallaxDepth () const; - /** - * @return If the image is fullscreen or not - */ - [[nodiscard]] bool isFullscreen () const; - /** - * @return If the image is passthrough or not - */ - [[nodiscard]] bool isPassthrough () const; - /** - * @return If the image is autosized or not - */ - [[nodiscard]] bool isAutosize () const; - - protected: - CImage ( - CScene* scene, Images::CMaterial* material, CUserSettingBoolean* visible, uint32_t id, std::string name, + protected: + CImage (CScene* scene, Images::CMaterial* material, CUserSettingBoolean* visible, uint32_t id, std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles, const glm::vec2& size, std::string alignment, CUserSettingVector3* color, CUserSettingFloat* alpha, float brightness, - uint32_t colorBlendMode, const glm::vec2& parallaxDepth, bool fullscreen, bool passthrough, bool autosize - ); + uint32_t colorBlendMode, const glm::vec2& parallaxDepth, bool fullscreen, bool passthrough, bool autosize); - /** - * Type value used to differentiate the different types of objects in a background - */ - static const std::string Type; + /** + * Type value used to differentiate the different types of objects in a background + */ + static const std::string Type; - private: - /** The image's size */ - glm::vec2 m_size; - /** Parallax depth */ - const glm::vec2 m_parallaxDepth; - /** Base material for the image */ - Images::CMaterial* m_material; - /** What type of alignment to use for the image's position */ - std::string m_alignment; - /** The alpha value for the image */ - CUserSettingFloat* m_alpha; - /** The brightness for the image */ - float m_brightness; - /** The color to use for the image */ - CUserSettingVector3* m_color; - /** The color blending mode used for the image, special value for shaders */ - uint32_t m_colorBlendMode; - /** If the image is fullscreen or not */ - bool m_fullscreen; - /** If the image is passthrough or not */ - bool m_passthrough; - /** If the image's size should be automatically determined */ - bool m_autosize; - }; -} + private: + /** The image's size */ + glm::vec2 m_size; + /** Parallax depth */ + const glm::vec2 m_parallaxDepth; + /** Base material for the image */ + Images::CMaterial* m_material; + /** What type of alignment to use for the image's position */ + std::string m_alignment; + /** The alpha value for the image */ + CUserSettingFloat* m_alpha; + /** The brightness for the image */ + float m_brightness; + /** The color to use for the image */ + CUserSettingVector3* m_color; + /** The color blending mode used for the image, special value for shaders */ + uint32_t m_colorBlendMode; + /** If the image is fullscreen or not */ + bool m_fullscreen; + /** If the image is passthrough or not */ + bool m_passthrough; + /** If the image's size should be automatically determined */ + bool m_autosize; +}; +} // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/CParticle.cpp b/src/WallpaperEngine/Core/Objects/CParticle.cpp index dec4c17..c988462 100644 --- a/src/WallpaperEngine/Core/Objects/CParticle.cpp +++ b/src/WallpaperEngine/Core/Objects/CParticle.cpp @@ -1,37 +1,21 @@ #include "CParticle.h" -#include #include "WallpaperEngine/FileSystem/FileSystem.h" +#include using namespace WallpaperEngine::Core::Objects; -CParticle* CParticle::fromFile ( - CScene* scene, - const std::string& filename, - CContainer* container, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale) -{ +CParticle* CParticle::fromFile (CScene* scene, const std::string& filename, CContainer* container, + CUserSettingBoolean* visible, uint32_t id, std::string name, + CUserSettingVector3* origin, CUserSettingVector3* scale) { json data = json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)); - auto controlpoint_it = data.find ("controlpoint"); - auto starttime_it = jsonFindRequired (data, "starttime", "Particles must have start time"); - auto maxcount_it = jsonFindRequired (data, "maxcount", "Particles must have maximum count"); - auto emitter_it = jsonFindRequired (data, "emitter", "Particles must have emitters"); - auto initializer_it = jsonFindRequired (data, "initializer", "Particles must have initializers"); + const auto controlpoint_it = data.find ("controlpoint"); + const auto starttime_it = jsonFindRequired (data, "starttime", "Particles must have start time"); + const auto maxcount_it = jsonFindRequired (data, "maxcount", "Particles must have maximum count"); + const auto emitter_it = jsonFindRequired (data, "emitter", "Particles must have emitters"); + const auto initializer_it = jsonFindRequired (data, "initializer", "Particles must have initializers"); - auto* particle = new CParticle ( - scene, - *starttime_it, - *maxcount_it, - visible, - id, - std::move(name), - origin, - scale - ); + auto* particle = new CParticle (scene, *starttime_it, *maxcount_it, visible, id, std::move (name), origin, scale); if (controlpoint_it != data.end ()) for (const auto& cur : (*controlpoint_it)) @@ -39,54 +23,39 @@ CParticle* CParticle::fromFile ( for (const auto& cur : (*emitter_it)) particle->insertEmitter (Particles::CEmitter::fromJSON (cur)); - for (const auto&cur : (*initializer_it)) + for (const auto& cur : (*initializer_it)) particle->insertInitializer (Particles::CInitializer::fromJSON (cur)); return particle; } -CParticle::CParticle ( - CScene* scene, - uint32_t starttime, - uint32_t maxcount, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale): - CObject (scene, visible, id, std::move(name), Type, origin, scale, glm::vec3 ()), +CParticle::CParticle (CScene* scene, uint32_t starttime, uint32_t maxcount, CUserSettingBoolean* visible, uint32_t id, + std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale) : + CObject (scene, visible, id, std::move (name), Type, origin, scale, glm::vec3 ()), m_starttime (starttime), - m_maxcount (maxcount) -{ -} + m_maxcount (maxcount) {} -const std::vector& CParticle::getEmitters () const -{ +const std::vector& CParticle::getEmitters () const { return this->m_emitters; } -const std::vector& CParticle::getControlPoints () const -{ +const std::vector& CParticle::getControlPoints () const { return this->m_controlpoints; } -const std::vector& CParticle::getInitializers () const -{ +const std::vector& CParticle::getInitializers () const { return this->m_initializers; } -void CParticle::insertControlPoint (Particles::CControlPoint* controlpoint) -{ +void CParticle::insertControlPoint (Particles::CControlPoint* controlpoint) { this->m_controlpoints.push_back (controlpoint); } -void CParticle::insertEmitter (Particles::CEmitter* emitter) -{ +void CParticle::insertEmitter (Particles::CEmitter* emitter) { this->m_emitters.push_back (emitter); } -void CParticle::insertInitializer (Particles::CInitializer* initializer) -{ +void CParticle::insertInitializer (Particles::CInitializer* initializer) { this->m_initializers.push_back (initializer); } diff --git a/src/WallpaperEngine/Core/Objects/CParticle.h b/src/WallpaperEngine/Core/Objects/CParticle.h index 5a0b10b..a235ede 100644 --- a/src/WallpaperEngine/Core/Objects/CParticle.h +++ b/src/WallpaperEngine/Core/Objects/CParticle.h @@ -4,85 +4,68 @@ #include "WallpaperEngine/Core/Objects/Particles/CEmitter.h" #include "WallpaperEngine/Core/Objects/Particles/CInitializer.h" -#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/CObject.h" +#include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Objects { +using json = nlohmann::json; + +/** + * Represents a particle system in the background + */ +class CParticle : public CObject { + friend class CObject; + + public: + static CParticle* fromFile (CScene* scene, const std::string& filename, CContainer* container, + CUserSettingBoolean* visible, uint32_t id, std::string name, + CUserSettingVector3* origin, CUserSettingVector3* scale); /** - * Represents a particle system in the background + * @return The list of emitters for the particle system */ - class CParticle : public CObject - { - friend class CObject; + [[nodiscard]] const std::vector& getEmitters () const; + /** + * @return The list of control points for the particle system + */ + [[nodiscard]] const std::vector& getControlPoints () const; + /** + * @return The list of initializers for the particle system + */ + [[nodiscard]] const std::vector& getInitializers () const; - public: - static CParticle* fromFile ( - CScene* scene, - const std::string& filename, - CContainer* container, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale - ); + protected: + CParticle (CScene* scene, uint32_t starttime, uint32_t maxcount, CUserSettingBoolean* visible, uint32_t id, + std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale); - /** - * @return The list of emitters for the particle system - */ - [[nodiscard]] const std::vector& getEmitters () const; - /** - * @return The list of control points for the particle system - */ - [[nodiscard]] const std::vector& getControlPoints () const; - /** - * @return The list of initializers for the particle system - */ - [[nodiscard]] const std::vector& getInitializers () const; + /** + * @param controlpoint The control point to add to the particle system + */ + void insertControlPoint (Particles::CControlPoint* controlpoint); + /** + * @param emitter The emitter to add to the particle system + */ + void insertEmitter (Particles::CEmitter* emitter); + /** + * @param initializer The initializer to add to the particle system + */ + void insertInitializer (Particles::CInitializer* initializer); - protected: - CParticle ( - CScene* scene, - uint32_t starttime, - uint32_t maxcount, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale - ); + /** + * Type value used to differentiate the different types of objects in a background + */ + static const std::string Type; - /** - * @param controlpoint The control point to add to the particle system - */ - void insertControlPoint (Particles::CControlPoint* controlpoint); - /** - * @param emitter The emitter to add to the particle system - */ - void insertEmitter (Particles::CEmitter* emitter); - /** - * @param initializer The initializer to add to the particle system - */ - void insertInitializer (Particles::CInitializer* initializer); - - /** - * Type value used to differentiate the different types of objects in a background - */ - static const std::string Type; - - private: - /** The time at which the particle system should start emitting */ - uint32_t m_starttime; - /** Maximum number of particles at the same time */ - uint32_t m_maxcount; - /** List of control points */ - std::vector m_controlpoints; - /** List of emitters */ - std::vector m_emitters; - /** List of initializers */ - std::vector m_initializers; - }; -} + private: + /** The time at which the particle system should start emitting */ + uint32_t m_starttime; + /** Maximum number of particles at the same time */ + uint32_t m_maxcount; + /** List of control points */ + std::vector m_controlpoints; + /** List of emitters */ + std::vector m_emitters; + /** List of initializers */ + std::vector m_initializers; +}; +} // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/CSound.cpp b/src/WallpaperEngine/Core/Objects/CSound.cpp index e22dd65..8fa5aef 100644 --- a/src/WallpaperEngine/Core/Objects/CSound.cpp +++ b/src/WallpaperEngine/Core/Objects/CSound.cpp @@ -1,55 +1,29 @@ -#include "common.h" -#include "WallpaperEngine/Core/CObject.h" #include "CSound.h" +#include "WallpaperEngine/Core/CObject.h" +#include "common.h" using namespace WallpaperEngine::Core::Objects; -CSound::CSound ( - CScene* scene, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles, - bool repeat -) : - CObject (scene, visible, id, std::move(name), Type, origin, scale, angles), - m_repeat (repeat) -{ -} +CSound::CSound (CScene* scene, CUserSettingBoolean* visible, uint32_t id, std::string name, CUserSettingVector3* origin, + CUserSettingVector3* scale, const glm::vec3& angles, bool repeat) : + CObject (scene, visible, id, std::move (name), Type, origin, scale, angles), + m_repeat (repeat) {} -WallpaperEngine::Core::CObject* CSound::fromJSON ( - CScene* scene, - json data, - CUserSettingBoolean* visible, - uint32_t id, - const std::string& name, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles) -{ +WallpaperEngine::Core::CObject* CSound::fromJSON (CScene* scene, json data, CUserSettingBoolean* visible, uint32_t id, + const std::string& name, CUserSettingVector3* origin, + CUserSettingVector3* scale, const glm::vec3& angles) { bool repeat = false; // TODO: PARSE AUDIO VOLUME - auto sound_it = jsonFindRequired (data, "sound", "Sound information not present"); - auto playbackmode = jsonFindDefault (data, "playbackmode", ""); + const auto sound_it = jsonFindRequired (data, "sound", "Sound information not present"); + const auto playbackmode = jsonFindDefault (data, "playbackmode", ""); if (playbackmode == "loop") repeat = true; - if (!(*sound_it).is_array ()) + if (!sound_it->is_array ()) sLog.exception ("Expected sound list on element ", name); - auto* sound = new CSound ( - scene, - visible, - id, - name, - origin, - scale, - angles, - repeat - ); + auto* sound = new CSound (scene, visible, id, name, origin, scale, angles, repeat); for (const auto& cur : (*sound_it)) sound->insertSound (cur); @@ -57,17 +31,15 @@ WallpaperEngine::Core::CObject* CSound::fromJSON ( return sound; } -void CSound::insertSound (const std::string& filename) -{ +void CSound::insertSound (const std::string& filename) { this->m_sounds.push_back (filename); } -const std::vector& CSound::getSounds () const -{ +const std::vector& CSound::getSounds () const { return this->m_sounds; } -bool CSound::isRepeat () const -{ + +bool CSound::isRepeat () const { return this->m_repeat; } diff --git a/src/WallpaperEngine/Core/Objects/CSound.h b/src/WallpaperEngine/Core/Objects/CSound.h index 096ec2a..8ffadd9 100644 --- a/src/WallpaperEngine/Core/Objects/CSound.h +++ b/src/WallpaperEngine/Core/Objects/CSound.h @@ -1,68 +1,51 @@ #pragma once -#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/CObject.h" +#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" -namespace WallpaperEngine::Core::Objects -{ - using json = nlohmann::json; - using namespace WallpaperEngine::Core::UserSettings; +namespace WallpaperEngine::Core::Objects { +using json = nlohmann::json; +using namespace WallpaperEngine::Core::UserSettings; + +/** + * Represents a sound played while the background is working + */ +class CSound : public CObject { + friend class CObject; + + public: + static CObject* fromJSON (CScene* scene, json data, CUserSettingBoolean* visible, uint32_t id, + const std::string& name, CUserSettingVector3* origin, CUserSettingVector3* scale, + const glm::vec3& angles); /** - * Represents a sound played while the background is working + * @return The list of sounds to play */ - class CSound : public CObject - { - friend class CObject; + [[nodiscard]] const std::vector& getSounds () const; + /** + * @return If the sound should repeat or not + */ + [[nodiscard]] bool isRepeat () const; - public: - static CObject* fromJSON ( - CScene* scene, - json data, - CUserSettingBoolean* visible, - uint32_t id, - const std::string& name, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles - ); + protected: + CSound (CScene* scene, CUserSettingBoolean* visible, uint32_t id, std::string name, CUserSettingVector3* origin, + CUserSettingVector3* scale, const glm::vec3& angles, bool repeat); - /** - * @return The list of sounds to play - */ - [[nodiscard]] const std::vector& getSounds () const; - /** - * @return If the sound should repeat or not - */ - [[nodiscard]] bool isRepeat () const; + /** + * @param filename The sound to add + */ + void insertSound (const std::string& filename); - protected: - CSound ( - CScene* scene, - CUserSettingBoolean* visible, - uint32_t id, - std::string name, - CUserSettingVector3* origin, - CUserSettingVector3* scale, - const glm::vec3& angles, - bool repeat - ); + /** + * Type value used to differentiate the different types of objects in a background + */ + static const std::string Type; - /** - * @param filename The sound to add - */ - void insertSound (const std::string& filename); - - /** - * Type value used to differentiate the different types of objects in a background - */ - static const std::string Type; - - private: - /** If the sounds should repeat or not */ - bool m_repeat; - /** The list of sounds to play */ - std::vector m_sounds; - }; -} + private: + /** If the sounds should repeat or not */ + bool m_repeat; + /** The list of sounds to play */ + std::vector m_sounds; +}; +} // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp b/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp index 13f0228..7522ff5 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp @@ -4,26 +4,19 @@ using namespace WallpaperEngine::Core::Objects::Effects; -CBind::CBind (std::string name, uint32_t index) : - m_name (std::move(name)), - m_index (index) -{ -} +CBind::CBind (std::string name, uint32_t index) : m_name (std::move (name)), m_index (index) {} -CBind* CBind::fromJSON (json data) -{ - auto name_it = jsonFindRequired (data, "name", "bind must have texture name"); - auto index_it = jsonFindRequired (data, "index", "bind must have index"); +CBind* CBind::fromJSON (json data) { + const auto name_it = jsonFindRequired (data, "name", "bind must have texture name"); + const auto index_it = jsonFindRequired (data, "index", "bind must have index"); return new CBind (*name_it, *index_it); } -const std::string& CBind::getName () const -{ +const std::string& CBind::getName () const { return this->m_name; } -const uint32_t& CBind::getIndex () const -{ +const uint32_t& CBind::getIndex () const { return this->m_index; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Effects/CBind.h b/src/WallpaperEngine/Core/Objects/Effects/CBind.h index 0bb2995..f4a229d 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CBind.h +++ b/src/WallpaperEngine/Core/Objects/Effects/CBind.h @@ -4,41 +4,39 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Effects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Objects::Effects { +using json = nlohmann::json; + +/** + * Material's bind information, describes for passes what textures to bind + * in what positions for shaders. Used to override the textures specified inside + * the object's passes + */ +class CBind { + public: + /** + * Parses bind information off the given json data + * + * @param data + * @return + */ + static CBind* fromJSON (json data); + + CBind (std::string name, uint32_t index); /** - * Material's bind information, describes for passes what textures to bind - * in what positions for shaders. Used to override the textures specified inside - * the object's passes + * @return The texture name, previous to use the one already specified by the object's passes */ - class CBind - { - public: - /** - * Parses bind information off the given json data - * - * @param data - * @return - */ - static CBind* fromJSON (json data); + [[nodiscard]] const std::string& getName () const; + /** + * @return The texture index to replace + */ + [[nodiscard]] const uint32_t& getIndex () const; - CBind (std::string name, uint32_t index); - - /** - * @return The texture name, previous to use the one already specified by the object's passes - */ - [[nodiscard]] const std::string& getName () const; - /** - * @return The texture index to replace - */ - [[nodiscard]] const uint32_t& getIndex () const; - - private: - /** The texture's name */ - std::string m_name; - /** The texture index to replace */ - uint32_t m_index; - }; -} + private: + /** The texture's name */ + std::string m_name; + /** The texture index to replace */ + uint32_t m_index; +}; +} // namespace WallpaperEngine::Core::Objects::Effects diff --git a/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp b/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp index 607f158..65633a5 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp @@ -6,36 +6,26 @@ using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Objects::Effects; CFBO::CFBO (std::string name, float scale, std::string format) : - m_name (std::move(name)), + m_name (std::move (name)), m_scale (scale), - m_format(std::move(format)) -{ + m_format (std::move (format)) {} + +CFBO* CFBO::fromJSON (json data) { + const auto name_it = jsonFindRequired (data, "name", "Name for an FBO is required"); + const auto scale = jsonFindDefault (data, "scale", 1.0); + const auto format = jsonFindDefault (data, "format", ""); + + return new CFBO (*name_it, scale, format); } -CFBO* CFBO::fromJSON (json data) -{ - auto name_it = jsonFindRequired (data, "name", "Name for an FBO is required"); - auto scale = jsonFindDefault (data, "scale", 1.0); - auto format = jsonFindDefault (data, "format", ""); - - return new CFBO ( - *name_it, - scale, - format - ); -} - -const std::string& CFBO::getName () const -{ +const std::string& CFBO::getName () const { return this->m_name; } -const float& CFBO::getScale () const -{ +const float& CFBO::getScale () const { return this->m_scale; } -const std::string& CFBO::getFormat () const -{ +const std::string& CFBO::getFormat () const { return this->m_format; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Effects/CFBO.h b/src/WallpaperEngine/Core/Objects/Effects/CFBO.h index bba9ce4..7e35b97 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CFBO.h +++ b/src/WallpaperEngine/Core/Objects/Effects/CFBO.h @@ -5,41 +5,39 @@ #include #include -namespace WallpaperEngine::Core::Objects::Effects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Objects::Effects { +using json = nlohmann::json; + +/** + * FBO = Frame Buffer Object + * + * Represents a framebuffer object used in objects with multiple effects or render passes + */ +class CFBO { + public: + CFBO (std::string name, float scale, std::string format); + + static CFBO* fromJSON (json data); /** - * FBO = Frame Buffer Object - * - * Represents a framebuffer object used in objects with multiple effects or render passes + * @return The FBO name used to identify it in the background's files */ - class CFBO - { - public: - CFBO (std::string name, float scale, std::string format); + [[nodiscard]] const std::string& getName () const; + /** + * @return The scale factor of the FBO + */ + [[nodiscard]] const float& getScale () const; + /** + * @return The FBO's format for the render + */ + [[nodiscard]] const std::string& getFormat () const; - static CFBO* fromJSON (json data); - - /** - * @return The FBO name used to identify it in the background's files - */ - [[nodiscard]] const std::string& getName () const; - /** - * @return The scale factor of the FBO - */ - [[nodiscard]] const float& getScale () const; - /** - * @return The FBO's format for the render - */ - [[nodiscard]] const std::string& getFormat () const; - - private: - /** The name of the FBO */ - std::string m_name; - /** The scale factor of the FBO */ - float m_scale; - /** The FBO's format for the render */ - std::string m_format; - }; -} \ No newline at end of file + private: + /** The name of the FBO */ + std::string m_name; + /** The scale factor of the FBO */ + float m_scale; + /** The FBO's format for the render */ + std::string m_format; +}; +} // namespace WallpaperEngine::Core::Objects::Effects \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp index df33ec8..fab60c3 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp @@ -2,12 +2,8 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstant::CShaderConstant (std::string type) : - m_type (std::move(type)) -{ -} +CShaderConstant::CShaderConstant (std::string type) : m_type (std::move (type)) {} -const std::string& CShaderConstant::getType () const -{ +const std::string& CShaderConstant::getType () const { return this->m_type; } diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h index f773035..7e191f2 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h @@ -2,27 +2,34 @@ #include -namespace WallpaperEngine::Core::Objects::Effects::Constants -{ +namespace WallpaperEngine::Core::Objects::Effects::Constants { +/** + * Shader constants base class + */ +class CShaderConstant { + public: + explicit CShaderConstant (std::string type); + + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); + } + + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } + + template bool is () { + return this->m_type == T::Type; + } + /** - * Shader constants base class + * @return The type name of this constant */ - class CShaderConstant - { - public: - explicit CShaderConstant (std::string type); + [[nodiscard]] const std::string& getType () const; - template const T* as () const { assert (is ()); return (const T*) this; } - template T* as () { assert (is ()); return (T*) this; } - - template bool is () { return this->m_type == T::Type; } - - /** - * @return The type name of this constant - */ - [[nodiscard]] const std::string& getType () const; - - private: - std::string m_type; - }; -} + private: + std::string m_type; +}; +} // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp index 2ba0687..04b1877 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp @@ -2,14 +2,9 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantFloat::CShaderConstantFloat (float value) : - CShaderConstant (Type), - m_value (value) -{ -} +CShaderConstantFloat::CShaderConstantFloat (float value) : CShaderConstant (Type), m_value (value) {} -float* CShaderConstantFloat::getValue () -{ +float* CShaderConstantFloat::getValue () { return &this->m_value; } diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h index 03a8c5a..84be76e 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h @@ -4,27 +4,26 @@ #include -namespace WallpaperEngine::Core::Objects::Effects::Constants -{ +namespace WallpaperEngine::Core::Objects::Effects::Constants { +/** + * Shader constant of type float + */ +class CShaderConstantFloat : public CShaderConstant { + public: + explicit CShaderConstantFloat (float value); + /** - * Shader constant of type float + * @return A pointer to the actual value of the constant */ - class CShaderConstantFloat : public CShaderConstant - { - public: - explicit CShaderConstantFloat (float value); + float* getValue (); - /** - * @return A pointer to the actual value of the constant - */ - float* getValue (); + /** + * Type string indicator + */ + static const std::string Type; - /** - * Type string indicator - */ - static const std::string Type; - protected: - /** The constant's value */ - float m_value; - }; -} + protected: + /** The constant's value */ + float m_value; +}; +} // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp index 24f5d02..7bc7b99 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp @@ -2,14 +2,9 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantInteger::CShaderConstantInteger (int32_t value) : - CShaderConstant (Type), - m_value (value) -{ -} +CShaderConstantInteger::CShaderConstantInteger (int32_t value) : CShaderConstant (Type), m_value (value) {} -int32_t* CShaderConstantInteger::getValue () -{ +int32_t* CShaderConstantInteger::getValue () { return &this->m_value; } diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h index e72caeb..9101191 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h @@ -4,27 +4,26 @@ #include -namespace WallpaperEngine::Core::Objects::Effects::Constants -{ +namespace WallpaperEngine::Core::Objects::Effects::Constants { +/** + * Shader constant of type integer + */ +class CShaderConstantInteger : public CShaderConstant { + public: + explicit CShaderConstantInteger (int32_t value); + /** - * Shader constant of type integer + * @return A pointer to the actual value of the constant */ - class CShaderConstantInteger : public CShaderConstant - { - public: - explicit CShaderConstantInteger (int32_t value); + int32_t* getValue (); - /** - * @return A pointer to the actual value of the constant - */ - int32_t* getValue (); + /** + * Type string indicator + */ + static const std::string Type; - /** - * Type string indicator - */ - static const std::string Type; - protected: - /** The constant's value */ - int32_t m_value; - }; -} + protected: + /** The constant's value */ + int32_t m_value; +}; +} // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp index 12f85f7..f361d80 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp @@ -2,15 +2,9 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; +CShaderConstantVector2::CShaderConstantVector2 (glm::vec2 value) : CShaderConstant (Type), m_value (value) {} -CShaderConstantVector2::CShaderConstantVector2 (glm::vec2 value) : - CShaderConstant (Type), - m_value (value) -{ -} - -glm::vec2* CShaderConstantVector2::getValue () -{ +glm::vec2* CShaderConstantVector2::getValue () { return &this->m_value; } diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h index 937de5d..2411825 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h @@ -2,31 +2,30 @@ #include "CShaderConstant.h" -#include #include #include +#include + +namespace WallpaperEngine::Core::Objects::Effects::Constants { +/** + * Shader constant of vector2 type + */ +class CShaderConstantVector2 : public CShaderConstant { + public: + explicit CShaderConstantVector2 (glm::vec2 value); -namespace WallpaperEngine::Core::Objects::Effects::Constants -{ /** - * Shader constant of vector2 type + * @return A pointer to the actual value of the constant */ - class CShaderConstantVector2 : public CShaderConstant - { - public: - explicit CShaderConstantVector2 (glm::vec2 value); + glm::vec2* getValue (); - /** - * @return A pointer to the actual value of the constant - */ - glm::vec2* getValue (); + /** + * Type string indicator + */ + static const std::string Type; - /** - * Type string indicator - */ - static const std::string Type; - protected: - /** The constant's value */ - glm::vec2 m_value; - }; -} + protected: + /** The constant's value */ + glm::vec2 m_value; +}; +} // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp index 5afd7bf..9afa86a 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp @@ -2,14 +2,9 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantVector3::CShaderConstantVector3 (glm::vec3 value) : - CShaderConstant (Type), - m_value (value) -{ -} +CShaderConstantVector3::CShaderConstantVector3 (glm::vec3 value) : CShaderConstant (Type), m_value (value) {} -glm::vec3* CShaderConstantVector3::getValue () -{ +glm::vec3* CShaderConstantVector3::getValue () { return &this->m_value; } diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h index 9e7a40c..989044f 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h @@ -2,30 +2,29 @@ #include "CShaderConstant.h" -#include #include +#include + +namespace WallpaperEngine::Core::Objects::Effects::Constants { +/** + * Shader constant of vector3 type + */ +class CShaderConstantVector3 : public CShaderConstant { + public: + explicit CShaderConstantVector3 (glm::vec3 value); -namespace WallpaperEngine::Core::Objects::Effects::Constants -{ /** - * Shader constant of vector3 type + * @return A pointer to the actual value of the constant */ - class CShaderConstantVector3 : public CShaderConstant - { - public: - explicit CShaderConstantVector3 (glm::vec3 value); + glm::vec3* getValue (); - /** - * @return A pointer to the actual value of the constant - */ - glm::vec3* getValue (); + /** + * Type string indicator + */ + static const std::string Type; - /** - * Type string indicator - */ - static const std::string Type; - protected: - /** The constant's value */ - glm::vec3 m_value; - }; -} + protected: + /** The constant's value */ + glm::vec3 m_value; +}; +} // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp index 173db22..7502a95 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp @@ -2,15 +2,9 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; +CShaderConstantVector4::CShaderConstantVector4 (glm::vec4 value) : CShaderConstant (Type), m_value (value) {} -CShaderConstantVector4::CShaderConstantVector4 (glm::vec4 value) : - CShaderConstant (Type), - m_value (value) -{ -} - -glm::vec4* CShaderConstantVector4::getValue () -{ +glm::vec4* CShaderConstantVector4::getValue () { return &this->m_value; } diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h index 9ef0b5b..e9aa7e3 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h @@ -2,30 +2,29 @@ #include "CShaderConstant.h" -#include #include +#include + +namespace WallpaperEngine::Core::Objects::Effects::Constants { +/** + * Shader constant of vector4 type + */ +class CShaderConstantVector4 : public CShaderConstant { + public: + explicit CShaderConstantVector4 (glm::vec4 value); -namespace WallpaperEngine::Core::Objects::Effects::Constants -{ /** - * Shader constant of vector4 type + * @return A pointer to the actual value of the constant */ - class CShaderConstantVector4 : public CShaderConstant - { - public: - explicit CShaderConstantVector4 (glm::vec4 value); + glm::vec4* getValue (); - /** - * @return A pointer to the actual value of the constant - */ - glm::vec4* getValue (); + /** + * Type string indicator + */ + static const std::string Type; - /** - * Type string indicator - */ - static const std::string Type; - protected: - /** The constant's value */ - glm::vec4 m_value; - }; -} + protected: + /** The constant's value */ + glm::vec4 m_value; +}; +} // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp b/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp index a85f348..e76ad57 100644 --- a/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp +++ b/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp @@ -10,37 +10,26 @@ using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Core::Objects; using namespace WallpaperEngine::Core::Objects::Images; -CMaterial::CMaterial (std::string name) : - m_target (), - m_name (std::move(name)) -{ +CMaterial::CMaterial (std::string name) : m_name (std::move (name)) {} + +CMaterial* CMaterial::fromFile (const std::string& filename, CContainer* container) { + return fromJSON (filename, json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container))); } -CMaterial* CMaterial::fromFile (const std::string& filename, CContainer* container) -{ - return fromJSON ( - filename, json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)) - ); -} -CMaterial* CMaterial::fromFile (const std::string& filename, const std::string& target, CContainer* container) -{ - return fromJSON ( - filename, json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)), target - ); +CMaterial* CMaterial::fromFile (const std::string& filename, const std::string& target, CContainer* container) { + return fromJSON (filename, json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)), target); } -CMaterial* CMaterial::fromJSON (const std::string& name, json data, const std::string& target) -{ - CMaterial* material = fromJSON (name, std::move(data)); +CMaterial* CMaterial::fromJSON (const std::string& name, json data, const std::string& target) { + CMaterial* material = fromJSON (name, std::move (data)); material->setTarget (target); return material; } -CMaterial* CMaterial::fromJSON (const std::string& name, json data) -{ - auto passes_it = jsonFindRequired (data, "passes", "Material must have at least one pass"); +CMaterial* CMaterial::fromJSON (const std::string& name, json data) { + const auto passes_it = jsonFindRequired (data, "passes", "Material must have at least one pass"); auto* material = new CMaterial (name); @@ -50,41 +39,34 @@ CMaterial* CMaterial::fromJSON (const std::string& name, json data) return material; } -void CMaterial::insertPass (Materials::CPass* mass) -{ - this->m_passes.push_back (mass); +void CMaterial::insertPass (Materials::CPass* pass) { + this->m_passes.push_back (pass); } -void CMaterial::insertTextureBind (Effects::CBind* bind) -{ +void CMaterial::insertTextureBind (Effects::CBind* bind) { this->m_textureBindings.insert (std::make_pair (bind->getIndex (), bind)); } -void CMaterial::setTarget (const std::string& target) -{ +void CMaterial::setTarget (const std::string& target) { this->m_target = target; } -const std::vector & CMaterial::getPasses () const -{ +const std::vector& CMaterial::getPasses () const { return this->m_passes; } -const std::map & CMaterial::getTextureBinds () const -{ + +const std::map& CMaterial::getTextureBinds () const { return this->m_textureBindings; } -const std::string& CMaterial::getTarget () const -{ +const std::string& CMaterial::getTarget () const { return this->m_target; } -const std::string& CMaterial::getName () const -{ +const std::string& CMaterial::getName () const { return this->m_name; } -bool CMaterial::hasTarget () const -{ +bool CMaterial::hasTarget () const { return !this->m_target.empty (); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Images/CMaterial.h b/src/WallpaperEngine/Core/Objects/Images/CMaterial.h index 7a1b827..6864e62 100644 --- a/src/WallpaperEngine/Core/Objects/Images/CMaterial.h +++ b/src/WallpaperEngine/Core/Objects/Images/CMaterial.h @@ -1,74 +1,72 @@ #pragma once -#include "WallpaperEngine/Core/Objects/Images/Materials/CPass.h" #include "WallpaperEngine/Core/Objects/Effects/CBind.h" +#include "WallpaperEngine/Core/Objects/Images/Materials/CPass.h" -#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Assets/CContainer.h" +#include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Images -{ - using json = nlohmann::json; - using namespace WallpaperEngine::Assets; +namespace WallpaperEngine::Core::Objects::Images { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; + +/** + * Represents a material in use in the background + */ +class CMaterial { + public: + static CMaterial* fromFile (const std::string& filename, Assets::CContainer* container); + static CMaterial* fromJSON (const std::string& name, json data); + static CMaterial* fromFile (const std::string& filename, const std::string& target, Assets::CContainer* container); + static CMaterial* fromJSON (const std::string& name, json data, const std::string& target); /** - * Represents a material in use in the background + * @param pass The rendering pass to add to the material */ - class CMaterial - { - public: - static CMaterial* fromFile (const std::string& filename, Assets::CContainer* container); - static CMaterial* fromJSON (const std::string& name, json data); - static CMaterial* fromFile (const std::string& filename, const std::string& target, Assets::CContainer* container); - static CMaterial* fromJSON (const std::string& name, json data, const std::string& target); + void insertPass (Materials::CPass* pass); + /** + * @param bind Texture bind override for the material + */ + void insertTextureBind (Effects::CBind* bind); - /** - * @param pass The rendering pass to add to the material - */ - void insertPass (Materials::CPass* pass); - /** - * @param bind Texture bind override for the material - */ - void insertTextureBind (Effects::CBind* bind); + /** + * @return All the rendering passes that happen for this material + */ + [[nodiscard]] const std::vector& getPasses () const; + /** + * @return The textures that have to be bound while rendering the material. + * These act as an override of the textures specified by the parent effect + */ + [[nodiscard]] const std::map& getTextureBinds () const; + /** + * @return The materials destination (fbo) if required + */ + [[nodiscard]] const std::string& getTarget () const; + /** + * @return Indicates if this material has a specific destination (fbo) while rendering + */ + [[nodiscard]] bool hasTarget () const; + /** + * @return The name of the material + */ + [[nodiscard]] const std::string& getName () const; - /** - * @return All the rendering passes that happen for this material - */ - [[nodiscard]] const std::vector & getPasses () const; - /** - * @return The textures that have to be bound while rendering the material. - * These act as an override of the textures specified by the parent effect - */ - [[nodiscard]] const std::map & getTextureBinds () const; - /** - * @return The materials destination (fbo) if required - */ - [[nodiscard]] const std::string& getTarget () const; - /** - * @return Indicates if this material has a specific destination (fbo) while rendering - */ - [[nodiscard]] bool hasTarget () const; - /** - * @return The name of the material - */ - [[nodiscard]] const std::string& getName () const; + protected: + explicit CMaterial (std::string name); - protected: - explicit CMaterial (std::string name); + /** + * @param target The new target while rendering this material + */ + void setTarget (const std::string& target); - /** - * @param target The new target while rendering this material - */ - void setTarget (const std::string& target); - - private: - /** All the shader passes required to render this material */ - std::vector m_passes; - /** List of texture bind overrides to use for this material */ - std::map m_textureBindings; - /** The FBO target to render to (if any) */ - std::string m_target; - /** The material's name */ - std::string m_name; - }; -} + private: + /** All the shader passes required to render this material */ + std::vector m_passes; + /** List of texture bind overrides to use for this material */ + std::map m_textureBindings; + /** The FBO target to render to (if any) */ + std::string m_target; + /** The material's name */ + std::string m_name; +}; +} // namespace WallpaperEngine::Core::Objects::Images diff --git a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp index 368b0ab..7b7c5fa 100644 --- a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp +++ b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp @@ -1,54 +1,43 @@ -#include "common.h" #include "CPass.h" +#include "common.h" #include using namespace WallpaperEngine::Core::Objects::Effects::Constants; using namespace WallpaperEngine::Core::Objects::Images::Materials; -CPass::CPass (std::string blending, std::string cullmode, std::string depthtest, std::string depthwrite, std::string shader) : - m_blending (std::move(blending)), - m_cullmode (std::move(cullmode)), - m_depthtest (std::move(depthtest)), - m_depthwrite (std::move(depthwrite)), - m_shader (std::move(shader)) -{ -} +CPass::CPass (std::string blending, std::string cullmode, std::string depthtest, std::string depthwrite, + std::string shader) : + m_blending (std::move (blending)), + m_cullmode (std::move (cullmode)), + m_depthtest (std::move (depthtest)), + m_depthwrite (std::move (depthwrite)), + m_shader (std::move (shader)) {} -CPass* CPass::fromJSON (json data) -{ +CPass* CPass::fromJSON (json data) { // TODO: FIGURE OUT DEFAULT BLENDING MODE - auto blending = jsonFindDefault (data, "blending", "normal"); - auto cullmode = jsonFindDefault (data, "cullmode", "nocull"); - auto depthtest_it = jsonFindRequired (data, "depthtest", "Material pass must have depthtest specified"); - auto depthwrite_it = jsonFindRequired (data, "depthwrite", "Material pass must have depthwrite specified"); - auto shader_it = jsonFindRequired (data, "shader", "Material pass must have shader specified"); - auto textures_it = data.find ("textures"); - auto combos_it = data.find ("combos"); + const auto blending = jsonFindDefault (data, "blending", "normal"); + const auto cullmode = jsonFindDefault (data, "cullmode", "nocull"); + const auto depthtest_it = jsonFindRequired (data, "depthtest", "Material pass must have depthtest specified"); + const auto depthwrite_it = jsonFindRequired (data, "depthwrite", "Material pass must have depthwrite specified"); + const auto shader_it = jsonFindRequired (data, "shader", "Material pass must have shader specified"); + const auto textures_it = data.find ("textures"); + const auto combos_it = data.find ("combos"); - if (textures_it != data.end ()) - { + if (textures_it != data.end ()) { // TODO: FETCH THIS FROM CImage TO MAKE IT COMPATIBLE WITH OLDER WALLPAPERS - if (!(*textures_it).is_array ()) + if (!textures_it->is_array ()) sLog.exception ("Material's textures must be a list"); } - auto* pass = new CPass ( - blending, - cullmode, - *depthtest_it, - *depthwrite_it, - *shader_it - ); + auto* pass = new CPass (blending, cullmode, *depthtest_it, *depthwrite_it, *shader_it); if (textures_it != data.end ()) for (const auto& cur : (*textures_it)) pass->insertTexture (cur.is_null () ? "" : cur); - if (combos_it != data.end ()) - { - for (const auto& cur : (*combos_it).items ()) - { + if (combos_it != data.end ()) { + for (const auto& cur : combos_it->items ()) { if (cur.value ().is_number_integer ()) pass->insertCombo (cur.key (), cur.value ()); else @@ -59,70 +48,57 @@ CPass* CPass::fromJSON (json data) return pass; } -void CPass::insertTexture (const std::string& texture) -{ +void CPass::insertTexture (const std::string& texture) { this->m_textures.push_back (texture); } -void CPass::setTexture (int index, const std::string& texture) -{ +void CPass::setTexture (int index, const std::string& texture) { this->m_textures.at (index) = texture; } -void CPass::insertCombo (const std::string& name, int value) -{ +void CPass::insertCombo (const std::string& name, int value) { std::string uppercase = std::string (name); std::transform (uppercase.begin (), uppercase.end (), uppercase.begin (), ::toupper); - this->m_combos.insert (std::pair (uppercase, value)); + this->m_combos.insert (std::pair (uppercase, value)); } -const std::vector& CPass::getTextures () const -{ +const std::vector& CPass::getTextures () const { return this->m_textures; } -const std::map& CPass::getConstants () const -{ +const std::map& CPass::getConstants () const { return this->m_constants; } -std::map* CPass::getCombos () -{ +std::map* CPass::getCombos () { return &this->m_combos; } -const std::string& CPass::getShader () const -{ +const std::string& CPass::getShader () const { return this->m_shader; } -const std::string& CPass::getBlendingMode () const -{ +const std::string& CPass::getBlendingMode () const { return this->m_blending; } -const std::string& CPass::getCullingMode () const -{ +const std::string& CPass::getCullingMode () const { return this->m_cullmode; } -const std::string& CPass::getDepthTest () const -{ +const std::string& CPass::getDepthTest () const { return this->m_depthtest; } -const std::string& CPass::getDepthWrite ()const -{ +const std::string& CPass::getDepthWrite () const { return this->m_depthwrite; } -void CPass::setBlendingMode (const std::string& mode) -{ +void CPass::setBlendingMode (const std::string& mode) { this->m_blending = mode; } -void CPass::insertConstant (const std::string& name, CShaderConstant* constant) -{ - this->m_constants.insert (std::pair (name, constant)); +void CPass::insertConstant (const std::string& name, CShaderConstant* constant) { + this->m_constants.insert (std::pair (name, constant)); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h index d28e5e4..3dd49bb 100644 --- a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h +++ b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h @@ -4,110 +4,109 @@ #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" -namespace WallpaperEngine::Core::Objects -{ - class CEffect; +namespace WallpaperEngine::Core::Objects { +class CEffect; } -namespace WallpaperEngine::Core::Objects::Images::Materials -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Objects::Images::Materials { +using json = nlohmann::json; + +/** + * Represents a shader pass of an object + */ +class CPass { + friend class WallpaperEngine::Core::Objects::CEffect; + + public: + static CPass* fromJSON (json data); /** - * Represents a shader pass of an object + * @return The list of textures to bind while rendering */ - class CPass - { - friend class WallpaperEngine::Core::Objects::CEffect; - public: - static CPass* fromJSON (json data); + [[nodiscard]] const std::vector& getTextures () const; + /** + * @return Shader constants that alter how the shader should behave + */ + [[nodiscard]] const std::map& getConstants () const; + /** + * @return Shader combos that alter how the shader should behave + */ + [[nodiscard]] std::map* getCombos (); + /** + * @return Shader to be used while rendering the pass + */ + [[nodiscard]] const std::string& getShader () const; + /** + * @return The blending mode to use while rendering + */ + [[nodiscard]] const std::string& getBlendingMode () const; + /** + * @return The culling mode to use while rendering + */ + [[nodiscard]] const std::string& getCullingMode () const; + /** + * @return If depth testing has to happen while rendering + */ + [[nodiscard]] const std::string& getDepthTest () const; + /** + * @return If depth write has to happen while rendering + */ + [[nodiscard]] const std::string& getDepthWrite () const; + /** + * @param mode The new blending mode to use + */ + void setBlendingMode (const std::string& mode); - /** - * @return The list of textures to bind while rendering - */ - [[nodiscard]] const std::vector& getTextures () const; - /** - * @return Shader constants that alter how the shader should behave - */ - [[nodiscard]] const std::map& getConstants () const; - /** - * @return Shader combos that alter how the shader should behave - */ - [[nodiscard]] std::map* getCombos (); - /** - * @return Shader to be used while rendering the pass - */ - [[nodiscard]] const std::string& getShader () const; - /** - * @return The blending mode to use while rendering - */ - [[nodiscard]] const std::string& getBlendingMode () const; - /** - * @return The culling mode to use while rendering - */ - [[nodiscard]] const std::string& getCullingMode () const; - /** - * @return If depth testing has to happen while rendering - */ - [[nodiscard]] const std::string& getDepthTest () const; - /** - * @return If depth write has to happen while rendering - */ - [[nodiscard]] const std::string& getDepthWrite () const; - /** - * @param mode The new blending mode to use - */ - void setBlendingMode (const std::string& mode); + /** + * Add a shader combo value to the list + * + * @param name The combo name + * @param value It's value + */ + void insertCombo (const std::string& name, int value); + /** + * Adds a shader constant to the list + * + * @param name The constant's name + * @param constant It's value + */ + void insertConstant (const std::string& name, Effects::Constants::CShaderConstant* constant); - /** - * Add a shader combo value to the list - * - * @param name The combo name - * @param value It's value - */ - void insertCombo (const std::string& name, int value); - /** - * Adds a shader constant to the list - * - * @param name The constant's name - * @param constant It's value - */ - void insertConstant (const std::string& name, Effects::Constants::CShaderConstant* constant); + protected: + CPass (std::string blending, std::string cullmode, std::string depthtest, std::string depthwrite, + std::string shader); - protected: - CPass (std::string blending, std::string cullmode, std::string depthtest, std::string depthwrite, std::string shader); + /** + * Adds a new texture to the list of textures to bind while rendering + * + * @param texture + */ + void insertTexture (const std::string& texture); + /** + * Updates a texture in the specified index for binding while rendering + * + * @param index + * @param texture + */ + void setTexture (int index, const std::string& texture); - /** - * Adds a new texture to the list of textures to bind while rendering - * - * @param texture - */ - void insertTexture (const std::string& texture); - /** - * Updates a texture in the specified index for binding while rendering - * - * @param index - * @param texture - */ - void setTexture (int index, const std::string& texture); - - private: - // TODO: CREATE ENUMERATIONS FOR THESE INSTEAD OF USING STRING VALUES! - /** The blending mode to use */ - std::string m_blending; - /** The culling mode to use */ - std::string m_cullmode; - /** If depthtesting has to happen while drawing */ - std::string m_depthtest; - /** If depthwrite has to happen while drawing */ - std::string m_depthwrite; - /** The shader to use */ - std::string m_shader; - /** The list of textures to use */ - std::vector m_textures; - /** Different combo settings for shader input */ - std::map m_combos; - /** Shader constant values to use for the shaders */ - std::map m_constants; - }; -} + private: + // TODO: CREATE ENUMERATIONS FOR THESE INSTEAD OF USING STRING VALUES! + /** The blending mode to use */ + std::string m_blending; + /** The culling mode to use */ + std::string m_cullmode; + /** If depthtesting has to happen while drawing */ + std::string m_depthtest; + /** If depthwrite has to happen while drawing */ + std::string m_depthwrite; + /** The shader to use */ + std::string m_shader; + /** The list of textures to use */ + std::vector m_textures; + /** Different combo settings for shader input */ + std::map m_combos; + /** Shader constant values to use for the shaders */ + std::map m_constants; +}; +} // namespace WallpaperEngine::Core::Objects::Images::Materials diff --git a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp index 29d8f66..47d55cd 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp @@ -2,11 +2,10 @@ using namespace WallpaperEngine::Core::Objects::Particles; -CControlPoint* CControlPoint::fromJSON (json data) -{ - auto flags_it = data.find ("flags"); - auto id_it = jsonFindRequired (data, "id", "Particle's control point must have id"); - auto offset_it = data.find ("offset"); +CControlPoint* CControlPoint::fromJSON (json data) { + const auto flags_it = data.find ("flags"); + const auto id_it = jsonFindRequired (data, "id", "Particle's control point must have id"); + const auto offset_it = data.find ("offset"); auto* controlpoint = new CControlPoint (*id_it, 0); @@ -19,33 +18,24 @@ CControlPoint* CControlPoint::fromJSON (json data) return controlpoint; } -CControlPoint::CControlPoint (uint32_t id, uint32_t flags) : - m_id (id), - m_flags (flags), - m_offset (glm::vec3 ()) -{ -} +CControlPoint::CControlPoint (uint32_t id, uint32_t flags) : m_id (id), m_flags (flags), m_offset (glm::vec3 ()) {} -void CControlPoint::setOffset (const glm::vec3& offset) -{ +void CControlPoint::setOffset (const glm::vec3& offset) { this->m_offset = offset; } -void CControlPoint::setFlags (uint32_t flags) -{ +void CControlPoint::setFlags (uint32_t flags) { this->m_flags = flags; } -uint32_t CControlPoint::getId () const -{ + +uint32_t CControlPoint::getId () const { return this->m_id; } -const glm::vec3& CControlPoint::getOffset () const -{ +const glm::vec3& CControlPoint::getOffset () const { return this->m_offset; } -uint32_t CControlPoint::getFlags () const -{ +uint32_t CControlPoint::getFlags () const { return this->m_flags; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h index 9ff961b..b9f0725 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h +++ b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h @@ -2,49 +2,47 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Particles -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Objects::Particles { +using json = nlohmann::json; + +/** + * Control point for particles + */ +class CControlPoint { + public: + static CControlPoint* fromJSON (json data); /** - * Control point for particles + * @return The id of the controlpoint used for ordering purposes */ - class CControlPoint - { - public: - static CControlPoint* fromJSON (json data); + [[nodiscard]] uint32_t getId () const; + /** + * @return The offset from origin + */ + [[nodiscard]] const glm::vec3& getOffset () const; + /** + * @return Flags for the control point, controls how it should behave + */ + [[nodiscard]] uint32_t getFlags () const; - /** - * @return The id of the controlpoint used for ordering purposes - */ - [[nodiscard]] uint32_t getId () const; - /** - * @return The offset from origin - */ - [[nodiscard]] const glm::vec3& getOffset () const; - /** - * @return Flags for the control point, controls how it should behave - */ - [[nodiscard]] uint32_t getFlags () const; + protected: + explicit CControlPoint (uint32_t id, uint32_t flags = 0); - protected: - explicit CControlPoint (uint32_t id, uint32_t flags = 0); + /** + * @param offset The new offset + */ + void setOffset (const glm::vec3& offset); + /** + * @param flags The new flags + */ + void setFlags (uint32_t flags); - /** - * @param offset The new offset - */ - void setOffset (const glm::vec3& offset); - /** - * @param flags The new flags - */ - void setFlags (uint32_t flags); - - private: - /** ID used for ordering purposes */ - uint32_t m_id; - /** Flags that control how it behaves */ - uint32_t m_flags; - /** The offset from starting position */ - glm::vec3 m_offset; - }; -} + private: + /** ID used for ordering purposes */ + uint32_t m_id; + /** Flags that control how it behaves */ + uint32_t m_flags; + /** The offset from starting position */ + glm::vec3 m_offset; +}; +} // namespace WallpaperEngine::Core::Objects::Particles diff --git a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp index 37f8844..0714411 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp @@ -2,76 +2,54 @@ using namespace WallpaperEngine::Core::Objects::Particles; -CEmitter* CEmitter::fromJSON (json data) -{ - auto directions_it = jsonFindRequired (data, "directions", "Particle emitter must have direction specified"); - auto distancemax_it = jsonFindRequired (data, "distancemax", "Particle emitter must have maximum distance"); - auto distancemin_it = jsonFindRequired (data, "distancemin", "Particle emitter must have minimum distance"); - auto id_it = data.find ("id"); - auto name_it = jsonFindRequired (data, "name", "Particle emitter must have a name"); - auto origin_it = jsonFindRequired (data, "origin", "Particle emitter must have an origin"); - auto rate_it = jsonFindRequired (data, "rate", "Particle emitter must have a rate"); +CEmitter* CEmitter::fromJSON (json data) { + const auto directions_it = jsonFindRequired (data, "directions", "Particle emitter must have direction specified"); + const auto distancemax_it = jsonFindRequired (data, "distancemax", "Particle emitter must have maximum distance"); + const auto distancemin_it = jsonFindRequired (data, "distancemin", "Particle emitter must have minimum distance"); + const auto id_it = data.find ("id"); + const auto name_it = jsonFindRequired (data, "name", "Particle emitter must have a name"); + const auto origin_it = jsonFindRequired (data, "origin", "Particle emitter must have an origin"); + const auto rate_it = jsonFindRequired (data, "rate", "Particle emitter must have a rate"); - return new CEmitter ( - WallpaperEngine::Core::aToVector3 (*directions_it), - *distancemax_it, - *distancemin_it, - (id_it == data.end () ? 0 : (uint32_t) (*id_it)), - *name_it, - WallpaperEngine::Core::aToVector3 (*origin_it), - *rate_it - ); + return new CEmitter (WallpaperEngine::Core::aToVector3 (*directions_it), *distancemax_it, *distancemin_it, + (id_it == data.end () ? 0 : static_cast (*id_it)), *name_it, + WallpaperEngine::Core::aToVector3 (*origin_it), *rate_it); } -CEmitter::CEmitter ( - const glm::vec3& directions, - uint32_t distancemax, - uint32_t distancemin, - uint32_t id, - std::string name, - const glm::vec3& origin, - double rate): +CEmitter::CEmitter (const glm::vec3& directions, uint32_t distancemax, uint32_t distancemin, uint32_t id, + std::string name, const glm::vec3& origin, double rate) : m_directions (directions), m_distancemax (distancemax), m_distancemin (distancemin), m_id (id), - m_name (std::move(name)), + m_name (std::move (name)), m_origin (origin), - m_rate (rate) -{ -} + m_rate (rate) {} -uint32_t CEmitter::getId () const -{ +uint32_t CEmitter::getId () const { return this->m_id; } -const std::string& CEmitter::getName () const -{ +const std::string& CEmitter::getName () const { return this->m_name; } -const uint32_t CEmitter::getDistanceMax () const -{ +const uint32_t CEmitter::getDistanceMax () const { return this->m_distancemax; } -const uint32_t CEmitter::getDistanceMin () const -{ +const uint32_t CEmitter::getDistanceMin () const { return this->m_distancemin; } -const glm::vec3& CEmitter::getDirections () const -{ +const glm::vec3& CEmitter::getDirections () const { return this->m_directions; } -const glm::vec3& CEmitter::getOrigin () const -{ +const glm::vec3& CEmitter::getOrigin () const { return this->m_origin; } -const double CEmitter::getRate () const -{ +const double CEmitter::getRate () const { return this->m_rate; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h index d6a6f0f..c34e34b 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h +++ b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h @@ -2,67 +2,63 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Particles -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Objects::Particles { +using json = nlohmann::json; + +/** + * Particle emitter, controls the area where the particles have to be created + */ +class CEmitter { + public: + static CEmitter* fromJSON (json data); /** - * Particle emitter, controls the area where the particles have to be created + * @return The ID of the emitter */ - class CEmitter - { - public: - static CEmitter* fromJSON (json data); + [[nodiscard]] uint32_t getId () const; + /** + * @return The name of the emitter, indicates what type of emission to do + */ + [[nodiscard]] const std::string& getName () const; + /** + * @return The maximum distance a particle can travel before being dead + */ + [[nodiscard]] const uint32_t getDistanceMax () const; + /** + * @return The minimum distance a particle can travel before being dead + */ + [[nodiscard]] const uint32_t getDistanceMin () const; + /** + * @return The direction a particle should move to + */ + [[nodiscard]] const glm::vec3& getDirections () const; + /** + * @return The center of the particle emission + */ + [[nodiscard]] const glm::vec3& getOrigin () const; + /** + * @return The rate of particle emission + */ + [[nodiscard]] const double getRate () const; - /** - * @return The ID of the emitter - */ - [[nodiscard]] uint32_t getId () const; - /** - * @return The name of the emitter, indicates what type of emission to do - */ - [[nodiscard]] const std::string& getName () const; - /** - * @return The maximum distance a particle can travel before being dead - */ - [[nodiscard]] const uint32_t getDistanceMax () const; - /** - * @return The minimum distance a particle can travel before being dead - */ - [[nodiscard]] const uint32_t getDistanceMin () const; - /** - * @return The direction a particle should move to - */ - [[nodiscard]] const glm::vec3& getDirections () const; - /** - * @return The center of the particle emission - */ - [[nodiscard]] const glm::vec3& getOrigin () const; - /** - * @return The rate of particle emission - */ - [[nodiscard]] const double getRate () const; + protected: + CEmitter (const glm::vec3& directions, uint32_t distancemax, uint32_t distancemin, uint32_t id, std::string name, + const glm::vec3& origin, double rate); - protected: - CEmitter ( - const glm::vec3& directions, uint32_t distancemax, uint32_t distancemin, uint32_t id, std::string name, - const glm::vec3& origin, double rate - ); - - private: - /** Direction the particles should move to */ - glm::vec3 m_directions; - /** Maximum distance before the particle is dead */ - uint32_t m_distancemax; - /** Minimum distance before the particle is dead */ - uint32_t m_distancemin; - /** ID of the emitter */ - uint32_t m_id; - /** Name of the emitter, indicates the type of emitter */ - std::string m_name; - /** The center of the emitter */ - glm::vec3 m_origin; - /** The rate of emission */ - double m_rate; - }; -} + private: + /** Direction the particles should move to */ + glm::vec3 m_directions; + /** Maximum distance before the particle is dead */ + uint32_t m_distancemax; + /** Minimum distance before the particle is dead */ + uint32_t m_distancemin; + /** ID of the emitter */ + uint32_t m_id; + /** Name of the emitter, indicates the type of emitter */ + std::string m_name; + /** The center of the emitter */ + glm::vec3 m_origin; + /** The rate of emission */ + double m_rate; +}; +} // namespace WallpaperEngine::Core::Objects::Particles diff --git a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp index 84d9db1..f7e1168 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp @@ -1,75 +1,56 @@ -#include "common.h" #include "CInitializer.h" +#include "common.h" -#include "WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h" -#include "WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h" -#include "WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h" -#include "WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h" -#include "WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h" #include "WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h" #include "WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h" +#include "WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h" +#include "WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h" +#include "WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h" +#include "WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h" #include "WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h" +#include "WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h" using namespace WallpaperEngine::Core::Objects::Particles; -CInitializer* CInitializer::fromJSON (json data) -{ - auto id_it = data.find ("id"); - auto name_it = jsonFindRequired (data, "name", "Particle's initializer must have a name"); - uint32_t id = ((id_it == data.end ()) ? 0 : (uint32_t) (*id_it)); +CInitializer* CInitializer::fromJSON (json data) { + const auto id_it = data.find ("id"); + const auto name_it = jsonFindRequired (data, "name", "Particle's initializer must have a name"); + const uint32_t id = ((id_it == data.end ()) ? 0 : static_cast (*id_it)); - if (*name_it == "lifetimerandom") - { + if (*name_it == "lifetimerandom") { return Initializers::CLifeTimeRandom::fromJSON (data, id); } - else if (*name_it == "sizerandom") - { + if (*name_it == "sizerandom") { return Initializers::CSizeRandom::fromJSON (data, id); } - else if (*name_it == "rotationrandom") - { + if (*name_it == "rotationrandom") { return Initializers::CRotationRandom::fromJSON (data, id); } - else if (*name_it == "velocityrandom") - { + if (*name_it == "velocityrandom") { return Initializers::CVelocityRandom::fromJSON (data, id); } - else if (*name_it == "colorrandom") - { + if (*name_it == "colorrandom") { return Initializers::CColorRandom::fromJSON (data, id); } - else if (*name_it == "alpharandom") - { + if (*name_it == "alpharandom") { return Initializers::CAlphaRandom::fromJSON (data, id); } - else if (*name_it == "angularvelocityrandom") - { + if (*name_it == "angularvelocityrandom") { return Initializers::CAngularVelocityRandom::fromJSON (data, id); } - else if (*name_it == "turbulentvelocityrandom") - { + if (*name_it == "turbulentvelocityrandom") { return Initializers::CTurbulentVelocityRandom::fromJSON (data, id); } - else - { - sLog.exception ("Found unknown initializer for particles: ", *name_it); - } + + sLog.exception ("Found unknown initializer for particles: ", *name_it); } +CInitializer::CInitializer (uint32_t id, std::string name) : m_id (id), m_name (std::move (name)) {} -CInitializer::CInitializer (uint32_t id, std::string name) : - m_id (id), - m_name (std::move(name)) -{ -} - - -const std::string& CInitializer::getName () const -{ +const std::string& CInitializer::getName () const { return this->m_name; } -uint32_t CInitializer::getId () const -{ +uint32_t CInitializer::getId () const { return this->m_id; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h index c76d728..e085f6c 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h +++ b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h @@ -2,35 +2,33 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Particles -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Objects::Particles { +using json = nlohmann::json; + +/** + * Initializer for particles, controls the different attributes a particle will have + * on emission + */ +class CInitializer { + public: + static CInitializer* fromJSON (json data); /** - * Initializer for particles, controls the different attributes a particle will have - * on emission + * @return The name of the particle initializer, indicates what type of initialization to do */ - class CInitializer - { - public: - static CInitializer* fromJSON (json data); + [[nodiscard]] const std::string& getName () const; + /** + * @return The id of the initializer + */ + [[nodiscard]] uint32_t getId () const; - /** - * @return The name of the particle initializer, indicates what type of initialization to do - */ - [[nodiscard]] const std::string& getName () const; - /** - * @return The id of the initializer - */ - [[nodiscard]] uint32_t getId () const; + protected: + CInitializer (uint32_t id, std::string name); - protected: - CInitializer (uint32_t id, std::string name); - - private: - /** ID for ordering purposes */ - uint32_t m_id; - /** The name of the initializer, indicates what type of initialization to do */ - std::string m_name; - }; -} + private: + /** ID for ordering purposes */ + uint32_t m_id; + /** The name of the initializer, indicates what type of initialization to do */ + std::string m_name; +}; +} // namespace WallpaperEngine::Core::Objects::Particles diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp index 27200b9..c54ca63 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp @@ -2,27 +2,22 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CAlphaRandom* CAlphaRandom::fromJSON (json data, uint32_t id) -{ - auto min_it = jsonFindRequired (data, "min", "Alpharandom initializer must have a minimum value"); - auto max_it = jsonFindRequired (data, "max", "Alpharandom initializer must have a maximum value"); +CAlphaRandom* CAlphaRandom::fromJSON (json data, uint32_t id) { + const auto min_it = jsonFindRequired (data, "min", "Alpharandom initializer must have a minimum value"); + const auto max_it = jsonFindRequired (data, "max", "Alpharandom initializer must have a maximum value"); return new CAlphaRandom (id, *min_it, *max_it); } CAlphaRandom::CAlphaRandom (uint32_t id, double min, double max) : - CInitializer (id, "alpharandom"), - m_min (min), - m_max (max) -{ -} + CInitializer (id, "alpharandom"), + m_min (min), + m_max (max) {} -double CAlphaRandom::getMinimum () const -{ +double CAlphaRandom::getMinimum () const { return this->m_min; } -double CAlphaRandom::getMaximum () const -{ +double CAlphaRandom::getMaximum () const { return this->m_max; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h index c8169ae..8df942a 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h @@ -3,34 +3,32 @@ #include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/Objects/Particles/CInitializer.h" -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ - /** - * Initializer for particles that decides the base alpha for the particles - */ - class CAlphaRandom : CInitializer - { - public: - /** - * @return The minimum alpha value to be used - */ - [[nodiscard]] double getMinimum () const; - /** - * @return The maximum alpha value to be used - */ - [[nodiscard]] double getMaximum () const; +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the base alpha for the particles + */ +class CAlphaRandom : CInitializer { + public: + /** + * @return The minimum alpha value to be used + */ + [[nodiscard]] double getMinimum () const; + /** + * @return The maximum alpha value to be used + */ + [[nodiscard]] double getMaximum () const; - protected: - friend class CInitializer; + protected: + friend class CInitializer; - static CAlphaRandom* fromJSON (json data, uint32_t id); + static CAlphaRandom* fromJSON (json data, uint32_t id); - CAlphaRandom (uint32_t id, double min, double max); + CAlphaRandom (uint32_t id, double min, double max); - private: - /** Maximum alpha */ - double m_max; - /** Minimum alpha */ - double m_min; - }; -} + private: + /** Maximum alpha */ + double m_max; + /** Minimum alpha */ + double m_min; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp index 8e3bc4c..2d0e61c 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp @@ -2,32 +2,23 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CAngularVelocityRandom* CAngularVelocityRandom::fromJSON (json data, uint32_t id) -{ - auto min_it = jsonFindRequired (data, "min", "Angularvelocityrandom initializer must have a minimum value"); - auto max_it = jsonFindRequired (data, "max", "Angularvelocityrandom initializer must have a maximum value"); +CAngularVelocityRandom* CAngularVelocityRandom::fromJSON (json data, uint32_t id) { + const auto min_it = jsonFindRequired (data, "min", "Angularvelocityrandom initializer must have a minimum value"); + const auto max_it = jsonFindRequired (data, "max", "Angularvelocityrandom initializer must have a maximum value"); - return new CAngularVelocityRandom ( - id, - WallpaperEngine::Core::aToVector3 (*min_it), - WallpaperEngine::Core::aToVector3 (*max_it) - ); + return new CAngularVelocityRandom (id, WallpaperEngine::Core::aToVector3 (*min_it), + WallpaperEngine::Core::aToVector3 (*max_it)); } - CAngularVelocityRandom::CAngularVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max) : - CInitializer (id, "angularvelocityrandom"), - m_min (min), - m_max (max) -{ -} + CInitializer (id, "angularvelocityrandom"), + m_min (min), + m_max (max) {} -const glm::vec3& CAngularVelocityRandom::getMinimum () const -{ +const glm::vec3& CAngularVelocityRandom::getMinimum () const { return this->m_min; } -const glm::vec3& CAngularVelocityRandom::getMaximum () const -{ +const glm::vec3& CAngularVelocityRandom::getMaximum () const { return this->m_max; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h index ef45cb2..b04d87d 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h @@ -3,34 +3,32 @@ #include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/Objects/Particles/CInitializer.h" -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ - /** - * Initializer for particles that decides the base angular velocity for particles - */ - class CAngularVelocityRandom : CInitializer - { - public: - /** - * @return Minimum angular velocity (direction * speed) - */ - [[nodiscard]] const glm::vec3& getMinimum () const; - /** - * @return Maximum angular velocity (direction * speed) - */ - [[nodiscard]] const glm::vec3& getMaximum () const; +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the base angular velocity for particles + */ +class CAngularVelocityRandom : CInitializer { + public: + /** + * @return Minimum angular velocity (direction * speed) + */ + [[nodiscard]] const glm::vec3& getMinimum () const; + /** + * @return Maximum angular velocity (direction * speed) + */ + [[nodiscard]] const glm::vec3& getMaximum () const; - protected: - friend class CInitializer; + protected: + friend class CInitializer; - static CAngularVelocityRandom* fromJSON (json data, uint32_t id); + static CAngularVelocityRandom* fromJSON (json data, uint32_t id); - CAngularVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max); + CAngularVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max); - private: - /** Maximum velocity (direction * speed) */ - glm::vec3 m_max; - /** Minimum velocity (direction * speed) */ - glm::vec3 m_min; - }; -} + private: + /** Maximum velocity (direction * speed) */ + glm::vec3 m_max; + /** Minimum velocity (direction * speed) */ + glm::vec3 m_min; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp index 210cfe1..a2952a2 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp @@ -2,32 +2,23 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CColorRandom* CColorRandom::fromJSON (json data, uint32_t id) -{ - auto min_it = jsonFindRequired (data, "min", "Colorrandom initializer must have a minimum value"); - auto max_it = jsonFindRequired (data, "max", "Colorrandom initializer must have a maximum value"); +CColorRandom* CColorRandom::fromJSON (json data, uint32_t id) { + const auto min_it = jsonFindRequired (data, "min", "Colorrandom initializer must have a minimum value"); + const auto max_it = jsonFindRequired (data, "max", "Colorrandom initializer must have a maximum value"); - return new CColorRandom ( - id, - WallpaperEngine::Core::aToColori (*min_it), - WallpaperEngine::Core::aToColori (*max_it) - ); + return new CColorRandom (id, WallpaperEngine::Core::aToColori (*min_it), + WallpaperEngine::Core::aToColori (*max_it)); } - CColorRandom::CColorRandom (uint32_t id, glm::ivec3 min, glm::ivec3 max) : - CInitializer (id, "colorrandom"), - m_min (min), - m_max (max) -{ -} + CInitializer (id, "colorrandom"), + m_min (min), + m_max (max) {} -const glm::ivec3& CColorRandom::getMinimum () const -{ +const glm::ivec3& CColorRandom::getMinimum () const { return this->m_min; } -const glm::ivec3& CColorRandom::getMaximum () const -{ +const glm::ivec3& CColorRandom::getMaximum () const { return this->m_max; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h index 338994b..af7cc2d 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h @@ -4,34 +4,32 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ - /** - * Initializer for particles that decides the base color - */ - class CColorRandom : CInitializer - { - public: - /** - * @return The minimum color to use (RGB) - */ - [[nodiscard]] const glm::ivec3& getMinimum () const; - /** - * @return The maximum color to use (RGB) - */ - [[nodiscard]] const glm::ivec3& getMaximum () const; +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the base color + */ +class CColorRandom : CInitializer { + public: + /** + * @return The minimum color to use (RGB) + */ + [[nodiscard]] const glm::ivec3& getMinimum () const; + /** + * @return The maximum color to use (RGB) + */ + [[nodiscard]] const glm::ivec3& getMaximum () const; - protected: - friend class CInitializer; + protected: + friend class CInitializer; - static CColorRandom* fromJSON (json data, uint32_t id); + static CColorRandom* fromJSON (json data, uint32_t id); - CColorRandom (uint32_t id, glm::ivec3 min, glm::ivec3 max); + CColorRandom (uint32_t id, glm::ivec3 min, glm::ivec3 max); - private: - /** Maximum color */ - glm::ivec3 m_max; - /** Minimum color */ - glm::ivec3 m_min; - }; -} + private: + /** Maximum color */ + glm::ivec3 m_max; + /** Minimum color */ + glm::ivec3 m_min; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp index fa7b5b9..cdc008d 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp @@ -2,28 +2,22 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CLifeTimeRandom* CLifeTimeRandom::fromJSON (json data, uint32_t id) -{ - auto min_it = jsonFindRequired (data, "min", "Lifetimerandom initializer must have a minimum value"); - auto max_it = jsonFindRequired (data, "max", "Lifetimerandom initializer must have a maximum value"); +CLifeTimeRandom* CLifeTimeRandom::fromJSON (json data, uint32_t id) { + const auto min_it = jsonFindRequired (data, "min", "Lifetimerandom initializer must have a minimum value"); + const auto max_it = jsonFindRequired (data, "max", "Lifetimerandom initializer must have a maximum value"); return new CLifeTimeRandom (id, *min_it, *max_it); } - CLifeTimeRandom::CLifeTimeRandom (uint32_t id, uint32_t min, uint32_t max) : CInitializer (id, "lifetimerandom"), m_min (min), - m_max (max) -{ -} + m_max (max) {} -uint32_t CLifeTimeRandom::getMinimum () const -{ +uint32_t CLifeTimeRandom::getMinimum () const { return this->m_min; } -uint32_t CLifeTimeRandom::getMaximum () const -{ +uint32_t CLifeTimeRandom::getMaximum () const { return this->m_max; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h index 2db0a7e..6285efb 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h @@ -4,33 +4,32 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the lifetime of each particle on startup + */ +class CLifeTimeRandom : CInitializer { + public: /** - * Initializer for particles that decides the lifetime of each particle on startup + * @return The minimum lifetime to be used */ - class CLifeTimeRandom : CInitializer - { - public: - /** - * @return The minimum lifetime to be used - */ - [[nodiscard]] uint32_t getMinimum () const; - /** - * @return The maximum lifetime to be used - */ - [[nodiscard]] uint32_t getMaximum () const; - protected: - friend class CInitializer; + [[nodiscard]] uint32_t getMinimum () const; + /** + * @return The maximum lifetime to be used + */ + [[nodiscard]] uint32_t getMaximum () const; - static CLifeTimeRandom* fromJSON (json data, uint32_t id); + protected: + friend class CInitializer; - CLifeTimeRandom (uint32_t id, uint32_t min, uint32_t max); + static CLifeTimeRandom* fromJSON (json data, uint32_t id); - private: - /** Maximum lifetime */ - uint32_t m_max; - /** Minimum lifetime */ - uint32_t m_min; - }; -} + CLifeTimeRandom (uint32_t id, uint32_t min, uint32_t max); + + private: + /** Maximum lifetime */ + uint32_t m_max; + /** Minimum lifetime */ + uint32_t m_min; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp index 8baa9e5..384e8d9 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp @@ -4,10 +4,9 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CRotationRandom* CRotationRandom::fromJSON (json data, uint32_t id) -{ - auto min_it = data.find ("minVector"); - auto max_it = data.find ("max"); +CRotationRandom* CRotationRandom::fromJSON (json data, uint32_t id) { + const auto min_it = data.find ("minVector"); + const auto max_it = data.find ("max"); glm::vec3 minVector = glm::vec3 (); glm::vec3 maxVector = glm::vec3 (); @@ -16,24 +15,18 @@ CRotationRandom* CRotationRandom::fromJSON (json data, uint32_t id) bool isMinVector = false; bool isMaxVector = false; - if (min_it != data.end () && min_it->is_string ()) - { + if (min_it != data.end () && min_it->is_string ()) { minVector = WallpaperEngine::Core::aToVector3 (*min_it); isMinVector = true; - } - else if (min_it != data.end () && min_it->is_number ()) - { + } else if (min_it != data.end () && min_it->is_number ()) { minNumber = *min_it; isMinVector = false; } - if (max_it != data.end () && max_it->is_string ()) - { + if (max_it != data.end () && max_it->is_string ()) { maxVector = WallpaperEngine::Core::aToVector3 (*max_it); isMaxVector = true; - } - else if(max_it != data.end () && max_it->is_number ()) - { + } else if (max_it != data.end () && max_it->is_number ()) { maxNumber = *max_it; isMaxVector = false; } @@ -41,61 +34,44 @@ CRotationRandom* CRotationRandom::fromJSON (json data, uint32_t id) return new CRotationRandom (id, minVector, minNumber, isMinVector, maxVector, maxNumber, isMaxVector); } -CRotationRandom::CRotationRandom ( - uint32_t id, - glm::vec3 minVector, - double minNumber, - bool isMinimumVector, - glm::vec3 maxVector, - double maxNumber, - bool isMaximumVector -) : +CRotationRandom::CRotationRandom (uint32_t id, glm::vec3 minVector, double minNumber, bool isMinimumVector, + glm::vec3 maxVector, double maxNumber, bool isMaximumVector) : CInitializer (id, "rotationrandom"), m_minVector (minVector), m_maxVector (maxVector), m_minNumber (minNumber), m_maxNumber (maxNumber), m_isMinimumVector (isMinimumVector), - m_isMaximumVector (isMaximumVector) -{ -} + m_isMaximumVector (isMaximumVector) {} -glm::vec3 CRotationRandom::getMinimumVector () const -{ +glm::vec3 CRotationRandom::getMinimumVector () const { return this->m_minVector; } -glm::vec3 CRotationRandom::getMaximumVector () const -{ +glm::vec3 CRotationRandom::getMaximumVector () const { return this->m_maxVector; } -double CRotationRandom::getMinimumNumber () const -{ +double CRotationRandom::getMinimumNumber () const { return this->m_minNumber; } -double CRotationRandom::getMaximumNumber () const -{ +double CRotationRandom::getMaximumNumber () const { return this->m_maxNumber; } -bool CRotationRandom::isMinimumVector () const -{ +bool CRotationRandom::isMinimumVector () const { return this->m_isMinimumVector; } -bool CRotationRandom::isMinimumNumber () const -{ +bool CRotationRandom::isMinimumNumber () const { return !this->m_isMinimumVector; } -bool CRotationRandom::isMaximumVector () const -{ +bool CRotationRandom::isMaximumVector () const { return this->m_isMaximumVector; } -bool CRotationRandom::isMaximumNumber () const -{ +bool CRotationRandom::isMaximumNumber () const { return !this->m_isMaximumVector; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h index 3f9f3f1..5e92e7c 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h @@ -4,76 +4,67 @@ #include -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the base rotation for the particles + */ +class CRotationRandom : CInitializer { + public: /** - * Initializer for particles that decides the base rotation for the particles + * @return The minimum rotation in vector format if available */ - class CRotationRandom : CInitializer - { - public: - /** - * @return The minimum rotation in vector format if available - */ - [[nodiscard]] glm::vec3 getMinimumVector () const; - /** - * @return The maximum rotation in vector format if available - */ - [[nodiscard]] glm::vec3 getMaximumVector () const; - /** - * @return The minimum rotation in angle format if available - */ - [[nodiscard]] double getMinimumNumber () const; - /** - * @return The maximum rotation in angle format if available - */ - [[nodiscard]] double getMaximumNumber () const; + [[nodiscard]] glm::vec3 getMinimumVector () const; + /** + * @return The maximum rotation in vector format if available + */ + [[nodiscard]] glm::vec3 getMaximumVector () const; + /** + * @return The minimum rotation in angle format if available + */ + [[nodiscard]] double getMinimumNumber () const; + /** + * @return The maximum rotation in angle format if available + */ + [[nodiscard]] double getMaximumNumber () const; - /** - * @return Indicates if the minimum rotation is a vector - */ - [[nodiscard]] bool isMinimumVector () const; - /** - * @return Indicates if the minimum rotation is an angle - */ - [[nodiscard]] bool isMinimumNumber () const; - /** - * @return Indicates if the maximum rotation is a vector - */ - [[nodiscard]] bool isMaximumVector () const; - /** - * @return Indicates if the maximum rotation is an angle - */ - [[nodiscard]] bool isMaximumNumber () const; + /** + * @return Indicates if the minimum rotation is a vector + */ + [[nodiscard]] bool isMinimumVector () const; + /** + * @return Indicates if the minimum rotation is an angle + */ + [[nodiscard]] bool isMinimumNumber () const; + /** + * @return Indicates if the maximum rotation is a vector + */ + [[nodiscard]] bool isMaximumVector () const; + /** + * @return Indicates if the maximum rotation is an angle + */ + [[nodiscard]] bool isMaximumNumber () const; - protected: - friend class CInitializer; + protected: + friend class CInitializer; - static CRotationRandom* fromJSON (json data, uint32_t id); + static CRotationRandom* fromJSON (json data, uint32_t id); - CRotationRandom ( - uint32_t id, - glm::vec3 minVector, - double minNumber, - bool isMinimumVector, - glm::vec3 maxVector, - double maxNumber, - bool isMaximumVector - ); + CRotationRandom (uint32_t id, glm::vec3 minVector, double minNumber, bool isMinimumVector, glm::vec3 maxVector, + double maxNumber, bool isMaximumVector); - private: - /** Maximum rotation vector */ - glm::vec3 m_maxVector; - /** Maximum rotation angle */ - double m_maxNumber; - /** Minimum rotation vector */ - glm::vec3 m_minVector; - /** Minimum rotation angle */ - double m_minNumber; + private: + /** Maximum rotation vector */ + glm::vec3 m_maxVector; + /** Maximum rotation angle */ + double m_maxNumber; + /** Minimum rotation vector */ + glm::vec3 m_minVector; + /** Minimum rotation angle */ + double m_minNumber; - /** If minimum is a vector */ - bool m_isMinimumVector; - /** If maximum is a vector */ - bool m_isMaximumVector; - }; -} + /** If minimum is a vector */ + bool m_isMinimumVector; + /** If maximum is a vector */ + bool m_isMaximumVector; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp index fde4dad..af455fa 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp @@ -2,10 +2,9 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CSizeRandom* CSizeRandom::fromJSON (json data, uint32_t id) -{ - auto min_it = jsonFindRequired (data, "min", "Sizerandom initializer must have a minimum value"); - auto max_it = jsonFindRequired (data, "max", "Sizerandom initializer must have a maximum value"); +CSizeRandom* CSizeRandom::fromJSON (json data, uint32_t id) { + const auto min_it = jsonFindRequired (data, "min", "Sizerandom initializer must have a minimum value"); + const auto max_it = jsonFindRequired (data, "max", "Sizerandom initializer must have a maximum value"); return new CSizeRandom (id, *min_it, *max_it); } @@ -13,16 +12,12 @@ CSizeRandom* CSizeRandom::fromJSON (json data, uint32_t id) CSizeRandom::CSizeRandom (uint32_t id, uint32_t min, uint32_t max) : CInitializer (id, "sizerandom"), m_min (min), - m_max (max) -{ -} + m_max (max) {} -uint32_t CSizeRandom::getMinimum () const -{ +uint32_t CSizeRandom::getMinimum () const { return this->m_min; } -uint32_t CSizeRandom::getMaximum () const -{ +uint32_t CSizeRandom::getMaximum () const { return this->m_max; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h index 156ef3e..9dcf4f9 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h @@ -4,34 +4,32 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the base size for the particles + */ +class CSizeRandom : CInitializer { + public: /** - * Initializer for particles that decides the base size for the particles + * @return The minimum size to be used */ - class CSizeRandom : CInitializer - { - public: - /** - * @return The minimum size to be used - */ - [[nodiscard]] uint32_t getMinimum () const; - /** - * @return The maximum size to be used - */ - [[nodiscard]] uint32_t getMaximum () const; + [[nodiscard]] uint32_t getMinimum () const; + /** + * @return The maximum size to be used + */ + [[nodiscard]] uint32_t getMaximum () const; - protected: - friend class CInitializer; + protected: + friend class CInitializer; - static CSizeRandom* fromJSON (json data, uint32_t id); + static CSizeRandom* fromJSON (json data, uint32_t id); - CSizeRandom (uint32_t id, uint32_t min, uint32_t max); + CSizeRandom (uint32_t id, uint32_t min, uint32_t max); - private: - /** Maximum size */ - uint32_t m_max; - /** Minimum size */ - uint32_t m_min; - }; -} + private: + /** Maximum size */ + uint32_t m_max; + /** Minimum size */ + uint32_t m_min; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp index 7db3190..e42877e 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp @@ -1,17 +1,16 @@ -#include "common.h" #include "CTurbulentVelocityRandom.h" +#include "common.h" #include "WallpaperEngine/Core/Core.h" using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CTurbulentVelocityRandom* CTurbulentVelocityRandom::fromJSON (json data, uint32_t id) -{ - json::const_iterator phasemax_it = data.find ("phasemax"); - json::const_iterator scale_it = data.find ("scale"); - json::const_iterator speedmax_it = data.find ("speedmax"); - json::const_iterator speedmin_it = data.find ("speedmin"); - json::const_iterator timescale_it = data.find ("timescale"); +CTurbulentVelocityRandom* CTurbulentVelocityRandom::fromJSON (json data, uint32_t id) { + const auto phasemax_it = data.find ("phasemax"); + const auto scale_it = data.find ("scale"); + const auto speedmax_it = data.find ("speedmax"); + const auto speedmin_it = data.find ("speedmin"); + const auto timescale_it = data.find ("timescale"); if (phasemax_it == data.end ()) sLog.exception ("TurbulentVelocityRandom initializer must have a phasemax value"); @@ -24,50 +23,34 @@ CTurbulentVelocityRandom* CTurbulentVelocityRandom::fromJSON (json data, uint32_ if (timescale_it == data.end ()) sLog.exception ("TurbulentVelocityRandom initializer must have a timescale value"); - return new CTurbulentVelocityRandom ( - id, - *phasemax_it, - *scale_it, - *timescale_it, - *speedmin_it, - *speedmax_it - ); + return new CTurbulentVelocityRandom (id, *phasemax_it, *scale_it, *timescale_it, *speedmin_it, *speedmax_it); } - -CTurbulentVelocityRandom::CTurbulentVelocityRandom (uint32_t id, - double phasemax, double scale, double timescale, uint32_t speedmin, uint32_t speedmax) : +CTurbulentVelocityRandom::CTurbulentVelocityRandom (uint32_t id, double phasemax, double scale, double timescale, + uint32_t speedmin, uint32_t speedmax) : CInitializer (id, "turbulentvelocityrandom"), m_phasemax (phasemax), m_scale (scale), m_timescale (timescale), m_speedmin (speedmin), - m_speedmax (speedmax) -{ -} + m_speedmax (speedmax) {} - -double CTurbulentVelocityRandom::getPhaseMax () -{ +double CTurbulentVelocityRandom::getPhaseMax () { return this->m_phasemax; } -double CTurbulentVelocityRandom::getScale () -{ +double CTurbulentVelocityRandom::getScale () { return this->m_scale; } -double CTurbulentVelocityRandom::getTimeScale () -{ +double CTurbulentVelocityRandom::getTimeScale () { return this->m_timescale; } -uint32_t CTurbulentVelocityRandom::getMinimumSpeed () -{ +uint32_t CTurbulentVelocityRandom::getMinimumSpeed () { return this->m_speedmin; } -uint32_t CTurbulentVelocityRandom::getMaximumSpeed () -{ +uint32_t CTurbulentVelocityRandom::getMaximumSpeed () { return this->m_speedmax; } diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h index f8a1ebd..33250fc 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h @@ -4,53 +4,51 @@ #include -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the turbulent velocity for the particles + */ +class CTurbulentVelocityRandom : CInitializer { + public: /** - * Initializer for particles that decides the turbulent velocity for the particles + * @return The phase to use */ - class CTurbulentVelocityRandom : CInitializer - { - public: - /** - * @return The phase to use - */ - double getPhaseMax (); - /** - * @return The scale to use - */ - double getScale (); - /** - * @return How time affects to the scale - */ - double getTimeScale (); - /** - * @return The minimum speed - */ - uint32_t getMinimumSpeed (); - /** - * @return The maximum speed - */ - uint32_t getMaximumSpeed (); + double getPhaseMax (); + /** + * @return The scale to use + */ + double getScale (); + /** + * @return How time affects to the scale + */ + double getTimeScale (); + /** + * @return The minimum speed + */ + uint32_t getMinimumSpeed (); + /** + * @return The maximum speed + */ + uint32_t getMaximumSpeed (); - protected: - friend class CInitializer; + protected: + friend class CInitializer; - static CTurbulentVelocityRandom* fromJSON (json data, uint32_t id); + static CTurbulentVelocityRandom* fromJSON (json data, uint32_t id); - CTurbulentVelocityRandom (uint32_t id, - double phasemax, double scale, double timescale, uint32_t speedmin, uint32_t speedmax); + CTurbulentVelocityRandom (uint32_t id, double phasemax, double scale, double timescale, uint32_t speedmin, + uint32_t speedmax); - private: - /** Phase */ - double m_phasemax; - /** Scale */ - double m_scale; - /** Time scale, how the time affects the scale */ - double m_timescale; - /** Minimum speed */ - uint32_t m_speedmin; - /** Maximum speed */ - uint32_t m_speedmax; - }; -} + private: + /** Phase */ + double m_phasemax; + /** Scale */ + double m_scale; + /** Time scale, how the time affects the scale */ + double m_timescale; + /** Minimum speed */ + uint32_t m_speedmin; + /** Maximum speed */ + uint32_t m_speedmax; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp index c525b5d..847db03 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp @@ -2,32 +2,23 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CVelocityRandom* CVelocityRandom::fromJSON (json data, uint32_t id) -{ - auto min_it = jsonFindRequired (data, "min", "Velocityrandom initializer must have a minimum value"); - auto max_it = jsonFindRequired (data, "max", "Velocityrandom initializer must have a maximum value"); +CVelocityRandom* CVelocityRandom::fromJSON (json data, uint32_t id) { + const auto min_it = jsonFindRequired (data, "min", "Velocityrandom initializer must have a minimum value"); + const auto max_it = jsonFindRequired (data, "max", "Velocityrandom initializer must have a maximum value"); - return new CVelocityRandom ( - id, - WallpaperEngine::Core::aToVector3 (*min_it), - WallpaperEngine::Core::aToVector3 (*max_it) - ); + return new CVelocityRandom (id, WallpaperEngine::Core::aToVector3 (*min_it), + WallpaperEngine::Core::aToVector3 (*max_it)); } - CVelocityRandom::CVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max) : CInitializer (id, "velocityrandom"), m_min (min), - m_max (max) -{ -} + m_max (max) {} -const glm::vec3& CVelocityRandom::getMinimum () const -{ +const glm::vec3& CVelocityRandom::getMinimum () const { return this->m_min; } -const glm::vec3& CVelocityRandom::getMaximum () const -{ +const glm::vec3& CVelocityRandom::getMaximum () const { return this->m_max; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h index 0d56209..bce80b1 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h @@ -4,34 +4,32 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Objects::Particles::Initializers -{ +namespace WallpaperEngine::Core::Objects::Particles::Initializers { +/** + * Initializer for particles that decides the base velocity for the particles + */ +class CVelocityRandom : CInitializer { + public: /** - * Initializer for particles that decides the base velocity for the particles + * @return The minimum velocity (direction * speed) */ - class CVelocityRandom : CInitializer - { - public: - /** - * @return The minimum velocity (direction * speed) - */ - [[nodiscard]] const glm::vec3& getMinimum () const; - /** - * @return The maximum velocity (direction * speed) - */ - [[nodiscard]] const glm::vec3& getMaximum () const; + [[nodiscard]] const glm::vec3& getMinimum () const; + /** + * @return The maximum velocity (direction * speed) + */ + [[nodiscard]] const glm::vec3& getMaximum () const; - protected: - friend class CInitializer; + protected: + friend class CInitializer; - static CVelocityRandom* fromJSON (json data, uint32_t id); + static CVelocityRandom* fromJSON (json data, uint32_t id); - CVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max); + CVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max); - private: - /** Maximum velocity */ - glm::vec3 m_max; - /** Minimum velocity */ - glm::vec3 m_min; - }; -} + private: + /** Maximum velocity */ + glm::vec3 m_max; + /** Minimum velocity */ + glm::vec3 m_min; +}; +} // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Projects/CProperty.cpp b/src/WallpaperEngine/Core/Projects/CProperty.cpp index c489d06..fd8fdb0 100644 --- a/src/WallpaperEngine/Core/Projects/CProperty.cpp +++ b/src/WallpaperEngine/Core/Projects/CProperty.cpp @@ -1,17 +1,16 @@ -#include "common.h" -#include #include "CProperty.h" +#include "CPropertyBoolean.h" #include "CPropertyColor.h" #include "CPropertyCombo.h" #include "CPropertySlider.h" -#include "CPropertyBoolean.h" #include "CPropertyText.h" +#include "common.h" +#include using namespace WallpaperEngine::Core::Projects; -CProperty* CProperty::fromJSON (json data, const std::string& name) -{ - auto type = jsonFindRequired (data, "type", "Project properties must have the type field"); +CProperty* CProperty::fromJSON (json data, const std::string& name) { + const auto type = jsonFindRequired (data, "type", "Project properties must have the type field"); if (*type == CPropertyColor::Type) return CPropertyColor::fromJSON (data, name); @@ -24,7 +23,6 @@ CProperty* CProperty::fromJSON (json data, const std::string& name) if (*type == CPropertyText::Type) return CPropertyText::fromJSON (data, name); - // show the error and ignore this property sLog.error ("Unexpected type for property: ", *type); sLog.error (data); @@ -33,23 +31,18 @@ CProperty* CProperty::fromJSON (json data, const std::string& name) } CProperty::CProperty (std::string name, std::string type, std::string text) : - m_name (std::move(name)), - m_type (std::move(type)), - m_text (std::move(text)) -{ -} + m_name (std::move (name)), + m_type (std::move (type)), + m_text (std::move (text)) {} -const std::string& CProperty::getName () const -{ +const std::string& CProperty::getName () const { return this->m_name; } -const std::string& CProperty::getType () const -{ +const std::string& CProperty::getType () const { return this->m_type; } -const std::string& CProperty::getText () const -{ +const std::string& CProperty::getText () const { return this->m_text; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Projects/CProperty.h b/src/WallpaperEngine/Core/Projects/CProperty.h index a479975..ef26d68 100644 --- a/src/WallpaperEngine/Core/Projects/CProperty.h +++ b/src/WallpaperEngine/Core/Projects/CProperty.h @@ -2,60 +2,68 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Projects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Projects { +using json = nlohmann::json; - /** - * Represents a property in a background - * - * Properties are settings that alter how the background looks or works - * and are configurable by the user so they can customize it to their likings - */ - class CPropertyColor; +/** + * Represents a property in a background + * + * Properties are settings that alter how the background looks or works + * and are configurable by the user so they can customize it to their likings + */ +class CPropertyColor; - class CProperty - { - public: - static CProperty* fromJSON (json data, const std::string& name); +class CProperty { + public: + virtual ~CProperty () = default; + static CProperty* fromJSON (json data, const std::string& name); - template const T* as () const { assert (is ()); return (const T*) this; } - template T* as () { assert (is ()); return (T*) this; } + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); + } - template bool is () { return this->m_type == T::Type; } + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } - /** - * @return Representation of what the property does and the default values - */ - [[nodiscard]] virtual std::string dump () const = 0; - /** - * Updates the value of the property with the one in the string - * - * @param value New value for the property - */ - virtual void update (const std::string& value) = 0; + template bool is () { + return this->m_type == T::Type; + } - /** - * @return Name of the property - */ - [[nodiscard]] const std::string& getName () const; - /** - * @return Type of the property - */ - [[nodiscard]] const std::string& getType () const; - /** - * @return Text of the property - */ - [[nodiscard]] const std::string& getText () const; + /** + * @return Representation of what the property does and the default values + */ + [[nodiscard]] virtual std::string dump () const = 0; + /** + * Updates the value of the property with the one in the string + * + * @param value New value for the property + */ + virtual void update (const std::string& value) = 0; - protected: - CProperty (std::string name, std::string type, std::string text); + /** + * @return Name of the property + */ + [[nodiscard]] const std::string& getName () const; + /** + * @return Type of the property + */ + [[nodiscard]] const std::string& getType () const; + /** + * @return Text of the property + */ + [[nodiscard]] const std::string& getText () const; - /** Type of property */ - std::string m_type; - /** Name of the property */ - std::string m_name; - /** Description of the property for the user */ - std::string m_text; - }; -} + protected: + CProperty (std::string name, std::string type, std::string text); + + /** Type of property */ + std::string m_type; + /** Name of the property */ + std::string m_name; + /** Description of the property for the user */ + std::string m_text; +}; +} // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp index 1f68aa6..950cd9d 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp @@ -5,40 +5,35 @@ using namespace WallpaperEngine::Core::Projects; -CPropertyBoolean* CPropertyBoolean::fromJSON (json data, const std::string& name) -{ - json::const_iterator value = data.find ("value"); - auto text = jsonFindDefault (data, "text", ""); +CPropertyBoolean* CPropertyBoolean::fromJSON (json data, const std::string& name) { + const json::const_iterator value = data.find ("value"); + const auto text = jsonFindDefault (data, "text", ""); return new CPropertyBoolean (*value, name, text); } -bool CPropertyBoolean::getValue () const -{ +bool CPropertyBoolean::getValue () const { return this->m_value; } -void CPropertyBoolean::update (const std::string& value) -{ +void CPropertyBoolean::update (const std::string& value) { this->m_value = value == "1" || value == "true"; } -std::string CPropertyBoolean::dump () const -{ +std::string CPropertyBoolean::dump () const { std::stringstream ss; - ss - << this->m_name << " - boolean" << std::endl - << "\t" << "Description: " << this->m_text << std::endl - << "\t" << "Value: " << this->m_value; + ss << this->m_name << " - boolean" << std::endl + << "\t" + << "Description: " << this->m_text << std::endl + << "\t" + << "Value: " << this->m_value; - return ss.str(); + return ss.str (); } CPropertyBoolean::CPropertyBoolean (bool value, const std::string& name, const std::string& text) : CProperty (name, Type, text), - m_value (value) -{ -} + m_value (value) {} const std::string CPropertyBoolean::Type = "bool"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h index 591e7bd..de4702b 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h @@ -2,33 +2,31 @@ #include "CProperty.h" -namespace WallpaperEngine::Core::Projects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Projects { +using json = nlohmann::json; + +/** + * Represents a boolean property + */ +class CPropertyBoolean final : public CProperty { + public: + static CPropertyBoolean* fromJSON (json data, const std::string& name); /** - * Represents a boolean property + * @return The value of the property */ - class CPropertyBoolean : public CProperty - { - public: - static CPropertyBoolean* fromJSON (json data, const std::string& name); + [[nodiscard]] bool getValue () const; + /** @inheritdoc */ + [[nodiscard]] std::string dump () const override; + /** @inheritdoc */ + void update (const std::string& value) override; - /** - * @return The value of the property - */ - [[nodiscard]] bool getValue () const; - /** @inheritdoc */ - [[nodiscard]] std::string dump () const override; - /** @inheritdoc */ - void update (const std::string& value) override; + static const std::string Type; - static const std::string Type; + private: + CPropertyBoolean (bool value, const std::string& name, const std::string& text); - private: - CPropertyBoolean (bool value, const std::string& name, const std::string& text); - - /** Property's value */ - bool m_value; - }; -} + /** Property's value */ + bool m_value; +}; +} // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp b/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp index ab2e092..d350465 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp @@ -4,65 +4,50 @@ using namespace WallpaperEngine::Core::Projects; -glm::vec3 ParseColor (std::string value) -{ - if (value.find (',') != std::string::npos) - { +glm::vec3 ParseColor (std::string value) { + if (value.find (',') != std::string::npos) { // replace commas with dots so it can be parsed std::replace (value.begin (), value.end (), ',', ' '); } - if (value.find ('.') == std::string::npos && value != "0 0 0" && value != "1 1 1") - { - glm::ivec3 intcolor = WallpaperEngine::Core::aToColori (value); + if (value.find ('.') == std::string::npos && value != "0 0 0" && value != "1 1 1") { + const glm::ivec3 intcolor = WallpaperEngine::Core::aToColori (value); - return { - intcolor.r / 255.0, - intcolor.g / 255.0, - intcolor.b / 255.0 - }; + return {intcolor.r / 255.0, intcolor.g / 255.0, intcolor.b / 255.0}; } return WallpaperEngine::Core::aToColorf (value); } -CPropertyColor* CPropertyColor::fromJSON (json data, const std::string& name) -{ - std::string value = *jsonFindRequired (data, "value", "Color property must have a value"); - auto text = jsonFindDefault (data, "text", ""); +CPropertyColor* CPropertyColor::fromJSON (json data, const std::string& name) { + const std::string value = *jsonFindRequired (data, "value", "Color property must have a value"); + const auto text = jsonFindDefault (data, "text", ""); return new CPropertyColor (ParseColor (value), name, text); } -const glm::vec3& CPropertyColor::getValue () const -{ +const glm::vec3& CPropertyColor::getValue () const { return this->m_color; } -void CPropertyColor::update (const std::string& value) -{ +void CPropertyColor::update (const std::string& value) { this->m_color = ParseColor (std::string (value)); } -std::string CPropertyColor::dump () const -{ +std::string CPropertyColor::dump () const { std::stringstream ss; - ss - << this->m_name << " - color" << std::endl - << "\t" << "Description: " << this->m_text << std::endl - << "\t" - << "R: " << this->m_color.r - << " G: " << this->m_color.g - << " B: " << this->m_color.b; + ss << this->m_name << " - color" << std::endl + << "\t" + << "Description: " << this->m_text << std::endl + << "\t" + << "R: " << this->m_color.r << " G: " << this->m_color.g << " B: " << this->m_color.b; - return ss.str(); + return ss.str (); } CPropertyColor::CPropertyColor (glm::vec3 color, const std::string& name, const std::string& text) : CProperty (name, Type, text), - m_color (color) -{ -} + m_color (color) {} const std::string CPropertyColor::Type = "color"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Projects/CPropertyColor.h b/src/WallpaperEngine/Core/Projects/CPropertyColor.h index b1ff3ba..cdfb083 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyColor.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyColor.h @@ -4,30 +4,28 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Projects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Projects { +using json = nlohmann::json; + +/** + * Represents a color property + */ +class CPropertyColor final : public CProperty { + public: + static CPropertyColor* fromJSON (json data, const std::string& name); /** - * Represents a color property + * @return The RGB color value in the 0-1 range */ - class CPropertyColor : public CProperty - { - public: - static CPropertyColor* fromJSON (json data, const std::string& name); + [[nodiscard]] const glm::vec3& getValue () const; + [[nodiscard]] std::string dump () const override; + void update (const std::string& value) override; - /** - * @return The RGB color value in the 0-1 range - */ - [[nodiscard]] const glm::vec3& getValue () const; - [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; + static const std::string Type; - static const std::string Type; + private: + CPropertyColor (glm::vec3 color, const std::string& name, const std::string& text); - private: - CPropertyColor (glm::vec3 color, const std::string& name, const std::string& text); - - glm::vec3 m_color; - }; -} + glm::vec3 m_color; +}; +} // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp b/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp index 8c41826..c6aeac4 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp @@ -3,28 +3,22 @@ #include "CPropertyCombo.h" -#include #include "WallpaperEngine/Core/Core.h" +#include using namespace WallpaperEngine::Core::Projects; -CPropertyCombo* CPropertyCombo::fromJSON (json data, const std::string& name) -{ - auto value = data.find ("value"); - auto text = jsonFindDefault (data, "text", ""); - auto options = jsonFindRequired (data, "options", "Options for a property combo is required"); +CPropertyCombo* CPropertyCombo::fromJSON (json data, const std::string& name) { + const auto value = data.find ("value"); + const auto text = jsonFindDefault (data, "text", ""); + const auto options = jsonFindRequired (data, "options", "Options for a property combo is required"); - auto* combo = new CPropertyCombo ( - name, - text, - *value - ); + auto* combo = new CPropertyCombo (name, text, *value); if (!options->is_array ()) sLog.exception ("Property combo options should be an array"); - for (auto& cur : (*options)) - { + for (auto& cur : (*options)) { // TODO: PROPERLY REPORT THESE ISSUES if (!cur.is_object ()) continue; @@ -39,40 +33,41 @@ CPropertyCombo* CPropertyCombo::fromJSON (json data, const std::string& name) return combo; } -CPropertyCombo::CPropertyCombo (const std::string& name, const std::string& text, std::string defaultValue) : +CPropertyCombo::CPropertyCombo (const std::string& name, const std::string& text, std::string defaultValue) : CProperty (name, Type, text), - m_defaultValue (std::move(defaultValue)) -{ + m_defaultValue (std::move (defaultValue)) {} + +CPropertyCombo::~CPropertyCombo () { + for (const auto* value : this->m_values) + delete value; } -const std::string& CPropertyCombo::getValue () const -{ +const std::string& CPropertyCombo::getValue () const { return this->m_defaultValue; } -std::string CPropertyCombo::dump () const -{ +std::string CPropertyCombo::dump () const { std::stringstream ss; - ss - << this->m_name << " - combolist" << std::endl - << "\t" << "Description: " << this->m_text << std::endl - << "\t" << "Value: " << this->m_defaultValue << std::endl - << "\t\t" << "Posible values:" << std::endl; + ss << this->m_name << " - combolist" << std::endl + << "\t" + << "Description: " << this->m_text << std::endl + << "\t" + << "Value: " << this->m_defaultValue << std::endl + << "\t\t" + << "Posible values:" << std::endl; - for (auto cur : this->m_values) + for (const auto cur : this->m_values) ss << "\t\t" << cur->label << " -> " << cur->value << std::endl; - return ss.str(); + return ss.str (); } -void CPropertyCombo::update (const std::string& value) -{ +void CPropertyCombo::update (const std::string& value) { bool found = false; // ensure the value is present somewhere in the value list - for (auto cur : this->m_values) - { + for (const auto cur : this->m_values) { if (cur->value != value) continue; @@ -85,9 +80,7 @@ void CPropertyCombo::update (const std::string& value) this->m_defaultValue = value; } - -void CPropertyCombo::addValue (std::string label, std::string value) -{ +void CPropertyCombo::addValue (std::string label, std::string value) { auto* prop = new CPropertyComboValue; prop->label = std::move (label); diff --git a/src/WallpaperEngine/Core/Projects/CPropertyCombo.h b/src/WallpaperEngine/Core/Projects/CPropertyCombo.h index 1340984..47275af 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyCombo.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyCombo.h @@ -2,55 +2,54 @@ #include "CProperty.h" -namespace WallpaperEngine::Core::Projects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Projects { +using json = nlohmann::json; + +/** + * Represents different combo values + */ +class CPropertyComboValue { + public: + std::string label; + std::string value; +}; + +/** + * Represents a combo property + * + * Combos are properties that have different values available and only one can be selected at once + * this limits the user's possibilities, used for things like the amount of samples to use in audioprocessing + * backgrounds + */ +class CPropertyCombo final : public CProperty { + public: + static CPropertyCombo* fromJSON (json data, const std::string& name); + + ~CPropertyCombo () override; /** - * Represents different combo values + * @return The selected value */ - class CPropertyComboValue - { - public: - std::string label; - std::string value; - }; + [[nodiscard]] const std::string& getValue () const; + [[nodiscard]] std::string dump () const override; + void update (const std::string& value) override; + + static const std::string Type; + + private: + CPropertyCombo (const std::string& name, const std::string& text, std::string defaultValue); /** - * Represents a combo property + * Adds a combo value to the list of possible values * - * Combos are properties that have different values available and only one can be selected at once - * this limits the user's possibilities, used for things like the amount of samples to use in audioprocessing - * backgrounds + * @param label + * @param value */ - class CPropertyCombo : public CProperty - { - public: - static CPropertyCombo* fromJSON (json data, const std::string& name); + void addValue (std::string label, std::string value); - /** - * @return The selected value - */ - [[nodiscard]] const std::string& getValue () const; - [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; - - static const std::string Type; - - private: - CPropertyCombo (const std::string& name, const std::string& text, std::string defaultValue); - - /** - * Adds a combo value to the list of possible values - * - * @param label - * @param value - */ - void addValue (std::string label, std::string value); - - /** List of values available to select */ - std::vector m_values; - /** The default value */ - std::string m_defaultValue; - }; -} + /** List of values available to select */ + std::vector m_values; + /** The default value */ + std::string m_defaultValue; +}; +} // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp b/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp index 7a828f0..5c0ecb5 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp @@ -1,58 +1,55 @@ +#include "CPropertySlider.h" #include "common.h" #include -#include "CPropertySlider.h" using namespace WallpaperEngine::Core::Projects; -CPropertySlider* CPropertySlider::fromJSON (json data, const std::string& name) -{ - auto value = data.find ("value"); - auto text = jsonFindDefault (data, "text", ""); - auto min = jsonFindDefault(data, "min", 0.0); - auto max = jsonFindDefault (data, "max", 0.0); - auto step = jsonFindDefault (data, "step", 0.0); +CPropertySlider* CPropertySlider::fromJSON (json data, const std::string& name) { + const auto value = data.find ("value"); + const auto text = jsonFindDefault (data, "text", ""); + const auto min = jsonFindDefault (data, "min", 0.0); + const auto max = jsonFindDefault (data, "max", 0.0); + const auto step = jsonFindDefault (data, "step", 0.0); return new CPropertySlider (*value, name, text, min, max, step); } -const double& CPropertySlider::getValue () const -{ +const double& CPropertySlider::getValue () const { return this->m_value; } -const double& CPropertySlider::getMinValue () const -{ +const double& CPropertySlider::getMinValue () const { return this->m_min; } -const double& CPropertySlider::getMaxValue () const -{ +const double& CPropertySlider::getMaxValue () const { return this->m_max; } -const double& CPropertySlider::getStep () const -{ +const double& CPropertySlider::getStep () const { return this->m_step; } -std::string CPropertySlider::dump () const -{ +std::string CPropertySlider::dump () const { std::stringstream ss; - ss - << this->m_name << " - slider" << std::endl - << "\t" << "Description: " << this->m_text << std::endl - << "\t" << "Value: " << this->m_value << std::endl - << "\t" << "Minimum value: " << this->m_min << std::endl - << "\t" << "Maximum value: " << this->m_max << std::endl - << "\t" << "Step: " << this->m_step << std::endl; + ss << this->m_name << " - slider" << std::endl + << "\t" + << "Description: " << this->m_text << std::endl + << "\t" + << "Value: " << this->m_value << std::endl + << "\t" + << "Minimum value: " << this->m_min << std::endl + << "\t" + << "Maximum value: " << this->m_max << std::endl + << "\t" + << "Step: " << this->m_step << std::endl; - return ss.str(); + return ss.str (); } -void CPropertySlider::update (const std::string& value) -{ - double newValue = strtod (value.c_str (), nullptr); +void CPropertySlider::update (const std::string& value) { + const double newValue = strtod (value.c_str (), nullptr); if (newValue < this->m_min || newValue > this->m_max) sLog.exception ("Slider value (", newValue, ") is out of range (", this->m_min, ",", this->m_max, ")"); @@ -60,10 +57,12 @@ void CPropertySlider::update (const std::string& value) this->m_value = newValue; } -CPropertySlider::CPropertySlider (double value, const std::string& name, const std::string& text, double min, double max, double step) : +CPropertySlider::CPropertySlider (double value, const std::string& name, const std::string& text, double min, + double max, double step) : CProperty (name, Type, text), - m_value (value), m_min (min), m_max (max), m_step (step) -{ -} + m_value (value), + m_min (min), + m_max (max), + m_step (step) {} const std::string CPropertySlider::Type = "slider"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Projects/CPropertySlider.h b/src/WallpaperEngine/Core/Projects/CPropertySlider.h index 0188d8c..d651526 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertySlider.h +++ b/src/WallpaperEngine/Core/Projects/CPropertySlider.h @@ -4,49 +4,48 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Projects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Projects { +using json = nlohmann::json; + +/** + * Represents a slider value with a minimum and maximum value + */ +class CPropertySlider final : public CProperty { + public: + static CPropertySlider* fromJSON (json data, const std::string& name); /** - * Represents a slider value with a minimum and maximum value + * @return The slider's value */ - class CPropertySlider : public CProperty - { - public: - static CPropertySlider* fromJSON (json data, const std::string& name); + [[nodiscard]] const double& getValue () const; + /** + * @return The slider's minimum value + */ + [[nodiscard]] const double& getMinValue () const; + /** + * @return The slider's maximum value + */ + [[nodiscard]] const double& getMaxValue () const; + /** + * @return The slider's value increment steps, only really used in the UI + */ + [[nodiscard]] const double& getStep () const; + [[nodiscard]] std::string dump () const override; + void update (const std::string& value) override; - /** - * @return The slider's value - */ - [[nodiscard]] const double& getValue () const; - /** - * @return The slider's minimum value - */ - [[nodiscard]] const double& getMinValue () const; - /** - * @return The slider's maximum value - */ - [[nodiscard]] const double& getMaxValue () const; - /** - * @return The slider's value increment steps, only really used in the UI - */ - [[nodiscard]] const double& getStep () const; - [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; + static const std::string Type; - static const std::string Type; + private: + CPropertySlider (double value, const std::string& name, const std::string& text, double min, double max, + double step); - private: - CPropertySlider (double value, const std::string& name, const std::string& text, double min, double max, double step); - - /** Actual slider value */ - double m_value; - /** Minimum value */ - double m_min; - /** Maximum value */ - double m_max; - /** Increment steps for the slider in the UI */ - double m_step; - }; -} + /** Actual slider value */ + double m_value; + /** Minimum value */ + double m_min; + /** Maximum value */ + double m_max; + /** Increment steps for the slider in the UI */ + double m_step; +}; +} // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyText.cpp b/src/WallpaperEngine/Core/Projects/CPropertyText.cpp index 646c310..b6892aa 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyText.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyText.cpp @@ -1,38 +1,29 @@ -#include #include "CPropertyText.h" #include "WallpaperEngine/Core/Core.h" +#include using namespace WallpaperEngine::Core::Projects; -CPropertyText* CPropertyText::fromJSON (json data, const std::string& name) -{ - json::const_iterator text = data.find ("type"); +CPropertyText* CPropertyText::fromJSON (json data, const std::string& name) { + const json::const_iterator text = data.find ("type"); - return new CPropertyText ( - name, - *text - ); + return new CPropertyText (name, *text); } -std::string CPropertyText::dump () const -{ +std::string CPropertyText::dump () const { std::stringstream ss; - ss - << this->m_name << " - text" << std::endl - << "\t" << "Value: " << this->m_text; + ss << this->m_name << " - text" << std::endl + << "\t" + << "Value: " << this->m_text; - return ss.str(); + return ss.str (); } -void CPropertyText::update (const std::string& value) -{ +void CPropertyText::update (const std::string& value) { this->m_text = value; } -CPropertyText::CPropertyText (const std::string& name, const std::string& text) : - CProperty (name, Type, text) -{ -} +CPropertyText::CPropertyText (const std::string& name, const std::string& text) : CProperty (name, Type, text) {} const std::string CPropertyText::Type = "text"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Projects/CPropertyText.h b/src/WallpaperEngine/Core/Projects/CPropertyText.h index f0d2277..1586076 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyText.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyText.h @@ -2,23 +2,21 @@ #include "CProperty.h" -namespace WallpaperEngine::Core::Projects -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Projects { +using json = nlohmann::json; - /** - * Represents a text property - */ - class CPropertyText : public CProperty - { - public: - static CPropertyText* fromJSON (json data, const std::string& name); - [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; +/** + * Represents a text property + */ +class CPropertyText final : public CProperty { + public: + static CPropertyText* fromJSON (json data, const std::string& name); + [[nodiscard]] std::string dump () const override; + void update (const std::string& value) override; - static const std::string Type; + static const std::string Type; - private: - CPropertyText (const std::string& name, const std::string& text); - }; -} + private: + CPropertyText (const std::string& name, const std::string& text); +}; +} // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Scenes/CCamera.cpp b/src/WallpaperEngine/Core/Scenes/CCamera.cpp index 4a229cd..3cae285 100644 --- a/src/WallpaperEngine/Core/Scenes/CCamera.cpp +++ b/src/WallpaperEngine/Core/Scenes/CCamera.cpp @@ -2,37 +2,25 @@ using namespace WallpaperEngine::Core::Scenes; -CCamera::CCamera (glm::vec3 center, glm::vec3 eye, glm::vec3 up) : - m_center (center), - m_eye (eye), - m_up (up) -{ -} +CCamera::CCamera (glm::vec3 center, glm::vec3 eye, glm::vec3 up) : m_center (center), m_eye (eye), m_up (up) {} -const glm::vec3& CCamera::getCenter () const -{ +const glm::vec3& CCamera::getCenter () const { return this->m_center; } -const glm::vec3& CCamera::getEye () const -{ +const glm::vec3& CCamera::getEye () const { return this->m_eye; } -const glm::vec3& CCamera::getUp () const -{ +const glm::vec3& CCamera::getUp () const { return this->m_up; } -CCamera* CCamera::fromJSON (json data) -{ - auto center_it = jsonFindRequired (data, "center", "Camera must have a center position"); - auto eye_it = jsonFindRequired (data, "eye", "Camera must have an eye position"); - auto up_it = jsonFindRequired (data, "up", "Camera must have a up position"); +CCamera* CCamera::fromJSON (json data) { + const auto center_it = jsonFindRequired (data, "center", "Camera must have a center position"); + const auto eye_it = jsonFindRequired (data, "eye", "Camera must have an eye position"); + const auto up_it = jsonFindRequired (data, "up", "Camera must have a up position"); - return new CCamera ( - WallpaperEngine::Core::aToVector3 (*center_it), - WallpaperEngine::Core::aToVector3 (*eye_it), - WallpaperEngine::Core::aToVector3 (*up_it) - ); + return new CCamera (WallpaperEngine::Core::aToVector3 (*center_it), WallpaperEngine::Core::aToVector3 (*eye_it), + WallpaperEngine::Core::aToVector3 (*up_it)); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Scenes/CCamera.h b/src/WallpaperEngine/Core/Scenes/CCamera.h index df9e20e..7ef63ca 100644 --- a/src/WallpaperEngine/Core/Scenes/CCamera.h +++ b/src/WallpaperEngine/Core/Scenes/CCamera.h @@ -2,23 +2,23 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Scenes -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Scenes { +using json = nlohmann::json; - class CCamera - { - public: - static CCamera* fromJSON (json data); +class CCamera { + public: + static CCamera* fromJSON (json data); - const glm::vec3& getCenter () const; - const glm::vec3& getEye () const; - const glm::vec3& getUp () const; - protected: - CCamera (glm::vec3 center, glm::vec3 eye, glm::vec3 up); - private: - glm::vec3 m_center; - glm::vec3 m_eye; - glm::vec3 m_up; - }; -} + const glm::vec3& getCenter () const; + const glm::vec3& getEye () const; + const glm::vec3& getUp () const; + + protected: + CCamera (glm::vec3 center, glm::vec3 eye, glm::vec3 up); + + private: + glm::vec3 m_center; + glm::vec3 m_eye; + glm::vec3 m_up; +}; +} // namespace WallpaperEngine::Core::Scenes diff --git a/src/WallpaperEngine/Core/Scenes/CProjection.cpp b/src/WallpaperEngine/Core/Scenes/CProjection.cpp index 1350aee..27aca72 100644 --- a/src/WallpaperEngine/Core/Scenes/CProjection.cpp +++ b/src/WallpaperEngine/Core/Scenes/CProjection.cpp @@ -2,58 +2,39 @@ using namespace WallpaperEngine::Core::Scenes; -CProjection::CProjection (uint32_t width, uint32_t height) : - m_isAuto (false), - m_width (width), - m_height (height) -{ -} +CProjection::CProjection (uint32_t width, uint32_t height) : m_isAuto (false), m_width (width), m_height (height) {} -CProjection::CProjection (bool isAuto) : - m_isAuto (isAuto), - m_width (0), - m_height (0) -{ -} +CProjection::CProjection (bool isAuto) : m_isAuto (isAuto), m_width (0), m_height (0) {} -const uint32_t& CProjection::getWidth () const -{ +const uint32_t& CProjection::getWidth () const { return this->m_width; } -const uint32_t& CProjection::getHeight () const -{ +const uint32_t& CProjection::getHeight () const { return this->m_height; } -bool CProjection::isAuto () const -{ +bool CProjection::isAuto () const { return this->m_isAuto; } -void CProjection::setWidth (uint32_t width) -{ +void CProjection::setWidth (uint32_t width) { this->m_width = width; } -void CProjection::setHeight (uint32_t height) -{ +void CProjection::setHeight (uint32_t height) { this->m_height = height; } -CProjection* CProjection::fromJSON (json data) -{ - auto auto_it = jsonFindDefault (data, "auto", false); +CProjection* CProjection::fromJSON (json data) { + const auto auto_it = jsonFindDefault (data, "auto", false); - auto width_it = jsonFindRequired (data, "width", "Projection must have width"); - auto height_it = jsonFindRequired (data, "height", "Projection must have height"); + const auto width_it = jsonFindRequired (data, "width", "Projection must have width"); + const auto height_it = jsonFindRequired (data, "height", "Projection must have height"); // TODO: PROPERLY SUPPORT AUTO-DETECTING SIZE if (auto_it) return new CProjection (true); - else - return new CProjection ( - *width_it, - *height_it - ); + + return new CProjection (*width_it, *height_it); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Scenes/CProjection.h b/src/WallpaperEngine/Core/Scenes/CProjection.h index 8f4af06..5269b2b 100644 --- a/src/WallpaperEngine/Core/Scenes/CProjection.h +++ b/src/WallpaperEngine/Core/Scenes/CProjection.h @@ -2,28 +2,27 @@ #include "WallpaperEngine/Core/Core.h" -namespace WallpaperEngine::Core::Scenes -{ - using json = nlohmann::json; +namespace WallpaperEngine::Core::Scenes { +using json = nlohmann::json; - class CProjection - { - public: - static CProjection* fromJSON (json data); +class CProjection { + public: + static CProjection* fromJSON (json data); - const uint32_t& getWidth () const; - const uint32_t& getHeight () const; - bool isAuto () const; + const uint32_t& getWidth () const; + const uint32_t& getHeight () const; + bool isAuto () const; - void setWidth (uint32_t width); - void setHeight (uint32_t height); + void setWidth (uint32_t width); + void setHeight (uint32_t height); - protected: - CProjection (uint32_t width, uint32_t height); - CProjection (bool isAuto); - private: - uint32_t m_width; - uint32_t m_height; - bool m_isAuto; - }; -} + protected: + CProjection (uint32_t width, uint32_t height); + explicit CProjection (bool isAuto); + + private: + uint32_t m_width; + uint32_t m_height; + bool m_isAuto; +}; +} // namespace WallpaperEngine::Core::Scenes diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp index b3eb5b0..4792825 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp @@ -1,6 +1,6 @@ -#include "common.h" #include "CUserSettingBoolean.h" #include "WallpaperEngine/Core/Core.h" +#include "common.h" #include "WallpaperEngine/Core/Projects/CProperty.h" #include "WallpaperEngine/Core/Projects/CPropertyBoolean.h" @@ -12,50 +12,40 @@ using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Projects; using namespace WallpaperEngine::Core::UserSettings; -CUserSettingBoolean::CUserSettingBoolean (bool hasCondition, bool hasSource, bool defaultValue, std::string source, std::string expectedValue) : +CUserSettingBoolean::CUserSettingBoolean (bool hasCondition, bool hasSource, bool defaultValue, std::string source, + std::string expectedValue) : CUserSettingValue (Type), m_hasCondition (hasCondition), - m_hasSource(hasSource), - m_default(defaultValue), - m_source (std::move(source)), - m_expectedValue(std::move(expectedValue)) -{ -} + m_hasSource (hasSource), + m_default (defaultValue), + m_source (std::move (source)), + m_expectedValue (std::move (expectedValue)) {} -CUserSettingBoolean* CUserSettingBoolean::fromJSON (nlohmann::json& data) -{ +CUserSettingBoolean* CUserSettingBoolean::fromJSON (nlohmann::json& data) { bool hasCondition = false; bool hasSource = false; bool defaultValue; std::string source; std::string expectedValue; - if (data.is_object ()) - { + if (data.is_object ()) { hasSource = true; auto userIt = data.find ("user"); defaultValue = jsonFindDefault (data, "value", true); // is this default value right? - if (userIt != data.end ()) - { - if (userIt->is_string ()) - { + if (userIt != data.end ()) { + if (userIt->is_string ()) { source = *userIt; - } - else - { + } else { hasCondition = true; source = *jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); - expectedValue = *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + expectedValue = + *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); } - } - else - { + } else { sLog.error ("Boolean property doesn't have user member, this could mean an scripted value"); } - } - else - { + } else { if (!data.is_boolean ()) sLog.error ("Expected boolean value on user setting"); @@ -65,37 +55,32 @@ CUserSettingBoolean* CUserSettingBoolean::fromJSON (nlohmann::json& data) return new CUserSettingBoolean (hasCondition, hasSource, defaultValue, source, expectedValue); } -CUserSettingBoolean* CUserSettingBoolean::fromScalar (bool value) -{ +CUserSettingBoolean* CUserSettingBoolean::fromScalar (bool value) { return new CUserSettingBoolean (false, false, value, "", ""); } -bool CUserSettingBoolean::getDefaultValue () const -{ +bool CUserSettingBoolean::getDefaultValue () const { return this->m_default; } -bool CUserSettingBoolean::processValue (const std::vector& properties) -{ +bool CUserSettingBoolean::processValue (const std::vector& properties) { if (!this->m_hasSource && !this->m_hasCondition) return this->getDefaultValue (); - for (auto cur : properties) - { + for (const auto cur : properties) { if (cur->getName () != this->m_source) continue; - if (!this->m_hasCondition) - { - if (cur->is ()) - return cur->as ()->getValue (); + if (!this->m_hasCondition) { + if (cur->is ()) + return cur->as ()->getValue (); sLog.exception ("Property without condition must match type boolean"); } // TODO: properly validate this as the combos might be more than just strings? - if (cur->is ()) - return cur->as ()->getValue () == this->m_expectedValue; + if (cur->is ()) + return cur->as ()->getValue () == this->m_expectedValue; sLog.exception ("Boolean property with condition doesn't match against combo value"); } diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h index 1e00027..09bd047 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h @@ -2,32 +2,30 @@ #include "CUserSettingValue.h" -namespace WallpaperEngine::Core::Projects -{ - class CProperty; +namespace WallpaperEngine::Core::Projects { +class CProperty; } -namespace WallpaperEngine::Core::UserSettings -{ - class CUserSettingBoolean : public CUserSettingValue - { - public: - typedef bool data_type; +namespace WallpaperEngine::Core::UserSettings { +class CUserSettingBoolean : public CUserSettingValue { + public: + typedef bool data_type; - static CUserSettingBoolean* fromJSON (nlohmann::json& data); - static CUserSettingBoolean* fromScalar (bool value); - static std::string Type; + static CUserSettingBoolean* fromJSON (nlohmann::json& data); + static CUserSettingBoolean* fromScalar (bool value); + static std::string Type; - bool processValue (const std::vector& properties); - bool getDefaultValue () const; + bool processValue (const std::vector& properties); + bool getDefaultValue () const; - private: - CUserSettingBoolean (bool hasCondition, bool hasSource, bool defaultValue, std::string source, std::string expectedValue); + private: + CUserSettingBoolean (bool hasCondition, bool hasSource, bool defaultValue, std::string source, + std::string expectedValue); - bool m_default; - bool m_hasCondition; - bool m_hasSource; - std::string m_source; - std::string m_expectedValue; - }; -} \ No newline at end of file + bool m_default; + bool m_hasCondition; + bool m_hasSource; + std::string m_source; + std::string m_expectedValue; +}; +} // namespace WallpaperEngine::Core::UserSettings \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp index 18e5970..2a8754c 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp @@ -1,6 +1,6 @@ -#include "common.h" #include "CUserSettingFloat.h" #include "WallpaperEngine/Core/Core.h" +#include "common.h" #include "WallpaperEngine/Core/Projects/CProperty.h" #include "WallpaperEngine/Core/Projects/CPropertySlider.h" @@ -9,50 +9,40 @@ using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Projects; using namespace WallpaperEngine::Core::UserSettings; -CUserSettingFloat::CUserSettingFloat (bool hasCondition, bool hasSource, double defaultValue, std::string source, std::string expectedValue) : +CUserSettingFloat::CUserSettingFloat (bool hasCondition, bool hasSource, double defaultValue, std::string source, + std::string expectedValue) : CUserSettingValue (Type), m_hasCondition (hasCondition), - m_hasSource(hasSource), - m_default(defaultValue), - m_source (std::move(source)), - m_expectedValue(std::move(expectedValue)) -{ -} + m_hasSource (hasSource), + m_default (defaultValue), + m_source (std::move (source)), + m_expectedValue (std::move (expectedValue)) {} -CUserSettingFloat* CUserSettingFloat::fromJSON (nlohmann::json& data) -{ +CUserSettingFloat* CUserSettingFloat::fromJSON (nlohmann::json& data) { double defaultValue; std::string source; std::string expectedValue; bool hasCondition = false; bool hasSource = false; - if (data.is_object ()) - { + if (data.is_object ()) { hasSource = true; auto userIt = data.find ("user"); defaultValue = jsonFindDefault (data, "value", 1.0); // is this default value right? - if (userIt != data.end ()) - { - if (userIt->is_string ()) - { + if (userIt != data.end ()) { + if (userIt->is_string ()) { source = *userIt; - } - else - { + } else { hasCondition = true; source = *jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); - expectedValue = *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + expectedValue = + *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); } - } - else - { + } else { sLog.error ("Float property doesn't have user member, this could mean an scripted value"); } - } - else - { + } else { if (!data.is_number ()) sLog.exception ("Expected numeric value on user settings"); @@ -62,30 +52,25 @@ CUserSettingFloat* CUserSettingFloat::fromJSON (nlohmann::json& data) return new CUserSettingFloat (hasCondition, hasSource, defaultValue, source, expectedValue); } -CUserSettingFloat* CUserSettingFloat::fromScalar (double value) -{ +CUserSettingFloat* CUserSettingFloat::fromScalar (double value) { return new CUserSettingFloat (false, false, value, "", ""); } -double CUserSettingFloat::getDefaultValue () const -{ +double CUserSettingFloat::getDefaultValue () const { return this->m_default; } -double CUserSettingFloat::processValue (const std::vector& properties) -{ +double CUserSettingFloat::processValue (const std::vector& properties) { if (!this->m_hasSource && !this->m_hasCondition) return this->getDefaultValue (); - for (auto cur : properties) - { + for (const auto cur : properties) { if (cur->getName () != this->m_source) continue; - if (!this->m_hasCondition) - { - if (cur->is ()) - return cur->as ()->getValue (); + if (!this->m_hasCondition) { + if (cur->is ()) + return cur->as ()->getValue (); sLog.exception ("Property without condition must match type (slider)"); } diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h index 5cab219..7ca5081 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h @@ -2,32 +2,30 @@ #include "CUserSettingValue.h" -namespace WallpaperEngine::Core::Projects -{ - class CProperty; +namespace WallpaperEngine::Core::Projects { +class CProperty; } -namespace WallpaperEngine::Core::UserSettings -{ - class CUserSettingFloat : public CUserSettingValue - { - public: - typedef double data_type; +namespace WallpaperEngine::Core::UserSettings { +class CUserSettingFloat : public CUserSettingValue { + public: + typedef double data_type; - static CUserSettingFloat* fromJSON (nlohmann::json& data); - static CUserSettingFloat* fromScalar (double value); - static std::string Type; + static CUserSettingFloat* fromJSON (nlohmann::json& data); + static CUserSettingFloat* fromScalar (double value); + static std::string Type; - double processValue (const std::vector& properties); - double getDefaultValue () const; + double processValue (const std::vector& properties); + double getDefaultValue () const; - private: - CUserSettingFloat (bool hasCondition, bool hasSource, double defaultValue, std::string source, std::string expectedValue); + private: + CUserSettingFloat (bool hasCondition, bool hasSource, double defaultValue, std::string source, + std::string expectedValue); - double m_default; - bool m_hasCondition; - bool m_hasSource; - std::string m_source; - std::string m_expectedValue; - }; -} \ No newline at end of file + double m_default; + bool m_hasCondition; + bool m_hasSource; + std::string m_source; + std::string m_expectedValue; +}; +} // namespace WallpaperEngine::Core::UserSettings \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp index 5cf1e04..3495739 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp @@ -4,7 +4,4 @@ using namespace WallpaperEngine::Core::UserSettings; -CUserSettingValue::CUserSettingValue (std::string type) : - m_type (std::move(type)) -{ -} \ No newline at end of file +CUserSettingValue::CUserSettingValue (std::string type) : m_type (std::move (type)) {} \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h index e706df6..b20a1cf 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h @@ -2,20 +2,27 @@ #include -namespace WallpaperEngine::Core::UserSettings -{ - class CUserSettingValue - { - public: - template const T* as () const { assert (is ()); return (const T*) this; } - template T* as () { assert (is ()); return (T*) this; } +namespace WallpaperEngine::Core::UserSettings { +class CUserSettingValue { + public: + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); + } - template bool is () { return this->m_type == T::Type; } + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } - protected: - explicit CUserSettingValue (std::string type); + template bool is () { + return this->m_type == T::Type; + } - private: - std::string m_type; - }; -} + protected: + explicit CUserSettingValue (std::string type); + + private: + std::string m_type; +}; +} // namespace WallpaperEngine::Core::UserSettings diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp index d0192fe..768c766 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp @@ -1,6 +1,6 @@ -#include "common.h" #include "CUserSettingVector3.h" #include "WallpaperEngine/Core/Core.h" +#include "common.h" #include "WallpaperEngine/Core/Projects/CProperty.h" #include "WallpaperEngine/Core/Projects/CPropertyColor.h" @@ -10,89 +10,72 @@ using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Projects; using namespace WallpaperEngine::Core::UserSettings; -CUserSettingVector3::CUserSettingVector3 (bool hasCondition, bool hasSource, glm::vec3 defaultValue, std::string source, std::string expectedValue) : +CUserSettingVector3::CUserSettingVector3 (bool hasCondition, bool hasSource, glm::vec3 defaultValue, std::string source, + std::string expectedValue) : CUserSettingValue (Type), m_hasCondition (hasCondition), - m_hasSource(hasSource), - m_default(defaultValue), - m_source (std::move(source)), - m_expectedValue(std::move(expectedValue)) -{ -} + m_hasSource (hasSource), + m_default (defaultValue), + m_source (std::move (source)), + m_expectedValue (std::move (expectedValue)) {} -CUserSettingVector3* CUserSettingVector3::fromJSON (nlohmann::json& data) -{ +CUserSettingVector3* CUserSettingVector3::fromJSON (nlohmann::json& data) { bool hasCondition = false; bool hasSource = false; glm::vec3 defaultValue; std::string source; std::string expectedValue; - if (data.is_object ()) - { + if (data.is_object ()) { hasSource = true; auto userIt = data.find ("user"); - defaultValue = WallpaperEngine::Core::aToColorf (jsonFindDefault (data, "value", "").c_str ()); // is this default value right? + defaultValue = WallpaperEngine::Core::aToColorf ( + jsonFindDefault (data, "value", "").c_str ()); // is this default value right? - if (userIt != data.end ()) - { - if (userIt->is_string ()) - { + if (userIt != data.end ()) { + if (userIt->is_string ()) { source = *userIt; - } - else - { + } else { hasCondition = true; source = *jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); - expectedValue = *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + expectedValue = + *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); } - } - else - { + } else { sLog.error ("Vector property doesn't have user member, this could mean an scripted value"); } - } - else - { + } else { if (!data.is_string ()) sLog.exception ("Expected vector value on user settings"); - defaultValue = WallpaperEngine::Core::aToColorf (data.get ().c_str ()); + defaultValue = WallpaperEngine::Core::aToColorf (data.get ().c_str ()); } return new CUserSettingVector3 (hasCondition, hasSource, defaultValue, source, expectedValue); } -CUserSettingVector3* CUserSettingVector3::fromScalar (glm::vec3 value) -{ +CUserSettingVector3* CUserSettingVector3::fromScalar (glm::vec3 value) { return new CUserSettingVector3 (false, false, value, "", ""); } -glm::vec3 CUserSettingVector3::getDefaultValue () const -{ +glm::vec3 CUserSettingVector3::getDefaultValue () const { return this->m_default; } -glm::vec3 CUserSettingVector3::processValue (const std::vector& properties) -{ +glm::vec3 CUserSettingVector3::processValue (const std::vector& properties) { if (!this->m_hasSource && !this->m_hasCondition) return this->getDefaultValue (); - for (auto cur : properties) - { + for (const auto cur : properties) { if (cur->getName () != this->m_source) continue; - if (!this->m_hasCondition) - { - if (cur->is ()) - return cur->as ()->getValue (); - if (cur->is ()) - return { - cur->as ()->getValue (), - cur->as ()->getValue (), - cur->as ()->getValue () - }; + if (!this->m_hasCondition) { + if (cur->is ()) + return cur->as ()->getValue (); + if (cur->is ()) + return {cur->as ()->getValue (), cur->as ()->getValue (), + cur->as ()->getValue ()}; sLog.exception ("Property without condition must match type (vector3)"); } diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h index 5fa629e..924936c 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h @@ -4,32 +4,30 @@ #include "CUserSettingValue.h" -namespace WallpaperEngine::Core::Projects -{ - class CProperty; +namespace WallpaperEngine::Core::Projects { +class CProperty; } -namespace WallpaperEngine::Core::UserSettings -{ - class CUserSettingVector3 : public CUserSettingValue - { - public: - typedef glm::vec3 data_type; +namespace WallpaperEngine::Core::UserSettings { +class CUserSettingVector3 : public CUserSettingValue { + public: + typedef glm::vec3 data_type; - static CUserSettingVector3* fromJSON (nlohmann::json& data); - static CUserSettingVector3* fromScalar (glm::vec3 value); - static std::string Type; + static CUserSettingVector3* fromJSON (nlohmann::json& data); + static CUserSettingVector3* fromScalar (glm::vec3 value); + static std::string Type; - glm::vec3 processValue (const std::vector& properties); - glm::vec3 getDefaultValue () const; + glm::vec3 processValue (const std::vector& properties); + glm::vec3 getDefaultValue () const; - private: - CUserSettingVector3 (bool hasCondition, bool hasSource, glm::vec3 defaultValue, std::string source, std::string expectedValue); + private: + CUserSettingVector3 (bool hasCondition, bool hasSource, glm::vec3 defaultValue, std::string source, + std::string expectedValue); - glm::vec3 m_default; - bool m_hasCondition; - bool m_hasSource; - std::string m_source; - std::string m_expectedValue; - }; -} \ No newline at end of file + glm::vec3 m_default; + bool m_hasCondition; + bool m_hasSource; + std::string m_source; + std::string m_expectedValue; +}; +} // namespace WallpaperEngine::Core::UserSettings \ No newline at end of file diff --git a/src/WallpaperEngine/FileSystem/FileSystem.cpp b/src/WallpaperEngine/FileSystem/FileSystem.cpp index 482a88b..92c099b 100644 --- a/src/WallpaperEngine/FileSystem/FileSystem.cpp +++ b/src/WallpaperEngine/FileSystem/FileSystem.cpp @@ -5,8 +5,7 @@ using namespace WallpaperEngine; -std::string FileSystem::loadFullFile (const std::string& file, WallpaperEngine::Assets::CContainer* containers) -{ +std::string FileSystem::loadFullFile (const std::string& file, const WallpaperEngine::Assets::CContainer* containers) { uint32_t length = 0; const void* contents = containers->readFile (file, &length); diff --git a/src/WallpaperEngine/FileSystem/FileSystem.h b/src/WallpaperEngine/FileSystem/FileSystem.h index 70668d2..c7fe214 100644 --- a/src/WallpaperEngine/FileSystem/FileSystem.h +++ b/src/WallpaperEngine/FileSystem/FileSystem.h @@ -3,19 +3,19 @@ */ #pragma once +#include #include #include -#include #include "WallpaperEngine/Assets/CContainer.h" -namespace WallpaperEngine::FileSystem -{ - /** - * Loads a full file into an std::string - * - * @param file - * @return - */ - std::string loadFullFile (const std::string& file, WallpaperEngine::Assets::CContainer* containers); -} +namespace WallpaperEngine::FileSystem { +/** + * Loads a full file into an std::string + * + * @param file + * @param containers + * @return + */ +std::string loadFullFile (const std::string& file, const WallpaperEngine::Assets::CContainer* containers); +} // namespace WallpaperEngine::FileSystem diff --git a/src/WallpaperEngine/Input/CInputContext.cpp b/src/WallpaperEngine/Input/CInputContext.cpp index 7c3970b..be57877 100644 --- a/src/WallpaperEngine/Input/CInputContext.cpp +++ b/src/WallpaperEngine/Input/CInputContext.cpp @@ -3,17 +3,12 @@ using namespace WallpaperEngine::Input; using namespace WallpaperEngine::Render::Drivers; -CInputContext::CInputContext (CMouseInput* mouseInput) : - m_mouse (mouseInput) -{ -} +CInputContext::CInputContext (CMouseInput* mouseInput) : m_mouse (mouseInput) {} -void CInputContext::update () -{ +void CInputContext::update () { this->m_mouse->update (); } -const CMouseInput& CInputContext::getMouseInput () const -{ +const CMouseInput& CInputContext::getMouseInput () const { return *this->m_mouse; } \ No newline at end of file diff --git a/src/WallpaperEngine/Input/CInputContext.h b/src/WallpaperEngine/Input/CInputContext.h index 40e0394..a1e09f6 100644 --- a/src/WallpaperEngine/Input/CInputContext.h +++ b/src/WallpaperEngine/Input/CInputContext.h @@ -2,26 +2,23 @@ #include "CMouseInput.h" -namespace WallpaperEngine::Render::Drivers -{ - class CVideoDriver; +namespace WallpaperEngine::Render::Drivers { +class CVideoDriver; } -namespace WallpaperEngine::Input -{ - class CInputContext - { - public: - explicit CInputContext (CMouseInput* mouseInput); +namespace WallpaperEngine::Input { +class CInputContext { + public: + explicit CInputContext (CMouseInput* mouseInput); - /** - * Updates input information - */ - void update (); + /** + * Updates input information + */ + void update (); - [[nodiscard]] const CMouseInput& getMouseInput () const; + [[nodiscard]] const CMouseInput& getMouseInput () const; - private: - CMouseInput* m_mouse; - }; -} + private: + CMouseInput* m_mouse; +}; +} // namespace WallpaperEngine::Input diff --git a/src/WallpaperEngine/Input/CMouseInput.h b/src/WallpaperEngine/Input/CMouseInput.h index 2624b93..ab35e95 100644 --- a/src/WallpaperEngine/Input/CMouseInput.h +++ b/src/WallpaperEngine/Input/CMouseInput.h @@ -2,23 +2,21 @@ #include -namespace WallpaperEngine::Input -{ +namespace WallpaperEngine::Input { +/** + * Handles mouse input for the background + */ +class CMouseInput { + public: + virtual ~CMouseInput () = default; /** - * Handles mouse input for the background + * Takes current mouse position and updates it */ - class CMouseInput - { - public: - /** - * Takes current mouse position and updates it - */ - virtual void update () = 0; - - /** - * The virtual pointer's position - */ - [[nodiscard]] virtual glm::dvec2 position () const = 0; - }; -} + virtual void update () = 0; + /** + * The virtual pointer's position + */ + [[nodiscard]] virtual glm::dvec2 position () const = 0; +}; +} // namespace WallpaperEngine::Input diff --git a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp index 1a0f06e..7ba1619 100644 --- a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp +++ b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp @@ -1,5 +1,5 @@ -#include #include "CGLFWMouseInput.h" +#include #include "WallpaperEngine/Render/Drivers/CX11OpenGLDriver.h" @@ -10,10 +10,8 @@ CGLFWMouseInput::CGLFWMouseInput (Render::Drivers::CX11OpenGLDriver* driver) : m_mousePosition (), m_driver (driver) {} -void CGLFWMouseInput::update () -{ - if (!this->m_driver->getApp ().getContext ().settings.mouse.enabled) - { +void CGLFWMouseInput::update () { + if (!this->m_driver->getApp ().getContext ().settings.mouse.enabled) { this->m_reportedPosition = {0, 0}; return; } @@ -24,7 +22,6 @@ void CGLFWMouseInput::update () this->m_reportedPosition = glm::mix (this->m_reportedPosition, this->m_mousePosition, 1.0); } -glm::dvec2 CGLFWMouseInput::position() const -{ +glm::dvec2 CGLFWMouseInput::position () const { return this->m_reportedPosition; } \ No newline at end of file diff --git a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h index 874917a..4e56525 100644 --- a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h +++ b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h @@ -4,39 +4,35 @@ #include -namespace WallpaperEngine::Render::Drivers -{ - class CX11OpenGLDriver; +namespace WallpaperEngine::Render::Drivers { +class CX11OpenGLDriver; } -namespace WallpaperEngine::Input::Drivers -{ +namespace WallpaperEngine::Input::Drivers { +/** + * Handles mouse input for the background + */ +class CGLFWMouseInput final : public CMouseInput { + public: + explicit CGLFWMouseInput (Render::Drivers::CX11OpenGLDriver* driver); + /** - * Handles mouse input for the background + * Takes current mouse position and updates it */ - class CGLFWMouseInput : public CMouseInput - { - public: - explicit CGLFWMouseInput(Render::Drivers::CX11OpenGLDriver* driver); + void update () override; - /** - * Takes current mouse position and updates it - */ - void update () override; + /** + * The virtual pointer's position + */ + [[nodiscard]] glm::dvec2 position () const override; - /** - * The virtual pointer's position - */ - [[nodiscard]] glm::dvec2 position () const override; - - private: - Render::Drivers::CX11OpenGLDriver* m_driver; - - /** - * The current mouse position - */ - glm::dvec2 m_mousePosition; - glm::dvec2 m_reportedPosition; - }; -} + private: + Render::Drivers::CX11OpenGLDriver* m_driver; + /** + * The current mouse position + */ + glm::dvec2 m_mousePosition; + glm::dvec2 m_reportedPosition; +}; +} // namespace WallpaperEngine::Input::Drivers diff --git a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp index 296a10f..eb77fee 100644 --- a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp +++ b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp @@ -1,21 +1,16 @@ -#include #include "CWaylandMouseInput.h" +#include using namespace WallpaperEngine::Input::Drivers; -CWaylandMouseInput::CWaylandMouseInput(WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* driver) : - waylandDriver (driver) -{ -} +CWaylandMouseInput::CWaylandMouseInput (WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* driver) : + waylandDriver (driver), + pos () {} -void CWaylandMouseInput::update () -{ -} +void CWaylandMouseInput::update () {} -glm::dvec2 CWaylandMouseInput::position() const -{ - if (!this->waylandDriver->getApp().getContext ().settings.mouse.enabled) - { +glm::dvec2 CWaylandMouseInput::position () const { + if (!this->waylandDriver->getApp ().getContext ().settings.mouse.enabled) { return {0, 0}; } diff --git a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h index d6d9109..6e4e446 100644 --- a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h +++ b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h @@ -1,41 +1,39 @@ -#ifdef ENABLE_WAYLAND #pragma once +#ifdef ENABLE_WAYLAND + #include "WallpaperEngine/Input/CMouseInput.h" #include "WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" -#include #include "GLFW/glfw3.h" +#include +namespace WallpaperEngine::Input::Drivers { +/** + * Handles mouse input for the background + */ +class CWaylandMouseInput final : public CMouseInput { + public: + explicit CWaylandMouseInput (WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* driver); -namespace WallpaperEngine::Input::Drivers -{ /** - * Handles mouse input for the background + * Takes current mouse position and updates it */ - class CWaylandMouseInput : public CMouseInput - { - public: - explicit CWaylandMouseInput(WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* driver); + void update () override; - /** - * Takes current mouse position and updates it - */ - void update () override; + /** + * The virtual pointer's position + */ + [[nodiscard]] glm::dvec2 position () const override; - /** - * The virtual pointer's position - */ - [[nodiscard]] glm::dvec2 position () const override; + private: + /** + * Wayland: Driver + */ + WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* waylandDriver = nullptr; - private: - /** - * Wayland: Driver - */ - WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* waylandDriver = nullptr; - - glm::dvec2 pos; - }; -} + glm::dvec2 pos; +}; +} // namespace WallpaperEngine::Input::Drivers #endif /* ENABLE_WAYLAND */ \ No newline at end of file diff --git a/src/WallpaperEngine/Logging/CLog.cpp b/src/WallpaperEngine/Logging/CLog.cpp index 35958de..45f35b6 100644 --- a/src/WallpaperEngine/Logging/CLog.cpp +++ b/src/WallpaperEngine/Logging/CLog.cpp @@ -4,27 +4,23 @@ using namespace WallpaperEngine::Logging; -CLog::CLog() -{ +CLog::CLog () { assert (this->sInstance == nullptr); } -CLog& CLog::get () -{ +CLog& CLog::get () { if (sInstance == nullptr) sInstance.reset (new CLog ()); return *sInstance; } -void CLog::addOutput (std::ostream* stream) -{ +void CLog::addOutput (std::ostream* stream) { this->mOutputs.push_back (stream); } -void CLog::addError (std::ostream* stream) -{ +void CLog::addError (std::ostream* stream) { this->mErrors.push_back (stream); } -std::shared_ptr CLog::sInstance = nullptr; \ No newline at end of file +std::shared_ptr CLog::sInstance = nullptr; \ No newline at end of file diff --git a/src/WallpaperEngine/Logging/CLog.h b/src/WallpaperEngine/Logging/CLog.h index a6146ca..cff431c 100644 --- a/src/WallpaperEngine/Logging/CLog.h +++ b/src/WallpaperEngine/Logging/CLog.h @@ -1,113 +1,99 @@ #pragma once #include -#include #include #include +#include -namespace WallpaperEngine::Logging -{ - /** - * Singleton class, simplifies logging for the whole app - */ - class CLog - { - public: - CLog (); +namespace WallpaperEngine::Logging { +/** + * Singleton class, simplifies logging for the whole app + */ +class CLog { + public: + CLog (); - void addOutput (std::ostream* stream); - void addError (std::ostream* stream); + void addOutput (std::ostream* stream); + void addError (std::ostream* stream); - template - void out (Data... data) - { - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); + template void out (Data... data) { + // buffer the string first + std::stringbuf buffer; + std::ostream bufferStream (&buffer); - ((bufferStream << std::forward(data)), ...); + ((bufferStream << std::forward (data)), ...); - // then send it to all the outputs configured - for (auto cur : this->mOutputs) - *cur << buffer.str () << std::endl; - } + // then send it to all the outputs configured + for (const auto cur : this->mOutputs) + *cur << buffer.str () << std::endl; + } - template - void debug (Data... data) - { + template void debug (Data... data) { #if (!NDEBUG) && (!ERRORONLY) - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); + // buffer the string first + std::stringbuf buffer; + std::ostream bufferStream (&buffer); - ((bufferStream << std::forward (data)), ...); + ((bufferStream << std::forward (data)), ...); - // then send it to all the outputs configured - for (auto cur : this->mOutputs) - *cur << buffer.str () << std::endl; + // then send it to all the outputs configured + for (const auto cur : this->mOutputs) + *cur << buffer.str () << std::endl; #endif /* DEBUG */ - } + } - template - void debugerror (Data... data) - { + template void debugerror (Data... data) { #if (!NDEBUG) && (ERRORONLY) - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); + // buffer the string first + std::stringbuf buffer; + std::ostream bufferStream (&buffer); - ((bufferStream << std::forward(data)), ...); + ((bufferStream << std::forward (data)), ...); - // then send it to all the outputs configured - for (auto cur : this->mOutputs) - *cur << buffer.str () << std::endl; + // then send it to all the outputs configured + for (const auto cur : this->mOutputs) + *cur << buffer.str () << std::endl; #endif /* DEBUG */ - } + } - template - void error (Data... data) - { - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); + template void error (Data... data) { + // buffer the string first + std::stringbuf buffer; + std::ostream bufferStream (&buffer); - ((bufferStream << std::forward(data)), ...); + ((bufferStream << std::forward (data)), ...); - // then send it to all the outputs configured - for (auto cur : this->mErrors) - *cur << buffer.str () << std::endl; - } + // then send it to all the outputs configured + for (const auto cur : this->mErrors) + *cur << buffer.str () << std::endl; + } - template - [[noreturn]] void exception (Data... data) - { - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); + template [[noreturn]] void exception (Data... data) { + // buffer the string first + std::stringbuf buffer; + std::ostream bufferStream (&buffer); - ((bufferStream << std::forward(data)), ...); + ((bufferStream << std::forward (data)), ...); - // then send it to all the outputs configured - for (auto cur : this->mErrors) - *cur << buffer.str () << std::endl; + // then send it to all the outputs configured + for (const auto cur : this->mErrors) + *cur << buffer.str () << std::endl; - // now throw the exception - throw EX (buffer.str ()); - } + // now throw the exception + throw EX (buffer.str ()); + } - template - [[noreturn]] void exception (Data... data) - { - this->exception (data...); - } + template [[noreturn]] void exception (Data... data) { + this->exception (data...); + } - static CLog& get (); + static CLog& get (); - private: - std::vector mOutputs; - std::vector mErrors; - static std::shared_ptr sInstance; - }; -} + private: + std::vector mOutputs; + std::vector mErrors; + static std::shared_ptr sInstance; +}; +} // namespace WallpaperEngine::Logging #define sLog (WallpaperEngine::Logging::CLog::get ()) \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CCamera.cpp b/src/WallpaperEngine/Render/CCamera.cpp index e8f3b8f..783cf25 100644 --- a/src/WallpaperEngine/Render/CCamera.cpp +++ b/src/WallpaperEngine/Render/CCamera.cpp @@ -10,57 +10,47 @@ CCamera::CCamera (CScene* scene, const Core::Scenes::CCamera* camera) : m_camera (camera), m_scene (scene), m_isOrthogonal (false), - m_projection (), - m_lookat () -{ + m_projection (), + m_lookat () { // get the lookat position // TODO: ENSURE THIS IS ONLY USED WHEN NOT DOING AN ORTOGRAPHIC CAMERA AS IT THROWS OFF POINTS this->m_lookat = glm::lookAt (this->getEye (), this->getCenter (), this->getUp ()); } -CCamera::~CCamera () -= default; +CCamera::~CCamera () = default; -const glm::vec3& CCamera::getCenter () const -{ +const glm::vec3& CCamera::getCenter () const { return this->m_camera->getCenter (); } -const glm::vec3& CCamera::getEye () const -{ +const glm::vec3& CCamera::getEye () const { return this->m_camera->getEye (); } -const glm::vec3& CCamera::getUp () const -{ +const glm::vec3& CCamera::getUp () const { return this->m_camera->getUp (); } -const glm::mat4& CCamera::getProjection () const -{ +const glm::mat4& CCamera::getProjection () const { return this->m_projection; } -const glm::mat4& CCamera::getLookAt () const -{ +const glm::mat4& CCamera::getLookAt () const { return this->m_lookat; } -bool CCamera::isOrthogonal () const -{ +bool CCamera::isOrthogonal () const { return this->m_isOrthogonal; } -CScene* CCamera::getScene () const -{ - return this->m_scene; +CScene* CCamera::getScene () const { + return this->m_scene; } -void CCamera::setOrthogonalProjection (float width, float height) -{ +void CCamera::setOrthogonalProjection (float width, float height) { // TODO: GET THE ZNEAR AND ZFAR FROM THE BACKGROUND (IF AVAILABLE) // get the orthogonal projection (the float is there to ensure the values are casted to float, so maths do work) - this->m_projection = glm::ortho (-width / 2.0, width / 2.0, -height / 2.0, height / 2.0, 0, 1000); + this->m_projection = glm::ortho (-width / 2.0, width / 2.0, -height / 2.0, height / 2.0, 0, 1000); this->m_projection = glm::translate (this->m_projection, this->getEye ()); // update the orthogonal flag this->m_isOrthogonal = true; diff --git a/src/WallpaperEngine/Render/CCamera.h b/src/WallpaperEngine/Render/CCamera.h index 9a4ea0f..86be65f 100644 --- a/src/WallpaperEngine/Render/CCamera.h +++ b/src/WallpaperEngine/Render/CCamera.h @@ -1,37 +1,35 @@ #pragma once -#include -#include -#include #include "CScene.h" +#include +#include +#include #include "WallpaperEngine/Core/Scenes/CCamera.h" -namespace WallpaperEngine::Render -{ - class CScene; +namespace WallpaperEngine::Render { +class CScene; - class CCamera - { - public: - CCamera (CScene* scene, const Core::Scenes::CCamera* camera); - ~CCamera (); +class CCamera { + public: + CCamera (CScene* scene, const Core::Scenes::CCamera* camera); + ~CCamera (); - void setOrthogonalProjection (float width, float height); + void setOrthogonalProjection (float width, float height); - const glm::vec3& getCenter () const; - const glm::vec3& getEye () const; - const glm::vec3& getUp () const; - const glm::mat4& getProjection () const; - const glm::mat4& getLookAt () const; - CScene* getScene () const; - bool isOrthogonal () const; + const glm::vec3& getCenter () const; + const glm::vec3& getEye () const; + const glm::vec3& getUp () const; + const glm::mat4& getProjection () const; + const glm::mat4& getLookAt () const; + CScene* getScene () const; + bool isOrthogonal () const; - private: - bool m_isOrthogonal; - glm::mat4 m_projection; - glm::mat4 m_lookat; - const Core::Scenes::CCamera* m_camera; - CScene* m_scene; - }; -} + private: + bool m_isOrthogonal; + glm::mat4 m_projection; + glm::mat4 m_lookat; + const Core::Scenes::CCamera* m_camera; + CScene* m_scene; +}; +} // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CFBO.cpp b/src/WallpaperEngine/Render/CFBO.cpp index ab79621..4605d96 100644 --- a/src/WallpaperEngine/Render/CFBO.cpp +++ b/src/WallpaperEngine/Render/CFBO.cpp @@ -1,27 +1,20 @@ -#include "common.h" #include "CFBO.h" +#include "common.h" using namespace WallpaperEngine::Render; -CFBO::CFBO ( - std::string name, - ITexture::TextureFormat format, - ITexture::TextureFlags flags, - float scale, - uint32_t realWidth, uint32_t realHeight, - uint32_t textureWidth, uint32_t textureHeight -) : +CFBO::CFBO (std::string name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, + uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight) : m_name (std::move (name)), m_format (format), m_scale (scale), m_flags (flags), - m_framebuffer (GL_NONE), - m_depthbuffer (GL_NONE), - m_texture (GL_NONE), - m_resolution () -{ + m_framebuffer (GL_NONE), + m_depthbuffer (GL_NONE), + m_texture (GL_NONE), + m_resolution () { // create an empty texture that'll be free'd so the FBO is transparent - GLenum drawBuffers [1] = {GL_COLOR_ATTACHMENT0}; + const GLenum drawBuffers [1] = {GL_COLOR_ATTACHMENT0}; // create the main framebuffer glGenFramebuffers (1, &this->m_framebuffer); glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer); @@ -33,32 +26,24 @@ CFBO::CFBO ( glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); // label stuff for debugging #if !NDEBUG - glObjectLabel (GL_TEXTURE, this->m_texture, -1, this->m_name.c_str ()); + glObjectLabel (GL_TEXTURE, this->m_texture, -1, this->m_name.c_str ()); #endif /* DEBUG */ // set filtering parameters, otherwise the texture is not rendered - if (flags & TextureFlags::ClampUVs) - { + if (flags & TextureFlags::ClampUVs) { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - } - else if (flags & TextureFlags::ClampUVsBorder) - { + } else if (flags & TextureFlags::ClampUVsBorder) { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - } - else - { + } else { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } - if (flags & TextureFlags::NoInterpolation) - { + if (flags & TextureFlags::NoInterpolation) { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - } - else - { + } else { glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } @@ -77,10 +62,7 @@ CFBO::CFBO ( // clear the framebuffer glClear (GL_COLOR_BUFFER_BIT); - this->m_resolution = { - textureWidth, textureHeight, - realWidth, realHeight - }; + this->m_resolution = {textureWidth, textureHeight, realWidth, realHeight}; // create the textureframe entries auto* frame = new TextureFrame; @@ -97,71 +79,68 @@ CFBO::CFBO ( this->m_frames.push_back (frame); } -const std::string& CFBO::getName () const -{ +CFBO::~CFBO () { + // free all the resources + for (const auto* frame : this->m_frames) + delete frame; + + // free opengl texture and framebuffer + glDeleteTextures (1, &this->m_texture); + glDeleteFramebuffers (1, &this->m_framebuffer); +} + +const std::string& CFBO::getName () const { return this->m_name; } -const float& CFBO::getScale () const -{ +const float& CFBO::getScale () const { return this->m_scale; } -const ITexture::TextureFormat CFBO::getFormat () const -{ +const ITexture::TextureFormat CFBO::getFormat () const { return this->m_format; } -const ITexture::TextureFlags CFBO::getFlags () const -{ +const ITexture::TextureFlags CFBO::getFlags () const { return this->m_flags; } -GLuint CFBO::getFramebuffer () const -{ +GLuint CFBO::getFramebuffer () const { return this->m_framebuffer; } -GLuint CFBO::getDepthbuffer () const -{ +GLuint CFBO::getDepthbuffer () const { return this->m_depthbuffer; } -const GLuint CFBO::getTextureID (uint32_t imageIndex) const -{ +const GLuint CFBO::getTextureID (uint32_t imageIndex) const { return this->m_texture; } -const uint32_t CFBO::getTextureWidth (uint32_t imageIndex) const -{ +const uint32_t CFBO::getTextureWidth (uint32_t imageIndex) const { return this->m_resolution.x; } -const uint32_t CFBO::getTextureHeight (uint32_t imageIndex) const -{ + +const uint32_t CFBO::getTextureHeight (uint32_t imageIndex) const { return this->m_resolution.y; } -const uint32_t CFBO::getRealWidth () const -{ +const uint32_t CFBO::getRealWidth () const { return this->m_resolution.z; } -const uint32_t CFBO::getRealHeight () const -{ +const uint32_t CFBO::getRealHeight () const { return this->m_resolution.w; } -const std::vector& CFBO::getFrames () const -{ +const std::vector& CFBO::getFrames () const { return this->m_frames; } -const glm::vec4* CFBO::getResolution () const -{ +const glm::vec4* CFBO::getResolution () const { return &this->m_resolution; } -const bool CFBO::isAnimated () const -{ +const bool CFBO::isAnimated () const { return false; } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CFBO.h b/src/WallpaperEngine/Render/CFBO.h index c99134f..19be83b 100644 --- a/src/WallpaperEngine/Render/CFBO.h +++ b/src/WallpaperEngine/Render/CFBO.h @@ -1,45 +1,45 @@ #pragma once -#include "WallpaperEngine/Core/Objects/Effects/CFBO.h" -#include "WallpaperEngine/Core/Objects/CImage.h" #include "WallpaperEngine/Assets/ITexture.h" +#include "WallpaperEngine/Core/Objects/CImage.h" +#include "WallpaperEngine/Core/Objects/Effects/CFBO.h" using namespace WallpaperEngine::Assets; -namespace WallpaperEngine::Render -{ - class CFBO : public ITexture - { - public: - CFBO (std::string name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight); - // TODO: ADD DESTRUCTOR TO FREE RESOURCES +namespace WallpaperEngine::Render { +class CFBO final : public ITexture { + public: + CFBO (std::string name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, + uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight); + ~CFBO () override; - const std::string& getName () const; - const float& getScale () const; - const ITexture::TextureFormat getFormat () const override; - const ITexture::TextureFlags getFlags () const override; - GLuint getFramebuffer () const; - GLuint getDepthbuffer () const; - const GLuint getTextureID (uint32_t imageIndex = 0) const override; - const uint32_t getTextureWidth (uint32_t imageIndex = 0) const override; - const uint32_t getTextureHeight (uint32_t imageIndex = 0) const override; - const uint32_t getRealWidth () const override; - const uint32_t getRealHeight () const override; - const std::vector& getFrames () const override; - const glm::vec4* getResolution () const override; - const bool isAnimated () const override; + // TODO: ADD DESTRUCTOR TO FREE RESOURCES - private: + const std::string& getName () const; + const float& getScale () const; + const ITexture::TextureFormat getFormat () const override; + const ITexture::TextureFlags getFlags () const override; + GLuint getFramebuffer () const; + GLuint getDepthbuffer () const; + const GLuint getTextureID (uint32_t imageIndex = 0) const override; + const uint32_t getTextureWidth (uint32_t imageIndex = 0) const override; + const uint32_t getTextureHeight (uint32_t imageIndex = 0) const override; + const uint32_t getRealWidth () const override; + const uint32_t getRealHeight () const override; + const std::vector& getFrames () const override; + const glm::vec4* getResolution () const override; + const bool isAnimated () const override; - GLuint m_framebuffer; - GLuint m_depthbuffer; - GLuint m_texture; - glm::vec4 m_resolution; - float m_scale; - std::string m_name; - ITexture::TextureFormat m_format; - ITexture::TextureFlags m_flags; - /** Placeholder for frames, FBOs only have ONE */ - std::vector m_frames; - }; -} + private: + GLuint m_framebuffer; + GLuint m_depthbuffer; + GLuint m_texture; + glm::vec4 m_resolution; + float m_scale; + std::string m_name; + ITexture::TextureFormat m_format; + ITexture::TextureFlags m_flags; + /** Placeholder for frames, FBOs only have ONE */ + std::vector m_frames; +}; +} // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CObject.cpp b/src/WallpaperEngine/Render/CObject.cpp index 6ca889d..ca05c35 100644 --- a/src/WallpaperEngine/Render/CObject.cpp +++ b/src/WallpaperEngine/Render/CObject.cpp @@ -5,28 +5,20 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Render; -CObject::CObject(CScene* scene, std::string type, Core::CObject *object) : +CObject::CObject (CScene* scene, std::string type, Core::CObject* object) : Helpers::CContextAware (scene), m_scene (scene), m_object (object), - m_type (std::move (type)) -{ -} + m_type (std::move (type)) {} -CObject::~CObject () -= default; - -CScene* CObject::getScene () const -{ +CScene* CObject::getScene () const { return this->m_scene; } -CContainer* CObject::getContainer () const -{ +CContainer* CObject::getContainer () const { return this->getScene ()->getContainer (); } -int CObject::getId () const -{ +int CObject::getId () const { return this->m_object->getId (); } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CObject.h b/src/WallpaperEngine/Render/CObject.h index fa1100d..6c233a5 100644 --- a/src/WallpaperEngine/Render/CObject.h +++ b/src/WallpaperEngine/Render/CObject.h @@ -7,32 +7,39 @@ #include "CScene.h" -namespace WallpaperEngine::Render -{ - class CScene; +namespace WallpaperEngine::Render { +class CScene; - class CObject : public Helpers::CContextAware - { - public: - template const T* as () const { assert (is()); return (const T*) this; } - template T* as () { assert (is()); return (T*) this; } +class CObject : public Helpers::CContextAware { + public: + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); + } - template bool is () { return this->m_type == T::Type; } + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } - virtual void render () = 0; + template bool is () { + return this->m_type == T::Type; + } - CScene* getScene () const; - CContainer* getContainer () const; - int getId () const; + virtual void render () = 0; - protected: - CObject (CScene* scene, std::string type, Core::CObject *object); - ~CObject (); + CScene* getScene () const; + CContainer* getContainer () const; + int getId () const; - private: - std::string m_type; + protected: + CObject (CScene* scene, std::string type, Core::CObject* object); + ~CObject () override = default; - CScene* m_scene; - Core::CObject* m_object; - }; -} \ No newline at end of file + private: + std::string m_type; + + CScene* m_scene; + Core::CObject* m_object; +}; +} // namespace WallpaperEngine::Render \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CRenderContext.cpp b/src/WallpaperEngine/Render/CRenderContext.cpp index 08ad438..9e98f03 100644 --- a/src/WallpaperEngine/Render/CRenderContext.cpp +++ b/src/WallpaperEngine/Render/CRenderContext.cpp @@ -7,78 +7,65 @@ #include "CVideo.h" #include "CWallpaper.h" -namespace WallpaperEngine::Render -{ - CRenderContext::CRenderContext ( - Drivers::CVideoDriver& driver, Input::CInputContext& input, - CWallpaperApplication& app - ) : - m_defaultWallpaper (nullptr), - m_driver (driver), - m_app (app), - m_input (input), - m_textureCache (new CTextureCache (*this)) - { - } +namespace WallpaperEngine::Render { +CRenderContext::CRenderContext (Drivers::CVideoDriver& driver, Input::CInputContext& input, + CWallpaperApplication& app) : + m_defaultWallpaper (nullptr), + m_driver (driver), + m_app (app), + m_input (input), + m_textureCache (new CTextureCache (*this)) {} - void CRenderContext::render (Drivers::Output::COutputViewport* viewport) - { - viewport->makeCurrent (); +void CRenderContext::render (Drivers::Output::COutputViewport* viewport) { + viewport->makeCurrent (); #if !NDEBUG - std::string str = "Rendering to output " + viewport->name; + const std::string str = "Rendering to output " + viewport->name; - glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ()); + glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ()); #endif /* DEBUG */ - // search the background in the viewport selection - auto ref = this->m_wallpapers.find (viewport->name); + // search the background in the viewport selection + const auto ref = this->m_wallpapers.find (viewport->name); - // render the background - if (ref != this->m_wallpapers.end ()) - ref->second->render (viewport->viewport, this->getOutput ().renderVFlip ()); - else - this->m_defaultWallpaper->render (viewport->viewport, this->getOutput ().renderVFlip ()); + // render the background + if (ref != this->m_wallpapers.end ()) + ref->second->render (viewport->viewport, this->getOutput ().renderVFlip ()); + else + this->m_defaultWallpaper->render (viewport->viewport, this->getOutput ().renderVFlip ()); #if !NDEBUG - glPopDebugGroup (); + glPopDebugGroup (); #endif /* DEBUG */ - viewport->swapOutput (); - } + viewport->swapOutput (); +} - void CRenderContext::setDefaultWallpaper (CWallpaper* wallpaper) - { - this->m_defaultWallpaper = wallpaper; - } +void CRenderContext::setDefaultWallpaper (CWallpaper* wallpaper) { + this->m_defaultWallpaper = wallpaper; +} - void CRenderContext::setWallpaper (const std::string& display, CWallpaper* wallpaper) - { - this->m_wallpapers.insert_or_assign (display, wallpaper); - } +void CRenderContext::setWallpaper (const std::string& display, CWallpaper* wallpaper) { + this->m_wallpapers.insert_or_assign (display, wallpaper); +} - Input::CInputContext& CRenderContext::getInputContext () const - { - return this->m_input; - } +Input::CInputContext& CRenderContext::getInputContext () const { + return this->m_input; +} - const CWallpaperApplication& CRenderContext::getApp () const - { - return this->m_app; - } +const CWallpaperApplication& CRenderContext::getApp () const { + return this->m_app; +} - const Drivers::CVideoDriver& CRenderContext::getDriver () const - { - return this->m_driver; - } +const Drivers::CVideoDriver& CRenderContext::getDriver () const { + return this->m_driver; +} - const Drivers::Output::COutput& CRenderContext::getOutput () const - { - return this->m_driver.getOutput (); - } +const Drivers::Output::COutput& CRenderContext::getOutput () const { + return this->m_driver.getOutput (); +} - const ITexture* CRenderContext::resolveTexture (const std::string& name) - { - return this->m_textureCache->resolve (name); - } -} \ No newline at end of file +const ITexture* CRenderContext::resolveTexture (const std::string& name) { + return this->m_textureCache->resolve (name); +} +} // namespace WallpaperEngine::Render \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CRenderContext.h b/src/WallpaperEngine/Render/CRenderContext.h index 2ce79e1..60e6082 100644 --- a/src/WallpaperEngine/Render/CRenderContext.h +++ b/src/WallpaperEngine/Render/CRenderContext.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include "CTextureCache.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" @@ -11,56 +11,50 @@ #include "WallpaperEngine/Render/Drivers/Output/COutput.h" #include "WallpaperEngine/Render/Drivers/Output/COutputViewport.h" -namespace WallpaperEngine -{ - namespace Application - { - class CWallpaperApplication; - } +namespace WallpaperEngine { +namespace Application { +class CWallpaperApplication; +} - namespace Render - { - namespace Drivers - { - class CVideoDriver; +namespace Render { +namespace Drivers { +class CVideoDriver; - namespace Output - { - class COutput; - class COutputViewport; - } - } +namespace Output { +class COutput; +class COutputViewport; +} // namespace Output +} // namespace Drivers - class CWallpaper; - class CTextureCache; +class CWallpaper; +class CTextureCache; - class CRenderContext - { - public: - CRenderContext (Drivers::CVideoDriver& driver, Input::CInputContext& input, CWallpaperApplication& app); +class CRenderContext { + public: + CRenderContext (Drivers::CVideoDriver& driver, Input::CInputContext& input, CWallpaperApplication& app); - void render (Drivers::Output::COutputViewport* viewport); - void setDefaultWallpaper (CWallpaper* wallpaper); - void setWallpaper (const std::string& display, CWallpaper* wallpaper); - [[nodiscard]] Input::CInputContext& getInputContext () const; - [[nodiscard]] const CWallpaperApplication& getApp () const; - [[nodiscard]] const Drivers::CVideoDriver& getDriver () const; - [[nodiscard]] const Drivers::Output::COutput& getOutput () const; - const ITexture* resolveTexture (const std::string& name); + void render (Drivers::Output::COutputViewport* viewport); + void setDefaultWallpaper (CWallpaper* wallpaper); + void setWallpaper (const std::string& display, CWallpaper* wallpaper); + [[nodiscard]] Input::CInputContext& getInputContext () const; + [[nodiscard]] const CWallpaperApplication& getApp () const; + [[nodiscard]] const Drivers::CVideoDriver& getDriver () const; + [[nodiscard]] const Drivers::Output::COutput& getOutput () const; + const ITexture* resolveTexture (const std::string& name); - private: - /** Video driver in use */ - Drivers::CVideoDriver& m_driver; - /** Maps screen -> wallpaper list */ - std::map m_wallpapers; - /** Default wallpaper to use */ - CWallpaper* m_defaultWallpaper; - /** Input context for interactions */ - Input::CInputContext& m_input; - /** App that holds the render context */ - CWallpaperApplication& m_app; - /** Texture cache for the render */ - CTextureCache* m_textureCache; - }; - } -} \ No newline at end of file + private: + /** Video driver in use */ + Drivers::CVideoDriver& m_driver; + /** Maps screen -> wallpaper list */ + std::map m_wallpapers; + /** Default wallpaper to use */ + CWallpaper* m_defaultWallpaper; + /** Input context for interactions */ + Input::CInputContext& m_input; + /** App that holds the render context */ + CWallpaperApplication& m_app; + /** Texture cache for the render */ + CTextureCache* m_textureCache; +}; +} // namespace Render +} // namespace WallpaperEngine \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CScene.cpp b/src/WallpaperEngine/Render/CScene.cpp index f635e62..e30c646 100644 --- a/src/WallpaperEngine/Render/CScene.cpp +++ b/src/WallpaperEngine/Render/CScene.cpp @@ -16,25 +16,23 @@ extern float g_TimeLast; using namespace WallpaperEngine; using namespace WallpaperEngine::Render; -CScene::CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode) : +CScene::CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode) : CWallpaper (scene, Type, context, audioContext, scalingMode), m_mousePosition (), m_mousePositionLast (), - m_parallaxDisplacement () -{ + m_parallaxDisplacement () { // setup the scene camera this->m_camera = new CCamera (this, scene->getCamera ()); // detect size if the orthogonal project is auto - if (scene->getOrthogonalProjection ()->isAuto ()) - { + if (scene->getOrthogonalProjection ()->isAuto ()) { // calculate the size of the projection based on the size of everything - for (const auto& cur : scene->getObjects ()) - { - if (!cur.second->is ()) + for (const auto& [id, sceneObject] : scene->getObjects ()) { + if (!sceneObject->is ()) continue; - glm::vec2 size = cur.second->as ()->getSize (); + const glm::vec2 size = sceneObject->as ()->getSize (); scene->getOrthogonalProjection ()->setWidth (size.x); scene->getOrthogonalProjection ()->setHeight (size.y); @@ -43,63 +41,44 @@ CScene::CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& aud this->m_parallaxDisplacement = {0, 0}; - this->m_camera->setOrthogonalProjection ( - scene->getOrthogonalProjection ()->getWidth (), - scene->getOrthogonalProjection ()->getHeight () - ); + this->m_camera->setOrthogonalProjection (scene->getOrthogonalProjection ()->getWidth (), + scene->getOrthogonalProjection ()->getHeight ()); // setup framebuffers here as they're required for the scene setup - this->setupFramebuffers(); + this->setupFramebuffers (); // set clear color - glm::vec3 clearColor = this->getScene ()->getClearColor (); + const glm::vec3 clearColor = this->getScene ()->getClearColor (); glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f); // create all objects based off their dependencies - for (const auto& cur : scene->getObjects ()) - this->createObject (cur.second); + for (const auto& [id, sceneObject] : scene->getObjects ()) + this->createObject (sceneObject); // copy over objects by render order - for (const auto& cur : scene->getObjectsByRenderOrder ()) - { + for (const auto& cur : scene->getObjectsByRenderOrder ()) { auto obj = this->m_objects.find (cur->getId ()); // ignores not created objects like particle systems if (obj == this->m_objects.end ()) continue; - this->m_objectsByRenderOrder.emplace_back ((*obj).second); + this->m_objectsByRenderOrder.emplace_back (obj->second); } - uint32_t sceneWidth = scene->getOrthogonalProjection ()->getWidth (); - uint32_t sceneHeight = scene->getOrthogonalProjection ()->getHeight (); + const uint32_t sceneWidth = scene->getOrthogonalProjection ()->getWidth (); + const uint32_t sceneHeight = scene->getOrthogonalProjection ()->getHeight (); // create extra framebuffers for the bloom effect - this->_rt_4FrameBuffer = this->createFBO ( - "_rt_4FrameBuffer", - ITexture::TextureFormat::ARGB8888, - ITexture::TextureFlags::ClampUVs, - 1.0, - sceneWidth / 4, sceneHeight / 4, - sceneWidth / 4, sceneHeight / 4 - ); - this->_rt_8FrameBuffer = this->createFBO ( - "_rt_8FrameBuffer", - ITexture::TextureFormat::ARGB8888, - ITexture::TextureFlags::ClampUVs, - 1.0, - sceneWidth / 8, sceneHeight / 8, - sceneWidth / 8, sceneHeight / 8 - ); - this->_rt_Bloom = this->createFBO ( - "_rt_Bloom", - ITexture::TextureFormat::ARGB8888, - ITexture::TextureFlags::ClampUVs, - 1.0, - sceneWidth / 8, sceneHeight / 8, - sceneWidth / 8, sceneHeight / 8 - ); + this->_rt_4FrameBuffer = + this->createFBO ("_rt_4FrameBuffer", ITexture::TextureFormat::ARGB8888, ITexture::TextureFlags::ClampUVs, 1.0, + sceneWidth / 4, sceneHeight / 4, sceneWidth / 4, sceneHeight / 4); + this->_rt_8FrameBuffer = + this->createFBO ("_rt_8FrameBuffer", ITexture::TextureFormat::ARGB8888, ITexture::TextureFlags::ClampUVs, 1.0, + sceneWidth / 8, sceneHeight / 8, sceneWidth / 8, sceneHeight / 8); + this->_rt_Bloom = this->createFBO ("_rt_Bloom", ITexture::TextureFormat::ARGB8888, ITexture::TextureFlags::ClampUVs, + 1.0, sceneWidth / 8, sceneHeight / 8, sceneWidth / 8, sceneHeight / 8); // // Had to get a little creative with the effects to achieve the same bloom effect without any custom code @@ -108,77 +87,85 @@ CScene::CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& aud // (it renders directly to the screen, whereas here we never do that from a scene) // - std::string imagejson = - "{" - "\t\"image\": \"models/wpenginelinux.json\"," - "\t\"name\": \"bloomimagewpenginelinux\"," - "\t\"visible\": true," - "\t\"scale\": \"1.0 1.0 1.0\"," - "\t\"angles\": \"0.0 0.0 0.0\"," - "\t\"origin\": \"" + std::to_string (sceneWidth / 2) + " " + std::to_string (sceneHeight / 2) + " 0.0\"," - "\t\"id\": " + std::to_string (0xFFFFFFFF) + "," - "\t\"effects\":" - "\t[" - "\t\t{" - "\t\t\t\"file\": \"effects/wpenginelinux/bloomeffect.json\"," - "\t\t\t\"id\": 15242000," - "\t\t\t\"name\": \"\"," - "\t\t\t\"passes\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"constantshadervalues\":" - "\t\t\t\t\t{" - "\t\t\t\t\t\t\"bloomstrength\": " + std::to_string (this->getScene ()->getBloomStrength ()) + "," - "\t\t\t\t\t\t\"bloomthreshold\": " + std::to_string (this->getScene ()->getBloomThreshold ()) + - "\t\t\t\t\t}" - "\t\t\t\t}," - "\t\t\t\t{" - "\t\t\t\t\t\"constantshadervalues\":" - "\t\t\t\t\t{" - "\t\t\t\t\t\t\"bloomstrength\": " + std::to_string (this->getScene ()->getBloomStrength ()) + "," - "\t\t\t\t\t\t\"bloomthreshold\": " + std::to_string (this->getScene ()->getBloomThreshold ()) + - "\t\t\t\t\t}" - "\t\t\t\t}," - "\t\t\t\t{" - "\t\t\t\t\t\"constantshadervalues\":" - "\t\t\t\t\t{" - "\t\t\t\t\t\t\"bloomstrength\": " + std::to_string (this->getScene ()->getBloomStrength ()) + "," - "\t\t\t\t\t\t\"bloomthreshold\": " + std::to_string (this->getScene ()->getBloomThreshold ()) + - "\t\t\t\t\t}" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}" - "\t]," - "\t\"size\": \"" + std::to_string (sceneWidth) + " " + std::to_string (sceneHeight) + "\"" - "}"; - auto json = nlohmann::json::parse (imagejson); + const std::string imagejson = "{" + "\t\"image\": \"models/wpenginelinux.json\"," + "\t\"name\": \"bloomimagewpenginelinux\"," + "\t\"visible\": true," + "\t\"scale\": \"1.0 1.0 1.0\"," + "\t\"angles\": \"0.0 0.0 0.0\"," + "\t\"origin\": \"" + + std::to_string (sceneWidth / 2) + " " + std::to_string (sceneHeight / 2) + + " 0.0\"," + "\t\"id\": " + + std::to_string (0xFFFFFFFF) + + "," + "\t\"effects\":" + "\t[" + "\t\t{" + "\t\t\t\"file\": \"effects/wpenginelinux/bloomeffect.json\"," + "\t\t\t\"id\": 15242000," + "\t\t\t\"name\": \"\"," + "\t\t\t\"passes\":" + "\t\t\t[" + "\t\t\t\t{" + "\t\t\t\t\t\"constantshadervalues\":" + "\t\t\t\t\t{" + "\t\t\t\t\t\t\"bloomstrength\": " + + std::to_string (this->getScene ()->getBloomStrength ()) + + "," + "\t\t\t\t\t\t\"bloomthreshold\": " + + std::to_string (this->getScene ()->getBloomThreshold ()) + + "\t\t\t\t\t}" + "\t\t\t\t}," + "\t\t\t\t{" + "\t\t\t\t\t\"constantshadervalues\":" + "\t\t\t\t\t{" + "\t\t\t\t\t\t\"bloomstrength\": " + + std::to_string (this->getScene ()->getBloomStrength ()) + + "," + "\t\t\t\t\t\t\"bloomthreshold\": " + + std::to_string (this->getScene ()->getBloomThreshold ()) + + "\t\t\t\t\t}" + "\t\t\t\t}," + "\t\t\t\t{" + "\t\t\t\t\t\"constantshadervalues\":" + "\t\t\t\t\t{" + "\t\t\t\t\t\t\"bloomstrength\": " + + std::to_string (this->getScene ()->getBloomStrength ()) + + "," + "\t\t\t\t\t\t\"bloomthreshold\": " + + std::to_string (this->getScene ()->getBloomThreshold ()) + + "\t\t\t\t\t}" + "\t\t\t\t}" + "\t\t\t]" + "\t\t}" + "\t]," + "\t\"size\": \"" + + std::to_string (sceneWidth) + " " + std::to_string (sceneHeight) + + "\"" + "}"; + const auto json = nlohmann::json::parse (imagejson); // create image for bloom passes - if (this->getScene ()->isBloom ()) - { + if (this->getScene ()->isBloom ()) { this->m_bloomObject = this->createObject ( - WallpaperEngine::Core::CObject::fromJSON ( - json, this->getScene (), this->getContainer () - ) - ); + WallpaperEngine::Core::CObject::fromJSON (json, this->getScene (), this->getContainer ())); this->m_objectsByRenderOrder.push_back (this->m_bloomObject); } } -Render::CObject* CScene::createObject (Core::CObject* object) -{ +Render::CObject* CScene::createObject (Core::CObject* object) { Render::CObject* renderObject = nullptr; // ensure the item is not loaded already - auto current = this->m_objects.find (object->getId ()); + const auto current = this->m_objects.find (object->getId ()); if (current != this->m_objects.end ()) - return (*current).second; + return current->second; // check dependencies too! - for (const auto& cur : object->getDependencies ()) - { + for (const auto& cur : object->getDependencies ()) { // self-dependency is a possibility... if (cur == object->getId ()) continue; @@ -186,28 +173,22 @@ Render::CObject* CScene::createObject (Core::CObject* object) auto dep = this->getScene ()->getObjects ().find (cur); if (dep != this->getScene ()->getObjects ().end ()) - this->createObject ((*dep).second); + this->createObject (dep->second); } - if (object->is ()) - { - auto* image = new Objects::CImage (this, object->as()); + if (object->is ()) { + auto* image = new Objects::CImage (this, object->as ()); - try - { + try { image->setup (); - } - catch (std::runtime_error& ex) - { + } catch (std::runtime_error&) { // this error message is already printed, so just show extra info about it sLog.error ("Cannot setup image ", image->getImage ()->getName ()); } renderObject = image; - } - else if (object->is ()) - { - renderObject = new Objects::CSound (this, object->as()); + } else if (object->is ()) { + renderObject = new Objects::CSound (this, object->as ()); } if (renderObject != nullptr) @@ -216,28 +197,27 @@ Render::CObject* CScene::createObject (Core::CObject* object) return renderObject; } -CCamera* CScene::getCamera () const -{ +CCamera* CScene::getCamera () const { return this->m_camera; } -void CScene::renderFrame (glm::ivec4 viewport) -{ +void CScene::renderFrame (glm::ivec4 viewport) { // ensure the virtual mouse position is up to date this->updateMouse (viewport); // update the parallax position if required - if (this->getScene ()->isCameraParallax ()) - { - float influence = this->getScene ()->getCameraParallaxMouseInfluence (); - float amount = this->getScene ()->getCameraParallaxAmount (); - float delay = glm::min ((float) this->getScene ()->getCameraParallaxDelay (), g_Time - g_TimeLast); + if (this->getScene ()->isCameraParallax ()) { + const float influence = this->getScene ()->getCameraParallaxMouseInfluence (); + const float amount = this->getScene ()->getCameraParallaxAmount (); + const float delay = + glm::min (static_cast (this->getScene ()->getCameraParallaxDelay ()), g_Time - g_TimeLast); - this->m_parallaxDisplacement = glm::mix (this->m_parallaxDisplacement, (this->m_mousePosition * amount) * influence, delay); + this->m_parallaxDisplacement = + glm::mix (this->m_parallaxDisplacement, (this->m_mousePosition * amount) * influence, delay); } // use the scene's framebuffer by default - glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer()); + glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ()); // ensure we render over the whole framebuffer glViewport (0, 0, this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ()); @@ -247,10 +227,9 @@ void CScene::renderFrame (glm::ivec4 viewport) cur->render (); } -void CScene::updateMouse (glm::ivec4 viewport) -{ +void CScene::updateMouse (glm::ivec4 viewport) { // update virtual mouse position first - glm::dvec2 position = this->getContext ().getInputContext ().getMouseInput ().position(); + const glm::dvec2 position = this->getContext ().getInputContext ().getMouseInput ().position (); // TODO: PROPERLY TRANSLATE THESE TO WHAT'S VISIBLE ON SCREEN (FOR BACKGROUNDS THAT DO NOT EXACTLY FIT ON SCREEN) // rollover the position to the last @@ -263,33 +242,27 @@ void CScene::updateMouse (glm::ivec4 viewport) // screen-space positions have to be transposed to what the screen will actually show } -Core::CScene* CScene::getScene () const -{ +Core::CScene* CScene::getScene () const { return this->getWallpaperData ()->as (); } -uint32_t CScene::getWidth () const -{ - return this->getScene ()->getOrthogonalProjection()->getWidth (); +uint32_t CScene::getWidth () const { + return this->getScene ()->getOrthogonalProjection ()->getWidth (); } -uint32_t CScene::getHeight () const -{ - return this->getScene ()->getOrthogonalProjection()->getHeight (); +uint32_t CScene::getHeight () const { + return this->getScene ()->getOrthogonalProjection ()->getHeight (); } -glm::vec2* CScene::getMousePosition () -{ +glm::vec2* CScene::getMousePosition () { return &this->m_mousePosition; } -glm::vec2* CScene::getMousePositionLast () -{ +glm::vec2* CScene::getMousePositionLast () { return &this->m_mousePositionLast; } -glm::vec2* CScene::getParallaxDisplacement () -{ +glm::vec2* CScene::getParallaxDisplacement () { return &this->m_parallaxDisplacement; } diff --git a/src/WallpaperEngine/Render/CScene.h b/src/WallpaperEngine/Render/CScene.h index 80b7186..f0175ed 100644 --- a/src/WallpaperEngine/Render/CScene.h +++ b/src/WallpaperEngine/Render/CScene.h @@ -5,49 +5,47 @@ #include "WallpaperEngine/Core/CScene.h" #include "WallpaperEngine/Render/CWallpaper.h" -#include "WallpaperEngine/Render/CObject.h" -namespace WallpaperEngine::Render -{ - class CCamera; - class CObject; +namespace WallpaperEngine::Render { +class CCamera; +class CObject; - class CScene : public CWallpaper - { - public: - CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode); +class CScene final : public CWallpaper { + public: + CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode); - CCamera* getCamera () const; + CCamera* getCamera () const; - Core::CScene* getScene () const; + Core::CScene* getScene () const; - uint32_t getWidth () const override; - uint32_t getHeight () const override; + uint32_t getWidth () const override; + uint32_t getHeight () const override; - glm::vec2* getMousePosition (); - glm::vec2* getMousePositionLast (); - glm::vec2* getParallaxDisplacement (); + glm::vec2* getMousePosition (); + glm::vec2* getMousePositionLast (); + glm::vec2* getParallaxDisplacement (); - protected: - void renderFrame (glm::ivec4 viewport) override; - void updateMouse (glm::ivec4 viewport); + protected: + void renderFrame (glm::ivec4 viewport) override; + void updateMouse (glm::ivec4 viewport); - friend class CWallpaper; + friend class CWallpaper; - static const std::string Type; + static const std::string Type; - private: - Render::CObject* createObject (Core::CObject* object); + private: + Render::CObject* createObject (Core::CObject* object); - CCamera* m_camera; - CObject* m_bloomObject; - std::map m_objects; - std::vector m_objectsByRenderOrder; - glm::vec2 m_mousePosition; - glm::vec2 m_mousePositionLast; - glm::vec2 m_parallaxDisplacement; - CFBO* _rt_4FrameBuffer; - CFBO* _rt_8FrameBuffer; - CFBO* _rt_Bloom; - }; -} + CCamera* m_camera; + CObject* m_bloomObject; + std::map m_objects; + std::vector m_objectsByRenderOrder; + glm::vec2 m_mousePosition; + glm::vec2 m_mousePositionLast; + glm::vec2 m_parallaxDisplacement; + CFBO* _rt_4FrameBuffer; + CFBO* _rt_8FrameBuffer; + CFBO* _rt_Bloom; +}; +} // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CTextureCache.cpp b/src/WallpaperEngine/Render/CTextureCache.cpp index 08bab28..ced3347 100644 --- a/src/WallpaperEngine/Render/CTextureCache.cpp +++ b/src/WallpaperEngine/Render/CTextureCache.cpp @@ -1,55 +1,41 @@ #include "CTextureCache.h" -#include "WallpaperEngine/Render/Helpers/CContextAware.h" #include "WallpaperEngine/Assets/CAssetLoadException.h" +#include "WallpaperEngine/Render/Helpers/CContextAware.h" using namespace WallpaperEngine::Render; using namespace WallpaperEngine::Assets; -CTextureCache::CTextureCache (CRenderContext& context) : - Helpers::CContextAware (context) -{ -} +CTextureCache::CTextureCache (CRenderContext& context) : Helpers::CContextAware (context) {} -CTextureCache::~CTextureCache () -= default; - -const ITexture* CTextureCache::resolve (const std::string& filename) -{ - auto found = this->m_textureCache.find (filename); +const ITexture* CTextureCache::resolve (const std::string& filename) { + const auto found = this->m_textureCache.find (filename); if (found != this->m_textureCache.end ()) - return (*found).second; + return found->second; // search for the texture in all the different containers just in case - for (auto it : this->getContext ().getApp ().getBackgrounds ()) - { - try - { + for (const auto it : this->getContext ().getApp ().getBackgrounds ()) { + try { const ITexture* texture = it.second->getContainer ()->readTexture (filename); this->store (filename, texture); return texture; - } - catch (CAssetLoadException& ex) - { + } catch (CAssetLoadException&) { // ignored, this happens if we're looking at the wrong background } } - if (this->getContext ().getApp ().getDefaultBackground () != nullptr) - { - try - { - const ITexture* texture = this->getContext ().getApp ().getDefaultBackground ()->getContainer ()->readTexture (filename); + if (this->getContext ().getApp ().getDefaultBackground () != nullptr) { + try { + const ITexture* texture = + this->getContext ().getApp ().getDefaultBackground ()->getContainer ()->readTexture (filename); this->store (filename, texture); return texture; - } - catch (CAssetLoadException& ex) - { + } catch (CAssetLoadException&) { // ignored, this happens if we're looking at the wrong background } } @@ -57,7 +43,6 @@ const ITexture* CTextureCache::resolve (const std::string& filename) throw CAssetLoadException (filename, "Cannot find file"); } -void CTextureCache::store (const std::string& name, const ITexture* texture) -{ +void CTextureCache::store (const std::string& name, const ITexture* texture) { this->m_textureCache.insert_or_assign (name, texture); } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CTextureCache.h b/src/WallpaperEngine/Render/CTextureCache.h index 94c6fc4..484539c 100644 --- a/src/WallpaperEngine/Render/CTextureCache.h +++ b/src/WallpaperEngine/Render/CTextureCache.h @@ -9,40 +9,36 @@ using namespace WallpaperEngine::Assets; -namespace WallpaperEngine::Render -{ - namespace Helpers - { - class CContextAware; - } - - class CRenderContext; - - class CTextureCache : Helpers::CContextAware - { - public: - explicit CTextureCache (CRenderContext& context); - ~CTextureCache (); - - /** - * Checks if the given texture was already loaded and returns it - * If the texture was not loaded yet, it tries to load it from the container - * - * @param filename - * @return - */ - const ITexture* resolve (const std::string& filename); - - /** - * Registers a texture in the cache - * - * @param name - * @param texture - */ - void store (const std::string& name, const ITexture* texture); - - private: - /** Cached textures */ - std::map m_textureCache; - }; +namespace WallpaperEngine::Render { +namespace Helpers { +class CContextAware; } + +class CRenderContext; + +class CTextureCache final : Helpers::CContextAware { + public: + explicit CTextureCache (CRenderContext& context); + + /** + * Checks if the given texture was already loaded and returns it + * If the texture was not loaded yet, it tries to load it from the container + * + * @param filename + * @return + */ + const ITexture* resolve (const std::string& filename); + + /** + * Registers a texture in the cache + * + * @param name + * @param texture + */ + void store (const std::string& name, const ITexture* texture); + + private: + /** Cached textures */ + std::map m_textureCache; +}; +} // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CVideo.cpp b/src/WallpaperEngine/Render/CVideo.cpp index 6b18f0b..3e133fe 100644 --- a/src/WallpaperEngine/Render/CVideo.cpp +++ b/src/WallpaperEngine/Render/CVideo.cpp @@ -1,22 +1,21 @@ -#include "common.h" #include "CVideo.h" +#include "common.h" #include using namespace WallpaperEngine; using namespace WallpaperEngine::Render; -void* get_proc_address (void* ctx, const char* name) -{ +void* get_proc_address (void* ctx, const char* name) { return static_cast (ctx)->getContext ().getDriver ().getProcAddress (name); } -CVideo::CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode) : +CVideo::CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode) : CWallpaper (video, Type, context, audioContext, scalingMode), m_width (16), m_height (16), - m_mpvGl (nullptr) -{ + m_mpvGl (nullptr) { double volume = this->getContext ().getApp ().getContext ().settings.audio.volume * 100.0 / 128.0; // create mpv contexts @@ -41,40 +40,33 @@ CVideo::CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& aud // initialize gl context for mpv mpv_opengl_init_params gl_init_params {get_proc_address, this}; - mpv_render_param params[] { - {MPV_RENDER_PARAM_API_TYPE, const_cast (MPV_RENDER_API_TYPE_OPENGL)}, - {MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init_params}, - {MPV_RENDER_PARAM_INVALID, nullptr} - }; + mpv_render_param params [] {{MPV_RENDER_PARAM_API_TYPE, const_cast (MPV_RENDER_API_TYPE_OPENGL)}, + {MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init_params}, + {MPV_RENDER_PARAM_INVALID, nullptr}}; if (mpv_render_context_create (&this->m_mpvGl, this->m_mpv, params) < 0) sLog.exception ("Failed to initialize MPV's GL context"); - std::filesystem::path videopath = this->getVideo ()->getProject ().getContainer ()->resolveRealFile (this->getVideo ()->getFilename ()); + const std::filesystem::path videopath = + this->getVideo ()->getProject ().getContainer ()->resolveRealFile (this->getVideo ()->getFilename ()); // build the path to the video file - const char* command [] = { - "loadfile", videopath.c_str (), nullptr - }; + const char* command [] = {"loadfile", videopath.c_str (), nullptr}; if (mpv_command (this->m_mpv, command) < 0) sLog.exception ("Cannot load video to play"); - if (!this->getContext ().getApp ().getContext ().settings.audio.enabled) - { - const char* mutecommand [] = { - "set", "mute", "yes", nullptr - }; + if (!this->getContext ().getApp ().getContext ().settings.audio.enabled) { + const char* mutecommand [] = {"set", "mute", "yes", nullptr}; mpv_command (this->m_mpv, mutecommand); } // setup framebuffers - this->setupFramebuffers(); + this->setupFramebuffers (); } -void CVideo::setSize (int64_t width, int64_t height) -{ +void CVideo::setSize (int64_t width, int64_t height) { this->m_width = width > 0 ? width : this->m_width; this->m_height = height > 0 ? height : this->m_height; @@ -83,23 +75,20 @@ void CVideo::setSize (int64_t width, int64_t height) return; // reconfigure the texture - glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture()); + glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture ()); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, this->m_width, this->m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); } -void CVideo::renderFrame (glm::ivec4 viewport) -{ +void CVideo::renderFrame (glm::ivec4 viewport) { // read any and all the events available - while (this->m_mpv) - { - mpv_event* event = mpv_wait_event (this->m_mpv, 0); + while (this->m_mpv) { + const mpv_event* event = mpv_wait_event (this->m_mpv, 0); if (event == nullptr || event->event_id == MPV_EVENT_NONE) break; // we do not care about any of the events - if (event->event_id == MPV_EVENT_VIDEO_RECONFIG) - { + if (event->event_id == MPV_EVENT_VIDEO_RECONFIG) { int64_t width, height; if (mpv_get_property (this->m_mpv, "dwidth", MPV_FORMAT_INT64, &width) >= 0 && @@ -111,37 +100,27 @@ void CVideo::renderFrame (glm::ivec4 viewport) // render the next glViewport (0, 0, this->getWidth (), this->getHeight ()); - mpv_opengl_fbo fbo { - static_cast (this->getWallpaperFramebuffer()), - static_cast (this->m_width), - static_cast (this->m_height), - GL_RGBA8 - }; + mpv_opengl_fbo fbo {static_cast (this->getWallpaperFramebuffer ()), static_cast (this->m_width), + static_cast (this->m_height), GL_RGBA8}; // no need to flip as it'll be handled by the wallpaper rendering code int flip_y = 0; mpv_render_param params [] = { - {MPV_RENDER_PARAM_OPENGL_FBO, &fbo}, - {MPV_RENDER_PARAM_FLIP_Y, &flip_y}, - {MPV_RENDER_PARAM_INVALID, nullptr} - }; + {MPV_RENDER_PARAM_OPENGL_FBO, &fbo}, {MPV_RENDER_PARAM_FLIP_Y, &flip_y}, {MPV_RENDER_PARAM_INVALID, nullptr}}; mpv_render_context_render (this->m_mpvGl, params); } -Core::CVideo* CVideo::getVideo () -{ +Core::CVideo* CVideo::getVideo () { return this->getWallpaperData ()->as (); } -uint32_t CVideo::getWidth () const -{ +uint32_t CVideo::getWidth () const { return this->m_width; } -uint32_t CVideo::getHeight () const -{ +uint32_t CVideo::getHeight () const { return this->m_height; } diff --git a/src/WallpaperEngine/Render/CVideo.h b/src/WallpaperEngine/Render/CVideo.h index d1ef5b6..685c602 100644 --- a/src/WallpaperEngine/Render/CVideo.h +++ b/src/WallpaperEngine/Render/CVideo.h @@ -7,32 +7,31 @@ #include #include -namespace WallpaperEngine::Render -{ - class CVideo : public CWallpaper - { - public: - CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode); +namespace WallpaperEngine::Render { +class CVideo final : public CWallpaper { + public: + CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode); - Core::CVideo* getVideo (); + Core::CVideo* getVideo (); - uint32_t getWidth () const override; - uint32_t getHeight () const override; + uint32_t getWidth () const override; + uint32_t getHeight () const override; - void setSize (int64_t width, int64_t height); + void setSize (int64_t width, int64_t height); - protected: - void renderFrame (glm::ivec4 viewport) override; + protected: + void renderFrame (glm::ivec4 viewport) override; - friend class CWallpaper; + friend class CWallpaper; - static const std::string Type; + static const std::string Type; - private: - mpv_handle* m_mpv; - mpv_render_context* m_mpvGl; + private: + mpv_handle* m_mpv; + mpv_render_context* m_mpvGl; - int64_t m_width; - int64_t m_height; - }; -} + int64_t m_width; + int64_t m_height; +}; +} // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CWallpaper.cpp b/src/WallpaperEngine/Render/CWallpaper.cpp index dbb1be5..3faee58 100644 --- a/src/WallpaperEngine/Render/CWallpaper.cpp +++ b/src/WallpaperEngine/Render/CWallpaper.cpp @@ -1,18 +1,19 @@ -#include "common.h" #include "CWallpaper.h" #include "CScene.h" #include "CVideo.h" +#include "common.h" -#include #include #include +#include using namespace WallpaperEngine::Render; -CWallpaper::CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode) : +CWallpaper::CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRenderContext& context, + CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode) : CContextAware (context), m_wallpaperData (wallpaperData), - m_type (std::move(type)), + m_type (std::move (type)), m_destFramebuffer (GL_NONE), m_sceneFBO (nullptr), m_texCoordBuffer (GL_NONE), @@ -23,32 +24,18 @@ CWallpaper::CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRend a_TexCoord (GL_NONE), m_vaoBuffer (GL_NONE), m_audioContext (audioContext), - m_state(scalingMode) -{ + m_state (scalingMode) { // generate the VAO to stop opengl from complaining glGenVertexArrays (1, &this->m_vaoBuffer); glBindVertexArray (this->m_vaoBuffer); this->setupShaders (); - GLfloat texCoords [] = { - 0.0f, 0.0f, - 1.0f, 0.0f, - 0.0f, 1.0f, - 0.0f, 1.0f, - 1.0f, 0.0f, - 1.0f, 1.0f - }; + const GLfloat texCoords [] = {0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f}; // inverted positions so the final texture is rendered properly - GLfloat position [] = { - -1.0f, 1.0f, 0.0f, - 1.0, 1.0f, 0.0f, - -1.0f, -1.0f, 0.0f, - -1.0f, -1.0f, 0.0f, - 1.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 0.0f - }; + const GLfloat position [] = {-1.0f, 1.0f, 0.0f, 1.0, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, + -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f}; glGenBuffers (1, &this->m_texCoordBuffer); glBindBuffer (GL_ARRAY_BUFFER, this->m_texCoordBuffer); @@ -59,33 +46,27 @@ CWallpaper::CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRend glBufferData (GL_ARRAY_BUFFER, sizeof (position), position, GL_STATIC_DRAW); } -CWallpaper::~CWallpaper () -= default; +CWallpaper::~CWallpaper () = default; -CContainer* CWallpaper::getContainer () const -{ +CContainer* CWallpaper::getContainer () const { return this->m_wallpaperData->getProject ().getContainer (); } -WallpaperEngine::Core::CWallpaper* CWallpaper::getWallpaperData () const -{ +WallpaperEngine::Core::CWallpaper* CWallpaper::getWallpaperData () const { return this->m_wallpaperData; } -GLuint CWallpaper::getWallpaperFramebuffer () const -{ +GLuint CWallpaper::getWallpaperFramebuffer () const { return this->m_sceneFBO->getFramebuffer (); } -GLuint CWallpaper::getWallpaperTexture () const -{ - return this->m_sceneFBO->getTextureID(0); +GLuint CWallpaper::getWallpaperTexture () const { + return this->m_sceneFBO->getTextureID (0); } -void CWallpaper::setupShaders () -{ +void CWallpaper::setupShaders () { // reserve shaders in OpenGL - GLuint vertexShaderID = glCreateShader (GL_VERTEX_SHADER); + const GLuint vertexShaderID = glCreateShader (GL_VERTEX_SHADER); // give shader's source code to OpenGL to be compiled const char* sourcePointer = "#version 330\n" @@ -108,23 +89,22 @@ void CWallpaper::setupShaders () glGetShaderiv (vertexShaderID, GL_COMPILE_STATUS, &result); glGetShaderiv (vertexShaderID, GL_INFO_LOG_LENGTH, &infoLogLength); - if (infoLogLength > 0) - { + if (infoLogLength > 0) { char* logBuffer = new char [infoLogLength + 1]; // ensure logBuffer ends with a \0 memset (logBuffer, 0, infoLogLength + 1); // get information about the error glGetShaderInfoLog (vertexShaderID, infoLogLength, nullptr, logBuffer); // throw an exception about the issue - std::string message = logBuffer; + const std::string message = logBuffer; // free the buffer - delete[] logBuffer; + delete [] logBuffer; // throw an exception sLog.exception (message); } // reserve shaders in OpenGL - GLuint fragmentShaderID = glCreateShader (GL_FRAGMENT_SHADER); + const GLuint fragmentShaderID = glCreateShader (GL_FRAGMENT_SHADER); // give shader's source code to OpenGL to be compiled sourcePointer = "#version 330\n" @@ -146,17 +126,16 @@ void CWallpaper::setupShaders () glGetShaderiv (fragmentShaderID, GL_COMPILE_STATUS, &result); glGetShaderiv (fragmentShaderID, GL_INFO_LOG_LENGTH, &infoLogLength); - if (infoLogLength > 0) - { + if (infoLogLength > 0) { char* logBuffer = new char [infoLogLength + 1]; // ensure logBuffer ends with a \0 memset (logBuffer, 0, infoLogLength + 1); // get information about the error glGetShaderInfoLog (fragmentShaderID, infoLogLength, nullptr, logBuffer); // throw an exception about the issue - std::string message = logBuffer; + const std::string message = logBuffer; // free the buffer - delete[] logBuffer; + delete [] logBuffer; // throw an exception sLog.exception (message); } @@ -174,17 +153,16 @@ void CWallpaper::setupShaders () glGetProgramiv (this->m_shader, GL_LINK_STATUS, &result); glGetProgramiv (this->m_shader, GL_INFO_LOG_LENGTH, &infoLogLength); - if (infoLogLength > 0) - { + if (infoLogLength > 0) { char* logBuffer = new char [infoLogLength + 1]; // ensure logBuffer ends with a \0 memset (logBuffer, 0, infoLogLength + 1); // get information about the error glGetProgramInfoLog (this->m_shader, infoLogLength, nullptr, logBuffer); // throw an exception about the issue - std::string message = logBuffer; + const std::string message = logBuffer; // free the buffer - delete[] logBuffer; + delete [] logBuffer; // throw an exception sLog.exception (message); } @@ -202,33 +180,26 @@ void CWallpaper::setupShaders () this->a_TexCoord = glGetAttribLocation (this->m_shader, "a_TexCoord"); } -void CWallpaper::setDestinationFramebuffer (GLuint framebuffer) -{ +void CWallpaper::setDestinationFramebuffer (GLuint framebuffer) { this->m_destFramebuffer = framebuffer; } -void CWallpaper::updateUVs(const glm::ivec4& viewport, const bool vflip){ - //update UVs if something has changed, otherwise use old values - if(this->m_state.hasChanged(viewport, vflip, this->getWidth(), this->getHeight())){ +void CWallpaper::updateUVs (const glm::ivec4& viewport, const bool vflip) { + // update UVs if something has changed, otherwise use old values + if (this->m_state.hasChanged (viewport, vflip, this->getWidth (), this->getHeight ())) { // Update wallpaper state - this->m_state.updateState(viewport, vflip, this->getWidth(), this->getHeight()); + this->m_state.updateState (viewport, vflip, this->getWidth (), this->getHeight ()); } } -void CWallpaper::render (glm::ivec4 viewport, bool vflip) -{ +void CWallpaper::render (glm::ivec4 viewport, bool vflip) { this->renderFrame (viewport); - //Update UVs coordinates according to scaling mode of this wallpaper - updateUVs(viewport,vflip); - auto [ ustart, uend, vstart, vend ] = this->m_state.getTextureUVs(); + // Update UVs coordinates according to scaling mode of this wallpaper + updateUVs (viewport, vflip); + auto [ustart, uend, vstart, vend] = this->m_state.getTextureUVs (); - GLfloat texCoords [] = { - ustart, vstart, - uend, vstart, - ustart, vend, - ustart, vend, - uend, vstart, - uend, vend, + const GLfloat texCoords [] = { + ustart, vstart, uend, vstart, ustart, vend, ustart, vend, uend, vstart, uend, vend, }; glViewport (viewport.x, viewport.y, viewport.z, viewport.w); @@ -260,30 +231,23 @@ void CWallpaper::render (glm::ivec4 viewport, bool vflip) glDrawArrays (GL_TRIANGLES, 0, 6); } -void CWallpaper::setupFramebuffers () -{ - uint32_t width = this->getWidth (); - uint32_t height = this->getHeight (); - ITexture::TextureFlags clamp = this->getContext().getApp().getContext().settings.render.window.clamp; - +void CWallpaper::setupFramebuffers () { + const uint32_t width = this->getWidth (); + const uint32_t height = this->getHeight (); + const ITexture::TextureFlags clamp = this->getContext ().getApp ().getContext ().settings.render.window.clamp; + // create framebuffer for the scene - this->m_sceneFBO = this->createFBO ( - "_rt_FullFrameBuffer", - ITexture::TextureFormat::ARGB8888, - clamp, - 1.0, - width, height, - width, height - ); + this->m_sceneFBO = this->createFBO ("_rt_FullFrameBuffer", ITexture::TextureFormat::ARGB8888, clamp, 1.0, width, + height, width, height); } -CAudioContext& CWallpaper::getAudioContext () -{ +CAudioContext& CWallpaper::getAudioContext () { return this->m_audioContext; } -CFBO* CWallpaper::createFBO (const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight) -{ +CFBO* CWallpaper::createFBO (const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, + float scale, uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, + uint32_t textureHeight) { CFBO* fbo = new CFBO (name, format, flags, scale, realWidth, realHeight, textureWidth, textureHeight); this->m_fbos.insert (std::make_pair (name, fbo)); @@ -291,15 +255,12 @@ CFBO* CWallpaper::createFBO (const std::string& name, ITexture::TextureFormat fo return fbo; } -const std::map& CWallpaper::getFBOs () const -{ +const std::map& CWallpaper::getFBOs () const { return this->m_fbos; } - -CFBO* CWallpaper::findFBO (const std::string& name) const -{ - auto it = this->m_fbos.find (name); +CFBO* CWallpaper::findFBO (const std::string& name) const { + const auto it = this->m_fbos.find (name); if (it == this->m_fbos.end ()) sLog.exception ("Cannot find FBO ", name); @@ -307,17 +268,17 @@ CFBO* CWallpaper::findFBO (const std::string& name) const return it->second; } -CFBO* CWallpaper::getFBO () const -{ +CFBO* CWallpaper::getFBO () const { return this->m_sceneFBO; } -CWallpaper* CWallpaper::fromWallpaper (Core::CWallpaper* wallpaper, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode) -{ - if (wallpaper->is ()) - return new WallpaperEngine::Render::CScene (wallpaper->as (), context, audioContext, scalingMode); - else if (wallpaper->is ()) - return new WallpaperEngine::Render::CVideo (wallpaper->as (), context, audioContext, scalingMode); - else - sLog.exception ("Unsupported wallpaper type"); +CWallpaper* CWallpaper::fromWallpaper (Core::CWallpaper* wallpaper, CRenderContext& context, + CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode) { + if (wallpaper->is ()) + return new WallpaperEngine::Render::CScene (wallpaper->as (), context, audioContext, scalingMode); + if (wallpaper->is ()) + return new WallpaperEngine::Render::CVideo (wallpaper->as (), context, audioContext, scalingMode); + + sLog.exception ("Unsupported wallpaper type"); } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CWallpaper.h b/src/WallpaperEngine/Render/CWallpaper.h index 1da4eb9..07656fc 100644 --- a/src/WallpaperEngine/Render/CWallpaper.h +++ b/src/WallpaperEngine/Render/CWallpaper.h @@ -6,12 +6,12 @@ #include "WallpaperEngine/Assets/CContainer.h" #include "WallpaperEngine/Audio/CAudioContext.h" -#include "WallpaperEngine/Core/CWallpaper.h" #include "WallpaperEngine/Core/CScene.h" #include "WallpaperEngine/Core/CVideo.h" +#include "WallpaperEngine/Core/CWallpaper.h" -#include "WallpaperEngine/Render/CRenderContext.h" #include "WallpaperEngine/Render/CFBO.h" +#include "WallpaperEngine/Render/CRenderContext.h" #include "WallpaperEngine/Render/Helpers/CContextAware.h" #include "CWallpaperState.h" @@ -19,143 +19,162 @@ using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Audio; -namespace WallpaperEngine::Render -{ - namespace Helpers - { - class CContextAware; +namespace WallpaperEngine::Render { +namespace Helpers { +class CContextAware; +} + +class CWallpaper : public Helpers::CContextAware { + public: + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); } - class CWallpaper : public Helpers::CContextAware - { - public: - template const T* as () const { assert (is ()); return (const T*) this; } - template T* as () { assert (is ()); return (T*) this; } + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } - template bool is () { return this->m_type == T::Type; } + template bool is () { + return this->m_type == T::Type; + } - ~CWallpaper (); + ~CWallpaper () override; - /** - * Performs a render pass of the wallpaper - */ - void render (glm::ivec4 viewport, bool vflip); + /** + * Performs a render pass of the wallpaper + */ + void render (glm::ivec4 viewport, bool vflip); - /** - * @return The container to resolve files for this wallpaper - */ - [[nodiscard]] CContainer* getContainer () const; + /** + * @return The container to resolve files for this wallpaper + */ + [[nodiscard]] CContainer* getContainer () const; - /** - * @return The current audio context for this wallpaper - */ - CAudioContext& getAudioContext (); + /** + * @return The current audio context for this wallpaper + */ + CAudioContext& getAudioContext (); - /** - * @return The scene's framebuffer - */ - [[nodiscard]] virtual GLuint getWallpaperFramebuffer () const; - /** - * @return The scene's texture - */ - [[nodiscard]] virtual GLuint getWallpaperTexture () const; - /** - * Creates a new FBO for this wallpaper - * - * @param name The name of the FBO - * @return - */ - CFBO* createFBO (const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight); + /** + * @return The scene's framebuffer + */ + [[nodiscard]] virtual GLuint getWallpaperFramebuffer () const; + /** + * @return The scene's texture + */ + [[nodiscard]] virtual GLuint getWallpaperTexture () const; + /** + * Creates a new FBO for this wallpaper + * + * @param name The name of the FBO + * @param format + * @param flags + * @param scale + * @param realWidth + * @param realHeight + * @param textureWidth + * @param textureHeight + * @return + */ + CFBO* createFBO (const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, + uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight); - /** - * @return The full FBO list to work with - */ - [[nodiscard]] const std::map& getFBOs () const; - /** - * Searches the FBO list for the given FBO - * - * @param name - * @return - */ - [[nodiscard]] CFBO* findFBO (const std::string& name) const; + /** + * @return The full FBO list to work with + */ + [[nodiscard]] const std::map& getFBOs () const; + /** + * Searches the FBO list for the given FBO + * + * @param name + * @return + */ + [[nodiscard]] CFBO* findFBO (const std::string& name) const; - /** - * @return The main FBO of this wallpaper - */ - [[nodiscard]] CFBO* getFBO () const; + /** + * @return The main FBO of this wallpaper + */ + [[nodiscard]] CFBO* getFBO () const; - /** - * Updates the UVs coordinates if window/screen/vflip/projection has changed - */ - void updateUVs (const glm::ivec4& viewport, const bool vflip); + /** + * Updates the UVs coordinates if window/screen/vflip/projection has changed + */ + void updateUVs (const glm::ivec4& viewport, const bool vflip); - /** - * Updates the destination framebuffer for this wallpaper - * - * @param framebuffer - */ - void setDestinationFramebuffer (GLuint framebuffer); + /** + * Updates the destination framebuffer for this wallpaper + * + * @param framebuffer + */ + void setDestinationFramebuffer (GLuint framebuffer); - /** - * @return The width of this wallpaper - */ - [[nodiscard]] virtual uint32_t getWidth () const = 0; + /** + * @return The width of this wallpaper + */ + [[nodiscard]] virtual uint32_t getWidth () const = 0; - /** - * @return The height of this wallpaper - */ - [[nodiscard]] virtual uint32_t getHeight () const = 0; + /** + * @return The height of this wallpaper + */ + [[nodiscard]] virtual uint32_t getHeight () const = 0; - /** - * Creates a new instance of CWallpaper based on the information provided by the read backgrounds - * - * @param wallpaper - * - * @return - */ - static CWallpaper* fromWallpaper (Core::CWallpaper* wallpaper, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode); + /** + * Creates a new instance of CWallpaper based on the information provided by the read backgrounds + * + * @param wallpaper + * @param context + * @param audioContext + * @param scalingMode + * + * @return + */ + static CWallpaper* fromWallpaper (Core::CWallpaper* wallpaper, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode); - protected: - CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRenderContext& context, CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode); + protected: + CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode); - /** - * Renders a frame of the wallpaper - */ - virtual void renderFrame (glm::ivec4 viewport) = 0; + /** + * Renders a frame of the wallpaper + */ + virtual void renderFrame (glm::ivec4 viewport) = 0; - /** - * Setups OpenGL's framebuffers for ping-pong and scene rendering - */ - void setupFramebuffers (); + /** + * Setups OpenGL's framebuffers for ping-pong and scene rendering + */ + void setupFramebuffers (); - Core::CWallpaper* m_wallpaperData; + Core::CWallpaper* m_wallpaperData; - [[nodiscard]] Core::CWallpaper* getWallpaperData () const; + [[nodiscard]] Core::CWallpaper* getWallpaperData () const; - /** The FBO used for scene output */ - CFBO* m_sceneFBO; + /** The FBO used for scene output */ + CFBO* m_sceneFBO; - private: - /** The texture used for the scene output */ - GLuint m_texCoordBuffer; - GLuint m_positionBuffer; - GLuint m_shader; - // shader variables - GLint g_Texture0; - GLint a_Position; - GLint a_TexCoord; - GLuint m_vaoBuffer; - /** The framebuffer to draw the background to */ - GLuint m_destFramebuffer; - /** Setups OpenGL's shaders for this wallpaper backbuffer */ - void setupShaders (); - /** The type of background this wallpaper is */ - std::string m_type; - /** List of FBOs registered for this wallpaper */ - std::map m_fbos; - /** Audio context that is using this wallpaper */ - CAudioContext& m_audioContext; - /** Current Wallpaper state */ - CWallpaperState m_state; - }; -} + private: + /** The texture used for the scene output */ + GLuint m_texCoordBuffer; + GLuint m_positionBuffer; + GLuint m_shader; + // shader variables + GLint g_Texture0; + GLint a_Position; + GLint a_TexCoord; + GLuint m_vaoBuffer; + /** The framebuffer to draw the background to */ + GLuint m_destFramebuffer; + /** Setups OpenGL's shaders for this wallpaper backbuffer */ + void setupShaders (); + /** The type of background this wallpaper is */ + std::string m_type; + /** List of FBOs registered for this wallpaper */ + std::map m_fbos; + /** Audio context that is using this wallpaper */ + CAudioContext& m_audioContext; + /** Current Wallpaper state */ + CWallpaperState m_state; +}; +} // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CWallpaperState.cpp b/src/WallpaperEngine/Render/CWallpaperState.cpp index f971fe8..7bf99cb 100644 --- a/src/WallpaperEngine/Render/CWallpaperState.cpp +++ b/src/WallpaperEngine/Render/CWallpaperState.cpp @@ -1,169 +1,153 @@ #include "CWallpaperState.h" -#include #include "WallpaperEngine/Logging/CLog.h" +#include using namespace WallpaperEngine::Render; // Reset UVs to 0/1 values -void CWallpaperState::resetUVs(){ - this->UVs.ustart=0; - this->UVs.uend=1; - if (vflip){ +void CWallpaperState::resetUVs () { + this->UVs.ustart = 0; + this->UVs.uend = 1; + if (vflip) { this->UVs.vstart = 0.0f; this->UVs.vend = 1.0f; - } - else{ - this->UVs.vstart=1.0f; - this->UVs.vend=0.0f; + } else { + this->UVs.vstart = 1.0f; + this->UVs.vend = 0.0f; } } // Update Us coordinates for current viewport and projection -void CWallpaperState::updateUs(const int& projectionWidth, const int& projectionHeight){ - const float viewportWidth = this->getViewportWidth(); - const float viewportHeight = this->getViewportHeight(); - int newWidth = viewportHeight / projectionHeight * projectionWidth; - float newCenter = newWidth / 2.0f; - float viewportCenter = viewportWidth / 2.0; +void CWallpaperState::updateUs (const int& projectionWidth, const int& projectionHeight) { + const float viewportWidth = this->getViewportWidth (); + const float viewportHeight = this->getViewportHeight (); + const int newWidth = viewportHeight / projectionHeight * projectionWidth; + const float newCenter = newWidth / 2.0f; + const float viewportCenter = viewportWidth / 2.0; - float left = newCenter - viewportCenter; - float right = newCenter + viewportCenter; + const float left = newCenter - viewportCenter; + const float right = newCenter + viewportCenter; this->UVs.ustart = left / newWidth; - this->UVs.uend = right / newWidth; + this->UVs.uend = right / newWidth; } -// Update Vs coordinates for current viewport and projection -void CWallpaperState::updateVs(const int& projectionWidth, const int& projectionHeight){ - const float viewportWidth = this->getViewportWidth(); - const float viewportHeight = this->getViewportHeight(); - int newHeight = viewportWidth / projectionWidth * projectionHeight; - float newCenter = newHeight / 2.0f; - float viewportCenter = viewportHeight / 2.0; +// Update Vs coordinates for current viewport and projection +void CWallpaperState::updateVs (const int& projectionWidth, const int& projectionHeight) { + const float viewportWidth = this->getViewportWidth (); + const float viewportHeight = this->getViewportHeight (); + const int newHeight = viewportWidth / projectionWidth * projectionHeight; + const float newCenter = newHeight / 2.0f; + const float viewportCenter = viewportHeight / 2.0; - float down = newCenter - viewportCenter; - float up = newCenter + viewportCenter; + const float down = newCenter - viewportCenter; + const float up = newCenter + viewportCenter; - if (vflip) - { + if (vflip) { this->UVs.vstart = down / newHeight; this->UVs.vend = up / newHeight; - } - else - { + } else { this->UVs.vstart = up / newHeight; this->UVs.vend = down / newHeight; } } - -template<> void CWallpaperState::updateTextureUVs(){ - this->resetUVs(); +template <> void CWallpaperState::updateTextureUVs () { + this->resetUVs (); } -template<> void CWallpaperState::updateTextureUVs(){ - this->resetUVs(); +template <> void CWallpaperState::updateTextureUVs () { + this->resetUVs (); - const int viewportWidth = this->getViewportWidth(); - const int viewportHeight = this->getViewportHeight(); - uint32_t projectionWidth = this->getProjectionWidth(); - uint32_t projectionHeight = this->getProjectionHeight(); + const int viewportWidth = this->getViewportWidth (); + const int viewportHeight = this->getViewportHeight (); + uint32_t projectionWidth = this->getProjectionWidth (); + uint32_t projectionHeight = this->getProjectionHeight (); - const float m1 = static_cast(viewportWidth) / projectionWidth; - const float m2 = static_cast(viewportHeight) / projectionHeight; - const float m = std::max(m1,m2); - projectionWidth*=m; - projectionHeight*=m; + const float m1 = static_cast (viewportWidth) / projectionWidth; + const float m2 = static_cast (viewportHeight) / projectionHeight; + const float m = std::max (m1, m2); + projectionWidth *= m; + projectionHeight *= m; - if (projectionWidth!=viewportWidth) - { - this->updateUs(projectionWidth,projectionHeight); - } - else if (projectionHeight!=viewportHeight) - { - this->updateVs(projectionWidth,projectionHeight); + if (projectionWidth != viewportWidth) { + this->updateUs (projectionWidth, projectionHeight); + } else if (projectionHeight != viewportHeight) { + this->updateVs (projectionWidth, projectionHeight); } } -template<> void CWallpaperState::updateTextureUVs(){ - this->resetUVs(); - - const int viewportWidth = this->getViewportWidth(); - const int viewportHeight = this->getViewportHeight(); - uint32_t projectionWidth = this->getProjectionWidth(); - uint32_t projectionHeight = this->getProjectionHeight(); +template <> void CWallpaperState::updateTextureUVs () { + this->resetUVs (); - const float m1 = static_cast(viewportWidth) / projectionWidth; - const float m2 = static_cast(viewportHeight) / projectionHeight; - const float m = std::min(m1,m2); - projectionWidth*=m; - projectionHeight*=m; + const int viewportWidth = this->getViewportWidth (); + const int viewportHeight = this->getViewportHeight (); + uint32_t projectionWidth = this->getProjectionWidth (); + uint32_t projectionHeight = this->getProjectionHeight (); - if (projectionWidth!=viewportWidth) - { - this->updateUs(projectionWidth,projectionHeight); - } - else if (projectionHeight!=viewportHeight) - { - this->updateVs(projectionWidth,projectionHeight); + const float m1 = static_cast (viewportWidth) / projectionWidth; + const float m2 = static_cast (viewportHeight) / projectionHeight; + const float m = std::min (m1, m2); + projectionWidth *= m; + projectionHeight *= m; + + if (projectionWidth != viewportWidth) { + this->updateUs (projectionWidth, projectionHeight); + } else if (projectionHeight != viewportHeight) { + this->updateVs (projectionWidth, projectionHeight); } } -template<> void CWallpaperState::updateTextureUVs(){ - this->resetUVs(); +template <> void CWallpaperState::updateTextureUVs () { + this->resetUVs (); - const int viewportWidth = this->getViewportWidth(); - const int viewportHeight = this->getViewportHeight(); - uint32_t projectionWidth = this->getProjectionWidth(); - uint32_t projectionHeight = this->getProjectionHeight(); + const int viewportWidth = this->getViewportWidth (); + const int viewportHeight = this->getViewportHeight (); + const uint32_t projectionWidth = this->getProjectionWidth (); + const uint32_t projectionHeight = this->getProjectionHeight (); - if ( - (viewportHeight > viewportWidth && projectionWidth >= projectionHeight) || - (viewportWidth > viewportHeight && projectionHeight > projectionWidth) - ) - { - updateUs(projectionWidth,projectionHeight); + if ((viewportHeight > viewportWidth && projectionWidth >= projectionHeight) || + (viewportWidth > viewportHeight && projectionHeight > projectionWidth)) { + updateUs (projectionWidth, projectionHeight); } - if ( - (viewportWidth > viewportHeight && projectionWidth >= projectionHeight) || - (viewportHeight > viewportWidth && projectionHeight > projectionWidth) - ) - { - updateVs(projectionWidth,projectionHeight); + if ((viewportWidth > viewportHeight && projectionWidth >= projectionHeight) || + (viewportHeight > viewportWidth && projectionHeight > projectionWidth)) { + updateVs (projectionWidth, projectionHeight); } } -template void CWallpaperState::updateTextureUVs(){ - sLog.exception("Using generic template for scaling is not allowed. Write specialization template for your scaling mode.\ +template void CWallpaperState::updateTextureUVs () { + sLog.exception ( + "Using generic template for scaling is not allowed. Write specialization template for your scaling mode.\ This message is for developers, if you are just user it's a bug."); } - -void CWallpaperState::updateState(const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, const int& projectionHeight){ +void CWallpaperState::updateState (const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, + const int& projectionHeight) { this->viewport.width = viewport.z; this->viewport.height = viewport.w; this->vflip = vflip; this->projection.width = projectionWidth; this->projection.height = projectionHeight; - //Set texture UVs according to choosen scaling mode for this wallpaper - switch (this->getTextureUVsScaling()) - { - case CWallpaperState::TextureUVsScaling::StretchUVs : - this->updateTextureUVs(); + // Set texture UVs according to choosen scaling mode for this wallpaper + switch (this->getTextureUVsScaling ()) { + case CWallpaperState::TextureUVsScaling::StretchUVs: + this->updateTextureUVs (); break; - case CWallpaperState::TextureUVsScaling::ZoomFillUVs : - this->updateTextureUVs(); + case CWallpaperState::TextureUVsScaling::ZoomFillUVs: + this->updateTextureUVs (); break; - case CWallpaperState::TextureUVsScaling::ZoomFitUVs : - this->updateTextureUVs(); + case CWallpaperState::TextureUVsScaling::ZoomFitUVs: + this->updateTextureUVs (); break; - case CWallpaperState::TextureUVsScaling::DefaultUVs : - this->updateTextureUVs(); + case CWallpaperState::TextureUVsScaling::DefaultUVs: + this->updateTextureUVs (); break; default: - sLog.exception("Switch case for specified scaling mode doesn't exist. Add your realisation in switch statement.\ + sLog.exception ( + "Switch case for specified scaling mode doesn't exist. Add your realisation in switch statement.\ This message is for developers, if you are just user it's a bug."); break; } diff --git a/src/WallpaperEngine/Render/CWallpaperState.h b/src/WallpaperEngine/Render/CWallpaperState.h index 6c9103f..1a00bb1 100644 --- a/src/WallpaperEngine/Render/CWallpaperState.h +++ b/src/WallpaperEngine/Render/CWallpaperState.h @@ -4,96 +4,106 @@ #include #include -namespace WallpaperEngine::Render -{ - /** - * Represents current wallpaper state - */ - class CWallpaperState - { - public: - // Scaling modes. Defines how UVs coordinates are calculated. - enum class TextureUVsScaling : uint8_t - { - DefaultUVs, - ZoomFitUVs, - ZoomFillUVs, - StretchUVs, - }; - - CWallpaperState(const TextureUVsScaling& textureUVsMode) : m_textureUVsMode(textureUVsMode) - {}; - - // Compares saved state values with passed arguments - bool hasChanged(const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, const int& projectionHeight) const{ - return this->viewport.width != viewport.z || this->viewport.height != viewport.w || - this->projection.width != projectionWidth || this->projection.height != projectionHeight || this->vflip != vflip; - } - - // Reset UVs to 0/1 values - void resetUVs(); - - // Update Us coordinates for current viewport and projection - void updateUs(const int& projectionWidth, const int& projectionHeight); - - // Update Vs coordinates for current viewport and projection - void updateVs(const int& projectionWidth, const int& projectionHeight); - - // Get texture UV coordinates - auto getTextureUVs() const {return UVs;}; - - // Set texture UV coordinates according to texture scaling mode - template void updateTextureUVs(); - - // Updates state with provided values - void updateState(const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, const int& projectionHeight); - - // @return The texture scaling mode - TextureUVsScaling getTextureUVsScaling () const { return m_textureUVsMode; }; - - // Set texture scaling mode - void setTextureUVsStrategy(const TextureUVsScaling strategy) { m_textureUVsMode=strategy; } ; - - // @return The width of viewport - int getViewportWidth () const { return viewport.width;}; - - // @return The height of viewport - int getViewportHeight () const { return viewport.height;}; - - // @return The width of viewport - uint32_t getProjectionWidth () const { return projection.width;}; - - // @return The height of viewport - uint32_t getProjectionHeight () const { return projection.height;}; - - private: - // Cached UVs value for texture coordinates. No need to recalculate if viewport and projection haven't changed. - struct - { - float ustart; - float uend; - float vstart; - float vend; - } UVs; - - // Viewport for which UVs were calculated - struct - { - int width; - int height; - } viewport{}; - - // Wallpaper dimensions - struct - { - uint32_t width; - uint32_t height; - } projection{}; - - // Are Vs coordinates fliped - bool vflip = false; - - // Texture scaling mode - TextureUVsScaling m_textureUVsMode = TextureUVsScaling::DefaultUVs; +namespace WallpaperEngine::Render { +/** + * Represents current wallpaper state + */ +class CWallpaperState { + public: + // Scaling modes. Defines how UVs coordinates are calculated. + enum class TextureUVsScaling : uint8_t { + DefaultUVs, + ZoomFitUVs, + ZoomFillUVs, + StretchUVs, }; -} \ No newline at end of file + + CWallpaperState (const TextureUVsScaling& textureUVsMode) : m_textureUVsMode (textureUVsMode) {}; + + // Compares saved state values with passed arguments + bool hasChanged (const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, + const int& projectionHeight) const { + return this->viewport.width != viewport.z || this->viewport.height != viewport.w || + this->projection.width != projectionWidth || this->projection.height != projectionHeight || + this->vflip != vflip; + } + + // Reset UVs to 0/1 values + void resetUVs (); + + // Update Us coordinates for current viewport and projection + void updateUs (const int& projectionWidth, const int& projectionHeight); + + // Update Vs coordinates for current viewport and projection + void updateVs (const int& projectionWidth, const int& projectionHeight); + + // Get texture UV coordinates + auto getTextureUVs () const { + return UVs; + }; + + // Set texture UV coordinates according to texture scaling mode + template void updateTextureUVs (); + + // Updates state with provided values + void updateState (const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, + const int& projectionHeight); + + // @return The texture scaling mode + TextureUVsScaling getTextureUVsScaling () const { + return m_textureUVsMode; + }; + + // Set texture scaling mode + void setTextureUVsStrategy (const TextureUVsScaling strategy) { + m_textureUVsMode = strategy; + }; + + // @return The width of viewport + int getViewportWidth () const { + return viewport.width; + }; + + // @return The height of viewport + int getViewportHeight () const { + return viewport.height; + }; + + // @return The width of viewport + uint32_t getProjectionWidth () const { + return projection.width; + }; + + // @return The height of viewport + uint32_t getProjectionHeight () const { + return projection.height; + }; + + private: + // Cached UVs value for texture coordinates. No need to recalculate if viewport and projection haven't changed. + struct { + float ustart; + float uend; + float vstart; + float vend; + } UVs; + + // Viewport for which UVs were calculated + struct { + int width; + int height; + } viewport {}; + + // Wallpaper dimensions + struct { + uint32_t width; + uint32_t height; + } projection {}; + + // Are Vs coordinates fliped + bool vflip = false; + + // Texture scaling mode + TextureUVsScaling m_textureUVsMode = TextureUVsScaling::DefaultUVs; +}; +} // namespace WallpaperEngine::Render \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp b/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp index cfb3b77..fb8c98a 100644 --- a/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp +++ b/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp @@ -2,16 +2,10 @@ using namespace WallpaperEngine::Render::Drivers; -CVideoDriver::CVideoDriver (CWallpaperApplication& app) : - m_app (app) -{ -} +CVideoDriver::CVideoDriver (CWallpaperApplication& app) : m_app (app) {} -CVideoDriver::~CVideoDriver () -{ -} +CVideoDriver::~CVideoDriver () {} -CWallpaperApplication& CVideoDriver::getApp () const -{ +CWallpaperApplication& CVideoDriver::getApp () const { return this->m_app; } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CVideoDriver.h b/src/WallpaperEngine/Render/Drivers/CVideoDriver.h index f42eb02..8ff388d 100644 --- a/src/WallpaperEngine/Render/Drivers/CVideoDriver.h +++ b/src/WallpaperEngine/Render/Drivers/CVideoDriver.h @@ -1,84 +1,80 @@ #pragma once -#include -#include -#include #include "WallpaperEngine/Render/Drivers/Output/COutput.h" +#include +#include +#include -namespace WallpaperEngine::Application -{ - class CWallpaperApplication; +namespace WallpaperEngine::Application { +class CWallpaperApplication; } -namespace WallpaperEngine::Render::Drivers -{ - namespace Detectors - { - class CFullScreenDetector; - } +namespace WallpaperEngine::Render::Drivers { +namespace Detectors { +class CFullScreenDetector; +} - class CVideoDriver - { - public: - CVideoDriver (CWallpaperApplication& app); - virtual ~CVideoDriver (); +class CVideoDriver { + public: + explicit CVideoDriver (CWallpaperApplication& app); + virtual ~CVideoDriver (); - /** - * @return The fullscreen detector this video driver uses - */ - [[nodiscard]] virtual Detectors::CFullScreenDetector& getFullscreenDetector () = 0; - /** - * @return The current output in use - */ - [[nodiscard]] virtual Output::COutput& getOutput () = 0; - /** - * @return The time that has passed since the driver started - */ - [[nodiscard]] virtual float getRenderTime () const = 0; - /** - * @return If a close was requested by the OS - */ - virtual bool closeRequested () = 0; - /** - * @param size The new size for the window - */ - virtual void resizeWindow (glm::ivec2 size) = 0; - /** - * @param size The new size and position of the window - */ - virtual void resizeWindow (glm::ivec4 positionAndSize) = 0; - /** - * Shows the window created by the driver - */ - virtual void showWindow () = 0; - /** - * Hides the window created by the driver - */ - virtual void hideWindow () = 0; - /** - * @return The size of the framebuffer available for the driver - */ - [[nodiscard]] virtual glm::ivec2 getFramebufferSize () const = 0; - /** - * @return The number of rendered frames since the start of the driver - */ - [[nodiscard]] virtual uint32_t getFrameCounter () const = 0; - /** - * @param name - * @return GetProcAddress for this video driver - */ - [[nodiscard]] virtual void* getProcAddress (const char* name) const = 0; - /** - * Process events on the driver and renders a frame - */ - virtual void dispatchEventQueue() = 0; - /** - * @return The app that owns this driver - */ - [[nodiscard]] CWallpaperApplication& getApp () const; + /** + * @return The fullscreen detector this video driver uses + */ + [[nodiscard]] virtual Detectors::CFullScreenDetector& getFullscreenDetector () = 0; + /** + * @return The current output in use + */ + [[nodiscard]] virtual Output::COutput& getOutput () = 0; + /** + * @return The time that has passed since the driver started + */ + [[nodiscard]] virtual float getRenderTime () const = 0; + /** + * @return If a close was requested by the OS + */ + virtual bool closeRequested () = 0; + /** + * @param size The new size for the window + */ + virtual void resizeWindow (glm::ivec2 size) = 0; + /** + * @param positionAndSize The new size and position of the window + */ + virtual void resizeWindow (glm::ivec4 positionAndSize) = 0; + /** + * Shows the window created by the driver + */ + virtual void showWindow () = 0; + /** + * Hides the window created by the driver + */ + virtual void hideWindow () = 0; + /** + * @return The size of the framebuffer available for the driver + */ + [[nodiscard]] virtual glm::ivec2 getFramebufferSize () const = 0; + /** + * @return The number of rendered frames since the start of the driver + */ + [[nodiscard]] virtual uint32_t getFrameCounter () const = 0; + /** + * @param name + * @return GetProcAddress for this video driver + */ + [[nodiscard]] virtual void* getProcAddress (const char* name) const = 0; + /** + * Process events on the driver and renders a frame + */ + virtual void dispatchEventQueue () = 0; + /** + * @return The app that owns this driver + */ + [[nodiscard]] CWallpaperApplication& getApp () const; - private: - /** App that owns this driver */ - CWallpaperApplication& m_app; - }; -} \ No newline at end of file + private: + /** App that owns this driver */ + CWallpaperApplication& m_app; +}; +} // namespace WallpaperEngine::Render::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp index e72aa9f..9e800d0 100644 --- a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp +++ b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp @@ -9,8 +9,8 @@ #define namespace _namespace #define static extern "C" { -#include "xdg-shell-protocol.h" #include "wlr-layer-shell-unstable-v1-protocol.h" +#include "xdg-shell-protocol.h" } #undef class #undef namespace @@ -21,34 +21,29 @@ extern "C" { using namespace WallpaperEngine::Render::Drivers; -static void handlePointerEnter ( - void* data, struct wl_pointer* wl_pointer, uint32_t serial, struct wl_surface* surface, - wl_fixed_t surface_x, wl_fixed_t surface_y) -{ - const auto driver = static_cast (data); +static void handlePointerEnter (void* data, struct wl_pointer* wl_pointer, uint32_t serial, struct wl_surface* surface, + wl_fixed_t surface_x, wl_fixed_t surface_y) { + const auto driver = static_cast (data); const auto viewport = driver->surfaceToViewport (surface); driver->viewportInFocus = viewport; - wl_surface_set_buffer_scale(viewport->cursorSurface, viewport->scale); - wl_surface_attach(viewport->cursorSurface, wl_cursor_image_get_buffer(viewport->pointer->images[0]), 0, 0); - wl_pointer_set_cursor(wl_pointer, serial, viewport->cursorSurface, viewport->pointer->images[0]->hotspot_x, viewport->pointer->images[0]->hotspot_y); - wl_surface_commit(viewport->cursorSurface); + wl_surface_set_buffer_scale (viewport->cursorSurface, viewport->scale); + wl_surface_attach (viewport->cursorSurface, wl_cursor_image_get_buffer (viewport->pointer->images [0]), 0, 0); + wl_pointer_set_cursor (wl_pointer, serial, viewport->cursorSurface, viewport->pointer->images [0]->hotspot_x, + viewport->pointer->images [0]->hotspot_y); + wl_surface_commit (viewport->cursorSurface); } -static void handlePointerLeave(void* data, struct wl_pointer* wl_pointer, uint32_t serial, struct wl_surface* surface) -{ -} +static void handlePointerLeave (void* data, struct wl_pointer* wl_pointer, uint32_t serial, + struct wl_surface* surface) {} -static void handlePointerAxis(void* data, wl_pointer* wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) -{ -} +static void handlePointerAxis (void* data, wl_pointer* wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {} -static void handlePointerMotion( - void* data, struct wl_pointer* wl_pointer, uint32_t time, wl_fixed_t surface_x, wl_fixed_t surface_y) -{ - const auto driver = static_cast (data); +static void handlePointerMotion (void* data, struct wl_pointer* wl_pointer, uint32_t time, wl_fixed_t surface_x, + wl_fixed_t surface_y) { + const auto driver = static_cast (data); - auto x = wl_fixed_to_double(surface_x); - auto y = wl_fixed_to_double(surface_y); + const auto x = wl_fixed_to_double (surface_x); + const auto y = wl_fixed_to_double (surface_y); if (!driver->viewportInFocus) return; @@ -56,170 +51,156 @@ static void handlePointerMotion( driver->viewportInFocus->mousePos = {x * driver->viewportInFocus->scale, y * driver->viewportInFocus->scale}; } -static void handlePointerButton( - void* data, struct wl_pointer* wl_pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t button_state) -{ -} +static void handlePointerButton (void* data, struct wl_pointer* wl_pointer, uint32_t serial, uint32_t time, + uint32_t button, uint32_t button_state) {} -const struct wl_pointer_listener pointerListener = -{ - .enter = handlePointerEnter, - .leave = handlePointerLeave, - .motion = handlePointerMotion, - .button = handlePointerButton, - .axis = handlePointerAxis -}; +constexpr struct wl_pointer_listener pointerListener = {.enter = handlePointerEnter, + .leave = handlePointerLeave, + .motion = handlePointerMotion, + .button = handlePointerButton, + .axis = handlePointerAxis}; -static void handleCapabilities(void* data, wl_seat* wl_seat, uint32_t capabilities) -{ +static void handleCapabilities (void* data, wl_seat* wl_seat, uint32_t capabilities) { if (capabilities & WL_SEAT_CAPABILITY_POINTER) - wl_pointer_add_listener(wl_seat_get_pointer(wl_seat), &pointerListener, data); + wl_pointer_add_listener (wl_seat_get_pointer (wl_seat), &pointerListener, data); } -const struct wl_seat_listener seatListener = -{ - .capabilities = handleCapabilities -}; +constexpr struct wl_seat_listener seatListener = {.capabilities = handleCapabilities}; -static void handleGlobal(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) -{ - const auto driver = static_cast (data); +static void handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const char* interface, + uint32_t version) { + const auto driver = static_cast (data); - if (strcmp(interface, wl_compositor_interface.name) == 0) { - driver->getWaylandContext()->compositor = (wl_compositor*)wl_registry_bind(registry, name, &wl_compositor_interface, 4); - } else if (strcmp(interface, wl_shm_interface.name) == 0) { - driver->getWaylandContext()->shm = (wl_shm*)wl_registry_bind(registry, name, &wl_shm_interface, 1); - } else if (strcmp(interface, wl_output_interface.name) == 0) { - driver->m_screens.emplace_back (new WallpaperEngine::Render::Drivers::Output::CWaylandOutputViewport (driver, name, registry)); - } else if (strcmp(interface, zwlr_layer_shell_v1_interface.name) == 0) { - driver->getWaylandContext()->layerShell = (zwlr_layer_shell_v1*)wl_registry_bind(registry, name, &zwlr_layer_shell_v1_interface, 1); - } else if (strcmp(interface, wl_seat_interface.name) == 0) { - driver->getWaylandContext()->seat = (wl_seat*)wl_registry_bind(registry, name, &wl_seat_interface, 1); - wl_seat_add_listener(driver->getWaylandContext()->seat, &seatListener, driver); + if (strcmp (interface, wl_compositor_interface.name) == 0) { + driver->getWaylandContext ()->compositor = + static_cast (wl_registry_bind (registry, name, &wl_compositor_interface, 4)); + } else if (strcmp (interface, wl_shm_interface.name) == 0) { + driver->getWaylandContext ()->shm = + static_cast (wl_registry_bind (registry, name, &wl_shm_interface, 1)); + } else if (strcmp (interface, wl_output_interface.name) == 0) { + driver->m_screens.emplace_back ( + new WallpaperEngine::Render::Drivers::Output::CWaylandOutputViewport (driver, name, registry)); + } else if (strcmp (interface, zwlr_layer_shell_v1_interface.name) == 0) { + driver->getWaylandContext ()->layerShell = + static_cast (wl_registry_bind (registry, name, &zwlr_layer_shell_v1_interface, 1)); + } else if (strcmp (interface, wl_seat_interface.name) == 0) { + driver->getWaylandContext ()->seat = + static_cast (wl_registry_bind (registry, name, &wl_seat_interface, 1)); + wl_seat_add_listener (driver->getWaylandContext ()->seat, &seatListener, driver); } } -static void handleGlobalRemoved(void *data, struct wl_registry *registry, uint32_t id) -{ +static void handleGlobalRemoved (void* data, struct wl_registry* registry, uint32_t id) { // todo: outputs } -const struct wl_registry_listener registryListener = -{ +constexpr struct wl_registry_listener registryListener = { .global = handleGlobal, .global_remove = handleGlobalRemoved, }; -void CWaylandOpenGLDriver::initEGL() -{ - const char* CLIENT_EXTENSIONS = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); +void CWaylandOpenGLDriver::initEGL () { + const char* CLIENT_EXTENSIONS = eglQueryString (EGL_NO_DISPLAY, EGL_EXTENSIONS); if (!CLIENT_EXTENSIONS) - sLog.exception("Failed to query EGL Extensions"); + sLog.exception ("Failed to query EGL Extensions"); - const std::string CLIENTEXTENSIONS = std::string(CLIENT_EXTENSIONS); - - if (CLIENTEXTENSIONS.find("EGL_EXT_platform_base") == std::string::npos) - sLog.exception("EGL_EXT_platform_base not supported by EGL!"); + const std::string CLIENTEXTENSIONS = std::string (CLIENT_EXTENSIONS); - if (CLIENTEXTENSIONS.find("EGL_EXT_platform_wayland") == std::string::npos) - sLog.exception("EGL_EXT_platform_wayland not supported by EGL!"); + if (CLIENTEXTENSIONS.find ("EGL_EXT_platform_base") == std::string::npos) + sLog.exception ("EGL_EXT_platform_base not supported by EGL!"); - PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT"); - m_eglContext.eglCreatePlatformWindowSurfaceEXT = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT"); + if (CLIENTEXTENSIONS.find ("EGL_EXT_platform_wayland") == std::string::npos) + sLog.exception ("EGL_EXT_platform_wayland not supported by EGL!"); + + const auto eglGetPlatformDisplayEXT = + reinterpret_cast (eglGetProcAddress ("eglGetPlatformDisplayEXT")); + m_eglContext.eglCreatePlatformWindowSurfaceEXT = reinterpret_cast ( + eglGetProcAddress ("eglCreatePlatformWindowSurfaceEXT")); if (!eglGetPlatformDisplayEXT || !m_eglContext.eglCreatePlatformWindowSurfaceEXT) - sLog.exception("EGL did not return EXT proc pointers!"); + sLog.exception ("EGL did not return EXT proc pointers!"); - auto deinitEGL = [&] () -> void { - eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - if (m_eglContext.display) - eglTerminate(m_eglContext.display); - eglReleaseThread(); - }; + m_eglContext.display = eglGetPlatformDisplayEXT (EGL_PLATFORM_WAYLAND_EXT, m_waylandContext.display, nullptr); - m_eglContext.display = eglGetPlatformDisplayEXT(EGL_PLATFORM_WAYLAND_EXT, m_waylandContext.display, nullptr); - - if (m_eglContext.display == EGL_NO_DISPLAY) - { - deinitEGL (); + if (m_eglContext.display == EGL_NO_DISPLAY) { + this->finishEGL (); sLog.exception ("eglGetPlatformDisplayEXT failed!"); } - if (!eglInitialize(m_eglContext.display, nullptr, nullptr)) - { - deinitEGL (); + if (!eglInitialize (m_eglContext.display, nullptr, nullptr)) { + this->finishEGL (); sLog.exception ("eglInitialize failed!"); } - const std::string CLIENTEXTENSIONSPOSTINIT = std::string(eglQueryString(m_eglContext.display, EGL_EXTENSIONS)); + const std::string CLIENTEXTENSIONSPOSTINIT = std::string (eglQueryString (m_eglContext.display, EGL_EXTENSIONS)); - if (CLIENTEXTENSIONSPOSTINIT.find("EGL_KHR_create_context") == std::string::npos) - { - deinitEGL (); + if (CLIENTEXTENSIONSPOSTINIT.find ("EGL_KHR_create_context") == std::string::npos) { + this->finishEGL (); sLog.exception ("EGL_KHR_create_context not supported!"); } EGLint matchedConfigs = 0; - const EGLint CONFIG_ATTRIBUTES[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RED_SIZE, 1, - EGL_GREEN_SIZE, 1, - EGL_BLUE_SIZE, 1, - EGL_SAMPLES, 4, - EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, - EGL_NONE, + const EGLint CONFIG_ATTRIBUTES [] = { + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 1, EGL_GREEN_SIZE, 1, EGL_BLUE_SIZE, 1, EGL_SAMPLES, 4, + EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE, }; - if (!eglChooseConfig(m_eglContext.display, CONFIG_ATTRIBUTES, &m_eglContext.config, 1, &matchedConfigs)) - { - deinitEGL (); + if (!eglChooseConfig (m_eglContext.display, CONFIG_ATTRIBUTES, &m_eglContext.config, 1, &matchedConfigs)) { + this->finishEGL (); sLog.exception ("eglChooseConfig failed!"); } - if (matchedConfigs == 0) - { - deinitEGL (); + if (matchedConfigs == 0) { + this->finishEGL (); sLog.exception ("eglChooseConfig failed! (matched 0 configs)"); } - if (!eglBindAPI(EGL_OPENGL_API)) - { - deinitEGL (); + if (!eglBindAPI (EGL_OPENGL_API)) { + this->finishEGL (); sLog.exception ("eglBindAPI failed!"); } - const EGLint CONTEXT_ATTRIBUTES[] = { - EGL_CONTEXT_MAJOR_VERSION_KHR, 3, - EGL_CONTEXT_MINOR_VERSION_KHR, 3, - EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR, + const EGLint CONTEXT_ATTRIBUTES [] = { + EGL_CONTEXT_MAJOR_VERSION_KHR, + 3, + EGL_CONTEXT_MINOR_VERSION_KHR, + 3, + EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR, + EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR, EGL_NONE, }; - m_eglContext.context = eglCreateContext(m_eglContext.display, m_eglContext.config, EGL_NO_CONTEXT, CONTEXT_ATTRIBUTES); + m_eglContext.context = + eglCreateContext (m_eglContext.display, m_eglContext.config, EGL_NO_CONTEXT, CONTEXT_ATTRIBUTES); - if (m_eglContext.context == EGL_NO_CONTEXT) - { - deinitEGL (); - sLog.error("eglCreateContext error " + std::to_string(eglGetError())); - sLog.exception("eglCreateContext failed!"); + if (m_eglContext.context == EGL_NO_CONTEXT) { + this->finishEGL (); + sLog.error ("eglCreateContext error " + std::to_string (eglGetError ())); + sLog.exception ("eglCreateContext failed!"); } } -void CWaylandOpenGLDriver::onLayerClose(Output::CWaylandOutputViewport* viewport) -{ +void CWaylandOpenGLDriver::finishEGL () const { + eglMakeCurrent (EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + if (m_eglContext.display) + eglTerminate (m_eglContext.display); + eglReleaseThread (); +} + +void CWaylandOpenGLDriver::onLayerClose (Output::CWaylandOutputViewport* viewport) { sLog.error ("Compositor closed our LS, freeing data..."); if (viewport->eglSurface) eglDestroySurface (m_eglContext.display, viewport->eglSurface); if (viewport->eglWindow) - wl_egl_window_destroy(viewport->eglWindow); + wl_egl_window_destroy (viewport->eglWindow); if (viewport->layerSurface) - zwlr_layer_surface_v1_destroy(viewport->layerSurface); + zwlr_layer_surface_v1_destroy (viewport->layerSurface); if (viewport->surface) - wl_surface_destroy(viewport->surface); + wl_surface_destroy (viewport->surface); // remove the output from the list std::remove (this->m_screens.begin (), this->m_screens.end (), viewport); @@ -231,34 +212,33 @@ void CWaylandOpenGLDriver::onLayerClose(Output::CWaylandOutputViewport* viewport delete viewport; } -CWaylandOpenGLDriver::CWaylandOpenGLDriver(CApplicationContext& context, CWallpaperApplication& app) : - m_frameCounter(0), +CWaylandOpenGLDriver::CWaylandOpenGLDriver (CApplicationContext& context, CWallpaperApplication& app) : + m_frameCounter (0), m_fullscreenDetector (context, *this), m_output (context, *this), m_requestedExit (false), m_context (context), - CVideoDriver (app) -{ + CVideoDriver (app) { m_waylandContext.display = wl_display_connect (nullptr); if (!m_waylandContext.display) sLog.exception ("Failed to query wayland display"); - m_waylandContext.registry = wl_display_get_registry(m_waylandContext.display); - wl_registry_add_listener(m_waylandContext.registry, ®istryListener, this); + m_waylandContext.registry = wl_display_get_registry (m_waylandContext.display); + wl_registry_add_listener (m_waylandContext.registry, ®istryListener, this); - wl_display_dispatch(m_waylandContext.display); - wl_display_roundtrip(m_waylandContext.display); + wl_display_dispatch (m_waylandContext.display); + wl_display_roundtrip (m_waylandContext.display); - if (!m_waylandContext.compositor || !m_waylandContext.shm || !m_waylandContext.layerShell || this->m_screens.empty()) + if (!m_waylandContext.compositor || !m_waylandContext.shm || !m_waylandContext.layerShell || + this->m_screens.empty ()) sLog.exception ("Failed to bind to required interfaces"); - initEGL(); + initEGL (); bool any = false; - for (auto& o : this->m_screens) - { + for (const auto& o : this->m_screens) { const auto cur = context.settings.general.screenBackgrounds.find (o->name); if (cur == context.settings.general.screenBackgrounds.end ()) @@ -269,18 +249,17 @@ CWaylandOpenGLDriver::CWaylandOpenGLDriver(CApplicationContext& context, CWallpa } if (!any) - sLog.exception("No outputs could be initialized, please check the parameters and try again"); + sLog.exception ("No outputs could be initialized, please check the parameters and try again"); - GLenum result = glewInit (); + const GLenum result = glewInit (); if (result != GLEW_OK) - sLog.error("Failed to initialize GLEW: ", glewGetErrorString (result)); + sLog.error ("Failed to initialize GLEW: ", glewGetErrorString (result)); FreeImage_Initialise (TRUE); } -CWaylandOpenGLDriver::~CWaylandOpenGLDriver () -{ +CWaylandOpenGLDriver::~CWaylandOpenGLDriver () { // stop EGL eglMakeCurrent (EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); @@ -295,16 +274,14 @@ CWaylandOpenGLDriver::~CWaylandOpenGLDriver () wl_display_disconnect (this->m_waylandContext.display); } -void CWaylandOpenGLDriver::dispatchEventQueue() -{ +void CWaylandOpenGLDriver::dispatchEventQueue () { static bool initialized = false; - if (!initialized) - { + if (!initialized) { initialized = true; - for (const auto& viewport : this->getOutput ().getViewports ()) - this->getApp ().update (viewport.second); + for (const auto& [screen, viewport] : this->getOutput ().getViewports ()) + this->getApp ().update (viewport); } // TODO: FRAMETIME CONTROL SHOULD GO BACK TO THE CWALLPAPAERAPPLICATION ONCE ACTUAL PARTICLES ARE IMPLEMENTED @@ -316,10 +293,10 @@ void CWaylandOpenGLDriver::dispatchEventQueue() // get the start time of the frame startTime = this->getRenderTime (); - if (wl_display_dispatch(m_waylandContext.display) == -1) + if (wl_display_dispatch (m_waylandContext.display) == -1) m_requestedExit = true; - m_frameCounter ++; + m_frameCounter++; endTime = this->getRenderTime (); @@ -328,71 +305,55 @@ void CWaylandOpenGLDriver::dispatchEventQueue() usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC); } -Detectors::CFullScreenDetector& CWaylandOpenGLDriver::getFullscreenDetector () -{ +Detectors::CFullScreenDetector& CWaylandOpenGLDriver::getFullscreenDetector () { return this->m_fullscreenDetector; } -Output::COutput& CWaylandOpenGLDriver::getOutput () -{ +Output::COutput& CWaylandOpenGLDriver::getOutput () { return this->m_output; } -float CWaylandOpenGLDriver::getRenderTime () const -{ - return (float)std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - renderStart).count() / 1000000.0; +float CWaylandOpenGLDriver::getRenderTime () const { + return static_cast (std::chrono::duration_cast ( + std::chrono::high_resolution_clock::now () - renderStart) + .count ()) / + 1000000.0; } -bool CWaylandOpenGLDriver::closeRequested () -{ +bool CWaylandOpenGLDriver::closeRequested () { return this->m_requestedExit; } -void CWaylandOpenGLDriver::resizeWindow (glm::ivec2 size) -{ +void CWaylandOpenGLDriver::resizeWindow (glm::ivec2 size) {} + +void CWaylandOpenGLDriver::resizeWindow (glm::ivec4 sizeandpos) {} + +void CWaylandOpenGLDriver::showWindow () {} + +void CWaylandOpenGLDriver::hideWindow () {} + +glm::ivec2 CWaylandOpenGLDriver::getFramebufferSize () const { + return glm::ivec2 {0, 0}; } -void CWaylandOpenGLDriver::resizeWindow (glm::ivec4 sizeandpos) -{ -} - -void CWaylandOpenGLDriver::showWindow () -{ -} - -void CWaylandOpenGLDriver::hideWindow () -{ -} - -glm::ivec2 CWaylandOpenGLDriver::getFramebufferSize () const -{ - return glm::ivec2{0, 0}; -} - -uint32_t CWaylandOpenGLDriver::getFrameCounter () const -{ +uint32_t CWaylandOpenGLDriver::getFrameCounter () const { return m_frameCounter; } -CWaylandOpenGLDriver::SEGLContext* CWaylandOpenGLDriver::getEGLContext () -{ +CWaylandOpenGLDriver::SEGLContext* CWaylandOpenGLDriver::getEGLContext () { return &this->m_eglContext; } -void* CWaylandOpenGLDriver::getProcAddress (const char* name) const -{ - return reinterpret_cast (eglGetProcAddress (name)); +void* CWaylandOpenGLDriver::getProcAddress (const char* name) const { + return reinterpret_cast (eglGetProcAddress (name)); } -CWaylandOpenGLDriver::SWaylandContext* CWaylandOpenGLDriver::getWaylandContext () -{ +CWaylandOpenGLDriver::SWaylandContext* CWaylandOpenGLDriver::getWaylandContext () { return &this->m_waylandContext; } -Output::CWaylandOutputViewport* CWaylandOpenGLDriver::surfaceToViewport(wl_surface* surface) -{ - for (auto& o : m_screens) - { +Output::CWaylandOutputViewport* CWaylandOpenGLDriver::surfaceToViewport (const wl_surface* surface) { + for (const auto& o : m_screens) { if (o->surface == surface) return o; } diff --git a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h index f6c71b0..1228d3b 100644 --- a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h +++ b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h @@ -1,115 +1,109 @@ -#ifdef ENABLE_WAYLAND #pragma once -#include -#include -#include +#ifdef ENABLE_WAYLAND + #include #include #include +#include +#include +#include -#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "WallpaperEngine/Application/CApplicationContext.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" +#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h" -#include "WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h" #include "WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h" +#include "WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h" -namespace WallpaperEngine::Application -{ - class CApplicationContext; - class CWallpaperApplication; -} +namespace WallpaperEngine::Application { +class CApplicationContext; +class CWallpaperApplication; +} // namespace WallpaperEngine::Application -namespace WallpaperEngine::Input::Drivers -{ - class CWaylandMouseInput; +namespace WallpaperEngine::Input::Drivers { +class CWaylandMouseInput; } struct zwlr_layer_shell_v1; struct zwlr_layer_surface_v1; -namespace WallpaperEngine::Render::Drivers -{ - using namespace WallpaperEngine::Application; - using namespace WallpaperEngine::Input::Drivers; - class CWaylandOpenGLDriver; +namespace WallpaperEngine::Render::Drivers { +using namespace WallpaperEngine::Application; +using namespace WallpaperEngine::Input::Drivers; +class CWaylandOpenGLDriver; - namespace Output - { - class CWaylandOutputViewport; - class CWaylandOutput; - } +namespace Output { +class CWaylandOutputViewport; +class CWaylandOutput; +} // namespace Output - class CWaylandOpenGLDriver : public CVideoDriver - { - friend class Output::CWaylandOutput; - friend class CWaylandMouseInput; - public: - struct SEGLContext - { - EGLDisplay display = nullptr; - EGLConfig config = nullptr; - EGLContext context = nullptr; - PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC eglCreatePlatformWindowSurfaceEXT = nullptr; - }; +class CWaylandOpenGLDriver final : public CVideoDriver { + friend class Output::CWaylandOutput; + friend class CWaylandMouseInput; - struct SWaylandContext - { - wl_display* display = nullptr; - wl_registry* registry = nullptr; - wl_compositor* compositor = nullptr; - wl_shm* shm = nullptr; - zwlr_layer_shell_v1* layerShell = nullptr; - wl_seat* seat = nullptr; - }; - - explicit CWaylandOpenGLDriver (CApplicationContext& context, CWallpaperApplication& app); - ~CWaylandOpenGLDriver(); - - [[nodiscard]] Detectors::CFullScreenDetector& getFullscreenDetector () override; - [[nodiscard]] Output::COutput& getOutput () override; - float getRenderTime () const override; - bool closeRequested () override; - void resizeWindow (glm::ivec2 size) override; - void resizeWindow (glm::ivec4 sizeandpos) override; - void showWindow () override; - void hideWindow () override; - glm::ivec2 getFramebufferSize () const override; - uint32_t getFrameCounter () const override; - void dispatchEventQueue() override; - [[nodiscard]] void* getProcAddress (const char* name) const override; - - void onLayerClose(Output::CWaylandOutputViewport*); - Output::CWaylandOutputViewport* surfaceToViewport(wl_surface*); - - Output::CWaylandOutputViewport* viewportInFocus = nullptr; - - [[nodiscard]] SEGLContext* getEGLContext (); - [[nodiscard]] SWaylandContext* getWaylandContext (); - - - /** List of available screens */ - std::vector m_screens; - - private: - /** Fullscreen detection used by this driver */ - Detectors::CWaylandFullScreenDetector m_fullscreenDetector; - /** The output used by the driver */ - Output::CWaylandOutput m_output; - /** The EGL context in use */ - SEGLContext m_eglContext; - /** The Wayland context in use */ - SWaylandContext m_waylandContext; - mutable bool m_requestedExit; - - void initEGL(); - void finishEGL(); - - uint32_t m_frameCounter; - CApplicationContext& m_context; - - std::chrono::high_resolution_clock::time_point renderStart = std::chrono::high_resolution_clock::now(); + public: + struct SEGLContext { + EGLDisplay display = nullptr; + EGLConfig config = nullptr; + EGLContext context = nullptr; + PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC eglCreatePlatformWindowSurfaceEXT = nullptr; }; -} + + struct SWaylandContext { + wl_display* display = nullptr; + wl_registry* registry = nullptr; + wl_compositor* compositor = nullptr; + wl_shm* shm = nullptr; + zwlr_layer_shell_v1* layerShell = nullptr; + wl_seat* seat = nullptr; + }; + + explicit CWaylandOpenGLDriver (CApplicationContext& context, CWallpaperApplication& app); + ~CWaylandOpenGLDriver (); + + [[nodiscard]] Detectors::CFullScreenDetector& getFullscreenDetector () override; + [[nodiscard]] Output::COutput& getOutput () override; + float getRenderTime () const override; + bool closeRequested () override; + void resizeWindow (glm::ivec2 size) override; + void resizeWindow (glm::ivec4 sizeandpos) override; + void showWindow () override; + void hideWindow () override; + glm::ivec2 getFramebufferSize () const override; + uint32_t getFrameCounter () const override; + void dispatchEventQueue () override; + [[nodiscard]] void* getProcAddress (const char* name) const override; + + void onLayerClose (Output::CWaylandOutputViewport*); + Output::CWaylandOutputViewport* surfaceToViewport (const wl_surface*); + + Output::CWaylandOutputViewport* viewportInFocus = nullptr; + + [[nodiscard]] SEGLContext* getEGLContext (); + [[nodiscard]] SWaylandContext* getWaylandContext (); + + /** List of available screens */ + std::vector m_screens; + + private: + /** Fullscreen detection used by this driver */ + Detectors::CWaylandFullScreenDetector m_fullscreenDetector; + /** The output used by the driver */ + Output::CWaylandOutput m_output; + /** The EGL context in use */ + SEGLContext m_eglContext; + /** The Wayland context in use */ + SWaylandContext m_waylandContext; + mutable bool m_requestedExit; + + void initEGL (); + void finishEGL () const; + + uint32_t m_frameCounter; + CApplicationContext& m_context; + + std::chrono::high_resolution_clock::time_point renderStart = std::chrono::high_resolution_clock::now (); +}; +} // namespace WallpaperEngine::Render::Drivers #endif /* ENABLE_WAYLAND */ \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.cpp b/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.cpp index ccb979d..adf3b5d 100644 --- a/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.cpp +++ b/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.cpp @@ -1,6 +1,6 @@ #include "CX11OpenGLDriver.h" -#include "common.h" #include "WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h" +#include "common.h" #include #define GLFW_EXPOSE_NATIVE_X11 @@ -10,8 +10,7 @@ using namespace WallpaperEngine::Render::Drivers; -void CustomGLFWErrorHandler (int errorCode, const char* reason) -{ +void CustomGLFWErrorHandler (int errorCode, const char* reason) { sLog.error ("GLFW error ", errorCode, ": ", reason); } @@ -19,8 +18,7 @@ CX11OpenGLDriver::CX11OpenGLDriver (const char* windowTitle, CApplicationContext m_frameCounter (0), m_fullscreenDetector (context, *this), m_context (context), - CVideoDriver (app) -{ + CVideoDriver (app) { glfwSetErrorCallback (CustomGLFWErrorHandler); // initialize glfw @@ -38,8 +36,7 @@ CX11OpenGLDriver::CX11OpenGLDriver (const char* windowTitle, CApplicationContext glfwWindowHintString (GLFW_X11_INSTANCE_NAME, "linux-wallpaperengine"); // for forced window mode, we can set some hints that'll help position the window - if (context.settings.render.mode == Application::CApplicationContext::EXPLICIT_WINDOW) - { + if (context.settings.render.mode == Application::CApplicationContext::EXPLICIT_WINDOW) { glfwWindowHint (GLFW_RESIZABLE, GLFW_FALSE); glfwWindowHint (GLFW_DECORATED, GLFW_FALSE); glfwWindowHint (GLFW_FLOATING, GLFW_TRUE); @@ -59,75 +56,62 @@ CX11OpenGLDriver::CX11OpenGLDriver (const char* windowTitle, CApplicationContext glfwMakeContextCurrent (this->m_window); // initialize glew for rendering - GLenum result = glewInit (); + const GLenum result = glewInit (); if (result != GLEW_OK) - sLog.error("Failed to initialize GLEW: ", glewGetErrorString (result)); + sLog.error ("Failed to initialize GLEW: ", glewGetErrorString (result)); // initialize free image FreeImage_Initialise (TRUE); // setup output if (context.settings.render.mode == CApplicationContext::EXPLICIT_WINDOW || - context.settings.render.mode == CApplicationContext::NORMAL_WINDOW) - { + context.settings.render.mode == CApplicationContext::NORMAL_WINDOW) { m_output = new WallpaperEngine::Render::Drivers::Output::CGLFWWindowOutput (context, *this); - } - else - { + } else { m_output = new WallpaperEngine::Render::Drivers::Output::CX11Output (context, *this); } } -CX11OpenGLDriver::~CX11OpenGLDriver () -{ +CX11OpenGLDriver::~CX11OpenGLDriver () { glfwTerminate (); - FreeImage_DeInitialise(); + FreeImage_DeInitialise (); } -Detectors::CFullScreenDetector& CX11OpenGLDriver::getFullscreenDetector () -{ +Detectors::CFullScreenDetector& CX11OpenGLDriver::getFullscreenDetector () { return this->m_fullscreenDetector; } -Output::COutput& CX11OpenGLDriver::getOutput () -{ +Output::COutput& CX11OpenGLDriver::getOutput () { return *this->m_output; } -float CX11OpenGLDriver::getRenderTime () const -{ - return (float) glfwGetTime (); +float CX11OpenGLDriver::getRenderTime () const { + return static_cast (glfwGetTime ()); } -bool CX11OpenGLDriver::closeRequested () -{ +bool CX11OpenGLDriver::closeRequested () { return glfwWindowShouldClose (this->m_window); } -void CX11OpenGLDriver::resizeWindow (glm::ivec2 size) -{ +void CX11OpenGLDriver::resizeWindow (glm::ivec2 size) { glfwSetWindowSize (this->m_window, size.x, size.y); } -void CX11OpenGLDriver::resizeWindow (glm::ivec4 sizeandpos) -{ +void CX11OpenGLDriver::resizeWindow (glm::ivec4 sizeandpos) { glfwSetWindowPos (this->m_window, sizeandpos.x, sizeandpos.y); glfwSetWindowSize (this->m_window, sizeandpos.z, sizeandpos.w); } -void CX11OpenGLDriver::showWindow () -{ +void CX11OpenGLDriver::showWindow () { glfwShowWindow (this->m_window); } -void CX11OpenGLDriver::hideWindow () -{ +void CX11OpenGLDriver::hideWindow () { glfwHideWindow (this->m_window); } -glm::ivec2 CX11OpenGLDriver::getFramebufferSize () const -{ +glm::ivec2 CX11OpenGLDriver::getFramebufferSize () const { glm::ivec2 size; glfwGetFramebufferSize (this->m_window, &size.x, &size.y); @@ -135,28 +119,24 @@ glm::ivec2 CX11OpenGLDriver::getFramebufferSize () const return size; } -uint32_t CX11OpenGLDriver::getFrameCounter () const -{ +uint32_t CX11OpenGLDriver::getFrameCounter () const { return this->m_frameCounter; } -void CX11OpenGLDriver::dispatchEventQueue() -{ +void CX11OpenGLDriver::dispatchEventQueue () { static float startTime, endTime, minimumTime = 1.0f / this->m_context.settings.render.maximumFPS; // get the start time of the frame startTime = this->getRenderTime (); // clear the screen glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - for (const auto& viewport : this->m_output->getViewports ()) - this->getApp ().update (viewport.second); + for (const auto& [screen, viewport] : this->m_output->getViewports ()) + this->getApp ().update (viewport); // read the full texture into the image if (this->m_output->haveImageBuffer ()) - glReadPixels ( - 0, 0, this->m_output->getFullWidth (), this->m_output->getFullHeight (), GL_BGRA, GL_UNSIGNED_BYTE, - this->m_output->getImageBuffer () - ); + glReadPixels (0, 0, this->m_output->getFullWidth (), this->m_output->getFullHeight (), GL_BGRA, + GL_UNSIGNED_BYTE, this->m_output->getImageBuffer ()); // TODO: FRAMETIME CONTROL SHOULD GO BACK TO THE CWALLPAPAERAPPLICATION ONCE ACTUAL PARTICLES ARE IMPLEMENTED // TODO: AS THOSE, MORE THAN LIKELY, WILL REQUIRE OF A DIFFERENT PROCESSING RATE @@ -167,7 +147,7 @@ void CX11OpenGLDriver::dispatchEventQueue() // poll for events glfwPollEvents (); // increase frame counter - this->m_frameCounter ++; + this->m_frameCounter++; // get the end time of the frame endTime = this->getRenderTime (); @@ -176,12 +156,10 @@ void CX11OpenGLDriver::dispatchEventQueue() usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC); } -void* CX11OpenGLDriver::getProcAddress (const char* name) const -{ - return reinterpret_cast (glfwGetProcAddress (name)); +void* CX11OpenGLDriver::getProcAddress (const char* name) const { + return reinterpret_cast (glfwGetProcAddress (name)); } -GLFWwindow* CX11OpenGLDriver::getWindow () -{ +GLFWwindow* CX11OpenGLDriver::getWindow () { return this->m_window; } diff --git a/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.h b/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.h index 2249959..8c3784e 100644 --- a/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.h +++ b/src/WallpaperEngine/Render/Drivers/CX11OpenGLDriver.h @@ -1,50 +1,47 @@ #pragma once -#include -#include -#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "WallpaperEngine/Application/CApplicationContext.h" +#include "WallpaperEngine/Application/CWallpaperApplication.h" +#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h" #include "WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h" #include "WallpaperEngine/Render/Drivers/Output/CX11Output.h" -#include "WallpaperEngine/Application/CWallpaperApplication.h" +#include +#include -namespace WallpaperEngine::Application -{ - class CApplicationContext; - class CWallpaperApplication; -} +namespace WallpaperEngine::Application { +class CApplicationContext; +class CWallpaperApplication; +} // namespace WallpaperEngine::Application -namespace WallpaperEngine::Render::Drivers -{ - using namespace WallpaperEngine::Application; +namespace WallpaperEngine::Render::Drivers { +using namespace WallpaperEngine::Application; - class CX11OpenGLDriver : public CVideoDriver - { - public: - explicit CX11OpenGLDriver (const char* windowTitle, CApplicationContext& context, CWallpaperApplication& app); - ~CX11OpenGLDriver(); +class CX11OpenGLDriver final : public CVideoDriver { + public: + explicit CX11OpenGLDriver (const char* windowTitle, CApplicationContext& context, CWallpaperApplication& app); + ~CX11OpenGLDriver () override; - [[nodiscard]] Detectors::CFullScreenDetector& getFullscreenDetector () override; - [[nodiscard]] Output::COutput& getOutput () override; - [[nodiscard]] float getRenderTime () const override; - bool closeRequested () override; - void resizeWindow (glm::ivec2 size) override; - void resizeWindow (glm::ivec4 sizeandpos) override; - void showWindow () override; - void hideWindow () override; - [[nodiscard]] glm::ivec2 getFramebufferSize () const override; - [[nodiscard]] uint32_t getFrameCounter () const override; - void dispatchEventQueue() override; - [[nodiscard]] void* getProcAddress (const char* name) const override; + [[nodiscard]] Detectors::CFullScreenDetector& getFullscreenDetector () override; + [[nodiscard]] Output::COutput& getOutput () override; + [[nodiscard]] float getRenderTime () const override; + bool closeRequested () override; + void resizeWindow (glm::ivec2 size) override; + void resizeWindow (glm::ivec4 sizeandpos) override; + void showWindow () override; + void hideWindow () override; + [[nodiscard]] glm::ivec2 getFramebufferSize () const override; + [[nodiscard]] uint32_t getFrameCounter () const override; + void dispatchEventQueue () override; + [[nodiscard]] void* getProcAddress (const char* name) const override; - GLFWwindow* getWindow (); + GLFWwindow* getWindow (); - private: - Detectors::CX11FullScreenDetector m_fullscreenDetector; - CApplicationContext& m_context; - Output::COutput* m_output; - GLFWwindow* m_window; - uint32_t m_frameCounter; - }; -} \ No newline at end of file + private: + Detectors::CX11FullScreenDetector m_fullscreenDetector; + CApplicationContext& m_context; + Output::COutput* m_output; + GLFWwindow* m_window; + uint32_t m_frameCounter; +}; +} // namespace WallpaperEngine::Render::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.cpp b/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.cpp index 1fd6c70..ef5e5d8 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.cpp +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.cpp @@ -4,11 +4,8 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Render::Drivers::Detectors; CFullScreenDetector::CFullScreenDetector (Application::CApplicationContext& appContext) : - m_applicationContext (appContext) -{ -} + m_applicationContext (appContext) {} -Application::CApplicationContext& CFullScreenDetector::getApplicationContext () const -{ +Application::CApplicationContext& CFullScreenDetector::getApplicationContext () const { return this->m_applicationContext; } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h b/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h index ed097dd..ee0d6d7 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h @@ -2,28 +2,27 @@ #include "WallpaperEngine/Application/CApplicationContext.h" -namespace WallpaperEngine::Render::Drivers::Detectors -{ - class CFullScreenDetector - { - public: - CFullScreenDetector (Application::CApplicationContext& appContext); +namespace WallpaperEngine::Render::Drivers::Detectors { +class CFullScreenDetector { + public: + explicit CFullScreenDetector (Application::CApplicationContext& appContext); + virtual ~CFullScreenDetector () = default; - /** - * @return If anything is fullscreen - */ - [[nodiscard]] virtual bool anythingFullscreen () const = 0; + /** + * @return If anything is fullscreen + */ + [[nodiscard]] virtual bool anythingFullscreen () const = 0; - /** - * Restarts the fullscreen detector, specially useful if there's any resources tied to the output driver - */ - virtual void reset () = 0; - /** - * @return The application context using this detector - */ - [[nodiscard]] Application::CApplicationContext& getApplicationContext () const; + /** + * Restarts the fullscreen detector, specially useful if there's any resources tied to the output driver + */ + virtual void reset () = 0; + /** + * @return The application context using this detector + */ + [[nodiscard]] Application::CApplicationContext& getApplicationContext () const; - private: - Application::CApplicationContext& m_applicationContext; - }; -} \ No newline at end of file + private: + Application::CApplicationContext& m_applicationContext; +}; +} // namespace WallpaperEngine::Render::Drivers::Detectors \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp index 2625e91..6390ba3 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp @@ -2,19 +2,12 @@ using namespace WallpaperEngine::Render::Drivers::Detectors; -CWaylandFullScreenDetector::CWaylandFullScreenDetector (Application::CApplicationContext& appContext, CWaylandOpenGLDriver& driver) : - CFullScreenDetector (appContext) -{ -} - -CWaylandFullScreenDetector::~CWaylandFullScreenDetector () { - ; -} +CWaylandFullScreenDetector::CWaylandFullScreenDetector (Application::CApplicationContext& appContext, + CWaylandOpenGLDriver& driver) : + CFullScreenDetector (appContext) {} bool CWaylandFullScreenDetector::anythingFullscreen () const { return false; // todo } -void CWaylandFullScreenDetector::reset () { - ; -} \ No newline at end of file +void CWaylandFullScreenDetector::reset () {} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h index 00650b0..2be1286 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h @@ -1,28 +1,26 @@ -#ifdef ENABLE_WAYLAND #pragma once +#ifdef ENABLE_WAYLAND + +#include #include #include -#include #include "CFullScreenDetector.h" #include "WallpaperEngine/Render/Drivers/CVideoDriver.h" -namespace WallpaperEngine::Render::Drivers -{ - class CWaylandOpenGLDriver; +namespace WallpaperEngine::Render::Drivers { +class CWaylandOpenGLDriver; - namespace Detectors - { - class CWaylandFullScreenDetector : public CFullScreenDetector - { - public: - CWaylandFullScreenDetector (Application::CApplicationContext& appContext, CWaylandOpenGLDriver& driver); - ~CWaylandFullScreenDetector (); +namespace Detectors { +class CWaylandFullScreenDetector final : public CFullScreenDetector { + public: + CWaylandFullScreenDetector (Application::CApplicationContext& appContext, CWaylandOpenGLDriver& driver); + ~CWaylandFullScreenDetector () override = default; - [[nodiscard]] bool anythingFullscreen () const override; - void reset () override; - }; - } -} + [[nodiscard]] bool anythingFullscreen () const override; + void reset () override; +}; +} // namespace Detectors +} // namespace WallpaperEngine::Render::Drivers #endif /* ENABLE_WAYLAND */ \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp index 10b3f30..deadafa 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp @@ -6,180 +6,156 @@ #include "WallpaperEngine/Render/Drivers/CX11OpenGLDriver.h" -namespace WallpaperEngine::Render::Drivers::Detectors -{ - void CustomXIOErrorExitHandler (Display* dsp, void* userdata) +namespace WallpaperEngine::Render::Drivers::Detectors { +void CustomXIOErrorExitHandler (Display* dsp, void* userdata) { + const auto context = static_cast (userdata); + + sLog.debugerror ("Critical XServer error detected. Attempting to recover..."); + + // refetch all the resources + context->reset (); +} + +int CustomXErrorHandler (Display* dpy, XErrorEvent* event) { + sLog.debugerror ("Detected X error"); + + return 0; +} + +int CustomXIOErrorHandler (Display* dsp) { + sLog.debugerror ("Detected X error"); + + return 0; +} + +CX11FullScreenDetector::CX11FullScreenDetector (Application::CApplicationContext& appContext, + CX11OpenGLDriver& driver) : + CFullScreenDetector (appContext), + m_driver (driver) { + // do not use previous handler, it might stop the app under weird circumstances + // these handlers might be replaced by other X11-specific functionality, they + // should only be used to ignore X11 errors and nothing else + // so this doesn't affect functionality + XSetErrorHandler (CustomXErrorHandler); + XSetIOErrorHandler (CustomXIOErrorHandler); + + this->initialize (); +} + +CX11FullScreenDetector::~CX11FullScreenDetector () { + this->stop (); +} + +bool CX11FullScreenDetector::anythingFullscreen () const { + if (!this->getApplicationContext ().settings.render.pauseOnFullscreen) + return false; + + // stop rendering if anything is fullscreen + bool isFullscreen = false; + XWindowAttributes attribs; + Window _; + Window* children; + unsigned int nchildren; + + if (!XQueryTree (this->m_display, this->m_root, &_, &_, &children, &nchildren)) + return false; + + const auto ourWindow = reinterpret_cast (this->m_driver.getWindow ()); + Window parentWindow; + { - auto context = static_cast (userdata); + Window root, *schildren = nullptr; + unsigned int num_children; - sLog.debugerror ("Critical XServer error detected. Attempting to recover..."); - - // refetch all the resources - context->reset (); - } - - int CustomXErrorHandler (Display* dpy, XErrorEvent* event) - { - sLog.debugerror ("Detected X error"); - - return 0; - } - - int CustomXIOErrorHandler (Display* dsp) - { - sLog.debugerror ("Detected X error"); - - return 0; - } - - CX11FullScreenDetector::CX11FullScreenDetector (Application::CApplicationContext& appContext, CX11OpenGLDriver& driver) : - CFullScreenDetector (appContext), - m_driver (driver) - { - // do not use previous handler, it might stop the app under weird circumstances - // these handlers might be replaced by other X11-specific functionality, they - // should only be used to ignore X11 errors and nothing else - // so this doesn't affect functionality - XSetErrorHandler (CustomXErrorHandler); - XSetIOErrorHandler (CustomXIOErrorHandler); - - this->initialize (); - } - - CX11FullScreenDetector::~CX11FullScreenDetector () - { - this->stop (); - } - - bool CX11FullScreenDetector::anythingFullscreen () const - { - if (!this->getApplicationContext ().settings.render.pauseOnFullscreen) + if (!XQueryTree (m_display, ourWindow, &root, &parentWindow, &schildren, &num_children)) return false; - // stop rendering if anything is fullscreen - bool isFullscreen = false; - XWindowAttributes attribs; - Window _; - Window* children; - unsigned int nchildren; + if (schildren) + XFree (children); + } - isFullscreen = false; + for (int i = 0; i < nchildren; i++) { + if (!XGetWindowAttributes (this->m_display, children [i], &attribs)) + continue; - if (!XQueryTree (this->m_display, this->m_root, &_, &_, &children, &nchildren)) - return false; + // ignore ourselves + if (ourWindow == children [i] || parentWindow == children [i]) + continue; - auto ourWindow = reinterpret_cast (this->m_driver.getWindow ()); - Window parentWindow; + if (attribs.map_state != IsViewable) + continue; - { - Window root, * schildren = NULL; - unsigned int num_children; - - if (!XQueryTree (m_display, ourWindow, &root, &parentWindow, &schildren, &num_children)) - return false; - - if (schildren) - XFree ((char*) children); - } - - for (int i = 0; i < nchildren; i++) - { - if (!XGetWindowAttributes (this->m_display, children [i], &attribs)) - continue; - - // ignore ourselves - if (ourWindow == children [i] || parentWindow == children [i]) - continue; - - if (attribs.map_state != IsViewable) - continue; - - // compare width and height with the different screens we have - for (const auto& screen : this->m_screens) - { - if ( - attribs.x == screen.viewport.x && attribs.y == screen.viewport.y && - attribs.width == screen.viewport.z && attribs.height == screen.viewport.w - ) - { - isFullscreen = true; - break; - } + // compare width and height with the different screens we have + for (const auto& [viewport, name] : this->m_screens) { + if (attribs.x == viewport.x && attribs.y == viewport.y && attribs.width == viewport.z && + attribs.height == viewport.w) { + isFullscreen = true; + break; } } - - XFree (children); - - return isFullscreen; } - void CX11FullScreenDetector::reset () - { - this->stop (); - this->initialize (); - } + XFree (children); - void CX11FullScreenDetector::initialize () - { - this->m_display = XOpenDisplay (nullptr); + return isFullscreen; +} + +void CX11FullScreenDetector::reset () { + this->stop (); + this->initialize (); +} + +void CX11FullScreenDetector::initialize () { + this->m_display = XOpenDisplay (nullptr); // set the error handling to try and recover from X disconnections #ifdef HAVE_XSETIOERROREXITHANDLER - XSetIOErrorExitHandler (this->m_display, CustomXIOErrorExitHandler, this); + XSetIOErrorExitHandler (this->m_display, CustomXIOErrorExitHandler, this); #endif /* HAVE_XSETIOERROREXITHANDLER */ - int xrandr_result, xrandr_error; + int xrandr_result, xrandr_error; - if (!XRRQueryExtension (this->m_display, &xrandr_result, &xrandr_error)) - { - sLog.error ("XRandr is not present, fullscreen detection might not work"); - return; - } - - this->m_root = DefaultRootWindow (this->m_display); - XRRScreenResources* screenResources = XRRGetScreenResources (this->m_display, this->m_root); - - if (screenResources == nullptr) - { - sLog.error ("Cannot detect screen sizes using xrandr, fullscreen detection might not work"); - return; - } - - for (int i = 0; i < screenResources->noutput; i ++) - { - XRROutputInfo* info = XRRGetOutputInfo (this->m_display, screenResources, screenResources->outputs [i]); - - // screen not in use, ignore it - if (info == nullptr || info->connection != RR_Connected) - continue; - - XRRCrtcInfo* crtc = XRRGetCrtcInfo (this->m_display, screenResources, info->crtc); - - // screen not active, ignore it - if (crtc == nullptr) - continue; - - // add the screen to the list of screens - this->m_screens.push_back ( - { - {crtc->x, crtc->y, crtc->width, crtc->height}, - info->name - } - ); - - XRRFreeCrtcInfo (crtc); - } - - XRRFreeScreenResources (screenResources); + if (!XRRQueryExtension (this->m_display, &xrandr_result, &xrandr_error)) { + sLog.error ("XRandr is not present, fullscreen detection might not work"); + return; } - void CX11FullScreenDetector::stop () - { - if (this->m_display == nullptr) - return; + this->m_root = DefaultRootWindow (this->m_display); + XRRScreenResources* screenResources = XRRGetScreenResources (this->m_display, this->m_root); - XCloseDisplay (this->m_display); - this->m_display = nullptr; + if (screenResources == nullptr) { + sLog.error ("Cannot detect screen sizes using xrandr, fullscreen detection might not work"); + return; } + for (int i = 0; i < screenResources->noutput; i++) { + const XRROutputInfo* info = XRRGetOutputInfo (this->m_display, screenResources, screenResources->outputs [i]); + + // screen not in use, ignore it + if (info == nullptr || info->connection != RR_Connected) + continue; + + XRRCrtcInfo* crtc = XRRGetCrtcInfo (this->m_display, screenResources, info->crtc); + + // screen not active, ignore it + if (crtc == nullptr) + continue; + + // add the screen to the list of screens + this->m_screens.push_back ({{crtc->x, crtc->y, crtc->width, crtc->height}, info->name}); + + XRRFreeCrtcInfo (crtc); + } + + XRRFreeScreenResources (screenResources); } + +void CX11FullScreenDetector::stop () { + if (this->m_display == nullptr) + return; + + XCloseDisplay (this->m_display); + this->m_display = nullptr; +} + +} // namespace WallpaperEngine::Render::Drivers::Detectors diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h index dd5b73a..34f1a8e 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h @@ -1,41 +1,37 @@ #pragma once +#include #include #include -#include #include "CFullScreenDetector.h" #include -namespace WallpaperEngine::Render::Drivers -{ - class CX11OpenGLDriver; +namespace WallpaperEngine::Render::Drivers { +class CX11OpenGLDriver; - namespace Detectors - { - class CX11FullScreenDetector : public CFullScreenDetector - { - public: - CX11FullScreenDetector (Application::CApplicationContext& appContext, CX11OpenGLDriver& driver); - ~CX11FullScreenDetector (); +namespace Detectors { +class CX11FullScreenDetector final : public CFullScreenDetector { + public: + CX11FullScreenDetector (Application::CApplicationContext& appContext, CX11OpenGLDriver& driver); + ~CX11FullScreenDetector () override; - [[nodiscard]] bool anythingFullscreen () const override; - void reset () override; + [[nodiscard]] bool anythingFullscreen () const override; + void reset () override; - private: - void initialize (); - void stop (); + private: + void initialize (); + void stop (); - struct ScreenInfo - { - glm::ivec4 viewport; - std::string name; - }; + struct ScreenInfo { + glm::ivec4 viewport; + std::string name; + }; - Display* m_display; - Window m_root; - std::vector m_screens; - CX11OpenGLDriver& m_driver; - }; - } -} \ No newline at end of file + Display* m_display; + Window m_root; + std::vector m_screens; + CX11OpenGLDriver& m_driver; +}; +} // namespace Detectors +} // namespace WallpaperEngine::Render::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp index d96f397..fbf8e2f 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp @@ -1,8 +1,8 @@ +#include "CGLFWWindowOutput.h" +#include "CX11OutputViewport.h" +#include "WallpaperEngine/Logging/CLog.h" #include #include -#include "CGLFWWindowOutput.h" -#include "WallpaperEngine/Logging/CLog.h" -#include "CX11OutputViewport.h" #include @@ -10,25 +10,19 @@ using namespace WallpaperEngine::Render::Drivers::Output; -CGLFWWindowOutput::CGLFWWindowOutput (CApplicationContext& context, CVideoDriver& driver) : - COutput (context, driver) -{ - if ( - this->m_context.settings.render.mode != Application::CApplicationContext::NORMAL_WINDOW && +CGLFWWindowOutput::CGLFWWindowOutput (CApplicationContext& context, CVideoDriver& driver) : COutput (context, driver) { + if (this->m_context.settings.render.mode != Application::CApplicationContext::NORMAL_WINDOW && this->m_context.settings.render.mode != Application::CApplicationContext::EXPLICIT_WINDOW) sLog.exception ("Initializing window output when not in output mode, how did you get here?!"); // window should be visible driver.showWindow (); - if (this->m_context.settings.render.mode == Application::CApplicationContext::EXPLICIT_WINDOW) - { + if (this->m_context.settings.render.mode == Application::CApplicationContext::EXPLICIT_WINDOW) { this->m_fullWidth = this->m_context.settings.render.window.geometry.z; this->m_fullHeight = this->m_context.settings.render.window.geometry.w; this->repositionWindow (); - } - else - { + } else { // take the size from the driver (default window size) this->m_fullWidth = this->m_driver.getFramebufferSize ().x; this->m_fullHeight = this->m_driver.getFramebufferSize ().y; @@ -38,39 +32,33 @@ CGLFWWindowOutput::CGLFWWindowOutput (CApplicationContext& context, CVideoDriver this->m_viewports ["default"] = new CX11OutputViewport {{0, 0, this->m_fullWidth, this->m_fullHeight}, "default"}; } -void CGLFWWindowOutput::repositionWindow () -{ +void CGLFWWindowOutput::repositionWindow () { // reposition the window this->m_driver.resizeWindow (this->m_context.settings.render.window.geometry); } -void CGLFWWindowOutput::reset () -{ +void CGLFWWindowOutput::reset () { if (this->m_context.settings.render.mode == Application::CApplicationContext::EXPLICIT_WINDOW) this->repositionWindow (); } -bool CGLFWWindowOutput::renderVFlip () const -{ +bool CGLFWWindowOutput::renderVFlip () const { return true; } -bool CGLFWWindowOutput::renderMultiple () const -{ +bool CGLFWWindowOutput::renderMultiple () const { return false; } -bool CGLFWWindowOutput::haveImageBuffer () const -{ +bool CGLFWWindowOutput::haveImageBuffer () const { return false; } -void* CGLFWWindowOutput::getImageBuffer () const -{ +void* CGLFWWindowOutput::getImageBuffer () const { return nullptr; } -void CGLFWWindowOutput::updateRender () const -{ + +void CGLFWWindowOutput::updateRender () const { if (this->m_context.settings.render.mode != Application::CApplicationContext::NORMAL_WINDOW) return; diff --git a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h index 099903a..f7d7582 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h @@ -1,23 +1,21 @@ #pragma once -#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "COutput.h" +#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" -namespace WallpaperEngine::Render::Drivers::Output -{ - class CGLFWWindowOutput : public COutput - { - public: - CGLFWWindowOutput (CApplicationContext& context, CVideoDriver& driver); +namespace WallpaperEngine::Render::Drivers::Output { +class CGLFWWindowOutput final : public COutput { + public: + CGLFWWindowOutput (CApplicationContext& context, CVideoDriver& driver); - void reset () override; - bool renderVFlip () const override; - bool renderMultiple () const override; - bool haveImageBuffer () const override; - void* getImageBuffer () const override; - void updateRender () const override; + void reset () override; + bool renderVFlip () const override; + bool renderMultiple () const override; + bool haveImageBuffer () const override; + void* getImageBuffer () const override; + void updateRender () const override; - private: - void repositionWindow (); - }; -} \ No newline at end of file + private: + void repositionWindow (); +}; +} // namespace WallpaperEngine::Render::Drivers::Output \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp b/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp index 6b514dc..2d39f11 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp @@ -3,22 +3,19 @@ using namespace WallpaperEngine::Render::Drivers::Output; COutput::COutput (CApplicationContext& context, CVideoDriver& driver) : + m_fullWidth (0), + m_fullHeight (0), m_context (context), - m_driver (driver) -{ -} + m_driver (driver) {} -const std::map & COutput::getViewports () const -{ +const std::map& COutput::getViewports () const { return this->m_viewports; } -int COutput::getFullWidth () const -{ +int COutput::getFullWidth () const { return this->m_fullWidth; } -int COutput::getFullHeight () const -{ +int COutput::getFullHeight () const { return this->m_fullHeight; } diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutput.h b/src/WallpaperEngine/Render/Drivers/Output/COutput.h index cabf9d2..934f411 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutput.h +++ b/src/WallpaperEngine/Render/Drivers/Output/COutput.h @@ -1,55 +1,51 @@ #pragma once +#include #include #include -#include #include "WallpaperEngine/Application/CApplicationContext.h" #include "WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h" using namespace WallpaperEngine::Application; -namespace WallpaperEngine::Application -{ - class CApplicationContext; +namespace WallpaperEngine::Application { +class CApplicationContext; } -namespace WallpaperEngine::Render::Drivers -{ - class CVideoDriver; +namespace WallpaperEngine::Render::Drivers { +class CVideoDriver; - namespace Detectors - { - class CFullScreenDetector; - } +namespace Detectors { +class CFullScreenDetector; +} - namespace Output - { - class COutputViewport; +namespace Output { +class COutputViewport; - class COutput - { - public: - COutput (CApplicationContext& context, CVideoDriver& driver); +class COutput { + public: + COutput (CApplicationContext& context, CVideoDriver& driver); + virtual ~COutput () = default; - virtual void reset () = 0; + virtual void reset () = 0; - int getFullWidth () const; - int getFullHeight () const; + int getFullWidth () const; + int getFullHeight () const; - virtual bool renderVFlip () const = 0; - virtual bool renderMultiple () const = 0; - virtual bool haveImageBuffer () const = 0; - const std::map & getViewports () const; - virtual void* getImageBuffer () const = 0; - virtual void updateRender () const = 0; + virtual bool renderVFlip () const = 0; + virtual bool renderMultiple () const = 0; + virtual bool haveImageBuffer () const = 0; + const std::map& getViewports () const; + virtual void* getImageBuffer () const = 0; + virtual void updateRender () const = 0; - protected: - mutable int m_fullWidth; - mutable int m_fullHeight; - mutable std::map m_viewports; - CApplicationContext& m_context; - CVideoDriver& m_driver; - }; - } -} \ No newline at end of file + protected: + mutable int m_fullWidth; + mutable int m_fullHeight; + mutable std::map m_viewports; + CApplicationContext& m_context; + CVideoDriver& m_driver; +}; +} // namespace Output +} // namespace WallpaperEngine::Render::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp index 11abc8b..52f216f 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp @@ -6,11 +6,7 @@ using namespace WallpaperEngine::Render::Drivers::Output; COutputViewport::COutputViewport (glm::ivec4 viewport, std::string name, bool single) : viewport (viewport), - name (std::move(name)), - single (single) -{ -} + name (std::move (name)), + single (single) {} -COutputViewport::~COutputViewport () -{ -} \ No newline at end of file +COutputViewport::~COutputViewport () {} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h index 3e5ce4a..be21f74 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h +++ b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h @@ -1,30 +1,28 @@ #pragma once -#include #include +#include -namespace WallpaperEngine::Render::Drivers::Output -{ - class COutputViewport - { - public: - COutputViewport (glm::ivec4 viewport, std::string name, bool single = false); - virtual ~COutputViewport (); +namespace WallpaperEngine::Render::Drivers::Output { +class COutputViewport { + public: + COutputViewport (glm::ivec4 viewport, std::string name, bool single = false); + virtual ~COutputViewport (); - glm::ivec4 viewport; - std::string name; + glm::ivec4 viewport; + std::string name; - /** Whether this viewport is single in the framebuffer or shares space with more viewports */ - bool single; + /** Whether this viewport is single in the framebuffer or shares space with more viewports */ + bool single; - /** - * Activates output's context for drawing - */ - virtual void makeCurrent () = 0; + /** + * Activates output's context for drawing + */ + virtual void makeCurrent () = 0; - /** - * Swaps buffers to present data on the viewport - */ - virtual void swapOutput () = 0; - }; -} + /** + * Swaps buffers to present data on the viewport + */ + virtual void swapOutput () = 0; +}; +} // namespace WallpaperEngine::Render::Drivers::Output diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp index 2a60a64..824b46e 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp @@ -1,33 +1,28 @@ -#include "common.h" #include "CWaylandOutput.h" #include "../CWaylandOpenGLDriver.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" +#include "common.h" using namespace WallpaperEngine::Render::Drivers::Output; CWaylandOutput::CWaylandOutput (CApplicationContext& context, CWaylandOpenGLDriver& driver) : - COutput (context, driver) -{ - updateViewports(); + COutput (context, driver) { + updateViewports (); } -CWaylandOutput::~CWaylandOutput () -{ -} +CWaylandOutput::~CWaylandOutput () {} -void CWaylandOutput::updateViewports() -{ - m_viewports.clear(); - const auto PDRIVER = (CWaylandOpenGLDriver*)&m_driver; - glm::ivec2 fullw = {0,0}; - for (auto& o : PDRIVER->m_screens) - { +void CWaylandOutput::updateViewports () { + m_viewports.clear (); + const auto PDRIVER = dynamic_cast (&m_driver); + glm::ivec2 fullw = {0, 0}; + for (const auto& o : PDRIVER->m_screens) { if (!o->layerSurface) continue; - m_viewports[o->name] = o; + m_viewports [o->name] = o; - fullw = fullw + glm::ivec2{o->size.x * o->scale, 0}; + fullw = fullw + glm::ivec2 {o->size.x * o->scale, 0}; if (o->size.y > fullw.y) fullw.y = o->size.y; } @@ -36,31 +31,24 @@ void CWaylandOutput::updateViewports() m_fullHeight = fullw.y; } -void CWaylandOutput::reset () -{ - updateViewports(); +void CWaylandOutput::reset () { + updateViewports (); } -bool CWaylandOutput::renderVFlip () const -{ +bool CWaylandOutput::renderVFlip () const { return true; } -bool CWaylandOutput::renderMultiple () const -{ +bool CWaylandOutput::renderMultiple () const { return false; // todo } -bool CWaylandOutput::haveImageBuffer () const -{ +bool CWaylandOutput::haveImageBuffer () const { return false; } -void* CWaylandOutput::getImageBuffer () const -{ +void* CWaylandOutput::getImageBuffer () const { return nullptr; } -void CWaylandOutput::updateRender () const -{ -} \ No newline at end of file +void CWaylandOutput::updateRender () const {} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h index eca4367..52b840b 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h @@ -1,36 +1,34 @@ -#ifdef ENABLE_WAYLAND #pragma once +#ifdef ENABLE_WAYLAND + +#include #include #include -#include -#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "COutput.h" +#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" -namespace WallpaperEngine::Render::Drivers -{ - class CWaylandOpenGLDriver; +namespace WallpaperEngine::Render::Drivers { +class CWaylandOpenGLDriver; - namespace Output - { - class CWaylandOutput : public COutput - { - public: - CWaylandOutput (CApplicationContext& context, CWaylandOpenGLDriver& driver); - ~CWaylandOutput (); +namespace Output { +class CWaylandOutput final : public COutput { + public: + CWaylandOutput (CApplicationContext& context, CWaylandOpenGLDriver& driver); + ~CWaylandOutput () override; - void reset () override; + void reset () override; - bool renderVFlip () const override; - bool renderMultiple () const override; - bool haveImageBuffer () const override; - void* getImageBuffer () const override; - void updateRender () const override; + bool renderVFlip () const override; + bool renderMultiple () const override; + bool haveImageBuffer () const override; + void* getImageBuffer () const override; + void updateRender () const override; - private: - void updateViewports(); - }; - } -} + private: + void updateViewports (); +}; +} // namespace Output +} // namespace WallpaperEngine::Render::Drivers #endif /* ENABLE_WAYLAND */ \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp index c47fa2b..91fed4d 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp @@ -1,13 +1,13 @@ -#include "WallpaperEngine/Application/CWallpaperApplication.h" #include "CWaylandOutputViewport.h" +#include "WallpaperEngine/Application/CWallpaperApplication.h" #include "WallpaperEngine/Logging/CLog.h" #define class _class #define namespace _namespace #define static extern "C" { -#include "xdg-shell-protocol.h" #include "wlr-layer-shell-unstable-v1-protocol.h" +#include "xdg-shell-protocol.h" } #undef class #undef namespace @@ -18,34 +18,28 @@ extern "C" { using namespace WallpaperEngine::Render::Drivers; using namespace WallpaperEngine::Render::Drivers::Output; -static void handleLSConfigure(void *data, zwlr_layer_surface_v1 *surface, uint32_t serial, uint32_t w, uint32_t h) -{ - const auto viewport = static_cast (data); +static void handleLSConfigure (void* data, zwlr_layer_surface_v1* surface, uint32_t serial, uint32_t w, uint32_t h) { + const auto viewport = static_cast (data); viewport->size = {w, h}; viewport->viewport = {0, 0, viewport->size.x * viewport->scale, viewport->size.y * viewport->scale}; viewport->resize (); - zwlr_layer_surface_v1_ack_configure(surface, serial); + zwlr_layer_surface_v1_ack_configure (surface, serial); } -static void handleLSClosed(void *data, zwlr_layer_surface_v1 *surface) -{ - const auto viewport = static_cast (data); +static void handleLSClosed (void* data, zwlr_layer_surface_v1* surface) { + const auto viewport = static_cast (data); - viewport->getDriver ()->onLayerClose(viewport); + viewport->getDriver ()->onLayerClose (viewport); } -static void geometry( - void* data, wl_output* output, int32_t x, int32_t y, int32_t width_mm, int32_t height_mm, int32_t subpixel, - const char* make, const char* model, int32_t transform -) -{ +static void geometry (void* data, wl_output* output, int32_t x, int32_t y, int32_t width_mm, int32_t height_mm, + int32_t subpixel, const char* make, const char* model, int32_t transform) { // ignored } -static void mode(void* data, wl_output* output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) -{ - const auto viewport = static_cast (data); +static void mode (void* data, wl_output* output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) { + const auto viewport = static_cast (data); // update viewport size too viewport->size = {width, height}; @@ -58,14 +52,12 @@ static void mode(void* data, wl_output* output, uint32_t flags, int32_t width, i viewport->getDriver ()->getOutput ().reset (); } -static void done(void* data, wl_output* wl_output) -{ - static_cast (data)->initialized = true; +static void done (void* data, wl_output* wl_output) { + static_cast (data)->initialized = true; } -static void scale(void* data, wl_output* wl_output, int32_t scale) -{ - const auto viewport = static_cast (data); +static void scale (void* data, wl_output* wl_output, int32_t scale) { + const auto viewport = static_cast (data); viewport->scale = scale; @@ -76,9 +68,8 @@ static void scale(void* data, wl_output* wl_output, int32_t scale) viewport->getDriver ()->getOutput ().reset (); } -static void name(void* data, wl_output* wl_output, const char* name) -{ - const auto viewport = static_cast (data); +static void name (void* data, wl_output* wl_output, const char* name) { + const auto viewport = static_cast (data); if (name) viewport->name = name; @@ -87,138 +78,122 @@ static void name(void* data, wl_output* wl_output, const char* name) viewport->getDriver ()->getOutput ().reset (); } -static void description(void* data, wl_output* wl_output, const char* description) -{ +static void description (void* data, wl_output* wl_output, const char* description) { // ignored } -static void surfaceFrameCallback(void *data, struct wl_callback *cb, uint32_t time) -{ - const auto viewport = static_cast (data); +static void surfaceFrameCallback (void* data, struct wl_callback* cb, uint32_t time) { + const auto viewport = static_cast (data); - wl_callback_destroy(cb); + wl_callback_destroy (cb); viewport->frameCallback = nullptr; viewport->rendering = true; viewport->getDriver ()->getApp ().update (viewport); viewport->rendering = false; - - float renderTime = viewport->getDriver ()->getRenderTime(); } -const struct wl_callback_listener frameListener = -{ - .done = surfaceFrameCallback -}; +constexpr struct wl_callback_listener frameListener = {.done = surfaceFrameCallback}; -const wl_output_listener outputListener = -{ - .geometry = geometry, - .mode = mode, - .done = done, - .scale = scale, - .name = name, - .description = description -}; +constexpr wl_output_listener outputListener = { + .geometry = geometry, .mode = mode, .done = done, .scale = scale, .name = name, .description = description}; -const struct zwlr_layer_surface_v1_listener layerSurfaceListener = { +constexpr struct zwlr_layer_surface_v1_listener layerSurfaceListener = { .configure = handleLSConfigure, .closed = handleLSClosed, }; -CWaylandOutputViewport::CWaylandOutputViewport (CWaylandOpenGLDriver* driver, uint32_t waylandName, struct wl_registry *registry) : +CWaylandOutputViewport::CWaylandOutputViewport (CWaylandOpenGLDriver* driver, uint32_t waylandName, + struct wl_registry* registry) : m_driver (driver), waylandName (waylandName), - COutputViewport ({0,0,0,0}, "", true) -{ + COutputViewport ({0, 0, 0, 0}, "", true) { // setup output listener - this->output = (wl_output*) wl_registry_bind(registry, waylandName, &wl_output_interface, 4); + this->output = static_cast (wl_registry_bind (registry, waylandName, &wl_output_interface, 4)); this->name = ""; this->size = {0, 0}; - wl_output_add_listener(output, &outputListener, this); + wl_output_add_listener (output, &outputListener, this); } -void CWaylandOutputViewport::setupLS () -{ - surface = wl_compositor_create_surface(m_driver->getWaylandContext()->compositor); - layerSurface = zwlr_layer_shell_v1_get_layer_surface(m_driver->getWaylandContext()->layerShell, surface, output, ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND, "linux-wallpaperengine"); +void CWaylandOutputViewport::setupLS () { + surface = wl_compositor_create_surface (m_driver->getWaylandContext ()->compositor); + layerSurface = + zwlr_layer_shell_v1_get_layer_surface (m_driver->getWaylandContext ()->layerShell, surface, output, + ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND, "linux-wallpaperengine"); if (!layerSurface) - sLog.exception("Failed to get a layer surface"); + sLog.exception ("Failed to get a layer surface"); - wl_region* region = wl_compositor_create_region(m_driver->getWaylandContext()->compositor); - wl_region_add(region, 0, 0, INT32_MAX, INT32_MAX); + wl_region* region = wl_compositor_create_region (m_driver->getWaylandContext ()->compositor); + wl_region_add (region, 0, 0, INT32_MAX, INT32_MAX); - zwlr_layer_surface_v1_set_size(layerSurface, 0, 0); - zwlr_layer_surface_v1_set_anchor(layerSurface, ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT | ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP | ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM); - zwlr_layer_surface_v1_set_keyboard_interactivity(layerSurface, false); - zwlr_layer_surface_v1_add_listener(layerSurface, &layerSurfaceListener, this); - zwlr_layer_surface_v1_set_exclusive_zone(layerSurface, -1); - wl_surface_set_input_region(surface, region); - wl_surface_commit(surface); - wl_display_roundtrip(m_driver->getWaylandContext()->display); + zwlr_layer_surface_v1_set_size (layerSurface, 0, 0); + zwlr_layer_surface_v1_set_anchor (layerSurface, + ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT | ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | + ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP | ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM); + zwlr_layer_surface_v1_set_keyboard_interactivity (layerSurface, false); + zwlr_layer_surface_v1_add_listener (layerSurface, &layerSurfaceListener, this); + zwlr_layer_surface_v1_set_exclusive_zone (layerSurface, -1); + wl_surface_set_input_region (surface, region); + wl_surface_commit (surface); + wl_display_roundtrip (m_driver->getWaylandContext ()->display); - eglWindow = wl_egl_window_create(surface, size.x * scale, size.y * scale); - eglSurface = m_driver->getEGLContext ()->eglCreatePlatformWindowSurfaceEXT(m_driver->getEGLContext ()->display, m_driver->getEGLContext ()->config, eglWindow, nullptr); - wl_surface_commit(surface); - wl_display_roundtrip(m_driver->getWaylandContext()->display); - wl_display_flush(m_driver->getWaylandContext()->display); + eglWindow = wl_egl_window_create (surface, size.x * scale, size.y * scale); + eglSurface = m_driver->getEGLContext ()->eglCreatePlatformWindowSurfaceEXT ( + m_driver->getEGLContext ()->display, m_driver->getEGLContext ()->config, eglWindow, nullptr); + wl_surface_commit (surface); + wl_display_roundtrip (m_driver->getWaylandContext ()->display); + wl_display_flush (m_driver->getWaylandContext ()->display); - static const auto XCURSORSIZE = getenv("XCURSOR_SIZE") ? std::stoi(getenv("XCURSOR_SIZE")) : 24; - const auto PRCURSORTHEME = wl_cursor_theme_load(getenv("XCURSOR_THEME"), XCURSORSIZE * scale, m_driver->getWaylandContext()->shm); + static const auto XCURSORSIZE = getenv ("XCURSOR_SIZE") ? std::stoi (getenv ("XCURSOR_SIZE")) : 24; + const auto PRCURSORTHEME = + wl_cursor_theme_load (getenv ("XCURSOR_THEME"), XCURSORSIZE * scale, m_driver->getWaylandContext ()->shm); if (!PRCURSORTHEME) - sLog.exception("Failed to get a cursor theme"); + sLog.exception ("Failed to get a cursor theme"); - pointer = wl_cursor_theme_get_cursor(PRCURSORTHEME, "left_ptr"); - cursorSurface = wl_compositor_create_surface(m_driver->getWaylandContext()->compositor); + pointer = wl_cursor_theme_get_cursor (PRCURSORTHEME, "left_ptr"); + cursorSurface = wl_compositor_create_surface (m_driver->getWaylandContext ()->compositor); if (!cursorSurface) - sLog.exception("Failed to get a cursor surface"); + sLog.exception ("Failed to get a cursor surface"); - if (eglMakeCurrent(m_driver->getEGLContext ()->display, eglSurface, eglSurface, m_driver->getEGLContext ()->context) == EGL_FALSE) - sLog.exception("Failed to make egl current"); + if (eglMakeCurrent (m_driver->getEGLContext ()->display, eglSurface, eglSurface, + m_driver->getEGLContext ()->context) == EGL_FALSE) + sLog.exception ("Failed to make egl current"); this->m_driver->getOutput ().reset (); } -CWaylandOpenGLDriver* CWaylandOutputViewport::getDriver () -{ +CWaylandOpenGLDriver* CWaylandOutputViewport::getDriver () { return this->m_driver; } -void CWaylandOutputViewport::makeCurrent () -{ - EGLBoolean result = eglMakeCurrent ( - m_driver->getEGLContext ()->display, - eglSurface, - eglSurface, - m_driver->getEGLContext ()->context - ); +void CWaylandOutputViewport::makeCurrent () { + const EGLBoolean result = eglMakeCurrent (m_driver->getEGLContext ()->display, eglSurface, eglSurface, + m_driver->getEGLContext ()->context); if (result == EGL_FALSE) sLog.error ("Couldn't make egl current"); } -void CWaylandOutputViewport::swapOutput () -{ +void CWaylandOutputViewport::swapOutput () { this->callbackInitialized = true; this->makeCurrent (); frameCallback = wl_surface_frame (surface); wl_callback_add_listener (frameCallback, &frameListener, this); eglSwapBuffers (m_driver->getEGLContext ()->display, this->eglSurface); - wl_surface_set_buffer_scale(surface, scale); - wl_surface_damage_buffer(surface, 0, 0, INT32_MAX, INT32_MAX); - wl_surface_commit(surface); + wl_surface_set_buffer_scale (surface, scale); + wl_surface_damage_buffer (surface, 0, 0, INT32_MAX, INT32_MAX); + wl_surface_commit (surface); } -void CWaylandOutputViewport::resize () -{ +void CWaylandOutputViewport::resize () { if (!this->eglWindow) return; - wl_egl_window_resize(this->eglWindow, this->size.x * this->scale, this->size.y * this->scale, 0, 0); + wl_egl_window_resize (this->eglWindow, this->size.x * this->scale, this->size.y * this->scale, 0, 0); - this->getDriver ()->getOutput().reset(); + this->getDriver ()->getOutput ().reset (); } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h index 671dfca..3ba17df 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h @@ -1,75 +1,73 @@ -#ifdef ENABLE_WAYLAND #pragma once -#include -#include -#include +#ifdef ENABLE_WAYLAND + #include #include #include +#include +#include +#include -#include -#include "COutputViewport.h" #include "../CWaylandOpenGLDriver.h" +#include "COutputViewport.h" +#include struct zwlr_layer_shell_v1; struct zwlr_layer_surface_v1; -namespace WallpaperEngine::Render::Drivers -{ - class CWaylandOpenGLDriver; +namespace WallpaperEngine::Render::Drivers { +class CWaylandOpenGLDriver; - namespace Output - { - class COutputViewport; +namespace Output { +class COutputViewport; - class CWaylandOutputViewport : public COutputViewport - { - public: - CWaylandOutputViewport (CWaylandOpenGLDriver* driver, uint32_t waylandName, struct wl_registry *registry); +class CWaylandOutputViewport final : public COutputViewport { + public: + CWaylandOutputViewport (CWaylandOpenGLDriver* driver, uint32_t waylandName, struct wl_registry* registry); - /** - * @return The wayland driver - */ - CWaylandOpenGLDriver* getDriver (); + /** + * @return The wayland driver + */ + CWaylandOpenGLDriver* getDriver (); - wl_output* output; - glm::ivec2 size; - uint32_t waylandName; - int scale = 1; - bool initialized = false; - bool rendering = false; + wl_output* output; + glm::ivec2 size; + uint32_t waylandName; + int scale = 1; + bool initialized = false; + bool rendering = false; - wl_egl_window* eglWindow = nullptr; - EGLSurface eglSurface = nullptr; - wl_surface* surface = nullptr; - zwlr_layer_surface_v1* layerSurface = nullptr; - wl_callback* frameCallback = nullptr; - glm::dvec2 mousePos = {0, 0}; - wl_cursor* pointer = nullptr; - wl_surface* cursorSurface = nullptr; - bool callbackInitialized = false; + wl_egl_window* eglWindow = nullptr; + EGLSurface eglSurface = nullptr; + wl_surface* surface = nullptr; + zwlr_layer_surface_v1* layerSurface = nullptr; + wl_callback* frameCallback = nullptr; + glm::dvec2 mousePos = {0, 0}; + wl_cursor* pointer = nullptr; + wl_surface* cursorSurface = nullptr; + bool callbackInitialized = false; - void setupLS (); + void setupLS (); - /** - * Activates output's context for drawing - */ - void makeCurrent () override; + /** + * Activates output's context for drawing + */ + void makeCurrent () override; - /** - * Swaps buffers to present data on the viewport - */ - void swapOutput () override; + /** + * Swaps buffers to present data on the viewport + */ + void swapOutput () override; - /** - * Updates the viewport size - */ - void resize (); + /** + * Updates the viewport size + */ + void resize (); - private: - CWaylandOpenGLDriver* m_driver; - }; - } -} + private: + CWaylandOpenGLDriver* m_driver; +}; +} // namespace Output +} // namespace WallpaperEngine::Render::Drivers #endif /* ENABLE_WAYLAND */ \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp index 5af35d8..784087e 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp @@ -1,19 +1,18 @@ -#include "common.h" #include "CX11Output.h" #include "CX11OutputViewport.h" +#include "common.h" -#include -#include #include +#include #include +#include #define FULLSCREEN_CHECK_WAIT_TIME 250 using namespace WallpaperEngine::Render::Drivers::Output; -void CustomXIOErrorExitHandler (Display* dsp, void* userdata) -{ - auto context = static_cast (userdata); +void CustomXIOErrorExitHandler (Display* dsp, void* userdata) { + const auto context = static_cast (userdata); sLog.debugerror ("Critical XServer error detected. Attempting to recover..."); @@ -21,23 +20,19 @@ void CustomXIOErrorExitHandler (Display* dsp, void* userdata) context->reset (); } -int CustomXErrorHandler (Display* dpy, XErrorEvent* event) -{ +int CustomXErrorHandler (Display* dpy, XErrorEvent* event) { sLog.debugerror ("Detected X error"); return 0; } -int CustomXIOErrorHandler (Display* dsp) -{ +int CustomXIOErrorHandler (Display* dsp) { sLog.debugerror ("Detected X error"); return 0; } -CX11Output::CX11Output (CApplicationContext& context, CVideoDriver& driver) : - COutput (context, driver) -{ +CX11Output::CX11Output (CApplicationContext& context, CVideoDriver& driver) : COutput (context, driver) { // do not use previous handler, it might stop the app under weird circumstances XSetErrorHandler (CustomXErrorHandler); XSetIOErrorHandler (CustomXIOErrorHandler); @@ -45,13 +40,11 @@ CX11Output::CX11Output (CApplicationContext& context, CVideoDriver& driver) : this->loadScreenInfo (); } -CX11Output::~CX11Output () -{ +CX11Output::~CX11Output () { this->free (); } -void CX11Output::reset () -{ +void CX11Output::reset () { // first free whatever we have right now this->free (); // re-load screen info @@ -60,11 +53,10 @@ void CX11Output::reset () this->m_driver.getFullscreenDetector ().reset (); } -void CX11Output::free () -{ +void CX11Output::free () { // go through all the viewports and free them - for(const auto& cur : this->m_viewports) - delete cur.second; + for (const auto& [screen, viewport] : this->m_viewports) + delete viewport; this->m_viewports.clear (); @@ -76,28 +68,23 @@ void CX11Output::free () XCloseDisplay (this->m_display); } -void* CX11Output::getImageBuffer () const -{ +void* CX11Output::getImageBuffer () const { return this->m_imageData; } -bool CX11Output::renderVFlip () const -{ +bool CX11Output::renderVFlip () const { return false; } -bool CX11Output::renderMultiple () const -{ +bool CX11Output::renderMultiple () const { return this->m_viewports.size () > 1; } -bool CX11Output::haveImageBuffer () const -{ +bool CX11Output::haveImageBuffer () const { return true; } -void CX11Output::loadScreenInfo () -{ +void CX11Output::loadScreenInfo () { // reset the viewports this->m_viewports.clear (); @@ -109,8 +96,7 @@ void CX11Output::loadScreenInfo () int xrandr_result, xrandr_error; - if (!XRRQueryExtension (this->m_display, &xrandr_result, &xrandr_error)) - { + if (!XRRQueryExtension (this->m_display, &xrandr_result, &xrandr_error)) { sLog.error ("XRandr is not present, cannot detect specified screens, running in window mode"); return; } @@ -120,15 +106,13 @@ void CX11Output::loadScreenInfo () this->m_fullHeight = DisplayHeight (this->m_display, DefaultScreen (this->m_display)); XRRScreenResources* screenResources = XRRGetScreenResources (this->m_display, DefaultRootWindow (this->m_display)); - if (screenResources == nullptr) - { + if (screenResources == nullptr) { sLog.error ("Cannot detect screen sizes using xrandr, running in window mode"); return; } - for (int i = 0; i < screenResources->noutput; i ++) - { - XRROutputInfo* info = XRRGetOutputInfo (this->m_display, screenResources, screenResources->outputs [i]); + for (int i = 0; i < screenResources->noutput; i++) { + const XRROutputInfo* info = XRRGetOutputInfo (this->m_display, screenResources, screenResources->outputs [i]); // screen not in use, ignore it if (info == nullptr || info->connection != RR_Connected) @@ -136,30 +120,21 @@ void CX11Output::loadScreenInfo () XRRCrtcInfo* crtc = XRRGetCrtcInfo (this->m_display, screenResources, info->crtc); - // screen not active, ignore it - if (crtc == nullptr) - continue; + // screen not active, ignore it + if (crtc == nullptr) + continue; // add the screen to the list of screens - this->m_screens.push_back ( - new CX11OutputViewport - { - {crtc->x, crtc->y, crtc->width, crtc->height}, - info->name - } - ); + this->m_screens.push_back (new CX11OutputViewport {{crtc->x, crtc->y, crtc->width, crtc->height}, info->name}); // only keep info of registered screens - if (this->m_context.settings.general.screenBackgrounds.find (info->name) != this->m_context.settings.general.screenBackgrounds.end ()) - { - sLog.out ("Found requested screen: ", info->name, " -> ", crtc->x, "x", crtc->y, ":", crtc->width, "x", crtc->height); + if (this->m_context.settings.general.screenBackgrounds.find (info->name) != + this->m_context.settings.general.screenBackgrounds.end ()) { + sLog.out ("Found requested screen: ", info->name, " -> ", crtc->x, "x", crtc->y, ":", crtc->width, "x", + crtc->height); - this->m_viewports[info->name] = - new CX11OutputViewport - { - {crtc->x, crtc->y, crtc->width, crtc->height}, - info->name - }; + this->m_viewports [info->name] = + new CX11OutputViewport {{crtc->x, crtc->y, crtc->width, crtc->height}, info->name}; } XRRFreeCrtcInfo (crtc); @@ -169,8 +144,7 @@ void CX11Output::loadScreenInfo () bool any = false; - for (auto& o : this->m_screens) - { + for (const auto& o : this->m_screens) { const auto cur = this->m_context.settings.general.screenBackgrounds.find (o->name); if (cur == this->m_context.settings.general.screenBackgrounds.end ()) @@ -180,7 +154,7 @@ void CX11Output::loadScreenInfo () } if (!any) - sLog.exception("No outputs could be initialized, please check the parameters and try again"); + sLog.exception ("No outputs could be initialized, please check the parameters and try again"); // create pixmap so we can draw things in there this->m_pixmap = XCreatePixmap (this->m_display, this->m_root, this->m_fullWidth, this->m_fullHeight, 24); @@ -192,26 +166,29 @@ void CX11Output::loadScreenInfo () // allocate space for the image's data this->m_imageData = new char [this->m_fullWidth * this->m_fullHeight * 4]; // create an image so we can copy it over - this->m_image = XCreateImage (this->m_display, CopyFromParent, 24, ZPixmap, 0, this->m_imageData, this->m_fullWidth, this->m_fullHeight, 32, 0); + this->m_image = XCreateImage (this->m_display, CopyFromParent, 24, ZPixmap, 0, this->m_imageData, this->m_fullWidth, + this->m_fullHeight, 32, 0); // setup driver's render changing the window's size this->m_driver.resizeWindow ({this->m_fullWidth, this->m_fullHeight}); } -void CX11Output::updateRender () const -{ +void CX11Output::updateRender () const { // put the image back into the screen - XPutImage (this->m_display, this->m_pixmap, this->m_gc, this->m_image, 0, 0, 0, 0, this->m_fullWidth, this->m_fullHeight); + XPutImage (this->m_display, this->m_pixmap, this->m_gc, this->m_image, 0, 0, 0, 0, this->m_fullWidth, + this->m_fullHeight); // _XROOTPMAP_ID & ESETROOT_PMAP_ID allow other programs (compositors) to // edit the background. Without these, other programs will clear the screen. // it also forces the compositor to refresh the background (tested with picom) - Atom prop_root = XInternAtom(this->m_display, "_XROOTPMAP_ID", False); - Atom prop_esetroot = XInternAtom(this->m_display, "ESETROOT_PMAP_ID", False); - XChangeProperty(this->m_display, this->m_root, prop_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &this->m_pixmap, 1); - XChangeProperty(this->m_display, this->m_root, prop_esetroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &this->m_pixmap, 1); + const Atom prop_root = XInternAtom (this->m_display, "_XROOTPMAP_ID", False); + const Atom prop_esetroot = XInternAtom (this->m_display, "ESETROOT_PMAP_ID", False); + XChangeProperty (this->m_display, this->m_root, prop_root, XA_PIXMAP, 32, PropModeReplace, + (unsigned char*) &this->m_pixmap, 1); + XChangeProperty (this->m_display, this->m_root, prop_esetroot, XA_PIXMAP, 32, PropModeReplace, + (unsigned char*) &this->m_pixmap, 1); - XClearWindow(this->m_display, this->m_root); - XFlush(this->m_display); + XClearWindow (this->m_display, this->m_root); + XFlush (this->m_display); // check for fullscreen windows and wait until there's none fullscreen while (this->m_driver.getFullscreenDetector ().anythingFullscreen () && this->m_context.state.general.keepRunning) diff --git a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h index e6be9c8..6e255c8 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h @@ -1,40 +1,38 @@ #pragma once +#include #include #include -#include #include -#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "COutput.h" +#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" -namespace WallpaperEngine::Render::Drivers::Output -{ - class CX11Output : public COutput - { - public: - CX11Output (CApplicationContext& context, CVideoDriver& driver); - ~CX11Output (); +namespace WallpaperEngine::Render::Drivers::Output { +class CX11Output final : public COutput { + public: + CX11Output (CApplicationContext& context, CVideoDriver& driver); + ~CX11Output () override; - void reset () override; + void reset () override; - bool renderVFlip () const override; - bool renderMultiple () const override; - bool haveImageBuffer () const override; - void* getImageBuffer () const override; - void updateRender () const override; + bool renderVFlip () const override; + bool renderMultiple () const override; + bool haveImageBuffer () const override; + void* getImageBuffer () const override; + void updateRender () const override; - private: - void loadScreenInfo (); - void free (); + private: + void loadScreenInfo (); + void free (); - Display* m_display; - Pixmap m_pixmap; - Window m_root; - GC m_gc; - char* m_imageData; - XImage* m_image; - std::vector m_screens; - }; -} \ No newline at end of file + Display* m_display; + Pixmap m_pixmap; + Window m_root; + GC m_gc; + char* m_imageData; + XImage* m_image; + std::vector m_screens; +}; +} // namespace WallpaperEngine::Render::Drivers::Output \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.cpp b/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.cpp index cb436bc..d9cfb4f 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.cpp @@ -5,14 +5,8 @@ using namespace WallpaperEngine::Render::Drivers::Output; CX11OutputViewport::CX11OutputViewport (glm::ivec4 viewport, std::string name) : - COutputViewport (viewport, std::move(name)) -{ -} + COutputViewport (viewport, std::move (name)) {} -void CX11OutputViewport::makeCurrent () -{ -} +void CX11OutputViewport::makeCurrent () {} -void CX11OutputViewport::swapOutput () -{ -} \ No newline at end of file +void CX11OutputViewport::swapOutput () {} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.h b/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.h index 42b6280..2738d07 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CX11OutputViewport.h @@ -2,14 +2,12 @@ #include "COutputViewport.h" -namespace WallpaperEngine::Render::Drivers::Output -{ - class CX11OutputViewport : public COutputViewport - { - public: - CX11OutputViewport (glm::ivec4 viewport, std::string name); +namespace WallpaperEngine::Render::Drivers::Output { +class CX11OutputViewport final : public COutputViewport { + public: + CX11OutputViewport (glm::ivec4 viewport, std::string name); - void makeCurrent () override; - void swapOutput () override; - }; -} + void makeCurrent () override; + void swapOutput () override; +}; +} // namespace WallpaperEngine::Render::Drivers::Output diff --git a/src/WallpaperEngine/Render/Helpers/CContextAware.cpp b/src/WallpaperEngine/Render/Helpers/CContextAware.cpp index 4786385..8eeab7b 100644 --- a/src/WallpaperEngine/Render/Helpers/CContextAware.cpp +++ b/src/WallpaperEngine/Render/Helpers/CContextAware.cpp @@ -1,24 +1,13 @@ #include "CContextAware.h" -namespace WallpaperEngine::Render::Helpers -{ - CContextAware::CContextAware (CContextAware& from) : - CContextAware (from.getContext ()) - { - } +namespace WallpaperEngine::Render::Helpers { +CContextAware::CContextAware (const CContextAware& from) : CContextAware (from.getContext ()) {} - CContextAware::CContextAware (CContextAware* from) : - CContextAware (from->getContext ()) - { - } +CContextAware::CContextAware (const CContextAware* from) : CContextAware (from->getContext ()) {} - CContextAware::CContextAware (CRenderContext& context) : - m_context (context) - { - } +CContextAware::CContextAware (CRenderContext& context) : m_context (context) {} - CRenderContext& CContextAware::getContext () const - { - return this->m_context; - } -} \ No newline at end of file +CRenderContext& CContextAware::getContext () const { + return this->m_context; +} +} // namespace WallpaperEngine::Render::Helpers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Helpers/CContextAware.h b/src/WallpaperEngine/Render/Helpers/CContextAware.h index 23f3075..352f923 100644 --- a/src/WallpaperEngine/Render/Helpers/CContextAware.h +++ b/src/WallpaperEngine/Render/Helpers/CContextAware.h @@ -1,35 +1,33 @@ #pragma once -namespace WallpaperEngine::Render -{ - class CRenderContext; +namespace WallpaperEngine::Render { +class CRenderContext; - namespace Helpers - { - /** - * Small helper class that provides access to the CRenderContext - * in use currently - */ - class CContextAware - { - public: - /** - * @param from Object to get the render context from - */ - CContextAware (CContextAware& from); - /** - * @param from Object to get the render context from - */ - explicit CContextAware (CContextAware* from); - explicit CContextAware (CRenderContext& context); +namespace Helpers { +/** + * Small helper class that provides access to the CRenderContext + * in use currently + */ +class CContextAware { + public: + virtual ~CContextAware () = default; + /** + * @param from Object to get the render context from + */ + CContextAware (const CContextAware& from); + /** + * @param from Object to get the render context from + */ + explicit CContextAware (const CContextAware* from); + explicit CContextAware (CRenderContext& context); - /** - * @return The CRenderContext in use right now - */ - [[nodiscard]] CRenderContext& getContext () const; + /** + * @return The CRenderContext in use right now + */ + [[nodiscard]] CRenderContext& getContext () const; - private: - CRenderContext& m_context; - }; - } -} \ No newline at end of file + private: + CRenderContext& m_context; +}; +} // namespace Helpers +} // namespace WallpaperEngine::Render \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/CEffect.cpp b/src/WallpaperEngine/Render/Objects/CEffect.cpp index dbf1e6e..1f3dc7a 100644 --- a/src/WallpaperEngine/Render/Objects/CEffect.cpp +++ b/src/WallpaperEngine/Render/Objects/CEffect.cpp @@ -3,26 +3,20 @@ using namespace WallpaperEngine::Render; using namespace WallpaperEngine::Render::Objects; -CEffect::CEffect (CImage* image, Core::Objects::CEffect* effect) : - m_image (image), - m_effect (effect) -{ +CEffect::CEffect (CImage* image, Core::Objects::CEffect* effect) : m_image (image), m_effect (effect) { this->generateFBOs (); this->generatePasses (); } -CImage* CEffect::getImage () const -{ +CImage* CEffect::getImage () const { return this->m_image; } -const std::vector& CEffect::getMaterials () const -{ +const std::vector& CEffect::getMaterials () const { return this->m_materials; } -const CFBO* CEffect::findFBO (const std::string& name) const -{ +const CFBO* CEffect::findFBO (const std::string& name) const { for (const auto& cur : this->m_fbos) if (cur->getName () == name) return cur; @@ -30,33 +24,24 @@ const CFBO* CEffect::findFBO (const std::string& name) const return nullptr; } -void CEffect::generatePasses () -{ +void CEffect::generatePasses () { for (const auto& cur : this->m_effect->getMaterials ()) this->m_materials.emplace_back (new Effects::CMaterial (this, cur)); } -void CEffect::generateFBOs () -{ - for (const auto& cur : this->m_effect->getFbos ()) - { +void CEffect::generateFBOs () { + for (const auto& cur : this->m_effect->getFbos ()) { // TODO: IS THAT DIVISION OKAY? SHOULDN'T IT BE A MULTIPLICATION? WTF? - this->m_fbos.push_back ( - new CFBO ( - cur->getName (), - ITexture::TextureFormat::ARGB8888, // TODO: CHANGE - this->m_image->getTexture ()->getFlags (), // TODO: CHANGE - cur->getScale (), - this->m_image->getSize ().x / cur->getScale (), - this->m_image->getSize ().y / cur->getScale (), - this->m_image->getSize ().x / cur->getScale (), - this->m_image->getSize ().y / cur->getScale () - ) - ); + this->m_fbos.push_back (new CFBO (cur->getName (), + ITexture::TextureFormat::ARGB8888, // TODO: CHANGE + this->m_image->getTexture ()->getFlags (), // TODO: CHANGE + cur->getScale (), this->m_image->getSize ().x / cur->getScale (), + this->m_image->getSize ().y / cur->getScale (), + this->m_image->getSize ().x / cur->getScale (), + this->m_image->getSize ().y / cur->getScale ())); } } -bool CEffect::isVisible () const -{ +bool CEffect::isVisible () const { return this->m_effect->isVisible (); } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/CEffect.h b/src/WallpaperEngine/Render/Objects/CEffect.h index 3469b36..06748cb 100644 --- a/src/WallpaperEngine/Render/Objects/CEffect.h +++ b/src/WallpaperEngine/Render/Objects/CEffect.h @@ -1,39 +1,36 @@ #pragma once -#include "WallpaperEngine/Render/Objects/CImage.h" #include "WallpaperEngine/Render/CFBO.h" -#include "WallpaperEngine/Render/Objects/Effects/CPass.h" +#include "WallpaperEngine/Render/Objects/CImage.h" #include "WallpaperEngine/Render/Objects/Effects/CMaterial.h" +#include "WallpaperEngine/Render/Objects/Effects/CPass.h" -namespace WallpaperEngine::Render::Objects::Effects -{ - class CMaterial; +namespace WallpaperEngine::Render::Objects::Effects { +class CMaterial; } -namespace WallpaperEngine::Render::Objects -{ - class CImage; +namespace WallpaperEngine::Render::Objects { +class CImage; - class CEffect - { - public: - CEffect (CImage* image, Core::Objects::CEffect* effect); +class CEffect { + public: + CEffect (CImage* image, Core::Objects::CEffect* effect); - CImage* getImage () const; + CImage* getImage () const; - const std::vector& getMaterials () const; + const std::vector& getMaterials () const; - const CFBO* findFBO (const std::string& name) const; - bool isVisible () const; + const CFBO* findFBO (const std::string& name) const; + bool isVisible () const; - private: - void generatePasses (); - void generateFBOs (); + private: + void generatePasses (); + void generateFBOs (); - CImage* m_image; - Core::Objects::CEffect* m_effect; + CImage* m_image; + Core::Objects::CEffect* m_effect; - std::vector m_fbos; - std::vector m_materials; - }; -} + std::vector m_fbos; + std::vector m_materials; +}; +} // namespace WallpaperEngine::Render::Objects diff --git a/src/WallpaperEngine/Render/Objects/CImage.cpp b/src/WallpaperEngine/Render/Objects/CImage.cpp index 0d7e38b..9d46b31 100644 --- a/src/WallpaperEngine/Render/Objects/CImage.cpp +++ b/src/WallpaperEngine/Render/Objects/CImage.cpp @@ -1,5 +1,5 @@ -#include #include "CImage.h" +#include using namespace WallpaperEngine; using namespace WallpaperEngine::Render::Objects; @@ -23,13 +23,12 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : m_modelViewProjectionCopyInverse (), m_modelViewProjectionPass (glm::mat4 (1.0)), m_modelViewProjectionPassInverse (glm::inverse (m_modelViewProjectionPass)), - m_pos () -{ + m_pos () { auto projection = this->getScene ()->getScene ()->getOrthogonalProjection (); // get scene width and height to calculate positions - auto scene_width = static_cast (projection->getWidth ()); - auto scene_height = static_cast (projection->getHeight ()); + auto scene_width = static_cast (projection->getWidth ()); + auto scene_height = static_cast (projection->getHeight ()); glm::vec3 origin = this->getImage ()->getOrigin (); glm::vec2 size = this->getSize (); @@ -37,10 +36,9 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : // fullscreen layers should use the whole projection's size // TODO: WHAT SHOULD AUTOSIZE DO? - if (this->getImage ()->isFullscreen ()) - { - size = { scene_width, scene_height }; - origin = { scene_width / 2, scene_height / 2, 0 }; + if (this->getImage ()->isFullscreen ()) { + size = {scene_width, scene_height}; + origin = {scene_width / 2, scene_height / 2, 0}; // TODO: CHANGE ALIGNMENT TOO? } @@ -53,24 +51,18 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : this->m_pos.z = origin.x + (scaledSize.x / 2); this->m_pos.y = origin.y - (scaledSize.y / 2); - if (this->getImage ()->getAlignment ().find ("top") != std::string::npos) - { + if (this->getImage ()->getAlignment ().find ("top") != std::string::npos) { this->m_pos.y -= scaledSize.y / 2; this->m_pos.w -= scaledSize.y / 2; - } - else if (this->getImage ()->getAlignment ().find ("bottom") != std::string::npos) - { + } else if (this->getImage ()->getAlignment ().find ("bottom") != std::string::npos) { this->m_pos.y += scaledSize.y / 2; this->m_pos.w += scaledSize.y / 2; } - if (this->getImage ()->getAlignment ().find ("left") != std::string::npos) - { + if (this->getImage ()->getAlignment ().find ("left") != std::string::npos) { this->m_pos.x += scaledSize.x / 2; this->m_pos.z += scaledSize.x / 2; - } - else if (this->getImage ()->getAlignment ().find ("right") != std::string::npos) - { + } else if (this->getImage ()->getAlignment ().find ("right") != std::string::npos) { this->m_pos.x -= scaledSize.x / 2; this->m_pos.z -= scaledSize.x / 2; } @@ -84,31 +76,20 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : // detect texture (if any) auto textures = (*this->m_image->getMaterial ()->getPasses ().begin ())->getTextures (); - if (!textures.empty()) - { + if (!textures.empty ()) { std::string textureName = *textures.begin (); - if (textureName.find ("_rt_") == 0) - { + if (textureName.find ("_rt_") == 0) { this->m_texture = this->getScene ()->findFBO (textureName); - } - else - { + } else { // get the first texture on the first pass (this one represents the image assigned to this object) this->m_texture = this->getContext ().resolveTexture (textureName); } - } - else - { - // TODO: create a dummy texture of correct size, fbo constructors should be enough, but this should be properly handled - this->m_texture = new CFBO ( - "", - ITexture::TextureFormat::ARGB8888, - ITexture::TextureFlags::NoFlags, - 1, - size.x, size.y, - size.x, size.y - ); + } else { + // TODO: create a dummy texture of correct size, fbo constructors should be enough, but this should be properly + // handled + this->m_texture = new CFBO ("", ITexture::TextureFormat::ARGB8888, ITexture::TextureFlags::NoFlags, 1, size.x, + size.y, size.x, size.y); } // register both FBOs into the scene @@ -118,52 +99,41 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : nameA << "_rt_imageLayerComposite_" << this->getImage ()->getId () << "_a"; nameB << "_rt_imageLayerComposite_" << this->getImage ()->getId () << "_b"; - this->m_currentMainFBO = this->m_mainFBO = scene->createFBO ( - nameA.str (), - ITexture::TextureFormat::ARGB8888, - this->m_texture->getFlags (), - 1, - this->m_texture->getRealWidth (), this->m_texture->getRealHeight (), - this->m_texture->getRealWidth (), this->m_texture->getRealHeight () - ); - this->m_currentSubFBO = this->m_subFBO = scene->createFBO ( - nameB.str (), - ITexture::TextureFormat::ARGB8888, - this->m_texture->getFlags (), - 1, - this->m_texture->getRealWidth (), this->m_texture->getRealHeight (), - this->m_texture->getRealWidth (), this->m_texture->getRealHeight () - ); + this->m_currentMainFBO = this->m_mainFBO = + scene->createFBO (nameA.str (), ITexture::TextureFormat::ARGB8888, this->m_texture->getFlags (), 1, + this->m_texture->getRealWidth (), this->m_texture->getRealHeight (), + this->m_texture->getRealWidth (), this->m_texture->getRealHeight ()); + this->m_currentSubFBO = this->m_subFBO = + scene->createFBO (nameB.str (), ITexture::TextureFormat::ARGB8888, this->m_texture->getFlags (), 1, + this->m_texture->getRealWidth (), this->m_texture->getRealHeight (), + this->m_texture->getRealWidth (), this->m_texture->getRealHeight ()); // build a list of vertices, these might need some change later (or maybe invert the camera) - GLfloat sceneSpacePosition [] = { - this->m_pos.x, this->m_pos.y, 0.0f, - this->m_pos.x, this->m_pos.w, 0.0f, - this->m_pos.z, this->m_pos.y, 0.0f, - this->m_pos.z, this->m_pos.y, 0.0f, - this->m_pos.x, this->m_pos.w, 0.0f, - this->m_pos.z, this->m_pos.w, 0.0f - }; + GLfloat sceneSpacePosition [] = {this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f, + this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f, + this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f}; float width = 1.0f; float height = 1.0f; - if (this->getTexture ()->isAnimated ()) - { + if (this->getTexture ()->isAnimated ()) { // animated images use different coordinates as they're essentially a texture atlas - width = static_cast (this->getTexture ()->getRealWidth ()) / static_cast (this->getTexture ()->getTextureWidth ()); - height = static_cast (this->getTexture ()->getRealHeight ()) / static_cast (this->getTexture ()->getTextureHeight ()); + width = static_cast (this->getTexture ()->getRealWidth ()) / + static_cast (this->getTexture ()->getTextureWidth ()); + height = static_cast (this->getTexture ()->getRealHeight ()) / + static_cast (this->getTexture ()->getTextureHeight ()); } - // calculate the correct texCoord limits for the texture based on the texture screen size and real size + // calculate the correct texCoord limits for the texture based on the texture screen size and real size else if (this->getTexture () != nullptr && - (this->getTexture ()->getTextureWidth () != this->getTexture ()->getRealWidth () || - this->getTexture ()->getTextureHeight () != this->getTexture ()->getRealHeight ()) - ) { + (this->getTexture ()->getTextureWidth () != this->getTexture ()->getRealWidth () || + this->getTexture ()->getTextureHeight () != this->getTexture ()->getRealHeight ())) { uint32_t x = 1; uint32_t y = 1; - while (x < size.x) x <<= 1; - while (y < size.y) y <<= 1; + while (x < size.x) + x <<= 1; + while (y < size.y) + y <<= 1; width = scaledSize.x / x; height = scaledSize.y / y; @@ -173,8 +143,7 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : float x = 0.0f; float y = 0.0f; - if (this->getTexture ()->isAnimated ()) - { + if (this->getTexture ()->isAnimated ()) { // animations should be copied completely x = 0.0f; y = 0.0f; @@ -187,15 +156,13 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : GLfloat realX = 0.0; GLfloat realY = 0.0; - if (this->getImage ()->isPassthrough()) - { + if (this->getImage ()->isPassthrough ()) { x = -((this->m_pos.x + (scene_width / 2)) / size.x); y = -((this->m_pos.w + (scene_height / 2)) / size.y); height = (this->m_pos.y + (scene_height / 2)) / size.y; width = (this->m_pos.z + (scene_width / 2)) / size.x; - if (this->getImage ()->isFullscreen ()) - { + if (this->getImage ()->isFullscreen ()) { realX = -1.0; realY = -1.0; realWidth = 1.0; @@ -203,41 +170,15 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : } } - GLfloat texcoordCopy [] = { - x, height, - x, y, - width, height, - width, height, - x, y, - width, y - }; + GLfloat texcoordCopy [] = {x, height, x, y, width, height, width, height, x, y, width, y}; - GLfloat copySpacePosition [] = { - realX, realHeight, 0.0f, - realX, realY, 0.0f, - realWidth, realHeight, 0.0f, - realWidth, realHeight, 0.0f, - realX, realY, 0.0f, - realWidth, realY, 0.0f - }; + GLfloat copySpacePosition [] = {realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f, + realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f}; - GLfloat texcoordPass [] = { - 0.0f, 1.0f, - 0.0f, 0.0f, - 1.0f, 1.0f, - 1.0f, 1.0f, - 0.0f, 0.0f, - 1.0f, 0.0f - }; + GLfloat texcoordPass [] = {0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f}; - GLfloat passSpacePosition [] = { - -1.0, 1.0, 0.0f, - -1.0, -1.0, 0.0f, - 1.0, 1.0, 0.0f, - 1.0, 1.0, 0.0f, - -1.0, -1.0, 0.0f, - 1.0, -1.0, 0.0f - }; + GLfloat passSpacePosition [] = {-1.0, 1.0, 0.0f, -1.0, -1.0, 0.0f, 1.0, 1.0, 0.0f, + 1.0, 1.0, 0.0f, -1.0, -1.0, 0.0f, 1.0, -1.0, 0.0f}; // bind vertex list to the openGL buffers glGenBuffers (1, &this->m_sceneSpacePosition); @@ -262,19 +203,17 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordPass), texcoordPass, GL_STATIC_DRAW); this->m_modelViewProjectionScreen = - this->getScene ()->getCamera ()->getProjection () * - this->getScene ()->getCamera ()->getLookAt (); + this->getScene ()->getCamera ()->getProjection () * this->getScene ()->getCamera ()->getLookAt (); this->m_modelViewProjectionScreenInverse = glm::inverse (this->m_modelViewProjectionScreen); - this->m_modelViewProjectionCopy = glm::ortho (0.0, size.x, 0.0, size.y); + this->m_modelViewProjectionCopy = glm::ortho (0.0, size.x, 0.0, size.y); this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy); - this->m_modelMatrix = glm::ortho (0.0, size.x, 0.0, size.y); + this->m_modelMatrix = glm::ortho (0.0, size.x, 0.0, size.y); this->m_viewProjectionMatrix = glm::mat4 (1.0); } -void CImage::setup () -{ +void CImage::setup () { // do not double-init stuff, that's bad! if (this->m_initialized) return; @@ -282,15 +221,15 @@ void CImage::setup () // TODO: SUPPORT PASSTHROUGH (IT'S A SHADER) // passthrough images without effects are bad, do not draw them - if (this->getImage ()->isPassthrough() && this->getImage ()->getEffects ().empty ()) + if (this->getImage ()->isPassthrough () && this->getImage ()->getEffects ().empty ()) return; { // generate the main material used to render the image this->m_material = new Effects::CMaterial ( - new CEffect (this, new Core::Objects::CEffect ("", "", "", "", this->m_image, Core::UserSettings::CUserSettingBoolean::fromScalar (true))), - this->m_image->getMaterial () - ); + new CEffect (this, new Core::Objects::CEffect ("", "", "", "", this->m_image, + Core::UserSettings::CUserSettingBoolean::fromScalar (true))), + this->m_image->getMaterial ()); // add blendmode to the combos for (const auto& cur : this->m_material->getPasses ()) @@ -298,11 +237,9 @@ void CImage::setup () } // prepare the passes list - if (!this->getImage ()->getEffects ().empty ()) - { + if (!this->getImage ()->getEffects ().empty ()) { // generate the effects used by this material - for (const auto& cur : this->getImage ()->getEffects ()) - { + for (const auto& cur : this->getImage ()->getEffects ()) { auto effect = new CEffect (this, cur); for (const auto& material : effect->getMaterials ()) @@ -313,18 +250,18 @@ void CImage::setup () } } - if (this->m_image->getColorBlendMode () > 0) - { - auto material = Core::Objects::Images::CMaterial::fromFile ("materials/util/effectpassthrough.json", this->getContainer ()); + if (this->m_image->getColorBlendMode () > 0) { + const auto material = + Core::Objects::Images::CMaterial::fromFile ("materials/util/effectpassthrough.json", this->getContainer ()); // effectpasshthrough only has one pass (*material->getPasses ().begin ())->insertCombo ("BLENDMODE", this->m_image->getColorBlendMode ()); // generate the main material used to render the image - this->m_colorBlendMaterial = new Effects::CMaterial( - new CEffect (this, new Core::Objects::CEffect ("", "", "", "", this->m_image, Core::UserSettings::CUserSettingBoolean::fromScalar (true))), - material - ); + this->m_colorBlendMaterial = new Effects::CMaterial ( + new CEffect (this, new Core::Objects::CEffect ("", "", "", "", this->m_image, + Core::UserSettings::CUserSettingBoolean::fromScalar (true))), + material); // add blendmode to the combos for (const auto& cur : this->m_colorBlendMaterial->getPasses ()) @@ -332,10 +269,9 @@ void CImage::setup () } // if there's more than one pass the blendmode has to be moved from the beginning to the end - if (this->m_passes.size () > 1) - { - auto first = this->m_passes.begin (); - auto last = this->m_passes.rbegin (); + if (this->m_passes.size () > 1) { + const auto first = this->m_passes.begin (); + const auto last = this->m_passes.rbegin (); (*last)->getPass ()->setBlendingMode ((*first)->getPass ()->getBlendingMode ()); (*first)->getPass ()->setBlendingMode ("normal"); @@ -351,8 +287,7 @@ void CImage::setup () this->m_initialized = true; } -void CImage::setupPasses () -{ +void CImage::setupPasses () { // do a pass on everything and setup proper inputs and values const CFBO* drawTo = this->m_currentMainFBO; const ITexture* asInput = this->getTexture (); @@ -362,22 +297,21 @@ void CImage::setupPasses () auto end = this->m_passes.end (); bool first = true; - for (; cur != end; cur ++) - { + for (; cur != end; ++cur) { // TODO: PROPERLY CHECK EFFECT'S VISIBILITY AND TAKE IT INTO ACCOUNT Effects::CPass* pass = *cur; const CFBO* prevDrawTo = drawTo; GLuint spacePosition = (first) ? this->getCopySpacePosition () : this->getPassSpacePosition (); - glm::mat4* projection = (first) ? &this->m_modelViewProjectionCopy : &this->m_modelViewProjectionPass; - glm::mat4* inverseProjection = (first) ? &this->m_modelViewProjectionCopyInverse : &this->m_modelViewProjectionPassInverse; + const glm::mat4* projection = (first) ? &this->m_modelViewProjectionCopy : &this->m_modelViewProjectionPass; + const glm::mat4* inverseProjection = + (first) ? &this->m_modelViewProjectionCopyInverse : &this->m_modelViewProjectionPassInverse; first = false; pass->setModelMatrix (&this->m_modelMatrix); pass->setViewProjectionMatrix (&this->m_viewProjectionMatrix); // set viewport and target texture if needed - if (pass->getMaterial ()->getMaterial ()->hasTarget ()) - { + if (pass->getMaterial ()->getMaterial ()->hasTarget ()) { // setup target texture std::string target = pass->getMaterial ()->getMaterial ()->getTarget (); drawTo = pass->getMaterial ()->getEffect ()->findFBO (target); @@ -388,9 +322,8 @@ void CImage::setupPasses () // this one throws if no fbo was found drawTo = this->getScene ()->findFBO (target); } - // determine if it's the last element in the list as this is a screen-copy-like process - else if (std::next (cur) == end && this->getImage ()->isVisible ()) - { + // determine if it's the last element in the list as this is a screen-copy-like process + else if (std::next (cur) == end && this->getImage ()->isVisible ()) { // TODO: PROPERLY CHECK EFFECT'S VISIBILITY AND TAKE IT INTO ACCOUNT spacePosition = this->getSceneSpacePosition (); drawTo = this->getScene ()->getFBO (); @@ -413,8 +346,7 @@ void CImage::setupPasses () } } -void CImage::pinpongFramebuffer (const CFBO** drawTo, const ITexture** asInput) -{ +void CImage::pinpongFramebuffer (const CFBO** drawTo, const ITexture** asInput) { // temporarily store FBOs used CFBO* currentMainFBO = this->m_currentMainFBO; CFBO* currentSubFBO = this->m_currentSubFBO; @@ -429,8 +361,7 @@ void CImage::pinpongFramebuffer (const CFBO** drawTo, const ITexture** asInput) this->m_currentSubFBO = currentMainFBO; } -void CImage::render () -{ +void CImage::render () { // do not try to render something that did not initialize successfully // non-visible materials do need to be rendered if (!this->m_initialized) @@ -448,20 +379,18 @@ void CImage::render () if (this->getScene ()->getScene ()->isBloom () && this->getId () == 0xFFFFFFFF) str += "bloom"; - else - { - str += this->getImage ()->getName () + - " (" + std::to_string (this->getId ()) + ", " + this->getImage ()->getMaterial ()->getName () + ")"; + else { + str += this->getImage ()->getName () + " (" + std::to_string (this->getId ()) + ", " + + this->getImage ()->getMaterial ()->getName () + ")"; } glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ()); #endif /* DEBUG */ auto cur = this->m_passes.begin (); - auto end = this->m_passes.end (); + const auto end = this->m_passes.end (); - for (; cur != end; cur ++) - { + for (; cur != end; ++cur) { // TODO: PROPERLY CHECK EFFECT'S VISIBILITY AND TAKE IT INTO ACCOUNT if (std::next (cur) == end) glColorMask (true, true, true, false); @@ -474,73 +403,59 @@ void CImage::render () #endif /* DEBUG */ } -void CImage::updateScreenSpacePosition () -{ - double parallaxAmount = this->getScene ()->getScene ()->getCameraParallaxAmount (); - glm::vec2 depth = this->getImage ()->getParallaxDepth (); - glm::vec2* displacement = this->getScene ()->getParallaxDisplacement (); +void CImage::updateScreenSpacePosition () { + const double parallaxAmount = this->getScene ()->getScene ()->getCameraParallaxAmount (); + const glm::vec2 depth = this->getImage ()->getParallaxDepth (); + const glm::vec2* displacement = this->getScene ()->getParallaxDisplacement (); float x = (depth.x + parallaxAmount) * displacement->x * this->getSize ().x; float y = (depth.y + parallaxAmount) * displacement->y * this->getSize ().x; - this->m_modelViewProjectionScreen = - glm::translate ( - this->getScene ()->getCamera ()->getProjection () * - this->getScene ()->getCamera ()->getLookAt (), - {x, y, 0.0f} - ); + this->m_modelViewProjectionScreen = glm::translate (this->getScene ()->getCamera ()->getProjection () * + this->getScene ()->getCamera ()->getLookAt (), + {x, y, 0.0f}); } -const ITexture* CImage::getTexture () const -{ +const ITexture* CImage::getTexture () const { return this->m_texture; } -double CImage::getAnimationTime () const -{ +double CImage::getAnimationTime () const { return this->m_animationTime; } -const Core::Objects::CImage* CImage::getImage () const -{ +const Core::Objects::CImage* CImage::getImage () const { return this->m_image; } -const std::vector& CImage::getEffects () const -{ +const std::vector& CImage::getEffects () const { return this->m_effects; } -glm::vec2 CImage::getSize() const -{ +glm::vec2 CImage::getSize () const { if (this->m_texture == nullptr) return this->getImage ()->getSize (); return {this->m_texture->getRealWidth (), this->m_texture->getRealHeight ()}; } -GLuint CImage::getSceneSpacePosition () const -{ +GLuint CImage::getSceneSpacePosition () const { return this->m_sceneSpacePosition; } -GLuint CImage::getCopySpacePosition () const -{ +GLuint CImage::getCopySpacePosition () const { return this->m_copySpacePosition; } -GLuint CImage::getPassSpacePosition () const -{ +GLuint CImage::getPassSpacePosition () const { return this->m_passSpacePosition; } -GLuint CImage::getTexCoordCopy () const -{ +GLuint CImage::getTexCoordCopy () const { return this->m_texcoordCopy; } -GLuint CImage::getTexCoordPass () const -{ +GLuint CImage::getTexCoordPass () const { return this->m_texcoordPass; } diff --git a/src/WallpaperEngine/Render/Objects/CImage.h b/src/WallpaperEngine/Render/Objects/CImage.h index c56ce6f..0429920 100644 --- a/src/WallpaperEngine/Render/Objects/CImage.h +++ b/src/WallpaperEngine/Render/Objects/CImage.h @@ -2,11 +2,11 @@ #include "WallpaperEngine/Core/Objects/CImage.h" -#include "WallpaperEngine/Render/Objects/Effects/CMaterial.h" -#include "WallpaperEngine/Render/Objects/Effects/CPass.h" -#include "WallpaperEngine/Render/Objects/CEffect.h" #include "WallpaperEngine/Render/CObject.h" #include "WallpaperEngine/Render/CScene.h" +#include "WallpaperEngine/Render/Objects/CEffect.h" +#include "WallpaperEngine/Render/Objects/Effects/CMaterial.h" +#include "WallpaperEngine/Render/Objects/Effects/CPass.h" #include "WallpaperEngine/Render/Shaders/Compiler.h" @@ -17,85 +17,84 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Assets; -namespace WallpaperEngine::Render::Objects::Effects -{ - class CMaterial; - class CPass; -} +namespace WallpaperEngine::Render::Objects::Effects { +class CMaterial; +class CPass; +} // namespace WallpaperEngine::Render::Objects::Effects -namespace WallpaperEngine::Render::Objects -{ - class CEffect; +namespace WallpaperEngine::Render::Objects { +class CEffect; - class CImage : public CObject - { - friend CObject; - public: - CImage (CScene* scene, Core::Objects::CImage* image); +class CImage final : public CObject { + friend CObject; - void setup (); - void render () override; + public: + CImage (CScene* scene, Core::Objects::CImage* image); - const Core::Objects::CImage* getImage () const; - const std::vector& getEffects () const; - glm::vec2 getSize() const; + void setup (); + void render () override; - GLuint getSceneSpacePosition () const; - GLuint getCopySpacePosition () const; - GLuint getPassSpacePosition () const; - GLuint getTexCoordCopy () const; - GLuint getTexCoordPass () const; - const ITexture* getTexture () const; - double getAnimationTime () const; + const Core::Objects::CImage* getImage () const; + const std::vector& getEffects () const; + glm::vec2 getSize () const; - /** - * Performs a ping-pong on the available framebuffers to be able to continue rendering things to them - * - * @param drawTo The framebuffer to use - * @param asInput The last texture used as output (if needed) - */ - void pinpongFramebuffer (const CFBO** drawTo, const ITexture** asInput); + GLuint getSceneSpacePosition () const; + GLuint getCopySpacePosition () const; + GLuint getPassSpacePosition () const; + GLuint getTexCoordCopy () const; + GLuint getTexCoordPass () const; + const ITexture* getTexture () const; + double getAnimationTime () const; - protected: - static const std::string Type; + /** + * Performs a ping-pong on the available framebuffers to be able to continue rendering things to them + * + * @param drawTo The framebuffer to use + * @param asInput The last texture used as output (if needed) + */ + void pinpongFramebuffer (const CFBO** drawTo, const ITexture** asInput); - void setupPasses (); + protected: + static const std::string Type; - void updateScreenSpacePosition (); - private: - const ITexture* m_texture; - GLuint m_sceneSpacePosition; - GLuint m_copySpacePosition; - GLuint m_passSpacePosition; - GLuint m_texcoordCopy; - GLuint m_texcoordPass; + void setupPasses (); - glm::mat4 m_modelViewProjectionScreen; - glm::mat4 m_modelViewProjectionPass; - glm::mat4 m_modelViewProjectionCopy; - glm::mat4 m_modelViewProjectionScreenInverse; - glm::mat4 m_modelViewProjectionPassInverse; - glm::mat4 m_modelViewProjectionCopyInverse; + void updateScreenSpacePosition (); - glm::mat4 m_modelMatrix; - glm::mat4 m_viewProjectionMatrix; + private: + const ITexture* m_texture; + GLuint m_sceneSpacePosition; + GLuint m_copySpacePosition; + GLuint m_passSpacePosition; + GLuint m_texcoordCopy; + GLuint m_texcoordPass; - CFBO* m_mainFBO; - CFBO* m_subFBO; - CFBO* m_currentMainFBO; - CFBO* m_currentSubFBO; + glm::mat4 m_modelViewProjectionScreen; + glm::mat4 m_modelViewProjectionPass; + glm::mat4 m_modelViewProjectionCopy; + glm::mat4 m_modelViewProjectionScreenInverse; + glm::mat4 m_modelViewProjectionPassInverse; + glm::mat4 m_modelViewProjectionCopyInverse; - Core::Objects::CImage* m_image; + glm::mat4 m_modelMatrix; + glm::mat4 m_viewProjectionMatrix; - std::vector m_effects; - Effects::CMaterial* m_material; - Effects::CMaterial* m_colorBlendMaterial; - std::vector m_passes; + CFBO* m_mainFBO; + CFBO* m_subFBO; + CFBO* m_currentMainFBO; + CFBO* m_currentSubFBO; - glm::vec4 m_pos; + Core::Objects::CImage* m_image; - double m_animationTime; + std::vector m_effects; + Effects::CMaterial* m_material; + Effects::CMaterial* m_colorBlendMaterial; + std::vector m_passes; - bool m_initialized; - }; -} + glm::vec4 m_pos; + + double m_animationTime; + + bool m_initialized; +}; +} // namespace WallpaperEngine::Render::Objects diff --git a/src/WallpaperEngine/Render/Objects/CSound.cpp b/src/WallpaperEngine/Render/Objects/CSound.cpp index 0aca8e7..68ac66e 100644 --- a/src/WallpaperEngine/Render/Objects/CSound.cpp +++ b/src/WallpaperEngine/Render/Objects/CSound.cpp @@ -4,18 +4,13 @@ using namespace WallpaperEngine::Render::Objects; -CSound::CSound (CScene* scene, Core::Objects::CSound* sound) : - CObject (scene, Type, sound), - m_sound (sound) -{ +CSound::CSound (CScene* scene, Core::Objects::CSound* sound) : CObject (scene, Type, sound), m_sound (sound) { if (this->getContext ().getApp ().getContext ().settings.audio.enabled) this->load (); } -void CSound::load () -{ - for (const auto& cur : this->m_sound->getSounds ()) - { +void CSound::load () { + for (const auto& cur : this->m_sound->getSounds ()) { uint32_t filesize = 0; const void* filebuffer = this->getContainer ()->readFile (cur, &filesize); @@ -31,8 +26,6 @@ void CSound::load () } } -void CSound::render () -{ -} +void CSound::render () {} const std::string CSound::Type = "sound"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/CSound.h b/src/WallpaperEngine/Render/Objects/CSound.h index 5f6aaff..8307e61 100644 --- a/src/WallpaperEngine/Render/Objects/CSound.h +++ b/src/WallpaperEngine/Render/Objects/CSound.h @@ -2,29 +2,27 @@ #include "WallpaperEngine/Core/Objects/CSound.h" -#include "WallpaperEngine/Render/CObject.h" #include "WallpaperEngine/Audio/CAudioStream.h" +#include "WallpaperEngine/Render/CObject.h" using namespace WallpaperEngine; -namespace WallpaperEngine::Render::Objects -{ - class CSound : public CObject - { - public: - CSound (CScene* scene, Core::Objects::CSound* sound); +namespace WallpaperEngine::Render::Objects { +class CSound final : public CObject { + public: + CSound (CScene* scene, Core::Objects::CSound* sound); - void render () override; + void render () override; - protected: - static const std::string Type; + protected: + static const std::string Type; - void load (); + void load (); - private: - std::vector m_soundBuffer; - std::vector m_audioStreams; + private: + std::vector m_soundBuffer; + std::vector m_audioStreams; - Core::Objects::CSound* m_sound; - }; -} + Core::Objects::CSound* m_sound; +}; +} // namespace WallpaperEngine::Render::Objects diff --git a/src/WallpaperEngine/Render/Objects/Effects/CMaterial.cpp b/src/WallpaperEngine/Render/Objects/Effects/CMaterial.cpp index 6468e11..717aab1 100644 --- a/src/WallpaperEngine/Render/Objects/Effects/CMaterial.cpp +++ b/src/WallpaperEngine/Render/Objects/Effects/CMaterial.cpp @@ -7,34 +7,28 @@ using namespace WallpaperEngine::Render::Objects::Effects; CMaterial::CMaterial (const Render::Objects::CEffect* effect, const Core::Objects::Images::CMaterial* material) : Helpers::CContextAware (effect->getImage ()), m_effect (effect), - m_material (material) -{ + m_material (material) { this->generatePasses (); } -const std::vector& CMaterial::getPasses () const -{ +const std::vector& CMaterial::getPasses () const { return this->m_passes; } -CImage* CMaterial::getImage () const -{ +CImage* CMaterial::getImage () const { return this->m_effect->getImage (); } -void CMaterial::generatePasses () -{ +void CMaterial::generatePasses () { // these are simple now, just create the entries and done for (const auto& cur : this->m_material->getPasses ()) this->m_passes.emplace_back (new CPass (this, cur)); } -const Core::Objects::Images::CMaterial* CMaterial::getMaterial () const -{ +const Core::Objects::Images::CMaterial* CMaterial::getMaterial () const { return this->m_material; } -const CEffect* CMaterial::getEffect () const -{ +const CEffect* CMaterial::getEffect () const { return this->m_effect; } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h b/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h index c482bb7..ec47a52 100644 --- a/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h +++ b/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h @@ -1,10 +1,10 @@ #pragma once -#include "WallpaperEngine/Core/Objects/Images/CMaterial.h" #include "WallpaperEngine/Core/Objects/CEffect.h" +#include "WallpaperEngine/Core/Objects/Images/CMaterial.h" -#include "WallpaperEngine/Render/Objects/Effects/CPass.h" #include "WallpaperEngine/Render/Objects/CEffect.h" +#include "WallpaperEngine/Render/Objects/Effects/CPass.h" #include "WallpaperEngine/Render/Helpers/CContextAware.h" @@ -12,33 +12,31 @@ using namespace WallpaperEngine; -namespace WallpaperEngine::Render::Objects -{ - class CEffect; - class CImage; -} +namespace WallpaperEngine::Render::Objects { +class CEffect; +class CImage; +} // namespace WallpaperEngine::Render::Objects -namespace WallpaperEngine::Render::Objects::Effects -{ - class CPass; +namespace WallpaperEngine::Render::Objects::Effects { +class CPass; - class CMaterial : public Helpers::CContextAware - { - friend class CPass; - public: - CMaterial (const Render::Objects::CEffect* effect, const Core::Objects::Images::CMaterial* material); +class CMaterial final : public Helpers::CContextAware { + friend class CPass; - [[nodiscard]] const std::vector& getPasses () const; - [[nodiscard]] CImage* getImage () const; - [[nodiscard]] const Core::Objects::Images::CMaterial* getMaterial () const; - [[nodiscard]] const CEffect* getEffect () const; + public: + CMaterial (const Render::Objects::CEffect* effect, const Core::Objects::Images::CMaterial* material); - private: - void generatePasses (); + [[nodiscard]] const std::vector& getPasses () const; + [[nodiscard]] CImage* getImage () const; + [[nodiscard]] const Core::Objects::Images::CMaterial* getMaterial () const; + [[nodiscard]] const CEffect* getEffect () const; - const Render::Objects::CEffect* m_effect; - const Core::Objects::Images::CMaterial* m_material; + private: + void generatePasses (); - std::vector m_passes; - }; -} + const Render::Objects::CEffect* m_effect; + const Core::Objects::Images::CMaterial* m_material; + + std::vector m_passes; +}; +} // namespace WallpaperEngine::Render::Objects::Effects diff --git a/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp b/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp index d987d5d..17fd060 100644 --- a/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp +++ b/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp @@ -1,7 +1,7 @@ -#include "common.h" -#include #include "CPass.h" #include "WallpaperEngine/Render/CFBO.h" +#include "common.h" +#include #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h" @@ -26,46 +26,41 @@ extern float g_Daytime; CPass::CPass (CMaterial* material, Core::Objects::Images::Materials::CPass* pass) : Helpers::CContextAware (material), m_material (material), - m_pass (pass) -{ + m_pass (pass) { this->setupTextures (); this->setupShaders (); this->setupShaderVariables (); } - -const ITexture* CPass::resolveTexture (const ITexture* expected, int index, const ITexture* previous) -{ - if (expected == nullptr) - { - auto it = this->m_fbos.find (index); +const ITexture* CPass::resolveTexture (const ITexture* expected, int index, const ITexture* previous) { + if (expected == nullptr) { + const auto it = this->m_fbos.find (index); if (it != this->m_fbos.end ()) - expected = (*it).second; + expected = it->second; } // first check in the binds and replace it if necessary - auto it = this->m_material->getMaterial ()->getTextureBinds ().find (index); + const auto it = this->m_material->getMaterial ()->getTextureBinds ().find (index); if (it == this->m_material->getMaterial ()->getTextureBinds ().end ()) return expected; // a bind named "previous" is just another way of telling it to use whatever texture there was already - if ((*it).second->getName () == "previous") + if (it->second->getName () == "previous") return previous ?: expected; // the bind actually has a name, search the FBO in the effect and return it - auto fbo = this->m_material->m_effect->findFBO ((*it).second->getName ()); + const auto fbo = this->m_material->m_effect->findFBO (it->second->getName ()); // try scene FBOs, these are our last resort, i guess the exception is better than a nullpo if (fbo == nullptr) - return this->m_material->getImage ()->getScene ()->findFBO ((*it).second->getName ()); + return this->m_material->getImage ()->getScene ()->findFBO (it->second->getName ()); return fbo; } -void CPass::render () -{ +void CPass::render () { // set the framebuffer we're drawing to glBindFramebuffer (GL_FRAMEBUFFER, this->m_drawTo->getFramebuffer ()); @@ -73,51 +68,35 @@ void CPass::render () glViewport (0, 0, this->m_drawTo->getRealWidth (), this->m_drawTo->getRealHeight ()); // set texture blending - if (this->m_pass->getBlendingMode () == "translucent") - { + if (this->m_pass->getBlendingMode () == "translucent") { glEnable (GL_BLEND); glBlendFuncSeparate (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - else if (this->m_pass->getBlendingMode () == "additive") - { + } else if (this->m_pass->getBlendingMode () == "additive") { glEnable (GL_BLEND); glBlendFuncSeparate (GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE); - } - else if (this->m_pass->getBlendingMode () == "normal") - { + } else if (this->m_pass->getBlendingMode () == "normal") { glEnable (GL_BLEND); glBlendFuncSeparate (GL_ONE, GL_ZERO, GL_ONE, GL_ZERO); - } - else - { + } else { glDisable (GL_BLEND); } // set depth testing - if (this->m_pass->getDepthTest () == "disabled") - { + if (this->m_pass->getDepthTest () == "disabled") { glDisable (GL_DEPTH_TEST); - } - else - { + } else { glEnable (GL_DEPTH_TEST); } - if (this->m_pass->getCullingMode () == "nocull") - { + if (this->m_pass->getCullingMode () == "nocull") { glDisable (GL_CULL_FACE); - } - else - { + } else { glEnable (GL_CULL_FACE); } - if (this->m_pass->getDepthWrite () == "disabled") - { + if (this->m_pass->getDepthWrite () == "disabled") { glDepthMask (false); - } - else - { + } else { glDepthMask (true); } @@ -131,17 +110,15 @@ void CPass::render () glm::vec2 translation = {0.0f, 0.0f}; glm::vec4 rotation = {0.0f, 0.0f, 0.0f, 0.0f}; - if (texture->isAnimated ()) - { + if (texture->isAnimated ()) { // calculate current texture and frame - double currentRenderTime = fmod (static_cast (this->getContext ().getDriver ().getRenderTime ()), this->m_material->getImage ()->getAnimationTime ()); + double currentRenderTime = fmod (static_cast (this->getContext ().getDriver ().getRenderTime ()), + this->m_material->getImage ()->getAnimationTime ()); - for (const auto& frameCur : texture->getFrames ()) - { + for (const auto& frameCur : texture->getFrames ()) { currentRenderTime -= frameCur->frametime; - if (currentRenderTime <= 0.0f) - { + if (currentRenderTime <= 0.0f) { // frame found, store coordinates and done currentTexture = frameCur->frameNumber; @@ -149,7 +126,7 @@ void CPass::render () translation.y = frameCur->y / texture->getTextureHeight (currentTexture); rotation.x = frameCur->width1 / static_cast (texture->getTextureWidth (currentTexture)); - rotation.y = frameCur->width2 / static_cast (texture->getTextureWidth(currentTexture)); + rotation.y = frameCur->width2 / static_cast (texture->getTextureWidth (currentTexture)); rotation.z = frameCur->height2 / static_cast (texture->getTextureHeight (currentTexture)); rotation.w = frameCur->height1 / static_cast (texture->getTextureHeight (currentTexture)); break; @@ -162,81 +139,63 @@ void CPass::render () glBindTexture (GL_TEXTURE_2D, texture->getTextureID (currentTexture)); // continue on the map from the second texture - if (!this->m_finalTextures.empty ()) - { - for (const auto& cur : this->m_finalTextures) - { - texture = this->resolveTexture (cur.second, cur.first, this->m_input); + if (!this->m_finalTextures.empty ()) { + for (const auto& [index, expectedTexture] : this->m_finalTextures) { + texture = this->resolveTexture (expectedTexture, index, this->m_input); - glActiveTexture (GL_TEXTURE0 + cur.first); + glActiveTexture (GL_TEXTURE0 + index); glBindTexture (GL_TEXTURE_2D, texture->getTextureID (0)); } } // add uniforms - for (const auto& cur : this->m_uniforms) - { - UniformEntry* entry = cur.second; - - switch (entry->type) - { - case Double: - glUniform1dv (entry->id, entry->count, reinterpret_cast (entry->value)); - break; - case Float: - glUniform1fv (entry->id, entry->count, reinterpret_cast (entry->value)); - break; - case Integer: - glUniform1iv (entry->id, entry->count, reinterpret_cast (entry->value)); - break; + for (const auto& [name, value] : this->m_uniforms) { + switch (value->type) { + case Double: glUniform1dv (value->id, value->count, static_cast (value->value)); break; + case Float: glUniform1fv (value->id, value->count, static_cast (value->value)); break; + case Integer: glUniform1iv (value->id, value->count, static_cast (value->value)); break; // TODO: THESE MIGHT NEED SPECIAL TREATMENT? IDK ONLY SUPPORT 1 FOR NOW case Vector4: - glUniform4fv (entry->id, 1, glm::value_ptr (*reinterpret_cast (entry->value))); + glUniform4fv (value->id, 1, glm::value_ptr (*static_cast (value->value))); break; case Vector3: - glUniform3fv (entry->id, 1, glm::value_ptr (*reinterpret_cast (entry->value))); + glUniform3fv (value->id, 1, glm::value_ptr (*static_cast (value->value))); break; case Vector2: - glUniform2fv (entry->id, 1, glm::value_ptr (*reinterpret_cast (entry->value))); + glUniform2fv (value->id, 1, glm::value_ptr (*static_cast (value->value))); break; case Matrix4: - glUniformMatrix4fv (entry->id, 1, GL_FALSE, glm::value_ptr (*reinterpret_cast (entry->value))); + glUniformMatrix4fv (value->id, 1, GL_FALSE, + glm::value_ptr (*static_cast (value->value))); break; case Matrix3: - glUniformMatrix3fv (entry->id, 1, GL_FALSE, glm::value_ptr (*reinterpret_cast (entry->value))); + glUniformMatrix3fv (value->id, 1, GL_FALSE, + glm::value_ptr (*static_cast (value->value))); break; } } // add reference uniforms - for (const auto& cur : this->m_referenceUniforms) - { - ReferenceUniformEntry* entry = cur.second; - - switch (entry->type) - { - case Double: - glUniform1d (entry->id, *reinterpret_cast (*entry->value)); - break; - case Float: - glUniform1f (entry->id, *reinterpret_cast (*entry->value)); - break; - case Integer: - glUniform1i (entry->id, *reinterpret_cast (*entry->value)); - break; + for (const auto& [name, value] : this->m_referenceUniforms) { + switch (value->type) { + case Double: glUniform1d (value->id, *static_cast (*value->value)); break; + case Float: glUniform1f (value->id, *static_cast (*value->value)); break; + case Integer: glUniform1i (value->id, *static_cast (*value->value)); break; case Vector4: - glUniform4fv (entry->id, 1, glm::value_ptr (*reinterpret_cast (*entry->value))); + glUniform4fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); break; case Vector3: - glUniform3fv (entry->id, 1, glm::value_ptr (*reinterpret_cast (*entry->value))); + glUniform3fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); break; case Vector2: - glUniform2fv (entry->id, 1, glm::value_ptr (*reinterpret_cast (*entry->value))); + glUniform2fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); break; case Matrix4: - glUniformMatrix4fv (entry->id, 1, GL_FALSE, glm::value_ptr (*reinterpret_cast (*entry->value))); + glUniformMatrix4fv (value->id, 1, GL_FALSE, + glm::value_ptr (*static_cast (*value->value))); break; case Matrix3: - glUniformMatrix3fv (entry->id, 1, GL_FALSE, glm::value_ptr (*reinterpret_cast (*entry->value))); + glUniformMatrix3fv (value->id, 1, GL_FALSE, + glm::value_ptr (*static_cast (*value->value))); break; } } @@ -249,19 +208,16 @@ void CPass::render () if (this->g_Texture0Translation != -1) glUniform2f (this->g_Texture0Translation, translation.x, translation.y); - for (const auto& cur : this->m_attribs) - { + for (const auto& cur : this->m_attribs) { glEnableVertexAttribArray (cur->id); glBindBuffer (GL_ARRAY_BUFFER, *cur->value); glVertexAttribPointer (cur->id, cur->elements, cur->type, GL_FALSE, 0, nullptr); #if !NDEBUG - glObjectLabel (GL_BUFFER, *cur->value, -1, ( - "Image " + std::to_string (this->getMaterial ()->getImage ()->getId ()) + - " Pass " + this->m_pass->getShader() + - " " + cur->name - ).c_str () - ); + glObjectLabel (GL_BUFFER, *cur->value, -1, + ("Image " + std::to_string (this->getMaterial ()->getImage ()->getId ()) + " Pass " + + this->m_pass->getShader () + " " + cur->name) + .c_str ()); #endif /* DEBUG */ } @@ -278,70 +234,57 @@ void CPass::render () glBindTexture (GL_TEXTURE_2D, 0); // continue on the map from the second texture - if (!this->m_finalTextures.empty ()) - { - for (const auto& cur : this->m_finalTextures) - { - glActiveTexture (GL_TEXTURE0 + cur.first); + if (!this->m_finalTextures.empty ()) { + for (const auto& [index, _] : this->m_finalTextures) { + glActiveTexture (GL_TEXTURE0 + index); glBindTexture (GL_TEXTURE_2D, 0); } } } -const CMaterial* CPass::getMaterial () const -{ +const CMaterial* CPass::getMaterial () const { return this->m_material; } -void CPass::setDestination (const CFBO* drawTo) -{ +void CPass::setDestination (const CFBO* drawTo) { this->m_drawTo = drawTo; } -void CPass::setInput (const ITexture* input) -{ +void CPass::setInput (const ITexture* input) { this->m_input = input; } -void CPass::setModelViewProjectionMatrix (const glm::mat4* projection) -{ +void CPass::setModelViewProjectionMatrix (const glm::mat4* projection) { this->m_modelViewProjectionMatrix = projection; } -void CPass::setModelViewProjectionMatrixInverse (const glm::mat4* projection) -{ +void CPass::setModelViewProjectionMatrixInverse (const glm::mat4* projection) { this->m_modelViewProjectionMatrixInverse = projection; } -void CPass::setModelMatrix (const glm::mat4* model) -{ +void CPass::setModelMatrix (const glm::mat4* model) { this->m_modelMatrix = model; } -void CPass::setViewProjectionMatrix (const glm::mat4* viewProjection) -{ +void CPass::setViewProjectionMatrix (const glm::mat4* viewProjection) { this->m_viewProjectionMatrix = viewProjection; } -void CPass::setTexCoord (GLuint texcoord) -{ +void CPass::setTexCoord (GLuint texcoord) { this->a_TexCoord = texcoord; } -void CPass::setPosition (GLuint position) -{ +void CPass::setPosition (GLuint position) { this->a_Position = position; } -Core::Objects::Images::Materials::CPass* CPass::getPass () -{ +Core::Objects::Images::Materials::CPass* CPass::getPass () { return this->m_pass; } -GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) -{ +GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) { // reserve shaders in OpenGL - GLuint shaderID = glCreateShader (type); + const GLuint shaderID = glCreateShader (type); // give shader's source code to OpenGL to be compiled const char* sourcePointer = shader->getCompiled ().c_str (); @@ -356,8 +299,7 @@ GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) glGetShaderiv (shaderID, GL_COMPILE_STATUS, &result); glGetShaderiv (shaderID, GL_INFO_LOG_LENGTH, &infoLogLength); - if (infoLogLength > 0) - { + if (infoLogLength > 0) { char* logBuffer = new char [infoLogLength + 1]; // ensure logBuffer ends with a \0 memset (logBuffer, 0, infoLogLength + 1); @@ -367,7 +309,7 @@ GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) std::stringstream buffer; buffer << logBuffer << std::endl << "Compiled source code:" << std::endl << shader->getCompiled (); // free the buffer - delete[] logBuffer; + delete [] logBuffer; // throw an exception sLog.exception (buffer.str ()); } @@ -375,51 +317,35 @@ GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) return shaderID; } -void CPass::setupShaders () -{ +void CPass::setupShaders () { // ensure the constants are defined const ITexture* texture0 = this->m_material->getImage ()->getTexture (); - // TODO: THE VALUES ARE THE SAME AS THE ENUMERATION, SO MAYBE IT HAS TO BE SPECIFIED FOR THE TEXTURE 0 OF ALL ELEMENTS? - if (texture0 != nullptr) - { - if (texture0->getFormat () == ITexture::TextureFormat::RG88) - { + // TODO: THE VALUES ARE THE SAME AS THE ENUMERATION, SO MAYBE IT HAS TO BE SPECIFIED FOR THE TEXTURE 0 OF ALL + // ELEMENTS? + if (texture0 != nullptr) { + if (texture0->getFormat () == ITexture::TextureFormat::RG88) { this->m_pass->insertCombo ("TEX0FORMAT", 8); - } - else if (texture0->getFormat () == ITexture::TextureFormat::R8) - { + } else if (texture0->getFormat () == ITexture::TextureFormat::R8) { this->m_pass->insertCombo ("TEX0FORMAT", 9); } } // prepare the shaders this->m_fragShader = new Render::Shaders::Compiler ( - this->m_material->getImage ()->getContainer (), - this->m_pass->getShader (), - Shaders::Compiler::Type_Pixel, - this->m_pass->getCombos (), - &m_foundCombos, - this->m_pass->getTextures (), - this->m_pass->getConstants () - ); + this->m_material->getImage ()->getContainer (), this->m_pass->getShader (), Shaders::Compiler::Type_Pixel, + this->m_pass->getCombos (), &m_foundCombos, this->m_pass->getTextures (), this->m_pass->getConstants ()); this->m_fragShader->precompile (); this->m_vertShader = new Render::Shaders::Compiler ( - this->m_material->getImage ()->getContainer (), - this->m_pass->getShader (), - Shaders::Compiler::Type_Vertex, - this->m_pass->getCombos (), - &m_foundCombos, - this->m_pass->getTextures (), - this->m_pass->getConstants () - ); + this->m_material->getImage ()->getContainer (), this->m_pass->getShader (), Shaders::Compiler::Type_Vertex, + this->m_pass->getCombos (), &m_foundCombos, this->m_pass->getTextures (), this->m_pass->getConstants ()); this->m_vertShader->precompile (); this->m_fragShader->precompile (); this->m_vertShader->precompile (); // compile the shaders - GLuint vertexShaderID = compileShader (this->m_vertShader, GL_VERTEX_SHADER); - GLuint fragmentShaderID = compileShader (this->m_fragShader, GL_FRAGMENT_SHADER); + const GLuint vertexShaderID = compileShader (this->m_vertShader, GL_VERTEX_SHADER); + const GLuint fragmentShaderID = compileShader (this->m_fragShader, GL_FRAGMENT_SHADER); // create the final program this->m_programID = glCreateProgram (); // link the shaders together @@ -433,17 +359,16 @@ void CPass::setupShaders () glGetProgramiv (this->m_programID, GL_LINK_STATUS, &result); glGetProgramiv (this->m_programID, GL_INFO_LOG_LENGTH, &infoLogLength); - if (infoLogLength > 0) - { + if (infoLogLength > 0) { char* logBuffer = new char [infoLogLength + 1]; // ensure logBuffer ends with a \0 memset (logBuffer, 0, infoLogLength + 1); // get information about the error glGetProgramInfoLog (this->m_programID, infoLogLength, nullptr, logBuffer); // throw an exception about the issue - std::string message = logBuffer; + const std::string message = logBuffer; // free the buffer - delete[] logBuffer; + delete [] logBuffer; // throw an exception sLog.exception (message); } @@ -471,14 +396,12 @@ void CPass::setupShaders () this->g_Texture0Translation = glGetUniformLocation (this->m_programID, "g_Texture0Translation"); } -void CPass::setupAttributes () -{ +void CPass::setupAttributes () { this->addAttribute ("a_TexCoord", GL_FLOAT, 2, &this->a_TexCoord); this->addAttribute ("a_Position", GL_FLOAT, 3, &this->a_Position); } -void CPass::setupUniforms () -{ +void CPass::setupUniforms () { // resolve the main texture const ITexture* texture = this->resolveTexture (this->m_material->getImage ()->getTexture (), 0); // register all the texture uniforms with correct values @@ -495,114 +418,102 @@ void CPass::setupUniforms () // do the real, final texture setup for the whole process { auto cur = this->m_textures.begin (); - auto end = this->m_textures.end (); + const auto end = this->m_textures.end (); auto fragCur = this->m_fragShader->getTextures ().begin (); - auto fragEnd = this->m_fragShader->getTextures ().end (); + const auto fragEnd = this->m_fragShader->getTextures ().end (); auto vertCur = this->m_vertShader->getTextures ().begin (); - auto vertEnd = this->m_vertShader->getTextures ().end (); + const auto vertEnd = this->m_vertShader->getTextures ().end (); auto bindCur = this->m_material->getMaterial ()->getTextureBinds ().begin (); - auto bindEnd = this->m_material->getMaterial ()->getTextureBinds ().end (); + const auto bindEnd = this->m_material->getMaterial ()->getTextureBinds ().end (); int index = 1; // technically m_textures should have the right amount of textures // but better be safe than sorry - while (bindCur != bindEnd || cur != end || fragCur != fragEnd || vertCur != vertEnd) - { - if (bindCur != bindEnd) - { - this->m_finalTextures [(*bindCur).first] = nullptr; - bindCur ++; + while (bindCur != bindEnd || cur != end || fragCur != fragEnd || vertCur != vertEnd) { + if (bindCur != bindEnd) { + this->m_finalTextures [bindCur->first] = nullptr; + ++bindCur; } - if (cur != end) - { + if (cur != end) { if ((*cur) != nullptr) this->m_finalTextures [index] = *cur; - index ++; - cur ++; + index++; + ++cur; } - if (fragCur != fragEnd) - { - std::string textureName = (*fragCur).second; + if (fragCur != fragEnd) { + std::string textureName = fragCur->second; - try - { + try { // resolve the texture first - const ITexture* textureRef = nullptr; + const ITexture* textureRef; - if (textureName.find ("_rt_") == 0) - { + if (textureName.find ("_rt_") == 0) { textureRef = this->getMaterial ()->getEffect ()->findFBO (textureName); if (textureRef == nullptr) textureRef = this->getMaterial ()->getImage ()->getScene ()->findFBO (textureName); - } - else + } else textureRef = this->getContext ().resolveTexture (textureName); - // ensure there's no texture in that slot already, shader textures are defaults in case nothing is there - if (this->m_finalTextures.find ((*fragCur).first) == this->m_finalTextures.end ()) - this->m_finalTextures [(*fragCur).first] = textureRef; - } - catch (std::runtime_error& ex) - { + // ensure there's no texture in that slot already, shader textures are defaults in case nothing is + // there + if (this->m_finalTextures.find (fragCur->first) == this->m_finalTextures.end ()) + this->m_finalTextures [fragCur->first] = textureRef; + } catch (std::runtime_error& ex) { sLog.error ("Cannot resolve texture ", textureName, " for fragment shader ", ex.what ()); } - fragCur ++; + ++fragCur; } - if (vertCur != vertEnd) - { - std::string textureName = (*vertCur).second; + if (vertCur != vertEnd) { + std::string textureName = vertCur->second; - try - { + try { // resolve the texture first - const ITexture* textureRef = nullptr; + const ITexture* textureRef; - if (textureName.find ("_rt_") == 0) - { + if (textureName.find ("_rt_") == 0) { textureRef = this->getMaterial ()->getEffect ()->findFBO (textureName); if (textureRef == nullptr) textureRef = this->getMaterial ()->getImage ()->getScene ()->findFBO (textureName); - } - else + } else textureRef = this->getContext ().resolveTexture (textureName); - // ensure there's no texture in that slot already, shader textures are defaults in case nothing is there - if (this->m_finalTextures.find ((*vertCur).first) == this->m_finalTextures.end ()) - this->m_finalTextures [(*vertCur).first] = textureRef; - } - catch (std::runtime_error& ex) - { + // ensure there's no texture in that slot already, shader textures are defaults in case nothing is + // there + if (this->m_finalTextures.find (vertCur->first) == this->m_finalTextures.end ()) + this->m_finalTextures [vertCur->first] = textureRef; + } catch (std::runtime_error& ex) { sLog.error ("Cannot resolve texture ", textureName, " for vertex shader ", ex.what ()); } - vertCur ++; + ++vertCur; } } } - for (const auto& cur : this->m_finalTextures) - { + for (const auto& [index, expectedTexture] : this->m_finalTextures) { std::ostringstream namestream; - namestream << "g_Texture" << cur.first << "Resolution"; + namestream << "g_Texture" << index << "Resolution"; - texture = this->resolveTexture (cur.second, cur.first, texture); + texture = this->resolveTexture (expectedTexture, index, texture); this->addUniform (namestream.str (), texture->getResolution ()); } - auto projection = this->getMaterial ()->getImage ()->getScene ()->getScene ()->getOrthogonalProjection (); + const auto projection = this->getMaterial ()->getImage ()->getScene ()->getScene ()->getOrthogonalProjection (); // lighting variables - this->addUniform ("g_LightAmbientColor", this->m_material->getImage ()->getScene ()->getScene ()->getAmbientColor ()); - this->addUniform ("g_LightSkylightColor", this->m_material->getImage ()->getScene ()->getScene ()->getSkylightColor ()); + this->addUniform ("g_LightAmbientColor", + this->m_material->getImage ()->getScene ()->getScene ()->getAmbientColor ()); + this->addUniform ("g_LightSkylightColor", + this->m_material->getImage ()->getScene ()->getScene ()->getSkylightColor ()); // register variables like brightness and alpha with some default value this->addUniform ("g_Brightness", this->m_material->getImage ()->getImage ()->getBrightness ()); this->addUniform ("g_UserAlpha", this->m_material->getImage ()->getImage ()->getAlpha ()); @@ -614,40 +525,41 @@ void CPass::setupUniforms () this->addUniform ("g_Time", &g_Time); this->addUniform ("g_Daytime", &g_Daytime); // add model-view-projection matrix - this->addUniform("g_ModelViewProjectionMatrixInverse", &this->m_modelViewProjectionMatrixInverse); + this->addUniform ("g_ModelViewProjectionMatrixInverse", &this->m_modelViewProjectionMatrixInverse); this->addUniform ("g_ModelViewProjectionMatrix", &this->m_modelViewProjectionMatrix); this->addUniform ("g_ModelMatrix", &this->m_modelMatrix); - this->addUniform ("g_NormalModelMatrix", glm::identity ()); + this->addUniform ("g_NormalModelMatrix", glm::identity ()); this->addUniform ("g_ViewProjectionMatrix", &this->m_viewProjectionMatrix); this->addUniform ("g_PointerPosition", this->m_material->getImage ()->getScene ()->getMousePosition ()); this->addUniform ("g_PointerPositionLast", this->m_material->getImage ()->getScene ()->getMousePositionLast ()); - this->addUniform ("g_EffectTextureProjectionMatrix", glm::mat4(1.0)); - this->addUniform ("g_EffectTextureProjectionMatrixInverse", glm::mat4(1.0)); + this->addUniform ("g_EffectTextureProjectionMatrix", glm::mat4 (1.0)); + this->addUniform ("g_EffectTextureProjectionMatrixInverse", glm::mat4 (1.0)); this->addUniform ("g_TexelSize", glm::vec2 (1.0 / projection->getWidth (), 1.0 / projection->getHeight ())); this->addUniform ("g_TexelSizeHalf", glm::vec2 (0.5 / projection->getWidth (), 0.5 / projection->getHeight ())); - this->addUniform ("g_AudioSpectrum16Left", this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio16, 16); - this->addUniform ("g_AudioSpectrum16Right", this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio16, 16); - this->addUniform ("g_AudioSpectrum32Left", this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio32, 32); - this->addUniform ("g_AudioSpectrum32Right", this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio32, 32); - this->addUniform ("g_AudioSpectrum64Left", this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio64, 64); - this->addUniform ("g_AudioSpectrum64Right", this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio64, 64); + this->addUniform ("g_AudioSpectrum16Left", + this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio16, 16); + this->addUniform ("g_AudioSpectrum16Right", + this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio16, 16); + this->addUniform ("g_AudioSpectrum32Left", + this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio32, 32); + this->addUniform ("g_AudioSpectrum32Right", + this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio32, 32); + this->addUniform ("g_AudioSpectrum64Left", + this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio64, 64); + this->addUniform ("g_AudioSpectrum64Right", + this->getMaterial ()->getImage ()->getScene ()->getAudioContext ().getRecorder ().audio64, 64); } -void CPass::addAttribute (const std::string& name, GLint type, GLint elements, const GLuint* value) -{ - GLint id = glGetAttribLocation (this->m_programID, name.c_str ()); +void CPass::addAttribute (const std::string& name, GLint type, GLint elements, const GLuint* value) { + const GLint id = glGetAttribLocation (this->m_programID, name.c_str ()); if (id == -1) return; - this->m_attribs.emplace_back ( - new AttribEntry (id, name, type, elements, value) - ); + this->m_attribs.emplace_back (new AttribEntry (id, name, type, elements, value)); } -template -void CPass::addUniform (const std::string& name, UniformType type, T value) -{ +template void CPass::addUniform (const std::string& name, UniformType type, T value) { GLint id = glGetUniformLocation (this->m_programID, name.c_str ()); // parameter not found, can be ignored @@ -658,14 +570,10 @@ void CPass::addUniform (const std::string& name, UniformType type, T value) T* newValue = new T (value); // uniform found, add it to the list - this->m_uniforms.insert ( - std::make_pair (name, new UniformEntry (id, name, type, newValue, 1)) - ); + this->m_uniforms.insert (std::make_pair (name, new UniformEntry (id, name, type, newValue, 1))); } -template -void CPass::addUniform (const std::string& name, UniformType type, T* value, int count) -{ +template void CPass::addUniform (const std::string& name, UniformType type, T* value, int count) { // this version is used to reference to system variables so things like g_Time works fine GLint id = glGetUniformLocation (this->m_programID, name.c_str ()); @@ -674,16 +582,12 @@ void CPass::addUniform (const std::string& name, UniformType type, T* value, int return; // uniform found, add it to the list - this->m_uniforms.insert ( - std::make_pair (name, new UniformEntry (id, name, type, value, count)) - ); + this->m_uniforms.insert (std::make_pair (name, new UniformEntry (id, name, type, value, count))); } -template -void CPass::addUniform (const std::string& name, UniformType type, T** value) -{ +template void CPass::addUniform (const std::string& name, UniformType type, T** value) { // this version is used to reference to system variables so things like g_Time works fine - GLint id = glGetUniformLocation (this->m_programID, name.c_str ()); + const GLint id = glGetUniformLocation (this->m_programID, name.c_str ()); // parameter not found, can be ignored if (id == -1) @@ -691,61 +595,44 @@ void CPass::addUniform (const std::string& name, UniformType type, T** value) // uniform found, add it to the list this->m_referenceUniforms.insert ( - std::make_pair (name, new ReferenceUniformEntry (id, name, type, reinterpret_cast (value))) - ); + std::make_pair (name, new ReferenceUniformEntry (id, name, type, reinterpret_cast (value)))); } - -void CPass::setupTextures () -{ +void CPass::setupTextures () { auto cur = this->m_pass->getTextures ().begin (); - auto end = this->m_pass->getTextures ().end (); + const auto end = this->m_pass->getTextures ().end (); - for (int index = 0; cur != end; cur ++, index ++) - { + for (int index = 0; cur != end; ++cur, index++) { // ignore first texture as that'll be the input of the last pass/image (unless the image is an FBO) if (index == 0) continue; - if ((*cur).find ("_rt_") == 0) - { + if (cur->find ("_rt_") == 0) { const CFBO* fbo = this->m_material->m_effect->findFBO ((*cur)); if (fbo == nullptr) fbo = this->m_material->getImage ()->getScene ()->findFBO ((*cur)); - if (fbo != nullptr) - { + if (fbo != nullptr) { this->m_fbos.insert (std::make_pair (index, fbo)); - this->m_textures.emplace_back ( - fbo - ); + this->m_textures.emplace_back (fbo); } // _rt_texture - } - else - { - if ((*cur).empty()) - { + } else { + if (cur->empty ()) { this->m_textures.emplace_back (nullptr); - } - else - { - this->m_textures.emplace_back ( - this->m_material->getImage ()->getContext ().resolveTexture ((*cur)) - ); + } else { + this->m_textures.emplace_back (this->m_material->getImage ()->getContext ().resolveTexture ((*cur))); } } } } -void CPass::setupShaderVariables () -{ +void CPass::setupShaderVariables () { // find variables in the shaders and set the value with the constants if possible - for (const auto& cur : this->m_pass->getConstants ()) - { - CShaderVariable* vertexVar = this->m_vertShader->findParameter (cur.first); - CShaderVariable* pixelVar = this->m_fragShader->findParameter (cur.first); + for (const auto& [name, value] : this->m_pass->getConstants ()) { + CShaderVariable* vertexVar = this->m_vertShader->findParameter (name); + CShaderVariable* pixelVar = this->m_fragShader->findParameter (name); // variable not found, can be ignored if (vertexVar == nullptr && pixelVar == nullptr) @@ -755,9 +642,8 @@ void CPass::setupShaderVariables () CShaderVariable* var = vertexVar == nullptr ? pixelVar : vertexVar; // ensure the shader's and the constant are of the same type - if (cur.second->getType () == var->getType ()) - { - this->addUniform (var->getName (), cur.second); + if (value->getType () == var->getType ()) { + this->addUniform (var->getName (), value); continue; } @@ -765,39 +651,25 @@ void CPass::setupShaderVariables () // integers and floats are equivalent, this could be detected at load time // but that'd mean to compile the shader in the load, and not on the render stage // so take into account these conversions here - if (cur.second->is () && var->is ()) - { + if (value->is () && var->is ()) { // create an integer value from a float - this->addUniform (var->getName (), static_cast (*cur.second->as ()->getValue ())); - } - else if (cur.second->is () && var->is ()) - { + this->addUniform (var->getName (), static_cast (*value->as ()->getValue ())); + } else if (value->is () && var->is ()) { // create a float value from an integer - this->addUniform (var->getName (), static_cast (*cur.second->as ()->getValue ())); - } - else if (cur.second->is () && var->is ()) - { - auto* val = cur.second->as (); + this->addUniform (var->getName (), static_cast (*value->as ()->getValue ())); + } else if (value->is () && var->is ()) { + auto* val = value->as (); // create a new vector2 with the first two values this->addUniform (var->getName (), {val->getValue ()->x, val->getValue ()->y}); - } - else if (cur.second->is () && var->is ()) - { - auto* val = cur.second->as (); + } else if (value->is () && var->is ()) { + auto* val = value->as (); this->addUniform (var->getName (), {val->getValue ()->x, val->getValue ()->y, val->getValue ()->z}); - } - else - { - sLog.exception ( - "Constant ", - cur.first, - " type does not match pixel/vertex shader variable and cannot be converted (", - cur.second->getType (), - " to ", - var->getType () - ); + } else { + sLog.exception ("Constant ", name, + " type does not match pixel/vertex shader variable and cannot be converted (", + value->getType (), " to ", var->getType ()); } } @@ -811,149 +683,126 @@ void CPass::setupShaderVariables () } // define some basic methods for the template -void CPass::addUniform (CShaderVariable* value) -{ - if (value->is ()) - this->addUniform (value->getName (), const_cast (reinterpret_cast (value->as ()->getValue ()))); - else if (value->is ()) - this->addUniform (value->getName (), const_cast (reinterpret_cast (value->as ()->getValue ()))); - else if (value->is ()) - this->addUniform (value->getName (), const_cast (reinterpret_cast (value->as ()->getValue ()))); - else if (value->is ()) - this->addUniform (value->getName (), const_cast (reinterpret_cast (value->as ()->getValue ()))); - else if (value->is ()) - this->addUniform (value->getName (), const_cast (reinterpret_cast (value->as ()->getValue ()))); -} -void CPass::addUniform (const std::string& name, CShaderConstant* value) -{ - // now determine the constant's type and register the correct uniform for it - if (value->is ()) - this->addUniform (name, value->as ()->getValue ()); - else if (value->is ()) - this->addUniform (name, value->as ()->getValue ()); - else if (value->is ()) - this->addUniform (name, value->as ()->getValue ()); +void CPass::addUniform (CShaderVariable* value) { + if (value->is ()) + this->addUniform (value->getName (), + static_cast (value->as ()->getValue ())); + else if (value->is ()) + this->addUniform (value->getName (), + static_cast (value->as ()->getValue ())); + else if (value->is ()) + this->addUniform (value->getName (), + static_cast (value->as ()->getValue ())); + else if (value->is ()) + this->addUniform (value->getName (), + static_cast (value->as ()->getValue ())); + else if (value->is ()) + this->addUniform (value->getName (), + static_cast (value->as ()->getValue ())); } -void CPass::addUniform (const std::string& name, int value) -{ +void CPass::addUniform (const std::string& name, CShaderConstant* value) { + // now determine the constant's type and register the correct uniform for it + if (value->is ()) + this->addUniform (name, value->as ()->getValue ()); + else if (value->is ()) + this->addUniform (name, value->as ()->getValue ()); + else if (value->is ()) + this->addUniform (name, value->as ()->getValue ()); +} + +void CPass::addUniform (const std::string& name, int value) { this->addUniform (name, UniformType::Integer, value); } -void CPass::addUniform (const std::string& name, const int* value, int count) -{ +void CPass::addUniform (const std::string& name, const int* value, int count) { this->addUniform (name, UniformType::Integer, value, count); } -void CPass::addUniform (const std::string& name, const int** value) -{ +void CPass::addUniform (const std::string& name, const int** value) { this->addUniform (name, UniformType::Integer, value); } -void CPass::addUniform (const std::string& name, double value) -{ +void CPass::addUniform (const std::string& name, double value) { this->addUniform (name, UniformType::Double, value); } -void CPass::addUniform (const std::string& name, const double* value, int count) -{ +void CPass::addUniform (const std::string& name, const double* value, int count) { this->addUniform (name, UniformType::Double, value, count); } -void CPass::addUniform (const std::string& name, const double** value) -{ +void CPass::addUniform (const std::string& name, const double** value) { this->addUniform (name, UniformType::Double, value); } -void CPass::addUniform (const std::string& name, float value) -{ +void CPass::addUniform (const std::string& name, float value) { this->addUniform (name, UniformType::Float, value); } -void CPass::addUniform (const std::string& name, const float* value, int count) -{ +void CPass::addUniform (const std::string& name, const float* value, int count) { this->addUniform (name, UniformType::Float, value, count); } -void CPass::addUniform (const std::string& name, const float** value) -{ +void CPass::addUniform (const std::string& name, const float** value) { this->addUniform (name, UniformType::Float, value); } - -void CPass::addUniform (const std::string& name, glm::vec2 value) -{ +void CPass::addUniform (const std::string& name, glm::vec2 value) { this->addUniform (name, UniformType::Vector2, value); } -void CPass::addUniform (const std::string& name, const glm::vec2* value) -{ +void CPass::addUniform (const std::string& name, const glm::vec2* value) { this->addUniform (name, UniformType::Vector2, value, 1); } -void CPass::addUniform (const std::string& name, const glm::vec2** value) -{ +void CPass::addUniform (const std::string& name, const glm::vec2** value) { this->addUniform (name, UniformType::Vector2, value, 1); } - -void CPass::addUniform (const std::string& name, glm::vec3 value) -{ +void CPass::addUniform (const std::string& name, glm::vec3 value) { this->addUniform (name, UniformType::Vector3, value); } -void CPass::addUniform (const std::string& name, const glm::vec3* value) -{ +void CPass::addUniform (const std::string& name, const glm::vec3* value) { this->addUniform (name, UniformType::Vector3, value, 1); } -void CPass::addUniform (const std::string& name, const glm::vec3** value) -{ +void CPass::addUniform (const std::string& name, const glm::vec3** value) { this->addUniform (name, UniformType::Vector3, value); } - -void CPass::addUniform (const std::string& name, glm::vec4 value) -{ +void CPass::addUniform (const std::string& name, const glm::vec4 value) { this->addUniform (name, UniformType::Vector4, value); } -void CPass::addUniform (const std::string& name, const glm::vec4* value) -{ +void CPass::addUniform (const std::string& name, const glm::vec4* value) { this->addUniform (name, UniformType::Vector4, value, 1); } -void CPass::addUniform (const std::string& name, const glm::vec4** value) -{ +void CPass::addUniform (const std::string& name, const glm::vec4** value) { this->addUniform (name, UniformType::Vector4, value); } -void CPass::addUniform (const std::string& name, glm::mat3 value) -{ +void CPass::addUniform (const std::string& name, const glm::mat3& value) { this->addUniform (name, UniformType::Matrix3, value); } -void CPass::addUniform (const std::string& name, const glm::mat3* value) -{ +void CPass::addUniform (const std::string& name, const glm::mat3* value) { this->addUniform (name, UniformType::Matrix3, value, 1); } -void CPass::addUniform (const std::string& name, const glm::mat3** value) -{ +void CPass::addUniform (const std::string& name, const glm::mat3** value) { this->addUniform (name, UniformType::Matrix3, value); } -void CPass::addUniform (const std::string& name, glm::mat4 value) -{ +void CPass::addUniform (const std::string& name, const glm::mat4 value) { this->addUniform (name, UniformType::Matrix4, value); } -void CPass::addUniform (const std::string& name, const glm::mat4* value) -{ +void CPass::addUniform (const std::string& name, const glm::mat4* value) { this->addUniform (name, UniformType::Matrix4, value, 1); } -void CPass::addUniform (const std::string& name, const glm::mat4** value) -{ +void CPass::addUniform (const std::string& name, const glm::mat4** value) { this->addUniform (name, UniformType::Matrix4, value); } diff --git a/src/WallpaperEngine/Render/Objects/Effects/CPass.h b/src/WallpaperEngine/Render/Objects/Effects/CPass.h index 2e6298d..a5dea99 100644 --- a/src/WallpaperEngine/Render/Objects/Effects/CPass.h +++ b/src/WallpaperEngine/Render/Objects/Effects/CPass.h @@ -3,162 +3,167 @@ #include #include -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" +#include "WallpaperEngine/Assets/ITexture.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" +#include "WallpaperEngine/Render/CFBO.h" #include "WallpaperEngine/Render/Objects/Effects/CMaterial.h" #include "WallpaperEngine/Render/Shaders/Compiler.h" -#include "WallpaperEngine/Assets/ITexture.h" -#include "WallpaperEngine/Render/CFBO.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" #include "WallpaperEngine/Render/Helpers/CContextAware.h" -namespace WallpaperEngine::Render::Objects::Effects -{ - using namespace WallpaperEngine::Assets; - using namespace WallpaperEngine::Render::Shaders::Variables; - using namespace WallpaperEngine::Core::Objects::Effects::Constants; +namespace WallpaperEngine::Render::Objects::Effects { +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Render::Shaders::Variables; +using namespace WallpaperEngine::Core::Objects::Effects::Constants; - class CMaterial; +class CMaterial; - class CPass : public Helpers::CContextAware - { - public: - CPass (CMaterial* material, Core::Objects::Images::Materials::CPass* pass); +class CPass final : public Helpers::CContextAware { + public: + CPass (CMaterial* material, Core::Objects::Images::Materials::CPass* pass); - void render (); + void render (); - void setDestination (const CFBO* drawTo); - void setInput (const ITexture* input); - void setTexCoord (GLuint texcoord); - void setPosition (GLuint position); - void setModelViewProjectionMatrix (const glm::mat4* projection); - void setModelViewProjectionMatrixInverse (const glm::mat4* projection); - void setModelMatrix (const glm::mat4* model); - void setViewProjectionMatrix (const glm::mat4* viewProjection); + void setDestination (const CFBO* drawTo); + void setInput (const ITexture* input); + void setTexCoord (GLuint texcoord); + void setPosition (GLuint position); + void setModelViewProjectionMatrix (const glm::mat4* projection); + void setModelViewProjectionMatrixInverse (const glm::mat4* projection); + void setModelMatrix (const glm::mat4* model); + void setViewProjectionMatrix (const glm::mat4* viewProjection); - const CMaterial* getMaterial () const; - Core::Objects::Images::Materials::CPass* getPass (); + const CMaterial* getMaterial () const; + Core::Objects::Images::Materials::CPass* getPass (); - private: - enum UniformType - { - Float = 0, - Matrix3 = 1, - Matrix4 = 2, - Integer = 3, - Vector2 = 4, - Vector3 = 5, - Vector4 = 6, - Double = 7 - }; - - class UniformEntry - { - public: - UniformEntry (GLint id, std::string name, UniformType type, const void* value, int count) : - id (id), name (std::move (name)), type (type), value (value), count (count) { } - - GLint id; - std::string name; - UniformType type; - const void* value; - int count; - }; - - class ReferenceUniformEntry - { - public: - ReferenceUniformEntry (GLint id, std::string name, UniformType type, const void** value) : - id (id), name (std::move (name)), type (type), value (value) { } - - GLint id; - std::string name; - UniformType type; - const void** value; - }; - - class AttribEntry - { - public: - AttribEntry (GLint id, std::string name, GLint type, GLint elements, const GLuint* value) : - id (id), name (std::move (name)), type (type), elements (elements), value (value) { } - - GLint id; - std::string name; - GLint type; - GLint elements; - const GLuint* value; - }; - - static GLuint compileShader (Render::Shaders::Compiler* shader, GLuint type); - void setupTextures (); - void setupShaders (); - void setupShaderVariables (); - void setupUniforms (); - void setupAttributes (); - void addAttribute (const std::string& name, GLint type, GLint elements, const GLuint* value); - void addUniform (CShaderVariable* value); - void addUniform (const std::string& name, CShaderConstant* value); - void addUniform (const std::string& name, int value); - void addUniform (const std::string& name, double value); - void addUniform (const std::string& name, float value); - void addUniform (const std::string& name, glm::vec2 value); - void addUniform (const std::string& name, glm::vec3 value); - void addUniform (const std::string& name, glm::vec4 value); - void addUniform (const std::string& name, glm::mat3 value); - void addUniform (const std::string& name, glm::mat4 value); - void addUniform (const std::string& name, const int* value, int count = 1); - void addUniform (const std::string& name, const double* value, int count = 1); - void addUniform (const std::string& name, const float* value, int count = 1); - void addUniform (const std::string& name, const glm::vec2* value); - void addUniform (const std::string& name, const glm::vec3* value); - void addUniform (const std::string& name, const glm::vec4* value); - void addUniform (const std::string& name, const glm::mat3* value); - void addUniform (const std::string& name, const glm::mat4* value); - void addUniform (const std::string& name, const int** value); - void addUniform (const std::string& name, const double** value); - void addUniform (const std::string& name, const float** value); - void addUniform (const std::string& name, const glm::vec2** value); - void addUniform (const std::string& name, const glm::vec3** value); - void addUniform (const std::string& name, const glm::vec4** value); - void addUniform (const std::string& name, const glm::mat3** value); - void addUniform (const std::string& name, const glm::mat4** value); - template void addUniform (const std::string& name, UniformType type, T value); - template void addUniform (const std::string& name, UniformType type, T* value, int count = 1); - template void addUniform (const std::string& name, UniformType type, T** value); - - const ITexture* resolveTexture (const ITexture* expected, int index, const ITexture* previous = nullptr); - - CMaterial* m_material; - Core::Objects::Images::Materials::CPass* m_pass; - std::vector m_textures; - std::map m_fbos; - std::map m_foundCombos; - std::vector m_attribs; - std::map m_uniforms; - std::map m_referenceUniforms; - const glm::mat4* m_modelViewProjectionMatrix; - const glm::mat4* m_modelViewProjectionMatrixInverse; - const glm::mat4* m_modelMatrix; - const glm::mat4* m_viewProjectionMatrix; - - /** - * Contains the final map of textures to be used - */ - std::map m_finalTextures; - - Render::Shaders::Compiler* m_fragShader; - Render::Shaders::Compiler* m_vertShader; - - const CFBO* m_drawTo; - const ITexture* m_input; - - GLuint m_programID; - - // shader variables used temporary - GLint g_Texture0Rotation; - GLint g_Texture0Translation; - GLuint a_TexCoord; - GLuint a_Position; + private: + enum UniformType { + Float = 0, + Matrix3 = 1, + Matrix4 = 2, + Integer = 3, + Vector2 = 4, + Vector3 = 5, + Vector4 = 6, + Double = 7 }; -} + + class UniformEntry { + public: + UniformEntry (const GLint id, std::string name, UniformType type, const void* value, int count) : + id (id), + name (std::move (name)), + type (type), + value (value), + count (count) {} + + const GLint id; + std::string name; + UniformType type; + const void* value; + int count; + }; + + class ReferenceUniformEntry { + public: + ReferenceUniformEntry (const GLint id, std::string name, UniformType type, const void** value) : + id (id), + name (std::move (name)), + type (type), + value (value) {} + + const GLint id; + std::string name; + UniformType type; + const void** value; + }; + + class AttribEntry { + public: + AttribEntry (const GLint id, std::string name, GLint type, GLint elements, const GLuint* value) : + id (id), + name (std::move (name)), + type (type), + elements (elements), + value (value) {} + + const GLint id; + std::string name; + GLint type; + GLint elements; + const GLuint* value; + }; + + static GLuint compileShader (Render::Shaders::Compiler* shader, GLuint type); + void setupTextures (); + void setupShaders (); + void setupShaderVariables (); + void setupUniforms (); + void setupAttributes (); + void addAttribute (const std::string& name, GLint type, GLint elements, const GLuint* value); + void addUniform (CShaderVariable* value); + void addUniform (const std::string& name, CShaderConstant* value); + void addUniform (const std::string& name, int value); + void addUniform (const std::string& name, double value); + void addUniform (const std::string& name, float value); + void addUniform (const std::string& name, glm::vec2 value); + void addUniform (const std::string& name, glm::vec3 value); + void addUniform (const std::string& name, glm::vec4 value); + void addUniform (const std::string& name, const glm::mat3& value); + void addUniform (const std::string& name, glm::mat4 value); + void addUniform (const std::string& name, const int* value, int count = 1); + void addUniform (const std::string& name, const double* value, int count = 1); + void addUniform (const std::string& name, const float* value, int count = 1); + void addUniform (const std::string& name, const glm::vec2* value); + void addUniform (const std::string& name, const glm::vec3* value); + void addUniform (const std::string& name, const glm::vec4* value); + void addUniform (const std::string& name, const glm::mat3* value); + void addUniform (const std::string& name, const glm::mat4* value); + void addUniform (const std::string& name, const int** value); + void addUniform (const std::string& name, const double** value); + void addUniform (const std::string& name, const float** value); + void addUniform (const std::string& name, const glm::vec2** value); + void addUniform (const std::string& name, const glm::vec3** value); + void addUniform (const std::string& name, const glm::vec4** value); + void addUniform (const std::string& name, const glm::mat3** value); + void addUniform (const std::string& name, const glm::mat4** value); + template void addUniform (const std::string& name, UniformType type, T value); + template void addUniform (const std::string& name, UniformType type, T* value, int count = 1); + template void addUniform (const std::string& name, UniformType type, T** value); + + const ITexture* resolveTexture (const ITexture* expected, int index, const ITexture* previous = nullptr); + + CMaterial* m_material; + Core::Objects::Images::Materials::CPass* m_pass; + std::vector m_textures; + std::map m_fbos; + std::map m_foundCombos; + std::vector m_attribs; + std::map m_uniforms; + std::map m_referenceUniforms; + const glm::mat4* m_modelViewProjectionMatrix; + const glm::mat4* m_modelViewProjectionMatrixInverse; + const glm::mat4* m_modelMatrix; + const glm::mat4* m_viewProjectionMatrix; + + /** + * Contains the final map of textures to be used + */ + std::map m_finalTextures; + + Render::Shaders::Compiler* m_fragShader; + Render::Shaders::Compiler* m_vertShader; + + const CFBO* m_drawTo; + const ITexture* m_input; + + GLuint m_programID; + + // shader variables used temporary + GLint g_Texture0Rotation; + GLint g_Texture0Translation; + GLuint a_TexCoord; + GLuint a_Position; +}; +} // namespace WallpaperEngine::Render::Objects::Effects diff --git a/src/WallpaperEngine/Render/Shaders/Compiler.cpp b/src/WallpaperEngine/Render/Shaders/Compiler.cpp index 4367fdc..5710312 100644 --- a/src/WallpaperEngine/Render/Shaders/Compiler.cpp +++ b/src/WallpaperEngine/Render/Shaders/Compiler.cpp @@ -1,6 +1,6 @@ #include "common.h" -#include #include +#include #include #include @@ -8,12 +8,12 @@ #include // shader compiler -#include -#include -#include #include -#include +#include +#include +#include #include +#include #include "WallpaperEngine/Assets/CAssetLoadException.h" #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" @@ -26,840 +26,736 @@ using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Assets; -namespace WallpaperEngine::Render::Shaders -{ - Compiler::Compiler ( - CContainer* container, - std::string filename, - Type type, - std::map * combos, - std::map * foundCombos, - const std::vector & textures, - const std::map& constants, - bool recursive) : - m_combos (combos), - m_foundCombos (foundCombos), - m_passTextures (textures), - m_recursive (recursive), - m_type (type), - m_file (std::move(filename)), - m_error (), - m_errorInfo (), - m_constants (constants), - m_container (container), - m_baseCombos () - { - if (type == Type_Vertex) - this->m_content = this->m_container->readVertexShader (this->m_file); - else if (type == Type_Pixel) - this->m_content = this->m_container->readFragmentShader (this->m_file); - else if (type == Type_Include) - this->m_content = this->m_container->readIncludeShader (this->m_file); +namespace WallpaperEngine::Render::Shaders { +Compiler::Compiler (CContainer* container, std::string filename, Type type, std::map* combos, + std::map* foundCombos, const std::vector& textures, + const std::map& constants, bool recursive) : + m_combos (combos), + m_foundCombos (foundCombos), + m_passTextures (textures), + m_recursive (recursive), + m_type (type), + m_file (std::move (filename)), + m_error (), + m_constants (constants), + m_container (container) { + if (type == Type_Vertex) + this->m_content = this->m_container->readVertexShader (this->m_file); + else if (type == Type_Pixel) + this->m_content = this->m_container->readFragmentShader (this->m_file); + else if (type == Type_Include) + this->m_content = this->m_container->readIncludeShader (this->m_file); - // clone the combos into the baseCombos to keep track of values that must be embedded no matter what - for (const auto& cur : *this->m_combos) - this->m_baseCombos.insert (std::make_pair (cur.first, cur.second)); - } + // clone the combos into the baseCombos to keep track of values that must be embedded no matter what + for (const auto& [name, value] : *this->m_combos) + this->m_baseCombos.insert (std::make_pair (name, value)); +} - bool Compiler::peekString(std::string str, std::string::const_iterator& it) - { - std::string::const_iterator check = str.begin(); - std::string::const_iterator cur = it; +bool Compiler::peekString (std::string str, std::string::const_iterator& it) { + std::string::const_iterator check = str.begin (); + std::string::const_iterator cur = it; - while (cur != this->m_content.end () && check != str.end ()) - { - if (*cur != *check) return false; - - cur ++; check ++; - } - - if (cur == this->m_content.end ()) - { + while (cur != this->m_content.end () && check != str.end ()) { + if (*cur != *check) return false; - } - if (check != str.end ()) - { - return false; - } - - it = cur; - - return true; + ++cur; + ++check; } - bool Compiler::expectSemicolon (std::string::const_iterator& it) - { - if (*it != ';') - { - this->m_error = true; - this->m_errorInfo = std::string ("Expected semicolon but got ") + *it; - return false; - } - - it ++; - - return true; + if (cur == this->m_content.end ()) { + return false; } - void Compiler::ignoreSpaces(std::string::const_iterator &it) - { - while (it != this->m_content.end() && (*it == ' ' || *it == '\t')) it ++; + if (check != str.end ()) { + return false; } - void Compiler::ignoreUpToNextLineFeed (std::string::const_iterator& it) - { - while (it != this->m_content.end() && *it != '\n') it ++; - } + it = cur; - void Compiler::ignoreUpToBlockCommentEnd (std::string::const_iterator& it) - { - while (it != this->m_content.end() && !this->peekString ("*/", it)) it ++; - } - - std::string Compiler::extractType (std::string::const_iterator& it) - { - // first of all check for highp/mediump/lowp as these operators have to be ignored - this->peekString ("highp", it); - this->peekString ("mediump", it); - this->peekString ("lowp", it); - this->ignoreSpaces (it); - - auto cur = sTypes.begin (); - auto end = sTypes.end (); - - while (cur != end) - { - if (this->peekString (*cur + " ", it)) - return *cur; - - cur ++; - } + return true; +} +bool Compiler::expectSemicolon (std::string::const_iterator& it) { + if (*it != ';') { this->m_error = true; - this->m_errorInfo = "Expected type"; + this->m_errorInfo = std::string ("Expected semicolon but got ") + *it; + return false; + } + + ++it; + + return true; +} + +void Compiler::ignoreSpaces (std::string::const_iterator& it) { + while (it != this->m_content.end () && (*it == ' ' || *it == '\t')) + ++it; +} + +void Compiler::ignoreUpToNextLineFeed (std::string::const_iterator& it) { + while (it != this->m_content.end () && *it != '\n') + ++it; +} + +void Compiler::ignoreUpToBlockCommentEnd (std::string::const_iterator& it) { + while (it != this->m_content.end () && !this->peekString ("*/", it)) + ++it; +} + +std::string Compiler::extractType (std::string::const_iterator& it) { + // first of all check for highp/mediump/lowp as these operators have to be ignored + this->peekString ("highp", it); + this->peekString ("mediump", it); + this->peekString ("lowp", it); + this->ignoreSpaces (it); + + auto cur = sTypes.begin (); + const auto end = sTypes.end (); + + while (cur != end) { + if (this->peekString (*cur + " ", it)) + return *cur; + + ++cur; + } + + this->m_error = true; + this->m_errorInfo = "Expected type"; + return ""; +} + +std::string Compiler::extractName (std::string::const_iterator& it) { + std::string::const_iterator cur = it; + std::string::const_iterator begin = cur; + + // first character has to be a valid alphabetic characer + if (!this->isChar (cur) && *cur != '_') { + this->m_error = true; + this->m_errorInfo = "Expected name doesn't start with a valid character"; return ""; } - std::string Compiler::extractName (std::string::const_iterator& it) - { - std::string::const_iterator cur = it; - std::string::const_iterator begin = cur; + ++cur; - // first character has to be a valid alphabetic characer - if (!this->isChar (cur) && *cur != '_') - { - this->m_error = true; - this->m_errorInfo = "Expected name doesn't start with a valid character"; + while (cur != this->m_content.end () && (this->isChar (cur) || *cur == '_' || this->isNumeric (cur))) + ++cur; + + it = cur; + + return {begin, cur}; +} + +std::string Compiler::extractArray (std::string::const_iterator& it, bool mustExists) { + auto cur = it; + auto begin = cur; + + if (*cur != '[') { + if (!mustExists) { return ""; } - cur ++; + this->m_error = true; + this->m_errorInfo = "Expected an array but found nothing"; + return ""; + } - while (cur != this->m_content.end () && (this->isChar (cur) || *cur == '_' || this->isNumeric (cur))) cur ++; + ++cur; + while (cur != this->m_content.end () && *cur != ']') + ++cur; + + it = ++cur; + + return {begin, cur}; +} + +bool Compiler::isChar (const std::string::const_iterator& it) { + return ((*it) >= 'A' && (*it) <= 'Z') || ((*it) >= 'a' && (*it) <= 'z'); +} + +bool Compiler::isNumeric (const std::string::const_iterator& it) { + return (*it) >= '0' && (*it) <= '9'; +} + +std::string Compiler::extractQuotedValue (std::string::const_iterator& it) { + std::string::const_iterator cur = it; + + if (*cur != '"') { + m_error = true; + m_errorInfo = std::string ("Expected opening \" but got ") + (*cur); + return ""; + } + + ++cur; + + while (cur != this->m_content.end () && *cur != '\n' && *cur != '"') + ++cur; + + if (cur == this->m_content.end ()) { + m_error = true; + m_errorInfo = "Expected closing \" not found"; it = cur; - - return {begin, cur}; + return ""; } - std::string Compiler::extractArray(std::string::const_iterator &it, bool mustExists) - { - std::string::const_iterator cur = it; - std::string::const_iterator begin = cur; + std::string filename = std::string (++it, cur); - if (*cur != '[') - { - if (!mustExists) - return ""; + it = ++cur; - this->m_error = true; - this->m_errorInfo = "Expected an array but found nothing"; - return ""; - } + return filename; +} - cur ++; +std::string Compiler::lookupShaderFile (std::string filename) { + // now compile the new shader + // do not include the default header (as it's already included in the parent) + Compiler loader (this->m_container, std::move (filename), Type_Include, this->m_combos, this->m_foundCombos, + this->m_passTextures, this->m_constants, true); - while (cur != this->m_content.end () && *cur != ']') cur ++; + loader.precompile (); - it = ++cur; + return loader.getCompiled (); +} - return {begin, cur}; +std::string& Compiler::getCompiled () { + return this->m_compiledContent; +} + +void Compiler::precompile () { + // TODO: SEPARATE THIS IN TWO SO THE COMBOS ARE DETECTED FIRST AND WE DO NOT REQUIRE DOUBLE COMPILATION OF THE + // SHADER'S SOURCE +#define BREAK_IF_ERROR \ + if (this->m_error) { \ + sLog.exception ("ERROR PRE-COMPILING SHADER.", this->m_errorInfo); \ } + // parse the shader and find #includes and such things and translate them to the correct name + // also remove any #version definition to prevent errors + std::string::const_iterator it = this->m_content.begin (); - bool Compiler::isChar (std::string::const_iterator& it) - { - return ((*it) >= 'A' && (*it) <= 'Z') || ((*it) >= 'a' && (*it) <= 'z'); - } + // reset error indicator + this->m_error = false; + this->m_errorInfo = ""; + this->m_compiledContent = ""; + this->m_includesContent = ""; + this->m_includesProcessed = false; - bool Compiler::isNumeric (std::string::const_iterator& it) - { - return (*it) >= '0' && (*it) <= '9'; - } + // search preprocessor macros and parse them + while (it != this->m_content.end () && !this->m_error) { + if (*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r' || *it == '\0' || *it == '{' || *it == '}' || + *it == '[' || *it == ']' || *it == '.') { + this->m_compiledContent += *it; + ++it; + } else if (*it == '#') { + if (this->peekString ("#include ", it)) { + // ignore whitespaces + this->ignoreSpaces (it); + BREAK_IF_ERROR + // extract value between quotes + std::string filename = this->extractQuotedValue (it); + BREAK_IF_ERROR - std::string Compiler::extractQuotedValue(std::string::const_iterator& it) - { - std::string::const_iterator cur = it; + if (this->m_recursive) { + this->m_compiledContent += "// begin of include from file " + filename + "\r\n"; + this->m_compiledContent += this->lookupShaderFile (filename); + this->m_compiledContent += "\r\n// end of included from file " + filename + "\r\n"; + } else { + // load the content to the includes contents and continue with the next one + // try to find the file first + this->m_includesContent += "// begin of included from file " + filename + "\r\n"; + this->m_includesContent += this->lookupShaderFile (filename); + this->m_includesContent += "\r\n// end of included from file " + filename + "\r\n"; + } + } else { + this->m_compiledContent += '#'; + ++it; + } + } else if (*it == 'u') { + // uniforms might have extra information for their values + if (this->peekString ("uniform ", it)) { + this->ignoreSpaces (it); + std::string type = this->extractType (it); + BREAK_IF_ERROR + this->ignoreSpaces (it); + std::string name = this->extractName (it); + BREAK_IF_ERROR + this->ignoreSpaces (it); + std::string array = this->extractArray (it, false); + BREAK_IF_ERROR + this->ignoreSpaces (it); + this->expectSemicolon (it); + BREAK_IF_ERROR + this->ignoreSpaces (it); - if (*cur != '"') - { - m_error = true; - m_errorInfo = std::string ("Expected opening \" but got ") + (*cur); - return ""; - } + // check if there is any actual extra information and parse it + if (this->peekString ("//", it)) { + this->ignoreSpaces (it); + std::string::const_iterator begin = it; + this->ignoreUpToNextLineFeed (it); - cur ++; + std::string configuration; + configuration.append (begin, it); - while (cur != this->m_content.end () && *cur != '\n' && *cur != '"') cur ++; - - if (cur == this->m_content.end ()) - { - m_error = true; - m_errorInfo = "Expected closing \" not found"; - it = cur; - return ""; - } - - std::string filename = std::string (++it, cur); - - it = ++cur; - - return filename; - } - - std::string Compiler::lookupShaderFile (std::string filename) - { - // now compile the new shader - // do not include the default header (as it's already included in the parent) - Compiler loader (this->m_container, std::move (filename), Type_Include, this->m_combos, this->m_foundCombos, this->m_passTextures, this->m_constants, true); - - loader.precompile (); - - return loader.getCompiled (); - } - - std::string& Compiler::getCompiled () - { - return this->m_compiledContent; - } - - void Compiler::precompile() - { - // TODO: SEPARATE THIS IN TWO SO THE COMBOS ARE DETECTED FIRST AND WE DO NOT REQUIRE DOUBLE COMPILATION OF THE SHADER'S SOURCE -#define BREAK_IF_ERROR if (this->m_error) { sLog.exception ("ERROR PRE-COMPILING SHADER.", this->m_errorInfo); } - // parse the shader and find #includes and such things and translate them to the correct name - // also remove any #version definition to prevent errors - std::string::const_iterator it = this->m_content.begin (); - - // reset error indicator - this->m_error = false; - this->m_errorInfo = ""; - this->m_compiledContent = ""; - this->m_includesContent = ""; - this->m_includesProcessed = false; - - // search preprocessor macros and parse them - while (it != this->m_content.end () && !this->m_error) - { - if (*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r' || *it == '\0' || *it == '{' || *it == '}' || *it == '[' || *it == ']' || *it == '.') - { + // parse the parameter information + this->parseParameterConfiguration (type, name, configuration); + BREAK_IF_ERROR + this->m_compiledContent += "uniform "; + this->m_compiledContent += type; + this->m_compiledContent += " "; + this->m_compiledContent += name; + this->m_compiledContent += array; + this->m_compiledContent += "; // "; + this->m_compiledContent += configuration; + } else { + this->m_compiledContent += "uniform "; + this->m_compiledContent += type; + this->m_compiledContent += " "; + this->m_compiledContent += name; + this->m_compiledContent += array; + this->m_compiledContent += ";"; + } + } else { + // continue reading the original shader as this most likely is a variable name or something + // that is not really interesting for the compiler this->m_compiledContent += *it; - it ++; + ++it; } - else if (*it == '#') - { - if (this->peekString ("#include ", it)) - { - // ignore whitespaces - this->ignoreSpaces (it); BREAK_IF_ERROR - // extract value between quotes - std::string filename = this->extractQuotedValue (it); BREAK_IF_ERROR + } else if (*it == 'a') { + // find attribute definitions + if (this->peekString ("attribute ", it)) { + this->ignoreSpaces (it); + std::string type = this->extractType (it); + BREAK_IF_ERROR + this->ignoreSpaces (it); + std::string name = this->extractName (it); + BREAK_IF_ERROR + this->ignoreSpaces (it); + std::string array = this->extractArray (it, false); + BREAK_IF_ERROR + this->ignoreSpaces (it); + this->expectSemicolon (it); + BREAK_IF_ERROR - if (this->m_recursive) - { - this->m_compiledContent += "// begin of include from file " + filename + "\r\n"; - this->m_compiledContent += this->lookupShaderFile (filename); - this->m_compiledContent += "\r\n// end of included from file " + filename + "\r\n"; - } - else - { - // load the content to the includes contents and continue with the next one - // try to find the file first - this->m_includesContent += "// begin of included from file " + filename + "\r\n"; - this->m_includesContent += this->lookupShaderFile (filename); - this->m_includesContent += "\r\n// end of included from file " + filename + "\r\n"; - } - } - else - { - this->m_compiledContent += '#'; - it ++; - } - } - else if (*it == 'u') - { - // uniforms might have extra information for their values - if (this->peekString ("uniform ", it)) - { - this->ignoreSpaces (it); - std::string type = this->extractType (it); BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string name = this->extractName (it); BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string array = this->extractArray (it, false); BREAK_IF_ERROR - this->ignoreSpaces (it); - this->expectSemicolon (it); BREAK_IF_ERROR - this->ignoreSpaces (it); - - // check if there is any actual extra information and parse it - if (this->peekString ("//", it)) - { - this->ignoreSpaces (it); - std::string::const_iterator begin = it; - this->ignoreUpToNextLineFeed (it); - - std::string configuration; configuration.append (begin, it); - - // parse the parameter information - this->parseParameterConfiguration (type, name, configuration); BREAK_IF_ERROR - this->m_compiledContent += "uniform "; - this->m_compiledContent += type; - this->m_compiledContent += " "; - this->m_compiledContent += name; - this->m_compiledContent += array; - this->m_compiledContent += "; // "; - this->m_compiledContent += configuration; - } - else - { - this->m_compiledContent += "uniform "; - this->m_compiledContent += type; - this->m_compiledContent += " "; - this->m_compiledContent += name; - this->m_compiledContent += array; - this->m_compiledContent += ";"; - } - } - else - { - // continue reading the original shader as this most likely is a variable name or something - // that is not really interesting for the compiler - this->m_compiledContent += *it; - it ++; - } - } - else if (*it == 'a') - { - // find attribute definitions - if (this->peekString ("attribute ", it)) - { - this->ignoreSpaces (it); - std::string type = this->extractType (it); BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string name = this->extractName (it); BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string array = this->extractArray (it, false); BREAK_IF_ERROR - this->ignoreSpaces (it); - this->expectSemicolon (it); BREAK_IF_ERROR - - this->m_compiledContent += "attribute " + type + " " + name + array + ";"; - } - else - { - // check for types first - std::string type = this->extractType (it); - - // types not found, try names - if (!this->m_error) - { - this->ignoreSpaces (it); - this->m_compiledContent += type; - } - else - { - this->m_error = false; - std::string name = this->extractName (it); - - if (!this->m_error) - { - // check if the name is a translated one or not - this->m_compiledContent += name; - } - else - { - this->m_error = false; - this->m_compiledContent += *it; - it ++; - } - } - } - } - else if (*it == '/') - { - if (this->peekString ("//", it)) - { - std::string::const_iterator begin = it - 2; - // is there a COMBO mark to take care of? - this->ignoreSpaces (it); - - if (this->peekString ("[COMBO]", it)) - { - // parse combo json data to define the proper variables - this->ignoreSpaces (it); - begin = it; - this->ignoreUpToNextLineFeed (it); - - std::string configuration; configuration.append (begin, it); - - this->m_compiledContent += "// [COMBO] " + configuration; - - this->parseComboConfiguration (configuration, 0); BREAK_IF_ERROR; - } - else if (this->peekString ("[COMBO_OFF]", it)) - { - // parse combo json data to define the proper variables - this->ignoreSpaces (it); - begin = it; - this->ignoreUpToNextLineFeed (it); - - std::string configuration; configuration.append (begin, it); - - this->m_compiledContent += "// [COMBO_OFF] " + configuration; - - this->parseComboConfiguration (configuration, 0); BREAK_IF_ERROR; - } - else - { - // the comment can be ignored and put back as is - this->ignoreUpToNextLineFeed(it); - this->m_compiledContent.append (begin, it); - } - } - else if (this->peekString ("/*", it)) - { - std::string::const_iterator begin = it - 2; - this->ignoreUpToBlockCommentEnd (it); - this->m_compiledContent.append (begin, it); - } - else - { - this->m_compiledContent += *it; - it ++; - } - } - else - { + this->m_compiledContent += "attribute " + type + " " + name + array + ";"; + } else { // check for types first std::string type = this->extractType (it); - // type found - if (!this->m_error) - { + // types not found, try names + if (!this->m_error) { this->ignoreSpaces (it); - // check for main, and take it into account, this also helps adding the includes - std::string name = this->extractName (it); - - this->ignoreSpaces (it); - - if (this->peekString ("(", it)) - { - if (!this->m_includesProcessed) - { - this->m_compiledContent += "\n\n" + this->m_includesContent + "\n\n"; - this->m_includesProcessed = true; - } - - this->m_compiledContent += type + " " + name + "("; - } - else - { - this->m_compiledContent += type + " " + name; - } - } - else - { + this->m_compiledContent += type; + } else { this->m_error = false; std::string name = this->extractName (it); - if (!this->m_error) - { + if (!this->m_error) { // check if the name is a translated one or not this->m_compiledContent += name; - } - else - { + } else { this->m_error = false; - this->m_compiledContent += *it++; + this->m_compiledContent += *it; + ++it; } } } - } + } else if (*it == '/') { + if (this->peekString ("//", it)) { + std::string::const_iterator begin = it - 2; + // is there a COMBO mark to take care of? + this->ignoreSpaces (it); - std::string finalCode; + if (this->peekString ("[COMBO]", it)) { + // parse combo json data to define the proper variables + this->ignoreSpaces (it); + begin = it; + this->ignoreUpToNextLineFeed (it); - if (!this->m_recursive) - { - // add the opengl compatibility at the top - finalCode = "#version 330\n" - "// ======================================================\n" - "// Processed shader " + this->m_file + "\n" - "// ======================================================\n" - "precision highp float;\n" - "#define mul(x, y) ((y) * (x))\n" - "#define max(x, y) max (y, x)\n" - "#define lerp mix\n" - "#define frac fract\n" - "#define CAST2(x) (vec2(x))\n" - "#define CAST3(x) (vec3(x))\n" - "#define CAST4(x) (vec4(x))\n" - "#define CAST3X3(x) (mat3(x))\n" - "#define saturate(x) (clamp(x, 0.0, 1.0))\n" - "#define texSample2D texture\n" - "#define texSample2DLod textureLod\n" - "#define atan2 atan\n" - "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n" - "#define ddx dFdx\n" - "#define ddy(x) dFdy(-(x))\n" - "#define GLSL 1\n\n"; + std::string configuration; + configuration.append (begin, it); - if (this->m_type == Type_Vertex) - { - finalCode += "#define attribute in\n" - "#define varying out\n"; - } - else - { - finalCode += "out vec4 out_FragColor;\n" - "#define varying in\n"; + this->m_compiledContent += "// [COMBO] " + configuration; + + this->parseComboConfiguration (configuration, 0); + BREAK_IF_ERROR; + } else if (this->peekString ("[COMBO_OFF]", it)) { + // parse combo json data to define the proper variables + this->ignoreSpaces (it); + begin = it; + this->ignoreUpToNextLineFeed (it); + + std::string configuration; + configuration.append (begin, it); + + this->m_compiledContent += "// [COMBO_OFF] " + configuration; + + this->parseComboConfiguration (configuration, 0); + BREAK_IF_ERROR; + } else { + // the comment can be ignored and put back as is + this->ignoreUpToNextLineFeed (it); + this->m_compiledContent.append (begin, it); + } + } else if (this->peekString ("/*", it)) { + std::string::const_iterator begin = it - 2; + this->ignoreUpToBlockCommentEnd (it); + this->m_compiledContent.append (begin, it); + } else { + this->m_compiledContent += *it; + ++it; } + } else { + // check for types first + std::string type = this->extractType (it); - finalCode += "// ======================================================\n" - "// Shader combo parameter definitions\n" - "// ======================================================\n"; + // type found + if (!this->m_error) { + this->ignoreSpaces (it); + // check for main, and take it into account, this also helps adding the includes + std::string name = this->extractName (it); - finalCode += "// found combos from current shader\n"; + this->ignoreSpaces (it); - // add combo values - for (const auto& cur : *this->m_foundCombos) - { - // find the right value for the combo in the combos map - auto combo = this->m_combos->find (cur.first); + if (this->peekString ("(", it)) { + if (!this->m_includesProcessed) { + this->m_compiledContent += "\n\n" + this->m_includesContent + "\n\n"; + this->m_includesProcessed = true; + } - if (combo == this->m_combos->end ()) - continue; + this->m_compiledContent += type + " " + name + "("; + } else { + this->m_compiledContent += type + " " + name; + } + } else { + this->m_error = false; + std::string name = this->extractName (it); - finalCode += "#define " + cur.first + " " + std::to_string ((*combo).second) + "\n"; - } - - finalCode += "// combos from pass\n"; - - // add base combos that come from the pass change that MUST be added - for (const auto& cur : this->m_baseCombos) - { - auto alreadyFound = this->m_foundCombos->find (cur.first); - - if (alreadyFound != this->m_foundCombos->end ()) - continue; - - finalCode += "#define " + cur.first + " " + std::to_string (cur.second) + "\n"; + if (!this->m_error) { + // check if the name is a translated one or not + this->m_compiledContent += name; + } else { + this->m_error = false; + this->m_compiledContent += *it++; + } } } + } - // replace gl_FragColor with the equivalent - std::string from = "gl_FragColor"; - std::string to = "out_FragColor"; + std::string finalCode; - size_t start_pos = 0; - while((start_pos = this->m_compiledContent.find(from, start_pos)) != std::string::npos) { - this->m_compiledContent.replace(start_pos, from.length(), to); - start_pos += to.length(); // Handles case where 'to' is a substring of 'from' + if (!this->m_recursive) { + // add the opengl compatibility at the top + finalCode = "#version 330\n" + "// ======================================================\n" + "// Processed shader " + + this->m_file + + "\n" + "// ======================================================\n" + "precision highp float;\n" + "#define mul(x, y) ((y) * (x))\n" + "#define max(x, y) max (y, x)\n" + "#define lerp mix\n" + "#define frac fract\n" + "#define CAST2(x) (vec2(x))\n" + "#define CAST3(x) (vec3(x))\n" + "#define CAST4(x) (vec4(x))\n" + "#define CAST3X3(x) (mat3(x))\n" + "#define saturate(x) (clamp(x, 0.0, 1.0))\n" + "#define texSample2D texture\n" + "#define texSample2DLod textureLod\n" + "#define atan2 atan\n" + "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n" + "#define ddx dFdx\n" + "#define ddy(x) dFdy(-(x))\n" + "#define GLSL 1\n\n"; + + if (this->m_type == Type_Vertex) { + finalCode += "#define attribute in\n" + "#define varying out\n"; + } else { + finalCode += "out vec4 out_FragColor;\n" + "#define varying in\n"; } - // replace sample occurrences - from = "sample"; - to = "_sample"; + finalCode += "// ======================================================\n" + "// Shader combo parameter definitions\n" + "// ======================================================\n"; - start_pos = 0; - while((start_pos = this->m_compiledContent.find(from, start_pos)) != std::string::npos) { - // ensure that after it comes something like a space or a ; or a tab - std::string after = this->m_compiledContent.substr (start_pos + from.length (), 1); + finalCode += "// found combos from current shader\n"; - if ( - after != " " && after != ";" && after != "\t" && - after != "=" && after != "+" && after != "-" && - after != "/" && after != "*" && after != "." && - after != "," && after != ")") - { - start_pos += to.length(); // Handles case where 'to' is a substring of 'from' + // add combo values + for (const auto& [name, value] : *this->m_foundCombos) { + // find the right value for the combo in the combos map + auto combo = this->m_combos->find (name); + + if (combo == this->m_combos->end ()) continue; - } - this->m_compiledContent.replace(start_pos, from.length(), to); - start_pos += to.length(); // Handles case where 'to' is a substring of 'from' + finalCode += "#define " + name + " " + std::to_string (combo->second) + "\n"; } - try - { - this->applyPatches (); + finalCode += "// combos from pass\n"; + + // add base combos that come from the pass change that MUST be added + for (const auto& [name, value] : this->m_baseCombos) { + auto alreadyFound = this->m_foundCombos->find (name); + + if (alreadyFound != this->m_foundCombos->end ()) + continue; + + finalCode += "#define " + name + " " + std::to_string (value) + "\n"; } - catch (CAssetLoadException&) - { - // nothing important, no patch was found + } + + // replace gl_FragColor with the equivalent + std::string from = "gl_FragColor"; + std::string to = "out_FragColor"; + + size_t start_pos = 0; + while ((start_pos = this->m_compiledContent.find (from, start_pos)) != std::string::npos) { + this->m_compiledContent.replace (start_pos, from.length (), to); + start_pos += to.length (); // Handles case where 'to' is a substring of 'from' + } + + // replace sample occurrences + from = "sample"; + to = "_sample"; + + start_pos = 0; + while ((start_pos = this->m_compiledContent.find (from, start_pos)) != std::string::npos) { + // ensure that after it comes something like a space or a ; or a tab + std::string after = this->m_compiledContent.substr (start_pos + from.length (), 1); + + if (after != " " && after != ";" && after != "\t" && after != "=" && after != "+" && after != "-" && + after != "/" && after != "*" && after != "." && after != "," && after != ")") { + start_pos += to.length (); // Handles case where 'to' is a substring of 'from' + continue; } - finalCode += this->m_compiledContent; + this->m_compiledContent.replace (start_pos, from.length (), to); + start_pos += to.length (); // Handles case where 'to' is a substring of 'from' + } - if (!this->m_recursive) - { - sLog.debug("======================== COMPILED ", (this->m_type == Type_Vertex ? "VERTEX" : "FRAGMENT"), " SHADER ", this->m_file, " ========================"); - sLog.debug(finalCode); - } + try { + this->applyPatches (); + } catch (CAssetLoadException&) { + // nothing important, no patch was found + } - // store the final final code here - this->m_compiledContent = finalCode; + finalCode += this->m_compiledContent; + + if (!this->m_recursive) { + sLog.debug ("======================== COMPILED ", (this->m_type == Type_Vertex ? "VERTEX" : "FRAGMENT"), + " SHADER ", this->m_file, " ========================"); + sLog.debug (finalCode); + } + + // store the final final code here + this->m_compiledContent = finalCode; #undef BREAK_IF_ERROR - } - - void Compiler::applyPatches () - { - // small patches for things, looks like the official wpengine does the same thing - std::filesystem::path file = this->m_file; - file = "patches" / file.filename (); - - if (this->m_type == Type_Vertex) - file += ".vert"; - else if (this->m_type == Type_Pixel) - file += ".frag"; - - file += ".json"; - - std::string tmp = file; - std::string patchContents = this->m_container->readFileAsString (file); - - json data = json::parse (patchContents); - auto patches = data.find ("patches"); - - for (auto patch : *patches) - { - auto matches = patch.find ("matches"); - - // check for matches first, as these signal whether the patch can be applied or not - for (const auto& match : *matches) - if (this->m_compiledContent.find (match) == std::string::npos) - continue; - - auto replacements = patch.find ("replacements"); - - for (const auto& replacement : (*replacements).items ()) - { - // replace gl_FragColor with the equivalent - std::string from = replacement.key (); - std::string to = replacement.value (); - - size_t start_pos = 0; - while((start_pos = this->m_compiledContent.find(from, start_pos)) != std::string::npos) { - this->m_compiledContent.replace(start_pos, from.length(), to); - start_pos += to.length(); // Handles case where 'to' is a substring of 'from' - } - } - } - } - - void Compiler::parseComboConfiguration (const std::string& content, int defaultValue) - { - json data = json::parse (content); - auto combo = jsonFindRequired (data, "combo", "cannot parse combo information"); - auto type = data.find ("type"); - auto defvalue = data.find ("default"); - - // add line feed just in case - this->m_compiledContent += "\n"; - - // check the combos - auto entry = this->m_combos->find ((*combo).get ()); - - // add the combo to the found list - this->m_foundCombos->insert (std::make_pair (*combo, true)); - - // if the combo was not found in the predefined values this means that the default value in the JSON data can be used - // so only define the ones that are not already defined - if (entry == this->m_combos->end ()) - { - if (type != data.end ()) - sLog.error ("Resorting to default value as type ", *type, " is unknown"); - - // if no combo is defined just load the default settings - if (defvalue == data.end ()) - { - // TODO: PROPERLY SUPPORT EMPTY COMBOS - this->m_combos->insert (std::make_pair (*combo, (int) defaultValue)); - } - else if ((*defvalue).is_number_float ()) - { - sLog.exception ("float combos are not supported in shader ", this->m_file, ". ", *combo); - } - else if ((*defvalue).is_number_integer ()) - { - this->m_combos->insert (std::make_pair (*combo, (*defvalue).get ())); - } - else if ((*defvalue).is_string ()) - { - sLog.exception ("string combos are not supported in shader ", this->m_file, ". ", *combo); - } - else - { - sLog.exception ("cannot parse combo information ", *combo, ". unknown type for ", defvalue->dump ()); - } - } - } - - void Compiler::parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content) - { - json data = json::parse (content); - auto material = data.find ("material"); - auto defvalue = data.find ("default"); - auto range = data.find ("range"); - auto combo = data.find ("combo"); - - // this is not a real parameter - auto constant = this->m_constants.end (); - - if (material != data.end ()) - constant = this->m_constants.find (*material); - - if (constant == this->m_constants.end () && defvalue == data.end ()) - { - if (type != "sampler2D") - sLog.exception ("Cannot parse parameter data for ", name, " in shader ", this->m_file); - } - - Variables::CShaderVariable* parameter = nullptr; - - // TODO: SUPPORT VALUES FOR ALL THESE TYPES - if (type == "vec4") - { - parameter = new Variables::CShaderVariableVector4 ( - constant == this->m_constants.end () - ? WallpaperEngine::Core::aToVector4 (*defvalue) - : *(*constant).second->as ()->getValue () - ); - } - else if (type == "vec3") - { - parameter = new Variables::CShaderVariableVector3 ( - constant == this->m_constants.end () - ? WallpaperEngine::Core::aToVector3 (*defvalue) - : *(*constant).second->as ()->getValue () - ); - } - else if (type == "vec2") - { - parameter = new Variables::CShaderVariableVector2 ( - WallpaperEngine::Core::aToVector2 (*defvalue) - ); - } - else if (type == "float") - { - float value = 0; - - if (constant == this->m_constants.end ()) - value = (*defvalue).get (); - else if ((*constant).second->is ()) - value = *(*constant).second->as ()->getValue (); - else if ((*constant).second->is ()) - value = *(*constant).second->as ()->getValue (); - - parameter = new Variables::CShaderVariableFloat (value); - } - else if (type == "int") - { - int value = 0; - - if (constant == this->m_constants.end ()) - value = (*defvalue).get (); - else if ((*constant).second->is ()) - value = *(*constant).second->as ()->getValue (); - else if ((*constant).second->is ()) - value = *(*constant).second->as ()->getValue (); - - parameter = new Variables::CShaderVariableInteger (value); - } - else if (type == "sampler2D") - { - // samplers can have special requirements, check what sampler we're working with and create definitions - // if needed - auto textureName = data.find ("default"); - // extract the texture number from the name - char value = name.at (std::string("g_Texture").length ()); - // now convert it to integer - int index = value - '0'; - - if (combo != data.end ()) - { - // if the texture exists (and is not null), add to the combo - if (this->m_passTextures.size () > index && (!this->m_passTextures.at (index).empty() || textureName != data.end ())) - { - // add the new combo to the list - this->m_combos->insert (std::make_pair (*combo, 1)); - - // textures linked to combos need to be tracked too - if (this->m_foundCombos->find (*combo) == this->m_foundCombos->end ()) - this->m_foundCombos->insert (std::make_pair (*combo, true)); - } - } - - if (textureName != data.end ()) - this->m_textures.insert (std::make_pair (index, *textureName)); - - // samplers are not saved, we can ignore them for now - return; - } - else - { - this->m_error = true; - this->m_errorInfo = "Unknown parameter type: " + type + " for " + name; - return; - } - - if (material != data.end ()) - { - parameter->setIdentifierName (*material); - parameter->setName (name); - - this->m_parameters.push_back (parameter); - } - } - - Variables::CShaderVariable* Compiler::findParameter (const std::string& identifier) - { - for (const auto& cur : this->m_parameters) - if (cur->getIdentifierName () == identifier) - return cur; - - return nullptr; - } - - const std::vector & Compiler::getParameters () const - { - return this->m_parameters; - } - - std::map * Compiler::getCombos () const - { - return this->m_combos; - } - - const std::map & Compiler::getTextures () const - { - return this->m_textures; - } - - std::vector Compiler::sTypes = - { - "vec4", "uvec4", "ivec4", "dvec4", "bvec4", - "vec3", "uvec3", "ivec3", "dvec3", "bvec3", - "vec2", "uvec2", "ivec2", "dvec2", "bvec2", - "float", "sampler2D", "mat4x3", "mat4", "mat3", "uint4", - "void" - }; } + +void Compiler::applyPatches () { + // small patches for things, looks like the official wpengine does the same thing + std::filesystem::path file = this->m_file; + file = "patches" / file.filename (); + + if (this->m_type == Type_Vertex) + file += ".vert"; + else if (this->m_type == Type_Pixel) + file += ".frag"; + + file += ".json"; + + std::string tmp = file; + const std::string patchContents = this->m_container->readFileAsString (file); + + json data = json::parse (patchContents); + const auto patches = data.find ("patches"); + + for (auto patch : *patches) { + auto matches = patch.find ("matches"); + bool canApply = true; + + // check for matches first, as these signal whether the patch can be applied or not + for (const auto& match : *matches) { + if (this->m_compiledContent.find (match) == std::string::npos) { + canApply = false; + break; + } + } + + if (canApply == false) + continue; + + const auto replacements = patch.find ("replacements"); + + for (const auto& replacement : replacements->items ()) { + // replace gl_FragColor with the equivalent + std::string from = replacement.key (); + std::string to = replacement.value (); + + size_t start_pos = 0; + while ((start_pos = this->m_compiledContent.find (from, start_pos)) != std::string::npos) { + this->m_compiledContent.replace (start_pos, from.length (), to); + start_pos += to.length (); // Handles case where 'to' is a substring of 'from' + } + } + } +} + +void Compiler::parseComboConfiguration (const std::string& content, int defaultValue) { + json data = json::parse (content); + const auto combo = jsonFindRequired (data, "combo", "cannot parse combo information"); + const auto type = data.find ("type"); + const auto defvalue = data.find ("default"); + + // add line feed just in case + this->m_compiledContent += "\n"; + + // check the combos + const auto entry = this->m_combos->find (combo->get ()); + + // add the combo to the found list + this->m_foundCombos->insert (std::make_pair (*combo, true)); + + // if the combo was not found in the predefined values this means that the default value in the JSON data can be + // used so only define the ones that are not already defined + if (entry == this->m_combos->end ()) { + if (type != data.end ()) + sLog.error ("Resorting to default value as type ", *type, " is unknown"); + + // if no combo is defined just load the default settings + if (defvalue == data.end ()) { + // TODO: PROPERLY SUPPORT EMPTY COMBOS + this->m_combos->insert (std::make_pair (*combo, (int) defaultValue)); + } else if (defvalue->is_number_float ()) { + sLog.exception ("float combos are not supported in shader ", this->m_file, ". ", *combo); + } else if (defvalue->is_number_integer ()) { + this->m_combos->insert (std::make_pair (*combo, defvalue->get ())); + } else if (defvalue->is_string ()) { + sLog.exception ("string combos are not supported in shader ", this->m_file, ". ", *combo); + } else { + sLog.exception ("cannot parse combo information ", *combo, ". unknown type for ", defvalue->dump ()); + } + } +} + +void Compiler::parseParameterConfiguration (const std::string& type, const std::string& name, + const std::string& content) { + json data = json::parse (content); + const auto material = data.find ("material"); + const auto defvalue = data.find ("default"); + // auto range = data.find ("range"); + const auto combo = data.find ("combo"); + + // this is not a real parameter + auto constant = this->m_constants.end (); + + if (material != data.end ()) + constant = this->m_constants.find (*material); + + if (constant == this->m_constants.end () && defvalue == data.end ()) { + if (type != "sampler2D") + sLog.exception ("Cannot parse parameter data for ", name, " in shader ", this->m_file); + } + + Variables::CShaderVariable* parameter; + + // TODO: SUPPORT VALUES FOR ALL THESE TYPES + if (type == "vec4") { + parameter = new Variables::CShaderVariableVector4 ( + constant == this->m_constants.end () ? WallpaperEngine::Core::aToVector4 (*defvalue) + : *constant->second->as ()->getValue ()); + } else if (type == "vec3") { + parameter = new Variables::CShaderVariableVector3 ( + constant == this->m_constants.end () ? WallpaperEngine::Core::aToVector3 (*defvalue) + : *constant->second->as ()->getValue ()); + } else if (type == "vec2") { + parameter = new Variables::CShaderVariableVector2 (WallpaperEngine::Core::aToVector2 (*defvalue)); + } else if (type == "float") { + float value = 0; + + if (constant == this->m_constants.end ()) + value = defvalue->get (); + else if (constant->second->is ()) + value = *constant->second->as ()->getValue (); + else if (constant->second->is ()) + value = *constant->second->as ()->getValue (); + + parameter = new Variables::CShaderVariableFloat (value); + } else if (type == "int") { + int value = 0; + + if (constant == this->m_constants.end ()) + value = defvalue->get (); + else if (constant->second->is ()) + value = *constant->second->as ()->getValue (); + else if (constant->second->is ()) + value = *constant->second->as ()->getValue (); + + parameter = new Variables::CShaderVariableInteger (value); + } else if (type == "sampler2D") { + // samplers can have special requirements, check what sampler we're working with and create definitions + // if needed + const auto textureName = data.find ("default"); + // extract the texture number from the name + const char value = name.at (std::string ("g_Texture").length ()); + // now convert it to integer + int index = value - '0'; + + if (combo != data.end ()) { + // if the texture exists (and is not null), add to the combo + if (this->m_passTextures.size () > index && + (!this->m_passTextures.at (index).empty () || textureName != data.end ())) { + // add the new combo to the list + this->m_combos->insert (std::make_pair (*combo, 1)); + + // textures linked to combos need to be tracked too + if (this->m_foundCombos->find (*combo) == this->m_foundCombos->end ()) + this->m_foundCombos->insert (std::make_pair (*combo, true)); + } + } + + if (textureName != data.end ()) + this->m_textures.insert (std::make_pair (index, *textureName)); + + // samplers are not saved, we can ignore them for now + return; + } else { + this->m_error = true; + this->m_errorInfo = "Unknown parameter type: " + type + " for " + name; + return; + } + + if (material != data.end ()) { + parameter->setIdentifierName (*material); + parameter->setName (name); + + this->m_parameters.push_back (parameter); + } +} + +Variables::CShaderVariable* Compiler::findParameter (const std::string& identifier) { + for (const auto& cur : this->m_parameters) + if (cur->getIdentifierName () == identifier) + return cur; + + return nullptr; +} + +const std::vector& Compiler::getParameters () const { + return this->m_parameters; +} + +std::map* Compiler::getCombos () const { + return this->m_combos; +} + +const std::map& Compiler::getTextures () const { + return this->m_textures; +} + +std::vector Compiler::sTypes = { + "vec4", "uvec4", "ivec4", "dvec4", "bvec4", "vec3", "uvec3", "ivec3", "dvec3", "bvec3", "vec2", + "uvec2", "ivec2", "dvec2", "bvec2", "float", "sampler2D", "mat4x3", "mat4", "mat3", "uint4", "void"}; +} // namespace WallpaperEngine::Render::Shaders diff --git a/src/WallpaperEngine/Render/Shaders/Compiler.h b/src/WallpaperEngine/Render/Shaders/Compiler.h index 0a6f311..79d69a5 100644 --- a/src/WallpaperEngine/Render/Shaders/Compiler.h +++ b/src/WallpaperEngine/Render/Shaders/Compiler.h @@ -1,274 +1,267 @@ #pragma once #include -#include #include +#include -#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Assets/CContainer.h" #include "WallpaperEngine/Assets/ITexture.h" -#include "WallpaperEngine/FileSystem/FileSystem.h" +#include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" +#include "WallpaperEngine/FileSystem/FileSystem.h" #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" -namespace WallpaperEngine::Render::Shaders -{ - using json = nlohmann::json; - using namespace WallpaperEngine::Assets; - using namespace WallpaperEngine::Core::Objects::Effects::Constants; +namespace WallpaperEngine::Render::Shaders { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Core::Objects::Effects::Constants; + +/** + * A basic shader loader that adds basic function definitions to every loaded shader + */ +class Compiler { + public: + /** + * Types of shaders + */ + enum Type { + Type_Vertex = 0, + Type_Pixel = 1, + Type_Include = 2 + }; /** - * A basic shader loader that adds basic function definitions to every loaded shader + * Types of variables the pre-processor understands */ - class Compiler - { - public: - /** - * Types of shaders - */ - enum Type - { - Type_Vertex = 0, - Type_Pixel = 1, - Type_Include = 2 - }; + static std::vector sTypes; - /** - * Types of variables the pre-processor understands - */ - static std::vector sTypes; + /** + * Compiler constructor, loads the given shader file and prepares + * the pre-processing and compilation of the shader, adding + * required definitions if needed + * + * @param container The container to use for file lookup + * @param filename The file to load + * @param type The type of shader + * @param combos Settings for the shader + * @param foundCombos The list of currently defined combos + * @param textures The list of available textures for the shader + * @param constants Default values for shader variables + * @param recursive Whether the compiler should add base definitions or not + */ + Compiler (CContainer* container, std::string filename, Type type, std::map* combos, + std::map* foundCombos, const std::vector& textures, + const std::map& constants, bool recursive = false); + /** + * Performs the actual pre-compilation/pre-processing over the shader files + * This step is kinda big, replaces variables names on sVariableReplacement, + * ensures #include directives are correctly handled + * and takes care of attribute comments for the wallpaper engine specifics + */ + void precompile (); + /** + * @return The compiled shader's text (if available) + */ + std::string& getCompiled (); - /** - * Compiler constructor, loads the given shader file and prepares - * the pre-processing and compilation of the shader, adding - * required definitions if needed - * - * @param context The irrlicht context - * @param file The file to load - * @param type The type of shader - * @param combos Settings for the shader - * @param constants Default values for shader variables - * @param recursive Whether the compiler should add base definitions or not - */ - Compiler ( - CContainer* container, - std::string filename, - Type type, - std::map* combos, - std::map* foundCombos, - const std::vector & textures, - const std::map& constants, - bool recursive = false - ); - /** - * Performs the actual pre-compilation/pre-processing over the shader files - * This step is kinda big, replaces variables names on sVariableReplacement, - * ensures #include directives are correctly handled - * and takes care of attribute comments for the wallpaper engine specifics - */ - void precompile (); - /** - * @return The compiled shader's text (if available) - */ - std::string& getCompiled (); + /** + * Searches the list of parameters available for the parameter with the given value + * + * @param identifier The identifier to search for + * @return The shader information + */ + Variables::CShaderVariable* findParameter (const std::string& identifier); - /** - * Searches the list of parameters available for the parameter with the given value - * - * @param identifier The identifier to search for - * @return The shader information - */ - Variables::CShaderVariable* findParameter (const std::string& identifier); + /** + * @return The list of parameters available for this shader with their default values + */ + [[nodiscard]] const std::vector& getParameters () const; + /** + * @return The list of combos available for this shader after compilation + */ + [[nodiscard]] std::map* getCombos () const; + /** + * @return The list of textures inferred from the shader's code + */ + [[nodiscard]] const std::map& getTextures () const; - /** - * @return The list of parameters available for this shader with their default values - */ - [[nodiscard]] const std::vector & getParameters () const; - /** - * @return The list of combos available for this shader after compilation - */ - [[nodiscard]] std::map * getCombos () const; - /** - * @return The list of textures inferred from the shader's code - */ - [[nodiscard]] const std::map & getTextures () const; + private: + /** + * Checks if there is "str" in the current position without advancing the + * iterator in use + * + * @param str The string to check for + * @param it The position to start checking at + * + * @return + */ + bool peekString (std::string str, std::string::const_iterator& it); + /** + * Checks for a semicolon as current character, advancing the iterator + * after finding it, otherwise returns an error + * + * @param it The position where to expect the semicolon + * + * @return + */ + bool expectSemicolon (std::string::const_iterator& it); + /** + * Ignores contiguous space characters in the string advancing the iterator + * until the first non-space character + * + * @param it The iterator to increase + */ + void ignoreSpaces (std::string::const_iterator& it); + /** + * Ignores all characters until next line-fee (\n) advancing the interator + * + * @param it The iterator to increase + */ + void ignoreUpToNextLineFeed (std::string::const_iterator& it); + /** + * Ignores all characters until a block comment end is found, advancing the iterator + * + * @param it The iterator to increase + */ + void ignoreUpToBlockCommentEnd (std::string::const_iterator& it); + /** + * Parses the current position as a variable type, extracts it and compares it + * to the registered types in the pre-processor, returning it's name if valid + * increasing the iterator at the same time + * + * @param it The position to extract it from + * + * @return The type name + */ + std::string extractType (std::string::const_iterator& it); + /** + * Parses the current position as a variable name, extractig it's name and + * increasing the iterator as the name is extracted + * + * @param it The position to start extracting the variable name from + * + * @return The variable name + */ + std::string extractName (std::string::const_iterator& it); + /** + * Parses the current position as an array indicator + * + * @param it The position to start extracting the array from + * @param mustExists Whether the array indicator must exists or not + * @return + */ + std::string extractArray (std::string::const_iterator& it, bool mustExists = false); + /** + * Parses the current position as a quoted value, extracting it's value + * and increasing the iterator at the same time + * + * @param it The position to start extracting the value from + * + * @return The value + */ + std::string extractQuotedValue (std::string::const_iterator& it); + /** + * Tries to find the given shader file and compile it + * + * @param filename The shader's filename + * + * @return The compiled contents + */ + std::string lookupShaderFile (std::string filename); - private: - /** - * Checks if there is "str" in the current position without advancing the - * iterator in use - * - * @param str The string to check for - * @param it The position to start checking at - * - * @return - */ - bool peekString (std::string str, std::string::const_iterator& it); - /** - * Checks for a semicolon as current character, advancing the iterator - * after finding it, otherwise returns an error - * - * @param it The position where to expect the semicolon - * - * @return - */ - bool expectSemicolon (std::string::const_iterator& it); - /** - * Ignores contiguous space characters in the string advancing the iterator - * until the first non-space character - * - * @param it The iterator to increase - */ - void ignoreSpaces (std::string::const_iterator& it); - /** - * Ignores all characters until next line-fee (\n) advancing the interator - * - * @param it The iterator to increase - */ - void ignoreUpToNextLineFeed (std::string::const_iterator& it); - /** - * Ignores all characters until a block comment end is found, advancing the iterator - * - * @param it The iterator to increase - */ - void ignoreUpToBlockCommentEnd (std::string::const_iterator& it); - /** - * Parses the current position as a variable type, extracts it and compares it - * to the registered types in the pre-processor, returning it's name if valid - * increasing the iterator at the same time - * - * @param it The position to extract it from - * - * @return The type name - */ - std::string extractType (std::string::const_iterator& it); - /** - * Parses the current position as a variable name, extractig it's name and - * increasing the iterator as the name is extracted - * - * @param it The position to start extracting the variable name from - * - * @return The variable name - */ - std::string extractName (std::string::const_iterator& it); - /** - * Parses the current position as an array indicator - * - * @param it The position to start extracting the array from - * @param mustExists Whether the array indicator must exists or not - * @return - */ - std::string extractArray(std::string::const_iterator &it, bool mustExists = false); - /** - * Parses the current position as a quoted value, extracting it's value - * and increasing the iterator at the same time - * - * @param it The position to start extracting the value from - * - * @return The value - */ - std::string extractQuotedValue (std::string::const_iterator& it); - /** - * Tries to find the given shader file and compile it - * - * @param filename The shader's filename - * - * @return The compiled contents - */ - std::string lookupShaderFile (std::string filename); + /** + * @return Whether the character in the current position is a character or not + */ + static bool isChar (const std::string::const_iterator& it); + /** + * @return Whether the character in the current position is a number or not + */ + static bool isNumeric (const std::string::const_iterator& it); + /** + * Parses a COMBO value to add the proper define to the code + * + * @param content The parameter configuration + * @param defaultValue + */ + void parseComboConfiguration (const std::string& content, int defaultValue = 0); + /** + * Parses a parameter extra metadata created by wallpaper engine + * + * @param type The type of variable to parse + * @param name The name of the variable in the shader (for actual variable declaration) + * @param content The parameter configuration + */ + void parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content); + /** + * Applies any available patches for this shader + */ + void applyPatches (); - /** - * @return Whether the character in the current position is a character or not - */ - static bool isChar (std::string::const_iterator& it); - /** - * @return Whether the character in the current position is a number or not - */ - static bool isNumeric (std::string::const_iterator& it); - /** - * Parses a COMBO value to add the proper define to the code - * - * @param content The parameter configuration - */ - void parseComboConfiguration (const std::string& content, int defaultValue = 0); - /** - * Parses a parameter extra metadata created by wallpaper engine - * - * @param type The type of variable to parse - * @param name The name of the variable in the shader (for actual variable declaration) - * @param content The parameter configuration - */ - void parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content); - /** - * Applies any available patches for this shader - */ - void applyPatches (); + /** + * The shader file this instance is loading + */ + std::string m_file; + /** + * The original file content + */ + std::string m_content; + /** The content of all the included files */ + std::string m_includesContent; + /** + * The final, compiled content ready to be used by OpenGL + */ + std::string m_compiledContent; + /** + * Whether there was any kind of error in the compilation or not + */ + bool m_error; + /** + * Extra information about the error (if any) + */ + std::string m_errorInfo; + /** + * The type of shader + */ + Type m_type; + /** + * The parameters the shader needs + */ + std::vector m_parameters; + /** + * The combos the shader should be generated with + */ + std::map* m_combos; - /** - * The shader file this instance is loading - */ - std::string m_file; - /** - * The original file content - */ - std::string m_content; - /** The content of all the included files */ - std::string m_includesContent; - /** - * The final, compiled content ready to be used by OpenGL - */ - std::string m_compiledContent; - /** - * Whether there was any kind of error in the compilation or not - */ - bool m_error; - /** - * Extra information about the error (if any) - */ - std::string m_errorInfo; - /** - * The type of shader - */ - Type m_type; - /** - * The parameters the shader needs - */ - std::vector m_parameters; - /** - * The combos the shader should be generated with - */ - std::map * m_combos; + /** + * Combos that come from the pass' chain that should be added + */ + std::map m_baseCombos; - /** - * Combos that come from the pass' chain that should be added - */ - std::map m_baseCombos; + /** + * The combos the shader code has defined (shared between fragment and vertex) + */ + std::map* m_foundCombos; - /** - * The combos the shader code has defined (shared between fragment and vertex) - */ - std::map * m_foundCombos; - - /** - * The list of textures the pass knows about - */ - const std::vector m_passTextures; - /** - * The shader constants with values for variables inside the shader - */ - const std::map& m_constants; - /** - * Whether this compilation is a recursive one or not - */ - bool m_recursive; - /** - * The container to load files from - */ - CContainer* m_container; - /** - * List of textures that the shader expects (inferred from sampler2D and it's JSON data) - */ - std::map m_textures; - bool m_includesProcessed = false; - }; -} + /** + * The list of textures the pass knows about + */ + const std::vector m_passTextures; + /** + * The shader constants with values for variables inside the shader + */ + const std::map& m_constants; + /** + * Whether this compilation is a recursive one or not + */ + bool m_recursive; + /** + * The container to load files from + */ + CContainer* m_container; + /** + * List of textures that the shader expects (inferred from sampler2D and it's JSON data) + */ + std::map m_textures; + bool m_includesProcessed = false; +}; +} // namespace WallpaperEngine::Render::Shaders diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp index 621accc..ecfe9ae 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp @@ -7,45 +7,35 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariable::CShaderVariable (void* defaultValue, void* value, std::string type) : m_defaultValue (defaultValue), m_value (value), - m_type (std::move(type)) -{ + m_type (std::move (type)) {} -} - -const void* CShaderVariable::getValue () const -{ +const void* CShaderVariable::getValue () const { if (this->m_value) return this->m_value; return this->m_defaultValue; } -void CShaderVariable::setValue (void* value) -{ +void CShaderVariable::setValue (void* value) { this->m_value = value; } -const std::string& CShaderVariable::getIdentifierName () const -{ +const std::string& CShaderVariable::getIdentifierName () const { return this->m_identifierName; } -const std::string& CShaderVariable::getName () const -{ +const std::string& CShaderVariable::getName () const { return this->m_name; } -const std::string& CShaderVariable::getType () const -{ +const std::string& CShaderVariable::getType () const { return this->m_type; } -void CShaderVariable::setIdentifierName (std::string identifierName) -{ - this->m_identifierName = std::move(identifierName); +void CShaderVariable::setIdentifierName (std::string identifierName) { + this->m_identifierName = std::move (identifierName); } -void CShaderVariable::setName (const std::string& name) -{ +void CShaderVariable::setName (const std::string& name) { this->m_name = name; } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h index 241f147..ebc00ef 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h @@ -2,37 +2,45 @@ #include -namespace WallpaperEngine::Render::Shaders::Variables -{ - class CShaderVariable - { - public: - CShaderVariable (void* defaultValue, void* value, std::string type); +namespace WallpaperEngine::Render::Shaders::Variables { +class CShaderVariable { + public: + CShaderVariable (void* defaultValue, void* value, std::string type); + virtual ~CShaderVariable () = default; - template const T* as () const { assert (is ()); return (const T*) this; } - template T* as () { assert (is ()); return (T*) this; } + template const T* as () const { + assert (is ()); + return reinterpret_cast (this); + } - template bool is () { return this->m_type == T::Type; } + template T* as () { + assert (is ()); + return reinterpret_cast (this); + } - const std::string& getIdentifierName () const; - const std::string& getName () const; - const std::string& getType () const; + template bool is () { + return this->m_type == T::Type; + } - void setIdentifierName (std::string identifierName); - void setName (const std::string& name); - const void* getValue () const; + const std::string& getIdentifierName () const; + const std::string& getName () const; + const std::string& getType () const; - virtual const int getSize () const = 0; + void setIdentifierName (std::string identifierName); + void setName (const std::string& name); + const void* getValue () const; - protected: - void setValue (void* value); + virtual const int getSize () const = 0; - private: - std::string m_identifierName; - std::string m_name; - std::string m_type; + protected: + void setValue (void* value); - void* m_defaultValue; - void* m_value; - }; -} + private: + std::string m_identifierName; + std::string m_name; + std::string m_type; + + void* m_defaultValue; + void* m_value; +}; +} // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp index 44cc17d..07d7e12 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp @@ -4,30 +4,25 @@ using namespace WallpaperEngine::Render::Shaders::Variables; -CShaderVariableFloat::CShaderVariableFloat(float defaultValue) : +CShaderVariableFloat::CShaderVariableFloat (float defaultValue) : m_defaultValue (defaultValue), m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ -} + CShaderVariable (&this->m_defaultValue, nullptr, Type) {} -CShaderVariableFloat::CShaderVariableFloat(float defaultValue, const std::string& name) : +CShaderVariableFloat::CShaderVariableFloat (float defaultValue, const std::string& name) : m_defaultValue (defaultValue), m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ + CShaderVariable (&this->m_defaultValue, nullptr, Type) { this->setName (name); } -void CShaderVariableFloat::setValue (float value) -{ +void CShaderVariableFloat::setValue (float value) { this->m_value = value; CShaderVariable::setValue (&this->m_value); } -const int CShaderVariableFloat::getSize () const -{ +const int CShaderVariableFloat::getSize () const { return 1; } diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h index df1527b..e60c460 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h @@ -2,22 +2,20 @@ #include "CShaderVariable.h" -namespace WallpaperEngine::Render::Shaders::Variables -{ - class CShaderVariableFloat : public CShaderVariable - { - public: - explicit CShaderVariableFloat (float defaultValue); - CShaderVariableFloat (float defaultValue, const std::string& name); +namespace WallpaperEngine::Render::Shaders::Variables { +class CShaderVariableFloat final : public CShaderVariable { + public: + explicit CShaderVariableFloat (float defaultValue); + CShaderVariableFloat (float defaultValue, const std::string& name); - const int getSize () const override; + const int getSize () const override; - void setValue (float value); + void setValue (float value); - static const std::string Type; + static const std::string Type; - private: - float m_defaultValue; - float m_value; - }; -} + private: + float m_defaultValue; + float m_value; +}; +} // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp index c1c49a5..117c753 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp @@ -4,29 +4,24 @@ using namespace WallpaperEngine::Render::Shaders::Variables; -CShaderVariableInteger::CShaderVariableInteger(int32_t defaultValue) : +CShaderVariableInteger::CShaderVariableInteger (int32_t defaultValue) : m_defaultValue (defaultValue), m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ -} + CShaderVariable (&this->m_defaultValue, nullptr, Type) {} -CShaderVariableInteger::CShaderVariableInteger(int32_t defaultValue, std::string name) : +CShaderVariableInteger::CShaderVariableInteger (int32_t defaultValue, std::string name) : m_defaultValue (defaultValue), m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ - this->setName (std::move(name)); + CShaderVariable (&this->m_defaultValue, nullptr, Type) { + this->setName (std::move (name)); } -void CShaderVariableInteger::setValue (int32_t value) -{ +void CShaderVariableInteger::setValue (int32_t value) { this->m_value = value; CShaderVariable::setValue (&this->m_value); } -const int CShaderVariableInteger::getSize () const -{ +const int CShaderVariableInteger::getSize () const { return 1; } diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h index 87af9ca..1011d92 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h @@ -2,22 +2,20 @@ #include "CShaderVariable.h" -namespace WallpaperEngine::Render::Shaders::Variables -{ - class CShaderVariableInteger : public CShaderVariable - { - public: - explicit CShaderVariableInteger (int32_t defaultValue); - CShaderVariableInteger (int32_t defaultValue, std::string name); +namespace WallpaperEngine::Render::Shaders::Variables { +class CShaderVariableInteger final : public CShaderVariable { + public: + explicit CShaderVariableInteger (int32_t defaultValue); + CShaderVariableInteger (int32_t defaultValue, std::string name); - const int getSize () const override; + const int getSize () const override; - static const std::string Type; + static const std::string Type; - void setValue (int32_t value); + void setValue (int32_t value); - private: - int32_t m_defaultValue; - int32_t m_value; - }; -} + private: + int32_t m_defaultValue; + int32_t m_value; +}; +} // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp index 5c9e515..4e89c22 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp @@ -7,28 +7,22 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableVector2::CShaderVariableVector2 (const glm::vec2& defaultValue) : m_defaultValue (defaultValue), m_value (glm::vec2 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ -} + CShaderVariable (&this->m_defaultValue, nullptr, Type) {} CShaderVariableVector2::CShaderVariableVector2 (const glm::vec2& defaultValue, std::string name) : m_defaultValue (defaultValue), m_value (glm::vec2 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ - this->setName (std::move(name)); + CShaderVariable (&this->m_defaultValue, nullptr, Type) { + this->setName (std::move (name)); } - -void CShaderVariableVector2::setValue (const glm::vec2& value) -{ +void CShaderVariableVector2::setValue (const glm::vec2& value) { this->m_value = value; CShaderVariable::setValue (&this->m_value); } -const int CShaderVariableVector2::getSize () const -{ +const int CShaderVariableVector2::getSize () const { return 2; } diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h index 8fecb0c..a992728 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h @@ -3,22 +3,20 @@ #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" -namespace WallpaperEngine::Render::Shaders::Variables -{ - class CShaderVariableVector2 : public CShaderVariable - { - public: - explicit CShaderVariableVector2 (const glm::vec2& defaultValue); - CShaderVariableVector2 (const glm::vec2& defaultValue, std::string name); +namespace WallpaperEngine::Render::Shaders::Variables { +class CShaderVariableVector2 final : public CShaderVariable { + public: + explicit CShaderVariableVector2 (const glm::vec2& defaultValue); + CShaderVariableVector2 (const glm::vec2& defaultValue, std::string name); - const int getSize () const override; + const int getSize () const override; - void setValue (const glm::vec2& value); + void setValue (const glm::vec2& value); - static const std::string Type; + static const std::string Type; - private: - glm::vec2 m_defaultValue; - glm::vec2 m_value; - }; -} + private: + glm::vec2 m_defaultValue; + glm::vec2 m_value; +}; +} // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp index 05a44a1..c2109e7 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp @@ -5,26 +5,21 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableVector3::CShaderVariableVector3 (const glm::vec3& defaultValue) : m_defaultValue (defaultValue), m_value (glm::vec3 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ -} + CShaderVariable (&this->m_defaultValue, nullptr, Type) {} CShaderVariableVector3::CShaderVariableVector3 (const glm::vec3& defaultValue, const std::string& name) : m_defaultValue (defaultValue), m_value (glm::vec3 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ + CShaderVariable (&this->m_defaultValue, nullptr, Type) { this->setName (name); } -void CShaderVariableVector3::setValue (const glm::vec3& value) -{ +void CShaderVariableVector3::setValue (const glm::vec3& value) { this->m_value = value; CShaderVariable::setValue (&this->m_value); } -const int CShaderVariableVector3::getSize () const -{ +const int CShaderVariableVector3::getSize () const { return 3; } diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h index 762f6b0..c7c8731 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h @@ -4,22 +4,20 @@ #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" -namespace WallpaperEngine::Render::Shaders::Variables -{ - class CShaderVariableVector3 : public CShaderVariable - { - public: - explicit CShaderVariableVector3 (const glm::vec3& defaultValue); - CShaderVariableVector3 (const glm::vec3& defaultValue, const std::string& name); +namespace WallpaperEngine::Render::Shaders::Variables { +class CShaderVariableVector3 final : public CShaderVariable { + public: + explicit CShaderVariableVector3 (const glm::vec3& defaultValue); + CShaderVariableVector3 (const glm::vec3& defaultValue, const std::string& name); - const int getSize () const override; + const int getSize () const override; - void setValue (const glm::vec3& value); + void setValue (const glm::vec3& value); - static const std::string Type; + static const std::string Type; - private: - glm::vec3 m_defaultValue; - glm::vec3 m_value; - }; -} + private: + glm::vec3 m_defaultValue; + glm::vec3 m_value; +}; +} // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp index e22890b..1349a40 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp @@ -7,26 +7,21 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableVector4::CShaderVariableVector4 (const glm::vec4& defaultValue) : m_defaultValue (defaultValue), m_value (glm::vec4 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ -} + CShaderVariable (&this->m_defaultValue, nullptr, Type) {} CShaderVariableVector4::CShaderVariableVector4 (const glm::vec4& defaultValue, const std::string& name) : m_defaultValue (defaultValue), m_value (glm::vec4 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) -{ + CShaderVariable (&this->m_defaultValue, nullptr, Type) { this->setName (name); } -void CShaderVariableVector4::setValue (const glm::vec4& value) -{ +void CShaderVariableVector4::setValue (const glm::vec4& value) { this->m_value = value; CShaderVariable::setValue (&this->m_value); } -const int CShaderVariableVector4::getSize () const -{ +const int CShaderVariableVector4::getSize () const { return 4; } diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h index 80ff958..6e05f89 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h @@ -3,22 +3,20 @@ #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" -namespace WallpaperEngine::Render::Shaders::Variables -{ - class CShaderVariableVector4 : public CShaderVariable - { - public: - explicit CShaderVariableVector4 (const glm::vec4& defaultValue); - CShaderVariableVector4 (const glm::vec4& defaultValue, const std::string& name); +namespace WallpaperEngine::Render::Shaders::Variables { +class CShaderVariableVector4 final : public CShaderVariable { + public: + explicit CShaderVariableVector4 (const glm::vec4& defaultValue); + CShaderVariableVector4 (const glm::vec4& defaultValue, const std::string& name); - const int getSize () const override; + const int getSize () const override; - void setValue (const glm::vec4& value); + void setValue (const glm::vec4& value); - static const std::string Type; + static const std::string Type; - private: - glm::vec4 m_defaultValue; - glm::vec4 m_value; - }; -} + private: + glm::vec4 m_defaultValue; + glm::vec4 m_value; +}; +} // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/common.h b/src/common.h index 6e4530b..77bc521 100644 --- a/src/common.h +++ b/src/common.h @@ -1 +1,3 @@ +#pragma once + #include "WallpaperEngine/Logging/CLog.h" diff --git a/tools/linting.sh b/tools/linting.sh new file mode 100644 index 0000000..be35f7c --- /dev/null +++ b/tools/linting.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +shopt -s globstar +clang-format -i src/**/*.cpp \ No newline at end of file