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