image.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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 rand::{rngs::OsRng, Rng};
  21. use std::{
  22. io::Cursor,
  23. sync::{Arc, Mutex as SyncMutex, OnceLock, Weak},
  24. };
  25. use crate::{
  26. gfx::{
  27. GfxDrawCall, GfxDrawInstruction, GfxDrawMesh, GfxTextureId, ManagedTexturePtr, Rectangle,
  28. RenderApi,
  29. },
  30. mesh::{MeshBuilder, MeshInfo, COLOR_WHITE},
  31. prop::{PropertyPtr, PropertyRect, PropertyStr, PropertyUint32, Role},
  32. scene::{Pimpl, SceneNodePtr, SceneNodeWeak},
  33. ExecutorPtr,
  34. };
  35. use super::{DrawUpdate, OnModify, UIObject};
  36. pub type ImagePtr = Arc<Image>;
  37. pub struct Image {
  38. node: SceneNodeWeak,
  39. render_api: RenderApi,
  40. tasks: OnceLock<Vec<smol::Task<()>>>,
  41. texture: SyncMutex<Option<ManagedTexturePtr>>,
  42. dc_key: u64,
  43. rect: PropertyRect,
  44. uv: PropertyRect,
  45. z_index: PropertyUint32,
  46. path: PropertyStr,
  47. parent_rect: SyncMutex<Option<Rectangle>>,
  48. }
  49. impl Image {
  50. pub async fn new(node: SceneNodeWeak, render_api: RenderApi, ex: ExecutorPtr) -> Pimpl {
  51. debug!(target: "ui::image", "Image::new()");
  52. let node_ref = &node.upgrade().unwrap();
  53. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  54. let uv = PropertyRect::wrap(node_ref, Role::Internal, "uv").unwrap();
  55. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  56. let path = PropertyStr::wrap(node_ref, Role::Internal, "path", 0).unwrap();
  57. let node_name = node_ref.name.clone();
  58. let node_id = node_ref.id;
  59. let self_ = Arc::new(Self {
  60. node,
  61. render_api,
  62. tasks: OnceLock::new(),
  63. texture: SyncMutex::new(None),
  64. dc_key: OsRng.gen(),
  65. rect,
  66. uv,
  67. z_index,
  68. path,
  69. parent_rect: SyncMutex::new(None),
  70. });
  71. *self_.texture.lock().unwrap() = Some(self_.load_texture());
  72. Pimpl::Image(self_)
  73. }
  74. async fn reload(self: Arc<Self>) {
  75. let texture = self.load_texture();
  76. let old_texture = std::mem::replace(&mut *self.texture.lock().unwrap(), Some(texture));
  77. self.clone().redraw().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().unwrap() = res,
  86. Err(e) => {
  87. error!(target: "ui::image", "Unable to open image: {path}");
  88. panic!("Resource not found!");
  89. }
  90. });
  91. let data = std::mem::take(&mut *data.lock().unwrap());
  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. let texture = self.render_api.new_texture(width, height, bmp);
  100. texture
  101. }
  102. async fn redraw(self: Arc<Self>) {
  103. let Some(parent_rect) = self.parent_rect.lock().unwrap().clone() else { return };
  104. let Some(draw_update) = self.get_draw_calls(parent_rect).await else {
  105. error!(target: "ui::image", "Image failed to draw");
  106. return;
  107. };
  108. self.render_api.replace_draw_calls(draw_update.draw_calls);
  109. debug!(target: "ui::image", "replace draw calls done");
  110. }
  111. /// Called whenever any property changes.
  112. fn regen_mesh(&self) -> MeshInfo {
  113. let rect = self.rect.get();
  114. let uv = self.uv.get();
  115. let mesh_rect = Rectangle::from([0., 0., rect.w, rect.h]);
  116. let mut mesh = MeshBuilder::new();
  117. mesh.draw_box(&mesh_rect, COLOR_WHITE, &uv);
  118. mesh.alloc(&self.render_api)
  119. }
  120. async fn get_draw_calls(&self, parent_rect: Rectangle) -> Option<DrawUpdate> {
  121. self.rect.eval(&parent_rect).ok()?;
  122. let rect = self.rect.get();
  123. self.uv.eval(&rect).ok()?;
  124. let mesh = self.regen_mesh();
  125. let texture = self.texture.lock().unwrap().clone().expect("Node missing texture_id!");
  126. let mesh = GfxDrawMesh {
  127. vertex_buffer: mesh.vertex_buffer,
  128. index_buffer: mesh.index_buffer,
  129. texture: Some(texture),
  130. num_elements: mesh.num_elements,
  131. };
  132. Some(DrawUpdate {
  133. key: self.dc_key,
  134. draw_calls: vec![(
  135. self.dc_key,
  136. GfxDrawCall {
  137. instrs: vec![
  138. GfxDrawInstruction::Move(rect.pos()),
  139. GfxDrawInstruction::Draw(mesh),
  140. ],
  141. dcs: vec![],
  142. z_index: self.z_index.get(),
  143. },
  144. )],
  145. })
  146. }
  147. }
  148. #[async_trait]
  149. impl UIObject for Image {
  150. fn z_index(&self) -> u32 {
  151. self.z_index.get()
  152. }
  153. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  154. let me = Arc::downgrade(&self);
  155. let node_ref = &self.node.upgrade().unwrap();
  156. let node_name = node_ref.name.clone();
  157. let node_id = node_ref.id;
  158. let mut on_modify = OnModify::new(ex, node_name, node_id, me.clone());
  159. on_modify.when_change(self.rect.prop(), Self::redraw);
  160. on_modify.when_change(self.uv.prop(), Self::redraw);
  161. on_modify.when_change(self.z_index.prop(), Self::redraw);
  162. on_modify.when_change(self.path.prop(), Self::reload);
  163. self.tasks.set(on_modify.tasks);
  164. }
  165. async fn draw(&self, parent_rect: Rectangle) -> Option<DrawUpdate> {
  166. debug!(target: "ui::image", "Image::draw()");
  167. *self.parent_rect.lock().unwrap() = Some(parent_rect);
  168. self.get_draw_calls(parent_rect).await
  169. }
  170. }
  171. impl Drop for Image {
  172. fn drop(&mut self) {
  173. self.render_api.replace_draw_calls(vec![(self.dc_key, Default::default())]);
  174. }
  175. }