Blender V5.3
mtl_immediate.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 "BKE_global.hh"
12
13#include "BLI_bit_span.hh"
14
15#include "GPU_vertex_format.hh"
17#include "gpu_shader_private.hh"
19
20#include "mtl_context.hh"
21#include "mtl_debug.hh"
22#include "mtl_immediate.hh"
23#include "mtl_primitive.hh"
24#include "mtl_shader.hh"
25#include "mtl_vertex_buffer.hh"
26
27namespace blender::gpu {
28
30{
31 context_ = ctx;
32}
33
35{
36 BLI_assert(!has_begun_);
37
38 /* Determine primitive type. */
39 metal_primitive_type_ = gpu_prim_type_to_metal(this->prim_type);
40 metal_primitive_mode_ = mtl_prim_type_to_topology_class(metal_primitive_type_);
41 has_begun_ = true;
42
43 /* If prim type is line loop, add an extra vertex at the end for placing the closing line,
44 * as metal does not support this primitive type. We treat this as a Line strip with one
45 * extra value. */
46 int vertex_alloc_length = vertex_len;
48 vertex_alloc_length++;
49 }
50
51 /* Allocate a range of data and return host-accessible pointer. */
52 const size_t bytes_needed = vertex_buffer_size(&vertex_format, vertex_alloc_length);
53 current_allocation_ = context_->get_scratch_buffer_manager()
54 .scratch_buffer_allocate_range_aligned(bytes_needed, 256);
55 [current_allocation_.metal_buffer retain];
56 return reinterpret_cast<uchar *>(current_allocation_.data);
57}
58
60{
61 /* Ensure we're between a `imm::begin` / `imm:end` pair. */
62 BLI_assert(has_begun_);
64
65 /* Verify context is valid, vertex data is written and a valid shader is bound. */
66 if (context_ && this->vertex_idx > 0 && this->shader) {
67
68 MTLShader *active_mtl_shader = static_cast<MTLShader *>(shader);
69
70 /* Skip draw if Metal shader is not valid. */
71 if (active_mtl_shader == nullptr || !active_mtl_shader->is_valid()) {
72 const StringRefNull ptr = (active_mtl_shader) ? active_mtl_shader->name_get() : "";
74 "MTLImmediate::end -- cannot perform draw as active shader is NULL or invalid (likely "
75 "unimplemented) (shader %p '%s')",
76 active_mtl_shader,
77 ptr.c_str());
78 return;
79 }
80
81 /* Ensure we are inside a render pass and fetch active RenderCommandEncoder. */
82 id<MTLRenderCommandEncoder> rec = context_->ensure_begin_render_pass();
83 BLI_assert(rec != nil);
84
85 /* Fetch active render pipeline state. */
86 MTLRenderPassState &rps = context_->main_command_buffer.get_render_pass_state();
87
88 /* Bind Shader. */
90
91 /* Debug markers for frame-capture and detailed error messages. */
92 if (G.debug & G_DEBUG_GPU) {
93 context_->main_command_buffer.unfold_pending_debug_groups();
94 [rec pushDebugGroup:[NSString stringWithFormat:@"immEnd(Shader:%s)",
95 active_mtl_shader->name_get().c_str()]];
96 }
97
98 /* Populate pipeline state vertex descriptor. */
99 MTLStateManager *state_manager = static_cast<MTLStateManager *>(
102 const MTLShaderInterface &interface = active_mtl_shader->get_interface();
103
104 /* Reset vertex descriptor to default state. */
106 desc.vertex_descriptor.total_attributes = interface.attr_len_;
109
110 for (int i = 0; i < desc.vertex_descriptor.total_attributes; i++) {
111 desc.vertex_descriptor.attributes[i].format = MTLVertexFormatInvalid;
112 }
113
114 if (interface.vertex_buffer_mask() == 0) {
115 MTL_LOG_ERROR("MTLImmediate::end Not enough buffer slot to bind attributes.");
116 BLI_assert_unreachable();
117 return;
118 }
119
120 int imm_buffer_slot = bitscan_forward_uint(interface.vertex_buffer_mask());
121
122 /* Populate Vertex descriptor and verify attributes.
123 * TODO(Metal): Cache this vertex state based on Vertex format and shaders. */
124 for (int i : bits::iter_1_indices(interface.enabled_attr_mask_)) {
125 const ShaderInput *input = interface.attr_get(i);
126 BLI_assert(input != nullptr);
127 StringRefNull input_name(interface.name_at_offset(input->name_offset));
128
129 GPUVertAttr *attr = nullptr;
130 /* Scan through vertex_format attributes until one with a name matching the shader interface
131 * is found. */
132 for (uint32_t a_idx = 0; a_idx < this->vertex_format.attr_len && attr == nullptr; a_idx++) {
133 GPUVertAttr *candidate = &this->vertex_format.attrs[a_idx];
134 /* Attributes can have multiple name aliases associated with them. */
135 for (uint32_t n_idx = 0; n_idx < candidate->name_len; n_idx++) {
136 StringRefNull name = GPU_vertformat_attr_name_get(
137 &this->vertex_format, candidate, n_idx);
138 if (name == input_name) {
139 attr = candidate;
140 break;
141 }
142 }
143 }
144
145 if (attr == nullptr) {
146 MTL_LOG_ERROR("MTLImmediate::end Could not find matching attribute '%s' in Vertex Format!",
147 input_name.c_str());
149 return;
150 }
151
153 pso_attr.format = gpu_vertex_format_to_metal(attr->type.format);
154 pso_attr.format_conversion_mode = (is_fetch_float(attr->type.format)) ?
157 /* Using attribute offset in vertex format, as this will be correct */
158 pso_attr.offset = attr->offset;
159 pso_attr.buffer_index = imm_buffer_slot;
160
162
163 BLI_assert(pso_attr.format != MTLVertexFormatInvalid);
164 }
165
166 /* Buffer bindings for singular vertex buffer. */
167 desc.vertex_descriptor.buffer_layouts[0].step_function = MTLVertexStepFunctionPerVertex;
168 desc.vertex_descriptor.buffer_layouts[0].step_rate = 1;
169 desc.vertex_descriptor.buffer_layouts[0].stride = this->vertex_format.stride;
170 desc.vertex_descriptor.buffer_layouts[0].buffer_slot = 0;
172
173 /* Emulate LineLoop using LineStrip. */
174 if (this->prim_type == GPU_PRIM_LINE_LOOP) {
175 /* Patch final vertex of line loop to close. Rendered using LineStrip.
176 * NOTE: vertex_len represents original length, however, allocated Metal
177 * buffer contains space for one extra vertex when LineLoop is used. */
178 uchar *buffer_data = reinterpret_cast<uchar *>(current_allocation_.data);
179 memcpy(buffer_data + (vertex_len)*vertex_format.stride, buffer_data, vertex_format.stride);
180 this->vertex_idx++;
182 }
183
184 if (this->shader->is_polyline) {
185 context_->get_scratch_buffer_manager().bind_as_ssbo(GPU_SSBO_POLYLINE_POS_BUF_SLOT);
186 context_->get_scratch_buffer_manager().bind_as_ssbo(GPU_SSBO_POLYLINE_COL_BUF_SLOT);
187 context_->get_scratch_buffer_manager().bind_as_ssbo(GPU_SSBO_INDEX_BUF_SLOT);
188 }
189
190 /* Bind Vertex Buffer. */
191 rps.bind_vertex_buffer(
192 current_allocation_.metal_buffer, current_allocation_.buffer_offset, imm_buffer_slot);
193
194 MTLPrimitiveType mtl_prim_type = gpu_prim_type_to_metal(this->prim_type);
195
196 if (context_->ensure_render_pipeline_state(mtl_prim_type)) {
197
198 /* Issue draw call. */
199 BLI_assert(this->vertex_idx > 0);
200
201 /* Metal API does not support triangle fan, so we can emulate this
202 * input data by generating an index buffer to re-map indices to
203 * a TriangleList.
204 *
205 * NOTE(Metal): Consider caching generated triangle fan index buffers.
206 * For immediate mode, generating these is currently very cheap, as we use
207 * fast scratch buffer allocations. Though we may benefit from caching of
208 * frequently used buffer sizes. */
209 bool rendered = false;
210 if (mtl_needs_topology_emulation(this->prim_type)) {
211
212 /* Emulate Tri-fan. */
213 switch (this->prim_type) {
214 case GPU_PRIM_TRI_FAN: {
215 /* Prepare Triangle-Fan emulation index buffer on CPU based on number of input
216 * vertices. */
217 uint32_t base_vert_count = this->vertex_idx;
218 uint32_t num_triangles = max_ii(base_vert_count - 2, 0);
219 uint32_t fan_index_count = num_triangles * 3;
220 BLI_assert(num_triangles > 0);
221
222 uint32_t alloc_size = sizeof(uint32_t) * fan_index_count;
223 uint32_t *index_buffer = nullptr;
224
225 MTLTemporaryBuffer allocation =
226 context_->get_scratch_buffer_manager().scratch_buffer_allocate_range_aligned(
227 alloc_size, 128);
228 index_buffer = (uint32_t *)allocation.data;
229
230 int a = 0;
231 for (int i = 0; i < num_triangles; i++) {
232 index_buffer[a++] = 0;
233 index_buffer[a++] = i + 1;
234 index_buffer[a++] = i + 2;
235 }
236
237 @autoreleasepool {
238 id<MTLBuffer> index_buffer_mtl = nil;
239 uint64_t index_buffer_offset = 0;
240
241 /* Region of scratch buffer used for topology emulation element data.
242 * NOTE(Metal): We do not need to manually flush as the entire scratch
243 * buffer for current command buffer is flushed upon submission. */
244 index_buffer_mtl = allocation.metal_buffer;
245 index_buffer_offset = allocation.buffer_offset;
246
247 /* Set depth stencil state (TODO: Move it back upstream, is legacy of depth bias). */
248 context_->ensure_depth_stencil_state();
249
250 /* Draw. */
251 [rec drawIndexedPrimitives:MTLPrimitiveTypeTriangle
252 indexCount:fan_index_count
253 indexType:MTLIndexTypeUInt32
254 indexBuffer:index_buffer_mtl
255 indexBufferOffset:index_buffer_offset];
256 context_->main_command_buffer.register_draw_counters(fan_index_count);
257 }
258
259 rendered = true;
260 } break;
261 default: {
263 } break;
264 }
265 }
266
267 /* If not yet rendered, run through main render path. LineLoop primitive topology emulation
268 * will simply amend original data passed into default rendering path. */
269 if (!rendered) {
270 MTLPrimitiveType primitive_type = metal_primitive_type_;
271 int vertex_count = this->vertex_idx;
272
273 /* Set depth stencil state (TODO: Move it back upstream, is legacy of depth bias). */
274 context_->ensure_depth_stencil_state();
275
276 if (this->shader->is_polyline) {
277 this->polyline_draw_workaround(current_allocation_.buffer_offset);
278 }
279 else {
280 /* Regular draw. */
281 [rec drawPrimitives:primitive_type vertexStart:0 vertexCount:vertex_count];
282 context_->main_command_buffer.register_draw_counters(vertex_count);
283 }
284 }
285 }
286 if (G.debug & G_DEBUG_GPU) {
287 [rec popDebugGroup];
288 }
289
290 if (this->shader->is_polyline) {
291 context_->get_scratch_buffer_manager().unbind_as_ssbo();
292
293 context_->pipeline_state.ssbo_bindings[GPU_SSBO_POLYLINE_POS_BUF_SLOT].ssbo = nil;
294 context_->pipeline_state.ssbo_bindings[GPU_SSBO_POLYLINE_COL_BUF_SLOT].ssbo = nil;
295 context_->pipeline_state.ssbo_bindings[GPU_SSBO_INDEX_BUF_SLOT].ssbo = nil;
296 context_->pipeline_state.ssbo_bindings[GPU_SSBO_POLYLINE_POS_BUF_SLOT].bound = false;
297 context_->pipeline_state.ssbo_bindings[GPU_SSBO_POLYLINE_COL_BUF_SLOT].bound = false;
298 context_->pipeline_state.ssbo_bindings[GPU_SSBO_INDEX_BUF_SLOT].bound = false;
299 }
300 }
301
302 /* Reset allocation after draw submission. */
303 has_begun_ = false;
304 if (current_allocation_.metal_buffer) {
305 [current_allocation_.metal_buffer release];
306 current_allocation_.metal_buffer = nil;
307 }
308}
309
310} // namespace blender::gpu
#define BLI_assert_unreachable()
constexpr const char * c_str() const
void polyline_draw_workaround(uint64_t offset)
static MTLContext * get()
uchar * begin() override
MTLImmediate(MTLContext *ctx)
MTLRenderPipelineStateDescriptor & get_pipeline_descriptor()
Definition mtl_state.hh:57
StringRefNull name_get() const
#define GPU_SSBO_POLYLINE_POS_BUF_SLOT
#define GPU_SSBO_POLYLINE_COL_BUF_SLOT
#define GPU_SSBO_INDEX_BUF_SLOT
#define MTL_LOG_WARNING(info,...)
Definition mtl_debug.hh:39
#define MTL_LOG_ERROR(info,...)
Definition mtl_debug.hh:31
OneBitIteratorRange iter_1_indices(BitInt value)
MTLVertexFormat gpu_vertex_format_to_metal(VertAttrType vert_format)
MTLBufferRange MTLTemporaryBuffer
bool is_fetch_float(VertAttrType attr_type)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
unsigned __int64 uint64_t
Definition BKE_text.h:91
MINLINE unsigned int bitscan_forward_uint(unsigned int a)
@ GPU_PRIM_LINE_STRIP
@ GPU_PRIM_LINE_LOOP
MINLINE int max_ii(int a, int b)
Global G
Definition blender.cc:57
unsigned int uint32_t
Definition BKE_text.h:81
unsigned char uchar
Definition BKE_text.h:58
void GPU_shader_bind(gpu::Shader *shader, const gpu::shader::SpecializationConstants *constants_state=nullptr)
uint vertex_buffer_size(const GPUVertFormat *format, uint vertex_len)
MTLVertexAttributeDescriptorPSO attributes[GPU_VERT_ATTR_MAX_LEN]