13 private class ThreadData
15 public readonly
int Start;
16 public readonly
int End;
18 public ThreadData(
int s,
int e)
25 private static Color[] texColors;
26 private static Color[] newColors;
28 private static float ratioX;
29 private static float ratioY;
30 private static int w2;
31 private static int finishCount;
32 private static Mutex mutex;
34 public static void Point(Texture2D tex,
int newWidth,
int newHeight)
36 ThreadedScale(tex, newWidth, newHeight,
false);
39 public static void Bilinear(Texture2D tex,
int newWidth,
int newHeight)
41 ThreadedScale(tex, newWidth, newHeight,
true);
44 private static void ThreadedScale(Texture2D tex,
int newWidth,
int newHeight,
bool useBilinear)
46 texColors = tex.GetPixels();
47 newColors =
new Color[newWidth * newHeight];
50 ratioX = 1.0f / ((float)newWidth / (tex.width - 1));
51 ratioY = 1.0f / ((float)newHeight / (tex.height - 1));
55 ratioX = (float)tex.width / newWidth;
56 ratioY = (
float)tex.height / newHeight;
60 var cores = Mathf.Min(SystemInfo.processorCount, newHeight);
61 var slice = newHeight / cores;
67 mutex =
new Mutex(
false);
73 ThreadData threadData;
75 for (i = 0; i < cores - 1; i++)
77 threadData =
new ThreadData(slice * i, slice * (i + 1));
78 ParameterizedThreadStart ts = useBilinear ? BilinearScale :
new ParameterizedThreadStart(PointScale);
79 var thread =
new Thread(ts);
80 thread.Start(threadData);
83 threadData =
new ThreadData(slice * i, newHeight);
86 BilinearScale(threadData);
90 PointScale(threadData);
93 while (finishCount < cores)
100 var threadData =
new ThreadData(0, newHeight);
104 BilinearScale(threadData);
108 PointScale(threadData);
112 tex.Resize(newWidth, newHeight, TextureFormat.ARGB32,
false);
113 tex.SetPixels(newColors);
122 var threadData = (ThreadData)obj;
123 for (var y = threadData.Start; y < threadData.End; y++)
125 int yFloor = (int)Mathf.Floor(y * ratioY);
127 var y2 = (yFloor + 1) * w;
130 for (var x = 0; x < w2; x++)
132 int xFloor = (int)Mathf.Floor(x * ratioX);
133 var xLerp = x * ratioX - xFloor;
134 newColors[yw + x] = ColorLerpUnclamped(ColorLerpUnclamped(texColors[y1 + xFloor], texColors[y1 + xFloor + 1], xLerp),
135 ColorLerpUnclamped(texColors[y2 + xFloor], texColors[y2 + xFloor + 1], xLerp),
136 y * ratioY - yFloor);
142 mutex.ReleaseMutex();
147 var threadData = (ThreadData)obj;
148 for (var y = threadData.Start; y < threadData.End; y++)
150 var thisY = (int)(ratioY * y) * w;
152 for (var x = 0; x < w2; x++)
154 newColors[yw + x] = texColors[(int)(thisY + ratioX * x)];
160 mutex.ReleaseMutex();
163 private static Color ColorLerpUnclamped(Color c1, Color c2,
float value)
165 return new Color(c1.r + (c2.r - c1.r) * value,
166 c1.g + (c2.g - c1.g) * value,
167 c1.b + (c2.b - c1.b) * value,
168 c1.a + (c2.a - c1.a) * value);
static void Point(Texture2D tex, int newWidth, int newHeight)
static void PointScale(object obj)
static void Bilinear(Texture2D tex, int newWidth, int newHeight)
static void BilinearScale(object obj)