Skip to main content

wgpu_hal/vulkan/
semaphore_list.rs

1//! Definition of the [`SemaphoreList`] type.
2
3use alloc::vec::Vec;
4use ash::vk;
5use core::mem::MaybeUninit;
6
7#[derive(Debug, PartialEq)]
8pub enum SemaphoreListMode {
9    Wait,
10    Signal,
11}
12
13/// A list of Vulkan semaphores to wait for or signal.
14///
15/// This represents a list of binary or timeline semaphores, together
16/// with values for the timeline semaphores, and stage masks, if these
17/// are used for waiting.
18///
19/// This type ensures that the array of semaphores to be signaled
20/// stays aligned with the array of values for timeline semaphores
21/// appearing in that list. The [`add_to_submit`] method prepares the
22/// `vkQueueSubmit` arguments appropriately for whatever semaphores we
23/// actually have.
24///
25/// [`add_to_submit`]: SemaphoreList::add_to_submit
26#[derive(Debug)]
27pub struct SemaphoreList {
28    /// Mode of the semaphore list. Used for validation.
29    mode: SemaphoreListMode,
30
31    /// Semaphores to use.
32    ///
33    /// This can be a mix of binary and timeline semaphores.
34    semaphores: Vec<vk::Semaphore>,
35
36    /// Values for the timeline semaphores.
37    ///
38    /// If no timeline semaphores are present in [`semaphores`], this
39    /// is empty. If any timeline semaphores are present, then this
40    /// has the same length as [`semaphores`], with dummy !0 values
41    /// in the elements corresponding to binary semaphores, since
42    /// Vulkan ignores these.
43    ///
44    /// [`semaphores`]: Self::semaphores
45    values: Vec<u64>,
46
47    /// Stage masks for wait semaphores.
48    ///
49    /// This is only used if `mode` is `Wait`.
50    pub stage_masks: Vec<vk::PipelineStageFlags>,
51}
52
53impl SemaphoreList {
54    pub fn new(mode: SemaphoreListMode) -> Self {
55        Self {
56            mode,
57            semaphores: Vec::new(),
58            values: Vec::new(),
59            stage_masks: Vec::new(),
60        }
61    }
62
63    pub fn is_empty(&self) -> bool {
64        self.semaphores.is_empty()
65    }
66
67    /// Add this list to the semaphores to be signalled by a `vkQueueSubmit` call.
68    ///
69    /// - Set `submit_info`'s `pSignalSemaphores` list to this list's
70    ///   semaphores.
71    ///
72    /// - If this list contains any timeline semaphores, then initialize
73    ///   `timeline_info`, set its `pSignalSemaphoreValues` to this
74    ///   list's values, and add it to `submit_info`s extension chain.
75    ///
76    /// - If either list contains a timeline semaphore, give every
77    ///   semaphore in both lists a value.
78    ///
79    /// Return the revised `submit_info` value.
80    pub fn add_to_submit<'info, 'semaphores: 'info>(
81        wait_semaphores: &'semaphores mut Self,
82        signal_semaphores: &'semaphores mut Self,
83        submit_info: vk::SubmitInfo<'info>,
84        timeline_info: &'info mut MaybeUninit<vk::TimelineSemaphoreSubmitInfo<'info>>,
85    ) -> vk::SubmitInfo<'info> {
86        wait_semaphores.check();
87        signal_semaphores.check();
88
89        assert!(matches!(wait_semaphores.mode, SemaphoreListMode::Wait));
90        assert!(matches!(signal_semaphores.mode, SemaphoreListMode::Signal));
91
92        let timeline_info = timeline_info.write(vk::TimelineSemaphoreSubmitInfo::default());
93
94        // Some drivers read a value for every semaphore when the timeline info is
95        // chained, and ignore the value counts. Seen on Imagination's proprietary
96        // driver (Pixel 10, Moto G54, Teclast P50AI) and on the Android 16 emulator
97        // (gfxstream).
98        // Vulkan ignores the values of binary semaphores.
99        //
100        // More info: https://github.com/gfx-rs/wgpu/pull/10677
101        if !wait_semaphores.values.is_empty() || !signal_semaphores.values.is_empty() {
102            wait_semaphores.pad_values();
103            signal_semaphores.pad_values();
104        }
105
106        let mut uses_timeline = false;
107
108        if !wait_semaphores.values.is_empty() {
109            *timeline_info = timeline_info.wait_semaphore_values(&wait_semaphores.values);
110            uses_timeline = true;
111        }
112
113        if !signal_semaphores.values.is_empty() {
114            *timeline_info = timeline_info.signal_semaphore_values(&signal_semaphores.values);
115            uses_timeline = true;
116        }
117
118        let mut submit_info = submit_info
119            .wait_semaphores(&wait_semaphores.semaphores)
120            .wait_dst_stage_mask(&wait_semaphores.stage_masks)
121            .signal_semaphores(&signal_semaphores.semaphores);
122
123        if uses_timeline {
124            submit_info = submit_info.push_next(timeline_info);
125        }
126
127        submit_info
128    }
129
130    /// Add a semaphore to be signaled. Panics if this is a list of semaphores to wait.
131    pub fn push_signal(&mut self, semaphore: SemaphoreType) {
132        assert!(matches!(self.mode, SemaphoreListMode::Signal));
133        self.push_inner(semaphore);
134    }
135
136    /// Add a semaphore to be waited for. Panics if this is a list of semaphores to signal.
137    pub fn push_wait(&mut self, semaphore: SemaphoreType, stage: vk::PipelineStageFlags) {
138        assert!(matches!(self.mode, SemaphoreListMode::Wait));
139
140        self.stage_masks.push(stage);
141        self.push_inner(semaphore);
142    }
143
144    fn push_inner(&mut self, semaphore: SemaphoreType) {
145        match semaphore {
146            SemaphoreType::Binary(semaphore) => {
147                self.semaphores.push(semaphore);
148                // Push a dummy value if necessary.
149                if !self.values.is_empty() {
150                    self.values.push(!0);
151                }
152            }
153            SemaphoreType::Timeline(semaphore, value) => {
154                // We may be the first timeline semaphore, ensure that the values
155                // array is filled with dummy values for existing binary semaphores.
156                self.pad_values();
157                self.semaphores.push(semaphore);
158                self.values.push(value);
159            }
160        }
161
162        self.check();
163    }
164
165    /// Remove all entries matching `semaphore` from the list. Returns `true`
166    /// if anything was removed.
167    pub fn remove(&mut self, semaphore: vk::Semaphore) -> bool {
168        let mut removed = false;
169        let mut i = 0;
170        while i < self.semaphores.len() {
171            if self.semaphores[i] == semaphore {
172                self.semaphores.swap_remove(i);
173                if !self.values.is_empty() {
174                    self.values.swap_remove(i);
175                }
176                if !self.stage_masks.is_empty() {
177                    self.stage_masks.swap_remove(i);
178                }
179                removed = true;
180            } else {
181                i += 1;
182            }
183        }
184        self.check();
185        removed
186    }
187
188    /// Append `other` to `self`, leaving `other` empty.
189    pub fn append(&mut self, other: &mut Self) {
190        assert_eq!(self.mode, other.mode);
191
192        // If we're about to receive values, ensure we're aligned first.
193        if !other.values.is_empty() {
194            self.pad_values();
195        }
196        self.semaphores.append(&mut other.semaphores);
197        self.values.append(&mut other.values);
198        // If we had values, but `other` did not, re-align.
199        if !self.values.is_empty() {
200            self.pad_values();
201        }
202        self.stage_masks.append(&mut other.stage_masks);
203        self.check();
204    }
205
206    /// Pad `self.values` with dummy values for binary semaphores,
207    /// in preparation for adding a timeline semaphore value.
208    ///
209    /// This is a no-op if we already have values.
210    fn pad_values(&mut self) {
211        self.values.resize(self.semaphores.len(), !0);
212    }
213
214    #[track_caller]
215    fn check(&self) {
216        debug_assert!(self.values.is_empty() || self.values.len() == self.semaphores.len());
217        match self.mode {
218            SemaphoreListMode::Wait => {
219                debug_assert!(
220                    self.stage_masks.is_empty() || self.stage_masks.len() == self.semaphores.len()
221                );
222            }
223            SemaphoreListMode::Signal => {
224                debug_assert!(self.stage_masks.is_empty());
225            }
226        }
227    }
228}
229
230pub enum SemaphoreType {
231    Binary(vk::Semaphore),
232    Timeline(vk::Semaphore, u64),
233}