image.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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::{gfxtag, DrawCall, DrawInstruction, DrawMesh, ManagedTexturePtr, Rectangle, RenderApi},
  27. mesh::{MeshBuilder, MeshInfo, COLOR_WHITE},
  28. prop::{BatchGuardPtr, PropertyAtomicGuard, PropertyRect, PropertyStr, PropertyUint32, Role},
  29. scene::{Pimpl, SceneNodeWeak},
  30. ExecutorPtr,
  31. };
  32. use super::{DrawUpdate, OnModify, UIObject};
  33. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::image", $($arg)*); } }
  34. pub type ImagePtr = Arc<Image>;
  35. pub struct Image {
  36. node: SceneNodeWeak,
  37. render_api: RenderApi,
  38. tasks: SyncMutex<Vec<smol::Task<()>>>,
  39. texture: SyncMutex<Option<ManagedTexturePtr>>,
  40. dc_key: u64,
  41. rect: PropertyRect,
  42. uv: PropertyRect,
  43. z_index: PropertyUint32,
  44. priority: PropertyUint32,
  45. path: PropertyStr,
  46. parent_rect: SyncMutex<Option<Rectangle>>,
  47. }
  48. impl Image {
  49. pub async fn new(node: SceneNodeWeak, render_api: RenderApi) -> Pimpl {
  50. let node_ref = &node.upgrade().unwrap();
  51. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  52. let uv = PropertyRect::wrap(node_ref, Role::Internal, "uv").unwrap();
  53. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  54. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  55. let path = PropertyStr::wrap(node_ref, Role::Internal, "path", 0).unwrap();
  56. let self_ = Arc::new(Self {
  57. node,
  58. render_api,
  59. tasks: SyncMutex::new(vec![]),
  60. texture: SyncMutex::new(None),
  61. dc_key: OsRng.gen(),
  62. rect,
  63. uv,
  64. z_index,
  65. priority,
  66. path,
  67. parent_rect: SyncMutex::new(None),
  68. });
  69. Pimpl::Image(self_)
  70. }
  71. async fn reload(self: Arc<Self>, batch: BatchGuardPtr) {
  72. let texture = self.load_texture();
  73. *self.texture.lock() = Some(texture);
  74. self.clone().redraw(batch).await;
  75. }
  76. fn load_texture(&self) -> ManagedTexturePtr {
  77. let path = self.path.get();
  78. // TODO we should NOT use panic here
  79. let data = Arc::new(SyncMutex::new(vec![]));
  80. let data2 = data.clone();
  81. miniquad::fs::load_file(&path.clone(), move |res| match res {
  82. Ok(res) => *data2.lock() = res,
  83. Err(e) => {
  84. error!(target: "ui::image", "Unable to open image: {path}: {e}");
  85. panic!("Resource not found! {e}");
  86. }
  87. });
  88. let data = std::mem::take(&mut *data.lock());
  89. let img =
  90. ImageReader::new(Cursor::new(data)).with_guessed_format().unwrap().decode().unwrap();
  91. let img = img.to_rgba8();
  92. //let img = image::ImageReader::open(path).unwrap().decode().unwrap().to_rgba8();
  93. let width = img.width() as u16;
  94. let height = img.height() as u16;
  95. let bmp = img.into_raw();
  96. self.render_api.new_texture(width, height, bmp, TextureFormat::RGBA8, gfxtag!("img"))
  97. }
  98. #[instrument(target = "ui::button")]
  99. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  100. let Some(parent_rect) = self.parent_rect.lock().clone() else { return };
  101. let atom = &mut batch.spawn();
  102. let Some(draw_update) = self.get_draw_calls(atom, parent_rect).await else {
  103. error!(target: "ui::image", "Image failed to draw");
  104. return
  105. };
  106. self.render_api.replace_draw_calls(batch.id, draw_update.draw_calls);
  107. }
  108. /// Called whenever any property changes.
  109. fn regen_mesh(&self) -> MeshInfo {
  110. let rect = self.rect.get();
  111. let uv = self.uv.get();
  112. let mesh_rect = Rectangle::from([0., 0., rect.w, rect.h]);
  113. let mut mesh = MeshBuilder::new(gfxtag!("img"));
  114. mesh.draw_box(&mesh_rect, COLOR_WHITE, &uv);
  115. mesh.alloc(&self.render_api)
  116. }
  117. async fn get_draw_calls(
  118. &self,
  119. atom: &mut PropertyAtomicGuard,
  120. parent_rect: Rectangle,
  121. ) -> Option<DrawUpdate> {
  122. self.rect.eval(atom, &parent_rect).ok()?;
  123. let rect = self.rect.get();
  124. self.uv.eval(atom, &rect).ok()?;
  125. let mesh = self.regen_mesh();
  126. let texture = self.texture.lock().clone().expect("Node missing texture_id!");
  127. let mesh = DrawMesh {
  128. vertex_buffer: mesh.vertex_buffer,
  129. index_buffer: mesh.index_buffer,
  130. textures: Some(vec![texture]),
  131. num_elements: mesh.num_elements,
  132. };
  133. Some(DrawUpdate {
  134. key: self.dc_key,
  135. draw_calls: vec![(
  136. self.dc_key,
  137. DrawCall::new(
  138. vec![DrawInstruction::Move(rect.pos()), DrawInstruction::Draw(mesh)],
  139. vec![],
  140. self.z_index.get(),
  141. "img",
  142. ),
  143. )],
  144. })
  145. }
  146. }
  147. #[async_trait]
  148. impl UIObject for Image {
  149. fn priority(&self) -> u32 {
  150. self.priority.get()
  151. }
  152. fn init(&self) {
  153. *self.texture.lock() = Some(self.load_texture());
  154. }
  155. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  156. let me = Arc::downgrade(&self);
  157. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  158. on_modify.when_change(self.rect.prop(), Self::redraw);
  159. on_modify.when_change(self.uv.prop(), Self::redraw);
  160. on_modify.when_change(self.z_index.prop(), Self::redraw);
  161. on_modify.when_change(self.path.prop(), Self::reload);
  162. *self.tasks.lock() = on_modify.tasks;
  163. }
  164. fn stop(&self) {
  165. self.tasks.lock().clear();
  166. *self.parent_rect.lock() = None;
  167. *self.texture.lock() = None;
  168. }
  169. #[instrument(target = "ui::button")]
  170. async fn draw(
  171. &self,
  172. parent_rect: Rectangle,
  173. atom: &mut PropertyAtomicGuard,
  174. ) -> Option<DrawUpdate> {
  175. *self.parent_rect.lock() = Some(parent_rect);
  176. self.get_draw_calls(atom, parent_rect).await
  177. }
  178. }
  179. impl Drop for Image {
  180. fn drop(&mut self) {
  181. let atom = self.render_api.make_guard(gfxtag!("Image::drop"));
  182. self.render_api.replace_draw_calls(atom.batch_id, vec![(self.dc_key, Default::default())]);
  183. }
  184. }
  185. impl std::fmt::Debug for Image {
  186. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  187. write!(f, "{:?}", self.node.upgrade().unwrap())
  188. }
  189. }