|
| 1 | +use bevy::prelude::Entity; |
| 2 | +use processing_webcam::{ |
| 3 | + WebcamFormat, webcam_create, webcam_create_with_format, webcam_destroy, webcam_image, |
| 4 | + webcam_is_connected, webcam_resolution, |
| 5 | +}; |
| 6 | +use pyo3::{exceptions::PyRuntimeError, prelude::*}; |
| 7 | + |
| 8 | +use crate::graphics::Image; |
| 9 | + |
| 10 | +#[pyclass(unsendable)] |
| 11 | +pub struct Webcam { |
| 12 | + entity: Entity, |
| 13 | +} |
| 14 | + |
| 15 | +#[pymethods] |
| 16 | +impl Webcam { |
| 17 | + #[new] |
| 18 | + #[pyo3(signature = (width=None, height=None, framerate=None))] |
| 19 | + pub fn new(width: Option<u32>, height: Option<u32>, framerate: Option<u32>) -> PyResult<Self> { |
| 20 | + let entity = match (width, height, framerate) { |
| 21 | + (Some(w), Some(h), Some(fps)) => webcam_create_with_format(WebcamFormat::Exact { |
| 22 | + resolution: bevy::math::UVec2::new(w, h), |
| 23 | + framerate: fps, |
| 24 | + }), |
| 25 | + (Some(w), Some(h), None) => { |
| 26 | + webcam_create_with_format(WebcamFormat::Resolution(bevy::math::UVec2::new(w, h))) |
| 27 | + } |
| 28 | + (None, None, Some(fps)) => webcam_create_with_format(WebcamFormat::FrameRate(fps)), |
| 29 | + _ => webcam_create(), |
| 30 | + } |
| 31 | + .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; |
| 32 | + |
| 33 | + Ok(Self { entity }) |
| 34 | + } |
| 35 | + |
| 36 | + pub fn is_connected(&self) -> PyResult<bool> { |
| 37 | + webcam_is_connected(self.entity).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) |
| 38 | + } |
| 39 | + |
| 40 | + pub fn resolution(&self) -> PyResult<(u32, u32)> { |
| 41 | + webcam_resolution(self.entity).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) |
| 42 | + } |
| 43 | + |
| 44 | + pub fn image(&self) -> PyResult<Image> { |
| 45 | + let entity = |
| 46 | + webcam_image(self.entity).map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; |
| 47 | + Ok(Image::from_entity(entity)) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl Drop for Webcam { |
| 52 | + fn drop(&mut self) { |
| 53 | + let _ = webcam_destroy(self.entity); |
| 54 | + } |
| 55 | +} |
0 commit comments