Blender V5.3
mtl_batch.mm
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2022-2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
10
11#include "BLI_assert.hh"
12#include "BLI_span.hh"
13
14#include "BKE_global.hh"
15
16#include "GPU_batch.hh"
17#include "GPU_common.hh"
18#include "gpu_shader_private.hh"
20
21#include "mtl_batch.hh"
22#include "mtl_context.hh"
23#include "mtl_debug.hh"
24#include "mtl_index_buffer.hh"
25#include "mtl_shader.hh"
26#include "mtl_storage_buffer.hh"
27#include "mtl_vertex_buffer.hh"
28
29#include <string>
30
31namespace blender::gpu {
32
33static CLG_LogRef LOG = {"gpu.metal"};
34
35/* -------------------------------------------------------------------- */
38void MTLBatch::draw(int v_first, int v_count, int i_first, int i_count)
39{
40 this->draw_advanced(v_first, v_count, i_first, i_count);
41}
42
43void MTLBatch::draw_indirect(StorageBuf *indirect_buf, intptr_t offset)
44{
45 this->draw_advanced_indirect(indirect_buf, offset);
46}
47
48void MTLBatch::MTLVertexDescriptorCache::vertex_descriptor_cache_init(MTLContext *ctx)
49{
50 BLI_assert(ctx != nullptr);
51 this->vertex_descriptor_cache_clear();
52 cache_context_ = ctx;
53}
54
55void MTLBatch::MTLVertexDescriptorCache::vertex_descriptor_cache_clear()
56{
57 cache_life_index_++;
58 cache_context_ = nullptr;
59}
60
61void MTLBatch::MTLVertexDescriptorCache::vertex_descriptor_cache_ensure()
62{
63 if (this->cache_context_ != nullptr) {
64
65 /* Invalidate vertex descriptor bindings cache if batch has changed. */
66 if (batch_->flag & GPU_BATCH_DIRTY) {
67 batch_->flag &= ~GPU_BATCH_DIRTY;
68 this->vertex_descriptor_cache_clear();
69 }
70 }
71
72 /* Initialize cache if not ready. */
73 if (cache_context_ == nullptr) {
74 this->vertex_descriptor_cache_init(MTLContext::get());
75 }
76}
77
78MTLBatch::VertexDescriptorShaderInterfacePair *MTLBatch::MTLVertexDescriptorCache::find(
79 const ShaderInterface *interface)
80{
81 this->vertex_descriptor_cache_ensure();
82 for (int i = 0; i < GPU_VAO_STATIC_LEN; ++i) {
83 if (cache_[i].interface == interface && cache_[i].cache_life_index == cache_life_index_) {
84 return &cache_[i];
85 }
86 }
87 return nullptr;
88}
89
90bool MTLBatch::MTLVertexDescriptorCache::insert(
91 MTLBatch::VertexDescriptorShaderInterfacePair &data)
92{
93 vertex_descriptor_cache_ensure();
94 for (int i = 0; i < GPU_VAO_STATIC_LEN; ++i) {
95 if (cache_[i].interface == nullptr || cache_[i].cache_life_index != cache_life_index_) {
96 cache_[i] = data;
97 cache_[i].cache_life_index = cache_life_index_;
98 return true;
99 }
100 }
101 return false;
102}
103
104/* Return index inside the vertex descriptor. */
105VertBufBinding MTLBatch::prepare_vertex_binding(MTLVertBuf *verts,
106 MTLRenderPipelineStateDescriptor &desc,
107 const MTLShaderInterface &interface,
108 uint16_t &attr_mask,
109 uint32_t &buffer_mask)
110{
111
112 const GPUVertFormat *format = &verts->format;
113 /* Per-vertex stride of current vertex buffer. */
114 int buffer_stride = format->stride;
115 /* Buffer binding index of the vertex buffer once added to the buffer layout descriptor. */
116 VertBufBinding binding{-1, -1};
117 int attribute_offset = 0;
118
119 /* Iterate over VertBuf vertex format and find attributes matching those in the active
120 * shader's interface. */
121 for (uint32_t a_idx = 0; a_idx < format->attr_len; a_idx++) {
122 const GPUVertAttr *a = &format->attrs[a_idx];
123
124 if (format->deinterleaved) {
125 attribute_offset += ((a_idx == 0) ? 0 : format->attrs[a_idx - 1].type.size()) *
126 verts->vertex_len;
127 buffer_stride = a->type.size();
128 }
129 else {
130 attribute_offset = a->offset;
131 }
132
133 /* Find attribute with the matching name. Attributes may have multiple compatible
134 * name aliases. */
135 for (uint32_t n_idx = 0; n_idx < a->name_len; n_idx++) {
136 const char *name = GPU_vertformat_attr_name_get(format, a, n_idx);
137 const ShaderInput *input = interface.attr_get(name);
138
139 if (input == nullptr || input->location == -1) {
140 continue;
141 }
142
143 /* Check if attribute is already present in the given slot. */
144 if ((~attr_mask) & (1 << input->location)) {
146 " -- [Batch] Skipping attribute with input location %d (As one is already bound)",
147 input->location);
148 continue;
149 }
150
151 /* Update attribute used-slot mask. */
152 attr_mask &= ~(1 << input->location);
153
154 /* Add buffer layout entry in descriptor if it has not yet been added
155 * for current vertex buffer. */
156 if (binding.desc_id == -1) {
157 if (buffer_mask == 0) {
158 MTL_LOG_DEBUG(" -- [Batch] Error: Not enough available slot to bind vertex buffer");
159 return binding;
160 }
161
162 binding.desc_id = desc.vertex_descriptor.num_vert_buffers++;
163 binding.slot_id = bitscan_forward_clear_uint(&buffer_mask);
164
165 auto &buffer_layout = desc.vertex_descriptor.buffer_layouts[binding.desc_id];
166 buffer_layout.step_function = MTLVertexStepFunctionPerVertex;
167 buffer_layout.step_rate = 1;
168 buffer_layout.stride = buffer_stride;
169 buffer_layout.buffer_slot = binding.slot_id;
170
171 MTL_LOG_DEBUG(" -- [Batch] Adding source vertex buffer (Index: %d, Stride: %d)",
172 binding.desc_id,
173 buffer_stride);
174 }
175 else {
176 /* Ensure stride is correct for de-interleaved attributes. */
177 desc.vertex_descriptor.buffer_layouts[binding.desc_id].stride = buffer_stride;
178 }
179
180 {
181 MTLVertexAttributeDescriptorPSO &pso_attr =
182 desc.vertex_descriptor.attributes[input->location];
183
184 pso_attr.format = gpu_vertex_format_to_metal(a->type.format);
185 pso_attr.offset = attribute_offset;
186 pso_attr.buffer_index = binding.slot_id;
187 pso_attr.format_conversion_mode = is_fetch_float(a->type.format) ?
190
191 desc.vertex_descriptor.max_attribute_value =
192 ((input->location) > desc.vertex_descriptor.max_attribute_value) ?
193 (input->location) :
194 desc.vertex_descriptor.max_attribute_value;
195 desc.vertex_descriptor.total_attributes++;
196
197 /* NOTE: We are setting max_attribute_value to be up to the maximum found index, because
198 * of this, it is possible that we may skip over certain attributes if they were not in
199 * the source GPUVertFormat. */
201 " -- Batch Attribute(%d): ORIG Vert format: %d, Vert "
202 "components: %d, Fetch Mode %d --> FINAL FORMAT: %d",
203 input->location,
204 (int)a->type.comp_type(),
205 (int)a->type.comp_len(),
206 (int)a->type.fetch_mode(),
207 (int)pso_attr.format);
208
210 " -- [Batch] matching vertex attribute '%s' (Attribute Index: %d, Buffer index: "
211 "%d, "
212 "offset: %d)",
213 name,
214 input->location,
215 binding.desc_id,
216 attribute_offset);
217 }
218 }
219 }
220 return binding;
221}
222
224{
225 /* Setup draw call and render pipeline state here. Called by every draw, but setup here so that
226 * MTLDrawList only needs to perform setup a single time. */
227 BLI_assert(this);
228
229 /* Fetch Metal device. */
231 if (!ctx) {
232 BLI_assert_msg(false, "No context available for rendering.");
233 return nil;
234 }
235
236 /* Fetch bound shader from context. */
237 active_shader_ = static_cast<MTLShader *>(ctx->shader);
238
239 if (active_shader_ == nullptr || !active_shader_->is_valid()) {
240 /* Skip drawing if there is no valid Metal shader.
241 * This will occur if the path through which the shader is prepared
242 * is invalid (e.g. Python without create-info), or, the source shader uses a geometry pass. */
243 BLI_assert_msg(false, "No valid Metal shader!");
244 return nil;
245 }
246
247 /* Prepare Vertex Descriptor and extract VertexBuffers to bind. */
248 MTLVertBuf *buffers[GPU_BATCH_VBO_MAX_LEN] = {nullptr};
249 int binding_slot[GPU_BATCH_VBO_MAX_LEN] = {0};
250 int num_buffers = 0;
251
252 /* Ensure Index Buffer is ready. */
253 MTLIndexBuf *mtl_elem = static_cast<MTLIndexBuf *>(this->elem);
254 if (mtl_elem != nullptr) {
255 mtl_elem->upload_data();
256 }
257
258 /* Populate vertex descriptor with attribute binding information.
259 * The vertex descriptor and buffer layout descriptors describe
260 * how vertex data from bound vertex buffers maps to the
261 * shader's input.
262 * A unique vertex descriptor will result in a new PipelineStateObject
263 * being generated for the currently bound shader. */
264 prepare_vertex_descriptor_and_bindings(
265 {buffers, GPU_BATCH_VBO_MAX_LEN}, {binding_slot, GPU_BATCH_VBO_MAX_LEN}, num_buffers);
266
267 /* Prepare Vertex Buffers - Run before RenderCommandEncoder in case BlitCommandEncoder buffer
268 * data operations are required. */
269 for (int i = 0; i < num_buffers; i++) {
270 buffers[i]->bind();
271 }
272
273 /* Ensure render pass is active and fetch active RenderCommandEncoder. */
275
276 /* Fetch RenderPassState to enable resource binding for active pass. */
278
279 /* Debug Check: Ensure Frame-buffer instance is not dirty. */
281
282 /* GPU debug markers. */
283 if (G.debug & G_DEBUG_GPU) {
285 [rec pushDebugGroup:[NSString stringWithFormat:@"Batch(Shader:%s)",
286 active_shader_->name_get().c_str()]];
287 }
288
289 /*** Bind Vertex Buffers and Index Buffers **/
290
291 /* Ensure Context Render Pipeline State is fully setup and ready to execute the draw.
292 * This should happen after all other final rendering setup is complete. */
293 MTLPrimitiveType mtl_prim_type = gpu_prim_type_to_metal(this->prim_type);
294 if (!ctx->ensure_render_pipeline_state(mtl_prim_type)) {
295 MTL_LOG_ERROR("Failed to prepare and apply render pipeline state.");
296 BLI_assert(false);
297 return nil;
298 }
299
300 /* Bind Vertex Buffers. */
301 for (int i = 0; i < num_buffers; i++) {
302 MTLVertBuf *buf_at_index = buffers[i];
303 /* Buffer handle. */
304 MTLVertBuf *mtlvbo = static_cast<MTLVertBuf *>(reinterpret_cast<VertBuf *>(buf_at_index));
305 mtlvbo->flag_used();
306
307 /* Fetch buffer from MTLVertexBuffer and bind. */
308 id<MTLBuffer> mtl_buffer = mtlvbo->get_metal_buffer();
309
310 BLI_assert(mtl_buffer != nil);
311 rps.bind_vertex_buffer(mtl_buffer, 0, binding_slot[i]);
312 }
313
314 /* Return Render Command Encoder used with setup. */
315 return rec;
316}
317
319{
320 /* Pop bind debug group. */
321 if (G.debug & G_DEBUG_GPU) {
322 [rec popDebugGroup];
323 }
324}
325
326void MTLBatch::prepare_vertex_descriptor_and_bindings(MutableSpan<MTLVertBuf *> buffers,
327 MutableSpan<int> buffer_slots,
328 int &num_buffers)
329{
330
331 /* Here we populate the MTLContext vertex descriptor and resolve which buffers need to be bound.
332 */
333 MTLStateManager *state_manager = static_cast<MTLStateManager *>(
336 const MTLShaderInterface &interface = active_shader_->get_interface();
337 uint16_t attr_mask = interface.enabled_attr_mask_;
338 uint32_t buffer_mask = interface.vertex_buffer_mask();
339
340 /* Reset vertex descriptor to default state. */
342
343 /* Fetch Vertex Buffers. */
344 Span<VertBuf *> mtl_verts(this->verts, GPU_BATCH_VBO_MAX_LEN);
345
346 /* Resolve Metal vertex buffer bindings. */
347 /* Vertex Descriptors
348 * ------------------
349 * Vertex Descriptors are required to generate a pipeline state, based on the current Batch's
350 * buffer bindings. These bindings are a unique matching, depending on what input attributes a
351 * batch has in its buffers, and those which are supported by the shader interface.
352 *
353 * We iterate through the buffers and resolve which attributes satisfy the requirements of the
354 * currently bound shader. We cache this data, for a given Batch<->ShaderInterface pairing in a
355 * VAO cache to avoid the need to recalculate this data. */
356
357 VertexDescriptorShaderInterfacePair *pair = this->vao_cache.find(&interface);
358 if (pair) {
359 desc.vertex_descriptor = pair->vertex_descriptor;
360 attr_mask = pair->attr_mask;
361 num_buffers = pair->num_buffers;
362
363 for (int bid = 0; bid < GPU_BATCH_VBO_MAX_LEN; ++bid) {
364 if (pair->bufferIds[bid].used) {
365 buffers[bid] = static_cast<MTLVertBuf *>(this->verts[pair->bufferIds[bid].id]);
366 buffer_slots[bid] = pair->bufferIds[bid].slot;
367 }
368 }
369 }
370 else {
371 VertexDescriptorShaderInterfacePair pair{};
372 pair.interface = &interface;
373
374 for (int i = 0; i < GPU_BATCH_VBO_MAX_LEN; ++i) {
375 pair.bufferIds[i].id = -1;
376 pair.bufferIds[i].used = 0;
377 }
378 /* NOTE: Attribute extraction order from buffer is the reverse of the OpenGL as we flag once an
379 * attribute is found, rather than pre-setting the mask. */
380
381 /* Extract Vertex attributes (First-bound vertex buffer takes priority). */
382 for (int v = 0; v < GPU_BATCH_VBO_MAX_LEN; v++) {
383 if (mtl_verts[v] != nullptr) {
384 MTL_LOG_DEBUG(" -- [Batch] Checking bindings for bound vertex buffer %p", mtl_verts[v]);
385 VertBufBinding bindings = this->prepare_vertex_binding(
386 static_cast<MTLVertBuf *>(this->verts[v]), desc, interface, attr_mask, buffer_mask);
387 if (bindings.desc_id >= 0) {
388 buffers[bindings.desc_id] = static_cast<MTLVertBuf *>(this->verts[v]);
389 buffer_slots[bindings.desc_id] = bindings.slot_id;
390 pair.bufferIds[bindings.desc_id].id = v;
391 pair.bufferIds[bindings.desc_id].used = 1;
392 pair.bufferIds[bindings.desc_id].slot = bindings.slot_id;
393 num_buffers = max_ii(bindings.desc_id + 1, num_buffers);
394 }
395 }
396 }
397
398 /* Add to VertexDescriptor cache */
399 pair.attr_mask = attr_mask;
400 pair.vertex_descriptor = desc.vertex_descriptor;
401 pair.num_buffers = num_buffers;
402 if (!this->vao_cache.insert(pair)) {
404 "Cache is full (Size: %d), vertex descriptor will not be cached",
406 }
407 }
408
409/* DEBUG: verify if our attribute bindings have been fully provided as expected. */
410#if MTL_DEBUG_SHADER_ATTRIBUTES == 1
411 if (attr_mask != 0) {
412 /* Attributes are not necessarily contiguous. */
413 for (int i = 0; i < active_shader_->get_interface()->get_total_attributes(); i++) {
414 const MTLShaderInputAttribute &attr = active_shader_->get_interface()->get_attribute(i);
415 if (attr_mask & (1 << attr.location)) {
417 "Warning: Missing expected attribute '%s' with location: %u in shader %s (attr "
418 "number: %u)",
419 active_shader_->get_interface()->name_at_offset(attr.name_offset),
420 attr.location,
421 active_shader_->name_get(),
422 i);
423
424 /* If an attribute is not included, then format in vertex descriptor should be invalid due
425 * to nil assignment. */
426 BLI_assert(desc.vertex_descriptor.attributes[attr.location].format ==
427 MTLVertexFormatInvalid);
428 }
429 }
430 }
431#endif
432}
433
434void MTLBatch::draw_advanced(int v_first, int v_count, int i_first, int i_count)
435{
436 BLI_assert(v_count > 0 && i_count > 0);
437
438 /* Setup RenderPipelineState for batch. */
439 MTLContext *ctx = MTLContext::get();
440 id<MTLRenderCommandEncoder> rec = this->bind();
441 if (rec == nil) {
442 /* End of draw. */
443 this->unbind(rec);
444 return;
445 }
446
447 /* Fetch IndexBuffer and resolve primitive type. */
448 MTLIndexBuf *mtl_elem = static_cast<MTLIndexBuf *>(reinterpret_cast<IndexBuf *>(this->elem));
449 MTLPrimitiveType mtl_prim_type = gpu_prim_type_to_metal(this->prim_type);
450
451 /* Perform regular draw. */
452 if (mtl_elem == nullptr) {
453 /* Primitive Type topology emulation. */
454 if (mtl_needs_topology_emulation(this->prim_type)) {
455 /* Generate index buffer for primitive types requiring emulation. */
456 GPUPrimType emulated_prim_type = this->prim_type;
457 uint32_t emulated_v_count = v_count;
458 id<MTLBuffer> generated_index_buffer = this->get_emulated_toplogy_buffer(emulated_prim_type,
459 emulated_v_count);
460 BLI_assert(generated_index_buffer != nil);
461
462 MTLPrimitiveType emulated_mtl_prim_type = gpu_prim_type_to_metal(emulated_prim_type);
463
464 /* Temp: Disable culling for emulated primitive types.
465 * TODO(Metal): Support face winding in topology buffer. */
466 [rec setCullMode:MTLCullModeNone];
467
468 if (generated_index_buffer != nil) {
469 BLI_assert(emulated_mtl_prim_type == MTLPrimitiveTypeTriangle ||
470 emulated_mtl_prim_type == MTLPrimitiveTypeLine);
471 if (emulated_mtl_prim_type == MTLPrimitiveTypeTriangle) {
472 BLI_assert(emulated_v_count % 3 == 0);
473 }
474 if (emulated_mtl_prim_type == MTLPrimitiveTypeLine) {
475 BLI_assert(emulated_v_count % 2 == 0);
476 }
477
478 /* Set depth stencil state (TODO: Move it back upstream, is legacy of depth bias). */
479 ctx->ensure_depth_stencil_state();
480
481 [rec drawIndexedPrimitives:emulated_mtl_prim_type
482 indexCount:emulated_v_count
483 indexType:MTLIndexTypeUInt32
484 indexBuffer:generated_index_buffer
485 indexBufferOffset:0
486 instanceCount:i_count
487 baseVertex:v_first
488 baseInstance:i_first];
489 }
490 else {
491 CLOG_WARN(&LOG,
492 "Cannot draw batch -- Emulated Topology mode: %u not yet supported",
493 this->prim_type);
494 }
495 }
496 else {
497 /* Set depth stencil state (TODO: Move it back upstream, is legacy of depth bias). */
498 ctx->ensure_depth_stencil_state();
499
500 /* Issue draw call. */
501 [rec drawPrimitives:mtl_prim_type
502 vertexStart:v_first
503 vertexCount:v_count
504 instanceCount:i_count
505 baseInstance:i_first];
506 }
507 ctx->main_command_buffer.register_draw_counters(v_count * i_count);
508 }
509 /* Perform indexed draw. */
510 else {
511
512 MTLIndexType index_type = MTLIndexBuf::gpu_index_type_to_metal(mtl_elem->index_type_);
513 uint32_t base_index = mtl_elem->index_base_;
514 uint32_t index_size = (mtl_elem->index_type_ == GPU_INDEX_U16) ? 2 : 4;
515 uint32_t v_first_ofs = ((v_first + mtl_elem->index_start_) * index_size);
516 BLI_assert_msg((v_first_ofs % index_size) == 0,
517 "Index offset is not 2/4-byte aligned as per METAL spec");
518
519 /* Fetch index buffer. May return an index buffer of a differing format,
520 * if index buffer optimization is used. In these cases, final_prim_type and
521 * index_count get updated with the new properties. */
522 GPUPrimType final_prim_type = this->prim_type;
523 uint index_count = v_count;
524
525 id<MTLBuffer> index_buffer = mtl_elem->get_index_buffer(final_prim_type, index_count);
526 mtl_prim_type = gpu_prim_type_to_metal(final_prim_type);
527 BLI_assert(index_buffer != nil);
528
529 if (index_buffer != nil) {
530
531 /* Set depth stencil state (TODO: Move it back upstream, is legacy of depth bias). */
532 ctx->ensure_depth_stencil_state();
533
534 /* Issue draw call. */
535 [rec drawIndexedPrimitives:mtl_prim_type
536 indexCount:index_count
537 indexType:index_type
538 indexBuffer:index_buffer
539 indexBufferOffset:v_first_ofs
540 instanceCount:i_count
541 baseVertex:base_index
542 baseInstance:i_first];
543 ctx->main_command_buffer.register_draw_counters(index_count * i_count);
544 }
545 else {
546 BLI_assert_msg(false, "Index buffer does not have backing Metal buffer");
547 }
548 }
549
550 /* End of draw. */
551 this->unbind(rec);
552}
553
554void MTLBatch::draw_advanced_indirect(StorageBuf *indirect_buf, intptr_t offset)
555{
556 this->draw_advanced_indirect_internal(indirect_buf, 1, offset, 0);
557}
558
560 int count,
561 intptr_t offset,
562 intptr_t stride)
563{
564 this->draw_advanced_indirect_internal(indirect_buf, count, offset, stride);
565}
566
567void MTLBatch::draw_advanced_indirect_internal(StorageBuf *indirect_buf,
568 int count,
569 intptr_t offset,
570 intptr_t stride)
571{
572 BLI_assert(count > 0);
573
574 /* Setup RenderPipelineState for batch. */
576 id<MTLRenderCommandEncoder> rec = this->bind();
577 if (rec == nil) {
578 CLOG_ERROR(&LOG, "Failed to open Render Command encoder for DRAW INDIRECT");
579
580 /* End of draw. */
581 this->unbind(rec);
582 return;
583 }
584
585 /* Fetch indirect buffer Metal handle. */
586 MTLStorageBuf *mtlssbo = static_cast<MTLStorageBuf *>(indirect_buf);
587 id<MTLBuffer> mtl_indirect_buf = mtlssbo->get_metal_buffer();
588 BLI_assert(mtl_indirect_buf != nil);
589 if (mtl_indirect_buf == nil) {
590 MTL_LOG_WARNING("Metal Indirect Draw Storage Buffer is nil.");
591
592 /* End of draw. */
593 this->unbind(rec);
594 return;
595 }
596
597 /* Unsupported primitive type check. */
598 BLI_assert_msg(this->prim_type != GPU_PRIM_TRI_FAN,
599 "TriangleFan is not supported in Metal for Indirect draws.");
600
601 /* Fetch IndexBuffer and resolve primitive type. */
602 MTLIndexBuf *mtl_elem = static_cast<MTLIndexBuf *>(reinterpret_cast<IndexBuf *>(this->elem));
603 MTLPrimitiveType mtl_prim_type = gpu_prim_type_to_metal(this->prim_type);
604
605 if (mtl_needs_topology_emulation(this->prim_type)) {
606 BLI_assert_msg(false, "Metal Topology emulation unsupported for draw indirect.\n");
607
608 /* End of draw. */
609 this->unbind(rec);
610 return;
611 }
612
613 /* Resolve the index buffer (and any primitive type change from index optimization) once.
614 * The indirect command encodes the per-command index count and first-index, so all commands
615 * of the batch share the same index buffer. */
616 MTLIndexType index_type;
617 GPUPrimType final_prim_type = this->prim_type;
618 id<MTLBuffer> index_buffer = nil;
619 if (mtl_elem != nullptr) {
620 uint index_count = 0;
621
622 index_type = MTLIndexBuf::gpu_index_type_to_metal(mtl_elem->index_type_);
623
624 /* Disable index optimization for indirect draws. */
625 mtl_elem->flag_can_optimize(false);
626
627 index_buffer = mtl_elem->get_index_buffer(final_prim_type, index_count);
628 mtl_prim_type = gpu_prim_type_to_metal(final_prim_type);
629 BLI_assert(index_buffer != nil);
630
631 if (index_buffer == nil) {
632 BLI_assert_msg(false, "Index buffer does not have backing Metal buffer");
633
634 /* End of draw. */
635 this->unbind(rec);
636 return;
637 }
638 }
639
640 /* Set depth stencil state (TODO: Move it back upstream, is legacy of depth bias). */
642
643 /* Issue one indirect draw per command. */
644 for (int i = 0; i < count; i++) {
645 intptr_t cmd_offset = offset + i * stride;
646 if (mtl_elem == nullptr) {
647 [rec drawPrimitives:mtl_prim_type
648 indirectBuffer:mtl_indirect_buf
649 indirectBufferOffset:cmd_offset];
650 }
651 else {
652 [rec drawIndexedPrimitives:mtl_prim_type
653 indexType:index_type
654 indexBuffer:index_buffer
655 indexBufferOffset:0
656 indirectBuffer:mtl_indirect_buf
657 indirectBufferOffset:cmd_offset];
658 }
659 }
661
662 /* End of draw. */
663 this->unbind(rec);
664}
665
667
668/* -------------------------------------------------------------------- */
671
672id<MTLBuffer> MTLBatch::get_emulated_toplogy_buffer(GPUPrimType &in_out_prim_type,
673 uint32_t &in_out_v_count)
674{
675
676 BLI_assert(in_out_v_count > 0);
677 /* Determine emulated primitive types. */
678 GPUPrimType input_prim_type = in_out_prim_type;
679 uint32_t v_count = in_out_v_count;
680 GPUPrimType output_prim_type;
681 switch (input_prim_type) {
682 case GPU_PRIM_POINTS:
683 case GPU_PRIM_LINES:
684 case GPU_PRIM_TRIS:
685 BLI_assert_msg(false, "Optimal primitive types should not reach here.");
686 return nil;
687 break;
690 BLI_assert_msg(false, "Adjacency primitive types should not reach here.");
691 return nil;
692 break;
696 output_prim_type = GPU_PRIM_LINES;
697 break;
699 case GPU_PRIM_TRI_FAN:
700 output_prim_type = GPU_PRIM_TRIS;
701 break;
702 default:
703 BLI_assert_msg(false, "Invalid primitive type.");
704 return nil;
705 }
706
707 /* Check if topology buffer exists and is valid. */
708 if (this->emulated_topology_buffer_ != nullptr &&
709 (emulated_topology_type_ != input_prim_type || topology_buffer_input_v_count_ != v_count))
710 {
711
712 /* Release existing topology buffer. */
713 emulated_topology_buffer_->free();
714 emulated_topology_buffer_ = nullptr;
715 }
716
717 /* Generate new topology index buffer. */
718 if (this->emulated_topology_buffer_ == nullptr) {
719 /* Calculate IB len. */
720 uint32_t output_prim_count = 0;
721 switch (input_prim_type) {
724 output_prim_count = v_count - 1;
725 break;
727 output_prim_count = v_count;
728 break;
730 case GPU_PRIM_TRI_FAN:
731 output_prim_count = v_count - 2;
732 break;
733 default:
734 BLI_assert_msg(false, "Cannot generate optimized topology buffer for other types.");
735 break;
736 }
737 uint32_t output_IB_elems = output_prim_count * ((output_prim_type == GPU_PRIM_TRIS) ? 3 : 2);
738
739 /* Allocate buffer. */
740 uint32_t buffer_bytes = output_IB_elems * 4;
741 BLI_assert(buffer_bytes > 0);
742 this->emulated_topology_buffer_ = MTLContext::get_global_memory_manager()->allocate(
743 buffer_bytes, true);
744
745 /* Populate. */
746 uint32_t *data = (uint32_t *)this->emulated_topology_buffer_->get_host_ptr();
747 BLI_assert(data != nullptr);
748
749 /* TODO(Metal): Support inverse winding modes. */
750 bool winding_clockwise = false;
751 UNUSED_VARS(winding_clockwise);
752
753 switch (input_prim_type) {
754 /* Line Loop. */
755 case GPU_PRIM_LINE_LOOP: {
756 int line = 0;
757 for (line = 0; line < output_prim_count - 1; line++) {
758 data[line * 2 + 0] = line + 0;
759 data[line * 2 + 1] = line + 1;
760 }
761 /* Closing line. */
762 data[line * 2 + 0] = line + 0;
763 data[line * 2 + 1] = 0;
764 } break;
765
766 /* Triangle Fan. */
767 case GPU_PRIM_TRI_FAN: {
768 for (int triangle = 0; triangle < output_prim_count; triangle++) {
769 data[triangle * 3 + 0] = 0; /* Always 0 */
770 data[triangle * 3 + 1] = triangle + 1;
771 data[triangle * 3 + 2] = triangle + 2;
772 }
773 } break;
774
775 default:
776 BLI_assert_msg(false, "Other primitive types do not require emulation.");
777 return nil;
778 }
779
780 /* Flush. */
781 this->emulated_topology_buffer_->flush();
782 /* Assign members relating to current cached IB. */
783 topology_buffer_input_v_count_ = v_count;
784 topology_buffer_output_v_count_ = output_IB_elems;
785 emulated_topology_type_ = input_prim_type;
786 }
787
788 /* Return. */
789 in_out_v_count = topology_buffer_output_v_count_;
790 in_out_prim_type = output_prim_type;
791 return (emulated_topology_buffer_) ? emulated_topology_buffer_->get_metal_buffer() : nil;
792}
793
795
796} // namespace blender::gpu
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define UNUSED_VARS(...)
#define BLI_assert(a)
#define BLI_assert_msg(a, msg)
SocketType::Type type() const
void draw_indirect(StorageBuf *indirect_buf, intptr_t offset) override
Definition mtl_batch.mm:43
void multi_draw_indirect(StorageBuf *indirect_buf, int count, intptr_t offset, intptr_t stride) override
Definition mtl_batch.mm:559
id< MTLRenderCommandEncoder > bind()
Definition mtl_batch.mm:223
void draw(int v_first, int v_count, int i_first, int i_count) override
Definition mtl_batch.mm:38
void unbind(id< MTLRenderCommandEncoder > rec)
Definition mtl_batch.mm:318
gpu::MTLBuffer * allocate(uint64_t size, bool cpu_visible)
void register_draw_counters(int vertex_submission)
MTLRenderPassState & get_render_pass_state()
bool ensure_render_pipeline_state(MTLPrimitiveType prim_type)
id< MTLRenderCommandEncoder > ensure_begin_render_pass()
static MTLContext * get()
MTLCommandBufferManager main_command_buffer
static MTLBufferPool * get_global_memory_manager()
static MTLIndexType gpu_index_type_to_metal(GPUIndexBufType type)
void bind_vertex_buffer(id< MTLBuffer > buffer, uint64_t buffer_offset, uint index)
MTLRenderPipelineStateDescriptor & get_pipeline_descriptor()
Definition mtl_state.hh:57
#define GPU_VAO_STATIC_LEN
Definition mtl_batch.hh:26
#define MTL_LOG_WARNING(info,...)
Definition mtl_debug.hh:39
#define MTL_LOG_DEBUG(info,...)
Definition mtl_debug.hh:46
#define MTL_LOG_ERROR(info,...)
Definition mtl_debug.hh:31
MTLVertexFormat gpu_vertex_format_to_metal(VertAttrType vert_format)
static CLG_LogRef LOG
bool is_fetch_float(VertAttrType attr_type)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
unsigned int uint
Definition BKE_text.h:55
BLI_INLINE const char * GPU_vertformat_attr_name_get(const GPUVertFormat *format, const GPUVertAttr *attr, uint n_idx)
@ GPU_PRIM_TRI_STRIP
@ GPU_PRIM_TRIS_ADJ
@ GPU_PRIM_LINES_ADJ
@ GPU_PRIM_LINE_STRIP_ADJ
@ GPU_PRIM_LINE_STRIP
@ GPU_PRIM_LINE_LOOP
MINLINE int max_ii(int a, int b)
ATTR_WARN_UNUSED_RESULT const BMVert * v
Global G
Definition blender.cc:57
unsigned short uint16_t
Definition BKE_text.h:80
MINLINE unsigned int bitscan_forward_clear_uint(unsigned int *a)
unsigned int uint32_t
Definition BKE_text.h:81
BMesh const char void * data
@ GPU_BATCH_DIRTY
Definition GPU_batch.hh:55
_W64 int intptr_t
Definition BKE_text.h:119
std::string format(const std::string &fmt, Args &&...args)
Definition diagnostic.hh:43
MTLVertexAttributeDescriptorPSO attributes[GPU_VERT_ATTR_MAX_LEN]