summaryrefslogtreecommitdiffstats
path: root/gfx/wgpu/player/tests/test.rs
blob: 1b33fff58f6110a791a9f1890af81f36a08513d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*! Tester for WebGPU
 *  It enumerates the available backends on the system,
 *  and run the tests through them.
 *
 *  Test requirements:
 *    - all IDs have the backend `Empty`
 *    - all expected buffers have `MAP_READ` usage
 *    - last action is `Submit`
 *    - no swapchain use
!*/

use player::{GlobalPlay, IdentityPassThroughFactory};
use std::{
    fs::{read_to_string, File},
    io::{Read, Seek, SeekFrom},
    path::{Path, PathBuf},
    ptr, slice,
};

#[derive(serde::Deserialize)]
struct RawId {
    index: u32,
    epoch: u32,
}

#[derive(serde::Deserialize)]
enum ExpectedData {
    Raw(Vec<u8>),
    File(String, usize),
}

impl ExpectedData {
    fn len(&self) -> usize {
        match self {
            ExpectedData::Raw(vec) => vec.len(),
            ExpectedData::File(_, size) => *size,
        }
    }
}

#[derive(serde::Deserialize)]
struct Expectation {
    name: String,
    buffer: RawId,
    offset: wgt::BufferAddress,
    data: ExpectedData,
}

#[derive(serde::Deserialize)]
struct Test<'a> {
    features: wgt::Features,
    expectations: Vec<Expectation>,
    actions: Vec<wgc::device::trace::Action<'a>>,
}

extern "C" fn map_callback(status: wgc::resource::BufferMapAsyncStatus, _user_data: *mut u8) {
    match status {
        wgc::resource::BufferMapAsyncStatus::Success => (),
        _ => panic!("Unable to map"),
    }
}

impl Test<'_> {
    fn load(path: PathBuf, backend: wgt::Backend) -> Self {
        let backend_name = match backend {
            wgt::Backend::Vulkan => "Vulkan",
            wgt::Backend::Metal => "Metal",
            wgt::Backend::Dx12 => "Dx12",
            wgt::Backend::Dx11 => "Dx11",
            wgt::Backend::Gl => "Gl",
            _ => unreachable!(),
        };
        let string = read_to_string(path).unwrap().replace("Empty", backend_name);
        ron::de::from_str(&string).unwrap()
    }

    fn run(
        self,
        dir: &Path,
        global: &wgc::hub::Global<IdentityPassThroughFactory>,
        adapter: wgc::id::AdapterId,
        test_num: u32,
    ) {
        let backend = adapter.backend();
        let device = wgc::id::TypedId::zip(test_num, 0, backend);
        let (_, error) = wgc::gfx_select!(adapter => global.adapter_request_device(
            adapter,
            &wgt::DeviceDescriptor {
                label: None,
                features: self.features | wgt::Features::MAPPABLE_PRIMARY_BUFFERS,
                limits: wgt::Limits::default(),
                shader_validation: true,
            },
            None,
            device
        ));
        if let Some(e) = error {
            panic!("{:?}", e);
        }

        let mut command_buffer_id_manager = wgc::hub::IdentityManager::default();
        println!("\t\t\tRunning...");
        for action in self.actions {
            wgc::gfx_select!(device => global.process(device, action, dir, &mut command_buffer_id_manager));
        }
        println!("\t\t\tMapping...");
        for expect in &self.expectations {
            let buffer = wgc::id::TypedId::zip(expect.buffer.index, expect.buffer.epoch, backend);
            wgc::gfx_select!(device => global.buffer_map_async(
                buffer,
                expect.offset .. expect.offset+expect.data.len() as wgt::BufferAddress,
                wgc::resource::BufferMapOperation {
                    host: wgc::device::HostMap::Read,
                    callback: map_callback,
                    user_data: ptr::null_mut(),
                }
            ))
            .unwrap();
        }

        println!("\t\t\tWaiting...");
        wgc::gfx_select!(device => global.device_poll(device, true)).unwrap();

        for expect in self.expectations {
            println!("\t\t\tChecking {}", expect.name);
            let buffer = wgc::id::TypedId::zip(expect.buffer.index, expect.buffer.epoch, backend);
            let ptr =
                wgc::gfx_select!(device => global.buffer_get_mapped_range(buffer, expect.offset, None))
                    .unwrap();
            let contents = unsafe { slice::from_raw_parts(ptr, expect.data.len()) };
            let expected_data = match expect.data {
                ExpectedData::Raw(vec) => vec,
                ExpectedData::File(name, size) => {
                    let mut bin = vec![0; size];
                    let mut file = File::open(dir.join(name)).unwrap();
                    file.seek(SeekFrom::Start(expect.offset)).unwrap();
                    file.read_exact(&mut bin[..]).unwrap();

                    bin
                }
            };

            assert_eq!(&expected_data[..], contents);
        }

        wgc::gfx_select!(device => global.clear_backend(()));
    }
}

#[derive(serde::Deserialize)]
struct Corpus {
    backends: wgt::BackendBit,
    tests: Vec<String>,
}

const BACKENDS: &[wgt::Backend] = &[
    wgt::Backend::Vulkan,
    wgt::Backend::Metal,
    wgt::Backend::Dx12,
    wgt::Backend::Dx11,
    wgt::Backend::Gl,
];

impl Corpus {
    fn run_from(path: PathBuf) {
        println!("Corpus {:?}", path);
        let dir = path.parent().unwrap();
        let corpus: Corpus = ron::de::from_reader(File::open(&path).unwrap()).unwrap();

        let global = wgc::hub::Global::new("test", IdentityPassThroughFactory, corpus.backends);
        for &backend in BACKENDS {
            if !corpus.backends.contains(backend.into()) {
                continue;
            }
            let adapter = match global.request_adapter(
                &wgc::instance::RequestAdapterOptions {
                    power_preference: wgt::PowerPreference::LowPower,
                    compatible_surface: None,
                },
                wgc::instance::AdapterInputs::IdSet(
                    &[wgc::id::TypedId::zip(0, 0, backend)],
                    |id| id.backend(),
                ),
            ) {
                Ok(adapter) => adapter,
                Err(_) => continue,
            };

            println!("\tBackend {:?}", backend);
            let supported_features =
                wgc::gfx_select!(adapter => global.adapter_features(adapter)).unwrap();
            let mut test_num = 0;
            for test_path in &corpus.tests {
                println!("\t\tTest '{:?}'", test_path);
                let test = Test::load(dir.join(test_path), adapter.backend());
                if !supported_features.contains(test.features) {
                    println!(
                        "\t\tSkipped due to missing features {:?}",
                        test.features - supported_features
                    );
                    continue;
                }
                test.run(dir, &global, adapter, test_num);
                test_num += 1;
            }
        }
    }
}

#[test]
fn test_api() {
    Corpus::run_from(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/all.ron"))
}