• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
5  * Copyright (C) 2008  VMware, Inc.  All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included
15  * in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23  * OTHER DEALINGS IN THE SOFTWARE.
24  */
25 
26 /**
27  * \file context.c
28  * Mesa context/visual/framebuffer management functions.
29  * \author Brian Paul
30  */
31 
32 /**
33  * \mainpage Mesa Main Module
34  *
35  * \section MainIntroduction Introduction
36  *
37  * The Mesa Main module consists of all the files in the main/ directory.
38  * Among the features of this module are:
39  * <UL>
40  * <LI> Structures to represent most GL state </LI>
41  * <LI> State set/get functions </LI>
42  * <LI> Display lists </LI>
43  * <LI> Texture unit, object and image handling </LI>
44  * <LI> Matrix and attribute stacks </LI>
45  * </UL>
46  *
47  * Other modules are responsible for API dispatch, vertex transformation,
48  * point/line/triangle setup, rasterization, vertex array caching,
49  * vertex/fragment programs/shaders, etc.
50  *
51  *
52  * \section AboutDoxygen About Doxygen
53  *
54  * If you're viewing this information as Doxygen-generated HTML you'll
55  * see the documentation index at the top of this page.
56  *
57  * The first line lists the Mesa source code modules.
58  * The second line lists the indexes available for viewing the documentation
59  * for each module.
60  *
61  * Selecting the <b>Main page</b> link will display a summary of the module
62  * (this page).
63  *
64  * Selecting <b>Data Structures</b> will list all C structures.
65  *
66  * Selecting the <b>File List</b> link will list all the source files in
67  * the module.
68  * Selecting a filename will show a list of all functions defined in that file.
69  *
70  * Selecting the <b>Data Fields</b> link will display a list of all
71  * documented structure members.
72  *
73  * Selecting the <b>Globals</b> link will display a list
74  * of all functions, structures, global variables and macros in the module.
75  *
76  */
77 
78 
79 #include "util/glheader.h"
80 
81 #include "accum.h"
82 #include "arrayobj.h"
83 #include "attrib.h"
84 #include "bbox.h"
85 #include "blend.h"
86 #include "buffers.h"
87 #include "bufferobj.h"
88 #include "conservativeraster.h"
89 #include "context.h"
90 #include "debug.h"
91 #include "debug_output.h"
92 #include "depth.h"
93 #include "dlist.h"
94 #include "draw_validate.h"
95 #include "eval.h"
96 #include "extensions.h"
97 #include "fbobject.h"
98 #include "feedback.h"
99 #include "fog.h"
100 #include "formats.h"
101 #include "framebuffer.h"
102 #include "glthread.h"
103 #include "hint.h"
104 #include "hash.h"
105 #include "light.h"
106 #include "lines.h"
107 #include "macros.h"
108 #include "matrix.h"
109 #include "multisample.h"
110 #include "performance_monitor.h"
111 #include "performance_query.h"
112 #include "pipelineobj.h"
113 #include "pixel.h"
114 #include "pixelstore.h"
115 #include "points.h"
116 #include "polygon.h"
117 #include "queryobj.h"
118 #include "syncobj.h"
119 #include "rastpos.h"
120 #include "remap.h"
121 #include "scissor.h"
122 #include "shared.h"
123 #include "shaderobj.h"
124 #include "shaderimage.h"
125 #include "state.h"
126 #include "util/u_debug.h"
127 #include "util/disk_cache.h"
128 #include "util/strtod.h"
129 #include "util/u_call_once.h"
130 #include "stencil.h"
131 #include "shaderimage.h"
132 #include "texcompress_s3tc.h"
133 #include "texstate.h"
134 #include "transformfeedback.h"
135 #include "mtypes.h"
136 #include "varray.h"
137 #include "version.h"
138 #include "viewport.h"
139 #include "texturebindless.h"
140 #include "program/program.h"
141 #include "math/m_matrix.h"
142 #include "main/dispatch.h" /* for _gloffset_COUNT */
143 #include "macros.h"
144 #include "git_sha1.h"
145 
146 #include "compiler/glsl_types.h"
147 #include "compiler/glsl/builtin_functions.h"
148 #include "compiler/glsl/glsl_parser_extras.h"
149 #include <stdbool.h>
150 #include "util/u_memory.h"
151 #include "api_exec_decl.h"
152 
153 #include "state_tracker/st_cb_texture.h"
154 #include "state_tracker/st_cb_flush.h"
155 
156 #ifndef MESA_VERBOSE
157 int MESA_VERBOSE = 0;
158 #endif
159 
160 #ifndef MESA_DEBUG_FLAGS
161 int MESA_DEBUG_FLAGS = 0;
162 #endif
163 
164 
165 /* ubyte -> float conversion */
166 GLfloat _mesa_ubyte_to_float_color_tab[256];
167 
168 
169 /**********************************************************************/
170 /** \name Context allocation, initialization, destroying
171  *
172  * The purpose of the most initialization functions here is to provide the
173  * default state values according to the OpenGL specification.
174  */
175 /**********************************************************************/
176 /*@{*/
177 
178 
179 /**
180  * Calls all the various one-time-fini functions in Mesa
181  */
182 
183 static void
one_time_fini(void)184 one_time_fini(void)
185 {
186    glsl_type_singleton_decref();
187 }
188 
189 /**
190  * Calls all the various one-time-init functions in Mesa
191  */
192 
193 static void
one_time_init(const char * extensions_override)194 one_time_init(const char *extensions_override)
195 {
196    GLuint i;
197 
198    STATIC_ASSERT(sizeof(GLbyte) == 1);
199    STATIC_ASSERT(sizeof(GLubyte) == 1);
200    STATIC_ASSERT(sizeof(GLshort) == 2);
201    STATIC_ASSERT(sizeof(GLushort) == 2);
202    STATIC_ASSERT(sizeof(GLint) == 4);
203    STATIC_ASSERT(sizeof(GLuint) == 4);
204 
205    _mesa_locale_init();
206 
207    const char *env_const = os_get_option("MESA_EXTENSION_OVERRIDE");
208    if (env_const) {
209       if (extensions_override &&
210           strcmp(extensions_override, env_const)) {
211          printf("Warning: MESA_EXTENSION_OVERRIDE used instead of driconf setting\n");
212       }
213       extensions_override = env_const;
214    }
215 
216    _mesa_one_time_init_extension_overrides(extensions_override);
217 
218 
219    for (i = 0; i < 256; i++) {
220       _mesa_ubyte_to_float_color_tab[i] = (float) i / 255.0F;
221    }
222 
223    atexit(one_time_fini);
224 
225 #if defined(DEBUG)
226    if (MESA_VERBOSE != 0) {
227       _mesa_debug(NULL, "Mesa " PACKAGE_VERSION " DEBUG build" MESA_GIT_SHA1 "\n");
228    }
229 #endif
230 
231    /* Take a glsl type reference for the duration of libGL's life to avoid
232     * unecessary creation/destruction of glsl types.
233     */
234    glsl_type_singleton_init_or_ref();
235 
236    _mesa_init_remap_table();
237 }
238 
239 /**
240  * Calls all the various one-time-init functions in Mesa.
241  *
242  * While holding a global mutex lock, calls several initialization functions,
243  * and sets the glapi callbacks if the \c MESA_DEBUG environment variable is
244  * defined.
245  */
246 void
_mesa_initialize(const char * extensions_override)247 _mesa_initialize(const char *extensions_override)
248 {
249    static util_once_flag once = UTIL_ONCE_FLAG_INIT;
250    util_call_once_data(&once,
251       (util_call_once_data_func)one_time_init, extensions_override);
252 }
253 
254 
255 /**
256  * Initialize fields of gl_current_attrib (aka ctx->Current.*)
257  */
258 static void
_mesa_init_current(struct gl_context * ctx)259 _mesa_init_current(struct gl_context *ctx)
260 {
261    GLuint i;
262 
263    /* Init all to (0,0,0,1) */
264    for (i = 0; i < ARRAY_SIZE(ctx->Current.Attrib); i++) {
265       ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 );
266    }
267 
268    /* redo special cases: */
269    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 );
270    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 );
271    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 );
272    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX], 1.0, 0.0, 0.0, 1.0 );
273    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG], 1.0, 0.0, 0.0, 1.0 );
274 }
275 
276 
277 /**
278  * Init vertex/fragment/geometry program limits.
279  * Important: drivers should override these with actual limits.
280  */
281 static void
init_program_limits(struct gl_constants * consts,gl_shader_stage stage,struct gl_program_constants * prog)282 init_program_limits(struct gl_constants *consts, gl_shader_stage stage,
283                     struct gl_program_constants *prog)
284 {
285    prog->MaxInstructions = MAX_PROGRAM_INSTRUCTIONS;
286    prog->MaxAluInstructions = MAX_PROGRAM_INSTRUCTIONS;
287    prog->MaxTexInstructions = MAX_PROGRAM_INSTRUCTIONS;
288    prog->MaxTexIndirections = MAX_PROGRAM_INSTRUCTIONS;
289    prog->MaxTemps = MAX_PROGRAM_TEMPS;
290    prog->MaxEnvParams = MAX_PROGRAM_ENV_PARAMS;
291    prog->MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS;
292    prog->MaxAddressOffset = MAX_PROGRAM_LOCAL_PARAMS;
293 
294    switch (stage) {
295    case MESA_SHADER_VERTEX:
296       prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
297       prog->MaxAttribs = MAX_VERTEX_GENERIC_ATTRIBS;
298       prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
299       prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
300       prog->MaxInputComponents = 0; /* value not used */
301       prog->MaxOutputComponents = 16 * 4; /* old limit not to break tnl and swrast */
302       break;
303    case MESA_SHADER_FRAGMENT:
304       prog->MaxParameters = MAX_FRAGMENT_PROGRAM_PARAMS;
305       prog->MaxAttribs = MAX_FRAGMENT_PROGRAM_INPUTS;
306       prog->MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS;
307       prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
308       prog->MaxInputComponents = 16 * 4; /* old limit not to break tnl and swrast */
309       prog->MaxOutputComponents = 0; /* value not used */
310       break;
311    case MESA_SHADER_TESS_CTRL:
312    case MESA_SHADER_TESS_EVAL:
313    case MESA_SHADER_GEOMETRY:
314       prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
315       prog->MaxAttribs = MAX_VERTEX_GENERIC_ATTRIBS;
316       prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
317       prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
318       prog->MaxInputComponents = 16 * 4; /* old limit not to break tnl and swrast */
319       prog->MaxOutputComponents = 16 * 4; /* old limit not to break tnl and swrast */
320       break;
321    case MESA_SHADER_COMPUTE:
322       prog->MaxParameters = 0; /* not meaningful for compute shaders */
323       prog->MaxAttribs = 0; /* not meaningful for compute shaders */
324       prog->MaxAddressRegs = 0; /* not meaningful for compute shaders */
325       prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
326       prog->MaxInputComponents = 0; /* not meaningful for compute shaders */
327       prog->MaxOutputComponents = 0; /* not meaningful for compute shaders */
328       break;
329    default:
330       assert(0 && "Bad shader stage in init_program_limits()");
331    }
332 
333    /* Set the native limits to zero.  This implies that there is no native
334     * support for shaders.  Let the drivers fill in the actual values.
335     */
336    prog->MaxNativeInstructions = 0;
337    prog->MaxNativeAluInstructions = 0;
338    prog->MaxNativeTexInstructions = 0;
339    prog->MaxNativeTexIndirections = 0;
340    prog->MaxNativeAttribs = 0;
341    prog->MaxNativeTemps = 0;
342    prog->MaxNativeAddressRegs = 0;
343    prog->MaxNativeParameters = 0;
344 
345    /* Set GLSL datatype range/precision info assuming IEEE float values.
346     * Drivers should override these defaults as needed.
347     */
348    prog->MediumFloat.RangeMin = 127;
349    prog->MediumFloat.RangeMax = 127;
350    prog->MediumFloat.Precision = 23;
351    prog->LowFloat = prog->HighFloat = prog->MediumFloat;
352 
353    /* Assume ints are stored as floats for now, since this is the least-common
354     * denominator.  The OpenGL ES spec implies (page 132) that the precision
355     * of integer types should be 0.  Practically speaking, IEEE
356     * single-precision floating point values can only store integers in the
357     * range [-0x01000000, 0x01000000] without loss of precision.
358     */
359    prog->MediumInt.RangeMin = 24;
360    prog->MediumInt.RangeMax = 24;
361    prog->MediumInt.Precision = 0;
362    prog->LowInt = prog->HighInt = prog->MediumInt;
363 
364    prog->MaxUniformBlocks = 12;
365    prog->MaxCombinedUniformComponents = (prog->MaxUniformComponents +
366                                          consts->MaxUniformBlockSize / 4 *
367                                          prog->MaxUniformBlocks);
368 
369    prog->MaxAtomicBuffers = 0;
370    prog->MaxAtomicCounters = 0;
371 
372    prog->MaxShaderStorageBlocks = 8;
373 }
374 
375 
376 /**
377  * Initialize fields of gl_constants (aka ctx->Const.*).
378  * Use defaults from config.h.  The device drivers will often override
379  * some of these values (such as number of texture units).
380  */
381 void
_mesa_init_constants(struct gl_constants * consts,gl_api api)382 _mesa_init_constants(struct gl_constants *consts, gl_api api)
383 {
384    int i;
385    assert(consts);
386 
387    /* Constants, may be overriden (usually only reduced) by device drivers */
388    consts->MaxTextureMbytes = MAX_TEXTURE_MBYTES;
389    consts->MaxTextureSize = 1 << (MAX_TEXTURE_LEVELS - 1);
390    consts->Max3DTextureLevels = MAX_TEXTURE_LEVELS;
391    consts->MaxCubeTextureLevels = MAX_TEXTURE_LEVELS;
392    consts->MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE;
393    consts->MaxArrayTextureLayers = MAX_ARRAY_TEXTURE_LAYERS;
394    consts->MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS;
395    consts->Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
396    consts->MaxTextureUnits = MIN2(consts->MaxTextureCoordUnits,
397                                      consts->Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits);
398    consts->MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY;
399    consts->MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS;
400    consts->MaxTextureBufferSize = 65536;
401    consts->TextureBufferOffsetAlignment = 1;
402    consts->MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE;
403    consts->SubPixelBits = SUB_PIXEL_BITS;
404    consts->MinPointSize = MIN_POINT_SIZE;
405    consts->MaxPointSize = MAX_POINT_SIZE;
406    consts->MinPointSizeAA = MIN_POINT_SIZE;
407    consts->MaxPointSizeAA = MAX_POINT_SIZE;
408    consts->PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY;
409    consts->MinLineWidth = MIN_LINE_WIDTH;
410    consts->MaxLineWidth = MAX_LINE_WIDTH;
411    consts->MinLineWidthAA = MIN_LINE_WIDTH;
412    consts->MaxLineWidthAA = MAX_LINE_WIDTH;
413    consts->LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY;
414    consts->MaxClipPlanes = 6;
415    consts->MaxLights = MAX_LIGHTS;
416    consts->MaxShininess = 128.0;
417    consts->MaxSpotExponent = 128.0;
418    consts->MaxViewportWidth = 16384;
419    consts->MaxViewportHeight = 16384;
420    consts->MinMapBufferAlignment = 64;
421 
422    /* Driver must override these values if ARB_viewport_array is supported. */
423    consts->MaxViewports = 1;
424    consts->ViewportSubpixelBits = 0;
425    consts->ViewportBounds.Min = 0;
426    consts->ViewportBounds.Max = 0;
427 
428    /** GL_ARB_uniform_buffer_object */
429    consts->MaxCombinedUniformBlocks = 36;
430    consts->MaxUniformBufferBindings = 36;
431    consts->MaxUniformBlockSize = 16384;
432    consts->UniformBufferOffsetAlignment = 1;
433 
434    /** GL_ARB_shader_storage_buffer_object */
435    consts->MaxCombinedShaderStorageBlocks = 8;
436    consts->MaxShaderStorageBufferBindings = 8;
437    consts->MaxShaderStorageBlockSize = 128 * 1024 * 1024; /* 2^27 */
438    consts->ShaderStorageBufferOffsetAlignment = 256;
439 
440    /* GL_ARB_explicit_uniform_location, GL_MAX_UNIFORM_LOCATIONS */
441    consts->MaxUserAssignableUniformLocations =
442       4 * MESA_SHADER_STAGES * MAX_UNIFORMS;
443 
444    for (i = 0; i < MESA_SHADER_STAGES; i++)
445       init_program_limits(consts, i, &consts->Program[i]);
446 
447    consts->MaxProgramMatrices = MAX_PROGRAM_MATRICES;
448    consts->MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH;
449 
450    /* Set the absolute minimum possible GLSL version.  API_OPENGL_CORE can
451     * mean an OpenGL 3.0 forward-compatible context, so that implies a minimum
452     * possible version of 1.30.  Otherwise, the minimum possible version 1.20.
453     * Since Mesa unconditionally advertises GL_ARB_shading_language_100 and
454     * GL_ARB_shader_objects, every driver has GLSL 1.20... even if they don't
455     * advertise any extensions to enable any shader stages (e.g.,
456     * GL_ARB_vertex_shader).
457     */
458    consts->GLSLVersion = api == API_OPENGL_CORE ? 130 : 120;
459    consts->GLSLVersionCompat = consts->GLSLVersion;
460 
461    consts->GLSLLowerConstArrays = true;
462 
463    /* GL_ARB_draw_buffers */
464    consts->MaxDrawBuffers = MAX_DRAW_BUFFERS;
465 
466    consts->MaxColorAttachments = MAX_COLOR_ATTACHMENTS;
467    consts->MaxRenderbufferSize = MAX_RENDERBUFFER_SIZE;
468 
469    consts->Program[MESA_SHADER_VERTEX].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
470    consts->MaxCombinedTextureImageUnits = MAX_COMBINED_TEXTURE_IMAGE_UNITS;
471    consts->MaxVarying = 16; /* old limit not to break tnl and swrast */
472    consts->Program[MESA_SHADER_GEOMETRY].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
473    consts->MaxGeometryOutputVertices = MAX_GEOMETRY_OUTPUT_VERTICES;
474    consts->MaxGeometryTotalOutputComponents = MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS;
475    consts->MaxGeometryShaderInvocations = MAX_GEOMETRY_SHADER_INVOCATIONS;
476 
477 #ifdef DEBUG
478    consts->GenerateTemporaryNames = true;
479 #else
480    consts->GenerateTemporaryNames = false;
481 #endif
482 
483    /* GL_ARB_framebuffer_object */
484    consts->MaxSamples = 0;
485 
486    /* GLSL default if NativeIntegers == FALSE */
487    consts->UniformBooleanTrue = FLOAT_AS_UNION(1.0f).u;
488 
489    /* GL_ARB_sync */
490    consts->MaxServerWaitTimeout = 0x7fffffff7fffffffULL;
491 
492    /* GL_EXT_provoking_vertex */
493    consts->QuadsFollowProvokingVertexConvention = GL_TRUE;
494 
495    /** GL_ARB_viewport_array */
496    consts->LayerAndVPIndexProvokingVertex = GL_UNDEFINED_VERTEX;
497 
498    /* GL_EXT_transform_feedback */
499    consts->MaxTransformFeedbackBuffers = MAX_FEEDBACK_BUFFERS;
500    consts->MaxTransformFeedbackSeparateComponents = 4 * MAX_FEEDBACK_ATTRIBS;
501    consts->MaxTransformFeedbackInterleavedComponents = 4 * MAX_FEEDBACK_ATTRIBS;
502    consts->MaxVertexStreams = 1;
503 
504    /* GL 3.2  */
505    consts->ProfileMask = api == API_OPENGL_CORE
506                           ? GL_CONTEXT_CORE_PROFILE_BIT
507                           : GL_CONTEXT_COMPATIBILITY_PROFILE_BIT;
508 
509    /* GL 4.4 */
510    consts->MaxVertexAttribStride = 2048;
511 
512    /** GL_EXT_gpu_shader4 */
513    consts->MinProgramTexelOffset = -8;
514    consts->MaxProgramTexelOffset = 7;
515 
516    /* GL_ARB_texture_gather */
517    consts->MinProgramTextureGatherOffset = -8;
518    consts->MaxProgramTextureGatherOffset = 7;
519 
520    /* GL_ARB_robustness */
521    consts->ResetStrategy = GL_NO_RESET_NOTIFICATION_ARB;
522 
523    /* GL_KHR_robustness */
524    consts->RobustAccess = GL_FALSE;
525 
526    /* ES 3.0 or ARB_ES3_compatibility */
527    consts->MaxElementIndex = 0xffffffffu;
528 
529    /* GL_ARB_texture_multisample */
530    consts->MaxColorTextureSamples = 1;
531    consts->MaxDepthTextureSamples = 1;
532    consts->MaxIntegerSamples = 1;
533 
534    /* GL_ARB_shader_atomic_counters */
535    consts->MaxAtomicBufferBindings = MAX_COMBINED_ATOMIC_BUFFERS;
536    consts->MaxAtomicBufferSize = MAX_ATOMIC_COUNTERS * ATOMIC_COUNTER_SIZE;
537    consts->MaxCombinedAtomicBuffers = MAX_COMBINED_ATOMIC_BUFFERS;
538    consts->MaxCombinedAtomicCounters = MAX_ATOMIC_COUNTERS;
539 
540    /* GL_ARB_vertex_attrib_binding */
541    consts->MaxVertexAttribRelativeOffset = 2047;
542    consts->MaxVertexAttribBindings = MAX_VERTEX_GENERIC_ATTRIBS;
543 
544    /* GL_ARB_compute_shader */
545    consts->MaxComputeWorkGroupCount[0] = 65535;
546    consts->MaxComputeWorkGroupCount[1] = 65535;
547    consts->MaxComputeWorkGroupCount[2] = 65535;
548    consts->MaxComputeWorkGroupSize[0] = 1024;
549    consts->MaxComputeWorkGroupSize[1] = 1024;
550    consts->MaxComputeWorkGroupSize[2] = 64;
551    /* Enables compute support for GLES 3.1 if >= 128 */
552    consts->MaxComputeWorkGroupInvocations = 0;
553 
554    /** GL_ARB_gpu_shader5 */
555    consts->MinFragmentInterpolationOffset = MIN_FRAGMENT_INTERPOLATION_OFFSET;
556    consts->MaxFragmentInterpolationOffset = MAX_FRAGMENT_INTERPOLATION_OFFSET;
557 
558    /** GL_KHR_context_flush_control */
559    consts->ContextReleaseBehavior = GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH;
560 
561    /** GL_ARB_tessellation_shader */
562    consts->MaxTessGenLevel = MAX_TESS_GEN_LEVEL;
563    consts->MaxPatchVertices = MAX_PATCH_VERTICES;
564    consts->Program[MESA_SHADER_TESS_CTRL].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
565    consts->Program[MESA_SHADER_TESS_EVAL].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
566    consts->MaxTessPatchComponents = MAX_TESS_PATCH_COMPONENTS;
567    consts->MaxTessControlTotalOutputComponents = MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS;
568    consts->PrimitiveRestartForPatches = false;
569 
570    /** GL_ARB_compute_variable_group_size */
571    consts->MaxComputeVariableGroupSize[0] = 512;
572    consts->MaxComputeVariableGroupSize[1] = 512;
573    consts->MaxComputeVariableGroupSize[2] = 64;
574    consts->MaxComputeVariableGroupInvocations = 512;
575 
576    /** GL_NV_conservative_raster */
577    consts->MaxSubpixelPrecisionBiasBits = 0;
578 
579    /** GL_NV_conservative_raster_dilate */
580    consts->ConservativeRasterDilateRange[0] = 0.0;
581    consts->ConservativeRasterDilateRange[1] = 0.0;
582    consts->ConservativeRasterDilateGranularity = 0.0;
583 
584    consts->glBeginEndBufferSize = 512 * 1024;
585 }
586 
587 
588 /**
589  * Do some sanity checks on the limits/constants for the given context.
590  * Only called the first time a context is bound.
591  */
592 static void
check_context_limits(struct gl_context * ctx)593 check_context_limits(struct gl_context *ctx)
594 {
595    (void) ctx;
596 
597    /* check that we don't exceed the size of various bitfields */
598    assert(VARYING_SLOT_MAX <=
599           (8 * sizeof(ctx->VertexProgram._Current->info.outputs_written)));
600    assert(VARYING_SLOT_MAX <=
601           (8 * sizeof(ctx->FragmentProgram._Current->info.inputs_read)));
602 
603    /* shader-related checks */
604    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
605    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
606 
607    /* Texture unit checks */
608    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits > 0);
609    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
610    assert(ctx->Const.MaxTextureCoordUnits > 0);
611    assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
612    assert(ctx->Const.MaxTextureUnits > 0);
613    assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
614    assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
615    assert(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits,
616                                              ctx->Const.MaxTextureCoordUnits));
617    assert(ctx->Const.MaxCombinedTextureImageUnits > 0);
618    assert(ctx->Const.MaxCombinedTextureImageUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
619    assert(ctx->Const.MaxTextureCoordUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
620    /* number of coord units cannot be greater than number of image units */
621    assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits);
622 
623 
624    /* Texture size checks */
625    assert(ctx->Const.MaxTextureSize <= (1 << (MAX_TEXTURE_LEVELS - 1)));
626    assert(ctx->Const.Max3DTextureLevels <= MAX_TEXTURE_LEVELS);
627    assert(ctx->Const.MaxCubeTextureLevels <= MAX_TEXTURE_LEVELS);
628    assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
629 
630    /* Max texture size should be <= max viewport size (render to texture) */
631    assert(ctx->Const.MaxTextureSize <= ctx->Const.MaxViewportWidth);
632    assert(ctx->Const.MaxTextureSize <= ctx->Const.MaxViewportHeight);
633 
634    assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS);
635 
636    /* if this fails, add more enum values to gl_buffer_index */
637    assert(BUFFER_COLOR0 + MAX_DRAW_BUFFERS <= BUFFER_COUNT);
638 
639    /* XXX probably add more tests */
640 }
641 
642 
643 /**
644  * Initialize the attribute groups in a GL context.
645  *
646  * \param ctx GL context.
647  *
648  * Initializes all the attributes, calling the respective <tt>init*</tt>
649  * functions for the more complex data structures.
650  */
651 static GLboolean
init_attrib_groups(struct gl_context * ctx)652 init_attrib_groups(struct gl_context *ctx)
653 {
654    assert(ctx);
655 
656    /* Constants */
657    _mesa_init_constants(&ctx->Const, ctx->API);
658 
659    /* Extensions */
660    _mesa_init_extensions(&ctx->Extensions);
661 
662    /* Attribute Groups */
663    _mesa_init_accum( ctx );
664    _mesa_init_attrib( ctx );
665    _mesa_init_bbox( ctx );
666    _mesa_init_buffer_objects( ctx );
667    _mesa_init_color( ctx );
668    _mesa_init_conservative_raster( ctx );
669    _mesa_init_current( ctx );
670    _mesa_init_depth( ctx );
671    _mesa_init_debug( ctx );
672    _mesa_init_debug_output( ctx );
673    _mesa_init_display_list( ctx );
674    _mesa_init_eval( ctx );
675    _mesa_init_feedback( ctx );
676    _mesa_init_fog( ctx );
677    _mesa_init_hint( ctx );
678    _mesa_init_image_units( ctx );
679    _mesa_init_line( ctx );
680    _mesa_init_lighting( ctx );
681    _mesa_init_matrix( ctx );
682    _mesa_init_multisample( ctx );
683    _mesa_init_performance_monitors( ctx );
684    _mesa_init_performance_queries( ctx );
685    _mesa_init_pipeline( ctx );
686    _mesa_init_pixel( ctx );
687    _mesa_init_pixelstore( ctx );
688    _mesa_init_point( ctx );
689    _mesa_init_polygon( ctx );
690    _mesa_init_varray( ctx ); /* should be before _mesa_init_program */
691    _mesa_init_program( ctx );
692    _mesa_init_queryobj( ctx );
693    _mesa_init_sync( ctx );
694    _mesa_init_rastpos( ctx );
695    _mesa_init_scissor( ctx );
696    _mesa_init_shader_state( ctx );
697    _mesa_init_stencil( ctx );
698    _mesa_init_transform( ctx );
699    _mesa_init_transform_feedback( ctx );
700    _mesa_init_viewport( ctx );
701    _mesa_init_resident_handles( ctx );
702 
703    if (!_mesa_init_texture( ctx ))
704       return GL_FALSE;
705 
706    /* Miscellaneous */
707    ctx->TileRasterOrderIncreasingX = GL_TRUE;
708    ctx->TileRasterOrderIncreasingY = GL_TRUE;
709    ctx->NewState = _NEW_ALL;
710    ctx->NewDriverState = ST_ALL_STATES_MASK;
711    ctx->ErrorValue = GL_NO_ERROR;
712    ctx->ShareGroupReset = false;
713    ctx->IntelBlackholeRender = debug_get_bool_option("INTEL_BLACKHOLE_DEFAULT", false);
714 
715    return GL_TRUE;
716 }
717 
718 
719 /**
720  * Update default objects in a GL context with respect to shared state.
721  *
722  * \param ctx GL context.
723  *
724  * Removes references to old default objects, (texture objects, program
725  * objects, etc.) and changes to reference those from the current shared
726  * state.
727  */
728 static GLboolean
update_default_objects(struct gl_context * ctx)729 update_default_objects(struct gl_context *ctx)
730 {
731    assert(ctx);
732 
733    _mesa_update_default_objects_program(ctx);
734    _mesa_update_default_objects_texture(ctx);
735    _mesa_update_default_objects_buffer_objects(ctx);
736 
737    return GL_TRUE;
738 }
739 
740 
741 /* XXX this is temporary and should be removed at some point in the
742  * future when there's a reasonable expectation that the libGL library
743  * contains the _glapi_new_nop_table() and _glapi_set_nop_handler()
744  * functions which were added in Mesa 10.6.
745  */
746 #if !defined(_WIN32)
747 /* Avoid libGL / driver ABI break */
748 #define USE_GLAPI_NOP_FEATURES 0
749 #else
750 #define USE_GLAPI_NOP_FEATURES 1
751 #endif
752 
753 
754 /**
755  * This function is called by the glapi no-op functions.  For each OpenGL
756  * function/entrypoint there's a simple no-op function.  These "no-op"
757  * functions call this function.
758  *
759  * If there's a current OpenGL context for the calling thread, we record a
760  * GL_INVALID_OPERATION error.  This can happen either because the app's
761  * calling an unsupported extension function, or calling an illegal function
762  * (such as glClear between glBegin/glEnd).
763  *
764  * If there's no current OpenGL context for the calling thread, we can
765  * print a message to stderr.
766  *
767  * \param name  the name of the OpenGL function
768  */
769 #if USE_GLAPI_NOP_FEATURES
770 static void
nop_handler(const char * name)771 nop_handler(const char *name)
772 {
773    GET_CURRENT_CONTEXT(ctx);
774    if (ctx) {
775       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(invalid call)", name);
776    }
777 #ifndef NDEBUG
778    else if (getenv("MESA_DEBUG") || getenv("LIBGL_DEBUG")) {
779       fprintf(stderr,
780               "GL User Error: gl%s called without a rendering context\n",
781               name);
782       fflush(stderr);
783    }
784 #endif
785 }
786 #endif
787 
788 
789 /**
790  * Special no-op glFlush, see below.
791  */
792 #if defined(_WIN32)
793 static void GLAPIENTRY
nop_glFlush(void)794 nop_glFlush(void)
795 {
796    /* don't record an error like we do in nop_handler() */
797 }
798 #endif
799 
800 
801 #if !USE_GLAPI_NOP_FEATURES
802 static int
generic_nop(void)803 generic_nop(void)
804 {
805    GET_CURRENT_CONTEXT(ctx);
806    _mesa_error(ctx, GL_INVALID_OPERATION,
807                "unsupported function called "
808                "(unsupported extension or deprecated function?)");
809    return 0;
810 }
811 #endif
812 
813 
814 static int
glthread_nop(void)815 glthread_nop(void)
816 {
817    /* This writes the error into the glthread command buffer if glthread is
818     * enabled.
819     */
820    CALL_InternalSetError(GET_DISPATCH(), (GL_INVALID_OPERATION));
821    return 0;
822 }
823 
824 
825 /**
826  * Create a new API dispatch table in which all entries point to the
827  * generic_nop() function.  This will not work on Windows because of
828  * the __stdcall convention which requires the callee to clean up the
829  * call stack.  That's impossible with one generic no-op function.
830  */
831 struct _glapi_table *
_mesa_new_nop_table(unsigned numEntries,bool glthread)832 _mesa_new_nop_table(unsigned numEntries, bool glthread)
833 {
834    struct _glapi_table *table;
835 
836 #if !USE_GLAPI_NOP_FEATURES
837    table = malloc(numEntries * sizeof(_glapi_proc));
838    if (table) {
839       _glapi_proc *entry = (_glapi_proc *) table;
840       unsigned i;
841       for (i = 0; i < numEntries; i++) {
842          entry[i] = (_glapi_proc) generic_nop;
843       }
844    }
845 #else
846    table = _glapi_new_nop_table(numEntries);
847 #endif
848 
849    if (glthread) {
850       _glapi_proc *entry = (_glapi_proc *) table;
851       for (unsigned i = 0; i < numEntries; i++)
852          entry[i] = (_glapi_proc)glthread_nop;
853    }
854 
855    return table;
856 }
857 
858 
859 /**
860  * Allocate and initialize a new dispatch table.  The table will be
861  * populated with pointers to "no-op" functions.  In turn, the no-op
862  * functions will call nop_handler() above.
863  */
864 struct _glapi_table *
_mesa_alloc_dispatch_table(bool glthread)865 _mesa_alloc_dispatch_table(bool glthread)
866 {
867    /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
868     * In practice, this'll be the same for stand-alone Mesa.  But for DRI
869     * Mesa we do this to accommodate different versions of libGL and various
870     * DRI drivers.
871     */
872    int numEntries = MAX2(_glapi_get_dispatch_table_size(), _gloffset_COUNT);
873 
874    struct _glapi_table *table = _mesa_new_nop_table(numEntries, glthread);
875 
876 #if defined(_WIN32)
877    if (table) {
878       /* This is a special case for Windows in the event that
879        * wglGetProcAddress is called between glBegin/End().
880        *
881        * The MS opengl32.dll library apparently calls glFlush from
882        * wglGetProcAddress().  If we're inside glBegin/End(), glFlush
883        * will dispatch to _mesa_generic_nop() and we'll generate a
884        * GL_INVALID_OPERATION error.
885        *
886        * The specific case which hits this is piglit's primitive-restart
887        * test which calls glPrimitiveRestartNV() inside glBegin/End.  The
888        * first time we call glPrimitiveRestartNV() Piglit's API dispatch
889        * code will try to resolve the function by calling wglGetProcAddress.
890        * This raises GL_INVALID_OPERATION and an assert(glGetError()==0)
891        * will fail causing the test to fail.  By suppressing the error, the
892        * assertion passes and the test continues.
893        */
894       SET_Flush(table, nop_glFlush);
895    }
896 #endif
897 
898 #if USE_GLAPI_NOP_FEATURES
899    _glapi_set_nop_handler(nop_handler);
900 #endif
901 
902    return table;
903 }
904 
905 /**
906  * Allocate dispatch tables and set all functions to nop.
907  * It also makes the OutsideBeginEnd dispatch table current within gl_dispatch.
908  *
909  * \param glthread Whether to set nop dispatch for glthread or regular dispatch
910  */
911 bool
_mesa_alloc_dispatch_tables(gl_api api,struct gl_dispatch * d,bool glthread)912 _mesa_alloc_dispatch_tables(gl_api api, struct gl_dispatch *d, bool glthread)
913 {
914    d->OutsideBeginEnd = _mesa_alloc_dispatch_table(glthread);
915    if (!d->OutsideBeginEnd)
916       return false;
917 
918    if (api == API_OPENGL_COMPAT) {
919       d->BeginEnd = _mesa_alloc_dispatch_table(glthread);
920       d->Save = _mesa_alloc_dispatch_table(glthread);
921       if (!d->BeginEnd || !d->Save)
922          return false;
923    }
924 
925    d->Current = d->Exec = d->OutsideBeginEnd;
926    return true;
927 }
928 
929 static void
_mesa_free_dispatch_tables(struct gl_dispatch * d)930 _mesa_free_dispatch_tables(struct gl_dispatch *d)
931 {
932    free(d->OutsideBeginEnd);
933    free(d->BeginEnd);
934    free(d->HWSelectModeBeginEnd);
935    free(d->Save);
936    free(d->ContextLost);
937 }
938 
939 bool
_mesa_initialize_dispatch_tables(struct gl_context * ctx)940 _mesa_initialize_dispatch_tables(struct gl_context *ctx)
941 {
942    if (!_mesa_alloc_dispatch_tables(ctx->API, &ctx->Dispatch, false))
943       return false;
944 
945    /* Do the code-generated initialization of dispatch tables. */
946    _mesa_init_dispatch(ctx);
947    vbo_init_dispatch_begin_end(ctx);
948 
949    if (_mesa_is_desktop_gl_compat(ctx)) {
950       _mesa_init_dispatch_save(ctx);
951       _mesa_init_dispatch_save_begin_end(ctx);
952    }
953 
954    /* This binds the dispatch table to the context, but MakeCurrent will
955     * bind it for the user. If glthread is enabled, it will override it.
956     */
957    ctx->GLApi = ctx->Dispatch.Current;
958    return true;
959 }
960 
961 /**
962  * Initialize a struct gl_context struct (rendering context).
963  *
964  * This includes allocating all the other structs and arrays which hang off of
965  * the context by pointers.
966  * Note that the driver needs to pass in its dd_function_table here since
967  * we need to at least call st_NewTextureObject to create the
968  * default texture objects.
969  *
970  * Called by _mesa_create_context().
971  *
972  * Performs the imports and exports callback tables initialization, and
973  * miscellaneous one-time initializations. If no shared context is supplied one
974  * is allocated, and increase its reference count.  Setups the GL API dispatch
975  * tables.  Initialize the TNL module. Sets the maximum Z buffer depth.
976  * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
977  * for debug flags.
978  *
979  * \param ctx the context to initialize
980  * \param api the GL API type to create the context for
981  * \param visual describes the visual attributes for this context or NULL to
982  *               create a configless context
983  * \param share_list points to context to share textures, display lists,
984  *        etc with, or NULL
985  * \param driverFunctions table of device driver functions for this context
986  *        to use
987  */
988 GLboolean
_mesa_initialize_context(struct gl_context * ctx,gl_api api,bool no_error,const struct gl_config * visual,struct gl_context * share_list,const struct dd_function_table * driverFunctions)989 _mesa_initialize_context(struct gl_context *ctx,
990                          gl_api api,
991                          bool no_error,
992                          const struct gl_config *visual,
993                          struct gl_context *share_list,
994                          const struct dd_function_table *driverFunctions)
995 {
996    struct gl_shared_state *shared;
997    int i;
998 
999    switch (api) {
1000    case API_OPENGL_COMPAT:
1001    case API_OPENGL_CORE:
1002       if (!HAVE_OPENGL)
1003          return GL_FALSE;
1004       break;
1005    case API_OPENGLES2:
1006       if (!HAVE_OPENGL_ES_2)
1007          return GL_FALSE;
1008       break;
1009    case API_OPENGLES:
1010       if (!HAVE_OPENGL_ES_1)
1011          return GL_FALSE;
1012       break;
1013    default:
1014       return GL_FALSE;
1015    }
1016 
1017    ctx->API = api;
1018    ctx->DrawBuffer = NULL;
1019    ctx->ReadBuffer = NULL;
1020    ctx->WinSysDrawBuffer = NULL;
1021    ctx->WinSysReadBuffer = NULL;
1022 
1023    if (visual) {
1024       ctx->Visual = *visual;
1025       ctx->HasConfig = GL_TRUE;
1026    }
1027    else {
1028       memset(&ctx->Visual, 0, sizeof ctx->Visual);
1029       ctx->HasConfig = GL_FALSE;
1030    }
1031 
1032    _mesa_override_gl_version(ctx);
1033 
1034    /* misc one-time initializations */
1035    _mesa_initialize(NULL);
1036 
1037    /* Plug in driver functions and context pointer here.
1038     * This is important because when we call alloc_shared_state() below
1039     * we'll call ctx->Driver.NewTextureObject() to create the default
1040     * textures.
1041     */
1042    ctx->Driver = *driverFunctions;
1043 
1044    if (share_list) {
1045       /* share state with another context */
1046       shared = share_list->Shared;
1047    }
1048    else {
1049       /* allocate new, unshared state */
1050       shared = _mesa_alloc_shared_state(ctx);
1051       if (!shared)
1052          return GL_FALSE;
1053    }
1054 
1055    /* all supported by default */
1056    ctx->Const.DriverSupportedPrimMask = 0xffffffff;
1057 
1058    _mesa_reference_shared_state(ctx, &ctx->Shared, shared);
1059 
1060    if (!init_attrib_groups( ctx ))
1061       goto fail;
1062 
1063    if (no_error)
1064       ctx->Const.ContextFlags |= GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR;
1065 
1066    _mesa_reset_vertex_processing_mode(ctx);
1067 
1068    /* Mesa core handles all the formats that mesa core knows about.
1069     * Drivers will want to override this list with just the formats
1070     * they can handle.
1071     */
1072    memset(&ctx->TextureFormatSupported, GL_TRUE,
1073           sizeof(ctx->TextureFormatSupported));
1074 
1075    switch (ctx->API) {
1076    case API_OPENGL_COMPAT:
1077    case API_OPENGL_CORE:
1078    case API_OPENGLES2:
1079       break;
1080    case API_OPENGLES:
1081       /**
1082        * GL_OES_texture_cube_map says
1083        * "Initially all texture generation modes are set to REFLECTION_MAP_OES"
1084        */
1085       for (i = 0; i < ARRAY_SIZE(ctx->Texture.FixedFuncUnit); i++) {
1086          struct gl_fixedfunc_texture_unit *texUnit =
1087             &ctx->Texture.FixedFuncUnit[i];
1088 
1089          texUnit->GenS.Mode = GL_REFLECTION_MAP_NV;
1090          texUnit->GenT.Mode = GL_REFLECTION_MAP_NV;
1091          texUnit->GenR.Mode = GL_REFLECTION_MAP_NV;
1092          texUnit->GenS._ModeBit = TEXGEN_REFLECTION_MAP_NV;
1093          texUnit->GenT._ModeBit = TEXGEN_REFLECTION_MAP_NV;
1094          texUnit->GenR._ModeBit = TEXGEN_REFLECTION_MAP_NV;
1095       }
1096       break;
1097    }
1098    ctx->VertexProgram.PointSizeEnabled = _mesa_is_gles2(ctx);
1099    ctx->PointSizeIsSet = GL_TRUE;
1100 
1101    ctx->FirstTimeCurrent = GL_TRUE;
1102 
1103    return GL_TRUE;
1104 
1105 fail:
1106    _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
1107    return GL_FALSE;
1108 }
1109 
1110 
1111 /**
1112  * Free the data associated with the given context.
1113  *
1114  * But doesn't free the struct gl_context struct itself.
1115  *
1116  * \sa _mesa_initialize_context() and init_attrib_groups().
1117  */
1118 void
_mesa_free_context_data(struct gl_context * ctx,bool destroy_debug_output)1119 _mesa_free_context_data(struct gl_context *ctx, bool destroy_debug_output)
1120 {
1121    if (!_mesa_get_current_context()){
1122       /* No current context, but we may need one in order to delete
1123        * texture objs, etc.  So temporarily bind the context now.
1124        */
1125       _mesa_make_current(ctx, NULL, NULL);
1126    }
1127 
1128    /* unreference WinSysDraw/Read buffers */
1129    _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
1130    _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
1131    _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
1132    _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
1133 
1134    _mesa_reference_program(ctx, &ctx->VertexProgram.Current, NULL);
1135    _mesa_reference_program(ctx, &ctx->VertexProgram._Current, NULL);
1136    _mesa_reference_program(ctx, &ctx->VertexProgram._TnlProgram, NULL);
1137 
1138    _mesa_reference_program(ctx, &ctx->TessCtrlProgram._Current, NULL);
1139    _mesa_reference_program(ctx, &ctx->TessEvalProgram._Current, NULL);
1140    _mesa_reference_program(ctx, &ctx->GeometryProgram._Current, NULL);
1141 
1142    _mesa_reference_program(ctx, &ctx->FragmentProgram.Current, NULL);
1143    _mesa_reference_program(ctx, &ctx->FragmentProgram._Current, NULL);
1144    _mesa_reference_program(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
1145 
1146    _mesa_reference_program(ctx, &ctx->ComputeProgram._Current, NULL);
1147 
1148    _mesa_reference_vao(ctx, &ctx->Array.VAO, NULL);
1149    _mesa_reference_vao(ctx, &ctx->Array.DefaultVAO, NULL);
1150    _mesa_reference_vao(ctx, &ctx->Array._DrawVAO, NULL);
1151 
1152    _mesa_free_attrib_data(ctx);
1153    _mesa_free_eval_data( ctx );
1154    _mesa_free_feedback(ctx);
1155    _mesa_free_texture_data( ctx );
1156    _mesa_free_image_textures(ctx);
1157    _mesa_free_matrix_data( ctx );
1158    _mesa_free_pipeline_data(ctx);
1159    _mesa_free_program_data(ctx);
1160    _mesa_free_shader_state(ctx);
1161    _mesa_free_queryobj_data(ctx);
1162    _mesa_free_sync_data(ctx);
1163    _mesa_free_varray_data(ctx);
1164    _mesa_free_transform_feedback(ctx);
1165    _mesa_free_performance_monitors(ctx);
1166    _mesa_free_performance_queries(ctx);
1167    _mesa_free_perfomance_monitor_groups(ctx);
1168    _mesa_free_resident_handles(ctx);
1169 
1170    _mesa_reference_buffer_object(ctx, &ctx->Pack.BufferObj, NULL);
1171    _mesa_reference_buffer_object(ctx, &ctx->Unpack.BufferObj, NULL);
1172    _mesa_reference_buffer_object(ctx, &ctx->DefaultPacking.BufferObj, NULL);
1173    _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
1174 
1175    /* This must be called after all buffers are unbound because global buffer
1176     * references that this context holds will be removed.
1177     */
1178    _mesa_free_buffer_objects(ctx);
1179 
1180    /* free dispatch tables */
1181    _mesa_free_dispatch_tables(&ctx->Dispatch);
1182    free(ctx->MarshalExec);
1183 
1184    /* Shared context state (display lists, textures, etc) */
1185    _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
1186 
1187    if (destroy_debug_output)
1188       _mesa_destroy_debug_output(ctx);
1189 
1190    free((void *)ctx->Extensions.String);
1191 
1192    free(ctx->VersionString);
1193 
1194    ralloc_free(ctx->SoftFP64);
1195 
1196    /* unbind the context if it's currently bound */
1197    if (ctx == _mesa_get_current_context()) {
1198       _mesa_make_current(NULL, NULL, NULL);
1199    }
1200 
1201    /* Do this after unbinding context to ensure any thread is finished. */
1202    if (ctx->shader_builtin_ref) {
1203       _mesa_glsl_builtin_functions_decref();
1204       ctx->shader_builtin_ref = false;
1205    }
1206 
1207    free(ctx->Const.SpirVExtensions);
1208    free(ctx->tmp_draws);
1209 }
1210 
1211 
1212 /**
1213  * Copy attribute groups from one context to another.
1214  *
1215  * \param src source context
1216  * \param dst destination context
1217  * \param mask bitwise OR of GL_*_BIT flags
1218  *
1219  * According to the bits specified in \p mask, copies the corresponding
1220  * attributes from \p src into \p dst.  For many of the attributes a simple \c
1221  * memcpy is not enough due to the existence of internal pointers in their data
1222  * structures.
1223  */
1224 void
_mesa_copy_context(const struct gl_context * src,struct gl_context * dst,GLuint mask)1225 _mesa_copy_context( const struct gl_context *src, struct gl_context *dst,
1226                     GLuint mask )
1227 {
1228    if (mask & GL_ACCUM_BUFFER_BIT) {
1229       /* OK to memcpy */
1230       dst->Accum = src->Accum;
1231    }
1232    if (mask & GL_COLOR_BUFFER_BIT) {
1233       /* OK to memcpy */
1234       dst->Color = src->Color;
1235    }
1236    if (mask & GL_CURRENT_BIT) {
1237       /* OK to memcpy */
1238       dst->Current = src->Current;
1239    }
1240    if (mask & GL_DEPTH_BUFFER_BIT) {
1241       /* OK to memcpy */
1242       dst->Depth = src->Depth;
1243    }
1244    if (mask & GL_ENABLE_BIT) {
1245       /* no op */
1246    }
1247    if (mask & GL_EVAL_BIT) {
1248       /* OK to memcpy */
1249       dst->Eval = src->Eval;
1250    }
1251    if (mask & GL_FOG_BIT) {
1252       /* OK to memcpy */
1253       dst->Fog = src->Fog;
1254    }
1255    if (mask & GL_HINT_BIT) {
1256       /* OK to memcpy */
1257       dst->Hint = src->Hint;
1258    }
1259    if (mask & GL_LIGHTING_BIT) {
1260       /* OK to memcpy */
1261       dst->Light = src->Light;
1262    }
1263    if (mask & GL_LINE_BIT) {
1264       /* OK to memcpy */
1265       dst->Line = src->Line;
1266    }
1267    if (mask & GL_LIST_BIT) {
1268       /* OK to memcpy */
1269       dst->List = src->List;
1270    }
1271    if (mask & GL_PIXEL_MODE_BIT) {
1272       /* OK to memcpy */
1273       dst->Pixel = src->Pixel;
1274    }
1275    if (mask & GL_POINT_BIT) {
1276       /* OK to memcpy */
1277       dst->Point = src->Point;
1278    }
1279    if (mask & GL_POLYGON_BIT) {
1280       /* OK to memcpy */
1281       dst->Polygon = src->Polygon;
1282    }
1283    if (mask & GL_POLYGON_STIPPLE_BIT) {
1284       /* Use loop instead of memcpy due to problem with Portland Group's
1285        * C compiler.  Reported by John Stone.
1286        */
1287       GLuint i;
1288       for (i = 0; i < 32; i++) {
1289          dst->PolygonStipple[i] = src->PolygonStipple[i];
1290       }
1291    }
1292    if (mask & GL_SCISSOR_BIT) {
1293       /* OK to memcpy */
1294       dst->Scissor = src->Scissor;
1295    }
1296    if (mask & GL_STENCIL_BUFFER_BIT) {
1297       /* OK to memcpy */
1298       dst->Stencil = src->Stencil;
1299    }
1300    if (mask & GL_TEXTURE_BIT) {
1301       /* Cannot memcpy because of pointers */
1302       _mesa_copy_texture_state(src, dst);
1303    }
1304    if (mask & GL_TRANSFORM_BIT) {
1305       /* OK to memcpy */
1306       dst->Transform = src->Transform;
1307    }
1308    if (mask & GL_VIEWPORT_BIT) {
1309       unsigned i;
1310       for (i = 0; i < src->Const.MaxViewports; i++) {
1311          /* OK to memcpy */
1312          dst->ViewportArray[i] = src->ViewportArray[i];
1313       }
1314    }
1315 
1316    /* XXX FIXME:  Call callbacks?
1317     */
1318    dst->NewState = _NEW_ALL;
1319    dst->NewDriverState = ST_ALL_STATES_MASK;
1320 }
1321 
1322 
1323 /**
1324  * Check if the given context can render into the given framebuffer
1325  * by checking visual attributes.
1326  *
1327  * \return GL_TRUE if compatible, GL_FALSE otherwise.
1328  */
1329 static GLboolean
check_compatible(const struct gl_context * ctx,const struct gl_framebuffer * buffer)1330 check_compatible(const struct gl_context *ctx,
1331                  const struct gl_framebuffer *buffer)
1332 {
1333    const struct gl_config *ctxvis = &ctx->Visual;
1334    const struct gl_config *bufvis = &buffer->Visual;
1335 
1336    if (buffer == _mesa_get_incomplete_framebuffer())
1337       return GL_TRUE;
1338 
1339 #define check_component(foo)           \
1340    if (ctxvis->foo && bufvis->foo &&   \
1341        ctxvis->foo != bufvis->foo)     \
1342       return GL_FALSE
1343 
1344    check_component(redShift);
1345    check_component(greenShift);
1346    check_component(blueShift);
1347    check_component(redBits);
1348    check_component(greenBits);
1349    check_component(blueBits);
1350    check_component(depthBits);
1351    check_component(stencilBits);
1352 
1353 #undef check_component
1354 
1355    return GL_TRUE;
1356 }
1357 
1358 
1359 /**
1360  * Check if the viewport/scissor size has not yet been initialized.
1361  * Initialize the size if the given width and height are non-zero.
1362  */
1363 static void
check_init_viewport(struct gl_context * ctx,GLuint width,GLuint height)1364 check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height)
1365 {
1366    if (!ctx->ViewportInitialized && width > 0 && height > 0) {
1367       unsigned i;
1368 
1369       /* Note: set flag here, before calling _mesa_set_viewport(), to prevent
1370        * potential infinite recursion.
1371        */
1372       ctx->ViewportInitialized = GL_TRUE;
1373 
1374       /* Note: ctx->Const.MaxViewports may not have been set by the driver
1375        * yet, so just initialize all of them.
1376        */
1377       for (i = 0; i < MAX_VIEWPORTS; i++) {
1378          _mesa_set_viewport(ctx, i, 0, 0, width, height);
1379          _mesa_set_scissor(ctx, i, 0, 0, width, height);
1380       }
1381    }
1382 }
1383 
1384 
1385 static void
handle_first_current(struct gl_context * ctx)1386 handle_first_current(struct gl_context *ctx)
1387 {
1388    if (ctx->Version == 0 || !ctx->DrawBuffer) {
1389       /* probably in the process of tearing down the context */
1390       return;
1391    }
1392 
1393    check_context_limits(ctx);
1394 
1395    _mesa_update_vertex_processing_mode(ctx);
1396 
1397    /* According to GL_MESA_configless_context the default value of
1398     * glDrawBuffers depends on the config of the first surface it is bound to.
1399     * For GLES it is always GL_BACK which has a magic interpretation.
1400     */
1401    if (!ctx->HasConfig && _mesa_is_desktop_gl(ctx)) {
1402       if (ctx->DrawBuffer != _mesa_get_incomplete_framebuffer()) {
1403          GLenum16 buffer;
1404 
1405          if (ctx->DrawBuffer->Visual.doubleBufferMode)
1406             buffer = GL_BACK;
1407          else
1408             buffer = GL_FRONT;
1409 
1410          _mesa_drawbuffers(ctx, ctx->DrawBuffer, 1, &buffer,
1411                            NULL /* destMask */);
1412       }
1413 
1414       if (ctx->ReadBuffer != _mesa_get_incomplete_framebuffer()) {
1415          gl_buffer_index bufferIndex;
1416          GLenum buffer;
1417 
1418          if (ctx->ReadBuffer->Visual.doubleBufferMode) {
1419             buffer = GL_BACK;
1420             bufferIndex = BUFFER_BACK_LEFT;
1421          }
1422          else {
1423             buffer = GL_FRONT;
1424             bufferIndex = BUFFER_FRONT_LEFT;
1425          }
1426 
1427          _mesa_readbuffer(ctx, ctx->ReadBuffer, buffer, bufferIndex);
1428       }
1429    }
1430 
1431    /* Determine if generic vertex attribute 0 aliases the conventional
1432     * glVertex position.
1433     */
1434    {
1435       const bool is_forward_compatible_context =
1436          ctx->Const.ContextFlags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT;
1437 
1438       /* In OpenGL 3.1 attribute 0 becomes non-magic, just like in OpenGL ES
1439        * 2.0.  Note that we cannot just check for API_OPENGL_COMPAT here because
1440        * that will erroneously allow this usage in a 3.0 forward-compatible
1441        * context too.
1442        */
1443       ctx->_AttribZeroAliasesVertex = (_mesa_is_gles1(ctx)
1444                                        || (_mesa_is_desktop_gl_compat(ctx)
1445                                            && !is_forward_compatible_context));
1446    }
1447 
1448    /* We can use this to help debug user's problems.  Tell them to set
1449     * the MESA_INFO env variable before running their app.  Then the
1450     * first time each context is made current we'll print some useful
1451     * information.
1452     */
1453    if (getenv("MESA_INFO")) {
1454       _mesa_print_info(ctx);
1455    }
1456 }
1457 
1458 /**
1459  * Bind the given context to the given drawBuffer and readBuffer and
1460  * make it the current context for the calling thread.
1461  * We'll render into the drawBuffer and read pixels from the
1462  * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
1463  *
1464  * We check that the context's and framebuffer's visuals are compatible
1465  * and return immediately if they're not.
1466  *
1467  * \param newCtx  the new GL context. If NULL then there will be no current GL
1468  *                context.
1469  * \param drawBuffer  the drawing framebuffer
1470  * \param readBuffer  the reading framebuffer
1471  */
1472 GLboolean
_mesa_make_current(struct gl_context * newCtx,struct gl_framebuffer * drawBuffer,struct gl_framebuffer * readBuffer)1473 _mesa_make_current( struct gl_context *newCtx,
1474                     struct gl_framebuffer *drawBuffer,
1475                     struct gl_framebuffer *readBuffer )
1476 {
1477    GET_CURRENT_CONTEXT(curCtx);
1478 
1479    if (MESA_VERBOSE & VERBOSE_API)
1480       _mesa_debug(newCtx, "_mesa_make_current()\n");
1481 
1482    /* Check that the context's and framebuffer's visuals are compatible.
1483     */
1484    if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
1485       if (!check_compatible(newCtx, drawBuffer)) {
1486          _mesa_warning(newCtx,
1487               "MakeCurrent: incompatible visuals for context and drawbuffer");
1488          return GL_FALSE;
1489       }
1490    }
1491    if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
1492       if (!check_compatible(newCtx, readBuffer)) {
1493          _mesa_warning(newCtx,
1494               "MakeCurrent: incompatible visuals for context and readbuffer");
1495          return GL_FALSE;
1496       }
1497    }
1498 
1499    if (curCtx &&
1500        /* make sure this context is valid for flushing */
1501        curCtx != newCtx &&
1502        curCtx->Const.ContextReleaseBehavior ==
1503        GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH) {
1504       FLUSH_VERTICES(curCtx, 0, 0);
1505       if (curCtx->st){
1506          st_glFlush(curCtx, 0);
1507       }
1508    }
1509 
1510    if (!newCtx) {
1511       _glapi_set_dispatch(NULL);  /* none current */
1512       /* We need old ctx to correctly release Draw/ReadBuffer
1513        * and avoid a surface leak in st_renderbuffer_delete.
1514        * Therefore, first drop buffers then set new ctx to NULL.
1515        */
1516       if (curCtx) {
1517          _mesa_reference_framebuffer(&curCtx->WinSysDrawBuffer, NULL);
1518          _mesa_reference_framebuffer(&curCtx->WinSysReadBuffer, NULL);
1519       }
1520       _glapi_set_context(NULL);
1521       assert(_mesa_get_current_context() == NULL);
1522    }
1523    else {
1524       _glapi_set_context((void *) newCtx);
1525       assert(_mesa_get_current_context() == newCtx);
1526       _glapi_set_dispatch(newCtx->GLApi);
1527 
1528       if (drawBuffer && readBuffer) {
1529          assert(_mesa_is_winsys_fbo(drawBuffer));
1530          assert(_mesa_is_winsys_fbo(readBuffer));
1531          _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
1532          _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
1533 
1534          /*
1535           * Only set the context's Draw/ReadBuffer fields if they're NULL
1536           * or not bound to a user-created FBO.
1537           */
1538          if (!newCtx->DrawBuffer || _mesa_is_winsys_fbo(newCtx->DrawBuffer)) {
1539             _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
1540             /* Update the FBO's list of drawbuffers/renderbuffers.
1541              * For winsys FBOs this comes from the GL state (which may have
1542              * changed since the last time this FBO was bound).
1543              */
1544             _mesa_update_draw_buffers(newCtx);
1545             _mesa_update_allow_draw_out_of_order(newCtx);
1546             _mesa_update_valid_to_render_state(newCtx);
1547          }
1548          if (!newCtx->ReadBuffer || _mesa_is_winsys_fbo(newCtx->ReadBuffer)) {
1549             _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
1550             /* In _mesa_initialize_window_framebuffer, for single-buffered
1551              * visuals, the ColorReadBuffer is set to be GL_FRONT, even with
1552              * GLES contexts. When calling read_buffer, we verify we are reading
1553              * from GL_BACK in is_legal_es3_readbuffer_enum.  But the default is
1554              * incorrect, and certain dEQP tests check this.  So fix it here.
1555              */
1556             if (_mesa_is_gles(newCtx) &&
1557                !newCtx->ReadBuffer->Visual.doubleBufferMode)
1558                if (newCtx->ReadBuffer->ColorReadBuffer == GL_FRONT)
1559                   newCtx->ReadBuffer->ColorReadBuffer = GL_BACK;
1560          }
1561 
1562          /* XXX only set this flag if we're really changing the draw/read
1563           * framebuffer bindings.
1564           */
1565          newCtx->NewState |= _NEW_BUFFERS;
1566 
1567          check_init_viewport(newCtx, drawBuffer->Width, drawBuffer->Height);
1568       }
1569 
1570       if (newCtx->FirstTimeCurrent) {
1571          handle_first_current(newCtx);
1572          newCtx->FirstTimeCurrent = GL_FALSE;
1573       }
1574    }
1575 
1576    return GL_TRUE;
1577 }
1578 
1579 
1580 /**
1581  * Make context 'ctx' share the display lists, textures and programs
1582  * that are associated with 'ctxToShare'.
1583  * Any display lists, textures or programs associated with 'ctx' will
1584  * be deleted if nobody else is sharing them.
1585  */
1586 GLboolean
_mesa_share_state(struct gl_context * ctx,struct gl_context * ctxToShare)1587 _mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare)
1588 {
1589    if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
1590       struct gl_shared_state *oldShared = NULL;
1591 
1592       /* save ref to old state to prevent it from being deleted immediately */
1593       _mesa_reference_shared_state(ctx, &oldShared, ctx->Shared);
1594 
1595       /* update ctx's Shared pointer */
1596       _mesa_reference_shared_state(ctx, &ctx->Shared, ctxToShare->Shared);
1597 
1598       update_default_objects(ctx);
1599 
1600       /* release the old shared state */
1601       _mesa_reference_shared_state(ctx, &oldShared, NULL);
1602 
1603       return GL_TRUE;
1604    }
1605    else {
1606       return GL_FALSE;
1607    }
1608 }
1609 
1610 
1611 
1612 /**
1613  * \return pointer to the current GL context for this thread.
1614  *
1615  * Calls _glapi_get_context(). This isn't the fastest way to get the current
1616  * context.  If you need speed, see the #GET_CURRENT_CONTEXT macro in
1617  * context.h.
1618  */
1619 struct gl_context *
_mesa_get_current_context(void)1620 _mesa_get_current_context( void )
1621 {
1622    return (struct gl_context *) _glapi_get_context();
1623 }
1624 
1625 /*@}*/
1626 
1627 
1628 /**********************************************************************/
1629 /** \name Miscellaneous functions                                     */
1630 /**********************************************************************/
1631 /*@{*/
1632 /**
1633  * Flush commands.
1634  */
1635 void
_mesa_flush(struct gl_context * ctx)1636 _mesa_flush(struct gl_context *ctx)
1637 {
1638    bool async = !ctx->Shared->HasExternallySharedImages;
1639    FLUSH_VERTICES(ctx, 0, 0);
1640 
1641    st_glFlush(ctx, async ? PIPE_FLUSH_ASYNC : 0);
1642 }
1643 
1644 
1645 
1646 /**
1647  * Flush commands and wait for completion.
1648  *
1649  * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1650  * dd_function_table::Finish driver callback, if not NULL.
1651  */
1652 void GLAPIENTRY
_mesa_Finish(void)1653 _mesa_Finish(void)
1654 {
1655    GET_CURRENT_CONTEXT(ctx);
1656    ASSERT_OUTSIDE_BEGIN_END(ctx);
1657 
1658    FLUSH_VERTICES(ctx, 0, 0);
1659 
1660    st_glFinish(ctx);
1661 }
1662 
1663 
1664 /**
1665  * Execute glFlush().
1666  *
1667  * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1668  * dd_function_table::Flush driver callback, if not NULL.
1669  */
1670 void GLAPIENTRY
_mesa_Flush(void)1671 _mesa_Flush(void)
1672 {
1673    GET_CURRENT_CONTEXT(ctx);
1674    ASSERT_OUTSIDE_BEGIN_END(ctx);
1675    _mesa_flush(ctx);
1676 }
1677 
1678 
1679 /*@}*/
1680