improved texture indexing

This commit is contained in:
Andrew Cassidy 2021-03-29 22:56:25 -07:00
parent 22bbdeb7b8
commit bd454d9d20
3 changed files with 28 additions and 8 deletions

View File

@ -101,8 +101,16 @@ PYBIND11_MODULE(_quicktex, m) {
py::class_<RawTexture> raw_texture(m, "RawTexture", texture); py::class_<RawTexture> raw_texture(m, "RawTexture", texture);
raw_texture.def(py::init<int, int>(), "width"_a, "height"_a); raw_texture.def(py::init<int, int>(), "width"_a, "height"_a);
raw_texture.def("get_pixel", &RawTexture::GetPixel); raw_texture.def("__getitem__", [](RawTexture &t, std::tuple<int, int> pnt) {
raw_texture.def("set_pixel", &RawTexture::SetPixel); int x, y;
PyIndex2D(pnt, t.Dimensions(), x, y);
return t.GetPixel(x, y);
});
raw_texture.def("__setitem__", [](RawTexture &t, std::tuple<int, int> pnt, Color val) {
int x, y;
PyIndex2D(pnt, t.Dimensions(), x, y);
t.SetPixel(x, y, val);
});
raw_texture.def_static("frombytes", &BufferToTexture<RawTexture>, "data"_a, "width"_a, "height"_a); raw_texture.def_static("frombytes", &BufferToTexture<RawTexture>, "data"_a, "width"_a, "height"_a);

View File

@ -60,6 +60,18 @@ template <typename T> T BufferToTexture(py::buffer buf, int width, int height) {
return output; return output;
} }
inline int PyIndex(int val, int size) {
if (val < -size) throw std::range_error("index out of range");
if (val >= size) throw std::range_error("index out of range");
if (val < 0) return size + val;
return val;
}
inline void PyIndex2D(std::tuple<int, int> pnt, std::tuple<int, int> size, int& x, int& y) {
x = PyIndex(std::get<0>(pnt), std::get<0>(size));
y = PyIndex(std::get<1>(pnt), std::get<1>(size));
}
template <typename B> py::class_<BlockTexture<B>> BindBlockTexture(py::module_& m, const char* name) { template <typename B> py::class_<BlockTexture<B>> BindBlockTexture(py::module_& m, const char* name) {
using BTex = BlockTexture<B>; using BTex = BlockTexture<B>;

View File

@ -25,12 +25,12 @@ class TestRawTexture(unittest.TestCase):
color1 = (69, 13, 12, 0) # totally random color color1 = (69, 13, 12, 0) # totally random color
color2 = (19, 142, 93, 44) color2 = (19, 142, 93, 44)
self.texture.set_pixel(0, 0, color1) self.texture[0, 0] = color1
self.texture.set_pixel(self.width - 1, self.height - 1, color2) self.texture[-1, -1] = color2
data = self.texture.tobytes() data = self.texture.tobytes()
self.assertEqual(self.texture.get_pixel(0, 0), color1) self.assertEqual(self.texture[0, 0], color1)
self.assertEqual(self.texture.get_pixel(self.width - 1, self.height - 1), color2) self.assertEqual(self.texture[-1, -1], color2)
self.assertEqual(tuple(data[0:4]), color1) self.assertEqual(tuple(data[0:4]), color1)
self.assertEqual(tuple(data[-4:]), color2) self.assertEqual(tuple(data[-4:]), color2)