mesa: separate exec allocation from initialization
[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
661
662 /**
663 * Do some sanity checks on the limits/constants for the given context.
664 * Only called the first time a context is bound.
665 */
666 static void
667 check_context_limits(struct gl_context *ctx)
668 {
669 /* check that we don't exceed the size of various bitfields */
670 assert(VERT_RESULT_MAX <=
671 (8 * sizeof(ctx->VertexProgram._Current->Base.OutputsWritten)));
672 assert(FRAG_ATTRIB_MAX <=
673 (8 * sizeof(ctx->FragmentProgram._Current->Base.InputsRead)));
674
675 assert(MAX_COMBINED_TEXTURE_IMAGE_UNITS <= 8 * sizeof(GLbitfield));
676
677 /* shader-related checks */
678 assert(ctx->Const.FragmentProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
679 assert(ctx->Const.VertexProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
680
681 /* Texture unit checks */
682 assert(ctx->Const.MaxTextureImageUnits > 0);
683 assert(ctx->Const.MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
684 assert(ctx->Const.MaxTextureCoordUnits > 0);
685 assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
686 assert(ctx->Const.MaxTextureUnits > 0);
687 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
688 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
689 assert(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.MaxTextureImageUnits,
690 ctx->Const.MaxTextureCoordUnits));
691 assert(ctx->Const.MaxCombinedTextureImageUnits > 0);
692 assert(ctx->Const.MaxCombinedTextureImageUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
693 assert(ctx->Const.MaxTextureCoordUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
694 /* number of coord units cannot be greater than number of image units */
695 assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.MaxTextureImageUnits);
696
697
698 /* Texture size checks */
699 assert(ctx->Const.MaxTextureLevels <= MAX_TEXTURE_LEVELS);
700 assert(ctx->Const.Max3DTextureLevels <= MAX_3D_TEXTURE_LEVELS);
701 assert(ctx->Const.MaxCubeTextureLevels <= MAX_CUBE_TEXTURE_LEVELS);
702 assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
703
704 /* Texture level checks */
705 assert(MAX_TEXTURE_LEVELS >= MAX_3D_TEXTURE_LEVELS);
706 assert(MAX_TEXTURE_LEVELS >= MAX_CUBE_TEXTURE_LEVELS);
707
708 /* Max texture size should be <= max viewport size (render to texture) */
709 assert((1U << (ctx->Const.MaxTextureLevels - 1))
710 <= ctx->Const.MaxViewportWidth);
711 assert((1U << (ctx->Const.MaxTextureLevels - 1))
712 <= ctx->Const.MaxViewportHeight);
713
714 assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS);
715
716 /* if this fails, add more enum values to gl_buffer_index */
717 assert(BUFFER_COLOR0 + MAX_DRAW_BUFFERS <= BUFFER_COUNT);
718
719 /* XXX probably add more tests */
720 }
721
722
723 /**
724 * Initialize the attribute groups in a GL context.
725 *
726 * \param ctx GL context.
727 *
728 * Initializes all the attributes, calling the respective <tt>init*</tt>
729 * functions for the more complex data structures.
730 */
731 static GLboolean
732 init_attrib_groups(struct gl_context *ctx)
733 {
734 assert(ctx);
735
736 /* Constants */
737 _mesa_init_constants( ctx );
738
739 /* Extensions */
740 _mesa_init_extensions( ctx );
741
742 /* Attribute Groups */
743 _mesa_init_accum( ctx );
744 _mesa_init_attrib( ctx );
745 _mesa_init_buffer_objects( ctx );
746 _mesa_init_color( ctx );
747 _mesa_init_current( ctx );
748 _mesa_init_depth( ctx );
749 _mesa_init_debug( ctx );
750 _mesa_init_display_list( ctx );
751 _mesa_init_errors( ctx );
752 _mesa_init_eval( ctx );
753 _mesa_init_fbobjects( ctx );
754 _mesa_init_feedback( ctx );
755 _mesa_init_fog( ctx );
756 _mesa_init_hint( ctx );
757 _mesa_init_line( ctx );
758 _mesa_init_lighting( ctx );
759 _mesa_init_matrix( ctx );
760 _mesa_init_multisample( ctx );
761 _mesa_init_pixel( ctx );
762 _mesa_init_pixelstore( ctx );
763 _mesa_init_point( ctx );
764 _mesa_init_polygon( ctx );
765 _mesa_init_program( ctx );
766 _mesa_init_queryobj( ctx );
767 _mesa_init_sync( ctx );
768 _mesa_init_rastpos( ctx );
769 _mesa_init_scissor( ctx );
770 _mesa_init_shader_state( ctx );
771 _mesa_init_stencil( ctx );
772 _mesa_init_transform( ctx );
773 _mesa_init_transform_feedback( ctx );
774 _mesa_init_varray( ctx );
775 _mesa_init_viewport( ctx );
776
777 if (!_mesa_init_texture( ctx ))
778 return GL_FALSE;
779
780 _mesa_init_texture_s3tc( ctx );
781
782 /* Miscellaneous */
783 ctx->NewState = _NEW_ALL;
784 ctx->NewDriverState = ~0;
785 ctx->ErrorValue = GL_NO_ERROR;
786 ctx->ResetStatus = GL_NO_ERROR;
787 ctx->varying_vp_inputs = VERT_BIT_ALL;
788
789 return GL_TRUE;
790 }
791
792
793 /**
794 * Update default objects in a GL context with respect to shared state.
795 *
796 * \param ctx GL context.
797 *
798 * Removes references to old default objects, (texture objects, program
799 * objects, etc.) and changes to reference those from the current shared
800 * state.
801 */
802 static GLboolean
803 update_default_objects(struct gl_context *ctx)
804 {
805 assert(ctx);
806
807 _mesa_update_default_objects_program(ctx);
808 _mesa_update_default_objects_texture(ctx);
809 _mesa_update_default_objects_buffer_objects(ctx);
810
811 return GL_TRUE;
812 }
813
814
815 /**
816 * This is the default function we plug into all dispatch table slots
817 * This helps prevents a segfault when someone calls a GL function without
818 * first checking if the extension's supported.
819 */
820 int
821 _mesa_generic_nop(void)
822 {
823 GET_CURRENT_CONTEXT(ctx);
824 _mesa_error(ctx, GL_INVALID_OPERATION,
825 "unsupported function called "
826 "(unsupported extension or deprecated function?)");
827 return 0;
828 }
829
830
831 /**
832 * Allocate and initialize a new dispatch table.
833 */
834 struct _glapi_table *
835 _mesa_alloc_dispatch_table(int size)
836 {
837 /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
838 * In practice, this'll be the same for stand-alone Mesa. But for DRI
839 * Mesa we do this to accomodate different versions of libGL and various
840 * DRI drivers.
841 */
842 GLint numEntries = MAX2(_glapi_get_dispatch_table_size(), _gloffset_COUNT);
843 struct _glapi_table *table;
844
845 /* should never happen, but just in case */
846 numEntries = MAX2(numEntries, size);
847
848 table = malloc(numEntries * sizeof(_glapi_proc));
849 if (table) {
850 _glapi_proc *entry = (_glapi_proc *) table;
851 GLint i;
852 for (i = 0; i < numEntries; i++) {
853 entry[i] = (_glapi_proc) _mesa_generic_nop;
854 }
855 }
856 return table;
857 }
858
859
860 /**
861 * Initialize a struct gl_context struct (rendering context).
862 *
863 * This includes allocating all the other structs and arrays which hang off of
864 * the context by pointers.
865 * Note that the driver needs to pass in its dd_function_table here since
866 * we need to at least call driverFunctions->NewTextureObject to create the
867 * default texture objects.
868 *
869 * Called by _mesa_create_context().
870 *
871 * Performs the imports and exports callback tables initialization, and
872 * miscellaneous one-time initializations. If no shared context is supplied one
873 * is allocated, and increase its reference count. Setups the GL API dispatch
874 * tables. Initialize the TNL module. Sets the maximum Z buffer depth.
875 * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
876 * for debug flags.
877 *
878 * \param ctx the context to initialize
879 * \param api the GL API type to create the context for
880 * \param visual describes the visual attributes for this context
881 * \param share_list points to context to share textures, display lists,
882 * etc with, or NULL
883 * \param driverFunctions table of device driver functions for this context
884 * to use
885 */
886 GLboolean
887 _mesa_initialize_context(struct gl_context *ctx,
888 gl_api api,
889 const struct gl_config *visual,
890 struct gl_context *share_list,
891 const struct dd_function_table *driverFunctions)
892 {
893 struct gl_shared_state *shared;
894 int i;
895
896 assert(driverFunctions->NewTextureObject);
897 assert(driverFunctions->FreeTextureImageBuffer);
898
899 ctx->API = api;
900 ctx->Visual = *visual;
901 ctx->DrawBuffer = NULL;
902 ctx->ReadBuffer = NULL;
903 ctx->WinSysDrawBuffer = NULL;
904 ctx->WinSysReadBuffer = NULL;
905
906 if (_mesa_is_desktop_gl(ctx)) {
907 _mesa_override_gl_version(ctx);
908 }
909
910 /* misc one-time initializations */
911 one_time_init(ctx);
912
913 /* Plug in driver functions and context pointer here.
914 * This is important because when we call alloc_shared_state() below
915 * we'll call ctx->Driver.NewTextureObject() to create the default
916 * textures.
917 */
918 ctx->Driver = *driverFunctions;
919
920 if (share_list) {
921 /* share state with another context */
922 shared = share_list->Shared;
923 }
924 else {
925 /* allocate new, unshared state */
926 shared = _mesa_alloc_shared_state(ctx);
927 if (!shared)
928 return GL_FALSE;
929 }
930
931 _mesa_reference_shared_state(ctx, &ctx->Shared, shared);
932
933 if (!init_attrib_groups( ctx )) {
934 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
935 return GL_FALSE;
936 }
937
938 /* setup the API dispatch tables with all nop functions */
939 ctx->Exec = _mesa_alloc_dispatch_table(_gloffset_COUNT);
940
941 /* setup the API exec functions */
942 _mesa_initialize_exec_table(ctx);
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 _mesa_install_save_vtxfmt( ctx, &ctx->ListState.ListVtxfmt );
978 /* fall-through */
979 case API_OPENGL_CORE:
980 break;
981 case API_OPENGLES:
982 /**
983 * GL_OES_texture_cube_map says
984 * "Initially all texture generation modes are set to REFLECTION_MAP_OES"
985 */
986 for (i = 0; i < MAX_TEXTURE_UNITS; i++) {
987 struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
988 texUnit->GenS.Mode = GL_REFLECTION_MAP_NV;
989 texUnit->GenT.Mode = GL_REFLECTION_MAP_NV;
990 texUnit->GenR.Mode = GL_REFLECTION_MAP_NV;
991 texUnit->GenS._ModeBit = TEXGEN_REFLECTION_MAP_NV;
992 texUnit->GenT._ModeBit = TEXGEN_REFLECTION_MAP_NV;
993 texUnit->GenR._ModeBit = TEXGEN_REFLECTION_MAP_NV;
994 }
995 break;
996 case API_OPENGLES2:
997 ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
998 ctx->VertexProgram._MaintainTnlProgram = GL_TRUE;
999 ctx->Point.PointSprite = GL_TRUE; /* always on for ES 2.x */
1000 break;
1001 }
1002
1003 ctx->FirstTimeCurrent = GL_TRUE;
1004
1005 return GL_TRUE;
1006 }
1007
1008
1009 /**
1010 * Allocate and initialize a struct gl_context structure.
1011 * Note that the driver needs to pass in its dd_function_table here since
1012 * we need to at least call driverFunctions->NewTextureObject to initialize
1013 * the rendering context.
1014 *
1015 * \param api the GL API type to create the context for
1016 * \param visual a struct gl_config pointer (we copy the struct contents)
1017 * \param share_list another context to share display lists with or NULL
1018 * \param driverFunctions points to the dd_function_table into which the
1019 * driver has plugged in all its special functions.
1020 *
1021 * \return pointer to a new __struct gl_contextRec or NULL if error.
1022 */
1023 struct gl_context *
1024 _mesa_create_context(gl_api api,
1025 const struct gl_config *visual,
1026 struct gl_context *share_list,
1027 const struct dd_function_table *driverFunctions)
1028 {
1029 struct gl_context *ctx;
1030
1031 ASSERT(visual);
1032
1033 ctx = calloc(1, sizeof(struct gl_context));
1034 if (!ctx)
1035 return NULL;
1036
1037 if (_mesa_initialize_context(ctx, api, visual, share_list,
1038 driverFunctions)) {
1039 return ctx;
1040 }
1041 else {
1042 free(ctx);
1043 return NULL;
1044 }
1045 }
1046
1047
1048 /**
1049 * Free the data associated with the given context.
1050 *
1051 * But doesn't free the struct gl_context struct itself.
1052 *
1053 * \sa _mesa_initialize_context() and init_attrib_groups().
1054 */
1055 void
1056 _mesa_free_context_data( struct gl_context *ctx )
1057 {
1058 if (!_mesa_get_current_context()){
1059 /* No current context, but we may need one in order to delete
1060 * texture objs, etc. So temporarily bind the context now.
1061 */
1062 _mesa_make_current(ctx, NULL, NULL);
1063 }
1064
1065 /* unreference WinSysDraw/Read buffers */
1066 _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
1067 _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
1068 _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
1069 _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
1070
1071 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
1072 _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
1073 _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram, NULL);
1074
1075 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
1076 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
1077 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
1078
1079 _mesa_reference_array_object(ctx, &ctx->Array.ArrayObj, NULL);
1080 _mesa_reference_array_object(ctx, &ctx->Array.DefaultArrayObj, NULL);
1081
1082 _mesa_free_attrib_data(ctx);
1083 _mesa_free_buffer_objects(ctx);
1084 _mesa_free_lighting_data( ctx );
1085 _mesa_free_eval_data( ctx );
1086 _mesa_free_texture_data( ctx );
1087 _mesa_free_matrix_data( ctx );
1088 _mesa_free_viewport_data( ctx );
1089 _mesa_free_program_data(ctx);
1090 _mesa_free_shader_state(ctx);
1091 _mesa_free_queryobj_data(ctx);
1092 _mesa_free_sync_data(ctx);
1093 _mesa_free_varray_data(ctx);
1094 _mesa_free_transform_feedback(ctx);
1095
1096 _mesa_reference_buffer_object(ctx, &ctx->Pack.BufferObj, NULL);
1097 _mesa_reference_buffer_object(ctx, &ctx->Unpack.BufferObj, NULL);
1098 _mesa_reference_buffer_object(ctx, &ctx->DefaultPacking.BufferObj, NULL);
1099 _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
1100
1101 /* free dispatch tables */
1102 free(ctx->Exec);
1103 free(ctx->Save);
1104
1105 /* Shared context state (display lists, textures, etc) */
1106 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
1107
1108 /* needs to be after freeing shared state */
1109 _mesa_free_display_list_data(ctx);
1110
1111 _mesa_free_errors_data(ctx);
1112
1113 free((void *)ctx->Extensions.String);
1114
1115 free(ctx->VersionString);
1116
1117 /* unbind the context if it's currently bound */
1118 if (ctx == _mesa_get_current_context()) {
1119 _mesa_make_current(NULL, NULL, NULL);
1120 }
1121 }
1122
1123
1124 /**
1125 * Destroy a struct gl_context structure.
1126 *
1127 * \param ctx GL context.
1128 *
1129 * Calls _mesa_free_context_data() and frees the gl_context object itself.
1130 */
1131 void
1132 _mesa_destroy_context( struct gl_context *ctx )
1133 {
1134 if (ctx) {
1135 _mesa_free_context_data(ctx);
1136 free( (void *) ctx );
1137 }
1138 }
1139
1140
1141 /**
1142 * Copy attribute groups from one context to another.
1143 *
1144 * \param src source context
1145 * \param dst destination context
1146 * \param mask bitwise OR of GL_*_BIT flags
1147 *
1148 * According to the bits specified in \p mask, copies the corresponding
1149 * attributes from \p src into \p dst. For many of the attributes a simple \c
1150 * memcpy is not enough due to the existence of internal pointers in their data
1151 * structures.
1152 */
1153 void
1154 _mesa_copy_context( const struct gl_context *src, struct gl_context *dst,
1155 GLuint mask )
1156 {
1157 if (mask & GL_ACCUM_BUFFER_BIT) {
1158 /* OK to memcpy */
1159 dst->Accum = src->Accum;
1160 }
1161 if (mask & GL_COLOR_BUFFER_BIT) {
1162 /* OK to memcpy */
1163 dst->Color = src->Color;
1164 }
1165 if (mask & GL_CURRENT_BIT) {
1166 /* OK to memcpy */
1167 dst->Current = src->Current;
1168 }
1169 if (mask & GL_DEPTH_BUFFER_BIT) {
1170 /* OK to memcpy */
1171 dst->Depth = src->Depth;
1172 }
1173 if (mask & GL_ENABLE_BIT) {
1174 /* no op */
1175 }
1176 if (mask & GL_EVAL_BIT) {
1177 /* OK to memcpy */
1178 dst->Eval = src->Eval;
1179 }
1180 if (mask & GL_FOG_BIT) {
1181 /* OK to memcpy */
1182 dst->Fog = src->Fog;
1183 }
1184 if (mask & GL_HINT_BIT) {
1185 /* OK to memcpy */
1186 dst->Hint = src->Hint;
1187 }
1188 if (mask & GL_LIGHTING_BIT) {
1189 GLuint i;
1190 /* begin with memcpy */
1191 dst->Light = src->Light;
1192 /* fixup linked lists to prevent pointer insanity */
1193 make_empty_list( &(dst->Light.EnabledList) );
1194 for (i = 0; i < MAX_LIGHTS; i++) {
1195 if (dst->Light.Light[i].Enabled) {
1196 insert_at_tail(&(dst->Light.EnabledList), &(dst->Light.Light[i]));
1197 }
1198 }
1199 }
1200 if (mask & GL_LINE_BIT) {
1201 /* OK to memcpy */
1202 dst->Line = src->Line;
1203 }
1204 if (mask & GL_LIST_BIT) {
1205 /* OK to memcpy */
1206 dst->List = src->List;
1207 }
1208 if (mask & GL_PIXEL_MODE_BIT) {
1209 /* OK to memcpy */
1210 dst->Pixel = src->Pixel;
1211 }
1212 if (mask & GL_POINT_BIT) {
1213 /* OK to memcpy */
1214 dst->Point = src->Point;
1215 }
1216 if (mask & GL_POLYGON_BIT) {
1217 /* OK to memcpy */
1218 dst->Polygon = src->Polygon;
1219 }
1220 if (mask & GL_POLYGON_STIPPLE_BIT) {
1221 /* Use loop instead of memcpy due to problem with Portland Group's
1222 * C compiler. Reported by John Stone.
1223 */
1224 GLuint i;
1225 for (i = 0; i < 32; i++) {
1226 dst->PolygonStipple[i] = src->PolygonStipple[i];
1227 }
1228 }
1229 if (mask & GL_SCISSOR_BIT) {
1230 /* OK to memcpy */
1231 dst->Scissor = src->Scissor;
1232 }
1233 if (mask & GL_STENCIL_BUFFER_BIT) {
1234 /* OK to memcpy */
1235 dst->Stencil = src->Stencil;
1236 }
1237 if (mask & GL_TEXTURE_BIT) {
1238 /* Cannot memcpy because of pointers */
1239 _mesa_copy_texture_state(src, dst);
1240 }
1241 if (mask & GL_TRANSFORM_BIT) {
1242 /* OK to memcpy */
1243 dst->Transform = src->Transform;
1244 }
1245 if (mask & GL_VIEWPORT_BIT) {
1246 /* Cannot use memcpy, because of pointers in GLmatrix _WindowMap */
1247 dst->Viewport.X = src->Viewport.X;
1248 dst->Viewport.Y = src->Viewport.Y;
1249 dst->Viewport.Width = src->Viewport.Width;
1250 dst->Viewport.Height = src->Viewport.Height;
1251 dst->Viewport.Near = src->Viewport.Near;
1252 dst->Viewport.Far = src->Viewport.Far;
1253 _math_matrix_copy(&dst->Viewport._WindowMap, &src->Viewport._WindowMap);
1254 }
1255
1256 /* XXX FIXME: Call callbacks?
1257 */
1258 dst->NewState = _NEW_ALL;
1259 dst->NewDriverState = ~0;
1260 }
1261
1262
1263 /**
1264 * Check if the given context can render into the given framebuffer
1265 * by checking visual attributes.
1266 *
1267 * Most of these tests could go away because Mesa is now pretty flexible
1268 * in terms of mixing rendering contexts with framebuffers. As long
1269 * as RGB vs. CI mode agree, we're probably good.
1270 *
1271 * \return GL_TRUE if compatible, GL_FALSE otherwise.
1272 */
1273 static GLboolean
1274 check_compatible(const struct gl_context *ctx,
1275 const struct gl_framebuffer *buffer)
1276 {
1277 const struct gl_config *ctxvis = &ctx->Visual;
1278 const struct gl_config *bufvis = &buffer->Visual;
1279
1280 if (buffer == _mesa_get_incomplete_framebuffer())
1281 return GL_TRUE;
1282
1283 #if 0
1284 /* disabling this fixes the fgl_glxgears pbuffer demo */
1285 if (ctxvis->doubleBufferMode && !bufvis->doubleBufferMode)
1286 return GL_FALSE;
1287 #endif
1288 if (ctxvis->stereoMode && !bufvis->stereoMode)
1289 return GL_FALSE;
1290 if (ctxvis->haveAccumBuffer && !bufvis->haveAccumBuffer)
1291 return GL_FALSE;
1292 if (ctxvis->haveDepthBuffer && !bufvis->haveDepthBuffer)
1293 return GL_FALSE;
1294 if (ctxvis->haveStencilBuffer && !bufvis->haveStencilBuffer)
1295 return GL_FALSE;
1296 if (ctxvis->redMask && ctxvis->redMask != bufvis->redMask)
1297 return GL_FALSE;
1298 if (ctxvis->greenMask && ctxvis->greenMask != bufvis->greenMask)
1299 return GL_FALSE;
1300 if (ctxvis->blueMask && ctxvis->blueMask != bufvis->blueMask)
1301 return GL_FALSE;
1302 #if 0
1303 /* disabled (see bug 11161) */
1304 if (ctxvis->depthBits && ctxvis->depthBits != bufvis->depthBits)
1305 return GL_FALSE;
1306 #endif
1307 if (ctxvis->stencilBits && ctxvis->stencilBits != bufvis->stencilBits)
1308 return GL_FALSE;
1309
1310 return GL_TRUE;
1311 }
1312
1313
1314 /**
1315 * Do one-time initialization for the given framebuffer. Specifically,
1316 * ask the driver for the window's current size and update the framebuffer
1317 * object to match.
1318 * Really, the device driver should totally take care of this.
1319 */
1320 static void
1321 initialize_framebuffer_size(struct gl_context *ctx, struct gl_framebuffer *fb)
1322 {
1323 GLuint width, height;
1324 if (ctx->Driver.GetBufferSize) {
1325 ctx->Driver.GetBufferSize(fb, &width, &height);
1326 if (ctx->Driver.ResizeBuffers)
1327 ctx->Driver.ResizeBuffers(ctx, fb, width, height);
1328 fb->Initialized = GL_TRUE;
1329 }
1330 }
1331
1332
1333 /**
1334 * Check if the viewport/scissor size has not yet been initialized.
1335 * Initialize the size if the given width and height are non-zero.
1336 */
1337 void
1338 _mesa_check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height)
1339 {
1340 if (!ctx->ViewportInitialized && width > 0 && height > 0) {
1341 /* Note: set flag here, before calling _mesa_set_viewport(), to prevent
1342 * potential infinite recursion.
1343 */
1344 ctx->ViewportInitialized = GL_TRUE;
1345 _mesa_set_viewport(ctx, 0, 0, width, height);
1346 _mesa_set_scissor(ctx, 0, 0, width, height);
1347 }
1348 }
1349
1350
1351 /**
1352 * Bind the given context to the given drawBuffer and readBuffer and
1353 * make it the current context for the calling thread.
1354 * We'll render into the drawBuffer and read pixels from the
1355 * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
1356 *
1357 * We check that the context's and framebuffer's visuals are compatible
1358 * and return immediately if they're not.
1359 *
1360 * \param newCtx the new GL context. If NULL then there will be no current GL
1361 * context.
1362 * \param drawBuffer the drawing framebuffer
1363 * \param readBuffer the reading framebuffer
1364 */
1365 GLboolean
1366 _mesa_make_current( struct gl_context *newCtx,
1367 struct gl_framebuffer *drawBuffer,
1368 struct gl_framebuffer *readBuffer )
1369 {
1370 GET_CURRENT_CONTEXT(curCtx);
1371
1372 if (MESA_VERBOSE & VERBOSE_API)
1373 _mesa_debug(newCtx, "_mesa_make_current()\n");
1374
1375 /* Check that the context's and framebuffer's visuals are compatible.
1376 */
1377 if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
1378 if (!check_compatible(newCtx, drawBuffer)) {
1379 _mesa_warning(newCtx,
1380 "MakeCurrent: incompatible visuals for context and drawbuffer");
1381 return GL_FALSE;
1382 }
1383 }
1384 if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
1385 if (!check_compatible(newCtx, readBuffer)) {
1386 _mesa_warning(newCtx,
1387 "MakeCurrent: incompatible visuals for context and readbuffer");
1388 return GL_FALSE;
1389 }
1390 }
1391
1392 if (curCtx &&
1393 (curCtx->WinSysDrawBuffer || curCtx->WinSysReadBuffer) &&
1394 /* make sure this context is valid for flushing */
1395 curCtx != newCtx)
1396 _mesa_flush(curCtx);
1397
1398 /* We used to call _glapi_check_multithread() here. Now do it in drivers */
1399 _glapi_set_context((void *) newCtx);
1400 ASSERT(_mesa_get_current_context() == newCtx);
1401
1402 if (!newCtx) {
1403 _glapi_set_dispatch(NULL); /* none current */
1404 }
1405 else {
1406 _glapi_set_dispatch(newCtx->CurrentDispatch);
1407
1408 if (drawBuffer && readBuffer) {
1409 ASSERT(_mesa_is_winsys_fbo(drawBuffer));
1410 ASSERT(_mesa_is_winsys_fbo(readBuffer));
1411 _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
1412 _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
1413
1414 /*
1415 * Only set the context's Draw/ReadBuffer fields if they're NULL
1416 * or not bound to a user-created FBO.
1417 */
1418 if (!newCtx->DrawBuffer || _mesa_is_winsys_fbo(newCtx->DrawBuffer)) {
1419 _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
1420 /* Update the FBO's list of drawbuffers/renderbuffers.
1421 * For winsys FBOs this comes from the GL state (which may have
1422 * changed since the last time this FBO was bound).
1423 */
1424 _mesa_update_draw_buffers(newCtx);
1425 }
1426 if (!newCtx->ReadBuffer || _mesa_is_winsys_fbo(newCtx->ReadBuffer)) {
1427 _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
1428 }
1429
1430 /* XXX only set this flag if we're really changing the draw/read
1431 * framebuffer bindings.
1432 */
1433 newCtx->NewState |= _NEW_BUFFERS;
1434
1435 #if 1
1436 /* We want to get rid of these lines: */
1437 if (!drawBuffer->Initialized) {
1438 initialize_framebuffer_size(newCtx, drawBuffer);
1439 }
1440 if (readBuffer != drawBuffer && !readBuffer->Initialized) {
1441 initialize_framebuffer_size(newCtx, readBuffer);
1442 }
1443
1444 _mesa_resizebuffers(newCtx);
1445 #else
1446 /* We want the drawBuffer and readBuffer to be initialized by
1447 * the driver.
1448 * This generally means the Width and Height match the actual
1449 * window size and the renderbuffers (both hardware and software
1450 * based) are allocated to match. The later can generally be
1451 * done with a call to _mesa_resize_framebuffer().
1452 *
1453 * It's theoretically possible for a buffer to have zero width
1454 * or height, but for now, assert check that the driver did what's
1455 * expected of it.
1456 */
1457 ASSERT(drawBuffer->Width > 0);
1458 ASSERT(drawBuffer->Height > 0);
1459 #endif
1460
1461 if (drawBuffer) {
1462 _mesa_check_init_viewport(newCtx,
1463 drawBuffer->Width, drawBuffer->Height);
1464 }
1465 }
1466
1467 if (newCtx->FirstTimeCurrent) {
1468 _mesa_compute_version(newCtx);
1469
1470 newCtx->Extensions.String = _mesa_make_extension_string(newCtx);
1471
1472 check_context_limits(newCtx);
1473
1474 /* We can use this to help debug user's problems. Tell them to set
1475 * the MESA_INFO env variable before running their app. Then the
1476 * first time each context is made current we'll print some useful
1477 * information.
1478 */
1479 if (_mesa_getenv("MESA_INFO")) {
1480 _mesa_print_info();
1481 }
1482
1483 newCtx->FirstTimeCurrent = GL_FALSE;
1484 }
1485 }
1486
1487 return GL_TRUE;
1488 }
1489
1490
1491 /**
1492 * Make context 'ctx' share the display lists, textures and programs
1493 * that are associated with 'ctxToShare'.
1494 * Any display lists, textures or programs associated with 'ctx' will
1495 * be deleted if nobody else is sharing them.
1496 */
1497 GLboolean
1498 _mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare)
1499 {
1500 if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
1501 struct gl_shared_state *oldShared = NULL;
1502
1503 /* save ref to old state to prevent it from being deleted immediately */
1504 _mesa_reference_shared_state(ctx, &oldShared, ctx->Shared);
1505
1506 /* update ctx's Shared pointer */
1507 _mesa_reference_shared_state(ctx, &ctx->Shared, ctxToShare->Shared);
1508
1509 update_default_objects(ctx);
1510
1511 /* release the old shared state */
1512 _mesa_reference_shared_state(ctx, &oldShared, NULL);
1513
1514 return GL_TRUE;
1515 }
1516 else {
1517 return GL_FALSE;
1518 }
1519 }
1520
1521
1522
1523 /**
1524 * \return pointer to the current GL context for this thread.
1525 *
1526 * Calls _glapi_get_context(). This isn't the fastest way to get the current
1527 * context. If you need speed, see the #GET_CURRENT_CONTEXT macro in
1528 * context.h.
1529 */
1530 struct gl_context *
1531 _mesa_get_current_context( void )
1532 {
1533 return (struct gl_context *) _glapi_get_context();
1534 }
1535
1536
1537 /**
1538 * Get context's current API dispatch table.
1539 *
1540 * It'll either be the immediate-mode execute dispatcher or the display list
1541 * compile dispatcher.
1542 *
1543 * \param ctx GL context.
1544 *
1545 * \return pointer to dispatch_table.
1546 *
1547 * Simply returns __struct gl_contextRec::CurrentDispatch.
1548 */
1549 struct _glapi_table *
1550 _mesa_get_dispatch(struct gl_context *ctx)
1551 {
1552 return ctx->CurrentDispatch;
1553 }
1554
1555 /*@}*/
1556
1557
1558 /**********************************************************************/
1559 /** \name Miscellaneous functions */
1560 /**********************************************************************/
1561 /*@{*/
1562
1563 /**
1564 * Record an error.
1565 *
1566 * \param ctx GL context.
1567 * \param error error code.
1568 *
1569 * Records the given error code and call the driver's dd_function_table::Error
1570 * function if defined.
1571 *
1572 * \sa
1573 * This is called via _mesa_error().
1574 */
1575 void
1576 _mesa_record_error(struct gl_context *ctx, GLenum error)
1577 {
1578 if (!ctx)
1579 return;
1580
1581 if (ctx->ErrorValue == GL_NO_ERROR) {
1582 ctx->ErrorValue = error;
1583 }
1584
1585 /* Call device driver's error handler, if any. This is used on the Mac. */
1586 if (ctx->Driver.Error) {
1587 ctx->Driver.Error(ctx);
1588 }
1589 }
1590
1591
1592 /**
1593 * Flush commands and wait for completion.
1594 */
1595 void
1596 _mesa_finish(struct gl_context *ctx)
1597 {
1598 FLUSH_VERTICES( ctx, 0 );
1599 FLUSH_CURRENT( ctx, 0 );
1600 if (ctx->Driver.Finish) {
1601 ctx->Driver.Finish(ctx);
1602 }
1603 }
1604
1605
1606 /**
1607 * Flush commands.
1608 */
1609 void
1610 _mesa_flush(struct gl_context *ctx)
1611 {
1612 FLUSH_VERTICES( ctx, 0 );
1613 FLUSH_CURRENT( ctx, 0 );
1614 if (ctx->Driver.Flush) {
1615 ctx->Driver.Flush(ctx);
1616 }
1617 }
1618
1619
1620
1621 /**
1622 * Execute glFinish().
1623 *
1624 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1625 * dd_function_table::Finish driver callback, if not NULL.
1626 */
1627 void GLAPIENTRY
1628 _mesa_Finish(void)
1629 {
1630 GET_CURRENT_CONTEXT(ctx);
1631 ASSERT_OUTSIDE_BEGIN_END(ctx);
1632 _mesa_finish(ctx);
1633 }
1634
1635
1636 /**
1637 * Execute glFlush().
1638 *
1639 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1640 * dd_function_table::Flush driver callback, if not NULL.
1641 */
1642 void GLAPIENTRY
1643 _mesa_Flush(void)
1644 {
1645 GET_CURRENT_CONTEXT(ctx);
1646 ASSERT_OUTSIDE_BEGIN_END(ctx);
1647 _mesa_flush(ctx);
1648 }
1649
1650
1651 /**
1652 * Set mvp_with_dp4 flag. If a driver has a preference for DP4 over
1653 * MUL/MAD, or vice versa, call this function to register that.
1654 * Otherwise we default to MUL/MAD.
1655 */
1656 void
1657 _mesa_set_mvp_with_dp4( struct gl_context *ctx,
1658 GLboolean flag )
1659 {
1660 ctx->mvp_with_dp4 = flag;
1661 }
1662
1663 /*
1664 * ARB_blend_func_extended - ERRORS section
1665 * "The error INVALID_OPERATION is generated by Begin or any procedure that
1666 * implicitly calls Begin if any draw buffer has a blend function requiring the
1667 * second color input (SRC1_COLOR, ONE_MINUS_SRC1_COLOR, SRC1_ALPHA or
1668 * ONE_MINUS_SRC1_ALPHA), and a framebuffer is bound that has more than
1669 * the value of MAX_DUAL_SOURCE_DRAW_BUFFERS-1 active color attachements."
1670 */
1671 static GLboolean
1672 _mesa_check_blend_func_error(struct gl_context *ctx)
1673 {
1674 GLuint i;
1675 for (i = ctx->Const.MaxDualSourceDrawBuffers;
1676 i < ctx->DrawBuffer->_NumColorDrawBuffers;
1677 i++) {
1678 if (ctx->Color.Blend[i]._UsesDualSrc) {
1679 _mesa_error(ctx, GL_INVALID_OPERATION,
1680 "dual source blend on illegal attachment");
1681 return GL_FALSE;
1682 }
1683 }
1684 return GL_TRUE;
1685 }
1686
1687 /**
1688 * Prior to drawing anything with glBegin, glDrawArrays, etc. this function
1689 * is called to see if it's valid to render. This involves checking that
1690 * the current shader is valid and the framebuffer is complete.
1691 * If an error is detected it'll be recorded here.
1692 * \return GL_TRUE if OK to render, GL_FALSE if not
1693 */
1694 GLboolean
1695 _mesa_valid_to_render(struct gl_context *ctx, const char *where)
1696 {
1697 bool vert_from_glsl_shader = false;
1698 bool geom_from_glsl_shader = false;
1699 bool frag_from_glsl_shader = false;
1700
1701 /* This depends on having up to date derived state (shaders) */
1702 if (ctx->NewState)
1703 _mesa_update_state(ctx);
1704
1705 if (ctx->Shader.CurrentVertexProgram) {
1706 vert_from_glsl_shader = true;
1707
1708 if (!ctx->Shader.CurrentVertexProgram->LinkStatus) {
1709 _mesa_error(ctx, GL_INVALID_OPERATION,
1710 "%s(shader not linked)", where);
1711 return GL_FALSE;
1712 }
1713 #if 0 /* not normally enabled */
1714 {
1715 char errMsg[100];
1716 if (!_mesa_validate_shader_program(ctx,
1717 ctx->Shader.CurrentVertexProgram,
1718 errMsg)) {
1719 _mesa_warning(ctx, "Shader program %u is invalid: %s",
1720 ctx->Shader.CurrentVertexProgram->Name, errMsg);
1721 }
1722 }
1723 #endif
1724 }
1725
1726 if (ctx->Shader.CurrentGeometryProgram) {
1727 geom_from_glsl_shader = true;
1728
1729 if (!ctx->Shader.CurrentGeometryProgram->LinkStatus) {
1730 _mesa_error(ctx, GL_INVALID_OPERATION,
1731 "%s(shader not linked)", where);
1732 return GL_FALSE;
1733 }
1734 #if 0 /* not normally enabled */
1735 {
1736 char errMsg[100];
1737 if (!_mesa_validate_shader_program(ctx,
1738 ctx->Shader.CurrentGeometryProgram,
1739 errMsg)) {
1740 _mesa_warning(ctx, "Shader program %u is invalid: %s",
1741 ctx->Shader.CurrentGeometryProgram->Name, errMsg);
1742 }
1743 }
1744 #endif
1745 }
1746
1747 if (ctx->Shader.CurrentFragmentProgram) {
1748 frag_from_glsl_shader = true;
1749
1750 if (!ctx->Shader.CurrentFragmentProgram->LinkStatus) {
1751 _mesa_error(ctx, GL_INVALID_OPERATION,
1752 "%s(shader not linked)", where);
1753 return GL_FALSE;
1754 }
1755 #if 0 /* not normally enabled */
1756 {
1757 char errMsg[100];
1758 if (!_mesa_validate_shader_program(ctx,
1759 ctx->Shader.CurrentFragmentProgram,
1760 errMsg)) {
1761 _mesa_warning(ctx, "Shader program %u is invalid: %s",
1762 ctx->Shader.CurrentFragmentProgram->Name, errMsg);
1763 }
1764 }
1765 #endif
1766 }
1767
1768 /* Any shader stages that are not supplied by the GLSL shader and have
1769 * assembly shaders enabled must now be validated.
1770 */
1771 if (!vert_from_glsl_shader
1772 && ctx->VertexProgram.Enabled && !ctx->VertexProgram._Enabled) {
1773 _mesa_error(ctx, GL_INVALID_OPERATION,
1774 "%s(vertex program not valid)", where);
1775 return GL_FALSE;
1776 }
1777
1778 /* FINISHME: If GL_NV_geometry_program4 is ever supported, the current
1779 * FINISHME: geometry program should validated here.
1780 */
1781 (void) geom_from_glsl_shader;
1782
1783 if (!frag_from_glsl_shader) {
1784 if (ctx->FragmentProgram.Enabled && !ctx->FragmentProgram._Enabled) {
1785 _mesa_error(ctx, GL_INVALID_OPERATION,
1786 "%s(fragment program not valid)", where);
1787 return GL_FALSE;
1788 }
1789
1790 /* If drawing to integer-valued color buffers, there must be an
1791 * active fragment shader (GL_EXT_texture_integer).
1792 */
1793 if (ctx->DrawBuffer && ctx->DrawBuffer->_IntegerColor) {
1794 _mesa_error(ctx, GL_INVALID_OPERATION,
1795 "%s(integer format but no fragment shader)", where);
1796 return GL_FALSE;
1797 }
1798 }
1799
1800 if (ctx->DrawBuffer->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
1801 _mesa_error(ctx, GL_INVALID_FRAMEBUFFER_OPERATION_EXT,
1802 "%s(incomplete framebuffer)", where);
1803 return GL_FALSE;
1804 }
1805
1806 if (_mesa_check_blend_func_error(ctx) == GL_FALSE) {
1807 return GL_FALSE;
1808 }
1809
1810 #ifdef DEBUG
1811 if (ctx->Shader.Flags & GLSL_LOG) {
1812 struct gl_shader_program *shProg[MESA_SHADER_TYPES];
1813 gl_shader_type i;
1814
1815 shProg[MESA_SHADER_VERTEX] = ctx->Shader.CurrentVertexProgram;
1816 shProg[MESA_SHADER_GEOMETRY] = ctx->Shader.CurrentGeometryProgram;
1817 shProg[MESA_SHADER_FRAGMENT] = ctx->Shader.CurrentFragmentProgram;
1818
1819 for (i = 0; i < MESA_SHADER_TYPES; i++) {
1820 if (shProg[i] == NULL || shProg[i]->_Used
1821 || shProg[i]->_LinkedShaders[i] == NULL)
1822 continue;
1823
1824 /* This is the first time this shader is being used.
1825 * Append shader's constants/uniforms to log file.
1826 *
1827 * Only log data for the program target that matches the shader
1828 * target. It's possible to have a program bound to the vertex
1829 * shader target that also supplied a fragment shader. If that
1830 * program isn't also bound to the fragment shader target we don't
1831 * want to log its fragment data.
1832 */
1833 _mesa_append_uniforms_to_file(shProg[i]->_LinkedShaders[i]);
1834 }
1835
1836 for (i = 0; i < MESA_SHADER_TYPES; i++) {
1837 if (shProg[i] != NULL)
1838 shProg[i]->_Used = GL_TRUE;
1839 }
1840 }
1841 #endif
1842
1843 return GL_TRUE;
1844 }
1845
1846
1847 /*@}*/