primitive.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. //! Console primitive types the host lacks. A rectangle list gives three
  2. //! corners per rectangle, the second the one between the other two, and
  3. //! the hardware adds the fourth at `v0 + v2 - v1` (the title's
  4. //! full-screen rectangles come as top left, bottom left, bottom right); on
  5. //! the host each rectangle becomes two triangles, with the fourth vertex
  6. //! made from the other three on the CPU.
  7. //!
  8. //! shortcut: the fourth vertex is computed from vertex inputs, not from
  9. //! vertex shader outputs as the hardware does; that is the same for vertex
  10. //! shaders linear in their inputs (blits, 2D quads). Inputs in formats
  11. //! [`components`] does not know keep the first vertex's value, and so do
  12. //! components past the end of the vertex (an element that reaches into the
  13. //! next one, which the layout allows).
  14. //!
  15. //! A pipeline the title makes for rectangles completes them on the GPU
  16. //! instead, in a geometry stage (`victory_shader::emit::rect_list_gs`):
  17. //! from the vertex shader's outputs, whichever vertex the corner is, for
  18. //! direct, indexed and indirect draws alike. This expansion is what is
  19. //! left for a pipeline that could not get that stage.
  20. /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six
  21. /// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both
  22. /// triangles turn the same way. `elements` are (byte offset, format).
  23. pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) {
  24. if stride == 0 {
  25. return;
  26. }
  27. let (Some(in_rect), Some(out_rect)) = (stride.checked_mul(3), stride.checked_mul(6)) else {
  28. return;
  29. };
  30. for (rect, out) in src
  31. .chunks_exact(in_rect)
  32. .zip(dst.chunks_exact_mut(out_rect))
  33. {
  34. let v = |i: usize| &rect[i * stride..(i + 1) * stride];
  35. for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() {
  36. out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i));
  37. }
  38. let fourth = &mut out[5 * stride..];
  39. fourth.copy_from_slice(v(0));
  40. for &(offset, format) in elements {
  41. let at = offset as usize;
  42. let Some((n, kind)) = components(format) else {
  43. continue;
  44. };
  45. // Only the components inside the vertex: the rest belong to the
  46. // next one.
  47. let inside = stride.saturating_sub(at) / kind.bytes();
  48. for c in 0..n.min(inside) {
  49. let get = |i: usize| kind.read(&v(i)[at..], c);
  50. let value = get(0) + get(2) - get(1);
  51. kind.write(&mut fourth[at..], c, value);
  52. }
  53. }
  54. }
  55. }
  56. #[derive(Clone, Copy)]
  57. enum Kind {
  58. F32,
  59. F16,
  60. Unorm8,
  61. Unorm16,
  62. Snorm8,
  63. Snorm16,
  64. }
  65. /// Component count and kind of the vertex formats rectangles use.
  66. fn components(format: u32) -> Option<(usize, Kind)> {
  67. Some(match format {
  68. 2 => (4, Kind::F32),
  69. 6 => (3, Kind::F32),
  70. 16 => (2, Kind::F32),
  71. 41 => (1, Kind::F32),
  72. 10 => (4, Kind::F16),
  73. 34 => (2, Kind::F16),
  74. 54 => (1, Kind::F16),
  75. 11 => (4, Kind::Unorm16),
  76. 35 => (2, Kind::Unorm16),
  77. 56 => (1, Kind::Unorm16),
  78. 28 | 29 | 87 | 91 => (4, Kind::Unorm8),
  79. 49 => (2, Kind::Unorm8),
  80. 61 => (1, Kind::Unorm8),
  81. 13 => (4, Kind::Snorm16),
  82. 37 => (2, Kind::Snorm16),
  83. 58 => (1, Kind::Snorm16),
  84. 31 => (4, Kind::Snorm8),
  85. 51 => (2, Kind::Snorm8),
  86. 63 => (1, Kind::Snorm8),
  87. _ => return None,
  88. })
  89. }
  90. impl Kind {
  91. fn bytes(self) -> usize {
  92. match self {
  93. Kind::F32 => 4,
  94. Kind::F16 | Kind::Unorm16 | Kind::Snorm16 => 2,
  95. Kind::Unorm8 | Kind::Snorm8 => 1,
  96. }
  97. }
  98. fn read(self, at: &[u8], c: usize) -> f32 {
  99. let b = &at[c * self.bytes()..];
  100. match self {
  101. Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
  102. Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])),
  103. Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0,
  104. Kind::Unorm8 => f32::from(b[0]) / 255.0,
  105. Kind::Snorm16 => (f32::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).max(-1.0),
  106. Kind::Snorm8 => (f32::from(b[0] as i8) / 127.0).max(-1.0),
  107. }
  108. }
  109. fn write(self, at: &mut [u8], c: usize, v: f32) {
  110. let n = self.bytes();
  111. let b = &mut at[c * n..(c + 1) * n];
  112. match self {
  113. Kind::F32 => b.copy_from_slice(&v.to_le_bytes()),
  114. Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()),
  115. Kind::Unorm16 => {
  116. b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes())
  117. }
  118. Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8,
  119. Kind::Snorm16 => {
  120. b.copy_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes())
  121. }
  122. Kind::Snorm8 => b[0] = (v.clamp(-1.0, 1.0) * 127.0).round() as i8 as u8,
  123. }
  124. }
  125. }
  126. fn half_to_f32(h: u16) -> f32 {
  127. let sign = u32::from(h >> 15) << 31;
  128. let exp = u32::from((h >> 10) & 0x1f);
  129. let man = u32::from(h & 0x3ff);
  130. let bits = match (exp, man) {
  131. (0, 0) => sign,
  132. // Subnormal: scale the mantissa.
  133. (0, m) => {
  134. let v = m as f32 * 2f32.powi(-24);
  135. return if sign != 0 { -v } else { v };
  136. }
  137. (31, m) => sign | 0x7f80_0000 | m << 13,
  138. (e, m) => sign | (e + 112) << 23 | m << 13,
  139. };
  140. f32::from_bits(bits)
  141. }
  142. fn f32_to_half(v: f32) -> u16 {
  143. let bits = v.to_bits();
  144. let sign = ((bits >> 16) & 0x8000) as u16;
  145. let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
  146. let man = bits & 0x7f_ffff;
  147. if exp >= 31 {
  148. return sign | 0x7c00; // too large: infinity
  149. }
  150. if exp <= 0 {
  151. if exp < -10 {
  152. return sign; // below half the smallest subnormal: zero
  153. }
  154. // Half subnormals are `m * 2^-24`. An f32 in this range is still
  155. // normal (exponent field >= 1), so its significand has the implicit
  156. // leading 1; shift it into the half mantissa, rounding to even.
  157. let sig = (1u32 << 23) | man;
  158. let shift = (14 - exp) as u32;
  159. let halfway = 1u32 << (shift - 1);
  160. let q = sig >> shift;
  161. let r = sig & ((1u32 << shift) - 1);
  162. let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0));
  163. return sign | m as u16;
  164. }
  165. // Rounded to nearest: a carry out of the mantissa is added into the
  166. // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00.
  167. let half = (exp as u32) << 10;
  168. sign | (half + ((man + 0x1000) >> 13)) as u16
  169. }
  170. #[cfg(test)]
  171. mod tests {
  172. use super::*;
  173. /// A rectangle of float2 positions and RGBA8 colors, given as top
  174. /// left, bottom left, bottom right: the fourth corner completes the
  175. /// parallelogram at the top right.
  176. #[test]
  177. fn rectangles_get_their_fourth_corner() {
  178. let vertex = |x: f32, y: f32, r: u8| {
  179. let mut v = Vec::new();
  180. v.extend(x.to_le_bytes());
  181. v.extend(y.to_le_bytes());
  182. v.extend([r, 0, 0, 255]);
  183. v
  184. };
  185. let src: Vec<u8> = [
  186. vertex(-1.0, 1.0, 0),
  187. vertex(-1.0, -1.0, 100),
  188. vertex(1.0, -1.0, 150),
  189. ]
  190. .concat();
  191. let mut dst = vec![0u8; 6 * 12];
  192. expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]);
  193. assert_eq!(dst[..36], src[..]);
  194. assert_eq!(dst[36..48], src[..12]);
  195. assert_eq!(dst[48..60], src[24..36]);
  196. assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]);
  197. assert_eq!(f32_to_half(1.5), 0x3e00);
  198. assert_eq!(half_to_f32(0x3e00), 1.5);
  199. assert_eq!(half_to_f32(0xc000), -2.0);
  200. }
  201. /// A rounding that carries out of the mantissa raises the exponent
  202. /// (the carry used to be or-ed into an odd exponent, halving the value).
  203. #[test]
  204. fn halves_round_up_into_the_next_power_of_two() {
  205. assert_eq!(f32_to_half(2.0 - 2f32.powi(-12)), 0x4000);
  206. assert_eq!(f32_to_half(0.5 - 2f32.powi(-13)), 0x3800);
  207. assert_eq!(f32_to_half(65520.0), 0x7c00, "past the largest half");
  208. // An R16_FLOAT element at 1.0, 2^-12 and 1.0: the fourth corner is
  209. // 2 - 2^-12, which rounds to 2.0.
  210. let src: Vec<u8> = [0x3c00_u16, 0x0c00, 0x3c00]
  211. .iter()
  212. .flat_map(|h| h.to_le_bytes())
  213. .collect();
  214. let mut dst = vec![0u8; 6 * 2];
  215. expand_rects(&src, &mut dst, 2, &[(0, 54)]);
  216. assert_eq!(dst[10..], 0x4000_u16.to_le_bytes());
  217. }
  218. /// An element that reaches past the stride (float4 at 4 in 8-byte
  219. /// vertices, RGBA8 at the stride itself): the components inside get
  220. /// the fourth corner, the rest keep the first vertex's bytes. The old
  221. /// code indexed past the vertex and panicked.
  222. #[test]
  223. fn elements_past_the_stride_are_left_alone() {
  224. let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat();
  225. let src = [vertex(0.0, 2.0), vertex(1.0, 3.0), vertex(5.0, 7.0)].concat();
  226. let mut dst = vec![0u8; 6 * 8];
  227. expand_rects(&src, &mut dst, 8, &[(0, 16), (4, 2), (8, 28)]);
  228. assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]);
  229. assert_eq!(dst[40..], vertex(4.0, 6.0)[..]);
  230. }
  231. #[test]
  232. fn normalized_attributes_are_interpolated_in_their_own_range() {
  233. let vertex = |rg: [u8; 2], u16_value: u16, u8_value: u8, snorm8: i8, snorm16: i16| {
  234. [
  235. &rg[..],
  236. &u16_value.to_le_bytes(),
  237. &[u8_value, snorm8 as u8],
  238. &snorm16.to_le_bytes(),
  239. ]
  240. .concat()
  241. };
  242. let src = [
  243. vertex([3, 250], 1000, 10, i8::MIN, -23000),
  244. vertex([8, 200], 500, 3, -120, -18000),
  245. vertex([20, 253], 10000, 100, -120, -32000),
  246. ]
  247. .concat();
  248. let mut dst = [0; 6 * 8];
  249. expand_rects(
  250. &src,
  251. &mut dst,
  252. 8,
  253. &[(0, 49), (2, 56), (4, 61), (5, 63), (6, 58)],
  254. );
  255. assert_eq!(dst[40..], vertex([15, 255], 10500, 107, -127, -32767));
  256. }
  257. /// `half_to_f32` reads subnormals, so an f16 rectangle output must be
  258. /// able to write them back instead of flushing every one to zero.
  259. #[test]
  260. fn half_subnormals_convert_in_both_directions() {
  261. assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001);
  262. assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001);
  263. assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002);
  264. assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff);
  265. // Ties go to an even mantissa: 0/1 and 1/2.
  266. assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000);
  267. assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002);
  268. // Below half the smallest subnormal, and normal values, are unchanged.
  269. assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000);
  270. assert_eq!(f32_to_half(1.5), 0x3e00);
  271. assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
  272. }
  273. #[test]
  274. fn zero_or_overflowing_stride_is_ignored_without_panicking() {
  275. let mut dst = [0xAAu8; 16];
  276. expand_rects(&[1, 2, 3], &mut dst, 0, &[(0, 16)]);
  277. assert_eq!(dst, [0xAAu8; 16]);
  278. expand_rects(&[1, 2, 3], &mut dst, usize::MAX / 2, &[(0, 16)]);
  279. assert_eq!(dst, [0xAAu8; 16]);
  280. }
  281. #[test]
  282. fn unorm16_unorm8_clamping_and_unknown_formats_expand_correctly() {
  283. // Vertex layout (12 bytes):
  284. // 0..4: R16G16_UNORM (format 35)
  285. // 4..8: R8G8B8A8_UNORM (format 28) — tests clamping below 0 and above 1
  286. // 8..12: unknown format (999) — must keep v0's bytes verbatim
  287. let v = |u0: u16, u1: u16, c: [u8; 4], raw: [u8; 4]| {
  288. let mut b = Vec::with_capacity(12);
  289. b.extend(u0.to_le_bytes());
  290. b.extend(u1.to_le_bytes());
  291. b.extend(c);
  292. b.extend(raw);
  293. b
  294. };
  295. let src = [
  296. v(
  297. 10_000,
  298. 50_000,
  299. [10, 200, 100, 255],
  300. [0xDE, 0xAD, 0xBE, 0xEF],
  301. ),
  302. v(20_000, 10_000, [100, 50, 100, 255], [1, 2, 3, 4]),
  303. v(30_000, 20_000, [20, 200, 100, 255], [5, 6, 7, 8]),
  304. ]
  305. .concat();
  306. let mut dst = vec![0u8; 6 * 12];
  307. expand_rects(&src, &mut dst, 12, &[(0, 35), (4, 28), (8, 999)]);
  308. let fourth = &dst[60..72];
  309. // u0: 10000 + 30000 - 20000 = 20000; u1: 50000 + 20000 - 10000 = 60000
  310. assert_eq!(u16::from_le_bytes([fourth[0], fourth[1]]), 20_000);
  311. assert_eq!(u16::from_le_bytes([fourth[2], fourth[3]]), 60_000);
  312. // c0: 10 + 20 - 100 -> clamped to 0; c1: 200 + 200 - 50 -> clamped to 255
  313. assert_eq!(&fourth[4..8], &[0, 255, 100, 255]);
  314. // Unknown format keeps v0 bytes
  315. assert_eq!(&fourth[8..12], &[0xDE, 0xAD, 0xBE, 0xEF]);
  316. }
  317. #[test]
  318. fn multiple_rectangles_and_f32_f16_vector_formats_expand_in_sequence() {
  319. // Two rectangles of R32G32B32_FLOAT (format 6, 12 bytes) + R16G16_FLOAT (format 34, 4 bytes) = 16 bytes
  320. let v = |p: [f32; 3], uv: [f32; 2]| {
  321. let mut b = Vec::with_capacity(16);
  322. for x in p {
  323. b.extend(x.to_le_bytes());
  324. }
  325. for x in uv {
  326. b.extend(f32_to_half(x).to_le_bytes());
  327. }
  328. b
  329. };
  330. let src = [
  331. // Rect 0
  332. v([0.0, 1.0, 0.5], [0.0, 0.0]),
  333. v([0.0, 0.0, 0.5], [0.0, 1.0]),
  334. v([2.0, 0.0, 0.5], [1.0, 1.0]),
  335. // Rect 1
  336. v([10.0, 20.0, 1.0], [0.25, 0.5]),
  337. v([10.0, 10.0, 1.0], [0.25, 1.0]),
  338. v([14.0, 10.0, 1.0], [0.75, 1.0]),
  339. ]
  340. .concat();
  341. let mut dst = vec![0u8; 12 * 16];
  342. expand_rects(&src, &mut dst, 16, &[(0, 6), (12, 34)]);
  343. assert_eq!(&dst[5 * 16..6 * 16], &v([2.0, 1.0, 0.5], [1.0, 0.0])[..]);
  344. assert_eq!(
  345. &dst[11 * 16..12 * 16],
  346. &v([14.0, 20.0, 1.0], [0.75, 0.5])[..]
  347. );
  348. }
  349. }