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