summaryrefslogtreecommitdiff
path: root/src/game_features.cpp
blob: 2eb7835d7f39cb13fabf3618e6d6be2210a6eb26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#include "game_features.h"

#include <algorithm>

#include <QTimer>

#include "iplugingame.h"
#include "log.h"

#include "bsainvalidation.h"
#include "dataarchives.h"
#include "gameplugins.h"
#include "localsavegames.h"
#include "organizercore.h"
#include "plugincontainer.h"
#include "savegameinfo.h"
#include "scriptextender.h"
#include "unmanagedmods.h"

using namespace MOBase;

// avoid updating features more than once every 100ms
constexpr std::chrono::milliseconds UPDATE_QUEUE_TIMER{100};

// specific type index for checker and content that behaves differently
const std::type_index ModDataCheckerIndex{typeid(ModDataChecker)};
const std::type_index ModDataContentIndex{typeid(ModDataContent)};

class GameFeatures::CombinedModDataChecker : public ModDataChecker
{
  std::vector<std::shared_ptr<ModDataChecker>> m_modDataCheckers;
  mutable std::shared_ptr<ModDataChecker> m_fixer = nullptr;

public:
  void setCheckers(std::vector<std::shared_ptr<ModDataChecker>> checkers)
  {
    m_modDataCheckers = std::move(checkers);
    m_fixer           = nullptr;
  }

  bool isValid() const { return !m_modDataCheckers.empty(); }

  CheckReturn
  dataLooksValid(std::shared_ptr<const MOBase::IFileTree> fileTree) const override
  {
    m_fixer = nullptr;

    // go through the available mod-data checker, if any returns valid, we also
    // return valid, otherwise, return the first one that is fixable
    for (const auto& modDataChecker : m_modDataCheckers) {
      auto check = modDataChecker->dataLooksValid(fileTree);

      switch (check) {
      case CheckReturn::FIXABLE:
        // only update fixer if there is not one with higher priority
        if (!m_fixer) {
          m_fixer = modDataChecker;
        }
        break;
      case CheckReturn::VALID:
        // clear fixer if one were found before and return VALID, not mandatory
        // but cleaner
        m_fixer = nullptr;
        return CheckReturn::VALID;
      case CheckReturn::INVALID:
        break;
      }
    }

    return m_fixer ? CheckReturn::FIXABLE : CheckReturn::INVALID;
  }

  std::shared_ptr<MOBase::IFileTree>
  fix(std::shared_ptr<MOBase::IFileTree> fileTree) const override
  {
    if (m_fixer) {
      return m_fixer->fix(fileTree);
    }

    return nullptr;
  }
};
class GameFeatures::CombinedModDataContent : public ModDataContent
{
  // store the ModDataContent and the offset to add to the content
  std::vector<std::pair<std::shared_ptr<ModDataContent>, std::unordered_map<int, int>>>
      m_modDataContents;
  std::vector<Content> m_allContents;

public:
  bool isValid() const { return !m_modDataContents.empty(); }

  void setContents(std::vector<std::shared_ptr<ModDataContent>> modDataContents)
  {
    m_modDataContents.clear();
    m_modDataContents.reserve(modDataContents.size());

    m_allContents.clear();

    // update all contents
    for (auto& modDataContent : modDataContents) {

      std::unordered_map<int, int> idMap;

      // extract contents for all ModDataContent, replacing ID with index in the list
      // and keeping track of the ID/index with the mapping (required since
      // getContentsFor returns ID, not index)
      for (const auto& content : modDataContent->getAllContents()) {
        const auto index    = static_cast<int>(m_allContents.size());
        idMap[content.id()] = index;
        m_allContents.emplace_back(index, content.name(), content.icon(),
                                   content.isOnlyForFilter());
      }

      m_modDataContents.emplace_back(modDataContent, std::move(idMap));
    }
  }

  std::vector<Content> getAllContents() const override { return m_allContents; }

  std::vector<int>
  getContentsFor(std::shared_ptr<const MOBase::IFileTree> fileTree) const
  {
    std::vector<int> contentsFor;
    for (const auto& modDataContent : m_modDataContents) {
      auto contentsForFrom = modDataContent.first->getContentsFor(fileTree);
      std::transform(contentsForFrom.begin(), contentsForFrom.end(),
                     std::back_inserter(contentsFor), [&modDataContent](auto content) {
                       return modDataContent.second.at(content);
                     });
    }

    return contentsFor;
  }
};

GameFeatures::GameFeatures(OrganizerCore* core, PluginContainer* plugins)
    : m_pluginContainer(*plugins),
      m_modDataChecker(std::make_unique<CombinedModDataChecker>()),
      m_modDataContent(std::make_unique<CombinedModDataContent>())
{
  // can be nullptr since the plugin container can be initialized with a Core (e.g.,
  // on first MO2 start)
  if (core) {
    connect(core, &OrganizerCore::managedGameChanged, [this] {
      updateCurrentFeatures();
    });
  }

  auto updateFeatures = [this] {
    QTimer::singleShot(UPDATE_QUEUE_TIMER, [this] {
      updateCurrentFeatures();
    });
  };

  connect(plugins, &PluginContainer::pluginEnabled, updateFeatures);
  connect(plugins, &PluginContainer::pluginDisabled, updateFeatures);
  connect(plugins, &PluginContainer::pluginRegistered, updateFeatures);
  connect(plugins, &PluginContainer::pluginUnregistered,
          [this, updateFeatures](MOBase::IPlugin* plugin) {
            // remove features from the current plugin
            for (auto& [_, features] : m_allFeatures) {
              features.erase(std::remove_if(features.begin(), features.end(),
                                            [plugin](const auto& feature) {
                                              return feature.plugin() == plugin;
                                            }),
                             features.end());
            }

            // update current features
            updateFeatures();
          });
}

