aboutsummaryrefslogtreecommitdiff
path: root/src/dawn/engine_dawn.cc
blob: 09be0c358b7b9ebb0ec24c3337e03069114110c7 (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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
// 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 "src/dawn/engine_dawn.h"

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <limits>
#include <string>
#include <utility>
#include <vector>

#include "amber/amber_dawn.h"
#include "dawn/dawncpp.h"
#include "src/dawn/pipeline_info.h"
#include "src/format.h"
#include "src/make_unique.h"
#include "src/sleep.h"

namespace amber {
namespace dawn {

namespace {

// The minimum multiple row pitch observed on Dawn on Metal.  Increase this
// as needed for other Dawn backends.
static const uint32_t kMinimumImageRowPitch = 256;
static const float kLodMin = 0.0;
static const float kLodMax = 1000.0;
static const uint32_t kMaxColorAttachments = 4u;
static const uint32_t kMaxVertexInputs = 16u;
static const uint32_t kMaxVertexAttributes = 16u;
static const uint32_t kMaxDawnBindGroup = 4u;

// This structure is a container for a few variables that are created during
// CreateRenderPipelineDescriptor and CreateRenderPassDescriptor and we want to
// make sure they don't go out of scope before we are done with them
struct DawnPipelineHelper {
  Result CreateRenderPipelineDescriptor(
      const RenderPipelineInfo& render_pipeline,
      const ::dawn::Device& device,
      const bool ignore_vertex_and_Index_buffers);
  Result CreateRenderPassDescriptor(const RenderPipelineInfo& render_pipeline,
                                    const ::dawn::Device& device,
                                    const ::dawn::TextureView texture_view);
  ::dawn::RenderPipelineDescriptor renderPipelineDescriptor;
  ::dawn::RenderPassDescriptor renderPassDescriptor;

  ::dawn::InputStateDescriptor tempInputState = {};
  ::dawn::VertexInputDescriptor vertexInput;
  std::array<::dawn::VertexInputDescriptor, kMaxVertexInputs> tempInputs;
  std::array<::dawn::VertexAttributeDescriptor, kMaxVertexAttributes>
      tempAttributes;
  ::dawn::VertexAttributeDescriptor vertexAttribute;

 private:
  ::dawn::RenderPassColorAttachmentDescriptor*
      colorAttachmentsInfoPtr[kMaxColorAttachments];
  ::dawn::RenderPassDepthStencilAttachmentDescriptor depthStencilAttachmentInfo;
  std::array<::dawn::RenderPassColorAttachmentDescriptor, kMaxColorAttachments>
      colorAttachmentsInfo;
  std::array<::dawn::ColorStateDescriptor*, kMaxColorAttachments> colorStates;
  ::dawn::DepthStencilStateDescriptor depthStencilState;
  ::dawn::ColorStateDescriptor colorStatesDescriptor[kMaxColorAttachments];
  ::dawn::PipelineStageDescriptor fragmentStage;
  ::dawn::PipelineStageDescriptor vertexStage;
  ::dawn::StencilStateFaceDescriptor stencilFace;
  ::dawn::BlendDescriptor blend;
  ::dawn::ColorStateDescriptor colorStateDescriptor;
  std::string vertexEntryPoint;
  std::string fragmentEntryPoint;
};

// Creates a device-side texture, and returns it through |result_ptr|.
// Assumes the device exists and is valid.  Assumes result_ptr is not null.
// Returns a result code.
Result MakeTexture(const ::dawn::Device& device,
                   ::dawn::TextureFormat format,
                   uint32_t width,
                   uint32_t height,
                   ::dawn::Texture* result_ptr) {
  assert(device);
  assert(result_ptr);
  assert(width * height > 0);
  ::dawn::TextureDescriptor descriptor;
  descriptor.dimension = ::dawn::TextureDimension::e2D;
  descriptor.size.width = width;
  descriptor.size.height = height;
  descriptor.size.depth = 1;
  descriptor.arrayLayerCount = 1;
  descriptor.format = format;
  descriptor.mipLevelCount = 1;
  descriptor.sampleCount = 1;
  descriptor.usage = ::dawn::TextureUsageBit::TransferSrc |
                     ::dawn::TextureUsageBit::OutputAttachment;
  // TODO(dneto): Get a better message by using the Dawn error callback.
  *result_ptr = device.CreateTexture(&descriptor);
  if (*result_ptr)
    return {};
  return Result("Dawn: Failed to allocate a framebuffer texture");
}

// Creates a host-side buffer  of |size| bytes for the framebuffer, and returns
// it through |result_ptr|. The buffer will be used as a transfer destination
// and for mapping-for-read.  Returns a result code.
Result MakeFramebufferBuffer(const ::dawn::Device& device,
                             ::dawn::Buffer* result_ptr,
                             uint32_t size) {
  assert(device);
  assert(size > 0);
  assert(result_ptr);

  ::dawn::BufferDescriptor descriptor;
  descriptor.size = size;
  descriptor.usage =
      ::dawn::BufferUsageBit::TransferDst | ::dawn::BufferUsageBit::MapRead;
  *result_ptr = device.CreateBuffer(&descriptor);
  if (*result_ptr)
    return {};
  return Result("Dawn: Failed to allocate a framebuffer buffer");
}

// Result status object and data pointer resulting from a buffer mapping.
struct MapResult {
  Result result;
  const void* data = nullptr;
  uint64_t dataLength = 0;
};

// Handles the update from an asynchronous buffer map request, updating the
// state of the MapResult object hidden inside the |userdata| parameter.
// On a successful mapping outcome, set the data pointer in the map result.
// Otherwise set the map result object to an error, and the data member is
// not changed.
void HandleBufferMapCallback(DawnBufferMapAsyncStatus status,
                             const void* data,
                             uint64_t dataLength,
                             DawnCallbackUserdata userdata) {
  MapResult& map_result = *reinterpret_cast<MapResult*>(userdata);
  switch (status) {
    case DAWN_BUFFER_MAP_ASYNC_STATUS_SUCCESS:
      map_result.data = data;
      map_result.dataLength = dataLength;
      break;
    case DAWN_BUFFER_MAP_ASYNC_STATUS_ERROR:
      map_result.result = Result("Buffer map for reading failed: error");
      break;
    case DAWN_BUFFER_MAP_ASYNC_STATUS_UNKNOWN:
    case DAWN_BUFFER_MAP_ASYNC_STATUS_FORCE32:
      map_result.result = Result("Buffer map for reading failed: unknown");
      break;
    case DAWN_BUFFER_MAP_ASYNC_STATUS_CONTEXT_LOST:
      map_result.result = Result("Buffer map for reading failed: context lost");
      break;
  }
}
// Returns |value| but rounded up to a multiple of |alignment|. |alignment| is
// assumed to be a power of 2.
uint32_t Align(uint32_t value, size_t alignment) {
  assert(alignment <= std::numeric_limits<uint32_t>::max());
  assert(alignment != 0);
  uint32_t alignment32 = static_cast<uint32_t>(alignment);
  return (value + (alignment32 - 1)) & ~(alignment32 - 1);
}
}  // namespace

// Maps the given buffer.  Assumes the buffer has usage bit
// ::dawn::BufferUsageBit::MapRead set.  Returns a MapResult structure, with
// the status saved in the |result| member and the host pointer to the mapped
// data in the |data| member. Mapping a buffer can fail if the context is
// lost, for example. In the failure case, the |data| member will be null.
MapResult MapBuffer(const ::dawn::Device& device, const ::dawn::Buffer& buf) {
  MapResult map_result;
  buf.MapReadAsync(HandleBufferMapCallback,
                   static_cast<DawnCallbackUserdata>(
                       reinterpret_cast<uintptr_t>(&map_result)));
  device.Tick();
  // Wait until the callback has been processed.  Use an exponential backoff
  // interval, but cap it at one second intervals.  But never loop forever.
  const int max_iters = 100;
  const int one_second_in_us = 1000000;
  for (int iters = 0, interval = 1;
       !map_result.data && map_result.result.IsSuccess();
       iters++, interval = std::min(2 * interval, one_second_in_us)) {
    device.Tick();
    if (iters > max_iters) {
      map_result.result = Result("MapBuffer timed out after 100 iterations");
      break;
    }
    USleep(uint32_t(interval));
  }
  return map_result;
}

// Creates and returns a dawn BufferCopyView
// Copied from Dawn utils source code.
::dawn::BufferCopyView CreateBufferCopyView(::dawn::Buffer buffer,
                                            uint64_t offset,
                                            uint32_t rowPitch,
                                            uint32_t imageHeight) {
  ::dawn::BufferCopyView bufferCopyView;
  bufferCopyView.buffer = buffer;
  bufferCopyView.offset = offset;
  bufferCopyView.rowPitch = rowPitch;
  bufferCopyView.imageHeight = imageHeight;

  return bufferCopyView;
}

// Creates and returns a dawn TextureCopyView
// Copied from Dawn utils source code.
::dawn::TextureCopyView CreateTextureCopyView(::dawn::Texture texture,
                                              uint32_t level,
                                              uint32_t slice,
                                              ::dawn::Origin3D origin) {
  ::dawn::TextureCopyView textureCopyView;
  textureCopyView.texture = texture;
  textureCopyView.level = level;
  textureCopyView.slice = slice;
  textureCopyView.origin = origin;

  return textureCopyView;
}

// Creates and submits a command to copy the colour attachments back to the
// host.
// TODO(sarahM0): Handle more than one colour attachment
// TODO(sarahM0): Copy the buffer data for buffers that are not
// colour-attachments back into the Amber buffer objects.
MapResult MapTextureToHostBuffer(const RenderPipelineInfo& render_pipeline,
                                 const ::dawn::Device& device) {
  const auto width = render_pipeline.pipeline->GetFramebufferWidth();
  const auto height = render_pipeline.pipeline->GetFramebufferHeight();
  const auto pixelSize = render_pipeline.pipeline->GetColorAttachments()[0]
                             .buffer->GetTexelStride();
  const auto dawn_row_pitch = Align(width * pixelSize, kMinimumImageRowPitch);
  {
    ::dawn::TextureCopyView textureCopyView =
        CreateTextureCopyView(render_pipeline.fb_texture, 0, 0, {0, 0, 0});

    ::dawn::BufferCopyView bufferCopyView =
        CreateBufferCopyView(render_pipeline.fb_buffer, 0, dawn_row_pitch, 0);

    ::dawn::Extent3D copySize = {width, height, 1};

    auto encoder = device.CreateCommandEncoder();
    encoder.CopyTextureToBuffer(&textureCopyView, &bufferCopyView, &copySize);

    auto commands = encoder.Finish();
    auto queue = device.CreateQueue();
    queue.Submit(1, &commands);
  }

  MapResult map = MapBuffer(device, render_pipeline.fb_buffer);
  const std::vector<amber::Pipeline::BufferInfo>& out_color_attachment =
      render_pipeline.pipeline->GetColorAttachments();

  for (size_t i = 0; i < out_color_attachment.size(); ++i) {
    auto& info = out_color_attachment[i];
    auto* values = info.buffer->ValuePtr();
    auto row_stride = pixelSize * width;
    assert(row_stride * height == info.buffer->GetSizeInBytes());
    // Each Dawn row has enough data to fill the target row.
    assert(dawn_row_pitch >= row_stride);
    values->resize(info.buffer->GetSizeInBytes());
    // Copy the framebuffer contents back into the host-side
    // framebuffer-buffer. In the Dawn buffer, the row stride is a multiple of
    // kMinimumImageRowPitch bytes, so it might have padding therefore memcpy
    // is done row by row.
    for (uint h = 0; h < height; h++) {
      std::memcpy(values->data() + h * row_stride,
                  static_cast<const uint8_t*>(map.data) + h * dawn_row_pitch,
                  row_stride);
    }
  }
  // Always unmap the buffer at the end of the engine's command.
  render_pipeline.fb_buffer.Unmap();
  return map;
}

// Creates a dawn buffer of |size| bytes with TransferDst and the given usage
// copied from Dawn utils source code
::dawn::Buffer CreateBufferFromData(const ::dawn::Device& device,
                                    const void* data,
                                    uint64_t size,
                                    ::dawn::BufferUsageBit usage) {
  ::dawn::BufferDescriptor descriptor;
  descriptor.size = size;
  descriptor.usage = usage | ::dawn::BufferUsageBit::TransferDst;

  ::dawn::Buffer buffer = device.CreateBuffer(&descriptor);
  if (data != nullptr)
    buffer.SetSubData(0, size, reinterpret_cast<const uint8_t*>(data));
  return buffer;
}

// Creates a default sampler descriptor. It does not set the sampling
// coordinates meaning it's set to default, normalized.
// copied from Dawn utils source code
::dawn::SamplerDescriptor GetDefaultSamplerDescriptor() {
  ::dawn::SamplerDescriptor desc;
  desc.minFilter = ::dawn::FilterMode::Linear;
  desc.magFilter = ::dawn::FilterMode::Linear;
  desc.mipmapFilter = ::dawn::FilterMode::Linear;
  desc.addressModeU = ::dawn::AddressMode::Repeat;
  desc.addressModeV = ::dawn::AddressMode::Repeat;
  desc.addressModeW = ::dawn::AddressMode::Repeat;
  desc.lodMinClamp = kLodMin;
  desc.lodMaxClamp = kLodMax;
  desc.compareFunction = ::dawn::CompareFunction::Never;

  return desc;
}
// Creates a bind group.
// Helpers to make creating bind groups look nicer:
//
//   utils::MakeBindGroup(device, layout, {
//       {0, mySampler},
//       {1, myBuffer, offset, size},
//       {3, myTexture}
//   });

// Structure with one constructor per-type of bindings, so that the
// initializer_list accepts bindings with the right type and no extra
// information.
struct BindingInitializationHelper {
  BindingInitializationHelper(uint32_t binding,
                              const ::dawn::Buffer& buffer,
                              uint64_t offset,
                              uint64_t size)
      : binding(binding), buffer(buffer), offset(offset), size(size) {}

  ::dawn::BindGroupBinding GetAsBinding() const {
    ::dawn::BindGroupBinding result;
    result.binding = binding;
    result.sampler = sampler;
    result.textureView = textureView;
    result.buffer = buffer;
    result.offset = offset;
    result.size = size;
    return result;
  }

  uint32_t binding;
  ::dawn::Sampler sampler;
  ::dawn::TextureView textureView;
  ::dawn::Buffer buffer;
  uint64_t offset = 0;
  uint64_t size = 0;
};

::dawn::BindGroup MakeBindGroup(
    const ::dawn::Device& device,
    const ::dawn::BindGroupLayout& layout,
    const std::vector<BindingInitializationHelper>& bindingsInitializer) {
  std::vector<::dawn::BindGroupBinding> bindings;
  for (const BindingInitializationHelper& helper : bindingsInitializer) {
    bindings.push_back(helper.GetAsBinding());
  }

  ::dawn::BindGroupDescriptor descriptor;
  descriptor.layout = layout;
  descriptor.bindingCount = bindings.size();
  descriptor.bindings = bindings.data();

  return device.CreateBindGroup(&descriptor);
}

// Creates a bind group layout.
// Copied from Dawn utils source code.
::dawn::BindGroupLayout MakeBindGroupLayout(
    const ::dawn::Device& device,
    const std::vector<::dawn::BindGroupLayoutBinding>& bindingsInitializer) {
  constexpr ::dawn::ShaderStageBit kNoStages{};

  std::vector<::dawn::BindGroupLayoutBinding> bindings;
  for (const ::dawn::BindGroupLayoutBinding& binding : bindingsInitializer) {
    if (binding.visibility != kNoStages) {
      bindings.push_back(binding);
    }
  }

  ::dawn::BindGroupLayoutDescriptor descriptor;
  descriptor.bindingCount = static_cast<uint32_t>(bindings.size());
  descriptor.bindings = bindings.data();
  return device.CreateBindGroupLayout(&descriptor);
}

// Creates a basic pipeline layout.
// Copied from Dawn utils source code.
::dawn::PipelineLayout MakeBasicPipelineLayout(
    const ::dawn::Device& device,
    std::vector<::dawn::BindGroupLayout> bindingInitializer) {
  ::dawn::PipelineLayoutDescriptor descriptor;
  descriptor.bindGroupLayoutCount = bindingInitializer.size();
  descriptor.bindGroupLayouts = bindingInitializer.data();
  return device.CreatePipelineLayout(&descriptor);
}

// Creates a default depth stencil view.
// Copied from Dawn utils source code.
::dawn::TextureView CreateDefaultDepthStencilView(
    const ::dawn::Device& device,
    const RenderPipelineInfo& render_pipeline,
    const ::dawn::TextureFormat depth_stencil_format) {
  ::dawn::TextureDescriptor descriptor;
  descriptor.dimension = ::dawn::TextureDimension::e2D;
  descriptor.size.width = render_pipeline.pipeline->GetFramebufferWidth();
  descriptor.size.height = render_pipeline.pipeline->GetFramebufferHeight();
  descriptor.size.depth = 1;
  descriptor.arrayLayerCount = 1;
  descriptor.sampleCount = 1;
  descriptor.format = depth_stencil_format;
  descriptor.mipLevelCount = 1;
  descriptor.usage = ::dawn::TextureUsageBit::OutputAttachment;
  auto depthStencilTexture = device.CreateTexture(&descriptor);
  return depthStencilTexture.CreateDefaultView();
}

// Converts an Amber format to a Dawn texture format, and sends the result out
// through |dawn_format_ptr|.  If the conversion fails, return an error
// result.
Result GetDawnTextureFormat(const ::amber::Format& amber_format,
                            ::dawn::TextureFormat* dawn_format_ptr) {
  if (!dawn_format_ptr)
    return Result("Internal error: format pointer argument is null");
  ::dawn::TextureFormat& dawn_format = *dawn_format_ptr;

  switch (amber_format.GetFormatType()) {
    // TODO(dneto): These are all the formats that Dawn currently knows about.
    case FormatType::kR8G8B8A8_UNORM:
      dawn_format = ::dawn::TextureFormat::R8G8B8A8Unorm;
      break;
    case FormatType::kR8G8_UNORM:
      dawn_format = ::dawn::TextureFormat::R8G8Unorm;
      break;
    case FormatType::kR8_UNORM:
      dawn_format = ::dawn::TextureFormat::R8Unorm;
      break;
    case FormatType::kR8G8B8A8_UINT:
      dawn_format = ::dawn::TextureFormat::R8G8B8A8Uint;
      break;
    case FormatType::kR8G8_UINT:
      dawn_format = ::dawn::TextureFormat::R8G8Uint;
      break;
    case FormatType::kR8_UINT:
      dawn_format = ::dawn::TextureFormat::R8Uint;
      break;
    case FormatType::kB8G8R8A8_UNORM:
      dawn_format = ::dawn::TextureFormat::B8G8R8A8Unorm;
      break;
    case FormatType::kD32_SFLOAT_S8_UINT:
      dawn_format = ::dawn::TextureFormat::D32FloatS8Uint;
      break;
    default:
      return Result(
          "Amber format " +
          std::to_string(static_cast<uint32_t>(amber_format.GetFormatType())) +
          " is invalid for Dawn");
  }

  return {};
}
// Converts an Amber format to a Dawn Vertex format, and sends the result out
// through |dawn_format_ptr|.  If the conversion fails, return an error
// result.
// TODO(sarahM0): support other ::dawn::VertexFormat
Result GetDawnVertexFormat(const ::amber::Format& amber_format,
                           ::dawn::VertexFormat* dawn_format_ptr) {
  ::dawn::VertexFormat& dawn_format = *dawn_format_ptr;
  switch (amber_format.GetFormatType()) {
    case FormatType::kR32_SFLOAT:
      dawn_format = ::dawn::VertexFormat::Float;
      break;
    case FormatType::kR32G32_SFLOAT:
      dawn_format = ::dawn::VertexFormat::Float2;
      break;
    case FormatType::kR32G32B32_SFLOAT:
      dawn_format = ::dawn::VertexFormat::Float3;
      break;
    case FormatType::kR32G32B32A32_SFLOAT:
      dawn_format = ::dawn::VertexFormat::Float4;
      break;
    case FormatType::kR8G8_SNORM:
      dawn_format = ::dawn::VertexFormat::Char2Norm;
      break;
    case FormatType::kR8G8B8A8_UNORM:
      dawn_format = ::dawn::VertexFormat::UChar4Norm;
      break;
    case FormatType::kR8G8B8A8_SNORM:
      dawn_format = ::dawn::VertexFormat::Char4Norm;
      break;
    default:
      return Result(
          "Amber vertex format " +
          std::to_string(static_cast<uint32_t>(amber_format.GetFormatType())) +
          " is invalid for Dawn or is not supported in amber-dawn");
  }
  return {};
}

// Converts an Amber format to a Dawn Index format, and sends the result out
// through |dawn_format_ptr|.  If the conversion fails, return an error
// result.
Result GetDawnIndexFormat(const ::amber::Format& amber_format,
                          ::dawn::IndexFormat* dawn_format_ptr) {
  ::dawn::IndexFormat& dawn_format = *dawn_format_ptr;
  switch (amber_format.GetFormatType()) {
    case FormatType::kR16_UINT:
      dawn_format = ::dawn::IndexFormat::Uint16;
      break;
    case FormatType::kR32_UINT:
      dawn_format = ::dawn::IndexFormat::Uint32;
      break;
    default:
      return Result(
          "Amber index format " +
          std::to_string(static_cast<uint32_t>(amber_format.GetFormatType())) +
          " is invalid for Dawn");
  }
  return {};
}

// Converts an Amber topology to a Dawn topology, and sends the result out
// through |dawn_topology_ptr|. It the conversion fails, return an error result.
Result GetDawnTopology(const ::amber::Topology& amber_topology,
                       ::dawn::PrimitiveTopology* dawn_topology_ptr) {
  ::dawn::PrimitiveTopology& dawn_topology = *dawn_topology_ptr;
  switch (amber_topology) {
    case Topology::kPointList:
      dawn_topology = ::dawn::PrimitiveTopology::PointList;
      break;
    case Topology::kLineList:
      dawn_topology = ::dawn::PrimitiveTopology::LineList;
      break;
    case Topology::kLineStrip:
      dawn_topology = ::dawn::PrimitiveTopology::LineStrip;
      break;
    case Topology::kTriangleList:
      dawn_topology = ::dawn::PrimitiveTopology::TriangleList;
      break;
    case Topology::kTriangleStrip:
      dawn_topology = ::dawn::PrimitiveTopology::TriangleStrip;
      break;
    default:
      return Result("Amber PrimitiveTopology " +
                    std::to_string(static_cast<uint32_t>(amber_topology)) +
                    " is not supported in Dawn");
  }
  return {};
}

EngineDawn::EngineDawn() : Engine() {}

EngineDawn::~EngineDawn() = default;

Result EngineDawn::Initialize(EngineConfig* config,
                              Delegate*,
                              const std::vector<std::string>&,
                              const std::vector<std::string>&,
                              const std::vector<std::string>&) {
  if (device_)
    return Result("Dawn:Initialize device_ already exists");

  if (!config)
    return Result("Dawn::Initialize config is null");
  DawnEngineConfig* dawn_config = static_cast<DawnEngineConfig*>(config);
  if (dawn_config->device == nullptr)
    return Result("Dawn:Initialize device is a null pointer");

  device_ = dawn_config->device;

  return {};
}

Result EngineDawn::CreatePipeline(::amber::Pipeline* pipeline) {
  if (!device_) {
    return Result("Dawn::CreatePipeline: device is not created");
  }
  std::unordered_map<ShaderType, ::dawn::ShaderModule, CastHash<ShaderType>>
      module_for_type;
  ::dawn::ShaderModuleDescriptor descriptor;
  descriptor.nextInChain = nullptr;

  for (const auto& shader_info : pipeline->GetShaders()) {
    ShaderType type = shader_info.GetShaderType();
    const std::vector<uint32_t>& code = shader_info.GetData();
    descriptor.code = code.data();
    descriptor.codeSize = uint32_t(code.size());

    auto shader = device_->CreateShaderModule(&descriptor);
    if (!shader) {
      return Result("Dawn::CreatePipeline: failed to create shader");
    }
    if (module_for_type.count(type)) {
      return Result("Dawn::CreatePipeline: module for type already exists");
    }
    module_for_type[type] = shader;
  }

  switch (pipeline->GetType()) {
    case PipelineType::kCompute: {
      auto& module = module_for_type[kShaderTypeCompute];
      if (!module)
        return Result("Dawn::CreatePipeline: no compute shader provided");
      pipeline_map_[pipeline].compute_pipeline.reset(
          new ComputePipelineInfo(pipeline, module));
      break;
    }

    case PipelineType::kGraphics: {
      // TODO(dneto): Handle other shader types as well.  They are optional.
      auto& vs = module_for_type[kShaderTypeVertex];
      auto& fs = module_for_type[kShaderTypeFragment];
      if (!vs) {
        return Result(
            "Dawn::CreatePipeline: no vertex shader provided for graphics "
            "pipeline");
      }
      if (!fs) {
        return Result(
            "Dawn::CreatePipeline: no fragment shader provided for graphics "
            "pipeline");
      }

      pipeline_map_[pipeline].render_pipeline.reset(
          new RenderPipelineInfo(pipeline, vs, fs));
      Result result = AttachBuffersAndTextures(
          pipeline_map_[pipeline].render_pipeline.get());
      if (!result.IsSuccess())
        return result;

      break;
    }
  }

  return {};
}

Result EngineDawn::DoClearColor(const ClearColorCommand* command) {
  RenderPipelineInfo* render_pipeline = GetRenderPipeline(command);
  if (!render_pipeline)
    return Result("ClearColor invoked on invalid or missing render pipeline");

  render_pipeline->clear_color_value = ::dawn::Color{
      command->GetR(), command->GetG(), command->GetB(), command->GetA()};

  return {};
}

Result EngineDawn::DoClearStencil(const ClearStencilCommand* command) {
  RenderPipelineInfo* render_pipeline = GetRenderPipeline(command);
  if (!render_pipeline)
    return Result("ClearStencil invoked on invalid or missing render pipeline");

  render_pipeline->clear_stencil_value = command->GetValue();
  return {};
}

Result EngineDawn::DoClearDepth(const ClearDepthCommand* command) {
  RenderPipelineInfo* render_pipeline = GetRenderPipeline(command);
  if (!render_pipeline)
    return Result("ClearDepth invoked on invalid or missing render pipeline");

  render_pipeline->clear_depth_value = command->GetValue();
  return {};
}

Result EngineDawn::DoClear(const ClearCommand* command) {
  RenderPipelineInfo* render_pipeline = GetRenderPipeline(command);
  if (!render_pipeline)
    return Result("Clear invoked on invalid or missing render pipeline");
  // Record a render pass in a command on the command buffer.
  //
  // First describe the color attachments, and how they are initialized
  // via the load op. The load op is "clear" to the clear colour.
  ::dawn::RenderPassColorAttachmentDescriptor color_attachment =
      ::dawn::RenderPassColorAttachmentDescriptor();
  color_attachment.attachment = texture_view_;
  color_attachment.resolveTarget = nullptr;
  color_attachment.clearColor = render_pipeline->clear_color_value;
  color_attachment.loadOp = ::dawn::LoadOp::Clear;
  color_attachment.storeOp = ::dawn::StoreOp::Store;
  ::dawn::RenderPassColorAttachmentDescriptor* color_attachment_descriptor[] = {
      &color_attachment};

  // Then describe the depthStencil attachment, and how it is initialized
  // via the load ops. Both load op are "clear" to the clear values.
  ::dawn::RenderPassDepthStencilAttachmentDescriptor depth_stencil_attachment =
      ::dawn::RenderPassDepthStencilAttachmentDescriptor();
  ::dawn::RenderPassDepthStencilAttachmentDescriptor* depth_stencil_descriptor =
      nullptr;
  if (render_pipeline->depth_stencil_texture) {
    depth_stencil_attachment.attachment =
        render_pipeline->depth_stencil_texture.CreateDefaultView();
    depth_stencil_attachment.clearDepth = render_pipeline->clear_depth_value;
    depth_stencil_attachment.clearStencil =
        render_pipeline->clear_stencil_value;
    depth_stencil_attachment.depthLoadOp = ::dawn::LoadOp::Clear;
    depth_stencil_attachment.depthStoreOp = ::dawn::StoreOp::Store;
    depth_stencil_attachment.stencilLoadOp = ::dawn::LoadOp::Clear;
    depth_stencil_attachment.stencilStoreOp = ::dawn::StoreOp::Store;
    depth_stencil_descriptor = &depth_stencil_attachment;
  }

  // Attach the depth/stencil and colour attachments to the render pass.
  ::dawn::RenderPassDescriptor rpd;
  rpd.colorAttachmentCount = 1;
  rpd.colorAttachments = color_attachment_descriptor;
  rpd.depthStencilAttachment = depth_stencil_descriptor;

  // Record the render pass as a command.
  auto encoder = device_->CreateCommandEncoder();
  ::dawn::RenderPassEncoder pass = encoder.BeginRenderPass(&rpd);
  pass.EndPass();
  // Finish recording the command buffer.  It only has one command.
  auto command_buffer = encoder.Finish();
  // Submit the command.
  auto queue = device_->CreateQueue();
  queue.Submit(1, &command_buffer);
  // Copy result back
  MapResult map = MapTextureToHostBuffer(*render_pipeline, *device_);

  return map.result;
}

// Creates a Dawn render pipeline descriptor for the given pipeline on the given
// device. When |ignore_vertex_and_Index_buffers| is true, ignores the vertex
// and index buffers attached to |render_pipeline| and instead configures the
// resulting descriptor to have a single vertex buffer with an attribute format
// of Float4 and input stride of 4*sizeof(float)
Result DawnPipelineHelper::CreateRenderPipelineDescriptor(
    const RenderPipelineInfo& render_pipeline,
    const ::dawn::Device& device,
    const bool ignore_vertex_and_Index_buffers) {
  Result result;

  auto* amber_format =
      render_pipeline.pipeline->GetColorAttachments()[0].buffer->GetFormat();
  if (!amber_format)
    return Result("Color attachment 0 has no format!");
  ::dawn::TextureFormat fb_format{};
  result = GetDawnTextureFormat(*amber_format, &fb_format);
  if (!result.IsSuccess())
    return result;

  ::dawn::TextureFormat depth_stencil_format{};
  auto* depthBuffer = render_pipeline.pipeline->GetDepthBuffer().buffer;
  if (depthBuffer) {
    auto* amber_depth_stencil_format = depthBuffer->GetFormat();
    if (!amber_depth_stencil_format)
      return Result("The depth/stencil attachment has no format!");
    result = GetDawnTextureFormat(*amber_depth_stencil_format,
                                  &depth_stencil_format);
    if (!result.IsSuccess())
      return result;
  } else {
    depth_stencil_format = ::dawn::TextureFormat::D32FloatS8Uint;
  }

  renderPipelineDescriptor.layout =
      MakeBasicPipelineLayout(device, render_pipeline.bind_group_layouts);

  renderPipelineDescriptor.primitiveTopology =
      ::dawn::PrimitiveTopology::TriangleList;
  renderPipelineDescriptor.sampleCount = 1;

  // Lookup shaders' entrypoints
  for (const auto& shader_info : render_pipeline.pipeline->GetShaders()) {
    if (shader_info.GetShaderType() == kShaderTypeVertex) {
      vertexEntryPoint = shader_info.GetEntryPoint();
    } else if (shader_info.GetShaderType() == kShaderTypeFragment) {
      fragmentEntryPoint = shader_info.GetEntryPoint();
    } else {
      return Result(
          "CreateRenderPipelineDescriptor: An unknown shader is attached to "
          "the render pipeline");
    }
  }
  // Fill the default values for vertexInput.
  // assuming #inputs = #attributes
  int num_inputs = 0;
  for (uint32_t i = 0; i < kMaxVertexInputs; ++i) {
    if (ignore_vertex_and_Index_buffers) {
      if (i == 0) {
        vertexInput.inputSlot = 0;
        vertexInput.stride = 4 * sizeof(float);
        vertexInput.stepMode = ::dawn::InputStepMode::Vertex;
        num_inputs = 1;
      } else {
        vertexInput.inputSlot = 0;
        vertexInput.stride = 0;
        vertexInput.stepMode = ::dawn::InputStepMode::Vertex;
      }
    } else {
      if (i < render_pipeline.pipeline->GetVertexBuffers().size()) {
        vertexInput.inputSlot = i;
        vertexInput.stride = render_pipeline.pipeline->GetVertexBuffers()[i]
                                 .buffer->GetTexelStride();
        vertexInput.stepMode = ::dawn::InputStepMode::Vertex;
        num_inputs = render_pipeline.pipeline->GetVertexBuffers().size();
      } else {
        vertexInput.inputSlot = 0;
        vertexInput.stride = 0;
        vertexInput.stepMode = ::dawn::InputStepMode::Vertex;
      }
    }
    tempInputs[i] = vertexInput;
  }
  tempInputState.numInputs = num_inputs;
  tempInputState.inputs = tempInputs.data();
  if (render_pipeline.pipeline->GetIndexBuffer()) {
    auto* amber_index_format =
        render_pipeline.pipeline->GetIndexBuffer()->GetFormat();
    GetDawnIndexFormat(*amber_index_format, &tempInputState.indexFormat);
    if (!result.IsSuccess())
      return result;
  } else {
    tempInputState.indexFormat = ::dawn::IndexFormat::Uint32;
  }
  // Fill the default values for vertexAttribute.
  vertexAttribute.offset = 0;
  for (uint32_t i = 0; i < kMaxVertexAttributes; ++i) {
    if (ignore_vertex_and_Index_buffers) {
      if (i == 0) {
        vertexAttribute.shaderLocation = 0;
        vertexAttribute.inputSlot = 0;
        vertexAttribute.format = ::dawn::VertexFormat::Float4;
      } else {
        vertexAttribute.shaderLocation = 0;
        vertexAttribute.inputSlot = 0;
        vertexAttribute.format = ::dawn::VertexFormat::Float;
      }
    } else {
      if (i < render_pipeline.pipeline->GetVertexBuffers().size()) {
        vertexAttribute.shaderLocation = i;
        vertexAttribute.inputSlot = i;
        auto* amber_vertex_format =
            render_pipeline.pipeline->GetVertexBuffers()[i].buffer->GetFormat();
        result =
            GetDawnVertexFormat(*amber_vertex_format, &vertexAttribute.format);
        if (!result.IsSuccess())
          return result;
      } else {
        vertexAttribute.shaderLocation = 0;
        vertexAttribute.inputSlot = 0;
        vertexAttribute.format = ::dawn::VertexFormat::Float;
      }
    }
    tempAttributes[i] = vertexAttribute;
  }
  tempInputState.numAttributes = num_inputs;
  tempInputState.attributes = tempAttributes.data();
  // Set input state descriptors
  renderPipelineDescriptor.inputState = &tempInputState;
  // Set defaults for the vertex stage descriptor.
  vertexStage.module = render_pipeline.vertex_shader;
  vertexStage.entryPoint = vertexEntryPoint.c_str();
  renderPipelineDescriptor.vertexStage = &vertexStage;

  // Set defaults for the fragment stage descriptor.
  fragmentStage.module = render_pipeline.fragment_shader;
  fragmentStage.entryPoint = fragmentEntryPoint.c_str();
  renderPipelineDescriptor.fragmentStage = std::move(&fragmentStage);

  // Set defaults for the color state descriptors.
  renderPipelineDescriptor.colorStateCount = 1;
  blend.operation = ::dawn::BlendOperation::Add;
  blend.srcFactor = ::dawn::BlendFactor::One;
  blend.dstFactor = ::dawn::BlendFactor::Zero;
  colorStateDescriptor.format = fb_format;
  colorStateDescriptor.alphaBlend = blend;
  colorStateDescriptor.colorBlend = blend;
  colorStateDescriptor.colorWriteMask = ::dawn::ColorWriteMask::All;
  for (uint32_t i = 0; i < kMaxColorAttachments; ++i) {
    colorStatesDescriptor[i] = colorStateDescriptor;
    colorStates[i] = &colorStatesDescriptor[i];
  }
  colorStates[0]->format = fb_format;
  renderPipelineDescriptor.colorStates = &colorStates[0];

  // Set defaults for the depth stencil state descriptors.
  stencilFace.compare = ::dawn::CompareFunction::Always;
  stencilFace.failOp = ::dawn::StencilOperation::Keep;
  stencilFace.depthFailOp = ::dawn::StencilOperation::Keep;
  stencilFace.passOp = ::dawn::StencilOperation::Keep;
  depthStencilState.format = fb_format;
  depthStencilState.depthWriteEnabled = false;
  depthStencilState.depthCompare = ::dawn::CompareFunction::Always;
  depthStencilState.stencilBack = stencilFace;
  depthStencilState.stencilFront = stencilFace;
  depthStencilState.stencilReadMask = 0xff;
  depthStencilState.stencilWriteMask = 0xff;
  depthStencilState.format = depth_stencil_format;
  renderPipelineDescriptor.depthStencilState = &depthStencilState;

  return {};
}

Result DawnPipelineHelper::CreateRenderPassDescriptor(
    const RenderPipelineInfo& render_pipeline,
    const ::dawn::Device& device,
    const ::dawn::TextureView texture_view) {
  std::initializer_list<::dawn::TextureView> colorAttachmentInfo = {
      texture_view};

  for (uint32_t i = 0; i < kMaxColorAttachments; ++i) {
    colorAttachmentsInfo[i].loadOp = ::dawn::LoadOp::Load;
    colorAttachmentsInfo[i].storeOp = ::dawn::StoreOp::Store;
    colorAttachmentsInfo[i].clearColor = render_pipeline.clear_color_value;
    colorAttachmentsInfoPtr[i] = nullptr;
  }

  depthStencilAttachmentInfo.clearDepth = render_pipeline.clear_depth_value;
  depthStencilAttachmentInfo.clearStencil = render_pipeline.clear_stencil_value;
  depthStencilAttachmentInfo.depthLoadOp = ::dawn::LoadOp::Clear;
  depthStencilAttachmentInfo.depthStoreOp = ::dawn::StoreOp::Store;
  depthStencilAttachmentInfo.stencilLoadOp = ::dawn::LoadOp::Clear;
  depthStencilAttachmentInfo.stencilStoreOp = ::dawn::StoreOp::Store;

  renderPassDescriptor.colorAttachmentCount =
      static_cast<uint32_t>(colorAttachmentInfo.size());
  uint32_t colorAttachmentIndex = 0;
  for (const ::dawn::TextureView& colorAttachment : colorAttachmentInfo) {
    if (colorAttachment.Get() != nullptr) {
      colorAttachmentsInfo[colorAttachmentIndex].attachment = colorAttachment;
      colorAttachmentsInfoPtr[colorAttachmentIndex] =
          &colorAttachmentsInfo[colorAttachmentIndex];
    }
    ++colorAttachmentIndex;
  }
  renderPassDescriptor.colorAttachments = colorAttachmentsInfoPtr;

  ::dawn::TextureFormat depth_stencil_format{};
  auto* depthBuffer = render_pipeline.pipeline->GetDepthBuffer().buffer;
  if (depthBuffer) {
    auto* amber_depth_stencil_format = depthBuffer->GetFormat();
    if (!amber_depth_stencil_format)
      return Result("The depth/stencil attachment has no format!");
    Result result = GetDawnTextureFormat(*amber_depth_stencil_format,
                                         &depth_stencil_format);
    if (!result.IsSuccess())
      return result;
  } else {
    depth_stencil_format = ::dawn::TextureFormat::D32FloatS8Uint;
  }

  ::dawn::TextureView depthStencilView = CreateDefaultDepthStencilView(
      device, render_pipeline, depth_stencil_format);
  if (depthStencilView.Get() != nullptr) {
    depthStencilAttachmentInfo.attachment = depthStencilView;
    renderPassDescriptor.depthStencilAttachment = &depthStencilAttachmentInfo;
  } else {
    renderPassDescriptor.depthStencilAttachment = nullptr;
  }

  return {};
}

Result EngineDawn::DoDrawRect(const DrawRectCommand* command) {
  RenderPipelineInfo* render_pipeline = GetRenderPipeline(command);
  if (!render_pipeline)
    return Result("DrawRect invoked on invalid or missing render pipeline");
  if (render_pipeline->vertex_buffers.size() > 1)
    return Result(
        "DrawRect invoked on a render pipeline with more than one "
        "VERTEX_DATA attached");

  float x = command->GetX();
  float y = command->GetY();
  float rectangleWidth = command->GetWidth();
  float rectangleHeight = command->GetHeight();

  const uint32_t frameWidth = render_pipeline->pipeline->GetFramebufferWidth();
  const uint32_t frameHeight =
      render_pipeline->pipeline->GetFramebufferHeight();

  if (command->IsOrtho()) {
    x = ((x / frameWidth) * 2.0f) - 1.0f;
    y = ((y / frameHeight) * 2.0f) - 1.0f;
    rectangleWidth = (rectangleWidth / frameWidth) * 2.0f;
    rectangleHeight = (rectangleHeight / frameHeight) * 2.0f;
  }

  static const uint32_t indexData[3 * 2] = {
      0, 1, 2, 0, 2, 3,
  };
  auto index_buffer = CreateBufferFromData(
      *device_, indexData, sizeof(indexData), ::dawn::BufferUsageBit::Index);

  const float vertexData[4 * 4] = {
      // Bottom left
      x,
      y + rectangleHeight,
      0.0f,
      1.0f,
      // Top left
      x,
      y,
      0.0f,
      1.0f,
      // Top right
      x + rectangleWidth,
      y,
      0.0f,
      1.0f,
      // Bottom right
      x + rectangleWidth,
      y + rectangleHeight,
      0.0f,
      1.0f,
  };

  auto vertex_buffer = CreateBufferFromData(
      *device_, vertexData, sizeof(vertexData), ::dawn::BufferUsageBit::Vertex);

  DawnPipelineHelper helper;
  helper.CreateRenderPipelineDescriptor(*render_pipeline, *device_, true);
  helper.CreateRenderPassDescriptor(*render_pipeline, *device_, texture_view_);
  ::dawn::RenderPipelineDescriptor* renderPipelineDescriptor =
      &helper.renderPipelineDescriptor;
  ::dawn::RenderPassDescriptor* renderPassDescriptor =
      &helper.renderPassDescriptor;

  const ::dawn::RenderPipeline pipeline =
      device_->CreateRenderPipeline(renderPipelineDescriptor);
  static const uint64_t vertexBufferOffsets[1] = {0};
  ::dawn::CommandEncoder encoder = device_->CreateCommandEncoder();
  ::dawn::RenderPassEncoder pass =
      encoder.BeginRenderPass(renderPassDescriptor);
  pass.SetPipeline(pipeline);
  for (uint32_t i = 0; i < render_pipeline->bind_groups.size(); i++) {
    if (render_pipeline->bind_groups[i]) {
      pass.SetBindGroup(i, render_pipeline->bind_groups[i], 0, nullptr);
    }
  }
  pass.SetVertexBuffers(0, 1, &vertex_buffer, vertexBufferOffsets);
  pass.SetIndexBuffer(index_buffer, 0);
  pass.DrawIndexed(6, 1, 0, 0, 0);
  pass.EndPass();

  ::dawn::CommandBuffer commands = encoder.Finish();
  ::dawn::Queue queue = device_->CreateQueue();
  queue.Submit(1, &commands);

  MapResult map = MapTextureToHostBuffer(*render_pipeline, *device_);

  return map.result;
}

Result EngineDawn::DoDrawArrays(const DrawArraysCommand* command) {
  Result result;

  RenderPipelineInfo* render_pipeline = GetRenderPipeline(command);
  if (!render_pipeline)
    return Result("DrawArrays invoked on invalid or missing render pipeline");

  if (command->IsIndexed()) {
    if (!render_pipeline->index_buffer)
      return Result("DrawArrays: Draw indexed is used without given indices");
  } else {
    std::vector<uint32_t> indexData;
    for (uint32_t i = 0;
         i < command->GetFirstVertexIndex() + command->GetVertexCount(); i++) {
      indexData.emplace_back(i);
    }
    render_pipeline->index_buffer = CreateBufferFromData(
        *device_, indexData.data(), indexData.size() * sizeof(uint32_t),
        ::dawn::BufferUsageBit::Index);
  }

  uint32_t instance_count = command->GetInstanceCount();
  if (instance_count == 0 && command->GetVertexCount() != 0)
    instance_count = 1;

  DawnPipelineHelper helper;
  result =
      helper.CreateRenderPipelineDescriptor(*render_pipeline, *device_, false);
  if (!result.IsSuccess())
    return result;
  result = helper.CreateRenderPassDescriptor(*render_pipeline, *device_,
                                             texture_view_);
  if (!result.IsSuccess())
    return result;

  ::dawn::RenderPipelineDescriptor* renderPipelineDescriptor =
      &helper.renderPipelineDescriptor;
  ::dawn::RenderPassDescriptor* renderPassDescriptor =
      &helper.renderPassDescriptor;

  result = GetDawnTopology(command->GetTopology(),
                           &renderPipelineDescriptor->primitiveTopology);
  if (!result.IsSuccess())
    return result;

  static const uint64_t vertexBufferOffsets[1] = {0};
  const ::dawn::RenderPipeline pipeline =
      device_->CreateRenderPipeline(renderPipelineDescriptor);
  ::dawn::CommandEncoder encoder = device_->CreateCommandEncoder();
  ::dawn::RenderPassEncoder pass =
      encoder.BeginRenderPass(renderPassDescriptor);
  pass.SetPipeline(pipeline);
  for (uint32_t i = 0; i < render_pipeline->bind_groups.size(); i++) {
    if (render_pipeline->bind_groups[i]) {
      pass.SetBindGroup(i, render_pipeline->bind_groups[i], 0, nullptr);
    }
  }
  // TODO(sarahM0): figure out what are startSlot, count and offsets
  for (uint32_t i = 0; i < render_pipeline->vertex_buffers.size(); i++) {
    pass.SetVertexBuffers(i,                                   /* startSlot */
                          1,                                   /* count */
                          &render_pipeline->vertex_buffers[i], /* buffer */
                          vertexBufferOffsets);                /* offsets */
  }
  // TODO(sarahM0): figure out what this offset means
  pass.SetIndexBuffer(render_pipeline->index_buffer, /* buffer */
                      0);                            /*offset*/
  pass.DrawIndexed(command->GetVertexCount(),        /* indexCount */
                   instance_count,                   /* instanceCount */
                   command->GetFirstVertexIndex(),   /* firstIndex */
                   0,                                /* baseVertex */
                   0 /* firstInstance */);

  pass.EndPass();
  ::dawn::CommandBuffer commands = encoder.Finish();
  ::dawn::Queue queue = device_->CreateQueue();
  queue.Submit(1, &commands);

  MapResult map = MapTextureToHostBuffer(*render_pipeline, *device_);

  return map.result;
}  // namespace dawn

Result EngineDawn::DoCompute(const ComputeCommand*) {
  return Result("Dawn:DoCompute not implemented");
}

Result EngineDawn::DoEntryPoint(const EntryPointCommand*) {
  return Result("Dawn:DoEntryPoint not implemented");
}

Result EngineDawn::DoPatchParameterVertices(
    const PatchParameterVerticesCommand*) {
  return Result("Dawn:DoPatch not implemented");
}

Result EngineDawn::DoBuffer(const BufferCommand* command) {
  Result result;

  // TODO(SarahM0): Make this work for compute pipeline
  RenderPipelineInfo* render_pipeline = GetRenderPipeline(command);
  if (!render_pipeline)
    return Result("DoBuffer: invoked on invalid or missing render pipeline");
  if (!command->IsSSBO() && !command->IsUniform())
    return Result("DoBuffer: only supports SSBO and uniform buffer type");

  if (render_pipeline->buffer_map.find(
          {command->GetDescriptorSet(), command->GetBinding()}) !=
      render_pipeline->buffer_map.end()) {
    auto dawn_buffer_index =
        render_pipeline
            ->buffer_map[{command->GetDescriptorSet(), command->GetBinding()}];
    ::dawn::Buffer& dawn_buffer = render_pipeline->buffers[dawn_buffer_index];

    Buffer* amber_buffer = command->GetBuffer();
    if (amber_buffer) {
      amber_buffer->SetDataWithOffset(command->GetValues(),
                                      command->GetOffset());

      dawn_buffer.SetSubData(0, amber_buffer->GetSizeInBytes(),
                             amber_buffer->ValuePtr()->data());
    }
  }
  return {};
}

Result EngineDawn::AttachBuffersAndTextures(
    RenderPipelineInfo* render_pipeline) {
  Result result;

  // TODO(sarahM0): rewrite this for more than one color attachment.
  const uint32_t width = render_pipeline->pipeline->GetFramebufferWidth();
  const uint32_t height = render_pipeline->pipeline->GetFramebufferHeight();
  const auto pixelSize = render_pipeline->pipeline->GetColorAttachments()[0]
                             .buffer->GetTexelStride();
  const auto dawn_row_pitch = Align(width * pixelSize, kMinimumImageRowPitch);
  const auto size = height * dawn_row_pitch;

  auto* amber_format =
      render_pipeline->pipeline->GetColorAttachments()[0].buffer->GetFormat();
  if (!amber_format)
    return Result(
        "AttachBuffersAndTextures: Color attachment 0 has no format!");
  ::dawn::TextureFormat fb_format{};
  result = GetDawnTextureFormat(*amber_format, &fb_format);
  if (!result.IsSuccess())
    return result;

  // First make the Dawn color attachment textures that the render pipeline
  // will write into.
  if (!fb_texture_) {
    result = MakeTexture(*device_, fb_format, width, height, &fb_texture_);
    if (!result.IsSuccess())
      return result;
    render_pipeline->fb_texture = fb_texture_;
    texture_view_ = render_pipeline->fb_texture.CreateDefaultView();
  } else {
    render_pipeline->fb_texture = fb_texture_;
  }

  // Now create the Dawn buffer to hold the framebuffer contents, but on the
  // host side.  This has to match dimensions of the framebuffer, but also
  // be linearly addressible by the CPU.
  if (!fb_buffer_) {
    result = MakeFramebufferBuffer(*device_, &fb_buffer_, size);
    if (!result.IsSuccess())
      return result;
    render_pipeline->fb_buffer = fb_buffer_;
  } else {
    render_pipeline->fb_buffer = fb_buffer_;
  }

  // Attach depth-stencil texture
  auto* depthBuffer = render_pipeline->pipeline->GetDepthBuffer().buffer;
  if (depthBuffer) {
    if (!depth_stencil_texture_) {
      auto* amber_depth_stencil_format = depthBuffer->GetFormat();
      if (!amber_depth_stencil_format)
        return Result(
            "AttachBuffersAndTextures: The depth/stencil attachment has no "
            "format!");
      ::dawn::TextureFormat depth_stencil_format{};
      result = GetDawnTextureFormat(*amber_depth_stencil_format,
                                    &depth_stencil_format);
      if (!result.IsSuccess())
        return result;

      result = MakeTexture(*device_, depth_stencil_format, width, height,
                           &depth_stencil_texture_);
      if (!result.IsSuccess())
        return result;
      render_pipeline->depth_stencil_texture = depth_stencil_texture_;
    } else {
      render_pipeline->depth_stencil_texture = depth_stencil_texture_;
    }
  }

  // Attach index buffer
  if (render_pipeline->pipeline->GetIndexBuffer()) {
    render_pipeline->index_buffer = CreateBufferFromData(
        *device_,
        render_pipeline->pipeline->GetIndexBuffer()->ValuePtr()->data(),
        render_pipeline->pipeline->GetIndexBuffer()->GetSizeInBytes(),
        ::dawn::BufferUsageBit::Index);
  }

  // Attach vertex buffers
  for (auto& vertex_info : render_pipeline->pipeline->GetVertexBuffers()) {
    render_pipeline->vertex_buffers.emplace_back(CreateBufferFromData(
        *device_, vertex_info.buffer->ValuePtr()->data(),
        vertex_info.buffer->GetSizeInBytes(), ::dawn::BufferUsageBit::Vertex));
  }

  // Do not attach pushConstants
  if (render_pipeline->pipeline->GetPushConstantBuffer().buffer != nullptr) {
    return Result(
        "AttachBuffersAndTextures: Dawn does not support push constants!");
  }

  ::dawn::ShaderStageBit kAllStages =
      ::dawn::ShaderStageBit::Vertex | ::dawn::ShaderStageBit::Fragment;
  std::vector<std::vector<BindingInitializationHelper>> bindingInitalizerHelper(
      kMaxDawnBindGroup);
  std::vector<std::vector<::dawn::BindGroupLayoutBinding>> layouts_info(
      kMaxDawnBindGroup);
  uint32_t max_descriptor_set = 0;

  // Attach storage/uniform buffers
  for (const auto& buf_info : render_pipeline->pipeline->GetBuffers()) {
    ::dawn::BufferUsageBit bufferUsage;
    ::dawn::BindingType bindingType;
    switch (buf_info.buffer->GetBufferType()) {
      case BufferType::kStorage: {
        bufferUsage = ::dawn::BufferUsageBit::Storage;
        bindingType = ::dawn::BindingType::StorageBuffer;
        break;
      }
      case BufferType::kUniform: {
        bufferUsage = ::dawn::BufferUsageBit::Uniform;
        bindingType = ::dawn::BindingType::UniformBuffer;
        break;
      }
      default: {
        return Result("AttachBuffersAndTextures: unknown buffer type: " +
                      std::to_string(static_cast<uint32_t>(
                          buf_info.buffer->GetBufferType())));
        break;
      }
    }

    if (buf_info.descriptor_set > kMaxDawnBindGroup - 1) {
      return Result(
          "AttachBuffersAndTextures: Dawn has maximum of 4 bindGroups "
          "(descriptor sets)");
    }

    render_pipeline->buffers.emplace_back(
        CreateBufferFromData(*device_, buf_info.buffer->ValuePtr()->data(),
                             buf_info.buffer->GetSizeInBytes(),
                             bufferUsage | ::dawn::BufferUsageBit::TransferSrc |
                                 ::dawn::BufferUsageBit::TransferDst));

    render_pipeline->buffer_map[{buf_info.descriptor_set, buf_info.binding}] =
        render_pipeline->buffers.size() - 1;

    render_pipeline->used_descriptor_set.insert(buf_info.descriptor_set);
    max_descriptor_set = std::max(max_descriptor_set, buf_info.descriptor_set);

    ::dawn::BindGroupLayoutBinding layout_info;
    layout_info.binding = buf_info.binding;
    layout_info.visibility = kAllStages;
    layout_info.type = bindingType;
    layouts_info[buf_info.descriptor_set].push_back(layout_info);

    BindingInitializationHelper tempBinding = BindingInitializationHelper(
        buf_info.binding, render_pipeline->buffers.back(), 0,
        buf_info.buffer->GetSizeInBytes());
    bindingInitalizerHelper[buf_info.descriptor_set].push_back(tempBinding);
  }

  // TODO(sarahM0): fix issue: Add support for doBuffer with sparse descriptor
  // sets #573
  if (render_pipeline->used_descriptor_set.size() != 0 &&
      render_pipeline->used_descriptor_set.size() != max_descriptor_set + 1) {
    return Result(
        "AttachBuffersAndTextures: Sparse descriptor_set is not supported");
  }

  for (uint32_t i = 0; i < kMaxDawnBindGroup; i++) {
    if (layouts_info[i].size() > 0 && bindingInitalizerHelper[i].size() > 0) {
      ::dawn::BindGroupLayout bindGroupLayout =
          MakeBindGroupLayout(*device_, layouts_info[i]);
      render_pipeline->bind_group_layouts.push_back(bindGroupLayout);

      ::dawn::BindGroup bindGroup =
          MakeBindGroup(*device_, render_pipeline->bind_group_layouts[i],
                        bindingInitalizerHelper[i]);
      render_pipeline->bind_groups.push_back(bindGroup);
    }
  }

  return {};
}

}  // namespace dawn
}  // namespace amber