Merge branch 'gallium-newclear'
[platform/upstream/mesa.git] / src / gallium / drivers / llvmpipe / lp_rast.c
1 /**************************************************************************
2  *
3  * Copyright 2009 VMware, Inc.
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 VMWARE 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 <limits.h>
29 #include "util/u_memory.h"
30 #include "util/u_math.h"
31 #include "util/u_surface.h"
32
33 #include "lp_scene_queue.h"
34 #include "lp_debug.h"
35 #include "lp_fence.h"
36 #include "lp_perf.h"
37 #include "lp_query.h"
38 #include "lp_rast.h"
39 #include "lp_rast_priv.h"
40 #include "lp_tile_soa.h"
41 #include "gallivm/lp_bld_debug.h"
42 #include "lp_scene.h"
43
44
45 /**
46  * Begin rasterizing a scene.
47  * Called once per scene by one thread.
48  */
49 static void
50 lp_rast_begin( struct lp_rasterizer *rast,
51                struct lp_scene *scene )
52 {
53    const struct pipe_framebuffer_state *fb = &scene->fb;
54    int i;
55
56    rast->curr_scene = scene;
57
58    LP_DBG(DEBUG_RAST, "%s\n", __FUNCTION__);
59
60    rast->state.nr_cbufs = scene->fb.nr_cbufs;
61    
62    for (i = 0; i < rast->state.nr_cbufs; i++) {
63       struct pipe_surface *cbuf = scene->fb.cbufs[i];
64       llvmpipe_resource_map(cbuf->texture,
65                             cbuf->face,
66                             cbuf->level,
67                             cbuf->zslice,
68                             LP_TEX_USAGE_READ_WRITE,
69                             LP_TEX_LAYOUT_NONE);
70    }
71
72    if (fb->zsbuf) {
73       struct pipe_surface *zsbuf = scene->fb.zsbuf;
74       rast->zsbuf.stride = llvmpipe_resource_stride(zsbuf->texture, zsbuf->level);
75       rast->zsbuf.blocksize = 
76          util_format_get_blocksize(zsbuf->texture->format);
77
78       rast->zsbuf.map = llvmpipe_resource_map(zsbuf->texture,
79                                              zsbuf->face,
80                                              zsbuf->level,
81                                              zsbuf->zslice,
82                                              LP_TEX_USAGE_READ_WRITE,
83                                              LP_TEX_LAYOUT_NONE);
84       assert(rast->zsbuf.map);
85    }
86
87    lp_scene_bin_iter_begin( scene );
88 }
89
90
91 static void
92 lp_rast_end( struct lp_rasterizer *rast )
93 {
94    struct lp_scene *scene = rast->curr_scene;
95    unsigned i;
96
97    /* Unmap color buffers */
98    for (i = 0; i < rast->state.nr_cbufs; i++) {
99       struct pipe_surface *cbuf = scene->fb.cbufs[i];
100       llvmpipe_resource_unmap(cbuf->texture,
101                              cbuf->face,
102                              cbuf->level,
103                              cbuf->zslice);
104    }
105
106    /* Unmap z/stencil buffer */
107    if (rast->zsbuf.map) {
108       struct pipe_surface *zsbuf = scene->fb.zsbuf;
109       llvmpipe_resource_unmap(zsbuf->texture,
110                              zsbuf->face,
111                              zsbuf->level,
112                              zsbuf->zslice);
113       rast->zsbuf.map = NULL;
114    }
115
116    lp_scene_reset( rast->curr_scene );
117
118    rast->curr_scene = NULL;
119
120 #ifdef DEBUG
121    if (0)
122       debug_printf("Post render scene: tile unswizzle: %u tile swizzle: %u\n",
123                    lp_tile_unswizzle_count, lp_tile_swizzle_count);
124 #endif
125 }
126
127
128 /**
129  * Begining rasterization of a tile.
130  * \param x  window X position of the tile, in pixels
131  * \param y  window Y position of the tile, in pixels
132  */
133 static void
134 lp_rast_tile_begin(struct lp_rasterizer_task *task,
135                    unsigned x, unsigned y)
136 {
137    struct lp_rasterizer *rast = task->rast;
138    struct lp_scene *scene = rast->curr_scene;
139    enum lp_texture_usage usage;
140    unsigned buf;
141
142    LP_DBG(DEBUG_RAST, "%s %d,%d\n", __FUNCTION__, x, y);
143
144    assert(x % TILE_SIZE == 0);
145    assert(y % TILE_SIZE == 0);
146
147    task->x = x;
148    task->y = y;
149
150    if (scene->has_color_clear)
151       usage = LP_TEX_USAGE_WRITE_ALL;
152    else
153       usage = LP_TEX_USAGE_READ_WRITE;
154
155    /* get pointers to color tile(s) */
156    for (buf = 0; buf < rast->state.nr_cbufs; buf++) {
157       struct pipe_surface *cbuf = rast->curr_scene->fb.cbufs[buf];
158       struct llvmpipe_resource *lpt;
159       assert(cbuf);
160       lpt = llvmpipe_resource(cbuf->texture);
161       task->color_tiles[buf] = llvmpipe_get_texture_tile(lpt,
162                                                          cbuf->face + cbuf->zslice,
163                                                          cbuf->level,
164                                                          usage,
165                                                          x, y);
166       assert(task->color_tiles[buf]);
167    }
168
169    /* get pointer to depth/stencil tile */
170    {
171       struct pipe_surface *zsbuf = rast->curr_scene->fb.zsbuf;
172       if (zsbuf) {
173          struct llvmpipe_resource *lpt = llvmpipe_resource(zsbuf->texture);
174
175          if (scene->has_depthstencil_clear)
176             usage = LP_TEX_USAGE_WRITE_ALL;
177          else
178             usage = LP_TEX_USAGE_READ_WRITE;
179
180          /* "prime" the tile: convert data from linear to tiled if necessary
181           * and update the tile's layout info.
182           */
183          (void) llvmpipe_get_texture_tile(lpt,
184                                           zsbuf->face + zsbuf->zslice,
185                                           zsbuf->level,
186                                           usage,
187                                           x, y);
188          /* Get actual pointer to the tile data.  Note that depth/stencil
189           * data is tiled differently than color data.
190           */
191          task->depth_tile = lp_rast_get_depth_block_pointer(rast, x, y);
192
193          assert(task->depth_tile);
194       }
195       else {
196          task->depth_tile = NULL;
197       }
198    }
199 }
200
201
202 /**
203  * Clear the rasterizer's current color tile.
204  * This is a bin command called during bin processing.
205  */
206 void
207 lp_rast_clear_color(struct lp_rasterizer_task *task,
208                     const union lp_rast_cmd_arg arg)
209 {
210    struct lp_rasterizer *rast = task->rast;
211    const uint8_t *clear_color = arg.clear_color;
212
213    unsigned i;
214
215    LP_DBG(DEBUG_RAST, "%s 0x%x,0x%x,0x%x,0x%x\n", __FUNCTION__, 
216               clear_color[0],
217               clear_color[1],
218               clear_color[2],
219               clear_color[3]);
220
221    if (clear_color[0] == clear_color[1] &&
222        clear_color[1] == clear_color[2] &&
223        clear_color[2] == clear_color[3]) {
224       /* clear to grayscale value {x, x, x, x} */
225       for (i = 0; i < rast->state.nr_cbufs; i++) {
226          uint8_t *ptr = task->color_tiles[i];
227          memset(ptr, clear_color[0], TILE_SIZE * TILE_SIZE * 4);
228       }
229    }
230    else {
231       /* Non-gray color.
232        * Note: if the swizzled tile layout changes (see TILE_PIXEL) this code
233        * will need to change.  It'll be pretty obvious when clearing no longer
234        * works.
235        */
236       const unsigned chunk = TILE_SIZE / 4;
237       for (i = 0; i < rast->state.nr_cbufs; i++) {
238          uint8_t *c = task->color_tiles[i];
239          unsigned j;
240
241          for (j = 0; j < 4 * TILE_SIZE; j++) {
242             memset(c, clear_color[0], chunk);
243             c += chunk;
244             memset(c, clear_color[1], chunk);
245             c += chunk;
246             memset(c, clear_color[2], chunk);
247             c += chunk;
248             memset(c, clear_color[3], chunk);
249             c += chunk;
250          }
251       }
252    }
253
254    LP_COUNT(nr_color_tile_clear);
255 }
256
257
258 /**
259  * Clear the rasterizer's current z/stencil tile.
260  * This is a bin command called during bin processing.
261  */
262 void
263 lp_rast_clear_zstencil(struct lp_rasterizer_task *task,
264                        const union lp_rast_cmd_arg arg)
265 {
266    struct lp_rasterizer *rast = task->rast;
267    const struct lp_rast_clearzs *clearzs = arg.clear_zstencil;
268    unsigned clear_value = clearzs->clearzs_value;
269    unsigned clear_mask = clearzs->clearzs_mask;
270    const unsigned height = TILE_SIZE / TILE_VECTOR_HEIGHT;
271    const unsigned width = TILE_SIZE * TILE_VECTOR_HEIGHT;
272    const unsigned block_size = rast->zsbuf.blocksize;
273    const unsigned dst_stride = rast->zsbuf.stride * TILE_VECTOR_HEIGHT;
274    uint8_t *dst;
275    unsigned i, j;
276
277    LP_DBG(DEBUG_RAST, "%s 0x%x%x\n", __FUNCTION__, clear_value, clear_mask);
278
279    /*
280     * Clear the aera of the swizzled depth/depth buffer matching this tile, in
281     * stripes of TILE_VECTOR_HEIGHT x TILE_SIZE at a time.
282     *
283     * The swizzled depth format is such that the depths for
284     * TILE_VECTOR_HEIGHT x TILE_VECTOR_WIDTH pixels have consecutive offsets.
285     */
286
287    dst = task->depth_tile;
288
289    assert(dst == lp_rast_get_depth_block_pointer(rast, task->x, task->y));
290
291    switch (block_size) {
292    case 1:
293       memset(dst, (uint8_t) clear_value, height * width);
294       break;
295    case 2:
296       for (i = 0; i < height; i++) {
297          uint16_t *row = (uint16_t *)dst;
298          for (j = 0; j < width; j++)
299             *row++ = (uint16_t) clear_value;
300          dst += dst_stride;
301       }
302       break;
303    case 4:
304       if (clear_mask == 0xffffffff) {
305          for (i = 0; i < height; i++) {
306             uint32_t *row = (uint32_t *)dst;
307             for (j = 0; j < width; j++)
308                *row++ = clear_value;
309             dst += dst_stride;
310          }
311       }
312       else {
313          for (i = 0; i < height; i++) {
314             uint32_t *row = (uint32_t *)dst;
315             for (j = 0; j < width; j++) {
316                uint32_t tmp = ~clear_mask & *row;
317                *row++ = (clear_value & clear_mask) | tmp;
318             }
319             dst += dst_stride;
320          }
321       }
322       break;
323    default:
324       assert(0);
325       break;
326    }
327 }
328
329
330 /**
331  * Load tile color from the framebuffer surface.
332  * This is a bin command called during bin processing.
333  */
334 #if 0
335 void
336 lp_rast_load_color(struct lp_rasterizer_task *task,
337                    const union lp_rast_cmd_arg arg)
338 {
339    struct lp_rasterizer *rast = task->rast;
340    unsigned buf;
341    enum lp_texture_usage usage;
342
343    LP_DBG(DEBUG_RAST, "%s at %u, %u\n", __FUNCTION__, x, y);
344
345    if (scene->has_color_clear)
346       usage = LP_TEX_USAGE_WRITE_ALL;
347    else
348       usage = LP_TEX_USAGE_READ_WRITE;
349
350    /* Get pointers to color tile(s).
351     * This will convert linear data to tiled if needed.
352     */
353    for (buf = 0; buf < rast->state.nr_cbufs; buf++) {
354       struct pipe_surface *cbuf = rast->curr_scene->fb.cbufs[buf];
355       struct llvmpipe_texture *lpt;
356       assert(cbuf);
357       lpt = llvmpipe_texture(cbuf->texture);
358       task->color_tiles[buf] = llvmpipe_get_texture_tile(lpt,
359                                                          cbuf->face + cbuf->zslice,
360                                                          cbuf->level,
361                                                          usage,
362                                                          task->x, task->y);
363       assert(task->color_tiles[buf]);
364    }
365 }
366 #endif
367
368
369 /**
370  * Convert the color tile from tiled to linear layout.
371  * This is generally only done when we're flushing the scene just prior to
372  * SwapBuffers.  If we didn't do this here, we'd have to convert the entire
373  * tiled color buffer to linear layout in the llvmpipe_texture_unmap()
374  * function.  It's better to do it here to take advantage of
375  * threading/parallelism.
376  * This is a bin command which is stored in all bins.
377  */
378 void
379 lp_rast_store_color( struct lp_rasterizer_task *task,
380                      const union lp_rast_cmd_arg arg)
381 {
382    struct lp_rasterizer *rast = task->rast;
383    struct lp_scene *scene = rast->curr_scene;
384    unsigned buf;
385
386    for (buf = 0; buf < rast->state.nr_cbufs; buf++) {
387       struct pipe_surface *cbuf = scene->fb.cbufs[buf];
388       const unsigned face = cbuf->face, level = cbuf->level;
389       struct llvmpipe_resource *lpt = llvmpipe_resource(cbuf->texture);
390       /* this will convert the tiled data to linear if needed */
391       (void) llvmpipe_get_texture_tile_linear(lpt, face, level,
392                                               LP_TEX_USAGE_READ,
393                                               task->x, task->y);
394    }
395 }
396
397
398 /**
399  * This is a bin command called during bin processing.
400  */
401 void
402 lp_rast_set_state(struct lp_rasterizer_task *task,
403                   const union lp_rast_cmd_arg arg)
404 {
405    const struct lp_rast_state *state = arg.set_state;
406
407    LP_DBG(DEBUG_RAST, "%s %p\n", __FUNCTION__, (void *) state);
408
409    /* just set the current state pointer for this rasterizer */
410    task->current_state = state;
411 }
412
413
414 /**
415  * Run the shader on all blocks in a tile.  This is used when a tile is
416  * completely contained inside a triangle.
417  * This is a bin command called during bin processing.
418  */
419 void
420 lp_rast_shade_tile(struct lp_rasterizer_task *task,
421                    const union lp_rast_cmd_arg arg)
422 {
423    struct lp_rasterizer *rast = task->rast;
424    const struct lp_rast_state *state = task->current_state;
425    const struct lp_rast_shader_inputs *inputs = arg.shade_tile;
426    struct lp_fragment_shader_variant *variant = state->variant;
427    const unsigned tile_x = task->x, tile_y = task->y;
428    unsigned x, y;
429
430    LP_DBG(DEBUG_RAST, "%s\n", __FUNCTION__);
431
432    /* render the whole 64x64 tile in 4x4 chunks */
433    for (y = 0; y < TILE_SIZE; y += 4){
434       for (x = 0; x < TILE_SIZE; x += 4) {
435          uint8_t *color[PIPE_MAX_COLOR_BUFS];
436          uint32_t *depth;
437          unsigned i;
438
439          /* color buffer */
440          for (i = 0; i < rast->state.nr_cbufs; i++)
441             color[i] = lp_rast_get_color_block_pointer(task, i,
442                                                        tile_x + x, tile_y + y);
443
444          /* depth buffer */
445          depth = lp_rast_get_depth_block_pointer(rast, tile_x + x, tile_y + y);
446
447          /* run shader on 4x4 block */
448          variant->jit_function[RAST_WHOLE]( &state->jit_context,
449                                           tile_x + x, tile_y + y,
450                                           inputs->facing,
451                                           inputs->a0,
452                                           inputs->dadx,
453                                           inputs->dady,
454                                           color,
455                                           depth,
456                                           INT_MIN, INT_MIN, INT_MIN,
457                                           NULL, NULL, NULL, &task->vis_counter);
458       }
459    }
460 }
461
462
463 /**
464  * Compute shading for a 4x4 block of pixels.
465  * This is a bin command called during bin processing.
466  * \param x  X position of quad in window coords
467  * \param y  Y position of quad in window coords
468  */
469 void lp_rast_shade_quads( struct lp_rasterizer_task *task,
470                           const struct lp_rast_shader_inputs *inputs,
471                           unsigned x, unsigned y,
472                           int32_t c1, int32_t c2, int32_t c3)
473 {
474    const struct lp_rast_state *state = task->current_state;
475    struct lp_fragment_shader_variant *variant = state->variant;
476    struct lp_rasterizer *rast = task->rast;
477    uint8_t *color[PIPE_MAX_COLOR_BUFS];
478    void *depth;
479    unsigned i;
480
481    assert(state);
482
483    /* Sanity checks */
484    assert(x % TILE_VECTOR_WIDTH == 0);
485    assert(y % TILE_VECTOR_HEIGHT == 0);
486
487    assert((x % 4) == 0);
488    assert((y % 4) == 0);
489
490    /* color buffer */
491    for (i = 0; i < rast->state.nr_cbufs; i++) {
492       color[i] = lp_rast_get_color_block_pointer(task, i, x, y);
493       assert(lp_check_alignment(color[i], 16));
494    }
495
496    /* depth buffer */
497    depth = lp_rast_get_depth_block_pointer(rast, x, y);
498
499
500    assert(lp_check_alignment(state->jit_context.blend_color, 16));
501
502    assert(lp_check_alignment(inputs->step[0], 16));
503    assert(lp_check_alignment(inputs->step[1], 16));
504    assert(lp_check_alignment(inputs->step[2], 16));
505
506    /* run shader on 4x4 block */
507    variant->jit_function[RAST_EDGE_TEST]( &state->jit_context,
508                                         x, y,
509                                         inputs->facing,
510                                         inputs->a0,
511                                         inputs->dadx,
512                                         inputs->dady,
513                                         color,
514                                         depth,
515                                         c1, c2, c3,
516                                         inputs->step[0],
517                                         inputs->step[1],
518                                         inputs->step[2],
519                                         &task->vis_counter);
520 }
521
522
523 /**
524  * Set top row and left column of the tile's pixels to white.  For debugging.
525  */
526 static void
527 outline_tile(uint8_t *tile)
528 {
529    const uint8_t val = 0xff;
530    unsigned i;
531
532    for (i = 0; i < TILE_SIZE; i++) {
533       TILE_PIXEL(tile, i, 0, 0) = val;
534       TILE_PIXEL(tile, i, 0, 1) = val;
535       TILE_PIXEL(tile, i, 0, 2) = val;
536       TILE_PIXEL(tile, i, 0, 3) = val;
537
538       TILE_PIXEL(tile, 0, i, 0) = val;
539       TILE_PIXEL(tile, 0, i, 1) = val;
540       TILE_PIXEL(tile, 0, i, 2) = val;
541       TILE_PIXEL(tile, 0, i, 3) = val;
542    }
543 }
544
545
546 /**
547  * Draw grid of gray lines at 16-pixel intervals across the tile to
548  * show the sub-tile boundaries.  For debugging.
549  */
550 static void
551 outline_subtiles(uint8_t *tile)
552 {
553    const uint8_t val = 0x80;
554    const unsigned step = 16;
555    unsigned i, j;
556
557    for (i = 0; i < TILE_SIZE; i += step) {
558       for (j = 0; j < TILE_SIZE; j++) {
559          TILE_PIXEL(tile, i, j, 0) = val;
560          TILE_PIXEL(tile, i, j, 1) = val;
561          TILE_PIXEL(tile, i, j, 2) = val;
562          TILE_PIXEL(tile, i, j, 3) = val;
563
564          TILE_PIXEL(tile, j, i, 0) = val;
565          TILE_PIXEL(tile, j, i, 1) = val;
566          TILE_PIXEL(tile, j, i, 2) = val;
567          TILE_PIXEL(tile, j, i, 3) = val;
568       }
569    }
570
571    outline_tile(tile);
572 }
573
574
575
576 /**
577  * Called when we're done writing to a color tile.
578  */
579 static void
580 lp_rast_tile_end(struct lp_rasterizer_task *task)
581 {
582 #ifdef DEBUG
583    if (LP_DEBUG & (DEBUG_SHOW_SUBTILES | DEBUG_SHOW_TILES)) {
584       struct lp_rasterizer *rast = task->rast;
585       unsigned buf;
586
587       for (buf = 0; buf < rast->state.nr_cbufs; buf++) {
588          uint8_t *color = lp_rast_get_color_block_pointer(task, buf,
589                                                           task->x, task->y);
590
591          if (LP_DEBUG & DEBUG_SHOW_SUBTILES)
592             outline_subtiles(color);
593          else if (LP_DEBUG & DEBUG_SHOW_TILES)
594             outline_tile(color);
595       }
596    }
597 #else
598    (void) outline_subtiles;
599 #endif
600
601    /* debug */
602    memset(task->color_tiles, 0, sizeof(task->color_tiles));
603    task->depth_tile = NULL;
604 }
605
606
607
608 /**
609  * Signal on a fence.  This is called during bin execution/rasterization.
610  * Called per thread.
611  */
612 void
613 lp_rast_fence(struct lp_rasterizer_task *task,
614               const union lp_rast_cmd_arg arg)
615 {
616    struct lp_fence *fence = arg.fence;
617    lp_fence_signal(fence);
618 }
619
620
621 /**
622  * Begin a new occlusion query.
623  * This is a bin command put in all bins.
624  * Called per thread.
625  */
626 void
627 lp_rast_begin_query(struct lp_rasterizer_task *task,
628                     const union lp_rast_cmd_arg arg)
629 {
630    /* Reset the the per-task counter */
631    task->vis_counter = 0;
632 }
633  
634
635 /**
636  * End the current occlusion query.
637  * This is a bin command put in all bins.
638  * Called per thread.
639  */
640 void
641 lp_rast_end_query(struct lp_rasterizer_task *task,
642                   const union lp_rast_cmd_arg arg)
643 {
644    struct llvmpipe_query *pq = arg.query_obj;
645
646    pipe_mutex_lock(pq->mutex);
647    {
648       /* Accumulate the visible fragment counter from this tile in
649        * the query object.
650        */
651       pq->count[task->thread_index] += task->vis_counter;
652
653       /* check if this is the last tile in the scene */
654       pq->tile_count++;
655       if (pq->tile_count == pq->num_tiles) {
656          uint i;
657
658          /* sum the per-thread counters for the query */
659          pq->result = 0;
660          for (i = 0; i < LP_MAX_THREADS; i++) {
661             pq->result += pq->count[i];
662          }
663
664          /* reset counters (in case this query is re-used in the scene) */
665          memset(pq->count, 0, sizeof(pq->count));
666
667          pq->tile_count = 0;
668          pq->binned = FALSE;
669          pq->done = TRUE;
670       }
671    }
672    pipe_mutex_unlock(pq->mutex);
673 }
674
675
676
677 /**
678  * Rasterize commands for a single bin.
679  * \param x, y  position of the bin's tile in the framebuffer
680  * Must be called between lp_rast_begin() and lp_rast_end().
681  * Called per thread.
682  */
683 static void
684 rasterize_bin(struct lp_rasterizer_task *task,
685               const struct cmd_bin *bin,
686               int x, int y)
687 {
688    const struct cmd_block_list *commands = &bin->commands;
689    struct cmd_block *block;
690    unsigned k;
691
692    lp_rast_tile_begin( task, x * TILE_SIZE, y * TILE_SIZE );
693
694    /* simply execute each of the commands in the block list */
695    for (block = commands->head; block; block = block->next) {
696       for (k = 0; k < block->count; k++) {
697          block->cmd[k]( task, block->arg[k] );
698       }
699    }
700
701    lp_rast_tile_end(task);
702
703    /* Free data for this bin.
704     */
705    lp_scene_bin_reset( task->rast->curr_scene, x, y);
706 }
707
708
709 #define RAST(x) { lp_rast_##x, #x }
710
711 static struct {
712    lp_rast_cmd cmd;
713    const char *name;
714 } cmd_names[] = 
715 {
716    RAST(clear_color),
717    RAST(clear_zstencil),
718    RAST(triangle),
719    RAST(shade_tile),
720    RAST(set_state),
721    RAST(store_color),
722    RAST(fence),
723    RAST(begin_query),
724    RAST(end_query),
725 };
726
727 static void
728 debug_bin( const struct cmd_bin *bin )
729 {
730    const struct cmd_block *head = bin->commands.head;
731    int i, j;
732
733    for (i = 0; i < head->count; i++) {
734       debug_printf("%d: ", i);
735       for (j = 0; j < Elements(cmd_names); j++) {
736          if (head->cmd[i] == cmd_names[j].cmd) {
737             debug_printf("%s\n", cmd_names[j].name);
738             break;
739          }
740       }
741       if (j == Elements(cmd_names))
742          debug_printf("...other\n");
743    }
744
745 }
746
747 /* An empty bin is one that just loads the contents of the tile and
748  * stores them again unchanged.  This typically happens when bins have
749  * been flushed for some reason in the middle of a frame, or when
750  * incremental updates are being made to a render target.
751  * 
752  * Try to avoid doing pointless work in this case.
753  */
754 static boolean
755 is_empty_bin( const struct cmd_bin *bin )
756 {
757    const struct cmd_block *head = bin->commands.head;
758    int i;
759    
760    if (0)
761       debug_bin(bin);
762    
763    /* We emit at most two load-tile commands at the start of the first
764     * command block.  In addition we seem to emit a couple of
765     * set-state commands even in empty bins.
766     *
767     * As a heuristic, if a bin has more than 4 commands, consider it
768     * non-empty.
769     */
770    if (head->next != NULL ||
771        head->count > 4) {
772       return FALSE;
773    }
774
775    for (i = 0; i < head->count; i++)
776       if (head->cmd[i] != lp_rast_set_state) {
777          return FALSE;
778       }
779
780    return TRUE;
781 }
782
783
784
785 /**
786  * Rasterize/execute all bins within a scene.
787  * Called per thread.
788  */
789 static void
790 rasterize_scene(struct lp_rasterizer_task *task,
791                 struct lp_scene *scene)
792 {
793    /* loop over scene bins, rasterize each */
794 #if 0
795    {
796       unsigned i, j;
797       for (i = 0; i < scene->tiles_x; i++) {
798          for (j = 0; j < scene->tiles_y; j++) {
799             struct cmd_bin *bin = lp_scene_get_bin(scene, i, j);
800             rasterize_bin(task, bin, i, j);
801          }
802       }
803    }
804 #else
805    {
806       struct cmd_bin *bin;
807       int x, y;
808
809       assert(scene);
810       while ((bin = lp_scene_bin_iter_next(scene, &x, &y))) {
811          if (!is_empty_bin( bin ))
812             rasterize_bin(task, bin, x, y);
813       }
814    }
815 #endif
816 }
817
818
819 /**
820  * Called by setup module when it has something for us to render.
821  */
822 void
823 lp_rast_queue_scene( struct lp_rasterizer *rast,
824                      struct lp_scene *scene)
825 {
826    LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);
827
828    if (rast->num_threads == 0) {
829       /* no threading */
830
831       lp_rast_begin( rast, scene );
832
833       rasterize_scene( &rast->tasks[0], scene );
834
835       lp_scene_reset( scene );
836
837       lp_rast_end( rast );
838
839       rast->curr_scene = NULL;
840    }
841    else {
842       /* threaded rendering! */
843       unsigned i;
844
845       lp_scene_enqueue( rast->full_scenes, scene );
846
847       /* signal the threads that there's work to do */
848       for (i = 0; i < rast->num_threads; i++) {
849          pipe_semaphore_signal(&rast->tasks[i].work_ready);
850       }
851    }
852
853    LP_DBG(DEBUG_SETUP, "%s done \n", __FUNCTION__);
854 }
855
856
857 void
858 lp_rast_finish( struct lp_rasterizer *rast )
859 {
860    if (rast->num_threads == 0) {
861       /* nothing to do */
862    }
863    else {
864       int i;
865
866       /* wait for work to complete */
867       for (i = 0; i < rast->num_threads; i++) {
868          pipe_semaphore_wait(&rast->tasks[i].work_done);
869       }
870    }
871 }
872
873
874 /**
875  * This is the thread's main entrypoint.
876  * It's a simple loop:
877  *   1. wait for work
878  *   2. do work
879  *   3. signal that we're done
880  */
881 static PIPE_THREAD_ROUTINE( thread_func, init_data )
882 {
883    struct lp_rasterizer_task *task = (struct lp_rasterizer_task *) init_data;
884    struct lp_rasterizer *rast = task->rast;
885    boolean debug = false;
886
887    while (1) {
888       /* wait for work */
889       if (debug)
890          debug_printf("thread %d waiting for work\n", task->thread_index);
891       pipe_semaphore_wait(&task->work_ready);
892
893       if (rast->exit_flag)
894          break;
895
896       if (task->thread_index == 0) {
897          /* thread[0]:
898           *  - get next scene to rasterize
899           *  - map the framebuffer surfaces
900           */
901          lp_rast_begin( rast, 
902                         lp_scene_dequeue( rast->full_scenes, TRUE ) );
903       }
904
905       /* Wait for all threads to get here so that threads[1+] don't
906        * get a null rast->curr_scene pointer.
907        */
908       pipe_barrier_wait( &rast->barrier );
909
910       /* do work */
911       if (debug)
912          debug_printf("thread %d doing work\n", task->thread_index);
913
914       rasterize_scene(task,
915                       rast->curr_scene);
916       
917       /* wait for all threads to finish with this scene */
918       pipe_barrier_wait( &rast->barrier );
919
920       /* XXX: shouldn't be necessary:
921        */
922       if (task->thread_index == 0) {
923          lp_rast_end( rast );
924       }
925
926       /* signal done with work */
927       if (debug)
928          debug_printf("thread %d done working\n", task->thread_index);
929
930       pipe_semaphore_signal(&task->work_done);
931    }
932
933    return NULL;
934 }
935
936
937 /**
938  * Initialize semaphores and spawn the threads.
939  */
940 static void
941 create_rast_threads(struct lp_rasterizer *rast)
942 {
943    unsigned i;
944
945    /* NOTE: if num_threads is zero, we won't use any threads */
946    for (i = 0; i < rast->num_threads; i++) {
947       pipe_semaphore_init(&rast->tasks[i].work_ready, 0);
948       pipe_semaphore_init(&rast->tasks[i].work_done, 0);
949       rast->threads[i] = pipe_thread_create(thread_func,
950                                             (void *) &rast->tasks[i]);
951    }
952 }
953
954
955
956 /**
957  * Create new lp_rasterizer.  If num_threads is zero, don't create any
958  * new threads, do rendering synchronously.
959  * \param num_threads  number of rasterizer threads to create
960  */
961 struct lp_rasterizer *
962 lp_rast_create( unsigned num_threads )
963 {
964    struct lp_rasterizer *rast;
965    unsigned i;
966
967    rast = CALLOC_STRUCT(lp_rasterizer);
968    if(!rast)
969       return NULL;
970
971    rast->full_scenes = lp_scene_queue_create();
972
973    for (i = 0; i < Elements(rast->tasks); i++) {
974       struct lp_rasterizer_task *task = &rast->tasks[i];
975       task->rast = rast;
976       task->thread_index = i;
977    }
978
979    rast->num_threads = num_threads;
980
981    create_rast_threads(rast);
982
983    /* for synchronizing rasterization threads */
984    pipe_barrier_init( &rast->barrier, rast->num_threads );
985
986    return rast;
987 }
988
989
990 /* Shutdown:
991  */
992 void lp_rast_destroy( struct lp_rasterizer *rast )
993 {
994    unsigned i;
995
996    /* Set exit_flag and signal each thread's work_ready semaphore.
997     * Each thread will be woken up, notice that the exit_flag is set and
998     * break out of its main loop.  The thread will then exit.
999     */
1000    rast->exit_flag = TRUE;
1001    for (i = 0; i < rast->num_threads; i++) {
1002       pipe_semaphore_signal(&rast->tasks[i].work_ready);
1003    }
1004
1005    /* Wait for threads to terminate before cleaning up per-thread data */
1006    for (i = 0; i < rast->num_threads; i++) {
1007       pipe_thread_wait(rast->threads[i]);
1008    }
1009
1010    /* Clean up per-thread data */
1011    for (i = 0; i < rast->num_threads; i++) {
1012       pipe_semaphore_destroy(&rast->tasks[i].work_ready);
1013       pipe_semaphore_destroy(&rast->tasks[i].work_done);
1014    }
1015
1016    /* for synchronizing rasterization threads */
1017    pipe_barrier_destroy( &rast->barrier );
1018
1019    lp_scene_queue_destroy(rast->full_scenes);
1020
1021    FREE(rast);
1022 }
1023
1024
1025 /** Return number of rasterization threads */
1026 unsigned
1027 lp_rast_get_num_threads( struct lp_rasterizer *rast )
1028 {
1029    return rast->num_threads;
1030 }
1031
1032