Olympe Engine 2.0
2D Game Engine with ECS Architecture
Loading...
Searching...
No Matches
DataManager.h
Go to the documentation of this file.
1/*
2Olympe Engine V2 2025
3Nicolas Chereau
4nchereau@gmail.com
5
6Purpose:
7- DataManager is a singleton responsible for loading, caching and
8 releasing game resources (textures, sprites, animations, sounds,
9 level data, navigation/collision maps, game object data, etc.).
10- It provides simple file-based JSON save/load helpers used by
11 VideoGame/GameEntity and related systems to persist runtime data.
12- Resources are categorized by type and category so calling code can
13 list and query resources by semantic groups.
14
15Notes:
16- Resource loading functions in this initial implementation focus on
17 textures (BMP via SDL). Extend to support PNG/JPEG/OGG/etc. with
18 appropriate libraries as needed.
19- JSON serialization of complex objects is expected to be done by
20 calling code; DataManager provides file IO helpers and a directory
21 layout convention: "./Gamedata/{videogameName}/{objectName}.json".
22*/
23
24#pragma once
25
26#include <SDL3/SDL.h>
27#include <string>
28#include <unordered_map>
29#include <memory>
30#include <mutex>
31#include <vector>
32#include <map>
33
34// File picker modal includes
37
39
42
43// Cat�gories et types de ressources
45{
46 Unknown = 0,
47 Texture,
48 Sprite,
50 Sound,
51 Music,
52 FX,
53 Level,
54 Sector,
55 NavMap,
58};
59
61{
62 System = 0, // engine-level data
63 GameEntity, // data related to interactive objects
64 Level // level / map data
65};
66
67// Generic resource container
69{
72 std::string id; // logical identifier
73 std::string path; // filesystem path
74
75 // data payloads depending on the resource type
76 Sprite* sprite_texture = nullptr; // for texture/sprite resources
77 void* data = nullptr; // generic pointer for deferred objects
78
79 Resource() = default;
80 ~Resource() = default;
81};
82
84{
85public:
87 virtual ~DataManager();
88
89 // Singleton access
90 static DataManager& GetInstance();
91 static DataManager& Get() { return GetInstance(); }
92
93 void Initialize();
94 void Shutdown();
95
96 // Texture loading / retrieval / release
97 bool PreloadTexture(const std::string& id, const std::string& path, ResourceCategory category = ResourceCategory::System);
98 bool PreloadSprite(const std::string& id, const std::string& path, ResourceCategory category = ResourceCategory::GameEntity);
99 Sprite* GetTexture(const std::string& id) const;
100 Sprite* GetSprite(const std::string& id, const std::string& path, ResourceCategory category = ResourceCategory::GameEntity);
101 bool GetSprite_data(const std::string& id, const std::string& path, VisualSprite_data& outData);
102 bool GetSpriteEditor_data(const std::string& id, const std::string& path, VisualEditor_data& outData);
103 bool ReleaseResource(const std::string& id);
104
105
106 // Resource helpers
107 void UnloadAll();
108 bool HasResource(const std::string& id) const;
109
110 std::vector<std::string> ListResourcesByType(ResourceType type) const;
111 std::vector<std::string> ListResourcesByCategory(ResourceCategory category) const;
112
113 // JSON file helpers
114 // Save JSON content for an object inside the videogame folder.
115 // Path used: "./Gamedata/{videogameName}/{objectName}.json"
116 bool SaveJSONForObject(const std::string& videogameName, const std::string& objectName, const std::string& jsonContent) const;
117 bool LoadJSONForObject(const std::string& videogameName, const std::string& objectName, std::string& outJson) const;
118
119 // Generic file helpers
120 bool SaveTextFile(const std::string& filepath, const std::string& content) const;
121 bool LoadTextFile(const std::string& filepath, std::string& outContent) const;
122
123 // Ensure directory exists (creates intermediate dirs if necessary)
124 bool EnsureDirectoryExists(const std::string& dirpath) const;
125
126 // Helper to build the standard game data path
127 static std::string BuildGameDataPath(const std::string& videogameName, const std::string& objectName);
128
129 // Preload system resources from a configuration JSON file (e.g. "olympe.ini")
130 // Expected format:
131 // { "system_resources": [ { "id":"ui_icon", "path":"assets/ui/icon.bmp", "type":"texture" }, ... ] }
132 bool PreloadSystemResources(const std::string& configFilePath);
133
134 // ========================================================================
135 // PHASE 2: Batch Preloading System (for 3-Phase Level Loading)
136 // ========================================================================
137
139 {
144 std::vector<std::string> failedPaths;
145 std::map<std::string, std::string> fallbackPaths; // original -> actual
146
150
151 bool IsSuccess() const { return completelyFailed == 0; }
152 float GetSuccessRate() const
153 {
154 return totalRequested > 0 ?
155 static_cast<float>(successfullyLoaded + failedWithFallback) / totalRequested : 1.0f;
156 }
157 };
158
160 {
161 std::string sourceFile; // .tsj file path
162 std::string imageFile; // Main tileset image
163 std::vector<std::string> individualImages; // For collection tilesets
165
167 };
168
198
199 // Batch preload methods
200 PreloadStats PreloadTextures(const std::vector<std::string>& paths,
202 bool enableFallbackScan = true);
203
204 PreloadStats PreloadSprites(const std::vector<std::string>& paths,
206 bool enableFallbackScan = true);
207
208 PreloadStats PreloadAudioFiles(const std::vector<std::string>& paths,
209 bool enableFallbackScan = true);
210
211 PreloadStats PreloadTilesets(const std::vector<TilesetInfo>& tilesets,
212 bool enableFallbackScan = true);
213
214 // Fallback resource discovery
215 std::string FindResourceRecursive(const std::string& filename,
216 const std::string& rootDir = "GameData") const;
217
218 // Phase 38: Enhanced path resolution for blueprint graphs
219 // Resolves relative or absolute paths by searching Blueprints and Gamedata directories
220 // Input: "AI\Boss1.ats" or "AI/Boss1.ats" (relative)
221 // Output: "Blueprints\AI\Boss1.ats" (absolute, first found)
222 // Returns empty string if not found
223 std::string ResolveFilePath(const std::string& relativePath) const;
224
225 // ========================================================================
226 // PHASE 39c Step 5: File Browser Service (Reusable Framework)
227 // ========================================================================
228
229 /**
230 * @brief Lists all .bt.json behavior tree files in a directory
231 * @param directory Directory to search (e.g., "Gamedata/BehaviorTree")
232 * @return Vector of .bt.json filenames found in directory
233 */
234 std::vector<std::string> GetBehaviorTreeFiles(const std::string& directory = "./Gamedata") const;
235
236 /**
237 * @brief Opens a file browser dialog for selecting a behavior tree file
238 * @param currentPath Optional current path to display initially
239 * @return Selected file path (absolute or relative), empty string if cancelled
240 *
241 * This is a framework-level service providing reusable file browsing
242 * for SubGraph node path selection and other file operations.
243 */
244 std::string SelectBehaviorTreeFile(const std::string& currentPath = "") const;
245
246 // ========================================================================
247 // PHASE 40: Centralized File Picker Modal
248 // ========================================================================
249
250 /**
251 * @brief Opens a centralized file picker modal for the specified file type.
252 * @param fileType Type of files to browse (BehaviorTree, SubGraph, Audio, etc.)
253 * @param currentPath Optional current path to display initially
254 * @return Selected file path if user confirmed, empty string if cancelled
255 *
256 * This method manages a centralized modal dialog that supports multiple
257 * file types. Call this from UI elements that need file selection, then
258 * check the return value to see if user made a selection.
259 *
260 * Example usage:
261 * std::string selected = DataManager::Get().OpenFilePickerModal(
262 * Olympe::FilePickerType::BehaviorTree, "./Gamedata"
263 * );
264 * if (!selected.empty()) {
265 * // User selected a file
266 * nodeProperties["subgraphPath"] = selected;
267 * }
268 */
269 std::string OpenFilePickerModal(Olympe::FilePickerType fileType, const std::string& currentPath = "");
270
271 /**
272 * @brief Renders the file picker modal if one is open.
273 *
274 * Call this every frame within the main ImGui rendering loop to display
275 * the modal UI. This is automatically called by the editor UI systems
276 * that integrate with DataManager.
277 */
279
280 /**
281 * @brief Checks if the file picker modal is currently visible.
282 * @return True if modal is open and waiting for user interaction
283 */
284 bool IsFilePickerModalOpen() const;
285
286 /**
287 * @brief Closes the file picker modal without user selection.
288 */
290
291 /**
292 * @brief Retrieves the selected file from the file picker modal.
293 * @return Selected file path if user confirmed and modal has a selection, empty string otherwise
294 *
295 * Call this after IsFilePickerModalOpen() returns false to check if user selected a file.
296 *
297 * Example usage:
298 * if (DataManager::Get().IsFilePickerModalOpen() == false && wasOpen) {
299 * std::string file = DataManager::Get().GetSelectedFileFromModal();
300 * if (!file.empty()) {
301 * // Process selected file
302 * }
303 * }
304 */
305 std::string GetSelectedFileFromModal() const;
306
307 // ====================================================================
308 // Phase 40 Enhancement: Centralized Save As Modal
309 // ====================================================================
310
311 /**
312 * @brief Opens the Save As file picker modal.
313 * @param fileType Type of file to save (BehaviorTree, Blueprint, etc.)
314 * @param directory Starting directory path
315 * @param suggestedFilename Suggested filename without extension
316 *
317 * Extension will be auto-appended based on file type.
318 * Call RenderSaveFilePickerModal() every frame.
319 * After modal closes, check IsSaveFilePickerModalOpen() and GetSelectedSaveFile().
320 */
322 const std::string& directory,
323 const std::string& suggestedFilename = "");
324
325 /**
326 * @brief Renders the Save As file picker modal UI.
327 * Must be called every frame during the main ImGui rendering loop.
328 */
330
331 /**
332 * @brief Checks if the Save As file picker modal is currently visible.
333 */
334 bool IsSaveFilePickerModalOpen() const;
335
336 /**
337 * @brief Closes the Save As file picker modal.
338 */
340
341 /**
342 * @brief Retrieves the selected file from the Save As modal.
343 * @return Full file path with extension if user confirmed, empty string otherwise
344 *
345 * Only valid after IsSaveFilePickerModalOpen() returns false and user confirmed.
346 */
347 std::string GetSelectedSaveFile() const;
348
349private:
350 std::string name;
351 mutable std::mutex m_mutex_;
352 std::unordered_map<std::string, std::shared_ptr<Resource>> m_resources_;
354
355 // Phase 40: Centralized file picker modals
356 std::unique_ptr<Olympe::FilePickerModal> m_filePickerModal;
357 std::unique_ptr<Olympe::SaveFilePickerModal> m_saveFilePickerModal;
358
359 // Platform-specific recursive search helpers
360#ifdef _WIN32
361 std::string FindResourceRecursive_Windows(const std::string& filename,
362 const std::string& rootDir) const;
363#else
364 std::string FindResourceRecursive_Unix(const std::string& filename,
365 const std::string& rootDir) const;
366#endif
367};
ResourceCategory
Definition DataManager.h:61
ResourceType
Definition DataManager.h:45
SDL_Texture Sprite
Definition DataManager.h:38
ComponentTypeID GetComponentTypeID_Static()
Definition ECS_Entity.h:56
Centralized file picker modal for all file selection operations (Phase 40).
Centralized Save As modal for all file save operations (Phase 40 Enhancement).
static std::string BuildGameDataPath(const std::string &videogameName, const std::string &objectName)
std::string FindResourceRecursive_Unix(const std::string &filename, const std::string &rootDir) const
static DataManager & Get()
Definition DataManager.h:91
bool PreloadSystemResources(const std::string &configFilePath)
Sprite * GetSprite(const std::string &id, const std::string &path, ResourceCategory category=ResourceCategory::GameEntity)
void Initialize()
PreloadStats PreloadSprites(const std::vector< std::string > &paths, ResourceCategory category=ResourceCategory::GameEntity, bool enableFallbackScan=true)
std::string GetSelectedFileFromModal() const
Retrieves the selected file from the file picker modal.
bool IsFilePickerModalOpen() const
Checks if the file picker modal is currently visible.
PreloadStats PreloadTextures(const std::vector< std::string > &paths, ResourceCategory category=ResourceCategory::Level, bool enableFallbackScan=true)
virtual ~DataManager()
std::string OpenFilePickerModal(Olympe::FilePickerType fileType, const std::string &currentPath="")
Opens a centralized file picker modal for the specified file type.
bool m_enableFallbackScan
std::string SelectBehaviorTreeFile(const std::string &currentPath="") const
Opens a file browser dialog for selecting a behavior tree file.
Sprite * GetTexture(const std::string &id) const
bool EnsureDirectoryExists(const std::string &dirpath) const
std::string FindResourceRecursive(const std::string &filename, const std::string &rootDir="GameData") const
bool SaveTextFile(const std::string &filepath, const std::string &content) const
static DataManager & GetInstance()
std::vector< std::string > ListResourcesByType(ResourceType type) const
void CloseSaveFilePickerModal()
Closes the Save As file picker modal.
bool HasResource(const std::string &id) const
bool LoadJSONForObject(const std::string &videogameName, const std::string &objectName, std::string &outJson) const
void CloseFilePickerModal()
Closes the file picker modal without user selection.
std::unordered_map< std::string, std::shared_ptr< Resource > > m_resources_
std::mutex m_mutex_
bool PreloadTexture(const std::string &id, const std::string &path, ResourceCategory category=ResourceCategory::System)
PreloadStats PreloadTilesets(const std::vector< TilesetInfo > &tilesets, bool enableFallbackScan=true)
bool SaveJSONForObject(const std::string &videogameName, const std::string &objectName, const std::string &jsonContent) const
bool ReleaseResource(const std::string &id)
PreloadStats PreloadAudioFiles(const std::vector< std::string > &paths, bool enableFallbackScan=true)
void RenderSaveFilePickerModal()
Renders the Save As file picker modal UI.
std::unique_ptr< Olympe::SaveFilePickerModal > m_saveFilePickerModal
bool LoadTextFile(const std::string &filepath, std::string &outContent) const
bool PreloadSprite(const std::string &id, const std::string &path, ResourceCategory category=ResourceCategory::GameEntity)
bool IsSaveFilePickerModalOpen() const
Checks if the Save As file picker modal is currently visible.
void RenderFilePickerModal()
Renders the file picker modal if one is open.
void Shutdown()
std::string ResolveFilePath(const std::string &relativePath) const
std::vector< std::string > GetBehaviorTreeFiles(const std::string &directory="./Gamedata") const
Lists all .bt.json behavior tree files in a directory.
std::vector< std::string > ListResourcesByCategory(ResourceCategory category) const
std::string name
void OpenSaveFilePickerModal(Olympe::SaveFileType fileType, const std::string &directory, const std::string &suggestedFilename="")
Opens the Save As file picker modal.
std::string GetSelectedSaveFile() const
Retrieves the selected file from the Save As modal.
bool GetSprite_data(const std::string &id, const std::string &path, VisualSprite_data &outData)
bool GetSpriteEditor_data(const std::string &id, const std::string &path, VisualEditor_data &outData)
std::unique_ptr< Olympe::FilePickerModal > m_filePickerModal
Definition Level.h:13
FilePickerType
Supported file types for the centralized file picker modal.
SaveFileType
Supported file types for the centralized save modal.
std::vector< std::string > failedPaths
std::map< std::string, std::string > fallbackPaths
float GetSuccessRate() const
std::vector< std::string > individualImages
ResourceCategory category
Definition DataManager.h:71
ResourceType type
Definition DataManager.h:70
std::string id
Definition DataManager.h:72
~Resource()=default
std::string path
Definition DataManager.h:73
Sprite * sprite_texture
Definition DataManager.h:76
Resource()=default
void * data
Definition DataManager.h:77