u_vbuf.c revision 634066946e265aa5d2628ddca16c6556d2091a66
1/**************************************************************************
2 *
3 * Copyright 2011 Marek Olšák <maraeo@gmail.com>
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28#include "util/u_vbuf.h"
29
30#include "util/u_dump.h"
31#include "util/u_format.h"
32#include "util/u_inlines.h"
33#include "util/u_memory.h"
34#include "util/u_upload_mgr.h"
35#include "translate/translate.h"
36#include "translate/translate_cache.h"
37#include "cso_cache/cso_cache.h"
38#include "cso_cache/cso_hash.h"
39
40struct u_vbuf_elements {
41   unsigned count;
42   struct pipe_vertex_element ve[PIPE_MAX_ATTRIBS];
43
44   unsigned src_format_size[PIPE_MAX_ATTRIBS];
45
46   /* If (velem[i].src_format != native_format[i]), the vertex buffer
47    * referenced by the vertex element cannot be used for rendering and
48    * its vertex data must be translated to native_format[i]. */
49   enum pipe_format native_format[PIPE_MAX_ATTRIBS];
50   unsigned native_format_size[PIPE_MAX_ATTRIBS];
51
52   /* This might mean two things:
53    * - src_format != native_format, as discussed above.
54    * - src_offset % 4 != 0 (if the caps don't allow such an offset). */
55   uint32_t incompatible_elem_mask; /* each bit describes a corresp. attrib  */
56   /* Which buffer has at least one vertex element referencing it
57    * incompatible. */
58   uint32_t incompatible_vb_mask_any;
59   /* Which buffer has all vertex elements referencing it incompatible. */
60   uint32_t incompatible_vb_mask_all;
61   /* Which buffer has at least one vertex element referencing it
62    * compatible. */
63   uint32_t compatible_vb_mask_any;
64   /* Which buffer has all vertex elements referencing it compatible. */
65   uint32_t compatible_vb_mask_all;
66
67   /* Which buffer has at least one vertex element referencing it
68    * non-instanced. */
69   uint32_t noninstance_vb_mask_any;
70
71   void *driver_cso;
72};
73
74enum {
75   VB_VERTEX = 0,
76   VB_INSTANCE = 1,
77   VB_CONST = 2,
78   VB_NUM = 3
79};
80
81struct u_vbuf {
82   struct u_vbuf_caps caps;
83
84   struct pipe_context *pipe;
85   struct translate_cache *translate_cache;
86   struct cso_cache *cso_cache;
87   struct u_upload_mgr *uploader;
88
89   /* This is what was set in set_vertex_buffers.
90    * May contain user buffers. */
91   struct pipe_vertex_buffer vertex_buffer[PIPE_MAX_ATTRIBS];
92   unsigned nr_vertex_buffers;
93
94   /* Saved vertex buffers. */
95   struct pipe_vertex_buffer vertex_buffer_saved[PIPE_MAX_ATTRIBS];
96   unsigned nr_vertex_buffers_saved;
97
98   /* Vertex buffers for the driver.
99    * There are no user buffers. */
100   struct pipe_vertex_buffer real_vertex_buffer[PIPE_MAX_ATTRIBS];
101   int nr_real_vertex_buffers;
102   boolean vertex_buffers_dirty;
103
104   /* The index buffer. */
105   struct pipe_index_buffer index_buffer;
106
107   /* Vertex elements. */
108   struct u_vbuf_elements *ve, *ve_saved;
109
110   /* Vertex elements used for the translate fallback. */
111   struct pipe_vertex_element fallback_velems[PIPE_MAX_ATTRIBS];
112   /* If non-NULL, this is a vertex element state used for the translate
113    * fallback and therefore used for rendering too. */
114   boolean using_translate;
115   /* The vertex buffer slot index where translated vertices have been
116    * stored in. */
117   unsigned fallback_vbs[VB_NUM];
118
119   /* Which buffer is a user buffer. */
120   uint32_t user_vb_mask; /* each bit describes a corresp. buffer */
121   /* Which buffer is incompatible (unaligned). */
122   uint32_t incompatible_vb_mask; /* each bit describes a corresp. buffer */
123   /* Which buffer has a non-zero stride. */
124   uint32_t nonzero_stride_vb_mask; /* each bit describes a corresp. buffer */
125};
126
127static void *
128u_vbuf_create_vertex_elements(struct u_vbuf *mgr, unsigned count,
129                              const struct pipe_vertex_element *attribs);
130static void u_vbuf_delete_vertex_elements(struct u_vbuf *mgr, void *cso);
131
132
133void u_vbuf_get_caps(struct pipe_screen *screen, struct u_vbuf_caps *caps)
134{
135   caps->format_fixed32 =
136      screen->is_format_supported(screen, PIPE_FORMAT_R32_FIXED, PIPE_BUFFER,
137                                  0, PIPE_BIND_VERTEX_BUFFER);
138
139   caps->format_float16 =
140      screen->is_format_supported(screen, PIPE_FORMAT_R16_FLOAT, PIPE_BUFFER,
141                                  0, PIPE_BIND_VERTEX_BUFFER);
142
143   caps->format_float64 =
144      screen->is_format_supported(screen, PIPE_FORMAT_R64_FLOAT, PIPE_BUFFER,
145                                  0, PIPE_BIND_VERTEX_BUFFER);
146
147   caps->format_norm32 =
148      screen->is_format_supported(screen, PIPE_FORMAT_R32_UNORM, PIPE_BUFFER,
149                                  0, PIPE_BIND_VERTEX_BUFFER) &&
150      screen->is_format_supported(screen, PIPE_FORMAT_R32_SNORM, PIPE_BUFFER,
151                                  0, PIPE_BIND_VERTEX_BUFFER);
152
153   caps->format_scaled32 =
154      screen->is_format_supported(screen, PIPE_FORMAT_R32_USCALED, PIPE_BUFFER,
155                                  0, PIPE_BIND_VERTEX_BUFFER) &&
156      screen->is_format_supported(screen, PIPE_FORMAT_R32_SSCALED, PIPE_BUFFER,
157                                  0, PIPE_BIND_VERTEX_BUFFER);
158
159   caps->buffer_offset_unaligned =
160      !screen->get_param(screen,
161                        PIPE_CAP_VERTEX_BUFFER_OFFSET_4BYTE_ALIGNED_ONLY);
162
163   caps->buffer_stride_unaligned =
164      !screen->get_param(screen,
165                        PIPE_CAP_VERTEX_BUFFER_STRIDE_4BYTE_ALIGNED_ONLY);
166
167   caps->velem_src_offset_unaligned =
168      !screen->get_param(screen,
169                        PIPE_CAP_VERTEX_ELEMENT_SRC_OFFSET_4BYTE_ALIGNED_ONLY);
170
171   caps->user_vertex_buffers =
172      screen->get_param(screen, PIPE_CAP_USER_VERTEX_BUFFERS);
173}
174
175struct u_vbuf *
176u_vbuf_create(struct pipe_context *pipe,
177              struct u_vbuf_caps *caps)
178{
179   struct u_vbuf *mgr = CALLOC_STRUCT(u_vbuf);
180
181   mgr->caps = *caps;
182   mgr->pipe = pipe;
183   mgr->cso_cache = cso_cache_create();
184   mgr->translate_cache = translate_cache_create();
185   memset(mgr->fallback_vbs, ~0, sizeof(mgr->fallback_vbs));
186
187   mgr->uploader = u_upload_create(pipe, 1024 * 1024, 4,
188                                   PIPE_BIND_VERTEX_BUFFER);
189
190   return mgr;
191}
192
193/* u_vbuf uses its own caching for vertex elements, because it needs to keep
194 * its own preprocessed state per vertex element CSO. */
195static struct u_vbuf_elements *
196u_vbuf_set_vertex_elements_internal(struct u_vbuf *mgr, unsigned count,
197                                    const struct pipe_vertex_element *states)
198{
199   struct pipe_context *pipe = mgr->pipe;
200   unsigned key_size, hash_key;
201   struct cso_hash_iter iter;
202   struct u_vbuf_elements *ve;
203   struct cso_velems_state velems_state;
204
205   /* need to include the count into the stored state data too. */
206   key_size = sizeof(struct pipe_vertex_element) * count + sizeof(unsigned);
207   velems_state.count = count;
208   memcpy(velems_state.velems, states,
209          sizeof(struct pipe_vertex_element) * count);
210   hash_key = cso_construct_key((void*)&velems_state, key_size);
211   iter = cso_find_state_template(mgr->cso_cache, hash_key, CSO_VELEMENTS,
212                                  (void*)&velems_state, key_size);
213
214   if (cso_hash_iter_is_null(iter)) {
215      struct cso_velements *cso = MALLOC_STRUCT(cso_velements);
216      memcpy(&cso->state, &velems_state, key_size);
217      cso->data = u_vbuf_create_vertex_elements(mgr, count, states);
218      cso->delete_state = (cso_state_callback)u_vbuf_delete_vertex_elements;
219      cso->context = (void*)mgr;
220
221      iter = cso_insert_state(mgr->cso_cache, hash_key, CSO_VELEMENTS, cso);
222      ve = cso->data;
223   } else {
224      ve = ((struct cso_velements *)cso_hash_iter_data(iter))->data;
225   }
226
227   assert(ve);
228   pipe->bind_vertex_elements_state(pipe, ve->driver_cso);
229   return ve;
230}
231
232void u_vbuf_set_vertex_elements(struct u_vbuf *mgr, unsigned count,
233                               const struct pipe_vertex_element *states)
234{
235   mgr->ve = u_vbuf_set_vertex_elements_internal(mgr, count, states);
236}
237
238void u_vbuf_destroy(struct u_vbuf *mgr)
239{
240   unsigned i;
241
242   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
243      pipe_resource_reference(&mgr->vertex_buffer[i].buffer, NULL);
244   }
245   for (i = 0; i < mgr->nr_real_vertex_buffers; i++) {
246      pipe_resource_reference(&mgr->real_vertex_buffer[i].buffer, NULL);
247   }
248
249   translate_cache_destroy(mgr->translate_cache);
250   u_upload_destroy(mgr->uploader);
251   cso_cache_delete(mgr->cso_cache);
252   FREE(mgr);
253}
254
255static void
256u_vbuf_translate_buffers(struct u_vbuf *mgr, struct translate_key *key,
257                         unsigned vb_mask, unsigned out_vb,
258                         int start_vertex, unsigned num_vertices,
259                         int start_index, unsigned num_indices, int min_index,
260                         boolean unroll_indices)
261{
262   struct translate *tr;
263   struct pipe_transfer *vb_transfer[PIPE_MAX_ATTRIBS] = {0};
264   struct pipe_resource *out_buffer = NULL;
265   uint8_t *out_map;
266   unsigned i, out_offset;
267
268   /* Get a translate object. */
269   tr = translate_cache_find(mgr->translate_cache, key);
270
271   /* Map buffers we want to translate. */
272   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
273      if (vb_mask & (1 << i)) {
274         struct pipe_vertex_buffer *vb = &mgr->vertex_buffer[i];
275         unsigned offset = vb->buffer_offset + vb->stride * start_vertex;
276         uint8_t *map;
277
278         if (vb->buffer->user_ptr) {
279            map = vb->buffer->user_ptr + offset;
280         } else {
281            unsigned size = vb->stride ? num_vertices * vb->stride
282                                       : sizeof(double)*4;
283
284            if (offset+size > vb->buffer->width0) {
285               size = vb->buffer->width0 - offset;
286            }
287
288            map = pipe_buffer_map_range(mgr->pipe, vb->buffer, offset, size,
289                                        PIPE_TRANSFER_READ, &vb_transfer[i]);
290         }
291
292         /* Subtract min_index so that indexing with the index buffer works. */
293         if (unroll_indices) {
294            map -= vb->stride * min_index;
295         }
296
297         tr->set_buffer(tr, i, map, vb->stride, ~0);
298      }
299   }
300
301   /* Translate. */
302   if (unroll_indices) {
303      struct pipe_index_buffer *ib = &mgr->index_buffer;
304      struct pipe_transfer *transfer = NULL;
305      unsigned offset = ib->offset + start_index * ib->index_size;
306      uint8_t *map;
307
308      assert(ib->buffer && ib->index_size);
309
310      if (ib->buffer->user_ptr) {
311         map = ib->buffer->user_ptr + offset;
312      } else {
313         map = pipe_buffer_map_range(mgr->pipe, ib->buffer, offset,
314                                     num_indices * ib->index_size,
315                                     PIPE_TRANSFER_READ, &transfer);
316      }
317
318      /* Create and map the output buffer. */
319      u_upload_alloc(mgr->uploader, 0,
320                     key->output_stride * num_indices,
321                     &out_offset, &out_buffer,
322                     (void**)&out_map);
323
324      switch (ib->index_size) {
325      case 4:
326         tr->run_elts(tr, (unsigned*)map, num_indices, 0, out_map);
327         break;
328      case 2:
329         tr->run_elts16(tr, (uint16_t*)map, num_indices, 0, out_map);
330         break;
331      case 1:
332         tr->run_elts8(tr, map, num_indices, 0, out_map);
333         break;
334      }
335
336      if (transfer) {
337         pipe_buffer_unmap(mgr->pipe, transfer);
338      }
339   } else {
340      /* Create and map the output buffer. */
341      u_upload_alloc(mgr->uploader,
342                     key->output_stride * start_vertex,
343                     key->output_stride * num_vertices,
344                     &out_offset, &out_buffer,
345                     (void**)&out_map);
346
347      out_offset -= key->output_stride * start_vertex;
348
349      tr->run(tr, 0, num_vertices, 0, out_map);
350   }
351
352   /* Unmap all buffers. */
353   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
354      if (vb_transfer[i]) {
355         pipe_buffer_unmap(mgr->pipe, vb_transfer[i]);
356      }
357   }
358
359   /* Setup the new vertex buffer. */
360   mgr->real_vertex_buffer[out_vb].buffer_offset = out_offset;
361   mgr->real_vertex_buffer[out_vb].stride = key->output_stride;
362
363   /* Move the buffer reference. */
364   pipe_resource_reference(
365      &mgr->real_vertex_buffer[out_vb].buffer, NULL);
366   mgr->real_vertex_buffer[out_vb].buffer = out_buffer;
367}
368
369static boolean
370u_vbuf_translate_find_free_vb_slots(struct u_vbuf *mgr,
371                                    unsigned mask[VB_NUM])
372{
373   unsigned type;
374   unsigned fallback_vbs[VB_NUM];
375   /* Set the bit for each buffer which is incompatible, or isn't set. */
376   uint32_t unused_vb_mask =
377      mgr->ve->incompatible_vb_mask_all | mgr->incompatible_vb_mask |
378      ~((1 << mgr->nr_vertex_buffers) - 1);
379
380   memset(fallback_vbs, ~0, sizeof(fallback_vbs));
381
382   /* Find free slots for each type if needed. */
383   for (type = 0; type < VB_NUM; type++) {
384      if (mask[type]) {
385         uint32_t index;
386
387         if (!unused_vb_mask) {
388            /* fail, reset the number to its original value */
389            mgr->nr_real_vertex_buffers = mgr->nr_vertex_buffers;
390            return FALSE;
391         }
392
393         index = ffs(unused_vb_mask) - 1;
394         fallback_vbs[type] = index;
395         if (index >= mgr->nr_real_vertex_buffers) {
396            mgr->nr_real_vertex_buffers = index + 1;
397         }
398         /*printf("found slot=%i for type=%i\n", index, type);*/
399      }
400   }
401
402   memcpy(mgr->fallback_vbs, fallback_vbs, sizeof(fallback_vbs));
403   return TRUE;
404}
405
406static boolean
407u_vbuf_translate_begin(struct u_vbuf *mgr,
408                       int start_vertex, unsigned num_vertices,
409                       int start_instance, unsigned num_instances,
410                       int start_index, unsigned num_indices, int min_index,
411                       boolean unroll_indices)
412{
413   unsigned mask[VB_NUM] = {0};
414   struct translate_key key[VB_NUM];
415   unsigned elem_index[VB_NUM][PIPE_MAX_ATTRIBS]; /* ... into key.elements */
416   unsigned i, type;
417
418   int start[VB_NUM] = {
419      start_vertex,     /* VERTEX */
420      start_instance,   /* INSTANCE */
421      0                 /* CONST */
422   };
423
424   unsigned num[VB_NUM] = {
425      num_vertices,     /* VERTEX */
426      num_instances,    /* INSTANCE */
427      1                 /* CONST */
428   };
429
430   memset(key, 0, sizeof(key));
431   memset(elem_index, ~0, sizeof(elem_index));
432
433   /* See if there are vertex attribs of each type to translate and
434    * which ones. */
435   for (i = 0; i < mgr->ve->count; i++) {
436      unsigned vb_index = mgr->ve->ve[i].vertex_buffer_index;
437
438      if (!mgr->vertex_buffer[vb_index].stride) {
439         if (!(mgr->ve->incompatible_elem_mask & (1 << i)) &&
440             !(mgr->incompatible_vb_mask & (1 << vb_index))) {
441            continue;
442         }
443         mask[VB_CONST] |= 1 << vb_index;
444      } else if (mgr->ve->ve[i].instance_divisor) {
445         if (!(mgr->ve->incompatible_elem_mask & (1 << i)) &&
446             !(mgr->incompatible_vb_mask & (1 << vb_index))) {
447            continue;
448         }
449         mask[VB_INSTANCE] |= 1 << vb_index;
450      } else {
451         if (!unroll_indices &&
452             !(mgr->ve->incompatible_elem_mask & (1 << i)) &&
453             !(mgr->incompatible_vb_mask & (1 << vb_index))) {
454            continue;
455         }
456         mask[VB_VERTEX] |= 1 << vb_index;
457      }
458   }
459
460   assert(mask[VB_VERTEX] || mask[VB_INSTANCE] || mask[VB_CONST]);
461
462   /* Find free vertex buffer slots. */
463   if (!u_vbuf_translate_find_free_vb_slots(mgr, mask)) {
464      return FALSE;
465   }
466
467   /* Initialize the translate keys. */
468   for (i = 0; i < mgr->ve->count; i++) {
469      struct translate_key *k;
470      struct translate_element *te;
471      unsigned bit, vb_index = mgr->ve->ve[i].vertex_buffer_index;
472      bit = 1 << vb_index;
473
474      if (!(mgr->ve->incompatible_elem_mask & (1 << i)) &&
475          !(mgr->incompatible_vb_mask & (1 << vb_index)) &&
476          (!unroll_indices || !(mask[VB_VERTEX] & bit))) {
477         continue;
478      }
479
480      /* Set type to what we will translate.
481       * Whether vertex, instance, or constant attribs. */
482      for (type = 0; type < VB_NUM; type++) {
483         if (mask[type] & bit) {
484            break;
485         }
486      }
487      assert(type < VB_NUM);
488      assert(translate_is_output_format_supported(mgr->ve->native_format[i]));
489      /*printf("velem=%i type=%i\n", i, type);*/
490
491      /* Add the vertex element. */
492      k = &key[type];
493      elem_index[type][i] = k->nr_elements;
494
495      te = &k->element[k->nr_elements];
496      te->type = TRANSLATE_ELEMENT_NORMAL;
497      te->instance_divisor = 0;
498      te->input_buffer = vb_index;
499      te->input_format = mgr->ve->ve[i].src_format;
500      te->input_offset = mgr->ve->ve[i].src_offset;
501      te->output_format = mgr->ve->native_format[i];
502      te->output_offset = k->output_stride;
503
504      k->output_stride += mgr->ve->native_format_size[i];
505      k->nr_elements++;
506   }
507
508   /* Translate buffers. */
509   for (type = 0; type < VB_NUM; type++) {
510      if (key[type].nr_elements) {
511         u_vbuf_translate_buffers(mgr, &key[type], mask[type],
512                                  mgr->fallback_vbs[type],
513                                  start[type], num[type],
514                                  start_index, num_indices, min_index,
515                                  unroll_indices && type == VB_VERTEX);
516
517         /* Fixup the stride for constant attribs. */
518         if (type == VB_CONST) {
519            mgr->real_vertex_buffer[mgr->fallback_vbs[VB_CONST]].stride = 0;
520         }
521      }
522   }
523
524   /* Setup new vertex elements. */
525   for (i = 0; i < mgr->ve->count; i++) {
526      for (type = 0; type < VB_NUM; type++) {
527         if (elem_index[type][i] < key[type].nr_elements) {
528            struct translate_element *te = &key[type].element[elem_index[type][i]];
529            mgr->fallback_velems[i].instance_divisor = mgr->ve->ve[i].instance_divisor;
530            mgr->fallback_velems[i].src_format = te->output_format;
531            mgr->fallback_velems[i].src_offset = te->output_offset;
532            mgr->fallback_velems[i].vertex_buffer_index = mgr->fallback_vbs[type];
533
534            /* elem_index[type][i] can only be set for one type. */
535            assert(type > VB_INSTANCE || elem_index[type+1][i] == ~0);
536            assert(type > VB_VERTEX   || elem_index[type+2][i] == ~0);
537            break;
538         }
539      }
540      /* No translating, just copy the original vertex element over. */
541      if (type == VB_NUM) {
542         memcpy(&mgr->fallback_velems[i], &mgr->ve->ve[i],
543                sizeof(struct pipe_vertex_element));
544      }
545   }
546
547   u_vbuf_set_vertex_elements_internal(mgr, mgr->ve->count,
548                                       mgr->fallback_velems);
549   mgr->using_translate = TRUE;
550   return TRUE;
551}
552
553static void u_vbuf_translate_end(struct u_vbuf *mgr)
554{
555   unsigned i;
556
557   /* Restore vertex elements. */
558   mgr->pipe->bind_vertex_elements_state(mgr->pipe, mgr->ve->driver_cso);
559   mgr->using_translate = FALSE;
560
561   /* Unreference the now-unused VBOs. */
562   for (i = 0; i < VB_NUM; i++) {
563      unsigned vb = mgr->fallback_vbs[i];
564      if (vb != ~0) {
565         pipe_resource_reference(&mgr->real_vertex_buffer[vb].buffer, NULL);
566         mgr->fallback_vbs[i] = ~0;
567      }
568   }
569   mgr->nr_real_vertex_buffers = mgr->nr_vertex_buffers;
570}
571
572#define FORMAT_REPLACE(what, withwhat) \
573    case PIPE_FORMAT_##what: format = PIPE_FORMAT_##withwhat; break
574
575static void *
576u_vbuf_create_vertex_elements(struct u_vbuf *mgr, unsigned count,
577                              const struct pipe_vertex_element *attribs)
578{
579   struct pipe_context *pipe = mgr->pipe;
580   unsigned i;
581   struct pipe_vertex_element driver_attribs[PIPE_MAX_ATTRIBS];
582   struct u_vbuf_elements *ve = CALLOC_STRUCT(u_vbuf_elements);
583   uint32_t used_buffers = 0;
584
585   ve->count = count;
586
587   memcpy(ve->ve, attribs, sizeof(struct pipe_vertex_element) * count);
588   memcpy(driver_attribs, attribs, sizeof(struct pipe_vertex_element) * count);
589
590   /* Set the best native format in case the original format is not
591    * supported. */
592   for (i = 0; i < count; i++) {
593      enum pipe_format format = ve->ve[i].src_format;
594
595      ve->src_format_size[i] = util_format_get_blocksize(format);
596
597      used_buffers |= 1 << ve->ve[i].vertex_buffer_index;
598
599      if (!ve->ve[i].instance_divisor) {
600         ve->noninstance_vb_mask_any |= 1 << ve->ve[i].vertex_buffer_index;
601      }
602
603      /* Choose a native format.
604       * For now we don't care about the alignment, that's going to
605       * be sorted out later. */
606      if (!mgr->caps.format_fixed32) {
607         switch (format) {
608            FORMAT_REPLACE(R32_FIXED,           R32_FLOAT);
609            FORMAT_REPLACE(R32G32_FIXED,        R32G32_FLOAT);
610            FORMAT_REPLACE(R32G32B32_FIXED,     R32G32B32_FLOAT);
611            FORMAT_REPLACE(R32G32B32A32_FIXED,  R32G32B32A32_FLOAT);
612            default:;
613         }
614      }
615      if (!mgr->caps.format_float16) {
616         switch (format) {
617            FORMAT_REPLACE(R16_FLOAT,           R32_FLOAT);
618            FORMAT_REPLACE(R16G16_FLOAT,        R32G32_FLOAT);
619            FORMAT_REPLACE(R16G16B16_FLOAT,     R32G32B32_FLOAT);
620            FORMAT_REPLACE(R16G16B16A16_FLOAT,  R32G32B32A32_FLOAT);
621            default:;
622         }
623      }
624      if (!mgr->caps.format_float64) {
625         switch (format) {
626            FORMAT_REPLACE(R64_FLOAT,           R32_FLOAT);
627            FORMAT_REPLACE(R64G64_FLOAT,        R32G32_FLOAT);
628            FORMAT_REPLACE(R64G64B64_FLOAT,     R32G32B32_FLOAT);
629            FORMAT_REPLACE(R64G64B64A64_FLOAT,  R32G32B32A32_FLOAT);
630            default:;
631         }
632      }
633      if (!mgr->caps.format_norm32) {
634         switch (format) {
635            FORMAT_REPLACE(R32_UNORM,           R32_FLOAT);
636            FORMAT_REPLACE(R32G32_UNORM,        R32G32_FLOAT);
637            FORMAT_REPLACE(R32G32B32_UNORM,     R32G32B32_FLOAT);
638            FORMAT_REPLACE(R32G32B32A32_UNORM,  R32G32B32A32_FLOAT);
639            FORMAT_REPLACE(R32_SNORM,           R32_FLOAT);
640            FORMAT_REPLACE(R32G32_SNORM,        R32G32_FLOAT);
641            FORMAT_REPLACE(R32G32B32_SNORM,     R32G32B32_FLOAT);
642            FORMAT_REPLACE(R32G32B32A32_SNORM,  R32G32B32A32_FLOAT);
643            default:;
644         }
645      }
646      if (!mgr->caps.format_scaled32) {
647         switch (format) {
648            FORMAT_REPLACE(R32_USCALED,         R32_FLOAT);
649            FORMAT_REPLACE(R32G32_USCALED,      R32G32_FLOAT);
650            FORMAT_REPLACE(R32G32B32_USCALED,   R32G32B32_FLOAT);
651            FORMAT_REPLACE(R32G32B32A32_USCALED,R32G32B32A32_FLOAT);
652            FORMAT_REPLACE(R32_SSCALED,         R32_FLOAT);
653            FORMAT_REPLACE(R32G32_SSCALED,      R32G32_FLOAT);
654            FORMAT_REPLACE(R32G32B32_SSCALED,   R32G32B32_FLOAT);
655            FORMAT_REPLACE(R32G32B32A32_SSCALED,R32G32B32A32_FLOAT);
656            default:;
657         }
658      }
659
660      driver_attribs[i].src_format = format;
661      ve->native_format[i] = format;
662      ve->native_format_size[i] =
663            util_format_get_blocksize(ve->native_format[i]);
664
665      if (ve->ve[i].src_format != format ||
666          (!mgr->caps.velem_src_offset_unaligned &&
667           ve->ve[i].src_offset % 4 != 0)) {
668         ve->incompatible_elem_mask |= 1 << i;
669         ve->incompatible_vb_mask_any |= 1 << ve->ve[i].vertex_buffer_index;
670      } else {
671         ve->compatible_vb_mask_any |= 1 << ve->ve[i].vertex_buffer_index;
672      }
673   }
674
675   ve->compatible_vb_mask_all = ~ve->incompatible_vb_mask_any & used_buffers;
676   ve->incompatible_vb_mask_all = ~ve->compatible_vb_mask_any & used_buffers;
677
678   /* Align the formats to the size of DWORD if needed. */
679   if (!mgr->caps.velem_src_offset_unaligned) {
680      for (i = 0; i < count; i++) {
681         ve->native_format_size[i] = align(ve->native_format_size[i], 4);
682      }
683   }
684
685   ve->driver_cso =
686      pipe->create_vertex_elements_state(pipe, count, driver_attribs);
687   return ve;
688}
689
690static void u_vbuf_delete_vertex_elements(struct u_vbuf *mgr, void *cso)
691{
692   struct pipe_context *pipe = mgr->pipe;
693   struct u_vbuf_elements *ve = cso;
694
695   pipe->delete_vertex_elements_state(pipe, ve->driver_cso);
696   FREE(ve);
697}
698
699void u_vbuf_set_vertex_buffers(struct u_vbuf *mgr, unsigned count,
700                               const struct pipe_vertex_buffer *bufs)
701{
702   unsigned i;
703
704   mgr->user_vb_mask = 0;
705   mgr->incompatible_vb_mask = 0;
706   mgr->nonzero_stride_vb_mask = 0;
707
708   for (i = 0; i < count; i++) {
709      const struct pipe_vertex_buffer *vb = &bufs[i];
710      struct pipe_vertex_buffer *orig_vb = &mgr->vertex_buffer[i];
711      struct pipe_vertex_buffer *real_vb = &mgr->real_vertex_buffer[i];
712
713      pipe_resource_reference(&orig_vb->buffer, vb->buffer);
714
715      real_vb->buffer_offset = orig_vb->buffer_offset = vb->buffer_offset;
716      real_vb->stride = orig_vb->stride = vb->stride;
717
718      if (vb->stride) {
719         mgr->nonzero_stride_vb_mask |= 1 << i;
720      }
721
722      if (!vb->buffer) {
723         pipe_resource_reference(&real_vb->buffer, NULL);
724         continue;
725      }
726
727      if ((!mgr->caps.buffer_offset_unaligned && vb->buffer_offset % 4 != 0) ||
728          (!mgr->caps.buffer_stride_unaligned && vb->stride % 4 != 0)) {
729         mgr->incompatible_vb_mask |= 1 << i;
730         pipe_resource_reference(&real_vb->buffer, NULL);
731         continue;
732      }
733
734      if (!mgr->caps.user_vertex_buffers && vb->buffer->user_ptr) {
735         mgr->user_vb_mask |= 1 << i;
736         pipe_resource_reference(&real_vb->buffer, NULL);
737         continue;
738      }
739
740      pipe_resource_reference(&real_vb->buffer, vb->buffer);
741   }
742
743   for (i = count; i < mgr->nr_vertex_buffers; i++) {
744      pipe_resource_reference(&mgr->vertex_buffer[i].buffer, NULL);
745   }
746   for (i = count; i < mgr->nr_real_vertex_buffers; i++) {
747      pipe_resource_reference(&mgr->real_vertex_buffer[i].buffer, NULL);
748   }
749
750   mgr->nr_vertex_buffers = count;
751   mgr->nr_real_vertex_buffers = count;
752   mgr->vertex_buffers_dirty = TRUE;
753}
754
755void u_vbuf_set_index_buffer(struct u_vbuf *mgr,
756                             const struct pipe_index_buffer *ib)
757{
758   struct pipe_context *pipe = mgr->pipe;
759
760   if (ib && ib->buffer) {
761      assert(ib->offset % ib->index_size == 0);
762      pipe_resource_reference(&mgr->index_buffer.buffer, ib->buffer);
763      mgr->index_buffer.offset = ib->offset;
764      mgr->index_buffer.index_size = ib->index_size;
765   } else {
766      pipe_resource_reference(&mgr->index_buffer.buffer, NULL);
767   }
768
769   pipe->set_index_buffer(pipe, ib);
770}
771
772static void
773u_vbuf_upload_buffers(struct u_vbuf *mgr,
774                      int start_vertex, unsigned num_vertices,
775                      int start_instance, unsigned num_instances)
776{
777   unsigned i;
778   unsigned nr_velems = mgr->ve->count;
779   unsigned nr_vbufs = mgr->nr_vertex_buffers;
780   struct pipe_vertex_element *velems =
781         mgr->using_translate ? mgr->fallback_velems : mgr->ve->ve;
782   unsigned start_offset[PIPE_MAX_ATTRIBS];
783   unsigned end_offset[PIPE_MAX_ATTRIBS] = {0};
784
785   /* Determine how much data needs to be uploaded. */
786   for (i = 0; i < nr_velems; i++) {
787      struct pipe_vertex_element *velem = &velems[i];
788      unsigned index = velem->vertex_buffer_index;
789      struct pipe_vertex_buffer *vb = &mgr->vertex_buffer[index];
790      unsigned instance_div, first, size;
791
792      /* Skip the buffers generated by translate. */
793      if (index == mgr->fallback_vbs[VB_VERTEX] ||
794          index == mgr->fallback_vbs[VB_INSTANCE] ||
795          index == mgr->fallback_vbs[VB_CONST]) {
796         continue;
797      }
798
799      assert(vb->buffer);
800
801      if (!vb->buffer->user_ptr) {
802         continue;
803      }
804
805      instance_div = velem->instance_divisor;
806      first = vb->buffer_offset + velem->src_offset;
807
808      if (!vb->stride) {
809         /* Constant attrib. */
810         size = mgr->ve->src_format_size[i];
811      } else if (instance_div) {
812         /* Per-instance attrib. */
813         unsigned count = (num_instances + instance_div - 1) / instance_div;
814         first += vb->stride * start_instance;
815         size = vb->stride * (count - 1) + mgr->ve->src_format_size[i];
816      } else {
817         /* Per-vertex attrib. */
818         first += vb->stride * start_vertex;
819         size = vb->stride * (num_vertices - 1) + mgr->ve->src_format_size[i];
820      }
821
822      /* Update offsets. */
823      if (!end_offset[index]) {
824         start_offset[index] = first;
825         end_offset[index] = first + size;
826      } else {
827         if (first < start_offset[index])
828            start_offset[index] = first;
829         if (first + size > end_offset[index])
830            end_offset[index] = first + size;
831      }
832   }
833
834   /* Upload buffers. */
835   for (i = 0; i < nr_vbufs; i++) {
836      unsigned start, end = end_offset[i];
837      struct pipe_vertex_buffer *real_vb;
838      uint8_t *ptr;
839
840      if (!end) {
841         continue;
842      }
843
844      start = start_offset[i];
845      assert(start < end);
846
847      real_vb = &mgr->real_vertex_buffer[i];
848      ptr = mgr->vertex_buffer[i].buffer->user_ptr;
849
850      u_upload_data(mgr->uploader, start, end - start, ptr + start,
851                    &real_vb->buffer_offset, &real_vb->buffer);
852
853      real_vb->buffer_offset -= start;
854   }
855}
856
857static boolean u_vbuf_need_minmax_index(struct u_vbuf *mgr)
858{
859   /* See if there are any per-vertex attribs which will be uploaded or
860    * translated. Use bitmasks to get the info instead of looping over vertex
861    * elements. */
862   return ((mgr->user_vb_mask | mgr->incompatible_vb_mask |
863            mgr->ve->incompatible_vb_mask_any) &
864           mgr->ve->noninstance_vb_mask_any & mgr->nonzero_stride_vb_mask) != 0;
865}
866
867static boolean u_vbuf_mapping_vertex_buffer_blocks(struct u_vbuf *mgr)
868{
869   /* Return true if there are hw buffers which don't need to be translated.
870    *
871    * We could query whether each buffer is busy, but that would
872    * be way more costly than this. */
873   return (~mgr->user_vb_mask & ~mgr->incompatible_vb_mask &
874           mgr->ve->compatible_vb_mask_all & mgr->ve->noninstance_vb_mask_any &
875           mgr->nonzero_stride_vb_mask) != 0;
876}
877
878static void u_vbuf_get_minmax_index(struct pipe_context *pipe,
879                                    struct pipe_index_buffer *ib,
880                                    const struct pipe_draw_info *info,
881                                    int *out_min_index,
882                                    int *out_max_index)
883{
884   struct pipe_transfer *transfer = NULL;
885   const void *indices;
886   unsigned i;
887   unsigned restart_index = info->restart_index;
888
889   if (ib->buffer->user_ptr) {
890      indices = ib->buffer->user_ptr +
891                ib->offset + info->start * ib->index_size;
892   } else {
893      indices = pipe_buffer_map_range(pipe, ib->buffer,
894                                      ib->offset + info->start * ib->index_size,
895                                      info->count * ib->index_size,
896                                      PIPE_TRANSFER_READ, &transfer);
897   }
898
899   switch (ib->index_size) {
900   case 4: {
901      const unsigned *ui_indices = (const unsigned*)indices;
902      unsigned max_ui = 0;
903      unsigned min_ui = ~0U;
904      if (info->primitive_restart) {
905         for (i = 0; i < info->count; i++) {
906            if (ui_indices[i] != restart_index) {
907               if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
908               if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
909            }
910         }
911      }
912      else {
913         for (i = 0; i < info->count; i++) {
914            if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
915            if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
916         }
917      }
918      *out_min_index = min_ui;
919      *out_max_index = max_ui;
920      break;
921   }
922   case 2: {
923      const unsigned short *us_indices = (const unsigned short*)indices;
924      unsigned max_us = 0;
925      unsigned min_us = ~0U;
926      if (info->primitive_restart) {
927         for (i = 0; i < info->count; i++) {
928            if (us_indices[i] != restart_index) {
929               if (us_indices[i] > max_us) max_us = us_indices[i];
930               if (us_indices[i] < min_us) min_us = us_indices[i];
931            }
932         }
933      }
934      else {
935         for (i = 0; i < info->count; i++) {
936            if (us_indices[i] > max_us) max_us = us_indices[i];
937            if (us_indices[i] < min_us) min_us = us_indices[i];
938         }
939      }
940      *out_min_index = min_us;
941      *out_max_index = max_us;
942      break;
943   }
944   case 1: {
945      const unsigned char *ub_indices = (const unsigned char*)indices;
946      unsigned max_ub = 0;
947      unsigned min_ub = ~0U;
948      if (info->primitive_restart) {
949         for (i = 0; i < info->count; i++) {
950            if (ub_indices[i] != restart_index) {
951               if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
952               if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
953            }
954         }
955      }
956      else {
957         for (i = 0; i < info->count; i++) {
958            if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
959            if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
960         }
961      }
962      *out_min_index = min_ub;
963      *out_max_index = max_ub;
964      break;
965   }
966   default:
967      assert(0);
968      *out_min_index = 0;
969      *out_max_index = 0;
970   }
971
972   if (transfer) {
973      pipe_buffer_unmap(pipe, transfer);
974   }
975}
976
977void u_vbuf_draw_vbo(struct u_vbuf *mgr, const struct pipe_draw_info *info)
978{
979   struct pipe_context *pipe = mgr->pipe;
980   int start_vertex, min_index;
981   unsigned num_vertices;
982   boolean unroll_indices = FALSE;
983
984   /* Normal draw. No fallback and no user buffers. */
985   if (!mgr->incompatible_vb_mask &&
986       !mgr->ve->incompatible_elem_mask &&
987       !mgr->user_vb_mask) {
988      /* Set vertex buffers if needed. */
989      if (mgr->vertex_buffers_dirty) {
990         pipe->set_vertex_buffers(pipe, mgr->nr_real_vertex_buffers,
991                                  mgr->real_vertex_buffer);
992         mgr->vertex_buffers_dirty = FALSE;
993      }
994
995      pipe->draw_vbo(pipe, info);
996      return;
997   }
998
999   if (info->indexed) {
1000      /* See if anything needs to be done for per-vertex attribs. */
1001      if (u_vbuf_need_minmax_index(mgr)) {
1002         int max_index;
1003
1004         if (info->max_index != ~0) {
1005            min_index = info->min_index;
1006            max_index = info->max_index;
1007         } else {
1008            u_vbuf_get_minmax_index(mgr->pipe, &mgr->index_buffer, info,
1009                                    &min_index, &max_index);
1010         }
1011
1012         assert(min_index <= max_index);
1013
1014         start_vertex = min_index + info->index_bias;
1015         num_vertices = max_index + 1 - min_index;
1016
1017         /* Primitive restart doesn't work when unrolling indices.
1018          * We would have to break this drawing operation into several ones. */
1019         /* Use some heuristic to see if unrolling indices improves
1020          * performance. */
1021         if (!info->primitive_restart &&
1022             num_vertices > info->count*2 &&
1023             num_vertices-info->count > 32 &&
1024             !u_vbuf_mapping_vertex_buffer_blocks(mgr)) {
1025            /*printf("num_vertices=%i count=%i\n", num_vertices, info->count);*/
1026            unroll_indices = TRUE;
1027         }
1028      } else {
1029         /* Nothing to do for per-vertex attribs. */
1030         start_vertex = 0;
1031         num_vertices = 0;
1032         min_index = 0;
1033      }
1034   } else {
1035      start_vertex = info->start;
1036      num_vertices = info->count;
1037      min_index = 0;
1038   }
1039
1040   /* Translate vertices with non-native layouts or formats. */
1041   if (unroll_indices ||
1042       mgr->incompatible_vb_mask ||
1043       mgr->ve->incompatible_elem_mask) {
1044      /* XXX check the return value */
1045      u_vbuf_translate_begin(mgr, start_vertex, num_vertices,
1046                             info->start_instance, info->instance_count,
1047                             info->start, info->count, min_index,
1048                             unroll_indices);
1049   }
1050
1051   /* Upload user buffers. */
1052   if (mgr->user_vb_mask) {
1053      u_vbuf_upload_buffers(mgr, start_vertex, num_vertices,
1054                            info->start_instance, info->instance_count);
1055   }
1056
1057   /*
1058   if (unroll_indices) {
1059      printf("unrolling indices: start_vertex = %i, num_vertices = %i\n",
1060             start_vertex, num_vertices);
1061      util_dump_draw_info(stdout, info);
1062      printf("\n");
1063   }
1064
1065   unsigned i;
1066   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
1067      printf("input %i: ", i);
1068      util_dump_vertex_buffer(stdout, mgr->vertex_buffer+i);
1069      printf("\n");
1070   }
1071   for (i = 0; i < mgr->nr_real_vertex_buffers; i++) {
1072      printf("real %i: ", i);
1073      util_dump_vertex_buffer(stdout, mgr->real_vertex_buffer+i);
1074      printf("\n");
1075   }
1076   */
1077
1078   u_upload_unmap(mgr->uploader);
1079   pipe->set_vertex_buffers(pipe, mgr->nr_real_vertex_buffers,
1080                            mgr->real_vertex_buffer);
1081
1082   if (unlikely(unroll_indices)) {
1083      struct pipe_draw_info new_info = *info;
1084      new_info.indexed = FALSE;
1085      new_info.index_bias = 0;
1086      new_info.min_index = 0;
1087      new_info.max_index = info->count - 1;
1088      new_info.start = 0;
1089
1090      pipe->draw_vbo(pipe, &new_info);
1091   } else {
1092      pipe->draw_vbo(pipe, info);
1093   }
1094
1095   if (mgr->using_translate) {
1096      u_vbuf_translate_end(mgr);
1097   }
1098   mgr->vertex_buffers_dirty = TRUE;
1099}
1100
1101void u_vbuf_save_vertex_elements(struct u_vbuf *mgr)
1102{
1103   assert(!mgr->ve_saved);
1104   mgr->ve_saved = mgr->ve;
1105}
1106
1107void u_vbuf_restore_vertex_elements(struct u_vbuf *mgr)
1108{
1109   if (mgr->ve != mgr->ve_saved) {
1110      struct pipe_context *pipe = mgr->pipe;
1111
1112      mgr->ve = mgr->ve_saved;
1113      pipe->bind_vertex_elements_state(pipe,
1114                                       mgr->ve ? mgr->ve->driver_cso : NULL);
1115   }
1116   mgr->ve_saved = NULL;
1117}
1118
1119void u_vbuf_save_vertex_buffers(struct u_vbuf *mgr)
1120{
1121   util_copy_vertex_buffers(mgr->vertex_buffer_saved,
1122                            &mgr->nr_vertex_buffers_saved,
1123                            mgr->vertex_buffer,
1124                            mgr->nr_vertex_buffers);
1125}
1126
1127void u_vbuf_restore_vertex_buffers(struct u_vbuf *mgr)
1128{
1129   unsigned i;
1130
1131   u_vbuf_set_vertex_buffers(mgr, mgr->nr_vertex_buffers_saved,
1132                             mgr->vertex_buffer_saved);
1133   for (i = 0; i < mgr->nr_vertex_buffers_saved; i++) {
1134      pipe_resource_reference(&mgr->vertex_buffer_saved[i].buffer, NULL);
1135   }
1136   mgr->nr_vertex_buffers_saved = 0;
1137}
1138