1 /**
2 * Copyright © Novelate 2020
3 * License: MIT (https://github.com/Novelate/NovelateEngine/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 * Website: https://novelate.com/
6 * ------
7 * Novelate is a free and open-source visual novel engine and framework written in the D programming language.
8 * It can be used freely for both personal and commercial projects.
9 * ------
10 * Module Description:
11 * Compile-time file management for reading files during compilation.
12 */
13 module novelate.scripting.files;
14 
15 /// Mixin template for loading the story at compile-time.
16 mixin template LoadStory()
17 {
18   /// Generates the code to load file contents at compile-time.
19   string generate()
20   {
21     import std.array : replace, split;
22     import std..string : strip;
23     import std.conv : to;
24 
25     string getFileContentString = "string[string] getFileContents() { string[string] fileContents; ";
26 
27     enum filesContent = import("files.txt");
28 
29     foreach (line; filesContent.replace("\r", "").split("\n"))
30     {
31       if (!line || !line.strip.length)
32       {
33         continue;
34       }
35 
36       getFileContentString ~= "fileContents[\"" ~ line ~ "\"] = import(\"" ~ line ~ "\");";
37     }
38 
39     getFileContentString ~= " return fileContents; }";
40 
41     return getFileContentString;
42   }
43 
44   mixin(generate());
45 }
46 
47 mixin LoadStory!();
48 
49 /// Enum for the loaded file content.
50 private enum loadedFiles = getFileContents();
51 
52 /**
53 * Reads text from a file loaded at compile-time. The file must be available in the parsed "files.txt" which can be found in the "config" folder in the root of the game project.
54 * Params:
55 *   fileName = The name of the file.
56 * Returns:
57 *   The contents of the file.
58 */
59 string readFileText(string fileName)
60 {
61   return loadedFiles.get(fileName, null);
62 }