18 private static Color[] texColors;
19 private static Color[] newColors;
21 private static float ratioX;
22 private static float ratioY;
23 private static int w2;
24 private static int finishCount;
25 private static Mutex mutex;
27 public static void Point(Texture2D tex,
int newWidth,
int newHeight)
29 ThreadedScale(tex, newWidth, newHeight,
false);
32 public static void Bilinear(Texture2D tex,
int newWidth,
int newHeight)
34 ThreadedScale(tex, newWidth, newHeight,
true);
37 private static void ThreadedScale(Texture2D tex,
int newWidth,
int newHeight,
bool useBilinear)
39 texColors = tex.GetPixels();
40 newColors =
new Color[newWidth * newHeight];
43 ratioX = 1.0f / ((float) newWidth / (tex.width - 1));
44 ratioY = 1.0f / ((float) newHeight / (tex.height - 1));
48 ratioX = (float) tex.width / newWidth;
49 ratioY = (
float) tex.height / newHeight;
54 var cores = Mathf.Min(SystemInfo.processorCount, newHeight);
55 var slice = newHeight / cores;
58 if (mutex ==
null) mutex =
new Mutex(
false);
62 ThreadData threadData;
63 for (i = 0; i < cores - 1; i++)
65 threadData =
new ThreadData(slice * i, slice * (i + 1));
67 var thread =
new Thread(ts);
68 thread.Start(threadData);
71 threadData =
new ThreadData(slice * i, newHeight);
76 while (finishCount < cores) Thread.Sleep(1);
80 var threadData =
new ThreadData(0, newHeight);
87 tex.Resize(newWidth, newHeight);
88 tex.SetPixels(newColors);
95 for (var y = threadData.start; y < threadData.end; y++)
97 var yFloor = (int) Mathf.Floor(y * ratioY);
99 var y2 = (yFloor + 1) * w;
102 for (var x = 0; x < w2; x++)
104 var xFloor = (int) Mathf.Floor(x * ratioX);
105 var xLerp = x * ratioX - xFloor;
106 newColors[yw + x] = ColorLerpUnclamped(
107 ColorLerpUnclamped(texColors[y1 + xFloor], texColors[y1 + xFloor + 1], xLerp),
108 ColorLerpUnclamped(texColors[y2 + xFloor], texColors[y2 + xFloor + 1], xLerp),
109 y * ratioY - yFloor);
115 mutex.ReleaseMutex();
121 for (var y = threadData.start; y < threadData.end; y++)
123 var thisY = (int) (ratioY * y) * w;
125 for (var x = 0; x < w2; x++) newColors[yw + x] = texColors[(
int) (thisY + ratioX * x)];
130 mutex.ReleaseMutex();
133 private static Color ColorLerpUnclamped(
Color c1,
Color c2,
float value)
135 return new Color(c1.r + (c2.r - c1.r) * value,
136 c1.g + (c2.g - c1.g) * value,
137 c1.b + (c2.b - c1.b) * value,
138 c1.a + (c2.a - c1.a) * value);
static void BilinearScale(object obj)
static void PointScale(object obj)
static void Point(Texture2D tex, int newWidth, int newHeight)
static void Bilinear(Texture2D tex, int newWidth, int newHeight)