use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::digest::Digest;
use crate::error::{Result, VisionError};
use crate::geometry::{Polygon, Region};
const MAX_NAME_CHARS: usize = 64;
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ZoneAnchor {
#[default]
Center,
BottomCenter,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Zone {
pub polygon: Polygon,
#[serde(default)]
pub anchor: ZoneAnchor,
}
impl Zone {
pub fn new(points: Vec<[f32; 2]>) -> Result<Self> {
let zone = Self { polygon: Polygon { points }, anchor: ZoneAnchor::default() };
zone.validate()?;
Ok(zone)
}
#[must_use]
pub fn with_anchor(mut self, anchor: ZoneAnchor) -> Self {
self.anchor = anchor;
self
}
pub fn validate(&self) -> Result<()> {
let points = &self.polygon.points;
if points.len() < 3 {
return Err(VisionError::InvalidInput(format!(
"a zone is a polygon of three vertices or more, not {}",
points.len()
)));
}
if points.iter().flatten().any(|c| !c.is_finite()) {
return Err(VisionError::InvalidInput(
"a zone's vertices must be finite pixel coordinates".into(),
));
}
Ok(())
}
pub fn contains(&self, [x, y]: [f32; 2]) -> bool {
let points = &self.polygon.points;
let mut inside = false;
let mut previous = match points.last() {
Some(last) => *last,
None => return false,
};
for ¤t in points {
let ([xi, yi], [xj, yj]) = (current, previous);
if (yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi {
inside = !inside;
}
previous = current;
}
inside
}
pub fn holds(&self, region: &Region) -> bool {
let Some(bbox) = region.shape.bbox() else { return false };
let point = match self.anchor {
ZoneAnchor::Center => bbox.center(),
ZoneAnchor::BottomCenter => [(bbox.x0 + bbox.x1) / 2.0, bbox.y1],
};
self.contains(point)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WatchCondition {
pub name: String,
#[serde(default)]
pub labels: Vec<String>,
pub min_score: f32,
pub min_frames: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub zone: Option<Zone>,
#[serde(default, rename = "cooldownMs", with = "millis")]
pub cooldown: Duration,
}
impl WatchCondition {
pub fn new<L: Into<String>>(
name: impl Into<String>,
labels: impl IntoIterator<Item = L>,
) -> Self {
Self {
name: name.into(),
labels: labels.into_iter().map(Into::into).collect(),
min_score: 0.5,
min_frames: 3,
zone: None,
cooldown: Duration::ZERO,
}
}
#[must_use]
pub fn with_min_score(mut self, min_score: f32) -> Self {
self.min_score = min_score;
self
}
#[must_use]
pub fn with_min_frames(mut self, min_frames: u32) -> Self {
self.min_frames = min_frames;
self
}
#[must_use]
pub fn with_zone(mut self, zone: Zone) -> Self {
self.zone = Some(zone);
self
}
#[must_use]
pub fn with_cooldown(mut self, cooldown: Duration) -> Self {
self.cooldown = cooldown;
self
}
pub fn validate(&self) -> Result<()> {
let name_ok = !self.name.is_empty()
&& self.name.chars().count() <= MAX_NAME_CHARS
&& self.name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
if !name_ok {
return Err(VisionError::InvalidInput(format!(
"watch condition name `{}` must be 1 to {MAX_NAME_CHARS} characters of \
[A-Za-z0-9._-]: it is part of every event key",
self.name
)));
}
if !(0.0..=1.0).contains(&self.min_score) {
return Err(VisionError::InvalidInput(format!(
"watch condition `{}` has min_score {}; use a score in [0, 1]",
self.name, self.min_score
)));
}
if self.min_frames == 0 {
return Err(VisionError::InvalidInput(format!(
"watch condition `{}` needs min_frames of at least 1",
self.name
)));
}
if let Some(zone) = &self.zone {
zone.validate()?;
}
Ok(())
}
pub fn matches(&self, region: &Region) -> bool {
let label_ok = self.labels.is_empty()
|| region.label.as_deref().is_some_and(|label| {
self.labels.iter().any(|wanted| wanted.eq_ignore_ascii_case(label))
});
label_ok
&& region.score.is_some_and(|score| score >= self.min_score)
&& self.zone.as_ref().is_none_or(|zone| zone.holds(region))
}
pub fn digest(&self) -> Digest {
Digest::of_json(self)
}
}
mod millis {
use std::time::Duration;
use serde::{Deserialize, Deserializer, Serializer};
pub(super) fn serialize<S: Serializer>(
value: &Duration,
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.serialize_u64(u64::try_from(value.as_millis()).unwrap_or(u64::MAX))
}
pub(super) fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Duration, D::Error> {
u64::deserialize(deserializer).map(Duration::from_millis)
}
}