source: TFP-WebServer/WebServer/src/UrlHandlers/ItemIconHandler.cs@ 505

Last change on this file since 505 was 505, checked in by alloc, 5 days ago

Changed: Load item icons in a coroutine to reduce time needed to get server in a connectable state
Fixed: WebAPI "Player" returns player levels again

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