image.rs 7.3 KB

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