-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathETCEncoder.cs
More file actions
93 lines (77 loc) · 3 KB
/
ETCEncoder.cs
File metadata and controls
93 lines (77 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System.Runtime.CompilerServices;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
#if Windows
using ETCEncodingDemo.Native.Win64;
#else
using ETCEncodingDemo.Native.Linux64;
#endif
namespace ETCEncodingDemo;
public class ETCEncoder<TPixel> where TPixel : unmanaged, IPixel<TPixel>
{
private readonly byte[] _image;
private readonly int _width;
private readonly int _height;
public ETCEncoder(Image<TPixel> sourceImage)
{
_width = sourceImage.Width;
_height = sourceImage.Height;
byte[] pixels = new byte[_width * _height * Unsafe.SizeOf<Bgra32>()];
if (typeof(TPixel) != typeof(Bgra32)) // no need to duplicate if correct type
{
var bgraPixels = sourceImage.CloneAs<Bgra32>();
bgraPixels.CopyPixelDataTo(pixels);
bgraPixels.Dispose();
}
else
{
sourceImage.CopyPixelDataTo(pixels);
}
_image = pixels;
}
public unsafe void ConvertToETC1(Stream outputStream, bool dither, bool writePkmHeader)
{
byte[] outputBuffer = new byte[(_width * _height / 2) + (int)(writePkmHeader ? UnityImageEncoding.PkmHeaderSize : 0)];
byte[] inputBuffer = _image;
fixed (byte* outputPtr = outputBuffer)
{
fixed (byte* inputPtr = inputBuffer)
{
var code = UnityImageEncoding.EncodeETC1(inputPtr, outputPtr, (uint)_width, (uint)_height, dither, writePkmHeader);
if (code != 0)
throw new Exception($"ETC1 Encoder returned status code {code}.");
}
}
outputStream.Write(outputBuffer);
}
public unsafe void ConvertToETC2Alpha(Stream outputStream, bool writePkmHeader)
{
byte[] outputBuffer = new byte[(_width * _height) + (int)(writePkmHeader ? UnityImageEncoding.PkmHeaderSize : 0)];
byte[] inputBuffer = _image;
fixed (byte* outputPtr = outputBuffer)
{
fixed (byte* inputPtr = inputBuffer)
{
var code = UnityImageEncoding.EncodeETC2Alpha(inputPtr, outputPtr, (uint)_width, (uint)_height, writePkmHeader);
if (code != 0)
throw new Exception($"ETC2A Encoder returned status code {code}.");
}
}
outputStream.Write(outputBuffer);
}
public unsafe void ConvertToETC2(Stream outputStream, bool writePkmHeader)
{
byte[] outputBuffer = new byte[(_width * _height / 2) + (int)(writePkmHeader ? UnityImageEncoding.PkmHeaderSize : 0)];
byte[] inputBuffer = _image;
fixed (byte* outputPtr = outputBuffer)
{
fixed (byte* inputPtr = inputBuffer)
{
var code = UnityImageEncoding.EncodeETC2(inputPtr, outputPtr, (uint)_width, (uint)_height, writePkmHeader);
if (code != 0)
throw new Exception($"ETC2 Encoder returned status code {code}.");
}
}
outputStream.Write(outputBuffer);
}
}