GameFeatures::~GameFeatures() {}

GameFeatures::CombinedModDataChecker& GameFeatures::modDataChecker() const
{
  return dynamic_cast<CombinedModDataChecker&>(*m_modDataChecker);
}
GameFeatures::CombinedModDataContent& GameFeatures::modDataContent() const
{
  return dynamic_cast<CombinedModDataContent&>(*m_modDataContent);
}

void GameFeatures::updateCurrentFeatures(std::type_index const& index)
{
  auto& features = m_allFeatures[index];

  m_currentFeatures[index].clear();

  // this can occur when starting MO2, just wait for the next update
  if (!m_pluginContainer.managedGame()) {
    return;
  }

  for (const auto& dataFeature : features) {

    // registering plugin is disabled
    if (!m_pluginContainer.isEnabled(dataFeature.plugin())) {
      continue;
    }

    // games does not match
    if (!dataFeature.games().isEmpty() &&
        !dataFeature.games().contains(m_pluginContainer.managedGame()->gameName())) {
      continue;
    }

    m_currentFeatures[index].push_back(dataFeature.feature());
  }

  // update mod data checker
  if (index == ModDataCheckerIndex) {
    auto& currentCheckers = m_currentFeatures[ModDataCheckerIndex];
    std::vector<std::shared_ptr<ModDataChecker>> checkers;
    checkers.reserve(currentCheckers.size());
    std::transform(currentCheckers.begin(), currentCheckers.end(),
                   std::back_inserter(checkers), [](auto const& checker) {
                     return std::dynamic_pointer_cast<ModDataChecker>(checker);
                   });
    modDataChecker().setCheckers(std::move(checkers));
    emit modDataCheckerUpdated(gameFeature<ModDataChecker>().get());
  }

  // update mod data content
  if (index == ModDataContentIndex) {
    auto& currentContents = m_currentFeatures[ModDataContentIndex];
    std::vector<std::shared_ptr<ModDataContent>> contents;
    contents.reserve(currentContents.size());
    std::transform(currentContents.begin(), currentContents.end(),
                   std::back_inserter(contents), [](auto const& checker) {
                     return std::dynamic_pointer_cast<ModDataContent>(checker);
                   });
    modDataContent().setContents(std::move(contents));
    emit modDataContentUpdated(gameFeature<ModDataContent>().get());
  }
}

void GameFeatures::updateCurrentFeatures()
{
  // TODO: this completely refilters everything currently, which should be ok since
  // this should only be triggered by function that are uncommon (enabling/disabling
  // plugin or changing the game), it should be possible to filter more finely by
  // maintaining more information (e.g., only removing features from current when a
  // plugin is disabled or unregistered)
  //

  for (auto& [info, _] : m_allFeatures) {
    updateCurrentFeatures(info);
  }
}

bool GameFeatures::registerGameFeature(MOBase::IPlugin* plugin,
                                       QStringList const& games,
                                       std::shared_ptr<MOBase::GameFeature> feature,
                                       int priority)
{
  auto& features = m_allFeatures[feature->typeInfo()];

  if (std::find_if(features.begin(), features.end(), [&feature](const auto& data) {
        return data.feature() == feature;
      }) != features.end()) {
    log::error("cannot register feature multiple time");
    return false;
  }

  std::decay_t<decltype(features)>::iterator it;
  if (dynamic_cast<IPluginGame*>(plugin)) {
    it = features.end();
  } else {
    it = std::lower_bound(features.begin(), features.end(), priority,
                          [](const auto& feature, int priority) {
                            return feature.priority() > priority;
                          });
  }

  features.emplace(it, feature, plugin, games, std::numeric_limits<int>::min());

  // TODO: only update if relevant
  updateCurrentFeatures(feature->typeInfo());

  return true;
}

// unregister game features
//
bool GameFeatures::unregisterGameFeature(std::shared_ptr<MOBase::GameFeature> feature)
{
  bool removed = false;
  for (auto& [_, features] : m_allFeatures) {
    auto it =
        std::find_if(features.begin(), features.end(), [&feature](const auto& data) {
          return data.feature() == feature;
        });

    // the feature can only exist for one kind of features and cannot be duplicated
    if (it != features.end()) {
      features.erase(it);
      removed = true;
      break;
    }
  }

  if (removed) {
    updateCurrentFeatures();
  }

  return removed;
}

int GameFeatures::unregisterGameFeatures(MOBase::IPlugin* plugin,
                                         std::type_info const& info)
{
  auto& features = m_allFeatures[info];

  const auto initialSize = features.size();

  features.erase(std::remove_if(features.begin(), features.end(),
                                [plugin](const auto& feature) {
                                  return feature.plugin() == plugin;
                                }),
                 features.end());

  const int removed = features.size() - initialSize;

  if (removed) {
    updateCurrentFeatures();
  }

  return removed;
}

std::shared_ptr<GameFeature> GameFeatures::gameFeature(std::type_info const& info) const
{
  if (info == ModDataCheckerIndex) {
    return modDataChecker().isValid() ? m_modDataChecker : nullptr;
  }

  if (info == ModDataContentIndex) {
    return modDataContent().isValid() ? m_modDataContent : nullptr;
  }

  auto it = m_currentFeatures.find(info);
  if (it == m_currentFeatures.end() || it->second.empty()) {
    return nullptr;
  }

  return it->second.front();
}