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