aboutsummaryrefslogtreecommitdiff
path: root/samples/amber.cc
blob: 33fcf70c64d57054c7d93ac31378236c1c6b9f97 (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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// Copyright 2018 The Amber Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <cassert>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <utility>
#include <vector>

#include "amber/amber.h"
#include "amber/recipe.h"
#include "samples/config_helper.h"
#include "samples/ppm.h"
#include "src/build-versions.h"
#include "src/make_unique.h"

namespace {

struct Options {
  std::vector<std::string> input_filenames;

  std::string image_filename;
  std::string buffer_filename;
  std::vector<amber::BufferInfo> buffer_to_dump;
  uint32_t engine_major = 1;
  uint32_t engine_minor = 0;
  bool parse_only = false;
  bool pipeline_create_only = false;
  bool disable_validation_layer = false;
  bool show_summary = false;
  bool show_help = false;
  bool show_version_info = false;
  amber::EngineType engine = amber::kEngineTypeVulkan;
  std::string spv_env;
};

const char kUsage[] = R"(Usage: amber [options] SCRIPT [SCRIPTS...]

 options:
  -p                        -- Parse input files only; Don't execute.
  -ps                       -- Parse input files, create pipelines; Don't execute.
  -s                        -- Print summary of pass/failure.
  -d                        -- Disable validation layers.
  -t <spirv_env>            -- The target SPIR-V environment. Defaults to SPV_ENV_UNIVERSAL_1_0.
  -i <filename>             -- Write rendering to <filename> as a PPM image.
  -b <filename>             -- Write contents of a UBO or SSBO to <filename>.
  -B [<desc set>:]<binding> -- Descriptor set and binding of buffer to write.
                               Default is [0:]0.
  -e <engine>               -- Specify graphics engine: vulkan, dawn. Default is vulkan.
  -v <engine version>       -- Engine version (eg, 1.1 for Vulkan). Default 1.0.
  -V, --version             -- Output version information for Amber and libraries.
  -h                        -- This help text.
)";

bool ParseArgs(const std::vector<std::string>& args, Options* opts) {
  for (size_t i = 1; i < args.size(); ++i) {
    const std::string& arg = args[i];
    if (arg == "-i") {
      ++i;
      if (i >= args.size()) {
        std::cerr << "Missing value for -i argument." << std::endl;
        return false;
      }
      opts->image_filename = args[i];

    } else if (arg == "-b") {
      ++i;
      if (i >= args.size()) {
        std::cerr << "Missing value for -b argument." << std::endl;
        return false;
      }
      opts->buffer_filename = args[i];

    } else if (arg == "-B") {
      ++i;
      if (i >= args.size()) {
        std::cerr << "Missing value for -B argument." << std::endl;
        return false;
      }
      opts->buffer_to_dump.emplace_back();
      opts->buffer_to_dump.back().buffer_name = args[i];
    } else if (arg == "-e") {
      ++i;
      if (i >= args.size()) {
        std::cerr << "Missing value for -e argument." << std::endl;
        return false;
      }
      const std::string& engine = args[i];
      if (engine == "vulkan") {
        opts->engine = amber::kEngineTypeVulkan;
      } else if (engine == "dawn") {
        opts->engine = amber::kEngineTypeDawn;
      } else {
        std::cerr
            << "Invalid value for -e argument. Must be one of: vulkan dawn"
            << std::endl;
        return false;
      }
    } else if (arg == "-t") {
      ++i;
      if (i >= args.size()) {
        std::cerr << "Missing value for -t argument." << std::endl;
        return false;
      }
      opts->spv_env = args[i];
    } else if (arg == "-h" || arg == "--help") {
      opts->show_help = true;
    } else if (arg == "-v") {
      ++i;
      if (i >= args.size()) {
        std::cerr << "Missing value for -v argument." << std::endl;
        return false;
      }
      const std::string& ver = args[i];

      size_t dot_pos = 0;
      int32_t val = std::stoi(ver, &dot_pos);
      if (val < 0) {
        std::cerr << "Version major must be non-negative" << std::endl;
        return false;
      }

      opts->engine_major = static_cast<uint32_t>(val);
      if (dot_pos != std::string::npos && (dot_pos + 1) < ver.size()) {
        val = std::stoi(ver.substr(dot_pos + 1));
        if (val < 0) {
          std::cerr << "Version minor must be non-negative" << std::endl;
          return false;
        }
        opts->engine_minor = static_cast<uint32_t>(val);
      }
    } else if (arg == "-V" || arg == "--version") {
      opts->show_version_info = true;
    } else if (arg == "-p") {
      opts->parse_only = true;
    } else if (arg == "-ps") {
      opts->pipeline_create_only = true;
    } else if (arg == "-d") {
      opts->disable_validation_layer = true;
    } else if (arg == "-s") {
      opts->show_summary = true;
    } else if (arg.size() > 0 && arg[0] == '-') {
      std::cerr << "Unrecognized option " << arg << std::endl;
      return false;
    } else if (!arg.empty()) {
      opts->input_filenames.push_back(arg);
    }
  }

  return true;
}

std::string ReadFile(const std::string& input_file) {
  FILE* file = nullptr;
#if defined(_MSC_VER)
  fopen_s(&file, input_file.c_str(), "rb");
#else
  file = fopen(input_file.c_str(), "rb");
#endif
  if (!file) {
    std::cerr << "Failed to open " << input_file << std::endl;
    return {};
  }

  fseek(file, 0, SEEK_END);
  uint64_t tell_file_size = static_cast<uint64_t>(ftell(file));
  if (tell_file_size <= 0) {
    std::cerr << "Input file of incorrect size: " << input_file << std::endl;
    return {};
  }
  fseek(file, 0, SEEK_SET);

  size_t file_size = static_cast<size_t>(tell_file_size);

  std::vector<char> data;
  data.resize(file_size);

  size_t bytes_read = fread(data.data(), sizeof(char), file_size, file);
  fclose(file);
  if (bytes_read != file_size) {
    std::cerr << "Failed to read " << input_file << std::endl;
    return {};
  }

  return std::string(data.begin(), data.end());
}

}  // namespace

