primitive.rs 9.2 KB

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