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