mesa: add missing ASSERT_OUTSIDE_BEGIN_END() in _mesa_GetInternalformativ()
[mesa.git] / src / mesa / main / context.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 7.3
4 *
5 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
6 * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
22 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR 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 #include "mfeatures.h"
81 #include "imports.h"
82 #include "accum.h"
83 #include "api_exec.h"
84 #include "arrayobj.h"
85 #include "attrib.h"
86 #include "blend.h"
87 #include "buffers.h"
88 #include "bufferobj.h"
89 #include "context.h"
90 #include "cpuinfo.h"
91 #include "debug.h"
92 #include "depth.h"
93 #include "dlist.h"
94 #include "eval.h"
95 #include "extensions.h"
96 #include "fbobject.h"
97 #include "feedback.h"
98 #include "fog.h"
99 #include "formats.h"
100 #include "framebuffer.h"
101 #include "hint.h"
102 #include "hash.h"
103 #include "light.h"
104 #include "lines.h"
105 #include "macros.h"
106 #include "matrix.h"
107 #include "multisample.h"
108 #include "pixel.h"
109 #include "pixelstore.h"
110 #include "points.h"
111 #include "polygon.h"
112 #include "queryobj.h"
113 #include "syncobj.h"
114 #include "rastpos.h"
115 #include "remap.h"
116 #include "scissor.h"
117 #include "shared.h"
118 #include "shaderobj.h"
119 #include "simple_list.h"
120 #include "state.h"
121 #include "stencil.h"
122 #include "texcompress_s3tc.h"
123 #include "texstate.h"
124 #include "transformfeedback.h"
125 #include "mtypes.h"
126 #include "varray.h"
127 #include "version.h"
128 #include "viewport.h"
129 #include "vtxfmt.h"
130 #include "program/program.h"
131 #include "program/prog_print.h"
132 #include "math/m_matrix.h"
133 #include "main/dispatch.h" /* for _gloffset_COUNT */
134
135 #ifdef USE_SPARC_ASM
136 #include "sparc/sparc.h"
137 #endif
138
139 #include "glsl_parser_extras.h"
140 #include <stdbool.h>
141
142
143 #ifndef MESA_VERBOSE
144 int MESA_VERBOSE = 0;
145 #endif
146
147 #ifndef MESA_DEBUG_FLAGS
148 int MESA_DEBUG_FLAGS = 0;
149 #endif
150
151
152 /* ubyte -> float conversion */
153 GLfloat _mesa_ubyte_to_float_color_tab[256];
154
155
156
157 /**
158 * Swap buffers notification callback.
159 *
160 * \param ctx GL context.
161 *
162 * Called by window system just before swapping buffers.
163 * We have to finish any pending rendering.
164 */
165 void
166 _mesa_notifySwapBuffers(struct gl_context *ctx)
167 {
168 if (MESA_VERBOSE & VERBOSE_SWAPBUFFERS)
169 _mesa_debug(ctx, "SwapBuffers\n");
170 FLUSH_CURRENT( ctx, 0 );
171 if (ctx->Driver.Flush) {
172 ctx->Driver.Flush(ctx);
173 }
174 }
175
176
177 /**********************************************************************/
178 /** \name GL Visual allocation/destruction */
179 /**********************************************************************/
180 /*@{*/
181
182 /**
183 * Allocates a struct gl_config structure and initializes it via
184 * _mesa_initialize_visual().
185 *
186 * \param dbFlag double buffering
187 * \param stereoFlag stereo buffer
188 * \param depthBits requested bits per depth buffer value. Any value in [0, 32]
189 * is acceptable but the actual depth type will be GLushort or GLuint as
190 * needed.
191 * \param stencilBits requested minimum bits per stencil buffer value
192 * \param accumRedBits, accumGreenBits, accumBlueBits, accumAlphaBits number
193 * of bits per color component in accum buffer.
194 * \param indexBits number of bits per pixel if \p rgbFlag is GL_FALSE
195 * \param redBits number of bits per color component in frame buffer for RGB(A)
196 * mode. We always use 8 in core Mesa though.
197 * \param greenBits same as above.
198 * \param blueBits same as above.
199 * \param alphaBits same as above.
200 * \param numSamples not really used.
201 *
202 * \return pointer to new struct gl_config or NULL if requested parameters
203 * can't be met.
204 *
205 * \note Need to add params for level and numAuxBuffers (at least)
206 */
207 struct gl_config *
208 _mesa_create_visual( GLboolean dbFlag,
209 GLboolean stereoFlag,
210 GLint redBits,
211 GLint greenBits,
212 GLint blueBits,
213 GLint alphaBits,
214 GLint depthBits,
215 GLint stencilBits,
216 GLint accumRedBits,
217 GLint accumGreenBits,
218 GLint accumBlueBits,
219 GLint accumAlphaBits,
220 GLint numSamples )
221 {
222 struct gl_config *vis = CALLOC_STRUCT(gl_config);
223 if (vis) {
224 if (!_mesa_initialize_visual(vis, dbFlag, stereoFlag,
225 redBits, greenBits, blueBits, alphaBits,
226 depthBits, stencilBits,
227 accumRedBits, accumGreenBits,
228 accumBlueBits, accumAlphaBits,
229 numSamples)) {
230 free(vis);
231 return NULL;
232 }
233 }
234 return vis;
235 }
236
237
238 /**
239 * Makes some sanity checks and fills in the fields of the struct
240 * gl_config object with the given parameters. If the caller needs to
241 * set additional fields, he should just probably init the whole
242 * gl_config object himself.
243 *
244 * \return GL_TRUE on success, or GL_FALSE on failure.
245 *
246 * \sa _mesa_create_visual() above for the parameter description.
247 */
248 GLboolean
249 _mesa_initialize_visual( struct gl_config *vis,
250 GLboolean dbFlag,
251 GLboolean stereoFlag,
252 GLint redBits,
253 GLint greenBits,
254 GLint blueBits,
255 GLint alphaBits,
256 GLint depthBits,
257 GLint stencilBits,
258 GLint accumRedBits,
259 GLint accumGreenBits,
260 GLint accumBlueBits,
261 GLint accumAlphaBits,
262 GLint numSamples )
263 {
264 assert(vis);
265
266 if (depthBits < 0 || depthBits > 32) {
267 return GL_FALSE;
268 }
269 if (stencilBits < 0 || stencilBits > 8) {
270 return GL_FALSE;
271 }
272 assert(accumRedBits >= 0);
273 assert(accumGreenBits >= 0);
274 assert(accumBlueBits >= 0);
275 assert(accumAlphaBits >= 0);
276
277 vis->rgbMode = GL_TRUE;
278 vis->doubleBufferMode = dbFlag;
279 vis->stereoMode = stereoFlag;
280
281 vis->redBits = redBits;
282 vis->greenBits = greenBits;
283 vis->blueBits = blueBits;
284 vis->alphaBits = alphaBits;
285 vis->rgbBits = redBits + greenBits + blueBits;
286
287 vis->indexBits = 0;
288 vis->depthBits = depthBits;
289 vis->stencilBits = stencilBits;
290
291 vis->accumRedBits = accumRedBits;
292 vis->accumGreenBits = accumGreenBits;
293 vis->accumBlueBits = accumBlueBits;
294 vis->accumAlphaBits = accumAlphaBits;
295
296 vis->haveAccumBuffer = accumRedBits > 0;
297 vis->haveDepthBuffer = depthBits > 0;
298 vis->haveStencilBuffer = stencilBits > 0;
299
300 vis->numAuxBuffers = 0;
301 vis->level = 0;
302 vis->sampleBuffers = numSamples > 0 ? 1 : 0;
303 vis->samples = numSamples;
304
305 return GL_TRUE;
306 }
307
308
309 /**
310 * Destroy a visual and free its memory.
311 *
312 * \param vis visual.
313 *
314 * Frees the visual structure.
315 */
316 void
317 _mesa_destroy_visual( struct gl_config *vis )
318 {
319 free(vis);
320 }
321
322 /*@}*/
323
324
325 /**********************************************************************/
326 /** \name Context allocation, initialization, destroying
327 *
328 * The purpose of the most initialization functions here is to provide the
329 * default state values according to the OpenGL specification.
330 */
331 /**********************************************************************/
332 /*@{*/
333
334
335 /**
336 * This is lame. gdb only seems to recognize enum types that are
337 * actually used somewhere. We want to be able to print/use enum
338 * values such as TEXTURE_2D_INDEX in gdb. But we don't actually use
339 * the gl_texture_index type anywhere. Thus, this lame function.
340 */
341 static void
342 dummy_enum_func(void)
343 {
344 gl_buffer_index bi = BUFFER_FRONT_LEFT;
345 gl_face_index fi = FACE_POS_X;
346 gl_frag_attrib fa = FRAG_ATTRIB_WPOS;
347 gl_frag_result fr = FRAG_RESULT_DEPTH;
348 gl_texture_index ti = TEXTURE_2D_ARRAY_INDEX;
349 gl_vert_attrib va = VERT_ATTRIB_POS;
350 gl_vert_result vr = VERT_RESULT_HPOS;
351 gl_geom_attrib ga = GEOM_ATTRIB_POSITION;
352 gl_geom_result gr = GEOM_RESULT_POS;
353
354 (void) bi;
355 (void) fi;
356 (void) fa;
357 (void) fr;
358 (void) ti;
359 (void) va;
360 (void) vr;
361 (void) ga;
362 (void) gr;
363 }
364
365
366 /**
367 * One-time initialization mutex lock.
368 *
369 * \sa Used by one_time_init().
370 */
371 _glthread_DECLARE_STATIC_MUTEX(OneTimeLock);
372
373
374
375 /**
376 * Calls all the various one-time-init functions in Mesa.
377 *
378 * While holding a global mutex lock, calls several initialization functions,
379 * and sets the glapi callbacks if the \c MESA_DEBUG environment variable is
380 * defined.
381 *
382 * \sa _math_init().
383 */
384 static void
385 one_time_init( struct gl_context *ctx )
386 {
387 static GLbitfield api_init_mask = 0x0;
388
389 _glthread_LOCK_MUTEX(OneTimeLock);
390
391 /* truly one-time init */
392 if (!api_init_mask) {
393 GLuint i;
394
395 /* do some implementation tests */
396 assert( sizeof(GLbyte) == 1 );
397 assert( sizeof(GLubyte) == 1 );
398 assert( sizeof(GLshort) == 2 );
399 assert( sizeof(GLushort) == 2 );
400 assert( sizeof(GLint) == 4 );
401 assert( sizeof(GLuint) == 4 );
402
403 _mesa_get_cpu_features();
404
405 for (i = 0; i < 256; i++) {
406 _mesa_ubyte_to_float_color_tab[i] = (float) i / 255.0F;
407 }
408
409 #if defined(DEBUG) && defined(__DATE__) && defined(__TIME__)
410 if (MESA_VERBOSE != 0) {
411 _mesa_debug(ctx, "Mesa %s DEBUG build %s %s\n",
412 MESA_VERSION_STRING, __DATE__, __TIME__);
413 }
414 #endif
415
416 #ifdef DEBUG
417 _mesa_test_formats();
418 #endif
419 }
420
421 /* per-API one-time init */
422 if (!(api_init_mask & (1 << ctx->API))) {
423 _mesa_init_get_hash(ctx);
424
425 _mesa_init_remap_table();
426 }
427
428 api_init_mask |= 1 << ctx->API;
429
430 _glthread_UNLOCK_MUTEX(OneTimeLock);
431
432 /* Hopefully atexit() is widely available. If not, we may need some
433 * #ifdef tests here.
434 */
435 atexit(_mesa_destroy_shader_compiler);
436
437 dummy_enum_func();
438 }
439
440
441 /**
442 * Initialize fields of gl_current_attrib (aka ctx->Current.*)
443 */
444 static void
445 _mesa_init_current(struct gl_context *ctx)
446 {
447 GLuint i;
448
449 /* Init all to (0,0,0,1) */
450 for (i = 0; i < Elements(ctx->Current.Attrib); i++) {
451 ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 );
452 }
453
454 /* redo special cases: */
455 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_WEIGHT], 1.0, 0.0, 0.0, 0.0 );
456 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 );
457 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 );
458 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 );
459 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX], 1.0, 0.0, 0.0, 1.0 );
460 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG], 1.0, 0.0, 0.0, 1.0 );
461 }
462
463
464 /**
465 * Init vertex/fragment/geometry program limits.
466 * Important: drivers should override these with actual limits.
467 */
468 static void
469 init_program_limits(struct gl_context *ctx, GLenum type,
470 struct gl_program_constants *prog)
471 {
472 prog->MaxInstructions = MAX_PROGRAM_INSTRUCTIONS;
473 prog->MaxAluInstructions = MAX_PROGRAM_INSTRUCTIONS;
474 prog->MaxTexInstructions = MAX_PROGRAM_INSTRUCTIONS;
475 prog->MaxTexIndirections = MAX_PROGRAM_INSTRUCTIONS;
476 prog->MaxTemps = MAX_PROGRAM_TEMPS;
477 prog->MaxEnvParams = MAX_PROGRAM_ENV_PARAMS;
478 prog->MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS;
479 prog->MaxAddressOffset = MAX_PROGRAM_LOCAL_PARAMS;
480
481 switch (type) {
482 case GL_VERTEX_PROGRAM_ARB:
483 prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
484 prog->MaxAttribs = MAX_VERTEX_GENERIC_ATTRIBS;
485 prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
486 prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
487 break;
488 case GL_FRAGMENT_PROGRAM_ARB:
489 prog->MaxParameters = MAX_NV_FRAGMENT_PROGRAM_PARAMS;
490 prog->MaxAttribs = MAX_NV_FRAGMENT_PROGRAM_INPUTS;
491 prog->MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS;
492 prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
493 break;
494 case MESA_GEOMETRY_PROGRAM:
495 prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
496 prog->MaxAttribs = MAX_VERTEX_GENERIC_ATTRIBS;
497 prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
498 prog->MaxUniformComponents = MAX_GEOMETRY_UNIFORM_COMPONENTS;
499 break;
500 default:
501 assert(0 && "Bad program type in init_program_limits()");
502 }
503
504 /* Set the native limits to zero. This implies that there is no native
505 * support for shaders. Let the drivers fill in the actual values.
506 */
507 prog->MaxNativeInstructions = 0;
508 prog->MaxNativeAluInstructions = 0;
509 prog->MaxNativeTexInstructions = 0;
510 prog->MaxNativeTexIndirections = 0;
511 prog->MaxNativeAttribs = 0;
512 prog->MaxNativeTemps = 0;
513 prog->MaxNativeAddressRegs = 0;
514 prog->MaxNativeParameters = 0;
515
516 /* Set GLSL datatype range/precision info assuming IEEE float values.
517 * Drivers should override these defaults as needed.
518 */
519 prog->MediumFloat.RangeMin = 127;
520 prog->MediumFloat.RangeMax = 127;
521 prog->MediumFloat.Precision = 23;
522 prog->LowFloat = prog->HighFloat = prog->MediumFloat;
523
524 /* Assume ints are stored as floats for now, since this is the least-common
525 * denominator. The OpenGL ES spec implies (page 132) that the precision
526 * of integer types should be 0. Practically speaking, IEEE
527 * single-precision floating point values can only store integers in the
528 * range [-0x01000000, 0x01000000] without loss of precision.
529 */
530 prog->MediumInt.RangeMin = 24;
531 prog->MediumInt.RangeMax = 24;
532 prog->MediumInt.Precision = 0;
533 prog->LowInt = prog->HighInt = prog->MediumInt;
534
535 prog->MaxUniformBlocks = 12;
536 prog->MaxCombinedUniformComponents = (prog->MaxUniformComponents +
537 ctx->Const.MaxUniformBlockSize / 4 *
538 prog->MaxUniformBlocks);
539 }
540
541
542 /**
543 * Initialize fields of gl_constants (aka ctx->Const.*).
544 * Use defaults from config.h. The device drivers will often override
545 * some of these values (such as number of texture units).
546 */
547 static void
548 _mesa_init_constants(struct gl_context *ctx)
549 {
550 assert(ctx);
551
552 /* Constants, may be overriden (usually only reduced) by device drivers */
553 ctx->Const.MaxTextureMbytes = MAX_TEXTURE_MBYTES;
554 ctx->Const.MaxTextureLevels = MAX_TEXTURE_LEVELS;
555 ctx->Const.Max3DTextureLevels = MAX_3D_TEXTURE_LEVELS;
556 ctx->Const.MaxCubeTextureLevels = MAX_CUBE_TEXTURE_LEVELS;
557 ctx->Const.MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE;
558 ctx->Const.MaxArrayTextureLayers = MAX_ARRAY_TEXTURE_LAYERS;
559 ctx->Const.MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS;
560 ctx->Const.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
561 ctx->Const.MaxTextureUnits = MIN2(ctx->Const.MaxTextureCoordUnits,
562 ctx->Const.MaxTextureImageUnits);
563 ctx->Const.MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY;
564 ctx->Const.MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS;
565 ctx->Const.MaxTextureBufferSize = 65536;
566 ctx->Const.MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE;
567 ctx->Const.SubPixelBits = SUB_PIXEL_BITS;
568 ctx->Const.MinPointSize = MIN_POINT_SIZE;
569 ctx->Const.MaxPointSize = MAX_POINT_SIZE;
570 ctx->Const.MinPointSizeAA = MIN_POINT_SIZE;
571 ctx->Const.MaxPointSizeAA = MAX_POINT_SIZE;
572 ctx->Const.PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY;
573 ctx->Const.MinLineWidth = MIN_LINE_WIDTH;
574 ctx->Const.MaxLineWidth = MAX_LINE_WIDTH;
575 ctx->Const.MinLineWidthAA = MIN_LINE_WIDTH;
576 ctx->Const.MaxLineWidthAA = MAX_LINE_WIDTH;
577 ctx->Const.LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY;
578 ctx->Const.MaxColorTableSize = MAX_COLOR_TABLE_SIZE;
579 ctx->Const.MaxClipPlanes = 6;
580 ctx->Const.MaxLights = MAX_LIGHTS;
581 ctx->Const.MaxShininess = 128.0;
582 ctx->Const.MaxSpotExponent = 128.0;
583 ctx->Const.MaxViewportWidth = MAX_VIEWPORT_WIDTH;
584 ctx->Const.MaxViewportHeight = MAX_VIEWPORT_HEIGHT;
585
586 /** GL_ARB_uniform_buffer_object */
587 ctx->Const.MaxCombinedUniformBlocks = 36;
588 ctx->Const.MaxUniformBufferBindings = 36;
589 ctx->Const.MaxUniformBlockSize = 16384;
590 ctx->Const.UniformBufferOffsetAlignment = 1;
591
592 init_program_limits(ctx, GL_VERTEX_PROGRAM_ARB, &ctx->Const.VertexProgram);
593 init_program_limits(ctx, GL_FRAGMENT_PROGRAM_ARB, &ctx->Const.FragmentProgram);
594 init_program_limits(ctx, MESA_GEOMETRY_PROGRAM, &ctx->Const.GeometryProgram);
595
596 ctx->Const.MaxProgramMatrices = MAX_PROGRAM_MATRICES;
597 ctx->Const.MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH;
598
599 /* CheckArrayBounds is overriden by drivers/x11 for X server */
600 ctx->Const.CheckArrayBounds = GL_FALSE;
601
602 /* GL_ARB_draw_buffers */
603 ctx->Const.MaxDrawBuffers = MAX_DRAW_BUFFERS;
604
605 ctx->Const.MaxColorAttachments = MAX_COLOR_ATTACHMENTS;
606 ctx->Const.MaxRenderbufferSize = MAX_RENDERBUFFER_SIZE;
607
608 ctx->Const.MaxVertexTextureImageUnits = MAX_VERTEX_TEXTURE_IMAGE_UNITS;
609 ctx->Const.MaxCombinedTextureImageUnits = MAX_COMBINED_TEXTURE_IMAGE_UNITS;
610 ctx->Const.MaxVarying = 16; /* old limit not to break tnl and swrast */
611 ctx->Const.MaxGeometryTextureImageUnits = MAX_GEOMETRY_TEXTURE_IMAGE_UNITS;
612 ctx->Const.MaxVertexVaryingComponents = MAX_VERTEX_VARYING_COMPONENTS;
613 ctx->Const.MaxGeometryVaryingComponents = MAX_GEOMETRY_VARYING_COMPONENTS;
614 ctx->Const.MaxGeometryOutputVertices = MAX_GEOMETRY_OUTPUT_VERTICES;
615 ctx->Const.MaxGeometryTotalOutputComponents = MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS;
616
617 /* Shading language version */
618 if (_mesa_is_desktop_gl(ctx)) {
619 ctx->Const.GLSLVersion = 120;
620 _mesa_override_glsl_version(ctx);
621 }
622 else if (ctx->API == API_OPENGLES2) {
623 ctx->Const.GLSLVersion = 100;
624 }
625 else if (ctx->API == API_OPENGLES) {
626 ctx->Const.GLSLVersion = 0; /* GLSL not supported */
627 }
628
629 /* GL_ARB_framebuffer_object */
630 ctx->Const.MaxSamples = 0;
631
632 /* GL_ARB_sync */
633 ctx->Const.MaxServerWaitTimeout = (GLuint64) ~0;
634
635 /* GL_ATI_envmap_bumpmap */
636 ctx->Const.SupportedBumpUnits = SUPPORTED_ATI_BUMP_UNITS;
637
638 /* GL_EXT_provoking_vertex */
639 ctx->Const.QuadsFollowProvokingVertexConvention = GL_TRUE;
640
641 /* GL_EXT_transform_feedback */
642 ctx->Const.MaxTransformFeedbackBuffers = MAX_FEEDBACK_BUFFERS;
643 ctx->Const.MaxTransformFeedbackSeparateComponents = 4 * MAX_FEEDBACK_ATTRIBS;
644 ctx->Const.MaxTransformFeedbackInterleavedComponents = 4 * MAX_FEEDBACK_ATTRIBS;
645 ctx->Const.MaxVertexStreams = 1;
646
647 /* GL 3.2: hard-coded for now: */
648 ctx->Const.ProfileMask = GL_CONTEXT_COMPATIBILITY_PROFILE_BIT;
649
650 /** GL_EXT_gpu_shader4 */
651 ctx->Const.MinProgramTexelOffset = -8;
652 ctx->Const.MaxProgramTexelOffset = 7;
653
654 /* GL_ARB_robustness */
655 ctx->Const.ResetStrategy = GL_NO_RESET_NOTIFICATION_ARB;
656
657 /* PrimitiveRestart */
658 ctx->Const.PrimitiveRestartInSoftware = GL_FALSE;
659
660 /* ES 3.0 or ARB_ES3_compatibility */
661 ctx->Const.MaxElementIndex = 0xffffffffu;
662 }
663
664
665 /**
666 * Do some sanity checks on the limits/constants for the given context.
667 * Only called the first time a context is bound.
668 */
669 static void
670 check_context_limits(struct gl_context *ctx)
671 {
672 /* check that we don't exceed the size of various bitfields */
673 assert(VERT_RESULT_MAX <=
674 (8 * sizeof(ctx->VertexProgram._Current->Base.OutputsWritten)));
675 assert(FRAG_ATTRIB_MAX <=
676 (8 * sizeof(ctx->FragmentProgram._Current->Base.InputsRead)));
677
678 assert(MAX_COMBINED_TEXTURE_IMAGE_UNITS <= 8 * sizeof(GLbitfield));
679
680 /* shader-related checks */
681 assert(ctx->Const.FragmentProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
682 assert(ctx->Const.VertexProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
683
684 /* Texture unit checks */
685 assert(ctx->Const.MaxTextureImageUnits > 0);
686 assert(ctx->Const.MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
687 assert(ctx->Const.MaxTextureCoordUnits > 0);
688 assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
689 assert(ctx->Const.MaxTextureUnits > 0);
690 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
691 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
692 assert(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.MaxTextureImageUnits,
693 ctx->Const.MaxTextureCoordUnits));
694 assert(ctx->Const.MaxCombinedTextureImageUnits > 0);
695 assert(ctx->Const.MaxCombinedTextureImageUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
696 assert(ctx->Const.MaxTextureCoordUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
697 /* number of coord units cannot be greater than number of image units */
698 assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.MaxTextureImageUnits);
699
700
701 /* Texture size checks */
702 assert(ctx->Const.MaxTextureLevels <= MAX_TEXTURE_LEVELS);
703 assert(ctx->Const.Max3DTextureLevels <= MAX_3D_TEXTURE_LEVELS);
704 assert(ctx->Const.MaxCubeTextureLevels <= MAX_CUBE_TEXTURE_LEVELS);
705 assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
706
707 /* Texture level checks */
708 assert(MAX_TEXTURE_LEVELS >= MAX_3D_TEXTURE_LEVELS);
709 assert(MAX_TEXTURE_LEVELS >= MAX_CUBE_TEXTURE_LEVELS);
710
711 /* Max texture size should be <= max viewport size (render to texture) */
712 assert((1U << (ctx->Const.MaxTextureLevels - 1))
713 <= ctx->Const.MaxViewportWidth);
714 assert((1U << (ctx->Const.MaxTextureLevels - 1))
715 <= 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
735 init_attrib_groups(struct gl_context *ctx)
736 {
737 assert(ctx);
738
739 /* Constants */
740 _mesa_init_constants( ctx );
741
742 /* Extensions */
743 _mesa_init_extensions( ctx );
744
745 /* Attribute Groups */
746 _mesa_init_accum( ctx );
747 _mesa_init_attrib( ctx );
748 _mesa_init_buffer_objects( ctx );
749 _mesa_init_color( ctx );
750 _mesa_init_current( ctx );
751 _mesa_init_depth( ctx );
752 _mesa_init_debug( ctx );
753 _mesa_init_display_list( ctx );
754 _mesa_init_errors( ctx );
755 _mesa_init_eval( ctx );
756 _mesa_init_fbobjects( ctx );
757 _mesa_init_feedback( ctx );
758 _mesa_init_fog( ctx );
759 _mesa_init_hint( ctx );
760 _mesa_init_line( ctx );
761 _mesa_init_lighting( ctx );
762 _mesa_init_matrix( ctx );
763 _mesa_init_multisample( ctx );
764 _mesa_init_pixel( ctx );
765 _mesa_init_pixelstore( ctx );
766 _mesa_init_point( ctx );
767 _mesa_init_polygon( ctx );
768 _mesa_init_program( ctx );
769 _mesa_init_queryobj( ctx );
770 _mesa_init_sync( ctx );
771 _mesa_init_rastpos( ctx );
772 _mesa_init_scissor( ctx );
773 _mesa_init_shader_state( ctx );
774 _mesa_init_stencil( ctx );
775 _mesa_init_transform( ctx );
776 _mesa_init_transform_feedback( ctx );
777 _mesa_init_varray( ctx );
778 _mesa_init_viewport( ctx );
779
780 if (!_mesa_init_texture( ctx ))
781 return GL_FALSE;
782
783 _mesa_init_texture_s3tc( ctx );
784
785 /* Miscellaneous */
786 ctx->NewState = _NEW_ALL;
787 ctx->NewDriverState = ~0;
788 ctx->ErrorValue = GL_NO_ERROR;
789 ctx->ResetStatus = GL_NO_ERROR;
790 ctx->varying_vp_inputs = VERT_BIT_ALL;
791
792 return GL_TRUE;
793 }
794
795
796 /**
797 * Update default objects in a GL context with respect to shared state.
798 *
799 * \param ctx GL context.
800 *
801 * Removes references to old default objects, (texture objects, program
802 * objects, etc.) and changes to reference those from the current shared
803 * state.
804 */
805 static GLboolean
806 update_default_objects(struct gl_context *ctx)
807 {
808 assert(ctx);
809
810 _mesa_update_default_objects_program(ctx);
811 _mesa_update_default_objects_texture(ctx);
812 _mesa_update_default_objects_buffer_objects(ctx);
813
814 return GL_TRUE;
815 }
816
817
818 /**
819 * This is the default function we plug into all dispatch table slots
820 * This helps prevents a segfault when someone calls a GL function without
821 * first checking if the extension's supported.
822 */
823 int
824 _mesa_generic_nop(void)
825 {
826 GET_CURRENT_CONTEXT(ctx);
827 _mesa_error(ctx, GL_INVALID_OPERATION,
828 "unsupported function called "
829 "(unsupported extension or deprecated function?)");
830 return 0;
831 }
832
833
834 /**
835 * Allocate and initialize a new dispatch table.
836 */
837 struct _glapi_table *
838 _mesa_alloc_dispatch_table(int size)
839 {
840 /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
841 * In practice, this'll be the same for stand-alone Mesa. But for DRI
842 * Mesa we do this to accomodate different versions of libGL and various
843 * DRI drivers.
844 */
845 GLint numEntries = MAX2(_glapi_get_dispatch_table_size(), _gloffset_COUNT);
846 struct _glapi_table *table;
847
848 /* should never happen, but just in case */
849 numEntries = MAX2(numEntries, size);
850
851 table = malloc(numEntries * sizeof(_glapi_proc));
852 if (table) {
853 _glapi_proc *entry = (_glapi_proc *) table;
854 GLint i;
855 for (i = 0; i < numEntries; i++) {
856 entry[i] = (_glapi_proc) _mesa_generic_nop;
857 }
858 }
859 return table;
860 }
861
862
863 /**
864 * Initialize a struct gl_context struct (rendering context).
865 *
866 * This includes allocating all the other structs and arrays which hang off of
867 * the context by pointers.
868 * Note that the driver needs to pass in its dd_function_table here since
869 * we need to at least call driverFunctions->NewTextureObject to create the
870 * default texture objects.
871 *
872 * Called by _mesa_create_context().
873 *
874 * Performs the imports and exports callback tables initialization, and
875 * miscellaneous one-time initializations. If no shared context is supplied one
876 * is allocated, and increase its reference count. Setups the GL API dispatch
877 * tables. Initialize the TNL module. Sets the maximum Z buffer depth.
878 * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
879 * for debug flags.
880 *
881 * \param ctx the context to initialize
882 * \param api the GL API type to create the context for
883 * \param visual describes the visual attributes for this context
884 * \param share_list points to context to share textures, display lists,
885 * etc with, or NULL
886 * \param driverFunctions table of device driver functions for this context
887 * to use
888 */
889 GLboolean
890 _mesa_initialize_context(struct gl_context *ctx,
891 gl_api api,
892 const struct gl_config *visual,
893 struct gl_context *share_list,
894 const struct dd_function_table *driverFunctions)
895 {
896 struct gl_shared_state *shared;
897 int i;
898
899 assert(driverFunctions->NewTextureObject);
900 assert(driverFunctions->FreeTextureImageBuffer);
901
902 ctx->API = api;
903 ctx->Visual = *visual;
904 ctx->DrawBuffer = NULL;
905 ctx->ReadBuffer = NULL;
906 ctx->WinSysDrawBuffer = NULL;
907 ctx->WinSysReadBuffer = NULL;
908
909 if (_mesa_is_desktop_gl(ctx)) {
910 _mesa_override_gl_version(ctx);
911 }
912
913 /* misc one-time initializations */
914 one_time_init(ctx);
915
916 /* Plug in driver functions and context pointer here.
917 * This is important because when we call alloc_shared_state() below
918 * we'll call ctx->Driver.NewTextureObject() to create the default
919 * textures.
920 */
921 ctx->Driver = *driverFunctions;
922
923 if (share_list) {
924 /* share state with another context */
925 shared = share_list->Shared;
926 }
927 else {
928 /* allocate new, unshared state */
929 shared = _mesa_alloc_shared_state(ctx);
930 if (!shared)
931 return GL_FALSE;
932 }
933
934 _mesa_reference_shared_state(ctx, &ctx->Shared, shared);
935
936 if (!init_attrib_groups( ctx )) {
937 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
938 return GL_FALSE;
939 }
940
941 /* setup the API dispatch tables with all nop functions */
942 ctx->Exec = _mesa_alloc_dispatch_table(_gloffset_COUNT);
943
944 if (!ctx->Exec) {
945 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
946 return GL_FALSE;
947 }
948 ctx->CurrentDispatch = ctx->Exec;
949
950 ctx->FragmentProgram._MaintainTexEnvProgram
951 = (_mesa_getenv("MESA_TEX_PROG") != NULL);
952
953 ctx->VertexProgram._MaintainTnlProgram
954 = (_mesa_getenv("MESA_TNL_PROG") != NULL);
955 if (ctx->VertexProgram._MaintainTnlProgram) {
956 /* this is required... */
957 ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
958 }
959
960 /* Mesa core handles all the formats that mesa core knows about.
961 * Drivers will want to override this list with just the formats
962 * they can handle, and confirm that appropriate fallbacks exist in
963 * _mesa_choose_tex_format().
964 */
965 memset(&ctx->TextureFormatSupported, GL_TRUE,
966 sizeof(ctx->TextureFormatSupported));
967
968 switch (ctx->API) {
969 case API_OPENGL_COMPAT:
970 ctx->Save = _mesa_create_save_table(ctx);
971 if (!ctx->Save) {
972 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
973 free(ctx->Exec);
974 return GL_FALSE;
975 }
976
977 /* fall-through */
978 case API_OPENGL_CORE:
979 break;
980 case API_OPENGLES:
981 /**
982 * GL_OES_texture_cube_map says
983 * "Initially all texture generation modes are set to REFLECTION_MAP_OES"
984 */
985 for (i = 0; i < MAX_TEXTURE_UNITS; i++) {
986 struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
987 texUnit->GenS.Mode = GL_REFLECTION_MAP_NV;
988 texUnit->GenT.Mode = GL_REFLECTION_MAP_NV;
989 texUnit->GenR.Mode = GL_REFLECTION_MAP_NV;
990 texUnit->GenS._ModeBit = TEXGEN_REFLECTION_MAP_NV;
991 texUnit->GenT._ModeBit = TEXGEN_REFLECTION_MAP_NV;
992 texUnit->GenR._ModeBit = TEXGEN_REFLECTION_MAP_NV;
993 }
994 break;
995 case API_OPENGLES2:
996 ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
997 ctx->VertexProgram._MaintainTnlProgram = GL_TRUE;
998 ctx->Point.PointSprite = GL_TRUE; /* always on for ES 2.x */
999 break;
1000 }
1001
1002 ctx->FirstTimeCurrent = GL_TRUE;
1003
1004 return GL_TRUE;
1005 }
1006
1007
1008 /**
1009 * Allocate and initialize a struct gl_context structure.
1010 * Note that the driver needs to pass in its dd_function_table here since
1011 * we need to at least call driverFunctions->NewTextureObject to initialize
1012 * the rendering context.
1013 *
1014 * \param api the GL API type to create the context for
1015 * \param visual a struct gl_config pointer (we copy the struct contents)
1016 * \param share_list another context to share display lists with or NULL
1017 * \param driverFunctions points to the dd_function_table into which the
1018 * driver has plugged in all its special functions.
1019 *
1020 * \return pointer to a new __struct gl_contextRec or NULL if error.
1021 */
1022 struct gl_context *
1023 _mesa_create_context(gl_api api,
1024 const struct gl_config *visual,
1025 struct gl_context *share_list,
1026 const struct dd_function_table *driverFunctions)
1027 {
1028 struct gl_context *ctx;
1029
1030 ASSERT(visual);
1031
1032 ctx = calloc(1, sizeof(struct gl_context));
1033 if (!ctx)
1034 return NULL;
1035
1036 if (_mesa_initialize_context(ctx, api, visual, share_list,
1037 driverFunctions)) {
1038 return ctx;
1039 }
1040 else {
1041 free(ctx);
1042 return NULL;
1043 }
1044 }
1045
1046
1047 /**
1048 * Free the data associated with the given context.
1049 *
1050 * But doesn't free the struct gl_context struct itself.
1051 *
1052 * \sa _mesa_initialize_context() and init_attrib_groups().
1053 */
1054 void
1055 _mesa_free_context_data( struct gl_context *ctx )
1056 {
1057 if (!_mesa_get_current_context()){
1058 /* No current context, but we may need one in order to delete
1059 * texture objs, etc. So temporarily bind the context now.
1060 */
1061 _mesa_make_current(ctx, NULL, NULL);
1062 }
1063
1064 /* unreference WinSysDraw/Read buffers */
1065 _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
1066 _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
1067 _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
1068 _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
1069
1070 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
1071 _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
1072 _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram, NULL);
1073
1074 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
1075 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
1076 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
1077
1078 _mesa_reference_array_object(ctx, &ctx->Array.ArrayObj, NULL);
1079 _mesa_reference_array_object(ctx, &ctx->Array.DefaultArrayObj, NULL);
1080
1081 _mesa_free_attrib_data(ctx);
1082 _mesa_free_buffer_objects(ctx);
1083 _mesa_free_lighting_data( ctx );
1084 _mesa_free_eval_data( ctx );
1085 _mesa_free_texture_data( ctx );
1086 _mesa_free_matrix_data( ctx );
1087 _mesa_free_viewport_data( ctx );
1088 _mesa_free_program_data(ctx);
1089 _mesa_free_shader_state(ctx);
1090 _mesa_free_queryobj_data(ctx);
1091 _mesa_free_sync_data(ctx);
1092 _mesa_free_varray_data(ctx);
1093 _mesa_free_transform_feedback(ctx);
1094
1095 _mesa_reference_buffer_object(ctx, &ctx->Pack.BufferObj, NULL);
1096 _mesa_reference_buffer_object(ctx, &ctx->Unpack.BufferObj, NULL);
1097 _mesa_reference_buffer_object(ctx, &ctx->DefaultPacking.BufferObj, NULL);
1098 _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
1099
1100 /* free dispatch tables */
1101 free(ctx->Exec);
1102 free(ctx->Save);
1103
1104 /* Shared context state (display lists, textures, etc) */
1105 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
1106
1107 /* needs to be after freeing shared state */
1108 _mesa_free_display_list_data(ctx);
1109
1110 _mesa_free_errors_data(ctx);
1111
1112 free((void *)ctx->Extensions.String);
1113
1114 free(ctx->VersionString);
1115
1116 /* unbind the context if it's currently bound */
1117 if (ctx == _mesa_get_current_context()) {
1118 _mesa_make_current(NULL, NULL, NULL);
1119 }
1120 }
1121
1122
1123 /**
1124 * Destroy a struct gl_context structure.
1125 *
1126 * \param ctx GL context.
1127 *
1128 * Calls _mesa_free_context_data() and frees the gl_context object itself.
1129 */
1130 void
1131 _mesa_destroy_context( struct gl_context *ctx )
1132 {
1133 if (ctx) {
1134 _mesa_free_context_data(ctx);
1135 free( (void *) ctx );
1136 }
1137 }
1138
1139
1140 /**
1141 * Copy attribute groups from one context to another.
1142 *
1143 * \param src source context
1144 * \param dst destination context
1145 * \param mask bitwise OR of GL_*_BIT flags
1146 *
1147 * According to the bits specified in \p mask, copies the corresponding
1148 * attributes from \p src into \p dst. For many of the attributes a simple \c
1149 * memcpy is not enough due to the existence of internal pointers in their data
1150 * structures.
1151 */
1152 void
1153 _mesa_copy_context( const struct gl_context *src, struct gl_context *dst,
1154 GLuint mask )
1155 {
1156 if (mask & GL_ACCUM_BUFFER_BIT) {
1157 /* OK to memcpy */
1158 dst->Accum = src->Accum;
1159 }
1160 if (mask & GL_COLOR_BUFFER_BIT) {
1161 /* OK to memcpy */
1162 dst->Color = src->Color;
1163 }
1164 if (mask & GL_CURRENT_BIT) {
1165 /* OK to memcpy */
1166 dst->Current = src->Current;
1167 }
1168 if (mask & GL_DEPTH_BUFFER_BIT) {
1169 /* OK to memcpy */
1170 dst->Depth = src->Depth;
1171 }
1172 if (mask & GL_ENABLE_BIT) {
1173 /* no op */
1174 }
1175 if (mask & GL_EVAL_BIT) {
1176 /* OK to memcpy */
1177 dst->Eval = src->Eval;
1178 }
1179 if (mask & GL_FOG_BIT) {
1180 /* OK to memcpy */
1181 dst->Fog = src->Fog;
1182 }
1183 if (mask & GL_HINT_BIT) {
1184 /* OK to memcpy */
1185 dst->Hint = src->Hint;
1186 }
1187 if (mask & GL_LIGHTING_BIT) {
1188 GLuint i;
1189 /* begin with memcpy */
1190 dst->Light = src->Light;
1191 /* fixup linked lists to prevent pointer insanity */
1192 make_empty_list( &(dst->Light.EnabledList) );
1193 for (i = 0; i < MAX_LIGHTS; i++) {
1194 if (dst->Light.Light[i].Enabled) {
1195 insert_at_tail(&(dst->Light.EnabledList), &(dst->Light.Light[i]));
1196 }
1197 }
1198 }
1199 if (mask & GL_LINE_BIT) {
1200 /* OK to memcpy */
1201 dst->Line = src->Line;
1202 }
1203 if (mask & GL_LIST_BIT) {
1204 /* OK to memcpy */
1205 dst->List = src->List;
1206 }
1207 if (mask & GL_PIXEL_MODE_BIT) {
1208 /* OK to memcpy */
1209 dst->Pixel = src->Pixel;
1210 }
1211 if (mask & GL_POINT_BIT) {
1212 /* OK to memcpy */
1213 dst->Point = src->Point;
1214 }
1215 if (mask & GL_POLYGON_BIT) {
1216 /* OK to memcpy */
1217 dst->Polygon = src->Polygon;
1218 }
1219 if (mask & GL_POLYGON_STIPPLE_BIT) {
1220 /* Use loop instead of memcpy due to problem with Portland Group's
1221 * C compiler. Reported by John Stone.
1222 */
1223 GLuint i;
1224 for (i = 0; i < 32; i++) {
1225 dst->PolygonStipple[i] = src->PolygonStipple[i];
1226 }
1227 }
1228 if (mask & GL_SCISSOR_BIT) {
1229 /* OK to memcpy */
1230 dst->Scissor = src->Scissor;
1231 }
1232 if (mask & GL_STENCIL_BUFFER_BIT) {
1233 /* OK to memcpy */
1234 dst->Stencil = src->Stencil;
1235 }
1236 if (mask & GL_TEXTURE_BIT) {
1237 /* Cannot memcpy because of pointers */
1238 _mesa_copy_texture_state(src, dst);
1239 }
1240 if (mask & GL_TRANSFORM_BIT) {
1241 /* OK to memcpy */
1242 dst->Transform = src->Transform;
1243 }
1244 if (mask & GL_VIEWPORT_BIT) {
1245 /* Cannot use memcpy, because of pointers in GLmatrix _WindowMap */
1246 dst->Viewport.X = src->Viewport.X;
1247 dst->Viewport.Y = src->Viewport.Y;
1248 dst->Viewport.Width = src->Viewport.Width;
1249 dst->Viewport.Height = src->Viewport.Height;
1250 dst->Viewport.Near = src->Viewport.Near;
1251 dst->Viewport.Far = src->Viewport.Far;
1252 _math_matrix_copy(&dst->Viewport._WindowMap, &src->Viewport._WindowMap);
1253 }
1254
1255 /* XXX FIXME: Call callbacks?
1256 */
1257 dst->NewState = _NEW_ALL;
1258 dst->NewDriverState = ~0;
1259 }
1260
1261
1262 /**
1263 * Check if the given context can render into the given framebuffer
1264 * by checking visual attributes.
1265 *
1266 * Most of these tests could go away because Mesa is now pretty flexible
1267 * in terms of mixing rendering contexts with framebuffers. As long
1268 * as RGB vs. CI mode agree, we're probably good.
1269 *
1270 * \return GL_TRUE if compatible, GL_FALSE otherwise.
1271 */
1272 static GLboolean
1273 check_compatible(const struct gl_context *ctx,
1274 const struct gl_framebuffer *buffer)
1275 {
1276 const struct gl_config *ctxvis = &ctx->Visual;
1277 const struct gl_config *bufvis = &buffer->Visual;
1278
1279 if (buffer == _mesa_get_incomplete_framebuffer())
1280 return GL_TRUE;
1281
1282 #if 0
1283 /* disabling this fixes the fgl_glxgears pbuffer demo */
1284 if (ctxvis->doubleBufferMode && !bufvis->doubleBufferMode)
1285 return GL_FALSE;
1286 #endif
1287 if (ctxvis->stereoMode && !bufvis->stereoMode)
1288 return GL_FALSE;
1289 if (ctxvis->haveAccumBuffer && !bufvis->haveAccumBuffer)
1290 return GL_FALSE;
1291 if (ctxvis->haveDepthBuffer && !bufvis->haveDepthBuffer)
1292 return GL_FALSE;
1293 if (ctxvis->haveStencilBuffer && !bufvis->haveStencilBuffer)
1294 return GL_FALSE;
1295 if (ctxvis->redMask && ctxvis->redMask != bufvis->redMask)
1296 return GL_FALSE;
1297 if (ctxvis->greenMask && ctxvis->greenMask != bufvis->greenMask)
1298 return GL_FALSE;
1299 if (ctxvis->blueMask && ctxvis->blueMask != bufvis->blueMask)
1300 return GL_FALSE;
1301 #if 0
1302 /* disabled (see bug 11161) */
1303 if (ctxvis->depthBits && ctxvis->depthBits != bufvis->depthBits)
1304 return GL_FALSE;
1305 #endif
1306 if (ctxvis->stencilBits && ctxvis->stencilBits != bufvis->stencilBits)
1307 return GL_FALSE;
1308
1309 return GL_TRUE;
1310 }
1311
1312
1313 /**
1314 * Do one-time initialization for the given framebuffer. Specifically,
1315 * ask the driver for the window's current size and update the framebuffer
1316 * object to match.
1317 * Really, the device driver should totally take care of this.
1318 */
1319 static void
1320 initialize_framebuffer_size(struct gl_context *ctx, struct gl_framebuffer *fb)
1321 {
1322 GLuint width, height;
1323 if (ctx->Driver.GetBufferSize) {
1324 ctx->Driver.GetBufferSize(fb, &width, &height);
1325 if (ctx->Driver.ResizeBuffers)
1326 ctx->Driver.ResizeBuffers(ctx, fb, width, height);
1327 fb->Initialized = GL_TRUE;
1328 }
1329 }
1330
1331
1332 /**
1333 * Check if the viewport/scissor size has not yet been initialized.
1334 * Initialize the size if the given width and height are non-zero.
1335 */
1336 void
1337 _mesa_check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height)
1338 {
1339 if (!ctx->ViewportInitialized && width > 0 && height > 0) {
1340 /* Note: set flag here, before calling _mesa_set_viewport(), to prevent
1341 * potential infinite recursion.
1342 */
1343 ctx->ViewportInitialized = GL_TRUE;
1344 _mesa_set_viewport(ctx, 0, 0, width, height);
1345 _mesa_set_scissor(ctx, 0, 0, width, height);
1346 }
1347 }
1348
1349
1350 /**
1351 * Bind the given context to the given drawBuffer and readBuffer and
1352 * make it the current context for the calling thread.
1353 * We'll render into the drawBuffer and read pixels from the
1354 * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
1355 *
1356 * We check that the context's and framebuffer's visuals are compatible
1357 * and return immediately if they're not.
1358 *
1359 * \param newCtx the new GL context. If NULL then there will be no current GL
1360 * context.
1361 * \param drawBuffer the drawing framebuffer
1362 * \param readBuffer the reading framebuffer
1363 */
1364 GLboolean
1365 _mesa_make_current( struct gl_context *newCtx,
1366 struct gl_framebuffer *drawBuffer,
1367 struct gl_framebuffer *readBuffer )
1368 {
1369 GET_CURRENT_CONTEXT(curCtx);
1370
1371 if (MESA_VERBOSE & VERBOSE_API)
1372 _mesa_debug(newCtx, "_mesa_make_current()\n");
1373
1374 /* Check that the context's and framebuffer's visuals are compatible.
1375 */
1376 if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
1377 if (!check_compatible(newCtx, drawBuffer)) {
1378 _mesa_warning(newCtx,
1379 "MakeCurrent: incompatible visuals for context and drawbuffer");
1380 return GL_FALSE;
1381 }
1382 }
1383 if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
1384 if (!check_compatible(newCtx, readBuffer)) {
1385 _mesa_warning(newCtx,
1386 "MakeCurrent: incompatible visuals for context and readbuffer");
1387 return GL_FALSE;
1388 }
1389 }
1390
1391 if (curCtx &&
1392 (curCtx->WinSysDrawBuffer || curCtx->WinSysReadBuffer) &&
1393 /* make sure this context is valid for flushing */
1394 curCtx != newCtx)
1395 _mesa_flush(curCtx);
1396
1397 /* We used to call _glapi_check_multithread() here. Now do it in drivers */
1398 _glapi_set_context((void *) newCtx);
1399 ASSERT(_mesa_get_current_context() == newCtx);
1400
1401 if (!newCtx) {
1402 _glapi_set_dispatch(NULL); /* none current */
1403 }
1404 else {
1405 _glapi_set_dispatch(newCtx->CurrentDispatch);
1406
1407 if (drawBuffer && readBuffer) {
1408 ASSERT(_mesa_is_winsys_fbo(drawBuffer));
1409 ASSERT(_mesa_is_winsys_fbo(readBuffer));
1410 _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
1411 _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
1412
1413 /*
1414 * Only set the context's Draw/ReadBuffer fields if they're NULL
1415 * or not bound to a user-created FBO.
1416 */
1417 if (!newCtx->DrawBuffer || _mesa_is_winsys_fbo(newCtx->DrawBuffer)) {
1418 _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
1419 /* Update the FBO's list of drawbuffers/renderbuffers.
1420 * For winsys FBOs this comes from the GL state (which may have
1421 * changed since the last time this FBO was bound).
1422 */
1423 _mesa_update_draw_buffers(newCtx);
1424 }
1425 if (!newCtx->ReadBuffer || _mesa_is_winsys_fbo(newCtx->ReadBuffer)) {
1426 _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
1427 }
1428
1429 /* XXX only set this flag if we're really changing the draw/read
1430 * framebuffer bindings.
1431 */
1432 newCtx->NewState |= _NEW_BUFFERS;
1433
1434 #if 1
1435 /* We want to get rid of these lines: */
1436 if (!drawBuffer->Initialized) {
1437 initialize_framebuffer_size(newCtx, drawBuffer);
1438 }
1439 if (readBuffer != drawBuffer && !readBuffer->Initialized) {
1440 initialize_framebuffer_size(newCtx, readBuffer);
1441 }
1442
1443 _mesa_resizebuffers(newCtx);
1444 #else
1445 /* We want the drawBuffer and readBuffer to be initialized by
1446 * the driver.
1447 * This generally means the Width and Height match the actual
1448 * window size and the renderbuffers (both hardware and software
1449 * based) are allocated to match. The later can generally be
1450 * done with a call to _mesa_resize_framebuffer().
1451 *
1452 * It's theoretically possible for a buffer to have zero width
1453 * or height, but for now, assert check that the driver did what's
1454 * expected of it.
1455 */
1456 ASSERT(drawBuffer->Width > 0);
1457 ASSERT(drawBuffer->Height > 0);
1458 #endif
1459
1460 if (drawBuffer) {
1461 _mesa_check_init_viewport(newCtx,
1462 drawBuffer->Width, drawBuffer->Height);
1463 }
1464 }
1465
1466 if (newCtx->FirstTimeCurrent) {
1467 assert(newCtx->Version > 0);
1468
1469 newCtx->Extensions.String = _mesa_make_extension_string(newCtx);
1470
1471 check_context_limits(newCtx);
1472
1473 /* We can use this to help debug user's problems. Tell them to set
1474 * the MESA_INFO env variable before running their app. Then the
1475 * first time each context is made current we'll print some useful
1476 * information.
1477 */
1478 if (_mesa_getenv("MESA_INFO")) {
1479 _mesa_print_info();
1480 }
1481
1482 newCtx->FirstTimeCurrent = GL_FALSE;
1483 }
1484 }
1485
1486 return GL_TRUE;
1487 }
1488
1489
1490 /**
1491 * Make context 'ctx' share the display lists, textures and programs
1492 * that are associated with 'ctxToShare'.
1493 * Any display lists, textures or programs associated with 'ctx' will
1494 * be deleted if nobody else is sharing them.
1495 */
1496 GLboolean
1497 _mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare)
1498 {
1499 if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
1500 struct gl_shared_state *oldShared = NULL;
1501
1502 /* save ref to old state to prevent it from being deleted immediately */
1503 _mesa_reference_shared_state(ctx, &oldShared, ctx->Shared);
1504
1505 /* update ctx's Shared pointer */
1506 _mesa_reference_shared_state(ctx, &ctx->Shared, ctxToShare->Shared);
1507
1508 update_default_objects(ctx);
1509
1510 /* release the old shared state */
1511 _mesa_reference_shared_state(ctx, &oldShared, NULL);
1512
1513 return GL_TRUE;
1514 }
1515 else {
1516 return GL_FALSE;
1517 }
1518 }
1519
1520
1521
1522 /**
1523 * \return pointer to the current GL context for this thread.
1524 *
1525 * Calls _glapi_get_context(). This isn't the fastest way to get the current
1526 * context. If you need speed, see the #GET_CURRENT_CONTEXT macro in
1527 * context.h.
1528 */
1529 struct gl_context *
1530 _mesa_get_current_context( void )
1531 {
1532 return (struct gl_context *) _glapi_get_context();
1533 }
1534
1535
1536 /**
1537 * Get context's current API dispatch table.
1538 *
1539 * It'll either be the immediate-mode execute dispatcher or the display list
1540 * compile dispatcher.
1541 *
1542 * \param ctx GL context.
1543 *
1544 * \return pointer to dispatch_table.
1545 *
1546 * Simply returns __struct gl_contextRec::CurrentDispatch.
1547 */
1548 struct _glapi_table *
1549 _mesa_get_dispatch(struct gl_context *ctx)
1550 {
1551 return ctx->CurrentDispatch;
1552 }
1553
1554 /*@}*/
1555
1556
1557 /**********************************************************************/
1558 /** \name Miscellaneous functions */
1559 /**********************************************************************/
1560 /*@{*/
1561
1562 /**
1563 * Record an error.
1564 *
1565 * \param ctx GL context.
1566 * \param error error code.
1567 *
1568 * Records the given error code and call the driver's dd_function_table::Error
1569 * function if defined.
1570 *
1571 * \sa
1572 * This is called via _mesa_error().
1573 */
1574 void
1575 _mesa_record_error(struct gl_context *ctx, GLenum error)
1576 {
1577 if (!ctx)
1578 return;
1579
1580 if (ctx->ErrorValue == GL_NO_ERROR) {
1581 ctx->ErrorValue = error;
1582 }
1583
1584 /* Call device driver's error handler, if any. This is used on the Mac. */
1585 if (ctx->Driver.Error) {
1586 ctx->Driver.Error(ctx);
1587 }
1588 }
1589
1590
1591 /**
1592 * Flush commands and wait for completion.
1593 */
1594 void
1595 _mesa_finish(struct gl_context *ctx)
1596 {
1597 FLUSH_VERTICES( ctx, 0 );
1598 FLUSH_CURRENT( ctx, 0 );
1599 if (ctx->Driver.Finish) {
1600 ctx->Driver.Finish(ctx);
1601 }
1602 }
1603
1604
1605 /**
1606 * Flush commands.
1607 */
1608 void
1609 _mesa_flush(struct gl_context *ctx)
1610 {
1611 FLUSH_VERTICES( ctx, 0 );
1612 FLUSH_CURRENT( ctx, 0 );
1613 if (ctx->Driver.Flush) {
1614 ctx->Driver.Flush(ctx);
1615 }
1616 }
1617
1618
1619
1620 /**
1621 * Execute glFinish().
1622 *
1623 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1624 * dd_function_table::Finish driver callback, if not NULL.
1625 */
1626 void GLAPIENTRY
1627 _mesa_Finish(void)
1628 {
1629 GET_CURRENT_CONTEXT(ctx);
1630 ASSERT_OUTSIDE_BEGIN_END(ctx);
1631 _mesa_finish(ctx);
1632 }
1633
1634
1635 /**
1636 * Execute glFlush().
1637 *
1638 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1639 * dd_function_table::Flush driver callback, if not NULL.
1640 */
1641 void GLAPIENTRY
1642 _mesa_Flush(void)
1643 {
1644 GET_CURRENT_CONTEXT(ctx);
1645 ASSERT_OUTSIDE_BEGIN_END(ctx);
1646 _mesa_flush(ctx);
1647 }
1648
1649
1650 /**
1651 * Set mvp_with_dp4 flag. If a driver has a preference for DP4 over
1652 * MUL/MAD, or vice versa, call this function to register that.
1653 * Otherwise we default to MUL/MAD.
1654 */
1655 void
1656 _mesa_set_mvp_with_dp4( struct gl_context *ctx,
1657 GLboolean flag )
1658 {
1659 ctx->mvp_with_dp4 = flag;
1660 }
1661
1662 /*
1663 * ARB_blend_func_extended - ERRORS section
1664 * "The error INVALID_OPERATION is generated by Begin or any procedure that
1665 * implicitly calls Begin if any draw buffer has a blend function requiring the
1666 * second color input (SRC1_COLOR, ONE_MINUS_SRC1_COLOR, SRC1_ALPHA or
1667 * ONE_MINUS_SRC1_ALPHA), and a framebuffer is bound that has more than
1668 * the value of MAX_DUAL_SOURCE_DRAW_BUFFERS-1 active color attachements."
1669 */
1670 static GLboolean
1671 _mesa_check_blend_func_error(struct gl_context *ctx)
1672 {
1673 GLuint i;
1674 for (i = ctx->Const.MaxDualSourceDrawBuffers;
1675 i < ctx->DrawBuffer->_NumColorDrawBuffers;
1676 i++) {
1677 if (ctx->Color.Blend[i]._UsesDualSrc) {
1678 _mesa_error(ctx, GL_INVALID_OPERATION,
1679 "dual source blend on illegal attachment");
1680 return GL_FALSE;
1681 }
1682 }
1683 return GL_TRUE;
1684 }
1685
1686 /**
1687 * Prior to drawing anything with glBegin, glDrawArrays, etc. this function
1688 * is called to see if it's valid to render. This involves checking that
1689 * the current shader is valid and the framebuffer is complete.
1690 * If an error is detected it'll be recorded here.
1691 * \return GL_TRUE if OK to render, GL_FALSE if not
1692 */
1693 GLboolean
1694 _mesa_valid_to_render(struct gl_context *ctx, const char *where)
1695 {
1696 bool vert_from_glsl_shader = false;
1697 bool geom_from_glsl_shader = false;
1698 bool frag_from_glsl_shader = false;
1699
1700 /* This depends on having up to date derived state (shaders) */
1701 if (ctx->NewState)
1702 _mesa_update_state(ctx);
1703
1704 if (ctx->Shader.CurrentVertexProgram) {
1705 vert_from_glsl_shader = true;
1706
1707 if (!ctx->Shader.CurrentVertexProgram->LinkStatus) {
1708 _mesa_error(ctx, GL_INVALID_OPERATION,
1709 "%s(shader not linked)", where);
1710 return GL_FALSE;
1711 }
1712 #if 0 /* not normally enabled */
1713 {
1714 char errMsg[100];
1715 if (!_mesa_validate_shader_program(ctx,
1716 ctx->Shader.CurrentVertexProgram,
1717 errMsg)) {
1718 _mesa_warning(ctx, "Shader program %u is invalid: %s",
1719 ctx->Shader.CurrentVertexProgram->Name, errMsg);
1720 }
1721 }
1722 #endif
1723 }
1724
1725 if (ctx->Shader.CurrentGeometryProgram) {
1726 geom_from_glsl_shader = true;
1727
1728 if (!ctx->Shader.CurrentGeometryProgram->LinkStatus) {
1729 _mesa_error(ctx, GL_INVALID_OPERATION,
1730 "%s(shader not linked)", where);
1731 return GL_FALSE;
1732 }
1733 #if 0 /* not normally enabled */
1734 {
1735 char errMsg[100];
1736 if (!_mesa_validate_shader_program(ctx,
1737 ctx->Shader.CurrentGeometryProgram,
1738 errMsg)) {
1739 _mesa_warning(ctx, "Shader program %u is invalid: %s",
1740 ctx->Shader.CurrentGeometryProgram->Name, errMsg);
1741 }
1742 }
1743 #endif
1744 }
1745
1746 if (ctx->Shader.CurrentFragmentProgram) {
1747 frag_from_glsl_shader = true;
1748
1749 if (!ctx->Shader.CurrentFragmentProgram->LinkStatus) {
1750 _mesa_error(ctx, GL_INVALID_OPERATION,
1751 "%s(shader not linked)", where);
1752 return GL_FALSE;
1753 }
1754 #if 0 /* not normally enabled */
1755 {
1756 char errMsg[100];
1757 if (!_mesa_validate_shader_program(ctx,
1758 ctx->Shader.CurrentFragmentProgram,
1759 errMsg)) {
1760 _mesa_warning(ctx, "Shader program %u is invalid: %s",
1761 ctx->Shader.CurrentFragmentProgram->Name, errMsg);
1762 }
1763 }
1764 #endif
1765 }
1766
1767 /* Any shader stages that are not supplied by the GLSL shader and have
1768 * assembly shaders enabled must now be validated.
1769 */
1770 if (!vert_from_glsl_shader
1771 && ctx->VertexProgram.Enabled && !ctx->VertexProgram._Enabled) {
1772 _mesa_error(ctx, GL_INVALID_OPERATION,
1773 "%s(vertex program not valid)", where);
1774 return GL_FALSE;
1775 }
1776
1777 /* FINISHME: If GL_NV_geometry_program4 is ever supported, the current
1778 * FINISHME: geometry program should validated here.
1779 */
1780 (void) geom_from_glsl_shader;
1781
1782 if (!frag_from_glsl_shader) {
1783 if (ctx->FragmentProgram.Enabled && !ctx->FragmentProgram._Enabled) {
1784 _mesa_error(ctx, GL_INVALID_OPERATION,
1785 "%s(fragment program not valid)", where);
1786 return GL_FALSE;
1787 }
1788
1789 /* If drawing to integer-valued color buffers, there must be an
1790 * active fragment shader (GL_EXT_texture_integer).
1791 */
1792 if (ctx->DrawBuffer && ctx->DrawBuffer->_IntegerColor) {
1793 _mesa_error(ctx, GL_INVALID_OPERATION,
1794 "%s(integer format but no fragment shader)", where);
1795 return GL_FALSE;
1796 }
1797 }
1798
1799 if (ctx->DrawBuffer->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
1800 _mesa_error(ctx, GL_INVALID_FRAMEBUFFER_OPERATION_EXT,
1801 "%s(incomplete framebuffer)", where);
1802 return GL_FALSE;
1803 }
1804
1805 if (_mesa_check_blend_func_error(ctx) == GL_FALSE) {
1806 return GL_FALSE;
1807 }
1808
1809 #ifdef DEBUG
1810 if (ctx->Shader.Flags & GLSL_LOG) {
1811 struct gl_shader_program *shProg[MESA_SHADER_TYPES];
1812 gl_shader_type i;
1813
1814 shProg[MESA_SHADER_VERTEX] = ctx->Shader.CurrentVertexProgram;
1815 shProg[MESA_SHADER_GEOMETRY] = ctx->Shader.CurrentGeometryProgram;
1816 shProg[MESA_SHADER_FRAGMENT] = ctx->Shader.CurrentFragmentProgram;
1817
1818 for (i = 0; i < MESA_SHADER_TYPES; i++) {
1819 if (shProg[i] == NULL || shProg[i]->_Used
1820 || shProg[i]->_LinkedShaders[i] == NULL)
1821 continue;
1822
1823 /* This is the first time this shader is being used.
1824 * Append shader's constants/uniforms to log file.
1825 *
1826 * Only log data for the program target that matches the shader
1827 * target. It's possible to have a program bound to the vertex
1828 * shader target that also supplied a fragment shader. If that
1829 * program isn't also bound to the fragment shader target we don't
1830 * want to log its fragment data.
1831 */
1832 _mesa_append_uniforms_to_file(shProg[i]->_LinkedShaders[i]);
1833 }
1834
1835 for (i = 0; i < MESA_SHADER_TYPES; i++) {
1836 if (shProg[i] != NULL)
1837 shProg[i]->_Used = GL_TRUE;
1838 }
1839 }
1840 #endif
1841
1842 return GL_TRUE;
1843 }
1844
1845
1846 /*@}*/