id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
35,634
main.cpp
OpenMW_openmw/apps/openmw_tests/main.cpp
#include <components/debug/debugging.hpp> #include <components/misc/strings/conversion.hpp> #include <components/settings/parser.hpp> #include <components/settings/values.hpp> #include <gtest/gtest.h> #include <filesystem> int main(int argc, char* argv[]) { Log::sMinDebugLevel = Debug::getDebugLevel(); const std::filesystem::path settingsDefaultPath = std::filesystem::path{ OPENMW_PROJECT_SOURCE_DIR } / "files" / Misc::StringUtils::stringToU8String("settings-default.cfg"); Settings::SettingsFileParser parser; parser.loadSettingsFile(settingsDefaultPath, Settings::Manager::mDefaultSettings); Settings::StaticValues::initDefaults(); Settings::Manager::mUserSettings = Settings::Manager::mDefaultSettings; Settings::StaticValues::init(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
859
C++
.cpp
19
41.421053
114
0.762936
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,635
options.cpp
OpenMW_openmw/apps/openmw_tests/options.cpp
#include "apps/openmw/options.hpp" #include <components/files/configurationmanager.hpp> #include <components/files/conversion.hpp> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> #include <algorithm> #include <array> #include <string> #include <utility> #include <vector> namespace { using namespace testing; using namespace OpenMW; namespace bpo = boost::program_options; template <class T, std::size_t size> std::string makeString(const T (&range)[size]) { static_assert(size > 0); return std::string(std::begin(range), std::end(range) - 1); } template <class... Args> std::vector<std::string> generateSupportedCharacters(Args&&... args) { std::vector<std::string> result; (result.emplace_back(makeString(args)), ...); for (int i = 1; i <= std::numeric_limits<char>::max(); ++i) if (i != '&' && i != '"' && i != ' ' && i != '\n') result.push_back(std::string(1, static_cast<char>(i))); return result; } MATCHER_P(IsPath, v, "") { return Files::pathToUnicodeString(arg) == v; } template <class T> void parseArgs(const T& arguments, bpo::variables_map& variables, bpo::options_description& description) { Files::parseArgs(static_cast<int>(arguments.size()), arguments.data(), variables, description); } TEST(OpenMWOptionsFromArguments, should_support_equality_to_separate_flag_and_value) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame=save.omwsave" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save.omwsave"); } TEST(OpenMWOptionsFromArguments, should_support_single_word_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", "save.omwsave" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save.omwsave"); } TEST(OpenMWOptionsFromArguments, should_support_multi_component_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", "/home/user/openmw/save.omwsave" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "/home/user/openmw/save.omwsave"); } TEST(OpenMWOptionsFromArguments, should_support_windows_multi_component_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", R"(C:\OpenMW\save.omwsave)" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(C:\OpenMW\save.omwsave)"); } TEST(OpenMWOptionsFromArguments, should_support_load_savegame_path_with_spaces) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", "my save.omwsave" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "my save.omwsave"); } TEST(OpenMWOptionsFromArguments, should_support_load_savegame_path_with_octothorpe) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", "my#save.omwsave" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "my#save.omwsave"); } TEST(OpenMWOptionsFromArguments, should_support_load_savegame_path_with_at_sign) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", "my@save.omwsave" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "my@save.omwsave"); } TEST(OpenMWOptionsFromArguments, should_support_load_savegame_path_with_quote) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", R"(my"save.omwsave)" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(my"save.omwsave)"); } TEST(OpenMWOptionsFromArguments, should_support_quoted_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", R"("save".omwsave)" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(save)"); } TEST(OpenMWOptionsFromArguments, should_support_quoted_load_savegame_path_with_escaped_quote_by_ampersand) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", R"("save&".omwsave")" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(save".omwsave)"); } TEST(OpenMWOptionsFromArguments, should_support_quoted_load_savegame_path_with_escaped_ampersand) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", R"("save.omwsave&&")" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save.omwsave&"); } TEST(OpenMWOptionsFromArguments, should_support_load_savegame_path_with_ampersand) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", "save&.omwsave" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save&.omwsave"); } TEST(OpenMWOptionsFromArguments, should_support_load_savegame_path_with_multiple_quotes) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", R"(my"save".omwsave)" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(my"save".omwsave)"); } TEST(OpenMWOptionsFromArguments, should_compose_data) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--data", "1", "--data", "2" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_THAT(variables["data"].as<Files::MaybeQuotedPathContainer>(), ElementsAre(IsPath("1"), IsPath("2"))); } TEST(OpenMWOptionsFromArguments, should_compose_data_from_single_flag) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--data", "1", "2" }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_THAT(variables["data"].as<Files::MaybeQuotedPathContainer>(), ElementsAre(IsPath("1"), IsPath("2"))); } TEST(OpenMWOptionsFromArguments, should_throw_on_multiple_load_savegame) { bpo::options_description description = makeOptionsDescription(); const std::array arguments{ "openmw", "--load-savegame", "1.omwsave", "--load-savegame", "2.omwsave" }; bpo::variables_map variables; EXPECT_THROW(parseArgs(arguments, variables, description), std::exception); } struct OpenMWOptionsFromArgumentsStrings : TestWithParam<std::string> { }; TEST_P(OpenMWOptionsFromArgumentsStrings, should_support_paths_with_certain_characters_in_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); const std::string path = "save_" + std::string(GetParam()) + ".omwsave"; const std::string pathArgument = "\"" + path + "\""; const std::array arguments{ "openmw", "--load-savegame", pathArgument.c_str() }; bpo::variables_map variables; parseArgs(arguments, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), path); } INSTANTIATE_TEST_SUITE_P(SupportedCharacters, OpenMWOptionsFromArgumentsStrings, ValuesIn(generateSupportedCharacters(u8"👍", u8"Ъ", u8"Ǽ", "\n"))); TEST(OpenMWOptionsFromConfig, should_support_single_word_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("load-savegame=save.omwsave"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save.omwsave"); } TEST(OpenMWOptionsFromConfig, should_strip_quotes_from_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame="save.omwsave")"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save.omwsave"); } TEST(OpenMWOptionsFromConfig, should_strip_outer_quotes_from_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame=""save".omwsave")"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), ""); } TEST(OpenMWOptionsFromConfig, should_strip_quotes_from_load_savegame_path_with_space) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame="my save.omwsave")"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "my save.omwsave"); } TEST(OpenMWOptionsFromConfig, should_support_quoted_load_savegame_path_with_octothorpe) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("load-savegame=save#.omwsave"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save#.omwsave"); } TEST(OpenMWOptionsFromConfig, should_support_quoted_load_savegame_path_with_at_sign) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("load-savegame=save@.omwsave"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save@.omwsave"); } TEST(OpenMWOptionsFromConfig, should_support_quoted_load_savegame_path_with_quote) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame=save".omwsave)"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(save".omwsave)"); } TEST(OpenMWOptionsFromConfig, should_support_confusing_savegame_path_with_lots_going_on) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame="one &"two"three".omwsave")"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(one "two)"); } TEST(OpenMWOptionsFromConfig, should_support_confusing_savegame_path_with_even_more_going_on) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame="one &"two"three ".omwsave")"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(one "two)"); } TEST(OpenMWOptionsFromConfig, should_ignore_commented_option) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("#load-savegame=save.omwsave"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), ""); } TEST(OpenMWOptionsFromConfig, should_ignore_whitespace_prefixed_commented_option) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(" \t#load-savegame=save.omwsave"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), ""); } TEST(OpenMWOptionsFromConfig, should_support_whitespace_around_option) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(" load-savegame = save.omwsave "); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save.omwsave"); } TEST(OpenMWOptionsFromConfig, should_throw_on_multiple_load_savegame) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("load-savegame=1.omwsave\nload-savegame=2.omwsave"); bpo::variables_map variables; EXPECT_THROW(Files::parseConfig(stream, variables, description), std::exception); } TEST(OpenMWOptionsFromConfig, should_support_multi_component_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("load-savegame=/home/user/openmw/save.omwsave"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "/home/user/openmw/save.omwsave"); } TEST(OpenMWOptionsFromConfig, should_support_windows_multi_component_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame=C:\OpenMW\save.omwsave)"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(C:\OpenMW\save.omwsave)"); } TEST(OpenMWOptionsFromConfig, should_compose_data) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("data=1\ndata=2"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_THAT(variables["data"].as<Files::MaybeQuotedPathContainer>(), ElementsAre(IsPath("1"), IsPath("2"))); } TEST(OpenMWOptionsFromConfig, should_support_quoted_load_savegame_path_with_escaped_quote_by_ampersand) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame="save&".omwsave")"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ( Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), R"(save".omwsave)"); } TEST(OpenMWOptionsFromConfig, should_support_quoted_load_savegame_path_with_escaped_ampersand) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream(R"(load-savegame="save.omwsave&&")"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save.omwsave&"); } TEST(OpenMWOptionsFromConfig, should_support_load_savegame_path_with_ampersand) { bpo::options_description description = makeOptionsDescription(); std::istringstream stream("load-savegame=save&.omwsave"); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), "save&.omwsave"); } struct OpenMWOptionsFromConfigStrings : TestWithParam<std::string> { }; TEST_P(OpenMWOptionsFromConfigStrings, should_support_paths_with_certain_characters_in_load_savegame_path) { bpo::options_description description = makeOptionsDescription(); const std::string path = "save_" + std::string(GetParam()) + ".omwsave"; std::istringstream stream("load-savegame=\"" + path + "\""); bpo::variables_map variables; Files::parseConfig(stream, variables, description); EXPECT_EQ(Files::pathToUnicodeString(variables["load-savegame"].as<Files::MaybeQuotedPath>()), path); } INSTANTIATE_TEST_SUITE_P(SupportedCharacters, OpenMWOptionsFromConfigStrings, ValuesIn(generateSupportedCharacters(u8"👍", u8"Ъ", u8"Ǽ"))); }
19,521
C++
.cpp
363
46.300275
120
0.696394
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,636
testduration.cpp
OpenMW_openmw/apps/openmw_tests/mwworld/testduration.cpp
#include <gtest/gtest.h> #include <cmath> #include "apps/openmw/mwworld/duration.hpp" namespace MWWorld { namespace { TEST(MWWorldDurationTest, fromHoursShouldProduceZeroDaysAndHoursFor0) { const Duration duration = Duration::fromHours(0); EXPECT_EQ(duration.getDays(), 0); EXPECT_EQ(duration.getHours(), 0); } TEST(MWWorldDurationTest, fromHoursShouldProduceOneDayAndZeroHoursFor24) { const Duration duration = Duration::fromHours(24); EXPECT_EQ(duration.getDays(), 1); EXPECT_EQ(duration.getHours(), 0); } TEST(MWWorldDurationTest, fromHoursShouldProduceOneDayAndRemainderHoursFor42) { const Duration duration = Duration::fromHours(42); EXPECT_EQ(duration.getDays(), 1); EXPECT_EQ(duration.getHours(), 18); } TEST(MWWorldDurationTest, fromHoursShouldProduceZeroDaysAndZeroHoursForMinDouble) { const Duration duration = Duration::fromHours(std::numeric_limits<double>::min()); EXPECT_EQ(duration.getDays(), 0); EXPECT_EQ(duration.getHours(), 0); } TEST(MWWorldDurationTest, fromHoursShouldProduceZeroDaysAndSomeHoursForMinFloat) { const Duration duration = Duration::fromHours(std::numeric_limits<float>::min()); EXPECT_EQ(duration.getDays(), 0); EXPECT_GT(duration.getHours(), 0); EXPECT_FLOAT_EQ(duration.getHours(), std::numeric_limits<float>::min()); } TEST(MWWorldDurationTest, fromHoursShouldProduceZeroDaysAndRemainderHoursForValueJustBelow24InDoublePrecision) { const Duration duration = Duration::fromHours(std::nextafter(24.0, 0.0)); EXPECT_EQ(duration.getDays(), 0); EXPECT_LT(duration.getHours(), 24); EXPECT_FLOAT_EQ(duration.getHours(), 24); } TEST(MWWorldDurationTest, fromHoursShouldProduceZeroDaysAndRemainderHoursForValueJustBelow24InFloatPrecision) { const Duration duration = Duration::fromHours(std::nextafter(24.0f, 0.0f)); EXPECT_EQ(duration.getDays(), 0); EXPECT_LT(duration.getHours(), 24); EXPECT_FLOAT_EQ(duration.getHours(), 24); } } }
2,342
C++
.cpp
54
33.537037
118
0.648091
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,637
test_store.cpp
OpenMW_openmw/apps/openmw_tests/mwworld/test_store.cpp
#include <gmock/gmock.h> #include <gtest/gtest.h> #include <algorithm> #include <array> #include <fstream> #include <span> #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> #include <components/esm/defs.hpp> #include <components/esm/records.hpp> #include <components/esm/typetraits.hpp> #include <components/esm3/esmreader.hpp> #include <components/esm3/esmwriter.hpp> #include <components/esm3/typetraits.hpp> #include <components/esm4/common.hpp> #include <components/esm4/reader.hpp> #include <components/esm4/readerutils.hpp> #include <components/files/configurationmanager.hpp> #include <components/files/conversion.hpp> #include <components/loadinglistener/loadinglistener.hpp> #include <components/misc/strings/algorithm.hpp> #include <components/testing/util.hpp> #include "apps/openmw/mwworld/esmstore.hpp" static Loading::Listener dummyListener; /// Base class for tests of ESMStore that rely on external content files to produce the test results struct ContentFileTest : public ::testing::Test { protected: void SetUp() override { readContentFiles(); // load the content files int index = 0; ESM::Dialogue* dialogue = nullptr; for (const auto& mContentFile : mContentFiles) { ESM::ESMReader lEsm; lEsm.setEncoder(nullptr); lEsm.setIndex(index); lEsm.open(mContentFile); mEsmStore.load(lEsm, &dummyListener, dialogue); ++index; } mEsmStore.setUp(); } void TearDown() override {} // read absolute path to content files from openmw.cfg void readContentFiles() { boost::program_options::variables_map variables; boost::program_options::options_description desc("Allowed options"); auto addOption = desc.add_options(); addOption("data", boost::program_options::value<Files::MaybeQuotedPathContainer>() ->default_value(Files::MaybeQuotedPathContainer(), "data") ->multitoken() ->composing()); addOption("content", boost::program_options::value<std::vector<std::string>>() ->default_value(std::vector<std::string>(), "") ->multitoken() ->composing(), "content file(s): esm/esp, or omwgame/omwaddon"); addOption("data-local", boost::program_options::value<Files::MaybeQuotedPathContainer::value_type>()->default_value( Files::MaybeQuotedPathContainer::value_type(), "")); Files::ConfigurationManager::addCommonOptions(desc); mConfigurationManager.readConfiguration(variables, desc, true); Files::PathContainer dataDirs, dataLocal; if (!variables["data"].empty()) { dataDirs = asPathContainer(variables["data"].as<Files::MaybeQuotedPathContainer>()); } Files::PathContainer::value_type local( variables["data-local"].as<Files::MaybeQuotedPathContainer::value_type>().u8string()); if (!local.empty()) dataLocal.push_back(local); mConfigurationManager.filterOutNonExistingPaths(dataDirs); mConfigurationManager.filterOutNonExistingPaths(dataLocal); if (!dataLocal.empty()) dataDirs.insert(dataDirs.end(), dataLocal.begin(), dataLocal.end()); Files::Collections collections(dataDirs); std::vector<std::string> contentFiles = variables["content"].as<std::vector<std::string>>(); for (auto& contentFile : contentFiles) { if (!Misc::StringUtils::ciEndsWith(contentFile, ".omwscripts")) mContentFiles.push_back(collections.getPath(contentFile)); } } protected: Files::ConfigurationManager mConfigurationManager; MWWorld::ESMStore mEsmStore; std::vector<std::filesystem::path> mContentFiles; }; /// Print results of the dialogue merging process, i.e. the resulting linked list. TEST_F(ContentFileTest, dialogue_merging_test) { if (mContentFiles.empty()) { std::cout << "No content files found, skipping test" << std::endl; return; } const auto file = TestingOpenMW::outputFilePath("test_dialogue_merging.txt"); std::ofstream stream(file); const MWWorld::Store<ESM::Dialogue>& dialStore = mEsmStore.get<ESM::Dialogue>(); for (const auto& dial : dialStore) { stream << "Dialogue: " << dial.mId << std::endl; for (const auto& info : dial.mInfo) { stream << info.mId << std::endl; } stream << std::endl; } std::cout << "dialogue_merging_test successful, results printed to " << Files::pathToUnicodeString(file) << std::endl; } // Note: here we don't test records that don't use string names (e.g. Land, Pathgrid, Cell) #define RUN_TEST_FOR_TYPES(func, arg1, arg2) \ func<ESM::Activator>(arg1, arg2); \ func<ESM::Apparatus>(arg1, arg2); \ func<ESM::Armor>(arg1, arg2); \ func<ESM::BirthSign>(arg1, arg2); \ func<ESM::BodyPart>(arg1, arg2); \ func<ESM::Book>(arg1, arg2); \ func<ESM::Class>(arg1, arg2); \ func<ESM::Clothing>(arg1, arg2); \ func<ESM::Container>(arg1, arg2); \ func<ESM::Creature>(arg1, arg2); \ func<ESM::CreatureLevList>(arg1, arg2); \ func<ESM::Dialogue>(arg1, arg2); \ func<ESM::Door>(arg1, arg2); \ func<ESM::Enchantment>(arg1, arg2); \ func<ESM::Faction>(arg1, arg2); \ func<ESM::GameSetting>(arg1, arg2); \ func<ESM::Global>(arg1, arg2); \ func<ESM::Ingredient>(arg1, arg2); \ func<ESM::ItemLevList>(arg1, arg2); \ func<ESM::Light>(arg1, arg2); \ func<ESM::Lockpick>(arg1, arg2); \ func<ESM::Miscellaneous>(arg1, arg2); \ func<ESM::NPC>(arg1, arg2); \ func<ESM::Potion>(arg1, arg2); \ func<ESM::Probe>(arg1, arg2); \ func<ESM::Race>(arg1, arg2); \ func<ESM::Region>(arg1, arg2); \ func<ESM::Repair>(arg1, arg2); \ func<ESM::Script>(arg1, arg2); \ func<ESM::Sound>(arg1, arg2); \ func<ESM::SoundGenerator>(arg1, arg2); \ func<ESM::Spell>(arg1, arg2); \ func<ESM::StartScript>(arg1, arg2); \ func<ESM::Weapon>(arg1, arg2); template <typename T> void printRecords(MWWorld::ESMStore& esmStore, std::ostream& outStream) { const MWWorld::Store<T>& store = esmStore.get<T>(); outStream << store.getSize() << " " << T::getRecordType() << " records" << std::endl; for (typename MWWorld::Store<T>::iterator it = store.begin(); it != store.end(); ++it) { const T& record = *it; outStream << record.mId << std::endl; } outStream << std::endl; } /// Print some basic diagnostics about the loaded content files, e.g. number of records and names of those records /// Also used to test the iteration order of records TEST_F(ContentFileTest, content_diagnostics_test) { if (mContentFiles.empty()) { std::cout << "No content files found, skipping test" << std::endl; return; } const auto file = TestingOpenMW::outputFilePath("test_content_diagnostics.txt"); std::ofstream stream(file); RUN_TEST_FOR_TYPES(printRecords, mEsmStore, stream); std::cout << "diagnostics_test successful, results printed to " << Files::pathToUnicodeString(file) << std::endl; } // TODO: /// Print results of autocalculated NPC spell lists. Also serves as test for attribute/skill autocalculation which the /// spell autocalculation heavily relies on /// - even incorrect rounding modes can completely change the resulting spell lists. /* TEST_F(ContentFileTest, autocalc_test) { if (mContentFiles.empty()) { std::cout << "No content files found, skipping test" << std::endl; return; } } */ /// Base class for tests of ESMStore that do not rely on external content files template <class T> struct StoreTest : public ::testing::Test { }; TYPED_TEST_SUITE_P(StoreTest); /// Create an ESM file in-memory containing the specified record. /// @param deleted Write record with deleted flag? template <typename T> std::unique_ptr<std::istream> getEsmFile(T record, bool deleted, ESM::FormatVersion formatVersion) { ESM::ESMWriter writer; auto stream = std::make_unique<std::stringstream>(); writer.setFormatVersion(formatVersion); writer.save(*stream); writer.startRecord(T::sRecordId); record.save(writer, deleted); writer.endRecord(T::sRecordId); return stream; } namespace { std::vector<ESM::FormatVersion> getFormats() { std::vector<ESM::FormatVersion> result({ ESM::DefaultFormatVersion, ESM::CurrentContentFormatVersion, ESM::MaxOldFogOfWarFormatVersion, ESM::MaxUnoptimizedCharacterDataFormatVersion, ESM::MaxOldTimeLeftFormatVersion, ESM::MaxIntFallbackFormatVersion, ESM::MaxClearModifiersFormatVersion, ESM::MaxOldAiPackageFormatVersion, ESM::MaxOldSkillsAndAttributesFormatVersion, ESM::MaxOldCreatureStatsFormatVersion, ESM::MaxStringRefIdFormatVersion, ESM::MaxUseEsmCellIdFormatVersion, }); for (ESM::FormatVersion v = result.back() + 1; v <= ESM::CurrentSaveGameFormatVersion; ++v) result.push_back(v); return result; } template <class T, class = std::void_t<>> struct HasBlankFunction : std::false_type { }; template <class T> struct HasBlankFunction<T, std::void_t<decltype(std::declval<T>().blank())>> : std::true_type { }; template <class T> constexpr bool hasBlankFunction = HasBlankFunction<T>::value; } /// Tests deletion of records. TYPED_TEST_P(StoreTest, delete_test) { using RecordType = TypeParam; for (const ESM::FormatVersion formatVersion : getFormats()) { SCOPED_TRACE("FormatVersion: " + std::to_string(formatVersion)); const ESM::RefId recordId = ESM::RefId::stringRefId("foobar"); RecordType record; if constexpr (hasBlankFunction<RecordType>) record.blank(); record.mId = recordId; ESM::ESMReader reader; ESM::Dialogue* dialogue = nullptr; { MWWorld::ESMStore esmStore; reader.open(getEsmFile(record, false, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); // master file inserts a record esmStore.setUp(); EXPECT_EQ(esmStore.get<RecordType>().getSize(), 1); } { MWWorld::ESMStore esmStore; reader.open(getEsmFile(record, false, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); // master file inserts a record reader.open(getEsmFile(record, true, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); // now a plugin deletes it esmStore.setUp(); EXPECT_EQ(esmStore.get<RecordType>().getSize(), 0); } { MWWorld::ESMStore esmStore; reader.open(getEsmFile(record, false, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); // master file inserts a record reader.open(getEsmFile(record, true, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); // now a plugin deletes it // now another plugin inserts it again // expected behaviour is the record to reappear rather than staying deleted reader.open(getEsmFile(record, false, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); esmStore.setUp(); EXPECT_EQ(esmStore.get<RecordType>().getSize(), 1); } } } template <typename T> static unsigned int hasSameRecordId(const MWWorld::Store<T>& store, ESM::RecNameInts RecName) { if constexpr (MWWorld::HasRecordId<T>::value) { return T::sRecordId == RecName ? 1 : 0; } else { return 0; } } template <typename T> static void testRecNameIntCount(const MWWorld::Store<T>& store, const MWWorld::ESMStore::StoreTuple& stores) { if constexpr (MWWorld::HasRecordId<T>::value) { const unsigned int recordIdCount = std::apply([](auto&&... x) { return (hasSameRecordId(x, T::sRecordId) + ...); }, stores); ASSERT_EQ(recordIdCount, static_cast<unsigned int>(1)) << "The same RecNameInt is used twice ESM::REC_" << ESM::getRecNameString(T::sRecordId).toStringView(); } } static void testAllRecNameIntUnique(const MWWorld::ESMStore::StoreTuple& stores) { std::apply([&stores](auto&&... x) { (testRecNameIntCount(x, stores), ...); }, stores); } TEST(StoreTest, eachRecordTypeShouldHaveUniqueRecordId) { testAllRecNameIntUnique(MWWorld::ESMStore::StoreTuple()); } /// Tests overwriting of records. TYPED_TEST_P(StoreTest, overwrite_test) { using RecordType = TypeParam; for (const ESM::FormatVersion formatVersion : getFormats()) { SCOPED_TRACE("FormatVersion: " + std::to_string(formatVersion)); const ESM::RefId recordId = ESM::RefId::stringRefId("foobar"); const ESM::RefId recordIdUpper = ESM::RefId::stringRefId("Foobar"); RecordType record; if constexpr (hasBlankFunction<RecordType>) record.blank(); record.mId = recordId; ESM::ESMReader reader; ESM::Dialogue* dialogue = nullptr; MWWorld::ESMStore esmStore; // master file inserts a record reader.open(getEsmFile(record, false, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); // now a plugin overwrites it with changed data record.mId = recordIdUpper; // change id to uppercase, to test case smashing while we're at it record.mModel = "the_new_model"; reader.open(getEsmFile(record, false, formatVersion), "filename"); esmStore.load(reader, &dummyListener, dialogue); esmStore.setUp(); // verify that changes were actually applied const RecordType* overwrittenRec = esmStore.get<RecordType>().search(recordId); ASSERT_NE(overwrittenRec, nullptr); EXPECT_EQ(overwrittenRec->mModel, "the_new_model"); } } namespace { using namespace ::testing; template <class T> struct StoreSaveLoadTest : public Test { }; TYPED_TEST_SUITE_P(StoreSaveLoadTest); TYPED_TEST_P(StoreSaveLoadTest, shouldNotChangeRefId) { using RecordType = TypeParam; const int index = 3; const std::string stringId = "foobar"; decltype(RecordType::mId) refId; if constexpr (ESM::hasIndex<RecordType> && !std::is_same_v<RecordType, ESM::LandTexture>) refId = RecordType::indexToRefId(index); else if constexpr (std::is_same_v<RecordType, ESM::Cell>) { refId = ESM::RefId::esm3ExteriorCell(0, 0); } else if constexpr (std::is_same_v<RecordType, ESM::Attribute>) refId = ESM::Attribute::Strength; else if constexpr (std::is_same_v<RecordType, ESM::Skill>) refId = ESM::Skill::Block; else refId = ESM::StringRefId(stringId); for (const ESM::FormatVersion formatVersion : getFormats()) { SCOPED_TRACE("FormatVersion: " + std::to_string(formatVersion)); RecordType record; if constexpr (hasBlankFunction<RecordType>) record.blank(); record.mId = refId; if constexpr (ESM::hasStringId<RecordType>) record.mStringId = stringId; if constexpr (ESM::hasIndex<RecordType>) record.mIndex = index; if constexpr (std::is_same_v<RecordType, ESM::Global>) record.mValue = ESM::Variant(42); ESM::ESMReader reader; ESM::Dialogue* dialogue = nullptr; MWWorld::ESMStore esmStore; if constexpr (std::is_same_v<RecordType, ESM::Attribute>) { ASSERT_ANY_THROW(getEsmFile(record, false, formatVersion)); continue; } reader.open(getEsmFile(record, false, formatVersion), "filename"); ASSERT_NO_THROW(esmStore.load(reader, &dummyListener, dialogue)); esmStore.setUp(); const RecordType* result = nullptr; if constexpr (std::is_same_v<RecordType, ESM::LandTexture>) { const std::string* texture = esmStore.get<RecordType>().search(index, 0); ASSERT_NE(texture, nullptr); return; } else if constexpr (ESM::hasIndex<RecordType>) result = esmStore.get<RecordType>().search(index); else result = esmStore.get<RecordType>().search(refId); ASSERT_NE(result, nullptr); EXPECT_EQ(result->mId, refId); } } static_assert(ESM::hasIndex<ESM::MagicEffect>); static_assert(ESM::hasStringId<ESM::Dialogue>); template <class T, class = std::void_t<>> struct HasSaveFunction : std::false_type { }; template <class T> struct HasSaveFunction<T, std::void_t<decltype(std::declval<T>().save(std::declval<ESM::ESMWriter&>(), bool()))>> : std::true_type { }; template <class Head, class List> struct ConcatTypes; template <class Head, class... Ts> struct ConcatTypes<Head, std::tuple<Ts...>> { using Type = std::tuple<Head, Ts...>; }; template <template <class...> class Predicate, class Out, class... Ins> struct FilterTypesImpl; template <template <class...> class Predicate, class Out, class Head, class... Tail> struct FilterTypesImpl<Predicate, Out, Head, Tail...> { using Type = typename FilterTypesImpl<Predicate, std::conditional_t<Predicate<Head>::value, typename ConcatTypes<Head, Out>::Type, Out>, Tail...>::Type; }; template <template <class...> class Predicate, class Out> struct FilterTypesImpl<Predicate, Out> { using Type = Out; }; template <template <class...> class Predicate, class List> struct FilterTypes; template <template <class...> class Predicate, class... Ts> struct FilterTypes<Predicate, std::tuple<Ts...>> { using Type = typename FilterTypesImpl<Predicate, std::tuple<>, Ts...>::Type; }; template <class... T> struct ToRecordTypes; template <class... T> struct ToRecordTypes<std::tuple<MWWorld::Store<T>...>> { using Type = std::tuple<T...>; }; template <class... T> struct AsTestingTypes; template <class... T> struct AsTestingTypes<std::tuple<T...>> { using Type = Types<T...>; }; using RecordTypes = typename ToRecordTypes<MWWorld::ESMStore::StoreTuple>::Type; using RecordTypesWithId = typename FilterTypes<ESM::HasId, RecordTypes>::Type; using RecordTypesWithSave = typename FilterTypes<HasSaveFunction, RecordTypesWithId>::Type; using RecordTypesWithModel = typename FilterTypes<ESM::HasModel, RecordTypesWithSave>::Type; REGISTER_TYPED_TEST_SUITE_P(StoreSaveLoadTest, shouldNotChangeRefId); static_assert(std::tuple_size_v<RecordTypesWithSave> == 40); INSTANTIATE_TYPED_TEST_SUITE_P( RecordTypesTest, StoreSaveLoadTest, typename AsTestingTypes<RecordTypesWithSave>::Type); } REGISTER_TYPED_TEST_SUITE_P(StoreTest, overwrite_test, delete_test); static_assert(std::tuple_size_v<RecordTypesWithModel> == 19); INSTANTIATE_TYPED_TEST_SUITE_P(RecordTypesTest, StoreTest, typename AsTestingTypes<RecordTypesWithModel>::Type); namespace ESM { inline std::ostream& operator<<(std::ostream& stream, const ESM::DialInfo& value) { return stream << "ESM::DialInfo{.mId = " << value.mId << "}"; } } namespace { using namespace ::testing; struct DialogueData { ESM::Dialogue mDialogue; std::vector<ESM::DialInfo> mInfos; }; DialogueData generateDialogueWithInfos(std::size_t infoCount) { DialogueData result; result.mDialogue.blank(); result.mDialogue.mId = ESM::RefId::stringRefId("dialogue"); result.mDialogue.mStringId = "Dialogue"; for (std::size_t i = 0; i < infoCount; ++i) { ESM::DialInfo& info = result.mInfos.emplace_back(); info.blank(); info.mId = ESM::RefId::stringRefId("info" + std::to_string(i)); } if (infoCount >= 2) { result.mInfos[0].mNext = result.mInfos[1].mId; result.mInfos[infoCount - 1].mPrev = result.mInfos[infoCount - 2].mId; } for (std::size_t i = 1; i < infoCount - 1; ++i) { result.mInfos[i].mPrev = result.mInfos[i - 1].mId; result.mInfos[i].mNext = result.mInfos[i + 1].mId; } return result; } std::unique_ptr<std::stringstream> saveDialogueWithInfos( const ESM::Dialogue& dialogue, std::span<const ESM::DialInfo> infos, std::span<const std::size_t> deleted = {}) { auto stream = std::make_unique<std::stringstream>(); ESM::ESMWriter writer; writer.setFormatVersion(ESM::CurrentSaveGameFormatVersion); writer.save(*stream); writer.startRecord(ESM::REC_DIAL); dialogue.save(writer); writer.endRecord(ESM::REC_DIAL); for (std::size_t i = 0; i < infos.size(); ++i) { writer.startRecord(ESM::REC_INFO); infos[i].save(writer, std::find(deleted.begin(), deleted.end(), i) != deleted.end()); writer.endRecord(ESM::REC_INFO); } return stream; } void loadEsmStore(int index, std::unique_ptr<std::istream>&& stream, MWWorld::ESMStore& esmStore) { ESM::ESMReader reader; ESM::Dialogue* dialogue = nullptr; reader.setIndex(index); reader.open(std::move(stream), "test"); esmStore.load(reader, &dummyListener, dialogue); } MATCHER_P(HasIdEqualTo, v, "") { return v == arg.mId; } TEST(MWWorldStoreTest, shouldLoadDialogueWithInfos) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info0"), HasIdEqualTo("info1"), HasIdEqualTo("info2"))); } TEST(MWWorldStoreTest, shouldIgnoreNextWhenLoadingDialogueInfos) { DialogueData data = generateDialogueWithInfos(3); std::reverse(data.mInfos.begin(), data.mInfos.end()); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info0"), HasIdEqualTo("info2"), HasIdEqualTo("info1"))); } TEST(MWWorldStoreTest, shouldLoadDialogueWithInfosInsertingNewRecordBasedOnPrev) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); ESM::DialInfo newInfo; newInfo.blank(); newInfo.mId = ESM::RefId::stringRefId("newInfo"); newInfo.mPrev = data.mInfos[1].mId; newInfo.mNext = ESM::RefId::stringRefId("invalid"); loadEsmStore(1, saveDialogueWithInfos(data.mDialogue, std::array{ newInfo }), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info0"), HasIdEqualTo("info1"), HasIdEqualTo("newInfo"), HasIdEqualTo("info2"))); } TEST(MWWorldStoreTest, shouldLoadDialogueWithInfosInsertingNewRecordToFrontBasedOnEmptyPrev) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); ESM::DialInfo newInfo; newInfo.blank(); newInfo.mId = ESM::RefId::stringRefId("newInfo"); newInfo.mNext = ESM::RefId::stringRefId("invalid"); loadEsmStore(1, saveDialogueWithInfos(data.mDialogue, std::array{ newInfo }), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("newInfo"), HasIdEqualTo("info0"), HasIdEqualTo("info1"), HasIdEqualTo("info2"))); } TEST(MWWorldStoreTest, shouldLoadDialogueWithInfosInsertingNewRecordToBackWhenPrevIsNotFound) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); ESM::DialInfo newInfo; newInfo.blank(); newInfo.mId = ESM::RefId::stringRefId("newInfo"); newInfo.mPrev = ESM::RefId::stringRefId("invalid"); loadEsmStore(1, saveDialogueWithInfos(data.mDialogue, std::array{ newInfo }), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info0"), HasIdEqualTo("info1"), HasIdEqualTo("info2"), HasIdEqualTo("newInfo"))); } TEST(MWWorldStoreTest, shouldLoadDialogueWithInfosUpdatingExistingRecord) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); ESM::DialInfo updatedInfo = data.mInfos[1]; updatedInfo.mActor = ESM::RefId::stringRefId("newActor"); loadEsmStore(1, saveDialogueWithInfos(data.mDialogue, std::array{ updatedInfo }), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); ASSERT_EQ(dialogue->mInfo.size(), 3); EXPECT_EQ(std::next(dialogue->mInfo.begin())->mActor, "newActor"); } TEST(MWWorldStoreTest, shouldLoadDialogueWithInfosMovingForwardExistingRecordBasedOnPrev) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); ESM::DialInfo updatedInfo = data.mInfos[0]; updatedInfo.mPrev = data.mInfos[2].mId; updatedInfo.mActor = ESM::RefId::stringRefId("newActor"); loadEsmStore(1, saveDialogueWithInfos(data.mDialogue, std::array{ updatedInfo }), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info1"), HasIdEqualTo("info2"), HasIdEqualTo("info0"))); EXPECT_EQ(std::prev(dialogue->mInfo.end())->mActor, "newActor"); } TEST(MWWorldStoreTest, shouldLoadDialogueWithInfosMovingBackwardExistingRecordBasedOnPrev) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); ESM::DialInfo updatedInfo = data.mInfos[2]; updatedInfo.mPrev = data.mInfos[0].mId; updatedInfo.mActor = ESM::RefId::stringRefId("newActor"); loadEsmStore(1, saveDialogueWithInfos(data.mDialogue, std::array{ updatedInfo }), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info0"), HasIdEqualTo("info2"), HasIdEqualTo("info1"))); EXPECT_EQ(std::next(dialogue->mInfo.begin())->mActor, "newActor"); } TEST(MWWorldStoreTest, shouldPreservePositionWhenPrevIsTheSame) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos), esmStore); ESM::DialInfo newInfo = data.mInfos[0]; newInfo.mPrev = data.mInfos[2].mId; newInfo.mNext = {}; loadEsmStore(1, saveDialogueWithInfos(data.mDialogue, std::array{ newInfo }), esmStore); newInfo = data.mInfos[1]; newInfo.mResponse = "test"; loadEsmStore(2, saveDialogueWithInfos(data.mDialogue, std::array{ newInfo }), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info1"), HasIdEqualTo("info2"), HasIdEqualTo("info0"))); EXPECT_EQ(dialogue->mInfo.begin()->mResponse, "test"); } TEST(MWWorldStoreTest, setUpShouldRemoveDeletedDialogueInfos) { const DialogueData data = generateDialogueWithInfos(3); MWWorld::ESMStore esmStore; const std::array<std::size_t, 1> deleted = { 1 }; loadEsmStore(0, saveDialogueWithInfos(data.mDialogue, data.mInfos, deleted), esmStore); esmStore.setUp(); const ESM::Dialogue* dialogue = esmStore.get<ESM::Dialogue>().search(ESM::RefId::stringRefId("dialogue")); ASSERT_NE(dialogue, nullptr); EXPECT_THAT(dialogue->mInfo, ElementsAre(HasIdEqualTo("info0"), HasIdEqualTo("info2"))); } }
33,354
C++
.cpp
695
40.392806
120
0.602931
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,638
testptr.cpp
OpenMW_openmw/apps/openmw_tests/mwworld/testptr.cpp
#include "apps/openmw/mwclass/npc.hpp" #include "apps/openmw/mwworld/esmstore.hpp" #include "apps/openmw/mwworld/livecellref.hpp" #include "apps/openmw/mwworld/ptr.hpp" #include "apps/openmw/mwworld/worldmodel.hpp" #include <components/esm3/loadnpc.hpp> #include <components/esm3/readerscache.hpp> #include <gtest/gtest.h> namespace MWWorld { namespace { using namespace testing; TEST(MWWorldPtrTest, toStringShouldReturnHumanReadableTextRepresentationOfPtrWithNullRef) { Ptr ptr; EXPECT_EQ(ptr.toString(), "null object"); } TEST(MWWorldPtrTest, toStringShouldReturnHumanReadableTextRepresentationOfPtrWithDeletedRef) { MWClass::Npc::registerSelf(); ESM::NPC npc; npc.blank(); npc.mId = ESM::RefId::stringRefId("Player"); ESMStore store; store.insert(npc); ESM::CellRef cellRef; cellRef.blank(); cellRef.mRefID = npc.mId; cellRef.mRefNum = ESM::RefNum{ .mIndex = 0x2a, .mContentFile = 0xd }; LiveCellRef<ESM::NPC> liveCellRef(cellRef, &npc); liveCellRef.mData.setDeletedByContentFile(true); Ptr ptr(&liveCellRef); EXPECT_EQ(ptr.toString(), "deleted object0xd00002a (NPC, \"player\")"); } TEST(MWWorldPtrTest, toStringShouldReturnHumanReadableTextRepresentationOfPtr) { MWClass::Npc::registerSelf(); ESM::NPC npc; npc.blank(); npc.mId = ESM::RefId::stringRefId("Player"); ESMStore store; store.insert(npc); ESM::CellRef cellRef; cellRef.blank(); cellRef.mRefID = npc.mId; cellRef.mRefNum = ESM::RefNum{ .mIndex = 0x2a, .mContentFile = 0xd }; LiveCellRef<ESM::NPC> liveCellRef(cellRef, &npc); Ptr ptr(&liveCellRef); EXPECT_EQ(ptr.toString(), "object0xd00002a (NPC, \"player\")"); } TEST(MWWorldPtrTest, underlyingLiveCellRefShouldBeDeregisteredOnDestruction) { MWClass::Npc::registerSelf(); ESM::NPC npc; npc.blank(); npc.mId = ESM::RefId::stringRefId("Player"); ESMStore store; store.insert(npc); ESM::ReadersCache readersCache; WorldModel worldModel(store, readersCache); ESM::CellRef cellRef; cellRef.blank(); cellRef.mRefID = npc.mId; cellRef.mRefNum = ESM::FormId{ .mIndex = 0x2a, .mContentFile = 0xd }; { LiveCellRef<ESM::NPC> liveCellRef(cellRef, &npc); Ptr ptr(&liveCellRef); worldModel.registerPtr(ptr); ASSERT_EQ(worldModel.getPtr(cellRef.mRefNum), ptr); } EXPECT_EQ(worldModel.getPtr(cellRef.mRefNum), Ptr()); } } }
2,940
C++
.cpp
75
28.666667
100
0.596571
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,639
testtimestamp.cpp
OpenMW_openmw/apps/openmw_tests/mwworld/testtimestamp.cpp
#include <gtest/gtest.h> #include <cmath> #include "apps/openmw/mwworld/timestamp.hpp" namespace MWWorld { namespace { TEST(MWWorldTimeStampTest, operatorPlusShouldNotChangeTimeStampForZero) { TimeStamp timeStamp; timeStamp += 0; EXPECT_EQ(timeStamp.getDay(), 0); EXPECT_EQ(timeStamp.getHour(), 0); } TEST(MWWorldTimeStampTest, operatorPlusShouldProperlyHandleDoubleValuesCloseTo24) { TimeStamp timeStamp; timeStamp += std::nextafter(24.0, 0.0); EXPECT_EQ(timeStamp.getDay(), 0); EXPECT_LT(timeStamp.getHour(), 24); EXPECT_FLOAT_EQ(timeStamp.getHour(), 24); } TEST(MWWorldTimeStampTest, operatorPlusShouldProperlyHandleFloatValuesCloseTo24) { TimeStamp timeStamp; timeStamp += std::nextafter(24.0f, 0.0f); EXPECT_EQ(timeStamp.getDay(), 0); EXPECT_LT(timeStamp.getHour(), 24); EXPECT_FLOAT_EQ(timeStamp.getHour(), 24); } TEST(MWWorldTimeStampTest, operatorPlusShouldAddDaysForEach24Hours) { TimeStamp timeStamp; timeStamp += 24.0 * 42; EXPECT_EQ(timeStamp.getDay(), 42); EXPECT_EQ(timeStamp.getHour(), 0); } TEST(MWWorldTimeStampTest, operatorPlusShouldAddDaysForEach24HoursAndSetRemainderToHours) { TimeStamp timeStamp; timeStamp += 24.0 * 42 + 13.0; EXPECT_EQ(timeStamp.getDay(), 42); EXPECT_EQ(timeStamp.getHour(), 13); } TEST(MWWorldTimeStampTest, operatorPlusShouldAccumulateExistingValue) { TimeStamp timeStamp(13, 42); timeStamp += 24.0 * 2 + 17.0; EXPECT_EQ(timeStamp.getDay(), 45); EXPECT_EQ(timeStamp.getHour(), 6); } TEST(MWWorldTimeStampTest, operatorPlusShouldThrowExceptionForNegativeValue) { TimeStamp timeStamp(13, 42); EXPECT_THROW(timeStamp += -1, std::runtime_error); } } }
2,117
C++
.cpp
58
26.448276
97
0.60439
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,640
test_scripts.cpp
OpenMW_openmw/apps/openmw_tests/mwscript/test_scripts.cpp
#include <gtest/gtest.h> #include <sstream> #include "test_utils.hpp" namespace { struct MWScriptTest : public ::testing::Test { MWScriptTest() : mErrorHandler() , mParser(mErrorHandler, mCompilerContext) { } std::optional<CompiledScript> compile(const std::string& scriptBody, bool shouldFail = false) { mParser.reset(); mErrorHandler.reset(); std::istringstream input(scriptBody); Compiler::Scanner scanner(mErrorHandler, input, mCompilerContext.getExtensions()); try { scanner.scan(mParser); } catch (...) { if (!shouldFail) logErrors(); throw; } if (mErrorHandler.isGood()) return CompiledScript(mParser.getProgram(), mParser.getLocals()); else if (!shouldFail) logErrors(); return {}; } void logErrors() { for (const auto& [error, loc] : mErrorHandler.getErrors()) { std::cout << error; if (loc.mLine) std::cout << " at line" << loc.mLine << " column " << loc.mColumn << " (" << loc.mLiteral << ")"; std::cout << "\n"; } } void registerExtensions() { Compiler::registerExtensions(mExtensions); mCompilerContext.setExtensions(&mExtensions); } void run(const CompiledScript& script, TestInterpreterContext& context) { mInterpreter.run(script.mProgram, context); } template <typename T, typename... TArgs> void installOpcode(int code, TArgs&&... args) { mInterpreter.installSegment5<T>(code, std::forward<TArgs&&>(args)...); } protected: void SetUp() override { Interpreter::installOpcodes(mInterpreter); } void TearDown() override {} private: TestErrorHandler mErrorHandler; TestCompilerContext mCompilerContext; Compiler::FileParser mParser; Compiler::Extensions mExtensions; Interpreter::Interpreter mInterpreter; }; const std::string sScript1 = R"mwscript(Begin basic_logic ; Comment short one short two set one to two if ( one == two ) set one to 1 elseif ( two == 1 ) set one to 2 else set one to 3 endif while ( one < two ) set one to ( one + 1 ) endwhile End)mwscript"; const std::string sScript2 = R"mwscript(Begin addtopic AddTopic "OpenMW Unit Test" End)mwscript"; const std::string sScript3 = R"mwscript(Begin math short a short b short c short d short e set b to ( a + 1 ) set c to ( a - 1 ) set d to ( b * c ) set e to ( d / a ) End)mwscript"; // https://forum.openmw.org/viewtopic.php?f=6&t=2262 const std::string sScript4 = R"mwscript(Begin scripting_once_again player -> addSpell "fire_bite", 645 PositionCell "Rabenfels, Taverne" 4480.000 3968.000 15820.000 0 End)mwscript"; const std::string sIssue587 = R"mwscript(Begin stalresetScript End stalreset Script)mwscript"; const std::string sIssue677 = R"mwscript(Begin _ase_dtree_dtree-owls End)mwscript"; const std::string sIssue685 = R"mwscript(Begin issue685 Choice: "Sicher. Hier, nehmt." 1 "Nein, ich denke nicht. Tut mir Leid." 2 StartScript GetPCGold End)mwscript"; const std::string sIssue694 = R"mwscript(Begin issue694 float timer if ( timer < .1 ) endif End)mwscript"; const std::string sIssue1062 = R"mwscript(Begin issue1026 short end End)mwscript"; const std::string sIssue1430 = R"mwscript(Begin issue1430 short var If ( menumode == 1 ) Player->AddItem "fur_boots", 1 Player->Equip "iron battle axe", 1 player->addspell "fire bite", 645 player->additem "ring_keley", 1, endif End)mwscript"; const std::string sIssue1593 = R"mwscript(Begin changeWater_-550_400 End)mwscript"; const std::string sIssue1730 = R"mwscript(Begin 4LOM_Corprusarium_Guards End)mwscript"; const std::string sIssue1767 = R"mwscript(Begin issue1767 player->GetPcRank "temple" End)mwscript"; const std::string sIssue2185 = R"mwscript(Begin issue2185 short a short b short eq short gt short lt short ne set eq to 0 if ( a == b ) set eq to ( eq + 1 ) endif if ( a = = b ) set eq to ( eq + 1 ) endif set gt to 0 if ( a > b ) set gt to ( gt + 1 ) endif if ( a > = b ) set gt to ( gt + 1 ) endif set lt to 0 if ( a < b ) set lt to ( lt + 1 ) endif if ( a < = b ) set lt to ( lt + 1 ) endif set ne to 0 if ( a != b ) set ne to ( ne + 1 ) endif if ( a ! = b ) set ne to ( ne + 1 ) endif End)mwscript"; const std::string sIssue2206 = R"mwscript(Begin issue2206 Choice ."Sklavin kaufen." 1 "Lebt wohl." 2 Choice Choice "Insister pour qu’il vous réponde." 6 "Le prier de vous accorder un peu de son temps." 6 " Le menacer de révéler qu'il prélève sa part sur les bénéfices de la mine d’ébonite." 7 End)mwscript"; const std::string sIssue2207 = R"mwscript(Begin issue2207 PositionCell -35 –473 -248 0 "Skaal-Dorf, Die Große Halle" End)mwscript"; const std::string sIssue2794 = R"mwscript(Begin issue2794 if ( player->"getlevel" == 1 ) ; do something endif End)mwscript"; const std::string sIssue2830 = R"mwscript(Begin issue2830 AddItem "if" 1 AddItem "endif" 1 GetItemCount "begin" End)mwscript"; const std::string sIssue2991 = R"mwscript(Begin issue2991 MessageBox "OnActivate" messagebox "messagebox" messagebox "if" messagebox "tcl" End)mwscript"; const std::string sIssue3006 = R"mwscript(Begin issue3006 short a if ( a == 1 ) set a to 2 else set a to 3 endif End)mwscript"; const std::string sIssue3725 = R"mwscript(Begin issue3725 onactivate if onactivate ; do something endif End)mwscript"; const std::string sIssue3744 = R"mwscript(Begin issue3744 short a short b short c set c to 0 if ( a => b ) set c to ( c + 1 ) endif if ( a =< b ) set c to ( c + 1 ) endif if ( a = b ) set c to ( c + 1 ) endif if ( a == b ) set c to ( c + 1 ) endif End)mwscript"; const std::string sIssue3836 = R"mwscript(Begin issue3836 MessageBox " Membership Level: %.0f Account Balance: %.0f Your Gold: %.0f Interest Rate: %.3f Service Charge Rate: %.3f Total Service Charges: %.0f Total Interest Earned: %.0f " Membership BankAccount YourGold InterestRate ServiceRate TotalServiceCharges TotalInterestEarned End)mwscript"; const std::string sIssue3846 = R"mwscript(Begin issue3846 Addtopic -spells... Addtopic -magicka... player->PositionCell, -97274, -94273, 8064, -12,-12 End)mwscript"; const std::string sIssue4061 = R"mwscript(Begin 01_Rz_neuvazhay-koryto2 End)mwscript"; const std::string sIssue4451 = R"mwscript(Begin, GlassDisplayScript ;[Script body] End, GlassDisplayScript)mwscript"; const std::string sIssue4597 = R"mwscript(Begin issue4597 short a short b short c short d set c to 0 set d to 0 if ( a <> b ) set c to ( c + 1 ) endif if ( a << b ) set c to ( c + 1 ) endif if ( a < b ) set c to ( c + 1 ) endif if ( a >< b ) set d to ( d + 1 ) endif if ( a >> b ) set d to ( d + 1 ) endif if ( a > b ) set d to ( d + 1 ) endif End)mwscript"; const std::string sIssue4598 = R"mwscript(Begin issue4598 StartScript kal_S_Pub_Jejubãr_Faraminos End)mwscript"; const std::string sIssue4803 = R"mwscript( -- +-Begin issue4803 End)mwscript"; const std::string sIssue4867 = R"mwscript(Begin issue4867 float PcMagickaMult : The gameplay setting fPcBaseMagickaMult - 1.0000 End)mwscript"; const std::string sIssue4888 = R"mwscript(Begin issue4888 if (player->GameHour == 10) set player->GameHour to 20 endif End)mwscript"; const std::string sIssue4996 = R"mwscript(---Begin issue4996 player-> SetPos, Z, myZ + 50 End)mwscript"; const std::string sIssue5087 = R"mwscript(Begin Begin player->sethealth 0 stopscript Begin End Begin)mwscript"; const std::string sIssue5097 = R"mwscript(Begin issue5097 setscale "0.3" End)mwscript"; const std::string sIssue5345 = R"mwscript(Begin issue5345 StartScript DN_MinionDrain_s" End)mwscript"; const std::string sIssue6066 = R"mwscript(Begin issue6066 addtopic "return" End)mwscript"; const std::string sIssue6282 = R"mwscript(Begin 11AA_LauraScript7.5 End)mwscript"; const std::string sIssue6363 = R"mwscript(Begin issue6363 short 1 if ( "1" == 1 ) PositionCell 0 1 2 3 4 5 "Morrowland" endif set 1 to 42 End)mwscript"; const std::string sIssue6380 = R"mwscript(,Begin,issue6380, ,short,a ,set,a,to,,,,(a,+1) messagebox,"this is a %g",a ,End,)mwscript"; const std::string sIssue6807 = R"mwscript(---Begin issue6807 short a ---------------------- +++++++++++ *************** ///////////////////// ????????? @@@@@@@@ ~~~~~~~~~~~~~~~~~~ set a to 1 ;------------------------------------------------------------------------------------------------------------------------------------------------------------- ; Collision Detection Check ------------------------------------------------------------------------------------------------------------------------------------------------------------- -+'\/.,><$@---!=\/?--------(){}------ show a ( GetDisabled == 1 ) GetDisabled == 1 End)mwscript"; TEST_F(MWScriptTest, mwscript_test_invalid) { EXPECT_THROW(compile("this is not a valid script", true), Compiler::SourceException); } TEST_F(MWScriptTest, mwscript_test_compilation) { EXPECT_FALSE(!compile(sScript1)); } TEST_F(MWScriptTest, mwscript_test_no_extensions) { EXPECT_THROW(compile(sScript2, true), Compiler::SourceException); } TEST_F(MWScriptTest, mwscript_test_function) { registerExtensions(); bool failed = true; if (const auto script = compile(sScript2)) { class AddTopic : public Interpreter::Opcode0 { bool& mFailed; public: AddTopic(bool& failed) : mFailed(failed) { } void execute(Interpreter::Runtime& runtime) { const auto topic = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); mFailed = false; EXPECT_EQ(topic, "OpenMW Unit Test"); } }; installOpcode<AddTopic>(Compiler::Dialogue::opcodeAddTopic, failed); TestInterpreterContext context; run(*script, context); } if (failed) { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_math) { if (const auto script = compile(sScript3)) { struct Algorithm { int a; int b; int c; int d; int e; void run(int input) { a = input; b = a + 1; c = a - 1; d = b * c; e = d / a; } void test(const TestInterpreterContext& context) const { EXPECT_EQ(a, context.getLocalShort(0)); EXPECT_EQ(b, context.getLocalShort(1)); EXPECT_EQ(c, context.getLocalShort(2)); EXPECT_EQ(d, context.getLocalShort(3)); EXPECT_EQ(e, context.getLocalShort(4)); } } algorithm; TestInterpreterContext context; for (int i = 1; i < 1000; ++i) { context.setLocalShort(0, i); run(*script, context); algorithm.run(i); algorithm.test(context); } } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_forum_thread) { registerExtensions(); EXPECT_FALSE(!compile(sScript4)); } TEST_F(MWScriptTest, mwscript_test_587) { EXPECT_FALSE(!compile(sIssue587)); } TEST_F(MWScriptTest, mwscript_test_677) { EXPECT_FALSE(!compile(sIssue677)); } TEST_F(MWScriptTest, mwscript_test_685) { registerExtensions(); EXPECT_FALSE(!compile(sIssue685)); } TEST_F(MWScriptTest, mwscript_test_694) { EXPECT_FALSE(!compile(sIssue694)); } TEST_F(MWScriptTest, mwscript_test_1062) { if (const auto script = compile(sIssue1062)) { EXPECT_EQ(script->mLocals.getIndex("end"), 0); } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_1430) { registerExtensions(); EXPECT_FALSE(!compile(sIssue1430)); } TEST_F(MWScriptTest, mwscript_test_1593) { EXPECT_FALSE(!compile(sIssue1593)); } TEST_F(MWScriptTest, mwscript_test_1730) { EXPECT_FALSE(!compile(sIssue1730)); } TEST_F(MWScriptTest, mwscript_test_1767) { registerExtensions(); EXPECT_FALSE(!compile(sIssue1767)); } TEST_F(MWScriptTest, mwscript_test_2185) { if (const auto script = compile(sIssue2185)) { TestInterpreterContext context; for (int a = 0; a < 100; ++a) { for (int b = 0; b < 100; ++b) { context.setLocalShort(0, a); context.setLocalShort(1, b); run(*script, context); EXPECT_EQ(context.getLocalShort(2), a == b ? 2 : 0); EXPECT_EQ(context.getLocalShort(3), a > b ? 2 : 0); EXPECT_EQ(context.getLocalShort(4), a < b ? 2 : 0); EXPECT_EQ(context.getLocalShort(5), a != b ? 2 : 0); } } } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_2206) { registerExtensions(); EXPECT_FALSE(!compile(sIssue2206)); } TEST_F(MWScriptTest, mwscript_test_2207) { registerExtensions(); EXPECT_FALSE(!compile(sIssue2207)); } TEST_F(MWScriptTest, mwscript_test_2794) { registerExtensions(); EXPECT_FALSE(!compile(sIssue2794)); } TEST_F(MWScriptTest, mwscript_test_2830) { registerExtensions(); EXPECT_FALSE(!compile(sIssue2830)); } TEST_F(MWScriptTest, mwscript_test_2991) { registerExtensions(); EXPECT_FALSE(!compile(sIssue2991)); } TEST_F(MWScriptTest, mwscript_test_3006) { if (const auto script = compile(sIssue3006)) { TestInterpreterContext context; context.setLocalShort(0, 0); run(*script, context); EXPECT_EQ(context.getLocalShort(0), 0); context.setLocalShort(0, 1); run(*script, context); EXPECT_EQ(context.getLocalShort(0), 2); } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_3725) { registerExtensions(); EXPECT_FALSE(!compile(sIssue3725)); } TEST_F(MWScriptTest, mwscript_test_3744) { if (const auto script = compile(sIssue3744)) { TestInterpreterContext context; for (int a = 0; a < 100; ++a) { for (int b = 0; b < 100; ++b) { context.setLocalShort(0, a); context.setLocalShort(1, b); run(*script, context); EXPECT_EQ(context.getLocalShort(2), a == b ? 4 : 0); } } } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_3836) { registerExtensions(); EXPECT_FALSE(!compile(sIssue3836)); } TEST_F(MWScriptTest, mwscript_test_3846) { registerExtensions(); if (const auto script = compile(sIssue3846)) { std::vector<std::string> topics = { "-spells...", "-magicka..." }; class AddTopic : public Interpreter::Opcode0 { std::vector<std::string>& mTopics; public: AddTopic(std::vector<std::string>& topics) : mTopics(topics) { } void execute(Interpreter::Runtime& runtime) { const auto topic = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); EXPECT_EQ(topic, mTopics[0]); mTopics.erase(mTopics.begin()); } }; class PositionCell : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) { std::string_view target = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); Interpreter::Type_Float x = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float y = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float z = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float zRot = runtime[0].mFloat; runtime.pop(); std::string_view cellID = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); EXPECT_EQ(target, "player"); EXPECT_EQ(x, -97274); EXPECT_EQ(y, -94273); EXPECT_EQ(z, 8064); EXPECT_EQ(zRot, -12); EXPECT_EQ(cellID, "-12"); } }; installOpcode<AddTopic>(Compiler::Dialogue::opcodeAddTopic, topics); installOpcode<PositionCell>(Compiler::Transformation::opcodePositionCellExplicit); TestInterpreterContext context; run(*script, context); EXPECT_TRUE(topics.empty()); } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_4061) { EXPECT_FALSE(!compile(sIssue4061)); } TEST_F(MWScriptTest, mwscript_test_4451) { EXPECT_FALSE(!compile(sIssue4451)); } TEST_F(MWScriptTest, mwscript_test_4597) { if (const auto script = compile(sIssue4597)) { TestInterpreterContext context; for (int a = 0; a < 100; ++a) { for (int b = 0; b < 100; ++b) { context.setLocalShort(0, a); context.setLocalShort(1, b); run(*script, context); EXPECT_EQ(context.getLocalShort(2), a < b ? 3 : 0); EXPECT_EQ(context.getLocalShort(3), a > b ? 3 : 0); } } } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_4598) { registerExtensions(); EXPECT_FALSE(!compile(sIssue4598)); } TEST_F(MWScriptTest, mwscript_test_4803) { EXPECT_FALSE(!compile(sIssue4803)); } TEST_F(MWScriptTest, mwscript_test_4867) { EXPECT_FALSE(!compile(sIssue4867)); } TEST_F(MWScriptTest, mwscript_test_4888) { EXPECT_FALSE(!compile(sIssue4888)); } TEST_F(MWScriptTest, mwscript_test_4996) { registerExtensions(); EXPECT_FALSE(!compile(sIssue4996)); } TEST_F(MWScriptTest, mwscript_test_5087) { registerExtensions(); EXPECT_FALSE(!compile(sIssue5087)); } TEST_F(MWScriptTest, mwscript_test_5097) { registerExtensions(); EXPECT_FALSE(!compile(sIssue5097)); } TEST_F(MWScriptTest, mwscript_test_5345) { registerExtensions(); EXPECT_FALSE(!compile(sIssue5345)); } TEST_F(MWScriptTest, mwscript_test_6066) { registerExtensions(); EXPECT_FALSE(!compile(sIssue6066)); } TEST_F(MWScriptTest, mwscript_test_6282) { EXPECT_FALSE(!compile(sIssue6282)); } TEST_F(MWScriptTest, mwscript_test_6363) { registerExtensions(); if (const auto script = compile(sIssue6363)) { class PositionCell : public Interpreter::Opcode0 { bool& mRan; public: PositionCell(bool& ran) : mRan(ran) { } void execute(Interpreter::Runtime& runtime) { mRan = true; } }; bool ran = false; installOpcode<PositionCell>(Compiler::Transformation::opcodePositionCell, ran); TestInterpreterContext context; context.setLocalShort(0, 0); run(*script, context); EXPECT_FALSE(ran); ran = false; context.setLocalShort(0, 1); run(*script, context); EXPECT_TRUE(ran); } else { FAIL(); } } TEST_F(MWScriptTest, mwscript_test_6380) { EXPECT_FALSE(!compile(sIssue6380)); } TEST_F(MWScriptTest, mwscript_test_6807) { registerExtensions(); EXPECT_FALSE(!compile(sIssue6807)); } }
21,852
C++
.cpp
740
21.474324
191
0.559931
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,641
test_keywordsearch.cpp
OpenMW_openmw/apps/openmw_tests/mwdialogue/test_keywordsearch.cpp
#include "apps/openmw/mwdialogue/keywordsearch.hpp" #include <gtest/gtest.h> struct KeywordSearchTest : public ::testing::Test { protected: void SetUp() override {} void TearDown() override {} }; TEST_F(KeywordSearchTest, keyword_test_conflict_resolution) { // test to make sure the longest keyword in a chain of conflicting keywords gets chosen MWDialogue::KeywordSearch<int> search; search.seed("foo bar", 0); search.seed("bar lock", 0); search.seed("lock switch", 0); std::string text = "foo bar lock switch"; std::vector<MWDialogue::KeywordSearch<int>::Match> matches; search.highlightKeywords(text.begin(), text.end(), matches); // Should contain: "foo bar", "lock switch" EXPECT_EQ(matches.size(), 2); EXPECT_EQ(std::string(matches.front().mBeg, matches.front().mEnd), "foo bar"); EXPECT_EQ(std::string(matches.rbegin()->mBeg, matches.rbegin()->mEnd), "lock switch"); } TEST_F(KeywordSearchTest, keyword_test_conflict_resolution2) { MWDialogue::KeywordSearch<int> search; search.seed("the dwemer", 0); search.seed("dwemer language", 0); std::string text = "the dwemer language"; std::vector<MWDialogue::KeywordSearch<int>::Match> matches; search.highlightKeywords(text.begin(), text.end(), matches); EXPECT_EQ(matches.size(), 1); EXPECT_EQ(std::string(matches.front().mBeg, matches.front().mEnd), "dwemer language"); } TEST_F(KeywordSearchTest, keyword_test_conflict_resolution3) { // testing that the longest keyword is chosen, rather than maximizing the // amount of highlighted characters by highlighting the first and last keyword MWDialogue::KeywordSearch<int> search; search.seed("foo bar", 0); search.seed("bar lock", 0); search.seed("lock so", 0); std::string text = "foo bar lock so"; std::vector<MWDialogue::KeywordSearch<int>::Match> matches; search.highlightKeywords(text.begin(), text.end(), matches); EXPECT_EQ(matches.size(), 1); EXPECT_EQ(std::string(matches.front().mBeg, matches.front().mEnd), "bar lock"); } TEST_F(KeywordSearchTest, keyword_test_utf8_word_begin) { // We make sure that the search works well even if the character is not ASCII MWDialogue::KeywordSearch<int> search; search.seed("états", 0); search.seed("ïrradiés", 0); search.seed("ça nous déçois", 0); search.seed("ois", 0); std::string text = "les nations unis ont réunis le monde entier, états units inclus pour parler du problème des gens ïrradiés " "et ça nous déçois"; std::vector<MWDialogue::KeywordSearch<int>::Match> matches; search.highlightKeywords(text.begin(), text.end(), matches); EXPECT_EQ(matches.size(), 3); EXPECT_EQ(std::string(matches[0].mBeg, matches[0].mEnd), "états"); EXPECT_EQ(std::string(matches[1].mBeg, matches[1].mEnd), "ïrradiés"); EXPECT_EQ(std::string(matches[2].mBeg, matches[2].mEnd), "ça nous déçois"); } TEST_F(KeywordSearchTest, keyword_test_non_alpha_non_whitespace_word_begin) { // We make sure that the search works well even if the separator is not a whitespace MWDialogue::KeywordSearch<int> search; search.seed("Report to caius cosades", 0); std::string text = "I was told to \"Report to caius cosades\""; std::vector<MWDialogue::KeywordSearch<int>::Match> matches; search.highlightKeywords(text.begin(), text.end(), matches); EXPECT_EQ(matches.size(), 1); EXPECT_EQ(std::string(matches[0].mBeg, matches[0].mEnd), "Report to caius cosades"); } TEST_F(KeywordSearchTest, keyword_test_russian_non_ascii_before) { // We make sure that the search works well even if the separator is not a whitespace with russian chars MWDialogue::KeywordSearch<int> search; search.seed("Доложить Каю Косадесу", 0); std::string text = "Что? Да. Я Кай Косадес. То есть как это, вам велели «Доложить Каю Косадесу»? О чем вы говорите?"; std::vector<MWDialogue::KeywordSearch<int>::Match> matches; search.highlightKeywords(text.begin(), text.end(), matches); EXPECT_EQ(matches.size(), 1); EXPECT_EQ(std::string(matches[0].mBeg, matches[0].mEnd), "Доложить Каю Косадесу"); } TEST_F(KeywordSearchTest, keyword_test_russian_ascii_before) { // We make sure that the search works well even if the separator is not a whitespace with russian chars MWDialogue::KeywordSearch<int> search; search.seed("Доложить Каю Косадесу", 0); std::string text = "Что? Да. Я Кай Косадес. То есть как это, вам велели 'Доложить Каю Косадесу'? О чем вы говорите?"; std::vector<MWDialogue::KeywordSearch<int>::Match> matches; search.highlightKeywords(text.begin(), text.end(), matches); EXPECT_EQ(matches.size(), 1); EXPECT_EQ(std::string(matches[0].mBeg, matches[0].mEnd), "Доложить Каю Косадесу"); }
5,069
C++
.cpp
101
43.415842
118
0.708874
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,645
ICSPrerequisites.cpp
OpenMW_openmw/extern/oics/ICSPrerequisites.cpp
/* ------------------------------------------------------- Copyright (c) 2011 Alberto G. Salguero (alberto.salguero (at) uca.es) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------- */ #include "ICSPrerequisites.h"
1,243
C++
.cpp
23
52.869565
69
0.741776
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
35,646
ICSChannel.cpp
OpenMW_openmw/extern/oics/ICSChannel.cpp
/* ------------------------------------------------------- Copyright (c) 2011 Alberto G. Salguero (alberto.salguero (at) uca.es) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------- */ #include "ICSInputControlSystem.h" #define B1(t) (t*t) #define B2(t) (2*t*(1-t)) #define B3(t) ((1-t)*(1-t)) namespace ICS { Channel::Channel(int number, float initialValue , float bezierMidPointY, float bezierMidPointX, float symmetricAt, float bezierStep) : mNumber(number) , mValue(initialValue) , mSymmetricAt(symmetricAt) , mBezierStep(bezierStep) , mEnabled(true) { mBezierMidPoint.x = bezierMidPointX; mBezierMidPoint.y = bezierMidPointY; setBezierFunction(bezierMidPointY, bezierMidPointX, symmetricAt, bezierStep); } void Channel::setEnabled(bool enabled) { mEnabled = enabled; } float Channel::getValue() { if(mValue == 0 || mValue == 1) { return mValue; } assert (!mBezierFunction.empty()); BezierFunction::iterator it = mBezierFunction.begin(); //size_t size_minus_1 = mBezierFunction.size() - 1; BezierFunction::iterator last = mBezierFunction.end(); --last; for ( ; it != last ; ) { BezierPoint left = (*it); BezierPoint right = (*(++it)); if( (left.x <= mValue) && (right.x > mValue) ) { float val = left.y - (left.x - mValue) * (left.y - right.y) / (left.x - right.x); return std::max<float>(0.0,std::min<float>(1.0, val)); } } return -1; } void Channel::setValue(float value) { float previousValue = this->getValue(); mValue = value; if(previousValue != value && mEnabled) { notifyListeners(previousValue); } } void Channel::notifyListeners(float previousValue) { std::list<ChannelListener*>::iterator pos = mListeners.begin(); while (pos != mListeners.end()) { (*pos)->channelChanged((Channel*)this, this->getValue(), previousValue); ++pos; } } void Channel::addControl(Control* control, Channel::ChannelDirection dir, float percentage) { ControlChannelBinderItem ccBinderItem; ccBinderItem.control = control; ccBinderItem.direction = dir; ccBinderItem.percentage = percentage; mAttachedControls.push_back(ccBinderItem); } Channel::ControlChannelBinderItem Channel::getAttachedControlBinding(Control* control) { for(std::vector<ControlChannelBinderItem>::iterator it = mAttachedControls.begin() ; it != mAttachedControls.end() ; it++) { if((*it).control == control) { return (*it); } } ControlChannelBinderItem nullBinderItem; nullBinderItem.control = NULL; nullBinderItem.direction = Channel/*::ChannelDirection*/::DIRECT; nullBinderItem.percentage = 0; return nullBinderItem; } void Channel::update() { if(this->getControlsCount() == 1) { ControlChannelBinderItem ccBinderItem = mAttachedControls.back(); float diff = ccBinderItem.control->getValue() - ccBinderItem.control->getInitialValue(); if(ccBinderItem.direction == ICS::Channel::DIRECT) { this->setValue(ccBinderItem.control->getInitialValue() + (ccBinderItem.percentage * diff)); } else { this->setValue(ccBinderItem.control->getInitialValue() - (ccBinderItem.percentage * diff)); } } else { float val = 0; std::vector<ControlChannelBinderItem>::const_iterator it; for(it=mAttachedControls.begin(); it!=mAttachedControls.end(); ++it) { ControlChannelBinderItem ccBinderItem = (*it); float diff = ccBinderItem.control->getValue() - ccBinderItem.control->getInitialValue(); if(ccBinderItem.direction == ICS::Channel::DIRECT) { val += (ccBinderItem.percentage * diff); } else { val -= (ccBinderItem.percentage * diff); } } if(mAttachedControls.size() > 0) { this->setValue(mAttachedControls.begin()->control->getInitialValue() + val); } } } void Channel::setBezierFunction(float bezierMidPointY, float bezierMidPointX, float symmetricAt, float bezierStep) { mBezierMidPoint.x = bezierMidPointX; mBezierMidPoint.y = bezierMidPointY; mBezierStep = bezierStep; mSymmetricAt = symmetricAt; mBezierFunction.clear(); BezierPoint start; start.x = 0; start.y = 0; BezierPoint end; end.x = 1; end.y = 1; mBezierFunction.push_front(end); FilterInterval interval; interval.startX = start.x; interval.startY = start.y; interval.midX = mBezierMidPoint.x; interval.midY = mBezierMidPoint.y; interval.endX = end.x; interval.endY = end.y; interval.step = bezierStep; mIntervals.push_back(interval); if(!(mBezierMidPoint.x == 0.5 && mBezierMidPoint.y == 0.5)) { float t = mBezierStep; while(t < 1) { BezierPoint p; p.x = start.x * B1(t) + mBezierMidPoint.x * B2(t) + end.x * B3(t); p.y = start.y * B1(t) + mBezierMidPoint.y * B2(t) + end.y * B3(t); mBezierFunction.push_front(p); t += mBezierStep; } } mBezierFunction.push_front(start); } void Channel::addBezierInterval(float startX, float startY, float midX, float midY , float endX, float endY, float step) { FilterInterval interval; interval.startX = startX; interval.startY = startY; interval.midX = midX; interval.midY = midY; interval.endX = endX; interval.endY = endY; interval.step = step; mIntervals.push_back(interval); float t = 0; while(t <= 1) { BezierPoint p; p.x = startX * B1(t) + midX * B2(t) + endX * B3(t); p.y = startY * B1(t) + midY * B2(t) + endY * B3(t); BezierFunction::iterator it = mBezierFunction.begin(); while( it != mBezierFunction.end() ) { BezierPoint left = (*it); BezierPoint right; ++it; if( it != mBezierFunction.end() ) { right = (*it); } else { right.x = endX; right.y = endY; } if(p.x > left.x && p.x < right.x) { mBezierFunction.insert(it, p); break; } } t += 1.0f / ((endX-startX)/step); } } }
7,164
C++
.cpp
227
26.991189
115
0.66802
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
true
true
false
35,648
ICSInputControlSystem.cpp
OpenMW_openmw/extern/oics/ICSInputControlSystem.cpp
/* ------------------------------------------------------- Copyright (c) 2011 Alberto G. Salguero (alberto.salguero (at) uca.es) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------- */ #include "ICSInputControlSystem.h" namespace ICS { const float ICS_MAX = std::numeric_limits<float>::max(); InputControlSystem::InputControlSystem(std::string file, bool active , DetectingBindingListener* detectingBindingListener , InputControlSystemLog* log, size_t channelCount) : mFileName(file) , mDeadZone(0.1f) , mLog(log) , mDetectingBindingListener(detectingBindingListener) , mDetectingBindingControl(NULL) , mDetectingBindingDirection(Control::STOP) , mXmouseAxisBinded(false), mYmouseAxisBinded(false) , mClientWidth(1) , mClientHeight(1) , mMouseAxisBindingInitialValues{0} { ICS_LOG(" - Creating InputControlSystem - "); this->mActive = active; ICS_LOG("Channel count = " + ToString<size_t>(channelCount) ); for(size_t i=0;i<channelCount;i++) { mChannels.push_back(new Channel((int)i)); } if(file != "") { TiXmlDocument* xmlDoc; TiXmlElement* xmlRoot; ICS_LOG("Loading file \""+file+"\""); xmlDoc = new TiXmlDocument(file.c_str()); xmlDoc->LoadFile(); if(xmlDoc->Error()) { std::ostringstream message; message << "TinyXml reported an error reading \""+ file + "\". Row " << (int)xmlDoc->ErrorRow() << ", Col " << (int)xmlDoc->ErrorCol() << ": " << xmlDoc->ErrorDesc() ; ICS_LOG(message.str()); delete xmlDoc; return; } xmlRoot = xmlDoc->RootElement(); if(std::string(xmlRoot->Value()) != "Controller") { ICS_LOG("Error: Invalid Controller file. Missing <Controller> element."); delete xmlDoc; return; } TiXmlElement* xmlControl = xmlRoot->FirstChildElement("Control"); size_t controlChannelCount = 0; while(xmlControl) { TiXmlElement* xmlChannel = xmlControl->FirstChildElement("Channel"); while(xmlChannel) { controlChannelCount = std::max(channelCount, FromString<size_t>(xmlChannel->Attribute("number"))+1); xmlChannel = xmlChannel->NextSiblingElement("Channel"); } xmlControl = xmlControl->NextSiblingElement("Control"); } static const size_t channelsCountLimit = 65536; if (controlChannelCount > channelsCountLimit) { ICS_LOG("Warning: requested channels count (" + ToString<size_t>(controlChannelCount) + ") exceeds allowed maximum (" + ToString<size_t>(channelsCountLimit) + "), clamping it"); controlChannelCount = channelsCountLimit; } if(controlChannelCount > channelCount) { size_t dif = controlChannelCount - channelCount; ICS_LOG("Warning: default channel count exceeded. Adding " + ToString<size_t>(dif) + " channels" ); for(size_t i = channelCount ; i < controlChannelCount ; i++) { mChannels.push_back(new Channel((int)i)); } } ICS_LOG("Applying filters to channels"); //<ChannelFilter number="0"> // <interval type="bezier" startX="0.0" startY="0.0" midX="0.25" midY="0.5" endX="0.5" endY="0.5" step="0.1" /> // <interval type="bezier" startX="0.5" startY="0.5" midX="0.75" midY="0.5" endX="1.0" endY="1.0" step="0.1" /> //</ChannelFilter> TiXmlElement* xmlChannelFilter = xmlRoot->FirstChildElement("ChannelFilter"); while(xmlChannelFilter) { size_t ch = FromString<size_t>(xmlChannelFilter->Attribute("number")); if(ch >= controlChannelCount) { ICS_LOG("ERROR: channel number (ch) is out of range"); xmlChannelFilter = xmlChannelFilter->NextSiblingElement("ChannelFilter"); continue; } TiXmlElement* xmlInterval = xmlChannelFilter->FirstChildElement("Interval"); while(xmlInterval) { std::string type = xmlInterval->Attribute("type"); if(type == "bezier") { float startX = FromString<float>(xmlInterval->Attribute("startX")); float startY = FromString<float>(xmlInterval->Attribute("startY")); float midX = FromString<float>(xmlInterval->Attribute("midX")); float midY = FromString<float>(xmlInterval->Attribute("midY")); float endX = FromString<float>(xmlInterval->Attribute("endX")); float endY = FromString<float>(xmlInterval->Attribute("endY")); float step = FromString<float>(xmlInterval->Attribute("step")); ICS_LOG("Applying Bezier filter to channel [number=" + ToString<size_t>(ch) + ", startX=" + ToString<float>(startX) + ", startY=" + ToString<float>(startY) + ", midX=" + ToString<float>(midX) + ", midY=" + ToString<float>(midY) + ", endX=" + ToString<float>(endX) + ", endY=" + ToString<float>(endY) + ", step=" + ToString<float>(step) + "]"); mChannels.at(ch)->addBezierInterval(startX, startY, midX, midY, endX, endY, step); } xmlInterval = xmlInterval->NextSiblingElement("Interval"); } xmlChannelFilter = xmlChannelFilter->NextSiblingElement("ChannelFilter"); } xmlControl = xmlRoot->FirstChildElement("Control"); while(xmlControl) { bool axisBindable = true; if(xmlControl->Attribute("axisBindable")) { axisBindable = (std::string( xmlControl->Attribute("axisBindable") ) == "true"); } ICS_LOG("Adding Control [name=" + std::string( xmlControl->Attribute("name") ) + ", autoChangeDirectionOnLimitsAfterStop=" + std::string( xmlControl->Attribute("autoChangeDirectionOnLimitsAfterStop") ) + ", autoReverseToInitialValue=" + std::string( xmlControl->Attribute("autoReverseToInitialValue") ) + ", initialValue=" + std::string( xmlControl->Attribute("initialValue") ) + ", stepSize=" + std::string( xmlControl->Attribute("stepSize") ) + ", stepsPerSeconds=" + std::string( xmlControl->Attribute("stepsPerSeconds") ) + ", axisBindable=" + std::string( (axisBindable)? "true" : "false" ) + "]"); float _stepSize = 0; if(xmlControl->Attribute("stepSize")) { std::string value(xmlControl->Attribute("stepSize")); if(value == "MAX") { _stepSize = ICS_MAX; } else { _stepSize = FromString<float>(value.c_str()); } } else { ICS_LOG("Warning: no stepSize value found. Default value is 0."); } float _stepsPerSeconds = 0; if(xmlControl->Attribute("stepsPerSeconds")) { std::string value(xmlControl->Attribute("stepsPerSeconds")); if(value == "MAX") { _stepsPerSeconds = ICS_MAX; } else { _stepsPerSeconds = FromString<float>(value.c_str()); } } else { ICS_LOG("Warning: no stepSize value found. Default value is 0."); } addControl( new Control(xmlControl->Attribute("name") , std::string( xmlControl->Attribute("autoChangeDirectionOnLimitsAfterStop") ) == "true" , std::string( xmlControl->Attribute("autoReverseToInitialValue") ) == "true" , FromString<float>(xmlControl->Attribute("initialValue")) , _stepSize , _stepsPerSeconds , axisBindable) ); loadKeyBinders(xmlControl); loadMouseAxisBinders(xmlControl); loadMouseButtonBinders(xmlControl); loadJoystickAxisBinders(xmlControl); loadJoystickButtonBinders(xmlControl); /* ---------------------------------------------------------------------------------------- * OPENMW CODE STARTS HERE * Mouse Wheel support added by Michael Stopa (Stomy) */ loadMouseWheelBinders(xmlControl); /* OPENMW CODE ENDS HERE * ------------------------------------------------------------------------------------- */ // Attach controls to channels TiXmlElement* xmlChannel = xmlControl->FirstChildElement("Channel"); while(xmlChannel) { ICS_LOG("\tAttaching control to channel [number=" + std::string( xmlChannel->Attribute("number") ) + ", direction=" + std::string( xmlChannel->Attribute("direction") ) + "]"); float percentage = 1; if(xmlChannel->Attribute("percentage")) { if(StringIsNumber<float>(xmlChannel->Attribute("percentage"))) { float val = FromString<float>(xmlChannel->Attribute("percentage")); if(val > 1 || val < 0) { ICS_LOG("ERROR: attaching percentage value range is [0,1]"); } else { percentage = val; } } else { ICS_LOG("ERROR: attaching percentage value range is [0,1]"); } } size_t chNumber = FromString<size_t>(xmlChannel->Attribute("number")); if(chNumber >= controlChannelCount) { ICS_LOG("ERROR: channel number (chNumber) is out of range"); } else { if(std::string(xmlChannel->Attribute("direction")) == "DIRECT") { mControls.back()->attachChannel(mChannels[ chNumber ],Channel::DIRECT, percentage); } else if(std::string(xmlChannel->Attribute("direction")) == "INVERSE") { mControls.back()->attachChannel(mChannels[ chNumber ],Channel::INVERSE, percentage); } } xmlChannel = xmlChannel->NextSiblingElement("Channel"); } xmlControl = xmlControl->NextSiblingElement("Control"); } std::vector<Channel *>::const_iterator o; for(o = mChannels.begin(); o != mChannels.end(); ++o) { (*o)->update(); } delete xmlDoc; } ICS_LOG(" - InputControlSystem Created - "); } InputControlSystem::~InputControlSystem() { ICS_LOG(" - Deleting InputControlSystem (" + mFileName + ") - "); mJoystickIDList.clear(); std::vector<Channel *>::const_iterator o; for(o = mChannels.begin(); o != mChannels.end(); ++o) { delete (*o); } mChannels.clear(); std::vector<Control *>::const_iterator o2; for(o2 = mControls.begin(); o2 != mControls.end(); ++o2) { delete (*o2); } mControls.clear(); mControlsKeyBinderMap.clear(); mControlsMouseButtonBinderMap.clear(); mControlsJoystickButtonBinderMap.clear(); /* ---------------------------------------------------------------------------------------- * OPENMW CODE STARTS HERE * Mouse Wheel support added by Michael Stopa (Stomy) */ mControlsMouseWheelBinderMap.clear(); /* OPENMW CODE ENDS HERE * ------------------------------------------------------------------------------------- */ ICS_LOG(" - InputControlSystem deleted - "); } std::string InputControlSystem::getBaseFileName() { size_t found = mFileName.find_last_of("/\\"); std::string file = mFileName.substr(found+1); return file.substr(0, file.find_last_of(".")); } bool InputControlSystem::save(const std::string& fileName) { TiXmlDocument doc(fileName.c_str()); TiXmlDeclaration dec; dec.Parse( "<?xml version='1.0' encoding='utf-8'?>", 0, TIXML_ENCODING_UNKNOWN ); doc.InsertEndChild(dec); TiXmlElement Controller( "Controller" ); for(std::vector<Channel*>::const_iterator o = mChannels.begin() ; o != mChannels.end(); ++o) { ICS::IntervalList intervals = (*o)->getIntervals(); if(intervals.size() > 1) // all channels have a default linear filter { TiXmlElement ChannelFilter( "ChannelFilter" ); ChannelFilter.SetAttribute("number", ToString<int>((*o)->getNumber()).c_str()); ICS::IntervalList::const_iterator interval = intervals.begin(); while( interval != intervals.end() ) { // if not default linear filter if(!( interval->step == 0.2f && interval->startX == 0.0f && interval->startY == 0.0f && interval->midX == 0.5f && interval->midY == 0.5f && interval->endX == 1.0f && interval->endY == 1.0f )) { TiXmlElement XMLInterval( "Interval" ); XMLInterval.SetAttribute("type", "bezier"); XMLInterval.SetAttribute("step", ToString<float>(interval->step).c_str()); XMLInterval.SetAttribute("startX", ToString<float>(interval->startX).c_str()); XMLInterval.SetAttribute("startY", ToString<float>(interval->startY).c_str()); XMLInterval.SetAttribute("midX", ToString<float>(interval->midX).c_str()); XMLInterval.SetAttribute("midY", ToString<float>(interval->midY).c_str()); XMLInterval.SetAttribute("endX", ToString<float>(interval->endX).c_str()); XMLInterval.SetAttribute("endY", ToString<float>(interval->endY).c_str()); ChannelFilter.InsertEndChild(XMLInterval); } ++interval; } Controller.InsertEndChild(ChannelFilter); } } for(std::vector<Control*>::const_iterator o = mControls.begin() ; o != mControls.end(); ++o) { TiXmlElement control( "Control" ); control.SetAttribute( "name", (*o)->getName().c_str() ); if((*o)->getAutoChangeDirectionOnLimitsAfterStop()) { control.SetAttribute( "autoChangeDirectionOnLimitsAfterStop", "true" ); } else { control.SetAttribute( "autoChangeDirectionOnLimitsAfterStop", "false" ); } if((*o)->getAutoReverse()) { control.SetAttribute( "autoReverseToInitialValue", "true" ); } else { control.SetAttribute( "autoReverseToInitialValue", "false" ); } control.SetAttribute( "initialValue", ToString<float>((*o)->getInitialValue()).c_str() ); if((*o)->getStepSize() == ICS_MAX) { control.SetAttribute( "stepSize", "MAX" ); } else { control.SetAttribute( "stepSize", ToString<float>((*o)->getStepSize()).c_str() ); } if((*o)->getStepsPerSeconds() == ICS_MAX) { control.SetAttribute( "stepsPerSeconds", "MAX" ); } else { control.SetAttribute( "stepsPerSeconds", ToString<float>((*o)->getStepsPerSeconds()).c_str() ); } if(!(*o)->isAxisBindable()) { control.SetAttribute( "axisBindable", "false" ); } if(getKeyBinding(*o, Control/*::ControlChangingDirection*/::INCREASE) != SDL_SCANCODE_UNKNOWN) { TiXmlElement keyBinder( "KeyBinder" ); keyBinder.SetAttribute( "key", ToString<int>( getKeyBinding(*o, Control/*::ControlChangingDirection*/::INCREASE)).c_str() ); keyBinder.SetAttribute( "direction", "INCREASE" ); control.InsertEndChild(keyBinder); } if(getKeyBinding(*o, Control/*::ControlChangingDirection*/::DECREASE) != SDL_SCANCODE_UNKNOWN) { TiXmlElement keyBinder( "KeyBinder" ); keyBinder.SetAttribute( "key", ToString<int>( getKeyBinding(*o, Control/*::ControlChangingDirection*/::DECREASE)).c_str() ); keyBinder.SetAttribute( "direction", "DECREASE" ); control.InsertEndChild(keyBinder); } if(getMouseAxisBinding(*o, Control/*::ControlChangingDirection*/::INCREASE) != InputControlSystem/*::NamedAxis*/::UNASSIGNED) { TiXmlElement binder( "MouseBinder" ); InputControlSystem::NamedAxis axis = getMouseAxisBinding(*o, Control/*::ControlChangingDirection*/::INCREASE); if(axis == InputControlSystem/*::NamedAxis*/::X) { binder.SetAttribute( "axis", "X" ); } else if(axis == InputControlSystem/*::NamedAxis*/::Y) { binder.SetAttribute( "axis", "Y" ); } else if(axis == InputControlSystem/*::NamedAxis*/::Z) { binder.SetAttribute( "axis", "Z" ); } binder.SetAttribute( "direction", "INCREASE" ); control.InsertEndChild(binder); } if(getMouseAxisBinding(*o, Control/*::ControlChangingDirection*/::DECREASE) != InputControlSystem/*::NamedAxis*/::UNASSIGNED) { TiXmlElement binder( "MouseBinder" ); InputControlSystem::NamedAxis axis = getMouseAxisBinding(*o, Control/*::ControlChangingDirection*/::DECREASE); if(axis == InputControlSystem/*::NamedAxis*/::X) { binder.SetAttribute( "axis", "X" ); } else if(axis == InputControlSystem/*::NamedAxis*/::Y) { binder.SetAttribute( "axis", "Y" ); } else if(axis == InputControlSystem/*::NamedAxis*/::Z) { binder.SetAttribute( "axis", "Z" ); } binder.SetAttribute( "direction", "DECREASE" ); control.InsertEndChild(binder); } /* ---------------------------------------------------------------------------------------- * OPENMW CODE STARTS HERE * Mouse Wheel support added by Stomy */ if(getMouseWheelBinding(*o, Control::INCREASE) != MouseWheelClick::UNASSIGNED) { TiXmlElement binder( "MouseWheelBinder" ); MouseWheelClick click = getMouseWheelBinding(*o, Control::INCREASE); bool skip = false; switch (click) { case MouseWheelClick::UP: { binder.SetAttribute("button", "UP"); } break; case MouseWheelClick::DOWN: { binder.SetAttribute("button", "DOWN"); } break; case MouseWheelClick::RIGHT: { binder.SetAttribute("button", "RIGHT"); } break; case MouseWheelClick::LEFT: { binder.SetAttribute("button", "LEFT"); } break; default: { skip = true; } break; } binder.SetAttribute( "direction", "INCREASE" ); if (!skip) control.InsertEndChild(binder); } if(getMouseWheelBinding(*o, Control::DECREASE) != MouseWheelClick::UNASSIGNED) { TiXmlElement binder( "MouseWheelBinder" ); MouseWheelClick click = getMouseWheelBinding(*o, Control::INCREASE); bool skip = false; switch (click) { case MouseWheelClick::UP: { binder.SetAttribute("button", "UP"); } break; case MouseWheelClick::DOWN: { binder.SetAttribute("button", "DOWN"); } break; case MouseWheelClick::RIGHT: { binder.SetAttribute("button", "RIGHT"); } break; case MouseWheelClick::LEFT: { binder.SetAttribute("button", "LEFT"); } break; default: { skip = true; } break; } binder.SetAttribute( "direction", "DECREASE" ); if (!skip) control.InsertEndChild(binder); } /* OPENMW CODE ENDS HERE * ------------------------------------------------------------------------------------- */ if(getMouseButtonBinding(*o, Control/*::ControlChangingDirection*/::INCREASE) != ICS_MAX_DEVICE_BUTTONS) { TiXmlElement binder( "MouseButtonBinder" ); unsigned int button = getMouseButtonBinding(*o, Control/*::ControlChangingDirection*/::INCREASE); if(button == SDL_BUTTON_LEFT) { binder.SetAttribute( "button", "LEFT" ); } else if(button == SDL_BUTTON_MIDDLE) { binder.SetAttribute( "button", "MIDDLE" ); } else if(button == SDL_BUTTON_RIGHT) { binder.SetAttribute( "button", "RIGHT" ); } else { binder.SetAttribute( "button", ToString<unsigned int>(button).c_str() ); } binder.SetAttribute( "direction", "INCREASE" ); control.InsertEndChild(binder); } if(getMouseButtonBinding(*o, Control/*::ControlChangingDirection*/::DECREASE) != ICS_MAX_DEVICE_BUTTONS) { TiXmlElement binder( "MouseButtonBinder" ); unsigned int button = getMouseButtonBinding(*o, Control/*::ControlChangingDirection*/::DECREASE); if(button == SDL_BUTTON_LEFT) { binder.SetAttribute( "button", "LEFT" ); } else if(button == SDL_BUTTON_MIDDLE) { binder.SetAttribute( "button", "MIDDLE" ); } else if(button == SDL_BUTTON_RIGHT) { binder.SetAttribute( "button", "RIGHT" ); } else { binder.SetAttribute( "button", ToString<unsigned int>(button).c_str() ); } binder.SetAttribute( "direction", "DECREASE" ); control.InsertEndChild(binder); } JoystickIDList::const_iterator it = mJoystickIDList.begin(); while(it!=mJoystickIDList.end()) { int deviceID = *it; if(getJoystickAxisBinding(*o, deviceID, Control/*::ControlChangingDirection*/::INCREASE) != /*NamedAxis::*/UNASSIGNED) { TiXmlElement binder( "JoystickAxisBinder" ); binder.SetAttribute( "axis", ToString<int>( getJoystickAxisBinding(*o, deviceID, Control/*::ControlChangingDirection*/::INCREASE)).c_str() ); binder.SetAttribute( "direction", "INCREASE" ); binder.SetAttribute( "deviceId", deviceID ); //completely useless, but required for backwards compatability control.InsertEndChild(binder); } if(getJoystickAxisBinding(*o, deviceID, Control/*::ControlChangingDirection*/::DECREASE) != /*NamedAxis::*/UNASSIGNED) { TiXmlElement binder( "JoystickAxisBinder" ); binder.SetAttribute( "axis", ToString<int>( getJoystickAxisBinding(*o, deviceID, Control/*::ControlChangingDirection*/::DECREASE)).c_str() ); binder.SetAttribute( "direction", "DECREASE" ); binder.SetAttribute( "deviceId", deviceID ); //completely useless, but required for backwards compatability control.InsertEndChild(binder); } if(getJoystickButtonBinding(*o, deviceID, Control/*::ControlChangingDirection*/::INCREASE) != ICS_MAX_DEVICE_BUTTONS) { TiXmlElement binder( "JoystickButtonBinder" ); binder.SetAttribute( "button", ToString<unsigned int>( getJoystickButtonBinding(*o, deviceID, Control/*::ControlChangingDirection*/::INCREASE)).c_str() ); binder.SetAttribute( "direction", "INCREASE" ); binder.SetAttribute( "deviceId", deviceID ); //completely useless, but required for backwards compatability control.InsertEndChild(binder); } if(getJoystickButtonBinding(*o, deviceID, Control/*::ControlChangingDirection*/::DECREASE) != ICS_MAX_DEVICE_BUTTONS) { TiXmlElement binder( "JoystickButtonBinder" ); binder.SetAttribute( "button", ToString<unsigned int>( getJoystickButtonBinding(*o, deviceID, Control/*::ControlChangingDirection*/::DECREASE)).c_str() ); binder.SetAttribute( "direction", "DECREASE" ); binder.SetAttribute( "deviceId", deviceID ); //completely useless, but required for backwards compatability control.InsertEndChild(binder); } it++; } std::list<Channel*> channels = (*o)->getAttachedChannels(); for(std::list<Channel*>::iterator it = channels.begin() ; it != channels.end() ; ++it) { TiXmlElement binder( "Channel" ); binder.SetAttribute( "number", ToString<int>((*it)->getNumber()).c_str() ); Channel::ChannelDirection direction = (*it)->getAttachedControlBinding(*o).direction; if(direction == Channel/*::ChannelDirection*/::DIRECT) { binder.SetAttribute( "direction", "DIRECT" ); } else { binder.SetAttribute( "direction", "INVERSE" ); } float percentage = (*it)->getAttachedControlBinding(*o).percentage; binder.SetAttribute( "percentage", ToString<float>(percentage).c_str() ); control.InsertEndChild(binder); } Controller.InsertEndChild(control); } doc.InsertEndChild(Controller); return doc.SaveFile(); } void InputControlSystem::update(float lTimeSinceLastFrame) { if(mActive) { std::vector<Control *>::const_iterator it; for(it=mControls.begin(); it!=mControls.end(); ++it) { (*it)->update(lTimeSinceLastFrame); } } //! @todo Future versions should consider channel exponentials and mixtures, so // after updating Controls, Channels should be updated according to their values } float InputControlSystem::getChannelValue(int i) { return std::max<float>(0.0,std::min<float>(1.0,mChannels[i]->getValue())); } float InputControlSystem::getControlValue(int i) { return mControls[i]->getValue(); } Control* InputControlSystem::findControl(std::string name) { if(mActive) { std::vector<Control *>::const_iterator it; for(it = mControls.begin(); it != mControls.end(); ++it) { if( ((Control*)(*it))->getName() == name) { return (Control*)(*it); } } } return NULL; } void InputControlSystem::enableDetectingBindingState(Control* control , Control::ControlChangingDirection direction) { mDetectingBindingControl = control; mDetectingBindingDirection = direction; mMouseAxisBindingInitialValues[0] = ICS_MOUSE_AXIS_BINDING_NULL_VALUE; } bool InputControlSystem::detectingBindingState() { return mDetectingBindingControl != NULL; } void InputControlSystem::cancelDetectingBindingState() { mDetectingBindingControl = NULL; } std::string InputControlSystem::scancodeToString(SDL_Scancode key) { return std::string(SDL_GetScancodeName(key)); } void InputControlSystem::adjustMouseRegion(Uint16 width, Uint16 height) { mClientWidth = width; mClientHeight = height; } }
25,929
C++
.cpp
674
32.350148
181
0.638654
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
35,649
ICSControl.cpp
OpenMW_openmw/extern/oics/ICSControl.cpp
/* ------------------------------------------------------- Copyright (c) 2011 Alberto G. Salguero (alberto.salguero (at) uca.es) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------- */ #include "ICSInputControlSystem.h" #include "ICSControl.h" namespace ICS { Control::Control(const std::string& name, bool autoChangeDirectionOnLimitsAfterStop, bool autoReverseToInitialValue , float initialValue, float stepSize, float stepsPerSeconds, bool axisBindable) : mValue(initialValue) , mInitialValue(initialValue) , mName(name) , mStepSize(stepSize) , mStepsPerSeconds(stepsPerSeconds) , mAutoReverseToInitialValue(autoReverseToInitialValue) , mIgnoreAutoReverse(false) , mAutoChangeDirectionOnLimitsAfterStop(autoChangeDirectionOnLimitsAfterStop) , mAxisBindable(axisBindable) , currentChangingDirection(STOP) { } Control::~Control() { mAttachedChannels.clear(); } void Control::setValue(float value) { float previousValue = mValue; mValue = std::max<float>(0.0,std::min<float>(1.0,value)); if(mValue != previousValue) { updateChannels(); notifyListeners(previousValue); } } void Control::attachChannel(Channel* channel, Channel::ChannelDirection direction, float percentage) { mAttachedChannels.push_back(channel); channel->addControl(this, direction, percentage); } void Control::updateChannels() { std::list<Channel*>::iterator pos = mAttachedChannels.begin(); while (pos != mAttachedChannels.end()) { ((Channel* )(*pos))->update(); ++pos; } } void Control::notifyListeners(float previousValue) { std::list<ControlListener*>::iterator pos = mListeners.begin(); while (pos != mListeners.end()) { (*pos)->controlChanged((Control*)this, this->getValue(), previousValue); ++pos; } } void Control::setChangingDirection(ControlChangingDirection direction) { currentChangingDirection = direction; mPendingActions.push_back(direction); } void Control::update(float timeSinceLastFrame) { if(!mPendingActions.empty()) { size_t timedActionsCount = 0; std::list<Control::ControlChangingDirection>::iterator cached_end = mPendingActions.end(); for(std::list<Control::ControlChangingDirection>::iterator it = mPendingActions.begin() ; it != cached_end ; ++it) { if( (*it) != Control::STOP ) { timedActionsCount++; } } float timeSinceLastFramePart = timeSinceLastFrame / std::max<size_t>(1, timedActionsCount); for(std::list<Control::ControlChangingDirection>::iterator it = mPendingActions.begin() ; it != cached_end ; ++it) { if( (*it) != Control::STOP ) { this->setValue(mValue + (((int)(*it)) * mStepSize * mStepsPerSeconds * (timeSinceLastFramePart))); } else if(mAutoReverseToInitialValue && !mIgnoreAutoReverse && mValue != mInitialValue ) { if(mValue > mInitialValue) { this->setValue( std::max<float>( mInitialValue, mValue - (mStepSize * mStepsPerSeconds * (timeSinceLastFramePart)))); } else if(mValue < mInitialValue) { this->setValue( std::min<float>( mInitialValue, mValue + (mStepSize * mStepsPerSeconds * (timeSinceLastFramePart)))); } } } mPendingActions.clear(); } else if( currentChangingDirection != Control::STOP ) { this->setValue(mValue + (((int)currentChangingDirection) * mStepSize * mStepsPerSeconds * (timeSinceLastFrame))); } else if(mAutoReverseToInitialValue && !mIgnoreAutoReverse && mValue != mInitialValue ) { if(mValue > mInitialValue) { this->setValue( std::max<float>( mInitialValue, mValue - (mStepSize * mStepsPerSeconds * (timeSinceLastFrame)))); } else if(mValue < mInitialValue) { this->setValue( std::min<float>( mInitialValue, mValue + (mStepSize * mStepsPerSeconds * (timeSinceLastFrame)))); } } } }
5,007
C++
.cpp
141
31.283688
119
0.703879
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
35,650
ICSInputControlSystem_joystick.cpp
OpenMW_openmw/extern/oics/ICSInputControlSystem_joystick.cpp
/* ------------------------------------------------------- Copyright (c) 2011 Alberto G. Salguero (alberto.salguero (at) uca.es) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------- */ #include "ICSInputControlSystem.h" #define SDL_JOY_AXIS_MIN -32768 #define SDL_JOY_AXIS_MAX 32767 namespace ICS { // load xml void InputControlSystem::loadJoystickAxisBinders(TiXmlElement* xmlControlNode) { TiXmlElement* xmlJoystickBinder = xmlControlNode->FirstChildElement("JoystickAxisBinder"); while(xmlJoystickBinder) { Control::ControlChangingDirection dir = Control::STOP; if(std::string(xmlJoystickBinder->Attribute("direction")) == "INCREASE") { dir = Control::INCREASE; } else if(std::string(xmlJoystickBinder->Attribute("direction")) == "DECREASE") { dir = Control::DECREASE; } addJoystickAxisBinding(mControls.back(), FromString<int>(xmlJoystickBinder->Attribute("deviceId")), FromString<int>(xmlJoystickBinder->Attribute("axis")), dir); xmlJoystickBinder = xmlJoystickBinder->NextSiblingElement("JoystickAxisBinder"); } } void InputControlSystem::loadJoystickButtonBinders(TiXmlElement* xmlControlNode) { TiXmlElement* xmlJoystickButtonBinder = xmlControlNode->FirstChildElement("JoystickButtonBinder"); while(xmlJoystickButtonBinder) { Control::ControlChangingDirection dir = Control::STOP; if(std::string(xmlJoystickButtonBinder->Attribute("direction")) == "INCREASE") { dir = Control::INCREASE; } else if(std::string(xmlJoystickButtonBinder->Attribute("direction")) == "DECREASE") { dir = Control::DECREASE; } addJoystickButtonBinding(mControls.back(), FromString<int>(xmlJoystickButtonBinder->Attribute("deviceId")), FromString<int>(xmlJoystickButtonBinder->Attribute("button")), dir); xmlJoystickButtonBinder = xmlJoystickButtonBinder->NextSiblingElement("JoystickButtonBinder"); } } // add bindings void InputControlSystem::addJoystickAxisBinding(Control* control, int deviceID, int axis, Control::ControlChangingDirection direction) { if (std::find(mJoystickIDList.begin(), mJoystickIDList.end(), deviceID) == mJoystickIDList.end()) mJoystickIDList.push_back(deviceID); ICS_LOG("\tAdding AxisBinder [axis=" + ToString<int>(axis) + ", deviceID=" + ToString<int>(deviceID) + ", direction=" + ToString<int>(direction) + "]"); control->setValue(0.5f); //all joystick axis start at .5, so do that ControlAxisBinderItem controlAxisBinderItem; controlAxisBinderItem.control = control; controlAxisBinderItem.direction = direction; mControlsJoystickAxisBinderMap[deviceID][axis] = controlAxisBinderItem; } void InputControlSystem::addJoystickButtonBinding(Control* control, int deviceID, unsigned int button, Control::ControlChangingDirection direction) { if (std::find(mJoystickIDList.begin(), mJoystickIDList.end(), deviceID) == mJoystickIDList.end()) mJoystickIDList.push_back(deviceID); // Hack: add the device to the list so bindings are saved in save() even when joystick is not connected ICS_LOG("\tAdding JoystickButtonBinder [button=" + ToString<int>(button) + ", deviceID=" + ToString<int>(deviceID) + ", direction=" + ToString<int>(direction) + "]"); ControlButtonBinderItem controlJoystickButtonBinderItem; controlJoystickButtonBinderItem.direction = direction; controlJoystickButtonBinderItem.control = control; mControlsJoystickButtonBinderMap[deviceID][button] = controlJoystickButtonBinderItem; } bool InputControlSystem::isJoystickButtonBound(int deviceID, unsigned int button) const { JoystickButtonBinderMapType::const_iterator found = mControlsJoystickButtonBinderMap.find(deviceID); if (found == mControlsJoystickButtonBinderMap.end()) return false; return (found->second.find(button) != found->second.end()); } bool InputControlSystem::isJoystickAxisBound(int deviceID, unsigned int axis) const { JoystickAxisBinderMapType::const_iterator found = mControlsJoystickAxisBinderMap.find(deviceID); if (found == mControlsJoystickAxisBinderMap.end()) return false; return (found->second.find(axis) != found->second.end()); } // get bindings int InputControlSystem::getJoystickAxisBinding(Control* control, int deviceID, ICS::Control::ControlChangingDirection direction) { if(mControlsJoystickAxisBinderMap.find(deviceID) != mControlsJoystickAxisBinderMap.end()) { ControlsAxisBinderMapType::iterator it = mControlsJoystickAxisBinderMap[deviceID].begin(); while(it != mControlsJoystickAxisBinderMap[deviceID].end()) { if(it->first >= 0 && it->second.control == control && it->second.direction == direction) { return it->first; } ++it; } } return /*NamedAxis::*/UNASSIGNED; } unsigned int InputControlSystem::getJoystickButtonBinding(Control* control, int deviceID, ICS::Control::ControlChangingDirection direction) { if(mControlsJoystickButtonBinderMap.find(deviceID) != mControlsJoystickButtonBinderMap.end()) { ControlsButtonBinderMapType::iterator it = mControlsJoystickButtonBinderMap[deviceID].begin(); while(it != mControlsJoystickButtonBinderMap[deviceID].end()) { if(it->second.control == control && it->second.direction == direction) { return it->first; } ++it; } } return ICS_MAX_DEVICE_BUTTONS; } // remove bindings void InputControlSystem::removeJoystickAxisBinding(int deviceID, int axis) { if(mControlsJoystickAxisBinderMap.find(deviceID) != mControlsJoystickAxisBinderMap.end()) { ControlsAxisBinderMapType::iterator it = mControlsJoystickAxisBinderMap[deviceID].find(axis); if(it != mControlsJoystickAxisBinderMap[deviceID].end()) { mControlsJoystickAxisBinderMap[deviceID].erase(it); } } } void InputControlSystem::removeJoystickButtonBinding(int deviceID, unsigned int button) { if(mControlsJoystickButtonBinderMap.find(deviceID) != mControlsJoystickButtonBinderMap.end()) { ControlsButtonBinderMapType::iterator it = mControlsJoystickButtonBinderMap[deviceID].find(button); if(it != mControlsJoystickButtonBinderMap[deviceID].end()) { mControlsJoystickButtonBinderMap[deviceID].erase(it); } } } // joyStick listeners void InputControlSystem::buttonPressed(int deviceID, const SDL_ControllerButtonEvent &evt) { if(mActive) { if(!mDetectingBindingControl) { if(mControlsJoystickButtonBinderMap.find(deviceID) != mControlsJoystickButtonBinderMap.end()) { ControlsButtonBinderMapType::const_iterator it = mControlsJoystickButtonBinderMap[deviceID].find(evt.button); if(it != mControlsJoystickButtonBinderMap[deviceID].end()) { it->second.control->setIgnoreAutoReverse(false); if(!it->second.control->getAutoChangeDirectionOnLimitsAfterStop()) { it->second.control->setChangingDirection(it->second.direction); } else { if(it->second.control->getValue() == 1) { it->second.control->setChangingDirection(Control::DECREASE); } else if(it->second.control->getValue() == 0) { it->second.control->setChangingDirection(Control::INCREASE); } } } } } } } void InputControlSystem::buttonReleased(int deviceID, const SDL_ControllerButtonEvent &evt) { if(mActive) { if(!mDetectingBindingControl) { if(mControlsJoystickButtonBinderMap.find(deviceID) != mControlsJoystickButtonBinderMap.end()) { ControlsButtonBinderMapType::const_iterator it = mControlsJoystickButtonBinderMap[deviceID].find(evt.button); if(it != mControlsJoystickButtonBinderMap[deviceID].end()) { it->second.control->setChangingDirection(Control::STOP); } } } else if(mDetectingBindingListener) { mDetectingBindingListener->joystickButtonBindingDetected(this, deviceID, mDetectingBindingControl, evt.button, mDetectingBindingDirection); } } } void InputControlSystem::axisMoved(int deviceID, const SDL_ControllerAxisEvent &evt) { if(mActive) { if(!mDetectingBindingControl) { if(mControlsJoystickAxisBinderMap.find(deviceID) != mControlsJoystickAxisBinderMap.end()) { ControlAxisBinderItem joystickBinderItem = mControlsJoystickAxisBinderMap[deviceID][evt.axis]; // joystic axis start at 0 index Control* ctrl = joystickBinderItem.control; if(ctrl) { ctrl->setIgnoreAutoReverse(true); float axisRange = SDL_JOY_AXIS_MAX - SDL_JOY_AXIS_MIN; float valDisplaced = (float)(evt.value - SDL_JOY_AXIS_MIN); float percent = valDisplaced / axisRange * (1+mDeadZone*2) - mDeadZone; //Assures all values, 0 through 1, are seen if(percent > .5-mDeadZone && percent < .5+mDeadZone) //close enough to center percent = .5; else if(percent > .5) percent -= mDeadZone; else percent += mDeadZone; if(joystickBinderItem.direction == Control::INCREASE) { ctrl->setValue( percent ); } else if(joystickBinderItem.direction == Control::DECREASE) { ctrl->setValue( 1 - ( percent ) ); } } } } else if(mDetectingBindingListener) { //ControlAxisBinderItem joystickBinderItem = mControlsJoystickAxisBinderMap[ evt.which ][ axis ]; // joystic axis start at 0 index //Control* ctrl = joystickBinderItem.control; //if(ctrl && ctrl->isAxisBindable()) if(mDetectingBindingControl->isAxisBindable()) { if( abs( evt.value ) > ICS_JOYSTICK_AXIS_BINDING_MARGIN) { mDetectingBindingListener->joystickAxisBindingDetected(this, deviceID, mDetectingBindingControl, evt.axis, mDetectingBindingDirection); } } } } } void InputControlSystem::controllerAdded(int deviceID, const SDL_ControllerDeviceEvent &args) { ICS_LOG("Adding joystick (index: " + ToString<int>(args.which) + ")"); SDL_GameController* cntrl = SDL_GameControllerOpen(args.which); int instanceID = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(cntrl)); if(std::find(mJoystickIDList.begin(), mJoystickIDList.end(), deviceID)==mJoystickIDList.end()) { for(int j = 0 ; j < ICS_MAX_JOYSTICK_AXIS ; j++) { if(mControlsJoystickAxisBinderMap[deviceID].find(j) == mControlsJoystickAxisBinderMap[deviceID].end()) { ControlAxisBinderItem controlJoystickBinderItem; controlJoystickBinderItem.direction = Control::STOP; controlJoystickBinderItem.control = NULL; mControlsJoystickAxisBinderMap[deviceID][j] = controlJoystickBinderItem; } } mJoystickIDList.push_front(deviceID); } mJoystickInstanceMap[instanceID] = cntrl; } void InputControlSystem::controllerRemoved(const SDL_ControllerDeviceEvent &args) { ICS_LOG("Removing joystick (instance id: " + ToString<int>(args.which) + ")"); if(mJoystickInstanceMap.count(args.which)!=0) { SDL_GameControllerClose(mJoystickInstanceMap.at(args.which)); mJoystickInstanceMap.erase(args.which); } } // joystick auto bindings void DetectingBindingListener::joystickAxisBindingDetected(InputControlSystem* ICS, int deviceID, Control* control, int axis, Control::ControlChangingDirection direction) { // if the joystick axis is used by another control, remove it ICS->removeJoystickAxisBinding(deviceID, axis); // if the control has an axis assigned, remove it int oldAxis = ICS->getJoystickAxisBinding(control, deviceID, direction); if(oldAxis != InputControlSystem::UNASSIGNED) { ICS->removeJoystickAxisBinding(deviceID, oldAxis); } ICS->addJoystickAxisBinding(control, deviceID, axis, direction); ICS->cancelDetectingBindingState(); } void DetectingBindingListener::joystickButtonBindingDetected(InputControlSystem* ICS, int deviceID, Control* control , unsigned int button, Control::ControlChangingDirection direction) { // if the joystick button is used by another control, remove it ICS->removeJoystickButtonBinding(deviceID, button); // if the control has a joystick button assigned, remove it unsigned int oldButton = ICS->getJoystickButtonBinding(control, deviceID, direction); if(oldButton != ICS_MAX_DEVICE_BUTTONS) { ICS->removeJoystickButtonBinding(deviceID, oldButton); } ICS->addJoystickButtonBinding(control, deviceID, button, direction); ICS->cancelDetectingBindingState(); } }
14,885
C++
.cpp
325
37.067692
179
0.670661
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,653
CompositeOsgRenderer.cpp
OpenMW_openmw/extern/osgQt/CompositeOsgRenderer.cpp
#include "CompositeOsgRenderer.hpp" #include "osgQOpenGLWidget.hpp" #include <mutex> #include <osgViewer/View> #include <thread> CompositeOsgRenderer::CompositeOsgRenderer(QObject* parent) : QObject(parent), osgViewer::CompositeViewer(), mSimulationTime(0.0) { _firstFrame = true; } CompositeOsgRenderer::CompositeOsgRenderer(osg::ArgumentParser* arguments, QObject* parent) : QObject(parent), osgViewer::CompositeViewer(*arguments), mSimulationTime(0.0) { _firstFrame = true; } CompositeOsgRenderer::~CompositeOsgRenderer() { } void CompositeOsgRenderer::update() { double dt = mFrameTimer.time_s(); mFrameTimer.setStartTick(); emit simulationUpdated(dt); mSimulationTime += dt; osgQOpenGLWidget* osgWidget = dynamic_cast<osgQOpenGLWidget*>(parent()); if (osgWidget) { osgWidget->update(); } double minFrameTime = _runMaxFrameRate > 0.0 ? 1.0 / _runMaxFrameRate : 0.0; if (dt < minFrameTime) { std::this_thread::sleep_for(std::chrono::duration<double>(minFrameTime - dt)); } } void CompositeOsgRenderer::resize(int windowWidth, int windowHeight) { if(!m_osgInitialized) return; for(RefViews::iterator itr = _views.begin(); itr != _views.end(); ++itr) { osgViewer::View* view = itr->get(); if(view) { m_osgWinEmb->resized(0, 0, windowWidth, windowHeight); m_osgWinEmb->getEventQueue()->windowResize(0, 0, windowWidth, windowHeight); } } update(); } void CompositeOsgRenderer::setGraphicsWindowEmbedded(osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> osgWinEmb) { m_osgWinEmb = osgWinEmb; } void CompositeOsgRenderer::setupOSG() { m_osgInitialized = true; m_osgWinEmb->getEventQueue()->syncWindowRectangleWithGraphicsContext(); // disable key event (default is Escape key) that the viewer checks on each // frame to see // if the viewer's done flag should be set to signal end of viewers main // loop. setKeyEventSetsDone(0); setReleaseContextAtEndOfFrameHint(false); setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); setRunFrameScheme(osgViewer::ViewerBase::ON_DEMAND); connect( &mTimer, SIGNAL(timeout()), this, SLOT(update()) ); mTimer.start( 10 ); osgViewer::CompositeViewer::Windows windows; getWindows(windows); } // called from ViewerWidget paintGL() method void CompositeOsgRenderer::frame(double simulationTime) { if(_done) return; if(_firstFrame) { viewerInit(); realize(); _firstFrame = false; } advance(simulationTime); eventTraversal(); updateTraversal(); renderingTraversals(); } void CompositeOsgRenderer::timerEvent(QTimerEvent* /*event*/) { // ask ViewerWidget to update 3D view if(getRunFrameScheme() != osgViewer::ViewerBase::ON_DEMAND || checkNeedToDoFrame()) { update(); } }
2,949
C++
.cpp
96
26.166667
111
0.703534
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,654
osgQOpenGLWidget.cpp
OpenMW_openmw/extern/osgQt/osgQOpenGLWidget.cpp
#include "CompositeOsgRenderer.hpp" #include "osgQOpenGLWidget.hpp" #include <mutex> #include <osgViewer/View> #include <QApplication> #include <QScreen> #include <QWindow> osgQOpenGLWidget::osgQOpenGLWidget(QWidget* parent) : QOpenGLWidget(parent) { m_renderer = new CompositeOsgRenderer(this); setMouseTracking(true); } osgQOpenGLWidget::osgQOpenGLWidget(osg::ArgumentParser* arguments, QWidget* parent) : QOpenGLWidget(parent), _arguments(arguments) { m_renderer = new CompositeOsgRenderer(this); } osgQOpenGLWidget::~osgQOpenGLWidget() { if (m_renderer) delete m_renderer; } osgViewer::View* osgQOpenGLWidget::getOsgView(unsigned i) { if (m_renderer) return m_renderer->getView(i); else return nullptr; } std::mutex* osgQOpenGLWidget::mutex() { return &_osgMutex; } void osgQOpenGLWidget::initializeGL() { createRenderer(); emit initialized(); } void osgQOpenGLWidget::resizeGL(int w, int h) { Q_ASSERT(m_renderer); QScreen* screen = windowHandle() && windowHandle()->screen() ? windowHandle()->screen() : qApp->screens().front(); m_renderer->resize(w * screen->devicePixelRatio(), h * screen->devicePixelRatio()); } void osgQOpenGLWidget::paintGL() { std::scoped_lock locker(_osgMutex); if (_isFirstFrame) { _isFirstFrame = false; for (unsigned int i = 0; i < m_renderer->getNumViews(); ++i) { m_renderer->getView(i)->getCamera()->getGraphicsContext()->setDefaultFboId(defaultFramebufferObject()); } } m_renderer->frame(); } void osgQOpenGLWidget::setDefaultDisplaySettings() { osg::DisplaySettings* ds = osg::DisplaySettings::instance().get(); ds->setNvOptimusEnablement(1); ds->setStereo(false); } CompositeOsgRenderer* osgQOpenGLWidget::getCompositeViewer() { if (m_renderer) return m_renderer; return nullptr; } void osgQOpenGLWidget::setGraphicsWindowEmbedded(osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> osgWinEmb) { if (m_renderer) m_renderer->setGraphicsWindowEmbedded(std::move(osgWinEmb)); } void osgQOpenGLWidget::createRenderer() { // call this before creating a View... setDefaultDisplaySettings(); if (!m_renderer) m_renderer = new CompositeOsgRenderer(this); m_renderer->setupOSG(); }
2,366
C++
.cpp
81
25.024691
115
0.706167
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,655
videostate.cpp
OpenMW_openmw/extern/osg-ffmpeg-videoplayer/videostate.cpp
#include "videostate.hpp" #include <algorithm> #include <cassert> #include <cstddef> #include <iostream> #include <memory> #include <thread> #include <chrono> #include <osg/Texture2D> #include <utility> #if defined(_MSC_VER) #pragma warning (push) #pragma warning (disable : 4244) #endif extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <libavutil/time.h> } #if defined(_MSC_VER) #pragma warning (pop) #endif static const char* flushString = "FLUSH"; struct FlushPacket : AVPacket { FlushPacket() : AVPacket() { data = ( (uint8_t*)flushString); } }; static FlushPacket flush_pkt; #include "videoplayer.hpp" #include "audiodecoder.hpp" #include "audiofactory.hpp" #include "libavformatdefines.hpp" namespace { const int MAX_AUDIOQ_SIZE = (5 * 16 * 1024); const int MAX_VIDEOQ_SIZE = (5 * 256 * 1024); struct AVPacketUnref { void operator()(AVPacket* packet) const { av_packet_unref(packet); } }; struct AVFrameFree { void operator()(AVFrame* frame) const { av_frame_free(&frame); } }; } namespace Video { struct PacketListFree { void operator()(Video::PacketList* list) const { av_packet_free(&list->pkt); av_free(&list); } }; VideoState::VideoState() : mAudioFactory(nullptr) , format_ctx(nullptr) , video_ctx(nullptr) , audio_ctx(nullptr) , av_sync_type(AV_SYNC_DEFAULT) , audio_st(nullptr) , video_st(nullptr), frame_last_pts(0.0) , video_clock(0.0), sws_context(nullptr) , sws_context_w(0), sws_context_h(0) , pictq_size(0), pictq_rindex(0), pictq_windex(0) , mSeekRequested(false) , mSeekPos(0) , mVideoEnded(false) , mPaused(false) , mQuit(false) { mFlushPktData = flush_pkt.data; // This is not needed any more above FFMpeg version 4.0 #if LIBAVCODEC_VERSION_INT < 3805796 av_register_all(); #endif } VideoState::~VideoState() { deinit(); } void VideoState::setAudioFactory(MovieAudioFactory *factory) { mAudioFactory = factory; } void PacketQueue::put(AVPacket *pkt) { std::unique_ptr<PacketList, PacketListFree> pkt1(static_cast<PacketList*>(av_malloc(sizeof(PacketList)))); if(!pkt1) throw std::bad_alloc(); if(pkt == &flush_pkt) pkt1->pkt = pkt; else { pkt1->pkt = av_packet_alloc(); av_packet_move_ref(pkt1->pkt, pkt); } pkt1->next = nullptr; std::lock_guard<std::mutex> lock(this->mutex); PacketList* ptr = pkt1.release(); if(!last_pkt) this->first_pkt = ptr; else this->last_pkt->next = ptr; this->last_pkt = ptr; this->nb_packets++; this->size += ptr->pkt->size; this->cond.notify_one(); } int PacketQueue::get(AVPacket *pkt, VideoState *is) { std::unique_lock<std::mutex> lock(this->mutex); while(!is->mQuit) { PacketList *pkt1 = this->first_pkt; if(pkt1) { this->first_pkt = pkt1->next; if(!this->first_pkt) this->last_pkt = nullptr; this->nb_packets--; this->size -= pkt1->pkt->size; av_packet_unref(pkt); av_packet_move_ref(pkt, pkt1->pkt); av_free(pkt1); return 1; } if(this->flushing) break; this->cond.wait(lock); } return -1; } void PacketQueue::flush() { this->flushing = true; this->cond.notify_one(); } void PacketQueue::clear() { PacketList *pkt, *pkt1; std::lock_guard<std::mutex> lock(this->mutex); for(pkt = this->first_pkt; pkt != nullptr; pkt = pkt1) { pkt1 = pkt->next; if (pkt->pkt->data != flush_pkt.data) av_packet_unref(pkt->pkt); av_freep(&pkt); } this->last_pkt = nullptr; this->first_pkt = nullptr; this->nb_packets = 0; this->size = 0; } int VideoPicture::set_dimensions(int w, int h) { if (this->rgbaFrame != nullptr && this->rgbaFrame->width == w && this->rgbaFrame->height == h) { return 0; } std::unique_ptr<AVFrame, VideoPicture::AVFrameDeleter> frame{ av_frame_alloc()}; if (frame == nullptr) { OSG_FATAL << "av_frame_alloc failed" << std::endl; return -1; } constexpr AVPixelFormat kPixFmt = AV_PIX_FMT_RGBA; frame->format = kPixFmt; frame->width = w; frame->height = h; if (av_image_alloc(frame->data, frame->linesize, frame->width, frame->height, kPixFmt, 1) < 0) { OSG_FATAL << "av_image_alloc failed" << std::endl; return -1; } this->rgbaFrame = std::move(frame); return 0; } void VideoPicture::AVFrameDeleter::operator()(AVFrame* frame) const { av_freep(frame->data); av_frame_free(&frame); } int VideoState::istream_read(void *user_data, uint8_t *buf, int buf_size) { try { std::istream& stream = *static_cast<VideoState*>(user_data)->stream; stream.clear(); stream.read((char*)buf, buf_size); if (stream.bad()) return AVERROR_UNKNOWN; auto count = stream.gcount(); // avio_alloc_context says we mustn't return 0 for stream protocols if (!count) return AVERROR_EOF; return count; } catch (std::exception& ) { return AVERROR_UNKNOWN; } } #if OPENMW_FFMPEG_CONST_WRITEPACKET int VideoState::istream_write(void *, const unsigned char *, int) #else int VideoState::istream_write(void *, uint8_t *, int) #endif { throw std::runtime_error("can't write to read-only stream"); } int64_t VideoState::istream_seek(void *user_data, int64_t offset, int whence) { std::istream& stream = *static_cast<VideoState*>(user_data)->stream; whence &= ~AVSEEK_FORCE; stream.clear(); if(whence == AVSEEK_SIZE) { size_t prev = stream.tellg(); stream.seekg(0, std::ios_base::end); size_t size = stream.tellg(); stream.seekg(prev, std::ios_base::beg); return size; } if(whence == SEEK_SET) stream.seekg(offset, std::ios_base::beg); else if(whence == SEEK_CUR) stream.seekg(offset, std::ios_base::cur); else if(whence == SEEK_END) stream.seekg(offset, std::ios_base::end); else return -1; return stream.tellg(); } void VideoState::video_display(VideoPicture *vp) { if(this->video_ctx->width != 0 && this->video_ctx->height != 0) { if (!mTexture.get()) { mTexture = new osg::Texture2D; mTexture->setDataVariance(osg::Object::DYNAMIC); mTexture->setResizeNonPowerOfTwoHint(false); mTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); mTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); } osg::ref_ptr<osg::Image> image = new osg::Image; image->setImage(this->video_ctx->width, this->video_ctx->height, 1, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, vp->rgbaFrame->data[0], osg::Image::NO_DELETE); mTexture->setImage(image); } } void VideoState::video_refresh() { std::lock_guard<std::mutex> lock(this->pictq_mutex); if(this->pictq_size == 0) return; if (this->av_sync_type == AV_SYNC_VIDEO_MASTER) { VideoPicture* vp = &this->pictq[this->pictq_rindex]; this->video_display(vp); this->pictq_rindex = (this->pictq_rindex+1) % this->pictq.size(); this->frame_last_pts = vp->pts; this->pictq_size--; this->pictq_cond.notify_one(); } else { const float threshold = 0.03f; if (this->pictq[pictq_rindex].pts > this->get_master_clock() + threshold) return; // not ready yet to show this picture // TODO: the conversion to RGBA is done in the decoding thread, so if a picture is skipped here, then it was // unnecessarily converted. But we may want to replace the conversion by a pixel shader anyway (see comment in queue_picture) int i=0; for (; i<this->pictq_size-1; ++i) { if (this->pictq[this->pictq_rindex].pts + threshold <= this->get_master_clock()) this->pictq_rindex = (this->pictq_rindex+1) % this->pictq.size(); // not enough time to show this picture else break; } assert (this->pictq_rindex < this->pictq.size()); VideoPicture* vp = &this->pictq[this->pictq_rindex]; this->video_display(vp); this->frame_last_pts = vp->pts; this->pictq_size -= i; // update queue for next picture this->pictq_size--; this->pictq_rindex = (this->pictq_rindex+1) % this->pictq.size(); this->pictq_cond.notify_one(); } } int VideoState::queue_picture(const AVFrame &pFrame, double pts) { VideoPicture *vp; /* wait until we have a new pic */ { std::unique_lock<std::mutex> lock(this->pictq_mutex); while(this->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !this->mQuit) this->pictq_cond.wait_for(lock, std::chrono::milliseconds(1)); } if(this->mQuit) return -1; std::lock_guard<std::mutex> lock(this->pictq_mutex); // windex is set to 0 initially vp = &this->pictq[this->pictq_windex]; // Convert the image into RGBA format // TODO: we could do this in a pixel shader instead, if the source format // matches a commonly used format (ie YUV420P) const int w = pFrame.width; const int h = pFrame.height; if(this->sws_context == nullptr || this->sws_context_w != w || this->sws_context_h != h) { if (this->sws_context != nullptr) sws_freeContext(this->sws_context); this->sws_context = sws_getContext(w, h, this->video_ctx->pix_fmt, w, h, AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr); if(this->sws_context == nullptr) throw std::runtime_error("Cannot initialize the conversion context!\n"); this->sws_context_w = w; this->sws_context_h = h; } vp->pts = pts; if (vp->set_dimensions(w, h) < 0) return -1; sws_scale(this->sws_context, pFrame.data, pFrame.linesize, 0, this->video_ctx->height, vp->rgbaFrame->data, vp->rgbaFrame->linesize); // now we inform our display thread that we have a pic ready this->pictq_windex = (this->pictq_windex+1) % this->pictq.size(); this->pictq_size++; return 0; } double VideoState::synchronize_video(const AVFrame &src_frame, double pts) { double frame_delay; /* if we have pts, set video clock to it */ if(pts != 0) this->video_clock = pts; else pts = this->video_clock; /* update the video clock */ frame_delay = av_q2d(this->video_ctx->pkt_timebase); /* if we are repeating a frame, adjust clock accordingly */ frame_delay += src_frame.repeat_pict * (frame_delay * 0.5); this->video_clock += frame_delay; return pts; } class VideoThread { public: explicit VideoThread(VideoState* self) : mVideoState(self) , mThread([this] { try { run(); } catch(std::exception& e) { OSG_FATAL << "An error occurred playing the video: " << e.what() << std::endl; } }) { } ~VideoThread() { mThread.join(); } void run() { VideoState* self = mVideoState; AVPacket* packetData = av_packet_alloc(); std::unique_ptr<AVPacket, AVPacketUnref> packet(packetData); std::unique_ptr<AVFrame, AVFrameFree> pFrame{av_frame_alloc()}; while(self->videoq.get(packet.get(), self) >= 0) { if(packet->data == flush_pkt.data) { avcodec_flush_buffers(self->video_ctx); self->pictq_mutex.lock(); self->pictq_size = 0; self->pictq_rindex = 0; self->pictq_windex = 0; self->pictq_mutex.unlock(); self->frame_last_pts = packet->pts * av_q2d((*self->video_st)->time_base); continue; } // Decode video frame int ret = avcodec_send_packet(self->video_ctx, packet.get()); // EAGAIN is not expected if (ret < 0) throw std::runtime_error("Error decoding video frame"); while (!ret) { ret = avcodec_receive_frame(self->video_ctx, pFrame.get()); if (!ret) { double pts = pFrame->best_effort_timestamp; pts *= av_q2d((*self->video_st)->time_base); pts = self->synchronize_video(*pFrame, pts); if(self->queue_picture(*pFrame, pts) < 0) break; } } } } private: VideoState* mVideoState; std::thread mThread; }; class ParseThread { public: explicit ParseThread(VideoState* self) : mVideoState(self) , mThread([this] { run(); }) { } ~ParseThread() { mThread.join(); } void run() { VideoState* self = mVideoState; AVFormatContext *pFormatCtx = self->format_ctx; AVPacket* packetData = av_packet_alloc(); std::unique_ptr<AVPacket, AVPacketUnref> packet(packetData); try { if(!self->video_st && !self->audio_st) throw std::runtime_error("No streams to decode"); // main decode loop while(!self->mQuit) { if(self->mSeekRequested) { uint64_t seek_target = self->mSeekPos; int streamIndex = -1; int videoStreamIndex = -1; int audioStreamIndex = -1; if (self->video_st) videoStreamIndex = self->video_st - self->format_ctx->streams; if (self->audio_st) audioStreamIndex = self->audio_st - self->format_ctx->streams; if(videoStreamIndex >= 0) streamIndex = videoStreamIndex; else if(audioStreamIndex >= 0) streamIndex = audioStreamIndex; uint64_t timestamp = seek_target; // QtCreator's highlighter doesn't like AV_TIME_BASE_Q's {} initializer for some reason AVRational avTimeBaseQ = AVRational(); // = AV_TIME_BASE_Q; avTimeBaseQ.num = 1; avTimeBaseQ.den = AV_TIME_BASE; if(streamIndex >= 0) timestamp = av_rescale_q(seek_target, avTimeBaseQ, self->format_ctx->streams[streamIndex]->time_base); // AVSEEK_FLAG_BACKWARD appears to be needed, otherwise ffmpeg may seek to a keyframe *after* the given time // we want to seek to any keyframe *before* the given time, so we can continue decoding as normal from there on if(av_seek_frame(self->format_ctx, streamIndex, timestamp, AVSEEK_FLAG_BACKWARD) < 0) { // In the FFMpeg 4.0 a "filename" field was replaced by "url" #if LIBAVCODEC_VERSION_INT < 3805796 OSG_FATAL << "Error seeking " << self->format_ctx->filename << std::endl; #else OSG_FATAL << "Error seeking " << self->format_ctx->url << std::endl; #endif } else { // Clear the packet queues and put a special packet with the new clock time if(audioStreamIndex >= 0) { self->audioq.clear(); flush_pkt.pts = av_rescale_q(seek_target, avTimeBaseQ, self->format_ctx->streams[audioStreamIndex]->time_base); self->audioq.put(&flush_pkt); } if(videoStreamIndex >= 0) { self->videoq.clear(); flush_pkt.pts = av_rescale_q(seek_target, avTimeBaseQ, self->format_ctx->streams[videoStreamIndex]->time_base); self->videoq.put(&flush_pkt); } self->pictq_mutex.lock(); self->pictq_size = 0; self->pictq_rindex = 0; self->pictq_windex = 0; self->pictq_mutex.unlock(); self->mExternalClock.set(seek_target); } self->mSeekRequested = false; } if((self->audio_st && self->audioq.size > MAX_AUDIOQ_SIZE) || (self->video_st && self->videoq.size > MAX_VIDEOQ_SIZE)) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } if(av_read_frame(pFormatCtx, packet.get()) < 0) { if (self->audioq.nb_packets == 0 && self->videoq.nb_packets == 0) { self->pictq_mutex.lock(); bool videoEnded = self->pictq_size == 0; self->pictq_mutex.unlock(); if (videoEnded) self->mVideoEnded = true; else std::this_thread::sleep_for(std::chrono::milliseconds(10)); } continue; } else self->mVideoEnded = false; // Is this a packet from the video stream? if(self->video_st && packet->stream_index == self->video_st-pFormatCtx->streams) self->videoq.put(packet.get()); else if(self->audio_st && packet->stream_index == self->audio_st-pFormatCtx->streams) self->audioq.put(packet.get()); else av_packet_unref(packet.get()); } } catch(std::exception& e) { OSG_FATAL << "An error occurred playing the video: " << e.what() << std::endl; } self->mQuit = true; } private: VideoState* mVideoState; std::thread mThread; }; bool VideoState::update() { this->video_refresh(); return !this->mVideoEnded; } int VideoState::stream_open(int stream_index, AVFormatContext *pFormatCtx) { if(stream_index < 0 || stream_index >= static_cast<int>(pFormatCtx->nb_streams)) return -1; // Get a pointer to the codec context for the video stream const AVCodec *codec = avcodec_find_decoder(pFormatCtx->streams[stream_index]->codecpar->codec_id); if(!codec) { fprintf(stderr, "Unsupported codec!\n"); return -1; } switch(pFormatCtx->streams[stream_index]->codecpar->codec_type) { case AVMEDIA_TYPE_AUDIO: this->audio_st = pFormatCtx->streams + stream_index; // Get a pointer to the codec context for the video stream this->audio_ctx = avcodec_alloc_context3(codec); avcodec_parameters_to_context(this->audio_ctx, pFormatCtx->streams[stream_index]->codecpar); // This is not needed any more above FFMpeg version 4.0 #if LIBAVCODEC_VERSION_INT < 3805796 av_codec_set_pkt_timebase(this->audio_ctx, pFormatCtx->streams[stream_index]->time_base); #endif if (avcodec_open2(this->audio_ctx, codec, nullptr) < 0) { fprintf(stderr, "Unsupported codec!\n"); return -1; } if (!mAudioFactory) { OSG_FATAL << "No audio factory registered, can not play audio stream" << std::endl; avcodec_free_context(&this->audio_ctx); this->audio_st = nullptr; return -1; } mAudioDecoder = mAudioFactory->createDecoder(this); if (!mAudioDecoder) { OSG_FATAL << "Failed to create audio decoder, can not play audio stream" << std::endl; avcodec_free_context(&this->audio_ctx); this->audio_st = nullptr; return -1; } mAudioDecoder->setupFormat(); break; case AVMEDIA_TYPE_VIDEO: this->video_st = pFormatCtx->streams + stream_index; // Get a pointer to the codec context for the video stream this->video_ctx = avcodec_alloc_context3(codec); avcodec_parameters_to_context(this->video_ctx, pFormatCtx->streams[stream_index]->codecpar); // This is not needed any more above FFMpeg version 4.0 #if LIBAVCODEC_VERSION_INT < 3805796 av_codec_set_pkt_timebase(this->video_ctx, pFormatCtx->streams[stream_index]->time_base); #endif if (avcodec_open2(this->video_ctx, codec, nullptr) < 0) { fprintf(stderr, "Unsupported codec!\n"); return -1; } this->video_thread = std::make_unique<VideoThread>(this); break; default: break; } return 0; } void VideoState::init(std::unique_ptr<std::istream>&& inputstream, const std::string &name) { int video_index = -1; int audio_index = -1; unsigned int i; this->av_sync_type = AV_SYNC_DEFAULT; this->mQuit = false; this->stream = std::move(inputstream); if(!this->stream) throw std::runtime_error("Failed to open video resource"); AVIOContext *ioCtx = avio_alloc_context(nullptr, 0, 0, this, istream_read, istream_write, istream_seek); if(!ioCtx) throw std::runtime_error("Failed to allocate AVIOContext"); this->format_ctx = avformat_alloc_context(); if(this->format_ctx) this->format_ctx->pb = ioCtx; // Open video file /// /// format_ctx->pb->buffer must be freed by hand, /// if not, valgrind will show memleak, see: /// /// https://trac.ffmpeg.org/ticket/1357 /// if(!this->format_ctx || avformat_open_input(&this->format_ctx, name.c_str(), nullptr, nullptr)) { if (this->format_ctx != nullptr) { if (this->format_ctx->pb != nullptr) { av_freep(&this->format_ctx->pb->buffer); #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 80, 100) avio_context_free(&this->format_ctx->pb); #else av_freep(&this->format_ctx->pb); #endif } } // "Note that a user-supplied AVFormatContext will be freed on failure." this->format_ctx = nullptr; #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 80, 100) avio_context_free(&ioCtx); #else av_freep(&ioCtx); #endif throw std::runtime_error("Failed to open video input"); } // Retrieve stream information if(avformat_find_stream_info(this->format_ctx, nullptr) < 0) throw std::runtime_error("Failed to retrieve stream information"); // Dump information about file onto standard error av_dump_format(this->format_ctx, 0, name.c_str(), 0); for(i = 0;i < this->format_ctx->nb_streams;i++) { if(this->format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_index < 0) video_index = i; if(this->format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_index < 0) audio_index = i; } mExternalClock.set(0); if(audio_index >= 0) this->stream_open(audio_index, this->format_ctx); if(video_index >= 0) { this->stream_open(video_index, this->format_ctx); } this->parse_thread = std::make_unique<ParseThread>(this); } void VideoState::deinit() { this->mQuit = true; this->audioq.flush(); this->videoq.flush(); mAudioDecoder.reset(); if (this->parse_thread) { this->parse_thread.reset(); } if (this->video_thread) { this->video_thread.reset(); } if(this->audio_ctx) avcodec_free_context(&this->audio_ctx); this->audio_st = nullptr; this->audio_ctx = nullptr; if(this->video_ctx) avcodec_free_context(&this->video_ctx); this->video_st = nullptr; this->video_ctx = nullptr; if(this->sws_context) sws_freeContext(this->sws_context); this->sws_context = nullptr; if(this->format_ctx) { /// /// format_ctx->pb->buffer must be freed by hand, /// if not, valgrind will show memleak, see: /// /// https://trac.ffmpeg.org/ticket/1357 /// if (this->format_ctx->pb != nullptr) { av_freep(&this->format_ctx->pb->buffer); #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 80, 100) avio_context_free(&this->format_ctx->pb); #else av_freep(&this->format_ctx->pb); #endif } avformat_close_input(&this->format_ctx); } if (mTexture) { // reset Image separately, it's pointing to *this and there might still be outside references to mTexture mTexture->setImage(nullptr); mTexture = nullptr; } // Deallocate RGBA frame queue. for (auto & i : this->pictq) i.rgbaFrame = nullptr; } double VideoState::get_external_clock() { return mExternalClock.get() / 1000000.0; } double VideoState::get_master_clock() { if(this->av_sync_type == AV_SYNC_VIDEO_MASTER) return this->get_video_clock(); if(this->av_sync_type == AV_SYNC_AUDIO_MASTER) return this->get_audio_clock(); return this->get_external_clock(); } double VideoState::get_video_clock() const { return this->frame_last_pts; } double VideoState::get_audio_clock() { if (!mAudioDecoder) return 0.0; return mAudioDecoder->getAudioClock(); } void VideoState::setPaused(bool isPaused) { this->mPaused = isPaused; mExternalClock.setPaused(isPaused); } void VideoState::seekTo(double time) { time = std::max(0.0, time); time = std::min(getDuration(), time); mSeekPos = (uint64_t) (time * AV_TIME_BASE); mSeekRequested = true; } double VideoState::getDuration() const { return this->format_ctx->duration / 1000000.0; } ExternalClock::ExternalClock() : mTimeBase(av_gettime()) , mPausedAt(0) , mPaused(false) { } void ExternalClock::setPaused(bool paused) { std::lock_guard<std::mutex> lock(mMutex); if (mPaused == paused) return; if (paused) { mPausedAt = av_gettime() - mTimeBase; } else mTimeBase = av_gettime() - mPausedAt; mPaused = paused; } uint64_t ExternalClock::get() { std::lock_guard<std::mutex> lock(mMutex); if (mPaused) return mPausedAt; else return av_gettime() - mTimeBase; } void ExternalClock::set(uint64_t time) { std::lock_guard<std::mutex> lock(mMutex); mTimeBase = av_gettime() - time; mPausedAt = time; } }
27,322
C++
.cpp
808
25.518564
133
0.57609
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,656
videoplayer.cpp
OpenMW_openmw/extern/osg-ffmpeg-videoplayer/videoplayer.cpp
#include "videoplayer.hpp" #include <iostream> #include <osg/Notify> #include <osg/Texture2D> #include "audiofactory.hpp" #include "videostate.hpp" namespace Video { VideoPlayer::VideoPlayer() : mState(nullptr) { } VideoPlayer::~VideoPlayer() { if(mState) close(); } void VideoPlayer::setAudioFactory(MovieAudioFactory *factory) { mAudioFactory.reset(factory); } void VideoPlayer::playVideo(std::unique_ptr<std::istream>&& inputstream, const std::string& name) { if(mState) close(); try { mState = new VideoState; mState->setAudioFactory(mAudioFactory.get()); mState->init(std::move(inputstream), name); // wait until we have the first picture while (mState->video_st && !mState->mTexture.get()) { if (!mState->update()) break; } } catch(std::exception& e) { OSG_FATAL << "Failed to play video: " << e.what() << std::endl; close(); } } bool VideoPlayer::update () { if(mState) return mState->update(); return false; } osg::ref_ptr<osg::Texture2D> VideoPlayer::getVideoTexture() { if (mState) return mState->mTexture; return osg::ref_ptr<osg::Texture2D>(); } int VideoPlayer::getVideoWidth() { int width=0; if (mState && mState->mTexture.get() && mState->mTexture->getImage()) width = mState->mTexture->getImage()->s(); return width; } int VideoPlayer::getVideoHeight() { int height=0; if (mState && mState->mTexture.get() && mState->mTexture->getImage()) height = mState->mTexture->getImage()->t(); return height; } void VideoPlayer::close() { if(mState) { mState->deinit(); delete mState; mState = nullptr; } } bool VideoPlayer::hasAudioStream() { return mState && mState->audio_st != nullptr; } void VideoPlayer::play() { if (mState) mState->setPaused(false); } void VideoPlayer::pause() { if (mState) mState->setPaused(true); } bool VideoPlayer::isPaused() { if (mState) return mState->mPaused; return true; } double VideoPlayer::getCurrentTime() { if (mState) return mState->get_master_clock(); return 0.0; } void VideoPlayer::seek(double time) { if (mState) mState->seekTo(time); } double VideoPlayer::getDuration() { if (mState) return mState->getDuration(); return 0.0; } }
2,450
C++
.cpp
114
17.254386
97
0.640415
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,657
audiodecoder.cpp
OpenMW_openmw/extern/osg-ffmpeg-videoplayer/audiodecoder.cpp
#include "audiodecoder.hpp" #include <extern/osg-ffmpeg-videoplayer/libavutildefines.hpp> #include <algorithm> #include <stdexcept> #include <string> #if defined(_MSC_VER) #pragma warning (push) #pragma warning (disable : 4244) #endif extern "C" { #include <libswresample/swresample.h> } #if defined(_MSC_VER) #pragma warning (pop) #endif #if OPENMW_FFMPEG_5_OR_GREATER #include <libavutil/channel_layout.h> #endif #include "videostate.hpp" namespace { void fail(const std::string &str) { throw std::runtime_error(str); } const double AUDIO_DIFF_AVG_NB = 20; } namespace Video { // Moved to implementation file, so that HAVE_SWRESAMPLE is used at library compile time only struct AudioResampler { AudioResampler() : mSwr(nullptr) { } ~AudioResampler() { swr_free(&mSwr); } SwrContext* mSwr; }; MovieAudioDecoder::MovieAudioDecoder(VideoState* videoState) : mVideoState(videoState) , mAVStream(*videoState->audio_st) , mOutputSampleFormat(AV_SAMPLE_FMT_NONE) #if OPENMW_FFMPEG_5_OR_GREATER , mOutputChannelLayout({}) #else , mOutputChannelLayout(0) #endif , mOutputSampleRate(0) , mFramePos(0) , mFrameSize(0) , mAudioClock(0.0) , mDataBuf(nullptr) , mFrameData(nullptr) , mDataBufLen(0) , mFrame(av_frame_alloc()) , mGetNextPacket(true) , mAudioDiffAccum(0.0) , mAudioDiffAvgCoef(exp(log(0.01 / AUDIO_DIFF_AVG_NB))) /* Correct audio only if larger error than this */ , mAudioDiffThreshold(2.0 * 0.050/* 50 ms */) , mAudioDiffAvgCount(0) { mAudioResampler.reset(new AudioResampler()); const AVCodec *codec = avcodec_find_decoder(mAVStream->codecpar->codec_id); if(!codec) { std::string ss = "No codec found for id " + std::to_string(mAVStream->codecpar->codec_id); throw std::runtime_error(ss); } AVCodecContext *avctx = avcodec_alloc_context3(codec); avcodec_parameters_to_context(avctx, mAVStream->codecpar); // This is not needed anymore above FFMpeg version 4.0 #if LIBAVCODEC_VERSION_INT < 3805796 av_codec_set_pkt_timebase(avctx, mAVStream->time_base); #endif mAudioContext = avctx; if(avcodec_open2(mAudioContext, codec, nullptr) < 0) throw std::runtime_error(std::string("Failed to open audio codec ") + codec->long_name); } MovieAudioDecoder::~MovieAudioDecoder() { if(mAudioContext) avcodec_free_context(&mAudioContext); av_frame_free(&mFrame); av_freep(&mDataBuf); } void MovieAudioDecoder::setupFormat() { if (mAudioResampler->mSwr) return; // already set up AVSampleFormat inputSampleFormat = mAudioContext->sample_fmt; #if OPENMW_FFMPEG_5_OR_GREATER AVChannelLayout inputChannelLayout = mAudioContext->ch_layout; if (inputChannelLayout.u.mask != 0) mOutputChannelLayout = inputChannelLayout; else av_channel_layout_default(&mOutputChannelLayout, mAudioContext->ch_layout.nb_channels); #else uint64_t inputChannelLayout = mAudioContext->channel_layout; if (inputChannelLayout == 0) inputChannelLayout = av_get_default_channel_layout(mAudioContext->channels); #endif int inputSampleRate = mAudioContext->sample_rate; mOutputSampleRate = inputSampleRate; mOutputSampleFormat = inputSampleFormat; #if OPENMW_FFMPEG_5_OR_GREATER adjustAudioSettings(mOutputSampleFormat, mOutputChannelLayout.u.mask, mOutputSampleRate); #else mOutputChannelLayout = inputChannelLayout; adjustAudioSettings(mOutputSampleFormat, mOutputChannelLayout, mOutputSampleRate); #endif if (inputSampleFormat != mOutputSampleFormat #if OPENMW_FFMPEG_5_OR_GREATER || inputChannelLayout.u.mask != mOutputChannelLayout.u.mask #else || inputChannelLayout != mOutputChannelLayout #endif || inputSampleRate != mOutputSampleRate) { #if OPENMW_FFMPEG_5_OR_GREATER swr_alloc_set_opts2(&mAudioResampler->mSwr, &mOutputChannelLayout, mOutputSampleFormat, mOutputSampleRate, &inputChannelLayout, inputSampleFormat, inputSampleRate, 0, // logging level offset nullptr); // log context #else mAudioResampler->mSwr = swr_alloc_set_opts(mAudioResampler->mSwr, mOutputChannelLayout, mOutputSampleFormat, mOutputSampleRate, inputChannelLayout, inputSampleFormat, inputSampleRate, 0, // logging level offset nullptr); // log context #endif if(!mAudioResampler->mSwr) fail(std::string("Couldn't allocate SwrContext")); if(swr_init(mAudioResampler->mSwr) < 0) fail(std::string("Couldn't initialize SwrContext")); } } int MovieAudioDecoder::synchronize_audio() { if(mVideoState->av_sync_type == AV_SYNC_AUDIO_MASTER) return 0; int sample_skip = 0; // accumulate the clock difference double diff = mVideoState->get_master_clock() - mVideoState->get_audio_clock(); mAudioDiffAccum = diff + mAudioDiffAvgCoef * mAudioDiffAccum; if(mAudioDiffAvgCount < AUDIO_DIFF_AVG_NB) mAudioDiffAvgCount++; else { double avg_diff = mAudioDiffAccum * (1.0 - mAudioDiffAvgCoef); if(fabs(avg_diff) >= mAudioDiffThreshold) { int n = av_get_bytes_per_sample(mOutputSampleFormat) * #if OPENMW_FFMPEG_5_OR_GREATER mOutputChannelLayout.nb_channels; #else av_get_channel_layout_nb_channels(mOutputChannelLayout); #endif sample_skip = ((int)(diff * mAudioContext->sample_rate) * n); } } return sample_skip; } int MovieAudioDecoder::audio_decode_frame(AVFrame *frame, int &sample_skip) { AVPacket *pkt = &mPacket; for(;;) { /* send the packet with the compressed data to the decoder */ int ret = 0; if (mGetNextPacket) ret = avcodec_send_packet(mAudioContext, pkt); /* read all the output frames (in general there may be any number of them */ while (ret >= 0) { ret = avcodec_receive_frame(mAudioContext, frame); if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) { // EAGAIN means that we need additional packages to decode this frame. // AVERROR_EOF means the end of package. mGetNextPacket = true; break; } else if (ret < 0) { // Error encountered. Stop to decode audio stream. av_packet_unref(&mPacket); mGetNextPacket = true; return -1; } if(frame->nb_samples <= 0) continue; if(mAudioResampler->mSwr) { if(!mDataBuf || mDataBufLen < frame->nb_samples) { av_freep(&mDataBuf); #if OPENMW_FFMPEG_5_OR_GREATER if(av_samples_alloc(&mDataBuf, nullptr, mOutputChannelLayout.nb_channels, #else if(av_samples_alloc(&mDataBuf, nullptr, av_get_channel_layout_nb_channels(mOutputChannelLayout), #endif frame->nb_samples, mOutputSampleFormat, 0) < 0) break; else mDataBufLen = frame->nb_samples; } if(swr_convert(mAudioResampler->mSwr, (uint8_t**)&mDataBuf, frame->nb_samples, (const uint8_t**)frame->extended_data, frame->nb_samples) < 0) { break; } mFrameData = &mDataBuf; } else mFrameData = &frame->data[0]; #if OPENMW_FFMPEG_5_OR_GREATER int result = frame->nb_samples * mOutputChannelLayout.nb_channels * #else int result = frame->nb_samples * av_get_channel_layout_nb_channels(mOutputChannelLayout) * #endif av_get_bytes_per_sample(mOutputSampleFormat); /* We have data, return it and come back for more later */ mGetNextPacket = false; return result; } av_packet_unref(pkt); mGetNextPacket = true; /* next packet */ if(mVideoState->audioq.get(pkt, mVideoState) < 0) return -1; if(pkt->data == mVideoState->mFlushPktData) { avcodec_flush_buffers(mAudioContext); mAudioDiffAccum = 0.0; mAudioDiffAvgCount = 0; mAudioClock = av_q2d(mAVStream->time_base)*pkt->pts; sample_skip = 0; if(mVideoState->audioq.get(pkt, mVideoState) < 0) return -1; } /* if update, update the audio clock w/pts */ if(pkt->pts != AV_NOPTS_VALUE) mAudioClock = av_q2d(mAVStream->time_base)*pkt->pts; } } size_t MovieAudioDecoder::read(char *stream, size_t len) { if (mVideoState->mPaused) { // fill the buffer with silence size_t sampleSize = av_get_bytes_per_sample(mOutputSampleFormat); char* data[1]; data[0] = stream; av_samples_set_silence((uint8_t**)data, 0, static_cast<int>(len/sampleSize), 1, mOutputSampleFormat); return len; } int sample_skip = synchronize_audio(); size_t total = 0; while(total < len) { if(mFramePos >= mFrameSize) { /* We have already sent all our data; get more */ mFrameSize = audio_decode_frame(mFrame, sample_skip); if(mFrameSize < 0) { /* If error, we're done */ break; } mFramePos = std::min<ssize_t>(mFrameSize, sample_skip); if(sample_skip > 0 || mFrameSize > -sample_skip) sample_skip -= static_cast<int>(mFramePos); continue; } size_t len1 = len - total; if(mFramePos >= 0) { len1 = std::min<size_t>(len1, mFrameSize-mFramePos); memcpy(stream, mFrameData[0]+mFramePos, len1); } else { len1 = std::min<size_t>(len1, -mFramePos); int n = av_get_bytes_per_sample(mOutputSampleFormat) #if OPENMW_FFMPEG_5_OR_GREATER * mOutputChannelLayout.nb_channels; #else * av_get_channel_layout_nb_channels(mOutputChannelLayout); #endif /* add samples by copying the first sample*/ if(n == 1) memset(stream, *mFrameData[0], len1); else if(n == 2) { const int16_t val = *((int16_t*)mFrameData[0]); for(size_t nb = 0;nb < len1;nb += n) *((int16_t*)(stream+nb)) = val; } else if(n == 4) { const int32_t val = *((int32_t*)mFrameData[0]); for(size_t nb = 0;nb < len1;nb += n) *((int32_t*)(stream+nb)) = val; } else if(n == 8) { const int64_t val = *((int64_t*)mFrameData[0]); for(size_t nb = 0;nb < len1;nb += n) *((int64_t*)(stream+nb)) = val; } else { for(size_t nb = 0;nb < len1;nb += n) memcpy(stream+nb, mFrameData[0], n); } } total += len1; stream += len1; mFramePos += len1; } return total; } double MovieAudioDecoder::getAudioClock() { return mAudioClock; } int MovieAudioDecoder::getOutputSampleRate() const { return mOutputSampleRate; } uint64_t MovieAudioDecoder::getOutputChannelLayout() const { #if OPENMW_FFMPEG_5_OR_GREATER return mOutputChannelLayout.u.mask; #else return mOutputChannelLayout; #endif } AVSampleFormat MovieAudioDecoder::getOutputSampleFormat() const { return mOutputSampleFormat; } }
12,405
C++
.cpp
359
25.554318
116
0.587602
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,659
types.hpp
OpenMW_openmw/components/stereo/types.hpp
#ifndef STEREO_TYPES_H #define STEREO_TYPES_H #include <osg/Matrix> #include <osg/Vec3> namespace Stereo { enum class Eye { Left = 0, Right = 1, Center = 2 }; struct Pose { //! Position in space osg::Vec3 position{ 0, 0, 0 }; //! Orientation in space. osg::Quat orientation{ 0, 0, 0, 1 }; //! Add one pose to another Pose operator+(const Pose& rhs); const Pose& operator+=(const Pose& rhs); //! Scale a pose (does not affect orientation) Pose operator*(float scalar); const Pose& operator*=(float scalar); Pose operator/(float scalar); const Pose& operator/=(float scalar); bool operator==(const Pose& rhs) const; }; struct FieldOfView { float angleLeft{ 0.f }; float angleRight{ 0.f }; float angleUp{ 0.f }; float angleDown{ 0.f }; bool operator==(const FieldOfView& rhs) const; }; struct View { Pose pose; FieldOfView fov; bool operator==(const View& rhs) const; osg::Matrix viewMatrix(bool useGLConventions); osg::Matrix perspectiveMatrix(float near, float far, bool reverseZ); }; std::ostream& operator<<(std::ostream& os, const Pose& pose); std::ostream& operator<<(std::ostream& os, const FieldOfView& fov); std::ostream& operator<<(std::ostream& os, const View& view); } #endif
1,465
C++
.h
49
23.183673
76
0.599715
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,660
stereomanager.hpp
OpenMW_openmw/components/stereo/stereomanager.hpp
#ifndef STEREO_MANAGER_H #define STEREO_MANAGER_H #include <osg/Camera> #include <osg/Matrix> #include <osg/StateSet> #include <osg/Vec3> #include <osgUtil/CullVisitor> #include <array> #include <memory> #include <components/shader/shadermanager.hpp> #include "types.hpp" namespace osg { class FrameBufferObject; class Texture2D; class Texture2DArray; } namespace osgViewer { class Viewer; } namespace SceneUtil { class MWShadowTechnique; } namespace Stereo { class MultiviewFramebuffer; class StereoFrustumManager; class MultiviewStereoStatesetUpdateCallback; bool getStereo(); //! Sets up any definitions necessary for stereo rendering void shaderStereoDefines(Shader::ShaderManager::DefineMap& defines); //! Class that provides tools for managing stereo mode class Manager { public: struct UpdateViewCallback { virtual ~UpdateViewCallback() = default; //! Called during the update traversal of every frame to update stereo views. virtual void updateView(View& left, View& right) = 0; }; //! An UpdateViewCallback that supplies a fixed, custom view. Useful for debugging purposes, //! such as emulating a given HMD's view. struct CustomViewCallback : public UpdateViewCallback { public: CustomViewCallback(View& left, View& right); void updateView(View& left, View& right) override; private: View mLeft; View mRight; }; //! Gets the singleton instance static Manager& instance(); //! Constructor //! //! @Param viewer the osg viewer whose stereo should be managed. //! @Param enableStereo whether or not stereo should be enabled. //! @Param enableMultiview whether or not to make use of the GL_OVR_Multiview extension, if supported. //! @Param near defines distance to near camera clipping plane from view point. //! @Param far defines distance to far camera clipping plane from view point. explicit Manager(osgViewer::Viewer* viewer, bool enableStereo, double near, double far); ~Manager(); //! Called during update traversal void update(); void updateSettings(double near, double far) { mNear = near; mFar = far; } //! Initializes all details of stereo if applicable. If the constructor was called with enableMultiview=true, //! and the GL_OVR_Multiview extension is supported, Stereo::getMultiview() will return true after this call. void initializeStereo(osg::GraphicsContext* gc, bool enableMultiview, bool sharedShadowMaps); //! Callback that updates stereo configuration during the update pass void setUpdateViewCallback(std::shared_ptr<UpdateViewCallback> cb); //! Set the cull callback on the appropriate camera object void setCullCallback(osg::ref_ptr<osg::NodeCallback> cb); osg::Matrixd computeEyeProjection(int view, bool reverseZ) const; osg::Matrixd computeEyeViewOffset(int view) const; const std::shared_ptr<MultiviewFramebuffer>& multiviewFramebuffer() { return mMultiviewFramebuffer; } //! Sets rendering resolution of each eye to eyeResolution. //! Once set, there will no longer be any connection between rendering resolution and screen/window resolution. void overrideEyeResolution(const osg::Vec2i& eyeResolution); //! Notify stereo manager that the screen/window resolution has changed. void screenResolutionChanged(); //! Get current eye resolution osg::Vec2i eyeResolution(); //! The projection intended for rendering. When reverse Z is enabled, this is not the same as the camera's //! projection matrix, and therefore must be provided to the manager explicitly. void setMasterProjectionMatrix(const osg::Matrixd& projectionMatrix) { mMasterProjectionMatrix = projectionMatrix; } //! Causes the subgraph represented by the node to draw to the full viewport. //! This has no effect if stereo is not enabled void disableStereoForNode(osg::Node* node); void setShadowTechnique(SceneUtil::MWShadowTechnique* shadowTechnique); /// Determine which view the cull visitor belongs to Eye getEye(const osgUtil::CullVisitor* cv) const; private: friend class MultiviewStereoStatesetUpdateCallback; void updateMultiviewStateset(osg::StateSet* stateset); void updateStereoFramebuffer(); void setupBruteForceTechnique(); void setupOVRMultiView2Technique(); osg::ref_ptr<osgViewer::Viewer> mViewer; osg::ref_ptr<osg::Camera> mMainCamera; osg::ref_ptr<osg::Callback> mUpdateCallback; std::string mError; osg::Matrixd mMasterProjectionMatrix; std::shared_ptr<MultiviewFramebuffer> mMultiviewFramebuffer; bool mEyeResolutionOverriden; osg::Vec2i mEyeResolutionOverride; double mNear; double mFar; std::array<View, 2> mView; std::array<osg::Matrixd, 2> mViewOffsetMatrix; std::array<osg::Matrixd, 2> mProjectionMatrix; std::array<osg::Matrixd, 2> mProjectionMatrixReverseZ; std::unique_ptr<StereoFrustumManager> mFrustumManager; std::shared_ptr<UpdateViewCallback> mUpdateViewCallback; using Identifier = osgUtil::CullVisitor::Identifier; osg::ref_ptr<Identifier> mIdentifierMain = new Identifier(); osg::ref_ptr<Identifier> mIdentifierLeft = new Identifier(); osg::ref_ptr<Identifier> mIdentifierRight = new Identifier(); }; struct CustomView { Stereo::View mLeft; Stereo::View mRight; }; struct Settings { bool mMultiview; bool mAllowDisplayListsForMultiview; bool mSharedShadowMaps; std::optional<CustomView> mCustomView; std::optional<osg::Vec2i> mEyeResolution; }; //! Performs stereo-specific initialization operations. class InitializeStereoOperation final : public osg::GraphicsOperation { public: explicit InitializeStereoOperation(const Settings& settings); void operator()(osg::GraphicsContext* graphicsContext) override; private: bool mMultiview; bool mSharedShadowMaps; std::optional<CustomView> mCustomView; std::optional<osg::Vec2i> mEyeResolution; }; } #endif
6,599
C++
.h
155
35.032258
119
0.694158
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,661
frustum.hpp
OpenMW_openmw/components/stereo/frustum.hpp
#ifndef STEREO_FRUSTUM_H #define STEREO_FRUSTUM_H #include <osg/BoundingBox> #include <osg/Camera> #include <osg/Matrix> #include <osg/StateSet> #include <osg/Vec3> #include <array> #include <map> #include <memory> namespace osg { class FrameBufferObject; class Texture2D; class Texture2DMultisample; class Texture2DArray; } namespace osgViewer { class Viewer; } namespace usgUtil { class CullVisitor; } namespace SceneUtil { class MWShadowTechnique; } namespace Stereo { struct MultiviewFrustumCallback; struct ShadowFrustumCallback; void joinBoundingBoxes( const osg::Matrix& masterProjection, const osg::Matrix& slaveProjection, osg::BoundingBoxd& bb); class StereoFrustumManager { public: StereoFrustumManager(bool sharedShadowMaps, osg::Camera* camera); ~StereoFrustumManager(); void update(std::array<osg::Matrix, 2> projections); const osg::BoundingBoxd& boundingBox() const { return mBoundingBox; } void setShadowTechnique(SceneUtil::MWShadowTechnique* shadowTechnique); void customFrustumCallback( osgUtil::CullVisitor& cv, osg::BoundingBoxd& customClipSpace, osgUtil::CullVisitor*& sharedFrustumHint); private: osg::ref_ptr<osg::Camera> mCamera; osg::ref_ptr<SceneUtil::MWShadowTechnique> mShadowTechnique; osg::ref_ptr<ShadowFrustumCallback> mShadowFrustumCallback; std::map<osgUtil::CullVisitor*, osgUtil::CullVisitor*> mSharedFrustums; osg::BoundingBoxd mBoundingBox; std::unique_ptr<MultiviewFrustumCallback> mMultiviewFrustumCallback; }; } #endif
1,654
C++
.h
55
25.581818
116
0.744788
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,662
multiview.hpp
OpenMW_openmw/components/stereo/multiview.hpp
#ifndef STEREO_MULTIVIEW_H #define STEREO_MULTIVIEW_H #include <osg/Camera> #include <osg/FrameBufferObject> #include <osg/GL> #include <osg/ref_ptr> #include <array> #include <memory> namespace osg { class FrameBufferObject; class Texture; class Texture2D; class Texture2DArray; } namespace osgUtil { class RenderStage; } namespace Stereo { class UpdateRenderStagesCallback; //! Check if TextureView is supported. Results are undefined if called before configureExtensions(). bool getTextureViewSupported(); //! Check if Multiview should be used. Results are undefined if called before configureExtensions(). bool getMultiview(); //! Use the provided context to check what extensions are supported and configure use of multiview based on //! extensions and settings. void configureExtensions(unsigned int contextID, bool enableMultiview); //! Sets the appropriate vertex buffer hint on OSG's display settings if needed void setVertexBufferHint(bool enableMultiview, bool allowDisplayListsForMultiview); //! Creates a Texture2D as a texture view into a Texture2DArray osg::ref_ptr<osg::Texture2D> createTextureView_Texture2DFromTexture2DArray( osg::Texture2DArray* textureArray, int layer); //! Class that manages the specifics of GL_OVR_Multiview aware framebuffers, separating the layers into separate //! framebuffers, and disabling class MultiviewFramebuffer { public: MultiviewFramebuffer(int width, int height, int samples); ~MultiviewFramebuffer(); void attachColorComponent(GLint sourceFormat, GLint sourceType, GLint internalFormat); void attachDepthComponent(GLint sourceFormat, GLint sourceType, GLint internalFormat); osg::FrameBufferObject* multiviewFbo(); osg::FrameBufferObject* layerFbo(int i); osg::FrameBufferObject* layerMsaaFbo(int i); osg::Texture2DArray* multiviewColorBuffer(); osg::Texture2DArray* multiviewDepthBuffer(); osg::Texture2D* layerColorBuffer(int i); osg::Texture2D* layerDepthBuffer(int i); void attachTo(osg::Camera* camera); void detachFrom(osg::Camera* camera); int width() const { return mWidth; } int height() const { return mHeight; } int samples() const { return mSamples; } private: osg::Texture2D* createTexture(GLint sourceFormat, GLint sourceType, GLint internalFormat); osg::Texture2DArray* createTextureArray(GLint sourceFormat, GLint sourceType, GLint internalFormat); int mWidth; int mHeight; int mSamples; bool mMultiview; osg::ref_ptr<UpdateRenderStagesCallback> mCullCallback; osg::ref_ptr<osg::FrameBufferObject> mMultiviewFbo; std::array<osg::ref_ptr<osg::FrameBufferObject>, 2> mLayerFbo; std::array<osg::ref_ptr<osg::FrameBufferObject>, 2> mLayerMsaaFbo; osg::ref_ptr<osg::Texture2DArray> mMultiviewColorTexture; osg::ref_ptr<osg::Texture2DArray> mMultiviewDepthTexture; std::array<osg::ref_ptr<osg::Texture2D>, 2> mColorTexture; std::array<osg::ref_ptr<osg::Texture2D>, 2> mDepthTexture; }; //! Sets up a draw callback on the render stage that performs the MSAA resolve operation void setMultiviewMSAAResolveCallback(osgUtil::RenderStage* renderStage); //! Sets up or updates multiview matrices for the given stateset void setMultiviewMatrices( osg::StateSet* stateset, const std::array<osg::Matrix, 2>& projection, bool createInverseMatrices = false); //! Sets the width/height of a texture by first down-casting it to the appropriate type. Sets depth to 2 always for //! Texture2DArray and Texture2DMultisampleArray. void setMultiviewCompatibleTextureSize(osg::Texture* tex, int w, int h); //! Creates a texture (Texture2D, Texture2DMultisample, Texture2DArray, or Texture2DMultisampleArray) based on //! multiview settings and sample count. osg::ref_ptr<osg::Texture> createMultiviewCompatibleTexture(int width, int height, int samples); //! Returns a framebuffer attachment from the texture, returning a multiview attachment if the texture is one of //! Texture2DArray or Texture2DMultisampleArray osg::FrameBufferAttachment createMultiviewCompatibleAttachment(osg::Texture* tex); //! If OSG has multiview, returns the magic number used to tell OSG to create a multiview attachment. Otherwise //! returns 0. unsigned int osgFaceControlledByMultiviewShader(); //! Implements resolving a multisamples multiview framebuffer. Does not automatically reflect changes to the fbo //! attachments, must call dirty() when the fbo attachments change. class MultiviewFramebufferResolve { public: MultiviewFramebufferResolve( osg::FrameBufferObject* msaaFbo, osg::FrameBufferObject* resolveFbo, GLbitfield blitMask); void resolveImplementation(osg::State& state); void dirty() { mDirtyLayers = true; } const osg::FrameBufferObject* resolveFbo() const { return mResolveFbo; } const osg::FrameBufferObject* msaaFbo() const { return mMsaaFbo; } void setResolveFbo(osg::FrameBufferObject* resolveFbo); void setMsaaFbo(osg::FrameBufferObject* msaaFbo); private: void setupLayers(); osg::ref_ptr<osg::FrameBufferObject> mResolveFbo; std::array<osg::ref_ptr<osg::FrameBufferObject>, 2> mResolveLayers{}; osg::ref_ptr<osg::FrameBufferObject> mMsaaFbo; std::array<osg::ref_ptr<osg::FrameBufferObject>, 2> mMsaaLayers{}; GLbitfield mBlitMask; bool mDirtyLayers = true; int mWidth = -1; int mHeight = -1; }; //! Wrapper for osg::CullSettings::InitialFrustumCallback, to avoid exposing osg multiview interfaces outside of //! multiview.cpp struct InitialFrustumCallback { InitialFrustumCallback(osg::Camera* camera); virtual ~InitialFrustumCallback(); virtual void setInitialFrustum( osg::CullStack& cullStack, osg::BoundingBoxd& bb, bool& nearCulling, bool& farCulling) const = 0; osg::observer_ptr<osg::Camera> mCamera; }; } #endif
6,256
C++
.h
124
43.943548
119
0.729539
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,663
flags.hpp
OpenMW_openmw/components/detournavigator/flags.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_FLAGS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_FLAGS_H namespace DetourNavigator { using Flags = unsigned short; enum Flag : Flags { Flag_none = 0, Flag_walk = 1 << 0, Flag_swim = 1 << 1, Flag_openDoor = 1 << 2, Flag_usePathgrid = 1 << 3, }; } #endif
355
C++
.h
15
18.733333
49
0.626113
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,664
changetype.hpp
OpenMW_openmw/components/detournavigator/changetype.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_CHANGETYPE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_CHANGETYPE_H namespace DetourNavigator { enum class ChangeType { remove = 0, add = 1, update = 2, }; } #endif
245
C++
.h
12
16.25
54
0.701299
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,665
updateguard.hpp
OpenMW_openmw/components/detournavigator/updateguard.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_UPDATEGUARD_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_UPDATEGUARD_H #include <memory> #include <mutex> namespace DetourNavigator { class UpdateGuard { public: explicit UpdateGuard(std::mutex& mutex) : mMutex(mutex) { } private: std::mutex& mMutex; friend struct UnlockUpdateGuard; }; struct UnlockUpdateGuard { void operator()(UpdateGuard* value) const { value->mMutex.unlock(); } }; using ScopedUpdateGuard = std::unique_ptr<UpdateGuard, UnlockUpdateGuard>; } #endif
615
C++
.h
24
20.333333
78
0.688356
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,666
objecttransform.hpp
OpenMW_openmw/components/detournavigator/objecttransform.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_OBJECTTRANSFORM_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_OBJECTTRANSFORM_H #include <components/esm/position.hpp> #include <tuple> namespace DetourNavigator { struct ObjectTransform { ESM::Position mPosition; float mScale; friend inline auto tie(const ObjectTransform& v) { return std::tie(v.mPosition, v.mScale); } friend inline bool operator<(const ObjectTransform& l, const ObjectTransform& r) { return tie(l) < tie(r); } }; } #endif
532
C++
.h
15
31.133333
116
0.741683
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,667
version.hpp
OpenMW_openmw/components/detournavigator/version.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_VERSION_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_VERSION_H #include <cstddef> #include <tuple> namespace DetourNavigator { struct Version { std::size_t mGeneration = 0; std::size_t mRevision = 0; friend inline auto tie(const Version& value) { return std::tie(value.mGeneration, value.mRevision); } friend inline bool operator<(const Version& lhs, const Version& rhs) { return tie(lhs) < tie(rhs); } friend inline bool operator<=(const Version& lhs, const Version& rhs) { return tie(lhs) <= tie(rhs); } friend inline bool operator==(const Version& lhs, const Version& rhs) { return tie(lhs) == tie(rhs); } friend inline bool operator!=(const Version& lhs, const Version& rhs) { return !(lhs == rhs); } }; } #endif
834
C++
.h
18
41.111111
110
0.688119
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,668
objectid.hpp
OpenMW_openmw/components/detournavigator/objectid.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_OBJECTID_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_OBJECTID_H #include <cstddef> #include <functional> namespace DetourNavigator { class ObjectId { public: template <class T> explicit ObjectId(T* value) noexcept : mValue(reinterpret_cast<std::size_t>(value)) { } explicit ObjectId(std::size_t value) noexcept : mValue(value) { } std::size_t value() const noexcept { return mValue; } friend bool operator<(const ObjectId lhs, const ObjectId rhs) noexcept { return lhs.mValue < rhs.mValue; } friend bool operator==(const ObjectId lhs, const ObjectId rhs) noexcept { return lhs.mValue == rhs.mValue; } private: std::size_t mValue; }; } namespace std { template <> struct hash<DetourNavigator::ObjectId> { std::size_t operator()(const DetourNavigator::ObjectId value) const noexcept { return value.value(); } }; } #endif
1,026
C++
.h
34
24.323529
116
0.662258
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,669
exceptions.hpp
OpenMW_openmw/components/detournavigator/exceptions.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_EXCEPTIONS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_EXCEPTIONS_H #include <stdexcept> namespace DetourNavigator { struct NavigatorException : std::runtime_error { NavigatorException(const std::string& message) : std::runtime_error(message) { } NavigatorException(const char* message) : std::runtime_error(message) { } }; struct InvalidArgument : std::invalid_argument { InvalidArgument(const std::string& message) : std::invalid_argument(message) { } InvalidArgument(const char* message) : std::invalid_argument(message) { } }; } #endif
754
C++
.h
29
19.068966
54
0.628294
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,670
recastmeshbuilder.hpp
OpenMW_openmw/components/detournavigator/recastmeshbuilder.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHBUILDER_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHBUILDER_H #include "recastmesh.hpp" #include "tilebounds.hpp" #include <components/resource/bulletshape.hpp> #include <osg/Vec3f> #include <LinearMath/btTransform.h> #include <array> #include <memory> #include <tuple> #include <vector> class btBoxShape; class btCollisionShape; class btCompoundShape; class btConcaveShape; class btHeightfieldTerrainShape; class btTriangleCallback; namespace DetourNavigator { struct RecastMeshTriangle { AreaType mAreaType; std::array<osg::Vec3f, 3> mVertices; friend inline bool operator<(const RecastMeshTriangle& lhs, const RecastMeshTriangle& rhs) { return std::tie(lhs.mAreaType, lhs.mVertices) < std::tie(rhs.mAreaType, rhs.mVertices); } }; class RecastMeshBuilder { public: explicit RecastMeshBuilder(const TileBounds& bounds) noexcept; void addObject(const btCollisionShape& shape, const btTransform& transform, const AreaType areaType, osg::ref_ptr<const Resource::BulletShape> source, const ObjectTransform& objectTransform); void addObject(const btCompoundShape& shape, const btTransform& transform, const AreaType areaType); void addObject(const btConcaveShape& shape, const btTransform& transform, const AreaType areaType); void addObject(const btHeightfieldTerrainShape& shape, const btTransform& transform, const AreaType areaType); void addObject(const btBoxShape& shape, const btTransform& transform, const AreaType areaType); void addWater(const osg::Vec2i& cellPosition, const Water& water); void addHeightfield(const osg::Vec2i& cellPosition, int cellSize, float height); void addHeightfield(const osg::Vec2i& cellPosition, int cellSize, const float* heights, std::size_t size, float minHeight, float maxHeight); std::shared_ptr<RecastMesh> create(const Version& version) &&; private: const TileBounds mBounds; std::vector<RecastMeshTriangle> mTriangles; std::vector<CellWater> mWater; std::vector<Heightfield> mHeightfields; std::vector<FlatHeightfield> mFlatHeightfields; std::vector<MeshSource> mSources; inline void addObject(const btCollisionShape& shape, const btTransform& transform, const AreaType areaType); void addObject(const btConcaveShape& shape, const btTransform& transform, btTriangleCallback&& callback); void addObject( const btHeightfieldTerrainShape& shape, const btTransform& transform, btTriangleCallback&& callback); }; Mesh makeMesh(std::vector<RecastMeshTriangle>&& triangles, const osg::Vec3f& shift = osg::Vec3f()); Mesh makeMesh(const Heightfield& heightfield); } #endif
2,873
C++
.h
59
42.525424
118
0.748297
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,671
recastmeshprovider.hpp
OpenMW_openmw/components/detournavigator/recastmeshprovider.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHPROVIDER_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHPROVIDER_H #include "recastmesh.hpp" #include "tilecachedrecastmeshmanager.hpp" #include "tileposition.hpp" #include <functional> #include <memory> namespace DetourNavigator { class RecastMesh; class RecastMeshProvider { public: RecastMeshProvider(TileCachedRecastMeshManager& impl) : mImpl(impl) { } std::shared_ptr<RecastMesh> getMesh(ESM::RefId worldspace, const TilePosition& tilePosition) const { return mImpl.get().getNewMesh(worldspace, tilePosition); } private: std::reference_wrapper<TileCachedRecastMeshManager> mImpl; }; } #endif
767
C++
.h
26
24.230769
106
0.731608
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,672
recast.hpp
OpenMW_openmw/components/detournavigator/recast.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECAST_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECAST_H #include <Recast.h> #include <cstddef> #include <type_traits> namespace DetourNavigator { constexpr std::size_t getVertsLength(const rcPolyMesh& value) noexcept { return 3 * static_cast<std::size_t>(value.nverts); } constexpr std::size_t getPolysLength(const rcPolyMesh& value) noexcept { return 2 * static_cast<std::size_t>(value.maxpolys * value.nvp); } constexpr std::size_t getRegsLength(const rcPolyMesh& value) noexcept { return static_cast<std::size_t>(value.maxpolys); } constexpr std::size_t getFlagsLength(const rcPolyMesh& value) noexcept { return static_cast<std::size_t>(value.npolys); } constexpr std::size_t getAreasLength(const rcPolyMesh& value) noexcept { return static_cast<std::size_t>(value.maxpolys); } constexpr std::size_t getMeshesLength(const rcPolyMeshDetail& value) noexcept { return 4 * static_cast<std::size_t>(value.nmeshes); } constexpr std::size_t getVertsLength(const rcPolyMeshDetail& value) noexcept { return 3 * static_cast<std::size_t>(value.nverts); } constexpr std::size_t getTrisLength(const rcPolyMeshDetail& value) noexcept { return 4 * static_cast<std::size_t>(value.ntris); } void* permRecastAlloc(std::size_t size); template <class T> inline void permRecastAlloc(T*& values, std::size_t size) { static_assert(std::is_arithmetic_v<T>); values = new (permRecastAlloc(size * sizeof(T))) T[size]; } void permRecastAlloc(rcPolyMesh& value); void permRecastAlloc(rcPolyMeshDetail& value); void freePolyMeshDetail(rcPolyMeshDetail& value) noexcept; void copyPolyMesh(const rcPolyMesh& src, rcPolyMesh& dst); void copyPolyMeshDetail(const rcPolyMeshDetail& src, rcPolyMeshDetail& dst); } #endif
1,969
C++
.h
53
31.735849
81
0.708641
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,673
settingsutils.hpp
OpenMW_openmw/components/detournavigator/settingsutils.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_SETTINGSUTILS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_SETTINGSUTILS_H #include "settings.hpp" #include "tilebounds.hpp" #include "tileposition.hpp" #include <osg/Vec2f> #include <osg/Vec3f> #include <algorithm> #include <cmath> namespace DetourNavigator { inline float toNavMeshCoordinates(const RecastSettings& settings, float value) { return value * settings.mRecastScaleFactor; } inline osg::Vec2f toNavMeshCoordinates(const RecastSettings& settings, osg::Vec2f position) { return position * settings.mRecastScaleFactor; } inline osg::Vec3f toNavMeshCoordinates(const RecastSettings& settings, osg::Vec3f position) { std::swap(position.y(), position.z()); return position * settings.mRecastScaleFactor; } inline TileBounds toNavMeshCoordinates(const RecastSettings& settings, const TileBounds& value) { return TileBounds{ toNavMeshCoordinates(settings, value.mMin), toNavMeshCoordinates(settings, value.mMax) }; } inline float fromNavMeshCoordinates(const RecastSettings& settings, float value) { return value / settings.mRecastScaleFactor; } inline osg::Vec3f fromNavMeshCoordinates(const RecastSettings& settings, osg::Vec3f position) { const auto factor = 1.0f / settings.mRecastScaleFactor; position *= factor; std::swap(position.y(), position.z()); return position; } // Returns value in NavMesh coordinates inline float getTileSize(const RecastSettings& settings) { return static_cast<float>(settings.mTileSize) * settings.mCellSize; } inline int getTilePosition(const RecastSettings& settings, float position) { const float v = std::floor(position / getTileSize(settings)); if (v < static_cast<float>(std::numeric_limits<int>::min())) return std::numeric_limits<int>::min(); if (v > static_cast<float>(std::numeric_limits<int>::max() - 1)) return std::numeric_limits<int>::max() - 1; return static_cast<int>(v); } // Returns integer tile position for position in navmesh coordinates inline TilePosition getTilePosition(const RecastSettings& settings, const osg::Vec2f& position) { return TilePosition(getTilePosition(settings, position.x()), getTilePosition(settings, position.y())); } // Returns integer tile position for position in navmesh coordinates inline TilePosition getTilePosition(const RecastSettings& settings, const osg::Vec3f& position) { return getTilePosition(settings, osg::Vec2f(position.x(), position.z())); } // Returns tile bounds in navmesh coordinates inline TileBounds makeTileBounds(const RecastSettings& settings, const TilePosition& tilePosition) { return TileBounds{ osg::Vec2f(tilePosition.x(), tilePosition.y()) * getTileSize(settings), osg::Vec2f(tilePosition.x() + 1, tilePosition.y() + 1) * getTileSize(settings), }; } // Returns border size relative to cell size inline float getBorderSize(const RecastSettings& settings) { return static_cast<float>(settings.mBorderSize) * settings.mCellSize; } inline float getRealTileSize(const RecastSettings& settings) { return settings.mTileSize * settings.mCellSize / settings.mRecastScaleFactor; } inline float getMaxNavmeshAreaRadius(const Settings& settings) { return std::floor(std::sqrt(settings.mMaxTilesNumber / osg::PI)) - 1; } // Returns tile bounds in real coordinates inline TileBounds makeRealTileBoundsWithBorder(const RecastSettings& settings, const TilePosition& tilePosition) { TileBounds result = makeTileBounds(settings, tilePosition); const float border = getBorderSize(settings); result.mMin -= osg::Vec2f(border, border); result.mMax += osg::Vec2f(border, border); result.mMin /= settings.mRecastScaleFactor; result.mMax /= settings.mRecastScaleFactor; return result; } } #endif
4,136
C++
.h
97
36.42268
116
0.713219
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,674
tilespositionsrange.hpp
OpenMW_openmw/components/detournavigator/tilespositionsrange.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_TILESPOSITIONSRANGE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_TILESPOSITIONSRANGE_H #include "tileposition.hpp" #include <tuple> namespace DetourNavigator { struct TilesPositionsRange { TilePosition mBegin; TilePosition mEnd; }; inline auto tie(const TilesPositionsRange& value) { return std::tie(value.mBegin, value.mEnd); } inline bool operator==(const TilesPositionsRange& lhs, const TilesPositionsRange& rhs) { return tie(lhs) == tie(rhs); } } #endif
573
C++
.h
21
22.761905
90
0.732601
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,675
waitconditiontype.hpp
OpenMW_openmw/components/detournavigator/waitconditiontype.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_WAITCONDITIONTYPE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_WAITCONDITIONTYPE_H namespace DetourNavigator { enum class WaitConditionType { requiredTilesPresent, allJobsDone, }; } #endif
260
C++
.h
11
19.909091
61
0.793522
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,676
preparednavmeshdatatuple.hpp
OpenMW_openmw/components/detournavigator/preparednavmeshdatatuple.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_PREPAREDNAVMESHDATATUPLE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_PREPAREDNAVMESHDATATUPLE_H #include "preparednavmeshdata.hpp" #include "recast.hpp" #include "ref.hpp" #include <Recast.h> #include <tuple> inline bool operator==(const rcPolyMesh& lhs, const rcPolyMesh& rhs) noexcept { const auto makeTuple = [](const rcPolyMesh& v) { using namespace DetourNavigator; return std::tuple(Span(v.verts, static_cast<int>(getVertsLength(v))), Span(v.polys, static_cast<int>(getPolysLength(v))), Span(v.regs, static_cast<int>(getRegsLength(v))), Span(v.flags, static_cast<int>(getFlagsLength(v))), Span(v.areas, static_cast<int>(getAreasLength(v))), ArrayRef(v.bmin), ArrayRef(v.bmax), v.cs, v.ch, v.borderSize, v.maxEdgeError); }; return makeTuple(lhs) == makeTuple(rhs); } inline bool operator==(const rcPolyMeshDetail& lhs, const rcPolyMeshDetail& rhs) noexcept { const auto makeTuple = [](const rcPolyMeshDetail& v) { using namespace DetourNavigator; return std::tuple(Span(v.meshes, static_cast<int>(getMeshesLength(v))), Span(v.verts, static_cast<int>(getVertsLength(v))), Span(v.tris, static_cast<int>(getTrisLength(v)))); }; return makeTuple(lhs) == makeTuple(rhs); } namespace DetourNavigator { inline auto makeTuple(const PreparedNavMeshData& v) noexcept { return std::tuple(v.mUserId, v.mCellHeight, v.mCellSize, Ref(v.mPolyMesh), Ref(v.mPolyMeshDetail)); } } #endif
1,548
C++
.h
35
39.485714
115
0.716467
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,677
cellgridbounds.hpp
OpenMW_openmw/components/detournavigator/cellgridbounds.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_CELLGRIDBOUNDS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_CELLGRIDBOUNDS_H #include <osg/Vec2i> namespace DetourNavigator { struct CellGridBounds { osg::Vec2i mCenter; int mHalfSize; }; } #endif
269
C++
.h
12
18.833333
58
0.767717
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,678
debug.hpp
OpenMW_openmw/components/detournavigator/debug.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_DEBUG_H #include "agentbounds.hpp" #include "areatype.hpp" #include "changetype.hpp" #include "flags.hpp" #include "recastmesh.hpp" #include "status.hpp" #include "tilebounds.hpp" #include <DetourStatus.h> #include <iosfwd> #include <string> class dtNavMesh; namespace DetourNavigator { struct Version; struct TilesPositionsRange; struct AreaCosts; struct DetourSettings; std::ostream& operator<<(std::ostream& stream, const TileBounds& value); std::ostream& operator<<(std::ostream& stream, Status value); std::ostream& operator<<(std::ostream& s, const Water& v); std::ostream& operator<<(std::ostream& s, const CellWater& v); std::ostream& operator<<(std::ostream& s, const FlatHeightfield& v); std::ostream& operator<<(std::ostream& s, const Heightfield& v); std::ostream& operator<<(std::ostream& s, CollisionShapeType v); std::ostream& operator<<(std::ostream& s, const AgentBounds& v); struct WriteDtStatus { dtStatus mStatus; }; std::ostream& operator<<(std::ostream& stream, const WriteDtStatus& value); std::ostream& operator<<(std::ostream& stream, const Flag value); struct WriteFlags { Flags mValue; }; std::ostream& operator<<(std::ostream& stream, const WriteFlags& value); std::ostream& operator<<(std::ostream& stream, AreaType value); std::ostream& operator<<(std::ostream& stream, ChangeType value); std::ostream& operator<<(std::ostream& stream, const Version& value); std::ostream& operator<<(std::ostream& stream, const TilesPositionsRange& value); std::ostream& operator<<(std::ostream& stream, const AreaCosts& value); std::ostream& operator<<(std::ostream& stream, const DetourSettings& value); class RecastMesh; struct RecastSettings; void writeToFile(const RecastMesh& recastMesh, const std::string& pathPrefix, const std::string& revision, const RecastSettings& settings); void writeToFile(const dtNavMesh& navMesh, const std::string& pathPrefix, const std::string& revision); } #endif
2,181
C++
.h
51
38.333333
110
0.723728
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,679
tilecachedrecastmeshmanager.hpp
OpenMW_openmw/components/detournavigator/tilecachedrecastmeshmanager.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_TILECACHEDRECASTMESHMANAGER_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_TILECACHEDRECASTMESHMANAGER_H #include "areatype.hpp" #include "changetype.hpp" #include "commulativeaabb.hpp" #include "gettilespositions.hpp" #include "heightfieldshape.hpp" #include "objectid.hpp" #include "recastmesh.hpp" #include "recastmeshobject.hpp" #include "tileposition.hpp" #include "updateguard.hpp" #include "version.hpp" #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/index/rtree.hpp> #include <LinearMath/btTransform.h> #include <osg/Vec2i> #include <map> #include <memory> #include <mutex> #include <optional> #include <unordered_map> namespace DetourNavigator { class RecastMesh; struct TileCachedRecastMeshManagerStats; class TileCachedRecastMeshManager { public: explicit TileCachedRecastMeshManager(const RecastSettings& settings); ScopedUpdateGuard makeUpdateGuard() { mMutex.lock(); return ScopedUpdateGuard(&mUpdateGuard); } void setRange(const TilesPositionsRange& range, const UpdateGuard* guard); TilesPositionsRange getLimitedObjectsRange() const; void setWorldspace(ESM::RefId worldspace, const UpdateGuard* guard); bool addObject(ObjectId id, const CollisionShape& shape, const btTransform& transform, AreaType areaType, const UpdateGuard* guard); bool updateObject(ObjectId id, const btTransform& transform, AreaType areaType, const UpdateGuard* guard); void removeObject(ObjectId id, const UpdateGuard* guard); void addWater(const osg::Vec2i& cellPosition, int cellSize, float level, const UpdateGuard* guard); void removeWater(const osg::Vec2i& cellPosition, const UpdateGuard* guard); void addHeightfield( const osg::Vec2i& cellPosition, int cellSize, const HeightfieldShape& shape, const UpdateGuard* guard); void removeHeightfield(const osg::Vec2i& cellPosition, const UpdateGuard* guard); std::shared_ptr<RecastMesh> getMesh(ESM::RefId worldspace, const TilePosition& tilePosition); std::shared_ptr<RecastMesh> getCachedMesh(ESM::RefId worldspace, const TilePosition& tilePosition) const; std::shared_ptr<RecastMesh> getNewMesh(ESM::RefId worldspace, const TilePosition& tilePosition) const; std::size_t getRevision() const { return mRevision; } void reportNavMeshChange(const TilePosition& tilePosition, Version recastMeshVersion, Version navMeshVersion); void addChangedTile(const TilePosition& tilePosition, ChangeType changeType); std::map<osg::Vec2i, ChangeType> takeChangedTiles(const UpdateGuard* guard); TileCachedRecastMeshManagerStats getStats() const; private: struct Report { std::size_t mRevision; Version mNavMeshVersion; }; struct ObjectData { RecastMeshObject mObject; TilesPositionsRange mRange; CommulativeAabb mAabb; std::size_t mGeneration = 0; std::size_t mRevision = 0; std::optional<Report> mLastNavMeshReportedChange; std::optional<Report> mLastNavMeshReport; }; struct WaterData { Water mWater; std::optional<TilesPositionsRange> mRange; std::size_t mRevision; }; struct HeightfieldData { int mCellSize; HeightfieldShape mShape; std::optional<TilesPositionsRange> mRange; std::size_t mRevision; }; struct CachedTile { Version mVersion; std::shared_ptr<RecastMesh> mRecastMesh; }; using IndexPoint = boost::geometry::model::point<int, 2, boost::geometry::cs::cartesian>; using IndexBox = boost::geometry::model::box<IndexPoint>; using ObjectIndexValue = std::pair<IndexBox, ObjectData*>; using WaterIndexValue = std::pair<IndexBox, std::map<osg::Vec2i, WaterData>::const_iterator>; using HeightfieldIndexValue = std::pair<IndexBox, std::map<osg::Vec2i, HeightfieldData>::const_iterator>; const RecastSettings& mSettings; TilesPositionsRange mRange; ESM::RefId mWorldspace; std::unordered_map<ObjectId, std::unique_ptr<ObjectData>> mObjects; boost::geometry::index::rtree<ObjectIndexValue, boost::geometry::index::quadratic<16>> mObjectIndex; std::map<osg::Vec2i, WaterData> mWater; std::map<osg::Vec2i, WaterData>::const_iterator mInfiniteWater = mWater.end(); boost::geometry::index::rtree<WaterIndexValue, boost::geometry::index::linear<4>> mWaterIndex; std::map<osg::Vec2i, HeightfieldData> mHeightfields; std::map<osg::Vec2i, HeightfieldData>::const_iterator mInfiniteHeightfield = mHeightfields.end(); boost::geometry::index::rtree<HeightfieldIndexValue, boost::geometry::index::linear<4>> mHeightfieldIndex; std::map<osg::Vec2i, ChangeType> mChangedTiles; std::map<TilePosition, CachedTile> mCache; std::size_t mGeneration = 0; std::size_t mRevision = 0; mutable std::mutex mMutex; UpdateGuard mUpdateGuard{ mMutex }; inline static IndexPoint makeIndexPoint(const TilePosition& tilePosition); inline static IndexBox makeIndexBox(const TilesPositionsRange& range); inline static ObjectIndexValue makeObjectIndexValue(const TilesPositionsRange& range, ObjectData* data); inline static WaterIndexValue makeWaterIndexValue( const TilesPositionsRange& range, std::map<osg::Vec2i, WaterData>::const_iterator it); inline static HeightfieldIndexValue makeHeightfieldIndexValue( const TilesPositionsRange& range, std::map<osg::Vec2i, HeightfieldData>::const_iterator it); inline static auto makeIndexQuery(const TilePosition& tilePosition) -> decltype(boost::geometry::index::intersects(IndexBox())); inline std::shared_ptr<RecastMesh> makeMesh(const TilePosition& tilePosition) const; inline void addChangedTiles(const std::optional<TilesPositionsRange>& range, ChangeType changeType); }; } #endif
6,347
C++
.h
126
42.18254
118
0.710633
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,680
navmeshdb.hpp
OpenMW_openmw/components/detournavigator/navmeshdb.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHDB_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHDB_H #include "tileposition.hpp" #include "tilespositionsrange.hpp" #include <components/esm/refid.hpp> #include <components/misc/strongtypedef.hpp> #include <components/sqlite3/db.hpp> #include <components/sqlite3/statement.hpp> #include <components/sqlite3/transaction.hpp> #include <components/sqlite3/types.hpp> #include <cstddef> #include <cstdint> #include <optional> #include <string_view> #include <vector> struct sqlite3; struct sqlite3_stmt; namespace DetourNavigator { using TileId = Misc::StrongTypedef<std::int64_t, struct TiledIdTag>; using TileRevision = Misc::StrongTypedef<std::int64_t, struct TileRevisionTag>; using TileVersion = Misc::StrongTypedef<std::int64_t, struct TileVersionTag>; using ShapeId = Misc::StrongTypedef<std::int64_t, struct ShapeIdTag>; struct Tile { TileId mTileId; TileVersion mVersion; }; struct TileData { TileId mTileId; TileVersion mVersion; std::vector<std::byte> mData; }; enum class ShapeType { Collision = 1, Avoid = 2, }; std::ostream& operator<<(std::ostream& stream, ShapeType value); namespace DbQueries { struct GetMaxTileId { static std::string_view text() noexcept; static void bind(sqlite3&, sqlite3_stmt&) {} }; struct FindTile { static std::string_view text() noexcept; static void bind(sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input); }; struct GetTileData { static std::string_view text() noexcept; static void bind(sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input); }; struct InsertTile { static std::string_view text() noexcept; static void bind(sqlite3& db, sqlite3_stmt& statement, TileId tileId, std::string_view worldspace, const TilePosition& tilePosition, TileVersion version, const std::vector<std::byte>& input, const std::vector<std::byte>& data); }; struct UpdateTile { static std::string_view text() noexcept; static void bind(sqlite3& db, sqlite3_stmt& statement, TileId tileId, TileVersion version, const std::vector<std::byte>& data); }; struct DeleteTilesAt { static std::string_view text() noexcept; static void bind( sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition); }; struct DeleteTilesAtExcept { static std::string_view text() noexcept; static void bind(sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilePosition& tilePosition, TileId excludeTileId); }; struct DeleteTilesOutsideRange { static std::string_view text() noexcept; static void bind( sqlite3& db, sqlite3_stmt& statement, std::string_view worldspace, const TilesPositionsRange& range); }; struct GetMaxShapeId { static std::string_view text() noexcept; static void bind(sqlite3&, sqlite3_stmt&) {} }; struct FindShapeId { static std::string_view text() noexcept; static void bind(sqlite3& db, sqlite3_stmt& statement, std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash); }; struct InsertShape { static std::string_view text() noexcept; static void bind(sqlite3& db, sqlite3_stmt& statement, ShapeId shapeId, std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash); }; struct Vacuum { static std::string_view text() noexcept; static void bind(sqlite3&, sqlite3_stmt&) {} }; } class NavMeshDb { public: explicit NavMeshDb(std::string_view path, std::uint64_t maxFileSize); Sqlite3::Transaction startTransaction(Sqlite3::TransactionMode mode = Sqlite3::TransactionMode::Default); TileId getMaxTileId(); std::optional<Tile> findTile( ESM::RefId worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input); std::optional<TileData> getTileData( ESM::RefId worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input); int insertTile(TileId tileId, ESM::RefId worldspace, const TilePosition& tilePosition, TileVersion version, const std::vector<std::byte>& input, const std::vector<std::byte>& data); int updateTile(TileId tileId, TileVersion version, const std::vector<std::byte>& data); int deleteTilesAt(ESM::RefId worldspace, const TilePosition& tilePosition); int deleteTilesAtExcept(ESM::RefId worldspace, const TilePosition& tilePosition, TileId excludeTileId); int deleteTilesOutsideRange(ESM::RefId worldspace, const TilesPositionsRange& range); ShapeId getMaxShapeId(); std::optional<ShapeId> findShapeId(std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash); int insertShape(ShapeId shapeId, std::string_view name, ShapeType type, const Sqlite3::ConstBlob& hash); void vacuum(); private: Sqlite3::Db mDb; Sqlite3::Statement<DbQueries::GetMaxTileId> mGetMaxTileId; Sqlite3::Statement<DbQueries::FindTile> mFindTile; Sqlite3::Statement<DbQueries::GetTileData> mGetTileData; Sqlite3::Statement<DbQueries::InsertTile> mInsertTile; Sqlite3::Statement<DbQueries::UpdateTile> mUpdateTile; Sqlite3::Statement<DbQueries::DeleteTilesAt> mDeleteTilesAt; Sqlite3::Statement<DbQueries::DeleteTilesAtExcept> mDeleteTilesAtExcept; Sqlite3::Statement<DbQueries::DeleteTilesOutsideRange> mDeleteTilesOutsideRange; Sqlite3::Statement<DbQueries::GetMaxShapeId> mGetMaxShapeId; Sqlite3::Statement<DbQueries::FindShapeId> mFindShapeId; Sqlite3::Statement<DbQueries::InsertShape> mInsertShape; Sqlite3::Statement<DbQueries::Vacuum> mVacuum; }; } #endif
6,606
C++
.h
150
35.246667
117
0.665524
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,681
serialization.hpp
OpenMW_openmw/components/detournavigator/serialization.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_SERIALIZATION_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_SERIALIZATION_H #include <cstddef> #include <cstdint> #include <vector> namespace DetourNavigator { class RecastMesh; struct DbRefGeometryObject; struct PreparedNavMeshData; struct RecastSettings; struct AgentBounds; constexpr char recastMeshMagic[] = { 'r', 'c', 's', 't' }; constexpr std::uint32_t recastMeshVersion = 2; constexpr char preparedNavMeshDataMagic[] = { 'p', 'n', 'a', 'v' }; constexpr std::uint32_t preparedNavMeshDataVersion = 1; std::vector<std::byte> serialize(const RecastSettings& settings, const AgentBounds& agentBounds, const RecastMesh& recastMesh, const std::vector<DbRefGeometryObject>& dbRefGeometryObjects); std::vector<std::byte> serialize(const PreparedNavMeshData& value); bool deserialize(const std::vector<std::byte>& data, PreparedNavMeshData& value); } #endif
960
C++
.h
22
39.727273
100
0.758065
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,682
preparednavmeshdata.hpp
OpenMW_openmw/components/detournavigator/preparednavmeshdata.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_PREPAREDNAVMESHDATA_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_PREPAREDNAVMESHDATA_H #include "recast.hpp" #include <Recast.h> #include <cstddef> namespace DetourNavigator { struct PreparedNavMeshData { unsigned int mUserId = 0; float mCellSize = 0; float mCellHeight = 0; rcPolyMesh mPolyMesh; rcPolyMeshDetail mPolyMeshDetail; PreparedNavMeshData() noexcept; PreparedNavMeshData(const PreparedNavMeshData& other); ~PreparedNavMeshData() noexcept; PreparedNavMeshData& operator=(const PreparedNavMeshData& other) = delete; friend bool operator==(const PreparedNavMeshData& lhs, const PreparedNavMeshData& rhs) noexcept; }; inline constexpr std::size_t getSize(const rcPolyMesh& value) noexcept { return getVertsLength(value) * sizeof(*value.verts) + getPolysLength(value) * sizeof(*value.polys) + getRegsLength(value) * sizeof(*value.regs) + getFlagsLength(value) * sizeof(*value.flags) + getAreasLength(value) * sizeof(*value.areas); } inline constexpr std::size_t getSize(const rcPolyMeshDetail& value) noexcept { return getMeshesLength(value) * sizeof(*value.meshes) + getVertsLength(value) * sizeof(*value.verts) + getTrisLength(value) * sizeof(*value.tris); } inline constexpr std::size_t getSize(const PreparedNavMeshData& value) noexcept { return getSize(value.mPolyMesh) + getSize(value.mPolyMeshDetail); } } #endif
1,568
C++
.h
37
35.972973
108
0.717577
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,683
navigatorutils.hpp
OpenMW_openmw/components/detournavigator/navigatorutils.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATORUTILS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATORUTILS_H #include "findsmoothpath.hpp" #include "flags.hpp" #include "navigator.hpp" #include "navmeshcacheitem.hpp" #include "settings.hpp" #include <components/misc/guarded.hpp> #include <iterator> #include <optional> namespace DetourNavigator { /** * @brief findPath fills output iterator with points of scene surfaces to be used for actor to walk through. * @param agentBounds defines which navmesh to use. * @param start path from given point. * @param end path at given point. * @param includeFlags setup allowed navmesh areas. * @param out the beginning of the destination range. * @param endTolerance defines maximum allowed distance to end path point in addition to agentHalfExtents * @return Status. * Equal to out if no path is found. */ inline Status findPath(const Navigator& navigator, const AgentBounds& agentBounds, const osg::Vec3f& start, const osg::Vec3f& end, const Flags includeFlags, const AreaCosts& areaCosts, float endTolerance, std::output_iterator<osg::Vec3f> auto out) { const auto navMesh = navigator.getNavMesh(agentBounds); if (navMesh == nullptr) return Status::NavMeshNotFound; const Settings& settings = navigator.getSettings(); FromNavMeshCoordinatesIterator outTransform(out, settings.mRecast); const auto locked = navMesh->lock(); return findSmoothPath(locked->getQuery(), toNavMeshCoordinates(settings.mRecast, agentBounds.mHalfExtents), toNavMeshCoordinates(settings.mRecast, start), toNavMeshCoordinates(settings.mRecast, end), includeFlags, areaCosts, settings.mDetour, endTolerance, outTransform); } /** * @brief findRandomPointAroundCircle returns random location on navmesh within the reach of specified location. * @param agentBounds defines which navmesh to use. * @param start is a position where the search starts. * @param maxRadius limit maximum distance from start. * @param includeFlags setup allowed navmesh areas. * @return not empty optional with position if point is found and empty optional if point is not found. */ std::optional<osg::Vec3f> findRandomPointAroundCircle(const Navigator& navigator, const AgentBounds& agentBounds, const osg::Vec3f& start, const float maxRadius, const Flags includeFlags, float (*prng)()); /** * @brief raycast finds farest navmesh point from start on a line from start to end that has path from start. * @param agentBounds defines which navmesh to use. * @param start of the line * @param end of the line * @param includeFlags setup allowed navmesh areas. * @return not empty optional with position if point is found and empty optional if point is not found. */ std::optional<osg::Vec3f> raycast(const Navigator& navigator, const AgentBounds& agentBounds, const osg::Vec3f& start, const osg::Vec3f& end, const Flags includeFlags); /** * @brief findNearestNavMeshPosition finds nearest position on navmesh within given area having given flags. * @param agentBounds defines which navmesh to use. * @param position is a center of the search area. * @param searchAreaHalfExtents defines AABB like area around given postion. * @param includeFlags setup allowed navmesh areas. * @return not empty optional with position if position is found and empty optional if position is not found. */ std::optional<osg::Vec3f> findNearestNavMeshPosition(const Navigator& navigator, const AgentBounds& agentBounds, const osg::Vec3f& position, const osg::Vec3f& searchAreaHalfExtents, const Flags includeFlags); } #endif
3,828
C++
.h
69
49.73913
117
0.740069
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,684
navmeshtilescache.hpp
OpenMW_openmw/components/detournavigator/navmeshtilescache.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHTILESCACHE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHTILESCACHE_H #include "agentbounds.hpp" #include "preparednavmeshdata.hpp" #include "recastmesh.hpp" #include "tileposition.hpp" #include <atomic> #include <cassert> #include <cstring> #include <list> #include <map> #include <mutex> #include <vector> namespace DetourNavigator { struct RecastMeshData { Mesh mMesh; std::vector<CellWater> mWater; std::vector<Heightfield> mHeightfields; std::vector<FlatHeightfield> mFlatHeightfields; }; inline bool operator<(const RecastMeshData& lhs, const RecastMeshData& rhs) { return std::tie(lhs.mMesh, lhs.mWater, lhs.mHeightfields, lhs.mFlatHeightfields) < std::tie(rhs.mMesh, rhs.mWater, rhs.mHeightfields, rhs.mFlatHeightfields); } inline bool operator<(const RecastMeshData& lhs, const RecastMesh& rhs) { return std::tie(lhs.mMesh, lhs.mWater, lhs.mHeightfields, lhs.mFlatHeightfields) < std::tie(rhs.getMesh(), rhs.getWater(), rhs.getHeightfields(), rhs.getFlatHeightfields()); } inline bool operator<(const RecastMesh& lhs, const RecastMeshData& rhs) { return std::tie(lhs.getMesh(), lhs.getWater(), lhs.getHeightfields(), lhs.getFlatHeightfields()) < std::tie(rhs.mMesh, rhs.mWater, rhs.mHeightfields, rhs.mFlatHeightfields); } struct NavMeshTilesCacheStats; class NavMeshTilesCache { public: struct Item { std::atomic<std::int64_t> mUseCount; AgentBounds mAgentBounds; TilePosition mChangedTile; RecastMeshData mRecastMeshData; std::unique_ptr<PreparedNavMeshData> mPreparedNavMeshData; std::size_t mSize; Item(const AgentBounds& agentBounds, const TilePosition& changedTile, RecastMeshData&& recastMeshData, std::size_t size) : mUseCount(0) , mAgentBounds(agentBounds) , mChangedTile(changedTile) , mRecastMeshData(std::move(recastMeshData)) , mSize(size) { } }; using ItemIterator = std::list<Item>::iterator; class Value { public: Value() : mOwner(nullptr) , mIterator() { } Value(NavMeshTilesCache& owner, ItemIterator iterator) : mOwner(&owner) , mIterator(iterator) { } Value(const Value& other) = delete; Value(Value&& other) : mOwner(other.mOwner) , mIterator(other.mIterator) { other.mOwner = nullptr; } ~Value() { if (mOwner) mOwner->releaseItem(mIterator); } Value& operator=(const Value& other) = delete; Value& operator=(Value&& other) { if (mOwner) mOwner->releaseItem(mIterator); mOwner = other.mOwner; mIterator = other.mIterator; other.mOwner = nullptr; return *this; } const PreparedNavMeshData& get() const { return *mIterator->mPreparedNavMeshData; } operator bool() const { return mOwner; } private: NavMeshTilesCache* mOwner; ItemIterator mIterator; }; NavMeshTilesCache(const std::size_t maxNavMeshDataSize); Value get(const AgentBounds& agentBounds, const TilePosition& changedTile, const RecastMesh& recastMesh); Value set(const AgentBounds& agentBounds, const TilePosition& changedTile, const RecastMesh& recastMesh, std::unique_ptr<PreparedNavMeshData>&& value); NavMeshTilesCacheStats getStats() const; private: mutable std::mutex mMutex; std::size_t mMaxNavMeshDataSize; std::size_t mUsedNavMeshDataSize; std::size_t mFreeNavMeshDataSize; std::size_t mHitCount; std::size_t mGetCount; std::list<Item> mBusyItems; std::list<Item> mFreeItems; std::map<std::tuple<AgentBounds, TilePosition, std::reference_wrapper<const RecastMeshData>>, ItemIterator, std::less<>> mValues; void removeLeastRecentlyUsed(); void acquireItemUnsafe(ItemIterator iterator); void releaseItem(ItemIterator iterator); }; } #endif
4,627
C++
.h
124
27.153226
115
0.610154
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,685
navmeshdata.hpp
OpenMW_openmw/components/detournavigator/navmeshdata.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHDATA_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHDATA_H #include <DetourAlloc.h> #include <memory> namespace DetourNavigator { struct NavMeshDataValueDeleter { void operator()(unsigned char* value) const { dtFree(value); } }; using NavMeshDataValue = std::unique_ptr<unsigned char, NavMeshDataValueDeleter>; struct NavMeshData { NavMeshDataValue mValue; int mSize = 0; NavMeshData() = default; NavMeshData(unsigned char* value, int size) : mValue(value) , mSize(size) { } }; } #endif
656
C++
.h
24
21.5
85
0.676282
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,686
recastallocutils.hpp
OpenMW_openmw/components/detournavigator/recastallocutils.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTALLOCUTILS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTALLOCUTILS_H #include <cstddef> namespace DetourNavigator { static_assert(sizeof(std::size_t) == sizeof(void*), ""); enum BufferType : std::size_t { BufferType_perm, BufferType_temp, BufferType_unused, }; inline BufferType* tempPtrBufferType(void* ptr) { return reinterpret_cast<BufferType*>(static_cast<std::size_t*>(ptr) + 1); } inline BufferType getTempPtrBufferType(void* ptr) { return *tempPtrBufferType(ptr); } inline void setTempPtrBufferType(void* ptr, BufferType value) { *tempPtrBufferType(ptr) = value; } inline void** tempPtrPrev(void* ptr) { return static_cast<void**>(ptr); } inline void* getTempPtrPrev(void* ptr) { return *tempPtrPrev(ptr); } inline void setTempPtrPrev(void* ptr, void* value) { *tempPtrPrev(ptr) = value; } inline void* getTempPtrDataPtr(void* ptr) { return reinterpret_cast<void*>(static_cast<std::size_t*>(ptr) + 2); } inline BufferType* dataPtrBufferType(void* dataPtr) { return reinterpret_cast<BufferType*>(static_cast<std::size_t*>(dataPtr) - 1); } inline BufferType getDataPtrBufferType(void* dataPtr) { return *dataPtrBufferType(dataPtr); } inline void setDataPtrBufferType(void* dataPtr, BufferType value) { *dataPtrBufferType(dataPtr) = value; } inline void* getTempDataPtrStackPtr(void* dataPtr) { return static_cast<std::size_t*>(dataPtr) - 2; } inline void* getPermDataPtrHeapPtr(void* dataPtr) { return static_cast<std::size_t*>(dataPtr) - 1; } inline void setPermPtrBufferType(void* ptr, BufferType value) { *static_cast<BufferType*>(ptr) = value; } inline void* getPermPtrDataPtr(void* ptr) { return static_cast<std::size_t*>(ptr) + 1; } } #endif
2,045
C++
.h
70
23.371429
85
0.658487
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,687
makenavmesh.hpp
OpenMW_openmw/components/detournavigator/makenavmesh.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_MAKENAVMESH_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_MAKENAVMESH_H #include "recastmesh.hpp" #include "tileposition.hpp" #include <components/esm/refid.hpp> #include <memory> #include <vector> class dtNavMesh; struct rcConfig; namespace DetourNavigator { struct Settings; struct PreparedNavMeshData; struct NavMeshData; struct OffMeshConnection; struct AgentBounds; struct RecastSettings; inline float getLength(const osg::Vec2i& value) { return std::sqrt(float(osg::square(value.x()) + osg::square(value.y()))); } inline float getDistance(const TilePosition& lhs, const TilePosition& rhs) { return getLength(lhs - rhs); } inline bool shouldAddTile(const TilePosition& changedTile, const TilePosition& playerTile, int maxTiles) { const auto expectedTilesCount = std::ceil(osg::PI * osg::square(getDistance(changedTile, playerTile))); return expectedTilesCount <= maxTiles; } inline bool isEmpty(const RecastMesh& recastMesh) { return recastMesh.getMesh().getIndices().empty() && recastMesh.getWater().empty() && recastMesh.getHeightfields().empty() && recastMesh.getFlatHeightfields().empty(); } std::unique_ptr<PreparedNavMeshData> prepareNavMeshTileData(const RecastMesh& recastMesh, ESM::RefId worldspace, const TilePosition& tilePosition, const AgentBounds& agentBounds, const RecastSettings& settings); NavMeshData makeNavMeshTileData(const PreparedNavMeshData& data, const std::vector<OffMeshConnection>& offMeshConnections, const AgentBounds& agentBounds, const TilePosition& tile, const RecastSettings& settings); void initEmptyNavMesh(const Settings& settings, dtNavMesh& navMesh); bool isSupportedAgentBounds(const RecastSettings& settings, const AgentBounds& agentBounds); } #endif
1,916
C++
.h
44
38.5
116
0.754575
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,688
navmeshmanager.hpp
OpenMW_openmw/components/detournavigator/navmeshmanager.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHMANAGER_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHMANAGER_H #include "agentbounds.hpp" #include "asyncnavmeshupdater.hpp" #include "cellgridbounds.hpp" #include "heightfieldshape.hpp" #include "offmeshconnectionsmanager.hpp" #include "recastmeshtiles.hpp" #include "waitconditiontype.hpp" #include <osg/Vec3f> #include <map> #include <memory> class dtNavMesh; namespace DetourNavigator { class NavMeshManager { public: explicit NavMeshManager(const Settings& settings, std::unique_ptr<NavMeshDb>&& db); ScopedUpdateGuard makeUpdateGuard() { return mRecastMeshManager.makeUpdateGuard(); } void updateBounds(ESM::RefId worldspace, const std::optional<CellGridBounds>& cellGridBounds, const osg::Vec3f& playerPosition, const UpdateGuard* guard); bool addObject(const ObjectId id, const CollisionShape& shape, const btTransform& transform, const AreaType areaType, const UpdateGuard* guard); bool updateObject(ObjectId id, const btTransform& transform, AreaType areaType, const UpdateGuard* guard); void removeObject(const ObjectId id, const UpdateGuard* guard); void addAgent(const AgentBounds& agentBounds); void addWater(const osg::Vec2i& cellPosition, int cellSize, float level, const UpdateGuard* guard); void removeWater(const osg::Vec2i& cellPosition, const UpdateGuard* guard); void addHeightfield( const osg::Vec2i& cellPosition, int cellSize, const HeightfieldShape& shape, const UpdateGuard* guard); void removeHeightfield(const osg::Vec2i& cellPosition, const UpdateGuard* guard); bool reset(const AgentBounds& agentBounds); void addOffMeshConnection( const ObjectId id, const osg::Vec3f& start, const osg::Vec3f& end, const AreaType areaType); void removeOffMeshConnections(const ObjectId id); void update(const osg::Vec3f& playerPosition, const UpdateGuard* guard); void wait(WaitConditionType waitConditionType, Loading::Listener* listener); SharedNavMeshCacheItem getNavMesh(const AgentBounds& agentBounds) const; std::map<AgentBounds, SharedNavMeshCacheItem> getNavMeshes() const; Stats getStats() const; RecastMeshTiles getRecastMeshTiles() const; private: const Settings& mSettings; const int mMaxRadius; ESM::RefId mWorldspace; std::optional<CellGridBounds> mCellGridBounds; TileCachedRecastMeshManager mRecastMeshManager; OffMeshConnectionsManager mOffMeshConnectionsManager; AsyncNavMeshUpdater mAsyncNavMeshUpdater; std::map<AgentBounds, SharedNavMeshCacheItem> mCache; std::size_t mGenerationCounter = 0; std::optional<TilePosition> mPlayerTile; std::size_t mLastRecastMeshManagerRevision = 0; inline SharedNavMeshCacheItem getCached(const AgentBounds& agentBounds) const; inline void update(const AgentBounds& agentBounds, const TilePosition& playerTile, const TilesPositionsRange& range, const SharedNavMeshCacheItem& cached, const std::map<osg::Vec2i, ChangeType>& changedTiles); }; } #endif
3,257
C++
.h
61
46.098361
115
0.746843
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,689
navmeshdbutils.hpp
OpenMW_openmw/components/detournavigator/navmeshdbutils.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHDBUTILS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHDBUTILS_H #include "navmeshdb.hpp" #include <optional> namespace DetourNavigator { struct MeshSource; ShapeId resolveMeshSource(NavMeshDb& db, const MeshSource& source, ShapeId& nextShapeId); std::optional<ShapeId> resolveMeshSource(NavMeshDb& db, const MeshSource& source); } #endif
410
C++
.h
11
34.636364
93
0.824427
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,690
ref.hpp
OpenMW_openmw/components/detournavigator/ref.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_REF_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_REF_H #include <algorithm> #include <cassert> #include <iterator> namespace DetourNavigator { template <typename T> struct Ref { T& mRef; constexpr explicit Ref(T& ref) noexcept : mRef(ref) { } friend bool operator==(const Ref& lhs, const Ref& rhs) { return lhs.mRef == rhs.mRef; } }; template <typename T, std::size_t size> struct ArrayRef { T (&mRef)[size]; constexpr explicit ArrayRef(T (&ref)[size]) noexcept : mRef(ref) { } friend bool operator==(const ArrayRef& lhs, const ArrayRef& rhs) { return std::equal(std::begin(lhs.mRef), std::end(lhs.mRef), std::begin(rhs.mRef)); } }; template <typename T> struct Span { T* mBegin; T* mEnd; constexpr explicit Span(T* data, int size) noexcept : mBegin(data) , mEnd(data + static_cast<std::size_t>(size)) { } friend bool operator==(const Span& lhs, const Span& rhs) { // size is already equal if headers are equal assert((lhs.mEnd - lhs.mBegin) == (rhs.mEnd - rhs.mBegin)); return std::equal(lhs.mBegin, lhs.mEnd, rhs.mBegin); } }; } #endif
1,394
C++
.h
49
21.020408
95
0.574963
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,691
navigatorimpl.hpp
OpenMW_openmw/components/detournavigator/navigatorimpl.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATORIMPL_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATORIMPL_H #include "navigator.hpp" #include "navmeshmanager.hpp" #include "updateguard.hpp" #include <map> #include <memory> #include <optional> #include <unordered_map> namespace DetourNavigator { class NavigatorImpl final : public Navigator { public: /** * @brief Navigator constructor initializes all internal data. Constructed object is ready to build a scene. * @param settings allows to customize navigator work. Constructor is only place to set navigator settings. */ explicit NavigatorImpl(const Settings& settings, std::unique_ptr<NavMeshDb>&& db); ScopedUpdateGuard makeUpdateGuard() override { return mNavMeshManager.makeUpdateGuard(); } bool addAgent(const AgentBounds& agentBounds) override; void removeAgent(const AgentBounds& agentBounds) override; void updateBounds(ESM::RefId worldspace, const std::optional<CellGridBounds>& cellGridBounds, const osg::Vec3f& playerPosition, const UpdateGuard* guard) override; void addObject(const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard) override; void addObject(const ObjectId id, const DoorShapes& shapes, const btTransform& transform, const UpdateGuard* guard) override; void updateObject(const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard) override; void updateObject(const ObjectId id, const DoorShapes& shapes, const btTransform& transform, const UpdateGuard* guard) override; void removeObject(const ObjectId id, const UpdateGuard* guard) override; void addWater(const osg::Vec2i& cellPosition, int cellSize, float level, const UpdateGuard* guard) override; void removeWater(const osg::Vec2i& cellPosition, const UpdateGuard* guard) override; void addHeightfield(const osg::Vec2i& cellPosition, int cellSize, const HeightfieldShape& shape, const UpdateGuard* guard) override; void removeHeightfield(const osg::Vec2i& cellPosition, const UpdateGuard* guard) override; void addPathgrid(const ESM::Cell& cell, const ESM::Pathgrid& pathgrid) override; void removePathgrid(const ESM::Pathgrid& pathgrid) override; void update(const osg::Vec3f& playerPosition, const UpdateGuard* guard) override; void wait(WaitConditionType waitConditionType, Loading::Listener* listener) override; SharedNavMeshCacheItem getNavMesh(const AgentBounds& agentBounds) const override; std::map<AgentBounds, SharedNavMeshCacheItem> getNavMeshes() const override; const Settings& getSettings() const override; Stats getStats() const override; RecastMeshTiles getRecastMeshTiles() const override; float getMaxNavmeshAreaRealRadius() const override; private: Settings mSettings; NavMeshManager mNavMeshManager; std::optional<TilePosition> mLastPlayerPosition; std::map<AgentBounds, std::size_t> mAgents; std::unordered_map<ObjectId, ObjectId> mAvoidIds; std::unordered_map<ObjectId, ObjectId> mWaterIds; inline bool addObjectImpl( const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard); inline void updateAvoidShapeId(const ObjectId id, const ObjectId avoidId, const UpdateGuard* guard); inline void updateId(const ObjectId id, const ObjectId waterId, std::unordered_map<ObjectId, ObjectId>& ids, const UpdateGuard* guard); inline void removeUnusedNavMeshes(); friend class UpdateGuard; }; } #endif
3,853
C++
.h
65
51.138462
116
0.736618
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,692
recastparams.hpp
OpenMW_openmw/components/detournavigator/recastparams.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTPARAMS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTPARAMS_H #include "agentbounds.hpp" #include <osg/Vec3f> #include <algorithm> #include <cassert> #include <cmath> namespace DetourNavigator { inline float getAgentHeight(const AgentBounds& agentBounds) { return 2.0f * agentBounds.mHalfExtents.z(); } inline float getAgentRadius(const AgentBounds& agentBounds) { switch (agentBounds.mShapeType) { case CollisionShapeType::Aabb: return std::max(agentBounds.mHalfExtents.x(), agentBounds.mHalfExtents.y()) * std::sqrt(2); case CollisionShapeType::RotatingBox: return agentBounds.mHalfExtents.x(); case CollisionShapeType::Cylinder: return std::max(agentBounds.mHalfExtents.x(), agentBounds.mHalfExtents.y()); } assert(false && "Unsupported agent shape type"); return 0; } } #endif
995
C++
.h
29
27.724138
107
0.688542
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,693
sharednavmeshcacheitem.hpp
OpenMW_openmw/components/detournavigator/sharednavmeshcacheitem.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_SHAREDNAVMESHCACHEITEM_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_SHAREDNAVMESHCACHEITEM_H #include "guardednavmeshcacheitem.hpp" #include <memory> namespace DetourNavigator { using SharedNavMeshCacheItem = std::shared_ptr<GuardedNavMeshCacheItem>; } #endif
309
C++
.h
9
32.444444
76
0.868243
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,694
navigatorstub.hpp
OpenMW_openmw/components/detournavigator/navigatorstub.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATORSTUB_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATORSTUB_H #include "navigator.hpp" #include "settings.hpp" #include "stats.hpp" #include "updateguard.hpp" namespace Loading { class Listener; } namespace DetourNavigator { class NavigatorStub final : public Navigator { public: NavigatorStub() = default; ScopedUpdateGuard makeUpdateGuard() override { return nullptr; } bool addAgent(const AgentBounds& /*agentBounds*/) override { return true; } void removeAgent(const AgentBounds& /*agentBounds*/) override {} void updateBounds(ESM::RefId /*worldspace*/, const std::optional<CellGridBounds>& /*cellGridBounds*/, const osg::Vec3f& /*playerPosition*/, const UpdateGuard* /*guard*/) override { } void addObject(const ObjectId /*id*/, const ObjectShapes& /*shapes*/, const btTransform& /*transform*/, const UpdateGuard* /*guard*/) override { } void addObject(const ObjectId /*id*/, const DoorShapes& /*shapes*/, const btTransform& /*transform*/, const UpdateGuard* /*guard*/) override { } void updateObject(const ObjectId /*id*/, const ObjectShapes& /*shapes*/, const btTransform& /*transform*/, const UpdateGuard* /*guard*/) override { } void updateObject(const ObjectId /*id*/, const DoorShapes& /*shapes*/, const btTransform& /*transform*/, const UpdateGuard* /*guard*/) override { } void removeObject(const ObjectId /*id*/, const UpdateGuard* /*guard*/) override {} void addWater(const osg::Vec2i& /*cellPosition*/, int /*cellSize*/, float /*level*/, const UpdateGuard* /*guard*/) override { } void removeWater(const osg::Vec2i& /*cellPosition*/, const UpdateGuard* /*guard*/) override {} void addHeightfield(const osg::Vec2i& /*cellPosition*/, int /*cellSize*/, const HeightfieldShape& /*height*/, const UpdateGuard* /*guard*/) override { } void removeHeightfield(const osg::Vec2i& /*cellPosition*/, const UpdateGuard* /*guard*/) override {} void addPathgrid(const ESM::Cell& /*cell*/, const ESM::Pathgrid& /*pathgrid*/) override {} void removePathgrid(const ESM::Pathgrid& /*pathgrid*/) override {} void update(const osg::Vec3f& /*playerPosition*/, const UpdateGuard* /*guard*/) override {} void wait(WaitConditionType /*waitConditionType*/, Loading::Listener* /*listener*/) override {} SharedNavMeshCacheItem getNavMesh(const AgentBounds& /*agentBounds*/) const override { return mEmptyNavMeshCacheItem; } std::map<AgentBounds, SharedNavMeshCacheItem> getNavMeshes() const override { return {}; } const Settings& getSettings() const override { return mDefaultSettings; } Stats getStats() const override { return Stats{}; } RecastMeshTiles getRecastMeshTiles() const override { return {}; } float getMaxNavmeshAreaRealRadius() const override { return std::numeric_limits<float>::max(); } private: Settings mDefaultSettings{}; SharedNavMeshCacheItem mEmptyNavMeshCacheItem; }; } #endif
3,328
C++
.h
69
40.217391
117
0.660477
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,695
generatenavmeshtile.hpp
OpenMW_openmw/components/detournavigator/generatenavmeshtile.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_GENERATENAVMESHTILE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_GENERATENAVMESHTILE_H #include "agentbounds.hpp" #include "recastmeshprovider.hpp" #include "tileposition.hpp" #include <components/sceneutil/workqueue.hpp> #include <cstdint> #include <memory> #include <optional> #include <string_view> #include <vector> namespace DetourNavigator { class OffMeshConnectionsManager; class RecastMesh; struct NavMeshTileConsumer; struct OffMeshConnection; struct PreparedNavMeshData; struct Settings; struct NavMeshTileInfo { std::int64_t mTileId; std::int64_t mVersion; }; struct NavMeshTileConsumer { virtual ~NavMeshTileConsumer() = default; virtual std::int64_t resolveMeshSource(const MeshSource& source) = 0; virtual std::optional<NavMeshTileInfo> find( ESM::RefId worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input) = 0; virtual void ignore(ESM::RefId worldspace, const TilePosition& tilePosition) = 0; virtual void identity(ESM::RefId worldspace, const TilePosition& tilePosition, std::int64_t tileId) = 0; virtual void insert(ESM::RefId worldspace, const TilePosition& tilePosition, std::int64_t version, const std::vector<std::byte>& input, PreparedNavMeshData& data) = 0; virtual void update(ESM::RefId worldspace, const TilePosition& tilePosition, std::int64_t tileId, std::int64_t version, PreparedNavMeshData& data) = 0; virtual void cancel(std::string_view reason) = 0; }; class GenerateNavMeshTile final : public SceneUtil::WorkItem { public: GenerateNavMeshTile(ESM::RefId worldspace, const TilePosition& tilePosition, RecastMeshProvider recastMeshProvider, const AgentBounds& agentBounds, const Settings& settings, std::weak_ptr<NavMeshTileConsumer> consumer); void doWork() final; private: const ESM::RefId mWorldspace; const TilePosition mTilePosition; const RecastMeshProvider mRecastMeshProvider; const AgentBounds mAgentBounds; const Settings& mSettings; std::weak_ptr<NavMeshTileConsumer> mConsumer; inline void impl() noexcept; }; } #endif
2,368
C++
.h
59
33.474576
112
0.715845
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,696
navmeshtileview.hpp
OpenMW_openmw/components/detournavigator/navmeshtileview.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHTILEVIEW_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHTILEVIEW_H struct dtMeshHeader; struct dtPoly; struct dtPolyDetail; struct dtBVNode; struct dtOffMeshConnection; struct dtMeshTile; namespace DetourNavigator { struct NavMeshTileConstView { const dtMeshHeader* mHeader; const dtPoly* mPolys; const float* mVerts; const dtPolyDetail* mDetailMeshes; const float* mDetailVerts; const unsigned char* mDetailTris; const dtBVNode* mBvTree; const dtOffMeshConnection* mOffMeshCons; friend bool operator==(const NavMeshTileConstView& lhs, const NavMeshTileConstView& rhs) noexcept; }; NavMeshTileConstView asNavMeshTileConstView(const unsigned char* data); NavMeshTileConstView asNavMeshTileConstView(const dtMeshTile& tile); } #endif
882
C++
.h
26
29.192308
106
0.779083
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,697
findsmoothpath.hpp
OpenMW_openmw/components/detournavigator/findsmoothpath.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_FINDSMOOTHPATH_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_FINDSMOOTHPATH_H #include "areatype.hpp" #include "flags.hpp" #include "settings.hpp" #include "settingsutils.hpp" #include "status.hpp" #include <DetourCommon.h> #include <DetourNavMesh.h> #include <DetourNavMeshQuery.h> #include <osg/Vec3f> #include <array> #include <cassert> #include <functional> #include <iterator> #include <span> #include <vector> namespace DetourNavigator { template <std::output_iterator<osg::Vec3f> OutputIterator> class FromNavMeshCoordinatesIterator { public: using iterator_category = std::output_iterator_tag; using value_type = osg::Vec3f; using difference_type = std::ptrdiff_t; using pointer = osg::Vec3f*; using reference = osg::Vec3f&; explicit FromNavMeshCoordinatesIterator(OutputIterator& impl, const RecastSettings& settings) : mImpl(impl) , mSettings(settings) { } FromNavMeshCoordinatesIterator& operator*() { return *this; } FromNavMeshCoordinatesIterator& operator++() { ++mImpl.get(); return *this; } FromNavMeshCoordinatesIterator operator++(int) { const auto copy = *this; ++(*this); return copy; } FromNavMeshCoordinatesIterator& operator=(const osg::Vec3f& value) { *mImpl.get() = fromNavMeshCoordinates(mSettings, value); return *this; } private: std::reference_wrapper<OutputIterator> mImpl; std::reference_wrapper<const RecastSettings> mSettings; }; inline std::optional<std::size_t> findPolygonPath(const dtNavMeshQuery& navMeshQuery, const dtPolyRef startRef, const dtPolyRef endRef, const osg::Vec3f& startPos, const osg::Vec3f& endPos, const dtQueryFilter& queryFilter, std::span<dtPolyRef> pathBuffer) { int pathLen = 0; const auto status = navMeshQuery.findPath(startRef, endRef, startPos.ptr(), endPos.ptr(), &queryFilter, pathBuffer.data(), &pathLen, static_cast<int>(pathBuffer.size())); if (!dtStatusSucceed(status)) return {}; assert(pathLen >= 0); assert(static_cast<std::size_t>(pathLen) <= pathBuffer.size()); return static_cast<std::size_t>(pathLen); } Status makeSmoothPath(const dtNavMeshQuery& navMeshQuery, const osg::Vec3f& start, const osg::Vec3f& end, std::span<dtPolyRef> polygonPath, std::size_t polygonPathSize, std::size_t maxSmoothPathSize, std::output_iterator<osg::Vec3f> auto& out) { assert(polygonPathSize <= polygonPath.size()); std::vector<float> cornerVertsBuffer(maxSmoothPathSize * 3); std::vector<unsigned char> cornerFlagsBuffer(maxSmoothPathSize); std::vector<dtPolyRef> cornerPolysBuffer(maxSmoothPathSize); int cornersCount = 0; constexpr int findStraightPathOptions = DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS; if (const dtStatus status = navMeshQuery.findStraightPath(start.ptr(), end.ptr(), polygonPath.data(), static_cast<int>(polygonPathSize), cornerVertsBuffer.data(), cornerFlagsBuffer.data(), cornerPolysBuffer.data(), &cornersCount, static_cast<int>(maxSmoothPathSize), findStraightPathOptions); dtStatusFailed(status)) return Status::FindStraightPathFailed; for (int i = 0; i < cornersCount; ++i) *out++ = Misc::Convert::makeOsgVec3f(&cornerVertsBuffer[static_cast<std::size_t>(i) * 3]); return Status::Success; } Status findSmoothPath(const dtNavMeshQuery& navMeshQuery, const osg::Vec3f& halfExtents, const osg::Vec3f& start, const osg::Vec3f& end, const Flags includeFlags, const AreaCosts& areaCosts, const DetourSettings& settings, float endTolerance, std::output_iterator<osg::Vec3f> auto out) { dtQueryFilter queryFilter; queryFilter.setIncludeFlags(includeFlags); queryFilter.setAreaCost(AreaType_water, areaCosts.mWater); queryFilter.setAreaCost(AreaType_door, areaCosts.mDoor); queryFilter.setAreaCost(AreaType_pathgrid, areaCosts.mPathgrid); queryFilter.setAreaCost(AreaType_ground, areaCosts.mGround); constexpr float polyDistanceFactor = 4; const osg::Vec3f polyHalfExtents = halfExtents * polyDistanceFactor; osg::Vec3f startNavMeshPos; dtPolyRef startRef = 0; if (const dtStatus status = navMeshQuery.findNearestPoly( start.ptr(), polyHalfExtents.ptr(), &queryFilter, &startRef, startNavMeshPos.ptr()); dtStatusFailed(status) || startRef == 0) return Status::StartPolygonNotFound; osg::Vec3f endNavMeshPos; const osg::Vec3f endPolyHalfExtents = polyHalfExtents + osg::Vec3f(endTolerance, endTolerance, endTolerance); dtPolyRef endRef; if (const dtStatus status = navMeshQuery.findNearestPoly( end.ptr(), endPolyHalfExtents.ptr(), &queryFilter, &endRef, endNavMeshPos.ptr()); dtStatusFailed(status) || endRef == 0) return Status::EndPolygonNotFound; std::vector<dtPolyRef> polygonPath(settings.mMaxPolygonPathSize); const auto polygonPathSize = findPolygonPath(navMeshQuery, startRef, endRef, startNavMeshPos, endNavMeshPos, queryFilter, polygonPath); if (!polygonPathSize.has_value()) return Status::FindPathOverPolygonsFailed; if (*polygonPathSize == 0) return Status::Success; osg::Vec3f targetNavMeshPos; if (const dtStatus status = navMeshQuery.closestPointOnPoly( polygonPath[*polygonPathSize - 1], end.ptr(), targetNavMeshPos.ptr(), nullptr); dtStatusFailed(status)) return Status::TargetPolygonNotFound; const bool partialPath = polygonPath[*polygonPathSize - 1] != endRef; const Status smoothStatus = makeSmoothPath(navMeshQuery, startNavMeshPos, targetNavMeshPos, polygonPath, *polygonPathSize, settings.mMaxSmoothPathSize, out); if (smoothStatus != Status::Success) return smoothStatus; return partialPath ? Status::PartialPath : Status::Success; } } #endif
6,404
C++
.h
132
39.969697
120
0.684337
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,698
navigator.hpp
OpenMW_openmw/components/detournavigator/navigator.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATOR_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVIGATOR_H #include <cassert> #include <filesystem> #include <optional> #include "cellgridbounds.hpp" #include "heightfieldshape.hpp" #include "objectid.hpp" #include "objecttransform.hpp" #include "recastmeshtiles.hpp" #include "sharednavmeshcacheitem.hpp" #include "updateguard.hpp" #include "waitconditiontype.hpp" #include <components/esm/refid.hpp> #include <components/resource/bulletshape.hpp> namespace ESM { struct Cell; struct Pathgrid; class RefId; } namespace Loading { class Listener; } namespace DetourNavigator { struct Settings; struct AgentBounds; struct Stats; struct ObjectShapes { osg::ref_ptr<const Resource::BulletShapeInstance> mShapeInstance; ObjectTransform mTransform; ObjectShapes( const osg::ref_ptr<const Resource::BulletShapeInstance>& shapeInstance, const ObjectTransform& transform) : mShapeInstance(shapeInstance) , mTransform(transform) { assert(mShapeInstance != nullptr); } }; struct DoorShapes : ObjectShapes { osg::Vec3f mConnectionStart; osg::Vec3f mConnectionEnd; DoorShapes(const osg::ref_ptr<const Resource::BulletShapeInstance>& shapeInstance, const ObjectTransform& transform, const osg::Vec3f& connectionStart, const osg::Vec3f& connectionEnd) : ObjectShapes(shapeInstance, transform) , mConnectionStart(connectionStart) , mConnectionEnd(connectionEnd) { } }; /** * @brief Top level interface of detournavigator component. Navigator allows to build a scene with navmesh and find * a path for an agent there. Scene contains agents, geometry objects and water. Agent are distinguished only by * half extents. Each object has unique identifier and could be added, updated or removed. Water could be added once * for each world cell at given level of height. Navmesh builds asynchronously in separate threads. To start build * navmesh call update method. */ struct Navigator { virtual ~Navigator() = default; virtual ScopedUpdateGuard makeUpdateGuard() = 0; /** * @brief addAgent should be called for each agent even if all of them has same half extents. * @param agentBounds allows to setup bounding cylinder for each agent, for each different half extents * there is different navmesh. * @return true if agent is successfully added or false if agent bounds are not supported. */ virtual bool addAgent(const AgentBounds& agentBounds) = 0; /** * @brief removeAgent should be called for each agent even if all of them has same half extents * @param agentBounds allows determine which agent to remove */ virtual void removeAgent(const AgentBounds& agentBounds) = 0; // Updates bounds for recast mesh and navmesh tiles, removes tiles outside the range. virtual void updateBounds(ESM::RefId worldspace, const std::optional<CellGridBounds>& cellGridBounds, const osg::Vec3f& playerPosition, const UpdateGuard* guard) = 0; /** * @brief addObject is used to add complex object with allowed to walk and avoided to walk shapes * @param id is used to distinguish different objects * @param shape members must live until object is updated by another shape removed from Navigator * @param transform allows to setup objects geometry according to its world state */ virtual void addObject( const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard) = 0; /** * @brief addObject is used to add doors. * @param id is used to distinguish different objects. * @param shape members must live until object is updated by another shape or removed from Navigator. * @param transform allows to setup objects geometry according to its world state. */ virtual void addObject( const ObjectId id, const DoorShapes& shapes, const btTransform& transform, const UpdateGuard* guard) = 0; /** * @brief updateObject replace object geometry by given data. * @param id is used to find object. * @param shape members must live until object is updated by another shape removed from Navigator. * @param transform allows to setup objects geometry according to its world state. */ virtual void updateObject( const ObjectId id, const ObjectShapes& shapes, const btTransform& transform, const UpdateGuard* guard) = 0; /** * @brief updateObject replace object geometry by given data. * @param id is used to find object. * @param shape members must live until object is updated by another shape removed from Navigator. * @param transform allows to setup objects geometry according to its world state. */ virtual void updateObject( const ObjectId id, const DoorShapes& shapes, const btTransform& transform, const UpdateGuard* guard) = 0; /** * @brief removeObject to make it no more available at the scene. * @param id is used to find object. */ virtual void removeObject(const ObjectId id, const UpdateGuard* guard) = 0; /** * @brief addWater is used to set water level at given world cell. * @param cellPosition allows to distinguish cells if there is many in current world. * @param cellSize set cell borders. std::numeric_limits<int>::max() disables cell borders. * @param shift set global shift of cell center. */ virtual void addWater(const osg::Vec2i& cellPosition, int cellSize, float level, const UpdateGuard* guard) = 0; /** * @brief removeWater to make it no more available at the scene. * @param cellPosition allows to find cell. */ virtual void removeWater(const osg::Vec2i& cellPosition, const UpdateGuard* guard) = 0; virtual void addHeightfield( const osg::Vec2i& cellPosition, int cellSize, const HeightfieldShape& shape, const UpdateGuard* guard) = 0; virtual void removeHeightfield(const osg::Vec2i& cellPosition, const UpdateGuard* guard) = 0; virtual void addPathgrid(const ESM::Cell& cell, const ESM::Pathgrid& pathgrid) = 0; virtual void removePathgrid(const ESM::Pathgrid& pathgrid) = 0; /** * @brief update starts background navmesh update using current scene state. * @param playerPosition setup initial point to order build tiles of navmesh. */ virtual void update(const osg::Vec3f& playerPosition, const UpdateGuard* guard) = 0; /** * @brief wait locks thread until tiles are updated from last update call based on passed condition type. * @param waitConditionType defines when waiting will stop * @param listener optional listener for a progress bar */ virtual void wait(WaitConditionType waitConditionType, Loading::Listener* listener) = 0; /** * @brief getNavMesh returns navmesh for specific agent half extents * @return navmesh */ virtual SharedNavMeshCacheItem getNavMesh(const AgentBounds& agentBounds) const = 0; /** * @brief getNavMeshes returns all current navmeshes * @return map of agent half extents to navmesh */ virtual std::map<AgentBounds, SharedNavMeshCacheItem> getNavMeshes() const = 0; virtual const Settings& getSettings() const = 0; virtual Stats getStats() const = 0; virtual RecastMeshTiles getRecastMeshTiles() const = 0; virtual float getMaxNavmeshAreaRealRadius() const = 0; }; std::unique_ptr<Navigator> makeNavigator(const Settings& settings, const std::filesystem::path& userDataPath); std::unique_ptr<Navigator> makeNavigatorStub(); } #endif
8,275
C++
.h
170
40.394118
120
0.684439
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,699
offmeshconnection.hpp
OpenMW_openmw/components/detournavigator/offmeshconnection.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_OFFMESHCONNECTION_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_OFFMESHCONNECTION_H #include "areatype.hpp" #include <osg/Vec3f> #include <tuple> #include <vector> namespace DetourNavigator { struct OffMeshConnection { osg::Vec3f mStart; osg::Vec3f mEnd; AreaType mAreaType; }; inline bool operator<(const OffMeshConnection& lhs, const OffMeshConnection& rhs) { return std::tie(lhs.mStart, lhs.mEnd, lhs.mAreaType) < std::tie(rhs.mStart, rhs.mEnd, rhs.mAreaType); } } #endif
577
C++
.h
20
24.75
109
0.735027
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,700
findrandompointaroundcircle.hpp
OpenMW_openmw/components/detournavigator/findrandompointaroundcircle.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_FINDRANDOMPOINTAROUNDCIRCLE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_FINDRANDOMPOINTAROUNDCIRCLE_H #include "flags.hpp" #include <osg/Vec3f> #include <optional> class dtNavMeshQuery; namespace DetourNavigator { struct DetourSettings; std::optional<osg::Vec3f> findRandomPointAroundCircle(const dtNavMeshQuery& navMeshQuery, const osg::Vec3f& halfExtents, const osg::Vec3f& start, const float maxRadius, const Flags includeFlags, float (*prng)()); } #endif
532
C++
.h
14
34.785714
112
0.806262
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,701
navmeshcacheitem.hpp
OpenMW_openmw/components/detournavigator/navmeshcacheitem.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHCACHEITEM_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_NAVMESHCACHEITEM_H #include "navmeshdata.hpp" #include "navmeshtilescache.hpp" #include "tileposition.hpp" #include "version.hpp" #include <DetourNavMesh.h> #include <DetourNavMeshQuery.h> #include <iosfwd> #include <map> #include <set> struct dtMeshTile; namespace DetourNavigator { struct Settings; enum class UpdateNavMeshStatus : unsigned { ignored = 0, removed = 1 << 0, added = 1 << 1, replaced = removed | added, failed = 1 << 2, lost = removed | failed, cached = 1 << 3, unchanged = replaced | cached, restored = added | cached, }; inline bool isSuccess(UpdateNavMeshStatus value) { return (static_cast<unsigned>(value) & static_cast<unsigned>(UpdateNavMeshStatus::failed)) == 0; } std::ostream& operator<<(std::ostream& stream, UpdateNavMeshStatus value); class UpdateNavMeshStatusBuilder { public: UpdateNavMeshStatusBuilder() = default; explicit UpdateNavMeshStatusBuilder(UpdateNavMeshStatus value) : mResult(value) { } UpdateNavMeshStatusBuilder removed(bool value) { if (value) set(UpdateNavMeshStatus::removed); else unset(UpdateNavMeshStatus::removed); return *this; } UpdateNavMeshStatusBuilder added(bool value) { if (value) set(UpdateNavMeshStatus::added); else unset(UpdateNavMeshStatus::added); return *this; } UpdateNavMeshStatusBuilder failed(bool value) { if (value) set(UpdateNavMeshStatus::failed); else unset(UpdateNavMeshStatus::failed); return *this; } UpdateNavMeshStatusBuilder cached(bool value) { if (value) set(UpdateNavMeshStatus::cached); else unset(UpdateNavMeshStatus::cached); return *this; } UpdateNavMeshStatus getResult() const { return mResult; } private: UpdateNavMeshStatus mResult = UpdateNavMeshStatus::ignored; void set(UpdateNavMeshStatus value) { mResult = static_cast<UpdateNavMeshStatus>(static_cast<unsigned>(mResult) | static_cast<unsigned>(value)); } void unset(UpdateNavMeshStatus value) { mResult = static_cast<UpdateNavMeshStatus>(static_cast<unsigned>(mResult) & ~static_cast<unsigned>(value)); } }; const dtMeshTile* getTile(const dtNavMesh& navMesh, const TilePosition& position); class NavMeshCacheItem { public: explicit NavMeshCacheItem(std::size_t generation, const Settings& settings); const dtNavMesh& getImpl() const { return mImpl; } dtNavMeshQuery& getQuery() { return mQuery; } const Version& getVersion() const { return mVersion; } UpdateNavMeshStatus updateTile( const TilePosition& position, NavMeshTilesCache::Value&& cached, NavMeshData&& navMeshData); UpdateNavMeshStatus removeTile(const TilePosition& position); UpdateNavMeshStatus markAsEmpty(const TilePosition& position); bool isEmptyTile(const TilePosition& position) const; template <class Function> void forEachUsedTile(Function&& function) const { for (const auto& [position, tile] : mUsedTiles) if (const dtMeshTile* meshTile = getTile(mImpl, position)) function(position, tile.mVersion, *meshTile); } template <class Function> void forEachTilePosition(Function&& function) const { for (const auto& [position, tile] : mUsedTiles) function(position); for (const TilePosition& position : mEmptyTiles) function(position); } private: struct Tile { Version mVersion; NavMeshTilesCache::Value mCached; NavMeshData mData; }; Version mVersion; dtNavMesh mImpl; dtNavMeshQuery mQuery; std::map<TilePosition, Tile> mUsedTiles; std::set<TilePosition> mEmptyTiles; }; } #endif
4,437
C++
.h
127
25.811024
119
0.626695
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,702
recastmesh.hpp
OpenMW_openmw/components/detournavigator/recastmesh.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESH_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESH_H #include "areatype.hpp" #include "objecttransform.hpp" #include "version.hpp" #include <components/resource/bulletshape.hpp> #include <osg/Vec2i> #include <osg/Vec3f> #include <cstdint> #include <memory> #include <numeric> #include <string> #include <tuple> #include <vector> namespace DetourNavigator { class Mesh { public: Mesh(std::vector<int>&& indices, std::vector<float>&& vertices, std::vector<AreaType>&& areaTypes); const std::vector<int>& getIndices() const noexcept { return mIndices; } const std::vector<float>& getVertices() const noexcept { return mVertices; } const std::vector<AreaType>& getAreaTypes() const noexcept { return mAreaTypes; } std::size_t getVerticesCount() const noexcept { return mVertices.size() / 3; } std::size_t getTrianglesCount() const noexcept { return mAreaTypes.size(); } private: std::vector<int> mIndices; std::vector<float> mVertices; std::vector<AreaType> mAreaTypes; friend inline bool operator<(const Mesh& lhs, const Mesh& rhs) noexcept { return std::tie(lhs.mIndices, lhs.mVertices, lhs.mAreaTypes) < std::tie(rhs.mIndices, rhs.mVertices, rhs.mAreaTypes); } friend inline std::size_t getSize(const Mesh& value) noexcept { return value.mIndices.size() * sizeof(int) + value.mVertices.size() * sizeof(float) + value.mAreaTypes.size() * sizeof(AreaType); } }; struct Water { int mCellSize; float mLevel; }; inline bool operator<(const Water& lhs, const Water& rhs) noexcept { const auto tie = [](const Water& v) { return std::tie(v.mCellSize, v.mLevel); }; return tie(lhs) < tie(rhs); } struct CellWater { osg::Vec2i mCellPosition; Water mWater; }; inline bool operator<(const CellWater& lhs, const CellWater& rhs) noexcept { const auto tie = [](const CellWater& v) { return std::tie(v.mCellPosition, v.mWater); }; return tie(lhs) < tie(rhs); } inline osg::Vec2f getWaterShift2d(const osg::Vec2i& cellPosition, int cellSize) { return osg::Vec2f((cellPosition.x() + 0.5f) * cellSize, (cellPosition.y() + 0.5f) * cellSize); } inline osg::Vec3f getWaterShift3d(const osg::Vec2i& cellPosition, int cellSize, float level) { return osg::Vec3f(getWaterShift2d(cellPosition, cellSize), level); } struct Heightfield { osg::Vec2i mCellPosition; int mCellSize; std::uint8_t mLength; float mMinHeight; float mMaxHeight; std::vector<float> mHeights; std::size_t mOriginalSize; std::uint8_t mMinX; std::uint8_t mMinY; }; inline auto makeTuple(const Heightfield& v) noexcept { return std::tie(v.mCellPosition, v.mCellSize, v.mLength, v.mMinHeight, v.mMaxHeight, v.mHeights, v.mOriginalSize, v.mMinX, v.mMinY); } inline bool operator<(const Heightfield& lhs, const Heightfield& rhs) noexcept { return makeTuple(lhs) < makeTuple(rhs); } struct FlatHeightfield { osg::Vec2i mCellPosition; int mCellSize; float mHeight; }; inline bool operator<(const FlatHeightfield& lhs, const FlatHeightfield& rhs) noexcept { const auto tie = [](const FlatHeightfield& v) { return std::tie(v.mCellPosition, v.mCellSize, v.mHeight); }; return tie(lhs) < tie(rhs); } struct MeshSource { osg::ref_ptr<const Resource::BulletShape> mShape; ObjectTransform mObjectTransform; AreaType mAreaType; }; class RecastMesh { public: explicit RecastMesh(const Version& version, Mesh mesh, std::vector<CellWater> water, std::vector<Heightfield> heightfields, std::vector<FlatHeightfield> flatHeightfields, std::vector<MeshSource> sources); const Version& getVersion() const noexcept { return mVersion; } const Mesh& getMesh() const noexcept { return mMesh; } const std::vector<CellWater>& getWater() const { return mWater; } const std::vector<Heightfield>& getHeightfields() const noexcept { return mHeightfields; } const std::vector<FlatHeightfield>& getFlatHeightfields() const noexcept { return mFlatHeightfields; } const std::vector<MeshSource>& getMeshSources() const noexcept { return mMeshSources; } private: Version mVersion; Mesh mMesh; std::vector<CellWater> mWater; std::vector<Heightfield> mHeightfields; std::vector<FlatHeightfield> mFlatHeightfields; std::vector<MeshSource> mMeshSources; friend inline std::size_t getSize(const RecastMesh& value) noexcept { return getSize(value.mMesh) + value.mWater.size() * sizeof(CellWater) + value.mHeightfields.size() * sizeof(Heightfield) + std::accumulate(value.mHeightfields.begin(), value.mHeightfields.end(), std::size_t{ 0 }, [](std::size_t r, const Heightfield& v) { return r + v.mHeights.size() * sizeof(float); }) + value.mFlatHeightfields.size() * sizeof(FlatHeightfield); } }; } #endif
5,425
C++
.h
136
32.514706
116
0.654241
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,703
tileposition.hpp
OpenMW_openmw/components/detournavigator/tileposition.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_TILEPOSITION_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_TILEPOSITION_H #include <osg/Vec2i> namespace DetourNavigator { using TilePosition = osg::Vec2i; } #endif
212
C++
.h
8
24.625
56
0.840796
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,704
recasttempallocator.hpp
OpenMW_openmw/components/detournavigator/recasttempallocator.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTTEMPALLOCATOR_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTTEMPALLOCATOR_H #include "recastallocutils.hpp" #include <RecastAlloc.h> #include <cassert> #include <memory> #include <vector> namespace DetourNavigator { class RecastTempAllocator { public: RecastTempAllocator(std::size_t capacity) : mStack(capacity) , mTop(mStack.data()) , mPrev(nullptr) { } void* alloc(std::size_t size) { std::size_t space = mStack.size() - getUsedSize(); void* top = mTop; const auto itemSize = 2 * sizeof(std::size_t) + size; if (rcUnlikely(!std::align(sizeof(std::size_t), itemSize, top, space))) return nullptr; setTempPtrBufferType(top, BufferType_temp); setTempPtrPrev(top, mPrev); mTop = static_cast<char*>(top) + itemSize; mPrev = static_cast<char*>(top); return getTempPtrDataPtr(top); } void free(void* ptr) { if (rcUnlikely(!ptr)) return; assert(BufferType_temp == getDataPtrBufferType(ptr)); if (!mPrev || getTempDataPtrStackPtr(ptr) != mPrev) { setDataPtrBufferType(ptr, BufferType_unused); return; } mTop = getTempDataPtrStackPtr(ptr); mPrev = getTempPtrPrev(mTop); while (mPrev && BufferType_unused == getTempPtrBufferType(mPrev)) { mTop = mPrev; mPrev = getTempPtrPrev(mTop); } } private: std::vector<char> mStack; void* mTop; void* mPrev; std::size_t getUsedSize() const { return static_cast<std::size_t>(static_cast<char*>(mTop) - mStack.data()); } }; } #endif
1,907
C++
.h
57
23.807018
118
0.569799
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,705
recastmeshobject.hpp
OpenMW_openmw/components/detournavigator/recastmeshobject.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHOBJECT_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHOBJECT_H #include "areatype.hpp" #include "objecttransform.hpp" #include <components/resource/bulletshape.hpp> #include <LinearMath/btTransform.h> #include <osg/ref_ptr> #include <functional> #include <vector> class btCollisionShape; class btCompoundShape; namespace DetourNavigator { class CollisionShape { public: CollisionShape(osg::ref_ptr<const Resource::BulletShapeInstance> instance, const btCollisionShape& shape, const ObjectTransform& transform) : mInstance(std::move(instance)) , mShape(shape) , mObjectTransform(transform) { } const osg::ref_ptr<const Resource::BulletShapeInstance>& getInstance() const { return mInstance; } const btCollisionShape& getShape() const { return mShape; } const ObjectTransform& getObjectTransform() const { return mObjectTransform; } private: osg::ref_ptr<const Resource::BulletShapeInstance> mInstance; std::reference_wrapper<const btCollisionShape> mShape; ObjectTransform mObjectTransform; }; class ChildRecastMeshObject { public: ChildRecastMeshObject(const btCollisionShape& shape, const btTransform& transform, const AreaType areaType); bool update(const btTransform& transform, const AreaType areaType); const btCollisionShape& getShape() const { return mShape; } const btTransform& getTransform() const { return mTransform; } AreaType getAreaType() const { return mAreaType; } private: std::reference_wrapper<const btCollisionShape> mShape; btTransform mTransform; AreaType mAreaType; btVector3 mLocalScaling; std::vector<ChildRecastMeshObject> mChildren; }; class RecastMeshObject { public: RecastMeshObject(const CollisionShape& shape, const btTransform& transform, const AreaType areaType); bool update(const btTransform& transform, const AreaType areaType) { return mImpl.update(transform, areaType); } const osg::ref_ptr<const Resource::BulletShapeInstance>& getInstance() const { return mInstance; } const btCollisionShape& getShape() const { return mImpl.getShape(); } const btTransform& getTransform() const { return mImpl.getTransform(); } AreaType getAreaType() const { return mImpl.getAreaType(); } const ObjectTransform& getObjectTransform() const { return mObjectTransform; } private: osg::ref_ptr<const Resource::BulletShapeInstance> mInstance; ObjectTransform mObjectTransform; ChildRecastMeshObject mImpl; }; } #endif
2,762
C++
.h
63
37.063492
120
0.725607
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,706
bounds.hpp
OpenMW_openmw/components/detournavigator/bounds.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_BOUNDS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_BOUNDS_H #include <osg/Vec3f> namespace DetourNavigator { struct Bounds { osg::Vec3f mMin; osg::Vec3f mMax; }; inline bool isEmpty(const Bounds& value) { return value.mMin == value.mMax; } } #endif
343
C++
.h
16
17.1875
50
0.696594
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,707
status.hpp
OpenMW_openmw/components/detournavigator/status.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_STATUS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_STATUS_H namespace DetourNavigator { enum class Status { Success, PartialPath, NavMeshNotFound, StartPolygonNotFound, EndPolygonNotFound, TargetPolygonNotFound, MoveAlongSurfaceFailed, FindPathOverPolygonsFailed, InitNavMeshQueryFailed, FindStraightPathFailed, }; constexpr const char* getMessage(Status value) { switch (value) { case Status::Success: return "success"; case Status::PartialPath: return "partial path is found"; case Status::NavMeshNotFound: return "navmesh is not found"; case Status::StartPolygonNotFound: return "polygon for start position is not found on navmesh"; case Status::EndPolygonNotFound: return "polygon for end position is not found on navmesh"; case Status::TargetPolygonNotFound: return "polygon for target position is not found on navmesh"; case Status::MoveAlongSurfaceFailed: return "move along surface on navmesh is failed"; case Status::FindPathOverPolygonsFailed: return "path over navmesh polygons is not found"; case Status::InitNavMeshQueryFailed: return "failed to init navmesh query"; case Status::FindStraightPathFailed: return "failed to straight path using polygon path"; } return "unknown error"; } } #endif
1,668
C++
.h
46
26.152174
77
0.630636
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,708
settings.hpp
OpenMW_openmw/components/detournavigator/settings.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_SETTINGS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_SETTINGS_H #include <chrono> #include <string> namespace DetourNavigator { struct RecastSettings { float mCellHeight = 0; float mCellSize = 0; float mDetailSampleDist = 0; float mDetailSampleMaxError = 0; float mMaxClimb = 0; float mMaxSimplificationError = 0; float mMaxSlope = 0; float mRecastScaleFactor = 0; float mSwimHeightScale = 0; int mBorderSize = 0; int mMaxEdgeLen = 0; int mMaxVertsPerPoly = 0; int mRegionMergeArea = 0; int mRegionMinArea = 0; int mTileSize = 0; }; struct DetourSettings { int mMaxPolys = 0; int mMaxNavMeshQueryNodes = 0; std::size_t mMaxPolygonPathSize = 0; std::size_t mMaxSmoothPathSize = 0; }; struct Settings { bool mEnableWriteRecastMeshToFile = false; bool mEnableWriteNavMeshToFile = false; bool mEnableRecastMeshFileNameRevision = false; bool mEnableNavMeshFileNameRevision = false; bool mEnableNavMeshDiskCache = false; bool mWriteToNavMeshDb = false; RecastSettings mRecast; DetourSettings mDetour; int mWaitUntilMinDistanceToPlayer = 0; int mMaxTilesNumber = 0; std::size_t mAsyncNavMeshUpdaterThreads = 0; std::size_t mMaxNavMeshTilesCacheSize = 0; std::string mRecastMeshPathPrefix; std::string mNavMeshPathPrefix; std::chrono::milliseconds mMinUpdateInterval; std::uint64_t mMaxDbFileSize = 0; }; inline constexpr std::int64_t navMeshFormatVersion = 2; Settings makeSettingsFromSettingsManager(); } #endif
1,779
C++
.h
54
25.814815
59
0.675786
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,709
dbrefgeometryobject.hpp
OpenMW_openmw/components/detournavigator/dbrefgeometryobject.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_DBREFGEOMETRYOBJECT_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_DBREFGEOMETRYOBJECT_H #include "objecttransform.hpp" #include "recastmesh.hpp" #include <components/misc/typetraits.hpp> #include <algorithm> #include <cstdint> #include <optional> #include <tuple> #include <type_traits> #include <variant> #include <vector> namespace DetourNavigator { struct DbRefGeometryObject { std::int64_t mShapeId; ObjectTransform mObjectTransform; friend inline auto tie(const DbRefGeometryObject& v) { return std::tie(v.mShapeId, v.mObjectTransform); } friend inline bool operator<(const DbRefGeometryObject& l, const DbRefGeometryObject& r) { return tie(l) < tie(r); } }; template <class ResolveMeshSource> inline auto makeDbRefGeometryObjects( const std::vector<MeshSource>& meshSources, ResolveMeshSource&& resolveMeshSource) -> std::conditional_t<Misc::isOptional<std::decay_t<decltype(resolveMeshSource(meshSources.front()))>>, std::variant<std::vector<DbRefGeometryObject>, MeshSource>, std::vector<DbRefGeometryObject>> { std::vector<DbRefGeometryObject> result; result.reserve(meshSources.size()); for (const MeshSource& meshSource : meshSources) { const auto shapeId = resolveMeshSource(meshSource); if constexpr (Misc::isOptional<std::decay_t<decltype(shapeId)>>) { if (!shapeId.has_value()) return meshSource; result.push_back(DbRefGeometryObject{ *shapeId, meshSource.mObjectTransform }); } else result.push_back(DbRefGeometryObject{ shapeId, meshSource.mObjectTransform }); } std::sort(result.begin(), result.end()); return result; } } #endif
1,895
C++
.h
49
31.387755
113
0.682807
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,710
asyncnavmeshupdater.hpp
OpenMW_openmw/components/detournavigator/asyncnavmeshupdater.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_ASYNCNAVMESHUPDATER_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_ASYNCNAVMESHUPDATER_H #include "agentbounds.hpp" #include "changetype.hpp" #include "guardednavmeshcacheitem.hpp" #include "navmeshcacheitem.hpp" #include "navmeshdb.hpp" #include "navmeshtilescache.hpp" #include "offmeshconnectionsmanager.hpp" #include "sharednavmeshcacheitem.hpp" #include "stats.hpp" #include "tilecachedrecastmeshmanager.hpp" #include "tileposition.hpp" #include "waitconditiontype.hpp" #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/index/rtree.hpp> #include <atomic> #include <chrono> #include <condition_variable> #include <deque> #include <iosfwd> #include <list> #include <memory> #include <mutex> #include <optional> #include <set> #include <thread> #include <tuple> class dtNavMesh; namespace Loading { class Listener; } namespace DetourNavigator { enum class JobState { Initial, WithDbResult, }; struct Job { const std::size_t mId; const AgentBounds mAgentBounds; const std::weak_ptr<GuardedNavMeshCacheItem> mNavMeshCacheItem; const ESM::RefId mWorldspace; const TilePosition mChangedTile; std::chrono::steady_clock::time_point mProcessTime; ChangeType mChangeType; JobState mState = JobState::Initial; std::vector<std::byte> mInput; std::shared_ptr<RecastMesh> mRecastMesh; std::optional<TileData> mCachedTileData; std::unique_ptr<PreparedNavMeshData> mGeneratedNavMeshData; Job(const AgentBounds& agentBounds, std::weak_ptr<GuardedNavMeshCacheItem> navMeshCacheItem, ESM::RefId worldspace, const TilePosition& changedTile, ChangeType changeType, std::chrono::steady_clock::time_point processTime); }; using JobIt = std::list<Job>::iterator; class SpatialJobQueue { public: std::size_t size() const { return mSize; } void clear(); void push(JobIt job); std::optional<JobIt> pop(TilePosition playerTile); void update(TilePosition playerTile, int maxTiles, std::vector<JobIt>& removing); private: using IndexPoint = boost::geometry::model::point<int, 2, boost::geometry::cs::cartesian>; using UpdatingMap = std::map<TilePosition, std::deque<JobIt>>; using IndexValue = std::pair<IndexPoint, UpdatingMap::iterator>; std::size_t mSize = 0; UpdatingMap mValues; boost::geometry::index::rtree<IndexValue, boost::geometry::index::linear<4>> mIndex; }; class JobQueue { public: JobQueueStats getStats() const { return JobQueueStats{ .mRemoving = mRemoving.size(), .mUpdating = mUpdating.size(), .mDelayed = mDelayed.size(), }; } bool hasJob(std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()) const; void clear(); void push(JobIt job, std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()); std::optional<JobIt> pop( TilePosition playerTile, std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()); void update(TilePosition playerTile, int maxTiles, std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()); private: std::vector<JobIt> mRemoving; SpatialJobQueue mUpdating; std::deque<JobIt> mDelayed; }; enum class JobStatus { Done, Fail, MemoryCacheMiss, }; std::ostream& operator<<(std::ostream& stream, JobStatus value); class DbJobQueue { public: void push(JobIt job); std::optional<JobIt> pop(); void update(TilePosition playerTile); void stop(); DbJobQueueStats getStats() const; private: mutable std::mutex mMutex; std::condition_variable mHasJob; SpatialJobQueue mReading; std::deque<JobIt> mWriting; TilePosition mPlayerTile; bool mShouldStop = false; }; class AsyncNavMeshUpdater; class DbWorker { public: DbWorker(AsyncNavMeshUpdater& updater, std::unique_ptr<NavMeshDb>&& db, TileVersion version, const RecastSettings& recastSettings, bool writeToDb); ~DbWorker(); DbWorkerStats getStats() const; void enqueueJob(JobIt job); void update(TilePosition playerTile) { mQueue.update(playerTile); } void stop(); private: AsyncNavMeshUpdater& mUpdater; const RecastSettings& mRecastSettings; const std::unique_ptr<NavMeshDb> mDb; const TileVersion mVersion; bool mWriteToDb; TileId mNextTileId; ShapeId mNextShapeId; DbJobQueue mQueue; std::atomic_bool mShouldStop{ false }; std::atomic_size_t mGetTileCount{ 0 }; std::thread mThread; inline void run() noexcept; inline void processJob(JobIt job); inline void processReadingJob(JobIt job); inline void processWritingJob(JobIt job); }; class AsyncNavMeshUpdater { public: AsyncNavMeshUpdater(const Settings& settings, TileCachedRecastMeshManager& recastMeshManager, OffMeshConnectionsManager& offMeshConnectionsManager, std::unique_ptr<NavMeshDb>&& db); ~AsyncNavMeshUpdater(); void post(const AgentBounds& agentBounds, const SharedNavMeshCacheItem& navMeshCacheItem, const TilePosition& playerTile, ESM::RefId worldspace, const std::map<TilePosition, ChangeType>& changedTiles); void wait(WaitConditionType waitConditionType, Loading::Listener* listener); void stop(); AsyncNavMeshUpdaterStats getStats() const; void enqueueJob(JobIt job); void removeJob(JobIt job); private: std::reference_wrapper<const Settings> mSettings; std::reference_wrapper<TileCachedRecastMeshManager> mRecastMeshManager; std::reference_wrapper<OffMeshConnectionsManager> mOffMeshConnectionsManager; std::atomic_bool mShouldStop; mutable std::mutex mMutex; std::condition_variable mHasJob; std::condition_variable mDone; std::condition_variable mProcessed; std::list<Job> mJobs; JobQueue mWaiting; std::set<std::tuple<AgentBounds, TilePosition>> mPushed; Misc::ScopeGuarded<TilePosition> mPlayerTile; NavMeshTilesCache mNavMeshTilesCache; Misc::ScopeGuarded<std::set<std::tuple<AgentBounds, TilePosition>>> mProcessingTiles; std::map<std::tuple<AgentBounds, TilePosition>, std::chrono::steady_clock::time_point> mLastUpdates; std::set<std::tuple<AgentBounds, TilePosition>> mPresentTiles; std::vector<std::thread> mThreads; std::unique_ptr<DbWorker> mDbWorker; std::atomic_size_t mDbGetTileHits{ 0 }; void process() noexcept; JobStatus processJob(Job& job); inline JobStatus processInitialJob(Job& job, GuardedNavMeshCacheItem& navMeshCacheItem); inline JobStatus processJobWithDbResult(Job& job, GuardedNavMeshCacheItem& navMeshCacheItem); inline JobStatus handleUpdateNavMeshStatus(UpdateNavMeshStatus status, const Job& job, const GuardedNavMeshCacheItem& navMeshCacheItem, const RecastMesh& recastMesh); JobIt getNextJob(); void postThreadJob(JobIt job, std::deque<JobIt>& queue); void writeDebugFiles(const Job& job, const RecastMesh* recastMesh) const; bool lockTile(std::size_t jobId, const AgentBounds& agentBounds, const TilePosition& changedTile); void unlockTile(std::size_t jobId, const AgentBounds& agentBounds, const TilePosition& changedTile); inline std::size_t getTotalJobs() const; void cleanupLastUpdates(); inline void waitUntilJobsDoneForNotPresentTiles(Loading::Listener* listener); inline void waitUntilAllJobsDone(); }; } #endif
8,133
C++
.h
201
32.985075
115
0.690821
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,711
recastcontext.hpp
OpenMW_openmw/components/detournavigator/recastcontext.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTCONTEXT_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTCONTEXT_H #include "tileposition.hpp" #include <components/esm/refid.hpp> #include <string> #include <Recast.h> namespace DetourNavigator { struct AgentBounds; class RecastContext final : public rcContext { public: explicit RecastContext(ESM::RefId worldspace, const TilePosition& tilePosition, const AgentBounds& agentBounds); const std::string& getPrefix() const { return mPrefix; } private: std::string mPrefix; void doLog(rcLogCategory category, const char* msg, int len) override; }; } #endif
670
C++
.h
20
29.2
120
0.75625
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,712
collisionshapetype.hpp
OpenMW_openmw/components/detournavigator/collisionshapetype.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_COLLISIONSHAPETYPE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_COLLISIONSHAPETYPE_H #include <cstdint> namespace DetourNavigator { enum class CollisionShapeType : std::uint8_t { Aabb = 0, RotatingBox = 1, Cylinder = 2, }; CollisionShapeType toCollisionShapeType(int value); } #endif
369
C++
.h
14
22.214286
62
0.749288
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,713
areatype.hpp
OpenMW_openmw/components/detournavigator/areatype.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_AREATYPE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_AREATYPE_H #include <Recast.h> namespace DetourNavigator { enum AreaType : unsigned char { AreaType_null = RC_NULL_AREA, AreaType_water, AreaType_door, AreaType_pathgrid, AreaType_ground = RC_WALKABLE_AREA, }; struct AreaCosts { float mWater = 1.0f; float mDoor = 2.0f; float mPathgrid = 1.0f; float mGround = 1.0f; }; } #endif
523
C++
.h
22
18.227273
52
0.651911
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,714
guardednavmeshcacheitem.hpp
OpenMW_openmw/components/detournavigator/guardednavmeshcacheitem.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_GUARDEDNAVMESHCACHEITEM_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_GUARDEDNAVMESHCACHEITEM_H namespace Misc { template <class T> class ScopeGuarded; } namespace DetourNavigator { class NavMeshCacheItem; using GuardedNavMeshCacheItem = Misc::ScopeGuarded<NavMeshCacheItem>; } #endif
345
C++
.h
13
24
73
0.841463
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,715
tilebounds.hpp
OpenMW_openmw/components/detournavigator/tilebounds.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_TILEBOUNDS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_TILEBOUNDS_H #include <components/misc/convert.hpp> #include <osg/Vec2f> #include <osg/Vec2i> #include <BulletCollision/CollisionShapes/btCollisionShape.h> #include <LinearMath/btTransform.h> #include <algorithm> #include <optional> #include <tuple> namespace DetourNavigator { struct TileBounds { osg::Vec2f mMin; osg::Vec2f mMax; }; inline auto tie(const TileBounds& value) noexcept { return std::tie(value.mMin, value.mMax); } inline bool operator<(const TileBounds& lhs, const TileBounds& rhs) noexcept { return tie(lhs) < tie(rhs); } inline bool operator==(const TileBounds& lhs, const TileBounds& rhs) noexcept { return tie(lhs) == tie(rhs); } inline bool operator!=(const TileBounds& lhs, const TileBounds& rhs) noexcept { return !(lhs == rhs); } inline std::optional<TileBounds> getIntersection(const TileBounds& a, const TileBounds& b) noexcept { const float minX = std::max(a.mMin.x(), b.mMin.x()); const float maxX = std::min(a.mMax.x(), b.mMax.x()); if (minX > maxX) return std::nullopt; const float minY = std::max(a.mMin.y(), b.mMin.y()); const float maxY = std::min(a.mMax.y(), b.mMax.y()); if (minY > maxY) return std::nullopt; return TileBounds{ osg::Vec2f(minX, minY), osg::Vec2f(maxX, maxY) }; } inline TileBounds maxCellTileBounds(const osg::Vec2i& position, int size) { return TileBounds{ osg::Vec2f(position.x(), position.y()) * size, osg::Vec2f(position.x() + 1, position.y() + 1) * size }; } inline TileBounds makeObjectTileBounds(const btCollisionShape& shape, const btTransform& transform) { btVector3 aabbMin; btVector3 aabbMax; shape.getAabb(transform, aabbMin, aabbMax); return TileBounds{ Misc::Convert::toOsgXY(aabbMin), Misc::Convert::toOsgXY(aabbMax) }; } } #endif
2,084
C++
.h
59
29.423729
103
0.659046
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,716
stats.hpp
OpenMW_openmw/components/detournavigator/stats.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_STATS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_STATS_H #include <cstddef> #include <optional> namespace osg { class Stats; } namespace DetourNavigator { struct JobQueueStats { std::size_t mRemoving = 0; std::size_t mUpdating = 0; std::size_t mDelayed = 0; }; struct DbJobQueueStats { std::size_t mReadingJobs = 0; std::size_t mWritingJobs = 0; }; struct DbWorkerStats { DbJobQueueStats mJobs; std::size_t mGetTileCount = 0; }; struct NavMeshTilesCacheStats { std::size_t mNavMeshCacheSize = 0; std::size_t mUsedNavMeshTiles = 0; std::size_t mCachedNavMeshTiles = 0; std::size_t mHitCount = 0; std::size_t mGetCount = 0; }; struct AsyncNavMeshUpdaterStats { std::size_t mJobs = 0; JobQueueStats mWaiting; std::size_t mPushed = 0; std::size_t mProcessing = 0; std::size_t mDbGetTileHits = 0; std::optional<DbWorkerStats> mDb; NavMeshTilesCacheStats mCache; }; struct TileCachedRecastMeshManagerStats { std::size_t mTiles = 0; std::size_t mObjects = 0; std::size_t mHeightfields = 0; std::size_t mWater = 0; }; struct Stats { AsyncNavMeshUpdaterStats mUpdater; TileCachedRecastMeshManagerStats mRecast; }; void reportStats(const Stats& stats, unsigned int frameNumber, osg::Stats& out); } #endif
1,541
C++
.h
59
19.983051
84
0.636982
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,717
gettilespositions.hpp
OpenMW_openmw/components/detournavigator/gettilespositions.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_GETTILESPOSITIONS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_GETTILESPOSITIONS_H #include "tilebounds.hpp" #include "tileposition.hpp" #include "tilespositionsrange.hpp" class btVector3; class btTransform; class btCollisionShape; namespace osg { class Vec2f; } namespace DetourNavigator { struct RecastSettings; TilesPositionsRange makeTilesPositionsRange( const osg::Vec2f& aabbMin, const osg::Vec2f& aabbMax, const RecastSettings& settings); TilesPositionsRange makeTilesPositionsRange( const btCollisionShape& shape, const btTransform& transform, const RecastSettings& settings); TilesPositionsRange makeTilesPositionsRange(const btCollisionShape& shape, const btTransform& transform, const TileBounds& bounds, const RecastSettings& settings); TilesPositionsRange makeTilesPositionsRange( const int cellSize, const btVector3& shift, const RecastSettings& settings); template <class Callback> inline void getTilesPositions(const TilesPositionsRange& range, Callback&& callback) { for (int tileX = range.mBegin.x(); tileX < range.mEnd.x(); ++tileX) for (int tileY = range.mBegin.y(); tileY < range.mEnd.y(); ++tileY) callback(TilePosition{ tileX, tileY }); } inline bool isInTilesPositionsRange(int begin, int end, int coordinate) { return begin <= coordinate && coordinate < end; } inline bool isInTilesPositionsRange(const TilesPositionsRange& range, const TilePosition& position) { return isInTilesPositionsRange(range.mBegin.x(), range.mEnd.x(), position.x()) && isInTilesPositionsRange(range.mBegin.y(), range.mEnd.y(), position.y()); } TilesPositionsRange getIntersection(const TilesPositionsRange& a, const TilesPositionsRange& b) noexcept; TilesPositionsRange getUnion(const TilesPositionsRange& a, const TilesPositionsRange& b) noexcept; } #endif
1,982
C++
.h
43
40.860465
109
0.757403
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,718
offmeshconnectionsmanager.hpp
OpenMW_openmw/components/detournavigator/offmeshconnectionsmanager.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_OFFMESHCONNECTIONSMANAGER_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_OFFMESHCONNECTIONSMANAGER_H #include "objectid.hpp" #include "offmeshconnection.hpp" #include "settings.hpp" #include "tileposition.hpp" #include <components/misc/guarded.hpp> #include <map> #include <set> #include <unordered_set> #include <vector> namespace DetourNavigator { class OffMeshConnectionsManager { public: explicit OffMeshConnectionsManager(const RecastSettings& settings); void add(const ObjectId id, const OffMeshConnection& value); std::set<TilePosition> remove(const ObjectId id); std::vector<OffMeshConnection> get(const TilePosition& tilePosition) const; private: struct Values { std::multimap<ObjectId, OffMeshConnection> mById; std::map<TilePosition, std::unordered_set<ObjectId>> mByTilePosition; }; const RecastSettings& mSettings; Misc::ScopeGuarded<Values> mValues; }; } #endif
1,041
C++
.h
31
28.516129
83
0.743
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,719
raycast.hpp
OpenMW_openmw/components/detournavigator/raycast.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RAYCAST_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RAYCAST_H #include "flags.hpp" #include <optional> #include <osg/Vec3f> class dtNavMeshQuery; namespace DetourNavigator { struct DetourSettings; std::optional<osg::Vec3f> raycast(const dtNavMeshQuery& navMeshQuery, const osg::Vec3f& halfExtents, const osg::Vec3f& start, const osg::Vec3f& end, const Flags includeFlags); } #endif
446
C++
.h
13
31.615385
104
0.796253
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,720
agentbounds.hpp
OpenMW_openmw/components/detournavigator/agentbounds.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_AGENTBOUNDS_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_AGENTBOUNDS_H #include "collisionshapetype.hpp" #include <osg/Vec3f> #include <tuple> namespace DetourNavigator { struct AgentBounds { CollisionShapeType mShapeType; osg::Vec3f mHalfExtents; }; inline auto tie(const AgentBounds& value) { return std::tie(value.mShapeType, value.mHalfExtents); } inline bool operator==(const AgentBounds& lhs, const AgentBounds& rhs) { return tie(lhs) == tie(rhs); } inline bool operator<(const AgentBounds& lhs, const AgentBounds& rhs) { return tie(lhs) < tie(rhs); } } #endif
704
C++
.h
26
22.384615
74
0.70597
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,721
commulativeaabb.hpp
OpenMW_openmw/components/detournavigator/commulativeaabb.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_COMMULATIVEAABB_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_COMMULATIVEAABB_H #include <BulletCollision/Gimpact/btBoxCollision.h> #include <cstddef> namespace DetourNavigator { class CommulativeAabb { public: explicit CommulativeAabb(std::size_t lastChangeRevision, const btAABB& aabb); bool update(std::size_t lastChangeRevision, const btAABB& aabb); private: std::size_t mLastChangeRevision; btAABB mAabb; }; } #endif
520
C++
.h
17
26.176471
85
0.762575
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,722
recastglobalallocator.hpp
OpenMW_openmw/components/detournavigator/recastglobalallocator.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTGLOBALALLOCATOR_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTGLOBALALLOCATOR_H #include "recasttempallocator.hpp" #include <DetourAlloc.h> #include <RecastAlloc.h> #include <cstdlib> namespace DetourNavigator { class RecastGlobalAllocator { public: static void init() { instance(); } static void* recastAlloc(size_t size, rcAllocHint hint) { return alloc(size, hint == RC_ALLOC_TEMP); } static void* detourAlloc(size_t size, dtAllocHint hint) { return alloc(size, hint == DT_ALLOC_TEMP); } static void* alloc(size_t size, bool temp) { void* result = nullptr; if (rcLikely(temp)) result = tempAllocator().alloc(size); if (rcUnlikely(!result)) result = allocPerm(size); return result; } static void free(void* ptr) { if (rcUnlikely(!ptr)) return; if (rcLikely(BufferType_temp == getDataPtrBufferType(ptr))) tempAllocator().free(ptr); else { assert(BufferType_perm == getDataPtrBufferType(ptr)); std::free(getPermDataPtrHeapPtr(ptr)); } } private: RecastGlobalAllocator() { rcAllocSetCustom(&RecastGlobalAllocator::recastAlloc, &RecastGlobalAllocator::free); dtAllocSetCustom(&RecastGlobalAllocator::detourAlloc, &RecastGlobalAllocator::free); } static RecastGlobalAllocator& instance() { static RecastGlobalAllocator value; return value; } static RecastTempAllocator& tempAllocator() { static thread_local RecastTempAllocator value(1024ul * 1024ul); return value; } static void* allocPerm(size_t size) { const auto ptr = std::malloc(size + sizeof(std::size_t)); if (rcUnlikely(!ptr)) return ptr; setPermPtrBufferType(ptr, BufferType_perm); return getPermPtrDataPtr(ptr); } }; } #endif
2,177
C++
.h
62
25.387097
110
0.602759
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,723
heightfieldshape.hpp
OpenMW_openmw/components/detournavigator/heightfieldshape.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_HEIGHFIELDSHAPE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_HEIGHFIELDSHAPE_H #include <components/bullethelpers/heightfield.hpp> #include <osg/Vec2i> #include <cstddef> #include <variant> namespace DetourNavigator { struct HeightfieldPlane { float mHeight; }; struct HeightfieldSurface { const float* mHeights; std::size_t mSize; float mMinHeight; float mMaxHeight; }; using HeightfieldShape = std::variant<HeightfieldPlane, HeightfieldSurface>; inline btVector3 getHeightfieldShift(const HeightfieldPlane& v, const osg::Vec2i& cellPosition, int cellSize) { return BulletHelpers::getHeightfieldShift(cellPosition.x(), cellPosition.y(), cellSize, v.mHeight, v.mHeight); } inline btVector3 getHeightfieldShift(const HeightfieldSurface& v, const osg::Vec2i& cellPosition, int cellSize) { return BulletHelpers::getHeightfieldShift( cellPosition.x(), cellPosition.y(), cellSize, v.mMinHeight, v.mMaxHeight); } inline btVector3 getHeightfieldShift(const HeightfieldShape& v, const osg::Vec2i& cellPosition, int cellSize) { return std::visit([&](const auto& w) { return getHeightfieldShift(w, cellPosition, cellSize); }, v); } } #endif
1,322
C++
.h
35
32.485714
118
0.733751
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,724
recastmeshtiles.hpp
OpenMW_openmw/components/detournavigator/recastmeshtiles.hpp
#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHTILE_H #define OPENMW_COMPONENTS_DETOURNAVIGATOR_RECASTMESHTILE_H #include "tileposition.hpp" #include <map> #include <memory> namespace DetourNavigator { class RecastMesh; using RecastMeshTiles = std::map<TilePosition, std::shared_ptr<RecastMesh>>; } #endif
324
C++
.h
11
27.272727
80
0.821429
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,725
compositemaprenderer.hpp
OpenMW_openmw/components/terrain/compositemaprenderer.hpp
#ifndef OPENMW_COMPONENTS_TERRAIN_COMPOSITEMAPRENDERER_H #define OPENMW_COMPONENTS_TERRAIN_COMPOSITEMAPRENDERER_H #include <osg/Drawable> #include <mutex> #include <set> namespace osg { class FrameBufferObject; class RenderInfo; class Texture2D; } namespace Terrain { class CompositeMap : public osg::Referenced { public: CompositeMap(); ~CompositeMap(); std::vector<osg::ref_ptr<osg::Drawable>> mDrawables; osg::ref_ptr<osg::Texture2D> mTexture; unsigned int mCompiled; }; /** * @brief The CompositeMapRenderer is responsible for updating composite map textures in a blocking or non-blocking * way. */ class CompositeMapRenderer : public osg::Drawable { public: CompositeMapRenderer(); ~CompositeMapRenderer(); void drawImplementation(osg::RenderInfo& renderInfo) const override; void compile(CompositeMap& compositeMap, osg::RenderInfo& renderInfo) const; /// Set the available time in seconds for compiling (non-immediate) composite maps each frame void setMinimumTimeAvailableForCompile(double time); /// If current frame rate is higher than this, the extra time will be set aside to do more compiling void setTargetFrameRate(float framerate); /// Add a composite map to be rendered void addCompositeMap(CompositeMap* map, bool immediate = false); /// Mark this composite map to be required for the current frame void setImmediate(CompositeMap* map); unsigned int getCompileSetSize() const; private: float mTargetFrameRate; double mMinimumTimeAvailable; mutable osg::Timer mTimer; typedef std::set<osg::ref_ptr<CompositeMap>> CompileSet; mutable CompileSet mCompileSet; mutable CompileSet mImmediateCompileSet; mutable std::mutex mMutex; osg::ref_ptr<osg::FrameBufferObject> mFBO; }; } #endif
1,992
C++
.h
54
30.425926
119
0.705422
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,726
texturemanager.hpp
OpenMW_openmw/components/terrain/texturemanager.hpp
#ifndef OPENMW_COMPONENTS_TERRAIN_TEXTUREMANAGER_H #define OPENMW_COMPONENTS_TERRAIN_TEXTUREMANAGER_H #include <components/resource/resourcemanager.hpp> #include <components/vfs/pathutil.hpp> namespace Resource { class SceneManager; } namespace osg { class Texture2D; } namespace Terrain { class TextureManager : public Resource::ResourceManager { public: explicit TextureManager(Resource::SceneManager* sceneMgr, double expiryDelay); void updateTextureFiltering(); osg::ref_ptr<osg::Texture2D> getTexture(VFS::Path::NormalizedView name); void reportStats(unsigned int frameNumber, osg::Stats* stats) const override; private: Resource::SceneManager* mSceneManager; }; } #endif
756
C++
.h
26
25.038462
86
0.763561
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,727
view.hpp
OpenMW_openmw/components/terrain/view.hpp
#ifndef COMPONENTS_TERRAIN_VIEW_H #define COMPONENTS_TERRAIN_VIEW_H #include <osg/Referenced> namespace Terrain { /** * @brief A View is a collection of rendering objects that are visible from a given camera/intersection. * The base View class is part of the interface for usage in conjunction with preload feature. */ class View : public osg::Referenced { public: virtual ~View() {} /// Reset internal structure so that the next addition to the view will override the previous frame's contents. virtual void reset() = 0; }; } #endif
598
C++
.h
18
28.666667
119
0.706087
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,728
defs.hpp
OpenMW_openmw/components/terrain/defs.hpp
#ifndef COMPONENTS_TERRAIN_DEFS_HPP #define COMPONENTS_TERRAIN_DEFS_HPP #include <components/vfs/pathutil.hpp> namespace Terrain { enum Direction { North = 0, East = 1, South = 2, West = 3 }; struct LayerInfo { VFS::Path::Normalized mDiffuseMap; VFS::Path::Normalized mNormalMap; bool mParallax; // Height info in normal map alpha channel? bool mSpecular; // Specular info in diffuse map alpha channel? bool requiresShaders() const { return !mNormalMap.empty() || mSpecular; } }; } #endif
592
C++
.h
22
21.227273
81
0.650089
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,729
terraindrawable.hpp
OpenMW_openmw/components/terrain/terraindrawable.hpp
#ifndef OPENMW_COMPONENTS_TERRAIN_DRAWABLE_H #define OPENMW_COMPONENTS_TERRAIN_DRAWABLE_H #include <osg/Geometry> namespace osg { class ClusterCullingCallback; } namespace osgUtil { class CullVisitor; } namespace SceneUtil { class LightListCallback; } namespace Terrain { class CompositeMap; class CompositeMapRenderer; /** * Subclass of Geometry that supports built in multi-pass rendering and built in LightListCallback. */ class TerrainDrawable : public osg::Geometry { public: osg::Object* cloneType() const override { return new TerrainDrawable(); } osg::Object* clone(const osg::CopyOp& copyop) const override { return new TerrainDrawable(*this, copyop); } bool isSameKindAs(const osg::Object* obj) const override { return dynamic_cast<const TerrainDrawable*>(obj) != nullptr; } const char* className() const override { return "TerrainDrawable"; } const char* libraryName() const override { return "Terrain"; } TerrainDrawable(); ~TerrainDrawable(); // has to be defined in the cpp file because we only forward declared some members. TerrainDrawable(const TerrainDrawable& copy, const osg::CopyOp& copyop); void accept(osg::NodeVisitor& nv) override; void cull(osgUtil::CullVisitor* cv); typedef std::vector<osg::ref_ptr<osg::StateSet>> PassVector; void setPasses(const PassVector& passes); const PassVector& getPasses() const { return mPasses; } void setLightListCallback(SceneUtil::LightListCallback* lightListCallback); void createClusterCullingCallback(); void compileGLObjects(osg::RenderInfo& renderInfo) const override; void setupWaterBoundingBox(float waterheight, float margin); const osg::BoundingBox& getWaterBoundingBox() const { return mWaterBoundingBox; } void setCompositeMap(CompositeMap* map) { mCompositeMap = map; } CompositeMap* getCompositeMap() const { return mCompositeMap; } void setCompositeMapRenderer(CompositeMapRenderer* renderer) { mCompositeMapRenderer = renderer; } private: osg::BoundingBox mWaterBoundingBox; PassVector mPasses; osg::ref_ptr<osg::ClusterCullingCallback> mClusterCullingCallback; osg::ref_ptr<SceneUtil::LightListCallback> mLightListCallback; osg::ref_ptr<CompositeMap> mCompositeMap; osg::ref_ptr<CompositeMapRenderer> mCompositeMapRenderer; }; } #endif
2,529
C++
.h
59
36.474576
115
0.720408
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,730
storage.hpp
OpenMW_openmw/components/terrain/storage.hpp
#ifndef COMPONENTS_TERRAIN_STORAGE_H #define COMPONENTS_TERRAIN_STORAGE_H #include <vector> #include <osg/Array> #include <osg/Vec2f> #include <osg/Vec3f> #include <osg/ref_ptr> #include <components/esm/exteriorcelllocation.hpp> #include <components/esm/refid.hpp> #include "defs.hpp" namespace osg { class Image; } namespace Terrain { /// We keep storage of terrain data abstract here since we need different implementations for game and editor /// @note The implementation must be thread safe. class Storage { public: virtual ~Storage() {} public: /// Get bounds of the whole terrain in cell units virtual void getBounds(float& minX, float& maxX, float& minY, float& maxY, ESM::RefId worldspace) = 0; /// Return true if there is land data for this cell /// May be overriden for a faster implementation virtual bool hasData(ESM::ExteriorCellLocation cellLocation) { float dummy; return getMinMaxHeights( 1, osg::Vec2f(cellLocation.mX + 0.5, cellLocation.mY + 0.5), cellLocation.mWorldspace, dummy, dummy); } /// Get the minimum and maximum heights of a terrain region. /// @note Will only be called for chunks with size = minBatchSize, i.e. leafs of the quad tree. /// Larger chunks can simply merge AABB of children. /// @param size size of the chunk in cell units /// @param center center of the chunk in cell units /// @param min min height will be stored here /// @param max max height will be stored here /// @return true if there was data available for this terrain chunk virtual bool getMinMaxHeights( float size, const osg::Vec2f& center, ESM::RefId worldspace, float& min, float& max) = 0; /// Fill vertex buffers for a terrain chunk. /// @note May be called from background threads. Make sure to only call thread-safe functions from here! /// @note returned colors need to be in render-system specific format! Use RenderSystem::convertColourValue. /// @note Vertices should be written in row-major order (a row is defined as parallel to the x-axis). /// The specified positions should be in local space, i.e. relative to the center of the terrain chunk. /// @param lodLevel LOD level, 0 = most detailed /// @param size size of the terrain chunk in cell units /// @param center center of the chunk in cell units /// @param positions buffer to write vertices /// @param normals buffer to write vertex normals /// @param colours buffer to write vertex colours virtual void fillVertexBuffers(int lodLevel, float size, const osg::Vec2f& center, ESM::RefId worldspace, osg::Vec3Array& positions, osg::Vec3Array& normals, osg::Vec4ubArray& colours) = 0; typedef std::vector<osg::ref_ptr<osg::Image>> ImageVector; /// Create textures holding layer blend values for a terrain chunk. /// @note The terrain chunk shouldn't be larger than one cell since otherwise we might /// have to do a ridiculous amount of different layers. For larger chunks, composite maps should be used. /// @note May be called from background threads. Make sure to only call thread-safe functions from here! /// @param chunkSize size of the terrain chunk in cell units /// @param chunkCenter center of the chunk in cell units /// @param blendmaps created blendmaps will be written here /// @param layerList names of the layer textures used will be written here virtual void getBlendmaps(float chunkSize, const osg::Vec2f& chunkCenter, ImageVector& blendmaps, std::vector<LayerInfo>& layerList, ESM::RefId worldspace) = 0; virtual float getHeightAt(const osg::Vec3f& worldPos, ESM::RefId worldspace) = 0; /// Get the transformation factor for mapping cell units to world units. virtual float getCellWorldSize(ESM::RefId worldspace) = 0; /// Get the number of vertices on one side for each cell. Should be (power of two)+1 virtual int getCellVertices(ESM::RefId worldspace) = 0; virtual int getBlendmapScale(float chunkSize) = 0; }; } #endif
4,355
C++
.h
79
47.531646
119
0.680207
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,731
world.hpp
OpenMW_openmw/components/terrain/world.hpp
#ifndef COMPONENTS_TERRAIN_WORLD_H #define COMPONENTS_TERRAIN_WORLD_H #include <osg/Referenced> #include <osg/Vec3f> #include <osg/ref_ptr> #include <memory> #include <set> #include <components/esm/refid.hpp> #include "cellborder.hpp" namespace osg { class Group; class Stats; } namespace Resource { class ResourceSystem; } namespace Loading { class Reporter; } namespace Terrain { class Storage; class TextureManager; class ChunkManager; class CompositeMapRenderer; class View; class HeightCullCallback; /** * @brief The basic interface for a terrain world. How the terrain chunks are paged and displayed * is up to the implementation. */ class World { public: /// @note takes ownership of \a storage /// @param storage Storage instance to get terrain data from (heights, normals, colors, textures..) /// @param nodeMask mask for the terrain root /// @param preCompileMask mask for pre compiling textures explicit World(osg::Group* parent, osg::Group* compileRoot, Resource::ResourceSystem* resourceSystem, Storage* storage, unsigned int nodeMask, unsigned int preCompileMask, unsigned int borderMask, ESM::RefId worldspace, double expiryDelay); World(osg::Group* parent, Storage* storage, unsigned int nodeMask, ESM::RefId worldspace); virtual ~World(); /// See CompositeMapRenderer::setTargetFrameRate void setTargetFrameRate(float rate); /// Apply the scene manager's texture filtering settings to all cached textures. /// @note Thread safe. void updateTextureFiltering(); float getHeightAt(const osg::Vec3f& worldPos); /// Clears the cached land and landtexture data. /// @note Thread safe. virtual void clearAssociatedCaches(); /// Load a terrain cell and store it in the View for later use. /// @note Thread safe. virtual void cacheCell(View* view, int x, int y) {} /// Load the cell into the scene graph. /// @note Not thread safe. virtual void loadCell(int x, int y); /// Remove the cell from the scene graph. /// @note Not thread safe. virtual void unloadCell(int x, int y); virtual void enable(bool enabled) {} virtual void setBordersVisible(bool visible); virtual bool getBordersVisible() { return mBorderVisible; } /// Create a View to use with preload feature. The caller is responsible for deleting the view. /// @note Thread safe. virtual View* createView() { return nullptr; } /// @note Thread safe, as long as you do not attempt to load into the same view from multiple threads. virtual void preload(View* view, const osg::Vec3f& viewPoint, const osg::Vec4i& cellgrid, std::atomic<bool>& abort, Loading::Reporter& reporter) { } virtual void rebuildViews() {} virtual void reportStats(unsigned int frameNumber, osg::Stats* stats) {} virtual void setViewDistance(float distance) {} ESM::RefId getWorldspace() { return mWorldspace; } Storage* getStorage() { return mStorage; } void enableHeightCullCallback(bool enable); osg::Callback* getHeightCullCallback(float highz, unsigned int mask); void setActiveGrid(const osg::Vec4i& grid) { mActiveGrid = grid; } protected: Storage* mStorage; osg::ref_ptr<osg::Group> mParent; osg::ref_ptr<osg::Group> mTerrainRoot; osg::ref_ptr<osg::Group> mCompositeMapCamera; osg::ref_ptr<CompositeMapRenderer> mCompositeMapRenderer; Resource::ResourceSystem* mResourceSystem; std::unique_ptr<TextureManager> mTextureManager; std::unique_ptr<ChunkManager> mChunkManager; std::unique_ptr<CellBorder> mCellBorder; bool mBorderVisible; std::set<std::pair<int, int>> mLoadedCells; osg::ref_ptr<HeightCullCallback> mHeightCullCallback; osg::Vec4i mActiveGrid; ESM::RefId mWorldspace; }; } #endif
4,148
C++
.h
101
34.029703
110
0.678643
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,732
viewdata.hpp
OpenMW_openmw/components/terrain/viewdata.hpp
#ifndef OPENMW_COMPONENTS_TERRAIN_VIEWDATA_H #define OPENMW_COMPONENTS_TERRAIN_VIEWDATA_H #include <deque> #include <vector> #include <osg/Node> #include "view.hpp" namespace Terrain { class QuadTreeNode; struct ViewDataEntry { ViewDataEntry(); bool set(QuadTreeNode* node); QuadTreeNode* mNode; unsigned int mLodFlags; osg::ref_ptr<osg::Node> mRenderingNode; }; class ViewData : public View { public: ViewData(); ~ViewData(); void add(QuadTreeNode* node); void reset() override; bool suitableToUse(const osg::Vec4i& activeGrid) const; void clear(); bool contains(const QuadTreeNode* node) const; void copyFrom(const ViewData& other); unsigned int getNumEntries() const { return mNumEntries; } ViewDataEntry& getEntry(unsigned int i) { return mEntries[i]; } double getLastUsageTimeStamp() const { return mLastUsageTimeStamp; } void setLastUsageTimeStamp(double timeStamp) { mLastUsageTimeStamp = timeStamp; } /// Indicates at least one mNode of mEntries has changed. /// @note Such changes may necessitate a revalidation of cached mRenderingNodes elsewhere depending /// on the parameters that affect the creation of mRenderingNode. bool hasChanged() const { return mChanged; } void resetChanged() { mChanged = false; } bool hasViewPoint() const { return mHasViewPoint; } void setViewPoint(const osg::Vec3f& viewPoint); const osg::Vec3f& getViewPoint() const { return mViewPoint; } void setActiveGrid(const osg::Vec4i& grid) { if (grid != mActiveGrid) { mActiveGrid = grid; mEntries.clear(); mNumEntries = 0; mNodes.clear(); } } unsigned int getWorldUpdateRevision() const { return mWorldUpdateRevision; } void setWorldUpdateRevision(int updateRevision) { mWorldUpdateRevision = updateRevision; } void buildNodeIndex(); void removeNodeFromIndex(const QuadTreeNode* node); private: std::vector<ViewDataEntry> mEntries; std::vector<const QuadTreeNode*> mNodes; unsigned int mNumEntries; double mLastUsageTimeStamp; bool mChanged; osg::Vec3f mViewPoint; bool mHasViewPoint; osg::Vec4i mActiveGrid; unsigned int mWorldUpdateRevision; }; class ViewDataMap : public osg::Referenced { public: ViewDataMap() : mReuseDistance( 150) // large value should be safe because the visibility of each node is still updated individually for // each camera even if the base view was reused. this value also serves as a threshold for when a // newly loaded LOD gets unloaded again so that if you hover around an LOD transition point the // LODs won't keep loading and unloading all the time. , mExpiryDelay(1.f) , mWorldUpdateRevision(0) { } ViewData* getViewData( osg::Object* viewer, const osg::Vec3f& viewPoint, const osg::Vec4i& activeGrid, bool& needsUpdate); ViewData* createOrReuseView(); ViewData* createIndependentView() const; void clearUnusedViews(double referenceTime); void rebuildViews(); float getReuseDistance() const { return mReuseDistance; } private: std::list<ViewData> mViewVector; typedef std::map<osg::ref_ptr<osg::Object>, ViewData*> ViewerMap; ViewerMap mViewers; float mReuseDistance; float mExpiryDelay; // time in seconds for unused view to be removed unsigned int mWorldUpdateRevision; std::deque<ViewData*> mUsedViews; std::deque<ViewData*> mUnusedViews; }; } #endif
3,962
C++
.h
97
31.752577
120
0.649334
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,733
chunkmanager.hpp
OpenMW_openmw/components/terrain/chunkmanager.hpp
#ifndef OPENMW_COMPONENTS_TERRAIN_CHUNKMANAGER_H #define OPENMW_COMPONENTS_TERRAIN_CHUNKMANAGER_H #include <tuple> #include <components/resource/resourcemanager.hpp> #include "buffercache.hpp" #include "quadtreeworld.hpp" namespace osg { class Group; class Texture2D; } namespace Resource { class SceneManager; } namespace Terrain { class TextureManager; class CompositeMapRenderer; class Storage; class CompositeMap; class TerrainDrawable; struct TemplateKey { osg::Vec2f mCenter; unsigned char mLod; }; inline auto tie(const TemplateKey& v) { return std::tie(v.mCenter, v.mLod); } inline bool operator<(const TemplateKey& l, const TemplateKey& r) { return tie(l) < tie(r); } inline bool operator==(const TemplateKey& l, const TemplateKey& r) { return tie(l) == tie(r); } struct ChunkKey { osg::Vec2f mCenter; unsigned char mLod; unsigned mLodFlags; }; inline auto tie(const ChunkKey& v) { return std::tie(v.mCenter, v.mLod, v.mLodFlags); } inline bool operator<(const ChunkKey& l, const ChunkKey& r) { return tie(l) < tie(r); } inline bool operator<(const ChunkKey& l, const TemplateKey& r) { return TemplateKey{ .mCenter = l.mCenter, .mLod = l.mLod } < r; } /// @brief Handles loading and caching of terrain chunks class ChunkManager : public Resource::GenericResourceManager<ChunkKey>, public QuadTreeWorld::ChunkManager { public: explicit ChunkManager(Storage* storage, Resource::SceneManager* sceneMgr, TextureManager* textureManager, CompositeMapRenderer* renderer, ESM::RefId worldspace, double expiryDelay); osg::ref_ptr<osg::Node> getChunk(float size, const osg::Vec2f& center, unsigned char lod, unsigned int lodFlags, bool activeGrid, const osg::Vec3f& viewPoint, bool compile) override; void setCompositeMapSize(unsigned int size) { mCompositeMapSize = size; } void setCompositeMapLevel(float level) { mCompositeMapLevel = level; } void setMaxCompositeGeometrySize(float maxCompGeometrySize) { mMaxCompGeometrySize = maxCompGeometrySize; } void setNodeMask(unsigned int mask) { mNodeMask = mask; } unsigned int getNodeMask() override { return mNodeMask; } void reportStats(unsigned int frameNumber, osg::Stats* stats) const override; void clearCache() override; void releaseGLObjects(osg::State* state) override; private: osg::ref_ptr<osg::Node> createChunk(float size, const osg::Vec2f& center, unsigned char lod, unsigned int lodFlags, bool compile, const TerrainDrawable* templateGeometry); osg::ref_ptr<osg::Texture2D> createCompositeMapRTT(); void createCompositeMapGeometry( float chunkSize, const osg::Vec2f& chunkCenter, const osg::Vec4f& texCoords, CompositeMap& map); std::vector<osg::ref_ptr<osg::StateSet>> createPasses( float chunkSize, const osg::Vec2f& chunkCenter, bool forCompositeMap); Terrain::Storage* mStorage; Resource::SceneManager* mSceneManager; TextureManager* mTextureManager; CompositeMapRenderer* mCompositeMapRenderer; BufferCache mBufferCache; osg::ref_ptr<osg::StateSet> mMultiPassRoot; unsigned int mNodeMask; unsigned int mCompositeMapSize; float mCompositeMapLevel; float mMaxCompGeometrySize; }; } #endif
3,578
C++
.h
94
31.489362
120
0.696118
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,734
buffercache.hpp
OpenMW_openmw/components/terrain/buffercache.hpp
#ifndef COMPONENTS_TERRAIN_BUFFERCACHE_H #define COMPONENTS_TERRAIN_BUFFERCACHE_H #include <osg/Array> #include <osg/PrimitiveSet> #include <osg/ref_ptr> #include <map> #include <mutex> namespace Terrain { /// @brief Implements creation and caching of vertex buffers for terrain chunks. class BufferCache { public: /// @param flags first 4*4 bits are LOD deltas on each edge, respectively (4 bits each) /// next 4 bits are LOD level of the index buffer (LOD 0 = don't omit any vertices) /// @note Thread safe. osg::ref_ptr<osg::DrawElements> getIndexBuffer(unsigned int numVerts, unsigned int flags); /// @note Thread safe. osg::ref_ptr<osg::Vec2Array> getUVBuffer(unsigned int numVerts); void clearCache(); void releaseGLObjects(osg::State* state); private: // Index buffers are shared across terrain batches where possible. There is one index buffer for each // combination of LOD deltas and index buffer LOD we may need. std::map<std::pair<int, int>, osg::ref_ptr<osg::DrawElements>> mIndexBufferMap; std::mutex mIndexBufferMutex; std::map<int, osg::ref_ptr<osg::Vec2Array>> mUvBufferMap; std::mutex mUvBufferMutex; }; } #endif
1,291
C++
.h
31
35.903226
109
0.68695
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,735
cellborder.hpp
OpenMW_openmw/components/terrain/cellborder.hpp
#ifndef GAME_RENDER_CELLBORDER #define GAME_RENDER_CELLBORDER #include <map> #include <osg/Group> #include <components/esm/refid.hpp> namespace Resource { class SceneManager; } namespace Terrain { class Storage; class World; /** * @Brief Handles the debug cell borders. */ class CellBorder { public: typedef std::map<std::pair<int, int>, osg::ref_ptr<osg::Node>> CellGrid; CellBorder(Terrain::World* world, osg::Group* root, int borderMask, Resource::SceneManager* sceneManager); void createCellBorderGeometry(int x, int y); void destroyCellBorderGeometry(int x, int y); /** Destroys the geometry for all borders. */ void destroyCellBorderGeometry(); static osg::ref_ptr<osg::Group> createBorderGeometry(float x, float y, float size, Storage* terrain, Resource::SceneManager* sceneManager, int mask, ESM::RefId worldspace, float offset = 10.0, osg::Vec4f color = { 1, 1, 0, 0 }); protected: Terrain::World* mWorld; Resource::SceneManager* mSceneManager; osg::Group* mRoot; CellGrid mCellBorderNodes; int mBorderMask; }; } #endif
1,225
C++
.h
39
25.384615
114
0.663543
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,736
heightcull.hpp
OpenMW_openmw/components/terrain/heightcull.hpp
#ifndef COMPONENTS_TERRAIN_HEIGHTCULL_H #define COMPONENTS_TERRAIN_HEIGHTCULL_H #include <osg/Referenced> #include <limits> #include <components/sceneutil/nodecallback.hpp> namespace osg { class Node; class NodeVisitor; } namespace Terrain { class HeightCullCallback : public SceneUtil::NodeCallback<HeightCullCallback> { public: void setLowZ(float z) { mLowZ = z; } float getLowZ() const { return mLowZ; } void setHighZ(float highZ) { mHighZ = highZ; } float getHighZ() const { return mHighZ; } void setCullMask(unsigned int mask) { mMask = mask; } unsigned int getCullMask() const { return mMask; } void operator()(osg::Node* node, osg::NodeVisitor* nv) { if (mLowZ <= mHighZ) traverse(node, nv); } private: float mLowZ{ -std::numeric_limits<float>::max() }; float mHighZ{ std::numeric_limits<float>::max() }; unsigned int mMask{ ~0u }; }; } #endif
1,014
C++
.h
33
24.787879
81
0.64433
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,737
quadtreeworld.hpp
OpenMW_openmw/components/terrain/quadtreeworld.hpp
#ifndef COMPONENTS_TERRAIN_QUADTREEWORLD_H #define COMPONENTS_TERRAIN_QUADTREEWORLD_H #include "terraingrid.hpp" #include <atomic> #include <memory> #include <mutex> #include <components/esm/refid.hpp> namespace osg { class NodeVisitor; class Group; class Stats; } namespace Terrain { class RootNode; class ViewDataMap; class ViewData; struct ViewDataEntry; class DebugChunkManager; /// @brief Terrain implementation that loads cells into a Quad Tree, with geometry LOD and texture LOD. class QuadTreeWorld : public TerrainGrid // note: derived from TerrainGrid is only to render default cells (see loadCell) { public: QuadTreeWorld(osg::Group* parent, osg::Group* compileRoot, Resource::ResourceSystem* resourceSystem, Storage* storage, unsigned int nodeMask, unsigned int preCompileMask, unsigned int borderMask, int compMapResolution, float comMapLevel, float lodFactor, int vertexLodMod, float maxCompGeometrySize, bool debugChunks, ESM::RefId worldspace, double expiryDelay); ~QuadTreeWorld(); void accept(osg::NodeVisitor& nv); void enable(bool enabled) override; void setViewDistance(float distance) override; void cacheCell(View* view, int x, int y) override {} /// @note Not thread safe. void loadCell(int x, int y) override; /// @note Not thread safe. void unloadCell(int x, int y) override; View* createView() override; void preload(View* view, const osg::Vec3f& eyePoint, const osg::Vec4i& cellgrid, std::atomic<bool>& abort, Loading::Reporter& reporter) override; void rebuildViews() override; void reportStats(unsigned int frameNumber, osg::Stats* stats) override; class ChunkManager { public: virtual ~ChunkManager() {} ChunkManager() = default; ChunkManager(ESM::RefId worldspace) : ChunkManager() { mWorldspace = worldspace; } virtual osg::ref_ptr<osg::Node> getChunk(float size, const osg::Vec2f& center, unsigned char lod, unsigned int lodFlags, bool activeGrid, const osg::Vec3f& viewPoint, bool compile) = 0; virtual unsigned int getNodeMask() { return 0; } void setViewDistance(float viewDistance) { mViewDistance = viewDistance; } float getViewDistance() const { return mViewDistance; } // Automatically set by addChunkManager based on getViewDistance() unsigned int getMaxLodLevel() const { return mMaxLodLevel; } void setMaxLodLevel(unsigned int level) { mMaxLodLevel = level; } protected: ESM::RefId mWorldspace = ESM::RefId(); private: float mViewDistance = 0.f; unsigned int mMaxLodLevel = ~0u; }; void addChunkManager(ChunkManager*); private: void ensureQuadTreeBuilt(); void loadRenderingNode( ViewDataEntry& entry, ViewData* vd, float cellWorldSize, const osg::Vec4i& gridbounds, bool compile); osg::ref_ptr<RootNode> mRootNode; osg::ref_ptr<ViewDataMap> mViewDataMap; std::vector<ChunkManager*> mChunkManagers; std::mutex mQuadTreeMutex; bool mQuadTreeBuilt; float mLodFactor; int mVertexLodMod; float mViewDistance; float mMinSize; bool mDebugTerrainChunks; std::unique_ptr<DebugChunkManager> mDebugChunkManager; }; } #endif
3,624
C++
.h
87
33
115
0.66192
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,738
terraingrid.hpp
OpenMW_openmw/components/terrain/terraingrid.hpp
#ifndef COMPONENTS_TERRAIN_TERRAINGRID_H #define COMPONENTS_TERRAIN_TERRAINGRID_H #include <map> #include <osg/Vec2f> #include "world.hpp" namespace osg { class Group; class Stats; } namespace Resource { class ResourceSystem; } namespace Terrain { class Storage; /// @brief Simple terrain implementation that loads cells in a grid, with no LOD. Only requested cells are loaded. class TerrainGrid : public Terrain::World { public: explicit TerrainGrid(osg::Group* parent, osg::Group* compileRoot, Resource::ResourceSystem* resourceSystem, Storage* storage, unsigned int nodeMask, ESM::RefId worldspace, double expiryDelay, unsigned int preCompileMask = ~0u, unsigned int borderMask = 0); TerrainGrid(osg::Group* parent, Storage* storage, ESM::RefId worldspace, unsigned int nodeMask = ~0u); ~TerrainGrid(); void cacheCell(View* view, int x, int y) override; /// @note Not thread safe. void loadCell(int x, int y) override; /// @note Not thread safe. void unloadCell(int x, int y) override; View* createView() override; protected: bool isGridEmpty() const { return mGrid.empty(); } private: osg::ref_ptr<osg::Node> buildTerrain(osg::Group* parent, float chunkSize, const osg::Vec2f& chunkCenter); void updateWaterCulling(); // split each ESM::Cell into mNumSplits*mNumSplits terrain chunks unsigned int mNumSplits; CellBorder::CellGrid mGrid; }; } #endif
1,557
C++
.h
43
30.465116
118
0.691589
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,739
quadtreenode.hpp
OpenMW_openmw/components/terrain/quadtreenode.hpp
#ifndef OPENMW_COMPONENTS_TERRAIN_QUADTREENODE_H #define OPENMW_COMPONENTS_TERRAIN_QUADTREENODE_H #include <osg/Group> #include "defs.hpp" namespace Terrain { enum ChildDirection { NW = 0, NE = 1, SW = 2, SE = 3, Root }; class QuadTreeNode; class LodCallback : public osg::Referenced { public: virtual ~LodCallback() {} enum ReturnValue { Deeper, StopTraversal, StopTraversalAndUse }; virtual ReturnValue isSufficientDetail(QuadTreeNode* node, float dist) = 0; }; class ViewData; float distance(const osg::BoundingBox&, const osg::Vec3f& v); class QuadTreeNode : public osg::Group { public: QuadTreeNode(QuadTreeNode* parent, ChildDirection dir, float size, const osg::Vec2f& center); virtual ~QuadTreeNode(); inline QuadTreeNode* getParent() { return mParent; } inline QuadTreeNode* getChild(unsigned int i) { return static_cast<QuadTreeNode*>(Group::getChild(i)); } inline unsigned int getNumChildren() const override { return _children.size(); } // osg::Group::addChild() does a lot of unrelated stuff, but we just really want to add a child node. void addChildNode(QuadTreeNode* child) { // QuadTree node should not contain more than 4 child nodes. // Reserve enough space if this node is supposed to have child nodes. _children.reserve(4); _children.push_back(child); child->addParent(this); } float distance(const osg::Vec3f& v) const; /// Returns our direction relative to the parent node, or Root if we are the root node. ChildDirection getDirection() { return mDirection; } /// Get neighbour node in this direction QuadTreeNode* getNeighbour(Direction dir); /// Initialize neighbours - do this after the quadtree is built void initNeighbours(); void setBoundingBox(const osg::BoundingBox& boundingBox); const osg::BoundingBox& getBoundingBox() const; bool hasValidBounds() const { return mValidBounds; } /// size in cell coordinates float getSize() const; /// center in cell coordinates const osg::Vec2f& getCenter() const; /// Traverse nodes according to LOD selection. void traverseNodes(ViewData* vd, const osg::Vec3f& viewPoint, LodCallback* lodCallback); private: QuadTreeNode* mParent; QuadTreeNode* mNeighbours[4]; ChildDirection mDirection; osg::BoundingBox mBoundingBox; bool mValidBounds; float mSize; osg::Vec2f mCenter; }; } #endif
2,770
C++
.h
73
29.863014
112
0.647829
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,740
material.hpp
OpenMW_openmw/components/terrain/material.hpp
#ifndef COMPONENTS_TERRAIN_MATERIAL_H #define COMPONENTS_TERRAIN_MATERIAL_H #include <osg/StateSet> namespace osg { class Texture2D; } namespace Resource { class SceneManager; } namespace Terrain { struct TextureLayer { osg::ref_ptr<osg::Texture2D> mDiffuseMap; osg::ref_ptr<osg::Texture2D> mNormalMap; // optional bool mParallax; bool mSpecular; }; std::vector<osg::ref_ptr<osg::StateSet>> createPasses(bool useShaders, Resource::SceneManager* sceneManager, const std::vector<TextureLayer>& layers, const std::vector<osg::ref_ptr<osg::Texture2D>>& blendmaps, int blendmapScale, float layerTileSize); } #endif
690
C++
.h
25
23.4
112
0.722983
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false