grafix_toolbox/kit/opengl/buffer/
mapping.rs

1use super::*;
2
3impl<T: Buffer, D> ArrObject<T, D> {
4	pub fn new(args: impl AllocArgs<D>) -> Self {
5		let (ptr, size, usage) = args.geta();
6		let o = Self::new_empty(size);
7		GL!(glBufferStorage(T::TYPE, o.obj, isize(o.size()), ptr, usage));
8		o
9	}
10	pub fn Update(&mut self, args: impl UpdateArgs<D>) {
11		let (ptr, size, offset) = args.getu();
12		ASSERT!(self.len >= offset + size, "Buffer {}({}) updated out of bounds", self.obj, type_name::<T>());
13		let s = type_size::<D>();
14		GL!(glBufferSubData(T::TYPE, self.obj, isize(offset * s), isize(size * s), ptr));
15	}
16	pub fn Map(&mut self, args: impl MappingArgs) -> Mapping<T, D> {
17		let (offset, len, access) = get_mapping_args(self, args);
18		Mapping::new(self, offset, len, access | gl::MAP_READ_BIT)
19	}
20	pub fn MapMut(&mut self, args: impl MappingArgs) -> MappingMut<T, D> {
21		let (offset, len, access) = get_mapping_args(self, args);
22		MappingMut::new(self, offset, len, access | gl::MAP_WRITE_BIT)
23	}
24}
25
26pub struct Mapping<'l, T: Buffer, D> {
27	o: &'l ArrObject<T, D>,
28	size: usize,
29	pub raw_mem: *const D,
30}
31impl<'l, T: Buffer, D> Mapping<'l, T, D> {
32	pub fn new(o: &'l ArrObject<T, D>, offset: isize, len: usize, access: GLbitfield) -> Self {
33		let raw_mem = GL!(glMapBufferRange(T::TYPE, o.obj, offset, isize(len), access)) as *const D;
34		Self { o, size: len / type_size::<D>(), raw_mem }
35	}
36	pub fn mem(&self) -> &'l [D] {
37		unsafe { slice::from_raw_parts(self.raw_mem, self.size) }
38	}
39}
40impl<T: Buffer, D> Drop for Mapping<'_, T, D> {
41	fn drop(&mut self) {
42		let _valid = GL!(glUnmapBuffer(T::TYPE, self.o.obj));
43		ASSERT!(_valid == gl::TRUE, "Buffer memory was corrupted by OS");
44	}
45}
46
47pub struct MappingMut<'l, T: Buffer, D> {
48	o: &'l ArrObject<T, D>,
49	size: usize,
50	pub raw_mem: *mut D,
51}
52impl<'l, T: Buffer, D> MappingMut<'l, T, D> {
53	pub fn new(o: &'l mut ArrObject<T, D>, offset: isize, len: usize, access: GLbitfield) -> Self {
54		let raw_mem = GL!(glMapBufferRange(T::TYPE, o.obj, offset, isize(len), access)) as *mut D;
55		Self { o, size: len / type_size::<D>(), raw_mem }
56	}
57	pub fn mem(&self) -> &'l mut [D] {
58		unsafe { slice::from_raw_parts_mut(self.raw_mem, self.size) }
59	}
60}
61impl<T: Buffer, D> Drop for MappingMut<'_, T, D> {
62	fn drop(&mut self) {
63		let _valid = GL!(glUnmapBuffer(T::TYPE, self.o.obj));
64		ASSERT!(_valid == gl::TRUE, "Buffer memory was corrupted by OS");
65	}
66}