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