image.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_trait::async_trait;
  19. use image::ImageReader;
  20. use miniquad::TextureFormat;
  21. use parking_lot::Mutex as SyncMutex;
  22. use rand::{rngs::OsRng, Rng};
  23. use std::{io::Cursor, sync::Arc};
  24. use tracing::instrument;
  25. use crate::{
  26. gfx::{
  27. gfxtag, DrawCall, DrawInstruction, DrawMesh, EpochCache, ManagedTexturePtr, Rectangle,
  28. RenderApi, Renderer,
  29. },
  30. mesh::{MeshBuilder, MeshInfo, COLOR_WHITE},
  31. prop::{BatchGuardPtr, PropertyAtomicGuard, PropertyRect, PropertyStr, PropertyUint32, Role},
  32. scene::{Pimpl, SceneNodeWeak},
  33. ExecutorPtr,
  34. };
  35. use super::{DrawUpdate, OnModify, RedrawTrigger, UIObject};
  36. pub type ImagePtr = Arc<Image>;
  37. pub struct Image {
  38. node: SceneNodeWeak,
  39. renderer: Renderer,
  40. redraw: RedrawTrigger,
  41. tasks: SyncMutex<Vec<smol::Task<()>>>,
  42. texture: SyncMutex<Option<ManagedTexturePtr>>,
  43. dc_key: u64,
  44. rect: PropertyRect,
  45. uv: PropertyRect,
  46. z_index: PropertyUint32,
  47. priority: PropertyUint32,
  48. path: PropertyStr,
  49. /// Cached draw instructions. Empty means stale. Entries from a dead
  50. /// UI epoch are evicted automatically.
  51. draw_cache: EpochCache<Vec<DrawInstruction>>,
  52. }
  53. impl Image {
  54. pub async fn new(node: SceneNodeWeak, renderer: Renderer, redraw: RedrawTrigger) -> Pimpl {
  55. let node_ref = &node.upgrade().unwrap();
  56. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  57. let uv = PropertyRect::wrap(node_ref, Role::Internal, "uv").unwrap();
  58. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  59. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  60. let path = PropertyStr::wrap(node_ref, Role::Internal, "path", 0).unwrap();
  61. let draw_cache = EpochCache::new(&renderer);
  62. let self_ = Arc::new(Self {
  63. node,
  64. renderer,
  65. redraw,
  66. tasks: SyncMutex::new(vec![]),
  67. texture: SyncMutex::new(None),
  68. dc_key: OsRng.gen(),
  69. rect,
  70. uv,
  71. z_index,
  72. priority,
  73. path,
  74. draw_cache,
  75. });
  76. Pimpl::Image(self_)
  77. }
  78. async fn reload(self_: Arc<Self>, _batch: BatchGuardPtr) {
  79. let texture = self_.load_texture();
  80. *self_.texture.lock() = Some(texture);
  81. self_.draw_cache.clear();
  82. self_.redraw.trigger();
  83. }
  84. fn load_texture(&self) -> ManagedTexturePtr {
  85. let path = self.path.get();
  86. // TODO we should NOT use panic here
  87. let data = Arc::new(SyncMutex::new(vec![]));
  88. let data2 = data.clone();
  89. miniquad::fs::load_file(&path.clone(), move |res| match res {
  90. Ok(res) => *data2.lock() = res,
  91. Err(e) => {
  92. error!(target: "ui::image", "Unable to open image: {path}: {e}");
  93. panic!("Resource not found! {e}");
  94. }
  95. });
  96. let data = std::mem::take(&mut *data.lock());
  97. let img =
  98. ImageReader::new(Cursor::new(data)).with_guessed_format().unwrap().decode().unwrap();
  99. let img = img.to_rgba8();
  100. //let img = image::ImageReader::open(path).unwrap().decode().unwrap().to_rgba8();
  101. let width = img.width() as u16;
  102. let height = img.height() as u16;
  103. let bmp = img.into_raw();
  104. self.renderer.new_texture(width, height, bmp, TextureFormat::RGBA8, gfxtag!("img"))
  105. }
  106. /// Called whenever any property changes.
  107. fn regen_mesh(&self) -> MeshInfo {
  108. let rect = self.rect.get();
  109. let uv = self.uv.get();
  110. let mesh_rect = Rectangle::from([0., 0., rect.w, rect.h]);
  111. let mut mesh = MeshBuilder::new(gfxtag!("img"));
  112. mesh.draw_box(&mesh_rect, COLOR_WHITE, &uv);
  113. mesh.alloc(&self.renderer)
  114. }
  115. fn get_draw_calls(
  116. &self,
  117. atom: &mut PropertyAtomicGuard,
  118. parent_rect: Rectangle,
  119. ) -> Option<DrawUpdate> {
  120. // Rect property is its own memo: compare before/after eval.
  121. let prev_rect = self.rect.get();
  122. self.rect.eval(atom, &parent_rect).ok()?;
  123. let rect = self.rect.get();
  124. let rect_changed = rect != prev_rect;
  125. self.uv.eval(atom, &rect).ok()?;
  126. // Mesh geometry depends on the rect; compute under the cache lock
  127. // so a concurrent invalidation lands before or after, never between.
  128. if rect_changed {
  129. self.draw_cache.clear();
  130. }
  131. let instrs = self.draw_cache.get_or_insert_with(|| {
  132. let mesh = self.regen_mesh();
  133. let texture = self.texture.lock().clone().expect("Node missing texture_id!");
  134. let mesh = DrawMesh {
  135. vertex_buffer: mesh.vertex_buffer,
  136. index_buffer: mesh.index_buffer,
  137. textures: Some(vec![texture]),
  138. num_elements: mesh.num_elements,
  139. };
  140. vec![DrawInstruction::Move(rect.pos()), DrawInstruction::Draw(mesh)]
  141. });
  142. Some(DrawUpdate {
  143. key: self.dc_key,
  144. draw_calls: vec![(
  145. self.dc_key,
  146. DrawCall::new(instrs, vec![], self.z_index.get(), "img"),
  147. )],
  148. })
  149. }
  150. }
  151. #[async_trait]
  152. impl UIObject for Image {
  153. fn priority(&self) -> u32 {
  154. self.priority.get()
  155. }
  156. fn init(&self) {
  157. *self.texture.lock() = Some(self.load_texture());
  158. }
  159. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  160. let me = Arc::downgrade(&self);
  161. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  162. // Invalidate the cache, then request a pass. Internal-role echoes
  163. // (the pass's own evals) are skipped.
  164. on_modify.when_change_external(self.rect.prop(), |self_, _| async move {
  165. self_.draw_cache.clear();
  166. self_.redraw.trigger();
  167. });
  168. on_modify.when_change_external(self.uv.prop(), |self_, _| async move {
  169. self_.draw_cache.clear();
  170. self_.redraw.trigger();
  171. });
  172. on_modify.when_change_external(self.z_index.prop(), |self_, _| async move {
  173. self_.draw_cache.clear();
  174. self_.redraw.trigger();
  175. });
  176. on_modify.when_change(self.path.prop(), Self::reload);
  177. *self.tasks.lock() = on_modify.tasks;
  178. }
  179. fn stop(&self) {
  180. self.tasks.lock().clear();
  181. self.draw_cache.clear();
  182. *self.texture.lock() = None;
  183. }
  184. #[instrument(target = "ui::button")]
  185. async fn draw(
  186. &self,
  187. parent_rect: Rectangle,
  188. atom: &mut PropertyAtomicGuard,
  189. ) -> Option<DrawUpdate> {
  190. self.get_draw_calls(atom, parent_rect)
  191. }
  192. }
  193. impl Drop for Image {
  194. fn drop(&mut self) {
  195. self.renderer.replace_draw_calls(vec![(self.dc_key, Default::default())]);
  196. }
  197. }
  198. impl std::fmt::Debug for Image {
  199. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  200. write!(f, "{:?}", self.node.upgrade().unwrap())
  201. }
  202. }