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