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