• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * \file texobj.c
3  * Texture object management.
4  */
5 
6 /*
7  * Mesa 3-D graphics library
8  *
9  * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included
19  * in all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
24  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
25  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
26  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27  * OTHER DEALINGS IN THE SOFTWARE.
28  */
29 
30 
31 #include <stdio.h>
32 #include "bufferobj.h"
33 #include "context.h"
34 #include "enums.h"
35 #include "fbobject.h"
36 #include "formats.h"
37 #include "hash.h"
38 #include "imports.h"
39 #include "macros.h"
40 #include "shaderimage.h"
41 #include "teximage.h"
42 #include "texobj.h"
43 #include "texstate.h"
44 #include "mtypes.h"
45 #include "program/prog_instruction.h"
46 
47 
48 
49 /**********************************************************************/
50 /** \name Internal functions */
51 /*@{*/
52 
53 /**
54  * This function checks for all valid combinations of Min and Mag filters for
55  * Float types, when extensions like OES_texture_float and
56  * OES_texture_float_linear are supported. OES_texture_float mentions support
57  * for NEAREST, NEAREST_MIPMAP_NEAREST magnification and minification filters.
58  * Mag filters like LINEAR and min filters like NEAREST_MIPMAP_LINEAR,
59  * LINEAR_MIPMAP_NEAREST and LINEAR_MIPMAP_LINEAR are only valid in case
60  * OES_texture_float_linear is supported.
61  *
62  * Returns true in case the filter is valid for given Float type else false.
63  */
64 static bool
valid_filter_for_float(const struct gl_context * ctx,const struct gl_texture_object * obj)65 valid_filter_for_float(const struct gl_context *ctx,
66                        const struct gl_texture_object *obj)
67 {
68    switch (obj->Sampler.MagFilter) {
69    case GL_LINEAR:
70       if (obj->_IsHalfFloat && !ctx->Extensions.OES_texture_half_float_linear) {
71          return false;
72       } else if (obj->_IsFloat && !ctx->Extensions.OES_texture_float_linear) {
73          return false;
74       }
75    case GL_NEAREST:
76    case GL_NEAREST_MIPMAP_NEAREST:
77       break;
78    default:
79       unreachable("Invalid mag filter");
80    }
81 
82    switch (obj->Sampler.MinFilter) {
83    case GL_LINEAR:
84    case GL_NEAREST_MIPMAP_LINEAR:
85    case GL_LINEAR_MIPMAP_NEAREST:
86    case GL_LINEAR_MIPMAP_LINEAR:
87       if (obj->_IsHalfFloat && !ctx->Extensions.OES_texture_half_float_linear) {
88          return false;
89       } else if (obj->_IsFloat && !ctx->Extensions.OES_texture_float_linear) {
90          return false;
91       }
92    case GL_NEAREST:
93    case GL_NEAREST_MIPMAP_NEAREST:
94       break;
95    default:
96       unreachable("Invalid min filter");
97    }
98 
99    return true;
100 }
101 
102 /**
103  * Return the gl_texture_object for a given ID.
104  */
105 struct gl_texture_object *
_mesa_lookup_texture(struct gl_context * ctx,GLuint id)106 _mesa_lookup_texture(struct gl_context *ctx, GLuint id)
107 {
108    return (struct gl_texture_object *)
109       _mesa_HashLookup(ctx->Shared->TexObjects, id);
110 }
111 
112 /**
113  * Wrapper around _mesa_lookup_texture that throws GL_INVALID_OPERATION if id
114  * is not in the hash table. After calling _mesa_error, it returns NULL.
115  */
116 struct gl_texture_object *
_mesa_lookup_texture_err(struct gl_context * ctx,GLuint id,const char * func)117 _mesa_lookup_texture_err(struct gl_context *ctx, GLuint id, const char* func)
118 {
119    struct gl_texture_object *texObj = NULL;
120 
121    if (id > 0)
122       texObj = _mesa_lookup_texture(ctx, id); /* Returns NULL if not found. */
123 
124    if (!texObj)
125       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(texture)", func);
126 
127    return texObj;
128 }
129 
130 void
_mesa_begin_texture_lookups(struct gl_context * ctx)131 _mesa_begin_texture_lookups(struct gl_context *ctx)
132 {
133    _mesa_HashLockMutex(ctx->Shared->TexObjects);
134 }
135 
136 
137 void
_mesa_end_texture_lookups(struct gl_context * ctx)138 _mesa_end_texture_lookups(struct gl_context *ctx)
139 {
140    _mesa_HashUnlockMutex(ctx->Shared->TexObjects);
141 }
142 
143 
144 struct gl_texture_object *
_mesa_lookup_texture_locked(struct gl_context * ctx,GLuint id)145 _mesa_lookup_texture_locked(struct gl_context *ctx, GLuint id)
146 {
147    return (struct gl_texture_object *)
148       _mesa_HashLookupLocked(ctx->Shared->TexObjects, id);
149 }
150 
151 /**
152  * Return a pointer to the current texture object for the given target
153  * on the current texture unit.
154  * Note: all <target> error checking should have been done by this point.
155  */
156 struct gl_texture_object *
_mesa_get_current_tex_object(struct gl_context * ctx,GLenum target)157 _mesa_get_current_tex_object(struct gl_context *ctx, GLenum target)
158 {
159    struct gl_texture_unit *texUnit = _mesa_get_current_tex_unit(ctx);
160    const GLboolean arrayTex = ctx->Extensions.EXT_texture_array;
161 
162    switch (target) {
163       case GL_TEXTURE_1D:
164          return texUnit->CurrentTex[TEXTURE_1D_INDEX];
165       case GL_PROXY_TEXTURE_1D:
166          return ctx->Texture.ProxyTex[TEXTURE_1D_INDEX];
167       case GL_TEXTURE_2D:
168          return texUnit->CurrentTex[TEXTURE_2D_INDEX];
169       case GL_PROXY_TEXTURE_2D:
170          return ctx->Texture.ProxyTex[TEXTURE_2D_INDEX];
171       case GL_TEXTURE_3D:
172          return texUnit->CurrentTex[TEXTURE_3D_INDEX];
173       case GL_PROXY_TEXTURE_3D:
174          return ctx->Texture.ProxyTex[TEXTURE_3D_INDEX];
175       case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
176       case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
177       case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
178       case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
179       case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
180       case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
181       case GL_TEXTURE_CUBE_MAP:
182          return ctx->Extensions.ARB_texture_cube_map
183                 ? texUnit->CurrentTex[TEXTURE_CUBE_INDEX] : NULL;
184       case GL_PROXY_TEXTURE_CUBE_MAP:
185          return ctx->Extensions.ARB_texture_cube_map
186                 ? ctx->Texture.ProxyTex[TEXTURE_CUBE_INDEX] : NULL;
187       case GL_TEXTURE_CUBE_MAP_ARRAY:
188          return _mesa_has_texture_cube_map_array(ctx)
189                 ? texUnit->CurrentTex[TEXTURE_CUBE_ARRAY_INDEX] : NULL;
190       case GL_PROXY_TEXTURE_CUBE_MAP_ARRAY:
191          return _mesa_has_texture_cube_map_array(ctx)
192                 ? ctx->Texture.ProxyTex[TEXTURE_CUBE_ARRAY_INDEX] : NULL;
193       case GL_TEXTURE_RECTANGLE_NV:
194          return ctx->Extensions.NV_texture_rectangle
195                 ? texUnit->CurrentTex[TEXTURE_RECT_INDEX] : NULL;
196       case GL_PROXY_TEXTURE_RECTANGLE_NV:
197          return ctx->Extensions.NV_texture_rectangle
198                 ? ctx->Texture.ProxyTex[TEXTURE_RECT_INDEX] : NULL;
199       case GL_TEXTURE_1D_ARRAY_EXT:
200          return arrayTex ? texUnit->CurrentTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
201       case GL_PROXY_TEXTURE_1D_ARRAY_EXT:
202          return arrayTex ? ctx->Texture.ProxyTex[TEXTURE_1D_ARRAY_INDEX] : NULL;
203       case GL_TEXTURE_2D_ARRAY_EXT:
204          return arrayTex ? texUnit->CurrentTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
205       case GL_PROXY_TEXTURE_2D_ARRAY_EXT:
206          return arrayTex ? ctx->Texture.ProxyTex[TEXTURE_2D_ARRAY_INDEX] : NULL;
207       case GL_TEXTURE_BUFFER:
208          return (_mesa_has_ARB_texture_buffer_object(ctx) ||
209                  _mesa_has_OES_texture_buffer(ctx)) ?
210                 texUnit->CurrentTex[TEXTURE_BUFFER_INDEX] : NULL;
211       case GL_TEXTURE_EXTERNAL_OES:
212          return _mesa_is_gles(ctx) && ctx->Extensions.OES_EGL_image_external
213             ? texUnit->CurrentTex[TEXTURE_EXTERNAL_INDEX] : NULL;
214       case GL_TEXTURE_2D_MULTISAMPLE:
215          return ctx->Extensions.ARB_texture_multisample
216             ? texUnit->CurrentTex[TEXTURE_2D_MULTISAMPLE_INDEX] : NULL;
217       case GL_PROXY_TEXTURE_2D_MULTISAMPLE:
218          return ctx->Extensions.ARB_texture_multisample
219             ? ctx->Texture.ProxyTex[TEXTURE_2D_MULTISAMPLE_INDEX] : NULL;
220       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
221          return ctx->Extensions.ARB_texture_multisample
222             ? texUnit->CurrentTex[TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX] : NULL;
223       case GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY:
224          return ctx->Extensions.ARB_texture_multisample
225             ? ctx->Texture.ProxyTex[TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX] : NULL;
226       default:
227          _mesa_problem(NULL, "bad target in _mesa_get_current_tex_object()");
228          return NULL;
229    }
230 }
231 
232 
233 /**
234  * Allocate and initialize a new texture object.  But don't put it into the
235  * texture object hash table.
236  *
237  * Called via ctx->Driver.NewTextureObject, unless overridden by a device
238  * driver.
239  *
240  * \param shared the shared GL state structure to contain the texture object
241  * \param name integer name for the texture object
242  * \param target either GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D,
243  * GL_TEXTURE_CUBE_MAP or GL_TEXTURE_RECTANGLE_NV.  zero is ok for the sake
244  * of GenTextures()
245  *
246  * \return pointer to new texture object.
247  */
248 struct gl_texture_object *
_mesa_new_texture_object(struct gl_context * ctx,GLuint name,GLenum target)249 _mesa_new_texture_object( struct gl_context *ctx, GLuint name, GLenum target )
250 {
251    struct gl_texture_object *obj;
252    (void) ctx;
253    obj = MALLOC_STRUCT(gl_texture_object);
254    _mesa_initialize_texture_object(ctx, obj, name, target);
255    return obj;
256 }
257 
258 
259 /**
260  * Initialize a new texture object to default values.
261  * \param obj  the texture object
262  * \param name  the texture name
263  * \param target  the texture target
264  */
265 void
_mesa_initialize_texture_object(struct gl_context * ctx,struct gl_texture_object * obj,GLuint name,GLenum target)266 _mesa_initialize_texture_object( struct gl_context *ctx,
267                                  struct gl_texture_object *obj,
268                                  GLuint name, GLenum target )
269 {
270    assert(target == 0 ||
271           target == GL_TEXTURE_1D ||
272           target == GL_TEXTURE_2D ||
273           target == GL_TEXTURE_3D ||
274           target == GL_TEXTURE_CUBE_MAP ||
275           target == GL_TEXTURE_RECTANGLE_NV ||
276           target == GL_TEXTURE_1D_ARRAY_EXT ||
277           target == GL_TEXTURE_2D_ARRAY_EXT ||
278           target == GL_TEXTURE_EXTERNAL_OES ||
279           target == GL_TEXTURE_CUBE_MAP_ARRAY ||
280           target == GL_TEXTURE_BUFFER ||
281           target == GL_TEXTURE_2D_MULTISAMPLE ||
282           target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY);
283 
284    memset(obj, 0, sizeof(*obj));
285    /* init the non-zero fields */
286    mtx_init(&obj->Mutex, mtx_plain);
287    obj->RefCount = 1;
288    obj->Name = name;
289    obj->Target = target;
290    if (target != 0) {
291       obj->TargetIndex = _mesa_tex_target_to_index(ctx, target);
292    }
293    else {
294       obj->TargetIndex = NUM_TEXTURE_TARGETS; /* invalid/error value */
295    }
296    obj->Priority = 1.0F;
297    obj->BaseLevel = 0;
298    obj->MaxLevel = 1000;
299 
300    /* must be one; no support for (YUV) planes in separate buffers */
301    obj->RequiredTextureImageUnits = 1;
302 
303    /* sampler state */
304    if (target == GL_TEXTURE_RECTANGLE_NV ||
305        target == GL_TEXTURE_EXTERNAL_OES) {
306       obj->Sampler.WrapS = GL_CLAMP_TO_EDGE;
307       obj->Sampler.WrapT = GL_CLAMP_TO_EDGE;
308       obj->Sampler.WrapR = GL_CLAMP_TO_EDGE;
309       obj->Sampler.MinFilter = GL_LINEAR;
310    }
311    else {
312       obj->Sampler.WrapS = GL_REPEAT;
313       obj->Sampler.WrapT = GL_REPEAT;
314       obj->Sampler.WrapR = GL_REPEAT;
315       obj->Sampler.MinFilter = GL_NEAREST_MIPMAP_LINEAR;
316    }
317    obj->Sampler.MagFilter = GL_LINEAR;
318    obj->Sampler.MinLod = -1000.0;
319    obj->Sampler.MaxLod = 1000.0;
320    obj->Sampler.LodBias = 0.0;
321    obj->Sampler.MaxAnisotropy = 1.0;
322    obj->Sampler.CompareMode = GL_NONE;         /* ARB_shadow */
323    obj->Sampler.CompareFunc = GL_LEQUAL;       /* ARB_shadow */
324    obj->DepthMode = ctx->API == API_OPENGL_CORE ? GL_RED : GL_LUMINANCE;
325    obj->StencilSampling = false;
326    obj->Sampler.CubeMapSeamless = GL_FALSE;
327    obj->Swizzle[0] = GL_RED;
328    obj->Swizzle[1] = GL_GREEN;
329    obj->Swizzle[2] = GL_BLUE;
330    obj->Swizzle[3] = GL_ALPHA;
331    obj->_Swizzle = SWIZZLE_NOOP;
332    obj->Sampler.sRGBDecode = GL_DECODE_EXT;
333    obj->BufferObjectFormat = GL_R8;
334    obj->_BufferObjectFormat = MESA_FORMAT_R_UNORM8;
335    obj->ImageFormatCompatibilityType = GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE;
336 }
337 
338 
339 /**
340  * Some texture initialization can't be finished until we know which
341  * target it's getting bound to (GL_TEXTURE_1D/2D/etc).
342  */
343 static void
finish_texture_init(struct gl_context * ctx,GLenum target,struct gl_texture_object * obj)344 finish_texture_init(struct gl_context *ctx, GLenum target,
345                     struct gl_texture_object *obj)
346 {
347    GLenum filter = GL_LINEAR;
348    assert(obj->Target == 0);
349 
350    obj->Target = target;
351    obj->TargetIndex = _mesa_tex_target_to_index(ctx, target);
352    assert(obj->TargetIndex < NUM_TEXTURE_TARGETS);
353 
354    switch (target) {
355       case GL_TEXTURE_2D_MULTISAMPLE:
356       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
357          filter = GL_NEAREST;
358          /* fallthrough */
359 
360       case GL_TEXTURE_RECTANGLE_NV:
361       case GL_TEXTURE_EXTERNAL_OES:
362          /* have to init wrap and filter state here - kind of klunky */
363          obj->Sampler.WrapS = GL_CLAMP_TO_EDGE;
364          obj->Sampler.WrapT = GL_CLAMP_TO_EDGE;
365          obj->Sampler.WrapR = GL_CLAMP_TO_EDGE;
366          obj->Sampler.MinFilter = filter;
367          obj->Sampler.MagFilter = filter;
368          if (ctx->Driver.TexParameter) {
369             /* XXX we probably don't need to make all these calls */
370             ctx->Driver.TexParameter(ctx, obj, GL_TEXTURE_WRAP_S);
371             ctx->Driver.TexParameter(ctx, obj, GL_TEXTURE_WRAP_T);
372             ctx->Driver.TexParameter(ctx, obj, GL_TEXTURE_WRAP_R);
373             ctx->Driver.TexParameter(ctx, obj, GL_TEXTURE_MIN_FILTER);
374             ctx->Driver.TexParameter(ctx, obj, GL_TEXTURE_MAG_FILTER);
375          }
376          break;
377 
378       default:
379          /* nothing needs done */
380          break;
381    }
382 }
383 
384 
385 /**
386  * Deallocate a texture object struct.  It should have already been
387  * removed from the texture object pool.
388  * Called via ctx->Driver.DeleteTexture() if not overriden by a driver.
389  *
390  * \param shared the shared GL state to which the object belongs.
391  * \param texObj the texture object to delete.
392  */
393 void
_mesa_delete_texture_object(struct gl_context * ctx,struct gl_texture_object * texObj)394 _mesa_delete_texture_object(struct gl_context *ctx,
395                             struct gl_texture_object *texObj)
396 {
397    GLuint i, face;
398 
399    /* Set Target to an invalid value.  With some assertions elsewhere
400     * we can try to detect possible use of deleted textures.
401     */
402    texObj->Target = 0x99;
403 
404    /* free the texture images */
405    for (face = 0; face < 6; face++) {
406       for (i = 0; i < MAX_TEXTURE_LEVELS; i++) {
407          if (texObj->Image[face][i]) {
408             ctx->Driver.DeleteTextureImage(ctx, texObj->Image[face][i]);
409          }
410       }
411    }
412 
413    _mesa_reference_buffer_object(ctx, &texObj->BufferObject, NULL);
414 
415    /* destroy the mutex -- it may have allocated memory (eg on bsd) */
416    mtx_destroy(&texObj->Mutex);
417 
418    free(texObj->Label);
419 
420    /* free this object */
421    free(texObj);
422 }
423 
424 
425 /**
426  * Copy texture object state from one texture object to another.
427  * Use for glPush/PopAttrib.
428  *
429  * \param dest destination texture object.
430  * \param src source texture object.
431  */
432 void
_mesa_copy_texture_object(struct gl_texture_object * dest,const struct gl_texture_object * src)433 _mesa_copy_texture_object( struct gl_texture_object *dest,
434                            const struct gl_texture_object *src )
435 {
436    dest->Target = src->Target;
437    dest->TargetIndex = src->TargetIndex;
438    dest->Name = src->Name;
439    dest->Priority = src->Priority;
440    dest->Sampler.BorderColor.f[0] = src->Sampler.BorderColor.f[0];
441    dest->Sampler.BorderColor.f[1] = src->Sampler.BorderColor.f[1];
442    dest->Sampler.BorderColor.f[2] = src->Sampler.BorderColor.f[2];
443    dest->Sampler.BorderColor.f[3] = src->Sampler.BorderColor.f[3];
444    dest->Sampler.WrapS = src->Sampler.WrapS;
445    dest->Sampler.WrapT = src->Sampler.WrapT;
446    dest->Sampler.WrapR = src->Sampler.WrapR;
447    dest->Sampler.MinFilter = src->Sampler.MinFilter;
448    dest->Sampler.MagFilter = src->Sampler.MagFilter;
449    dest->Sampler.MinLod = src->Sampler.MinLod;
450    dest->Sampler.MaxLod = src->Sampler.MaxLod;
451    dest->Sampler.LodBias = src->Sampler.LodBias;
452    dest->BaseLevel = src->BaseLevel;
453    dest->MaxLevel = src->MaxLevel;
454    dest->Sampler.MaxAnisotropy = src->Sampler.MaxAnisotropy;
455    dest->Sampler.CompareMode = src->Sampler.CompareMode;
456    dest->Sampler.CompareFunc = src->Sampler.CompareFunc;
457    dest->Sampler.CubeMapSeamless = src->Sampler.CubeMapSeamless;
458    dest->DepthMode = src->DepthMode;
459    dest->StencilSampling = src->StencilSampling;
460    dest->Sampler.sRGBDecode = src->Sampler.sRGBDecode;
461    dest->_MaxLevel = src->_MaxLevel;
462    dest->_MaxLambda = src->_MaxLambda;
463    dest->GenerateMipmap = src->GenerateMipmap;
464    dest->_BaseComplete = src->_BaseComplete;
465    dest->_MipmapComplete = src->_MipmapComplete;
466    COPY_4V(dest->Swizzle, src->Swizzle);
467    dest->_Swizzle = src->_Swizzle;
468    dest->_IsHalfFloat = src->_IsHalfFloat;
469    dest->_IsFloat = src->_IsFloat;
470 
471    dest->RequiredTextureImageUnits = src->RequiredTextureImageUnits;
472 }
473 
474 
475 /**
476  * Free all texture images of the given texture object.
477  *
478  * \param ctx GL context.
479  * \param t texture object.
480  *
481  * \sa _mesa_clear_texture_image().
482  */
483 void
_mesa_clear_texture_object(struct gl_context * ctx,struct gl_texture_object * texObj)484 _mesa_clear_texture_object(struct gl_context *ctx,
485                            struct gl_texture_object *texObj)
486 {
487    GLuint i, j;
488 
489    if (texObj->Target == 0)
490       return;
491 
492    for (i = 0; i < MAX_FACES; i++) {
493       for (j = 0; j < MAX_TEXTURE_LEVELS; j++) {
494          struct gl_texture_image *texImage = texObj->Image[i][j];
495          if (texImage)
496             _mesa_clear_texture_image(ctx, texImage);
497       }
498    }
499 }
500 
501 
502 /**
503  * Check if the given texture object is valid by examining its Target field.
504  * For debugging only.
505  */
506 static GLboolean
valid_texture_object(const struct gl_texture_object * tex)507 valid_texture_object(const struct gl_texture_object *tex)
508 {
509    switch (tex->Target) {
510    case 0:
511    case GL_TEXTURE_1D:
512    case GL_TEXTURE_2D:
513    case GL_TEXTURE_3D:
514    case GL_TEXTURE_CUBE_MAP:
515    case GL_TEXTURE_RECTANGLE_NV:
516    case GL_TEXTURE_1D_ARRAY_EXT:
517    case GL_TEXTURE_2D_ARRAY_EXT:
518    case GL_TEXTURE_BUFFER:
519    case GL_TEXTURE_EXTERNAL_OES:
520    case GL_TEXTURE_CUBE_MAP_ARRAY:
521    case GL_TEXTURE_2D_MULTISAMPLE:
522    case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
523       return GL_TRUE;
524    case 0x99:
525       _mesa_problem(NULL, "invalid reference to a deleted texture object");
526       return GL_FALSE;
527    default:
528       _mesa_problem(NULL, "invalid texture object Target 0x%x, Id = %u",
529                     tex->Target, tex->Name);
530       return GL_FALSE;
531    }
532 }
533 
534 
535 /**
536  * Reference (or unreference) a texture object.
537  * If '*ptr', decrement *ptr's refcount (and delete if it becomes zero).
538  * If 'tex' is non-null, increment its refcount.
539  * This is normally only called from the _mesa_reference_texobj() macro
540  * when there's a real pointer change.
541  */
542 void
_mesa_reference_texobj_(struct gl_texture_object ** ptr,struct gl_texture_object * tex)543 _mesa_reference_texobj_(struct gl_texture_object **ptr,
544                         struct gl_texture_object *tex)
545 {
546    assert(ptr);
547 
548    if (*ptr) {
549       /* Unreference the old texture */
550       GLboolean deleteFlag = GL_FALSE;
551       struct gl_texture_object *oldTex = *ptr;
552 
553       assert(valid_texture_object(oldTex));
554       (void) valid_texture_object; /* silence warning in release builds */
555 
556       mtx_lock(&oldTex->Mutex);
557       assert(oldTex->RefCount > 0);
558       oldTex->RefCount--;
559 
560       deleteFlag = (oldTex->RefCount == 0);
561       mtx_unlock(&oldTex->Mutex);
562 
563       if (deleteFlag) {
564          /* Passing in the context drastically changes the driver code for
565           * framebuffer deletion.
566           */
567          GET_CURRENT_CONTEXT(ctx);
568          if (ctx)
569             ctx->Driver.DeleteTexture(ctx, oldTex);
570          else
571             _mesa_problem(NULL, "Unable to delete texture, no context");
572       }
573 
574       *ptr = NULL;
575    }
576    assert(!*ptr);
577 
578    if (tex) {
579       /* reference new texture */
580       assert(valid_texture_object(tex));
581       mtx_lock(&tex->Mutex);
582       if (tex->RefCount == 0) {
583          /* this texture's being deleted (look just above) */
584          /* Not sure this can every really happen.  Warn if it does. */
585          _mesa_problem(NULL, "referencing deleted texture object");
586          *ptr = NULL;
587       }
588       else {
589          tex->RefCount++;
590          *ptr = tex;
591       }
592       mtx_unlock(&tex->Mutex);
593    }
594 }
595 
596 
597 enum base_mipmap { BASE, MIPMAP };
598 
599 
600 /**
601  * Mark a texture object as incomplete.  There are actually three kinds of
602  * (in)completeness:
603  * 1. "base incomplete": the base level of the texture is invalid so no
604  *    texturing is possible.
605  * 2. "mipmap incomplete": a non-base level of the texture is invalid so
606  *    mipmap filtering isn't possible, but non-mipmap filtering is.
607  * 3. "texture incompleteness": some combination of texture state and
608  *    sampler state renders the texture incomplete.
609  *
610  * \param t  texture object
611  * \param bm  either BASE or MIPMAP to indicate what's incomplete
612  * \param fmt...  string describing why it's incomplete (for debugging).
613  */
614 static void
incomplete(struct gl_texture_object * t,enum base_mipmap bm,const char * fmt,...)615 incomplete(struct gl_texture_object *t, enum base_mipmap bm,
616            const char *fmt, ...)
617 {
618    if (MESA_DEBUG_FLAGS & DEBUG_INCOMPLETE_TEXTURE) {
619       va_list args;
620       char s[100];
621 
622       va_start(args, fmt);
623       vsnprintf(s, sizeof(s), fmt, args);
624       va_end(args);
625 
626       _mesa_debug(NULL, "Texture Obj %d incomplete because: %s\n", t->Name, s);
627    }
628 
629    if (bm == BASE)
630       t->_BaseComplete = GL_FALSE;
631    t->_MipmapComplete = GL_FALSE;
632 }
633 
634 
635 /**
636  * Examine a texture object to determine if it is complete.
637  *
638  * The gl_texture_object::Complete flag will be set to GL_TRUE or GL_FALSE
639  * accordingly.
640  *
641  * \param ctx GL context.
642  * \param t texture object.
643  *
644  * According to the texture target, verifies that each of the mipmaps is
645  * present and has the expected size.
646  */
647 void
_mesa_test_texobj_completeness(const struct gl_context * ctx,struct gl_texture_object * t)648 _mesa_test_texobj_completeness( const struct gl_context *ctx,
649                                 struct gl_texture_object *t )
650 {
651    const GLint baseLevel = t->BaseLevel;
652    const struct gl_texture_image *baseImage;
653    GLint maxLevels = 0;
654 
655    /* We'll set these to FALSE if tests fail below */
656    t->_BaseComplete = GL_TRUE;
657    t->_MipmapComplete = GL_TRUE;
658 
659    if (t->Target == GL_TEXTURE_BUFFER) {
660       /* Buffer textures are always considered complete.  The obvious case where
661        * they would be incomplete (no BO attached) is actually specced to be
662        * undefined rendering results.
663        */
664       return;
665    }
666 
667    /* Detect cases where the application set the base level to an invalid
668     * value.
669     */
670    if ((baseLevel < 0) || (baseLevel >= MAX_TEXTURE_LEVELS)) {
671       incomplete(t, BASE, "base level = %d is invalid", baseLevel);
672       return;
673    }
674 
675    if (t->MaxLevel < baseLevel) {
676       incomplete(t, MIPMAP, "MAX_LEVEL (%d) < BASE_LEVEL (%d)",
677 		 t->MaxLevel, baseLevel);
678       return;
679    }
680 
681    baseImage = t->Image[0][baseLevel];
682 
683    /* Always need the base level image */
684    if (!baseImage) {
685       incomplete(t, BASE, "Image[baseLevel=%d] == NULL", baseLevel);
686       return;
687    }
688 
689    /* Check width/height/depth for zero */
690    if (baseImage->Width == 0 ||
691        baseImage->Height == 0 ||
692        baseImage->Depth == 0) {
693       incomplete(t, BASE, "texture width or height or depth = 0");
694       return;
695    }
696 
697    /* Check if the texture values are integer */
698    {
699       GLenum datatype = _mesa_get_format_datatype(baseImage->TexFormat);
700       t->_IsIntegerFormat = datatype == GL_INT || datatype == GL_UNSIGNED_INT;
701    }
702 
703    /* Check if the texture type is Float or HalfFloatOES and ensure Min and Mag
704     * filters are supported in this case.
705     */
706    if (_mesa_is_gles(ctx) && !valid_filter_for_float(ctx, t)) {
707       incomplete(t, BASE, "Filter is not supported with Float types.");
708       return;
709    }
710 
711    /* Compute _MaxLevel (the maximum mipmap level we'll sample from given the
712     * mipmap image sizes and GL_TEXTURE_MAX_LEVEL state).
713     */
714    switch (t->Target) {
715    case GL_TEXTURE_1D:
716    case GL_TEXTURE_1D_ARRAY_EXT:
717       maxLevels = ctx->Const.MaxTextureLevels;
718       break;
719    case GL_TEXTURE_2D:
720    case GL_TEXTURE_2D_ARRAY_EXT:
721       maxLevels = ctx->Const.MaxTextureLevels;
722       break;
723    case GL_TEXTURE_3D:
724       maxLevels = ctx->Const.Max3DTextureLevels;
725       break;
726    case GL_TEXTURE_CUBE_MAP:
727    case GL_TEXTURE_CUBE_MAP_ARRAY:
728       maxLevels = ctx->Const.MaxCubeTextureLevels;
729       break;
730    case GL_TEXTURE_RECTANGLE_NV:
731    case GL_TEXTURE_BUFFER:
732    case GL_TEXTURE_EXTERNAL_OES:
733    case GL_TEXTURE_2D_MULTISAMPLE:
734    case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
735       maxLevels = 1;  /* no mipmapping */
736       break;
737    default:
738       _mesa_problem(ctx, "Bad t->Target in _mesa_test_texobj_completeness");
739       return;
740    }
741 
742    assert(maxLevels > 0);
743 
744    t->_MaxLevel = MIN3(t->MaxLevel,
745                        /* 'p' in the GL spec */
746                        (int) (baseLevel + baseImage->MaxNumLevels - 1),
747                        /* 'q' in the GL spec */
748                        maxLevels - 1);
749 
750    if (t->Immutable) {
751       /* Adjust max level for views: the data store may have more levels than
752        * the view exposes.
753        */
754       t->_MaxLevel = MIN2(t->_MaxLevel, t->NumLevels - 1);
755    }
756 
757    /* Compute _MaxLambda = q - p in the spec used during mipmapping */
758    t->_MaxLambda = (GLfloat) (t->_MaxLevel - baseLevel);
759 
760    if (t->Immutable) {
761       /* This texture object was created with glTexStorage1/2/3D() so we
762        * know that all the mipmap levels are the right size and all cube
763        * map faces are the same size.
764        * We don't need to do any of the additional checks below.
765        */
766       return;
767    }
768 
769    if (t->Target == GL_TEXTURE_CUBE_MAP) {
770       /* Make sure that all six cube map level 0 images are the same size and
771        * format.
772        * Note:  we know that the image's width==height (we enforce that
773        * at glTexImage time) so we only need to test the width here.
774        */
775       GLuint face;
776       assert(baseImage->Width2 == baseImage->Height);
777       for (face = 1; face < 6; face++) {
778          assert(t->Image[face][baseLevel] == NULL ||
779                 t->Image[face][baseLevel]->Width2 ==
780                 t->Image[face][baseLevel]->Height2);
781          if (t->Image[face][baseLevel] == NULL ||
782              t->Image[face][baseLevel]->Width2 != baseImage->Width2) {
783             incomplete(t, BASE, "Cube face missing or mismatched size");
784             return;
785          }
786          if (t->Image[face][baseLevel]->InternalFormat !=
787              baseImage->InternalFormat) {
788             incomplete(t, BASE, "Cube face format mismatch");
789             return;
790          }
791          if (t->Image[face][baseLevel]->Border != baseImage->Border) {
792             incomplete(t, BASE, "Cube face border size mismatch");
793             return;
794          }
795       }
796    }
797 
798    /*
799     * Do mipmap consistency checking.
800     * Note: we don't care about the current texture sampler state here.
801     * To determine texture completeness we'll either look at _BaseComplete
802     * or _MipmapComplete depending on the current minification filter mode.
803     */
804    {
805       GLint i;
806       const GLint minLevel = baseLevel;
807       const GLint maxLevel = t->_MaxLevel;
808       const GLuint numFaces = _mesa_num_tex_faces(t->Target);
809       GLuint width, height, depth, face;
810 
811       if (minLevel > maxLevel) {
812          incomplete(t, MIPMAP, "minLevel > maxLevel");
813          return;
814       }
815 
816       /* Get the base image's dimensions */
817       width = baseImage->Width2;
818       height = baseImage->Height2;
819       depth = baseImage->Depth2;
820 
821       /* Note: this loop will be a no-op for RECT, BUFFER, EXTERNAL,
822        * MULTISAMPLE and MULTISAMPLE_ARRAY textures
823        */
824       for (i = baseLevel + 1; i < maxLevels; i++) {
825          /* Compute the expected size of image at level[i] */
826          if (width > 1) {
827             width /= 2;
828          }
829          if (height > 1 && t->Target != GL_TEXTURE_1D_ARRAY) {
830             height /= 2;
831          }
832          if (depth > 1 && t->Target != GL_TEXTURE_2D_ARRAY
833              && t->Target != GL_TEXTURE_CUBE_MAP_ARRAY) {
834             depth /= 2;
835          }
836 
837          /* loop over cube faces (or single face otherwise) */
838          for (face = 0; face < numFaces; face++) {
839             if (i >= minLevel && i <= maxLevel) {
840                const struct gl_texture_image *img = t->Image[face][i];
841 
842                if (!img) {
843                   incomplete(t, MIPMAP, "TexImage[%d] is missing", i);
844                   return;
845                }
846                if (img->InternalFormat != baseImage->InternalFormat) {
847                   incomplete(t, MIPMAP, "Format[i] != Format[baseLevel]");
848                   return;
849                }
850                if (img->Border != baseImage->Border) {
851                   incomplete(t, MIPMAP, "Border[i] != Border[baseLevel]");
852                   return;
853                }
854                if (img->Width2 != width) {
855                   incomplete(t, MIPMAP, "TexImage[%d] bad width %u", i,
856                              img->Width2);
857                   return;
858                }
859                if (img->Height2 != height) {
860                   incomplete(t, MIPMAP, "TexImage[%d] bad height %u", i,
861                              img->Height2);
862                   return;
863                }
864                if (img->Depth2 != depth) {
865                   incomplete(t, MIPMAP, "TexImage[%d] bad depth %u", i,
866                              img->Depth2);
867                   return;
868                }
869             }
870          }
871 
872          if (width == 1 && height == 1 && depth == 1) {
873             return;  /* found smallest needed mipmap, all done! */
874          }
875       }
876    }
877 }
878 
879 
880 GLboolean
_mesa_cube_level_complete(const struct gl_texture_object * texObj,const GLint level)881 _mesa_cube_level_complete(const struct gl_texture_object *texObj,
882                           const GLint level)
883 {
884    const struct gl_texture_image *img0, *img;
885    GLuint face;
886 
887    if (texObj->Target != GL_TEXTURE_CUBE_MAP)
888       return GL_FALSE;
889 
890    if ((level < 0) || (level >= MAX_TEXTURE_LEVELS))
891       return GL_FALSE;
892 
893    /* check first face */
894    img0 = texObj->Image[0][level];
895    if (!img0 ||
896        img0->Width < 1 ||
897        img0->Width != img0->Height)
898       return GL_FALSE;
899 
900    /* check remaining faces vs. first face */
901    for (face = 1; face < 6; face++) {
902       img = texObj->Image[face][level];
903       if (!img ||
904           img->Width != img0->Width ||
905           img->Height != img0->Height ||
906           img->TexFormat != img0->TexFormat)
907          return GL_FALSE;
908    }
909 
910    return GL_TRUE;
911 }
912 
913 /**
914  * Check if the given cube map texture is "cube complete" as defined in
915  * the OpenGL specification.
916  */
917 GLboolean
_mesa_cube_complete(const struct gl_texture_object * texObj)918 _mesa_cube_complete(const struct gl_texture_object *texObj)
919 {
920    return _mesa_cube_level_complete(texObj, texObj->BaseLevel);
921 }
922 
923 /**
924  * Mark a texture object dirty.  It forces the object to be incomplete
925  * and forces the context to re-validate its state.
926  *
927  * \param ctx GL context.
928  * \param texObj texture object.
929  */
930 void
_mesa_dirty_texobj(struct gl_context * ctx,struct gl_texture_object * texObj)931 _mesa_dirty_texobj(struct gl_context *ctx, struct gl_texture_object *texObj)
932 {
933    texObj->_BaseComplete = GL_FALSE;
934    texObj->_MipmapComplete = GL_FALSE;
935    ctx->NewState |= _NEW_TEXTURE;
936 }
937 
938 
939 /**
940  * Return pointer to a default/fallback texture of the given type/target.
941  * The texture is an RGBA texture with all texels = (0,0,0,1).
942  * That's the value a GLSL sampler should get when sampling from an
943  * incomplete texture.
944  */
945 struct gl_texture_object *
_mesa_get_fallback_texture(struct gl_context * ctx,gl_texture_index tex)946 _mesa_get_fallback_texture(struct gl_context *ctx, gl_texture_index tex)
947 {
948    if (!ctx->Shared->FallbackTex[tex]) {
949       /* create fallback texture now */
950       const GLsizei width = 1, height = 1;
951       GLsizei depth = 1;
952       GLubyte texel[24];
953       struct gl_texture_object *texObj;
954       struct gl_texture_image *texImage;
955       mesa_format texFormat;
956       GLuint dims, face, numFaces = 1;
957       GLenum target;
958 
959       for (face = 0; face < 6; face++) {
960          texel[4*face + 0] =
961          texel[4*face + 1] =
962          texel[4*face + 2] = 0x0;
963          texel[4*face + 3] = 0xff;
964       }
965 
966       switch (tex) {
967       case TEXTURE_2D_ARRAY_INDEX:
968          dims = 3;
969          target = GL_TEXTURE_2D_ARRAY;
970          break;
971       case TEXTURE_1D_ARRAY_INDEX:
972          dims = 2;
973          target = GL_TEXTURE_1D_ARRAY;
974          break;
975       case TEXTURE_CUBE_INDEX:
976          dims = 2;
977          target = GL_TEXTURE_CUBE_MAP;
978          numFaces = 6;
979          break;
980       case TEXTURE_3D_INDEX:
981          dims = 3;
982          target = GL_TEXTURE_3D;
983          break;
984       case TEXTURE_RECT_INDEX:
985          dims = 2;
986          target = GL_TEXTURE_RECTANGLE;
987          break;
988       case TEXTURE_2D_INDEX:
989          dims = 2;
990          target = GL_TEXTURE_2D;
991          break;
992       case TEXTURE_1D_INDEX:
993          dims = 1;
994          target = GL_TEXTURE_1D;
995          break;
996       case TEXTURE_BUFFER_INDEX:
997          dims = 0;
998          target = GL_TEXTURE_BUFFER;
999          break;
1000       case TEXTURE_CUBE_ARRAY_INDEX:
1001          dims = 3;
1002          target = GL_TEXTURE_CUBE_MAP_ARRAY;
1003          depth = 6;
1004          break;
1005       case TEXTURE_EXTERNAL_INDEX:
1006          dims = 2;
1007          target = GL_TEXTURE_EXTERNAL_OES;
1008          break;
1009       case TEXTURE_2D_MULTISAMPLE_INDEX:
1010          dims = 2;
1011          target = GL_TEXTURE_2D_MULTISAMPLE;
1012          break;
1013       case TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX:
1014          dims = 3;
1015          target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
1016          break;
1017       default:
1018          /* no-op */
1019          return NULL;
1020       }
1021 
1022       /* create texture object */
1023       texObj = ctx->Driver.NewTextureObject(ctx, 0, target);
1024       if (!texObj)
1025          return NULL;
1026 
1027       assert(texObj->RefCount == 1);
1028       texObj->Sampler.MinFilter = GL_NEAREST;
1029       texObj->Sampler.MagFilter = GL_NEAREST;
1030 
1031       texFormat = ctx->Driver.ChooseTextureFormat(ctx, target,
1032                                                   GL_RGBA, GL_RGBA,
1033                                                   GL_UNSIGNED_BYTE);
1034 
1035       /* need a loop here just for cube maps */
1036       for (face = 0; face < numFaces; face++) {
1037          const GLenum faceTarget = _mesa_cube_face_target(target, face);
1038 
1039          /* initialize level[0] texture image */
1040          texImage = _mesa_get_tex_image(ctx, texObj, faceTarget, 0);
1041 
1042          _mesa_init_teximage_fields(ctx, texImage,
1043                                     width,
1044                                     (dims > 1) ? height : 1,
1045                                     (dims > 2) ? depth : 1,
1046                                     0, /* border */
1047                                     GL_RGBA, texFormat);
1048 
1049          ctx->Driver.TexImage(ctx, dims, texImage,
1050                               GL_RGBA, GL_UNSIGNED_BYTE, texel,
1051                               &ctx->DefaultPacking);
1052       }
1053 
1054       _mesa_test_texobj_completeness(ctx, texObj);
1055       assert(texObj->_BaseComplete);
1056       assert(texObj->_MipmapComplete);
1057 
1058       ctx->Shared->FallbackTex[tex] = texObj;
1059    }
1060    return ctx->Shared->FallbackTex[tex];
1061 }
1062 
1063 
1064 /**
1065  * Compute the size of the given texture object, in bytes.
1066  */
1067 static GLuint
texture_size(const struct gl_texture_object * texObj)1068 texture_size(const struct gl_texture_object *texObj)
1069 {
1070    const GLuint numFaces = _mesa_num_tex_faces(texObj->Target);
1071    GLuint face, level, size = 0;
1072 
1073    for (face = 0; face < numFaces; face++) {
1074       for (level = 0; level < MAX_TEXTURE_LEVELS; level++) {
1075          const struct gl_texture_image *img = texObj->Image[face][level];
1076          if (img) {
1077             GLuint sz = _mesa_format_image_size(img->TexFormat, img->Width,
1078                                                 img->Height, img->Depth);
1079             size += sz;
1080          }
1081       }
1082    }
1083 
1084    return size;
1085 }
1086 
1087 
1088 /**
1089  * Callback called from _mesa_HashWalk()
1090  */
1091 static void
count_tex_size(GLuint key,void * data,void * userData)1092 count_tex_size(GLuint key, void *data, void *userData)
1093 {
1094    const struct gl_texture_object *texObj =
1095       (const struct gl_texture_object *) data;
1096    GLuint *total = (GLuint *) userData;
1097 
1098    (void) key;
1099 
1100    *total = *total + texture_size(texObj);
1101 }
1102 
1103 
1104 /**
1105  * Compute total size (in bytes) of all textures for the given context.
1106  * For debugging purposes.
1107  */
1108 GLuint
_mesa_total_texture_memory(struct gl_context * ctx)1109 _mesa_total_texture_memory(struct gl_context *ctx)
1110 {
1111    GLuint tgt, total = 0;
1112 
1113    _mesa_HashWalk(ctx->Shared->TexObjects, count_tex_size, &total);
1114 
1115    /* plus, the default texture objects */
1116    for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
1117       total += texture_size(ctx->Shared->DefaultTex[tgt]);
1118    }
1119 
1120    return total;
1121 }
1122 
1123 
1124 /**
1125  * Return the base format for the given texture object by looking
1126  * at the base texture image.
1127  * \return base format (such as GL_RGBA) or GL_NONE if it can't be determined
1128  */
1129 GLenum
_mesa_texture_base_format(const struct gl_texture_object * texObj)1130 _mesa_texture_base_format(const struct gl_texture_object *texObj)
1131 {
1132    const struct gl_texture_image *texImage = _mesa_base_tex_image(texObj);
1133 
1134    return texImage ? texImage->_BaseFormat : GL_NONE;
1135 }
1136 
1137 
1138 static struct gl_texture_object *
invalidate_tex_image_error_check(struct gl_context * ctx,GLuint texture,GLint level,const char * name)1139 invalidate_tex_image_error_check(struct gl_context *ctx, GLuint texture,
1140                                  GLint level, const char *name)
1141 {
1142    /* The GL_ARB_invalidate_subdata spec says:
1143     *
1144     *     "If <texture> is zero or is not the name of a texture, the error
1145     *     INVALID_VALUE is generated."
1146     *
1147     * This performs the error check in a different order than listed in the
1148     * spec.  We have to get the texture object before we can validate the
1149     * other parameters against values in the texture object.
1150     */
1151    struct gl_texture_object *const t = _mesa_lookup_texture(ctx, texture);
1152    if (texture == 0 || t == NULL) {
1153       _mesa_error(ctx, GL_INVALID_VALUE, "%s(texture)", name);
1154       return NULL;
1155    }
1156 
1157    /* The GL_ARB_invalidate_subdata spec says:
1158     *
1159     *     "If <level> is less than zero or greater than the base 2 logarithm
1160     *     of the maximum texture width, height, or depth, the error
1161     *     INVALID_VALUE is generated."
1162     */
1163    if (level < 0 || level > t->MaxLevel) {
1164       _mesa_error(ctx, GL_INVALID_VALUE, "%s(level)", name);
1165       return NULL;
1166    }
1167 
1168    /* The GL_ARB_invalidate_subdata spec says:
1169     *
1170     *     "If the target of <texture> is TEXTURE_RECTANGLE, TEXTURE_BUFFER,
1171     *     TEXTURE_2D_MULTISAMPLE, or TEXTURE_2D_MULTISAMPLE_ARRAY, and <level>
1172     *     is not zero, the error INVALID_VALUE is generated."
1173     */
1174    if (level != 0) {
1175       switch (t->Target) {
1176       case GL_TEXTURE_RECTANGLE:
1177       case GL_TEXTURE_BUFFER:
1178       case GL_TEXTURE_2D_MULTISAMPLE:
1179       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
1180          _mesa_error(ctx, GL_INVALID_VALUE, "%s(level)", name);
1181          return NULL;
1182 
1183       default:
1184          break;
1185       }
1186    }
1187 
1188    return t;
1189 }
1190 
1191 
1192 /**
1193  * Helper function for glCreateTextures and glGenTextures. Need this because
1194  * glCreateTextures should throw errors if target = 0. This is not exposed to
1195  * the rest of Mesa to encourage Mesa internals to use nameless textures,
1196  * which do not require expensive hash lookups.
1197  * \param target  either 0 or a valid / error-checked texture target enum
1198  */
1199 static void
create_textures(struct gl_context * ctx,GLenum target,GLsizei n,GLuint * textures,const char * caller)1200 create_textures(struct gl_context *ctx, GLenum target,
1201                 GLsizei n, GLuint *textures, const char *caller)
1202 {
1203    GLuint first;
1204    GLint i;
1205 
1206    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1207       _mesa_debug(ctx, "%s %d\n", caller, n);
1208 
1209    if (n < 0) {
1210       _mesa_error(ctx, GL_INVALID_VALUE, "%s(n < 0)", caller);
1211       return;
1212    }
1213 
1214    if (!textures)
1215       return;
1216 
1217    /*
1218     * This must be atomic (generation and allocation of texture IDs)
1219     */
1220    _mesa_HashLockMutex(ctx->Shared->TexObjects);
1221 
1222    first = _mesa_HashFindFreeKeyBlock(ctx->Shared->TexObjects, n);
1223 
1224    /* Allocate new, empty texture objects */
1225    for (i = 0; i < n; i++) {
1226       struct gl_texture_object *texObj;
1227       GLuint name = first + i;
1228       texObj = ctx->Driver.NewTextureObject(ctx, name, target);
1229       if (!texObj) {
1230          _mesa_HashUnlockMutex(ctx->Shared->TexObjects);
1231          _mesa_error(ctx, GL_OUT_OF_MEMORY, "gl%sTextures", caller);
1232          return;
1233       }
1234 
1235       /* insert into hash table */
1236       _mesa_HashInsertLocked(ctx->Shared->TexObjects, texObj->Name, texObj);
1237 
1238       textures[i] = name;
1239    }
1240 
1241    _mesa_HashUnlockMutex(ctx->Shared->TexObjects);
1242 }
1243 
1244 /*@}*/
1245 
1246 
1247 /***********************************************************************/
1248 /** \name API functions */
1249 /*@{*/
1250 
1251 
1252 /**
1253  * Generate texture names.
1254  *
1255  * \param n number of texture names to be generated.
1256  * \param textures an array in which will hold the generated texture names.
1257  *
1258  * \sa glGenTextures(), glCreateTextures().
1259  *
1260  * Calls _mesa_HashFindFreeKeyBlock() to find a block of free texture
1261  * IDs which are stored in \p textures.  Corresponding empty texture
1262  * objects are also generated.
1263  */
1264 void GLAPIENTRY
_mesa_GenTextures(GLsizei n,GLuint * textures)1265 _mesa_GenTextures(GLsizei n, GLuint *textures)
1266 {
1267    GET_CURRENT_CONTEXT(ctx);
1268    create_textures(ctx, 0, n, textures, "glGenTextures");
1269 }
1270 
1271 /**
1272  * Create texture objects.
1273  *
1274  * \param target the texture target for each name to be generated.
1275  * \param n number of texture names to be generated.
1276  * \param textures an array in which will hold the generated texture names.
1277  *
1278  * \sa glCreateTextures(), glGenTextures().
1279  *
1280  * Calls _mesa_HashFindFreeKeyBlock() to find a block of free texture
1281  * IDs which are stored in \p textures.  Corresponding empty texture
1282  * objects are also generated.
1283  */
1284 void GLAPIENTRY
_mesa_CreateTextures(GLenum target,GLsizei n,GLuint * textures)1285 _mesa_CreateTextures(GLenum target, GLsizei n, GLuint *textures)
1286 {
1287    GLint targetIndex;
1288    GET_CURRENT_CONTEXT(ctx);
1289 
1290    /*
1291     * The 4.5 core profile spec (30.10.2014) doesn't specify what
1292     * glCreateTextures should do with invalid targets, which was probably an
1293     * oversight.  This conforms to the spec for glBindTexture.
1294     */
1295    targetIndex = _mesa_tex_target_to_index(ctx, target);
1296    if (targetIndex < 0) {
1297       _mesa_error(ctx, GL_INVALID_ENUM, "glCreateTextures(target)");
1298       return;
1299    }
1300 
1301    create_textures(ctx, target, n, textures, "glCreateTextures");
1302 }
1303 
1304 /**
1305  * Check if the given texture object is bound to the current draw or
1306  * read framebuffer.  If so, Unbind it.
1307  */
1308 static void
unbind_texobj_from_fbo(struct gl_context * ctx,struct gl_texture_object * texObj)1309 unbind_texobj_from_fbo(struct gl_context *ctx,
1310                        struct gl_texture_object *texObj)
1311 {
1312    bool progress = false;
1313 
1314    /* Section 4.4.2 (Attaching Images to Framebuffer Objects), subsection
1315     * "Attaching Texture Images to a Framebuffer," of the OpenGL 3.1 spec
1316     * says:
1317     *
1318     *     "If a texture object is deleted while its image is attached to one
1319     *     or more attachment points in the currently bound framebuffer, then
1320     *     it is as if FramebufferTexture* had been called, with a texture of
1321     *     zero, for each attachment point to which this image was attached in
1322     *     the currently bound framebuffer. In other words, this texture image
1323     *     is first detached from all attachment points in the currently bound
1324     *     framebuffer. Note that the texture image is specifically not
1325     *     detached from any other framebuffer objects. Detaching the texture
1326     *     image from any other framebuffer objects is the responsibility of
1327     *     the application."
1328     */
1329    if (_mesa_is_user_fbo(ctx->DrawBuffer)) {
1330       progress = _mesa_detach_renderbuffer(ctx, ctx->DrawBuffer, texObj);
1331    }
1332    if (_mesa_is_user_fbo(ctx->ReadBuffer)
1333        && ctx->ReadBuffer != ctx->DrawBuffer) {
1334       progress = _mesa_detach_renderbuffer(ctx, ctx->ReadBuffer, texObj)
1335          || progress;
1336    }
1337 
1338    if (progress)
1339       /* Vertices are already flushed by _mesa_DeleteTextures */
1340       ctx->NewState |= _NEW_BUFFERS;
1341 }
1342 
1343 
1344 /**
1345  * Check if the given texture object is bound to any texture image units and
1346  * unbind it if so (revert to default textures).
1347  */
1348 static void
unbind_texobj_from_texunits(struct gl_context * ctx,struct gl_texture_object * texObj)1349 unbind_texobj_from_texunits(struct gl_context *ctx,
1350                             struct gl_texture_object *texObj)
1351 {
1352    const gl_texture_index index = texObj->TargetIndex;
1353    GLuint u;
1354 
1355    if (texObj->Target == 0) {
1356       /* texture was never bound */
1357       return;
1358    }
1359 
1360    assert(index < NUM_TEXTURE_TARGETS);
1361 
1362    for (u = 0; u < ctx->Texture.NumCurrentTexUsed; u++) {
1363       struct gl_texture_unit *unit = &ctx->Texture.Unit[u];
1364 
1365       if (texObj == unit->CurrentTex[index]) {
1366          /* Bind the default texture for this unit/target */
1367          _mesa_reference_texobj(&unit->CurrentTex[index],
1368                                 ctx->Shared->DefaultTex[index]);
1369          unit->_BoundTextures &= ~(1 << index);
1370       }
1371    }
1372 }
1373 
1374 
1375 /**
1376  * Check if the given texture object is bound to any shader image unit
1377  * and unbind it if that's the case.
1378  */
1379 static void
unbind_texobj_from_image_units(struct gl_context * ctx,struct gl_texture_object * texObj)1380 unbind_texobj_from_image_units(struct gl_context *ctx,
1381                                struct gl_texture_object *texObj)
1382 {
1383    GLuint i;
1384 
1385    for (i = 0; i < ctx->Const.MaxImageUnits; i++) {
1386       struct gl_image_unit *unit = &ctx->ImageUnits[i];
1387 
1388       if (texObj == unit->TexObj) {
1389          _mesa_reference_texobj(&unit->TexObj, NULL);
1390          *unit = _mesa_default_image_unit(ctx);
1391       }
1392    }
1393 }
1394 
1395 
1396 /**
1397  * Unbinds all textures bound to the given texture image unit.
1398  */
1399 static void
unbind_textures_from_unit(struct gl_context * ctx,GLuint unit)1400 unbind_textures_from_unit(struct gl_context *ctx, GLuint unit)
1401 {
1402    struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
1403 
1404    while (texUnit->_BoundTextures) {
1405       const GLuint index = ffs(texUnit->_BoundTextures) - 1;
1406       struct gl_texture_object *texObj = ctx->Shared->DefaultTex[index];
1407 
1408       _mesa_reference_texobj(&texUnit->CurrentTex[index], texObj);
1409 
1410       /* Pass BindTexture call to device driver */
1411       if (ctx->Driver.BindTexture)
1412          ctx->Driver.BindTexture(ctx, unit, 0, texObj);
1413 
1414       texUnit->_BoundTextures &= ~(1 << index);
1415       ctx->NewState |= _NEW_TEXTURE;
1416    }
1417 }
1418 
1419 
1420 /**
1421  * Delete named textures.
1422  *
1423  * \param n number of textures to be deleted.
1424  * \param textures array of texture IDs to be deleted.
1425  *
1426  * \sa glDeleteTextures().
1427  *
1428  * If we're about to delete a texture that's currently bound to any
1429  * texture unit, unbind the texture first.  Decrement the reference
1430  * count on the texture object and delete it if it's zero.
1431  * Recall that texture objects can be shared among several rendering
1432  * contexts.
1433  */
1434 void GLAPIENTRY
_mesa_DeleteTextures(GLsizei n,const GLuint * textures)1435 _mesa_DeleteTextures( GLsizei n, const GLuint *textures)
1436 {
1437    GET_CURRENT_CONTEXT(ctx);
1438    GLint i;
1439 
1440    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1441       _mesa_debug(ctx, "glDeleteTextures %d\n", n);
1442 
1443    if (n < 0) {
1444       _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteTextures(n < 0)");
1445       return;
1446    }
1447 
1448    FLUSH_VERTICES(ctx, 0); /* too complex */
1449 
1450    if (n < 0) {
1451       _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteTextures(n)");
1452       return;
1453    }
1454 
1455    if (!textures)
1456       return;
1457 
1458    for (i = 0; i < n; i++) {
1459       if (textures[i] > 0) {
1460          struct gl_texture_object *delObj
1461             = _mesa_lookup_texture(ctx, textures[i]);
1462 
1463          if (delObj) {
1464             _mesa_lock_texture(ctx, delObj);
1465 
1466             /* Check if texture is bound to any framebuffer objects.
1467              * If so, unbind.
1468              * See section 4.4.2.3 of GL_EXT_framebuffer_object.
1469              */
1470             unbind_texobj_from_fbo(ctx, delObj);
1471 
1472             /* Check if this texture is currently bound to any texture units.
1473              * If so, unbind it.
1474              */
1475             unbind_texobj_from_texunits(ctx, delObj);
1476 
1477             /* Check if this texture is currently bound to any shader
1478              * image unit.  If so, unbind it.
1479              * See section 3.9.X of GL_ARB_shader_image_load_store.
1480              */
1481             unbind_texobj_from_image_units(ctx, delObj);
1482 
1483             _mesa_unlock_texture(ctx, delObj);
1484 
1485             ctx->NewState |= _NEW_TEXTURE;
1486 
1487             /* The texture _name_ is now free for re-use.
1488              * Remove it from the hash table now.
1489              */
1490             _mesa_HashRemove(ctx->Shared->TexObjects, delObj->Name);
1491 
1492             /* Unreference the texobj.  If refcount hits zero, the texture
1493              * will be deleted.
1494              */
1495             _mesa_reference_texobj(&delObj, NULL);
1496          }
1497       }
1498    }
1499 }
1500 
1501 /**
1502  * This deletes a texObj without altering the hash table.
1503  */
1504 void
_mesa_delete_nameless_texture(struct gl_context * ctx,struct gl_texture_object * texObj)1505 _mesa_delete_nameless_texture(struct gl_context *ctx,
1506                               struct gl_texture_object *texObj)
1507 {
1508    if (!texObj)
1509       return;
1510 
1511    FLUSH_VERTICES(ctx, 0);
1512 
1513    _mesa_lock_texture(ctx, texObj);
1514    {
1515       /* Check if texture is bound to any framebuffer objects.
1516        * If so, unbind.
1517        * See section 4.4.2.3 of GL_EXT_framebuffer_object.
1518        */
1519       unbind_texobj_from_fbo(ctx, texObj);
1520 
1521       /* Check if this texture is currently bound to any texture units.
1522        * If so, unbind it.
1523        */
1524       unbind_texobj_from_texunits(ctx, texObj);
1525 
1526       /* Check if this texture is currently bound to any shader
1527        * image unit.  If so, unbind it.
1528        * See section 3.9.X of GL_ARB_shader_image_load_store.
1529        */
1530       unbind_texobj_from_image_units(ctx, texObj);
1531    }
1532    _mesa_unlock_texture(ctx, texObj);
1533 
1534    ctx->NewState |= _NEW_TEXTURE;
1535 
1536    /* Unreference the texobj.  If refcount hits zero, the texture
1537     * will be deleted.
1538     */
1539    _mesa_reference_texobj(&texObj, NULL);
1540 }
1541 
1542 
1543 /**
1544  * Convert a GL texture target enum such as GL_TEXTURE_2D or GL_TEXTURE_3D
1545  * into the corresponding Mesa texture target index.
1546  * Note that proxy targets are not valid here.
1547  * \return TEXTURE_x_INDEX or -1 if target is invalid
1548  */
1549 int
_mesa_tex_target_to_index(const struct gl_context * ctx,GLenum target)1550 _mesa_tex_target_to_index(const struct gl_context *ctx, GLenum target)
1551 {
1552    switch (target) {
1553    case GL_TEXTURE_1D:
1554       return _mesa_is_desktop_gl(ctx) ? TEXTURE_1D_INDEX : -1;
1555    case GL_TEXTURE_2D:
1556       return TEXTURE_2D_INDEX;
1557    case GL_TEXTURE_3D:
1558       return ctx->API != API_OPENGLES ? TEXTURE_3D_INDEX : -1;
1559    case GL_TEXTURE_CUBE_MAP:
1560       return ctx->Extensions.ARB_texture_cube_map
1561          ? TEXTURE_CUBE_INDEX : -1;
1562    case GL_TEXTURE_RECTANGLE:
1563       return _mesa_is_desktop_gl(ctx) && ctx->Extensions.NV_texture_rectangle
1564          ? TEXTURE_RECT_INDEX : -1;
1565    case GL_TEXTURE_1D_ARRAY:
1566       return _mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_array
1567          ? TEXTURE_1D_ARRAY_INDEX : -1;
1568    case GL_TEXTURE_2D_ARRAY:
1569       return (_mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_array)
1570          || _mesa_is_gles3(ctx)
1571          ? TEXTURE_2D_ARRAY_INDEX : -1;
1572    case GL_TEXTURE_BUFFER:
1573       return (_mesa_has_ARB_texture_buffer_object(ctx) ||
1574               _mesa_has_OES_texture_buffer(ctx)) ?
1575              TEXTURE_BUFFER_INDEX : -1;
1576    case GL_TEXTURE_EXTERNAL_OES:
1577       return _mesa_is_gles(ctx) && ctx->Extensions.OES_EGL_image_external
1578          ? TEXTURE_EXTERNAL_INDEX : -1;
1579    case GL_TEXTURE_CUBE_MAP_ARRAY:
1580       return _mesa_has_texture_cube_map_array(ctx)
1581          ? TEXTURE_CUBE_ARRAY_INDEX : -1;
1582    case GL_TEXTURE_2D_MULTISAMPLE:
1583       return ((_mesa_is_desktop_gl(ctx) && ctx->Extensions.ARB_texture_multisample) ||
1584               _mesa_is_gles31(ctx)) ? TEXTURE_2D_MULTISAMPLE_INDEX: -1;
1585    case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
1586       return ((_mesa_is_desktop_gl(ctx) && ctx->Extensions.ARB_texture_multisample) ||
1587               _mesa_is_gles31(ctx))
1588          ? TEXTURE_2D_MULTISAMPLE_ARRAY_INDEX: -1;
1589    default:
1590       return -1;
1591    }
1592 }
1593 
1594 
1595 /**
1596  * Do actual texture binding.  All error checking should have been done prior
1597  * to calling this function.  Note that the texture target (1D, 2D, etc) is
1598  * always specified by the texObj->TargetIndex.
1599  *
1600  * \param unit  index of texture unit to update
1601  * \param texObj  the new texture object (cannot be NULL)
1602  */
1603 static void
bind_texture(struct gl_context * ctx,unsigned unit,struct gl_texture_object * texObj)1604 bind_texture(struct gl_context *ctx,
1605              unsigned unit,
1606              struct gl_texture_object *texObj)
1607 {
1608    struct gl_texture_unit *texUnit;
1609    int targetIndex;
1610 
1611    assert(unit < ARRAY_SIZE(ctx->Texture.Unit));
1612    texUnit = &ctx->Texture.Unit[unit];
1613 
1614    assert(texObj);
1615    assert(valid_texture_object(texObj));
1616 
1617    targetIndex = texObj->TargetIndex;
1618    assert(targetIndex >= 0);
1619    assert(targetIndex < NUM_TEXTURE_TARGETS);
1620 
1621    /* Check if this texture is only used by this context and is already bound.
1622     * If so, just return.
1623     */
1624    {
1625       bool early_out;
1626       mtx_lock(&ctx->Shared->Mutex);
1627       early_out = ((ctx->Shared->RefCount == 1)
1628                    && (texObj == texUnit->CurrentTex[targetIndex]));
1629       mtx_unlock(&ctx->Shared->Mutex);
1630       if (early_out) {
1631          return;
1632       }
1633    }
1634 
1635    /* flush before changing binding */
1636    FLUSH_VERTICES(ctx, _NEW_TEXTURE);
1637 
1638    /* If the refcount on the previously bound texture is decremented to
1639     * zero, it'll be deleted here.
1640     */
1641    _mesa_reference_texobj(&texUnit->CurrentTex[targetIndex], texObj);
1642 
1643    ctx->Texture.NumCurrentTexUsed = MAX2(ctx->Texture.NumCurrentTexUsed,
1644                                          unit + 1);
1645 
1646    if (texObj->Name != 0)
1647       texUnit->_BoundTextures |= (1 << targetIndex);
1648    else
1649       texUnit->_BoundTextures &= ~(1 << targetIndex);
1650 
1651    /* Pass BindTexture call to device driver */
1652    if (ctx->Driver.BindTexture) {
1653       ctx->Driver.BindTexture(ctx, unit, texObj->Target, texObj);
1654    }
1655 }
1656 
1657 
1658 /**
1659  * Implement glBindTexture().  Do error checking, look-up or create a new
1660  * texture object, then bind it in the current texture unit.
1661  *
1662  * \param target texture target.
1663  * \param texName texture name.
1664  */
1665 void GLAPIENTRY
_mesa_BindTexture(GLenum target,GLuint texName)1666 _mesa_BindTexture( GLenum target, GLuint texName )
1667 {
1668    GET_CURRENT_CONTEXT(ctx);
1669    struct gl_texture_object *newTexObj = NULL;
1670    GLint targetIndex;
1671 
1672    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1673       _mesa_debug(ctx, "glBindTexture %s %d\n",
1674                   _mesa_enum_to_string(target), (GLint) texName);
1675 
1676    targetIndex = _mesa_tex_target_to_index(ctx, target);
1677    if (targetIndex < 0) {
1678       _mesa_error(ctx, GL_INVALID_ENUM, "glBindTexture(target)");
1679       return;
1680    }
1681    assert(targetIndex < NUM_TEXTURE_TARGETS);
1682 
1683    /*
1684     * Get pointer to new texture object (newTexObj)
1685     */
1686    if (texName == 0) {
1687       /* Use a default texture object */
1688       newTexObj = ctx->Shared->DefaultTex[targetIndex];
1689    }
1690    else {
1691       /* non-default texture object */
1692       newTexObj = _mesa_lookup_texture(ctx, texName);
1693       if (newTexObj) {
1694          /* error checking */
1695          if (newTexObj->Target != 0 && newTexObj->Target != target) {
1696             /* The named texture object's target doesn't match the
1697              * given target
1698              */
1699             _mesa_error( ctx, GL_INVALID_OPERATION,
1700                          "glBindTexture(target mismatch)" );
1701             return;
1702          }
1703          if (newTexObj->Target == 0) {
1704             finish_texture_init(ctx, target, newTexObj);
1705          }
1706       }
1707       else {
1708          if (ctx->API == API_OPENGL_CORE) {
1709             _mesa_error(ctx, GL_INVALID_OPERATION,
1710                         "glBindTexture(non-gen name)");
1711             return;
1712          }
1713 
1714          /* if this is a new texture id, allocate a texture object now */
1715          newTexObj = ctx->Driver.NewTextureObject(ctx, texName, target);
1716          if (!newTexObj) {
1717             _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindTexture");
1718             return;
1719          }
1720 
1721          /* and insert it into hash table */
1722          _mesa_HashInsert(ctx->Shared->TexObjects, texName, newTexObj);
1723       }
1724    }
1725 
1726    assert(newTexObj->Target == target);
1727    assert(newTexObj->TargetIndex == targetIndex);
1728 
1729    bind_texture(ctx, ctx->Texture.CurrentUnit, newTexObj);
1730 }
1731 
1732 
1733 /**
1734  * OpenGL 4.5 / GL_ARB_direct_state_access glBindTextureUnit().
1735  *
1736  * \param unit texture unit.
1737  * \param texture texture name.
1738  *
1739  * \sa glBindTexture().
1740  *
1741  * If the named texture is 0, this will reset each target for the specified
1742  * texture unit to its default texture.
1743  * If the named texture is not 0 or a recognized texture name, this throws
1744  * GL_INVALID_OPERATION.
1745  */
1746 void GLAPIENTRY
_mesa_BindTextureUnit(GLuint unit,GLuint texture)1747 _mesa_BindTextureUnit(GLuint unit, GLuint texture)
1748 {
1749    GET_CURRENT_CONTEXT(ctx);
1750    struct gl_texture_object *texObj;
1751 
1752    if (unit >= _mesa_max_tex_unit(ctx)) {
1753       _mesa_error(ctx, GL_INVALID_VALUE, "glBindTextureUnit(unit=%u)", unit);
1754       return;
1755    }
1756 
1757    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1758       _mesa_debug(ctx, "glBindTextureUnit %s %d\n",
1759                   _mesa_enum_to_string(GL_TEXTURE0+unit), (GLint) texture);
1760 
1761    /* Section 8.1 (Texture Objects) of the OpenGL 4.5 core profile spec
1762     * (20141030) says:
1763     *    "When texture is zero, each of the targets enumerated at the
1764     *    beginning of this section is reset to its default texture for the
1765     *    corresponding texture image unit."
1766     */
1767    if (texture == 0) {
1768       unbind_textures_from_unit(ctx, unit);
1769       return;
1770    }
1771 
1772    /* Get the non-default texture object */
1773    texObj = _mesa_lookup_texture(ctx, texture);
1774 
1775    /* Error checking */
1776    if (!texObj) {
1777       _mesa_error(ctx, GL_INVALID_OPERATION,
1778                   "glBindTextureUnit(non-gen name)");
1779       return;
1780    }
1781    if (texObj->Target == 0) {
1782       /* Texture object was gen'd but never bound so the target is not set */
1783       _mesa_error(ctx, GL_INVALID_OPERATION, "glBindTextureUnit(target)");
1784       return;
1785    }
1786    assert(valid_texture_object(texObj));
1787 
1788    bind_texture(ctx, unit, texObj);
1789 }
1790 
1791 
1792 /**
1793  * OpenGL 4.4 / GL_ARB_multi_bind glBindTextures().
1794  */
1795 void GLAPIENTRY
_mesa_BindTextures(GLuint first,GLsizei count,const GLuint * textures)1796 _mesa_BindTextures(GLuint first, GLsizei count, const GLuint *textures)
1797 {
1798    GET_CURRENT_CONTEXT(ctx);
1799    GLint i;
1800 
1801    /* The ARB_multi_bind spec says:
1802     *
1803     *     "An INVALID_OPERATION error is generated if <first> + <count>
1804     *      is greater than the number of texture image units supported
1805     *      by the implementation."
1806     */
1807    if (first + count > ctx->Const.MaxCombinedTextureImageUnits) {
1808       _mesa_error(ctx, GL_INVALID_OPERATION,
1809                   "glBindTextures(first=%u + count=%d > the value of "
1810                   "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS=%u)",
1811                   first, count, ctx->Const.MaxCombinedTextureImageUnits);
1812       return;
1813    }
1814 
1815    if (textures) {
1816       /* Note that the error semantics for multi-bind commands differ from
1817        * those of other GL commands.
1818        *
1819        * The issues section in the ARB_multi_bind spec says:
1820        *
1821        *    "(11) Typically, OpenGL specifies that if an error is generated by
1822        *          a command, that command has no effect.  This is somewhat
1823        *          unfortunate for multi-bind commands, because it would require
1824        *          a first pass to scan the entire list of bound objects for
1825        *          errors and then a second pass to actually perform the
1826        *          bindings.  Should we have different error semantics?
1827        *
1828        *       RESOLVED:  Yes.  In this specification, when the parameters for
1829        *       one of the <count> binding points are invalid, that binding
1830        *       point is not updated and an error will be generated.  However,
1831        *       other binding points in the same command will be updated if
1832        *       their parameters are valid and no other error occurs."
1833        */
1834 
1835       _mesa_begin_texture_lookups(ctx);
1836 
1837       for (i = 0; i < count; i++) {
1838          if (textures[i] != 0) {
1839             struct gl_texture_unit *texUnit = &ctx->Texture.Unit[first + i];
1840             struct gl_texture_object *current = texUnit->_Current;
1841             struct gl_texture_object *texObj;
1842 
1843             if (current && current->Name == textures[i])
1844                texObj = current;
1845             else
1846                texObj = _mesa_lookup_texture_locked(ctx, textures[i]);
1847 
1848             if (texObj && texObj->Target != 0) {
1849                bind_texture(ctx, first + i, texObj);
1850             } else {
1851                /* The ARB_multi_bind spec says:
1852                 *
1853                 *     "An INVALID_OPERATION error is generated if any value
1854                 *      in <textures> is not zero or the name of an existing
1855                 *      texture object (per binding)."
1856                 */
1857                _mesa_error(ctx, GL_INVALID_OPERATION,
1858                            "glBindTextures(textures[%d]=%u is not zero "
1859                            "or the name of an existing texture object)",
1860                            i, textures[i]);
1861             }
1862          } else {
1863             unbind_textures_from_unit(ctx, first + i);
1864          }
1865       }
1866 
1867       _mesa_end_texture_lookups(ctx);
1868    } else {
1869       /* Unbind all textures in the range <first> through <first>+<count>-1 */
1870       for (i = 0; i < count; i++)
1871          unbind_textures_from_unit(ctx, first + i);
1872    }
1873 }
1874 
1875 
1876 /**
1877  * Set texture priorities.
1878  *
1879  * \param n number of textures.
1880  * \param texName texture names.
1881  * \param priorities corresponding texture priorities.
1882  *
1883  * \sa glPrioritizeTextures().
1884  *
1885  * Looks up each texture in the hash, clamps the corresponding priority between
1886  * 0.0 and 1.0, and calls dd_function_table::PrioritizeTexture.
1887  */
1888 void GLAPIENTRY
_mesa_PrioritizeTextures(GLsizei n,const GLuint * texName,const GLclampf * priorities)1889 _mesa_PrioritizeTextures( GLsizei n, const GLuint *texName,
1890                           const GLclampf *priorities )
1891 {
1892    GET_CURRENT_CONTEXT(ctx);
1893    GLint i;
1894 
1895    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1896       _mesa_debug(ctx, "glPrioritizeTextures %d\n", n);
1897 
1898    FLUSH_VERTICES(ctx, 0);
1899 
1900    if (n < 0) {
1901       _mesa_error( ctx, GL_INVALID_VALUE, "glPrioritizeTextures" );
1902       return;
1903    }
1904 
1905    if (!priorities)
1906       return;
1907 
1908    for (i = 0; i < n; i++) {
1909       if (texName[i] > 0) {
1910          struct gl_texture_object *t = _mesa_lookup_texture(ctx, texName[i]);
1911          if (t) {
1912             t->Priority = CLAMP( priorities[i], 0.0F, 1.0F );
1913          }
1914       }
1915    }
1916 
1917    ctx->NewState |= _NEW_TEXTURE;
1918 }
1919 
1920 
1921 
1922 /**
1923  * See if textures are loaded in texture memory.
1924  *
1925  * \param n number of textures to query.
1926  * \param texName array with the texture names.
1927  * \param residences array which will hold the residence status.
1928  *
1929  * \return GL_TRUE if all textures are resident and
1930  *                 residences is left unchanged,
1931  *
1932  * Note: we assume all textures are always resident
1933  */
1934 GLboolean GLAPIENTRY
_mesa_AreTexturesResident(GLsizei n,const GLuint * texName,GLboolean * residences)1935 _mesa_AreTexturesResident(GLsizei n, const GLuint *texName,
1936                           GLboolean *residences)
1937 {
1938    GET_CURRENT_CONTEXT(ctx);
1939    GLboolean allResident = GL_TRUE;
1940    GLint i;
1941    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
1942 
1943    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1944       _mesa_debug(ctx, "glAreTexturesResident %d\n", n);
1945 
1946    if (n < 0) {
1947       _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident(n)");
1948       return GL_FALSE;
1949    }
1950 
1951    if (!texName || !residences)
1952       return GL_FALSE;
1953 
1954    /* We only do error checking on the texture names */
1955    for (i = 0; i < n; i++) {
1956       struct gl_texture_object *t;
1957       if (texName[i] == 0) {
1958          _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident");
1959          return GL_FALSE;
1960       }
1961       t = _mesa_lookup_texture(ctx, texName[i]);
1962       if (!t) {
1963          _mesa_error(ctx, GL_INVALID_VALUE, "glAreTexturesResident");
1964          return GL_FALSE;
1965       }
1966    }
1967 
1968    return allResident;
1969 }
1970 
1971 
1972 /**
1973  * See if a name corresponds to a texture.
1974  *
1975  * \param texture texture name.
1976  *
1977  * \return GL_TRUE if texture name corresponds to a texture, or GL_FALSE
1978  * otherwise.
1979  *
1980  * \sa glIsTexture().
1981  *
1982  * Calls _mesa_HashLookup().
1983  */
1984 GLboolean GLAPIENTRY
_mesa_IsTexture(GLuint texture)1985 _mesa_IsTexture( GLuint texture )
1986 {
1987    struct gl_texture_object *t;
1988    GET_CURRENT_CONTEXT(ctx);
1989    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
1990 
1991    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
1992       _mesa_debug(ctx, "glIsTexture %d\n", texture);
1993 
1994    if (!texture)
1995       return GL_FALSE;
1996 
1997    t = _mesa_lookup_texture(ctx, texture);
1998 
1999    /* IsTexture is true only after object has been bound once. */
2000    return t && t->Target;
2001 }
2002 
2003 
2004 /**
2005  * Simplest implementation of texture locking: grab the shared tex
2006  * mutex.  Examine the shared context state timestamp and if there has
2007  * been a change, set the appropriate bits in ctx->NewState.
2008  *
2009  * This is used to deal with synchronizing things when a texture object
2010  * is used/modified by different contexts (or threads) which are sharing
2011  * the texture.
2012  *
2013  * See also _mesa_lock/unlock_texture() in teximage.h
2014  */
2015 void
_mesa_lock_context_textures(struct gl_context * ctx)2016 _mesa_lock_context_textures( struct gl_context *ctx )
2017 {
2018    mtx_lock(&ctx->Shared->TexMutex);
2019 
2020    if (ctx->Shared->TextureStateStamp != ctx->TextureStateTimestamp) {
2021       ctx->NewState |= _NEW_TEXTURE;
2022       ctx->TextureStateTimestamp = ctx->Shared->TextureStateStamp;
2023    }
2024 }
2025 
2026 
2027 void
_mesa_unlock_context_textures(struct gl_context * ctx)2028 _mesa_unlock_context_textures( struct gl_context *ctx )
2029 {
2030    assert(ctx->Shared->TextureStateStamp == ctx->TextureStateTimestamp);
2031    mtx_unlock(&ctx->Shared->TexMutex);
2032 }
2033 
2034 
2035 void GLAPIENTRY
_mesa_InvalidateTexSubImage(GLuint texture,GLint level,GLint xoffset,GLint yoffset,GLint zoffset,GLsizei width,GLsizei height,GLsizei depth)2036 _mesa_InvalidateTexSubImage(GLuint texture, GLint level, GLint xoffset,
2037                             GLint yoffset, GLint zoffset, GLsizei width,
2038                             GLsizei height, GLsizei depth)
2039 {
2040    struct gl_texture_object *t;
2041    struct gl_texture_image *image;
2042    GET_CURRENT_CONTEXT(ctx);
2043 
2044    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
2045       _mesa_debug(ctx, "glInvalidateTexSubImage %d\n", texture);
2046 
2047    t = invalidate_tex_image_error_check(ctx, texture, level,
2048                                         "glInvalidateTexSubImage");
2049 
2050    /* The GL_ARB_invalidate_subdata spec says:
2051     *
2052     *     "...the specified subregion must be between -<b> and <dim>+<b> where
2053     *     <dim> is the size of the dimension of the texture image, and <b> is
2054     *     the size of the border of that texture image, otherwise
2055     *     INVALID_VALUE is generated (border is not applied to dimensions that
2056     *     don't exist in a given texture target)."
2057     */
2058    image = t->Image[0][level];
2059    if (image) {
2060       int xBorder;
2061       int yBorder;
2062       int zBorder;
2063       int imageWidth;
2064       int imageHeight;
2065       int imageDepth;
2066 
2067       /* The GL_ARB_invalidate_subdata spec says:
2068        *
2069        *     "For texture targets that don't have certain dimensions, this
2070        *     command treats those dimensions as having a size of 1. For
2071        *     example, to invalidate a portion of a two-dimensional texture,
2072        *     the application would use <zoffset> equal to zero and <depth>
2073        *     equal to one."
2074        */
2075       switch (t->Target) {
2076       case GL_TEXTURE_BUFFER:
2077          xBorder = 0;
2078          yBorder = 0;
2079          zBorder = 0;
2080          imageWidth = 1;
2081          imageHeight = 1;
2082          imageDepth = 1;
2083          break;
2084       case GL_TEXTURE_1D:
2085          xBorder = image->Border;
2086          yBorder = 0;
2087          zBorder = 0;
2088          imageWidth = image->Width;
2089          imageHeight = 1;
2090          imageDepth = 1;
2091          break;
2092       case GL_TEXTURE_1D_ARRAY:
2093          xBorder = image->Border;
2094          yBorder = 0;
2095          zBorder = 0;
2096          imageWidth = image->Width;
2097          imageHeight = image->Height;
2098          imageDepth = 1;
2099          break;
2100       case GL_TEXTURE_2D:
2101       case GL_TEXTURE_CUBE_MAP:
2102       case GL_TEXTURE_RECTANGLE:
2103       case GL_TEXTURE_2D_MULTISAMPLE:
2104          xBorder = image->Border;
2105          yBorder = image->Border;
2106          zBorder = 0;
2107          imageWidth = image->Width;
2108          imageHeight = image->Height;
2109          imageDepth = 1;
2110          break;
2111       case GL_TEXTURE_2D_ARRAY:
2112       case GL_TEXTURE_CUBE_MAP_ARRAY:
2113       case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
2114          xBorder = image->Border;
2115          yBorder = image->Border;
2116          zBorder = 0;
2117          imageWidth = image->Width;
2118          imageHeight = image->Height;
2119          imageDepth = image->Depth;
2120          break;
2121       case GL_TEXTURE_3D:
2122          xBorder = image->Border;
2123          yBorder = image->Border;
2124          zBorder = image->Border;
2125          imageWidth = image->Width;
2126          imageHeight = image->Height;
2127          imageDepth = image->Depth;
2128          break;
2129       default:
2130          assert(!"Should not get here.");
2131          xBorder = 0;
2132          yBorder = 0;
2133          zBorder = 0;
2134          imageWidth = 0;
2135          imageHeight = 0;
2136          imageDepth = 0;
2137          break;
2138       }
2139 
2140       if (xoffset < -xBorder) {
2141          _mesa_error(ctx, GL_INVALID_VALUE, "glInvalidateSubTexImage(xoffset)");
2142          return;
2143       }
2144 
2145       if (xoffset + width > imageWidth + xBorder) {
2146          _mesa_error(ctx, GL_INVALID_VALUE,
2147                      "glInvalidateSubTexImage(xoffset+width)");
2148          return;
2149       }
2150 
2151       if (yoffset < -yBorder) {
2152          _mesa_error(ctx, GL_INVALID_VALUE, "glInvalidateSubTexImage(yoffset)");
2153          return;
2154       }
2155 
2156       if (yoffset + height > imageHeight + yBorder) {
2157          _mesa_error(ctx, GL_INVALID_VALUE,
2158                      "glInvalidateSubTexImage(yoffset+height)");
2159          return;
2160       }
2161 
2162       if (zoffset < -zBorder) {
2163          _mesa_error(ctx, GL_INVALID_VALUE,
2164                      "glInvalidateSubTexImage(zoffset)");
2165          return;
2166       }
2167 
2168       if (zoffset + depth  > imageDepth + zBorder) {
2169          _mesa_error(ctx, GL_INVALID_VALUE,
2170                      "glInvalidateSubTexImage(zoffset+depth)");
2171          return;
2172       }
2173    }
2174 
2175    /* We don't actually do anything for this yet.  Just return after
2176     * validating the parameters and generating the required errors.
2177     */
2178    return;
2179 }
2180 
2181 
2182 void GLAPIENTRY
_mesa_InvalidateTexImage(GLuint texture,GLint level)2183 _mesa_InvalidateTexImage(GLuint texture, GLint level)
2184 {
2185    GET_CURRENT_CONTEXT(ctx);
2186 
2187    if (MESA_VERBOSE & (VERBOSE_API|VERBOSE_TEXTURE))
2188       _mesa_debug(ctx, "glInvalidateTexImage(%d, %d)\n", texture, level);
2189 
2190    invalidate_tex_image_error_check(ctx, texture, level,
2191                                     "glInvalidateTexImage");
2192 
2193    /* We don't actually do anything for this yet.  Just return after
2194     * validating the parameters and generating the required errors.
2195     */
2196    return;
2197 }
2198 
2199 /*@}*/
2200