2
0

primitive.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. for (rect, out) in src
  25. .chunks_exact(3 * stride)
  26. .zip(dst.chunks_exact_mut(6 * stride))
  27. {
  28. let v = |i: usize| &rect[i * stride..(i + 1) * stride];
  29. for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() {
  30. out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i));
  31. }
  32. let fourth = &mut out[5 * stride..];
  33. fourth.copy_from_slice(v(0));
  34. for &(offset, format) in elements {
  35. let at = offset as usize;
  36. let Some((n, kind)) = components(format) else {
  37. continue;
  38. };
  39. // Only the components inside the vertex: the rest belong to the
  40. // next one.
  41. let inside = stride.saturating_sub(at) / kind.bytes();
  42. for c in 0..n.min(inside) {
  43. let get = |i: usize| kind.read(&v(i)[at..], c);
  44. let value = get(0) + get(2) - get(1);
  45. kind.write(&mut fourth[at..], c, value);
  46. }
  47. }
  48. }
  49. }
  50. #[derive(Clone, Copy)]
  51. enum Kind {
  52. F32,
  53. F16,
  54. Unorm8,
  55. Unorm16,
  56. Snorm8,
  57. Snorm16,
  58. }
  59. /// Component count and kind of the vertex formats rectangles use.
  60. fn components(format: u32) -> Option<(usize, Kind)> {
  61. Some(match format {
  62. 2 => (4, Kind::F32),
  63. 6 => (3, Kind::F32),
  64. 16 => (2, Kind::F32),
  65. 41 => (1, Kind::F32),
  66. 10 => (4, Kind::F16),
  67. 34 => (2, Kind::F16),
  68. 54 => (1, Kind::F16),
  69. 11 => (4, Kind::Unorm16),
  70. 35 => (2, Kind::Unorm16),
  71. 56 => (1, Kind::Unorm16),
  72. 28 | 29 | 87 | 91 => (4, Kind::Unorm8),
  73. 49 => (2, Kind::Unorm8),
  74. 61 => (1, Kind::Unorm8),
  75. 13 => (4, Kind::Snorm16),
  76. 37 => (2, Kind::Snorm16),
  77. 58 => (1, Kind::Snorm16),
  78. 31 => (4, Kind::Snorm8),
  79. 51 => (2, Kind::Snorm8),
  80. 63 => (1, Kind::Snorm8),
  81. _ => return None,
  82. })
  83. }
  84. impl Kind {
  85. fn bytes(self) -> usize {
  86. match self {
  87. Kind::F32 => 4,
  88. Kind::F16 | Kind::Unorm16 | Kind::Snorm16 => 2,
  89. Kind::Unorm8 | Kind::Snorm8 => 1,
  90. }
  91. }
  92. fn read(self, at: &[u8], c: usize) -> f32 {
  93. let b = &at[c * self.bytes()..];
  94. match self {
  95. Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
  96. Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])),
  97. Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0,
  98. Kind::Unorm8 => f32::from(b[0]) / 255.0,
  99. Kind::Snorm16 => (f32::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).max(-1.0),
  100. Kind::Snorm8 => (f32::from(b[0] as i8) / 127.0).max(-1.0),
  101. }
  102. }
  103. fn write(self, at: &mut [u8], c: usize, v: f32) {
  104. let n = self.bytes();
  105. let b = &mut at[c * n..(c + 1) * n];
  106. match self {
  107. Kind::F32 => b.copy_from_slice(&v.to_le_bytes()),
  108. Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()),
  109. Kind::Unorm16 => {
  110. b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes())
  111. }
  112. Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8,
  113. Kind::Snorm16 => {
  114. b.copy_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes())
  115. }
  116. Kind::Snorm8 => b[0] = (v.clamp(-1.0, 1.0) * 127.0).round() as i8 as u8,
  117. }
  118. }
  119. }
  120. fn half_to_f32(h: u16) -> f32 {
  121. let sign = u32::from(h >> 15) << 31;
  122. let exp = u32::from((h >> 10) & 0x1f);
  123. let man = u32::from(h & 0x3ff);
  124. let bits = match (exp, man) {
  125. (0, 0) => sign,
  126. // Subnormal: scale the mantissa.
  127. (0, m) => {
  128. let v = m as f32 * 2f32.powi(-24);
  129. return if sign != 0 { -v } else { v };
  130. }
  131. (31, m) => sign | 0x7f80_0000 | m << 13,
  132. (e, m) => sign | (e + 112) << 23 | m << 13,
  133. };
  134. f32::from_bits(bits)
  135. }
  136. fn f32_to_half(v: f32) -> u16 {
  137. let bits = v.to_bits();
  138. let sign = ((bits >> 16) & 0x8000) as u16;
  139. let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
  140. let man = bits & 0x7f_ffff;
  141. if exp >= 31 {
  142. return sign | 0x7c00; // too large: infinity
  143. }
  144. if exp <= 0 {
  145. if exp < -10 {
  146. return sign; // below half the smallest subnormal: zero
  147. }
  148. // Half subnormals are `m * 2^-24`. An f32 in this range is still
  149. // normal (exponent field >= 1), so its significand has the implicit
  150. // leading 1; shift it into the half mantissa, rounding to even.
  151. let sig = (1u32 << 23) | man;
  152. let shift = (14 - exp) as u32;
  153. let halfway = 1u32 << (shift - 1);
  154. let q = sig >> shift;
  155. let r = sig & ((1u32 << shift) - 1);
  156. let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0));
  157. return sign | m as u16;
  158. }
  159. // Rounded to nearest: a carry out of the mantissa is added into the
  160. // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00.
  161. let half = (exp as u32) << 10;
  162. sign | (half + ((man + 0x1000) >> 13)) as u16
  163. }
  164. #[cfg(test)]
  165. mod tests {
  166. use super::*;
  167. /// A rectangle of float2 positions and RGBA8 colors, given as top
  168. /// left, bottom left, bottom right: the fourth corner completes the
  169. /// parallelogram at the top right.
  170. #[test]
  171. fn rectangles_get_their_fourth_corner() {
  172. let vertex = |x: f32, y: f32, r: u8| {
  173. let mut v = Vec::new();
  174. v.extend(x.to_le_bytes());
  175. v.extend(y.to_le_bytes());
  176. v.extend([r, 0, 0, 255]);
  177. v
  178. };
  179. let src: Vec<u8> = [
  180. vertex(-1.0, 1.0, 0),
  181. vertex(-1.0, -1.0, 100),
  182. vertex(1.0, -1.0, 150),
  183. ]
  184. .concat();
  185. let mut dst = vec![0u8; 6 * 12];
  186. expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]);
  187. assert_eq!(dst[..36], src[..]);
  188. assert_eq!(dst[36..48], src[..12]);
  189. assert_eq!(dst[48..60], src[24..36]);
  190. assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]);
  191. assert_eq!(f32_to_half(1.5), 0x3e00);
  192. assert_eq!(half_to_f32(0x3e00), 1.5);
  193. assert_eq!(half_to_f32(0xc000), -2.0);
  194. }
  195. /// A rounding that carries out of the mantissa raises the exponent
  196. /// (the carry used to be or-ed into an odd exponent, halving the value).
  197. #[test]
  198. fn halves_round_up_into_the_next_power_of_two() {
  199. assert_eq!(f32_to_half(2.0 - 2f32.powi(-12)), 0x4000);
  200. assert_eq!(f32_to_half(0.5 - 2f32.powi(-13)), 0x3800);
  201. assert_eq!(f32_to_half(65520.0), 0x7c00, "past the largest half");
  202. // An R16_FLOAT element at 1.0, 2^-12 and 1.0: the fourth corner is
  203. // 2 - 2^-12, which rounds to 2.0.
  204. let src: Vec<u8> = [0x3c00_u16, 0x0c00, 0x3c00]
  205. .iter()
  206. .flat_map(|h| h.to_le_bytes())
  207. .collect();
  208. let mut dst = vec![0u8; 6 * 2];
  209. expand_rects(&src, &mut dst, 2, &[(0, 54)]);
  210. assert_eq!(dst[10..], 0x4000_u16.to_le_bytes());
  211. }
  212. /// An element that reaches past the stride (float4 at 4 in 8-byte
  213. /// vertices, RGBA8 at the stride itself): the components inside get
  214. /// the fourth corner, the rest keep the first vertex's bytes. The old
  215. /// code indexed past the vertex and panicked.
  216. #[test]
  217. fn elements_past_the_stride_are_left_alone() {
  218. let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat();
  219. let src = [vertex(0.0, 2.0), vertex(1.0, 3.0), vertex(5.0, 7.0)].concat();
  220. let mut dst = vec![0u8; 6 * 8];
  221. expand_rects(&src, &mut dst, 8, &[(0, 16), (4, 2), (8, 28)]);
  222. assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]);
  223. assert_eq!(dst[40..], vertex(4.0, 6.0)[..]);
  224. }
  225. #[test]
  226. fn normalized_attributes_are_interpolated_in_their_own_range() {
  227. let vertex = |rg: [u8; 2], u16_value: u16, u8_value: u8, snorm8: i8, snorm16: i16| {
  228. [
  229. &rg[..],
  230. &u16_value.to_le_bytes(),
  231. &[u8_value, snorm8 as u8],
  232. &snorm16.to_le_bytes(),
  233. ]
  234. .concat()
  235. };
  236. let src = [
  237. vertex([3, 250], 1000, 10, i8::MIN, -23000),
  238. vertex([8, 200], 500, 3, -120, -18000),
  239. vertex([20, 253], 10000, 100, -120, -32000),
  240. ]
  241. .concat();
  242. let mut dst = [0; 6 * 8];
  243. expand_rects(
  244. &src,
  245. &mut dst,
  246. 8,
  247. &[(0, 49), (2, 56), (4, 61), (5, 63), (6, 58)],
  248. );
  249. assert_eq!(dst[40..], vertex([15, 255], 10500, 107, -127, -32767));
  250. }
  251. /// `half_to_f32` reads subnormals, so an f16 rectangle output must be
  252. /// able to write them back instead of flushing every one to zero.
  253. #[test]
  254. fn half_subnormals_convert_in_both_directions() {
  255. assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001);
  256. assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001);
  257. assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002);
  258. assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff);
  259. // Ties go to an even mantissa: 0/1 and 1/2.
  260. assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000);
  261. assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002);
  262. // Below half the smallest subnormal, and normal values, are unchanged.
  263. assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000);
  264. assert_eq!(f32_to_half(1.5), 0x3e00);
  265. assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
  266. }
  267. }