Tizen 2.0 Release
[profile/ivi/osmesa.git] / src / mesa / state_tracker / st_gen_mipmap.c
1 /**************************************************************************
2  * 
3  * Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
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 TUNGSTEN GRAPHICS 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
29 #include "main/imports.h"
30 #include "main/mipmap.h"
31 #include "main/teximage.h"
32
33 #include "pipe/p_context.h"
34 #include "pipe/p_defines.h"
35 #include "util/u_inlines.h"
36 #include "util/u_format.h"
37 #include "util/u_gen_mipmap.h"
38
39 #include "st_debug.h"
40 #include "st_context.h"
41 #include "st_texture.h"
42 #include "st_gen_mipmap.h"
43 #include "st_cb_texture.h"
44
45
46 /**
47  * one-time init for generate mipmap
48  * XXX Note: there may be other times we need no-op/simple state like this.
49  * In that case, some code refactoring would be good.
50  */
51 void
52 st_init_generate_mipmap(struct st_context *st)
53 {
54    st->gen_mipmap = util_create_gen_mipmap(st->pipe, st->cso_context);
55 }
56
57
58 void
59 st_destroy_generate_mipmap(struct st_context *st)
60 {
61    util_destroy_gen_mipmap(st->gen_mipmap);
62    st->gen_mipmap = NULL;
63 }
64
65
66 /**
67  * Generate mipmap levels using hardware rendering.
68  * \return TRUE if successful, FALSE if not possible
69  */
70 static boolean
71 st_render_mipmap(struct st_context *st,
72                  GLenum target,
73                  struct st_texture_object *stObj,
74                  uint baseLevel, uint lastLevel)
75 {
76    struct pipe_context *pipe = st->pipe;
77    struct pipe_screen *screen = pipe->screen;
78    struct pipe_sampler_view *psv = st_get_texture_sampler_view(stObj, pipe);
79    const uint face = _mesa_tex_target_to_face(target);
80
81    assert(psv->texture == stObj->pt);
82 #if 0
83    assert(target != GL_TEXTURE_3D); /* implemented but untested */
84 #endif
85
86    /* check if we can render in the texture's format */
87    /* XXX should probably kill this and always use util_gen_mipmap
88       since this implements a sw fallback as well */
89    if (!screen->is_format_supported(screen, psv->format, psv->texture->target,
90                                     0, PIPE_BIND_RENDER_TARGET)) {
91       return FALSE;
92    }
93
94    /* Disable conditional rendering. */
95    if (st->render_condition) {
96       pipe->render_condition(pipe, NULL, 0);
97    }
98
99    util_gen_mipmap(st->gen_mipmap, psv, face, baseLevel, lastLevel,
100                    PIPE_TEX_FILTER_LINEAR);
101
102    if (st->render_condition) {
103       pipe->render_condition(pipe, st->render_condition, st->condition_mode);
104    }
105
106    return TRUE;
107 }
108
109
110 /**
111  * Helper function to decompress an image.  The result is a 32-bpp RGBA
112  * image with stride==width.
113  */
114 static void
115 decompress_image(enum pipe_format format, int datatype,
116                  const uint8_t *src, void *dst,
117                  unsigned width, unsigned height, unsigned src_stride)
118 {
119    const struct util_format_description *desc = util_format_description(format);
120    const uint bw = util_format_get_blockwidth(format);
121    const uint bh = util_format_get_blockheight(format);
122    uint dst_stride = 4 * MAX2(width, bw);
123
124    if (datatype == GL_FLOAT) {
125       desc->unpack_rgba_float((float *)dst, dst_stride * sizeof(GLfloat), src, src_stride, width, height);
126       if (width < bw || height < bh) {
127          float *dst_p = (float *)dst;
128          /* We're decompressing an image smaller than the compression
129           * block size.  We don't want garbage pixel values in the region
130           * outside (width x height) so replicate pixels from the (width
131           * x height) region to fill out the (bw x bh) block size.
132           */
133          uint x, y;
134          for (y = 0; y < bh; y++) {
135             for (x = 0; x < bw; x++) {
136                if (x >= width || y >= height) {
137                   uint p = (y * bw + x) * 4;
138                   dst_p[p + 0] = dst_p[0];
139                   dst_p[p + 1] = dst_p[1];
140                   dst_p[p + 2] = dst_p[2];
141                   dst_p[p + 3] = dst_p[3];
142                }
143             }
144          }
145       }
146    } else {
147       desc->unpack_rgba_8unorm((uint8_t *)dst, dst_stride, src, src_stride, width, height);
148       if (width < bw || height < bh) {
149          uint8_t *dst_p = (uint8_t *)dst;
150          /* We're decompressing an image smaller than the compression
151           * block size.  We don't want garbage pixel values in the region
152           * outside (width x height) so replicate pixels from the (width
153           * x height) region to fill out the (bw x bh) block size.
154           */
155          uint x, y;
156          for (y = 0; y < bh; y++) {
157             for (x = 0; x < bw; x++) {
158                if (x >= width || y >= height) {
159                   uint p = (y * bw + x) * 4;
160                   dst_p[p + 0] = dst_p[0];
161                   dst_p[p + 1] = dst_p[1];
162                   dst_p[p + 2] = dst_p[2];
163                   dst_p[p + 3] = dst_p[3];
164                }
165             }
166          }
167       }
168    }
169 }
170
171 /**
172  * Helper function to compress an image.  The source is a 32-bpp RGBA image
173  * with stride==width.
174  */
175 static void
176 compress_image(enum pipe_format format, int datatype,
177                const void *src, uint8_t *dst,
178                unsigned width, unsigned height, unsigned dst_stride)
179 {
180    const struct util_format_description *desc = util_format_description(format);
181    const uint src_stride = 4 * width;
182
183    if (datatype == GL_FLOAT)
184       desc->pack_rgba_float(dst, dst_stride, (GLfloat *)src, src_stride * sizeof(GLfloat), width, height);
185    else
186       desc->pack_rgba_8unorm(dst, dst_stride, (uint8_t *)src, src_stride, width, height);
187 }
188
189
190 /**
191  * Software fallback for generate mipmap levels.
192  */
193 static void
194 fallback_generate_mipmap(struct gl_context *ctx, GLenum target,
195                          struct gl_texture_object *texObj)
196 {
197    struct pipe_context *pipe = st_context(ctx)->pipe;
198    struct pipe_resource *pt = st_get_texobj_resource(texObj);
199    const uint baseLevel = texObj->BaseLevel;
200    const uint lastLevel = pt->last_level;
201    const uint face = _mesa_tex_target_to_face(target);
202    uint dstLevel;
203    GLenum datatype;
204    GLuint comps;
205    GLboolean compressed;
206
207    if (ST_DEBUG & DEBUG_FALLBACK)
208       debug_printf("%s: fallback processing\n", __FUNCTION__);
209
210    assert(target != GL_TEXTURE_3D); /* not done yet */
211
212    compressed =
213       _mesa_is_format_compressed(texObj->Image[face][baseLevel]->TexFormat);
214
215    if (compressed) {
216       GLenum type =
217          _mesa_get_format_datatype(texObj->Image[face][baseLevel]->TexFormat);
218
219       datatype = type == GL_UNSIGNED_NORMALIZED ? GL_UNSIGNED_BYTE : GL_FLOAT;
220       comps = 4;
221    }
222    else {
223       _mesa_format_to_type_and_comps(texObj->Image[face][baseLevel]->TexFormat,
224                                      &datatype, &comps);
225       assert(comps > 0 && "bad texture format in fallback_generate_mipmap()");
226    }
227
228    for (dstLevel = baseLevel + 1; dstLevel <= lastLevel; dstLevel++) {
229       const uint srcLevel = dstLevel - 1;
230       const uint srcWidth = u_minify(pt->width0, srcLevel);
231       const uint srcHeight = u_minify(pt->height0, srcLevel);
232       const uint srcDepth = u_minify(pt->depth0, srcLevel);
233       const uint dstWidth = u_minify(pt->width0, dstLevel);
234       const uint dstHeight = u_minify(pt->height0, dstLevel);
235       const uint dstDepth = u_minify(pt->depth0, dstLevel);
236       struct pipe_transfer *srcTrans, *dstTrans;
237       const ubyte *srcData;
238       ubyte *dstData;
239       int srcStride, dstStride;
240
241       srcTrans = pipe_get_transfer(pipe, pt, srcLevel,
242                                    face,
243                                    PIPE_TRANSFER_READ, 0, 0,
244                                    srcWidth, srcHeight);
245
246       dstTrans = pipe_get_transfer(pipe, pt, dstLevel,
247                                    face,
248                                    PIPE_TRANSFER_WRITE, 0, 0,
249                                    dstWidth, dstHeight);
250
251       srcData = (ubyte *) pipe_transfer_map(pipe, srcTrans);
252       dstData = (ubyte *) pipe_transfer_map(pipe, dstTrans);
253
254       srcStride = srcTrans->stride / util_format_get_blocksize(srcTrans->resource->format);
255       dstStride = dstTrans->stride / util_format_get_blocksize(dstTrans->resource->format);
256
257      /* this cannot work correctly for 3d since it does
258         not respect layerStride. */
259       if (compressed) {
260          const enum pipe_format format = pt->format;
261          const uint bw = util_format_get_blockwidth(format);
262          const uint bh = util_format_get_blockheight(format);
263          const uint srcWidth2 = align(srcWidth, bw);
264          const uint srcHeight2 = align(srcHeight, bh);
265          const uint dstWidth2 = align(dstWidth, bw);
266          const uint dstHeight2 = align(dstHeight, bh);
267          uint8_t *srcTemp, *dstTemp;
268
269          assert(comps == 4);
270
271          srcTemp = malloc(srcWidth2 * srcHeight2 * comps * (datatype == GL_FLOAT ? 4 : 1));
272          dstTemp = malloc(dstWidth2 * dstHeight2 * comps * (datatype == GL_FLOAT ? 4 : 1));
273
274          /* decompress the src image: srcData -> srcTemp */
275          decompress_image(format, datatype, srcData, srcTemp, srcWidth2, srcHeight2, srcTrans->stride);
276
277          _mesa_generate_mipmap_level(target, datatype, comps,
278                                      0 /*border*/,
279                                      srcWidth2, srcHeight2, srcDepth,
280                                      srcTemp,
281                                      srcWidth2, /* stride in texels */
282                                      dstWidth2, dstHeight2, dstDepth,
283                                      dstTemp,
284                                      dstWidth2); /* stride in texels */
285
286          /* compress the new image: dstTemp -> dstData */
287          compress_image(format, datatype, dstTemp, dstData, dstWidth2, dstHeight2, dstTrans->stride);
288
289          free(srcTemp);
290          free(dstTemp);
291       }
292       else {
293          _mesa_generate_mipmap_level(target, datatype, comps,
294                                      0 /*border*/,
295                                      srcWidth, srcHeight, srcDepth,
296                                      srcData,
297                                      srcStride, /* stride in texels */
298                                      dstWidth, dstHeight, dstDepth,
299                                      dstData,
300                                      dstStride); /* stride in texels */
301       }
302
303       pipe_transfer_unmap(pipe, srcTrans);
304       pipe_transfer_unmap(pipe, dstTrans);
305
306       pipe->transfer_destroy(pipe, srcTrans);
307       pipe->transfer_destroy(pipe, dstTrans);
308    }
309 }
310
311
312 /**
313  * Compute the expected number of mipmap levels in the texture given
314  * the width/height/depth of the base image and the GL_TEXTURE_BASE_LEVEL/
315  * GL_TEXTURE_MAX_LEVEL settings.  This will tell us how many mipmap
316  * levels should be generated.
317  */
318 static GLuint
319 compute_num_levels(struct gl_context *ctx,
320                    struct gl_texture_object *texObj,
321                    GLenum target)
322 {
323    if (target == GL_TEXTURE_RECTANGLE_ARB) {
324       return 1;
325    }
326    else {
327       const struct gl_texture_image *baseImage = 
328          _mesa_get_tex_image(ctx, texObj, target, texObj->BaseLevel);
329       GLuint size, numLevels;
330
331       size = MAX2(baseImage->Width2, baseImage->Height2);
332       size = MAX2(size, baseImage->Depth2);
333
334       numLevels = texObj->BaseLevel;
335
336       while (size > 0) {
337          numLevels++;
338          size >>= 1;
339       }
340
341       numLevels = MIN2(numLevels, texObj->MaxLevel + 1);
342
343       assert(numLevels >= 1);
344
345       return numLevels;
346    }
347 }
348
349
350 /**
351  * Called via ctx->Driver.GenerateMipmap().
352  */
353 void
354 st_generate_mipmap(struct gl_context *ctx, GLenum target,
355                    struct gl_texture_object *texObj)
356 {
357    struct st_context *st = st_context(ctx);
358    struct st_texture_object *stObj = st_texture_object(texObj);
359    struct pipe_resource *pt = st_get_texobj_resource(texObj);
360    const uint baseLevel = texObj->BaseLevel;
361    uint lastLevel;
362    uint dstLevel;
363
364    if (!pt)
365       return;
366
367    /* not sure if this ultimately actually should work,
368       but we're not supporting multisampled textures yet. */
369    assert(pt->nr_samples < 2);
370
371    /* find expected last mipmap level to generate*/
372    lastLevel = compute_num_levels(ctx, texObj, target) - 1;
373
374    if (lastLevel == 0)
375       return;
376
377    /* The texture isn't in a "complete" state yet so set the expected
378     * lastLevel here, since it won't get done in st_finalize_texture().
379     */
380    stObj->lastLevel = lastLevel;
381
382    if (pt->last_level < lastLevel) {
383       /* The current gallium texture doesn't have space for all the
384        * mipmap levels we need to generate.  So allocate a new texture.
385        */
386       struct pipe_resource *oldTex = stObj->pt;
387
388       /* create new texture with space for more levels */
389       stObj->pt = st_texture_create(st,
390                                     oldTex->target,
391                                     oldTex->format,
392                                     lastLevel,
393                                     oldTex->width0,
394                                     oldTex->height0,
395                                     oldTex->depth0,
396                                     oldTex->array_size,
397                                     oldTex->bind);
398
399       /* This will copy the old texture's base image into the new texture
400        * which we just allocated.
401        */
402       st_finalize_texture(ctx, st->pipe, texObj);
403
404       /* release the old tex (will likely be freed too) */
405       pipe_resource_reference(&oldTex, NULL);
406       pipe_sampler_view_reference(&stObj->sampler_view, NULL);
407    }
408    else {
409       /* Make sure that the base texture image data is present in the
410        * texture buffer.
411        */
412       st_finalize_texture(ctx, st->pipe, texObj);
413    }
414
415    pt = stObj->pt;
416
417    assert(pt->last_level >= lastLevel);
418
419    /* Try to generate the mipmap by rendering/texturing.  If that fails,
420     * use the software fallback.
421     */
422    if (!st_render_mipmap(st, target, stObj, baseLevel, lastLevel)) {
423       /* since the util code actually also has a fallback, should
424          probably make it never fail and kill this */
425       fallback_generate_mipmap(ctx, target, texObj);
426    }
427
428    /* Fill in the Mesa gl_texture_image fields */
429    for (dstLevel = baseLevel + 1; dstLevel <= lastLevel; dstLevel++) {
430       const uint srcLevel = dstLevel - 1;
431       const struct gl_texture_image *srcImage
432          = _mesa_get_tex_image(ctx, texObj, target, srcLevel);
433       struct gl_texture_image *dstImage;
434       struct st_texture_image *stImage;
435       uint dstWidth = u_minify(pt->width0, dstLevel);
436       uint dstHeight = u_minify(pt->height0, dstLevel);
437       uint dstDepth = u_minify(pt->depth0, dstLevel); 
438       uint border = srcImage->Border;
439
440       dstImage = _mesa_get_tex_image(ctx, texObj, target, dstLevel);
441       if (!dstImage) {
442          _mesa_error(ctx, GL_OUT_OF_MEMORY, "generating mipmaps");
443          return;
444       }
445
446       /* Free old image data */
447       if (dstImage->Data)
448          ctx->Driver.FreeTexImageData(ctx, dstImage);
449
450       /* initialize new image */
451       _mesa_init_teximage_fields(ctx, target, dstImage, dstWidth, dstHeight,
452                                  dstDepth, border, srcImage->InternalFormat,
453                                  srcImage->TexFormat);
454
455       stImage = st_texture_image(dstImage);
456       stImage->level = dstLevel;
457
458       pipe_resource_reference(&stImage->pt, pt);
459    }
460 }