OSDN Git Service

mesa/main: Make FEATURE_attrib_stack follow feature conventions.
[android-x86/external-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 "colortab.h"
90 #include "context.h"
91 #include "cpuinfo.h"
92 #include "debug.h"
93 #include "depth.h"
94 #if FEATURE_dlist
95 #include "dlist.h"
96 #endif
97 #if FEATURE_evaluators
98 #include "eval.h"
99 #endif
100 #include "enums.h"
101 #include "extensions.h"
102 #include "fbobject.h"
103 #if FEATURE_feedback
104 #include "feedback.h"
105 #endif
106 #include "fog.h"
107 #include "framebuffer.h"
108 #include "get.h"
109 #if FEATURE_histogram
110 #include "histogram.h"
111 #endif
112 #include "hint.h"
113 #include "hash.h"
114 #include "light.h"
115 #include "lines.h"
116 #include "macros.h"
117 #include "matrix.h"
118 #include "multisample.h"
119 #include "pixel.h"
120 #include "pixelstore.h"
121 #include "points.h"
122 #include "polygon.h"
123 #if FEATURE_ARB_occlusion_query
124 #include "queryobj.h"
125 #endif
126 #if FEATURE_ARB_sync
127 #include "syncobj.h"
128 #endif
129 #if FEATURE_drawpix
130 #include "rastpos.h"
131 #endif
132 #include "scissor.h"
133 #include "shared.h"
134 #include "simple_list.h"
135 #include "state.h"
136 #include "stencil.h"
137 #include "texcompress.h"
138 #include "teximage.h"
139 #include "texobj.h"
140 #include "texstate.h"
141 #include "mtypes.h"
142 #include "varray.h"
143 #include "version.h"
144 #include "viewport.h"
145 #include "vtxfmt.h"
146 #include "glapi/glthread.h"
147 #include "glapi/glapioffsets.h"
148 #include "glapi/glapitable.h"
149 #include "shader/program.h"
150 #include "shader/prog_print.h"
151 #include "shader/shader_api.h"
152 #if FEATURE_ATI_fragment_shader
153 #include "shader/atifragshader.h"
154 #endif
155 #if _HAVE_FULL_GL
156 #include "math/m_matrix.h"
157 #endif
158
159 #ifdef USE_SPARC_ASM
160 #include "sparc/sparc.h"
161 #endif
162
163 #ifndef MESA_VERBOSE
164 int MESA_VERBOSE = 0;
165 #endif
166
167 #ifndef MESA_DEBUG_FLAGS
168 int MESA_DEBUG_FLAGS = 0;
169 #endif
170
171
172 /* ubyte -> float conversion */
173 GLfloat _mesa_ubyte_to_float_color_tab[256];
174
175
176
177 /**
178  * Swap buffers notification callback.
179  * 
180  * \param ctx GL context.
181  *
182  * Called by window system just before swapping buffers.
183  * We have to finish any pending rendering.
184  */
185 void
186 _mesa_notifySwapBuffers(__GLcontext *ctx)
187 {
188    FLUSH_CURRENT( ctx, 0 );
189    if (ctx->Driver.Flush) {
190       ctx->Driver.Flush(ctx);
191    }
192 }
193
194
195 /**********************************************************************/
196 /** \name GL Visual allocation/destruction                            */
197 /**********************************************************************/
198 /*@{*/
199
200 /**
201  * Allocates a GLvisual structure and initializes it via
202  * _mesa_initialize_visual().
203  * 
204  * \param rgbFlag GL_TRUE for RGB(A) mode, GL_FALSE for Color Index mode.
205  * \param dbFlag double buffering
206  * \param stereoFlag stereo buffer
207  * \param depthBits requested bits per depth buffer value. Any value in [0, 32]
208  * is acceptable but the actual depth type will be GLushort or GLuint as
209  * needed.
210  * \param stencilBits requested minimum bits per stencil buffer value
211  * \param accumRedBits, accumGreenBits, accumBlueBits, accumAlphaBits number of bits per color component in accum buffer.
212  * \param indexBits number of bits per pixel if \p rgbFlag is GL_FALSE
213  * \param redBits number of bits per color component in frame buffer for RGB(A)
214  * mode.  We always use 8 in core Mesa though.
215  * \param greenBits same as above.
216  * \param blueBits same as above.
217  * \param alphaBits same as above.
218  * \param numSamples not really used.
219  * 
220  * \return pointer to new GLvisual or NULL if requested parameters can't be
221  * met.
222  *
223  * \note Need to add params for level and numAuxBuffers (at least)
224  */
225 GLvisual *
226 _mesa_create_visual( GLboolean rgbFlag,
227                      GLboolean dbFlag,
228                      GLboolean stereoFlag,
229                      GLint redBits,
230                      GLint greenBits,
231                      GLint blueBits,
232                      GLint alphaBits,
233                      GLint indexBits,
234                      GLint depthBits,
235                      GLint stencilBits,
236                      GLint accumRedBits,
237                      GLint accumGreenBits,
238                      GLint accumBlueBits,
239                      GLint accumAlphaBits,
240                      GLint numSamples )
241 {
242    GLvisual *vis = (GLvisual *) _mesa_calloc(sizeof(GLvisual));
243    if (vis) {
244       if (!_mesa_initialize_visual(vis, rgbFlag, dbFlag, stereoFlag,
245                                    redBits, greenBits, blueBits, alphaBits,
246                                    indexBits, depthBits, stencilBits,
247                                    accumRedBits, accumGreenBits,
248                                    accumBlueBits, accumAlphaBits,
249                                    numSamples)) {
250          _mesa_free(vis);
251          return NULL;
252       }
253    }
254    return vis;
255 }
256
257 /**
258  * Makes some sanity checks and fills in the fields of the
259  * GLvisual object with the given parameters.  If the caller needs
260  * to set additional fields, he should just probably init the whole GLvisual
261  * object himself.
262  * \return GL_TRUE on success, or GL_FALSE on failure.
263  *
264  * \sa _mesa_create_visual() above for the parameter description.
265  */
266 GLboolean
267 _mesa_initialize_visual( GLvisual *vis,
268                          GLboolean rgbFlag,
269                          GLboolean dbFlag,
270                          GLboolean stereoFlag,
271                          GLint redBits,
272                          GLint greenBits,
273                          GLint blueBits,
274                          GLint alphaBits,
275                          GLint indexBits,
276                          GLint depthBits,
277                          GLint stencilBits,
278                          GLint accumRedBits,
279                          GLint accumGreenBits,
280                          GLint accumBlueBits,
281                          GLint accumAlphaBits,
282                          GLint numSamples )
283 {
284    assert(vis);
285
286    if (depthBits < 0 || depthBits > 32) {
287       return GL_FALSE;
288    }
289    if (stencilBits < 0 || stencilBits > STENCIL_BITS) {
290       return GL_FALSE;
291    }
292    assert(accumRedBits >= 0);
293    assert(accumGreenBits >= 0);
294    assert(accumBlueBits >= 0);
295    assert(accumAlphaBits >= 0);
296
297    vis->rgbMode          = rgbFlag;
298    vis->doubleBufferMode = dbFlag;
299    vis->stereoMode       = stereoFlag;
300
301    vis->redBits          = redBits;
302    vis->greenBits        = greenBits;
303    vis->blueBits         = blueBits;
304    vis->alphaBits        = alphaBits;
305    vis->rgbBits          = redBits + greenBits + blueBits;
306
307    vis->indexBits      = indexBits;
308    vis->depthBits      = depthBits;
309    vis->stencilBits    = stencilBits;
310
311    vis->accumRedBits   = accumRedBits;
312    vis->accumGreenBits = accumGreenBits;
313    vis->accumBlueBits  = accumBlueBits;
314    vis->accumAlphaBits = accumAlphaBits;
315
316    vis->haveAccumBuffer   = accumRedBits > 0;
317    vis->haveDepthBuffer   = depthBits > 0;
318    vis->haveStencilBuffer = stencilBits > 0;
319
320    vis->numAuxBuffers = 0;
321    vis->level = 0;
322    vis->pixmapMode = 0;
323    vis->sampleBuffers = numSamples > 0 ? 1 : 0;
324    vis->samples = numSamples;
325
326    return GL_TRUE;
327 }
328
329
330 /**
331  * Destroy a visual and free its memory.
332  *
333  * \param vis visual.
334  * 
335  * Frees the visual structure.
336  */
337 void
338 _mesa_destroy_visual( GLvisual *vis )
339 {
340    _mesa_free(vis);
341 }
342
343 /*@}*/
344
345
346 /**********************************************************************/
347 /** \name Context allocation, initialization, destroying
348  *
349  * The purpose of the most initialization functions here is to provide the
350  * default state values according to the OpenGL specification.
351  */
352 /**********************************************************************/
353 /*@{*/
354
355
356 /**
357  * This is lame.  gdb only seems to recognize enum types that are
358  * actually used somewhere.  We want to be able to print/use enum
359  * values such as TEXTURE_2D_INDEX in gdb.  But we don't actually use
360  * the gl_texture_index type anywhere.  Thus, this lame function.
361  */
362 static void
363 dummy_enum_func(void)
364 {
365    gl_buffer_index bi;
366    gl_colortable_index ci;
367    gl_face_index fi;
368    gl_frag_attrib fa;
369    gl_frag_result fr;
370    gl_texture_index ti;
371    gl_vert_attrib va;
372    gl_vert_result vr;
373
374    (void) bi;
375    (void) ci;
376    (void) fi;
377    (void) fa;
378    (void) fr;
379    (void) ti;
380    (void) va;
381    (void) vr;
382 }
383
384
385 /**
386  * One-time initialization mutex lock.
387  *
388  * \sa Used by one_time_init().
389  */
390 _glthread_DECLARE_STATIC_MUTEX(OneTimeLock);
391
392 /**
393  * Calls all the various one-time-init functions in Mesa.
394  *
395  * While holding a global mutex lock, calls several initialization functions,
396  * and sets the glapi callbacks if the \c MESA_DEBUG environment variable is
397  * defined.
398  *
399  * \sa _math_init().
400  */
401 static void
402 one_time_init( GLcontext *ctx )
403 {
404    static GLboolean alreadyCalled = GL_FALSE;
405    (void) ctx;
406    _glthread_LOCK_MUTEX(OneTimeLock);
407    if (!alreadyCalled) {
408       GLuint i;
409
410       /* do some implementation tests */
411       assert( sizeof(GLbyte) == 1 );
412       assert( sizeof(GLubyte) == 1 );
413       assert( sizeof(GLshort) == 2 );
414       assert( sizeof(GLushort) == 2 );
415       assert( sizeof(GLint) == 4 );
416       assert( sizeof(GLuint) == 4 );
417
418       _mesa_get_cpu_features();
419
420       _mesa_init_sqrt_table();
421
422       for (i = 0; i < 256; i++) {
423          _mesa_ubyte_to_float_color_tab[i] = (float) i / 255.0F;
424       }
425
426       if (_mesa_getenv("MESA_DEBUG")) {
427          _glapi_noop_enable_warnings(GL_TRUE);
428          _glapi_set_warning_func( (_glapi_warning_func) _mesa_warning );
429       }
430       else {
431          _glapi_noop_enable_warnings(GL_FALSE);
432       }
433
434 #if defined(DEBUG) && defined(__DATE__) && defined(__TIME__)
435       _mesa_debug(ctx, "Mesa %s DEBUG build %s %s\n",
436                   MESA_VERSION_STRING, __DATE__, __TIME__);
437 #endif
438
439       alreadyCalled = GL_TRUE;
440    }
441    _glthread_UNLOCK_MUTEX(OneTimeLock);
442
443    dummy_enum_func();
444 }
445
446
447 /**
448  * Initialize fields of gl_current_attrib (aka ctx->Current.*)
449  */
450 static void
451 _mesa_init_current(GLcontext *ctx)
452 {
453    GLuint i;
454
455    /* Init all to (0,0,0,1) */
456    for (i = 0; i < Elements(ctx->Current.Attrib); i++) {
457       ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 );
458    }
459
460    /* redo special cases: */
461    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_WEIGHT], 1.0, 0.0, 0.0, 0.0 );
462    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 );
463    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 );
464    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 );
465    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX], 1.0, 0.0, 0.0, 1.0 );
466    ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG], 1.0, 0.0, 0.0, 1.0 );
467 }
468
469
470 /**
471  * Init vertex/fragment program limits.
472  * Important: drivers should override these with actual limits.
473  */
474 static void
475 init_program_limits(GLenum type, struct gl_program_constants *prog)
476 {
477    prog->MaxInstructions = MAX_PROGRAM_INSTRUCTIONS;
478    prog->MaxAluInstructions = MAX_PROGRAM_INSTRUCTIONS;
479    prog->MaxTexInstructions = MAX_PROGRAM_INSTRUCTIONS;
480    prog->MaxTexIndirections = MAX_PROGRAM_INSTRUCTIONS;
481    prog->MaxTemps = MAX_PROGRAM_TEMPS;
482    prog->MaxEnvParams = MAX_PROGRAM_ENV_PARAMS;
483    prog->MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS;
484    prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
485
486    if (type == GL_VERTEX_PROGRAM_ARB) {
487       prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
488       prog->MaxAttribs = MAX_NV_VERTEX_PROGRAM_INPUTS;
489       prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
490    }
491    else {
492       prog->MaxParameters = MAX_NV_FRAGMENT_PROGRAM_PARAMS;
493       prog->MaxAttribs = MAX_NV_FRAGMENT_PROGRAM_INPUTS;
494       prog->MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS;
495    }
496
497    /* Set the native limits to zero.  This implies that there is no native
498     * support for shaders.  Let the drivers fill in the actual values.
499     */
500    prog->MaxNativeInstructions = 0;
501    prog->MaxNativeAluInstructions = 0;
502    prog->MaxNativeTexInstructions = 0;
503    prog->MaxNativeTexIndirections = 0;
504    prog->MaxNativeAttribs = 0;
505    prog->MaxNativeTemps = 0;
506    prog->MaxNativeAddressRegs = 0;
507    prog->MaxNativeParameters = 0;
508 }
509
510
511 /**
512  * Initialize fields of gl_constants (aka ctx->Const.*).
513  * Use defaults from config.h.  The device drivers will often override
514  * some of these values (such as number of texture units).
515  */
516 static void 
517 _mesa_init_constants(GLcontext *ctx)
518 {
519    assert(ctx);
520
521    assert(MAX_TEXTURE_LEVELS >= MAX_3D_TEXTURE_LEVELS);
522    assert(MAX_TEXTURE_LEVELS >= MAX_CUBE_TEXTURE_LEVELS);
523
524    /* Max texture size should be <= max viewport size (render to texture) */
525    assert((1 << (MAX_TEXTURE_LEVELS - 1)) <= MAX_WIDTH);
526
527    /* Constants, may be overriden (usually only reduced) by device drivers */
528    ctx->Const.MaxTextureLevels = MAX_TEXTURE_LEVELS;
529    ctx->Const.Max3DTextureLevels = MAX_3D_TEXTURE_LEVELS;
530    ctx->Const.MaxCubeTextureLevels = MAX_CUBE_TEXTURE_LEVELS;
531    ctx->Const.MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE;
532    ctx->Const.MaxArrayTextureLayers = MAX_ARRAY_TEXTURE_LAYERS;
533    ctx->Const.MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS;
534    ctx->Const.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
535    ctx->Const.MaxTextureUnits = MIN2(ctx->Const.MaxTextureCoordUnits,
536                                      ctx->Const.MaxTextureImageUnits);
537    ctx->Const.MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY;
538    ctx->Const.MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS;
539    ctx->Const.MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE;
540    ctx->Const.SubPixelBits = SUB_PIXEL_BITS;
541    ctx->Const.MinPointSize = MIN_POINT_SIZE;
542    ctx->Const.MaxPointSize = MAX_POINT_SIZE;
543    ctx->Const.MinPointSizeAA = MIN_POINT_SIZE;
544    ctx->Const.MaxPointSizeAA = MAX_POINT_SIZE;
545    ctx->Const.PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY;
546    ctx->Const.MinLineWidth = MIN_LINE_WIDTH;
547    ctx->Const.MaxLineWidth = MAX_LINE_WIDTH;
548    ctx->Const.MinLineWidthAA = MIN_LINE_WIDTH;
549    ctx->Const.MaxLineWidthAA = MAX_LINE_WIDTH;
550    ctx->Const.LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY;
551    ctx->Const.MaxColorTableSize = MAX_COLOR_TABLE_SIZE;
552    ctx->Const.MaxConvolutionWidth = MAX_CONVOLUTION_WIDTH;
553    ctx->Const.MaxConvolutionHeight = MAX_CONVOLUTION_HEIGHT;
554    ctx->Const.MaxClipPlanes = MAX_CLIP_PLANES;
555    ctx->Const.MaxLights = MAX_LIGHTS;
556    ctx->Const.MaxShininess = 128.0;
557    ctx->Const.MaxSpotExponent = 128.0;
558    ctx->Const.MaxViewportWidth = MAX_WIDTH;
559    ctx->Const.MaxViewportHeight = MAX_HEIGHT;
560 #if FEATURE_ARB_vertex_program
561    init_program_limits(GL_VERTEX_PROGRAM_ARB, &ctx->Const.VertexProgram);
562 #endif
563 #if FEATURE_ARB_fragment_program
564    init_program_limits(GL_FRAGMENT_PROGRAM_ARB, &ctx->Const.FragmentProgram);
565 #endif
566    ctx->Const.MaxProgramMatrices = MAX_PROGRAM_MATRICES;
567    ctx->Const.MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH;
568
569    /* CheckArrayBounds is overriden by drivers/x11 for X server */
570    ctx->Const.CheckArrayBounds = GL_FALSE;
571
572    /* GL_ARB_draw_buffers */
573    ctx->Const.MaxDrawBuffers = MAX_DRAW_BUFFERS;
574
575    /* GL_OES_read_format */
576    ctx->Const.ColorReadFormat = GL_RGBA;
577    ctx->Const.ColorReadType = GL_UNSIGNED_BYTE;
578
579 #if FEATURE_EXT_framebuffer_object
580    ctx->Const.MaxColorAttachments = MAX_COLOR_ATTACHMENTS;
581    ctx->Const.MaxRenderbufferSize = MAX_WIDTH;
582 #endif
583
584 #if FEATURE_ARB_vertex_shader
585    ctx->Const.MaxVertexTextureImageUnits = MAX_VERTEX_TEXTURE_IMAGE_UNITS;
586    ctx->Const.MaxVarying = MAX_VARYING;
587 #endif
588
589    /* GL_ARB_framebuffer_object */
590    ctx->Const.MaxSamples = 0;
591
592    /* GL_ARB_sync */
593    ctx->Const.MaxServerWaitTimeout = (GLuint64) ~0;
594
595    /* GL_ATI_envmap_bumpmap */
596    ctx->Const.SupportedBumpUnits = SUPPORTED_ATI_BUMP_UNITS;
597
598    /* GL_EXT_provoking_vertex */
599    ctx->Const.QuadsFollowProvokingVertexConvention = GL_TRUE;
600
601    /* sanity checks */
602    ASSERT(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.MaxTextureImageUnits,
603                                              ctx->Const.MaxTextureCoordUnits));
604    ASSERT(ctx->Const.FragmentProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
605    ASSERT(ctx->Const.VertexProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
606
607    ASSERT(MAX_NV_FRAGMENT_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
608    ASSERT(MAX_NV_VERTEX_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
609    ASSERT(MAX_NV_VERTEX_PROGRAM_INPUTS <= VERT_ATTRIB_MAX);
610    ASSERT(MAX_NV_VERTEX_PROGRAM_OUTPUTS <= VERT_RESULT_MAX);
611
612    /* check that we don't exceed various 32-bit bitfields */
613    ASSERT(VERT_RESULT_MAX <= 32);
614    ASSERT(FRAG_ATTRIB_MAX <= 32);
615 }
616
617
618 /**
619  * Do some sanity checks on the limits/constants for the given context.
620  * Only called the first time a context is bound.
621  */
622 static void
623 check_context_limits(GLcontext *ctx)
624 {
625    /* Many context limits/constants are limited by the size of
626     * internal arrays.
627     */
628    assert(ctx->Const.MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
629    assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
630    assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
631    assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
632
633    /* number of coord units cannot be greater than number of image units */
634    assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.MaxTextureImageUnits);
635
636    assert(ctx->Const.MaxTextureLevels <= MAX_TEXTURE_LEVELS);
637    assert(ctx->Const.Max3DTextureLevels <= MAX_3D_TEXTURE_LEVELS);
638    assert(ctx->Const.MaxCubeTextureLevels <= MAX_CUBE_TEXTURE_LEVELS);
639    assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
640
641    /* make sure largest texture image is <= MAX_WIDTH in size */
642    assert((1 << (ctx->Const.MaxTextureLevels - 1)) <= MAX_WIDTH);
643    assert((1 << (ctx->Const.MaxCubeTextureLevels - 1)) <= MAX_WIDTH);
644    assert((1 << (ctx->Const.Max3DTextureLevels - 1)) <= MAX_WIDTH);
645
646    assert(ctx->Const.MaxViewportWidth <= MAX_WIDTH);
647    assert(ctx->Const.MaxViewportHeight <= MAX_WIDTH);
648
649    assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS);
650
651    /* XXX probably add more tests */
652 }
653
654
655 /**
656  * Initialize the attribute groups in a GL context.
657  *
658  * \param ctx GL context.
659  *
660  * Initializes all the attributes, calling the respective <tt>init*</tt>
661  * functions for the more complex data structures.
662  */
663 static GLboolean
664 init_attrib_groups(GLcontext *ctx)
665 {
666    assert(ctx);
667
668    /* Constants */
669    _mesa_init_constants( ctx );
670
671    /* Extensions */
672    _mesa_init_extensions( ctx );
673
674    /* Attribute Groups */
675    _mesa_init_accum( ctx );
676    _mesa_init_attrib( ctx );
677    _mesa_init_buffer_objects( ctx );
678    _mesa_init_color( ctx );
679    _mesa_init_colortables( ctx );
680    _mesa_init_current( ctx );
681    _mesa_init_depth( ctx );
682    _mesa_init_debug( ctx );
683 #if FEATURE_dlist
684    _mesa_init_display_list( ctx );
685 #endif
686 #if FEATURE_evaluators
687    _mesa_init_eval( ctx );
688 #endif
689    _mesa_init_fbobjects( ctx );
690 #if FEATURE_feedback
691    _mesa_init_feedback( ctx );
692 #else
693    ctx->RenderMode = GL_RENDER;
694 #endif
695    _mesa_init_fog( ctx );
696 #if FEATURE_histogram
697    _mesa_init_histogram( ctx );
698 #endif
699    _mesa_init_hint( ctx );
700    _mesa_init_line( ctx );
701    _mesa_init_lighting( ctx );
702    _mesa_init_matrix( ctx );
703    _mesa_init_multisample( ctx );
704    _mesa_init_pixel( ctx );
705    _mesa_init_pixelstore( ctx );
706    _mesa_init_point( ctx );
707    _mesa_init_polygon( ctx );
708    _mesa_init_program( ctx );
709 #if FEATURE_ARB_occlusion_query
710    _mesa_init_query( ctx );
711 #endif
712 #if FEATURE_ARB_sync
713    _mesa_init_sync( ctx );
714 #endif
715 #if FEATURE_drawpix
716    _mesa_init_rastpos( ctx );
717 #endif
718    _mesa_init_scissor( ctx );
719    _mesa_init_shader_state( ctx );
720    _mesa_init_stencil( ctx );
721    _mesa_init_transform( ctx );
722    _mesa_init_varray( ctx );
723    _mesa_init_viewport( ctx );
724
725    if (!_mesa_init_texture( ctx ))
726       return GL_FALSE;
727
728 #if FEATURE_texture_s3tc
729    _mesa_init_texture_s3tc( ctx );
730 #endif
731 #if FEATURE_texture_fxt1
732    _mesa_init_texture_fxt1( ctx );
733 #endif
734
735    /* Miscellaneous */
736    ctx->NewState = _NEW_ALL;
737    ctx->ErrorValue = (GLenum) GL_NO_ERROR;
738    ctx->varying_vp_inputs = ~0;
739
740    return GL_TRUE;
741 }
742
743
744 /**
745  * Update default objects in a GL context with respect to shared state.
746  *
747  * \param ctx GL context.
748  *
749  * Removes references to old default objects, (texture objects, program
750  * objects, etc.) and changes to reference those from the current shared
751  * state.
752  */
753 static GLboolean
754 update_default_objects(GLcontext *ctx)
755 {
756    assert(ctx);
757
758    _mesa_update_default_objects_program(ctx);
759    _mesa_update_default_objects_texture(ctx);
760    _mesa_update_default_objects_buffer_objects(ctx);
761
762    return GL_TRUE;
763 }
764
765
766 /**
767  * This is the default function we plug into all dispatch table slots
768  * This helps prevents a segfault when someone calls a GL function without
769  * first checking if the extension's supported.
770  */
771 static int
772 generic_nop(void)
773 {
774    _mesa_warning(NULL, "User called no-op dispatch function (an unsupported extension function?)");
775    return 0;
776 }
777
778
779 /**
780  * Allocate and initialize a new dispatch table.
781  */
782 static struct _glapi_table *
783 alloc_dispatch_table(void)
784 {
785    /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
786     * In practice, this'll be the same for stand-alone Mesa.  But for DRI
787     * Mesa we do this to accomodate different versions of libGL and various
788     * DRI drivers.
789     */
790    GLint numEntries = MAX2(_glapi_get_dispatch_table_size(),
791                            sizeof(struct _glapi_table) / sizeof(_glapi_proc));
792    struct _glapi_table *table =
793       (struct _glapi_table *) _mesa_malloc(numEntries * sizeof(_glapi_proc));
794    if (table) {
795       _glapi_proc *entry = (_glapi_proc *) table;
796       GLint i;
797       for (i = 0; i < numEntries; i++) {
798          entry[i] = (_glapi_proc) generic_nop;
799       }
800    }
801    return table;
802 }
803
804
805 /**
806  * Initialize a GLcontext struct (rendering context).
807  *
808  * This includes allocating all the other structs and arrays which hang off of
809  * the context by pointers.
810  * Note that the driver needs to pass in its dd_function_table here since
811  * we need to at least call driverFunctions->NewTextureObject to create the
812  * default texture objects.
813  * 
814  * Called by _mesa_create_context().
815  *
816  * Performs the imports and exports callback tables initialization, and
817  * miscellaneous one-time initializations. If no shared context is supplied one
818  * is allocated, and increase its reference count.  Setups the GL API dispatch
819  * tables.  Initialize the TNL module. Sets the maximum Z buffer depth.
820  * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
821  * for debug flags.
822  *
823  * \param ctx the context to initialize
824  * \param visual describes the visual attributes for this context
825  * \param share_list points to context to share textures, display lists,
826  *        etc with, or NULL
827  * \param driverFunctions table of device driver functions for this context
828  *        to use
829  * \param driverContext pointer to driver-specific context data
830  */
831 GLboolean
832 _mesa_initialize_context(GLcontext *ctx,
833                          const GLvisual *visual,
834                          GLcontext *share_list,
835                          const struct dd_function_table *driverFunctions,
836                          void *driverContext)
837 {
838    struct gl_shared_state *shared;
839
840    /*ASSERT(driverContext);*/
841    assert(driverFunctions->NewTextureObject);
842    assert(driverFunctions->FreeTexImageData);
843
844    /* misc one-time initializations */
845    one_time_init(ctx);
846
847    ctx->Visual = *visual;
848    ctx->DrawBuffer = NULL;
849    ctx->ReadBuffer = NULL;
850    ctx->WinSysDrawBuffer = NULL;
851    ctx->WinSysReadBuffer = NULL;
852
853    /* Plug in driver functions and context pointer here.
854     * This is important because when we call alloc_shared_state() below
855     * we'll call ctx->Driver.NewTextureObject() to create the default
856     * textures.
857     */
858    ctx->Driver = *driverFunctions;
859    ctx->DriverCtx = driverContext;
860
861    if (share_list) {
862       /* share state with another context */
863       shared = share_list->Shared;
864    }
865    else {
866       /* allocate new, unshared state */
867       shared = _mesa_alloc_shared_state(ctx);
868       if (!shared)
869          return GL_FALSE;
870    }
871
872    _glthread_LOCK_MUTEX(shared->Mutex);
873    ctx->Shared = shared;
874    shared->RefCount++;
875    _glthread_UNLOCK_MUTEX(shared->Mutex);
876
877    if (!init_attrib_groups( ctx )) {
878       _mesa_free_shared_state(ctx, ctx->Shared);
879       return GL_FALSE;
880    }
881
882    /* setup the API dispatch tables */
883    ctx->Exec = alloc_dispatch_table();
884    ctx->Save = alloc_dispatch_table();
885    if (!ctx->Exec || !ctx->Save) {
886       _mesa_free_shared_state(ctx, ctx->Shared);
887       if (ctx->Exec)
888          _mesa_free(ctx->Exec);
889    }
890 #if FEATURE_dispatch
891    _mesa_init_exec_table(ctx->Exec);
892 #endif
893    ctx->CurrentDispatch = ctx->Exec;
894 #if FEATURE_dlist
895    _mesa_init_dlist_table(ctx->Save);
896    _mesa_install_save_vtxfmt( ctx, &ctx->ListState.ListVtxfmt );
897 #endif
898    /* Neutral tnl module stuff */
899    _mesa_init_exec_vtxfmt( ctx ); 
900    ctx->TnlModule.Current = NULL;
901    ctx->TnlModule.SwapCount = 0;
902
903    ctx->FragmentProgram._MaintainTexEnvProgram
904       = (_mesa_getenv("MESA_TEX_PROG") != NULL);
905
906    ctx->VertexProgram._MaintainTnlProgram
907       = (_mesa_getenv("MESA_TNL_PROG") != NULL);
908    if (ctx->VertexProgram._MaintainTnlProgram) {
909       /* this is required... */
910       ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
911    }
912
913 #ifdef FEATURE_extra_context_init
914    _mesa_initialize_context_extra(ctx);
915 #endif
916
917    ctx->FirstTimeCurrent = GL_TRUE;
918
919    return GL_TRUE;
920 }
921
922
923 /**
924  * Allocate and initialize a GLcontext structure.
925  * Note that the driver needs to pass in its dd_function_table here since
926  * we need to at least call driverFunctions->NewTextureObject to initialize
927  * the rendering context.
928  *
929  * \param visual a GLvisual pointer (we copy the struct contents)
930  * \param share_list another context to share display lists with or NULL
931  * \param driverFunctions points to the dd_function_table into which the
932  *        driver has plugged in all its special functions.
933  * \param driverContext points to the device driver's private context state
934  * 
935  * \return pointer to a new __GLcontextRec or NULL if error.
936  */
937 GLcontext *
938 _mesa_create_context(const GLvisual *visual,
939                      GLcontext *share_list,
940                      const struct dd_function_table *driverFunctions,
941                      void *driverContext)
942 {
943    GLcontext *ctx;
944
945    ASSERT(visual);
946    /*ASSERT(driverContext);*/
947
948    ctx = (GLcontext *) _mesa_calloc(sizeof(GLcontext));
949    if (!ctx)
950       return NULL;
951
952    if (_mesa_initialize_context(ctx, visual, share_list,
953                                 driverFunctions, driverContext)) {
954       return ctx;
955    }
956    else {
957       _mesa_free(ctx);
958       return NULL;
959    }
960 }
961
962
963 /**
964  * Free the data associated with the given context.
965  * 
966  * But doesn't free the GLcontext struct itself.
967  *
968  * \sa _mesa_initialize_context() and init_attrib_groups().
969  */
970 void
971 _mesa_free_context_data( GLcontext *ctx )
972 {
973    GLint RefCount;
974
975    if (!_mesa_get_current_context()){
976       /* No current context, but we may need one in order to delete
977        * texture objs, etc.  So temporarily bind the context now.
978        */
979       _mesa_make_current(ctx, NULL, NULL);
980    }
981
982    /* unreference WinSysDraw/Read buffers */
983    _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
984    _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
985    _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
986    _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
987
988    _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
989    _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
990    _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram, NULL);
991
992    _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
993    _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
994    _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
995
996    _mesa_free_attrib_data(ctx);
997    _mesa_free_lighting_data( ctx );
998 #if FEATURE_evaluators
999    _mesa_free_eval_data( ctx );
1000 #endif
1001    _mesa_free_texture_data( ctx );
1002    _mesa_free_matrix_data( ctx );
1003    _mesa_free_viewport_data( ctx );
1004    _mesa_free_colortables_data( ctx );
1005    _mesa_free_program_data(ctx);
1006    _mesa_free_shader_state(ctx);
1007 #if FEATURE_ARB_occlusion_query
1008    _mesa_free_query_data(ctx);
1009 #endif
1010 #if FEATURE_ARB_sync
1011    _mesa_free_sync_data(ctx);
1012 #endif
1013    _mesa_free_varray_data(ctx);
1014
1015    _mesa_delete_array_object(ctx, ctx->Array.DefaultArrayObj);
1016
1017 #if FEATURE_ARB_pixel_buffer_object
1018    _mesa_reference_buffer_object(ctx, &ctx->Pack.BufferObj, NULL);
1019    _mesa_reference_buffer_object(ctx, &ctx->Unpack.BufferObj, NULL);
1020 #endif
1021
1022 #if FEATURE_ARB_vertex_buffer_object
1023    _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
1024    _mesa_reference_buffer_object(ctx, &ctx->Array.ElementArrayBufferObj, NULL);
1025 #endif
1026
1027    /* free dispatch tables */
1028    _mesa_free(ctx->Exec);
1029    _mesa_free(ctx->Save);
1030
1031    /* Shared context state (display lists, textures, etc) */
1032    _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
1033    RefCount = --ctx->Shared->RefCount;
1034    _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
1035    assert(RefCount >= 0);
1036    if (RefCount == 0) {
1037       /* free shared state */
1038       _mesa_free_shared_state( ctx, ctx->Shared );
1039    }
1040
1041    if (ctx->Extensions.String)
1042       _mesa_free((void *) ctx->Extensions.String);
1043
1044    /* unbind the context if it's currently bound */
1045    if (ctx == _mesa_get_current_context()) {
1046       _mesa_make_current(NULL, NULL, NULL);
1047    }
1048 }
1049
1050
1051 /**
1052  * Destroy a GLcontext structure.
1053  *
1054  * \param ctx GL context.
1055  * 
1056  * Calls _mesa_free_context_data() and frees the GLcontext structure itself.
1057  */
1058 void
1059 _mesa_destroy_context( GLcontext *ctx )
1060 {
1061    if (ctx) {
1062       _mesa_free_context_data(ctx);
1063       _mesa_free( (void *) ctx );
1064    }
1065 }
1066
1067
1068 #if _HAVE_FULL_GL
1069 /**
1070  * Copy attribute groups from one context to another.
1071  * 
1072  * \param src source context
1073  * \param dst destination context
1074  * \param mask bitwise OR of GL_*_BIT flags
1075  *
1076  * According to the bits specified in \p mask, copies the corresponding
1077  * attributes from \p src into \p dst.  For many of the attributes a simple \c
1078  * memcpy is not enough due to the existence of internal pointers in their data
1079  * structures.
1080  */
1081 void
1082 _mesa_copy_context( const GLcontext *src, GLcontext *dst, GLuint mask )
1083 {
1084    if (mask & GL_ACCUM_BUFFER_BIT) {
1085       /* OK to memcpy */
1086       dst->Accum = src->Accum;
1087    }
1088    if (mask & GL_COLOR_BUFFER_BIT) {
1089       /* OK to memcpy */
1090       dst->Color = src->Color;
1091    }
1092    if (mask & GL_CURRENT_BIT) {
1093       /* OK to memcpy */
1094       dst->Current = src->Current;
1095    }
1096    if (mask & GL_DEPTH_BUFFER_BIT) {
1097       /* OK to memcpy */
1098       dst->Depth = src->Depth;
1099    }
1100    if (mask & GL_ENABLE_BIT) {
1101       /* no op */
1102    }
1103    if (mask & GL_EVAL_BIT) {
1104       /* OK to memcpy */
1105       dst->Eval = src->Eval;
1106    }
1107    if (mask & GL_FOG_BIT) {
1108       /* OK to memcpy */
1109       dst->Fog = src->Fog;
1110    }
1111    if (mask & GL_HINT_BIT) {
1112       /* OK to memcpy */
1113       dst->Hint = src->Hint;
1114    }
1115    if (mask & GL_LIGHTING_BIT) {
1116       GLuint i;
1117       /* begin with memcpy */
1118       dst->Light = src->Light;
1119       /* fixup linked lists to prevent pointer insanity */
1120       make_empty_list( &(dst->Light.EnabledList) );
1121       for (i = 0; i < MAX_LIGHTS; i++) {
1122          if (dst->Light.Light[i].Enabled) {
1123             insert_at_tail(&(dst->Light.EnabledList), &(dst->Light.Light[i]));
1124          }
1125       }
1126    }
1127    if (mask & GL_LINE_BIT) {
1128       /* OK to memcpy */
1129       dst->Line = src->Line;
1130    }
1131    if (mask & GL_LIST_BIT) {
1132       /* OK to memcpy */
1133       dst->List = src->List;
1134    }
1135    if (mask & GL_PIXEL_MODE_BIT) {
1136       /* OK to memcpy */
1137       dst->Pixel = src->Pixel;
1138    }
1139    if (mask & GL_POINT_BIT) {
1140       /* OK to memcpy */
1141       dst->Point = src->Point;
1142    }
1143    if (mask & GL_POLYGON_BIT) {
1144       /* OK to memcpy */
1145       dst->Polygon = src->Polygon;
1146    }
1147    if (mask & GL_POLYGON_STIPPLE_BIT) {
1148       /* Use loop instead of MEMCPY due to problem with Portland Group's
1149        * C compiler.  Reported by John Stone.
1150        */
1151       GLuint i;
1152       for (i = 0; i < 32; i++) {
1153          dst->PolygonStipple[i] = src->PolygonStipple[i];
1154       }
1155    }
1156    if (mask & GL_SCISSOR_BIT) {
1157       /* OK to memcpy */
1158       dst->Scissor = src->Scissor;
1159    }
1160    if (mask & GL_STENCIL_BUFFER_BIT) {
1161       /* OK to memcpy */
1162       dst->Stencil = src->Stencil;
1163    }
1164    if (mask & GL_TEXTURE_BIT) {
1165       /* Cannot memcpy because of pointers */
1166       _mesa_copy_texture_state(src, dst);
1167    }
1168    if (mask & GL_TRANSFORM_BIT) {
1169       /* OK to memcpy */
1170       dst->Transform = src->Transform;
1171    }
1172    if (mask & GL_VIEWPORT_BIT) {
1173       /* Cannot use memcpy, because of pointers in GLmatrix _WindowMap */
1174       dst->Viewport.X = src->Viewport.X;
1175       dst->Viewport.Y = src->Viewport.Y;
1176       dst->Viewport.Width = src->Viewport.Width;
1177       dst->Viewport.Height = src->Viewport.Height;
1178       dst->Viewport.Near = src->Viewport.Near;
1179       dst->Viewport.Far = src->Viewport.Far;
1180       _math_matrix_copy(&dst->Viewport._WindowMap, &src->Viewport._WindowMap);
1181    }
1182
1183    /* XXX FIXME:  Call callbacks?
1184     */
1185    dst->NewState = _NEW_ALL;
1186 }
1187 #endif
1188
1189
1190 /**
1191  * Check if the given context can render into the given framebuffer
1192  * by checking visual attributes.
1193  *
1194  * Most of these tests could go away because Mesa is now pretty flexible
1195  * in terms of mixing rendering contexts with framebuffers.  As long
1196  * as RGB vs. CI mode agree, we're probably good.
1197  *
1198  * \return GL_TRUE if compatible, GL_FALSE otherwise.
1199  */
1200 static GLboolean 
1201 check_compatible(const GLcontext *ctx, const GLframebuffer *buffer)
1202 {
1203    const GLvisual *ctxvis = &ctx->Visual;
1204    const GLvisual *bufvis = &buffer->Visual;
1205
1206    if (ctxvis == bufvis)
1207       return GL_TRUE;
1208
1209    if (ctxvis->rgbMode != bufvis->rgbMode)
1210       return GL_FALSE;
1211 #if 0
1212    /* disabling this fixes the fgl_glxgears pbuffer demo */
1213    if (ctxvis->doubleBufferMode && !bufvis->doubleBufferMode)
1214       return GL_FALSE;
1215 #endif
1216    if (ctxvis->stereoMode && !bufvis->stereoMode)
1217       return GL_FALSE;
1218    if (ctxvis->haveAccumBuffer && !bufvis->haveAccumBuffer)
1219       return GL_FALSE;
1220    if (ctxvis->haveDepthBuffer && !bufvis->haveDepthBuffer)
1221       return GL_FALSE;
1222    if (ctxvis->haveStencilBuffer && !bufvis->haveStencilBuffer)
1223       return GL_FALSE;
1224    if (ctxvis->redMask && ctxvis->redMask != bufvis->redMask)
1225       return GL_FALSE;
1226    if (ctxvis->greenMask && ctxvis->greenMask != bufvis->greenMask)
1227       return GL_FALSE;
1228    if (ctxvis->blueMask && ctxvis->blueMask != bufvis->blueMask)
1229       return GL_FALSE;
1230 #if 0
1231    /* disabled (see bug 11161) */
1232    if (ctxvis->depthBits && ctxvis->depthBits != bufvis->depthBits)
1233       return GL_FALSE;
1234 #endif
1235    if (ctxvis->stencilBits && ctxvis->stencilBits != bufvis->stencilBits)
1236       return GL_FALSE;
1237
1238    return GL_TRUE;
1239 }
1240
1241
1242 /**
1243  * Do one-time initialization for the given framebuffer.  Specifically,
1244  * ask the driver for the window's current size and update the framebuffer
1245  * object to match.
1246  * Really, the device driver should totally take care of this.
1247  */
1248 static void
1249 initialize_framebuffer_size(GLcontext *ctx, GLframebuffer *fb)
1250 {
1251    GLuint width, height;
1252    if (ctx->Driver.GetBufferSize) {
1253       ctx->Driver.GetBufferSize(fb, &width, &height);
1254       if (ctx->Driver.ResizeBuffers)
1255          ctx->Driver.ResizeBuffers(ctx, fb, width, height);
1256       fb->Initialized = GL_TRUE;
1257    }
1258 }
1259
1260
1261 /**
1262  * Check if the viewport/scissor size has not yet been initialized.
1263  * Initialize the size if the given width and height are non-zero.
1264  */
1265 void
1266 _mesa_check_init_viewport(GLcontext *ctx, GLuint width, GLuint height)
1267 {
1268    if (!ctx->ViewportInitialized && width > 0 && height > 0) {
1269       /* Note: set flag here, before calling _mesa_set_viewport(), to prevent
1270        * potential infinite recursion.
1271        */
1272       ctx->ViewportInitialized = GL_TRUE;
1273       _mesa_set_viewport(ctx, 0, 0, width, height);
1274       _mesa_set_scissor(ctx, 0, 0, width, height);
1275    }
1276 }
1277
1278
1279 /**
1280  * Bind the given context to the given drawBuffer and readBuffer and
1281  * make it the current context for the calling thread.
1282  * We'll render into the drawBuffer and read pixels from the
1283  * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
1284  *
1285  * We check that the context's and framebuffer's visuals are compatible
1286  * and return immediately if they're not.
1287  *
1288  * \param newCtx  the new GL context. If NULL then there will be no current GL
1289  *                context.
1290  * \param drawBuffer  the drawing framebuffer
1291  * \param readBuffer  the reading framebuffer
1292  */
1293 GLboolean
1294 _mesa_make_current( GLcontext *newCtx, GLframebuffer *drawBuffer,
1295                     GLframebuffer *readBuffer )
1296 {
1297    if (MESA_VERBOSE & VERBOSE_API)
1298       _mesa_debug(newCtx, "_mesa_make_current()\n");
1299
1300    /* Check that the context's and framebuffer's visuals are compatible.
1301     */
1302    if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
1303       if (!check_compatible(newCtx, drawBuffer)) {
1304          _mesa_warning(newCtx,
1305               "MakeCurrent: incompatible visuals for context and drawbuffer");
1306          return GL_FALSE;
1307       }
1308    }
1309    if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
1310       if (!check_compatible(newCtx, readBuffer)) {
1311          _mesa_warning(newCtx,
1312               "MakeCurrent: incompatible visuals for context and readbuffer");
1313          return GL_FALSE;
1314       }
1315    }
1316
1317    /* We used to call _glapi_check_multithread() here.  Now do it in drivers */
1318    _glapi_set_context((void *) newCtx);
1319    ASSERT(_mesa_get_current_context() == newCtx);
1320
1321    if (!newCtx) {
1322       _glapi_set_dispatch(NULL);  /* none current */
1323    }
1324    else {
1325       _glapi_set_dispatch(newCtx->CurrentDispatch);
1326
1327       if (drawBuffer && readBuffer) {
1328          /* TODO: check if newCtx and buffer's visual match??? */
1329
1330          ASSERT(drawBuffer->Name == 0);
1331          ASSERT(readBuffer->Name == 0);
1332          _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
1333          _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
1334
1335          /*
1336           * Only set the context's Draw/ReadBuffer fields if they're NULL
1337           * or not bound to a user-created FBO.
1338           */
1339          if (!newCtx->DrawBuffer || newCtx->DrawBuffer->Name == 0) {
1340             /* KW: merge conflict here, revisit. 
1341              */
1342             /* fix up the fb fields - these will end up wrong otherwise
1343              * if the DRIdrawable changes, and everything relies on them.
1344              * This is a bit messy (same as needed in _mesa_BindFramebufferEXT)
1345              */
1346             unsigned int i;
1347             GLenum buffers[MAX_DRAW_BUFFERS];
1348
1349             _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
1350
1351             for(i = 0; i < newCtx->Const.MaxDrawBuffers; i++) {
1352                buffers[i] = newCtx->Color.DrawBuffer[i];
1353             }
1354
1355             _mesa_drawbuffers(newCtx, newCtx->Const.MaxDrawBuffers, buffers, NULL);
1356          }
1357          if (!newCtx->ReadBuffer || newCtx->ReadBuffer->Name == 0) {
1358             _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
1359          }
1360
1361          /* XXX only set this flag if we're really changing the draw/read
1362           * framebuffer bindings.
1363           */
1364          newCtx->NewState |= _NEW_BUFFERS;
1365
1366 #if 1
1367          /* We want to get rid of these lines: */
1368
1369 #if _HAVE_FULL_GL
1370          if (!drawBuffer->Initialized) {
1371             initialize_framebuffer_size(newCtx, drawBuffer);
1372          }
1373          if (readBuffer != drawBuffer && !readBuffer->Initialized) {
1374             initialize_framebuffer_size(newCtx, readBuffer);
1375          }
1376
1377          _mesa_resizebuffers(newCtx);
1378 #endif
1379
1380 #else
1381          /* We want the drawBuffer and readBuffer to be initialized by
1382           * the driver.
1383           * This generally means the Width and Height match the actual
1384           * window size and the renderbuffers (both hardware and software
1385           * based) are allocated to match.  The later can generally be
1386           * done with a call to _mesa_resize_framebuffer().
1387           *
1388           * It's theoretically possible for a buffer to have zero width
1389           * or height, but for now, assert check that the driver did what's
1390           * expected of it.
1391           */
1392          ASSERT(drawBuffer->Width > 0);
1393          ASSERT(drawBuffer->Height > 0);
1394 #endif
1395
1396          if (drawBuffer) {
1397             _mesa_check_init_viewport(newCtx,
1398                                       drawBuffer->Width, drawBuffer->Height);
1399          }
1400       }
1401
1402       if (newCtx->FirstTimeCurrent) {
1403          check_context_limits(newCtx);
1404
1405          /* We can use this to help debug user's problems.  Tell them to set
1406           * the MESA_INFO env variable before running their app.  Then the
1407           * first time each context is made current we'll print some useful
1408           * information.
1409           */
1410          if (_mesa_getenv("MESA_INFO")) {
1411             _mesa_print_info();
1412          }
1413
1414          newCtx->FirstTimeCurrent = GL_FALSE;
1415       }
1416    }
1417    
1418    return GL_TRUE;
1419 }
1420
1421
1422 /**
1423  * Make context 'ctx' share the display lists, textures and programs
1424  * that are associated with 'ctxToShare'.
1425  * Any display lists, textures or programs associated with 'ctx' will
1426  * be deleted if nobody else is sharing them.
1427  */
1428 GLboolean
1429 _mesa_share_state(GLcontext *ctx, GLcontext *ctxToShare)
1430 {
1431    if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
1432       struct gl_shared_state *oldSharedState = ctx->Shared;
1433       GLint RefCount;
1434
1435       ctx->Shared = ctxToShare->Shared;
1436       
1437       _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
1438       ctx->Shared->RefCount++;
1439       _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
1440
1441       update_default_objects(ctx);
1442
1443       _glthread_LOCK_MUTEX(oldSharedState->Mutex);
1444       RefCount = --oldSharedState->RefCount;
1445       _glthread_UNLOCK_MUTEX(oldSharedState->Mutex);
1446
1447       if (RefCount == 0) {
1448          _mesa_free_shared_state(ctx, oldSharedState);
1449       }
1450
1451       return GL_TRUE;
1452    }
1453    else {
1454       return GL_FALSE;
1455    }
1456 }
1457
1458
1459
1460 /**
1461  * \return pointer to the current GL context for this thread.
1462  * 
1463  * Calls _glapi_get_context(). This isn't the fastest way to get the current
1464  * context.  If you need speed, see the #GET_CURRENT_CONTEXT macro in
1465  * context.h.
1466  */
1467 GLcontext *
1468 _mesa_get_current_context( void )
1469 {
1470    return (GLcontext *) _glapi_get_context();
1471 }
1472
1473
1474 /**
1475  * Get context's current API dispatch table.
1476  *
1477  * It'll either be the immediate-mode execute dispatcher or the display list
1478  * compile dispatcher.
1479  * 
1480  * \param ctx GL context.
1481  *
1482  * \return pointer to dispatch_table.
1483  *
1484  * Simply returns __GLcontextRec::CurrentDispatch.
1485  */
1486 struct _glapi_table *
1487 _mesa_get_dispatch(GLcontext *ctx)
1488 {
1489    return ctx->CurrentDispatch;
1490 }
1491
1492 /*@}*/
1493
1494
1495 /**********************************************************************/
1496 /** \name Miscellaneous functions                                     */
1497 /**********************************************************************/
1498 /*@{*/
1499
1500 /**
1501  * Record an error.
1502  *
1503  * \param ctx GL context.
1504  * \param error error code.
1505  * 
1506  * Records the given error code and call the driver's dd_function_table::Error
1507  * function if defined.
1508  *
1509  * \sa
1510  * This is called via _mesa_error().
1511  */
1512 void
1513 _mesa_record_error(GLcontext *ctx, GLenum error)
1514 {
1515    if (!ctx)
1516       return;
1517
1518    if (ctx->ErrorValue == GL_NO_ERROR) {
1519       ctx->ErrorValue = error;
1520    }
1521
1522    /* Call device driver's error handler, if any.  This is used on the Mac. */
1523    if (ctx->Driver.Error) {
1524       ctx->Driver.Error(ctx);
1525    }
1526 }
1527
1528
1529 /**
1530  * Execute glFinish().
1531  *
1532  * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1533  * dd_function_table::Finish driver callback, if not NULL.
1534  */
1535 void GLAPIENTRY
1536 _mesa_Finish(void)
1537 {
1538    GET_CURRENT_CONTEXT(ctx);
1539    ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
1540    FLUSH_CURRENT( ctx, 0 );
1541    if (ctx->Driver.Finish) {
1542       ctx->Driver.Finish(ctx);
1543    }
1544 }
1545
1546
1547 /**
1548  * Execute glFlush().
1549  *
1550  * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1551  * dd_function_table::Flush driver callback, if not NULL.
1552  */
1553 void GLAPIENTRY
1554 _mesa_Flush(void)
1555 {
1556    GET_CURRENT_CONTEXT(ctx);
1557    ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
1558    FLUSH_CURRENT( ctx, 0 );
1559    if (ctx->Driver.Flush) {
1560       ctx->Driver.Flush(ctx);
1561    }
1562 }
1563
1564
1565 /**
1566  * Set mvp_with_dp4 flag.  If a driver has a preference for DP4 over
1567  * MUL/MAD, or vice versa, call this function to register that.
1568  * Otherwise we default to MUL/MAD.
1569  */
1570 void
1571 _mesa_set_mvp_with_dp4( GLcontext *ctx,
1572                         GLboolean flag )
1573 {
1574    ctx->mvp_with_dp4 = flag;
1575 }
1576
1577
1578
1579 /**
1580  * Prior to drawing anything with glBegin, glDrawArrays, etc. this function
1581  * is called to see if it's valid to render.  This involves checking that
1582  * the current shader is valid and the framebuffer is complete.
1583  * If an error is detected it'll be recorded here.
1584  * \return GL_TRUE if OK to render, GL_FALSE if not
1585  */
1586 GLboolean
1587 _mesa_valid_to_render(GLcontext *ctx, const char *where)
1588 {
1589    if (ctx->Shader.CurrentProgram) {
1590       /* using shaders */
1591       if (!ctx->Shader.CurrentProgram->LinkStatus) {
1592          _mesa_error(ctx, GL_INVALID_OPERATION,
1593                      "%s(shader not linked), where");
1594          return GL_FALSE;
1595       }
1596 #if 0 /* not normally enabled */
1597       {
1598          char errMsg[100];
1599          if (!_mesa_validate_shader_program(ctx, ctx->Shader.CurrentProgram,
1600                                             errMsg)) {
1601             _mesa_warning(ctx, "Shader program %u is invalid: %s",
1602                           ctx->Shader.CurrentProgram->Name, errMsg);
1603          }
1604       }
1605 #endif
1606    }
1607    else {
1608       if (ctx->VertexProgram.Enabled && !ctx->VertexProgram._Enabled) {
1609          _mesa_error(ctx, GL_INVALID_OPERATION,
1610                      "%s(vertex program not valid)", where);
1611          return GL_FALSE;
1612       }
1613       if (ctx->FragmentProgram.Enabled && !ctx->FragmentProgram._Enabled) {
1614          _mesa_error(ctx, GL_INVALID_OPERATION,
1615                      "%s(fragment program not valid)", where);
1616          return GL_FALSE;
1617       }
1618    }
1619
1620    if (ctx->DrawBuffer->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
1621       _mesa_error(ctx, GL_INVALID_FRAMEBUFFER_OPERATION_EXT,
1622                   "%s(incomplete framebuffer)", where);
1623       return GL_FALSE;
1624    }
1625
1626 #ifdef DEBUG
1627    if (ctx->Shader.Flags & GLSL_LOG) {
1628       struct gl_shader_program *shProg = ctx->Shader.CurrentProgram;
1629       if (shProg) {
1630          if (!shProg->_Used) {
1631             /* This is the first time this shader is being used.
1632              * Append shader's constants/uniforms to log file.
1633              */
1634             GLuint i;
1635             for (i = 0; i < shProg->NumShaders; i++) {
1636                struct gl_shader *sh = shProg->Shaders[i];
1637                if (sh->Type == GL_VERTEX_SHADER) {
1638                   _mesa_append_uniforms_to_file(sh,
1639                                                 &shProg->VertexProgram->Base);
1640                }
1641                else if (sh->Type == GL_FRAGMENT_SHADER) {
1642                   _mesa_append_uniforms_to_file(sh,
1643                                                 &shProg->FragmentProgram->Base);
1644                }
1645             }
1646             shProg->_Used = GL_TRUE;
1647          }
1648       }
1649    }
1650 #endif
1651
1652    return GL_TRUE;
1653 }
1654
1655
1656 /*@}*/