source: binary-improvements2/WebServer/src/UrlHandlers/ItemIconHandler.cs@ 415

Last change on this file since 415 was 402, checked in by alloc, 22 months ago
  • Major refactoring
  • Using Utf8Json for (de)serialization
  • Moving APIs to REST
  • Removing dependencies from WebServer and MapRenderer to ServerFixes
File size: 5.8 KB
RevLine 
[391]1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Net;
5using UnityEngine;
6using Object = UnityEngine.Object;
7
8namespace Webserver.UrlHandlers {
9 public class ItemIconHandler : AbsHandler {
10 private readonly Dictionary<string, byte[]> icons = new Dictionary<string, byte[]> ();
11 private readonly bool logMissingFiles;
12
13 private bool loaded;
14
15 static ItemIconHandler () {
16 Instance = null;
17 }
18
19 public ItemIconHandler (bool _logMissingFiles, string _moduleName = null) : base (_moduleName) {
20 logMissingFiles = _logMissingFiles;
21 Instance = this;
22 }
23
24 public static ItemIconHandler Instance { get; private set; }
25
26 public override void HandleRequest (RequestContext _context) {
27 if (!loaded) {
28 _context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
[399]29 Log.Out ("[Web] IconHandler: Icons not loaded");
[391]30 return;
31 }
32
33 string requestFileName = _context.RequestPath.Remove (0, urlBasePath.Length);
34 requestFileName = requestFileName.Remove (requestFileName.LastIndexOf ('.'));
35
36 if (icons.ContainsKey (requestFileName) && _context.RequestPath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {
37 _context.Response.ContentType = MimeType.GetMimeType (".png");
38
39 byte[] itemIconData = icons [requestFileName];
40
41 _context.Response.ContentLength64 = itemIconData.Length;
42 _context.Response.OutputStream.Write (itemIconData, 0, itemIconData.Length);
43 } else {
44 _context.Response.StatusCode = (int) HttpStatusCode.NotFound;
45 if (logMissingFiles) {
[402]46 Log.Out ($"[Web] IconHandler: FileNotFound: \"{_context.RequestPath}\" ");
[391]47 }
48 }
49 }
50
[402]51 private class LoadingStats {
52 public int Files;
53 public int Tints;
54 public readonly MicroStopwatch MswTotal = new MicroStopwatch (false);
55 public readonly MicroStopwatch MswLoading = new MicroStopwatch (false);
56 public readonly MicroStopwatch MswEncoding = new MicroStopwatch (false);
57 public readonly MicroStopwatch MswTinting = new MicroStopwatch (false);
58 }
59
[391]60 public bool LoadIcons () {
61
62 lock (icons) {
63 if (loaded) {
64 return true;
65 }
66
[402]67 LoadingStats stats = new LoadingStats ();
68 stats?.MswTotal.Start ();
[391]69
70 // Get list of used tints for all items
71 Dictionary<string, List<Color>> tintedIcons = new Dictionary<string, List<Color>> ();
72 foreach (ItemClass ic in ItemClass.list) {
73 if (ic == null) {
74 continue;
75 }
76
77 Color tintColor = ic.GetIconTint ();
78 if (tintColor == Color.white) {
79 continue;
80 }
81
82 string name = ic.GetIconName ();
[402]83 if (!tintedIcons.TryGetValue (name, out List<Color> tintsList)) {
84 tintsList = new List<Color> ();
85 tintedIcons.Add (name, tintsList);
[391]86 }
87
[402]88 tintsList.Add (tintColor);
[391]89 }
90
91 try {
[402]92 loadIconsFromFolder (GameIO.GetGameDir ("Data/ItemIcons"), tintedIcons, stats);
[391]93 } catch (Exception e) {
[399]94 Log.Error ("[Web] Failed loading icons from base game");
[391]95 Log.Exception (e);
96 }
97
98 // Load icons from mods
99 foreach (Mod mod in ModManager.GetLoadedMods ()) {
100 try {
[402]101 string modIconsPath = $"{mod.Path}/ItemIcons";
102 loadIconsFromFolder (modIconsPath, tintedIcons, stats);
[391]103 } catch (Exception e) {
[402]104 Log.Error ($"[Web] Failed loading icons from mod {mod.Name}");
[391]105 Log.Exception (e);
106 }
107 }
[402]108
[391]109 loaded = true;
110
[402]111 if (stats == null) {
112 Log.Out ($"[Web] IconHandler: Loaded {icons.Count} icons");
113 } else {
114 stats?.MswTotal.Stop ();
115 Log.Out ($"[Web] IconHandler: Loaded {icons.Count} icons ({stats.Files} source images with {stats.Tints} tints applied)");
116 Log.Out ($"[Web] IconHandler: Total time {stats.MswTotal.ElapsedMilliseconds} ms, loading files {stats.MswLoading.ElapsedMilliseconds} ms, tinting files {stats.MswTinting.ElapsedMilliseconds} ms, encoding files {stats.MswEncoding.ElapsedMilliseconds} ms");
117
118 int totalSize = 0;
119 foreach ((string _, byte[] iconData) in icons) {
120 totalSize += iconData.Length;
121 }
122
123 Log.Out ($"[Web] IconHandler: Cached {totalSize / 1024} KiB");
124 }
125
[391]126 return true;
127 }
128 }
129
[402]130 private void loadIconsFromFolder (string _path, Dictionary<string, List<Color>> _tintedIcons, LoadingStats _stats) {
[391]131 if (!Directory.Exists (_path)) {
132 return;
133 }
134
135 foreach (string file in Directory.GetFiles (_path)) {
136 try {
137 if (!file.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {
138 continue;
139 }
140
141 string name = Path.GetFileNameWithoutExtension (file);
142 Texture2D tex = new Texture2D (1, 1, TextureFormat.ARGB32, false);
[402]143
144 _stats?.MswLoading.Start ();
145 byte[] sourceBytes = File.ReadAllBytes (file);
146 if (!tex.LoadImage (sourceBytes)) {
147 _stats?.MswLoading.Stop ();
[391]148 continue;
149 }
[402]150 _stats?.MswLoading.Stop ();
[391]151
[402]152 AddIcon (name, sourceBytes, tex, _tintedIcons, _stats);
[391]153
154 Object.Destroy (tex);
155 } catch (Exception e) {
156 Log.Exception (e);
157 }
158 }
159 }
160
[402]161 private void AddIcon (string _name, byte[] _sourceBytes, Texture2D _tex, Dictionary<string, List<Color>> _tintedIcons, LoadingStats _stats) {
162 _stats?.MswEncoding.Start ();
163 icons [$"{_name}__FFFFFF"] = _sourceBytes;
164 _stats?.MswEncoding.Stop ();
[391]165
[402]166 if (_stats != null) {
167 _stats.Files++;
168 }
169
170 if (!_tintedIcons.TryGetValue (_name, out List<Color> tintsList)) {
[391]171 return;
172 }
173
[402]174 foreach (Color c in tintsList) {
175 string tintedName = $"{_name}__{c.ToHexCode ()}";
[391]176 if (icons.ContainsKey (tintedName)) {
177 continue;
178 }
179
180 Texture2D tintedTex = new Texture2D (_tex.width, _tex.height, TextureFormat.ARGB32, false);
181
[402]182 _stats?.MswTinting.Start ();
183 TextureUtils.ApplyTint (_tex, tintedTex, c);
184 _stats?.MswTinting.Stop ();
[391]185
[402]186 _stats?.MswEncoding.Start ();
[391]187 icons [tintedName] = tintedTex.EncodeToPNG ();
[402]188 _stats?.MswEncoding.Stop ();
[391]189
190 Object.Destroy (tintedTex);
[402]191
192 if (_stats != null) {
193 _stats.Tints++;
194 }
[391]195 }
196 }
[402]197
[391]198 }
199}
Note: See TracBrowser for help on using the repository browser.