forked from sims3fiend/Sims3SettingsSetter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimization.cpp
More file actions
328 lines (281 loc) · 11.6 KB
/
optimization.cpp
File metadata and controls
328 lines (281 loc) · 11.6 KB
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
#include "optimization.h"
#include "patch_system.h"
#include <intrin.h>
#include <format>
#include <unordered_map>
#include <detours/detours.h>
#include "intersection_patch.h"
#include "cpu_optimization.h"
#include "utils.h"
#include "logger.h"
// Metadata storage for patches (use unique_ptr to avoid pointer invalidation on reallocation)
static std::vector<std::unique_ptr<PatchMetadata>>& GetMetadataStorage() {
static std::vector<std::unique_ptr<PatchMetadata>> storage;
return storage;
}
void OptimizationPatch::SetMetadata(const PatchMetadata& meta) {
// Store in static storage to ensure lifetime
// Using unique_ptr so pointers remain valid even if vector grows
GetMetadataStorage().push_back(std::make_unique<PatchMetadata>(meta));
metadata = GetMetadataStorage().back().get();
}
bool OptimizationPatch::IsCompatibleWithCurrentVersion() const {
if (!metadata) {
return true; // No metadata = assume compatible
}
return IsVersionSupported(metadata->supportedVersions);
}
void OptimizationPatch::MaybeSampleMinimal(LONG currentCalls) {
auto now = std::chrono::steady_clock::now();
if (now - currentWindow.start >= SAMPLE_INTERVAL) {
std::lock_guard<std::mutex> lock(statsMutex);
if (now - currentWindow.start >= SAMPLE_INTERVAL) {
lastSampleRate = currentCalls /
std::chrono::duration<double>(SAMPLE_INTERVAL).count();
char buffer[256];
sprintf_s(buffer, "[%s] Calls/sec: %.0f\n", patchName.c_str(), lastSampleRate);
LOG_DEBUG(buffer);
InterlockedExchange(¤tWindow.calls, 0);
currentWindow.start = now;
}
}
}
CPUFeatures::CPUFeatures() {
int leaves[4] = { 0 };
__cpuid(leaves, 1);
hasSSE41 = (leaves[2] & (1 << 19)) != 0;
hasFMA = (leaves[2] & (1 << 12)) != 0;
// Check for AVX2 (CPUID leaf 7, EBX bit 5)
__cpuidex(leaves, 7, 0);
hasAVX2 = (leaves[1] & (1 << 5)) != 0;
}
const CPUFeatures& CPUFeatures::Get() {
static CPUFeatures instance;
return instance;
}
OptimizationManager& OptimizationManager::Get() {
static OptimizationManager instance;
// Register all patches when the manager is first created
static bool initialized = false;
static bool initializing = false;
if (!initialized && !initializing) {
initializing = true; // Prevent re-entry
LOG_INFO("[PatchSystem] Initializing patches...");
try {
// Use PatchRegistry to auto-register all patches
PatchRegistry::InstantiateAll(instance);
// Log all registered patches
LOG_INFO("[PatchSystem] Registered " + std::to_string(instance.patches.size()) + " patches:");
for (const auto& patch : instance.patches) {
LOG_INFO(" - " + patch->GetName());
}
LOG_INFO("[PatchSystem] Patch registration complete");
}
catch (const std::exception& e) {
LOG_ERROR("[PatchSystem] Exception during patch initialization: " + std::string(e.what()));
}
catch (...) {
LOG_ERROR("[PatchSystem] Unknown exception during patch initialization");
}
initialized = true;
initializing = false;
}
else if (initializing) {
LOG_ERROR("[PatchSystem] Recursive call detected during initialization!");
}
return instance;
}
const std::vector<std::unique_ptr<OptimizationPatch>>& OptimizationManager::GetPatches() const {
return patches;
}
bool OptimizationManager::EnablePatch(const std::string& name) {
for (auto& patch : patches) {
if (patch->GetName() == name) {
return patch->Install();
}
}
return false;
}
bool OptimizationManager::DisablePatch(const std::string& name) {
for (auto& patch : patches) {
if (patch->GetName() == name) {
return patch->Uninstall();
}
}
return false;
}
bool OptimizationManager::SaveState(const std::string& filename) {
try {
// First, read entire file content
std::vector<std::string> existingContent;
{
std::ifstream inFile(filename);
if (inFile.is_open()) {
std::string line;
while (std::getline(inFile, line)) {
existingContent.push_back(line);
}
}
}
// Find and remove existing patch settings section
bool inSection = false;
auto it = existingContent.begin();
while (it != existingContent.end()) {
if (*it == "; Patch Settings" || *it == "; Optimization Settings") { // Support both old and new format
inSection = true;
it = existingContent.erase(it);
}
else if (inSection) {
// Check if we've reached a new section (starts with [ or ; at beginning of line)
if (!it->empty() && ((*it)[0] == '[' || ((*it)[0] == ';' && it->find("; Optimization") != 0))) {
// Found a new section, stop removing
inSection = false;
it++;
} else {
// Still in optimization section, remove this line
it = existingContent.erase(it);
}
}
else {
it++;
}
}
// Write back file with updated content
std::ofstream outFile(filename);
if (!outFile.is_open()) {
LOG_ERROR("[PatchSystem] Failed to open file for saving: " + filename);
return false;
}
// Write existing content
for (const auto& line : existingContent) {
outFile << line << "\n";
}
// Ensure there's a blank line before optimization section
if (!existingContent.empty() && !existingContent.back().empty()) {
outFile << "\n";
}
// Write patch settings section
outFile << "; Patch Settings\n";
for (const auto& patch : patches) {
patch->SaveState(outFile);
}
return true;
}
catch (const std::exception& e) {
LOG_ERROR(std::string("[PatchSystem] Error saving state: ") + e.what());
return false;
}
}
bool OptimizationManager::LoadState(const std::string& filename) {
try {
LOG_DEBUG("[PatchSystem] Attempting to load from: " + filename);
std::ifstream file(filename);
if (!file.is_open()) {
LOG_ERROR("[PatchSystem] Failed to open file for loading: " + filename);
return false;
}
// Look for patch settings section
std::string line;
bool foundOptSection = false;
while (std::getline(file, line)) {
if (line == "; Patch Settings" || line == "; Optimization Settings") { // Support old format too
foundOptSection = true;
LOG_DEBUG("[PatchSystem] Found patch settings section");
break;
}
}
if (!foundOptSection) {
LOG_DEBUG("[PatchSystem] No patch section found in file");
return true; // Not an error, just no settings
}
// First pass collect all settings per patch
// We need to apply Settings.* BEFORE Enabled so patches install with correct values!!!!!!!!!!!!!!!!!
struct PatchSettings {
std::vector<std::pair<std::string, std::string>> settings; // Settings.* entries
std::string enabledValue; // "true" or "false" or empty if not specified
};
std::unordered_map<std::string, PatchSettings> patchSettingsMap;
std::string currentPatchName;
bool foundAnyOptimizations = false;
while (std::getline(file, line)) {
// Skip empty lines and comments
if (line.empty() || line[0] == ';') {
continue;
}
// Check for optimization section header like [Optimization_FrameRate]
if (!line.empty() && line[0] == '[' && line.back() == ']') {
size_t start = line.find('_'); // Find the underscore after "Optimization"
if (start != std::string::npos && start + 1 < line.length() - 1) {
currentPatchName = line.substr(start + 1, line.length() - start - 2); // Extract patch name
LOG_DEBUG("[PatchSystem] Found patch section: " + currentPatchName);
foundAnyOptimizations = true;
} else {
currentPatchName.clear(); // Invalid section header
}
continue;
}
// Parse key=value pairs within a valid section
size_t equalPos = line.find('=');
if (equalPos != std::string::npos && !currentPatchName.empty()) {
std::string key = line.substr(0, equalPos);
std::string value = line.substr(equalPos + 1);
LOG_DEBUG("[PatchSystem] Found setting for [" + currentPatchName + "] - Key: " + key + ", Value: " + value);
// Store in our map for later application
if (key == "Enabled") {
patchSettingsMap[currentPatchName].enabledValue = value;
} else {
patchSettingsMap[currentPatchName].settings.emplace_back(key, value);
}
}
}
// Second pass apply settings to patches in correct order
// First apply all Settings.* values (so patches have correct config before install)
// Then apply Enabled state (which may trigger Instal)
for (auto& [patchName, patchSettings] : patchSettingsMap) {
// Find the patch
OptimizationPatch* patch = nullptr;
for (auto& p : patches) {
if (p->GetName() == patchName) {
patch = p.get();
break;
}
}
if (!patch) {
LOG_WARNING("[PatchSystem] No matching patch found for section: " + patchName);
continue;
}
// Apply settings first (before Enabled)
for (const auto& [key, value] : patchSettings.settings) {
LOG_DEBUG("[PatchSystem] Applying setting to patch [" + patchName + "]: " + key + "=" + value);
patch->LoadState(key, value);
}
// Now apply Enabled state (may trigger Install with correct settings)
if (!patchSettings.enabledValue.empty()) {
LOG_DEBUG("[PatchSystem] Applying Enabled=" + patchSettings.enabledValue + " to patch: " + patchName);
patch->LoadState("Enabled", patchSettings.enabledValue);
}
}
if (!foundAnyOptimizations) {
LOG_DEBUG("[PatchSystem] No patch sections found in file");
}
return true;
}
catch (const std::exception& e) {
LOG_ERROR(std::string("[PatchSystem] Error loading state: ") + e.what());
return false;
}
}
// Register a new patch in the system
void OptimizationManager::RegisterPatch(std::unique_ptr<OptimizationPatch> patch) {
// Check if a patch with the same name already exists
std::string patchName = patch->GetName();
for (const auto& existingPatch : patches) {
if (existingPatch->GetName() == patchName) {
LOG_WARNING("[PatchSystem] Patch already registered: " + patchName);
return; // Skip this patch since it's already registered
}
}
// If we get here, this is a new patch
patches.push_back(std::move(patch));
LOG_DEBUG("[PatchSystem] Registered patch: " + patchName);
}