source: binary-improvements/7dtd-server-fixes/src/FileCache/MapTileCache.cs@ 294

Last change on this file since 294 was 269, checked in by alloc, 9 years ago

Fixes #124: Send transparent tile for map tiles not available instead of 404

File size: 2.3 KB
RevLine 
[199]1using System;
2using System.Collections.Generic;
3using System.IO;
4
5namespace AllocsFixes.FileCache
6{
7 // Special "cache" for map tile folder as both map rendering and webserver access files in there.
8 // Only map rendering tiles are cached. Writing is done by WriteThrough.
9 public class MapTileCache : AbstractCache
10 {
11 private struct CurrentZoomFile
12 {
13 public string filename;
14 public byte[] data;
15 }
16
17 private CurrentZoomFile[] cache;
18
[269]19 private byte[] transparentTile;
20
21 public MapTileCache (int _tileSize)
[199]22 {
[269]23 UnityEngine.Texture2D tex = new UnityEngine.Texture2D (_tileSize, _tileSize);
24 UnityEngine.Color nullColor = new UnityEngine.Color (0, 0, 0, 0);
25 for (int x = 0; x < _tileSize; x++) {
26 for (int y = 0; y < _tileSize; y++) {
27 tex.SetPixel (x, y, nullColor);
28 }
29 }
30 transparentTile = tex.EncodeToPNG ();
31 UnityEngine.Object.Destroy (tex);
[199]32 }
33
34 public void SetZoomCount (int count)
35 {
36 cache = new CurrentZoomFile[count];
37 }
38
39 public byte[] LoadTile (int zoomlevel, string filename)
40 {
41 try {
42 lock (cache) {
43 if (cache [zoomlevel].filename == null || !cache [zoomlevel].filename.Equals (filename)) {
44 cache [zoomlevel].filename = filename;
45
46 if (!File.Exists (filename)) {
47 cache [zoomlevel].data = null;
48 return null;
49 }
50
51 cache [zoomlevel].data = File.ReadAllBytes (filename);
52 }
53 return cache [zoomlevel].data;
54 }
55 } catch (Exception e) {
56 Log.Out ("Error in MapTileCache.LoadTile: " + e);
57 }
58 return null;
59 }
60
61 public void SaveTile (int zoomlevel, byte[] content)
62 {
63 try {
64 lock (cache) {
65 if (cache [zoomlevel].filename != null) {
66 cache [zoomlevel].data = content;
67 File.WriteAllBytes (cache [zoomlevel].filename, content);
68 }
69 }
70 } catch (Exception e) {
71 Log.Out ("Error in MapTileCache.SaveTile: " + e);
72 }
73 }
74
75 public override byte[] GetFileContent (string filename)
76 {
77 try {
78 lock (cache) {
79 foreach (CurrentZoomFile czf in cache) {
80 if (czf.filename != null && czf.filename.Equals (filename))
81 return czf.data;
82 }
83
84 if (!File.Exists (filename)) {
[269]85 return transparentTile;
[199]86 }
87 return File.ReadAllBytes (filename);
88 }
89 } catch (Exception e) {
90 Log.Out ("Error in MapTileCache.GetFileContent: " + e);
91 }
92 return null;
93 }
94
95 }
96}
97
Note: See TracBrowser for help on using the repository browser.