r300_render.c revision 66d45567b4e2c6f2585789b68667e6c00b7567e1
1/*
2 * Copyright 2009 Corbin Simpson <MostAwesomeDude@gmail.com>
3 * Copyright 2010 Marek Olšák <maraeo@gmail.com>
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * on the rights to use, copy, modify, merge, publish, distribute, sub
9 * license, and/or sell copies of the Software, and to permit persons to whom
10 * the Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
14 * Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22 * USE OR OTHER DEALINGS IN THE SOFTWARE. */
23
24/* r300_render: Vertex and index buffer primitive emission. Contains both
25 * HW TCL fastpath rendering, and SW TCL Draw-assisted rendering. */
26
27#include "draw/draw_context.h"
28#include "draw/draw_vbuf.h"
29
30#include "util/u_inlines.h"
31
32#include "util/u_format.h"
33#include "util/u_memory.h"
34#include "util/u_upload_mgr.h"
35#include "util/u_prim.h"
36
37#include "r300_cs.h"
38#include "r300_context.h"
39#include "r300_screen_buffer.h"
40#include "r300_emit.h"
41#include "r300_reg.h"
42#include "r300_state_derived.h"
43
44#include <limits.h>
45
46#define IMMD_DWORDS 32
47
48static uint32_t r300_translate_primitive(unsigned prim)
49{
50    switch (prim) {
51        case PIPE_PRIM_POINTS:
52            return R300_VAP_VF_CNTL__PRIM_POINTS;
53        case PIPE_PRIM_LINES:
54            return R300_VAP_VF_CNTL__PRIM_LINES;
55        case PIPE_PRIM_LINE_LOOP:
56            return R300_VAP_VF_CNTL__PRIM_LINE_LOOP;
57        case PIPE_PRIM_LINE_STRIP:
58            return R300_VAP_VF_CNTL__PRIM_LINE_STRIP;
59        case PIPE_PRIM_TRIANGLES:
60            return R300_VAP_VF_CNTL__PRIM_TRIANGLES;
61        case PIPE_PRIM_TRIANGLE_STRIP:
62            return R300_VAP_VF_CNTL__PRIM_TRIANGLE_STRIP;
63        case PIPE_PRIM_TRIANGLE_FAN:
64            return R300_VAP_VF_CNTL__PRIM_TRIANGLE_FAN;
65        case PIPE_PRIM_QUADS:
66            return R300_VAP_VF_CNTL__PRIM_QUADS;
67        case PIPE_PRIM_QUAD_STRIP:
68            return R300_VAP_VF_CNTL__PRIM_QUAD_STRIP;
69        case PIPE_PRIM_POLYGON:
70            return R300_VAP_VF_CNTL__PRIM_POLYGON;
71        default:
72            return 0;
73    }
74}
75
76static uint32_t r300_provoking_vertex_fixes(struct r300_context *r300,
77                                            unsigned mode)
78{
79    struct r300_rs_state* rs = (struct r300_rs_state*)r300->rs_state.state;
80    uint32_t color_control = rs->color_control;
81
82    /* By default (see r300_state.c:r300_create_rs_state) color_control is
83     * initialized to provoking the first vertex.
84     *
85     * Triangle fans must be reduced to the second vertex, not the first, in
86     * Gallium flatshade-first mode, as per the GL spec.
87     * (http://www.opengl.org/registry/specs/ARB/provoking_vertex.txt)
88     *
89     * Quads never provoke correctly in flatshade-first mode. The first
90     * vertex is never considered as provoking, so only the second, third,
91     * and fourth vertices can be selected, and both "third" and "last" modes
92     * select the fourth vertex. This is probably due to D3D lacking quads.
93     *
94     * Similarly, polygons reduce to the first, not the last, vertex, when in
95     * "last" mode, and all other modes start from the second vertex.
96     *
97     * ~ C.
98     */
99
100    if (rs->rs.flatshade_first) {
101        switch (mode) {
102            case PIPE_PRIM_TRIANGLE_FAN:
103                color_control |= R300_GA_COLOR_CONTROL_PROVOKING_VERTEX_SECOND;
104                break;
105            case PIPE_PRIM_QUADS:
106            case PIPE_PRIM_QUAD_STRIP:
107            case PIPE_PRIM_POLYGON:
108                color_control |= R300_GA_COLOR_CONTROL_PROVOKING_VERTEX_LAST;
109                break;
110            default:
111                color_control |= R300_GA_COLOR_CONTROL_PROVOKING_VERTEX_FIRST;
112                break;
113        }
114    } else {
115        color_control |= R300_GA_COLOR_CONTROL_PROVOKING_VERTEX_LAST;
116    }
117
118    return color_control;
119}
120
121void r500_emit_index_bias(struct r300_context *r300, int index_bias)
122{
123    CS_LOCALS(r300);
124
125    BEGIN_CS(2);
126    OUT_CS_REG(R500_VAP_INDEX_OFFSET,
127               (index_bias & 0xFFFFFF) | (index_bias < 0 ? 1<<24 : 0));
128    END_CS;
129}
130
131/* This function splits the index bias value into two parts:
132 * - buffer_offset: the value that can be safely added to buffer offsets
133 *   in r300_emit_aos (it must yield a positive offset when added to
134 *   a vertex buffer offset)
135 * - index_offset: the value that must be manually subtracted from indices
136 *   in an index buffer to achieve negative offsets. */
137static void r300_split_index_bias(struct r300_context *r300, int index_bias,
138                                  int *buffer_offset, int *index_offset)
139{
140    struct pipe_vertex_buffer *vb, *vbufs = r300->vertex_buffer;
141    struct pipe_vertex_element *velem = r300->velems->velem;
142    unsigned i, size;
143    int max_neg_bias;
144
145    if (index_bias < 0) {
146        /* See how large index bias we may subtract. We must be careful
147         * here because negative buffer offsets are not allowed
148         * by the DRM API. */
149        max_neg_bias = INT_MAX;
150        for (i = 0; i < r300->velems->count; i++) {
151            vb = &vbufs[velem[i].vertex_buffer_index];
152            size = (vb->buffer_offset + velem[i].src_offset) / vb->stride;
153            max_neg_bias = MIN2(max_neg_bias, size);
154        }
155
156        /* Now set the minimum allowed value. */
157        *buffer_offset = MAX2(-max_neg_bias, index_bias);
158    } else {
159        /* A positive index bias is OK. */
160        *buffer_offset = index_bias;
161    }
162
163    *index_offset = index_bias - *buffer_offset;
164}
165
166enum r300_prepare_flags {
167    PREP_FIRST_DRAW     = (1 << 0), /* call emit_dirty_state and friends? */
168    PREP_VALIDATE_VBOS  = (1 << 1), /* validate VBOs? */
169    PREP_EMIT_AOS       = (1 << 2), /* call emit_aos? */
170    PREP_EMIT_AOS_SWTCL = (1 << 3), /* call emit_aos_swtcl? */
171    PREP_INDEXED        = (1 << 4)  /* is this draw_elements? */
172};
173
174/**
175 * Check if the requested number of dwords is available in the CS and
176 * if not, flush.
177 * \param r300          The context.
178 * \param flags         See r300_prepare_flags.
179 * \param cs_dwords     The number of dwords to reserve in CS.
180 * \return TRUE if the CS was flushed
181 */
182static boolean r300_reserve_cs_dwords(struct r300_context *r300,
183                                   enum r300_prepare_flags flags,
184                                   unsigned cs_dwords)
185{
186    boolean flushed        = FALSE;
187    boolean first_draw     = flags & PREP_FIRST_DRAW;
188    boolean emit_aos       = flags & PREP_EMIT_AOS;
189    boolean emit_aos_swtcl = flags & PREP_EMIT_AOS_SWTCL;
190
191    /* Add dirty state, index offset, and AOS. */
192    if (first_draw) {
193        cs_dwords += r300_get_num_dirty_dwords(r300);
194
195        if (r300->screen->caps.index_bias_supported)
196            cs_dwords += 2; /* emit_index_offset */
197
198        if (emit_aos)
199            cs_dwords += 55; /* emit_aos */
200
201        if (emit_aos_swtcl)
202            cs_dwords += 7; /* emit_aos_swtcl */
203    }
204
205    cs_dwords += r300_get_num_cs_end_dwords(r300);
206
207    /* Reserve requested CS space. */
208    if (cs_dwords > (R300_MAX_CMDBUF_DWORDS - r300->cs->cdw)) {
209        r300->context.flush(&r300->context, 0, NULL);
210        flushed = TRUE;
211    }
212
213    return flushed;
214}
215
216/**
217 * Validate buffers and emit dirty state.
218 * \param r300          The context.
219 * \param flags         See r300_prepare_flags.
220 * \param index_buffer  The index buffer to validate. The parameter may be NULL.
221 * \param aos_offset    The offset passed to emit_aos.
222 * \param index_bias    The index bias to emit.
223 * \return TRUE if rendering should be skipped
224 */
225static boolean r300_emit_states(struct r300_context *r300,
226                                enum r300_prepare_flags flags,
227                                struct pipe_resource *index_buffer,
228                                int aos_offset,
229                                int index_bias)
230{
231    boolean first_draw     = flags & PREP_FIRST_DRAW;
232    boolean emit_aos       = flags & PREP_EMIT_AOS;
233    boolean emit_aos_swtcl = flags & PREP_EMIT_AOS_SWTCL;
234    boolean indexed        = flags & PREP_INDEXED;
235
236    /* Validate buffers and emit dirty state if needed. */
237    if (first_draw) {
238        if (!r300_emit_buffer_validate(r300, flags & PREP_VALIDATE_VBOS,
239                                       index_buffer)) {
240            fprintf(stderr, "r300: CS space validation failed. "
241                    "(not enough memory?) Skipping rendering.\n");
242            return FALSE;
243        }
244
245        r300_emit_dirty_state(r300);
246        if (r300->screen->caps.index_bias_supported) {
247            if (r300->screen->caps.has_tcl)
248                r500_emit_index_bias(r300, index_bias);
249            else
250                r500_emit_index_bias(r300, 0);
251        }
252
253        if (emit_aos)
254            r300_emit_aos(r300, aos_offset, indexed);
255
256        if (emit_aos_swtcl)
257            r300_emit_aos_swtcl(r300, indexed);
258    }
259
260    return TRUE;
261}
262
263/**
264 * Check if the requested number of dwords is available in the CS and
265 * if not, flush. Then validate buffers and emit dirty state.
266 * \param r300          The context.
267 * \param flags         See r300_prepare_flags.
268 * \param index_buffer  The index buffer to validate. The parameter may be NULL.
269 * \param cs_dwords     The number of dwords to reserve in CS.
270 * \param aos_offset    The offset passed to emit_aos.
271 * \param index_bias    The index bias to emit.
272 * \return TRUE if rendering should be skipped
273 */
274static boolean r300_prepare_for_rendering(struct r300_context *r300,
275                                          enum r300_prepare_flags flags,
276                                          struct pipe_resource *index_buffer,
277                                          unsigned cs_dwords,
278                                          int aos_offset,
279                                          int index_bias)
280{
281    if (r300_reserve_cs_dwords(r300, flags, cs_dwords))
282        flags |= PREP_FIRST_DRAW;
283
284    return r300_emit_states(r300, flags, index_buffer, aos_offset, index_bias);
285}
286
287static boolean immd_is_good_idea(struct r300_context *r300,
288                                 unsigned count)
289{
290    struct pipe_vertex_element* velem;
291    struct pipe_vertex_buffer* vbuf;
292    boolean checked[PIPE_MAX_ATTRIBS] = {0};
293    unsigned vertex_element_count = r300->velems->count;
294    unsigned i, vbi;
295
296    if (DBG_ON(r300, DBG_NO_IMMD)) {
297        return FALSE;
298    }
299
300    if (r300->draw) {
301        return FALSE;
302    }
303
304    if (count * r300->velems->vertex_size_dwords > IMMD_DWORDS) {
305        return FALSE;
306    }
307
308    /* We shouldn't map buffers referenced by CS, busy buffers,
309     * and ones placed in VRAM. */
310    for (i = 0; i < vertex_element_count; i++) {
311        velem = &r300->velems->velem[i];
312        vbi = velem->vertex_buffer_index;
313
314        if (!checked[vbi]) {
315            vbuf = &r300->vertex_buffer[vbi];
316
317            if (!(r300_buffer(vbuf->buffer)->domain & R300_DOMAIN_GTT)) {
318                return FALSE;
319            }
320
321            if (r300_buffer_is_referenced(&r300->context,
322                                          vbuf->buffer,
323                                          R300_REF_CS | R300_REF_HW)) {
324                /* It's a very bad idea to map it... */
325                return FALSE;
326            }
327            checked[vbi] = TRUE;
328        }
329    }
330    return TRUE;
331}
332
333/*****************************************************************************
334 * The HWTCL draw functions.                                                 *
335 ****************************************************************************/
336
337static void r300_emit_draw_arrays_immediate(struct r300_context *r300,
338                                            unsigned mode,
339                                            unsigned start,
340                                            unsigned count)
341{
342    struct pipe_vertex_element* velem;
343    struct pipe_vertex_buffer* vbuf;
344    unsigned vertex_element_count = r300->velems->count;
345    unsigned i, v, vbi;
346
347    /* Size of the vertex, in dwords. */
348    unsigned vertex_size = r300->velems->vertex_size_dwords;
349
350    /* The number of dwords for this draw operation. */
351    unsigned dwords = 9 + count * vertex_size;
352
353    /* Size of the vertex element, in dwords. */
354    unsigned size[PIPE_MAX_ATTRIBS];
355
356    /* Stride to the same attrib in the next vertex in the vertex buffer,
357     * in dwords. */
358    unsigned stride[PIPE_MAX_ATTRIBS];
359
360    /* Mapped vertex buffers. */
361    uint32_t* map[PIPE_MAX_ATTRIBS];
362    uint32_t* mapelem[PIPE_MAX_ATTRIBS];
363    struct pipe_transfer* transfer[PIPE_MAX_ATTRIBS] = {0};
364
365    CS_LOCALS(r300);
366
367    if (!r300_prepare_for_rendering(r300, PREP_FIRST_DRAW, NULL, dwords, 0, 0))
368        return;
369
370    /* Calculate the vertex size, offsets, strides etc. and map the buffers. */
371    for (i = 0; i < vertex_element_count; i++) {
372        velem = &r300->velems->velem[i];
373        size[i] = r300->velems->hw_format_size[i] / 4;
374        vbi = velem->vertex_buffer_index;
375        vbuf = &r300->vertex_buffer[vbi];
376        stride[i] = vbuf->stride / 4;
377
378        /* Map the buffer. */
379        if (!transfer[vbi]) {
380            map[vbi] = (uint32_t*)pipe_buffer_map(&r300->context,
381                                                  vbuf->buffer,
382                                                  PIPE_TRANSFER_READ,
383						  &transfer[vbi]);
384            map[vbi] += (vbuf->buffer_offset / 4) + stride[i] * start;
385        }
386        mapelem[i] = map[vbi] + (velem->src_offset / 4);
387    }
388
389    BEGIN_CS(dwords);
390    OUT_CS_REG(R300_GA_COLOR_CONTROL,
391            r300_provoking_vertex_fixes(r300, mode));
392    OUT_CS_REG(R300_VAP_VTX_SIZE, vertex_size);
393    OUT_CS_REG_SEQ(R300_VAP_VF_MAX_VTX_INDX, 2);
394    OUT_CS(count - 1);
395    OUT_CS(0);
396    OUT_CS_PKT3(R300_PACKET3_3D_DRAW_IMMD_2, count * vertex_size);
397    OUT_CS(R300_VAP_VF_CNTL__PRIM_WALK_VERTEX_EMBEDDED | (count << 16) |
398            r300_translate_primitive(mode));
399
400    /* Emit vertices. */
401    for (v = 0; v < count; v++) {
402        for (i = 0; i < vertex_element_count; i++) {
403            OUT_CS_TABLE(&mapelem[i][stride[i] * v], size[i]);
404        }
405    }
406    END_CS;
407
408    /* Unmap buffers. */
409    for (i = 0; i < vertex_element_count; i++) {
410        vbi = r300->velems->velem[i].vertex_buffer_index;
411
412        if (transfer[vbi]) {
413            vbuf = &r300->vertex_buffer[vbi];
414            pipe_buffer_unmap(&r300->context, vbuf->buffer, transfer[vbi]);
415            transfer[vbi] = NULL;
416        }
417    }
418}
419
420static void r300_emit_draw_arrays(struct r300_context *r300,
421                                  unsigned mode,
422                                  unsigned count)
423{
424    boolean alt_num_verts = count > 65535;
425    CS_LOCALS(r300);
426
427    if (count >= (1 << 24)) {
428        fprintf(stderr, "r300: Got a huge number of vertices: %i, "
429                "refusing to render.\n", count);
430        return;
431    }
432
433    BEGIN_CS(7 + (alt_num_verts ? 2 : 0));
434    if (alt_num_verts) {
435        OUT_CS_REG(R500_VAP_ALT_NUM_VERTICES, count);
436    }
437    OUT_CS_REG(R300_GA_COLOR_CONTROL,
438            r300_provoking_vertex_fixes(r300, mode));
439    OUT_CS_REG_SEQ(R300_VAP_VF_MAX_VTX_INDX, 2);
440    OUT_CS(count - 1);
441    OUT_CS(0);
442    OUT_CS_PKT3(R300_PACKET3_3D_DRAW_VBUF_2, 0);
443    OUT_CS(R300_VAP_VF_CNTL__PRIM_WALK_VERTEX_LIST | (count << 16) |
444           r300_translate_primitive(mode) |
445           (alt_num_verts ? R500_VAP_VF_CNTL__USE_ALT_NUM_VERTS : 0));
446    END_CS;
447}
448
449static void r300_emit_draw_elements(struct r300_context *r300,
450                                    struct pipe_resource* indexBuffer,
451                                    unsigned indexSize,
452                                    unsigned minIndex,
453                                    unsigned maxIndex,
454                                    unsigned mode,
455                                    unsigned start,
456                                    unsigned count)
457{
458    uint32_t count_dwords;
459    uint32_t offset_dwords = indexSize * start / sizeof(uint32_t);
460    boolean alt_num_verts = count > 65535;
461    CS_LOCALS(r300);
462
463    if (count >= (1 << 24)) {
464        fprintf(stderr, "r300: Got a huge number of vertices: %i, "
465                "refusing to render.\n", count);
466        return;
467    }
468
469    maxIndex = MIN2(maxIndex, r300->vertex_buffer_max_index);
470
471    DBG(r300, DBG_DRAW, "r300: Indexbuf of %u indices, min %u max %u\n",
472        count, minIndex, maxIndex);
473
474    BEGIN_CS(13 + (alt_num_verts ? 2 : 0));
475    if (alt_num_verts) {
476        OUT_CS_REG(R500_VAP_ALT_NUM_VERTICES, count);
477    }
478    OUT_CS_REG(R300_GA_COLOR_CONTROL,
479            r300_provoking_vertex_fixes(r300, mode));
480    OUT_CS_REG_SEQ(R300_VAP_VF_MAX_VTX_INDX, 2);
481    OUT_CS(maxIndex);
482    OUT_CS(minIndex);
483    OUT_CS_PKT3(R300_PACKET3_3D_DRAW_INDX_2, 0);
484    if (indexSize == 4) {
485        count_dwords = count;
486        OUT_CS(R300_VAP_VF_CNTL__PRIM_WALK_INDICES | (count << 16) |
487               R300_VAP_VF_CNTL__INDEX_SIZE_32bit |
488               r300_translate_primitive(mode) |
489               (alt_num_verts ? R500_VAP_VF_CNTL__USE_ALT_NUM_VERTS : 0));
490    } else {
491        count_dwords = (count + 1) / 2;
492        OUT_CS(R300_VAP_VF_CNTL__PRIM_WALK_INDICES | (count << 16) |
493               r300_translate_primitive(mode) |
494               (alt_num_verts ? R500_VAP_VF_CNTL__USE_ALT_NUM_VERTS : 0));
495    }
496
497    /* INDX_BUFFER is a truly special packet3.
498     * Unlike most other packet3, where the offset is after the count,
499     * the order is reversed, so the relocation ends up carrying the
500     * size of the indexbuf instead of the offset.
501     */
502    OUT_CS_PKT3(R300_PACKET3_INDX_BUFFER, 2);
503    OUT_CS(R300_INDX_BUFFER_ONE_REG_WR | (R300_VAP_PORT_IDX0 >> 2) |
504           (0 << R300_INDX_BUFFER_SKIP_SHIFT));
505    OUT_CS(offset_dwords << 2);
506    OUT_CS_BUF_RELOC(indexBuffer, count_dwords,
507                     r300_buffer(indexBuffer)->domain, 0);
508
509    END_CS;
510}
511
512/* This is the fast-path drawing & emission for HW TCL. */
513static void r300_draw_range_elements(struct pipe_context* pipe,
514                                     struct pipe_resource* indexBuffer,
515                                     unsigned indexSize,
516                                     int indexBias,
517                                     unsigned minIndex,
518                                     unsigned maxIndex,
519                                     unsigned mode,
520                                     unsigned start,
521                                     unsigned count)
522{
523    struct r300_context* r300 = r300_context(pipe);
524    struct pipe_resource* orgIndexBuffer = indexBuffer;
525    boolean alt_num_verts = r300->screen->caps.is_r500 &&
526                            count > 65536 &&
527                            r300->rws->get_value(r300->rws, R300_VID_DRM_2_3_0);
528    unsigned short_count;
529    int buffer_offset = 0, index_offset = 0; /* for index bias emulation */
530    unsigned new_offset;
531
532    if (indexBias && !r300->screen->caps.index_bias_supported) {
533        r300_split_index_bias(r300, indexBias, &buffer_offset, &index_offset);
534    }
535
536    r300_translate_index_buffer(r300, &indexBuffer, &indexSize, index_offset,
537                                &start, count);
538
539    r300_update_derived_state(r300);
540    r300_upload_index_buffer(r300, &indexBuffer, indexSize, start, count, &new_offset);
541
542    start = new_offset;
543
544    /* 15 dwords for emit_draw_elements. Give up if the function fails. */
545    if (!r300_prepare_for_rendering(r300,
546            PREP_FIRST_DRAW | PREP_VALIDATE_VBOS | PREP_EMIT_AOS |
547            PREP_INDEXED, indexBuffer, 15, buffer_offset, indexBias))
548        goto done;
549
550    if (alt_num_verts || count <= 65535) {
551        r300_emit_draw_elements(r300, indexBuffer, indexSize,
552				minIndex, maxIndex, mode, start, count);
553    } else {
554        do {
555            short_count = MIN2(count, 65534);
556            r300_emit_draw_elements(r300, indexBuffer, indexSize,
557                                     minIndex, maxIndex,
558                                     mode, start, short_count);
559
560            start += short_count;
561            count -= short_count;
562
563            /* 15 dwords for emit_draw_elements */
564            if (count) {
565                if (!r300_prepare_for_rendering(r300,
566                        PREP_VALIDATE_VBOS | PREP_EMIT_AOS | PREP_INDEXED,
567                        indexBuffer, 15, buffer_offset, indexBias))
568                    goto done;
569            }
570        } while (count);
571    }
572
573done:
574    if (indexBuffer != orgIndexBuffer) {
575        pipe_resource_reference( &indexBuffer, NULL );
576    }
577}
578
579static void r300_draw_arrays(struct pipe_context* pipe, unsigned mode,
580                             unsigned start, unsigned count)
581{
582    struct r300_context* r300 = r300_context(pipe);
583    boolean alt_num_verts = r300->screen->caps.is_r500 &&
584                            count > 65536 &&
585                            r300->rws->get_value(r300->rws, R300_VID_DRM_2_3_0);
586    unsigned short_count;
587
588    r300_update_derived_state(r300);
589
590    if (immd_is_good_idea(r300, count)) {
591        r300_emit_draw_arrays_immediate(r300, mode, start, count);
592    } else {
593        /* 9 spare dwords for emit_draw_arrays. Give up if the function fails. */
594        if (!r300_prepare_for_rendering(r300,
595                PREP_FIRST_DRAW | PREP_VALIDATE_VBOS | PREP_EMIT_AOS,
596                NULL, 9, start, 0))
597            return;
598
599        if (alt_num_verts || count <= 65535) {
600            r300_emit_draw_arrays(r300, mode, count);
601        } else {
602            do {
603                short_count = MIN2(count, 65535);
604                r300_emit_draw_arrays(r300, mode, short_count);
605
606                start += short_count;
607                count -= short_count;
608
609                /* 9 spare dwords for emit_draw_arrays. Give up if the function fails. */
610                if (count) {
611                    if (!r300_prepare_for_rendering(r300,
612                            PREP_VALIDATE_VBOS | PREP_EMIT_AOS, NULL, 9,
613                            start, 0))
614                        return;
615                }
616            } while (count);
617        }
618    }
619}
620
621static void r300_draw_vbo(struct pipe_context* pipe,
622                          const struct pipe_draw_info *info)
623{
624    struct r300_context* r300 = r300_context(pipe);
625    unsigned count = info->count;
626    boolean translate = FALSE;
627    boolean indexed = info->indexed && r300->index_buffer.buffer;
628    unsigned start_indexed = 0;
629
630    if (r300->skip_rendering) {
631        return;
632    }
633
634    if (!u_trim_pipe_prim(info->mode, &count)) {
635        return;
636    }
637
638    /* Index buffer range checking. */
639    if (indexed) {
640        assert(r300->index_buffer.offset % r300->index_buffer.index_size == 0);
641
642        /* Compute start for draw_elements, taking the offset into account. */
643        start_indexed =
644            info->start +
645            (r300->index_buffer.offset / r300->index_buffer.index_size);
646
647        if ((start_indexed + count) * r300->index_buffer.index_size >
648            r300->index_buffer.buffer->width0) {
649            fprintf(stderr, "r300: Invalid index buffer range. Skipping rendering.\n");
650            return;
651        }
652    }
653
654    /* Set up fallback for incompatible vertex layout if needed. */
655    if (r300->incompatible_vb_layout || r300->velems->incompatible_layout) {
656        r300_begin_vertex_translate(r300);
657        translate = TRUE;
658    }
659
660    if (indexed) {
661        r300_draw_range_elements(pipe,
662                                 r300->index_buffer.buffer,
663                                 r300->index_buffer.index_size,
664                                 info->index_bias,
665                                 info->min_index,
666                                 info->max_index,
667                                 info->mode,
668                                 start_indexed,
669                                 count);
670    } else {
671        r300_draw_arrays(pipe,
672                         info->mode,
673                         info->start,
674                         count);
675    }
676
677    if (translate) {
678        r300_end_vertex_translate(r300);
679    }
680}
681
682/****************************************************************************
683 * The rest of this file is for SW TCL rendering only. Please be polite and *
684 * keep these functions separated so that they are easier to locate. ~C.    *
685 ***************************************************************************/
686
687/* SW TCL elements, using Draw. */
688static void r300_swtcl_draw_vbo(struct pipe_context* pipe,
689                                const struct pipe_draw_info *info)
690{
691    struct r300_context* r300 = r300_context(pipe);
692    struct pipe_transfer *vb_transfer[PIPE_MAX_ATTRIBS];
693    struct pipe_transfer *ib_transfer = NULL;
694    unsigned count = info->count;
695    int i;
696    void *indices = NULL;
697    boolean indexed = info->indexed && r300->index_buffer.buffer;
698
699    if (r300->skip_rendering) {
700        return;
701    }
702
703    if (!u_trim_pipe_prim(info->mode, &count)) {
704        return;
705    }
706
707    r300_update_derived_state(r300);
708
709    r300_reserve_cs_dwords(r300,
710            PREP_FIRST_DRAW | PREP_EMIT_AOS_SWTCL |
711            (indexed ? PREP_INDEXED : 0),
712            indexed ? 256 : 6);
713
714    for (i = 0; i < r300->vertex_buffer_count; i++) {
715        if (r300->vertex_buffer[i].buffer) {
716            void *buf = pipe_buffer_map(pipe,
717                                  r300->vertex_buffer[i].buffer,
718                                  PIPE_TRANSFER_READ,
719                                  &vb_transfer[i]);
720            draw_set_mapped_vertex_buffer(r300->draw, i, buf);
721        }
722    }
723
724    if (indexed) {
725        indices = pipe_buffer_map(pipe, r300->index_buffer.buffer,
726                                  PIPE_TRANSFER_READ, &ib_transfer);
727    }
728
729    draw_set_mapped_index_buffer(r300->draw, indices);
730
731    r300->draw_vbo_locked = TRUE;
732    r300->draw_first_emitted = FALSE;
733    draw_vbo(r300->draw, info);
734    draw_flush(r300->draw);
735    r300->draw_vbo_locked = FALSE;
736
737    for (i = 0; i < r300->vertex_buffer_count; i++) {
738        if (r300->vertex_buffer[i].buffer) {
739            pipe_buffer_unmap(pipe, r300->vertex_buffer[i].buffer,
740                              vb_transfer[i]);
741            draw_set_mapped_vertex_buffer(r300->draw, i, NULL);
742        }
743    }
744
745    if (indexed) {
746        pipe_buffer_unmap(pipe, r300->index_buffer.buffer, ib_transfer);
747        draw_set_mapped_index_buffer(r300->draw, NULL);
748    }
749}
750
751/* Object for rendering using Draw. */
752struct r300_render {
753    /* Parent class */
754    struct vbuf_render base;
755
756    /* Pipe context */
757    struct r300_context* r300;
758
759    /* Vertex information */
760    size_t vertex_size;
761    unsigned prim;
762    unsigned hwprim;
763
764    /* VBO */
765    size_t vbo_max_used;
766    void * vbo_ptr;
767
768    struct pipe_transfer *vbo_transfer;
769};
770
771static INLINE struct r300_render*
772r300_render(struct vbuf_render* render)
773{
774    return (struct r300_render*)render;
775}
776
777static const struct vertex_info*
778r300_render_get_vertex_info(struct vbuf_render* render)
779{
780    struct r300_render* r300render = r300_render(render);
781    struct r300_context* r300 = r300render->r300;
782
783    return &r300->vertex_info;
784}
785
786static boolean r300_render_allocate_vertices(struct vbuf_render* render,
787                                                   ushort vertex_size,
788                                                   ushort count)
789{
790    struct r300_render* r300render = r300_render(render);
791    struct r300_context* r300 = r300render->r300;
792    struct pipe_screen* screen = r300->context.screen;
793    size_t size = (size_t)vertex_size * (size_t)count;
794
795    DBG(r300, DBG_DRAW, "r300: render_allocate_vertices (size: %d)\n", size);
796
797    if (size + r300->draw_vbo_offset > r300->draw_vbo_size)
798    {
799	pipe_resource_reference(&r300->vbo, NULL);
800        r300->vbo = pipe_buffer_create(screen,
801				       PIPE_BIND_VERTEX_BUFFER,
802				       R300_MAX_DRAW_VBO_SIZE);
803        r300->draw_vbo_offset = 0;
804        r300->draw_vbo_size = R300_MAX_DRAW_VBO_SIZE;
805    }
806
807    r300render->vertex_size = vertex_size;
808
809    return (r300->vbo) ? TRUE : FALSE;
810}
811
812static void* r300_render_map_vertices(struct vbuf_render* render)
813{
814    struct r300_render* r300render = r300_render(render);
815    struct r300_context* r300 = r300render->r300;
816
817    assert(!r300render->vbo_transfer);
818
819    DBG(r300, DBG_DRAW, "r300: render_map_vertices\n");
820
821    r300render->vbo_ptr = pipe_buffer_map(&r300render->r300->context,
822					  r300->vbo,
823                                          PIPE_TRANSFER_WRITE,
824					  &r300render->vbo_transfer);
825
826    assert(r300render->vbo_ptr);
827
828    return ((uint8_t*)r300render->vbo_ptr + r300->draw_vbo_offset);
829}
830
831static void r300_render_unmap_vertices(struct vbuf_render* render,
832                                             ushort min,
833                                             ushort max)
834{
835    struct r300_render* r300render = r300_render(render);
836    struct pipe_context* context = &r300render->r300->context;
837    struct r300_context* r300 = r300render->r300;
838
839    assert(r300render->vbo_transfer);
840
841    DBG(r300, DBG_DRAW, "r300: render_unmap_vertices\n");
842
843    r300render->vbo_max_used = MAX2(r300render->vbo_max_used,
844                                    r300render->vertex_size * (max + 1));
845    pipe_buffer_unmap(context, r300->vbo, r300render->vbo_transfer);
846
847    r300render->vbo_transfer = NULL;
848}
849
850static void r300_render_release_vertices(struct vbuf_render* render)
851{
852    struct r300_render* r300render = r300_render(render);
853    struct r300_context* r300 = r300render->r300;
854
855    DBG(r300, DBG_DRAW, "r300: render_release_vertices\n");
856
857    r300->draw_vbo_offset += r300render->vbo_max_used;
858    r300render->vbo_max_used = 0;
859}
860
861static boolean r300_render_set_primitive(struct vbuf_render* render,
862                                               unsigned prim)
863{
864    struct r300_render* r300render = r300_render(render);
865
866    r300render->prim = prim;
867    r300render->hwprim = r300_translate_primitive(prim);
868
869    return TRUE;
870}
871
872static void r300_render_draw_arrays(struct vbuf_render* render,
873                                    unsigned start,
874                                    unsigned count)
875{
876    struct r300_render* r300render = r300_render(render);
877    struct r300_context* r300 = r300render->r300;
878    uint8_t* ptr;
879    unsigned i;
880    unsigned dwords = 6;
881
882    CS_LOCALS(r300);
883    (void) i; (void) ptr;
884
885    DBG(r300, DBG_DRAW, "r300: render_draw_arrays (count: %d)\n", count);
886
887    if (r300->draw_first_emitted) {
888        if (!r300_prepare_for_rendering(r300,
889                PREP_FIRST_DRAW | PREP_EMIT_AOS_SWTCL,
890                NULL, 6, 0, 0))
891            return;
892    } else {
893        if (!r300_emit_states(r300,
894                PREP_FIRST_DRAW | PREP_EMIT_AOS_SWTCL,
895                NULL, 0, 0))
896            return;
897    }
898
899    /* Uncomment to dump all VBOs rendered through this interface.
900     * Slow and noisy!
901    ptr = pipe_buffer_map(&r300render->r300->context,
902                          r300render->vbo, PIPE_TRANSFER_READ,
903                          &r300render->vbo_transfer);
904
905    for (i = 0; i < count; i++) {
906        printf("r300: Vertex %d\n", i);
907        draw_dump_emitted_vertex(&r300->vertex_info, ptr);
908        ptr += r300->vertex_info.size * 4;
909        printf("\n");
910    }
911
912    pipe_buffer_unmap(&r300render->r300->context, r300render->vbo,
913        r300render->vbo_transfer);
914    */
915
916    BEGIN_CS(dwords);
917    OUT_CS_REG(R300_GA_COLOR_CONTROL,
918            r300_provoking_vertex_fixes(r300, r300render->prim));
919    OUT_CS_REG(R300_VAP_VF_MAX_VTX_INDX, count - 1);
920    OUT_CS_PKT3(R300_PACKET3_3D_DRAW_VBUF_2, 0);
921    OUT_CS(R300_VAP_VF_CNTL__PRIM_WALK_VERTEX_LIST | (count << 16) |
922           r300render->hwprim);
923    END_CS;
924
925    r300->draw_first_emitted = TRUE;
926}
927
928static void r300_render_draw_elements(struct vbuf_render* render,
929                                      const ushort* indices,
930                                      uint count)
931{
932    struct r300_render* r300render = r300_render(render);
933    struct r300_context* r300 = r300render->r300;
934    int i;
935    unsigned end_cs_dwords;
936    unsigned max_index = (r300->draw_vbo_size - r300->draw_vbo_offset) /
937                         (r300render->r300->vertex_info.size * 4) - 1;
938    unsigned short_count;
939    unsigned free_dwords;
940
941    CS_LOCALS(r300);
942    DBG(r300, DBG_DRAW, "r300: render_draw_elements (count: %d)\n", count);
943
944    if (r300->draw_first_emitted) {
945        if (!r300_prepare_for_rendering(r300,
946                PREP_FIRST_DRAW | PREP_EMIT_AOS_SWTCL | PREP_INDEXED,
947                NULL, 256, 0, 0))
948            return;
949    } else {
950        if (!r300_emit_states(r300,
951                PREP_FIRST_DRAW | PREP_EMIT_AOS_SWTCL | PREP_INDEXED,
952                NULL, 0, 0))
953            return;
954    }
955
956    /* Below we manage the CS space manually because there may be more
957     * indices than it can fit in CS. */
958
959    end_cs_dwords = r300_get_num_cs_end_dwords(r300);
960
961    while (count) {
962        free_dwords = R300_MAX_CMDBUF_DWORDS - r300->cs->cdw;
963
964        short_count = MIN2(count, (free_dwords - end_cs_dwords - 6) * 2);
965
966        BEGIN_CS(6 + (short_count+1)/2);
967        OUT_CS_REG(R300_GA_COLOR_CONTROL,
968                r300_provoking_vertex_fixes(r300, r300render->prim));
969        OUT_CS_REG(R300_VAP_VF_MAX_VTX_INDX, max_index);
970        OUT_CS_PKT3(R300_PACKET3_3D_DRAW_INDX_2, (short_count+1)/2);
971        OUT_CS(R300_VAP_VF_CNTL__PRIM_WALK_INDICES | (short_count << 16) |
972               r300render->hwprim);
973        for (i = 0; i < short_count-1; i += 2) {
974            OUT_CS(indices[i+1] << 16 | indices[i]);
975        }
976        if (short_count % 2) {
977            OUT_CS(indices[short_count-1]);
978        }
979        END_CS;
980
981        /* OK now subtract the emitted indices and see if we need to emit
982         * another draw packet. */
983        indices += short_count;
984        count -= short_count;
985
986        if (count) {
987            if (!r300_prepare_for_rendering(r300,
988                    PREP_EMIT_AOS_SWTCL | PREP_INDEXED,
989                    NULL, 256, 0, 0))
990                return;
991
992            end_cs_dwords = r300_get_num_cs_end_dwords(r300);
993        }
994    }
995
996    r300->draw_first_emitted = TRUE;
997}
998
999static void r300_render_destroy(struct vbuf_render* render)
1000{
1001    FREE(render);
1002}
1003
1004static struct vbuf_render* r300_render_create(struct r300_context* r300)
1005{
1006    struct r300_render* r300render = CALLOC_STRUCT(r300_render);
1007
1008    r300render->r300 = r300;
1009
1010    /* XXX find real numbers plz */
1011    r300render->base.max_vertex_buffer_bytes = 128 * 1024;
1012    r300render->base.max_indices = 16 * 1024;
1013
1014    r300render->base.get_vertex_info = r300_render_get_vertex_info;
1015    r300render->base.allocate_vertices = r300_render_allocate_vertices;
1016    r300render->base.map_vertices = r300_render_map_vertices;
1017    r300render->base.unmap_vertices = r300_render_unmap_vertices;
1018    r300render->base.set_primitive = r300_render_set_primitive;
1019    r300render->base.draw_elements = r300_render_draw_elements;
1020    r300render->base.draw_arrays = r300_render_draw_arrays;
1021    r300render->base.release_vertices = r300_render_release_vertices;
1022    r300render->base.destroy = r300_render_destroy;
1023
1024    return &r300render->base;
1025}
1026
1027struct draw_stage* r300_draw_stage(struct r300_context* r300)
1028{
1029    struct vbuf_render* render;
1030    struct draw_stage* stage;
1031
1032    render = r300_render_create(r300);
1033
1034    if (!render) {
1035        return NULL;
1036    }
1037
1038    stage = draw_vbuf_stage(r300->draw, render);
1039
1040    if (!stage) {
1041        render->destroy(render);
1042        return NULL;
1043    }
1044
1045    draw_set_render(r300->draw, render);
1046
1047    return stage;
1048}
1049
1050void r300_draw_flush_vbuf(struct r300_context *r300)
1051{
1052    pipe_resource_reference(&r300->vbo, NULL);
1053    r300->draw_vbo_size = 0;
1054}
1055
1056/****************************************************************************
1057 *                         End of SW TCL functions                          *
1058 ***************************************************************************/
1059
1060/* This functions is used to draw a rectangle for the blitter module.
1061 *
1062 * If we rendered a quad, the pixels on the main diagonal
1063 * would be computed and stored twice, which makes the clear/copy codepaths
1064 * somewhat inefficient. Instead we use a rectangular point sprite. */
1065static void r300_blitter_draw_rectangle(struct blitter_context *blitter,
1066                                        unsigned x1, unsigned y1,
1067                                        unsigned x2, unsigned y2,
1068                                        float depth,
1069                                        enum blitter_attrib_type type,
1070                                        const float attrib[4])
1071{
1072    struct r300_context *r300 = r300_context(util_blitter_get_pipe(blitter));
1073    unsigned last_sprite_coord_enable = r300->sprite_coord_enable;
1074    unsigned width = x2 - x1;
1075    unsigned height = y2 - y1;
1076    unsigned vertex_size =
1077            type == UTIL_BLITTER_ATTRIB_COLOR || !r300->draw ? 8 : 4;
1078    unsigned dwords = 13 + vertex_size +
1079                      (type == UTIL_BLITTER_ATTRIB_TEXCOORD ? 7 : 0);
1080    const float zeros[4] = {0, 0, 0, 0};
1081    CS_LOCALS(r300);
1082
1083    if (type == UTIL_BLITTER_ATTRIB_TEXCOORD)
1084        r300->sprite_coord_enable = 1;
1085
1086    r300_update_derived_state(r300);
1087
1088    /* Mark some states we don't care about as non-dirty. */
1089    r300->clip_state.dirty = FALSE;
1090    r300->viewport_state.dirty = FALSE;
1091
1092    if (!r300_prepare_for_rendering(r300, PREP_FIRST_DRAW, NULL, dwords, 0, 0))
1093        goto done;
1094
1095    DBG(r300, DBG_DRAW, "r300: draw_rectangle\n");
1096
1097    BEGIN_CS(dwords);
1098    /* Set up GA. */
1099    OUT_CS_REG(R300_GA_POINT_SIZE, (height * 6) | ((width * 6) << 16));
1100
1101    if (type == UTIL_BLITTER_ATTRIB_TEXCOORD) {
1102        /* Set up the GA to generate texcoords. */
1103        OUT_CS_REG(R300_GB_ENABLE, R300_GB_POINT_STUFF_ENABLE |
1104                   (R300_GB_TEX_STR << R300_GB_TEX0_SOURCE_SHIFT));
1105        OUT_CS_REG_SEQ(R300_GA_POINT_S0, 4);
1106        OUT_CS_32F(attrib[0]);
1107        OUT_CS_32F(attrib[3]);
1108        OUT_CS_32F(attrib[2]);
1109        OUT_CS_32F(attrib[1]);
1110    }
1111
1112    /* Set up VAP controls. */
1113    OUT_CS_REG(R300_VAP_CLIP_CNTL, R300_CLIP_DISABLE);
1114    OUT_CS_REG(R300_VAP_VTE_CNTL, R300_VTX_XY_FMT | R300_VTX_Z_FMT);
1115    OUT_CS_REG(R300_VAP_VTX_SIZE, vertex_size);
1116    OUT_CS_REG_SEQ(R300_VAP_VF_MAX_VTX_INDX, 2);
1117    OUT_CS(1);
1118    OUT_CS(0);
1119
1120    /* Draw. */
1121    OUT_CS_PKT3(R300_PACKET3_3D_DRAW_IMMD_2, vertex_size);
1122    OUT_CS(R300_VAP_VF_CNTL__PRIM_WALK_VERTEX_EMBEDDED | (1 << 16) |
1123           R300_VAP_VF_CNTL__PRIM_POINTS);
1124
1125    OUT_CS_32F(x1 + width * 0.5f);
1126    OUT_CS_32F(y1 + height * 0.5f);
1127    OUT_CS_32F(depth);
1128    OUT_CS_32F(1);
1129
1130    if (vertex_size == 8) {
1131        if (!attrib)
1132            attrib = zeros;
1133        OUT_CS_TABLE(attrib, 4);
1134    }
1135    END_CS;
1136
1137done:
1138    /* Restore the state. */
1139    r300_mark_atom_dirty(r300, &r300->clip_state);
1140    r300_mark_atom_dirty(r300, &r300->rs_state);
1141    r300_mark_atom_dirty(r300, &r300->viewport_state);
1142
1143    r300->sprite_coord_enable = last_sprite_coord_enable;
1144}
1145
1146static void r300_resource_resolve(struct pipe_context* pipe,
1147                                  struct pipe_resource* dest,
1148                                  unsigned dst_layer,
1149                                  struct pipe_resource* src,
1150                                  unsigned src_layer)
1151{
1152    struct r300_context* r300 = r300_context(pipe);
1153    struct pipe_surface* srcsurf, surf_tmpl;
1154    struct r300_aa_state *aa = (struct r300_aa_state*)r300->aa_state.state;
1155    float color[] = {0, 0, 0, 0};
1156
1157    memset(&surf_tmpl, 0, sizeof(surf_tmpl));
1158    surf_tmpl.format = src->format;
1159    surf_tmpl.usage = 0; /* not really a surface hence no bind flags */
1160    surf_tmpl.u.tex.level = 0; /* msaa resources cannot have mipmaps */
1161    surf_tmpl.u.tex.first_layer = src_layer;
1162    surf_tmpl.u.tex.last_layer = src_layer;
1163    srcsurf = pipe->create_surface(pipe, src, &surf_tmpl);
1164    surf_tmpl.format = dest->format;
1165    surf_tmpl.u.tex.first_layer = dst_layer;
1166    surf_tmpl.u.tex.last_layer = dst_layer;
1167
1168    DBG(r300, DBG_DRAW, "r300: Resolving resource...\n");
1169
1170    /* Enable AA resolve. */
1171    aa->dest = r300_surface(pipe->create_surface(pipe, dest, &surf_tmpl));
1172
1173    aa->aaresolve_ctl =
1174        R300_RB3D_AARESOLVE_CTL_AARESOLVE_MODE_RESOLVE |
1175        R300_RB3D_AARESOLVE_CTL_AARESOLVE_ALPHA_AVERAGE;
1176    r300->aa_state.size = 12;
1177    r300_mark_atom_dirty(r300, &r300->aa_state);
1178
1179    /* Resolve the surface. */
1180    r300->context.clear_render_target(pipe,
1181        srcsurf, color, 0, 0, src->width0, src->height0);
1182
1183    /* Disable AA resolve. */
1184    aa->aaresolve_ctl = 0;
1185    r300->aa_state.size = 4;
1186    r300_mark_atom_dirty(r300, &r300->aa_state);
1187
1188    pipe_surface_reference((struct pipe_surface**)&srcsurf, NULL);
1189    pipe_surface_reference((struct pipe_surface**)&aa->dest, NULL);
1190}
1191
1192void r300_init_render_functions(struct r300_context *r300)
1193{
1194    /* Set draw functions based on presence of HW TCL. */
1195    if (r300->screen->caps.has_tcl) {
1196        r300->context.draw_vbo = r300_draw_vbo;
1197    } else {
1198        r300->context.draw_vbo = r300_swtcl_draw_vbo;
1199    }
1200
1201    r300->context.resource_resolve = r300_resource_resolve;
1202    r300->blitter->draw_rectangle = r300_blitter_draw_rectangle;
1203
1204    /* Plug in the two-sided stencil reference value fallback if needed. */
1205    if (!r300->screen->caps.is_r500)
1206        r300_plug_in_stencil_ref_fallback(r300);
1207}
1208