Skip to main content

dear_imgui_rs/context/
snapshot_hub.rs

1use std::collections::{BTreeMap, HashSet, VecDeque};
2use std::num::NonZeroU64;
3use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
4
5#[cfg(feature = "multi-viewport")]
6use crate::render::snapshot::capture_platform_io;
7use crate::render::snapshot::{
8    DetachedRendererConsumer, FrameSnapshot, PendingSnapshot, PendingTextureRequest,
9    RendererConsumerCapability, RendererConsumerError, SnapshotCompletionOutcome,
10    SnapshotCompletionProgress, SnapshotEpoch, SnapshotError, SnapshotMessage, SnapshotTextureId,
11    SynchronousRendererConsumer, TextureFeedback, TextureRequest, TextureRequestKey,
12    capture_draw_data, capture_texture_requests_only, finalize_texture_requests,
13    validate_texture_feedback,
14};
15
16use super::binding::CTX_MUTEX;
17use super::texture_registry::{
18    FontAtlasSnapshotTarget, FontAtlasTextureTarget, ManagedTextureRegistry,
19};
20use super::{Context, ContextId};
21
22#[derive(Copy, Clone, Debug, Eq, PartialEq)]
23enum ConsumerPhase {
24    Unbound,
25    Active(NonZeroU64),
26    Draining(NonZeroU64),
27}
28
29fn consumer_generation_raw(consumer: &(impl RendererConsumerCapability + ?Sized)) -> NonZeroU64 {
30    NonZeroU64::new(consumer.generation())
31        .expect("renderer consumer generations are always non-zero")
32}
33
34#[derive(Debug)]
35struct OutstandingEpoch {
36    epoch: SnapshotEpoch,
37    expected: HashSet<TextureRequestKey>,
38    completion: Option<SnapshotCompletionOutcome>,
39}
40
41#[derive(Copy, Clone, Debug, Eq, PartialEq)]
42enum SynchronousFrameStatus {
43    Pending,
44    Reconciled,
45    Abandoned,
46}
47
48#[derive(Copy, Clone, Debug, Eq, PartialEq)]
49struct SynchronousFrameState {
50    native_frame_count: i32,
51    epoch: Option<SnapshotEpoch>,
52    status: SynchronousFrameStatus,
53}
54
55#[derive(Debug)]
56pub(super) struct SnapshotHub {
57    context: ContextId,
58    sender: Sender<SnapshotMessage>,
59    receiver: Receiver<SnapshotMessage>,
60    phase: ConsumerPhase,
61    // A renderer may have uploaded a request even when its completion was lost.
62    texture_owner: Option<NonZeroU64>,
63    next_consumer_generation: Option<NonZeroU64>,
64    next_epoch: Option<NonZeroU64>,
65    completion_watermark: u64,
66    outstanding: BTreeMap<u64, OutstandingEpoch>,
67    pending_errors: VecDeque<RendererConsumerError>,
68    synchronous_frame: Option<SynchronousFrameState>,
69}
70
71impl SnapshotHub {
72    pub(super) fn new(context: ContextId) -> Self {
73        let (sender, receiver) = channel();
74        Self {
75            context,
76            sender,
77            receiver,
78            phase: ConsumerPhase::Unbound,
79            texture_owner: None,
80            next_consumer_generation: Some(NonZeroU64::MIN),
81            next_epoch: Some(NonZeroU64::MIN),
82            completion_watermark: 0,
83            outstanding: BTreeMap::new(),
84            pending_errors: VecDeque::new(),
85            synchronous_frame: None,
86        }
87    }
88
89    pub(super) const fn completion_watermark(&self) -> u64 {
90        self.completion_watermark
91    }
92
93    pub(super) fn begin_synchronous_native_frame(&mut self, native_frame_count: i32) {
94        self.synchronous_frame = Some(SynchronousFrameState {
95            native_frame_count,
96            epoch: None,
97            status: SynchronousFrameStatus::Pending,
98        });
99    }
100
101    #[cfg(feature = "multi-viewport")]
102    pub(super) fn is_synchronous_frame_reconciled(&mut self, native_frame_count: i32) -> bool {
103        // The application may have dropped the renderer after reconciling the main viewport.
104        self.drain_messages();
105        self.synchronous_frame.is_some_and(|frame| {
106            frame.native_frame_count == native_frame_count
107                && frame.epoch.is_some_and(|epoch| {
108                    self.phase == ConsumerPhase::Active(epoch.consumer_generation_raw())
109                })
110                && frame.status == SynchronousFrameStatus::Reconciled
111        })
112    }
113
114    pub(super) fn validate_consumer_admission(&self) -> Result<NonZeroU64, RendererConsumerError> {
115        if let Some(error) = self.pending_errors.front().copied() {
116            return Err(error);
117        }
118        match self.phase {
119            ConsumerPhase::Active(_) => {
120                return Err(RendererConsumerError::ConsumerAlreadyActive);
121            }
122            ConsumerPhase::Draining(_) => return Err(RendererConsumerError::ConsumerDraining),
123            ConsumerPhase::Unbound => {}
124        }
125        self.next_consumer_generation
126            .ok_or(RendererConsumerError::ConsumerGenerationExhausted)
127    }
128
129    fn commit_consumer_admission(&mut self, generation: NonZeroU64) {
130        debug_assert_eq!(
131            self.validate_consumer_admission(),
132            Ok(generation),
133            "renderer consumer admission must be validated before it is committed"
134        );
135        let claimed_generation = self
136            .next_consumer_generation
137            .take()
138            .expect("validated renderer consumer generation must remain available");
139        assert_eq!(
140            claimed_generation, generation,
141            "renderer consumer generation changed after admission validation"
142        );
143        self.next_consumer_generation = generation.get().checked_add(1).and_then(NonZeroU64::new);
144        self.phase = ConsumerPhase::Active(generation);
145    }
146
147    pub(super) fn commit_synchronous_consumer_admission(
148        &mut self,
149        generation: NonZeroU64,
150    ) -> SynchronousRendererConsumer {
151        self.commit_consumer_admission(generation);
152        SynchronousRendererConsumer::new(self.context, generation, self.sender.clone())
153    }
154
155    pub(super) fn commit_detached_consumer_admission(
156        &mut self,
157        generation: NonZeroU64,
158    ) -> DetachedRendererConsumer {
159        self.commit_consumer_admission(generation);
160        DetachedRendererConsumer::new(self.context, generation, self.sender.clone())
161    }
162
163    pub(super) fn begin_snapshot(
164        &mut self,
165        consumer: &DetachedRendererConsumer,
166        pending: PendingSnapshot,
167        requests: Vec<PendingTextureRequest>,
168        registry: &mut ManagedTextureRegistry,
169        atlas: &FontAtlasSnapshotTarget,
170    ) -> Result<FrameSnapshot, SnapshotError> {
171        let generation = self.validate_consumer(consumer)?;
172        let sequence = self.allocate_epoch()?;
173        let epoch = SnapshotEpoch::new(self.context, generation, sequence);
174        let referenced = pending.referenced_user_textures(&requests);
175        registry.record_snapshot_references(&referenced, sequence.get())?;
176        for request in &requests {
177            if matches!(request.texture, SnapshotTextureId::FontAtlas { .. }) {
178                atlas.record_request_reference(request.texture, sequence.get());
179            }
180        }
181        let (snapshot, expected) = pending.into_frame(requests, epoch, self.sender.clone());
182        if !expected.is_empty() {
183            self.texture_owner = Some(generation);
184        }
185        let previous = self.outstanding.insert(
186            sequence.get(),
187            OutstandingEpoch {
188                epoch,
189                expected,
190                completion: None,
191            },
192        );
193        debug_assert!(previous.is_none(), "snapshot epoch was allocated twice");
194        Ok(snapshot)
195    }
196
197    pub(super) fn begin_synchronous(
198        &mut self,
199        consumer: &SynchronousRendererConsumer,
200        pending: Vec<PendingTextureRequest>,
201        atlas: &FontAtlasSnapshotTarget,
202    ) -> Result<(SnapshotEpoch, Vec<TextureRequest>), RendererConsumerError> {
203        let generation = self.validate_consumer(consumer)?;
204        debug_assert!(self.outstanding.is_empty());
205        let sequence = self.allocate_epoch()?;
206        let epoch = SnapshotEpoch::new(self.context, generation, sequence);
207        if let Some(frame) = self.synchronous_frame.as_mut() {
208            frame.epoch = Some(epoch);
209        }
210        for request in &pending {
211            if matches!(request.texture, SnapshotTextureId::FontAtlas { .. }) {
212                atlas.record_request_reference(request.texture, sequence.get());
213            }
214        }
215        let (requests, expected) = finalize_texture_requests(pending, epoch);
216        if !expected.is_empty() {
217            self.texture_owner = Some(generation);
218        }
219        self.outstanding.insert(
220            sequence.get(),
221            OutstandingEpoch {
222                epoch,
223                expected,
224                completion: None,
225            },
226        );
227        Ok((epoch, requests))
228    }
229
230    pub(super) fn complete_synchronous(
231        &mut self,
232        epoch: SnapshotEpoch,
233        feedback: Vec<TextureFeedback>,
234        registry: &mut ManagedTextureRegistry,
235        atlas: FontAtlasSnapshotTarget,
236    ) -> Result<SnapshotCompletionProgress, RendererConsumerError> {
237        let result = self
238            .set_direct_completion(epoch, SnapshotCompletionOutcome::Committed(feedback))
239            .and_then(|()| self.advance(registry, &atlas));
240        self.finish_synchronous_frame(epoch, result.is_ok());
241        result
242    }
243
244    pub(super) fn abandon_synchronous(
245        &mut self,
246        epoch: SnapshotEpoch,
247        registry: &mut ManagedTextureRegistry,
248        atlas: FontAtlasSnapshotTarget,
249    ) {
250        if self
251            .set_direct_completion(epoch, SnapshotCompletionOutcome::Abandoned)
252            .is_ok()
253        {
254            let _ = self.advance(registry, &atlas);
255        }
256        self.finish_synchronous_frame(epoch, false);
257    }
258
259    fn finish_synchronous_frame(&mut self, epoch: SnapshotEpoch, reconciled: bool) {
260        let Some(frame) = self.synchronous_frame.as_mut() else {
261            return;
262        };
263        if frame.epoch != Some(epoch) {
264            return;
265        }
266        frame.status = if reconciled {
267            SynchronousFrameStatus::Reconciled
268        } else {
269            SynchronousFrameStatus::Abandoned
270        };
271    }
272
273    fn set_direct_completion(
274        &mut self,
275        epoch: SnapshotEpoch,
276        outcome: SnapshotCompletionOutcome,
277    ) -> Result<(), RendererConsumerError> {
278        let Some(outstanding) = self.outstanding.get_mut(&epoch.sequence()) else {
279            return Err(RendererConsumerError::UnknownEpoch {
280                epoch: epoch.sequence(),
281            });
282        };
283        if outstanding.epoch != epoch {
284            return Err(RendererConsumerError::StaleConsumerGeneration {
285                expected: outstanding.epoch.consumer_generation(),
286                actual: epoch.consumer_generation(),
287            });
288        }
289        if outstanding.completion.is_some() {
290            return Err(RendererConsumerError::EpochAlreadyCompleted {
291                epoch: epoch.sequence(),
292            });
293        }
294        if let SnapshotCompletionOutcome::Committed(feedback) = &outcome {
295            validate_texture_feedback(epoch, &outstanding.expected, feedback)?;
296        }
297        outstanding.completion = Some(outcome);
298        Ok(())
299    }
300
301    fn allocate_epoch(&mut self) -> Result<NonZeroU64, RendererConsumerError> {
302        let sequence = self
303            .next_epoch
304            .take()
305            .ok_or(RendererConsumerError::EpochExhausted)?;
306        self.next_epoch = sequence.get().checked_add(1).and_then(NonZeroU64::new);
307        Ok(sequence)
308    }
309
310    pub(super) fn validate_consumer(
311        &self,
312        consumer: &impl RendererConsumerCapability,
313    ) -> Result<NonZeroU64, RendererConsumerError> {
314        let generation = self.validate_consumer_identity(consumer)?;
315        if self.texture_owner.is_some_and(|owner| owner != generation) {
316            return Err(RendererConsumerError::RendererTextureResetRequired);
317        }
318        Ok(generation)
319    }
320
321    fn validate_consumer_identity(
322        &self,
323        consumer: &impl RendererConsumerCapability,
324    ) -> Result<NonZeroU64, RendererConsumerError> {
325        if consumer.context_id() != self.context {
326            return Err(RendererConsumerError::ForeignContext {
327                expected: self.context,
328                actual: consumer.context_id(),
329            });
330        }
331        match self.phase {
332            ConsumerPhase::Unbound => Err(RendererConsumerError::NoActiveConsumer),
333            ConsumerPhase::Draining(_) => Err(RendererConsumerError::ConsumerDraining),
334            ConsumerPhase::Active(expected) if expected != consumer_generation_raw(consumer) => {
335                Err(RendererConsumerError::StaleConsumerGeneration {
336                    expected: expected.get(),
337                    actual: consumer.generation(),
338                })
339            }
340            ConsumerPhase::Active(generation) => Ok(generation),
341        }
342    }
343
344    pub(super) fn poll(
345        &mut self,
346        registry: &mut ManagedTextureRegistry,
347        atlas: &FontAtlasSnapshotTarget,
348    ) -> Result<SnapshotCompletionProgress, RendererConsumerError> {
349        self.drain_messages();
350        self.advance(registry, atlas)
351    }
352
353    fn advance(
354        &mut self,
355        registry: &mut ManagedTextureRegistry,
356        atlas: &FontAtlasSnapshotTarget,
357    ) -> Result<SnapshotCompletionProgress, RendererConsumerError> {
358        let mut progress = SnapshotCompletionProgress {
359            watermark: self.completion_watermark,
360            ..Default::default()
361        };
362        let previous_watermark = self.completion_watermark;
363
364        while let Some((&sequence, outstanding)) = self.outstanding.first_key_value() {
365            if outstanding.completion.is_none() {
366                break;
367            }
368            let mut outstanding = self
369                .outstanding
370                .remove(&sequence)
371                .expect("first outstanding epoch still exists");
372            let outcome = outstanding
373                .completion
374                .take()
375                .expect("completed epoch contains an outcome");
376            match outcome {
377                SnapshotCompletionOutcome::Committed(feedback) => {
378                    match validate_texture_feedback(
379                        outstanding.epoch,
380                        &outstanding.expected,
381                        &feedback,
382                    )
383                    .and_then(|()| registry.apply_snapshot_feedback(&feedback, atlas, sequence))
384                    {
385                        Ok(applied) => {
386                            progress.committed += 1;
387                            progress.feedback_applied += applied;
388                        }
389                        Err(error) => {
390                            self.pending_errors.push_back(error);
391                            progress.abandoned += 1;
392                        }
393                    }
394                }
395                SnapshotCompletionOutcome::Abandoned => {
396                    progress.abandoned += 1;
397                }
398            }
399            self.completion_watermark = sequence;
400            progress.watermark = sequence;
401        }
402
403        if self.completion_watermark != previous_watermark {
404            registry.reap_destroyed(self.completion_watermark);
405            atlas.prune_tombstones(self.completion_watermark);
406        }
407        if matches!(self.phase, ConsumerPhase::Draining(_)) && self.outstanding.is_empty() {
408            self.phase = ConsumerPhase::Unbound;
409        }
410        if let Some(error) = self.pending_errors.pop_front() {
411            Err(error)
412        } else {
413            Ok(progress)
414        }
415    }
416
417    fn drain_messages(&mut self) {
418        loop {
419            match self.receiver.try_recv() {
420                Ok(SnapshotMessage::Completion(completion)) => {
421                    let sequence = completion.epoch.sequence();
422                    if completion.epoch.context_id() != self.context {
423                        self.pending_errors
424                            .push_back(RendererConsumerError::ForeignContext {
425                                expected: self.context,
426                                actual: completion.epoch.context_id(),
427                            });
428                        continue;
429                    }
430                    let Some(outstanding) = self.outstanding.get_mut(&sequence) else {
431                        self.pending_errors
432                            .push_back(RendererConsumerError::UnknownEpoch { epoch: sequence });
433                        continue;
434                    };
435                    if outstanding.epoch != completion.epoch {
436                        self.pending_errors.push_back(
437                            RendererConsumerError::StaleConsumerGeneration {
438                                expected: outstanding.epoch.consumer_generation(),
439                                actual: completion.epoch.consumer_generation(),
440                            },
441                        );
442                        continue;
443                    }
444                    if outstanding.completion.is_some() {
445                        self.pending_errors.push_back(
446                            RendererConsumerError::EpochAlreadyCompleted { epoch: sequence },
447                        );
448                        continue;
449                    }
450                    outstanding.completion = Some(completion.outcome);
451                }
452                Ok(SnapshotMessage::Detach {
453                    context,
454                    generation,
455                }) => {
456                    if context != self.context {
457                        self.pending_errors
458                            .push_back(RendererConsumerError::ForeignContext {
459                                expected: self.context,
460                                actual: context,
461                            });
462                        continue;
463                    }
464                    match self.phase {
465                        ConsumerPhase::Active(active) if active == generation => {
466                            self.phase = ConsumerPhase::Draining(generation);
467                        }
468                        ConsumerPhase::Draining(active) if active == generation => {}
469                        ConsumerPhase::Active(active) | ConsumerPhase::Draining(active) => {
470                            self.pending_errors.push_back(
471                                RendererConsumerError::StaleConsumerGeneration {
472                                    expected: active.get(),
473                                    actual: generation.get(),
474                                },
475                            );
476                        }
477                        ConsumerPhase::Unbound => {
478                            self.pending_errors
479                                .push_back(RendererConsumerError::NoActiveConsumer);
480                        }
481                    }
482                }
483                Err(TryRecvError::Empty | TryRecvError::Disconnected) => break,
484            }
485        }
486    }
487
488    pub(super) fn close(&mut self) {
489        self.outstanding.clear();
490        self.phase = ConsumerPhase::Unbound;
491        self.synchronous_frame = None;
492    }
493}
494
495/// One-use permission to reset Context-owned renderer texture bindings.
496///
497/// [`Context::prepare_renderer_texture_reset`] validates that the matching renderer consumer is
498/// idle before any GPU resource is released. The permit then keeps both the Context and consumer
499/// borrowed while the backend destroys its texture map. Call [`Self::commit`] only after those GPU
500/// resources are no longer reachable. Dropping the permit without committing leaves every native
501/// binding unchanged.
502#[must_use = "destroy the renderer texture map, then commit this reset permit"]
503pub struct RendererTextureReset<'context, 'consumer> {
504    context: &'context mut Context,
505    _consumer: &'consumer dyn RendererConsumerCapability,
506    watermark: u64,
507}
508
509impl RendererTextureReset<'_, '_> {
510    /// Clear the bindings covered by this already-validated reset transaction.
511    ///
512    /// This operation is infallible because the permit exclusively borrows the Context, keeps the
513    /// validated consumer alive, and was created only after all of its epochs completed.
514    pub fn commit(self) {
515        let binding = self.context.binding();
516        binding.with_bound_context(|| self.commit_unlocked());
517    }
518
519    fn commit_unlocked(self) {
520        self.context
521            .commit_renderer_texture_reset_unlocked(self.watermark);
522    }
523}
524
525impl Context {
526    /// Validate whether this Context can attach a managed renderer consumer.
527    ///
528    /// This check is non-mutating: it neither reserves a consumer generation nor claims the font
529    /// atlas for managed rendering. It is intended for integrations that must validate several
530    /// Contexts before attaching any renderer. A successful preflight is only a snapshot of the
531    /// current state; both consumer creation methods repeat the validation when they commit.
532    ///
533    /// Pending detached completions are not polled by this method. Call
534    /// [`Self::poll_snapshot_completions`] first when retrying after a consumer entered its
535    /// draining phase.
536    pub fn preflight_renderer_consumer(&self) -> Result<(), RendererConsumerError> {
537        let _guard = CTX_MUTEX.lock();
538        self.validate_renderer_consumer_admission_unlocked("Context::preflight_renderer_consumer()")
539            .map(|_| ())
540    }
541
542    /// Register the sole synchronous renderer consumer for this Context.
543    ///
544    /// The generation is fixed to synchronous rendering when it is created and cannot be used to
545    /// build detached snapshots.
546    ///
547    /// A [`SharedFontAtlas`](crate::SharedFontAtlas) must be registered with exactly one context
548    /// before it can enter managed renderer mode. If multiple contexts still share the atlas, this
549    /// returns [`RendererConsumerError::SharedFontAtlasRequiresExclusiveContext`]. Multiple-context
550    /// shared atlases remain available to legacy renderer-managed texture handling.
551    /// When replacing a renderer that issued texture requests, release its resources and commit
552    /// [`Self::prepare_renderer_texture_reset`] before rendering with the replacement.
553    pub fn create_synchronous_renderer_consumer(
554        &mut self,
555    ) -> Result<SynchronousRendererConsumer, RendererConsumerError> {
556        let _guard = CTX_MUTEX.lock();
557        let generation = self.commit_renderer_consumer_admission_unlocked(
558            "Context::create_synchronous_renderer_consumer()",
559        )?;
560        Ok(self
561            .snapshot_hub
562            .commit_synchronous_consumer_admission(generation))
563    }
564
565    /// Register the sole detached renderer consumer for this Context.
566    ///
567    /// The generation is fixed to pointer-free snapshot rendering when it is created. Dropping the
568    /// capability begins draining any outstanding snapshot epochs.
569    /// If its predecessor issued texture requests, release the old renderer's resources and
570    /// commit [`Self::prepare_renderer_texture_reset`] before capturing with the replacement.
571    pub fn create_detached_renderer_consumer(
572        &mut self,
573    ) -> Result<DetachedRendererConsumer, RendererConsumerError> {
574        let _guard = CTX_MUTEX.lock();
575        let generation = self.commit_renderer_consumer_admission_unlocked(
576            "Context::create_detached_renderer_consumer()",
577        )?;
578        Ok(self
579            .snapshot_hub
580            .commit_detached_consumer_admission(generation))
581    }
582
583    fn commit_renderer_consumer_admission_unlocked(
584        &mut self,
585        caller: &str,
586    ) -> Result<NonZeroU64, RendererConsumerError> {
587        self.assert_current_context(caller);
588        let atlas_target = self.font_atlas_snapshot_target();
589        let _ = self.poll_snapshot_completions_with_target(&atlas_target)?;
590        let (atlas, generation) = self.validate_renderer_consumer_admission_unlocked(caller)?;
591        let _ = crate::fonts::claim_validated_font_atlas_managed_renderer(atlas, self.raw);
592        Ok(generation)
593    }
594
595    fn validate_renderer_consumer_admission_unlocked(
596        &self,
597        caller: &str,
598    ) -> Result<(*mut crate::sys::ImFontAtlas, NonZeroU64), RendererConsumerError> {
599        self.assert_current_context(caller);
600        let io = self.io_ptr(caller);
601        let atlas = unsafe { (*io).Fonts };
602        crate::fonts::validate_font_atlas_managed_renderer(atlas, self.raw)?;
603        let generation = self.snapshot_hub.validate_consumer_admission()?;
604        Ok((atlas, generation))
605    }
606
607    /// Merge all currently available detached completion messages.
608    pub fn poll_snapshot_completions(
609        &mut self,
610    ) -> Result<SnapshotCompletionProgress, RendererConsumerError> {
611        let _guard = CTX_MUTEX.lock();
612        self.poll_snapshot_completions_unlocked()
613    }
614
615    pub(super) fn poll_snapshot_completions_unlocked(
616        &mut self,
617    ) -> Result<SnapshotCompletionProgress, RendererConsumerError> {
618        self.assert_current_context("Context::poll_snapshot_completions()");
619        let atlas = self.font_atlas_snapshot_target();
620        self.poll_snapshot_completions_with_target(&atlas)
621    }
622
623    fn poll_snapshot_completions_with_target(
624        &mut self,
625        atlas: &FontAtlasSnapshotTarget,
626    ) -> Result<SnapshotCompletionProgress, RendererConsumerError> {
627        self.snapshot_hub
628            .poll(&mut self.texture_registry.borrow_mut(), atlas)
629    }
630
631    /// Validate an idle renderer generation before destroying its complete GPU texture map.
632    ///
633    /// This two-phase transaction is the only safe renderer-reset path. Prepare the reset while
634    /// the renderer is still intact, release every GPU resource keyed by this consumer, then call
635    /// [`RendererTextureReset::commit`]. If preparation fails, the backend can return without
636    /// partially destroying its resource map. Dropping the permit without commit does not mutate
637    /// native texture state.
638    ///
639    /// A single-call reset is intentionally unavailable because the Context cannot prove that an
640    /// external renderer released its GPU map first:
641    ///
642    /// ```compile_fail
643    /// use dear_imgui_rs::Context;
644    ///
645    /// let mut context = Context::create();
646    /// let consumer = context.create_synchronous_renderer_consumer().unwrap();
647    /// let _ = context.reset_renderer_texture_bindings(&consumer);
648    /// ```
649    pub fn prepare_renderer_texture_reset<'context, 'consumer>(
650        &'context mut self,
651        consumer: &'consumer impl RendererConsumerCapability,
652    ) -> Result<RendererTextureReset<'context, 'consumer>, RendererConsumerError> {
653        let _guard = CTX_MUTEX.lock();
654        self.prepare_renderer_texture_reset_unlocked(consumer)
655    }
656
657    /// Prepares a reset while `Context::drop` already owns the Context lock.
658    ///
659    /// The only caller is the phase-limited attachment capability. Not reacquiring the global
660    /// lock avoids recursive locking during Context teardown while retaining the ordinary public
661    /// transaction for all external renderers.
662    pub(super) fn prepare_renderer_texture_reset_during_teardown(
663        &mut self,
664        consumer: &impl RendererConsumerCapability,
665    ) -> Result<u64, RendererConsumerError> {
666        self.validate_renderer_texture_reset_unlocked(consumer)
667    }
668
669    fn prepare_renderer_texture_reset_unlocked<'context, 'consumer>(
670        &'context mut self,
671        consumer: &'consumer impl RendererConsumerCapability,
672    ) -> Result<RendererTextureReset<'context, 'consumer>, RendererConsumerError> {
673        let watermark = self.validate_renderer_texture_reset_unlocked(consumer)?;
674        Ok(RendererTextureReset {
675            context: self,
676            _consumer: consumer,
677            watermark,
678        })
679    }
680
681    fn validate_renderer_texture_reset_unlocked(
682        &mut self,
683        consumer: &impl RendererConsumerCapability,
684    ) -> Result<u64, RendererConsumerError> {
685        self.assert_current_context("Context::prepare_renderer_texture_reset()");
686        self.snapshot_hub.validate_consumer_identity(consumer)?;
687        let atlas = self.font_atlas_snapshot_target();
688        let _ = self.poll_snapshot_completions_with_target(&atlas)?;
689        if !self.snapshot_hub.outstanding.is_empty() {
690            return Err(RendererConsumerError::OutstandingEpochs {
691                count: self.snapshot_hub.outstanding.len(),
692            });
693        }
694        Ok(self.snapshot_hub.completion_watermark())
695    }
696
697    pub(super) fn commit_renderer_texture_reset_during_teardown(&mut self, watermark: u64) {
698        self.commit_renderer_texture_reset_unlocked(watermark);
699    }
700
701    fn commit_renderer_texture_reset_unlocked(&mut self, watermark: u64) {
702        self.assert_current_context("RendererTextureReset::commit()");
703        let atlas = self.font_atlas_snapshot_target();
704        atlas.reset_renderer_bindings();
705        self.texture_registry
706            .borrow_mut()
707            .reset_renderer_bindings(watermark);
708        self.snapshot_hub.texture_owner = None;
709        self.snapshot_hub.synchronous_frame = None;
710    }
711
712    pub(super) fn capture_main_snapshot(
713        &mut self,
714        consumer: &DetachedRendererConsumer,
715        draw_data: *const crate::render::DrawData,
716    ) -> Result<FrameSnapshot, SnapshotError> {
717        let atlas = self.font_atlas_snapshot_target();
718        let _ = self.poll_snapshot_completions_with_target(&atlas)?;
719        let pending = {
720            let registry = self.texture_registry.borrow();
721            let mut resolve = |native| registry.resolve_snapshot_texture(native, &atlas);
722            capture_draw_data(unsafe { &*draw_data }, &mut resolve)?
723        };
724        let requests = self
725            .texture_registry
726            .borrow_mut()
727            .stage_snapshot_operations(&pending.texture_operations, &atlas)?;
728        self.snapshot_hub.begin_snapshot(
729            consumer,
730            pending,
731            requests,
732            &mut self.texture_registry.borrow_mut(),
733            &atlas,
734        )
735    }
736
737    pub(super) fn begin_synchronous_render(
738        &mut self,
739        consumer: &SynchronousRendererConsumer,
740        draw_data: *const crate::render::DrawData,
741    ) -> Result<(SnapshotEpoch, Vec<TextureRequest>), SnapshotError> {
742        let native_frame_count = unsafe { (*self.raw).FrameCount };
743        self.snapshot_hub
744            .begin_synchronous_native_frame(native_frame_count);
745        let atlas = self.font_atlas_snapshot_target();
746        let _ = self.poll_snapshot_completions_with_target(&atlas)?;
747        let captured = {
748            let registry = self.texture_registry.borrow();
749            let mut resolve = |native| registry.resolve_snapshot_texture(native, &atlas);
750            capture_texture_requests_only(unsafe { &*draw_data }, &mut resolve)?
751        };
752        let pending = self
753            .texture_registry
754            .borrow_mut()
755            .stage_snapshot_operations(&captured, &atlas)?;
756        let (epoch, requests) = self
757            .snapshot_hub
758            .begin_synchronous(consumer, pending, &atlas)?;
759        let ids = requests
760            .iter()
761            .filter_map(|request| match request.texture() {
762                crate::render::snapshot::SnapshotTextureId::User(id) => Some(id),
763                crate::render::snapshot::SnapshotTextureId::FontAtlas { .. } => None,
764            })
765            .collect();
766        self.texture_registry
767            .borrow_mut()
768            .record_snapshot_references(&ids, epoch.sequence())?;
769        Ok((epoch, requests))
770    }
771
772    pub(crate) fn complete_synchronous_render(
773        &mut self,
774        epoch: SnapshotEpoch,
775        feedback: Vec<TextureFeedback>,
776    ) -> Result<SnapshotCompletionProgress, RendererConsumerError> {
777        let atlas = self.font_atlas_snapshot_target();
778        self.snapshot_hub.complete_synchronous(
779            epoch,
780            feedback,
781            &mut self.texture_registry.borrow_mut(),
782            atlas,
783        )
784    }
785
786    pub(crate) fn abandon_synchronous_render(&mut self, epoch: SnapshotEpoch) {
787        let atlas = self.font_atlas_snapshot_target();
788        self.snapshot_hub.abandon_synchronous(
789            epoch,
790            &mut self.texture_registry.borrow_mut(),
791            atlas,
792        );
793    }
794
795    #[cfg(feature = "multi-viewport")]
796    pub(super) fn capture_platform_snapshot(
797        &mut self,
798        consumer: &DetachedRendererConsumer,
799    ) -> Result<FrameSnapshot, SnapshotError> {
800        let atlas = self.font_atlas_snapshot_target();
801        let _ = self.poll_snapshot_completions_with_target(&atlas)?;
802        let platform_io_ptr = self.platform_io_ptr("Context::capture_platform_snapshot()");
803        let platform_io =
804            unsafe { crate::platform_io::PlatformIo::from_raw(platform_io_ptr.cast_const()) };
805        let pending = {
806            let registry = self.texture_registry.borrow();
807            let mut resolve = |native| registry.resolve_snapshot_texture(native, &atlas);
808            // SAFETY: this Context owns the live rendered frame and PlatformIO draw pointers;
809            // capture copies all data before either can be advanced or destroyed.
810            unsafe { capture_platform_io(platform_io, &mut resolve)? }
811        };
812        let requests = self
813            .texture_registry
814            .borrow_mut()
815            .stage_snapshot_operations(&pending.texture_operations, &atlas)?;
816        self.snapshot_hub.begin_snapshot(
817            consumer,
818            pending,
819            requests,
820            &mut self.texture_registry.borrow_mut(),
821            &atlas,
822        )
823    }
824
825    pub(super) fn font_atlas_snapshot_target(&self) -> FontAtlasSnapshotTarget {
826        let io = self.io_ptr("Context snapshot texture capture");
827        let atlas = unsafe { (*io).Fonts };
828        assert!(!atlas.is_null(), "Context has no font atlas");
829        let textures = crate::fonts::font_atlas_snapshot_identities(atlas, self.raw)
830            .into_iter()
831            .map(|identity| {
832                FontAtlasTextureTarget::new(
833                    SnapshotTextureId::FontAtlas {
834                        context: self.id(),
835                        stamp: identity.stamp,
836                        generation: identity.texture_generation,
837                    },
838                    identity.texture,
839                )
840            })
841            .collect();
842        FontAtlasSnapshotTarget::new(atlas, self.id(), textures)
843    }
844}
845
846#[cfg(test)]
847mod tests {
848    use super::*;
849
850    #[test]
851    fn renderer_consumer_preflight_failure_does_not_claim_the_font_atlas() {
852        let _guard = crate::test_support::imgui_context_guard();
853        let atlas = crate::SharedFontAtlas::create();
854        let first = Context::create_with_shared_font_atlas(atlas.clone());
855        let suspended = first.suspend_or_panic();
856        let second = Context::create_with_shared_font_atlas(atlas.clone());
857
858        assert_eq!(
859            second.preflight_renderer_consumer(),
860            Err(
861                RendererConsumerError::SharedFontAtlasRequiresExclusiveContext {
862                    registered_contexts: 2,
863                }
864            )
865        );
866
867        drop(second);
868        let replacement = Context::try_create_with_shared_font_atlas(atlas.clone())
869            .expect("preflight must not claim the shared font atlas");
870        drop(replacement);
871        drop(suspended);
872    }
873
874    #[test]
875    fn renderer_consumer_hub_failure_does_not_claim_the_font_atlas() {
876        let _guard = crate::test_support::imgui_context_guard();
877        let atlas = crate::SharedFontAtlas::create();
878        let mut context = Context::create_with_shared_font_atlas(atlas.clone());
879        context.snapshot_hub.next_consumer_generation = None;
880
881        assert!(matches!(
882            context.create_synchronous_renderer_consumer(),
883            Err(RendererConsumerError::ConsumerGenerationExhausted)
884        ));
885
886        let suspended = context.suspend_or_panic();
887        let second = Context::try_create_with_shared_font_atlas(atlas.clone())
888            .expect("failed consumer admission must not claim the shared font atlas");
889        drop(second);
890        drop(suspended);
891    }
892}