| 1 | //! This terminal's own dot whale, projected from its own session's typed |
| 2 | //! Engine metadata by the bundled reducer and dot field. |
| 3 | //! |
| 4 | //! Known limits: events before the first `/whale` in a process are not seen; |
| 5 | //! the frame uses the dot field's raw pigment. Any failure leaves the view on |
| 6 | //! its fallback. |
| 7 | use rquickjs::{Context, Function, Runtime}; |
| 8 | use std::sync::{ |
| 9 | Arc, Mutex, |
| 10 | atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, |
| 11 | mpsc::{self, RecvTimeoutError, Sender}, |
| 12 | }; |
| 13 | use std::time::{Duration, Instant}; |
| 14 | |
| 15 | const POINTS: usize = 980; |
| 16 | const PENDING: usize = 4096; |
| 17 | const PRELUDE: &str = r#"(function(){ |
| 18 | const F=globalThis.PetDotField,E=globalThis.PetEngineTelemetry; |
| 19 | if(!F||typeof F.projectDotField!=='function'||typeof F.blendDotFields!=='function'||typeof F.dotFieldKey!=='function'||typeof E!=='function')throw Error('Pet dot field unavailable.'); |
| 20 | let s; |
| 21 | const reset=()=>{s={engine:new E(),at:0,from:undefined,last:undefined,key:'',still:''};}; |
| 22 | reset(); |
| 23 | const flat=(f,hollow,busy)=>{ |
| 24 | if(!f||!Array.isArray(f.points)||!Array.isArray(f.materials)||f.points.length!==980||f.materials.length!==980)throw Error('Invalid pet dot field.'); |
| 25 | const o=new Array(2+980*6);o[0]=hollow?1:0;o[1]=busy?1:0; |
| 26 | for(let i=0;i<980;i++){const p=f.points[i],m=f.materials[i],k=2+i*6;o[k]=p[0];o[k+1]=p[1];o[k+2]=m[0];o[k+3]=m[1];o[k+4]=m[2];o[k+5]=m[3];} |
| 27 | return o;}; |
| 28 | globalThis.localReset=reset; |
| 29 | globalThis.localForget=()=>{s.still='';}; |
| 30 | globalThis.localFresh=(t)=>s.engine.lastObservedAt!==undefined&&t-s.engine.lastObservedAt<=12500; |
| 31 | globalThis.localObserve=(json,t)=>{ |
| 32 | const ev=JSON.parse(json);if(!Array.isArray(ev))throw Error('Invalid pet batch.'); |
| 33 | const n=s.engine.clone(); |
| 34 | try{for(const e of ev)n.observe(e,t);s.engine=n;return;}catch(_){} |
| 35 | for(const e of ev){const m=s.engine.clone();try{m.observe(e,t);s.engine=m;}catch(_){}}}; |
| 36 | globalThis.localFrame=(t,still,waiting)=>{ |
| 37 | s.engine.confirmWaiting(t,waiting); |
| 38 | const a=s.engine.activity(t),o={bodyStyle:'smooth'},hollow=!(a.observed&&a.freshness==='fresh'); |
| 39 | const k=F.dotFieldKey(a); |
| 40 | if(k!==s.key){if(s.key&&s.last){s.from=s.last;s.at=t;}s.key=k;} |
| 41 | if(still){ |
| 42 | const done=!hollow&&a.authoritativePresence==='done'&&t-(a.observedAtMs??t)<2600; |
| 43 | const sk=k+':'+hollow+':'+done; |
| 44 | if(sk===s.still)return null; |
| 45 | const r=flat(F.projectDotField(a,t,true,0,o),hollow,false); |
| 46 | s.still=sk; |
| 47 | return r;} |
| 48 | s.still=''; |
| 49 | const target=F.projectDotField(a,t,false,s.at,o); |
| 50 | const f=s.from?F.blendDotFields(s.from,target,(t-s.at)/560):target; |
| 51 | const busy=!!s.from||target.morph>0; |
| 52 | if(s.from&&t-s.at>=560)s.from=undefined; |
| 53 | s.last=f; |
| 54 | return flat(f,hollow,busy);}; |
| 55 | })();"#; |
| 56 | |
| 57 | const BUNDLE: &str = include_str!("pet-native.js"); |
| 58 | |
| 59 | #[derive(Clone, Debug, PartialEq)] |
| 60 | pub(super) struct Frame { |
| 61 | pub points: Vec<[f64; 2]>, |
| 62 | pub materials: Vec<[f64; 4]>, |
| 63 | pub hollow: bool, |
| 64 | pub busy: bool, |
| 65 | } |
| 66 | |
| 67 | impl Frame { |
| 68 | fn from_flat(flat: &[f64]) -> Option<Self> { |
| 69 | if flat.len() != 2 + POINTS * 6 || !flat.iter().all(|v| v.is_finite()) { |
| 70 | return None; |
| 71 | } |
| 72 | let mut points = Vec::with_capacity(POINTS); |
| 73 | let mut materials = Vec::with_capacity(POINTS); |
| 74 | for &[x, y, r, g, b, a] in flat[2..].as_chunks::<6>().0 { |
| 75 | let point = [x, y]; |
| 76 | let material = [r, g, b, a]; |
| 77 | if !point.iter().all(|v| (-1.0..=1.0).contains(v)) |
| 78 | || !material[..3].iter().all(|v| (0.0..=255.0).contains(v)) |
| 79 | || !(0.0..=1.0).contains(&material[3]) |
| 80 | { |
| 81 | return None; |
| 82 | } |
| 83 | points.push(point); |
| 84 | materials.push(material); |
| 85 | } |
| 86 | Some(Self { |
| 87 | points, |
| 88 | materials, |
| 89 | hollow: flat[0] != 0.0, |
| 90 | busy: flat[1] != 0.0, |
| 91 | }) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | pub(super) struct Projector { |
| 96 | context: Context, |
| 97 | _runtime: Runtime, |
| 98 | deadline: Arc<Mutex<Instant>>, |
| 99 | } |
| 100 | |
| 101 | impl Projector { |
| 102 | #[cfg(test)] |
| 103 | pub(super) fn new() -> Option<Self> { |
| 104 | Self::from_source(BUNDLE) |
| 105 | } |
| 106 | |
| 107 | fn from_source(source: &str) -> Option<Self> { |
| 108 | let runtime = Runtime::new().ok()?; |
| 109 | runtime.set_memory_limit(64 * 1024 * 1024); |
| 110 | runtime.set_max_stack_size(2 * 1024 * 1024); |
| 111 | let deadline = Arc::new(Mutex::new(Instant::now() + Duration::from_secs(10))); |
| 112 | let limit = Arc::clone(&deadline); |
| 113 | runtime.set_interrupt_handler(Some(Box::new(move || { |
| 114 | limit.lock().map_or(true, |d| Instant::now() > *d) |
| 115 | }))); |
| 116 | let context = Context::full(&runtime).ok()?; |
| 117 | context |
| 118 | .with(|ctx| -> rquickjs::Result<()> { |
| 119 | ctx.eval::<(), _>(source)?; |
| 120 | ctx.eval::<(), _>(PRELUDE) |
| 121 | }) |
| 122 | .ok()?; |
| 123 | Some(Self { |
| 124 | context, |
| 125 | _runtime: runtime, |
| 126 | deadline, |
| 127 | }) |
| 128 | } |
| 129 | |
| 130 | fn arm(&self, limit: Duration) -> bool { |
| 131 | self.deadline |
| 132 | .lock() |
| 133 | .map(|mut d| *d = Instant::now() + limit) |
| 134 | .is_ok() |
| 135 | } |
| 136 | |
| 137 | pub(super) fn observe(&self, json: &str, t: f64) -> bool { |
| 138 | self.arm(Duration::from_secs(5)) |
| 139 | && self.context.with(|ctx| { |
| 140 | let result = ctx |
| 141 | .globals() |
| 142 | .get::<_, Function>("localObserve") |
| 143 | .and_then(|f| f.call::<_, ()>((json, t))); |
| 144 | if result.is_err() { |
| 145 | let _ = ctx.catch(); |
| 146 | } |
| 147 | result.is_ok() |
| 148 | }) |
| 149 | } |
| 150 | |
| 151 | pub(super) fn reset(&self) -> bool { |
| 152 | self.arm(Duration::from_secs(1)) |
| 153 | && self.context.with(|ctx| { |
| 154 | let result = ctx |
| 155 | .globals() |
| 156 | .get::<_, Function>("localReset") |
| 157 | .and_then(|f| f.call::<_, ()>(())); |
| 158 | if result.is_err() { |
| 159 | let _ = ctx.catch(); |
| 160 | } |
| 161 | result.is_ok() |
| 162 | }) |
| 163 | } |
| 164 | |
| 165 | pub(super) fn frame(&self, t: f64, still: bool, waiting: bool) -> Result<Option<Frame>, ()> { |
| 166 | if !self.arm(Duration::from_secs(60)) { |
| 167 | return Err(()); |
| 168 | } |
| 169 | let flat = self.context.with(|ctx| { |
| 170 | let result = ctx |
| 171 | .globals() |
| 172 | .get::<_, Function>("localFrame") |
| 173 | .and_then(|f| f.call::<_, Option<Vec<f64>>>((t, still, waiting))); |
| 174 | if result.is_err() { |
| 175 | let _ = ctx.catch(); |
| 176 | } |
| 177 | result.map_err(|_| ()) |
| 178 | })?; |
| 179 | match flat.map(|flat| Frame::from_flat(&flat)) { |
| 180 | None => Ok(None), |
| 181 | Some(Some(frame)) => Ok(Some(frame)), |
| 182 | Some(None) => { |
| 183 | self.forget(); |
| 184 | Err(()) |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | fn fresh(&self, t: f64) -> bool { |
| 190 | self.arm(Duration::from_secs(1)) |
| 191 | && self.context.with(|ctx| { |
| 192 | let result = ctx |
| 193 | .globals() |
| 194 | .get::<_, Function>("localFresh") |
| 195 | .and_then(|f| f.call::<_, bool>((t,))); |
| 196 | if result.is_err() { |
| 197 | let _ = ctx.catch(); |
| 198 | } |
| 199 | result.unwrap_or(true) |
| 200 | }) |
| 201 | } |
| 202 | |
| 203 | fn forget(&self) { |
| 204 | if self.arm(Duration::from_secs(1)) { |
| 205 | self.context.with(|ctx| { |
| 206 | let result = ctx |
| 207 | .globals() |
| 208 | .get::<_, Function>("localForget") |
| 209 | .and_then(|f| f.call::<_, ()>(())); |
| 210 | if result.is_err() { |
| 211 | let _ = ctx.catch(); |
| 212 | } |
| 213 | }); |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[derive(Clone, Copy)] |
| 219 | struct View { |
| 220 | visible: bool, |
| 221 | motion: bool, |
| 222 | waiting: bool, |
| 223 | } |
| 224 | |
| 225 | enum Msg { |
| 226 | Observe(String), |
| 227 | Reset(u64), |
| 228 | Wake, |
| 229 | } |
| 230 | |
| 231 | pub(super) struct Dots { |
| 232 | tx: Sender<Msg>, |
| 233 | pending: Arc<AtomicUsize>, |
| 234 | gap: Arc<AtomicBool>, |
| 235 | generation: Arc<AtomicU64>, |
| 236 | view: Arc<Mutex<View>>, |
| 237 | latest: Arc<Mutex<Option<(u64, Frame)>>>, |
| 238 | failed: Arc<AtomicBool>, |
| 239 | } |
| 240 | |
| 241 | struct Shared { |
| 242 | pending: Arc<AtomicUsize>, |
| 243 | gap: Arc<AtomicBool>, |
| 244 | generation: Arc<AtomicU64>, |
| 245 | view: Arc<Mutex<View>>, |
| 246 | latest: Arc<Mutex<Option<(u64, Frame)>>>, |
| 247 | } |
| 248 | |
| 249 | impl Dots { |
| 250 | pub(super) fn start() -> Self { |
| 251 | Self::start_from(BUNDLE) |
| 252 | } |
| 253 | |
| 254 | fn start_from(source: &'static str) -> Self { |
| 255 | let (tx, rx) = mpsc::channel(); |
| 256 | let dots = Self { |
| 257 | tx, |
| 258 | pending: Arc::new(AtomicUsize::new(0)), |
| 259 | gap: Arc::new(AtomicBool::new(false)), |
| 260 | generation: Arc::new(AtomicU64::new(0)), |
| 261 | view: Arc::new(Mutex::new(View { |
| 262 | visible: false, |
| 263 | motion: false, |
| 264 | waiting: false, |
| 265 | })), |
| 266 | latest: Arc::new(Mutex::new(None)), |
| 267 | failed: Arc::new(AtomicBool::new(false)), |
| 268 | }; |
| 269 | let shared = Shared { |
| 270 | pending: Arc::clone(&dots.pending), |
| 271 | gap: Arc::clone(&dots.gap), |
| 272 | generation: Arc::clone(&dots.generation), |
| 273 | view: Arc::clone(&dots.view), |
| 274 | latest: Arc::clone(&dots.latest), |
| 275 | }; |
| 276 | let failed = Arc::clone(&dots.failed); |
| 277 | let spawned = std::thread::Builder::new() |
| 278 | .name("pet-dots".into()) |
| 279 | .stack_size(8 * 1024 * 1024) |
| 280 | .spawn(move || { |
| 281 | let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 282 | let projector = Projector::from_source(source).ok_or(())?; |
| 283 | run(&projector, &rx, &shared) |
| 284 | })); |
| 285 | if !matches!(ran, Ok(Ok(()))) { |
| 286 | failed.store(true, Ordering::Release); |
| 287 | } |
| 288 | }); |
| 289 | if spawned.is_err() { |
| 290 | dots.failed.store(true, Ordering::Release); |
| 291 | } |
| 292 | dots |
| 293 | } |
| 294 | |
| 295 | pub(super) fn observe(&self, json: String) { |
| 296 | if self.pending.fetch_add(1, Ordering::AcqRel) >= PENDING { |
| 297 | self.pending.fetch_sub(1, Ordering::AcqRel); |
| 298 | self.gap.store(true, Ordering::Release); |
| 299 | } else if self.tx.send(Msg::Observe(json)).is_err() { |
| 300 | self.pending.fetch_sub(1, Ordering::AcqRel); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | pub(super) fn reset(&self) { |
| 305 | let generation = self.generation.fetch_add(1, Ordering::AcqRel) + 1; |
| 306 | if let Ok(mut latest) = self.latest.lock() { |
| 307 | *latest = None; |
| 308 | } |
| 309 | let _ = self.tx.send(Msg::Reset(generation)); |
| 310 | } |
| 311 | |
| 312 | pub(super) fn set_view(&self, visible: bool, motion: bool, waiting: bool) { |
| 313 | let woke = self.view.lock().is_ok_and(|mut view| { |
| 314 | let next = View { |
| 315 | visible, |
| 316 | motion, |
| 317 | waiting, |
| 318 | }; |
| 319 | let woke = visible |
| 320 | && (!view.visible || view.motion != next.motion || view.waiting != next.waiting); |
| 321 | *view = next; |
| 322 | woke |
| 323 | }); |
| 324 | if woke { |
| 325 | let _ = self.tx.send(Msg::Wake); |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | pub(super) fn take(&self) -> Option<Frame> { |
| 330 | let current = self.generation.load(Ordering::Acquire); |
| 331 | self.latest |
| 332 | .lock() |
| 333 | .ok() |
| 334 | .and_then(|mut latest| latest.take()) |
| 335 | .and_then(|(generation, frame)| (generation == current).then_some(frame)) |
| 336 | } |
| 337 | |
| 338 | pub(super) fn failed(&self) -> bool { |
| 339 | self.failed.load(Ordering::Acquire) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | fn run(projector: &Projector, rx: &mpsc::Receiver<Msg>, shared: &Shared) -> Result<(), ()> { |
| 344 | let origin = Instant::now(); |
| 345 | let mut due = origin; |
| 346 | let mut errors = 0u8; |
| 347 | let mut applied = 0u64; |
| 348 | let mut batch: Vec<String> = Vec::new(); |
| 349 | let mut reset = false; |
| 350 | let mut force = true; |
| 351 | let mut settled = false; |
| 352 | loop { |
| 353 | let visible = shared.view.lock().map_err(|_| ())?.visible; |
| 354 | let first = if (!visible || settled) && batch.is_empty() && !reset && !force { |
| 355 | rx.recv().map_err(|_| RecvTimeoutError::Disconnected) |
| 356 | } else { |
| 357 | rx.recv_timeout(due.saturating_duration_since(Instant::now())) |
| 358 | }; |
| 359 | let mut next = match first { |
| 360 | Ok(msg) => Some(msg), |
| 361 | Err(RecvTimeoutError::Timeout) => None, |
| 362 | Err(RecvTimeoutError::Disconnected) => return Ok(()), |
| 363 | }; |
| 364 | while let Some(msg) = next.take() { |
| 365 | match msg { |
| 366 | Msg::Observe(json) => { |
| 367 | shared.pending.fetch_sub(1, Ordering::AcqRel); |
| 368 | batch.push(json); |
| 369 | } |
| 370 | Msg::Reset(generation) => { |
| 371 | batch.clear(); |
| 372 | reset = true; |
| 373 | force = true; |
| 374 | applied = generation; |
| 375 | } |
| 376 | Msg::Wake => force = true, |
| 377 | } |
| 378 | next = rx.try_recv().ok(); |
| 379 | } |
| 380 | if shared.gap.swap(false, Ordering::AcqRel) { |
| 381 | batch.clear(); |
| 382 | reset = true; |
| 383 | applied = shared.generation.load(Ordering::Acquire); |
| 384 | } |
| 385 | if !force && Instant::now() < due { |
| 386 | continue; |
| 387 | } |
| 388 | force = false; |
| 389 | let t = origin.elapsed().as_secs_f64() * 1000.0; |
| 390 | if std::mem::take(&mut reset) { |
| 391 | projector.reset(); |
| 392 | } |
| 393 | if !batch.is_empty() { |
| 394 | projector.observe(&format!("[{}]", batch.join(",")), t); |
| 395 | batch.clear(); |
| 396 | } |
| 397 | let view = *shared.view.lock().map_err(|_| ())?; |
| 398 | let busy = if !view.visible { |
| 399 | false |
| 400 | } else { |
| 401 | match projector.frame(t, !view.motion, view.waiting) { |
| 402 | Ok(Some(frame)) => { |
| 403 | errors = 0; |
| 404 | let busy = frame.busy; |
| 405 | *shared.latest.lock().map_err(|_| ())? = Some((applied, frame)); |
| 406 | busy |
| 407 | } |
| 408 | Ok(None) => { |
| 409 | errors = 0; |
| 410 | false |
| 411 | } |
| 412 | Err(()) => { |
| 413 | errors += 1; |
| 414 | if errors >= 3 { |
| 415 | return Err(()); |
| 416 | } |
| 417 | false |
| 418 | } |
| 419 | } |
| 420 | }; |
| 421 | settled = view.visible && !view.motion && !projector.fresh(t); |
| 422 | due = Instant::now() |
| 423 | + Duration::from_millis(match (view.visible, view.motion) { |
| 424 | (true, true) if busy => 66, |
| 425 | (true, false) => 500, |
| 426 | _ => 250, |
| 427 | }); |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | #[cfg(test)] |
| 432 | pub(super) fn failing_for_test() -> Dots { |
| 433 | Dots::start_from("throw Error('no dot field');") |
| 434 | } |
| 435 | |
| 436 | #[cfg(test)] |
| 437 | mod tests { |
| 438 | #[test] |
| 439 | fn the_committed_bundle_exports_the_reducer_and_the_dot_field() { |
| 440 | assert!(super::Projector::from_source(super::BUNDLE).is_some()); |
| 441 | assert!(super::Projector::from_source("globalThis.PetDotField={};").is_none()); |
| 442 | } |
| 443 | } |
| 444 |