int main(int argc, const char** argv) {
  std::vector<std::string> args(argv, argv + argc);
  Options options;

  if (!ParseArgs(args, &options)) {
    std::cerr << "Failed to parse arguments." << std::endl;
    return 1;
  }

  if (options.show_version_info) {
    std::cout << "Amber        : " << AMBER_VERSION << std::endl;
#if AMBER_ENABLE_SPIRV_TOOLS
    std::cout << "SPIRV-Tools  : " << SPIRV_TOOLS_VERSION << std::endl;
    std::cout << "SPIRV-Headers: " << SPIRV_HEADERS_VERSION << std::endl;
#endif  // AMBER_ENABLE_SPIRV_TOOLS
#if AMBER_ENABLE_SHADERC
    std::cout << "GLSLang      : " << GLSLANG_VERSION << std::endl;
    std::cout << "Shaderc      : " << SHADERC_VERSION << std::endl;
#endif  // AMBER_ENABLE_SHADERC
  }

  if (options.show_help) {
    std::cout << kUsage << std::endl;
    return 0;
  }

  if (options.input_filenames.empty()) {
    std::cerr << "Input file must be provided." << std::endl;
    return 2;
  }

  amber::Result result;
  std::vector<std::string> failures;
  struct RecipeData {
    std::string file;
    std::unique_ptr<amber::Recipe> recipe;
  };
  std::vector<RecipeData> recipe_data;
  for (const auto& file : options.input_filenames) {
    auto data = ReadFile(file);
    if (data.empty()) {
      std::cerr << file << " is empty." << std::endl;
      failures.push_back(file);
      continue;
    }

    amber::Amber am;
    std::unique_ptr<amber::Recipe> recipe = amber::MakeUnique<amber::Recipe>();

    result = am.Parse(data, recipe.get());
    if (!result.IsSuccess()) {
      std::cerr << file << ": " << result.Error() << std::endl;
      failures.push_back(file);
      continue;
    }

    recipe_data.emplace_back();
    recipe_data.back().file = file;
    recipe_data.back().recipe = std::move(recipe);
  }

  if (options.parse_only)
    return 0;

  amber::Options amber_options;
  amber_options.engine = options.engine;
  amber_options.spv_env = options.spv_env;
  amber_options.pipeline_create_only = options.pipeline_create_only;

  std::set<std::string> required_features;
  std::set<std::string> required_extensions;
  for (const auto& recipe_data_elem : recipe_data) {
    const auto features = recipe_data_elem.recipe->GetRequiredFeatures();
    required_features.insert(features.begin(), features.end());

    const auto extensions = recipe_data_elem.recipe->GetRequiredExtensions();
    required_extensions.insert(extensions.begin(), extensions.end());
  }

  sample::ConfigHelper config_helper;
  std::unique_ptr<amber::EngineConfig> config;

  amber::Result r = config_helper.CreateConfig(
      amber_options.engine, options.engine_major, options.engine_minor,
      std::vector<std::string>(required_features.begin(),
                               required_features.end()),
      std::vector<std::string>(required_extensions.begin(),
                               required_extensions.end()),
      options.disable_validation_layer, &config);

  if (!r.IsSuccess()) {
    std::cout << r.Error() << std::endl;
    return 1;
  }

  amber_options.config = config.get();

  if (!options.buffer_filename.empty()) {
    // Have a filename to dump, but no explicit buffer, set the default of 0:0.
    if (options.buffer_to_dump.empty()) {
      options.buffer_to_dump.emplace_back();
      options.buffer_to_dump.back().buffer_name = "0:0";
    }

    amber_options.extractions.insert(amber_options.extractions.end(),
                                     options.buffer_to_dump.begin(),
                                     options.buffer_to_dump.end());
  }

  if (!options.image_filename.empty()) {
    amber::BufferInfo buffer_info;
    buffer_info.buffer_name = "framebuffer";
    amber_options.extractions.push_back(buffer_info);
  }

  for (const auto& recipe_data_elem : recipe_data) {
    const auto* recipe = recipe_data_elem.recipe.get();
    const auto& file = recipe_data_elem.file;

    amber::Amber am;
    result = am.Execute(recipe, &amber_options);
    if (!result.IsSuccess()) {
      std::cerr << file << ": " << result.Error() << std::endl;
      failures.push_back(file);
      continue;
    }

    if (!options.image_filename.empty()) {
      std::string image;
      for (amber::BufferInfo buffer_info : amber_options.extractions) {
        if (buffer_info.buffer_name == "framebuffer") {
          std::tie(result, image) = ppm::ConvertToPPM(
              buffer_info.width, buffer_info.height, buffer_info.values);
          break;
        }
      }
      if (!result.IsSuccess()) {
        std::cerr << result.Error() << std::endl;
        continue;
      }
      std::ofstream image_file;
      image_file.open(options.image_filename, std::ios::out | std::ios::binary);
      if (!image_file.is_open()) {
        std::cerr << "Cannot open file for image dump: ";
        std::cerr << options.image_filename << std::endl;
        continue;
      }
      image_file << image;
      image_file.close();
    }

    if (!options.buffer_filename.empty()) {
      std::ofstream buffer_file;
      buffer_file.open(options.buffer_filename, std::ios::out);
      if (!buffer_file.is_open()) {
        std::cerr << "Cannot open file for buffer dump: ";
        std::cerr << options.buffer_filename << std::endl;
      } else {
        for (amber::BufferInfo buffer_info : amber_options.extractions) {
          if (buffer_info.buffer_name == "framebuffer")
            continue;

          buffer_file << buffer_info.buffer_name << std::endl;
          const auto& values = buffer_info.values;
          for (size_t i = 0; i < values.size(); ++i) {
            buffer_file << " " << std::setfill('0') << std::setw(2) << std::hex
                        << values[i].AsUint32();
            if (i % 16 == 15)
              buffer_file << std::endl;
          }
          buffer_file << std::endl;
        }
        buffer_file.close();
      }
    }
  }

  if (options.show_summary) {
    if (!failures.empty()) {
      std::cout << "\nSummary of Failures:" << std::endl;

      for (const auto& failure : failures)
        std::cout << "  " << failure << std::endl;
    }

    std::cout << "\nSummary: "
              << (options.input_filenames.size() - failures.size()) << " pass, "
              << failures.size() << " fail" << std::endl;
  }

  config_helper.Shutdown();

  return !failures.empty();
}