aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/cc/polyfrost/oneconfig/renderer/AssetLoader.java
blob: 3e70ce1de893f244c3bb7693e02a0da97940da55 (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
/*
 * This file is part of OneConfig.
 * OneConfig - Next Generation Config Library for Minecraft: Java Edition
 * Copyright (C) 2021, 2022 Polyfrost.
 *   <https://polyfrost.cc> <https://github.com/Polyfrost/>
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 *   OneConfig is licensed under the terms of version 3 of the GNU Lesser
 * General Public License as published by the Free Software Foundation, AND
 * under the Additional Terms Applicable to OneConfig, as published by Polyfrost,
 * either version 1.0 of the Additional Terms, or (at your option) any later
 * version.
 *
 *   This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 * License.  If not, see <https://www.gnu.org/licenses/>. You should
 * have also received a copy of the Additional Terms Applicable
 * to OneConfig, as published by Polyfrost. If not, see
 * <https://polyfrost.cc/legal/oneconfig/additional-terms>
 */

package cc.polyfrost.oneconfig.renderer;

import cc.polyfrost.oneconfig.internal.assets.Images;
import cc.polyfrost.oneconfig.internal.assets.SVGs;
import cc.polyfrost.oneconfig.utils.IOUtils;
import org.lwjgl.BufferUtils;
import org.lwjgl.nanovg.NSVGImage;
import org.lwjgl.nanovg.NanoSVG;
import org.lwjgl.nanovg.NanoVG;
import org.lwjgl.stb.STBImage;
import org.lwjgl.system.MemoryUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Objects;

/**
 * Loads images and SVGs from resources into NanoVG.
 *
 * @see cc.polyfrost.oneconfig.renderer.RenderManager
 * @see Images
 * @see SVGs
 */
public final class AssetLoader {
    private AssetLoader() {

    }

    public static final int DEFAULT_FLAGS = NanoVG.NVG_IMAGE_REPEATX | NanoVG.NVG_IMAGE_REPEATY | NanoVG.NVG_IMAGE_GENERATE_MIPMAPS;
    private final HashMap<String, NVGAsset> imageHashMap = new HashMap<>();
    private final HashMap<String, NVGAsset> svgHashMap = new HashMap<>();
    public static AssetLoader INSTANCE = new AssetLoader();

    /**
     * Loads an assets from resources.
     *
     * @param vg       The NanoVG context.
     * @param fileName The name of the file to load.
     * @param flags    The image flags
     * @return Whether the asset was loaded successfully.
     */
    public boolean loadImage(long vg, String fileName, int flags) {
        if (!imageHashMap.containsKey(fileName)) {
            int[] width = {0};
            int[] height = {0};
            int[] channels = {0};

            ByteBuffer image = IOUtils.resourceToByteBufferNullable(fileName);
            if (image == null) {
                return false;
            }

            ByteBuffer buffer = STBImage.stbi_load_from_memory(image, width, height, channels, 4);
            if (buffer == null) {
                return false;
            }

            imageHashMap.put(fileName, new NVGAsset(NanoVG.nvgCreateImageRGBA(vg, width[0], height[0], flags, buffer), width[0], height[0]));
            return true;
        }
        return true;
    }

    /**
     * Loads an assets from resources.
     *
     * @param vg    The NanoVG context.
     * @param image The Image
     * @return Whether the asset was loaded successfully.
     */
    public boolean loadImage(long vg, Image image) {
        return loadImage(vg, image.filePath, image.flags);
    }

    /**
     * Loads an assets from resources.
     *
     * @param vg       The NanoVG context.
     * @param fileName The name of the file to load.
     * @return Whether the asset was loaded successfully.
     */
    public boolean loadImage(long vg, String fileName) {
        return loadImage(vg, fileName, DEFAULT_FLAGS);
    }

    /**
     * Loads an SVG from resources.
     *
     * @param vg       The NanoVG context.
     * @param fileName The name of the file to load.
     * @param width    The width of the SVG.
     * @param height   The height of the SVG.
     * @param flags    The image flags
     * @return Whether the SVG was loaded successfully.
     */
    public boolean loadSVG(long vg, String fileName, float width, float height, int flags) {
        String name = fileName + "-" + width + "-" + height;
        if (!svgHashMap.containsKey(name)) {
            try {
                InputStream inputStream = this.getClass().getResourceAsStream(fileName);
                if (inputStream == null) return false;
                StringBuilder resultStringBuilder = new StringBuilder();
                try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        resultStringBuilder.append(line);
                    }
                }
                CharSequence s = resultStringBuilder.toString();
                NSVGImage svg = NanoSVG.nsvgParse(s, "px", 96f);
                if (svg == null) return false;
                long rasterizer = NanoSVG.nsvgCreateRasterizer();

                int w = (int) svg.width();
                int h = (int) svg.height();
                float scale = Math.max(width / w, height / h);
                w = (int) (w * scale);
                h = (int) (h * scale);

                ByteBuffer image = MemoryUtil.memAlloc(w * h * 4);
                NanoSVG.nsvgRasterize(rasterizer, svg, 0, 0, scale, image, w, h, w * 4);

                NanoSVG.nsvgDeleteRasterizer(rasterizer);
                NanoSVG.nsvgDelete(svg);

                svgHashMap.put(name, new NVGAsset(NanoVG.nvgCreateImageRGBA(vg, w, h, flags, image), w, h));
                return true;
            } catch (Exception e) {
                System.err.println("Failed to parse SVG file");
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * Loads an assets from resources.
     *
     * @param vg     The NanoVG context.
     * @param svg    The SVG
     * @param width  The width of the SVG.
     * @param height The height of the SVG.
     * @return Whether the asset was loaded successfully.
     */
    public boolean loadSVG(long vg, SVG svg, float width, float height) {
        return loadSVG(vg, svg.filePath, width, height, svg.flags);
    }

    /**
     * Loads an SVG from resources.
     *
     * @param vg       The NanoVG context.
     * @param fileName The name of the file to load.
     * @param width    The width of the SVG.
     * @param height   The height of the SVG.
     * @return Whether the SVG was loaded successfully.
     */
    public boolean loadSVG(long vg, String fileName, float width, float height) {
        return loadSVG(vg, fileName, width, height, DEFAULT_FLAGS);
    }

    /**
     * Get a loaded assets from the cache.
     * <p><b>Requires the assets to have been loaded first.</b></p>
     *
     * @param fileName The name of the file to load.
     * @return The assets
     * @see AssetLoader#loadImage(long, String)
     */
    public int getImage(String fileName) {
        return imageHashMap.get(fileName).getImage();
    }

    /**
     * Get a loaded assets from the cache.
     * <p><b>Requires the assets to have been loaded first.</b></p>
     *
     * @param fileName The name of the file to load.
     * @return The image and its data
     * @see AssetLoader#loadImage(long, String)
     */
    public NVGAsset getNVGImage(String fileName) {
        return imageHashMap.get(fileName);
    }

    /**
     * Remove an assets from the cache, allowing the assets to be garbage collected.
     * Should be used when the GUI rendering the assets is closed.
     *
     * @param vg       The NanoVG context.
     * @param fileName The name of the file to remove.
     * @see AssetLoader#loadImage(long, String)
     */
    public void removeImage(long vg, String fileName) {
        NanoVG.nvgDeleteImage(vg, imageHashMap.get(fileName).getImage());
        imageHashMap.remove(fileName);
    }

    /**
     * Clears all images from the cache, allowing the images cleared to be garbage collected.
     * Should be used when the GUI rendering loaded images are closed.
     *
     * @param vg The NanoVG context.
     */
    public void clearImages(long vg) {
        HashMap<String, NVGAsset> temp = new HashMap<>(imageHashMap);
        for (String image : temp.keySet()) {
            NanoVG.nvgDeleteImage(vg, imageHashMap.get(image).getImage());
            imageHashMap.remove(image);
        }
    }

    /**
     * Get a loaded SVG from the cache.
     * <p><b>Requires the SVG to have been loaded first.</b></p>
     *
     * @param fileName The name of the file to load.
     * @return The SVG
     * @see AssetLoader#loadSVG(long, String, float, float)
     */
    public int getSVG(String fileName, float width, float height) {
        String name = fileName + "-" + width + "-" + height;
        return svgHashMap.get(name).getImage();
    }

    /**
     * Get a loaded assets from the cache.
     * <p><b>Requires the assets to have been loaded first.</b></p>
     *
     * @param fileName The name of the file to load.
     * @return The SVG and its data
     * @see AssetLoader#loadImage(long, String)
     */
    public NVGAsset getNVGSVG(String fileName) {
        return svgHashMap.get(fileName);
    }

    /**
     * Remove an SVG from the cache, allowing the SVG to be garbage collected.
     * Should be used when the GUI rendering the SVG is closed.
     *
     * @param vg       The NanoVG context.
     * @param fileName The name of the file to remove.
     * @see AssetLoader#loadSVG(long, String, float, float)
     */
    public void removeSVG(long vg, String fileName, float width, float height) {
        String name = fileName + "-" + width + "-" + height;
        NanoVG.nvgDeleteImage(vg, imageHashMap.get(name).getImage());
        svgHashMap.remove(name);
    }

    /**
     * Clears all SVGs from the cache, allowing the SVGs cleared to be garbage collected.
     * Should be used when the GUI rendering loaded SVGs are closed.
     *
     * @param vg The NanoVG context.
     */
    public void clearSVGs(long vg) {
        HashMap<String, NVGAsset> temp = new HashMap<>(svgHashMap);
        for (String image : temp.keySet()) {
            NanoVG.nvgDeleteImage(vg, svgHashMap.get(image).getImage());
            svgHashMap.remove(image);
        }
    }

    /**
     * Convert the given image (as a quantified path) to an IntBuffer, of its pixels, in order, stored as integers in ARGB format.
     * Mostly an internal method; used by LWJGL.
     *
     * @param fileName quantified path to the image
     * @return intBuffer of the image's pixels in ARGB format
     */
    public IntBuffer imageToIntBuffer(String fileName) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream(fileName);
            BufferedImage img = ImageIO.read(Objects.requireNonNull(inputStream));
            int width = img.getWidth();
            int height = img.getHeight();
            IntBuffer intBuffer = BufferUtils.createIntBuffer(256);
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    intBuffer.put(img.getRGB(x, y));
                }
            }
            return intBuffer;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Failed to load asset: " + fileName);
            return BufferUtils.createIntBuffer(256);
        }

    }
}