fbobject.c revision a8bb7a65
1/*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 1999-2008  Brian Paul   All Rights Reserved.
5 * Copyright (C) 1999-2009  VMware, Inc.  All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 * OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26
27/*
28 * GL_EXT/ARB_framebuffer_object extensions
29 *
30 * Authors:
31 *   Brian Paul
32 */
33
34#include <stdbool.h>
35
36#include "buffers.h"
37#include "context.h"
38#include "debug_output.h"
39#include "enums.h"
40#include "fbobject.h"
41#include "formats.h"
42#include "framebuffer.h"
43#include "glformats.h"
44#include "hash.h"
45#include "macros.h"
46#include "multisample.h"
47#include "mtypes.h"
48#include "renderbuffer.h"
49#include "state.h"
50#include "teximage.h"
51#include "texobj.h"
52
53
54/**
55 * Notes:
56 *
57 * None of the GL_EXT_framebuffer_object functions are compiled into
58 * display lists.
59 */
60
61
62
63/*
64 * When glGenRender/FramebuffersEXT() is called we insert pointers to
65 * these placeholder objects into the hash table.
66 * Later, when the object ID is first bound, we replace the placeholder
67 * with the real frame/renderbuffer.
68 */
69static struct gl_framebuffer DummyFramebuffer;
70static struct gl_renderbuffer DummyRenderbuffer;
71
72/* We bind this framebuffer when applications pass a NULL
73 * drawable/surface in make current. */
74static struct gl_framebuffer IncompleteFramebuffer;
75
76
77static void
78delete_dummy_renderbuffer(struct gl_context *ctx, struct gl_renderbuffer *rb)
79{
80   /* no op */
81}
82
83static void
84delete_dummy_framebuffer(struct gl_framebuffer *fb)
85{
86   /* no op */
87}
88
89
90void
91_mesa_init_fbobjects(struct gl_context *ctx)
92{
93   simple_mtx_init(&DummyFramebuffer.Mutex, mtx_plain);
94   simple_mtx_init(&DummyRenderbuffer.Mutex, mtx_plain);
95   simple_mtx_init(&IncompleteFramebuffer.Mutex, mtx_plain);
96   DummyFramebuffer.Delete = delete_dummy_framebuffer;
97   DummyRenderbuffer.Delete = delete_dummy_renderbuffer;
98   IncompleteFramebuffer.Delete = delete_dummy_framebuffer;
99}
100
101struct gl_framebuffer *
102_mesa_get_incomplete_framebuffer(void)
103{
104   return &IncompleteFramebuffer;
105}
106
107/**
108 * Helper routine for getting a gl_renderbuffer.
109 */
110struct gl_renderbuffer *
111_mesa_lookup_renderbuffer(struct gl_context *ctx, GLuint id)
112{
113   struct gl_renderbuffer *rb;
114
115   if (id == 0)
116      return NULL;
117
118   rb = (struct gl_renderbuffer *)
119      _mesa_HashLookup(ctx->Shared->RenderBuffers, id);
120   return rb;
121}
122
123
124/**
125 * A convenience function for direct state access that throws
126 * GL_INVALID_OPERATION if the renderbuffer doesn't exist.
127 */
128struct gl_renderbuffer *
129_mesa_lookup_renderbuffer_err(struct gl_context *ctx, GLuint id,
130                              const char *func)
131{
132   struct gl_renderbuffer *rb;
133
134   rb = _mesa_lookup_renderbuffer(ctx, id);
135   if (!rb || rb == &DummyRenderbuffer) {
136      _mesa_error(ctx, GL_INVALID_OPERATION,
137                  "%s(non-existent renderbuffer %u)", func, id);
138      return NULL;
139   }
140
141   return rb;
142}
143
144
145/**
146 * Helper routine for getting a gl_framebuffer.
147 */
148struct gl_framebuffer *
149_mesa_lookup_framebuffer(struct gl_context *ctx, GLuint id)
150{
151   struct gl_framebuffer *fb;
152
153   if (id == 0)
154      return NULL;
155
156   fb = (struct gl_framebuffer *)
157      _mesa_HashLookup(ctx->Shared->FrameBuffers, id);
158   return fb;
159}
160
161
162/**
163 * A convenience function for direct state access that throws
164 * GL_INVALID_OPERATION if the framebuffer doesn't exist.
165 */
166struct gl_framebuffer *
167_mesa_lookup_framebuffer_err(struct gl_context *ctx, GLuint id,
168                             const char *func)
169{
170   struct gl_framebuffer *fb;
171
172   fb = _mesa_lookup_framebuffer(ctx, id);
173   if (!fb || fb == &DummyFramebuffer) {
174      _mesa_error(ctx, GL_INVALID_OPERATION,
175                  "%s(non-existent framebuffer %u)", func, id);
176      return NULL;
177   }
178
179   return fb;
180}
181
182
183/**
184 * Mark the given framebuffer as invalid.  This will force the
185 * test for framebuffer completeness to be done before the framebuffer
186 * is used.
187 */
188static void
189invalidate_framebuffer(struct gl_framebuffer *fb)
190{
191   fb->_Status = 0; /* "indeterminate" */
192}
193
194
195/**
196 * Return the gl_framebuffer object which corresponds to the given
197 * framebuffer target, such as GL_DRAW_FRAMEBUFFER.
198 * Check support for GL_EXT_framebuffer_blit to determine if certain
199 * targets are legal.
200 * \return gl_framebuffer pointer or NULL if target is illegal
201 */
202static struct gl_framebuffer *
203get_framebuffer_target(struct gl_context *ctx, GLenum target)
204{
205   bool have_fb_blit = _mesa_is_gles3(ctx) || _mesa_is_desktop_gl(ctx);
206   switch (target) {
207   case GL_DRAW_FRAMEBUFFER:
208      return have_fb_blit ? ctx->DrawBuffer : NULL;
209   case GL_READ_FRAMEBUFFER:
210      return have_fb_blit ? ctx->ReadBuffer : NULL;
211   case GL_FRAMEBUFFER_EXT:
212      return ctx->DrawBuffer;
213   default:
214      return NULL;
215   }
216}
217
218
219/**
220 * Given a GL_*_ATTACHMENTn token, return a pointer to the corresponding
221 * gl_renderbuffer_attachment object.
222 * This function is only used for user-created FB objects, not the
223 * default / window-system FB object.
224 * If \p attachment is GL_DEPTH_STENCIL_ATTACHMENT, return a pointer to
225 * the depth buffer attachment point.
226 * Returns if the attachment is a GL_COLOR_ATTACHMENTm_EXT on
227 * is_color_attachment, because several callers would return different errors
228 * if they don't find the attachment.
229 */
230static struct gl_renderbuffer_attachment *
231get_attachment(struct gl_context *ctx, struct gl_framebuffer *fb,
232               GLenum attachment, bool *is_color_attachment)
233{
234   GLuint i;
235
236   assert(_mesa_is_user_fbo(fb));
237
238   if (is_color_attachment)
239      *is_color_attachment = false;
240
241   switch (attachment) {
242   case GL_COLOR_ATTACHMENT0_EXT:
243   case GL_COLOR_ATTACHMENT1_EXT:
244   case GL_COLOR_ATTACHMENT2_EXT:
245   case GL_COLOR_ATTACHMENT3_EXT:
246   case GL_COLOR_ATTACHMENT4_EXT:
247   case GL_COLOR_ATTACHMENT5_EXT:
248   case GL_COLOR_ATTACHMENT6_EXT:
249   case GL_COLOR_ATTACHMENT7_EXT:
250   case GL_COLOR_ATTACHMENT8_EXT:
251   case GL_COLOR_ATTACHMENT9_EXT:
252   case GL_COLOR_ATTACHMENT10_EXT:
253   case GL_COLOR_ATTACHMENT11_EXT:
254   case GL_COLOR_ATTACHMENT12_EXT:
255   case GL_COLOR_ATTACHMENT13_EXT:
256   case GL_COLOR_ATTACHMENT14_EXT:
257   case GL_COLOR_ATTACHMENT15_EXT:
258      if (is_color_attachment)
259         *is_color_attachment = true;
260      /* Only OpenGL ES 1.x forbids color attachments other than
261       * GL_COLOR_ATTACHMENT0.  For all other APIs the limit set by the
262       * hardware is used.
263       */
264      i = attachment - GL_COLOR_ATTACHMENT0_EXT;
265      if (i >= ctx->Const.MaxColorAttachments
266          || (i > 0 && ctx->API == API_OPENGLES)) {
267         return NULL;
268      }
269      return &fb->Attachment[BUFFER_COLOR0 + i];
270   case GL_DEPTH_STENCIL_ATTACHMENT:
271      if (!_mesa_is_desktop_gl(ctx) && !_mesa_is_gles3(ctx))
272         return NULL;
273      /* fall-through */
274   case GL_DEPTH_ATTACHMENT_EXT:
275      return &fb->Attachment[BUFFER_DEPTH];
276   case GL_STENCIL_ATTACHMENT_EXT:
277      return &fb->Attachment[BUFFER_STENCIL];
278   default:
279      return NULL;
280   }
281}
282
283
284/**
285 * As above, but only used for getting attachments of the default /
286 * window-system framebuffer (not user-created framebuffer objects).
287 */
288static struct gl_renderbuffer_attachment *
289get_fb0_attachment(struct gl_context *ctx, struct gl_framebuffer *fb,
290                   GLenum attachment)
291{
292   assert(_mesa_is_winsys_fbo(fb));
293
294   if (_mesa_is_gles3(ctx)) {
295      assert(attachment == GL_BACK ||
296             attachment == GL_DEPTH ||
297             attachment == GL_STENCIL);
298      switch (attachment) {
299      case GL_BACK:
300         /* Since there is no stereo rendering in ES 3.0, only return the
301          * LEFT bits.
302          */
303         if (ctx->DrawBuffer->Visual.doubleBufferMode)
304            return &fb->Attachment[BUFFER_BACK_LEFT];
305         return &fb->Attachment[BUFFER_FRONT_LEFT];
306      case GL_DEPTH:
307         return &fb->Attachment[BUFFER_DEPTH];
308      case GL_STENCIL:
309         return &fb->Attachment[BUFFER_STENCIL];
310      }
311   }
312
313   switch (attachment) {
314   case GL_FRONT_LEFT:
315      /* Front buffers can be allocated on the first use, but
316       * glGetFramebufferAttachmentParameteriv must work even if that
317       * allocation hasn't happened yet. In such case, use the back buffer,
318       * which should be the same.
319       */
320      if (fb->Attachment[BUFFER_FRONT_LEFT].Type == GL_NONE)
321         return &fb->Attachment[BUFFER_BACK_LEFT];
322      else
323         return &fb->Attachment[BUFFER_FRONT_LEFT];
324   case GL_FRONT_RIGHT:
325      /* Same as above. */
326      if (fb->Attachment[BUFFER_FRONT_RIGHT].Type == GL_NONE)
327         return &fb->Attachment[BUFFER_BACK_RIGHT];
328      else
329         return &fb->Attachment[BUFFER_FRONT_RIGHT];
330   case GL_BACK_LEFT:
331      return &fb->Attachment[BUFFER_BACK_LEFT];
332   case GL_BACK_RIGHT:
333      return &fb->Attachment[BUFFER_BACK_RIGHT];
334   case GL_BACK:
335      /* The ARB_ES3_1_compatibility spec says:
336       *
337       *    "Since this command can only query a single framebuffer
338       *     attachment, BACK is equivalent to BACK_LEFT."
339       */
340      if (ctx->Extensions.ARB_ES3_1_compatibility)
341         return &fb->Attachment[BUFFER_BACK_LEFT];
342      return NULL;
343   case GL_AUX0:
344      if (fb->Visual.numAuxBuffers == 1) {
345         return &fb->Attachment[BUFFER_AUX0];
346      }
347      return NULL;
348
349   /* Page 336 (page 352 of the PDF) of the OpenGL 3.0 spec says:
350    *
351    *     "If the default framebuffer is bound to target, then attachment must
352    *     be one of FRONT LEFT, FRONT RIGHT, BACK LEFT, BACK RIGHT, or AUXi,
353    *     identifying a color buffer; DEPTH, identifying the depth buffer; or
354    *     STENCIL, identifying the stencil buffer."
355    *
356    * Revision #34 of the ARB_framebuffer_object spec has essentially the same
357    * language.  However, revision #33 of the ARB_framebuffer_object spec
358    * says:
359    *
360    *     "If the default framebuffer is bound to <target>, then <attachment>
361    *     must be one of FRONT_LEFT, FRONT_RIGHT, BACK_LEFT, BACK_RIGHT, AUXi,
362    *     DEPTH_BUFFER, or STENCIL_BUFFER, identifying a color buffer, the
363    *     depth buffer, or the stencil buffer, and <pname> may be
364    *     FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE or
365    *     FRAMEBUFFER_ATTACHMENT_OBJECT_NAME."
366    *
367    * The enum values for DEPTH_BUFFER and STENCIL_BUFFER have been removed
368    * from glext.h, so shipping apps should not use those values.
369    *
370    * Note that neither EXT_framebuffer_object nor OES_framebuffer_object
371    * support queries of the window system FBO.
372    */
373   case GL_DEPTH:
374      return &fb->Attachment[BUFFER_DEPTH];
375   case GL_STENCIL:
376      return &fb->Attachment[BUFFER_STENCIL];
377   default:
378      return NULL;
379   }
380}
381
382
383
384/**
385 * Remove any texture or renderbuffer attached to the given attachment
386 * point.  Update reference counts, etc.
387 */
388static void
389remove_attachment(struct gl_context *ctx,
390                  struct gl_renderbuffer_attachment *att)
391{
392   struct gl_renderbuffer *rb = att->Renderbuffer;
393
394   /* tell driver that we're done rendering to this texture. */
395   if (rb && rb->NeedsFinishRenderTexture)
396      ctx->Driver.FinishRenderTexture(ctx, rb);
397
398   if (att->Type == GL_TEXTURE) {
399      assert(att->Texture);
400      _mesa_reference_texobj(&att->Texture, NULL); /* unbind */
401      assert(!att->Texture);
402   }
403   if (att->Type == GL_TEXTURE || att->Type == GL_RENDERBUFFER_EXT) {
404      assert(!att->Texture);
405      _mesa_reference_renderbuffer(&att->Renderbuffer, NULL); /* unbind */
406      assert(!att->Renderbuffer);
407   }
408   att->Type = GL_NONE;
409   att->Complete = GL_TRUE;
410}
411
412/**
413 * Verify a couple error conditions that will lead to an incomplete FBO and
414 * may cause problems for the driver's RenderTexture path.
415 */
416static bool
417driver_RenderTexture_is_safe(const struct gl_renderbuffer_attachment *att)
418{
419   const struct gl_texture_image *const texImage =
420      att->Texture->Image[att->CubeMapFace][att->TextureLevel];
421
422   if (!texImage ||
423       texImage->Width == 0 || texImage->Height == 0 || texImage->Depth == 0)
424      return false;
425
426   if ((texImage->TexObject->Target == GL_TEXTURE_1D_ARRAY
427        && att->Zoffset >= texImage->Height)
428       || (texImage->TexObject->Target != GL_TEXTURE_1D_ARRAY
429           && att->Zoffset >= texImage->Depth))
430      return false;
431
432   return true;
433}
434
435/**
436 * Create a renderbuffer which will be set up by the driver to wrap the
437 * texture image slice.
438 *
439 * By using a gl_renderbuffer (like user-allocated renderbuffers), drivers get
440 * to share most of their framebuffer rendering code between winsys,
441 * renderbuffer, and texture attachments.
442 *
443 * The allocated renderbuffer uses a non-zero Name so that drivers can check
444 * it for determining vertical orientation, but we use ~0 to make it fairly
445 * unambiguous with actual user (non-texture) renderbuffers.
446 */
447void
448_mesa_update_texture_renderbuffer(struct gl_context *ctx,
449                                  struct gl_framebuffer *fb,
450                                  struct gl_renderbuffer_attachment *att)
451{
452   struct gl_texture_image *texImage;
453   struct gl_renderbuffer *rb;
454
455   texImage = att->Texture->Image[att->CubeMapFace][att->TextureLevel];
456
457   rb = att->Renderbuffer;
458   if (!rb) {
459      rb = ctx->Driver.NewRenderbuffer(ctx, ~0);
460      if (!rb) {
461         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glFramebufferTexture()");
462         return;
463      }
464      att->Renderbuffer = rb;
465
466      /* This can't get called on a texture renderbuffer, so set it to NULL
467       * for clarity compared to user renderbuffers.
468       */
469      rb->AllocStorage = NULL;
470
471      rb->NeedsFinishRenderTexture = ctx->Driver.FinishRenderTexture != NULL;
472   }
473
474   if (!texImage)
475      return;
476
477   rb->_BaseFormat = texImage->_BaseFormat;
478   rb->Format = texImage->TexFormat;
479   rb->InternalFormat = texImage->InternalFormat;
480   rb->Width = texImage->Width2;
481   rb->Height = texImage->Height2;
482   rb->Depth = texImage->Depth2;
483   rb->NumSamples = texImage->NumSamples;
484   rb->NumStorageSamples = texImage->NumSamples;
485   rb->TexImage = texImage;
486
487   if (driver_RenderTexture_is_safe(att))
488      ctx->Driver.RenderTexture(ctx, fb, att);
489}
490
491/**
492 * Bind a texture object to an attachment point.
493 * The previous binding, if any, will be removed first.
494 */
495static void
496set_texture_attachment(struct gl_context *ctx,
497                       struct gl_framebuffer *fb,
498                       struct gl_renderbuffer_attachment *att,
499                       struct gl_texture_object *texObj,
500                       GLenum texTarget, GLuint level, GLsizei samples,
501                       GLuint layer, GLboolean layered)
502{
503   struct gl_renderbuffer *rb = att->Renderbuffer;
504
505   if (rb && rb->NeedsFinishRenderTexture)
506      ctx->Driver.FinishRenderTexture(ctx, rb);
507
508   if (att->Texture == texObj) {
509      /* re-attaching same texture */
510      assert(att->Type == GL_TEXTURE);
511   }
512   else {
513      /* new attachment */
514      remove_attachment(ctx, att);
515      att->Type = GL_TEXTURE;
516      assert(!att->Texture);
517      _mesa_reference_texobj(&att->Texture, texObj);
518   }
519   invalidate_framebuffer(fb);
520
521   /* always update these fields */
522   att->TextureLevel = level;
523   att->NumSamples = samples;
524   att->CubeMapFace = _mesa_tex_target_to_face(texTarget);
525   att->Zoffset = layer;
526   att->Layered = layered;
527   att->Complete = GL_FALSE;
528
529   _mesa_update_texture_renderbuffer(ctx, fb, att);
530}
531
532
533/**
534 * Bind a renderbuffer to an attachment point.
535 * The previous binding, if any, will be removed first.
536 */
537static void
538set_renderbuffer_attachment(struct gl_context *ctx,
539                            struct gl_renderbuffer_attachment *att,
540                            struct gl_renderbuffer *rb)
541{
542   /* XXX check if re-doing same attachment, exit early */
543   remove_attachment(ctx, att);
544   att->Type = GL_RENDERBUFFER_EXT;
545   att->Texture = NULL; /* just to be safe */
546   att->Layered = GL_FALSE;
547   att->Complete = GL_FALSE;
548   _mesa_reference_renderbuffer(&att->Renderbuffer, rb);
549}
550
551
552/**
553 * Fallback for ctx->Driver.FramebufferRenderbuffer()
554 * Attach a renderbuffer object to a framebuffer object.
555 */
556void
557_mesa_FramebufferRenderbuffer_sw(struct gl_context *ctx,
558                                 struct gl_framebuffer *fb,
559                                 GLenum attachment,
560                                 struct gl_renderbuffer *rb)
561{
562   struct gl_renderbuffer_attachment *att;
563
564   simple_mtx_lock(&fb->Mutex);
565
566   att = get_attachment(ctx, fb, attachment, NULL);
567   assert(att);
568   if (rb) {
569      set_renderbuffer_attachment(ctx, att, rb);
570      if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) {
571         /* do stencil attachment here (depth already done above) */
572         att = get_attachment(ctx, fb, GL_STENCIL_ATTACHMENT_EXT, NULL);
573         assert(att);
574         set_renderbuffer_attachment(ctx, att, rb);
575      }
576      rb->AttachedAnytime = GL_TRUE;
577   }
578   else {
579      remove_attachment(ctx, att);
580      if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) {
581         /* detach stencil (depth was detached above) */
582         att = get_attachment(ctx, fb, GL_STENCIL_ATTACHMENT_EXT, NULL);
583         assert(att);
584         remove_attachment(ctx, att);
585      }
586   }
587
588   invalidate_framebuffer(fb);
589
590   simple_mtx_unlock(&fb->Mutex);
591}
592
593
594/**
595 * Fallback for ctx->Driver.ValidateFramebuffer()
596 * Check if the renderbuffer's formats are supported by the software
597 * renderer.
598 * Drivers should probably override this.
599 */
600void
601_mesa_validate_framebuffer(struct gl_context *ctx, struct gl_framebuffer *fb)
602{
603   gl_buffer_index buf;
604   for (buf = 0; buf < BUFFER_COUNT; buf++) {
605      const struct gl_renderbuffer *rb = fb->Attachment[buf].Renderbuffer;
606      if (rb) {
607         switch (rb->_BaseFormat) {
608         case GL_ALPHA:
609         case GL_LUMINANCE_ALPHA:
610         case GL_LUMINANCE:
611         case GL_INTENSITY:
612         case GL_RED:
613         case GL_RG:
614            fb->_Status = GL_FRAMEBUFFER_UNSUPPORTED;
615            return;
616
617         default:
618            switch (rb->Format) {
619            /* XXX This list is likely incomplete. */
620            case MESA_FORMAT_R9G9B9E5_FLOAT:
621               fb->_Status = GL_FRAMEBUFFER_UNSUPPORTED;
622               return;
623            default:;
624               /* render buffer format is supported by software rendering */
625            }
626         }
627      }
628   }
629}
630
631
632/**
633 * Return true if the framebuffer has a combined depth/stencil
634 * renderbuffer attached.
635 */
636GLboolean
637_mesa_has_depthstencil_combined(const struct gl_framebuffer *fb)
638{
639   const struct gl_renderbuffer_attachment *depth =
640         &fb->Attachment[BUFFER_DEPTH];
641   const struct gl_renderbuffer_attachment *stencil =
642         &fb->Attachment[BUFFER_STENCIL];
643
644   if (depth->Type == stencil->Type) {
645      if (depth->Type == GL_RENDERBUFFER_EXT &&
646          depth->Renderbuffer == stencil->Renderbuffer)
647         return GL_TRUE;
648
649      if (depth->Type == GL_TEXTURE &&
650          depth->Texture == stencil->Texture)
651         return GL_TRUE;
652   }
653
654   return GL_FALSE;
655}
656
657
658/**
659 * For debug only.
660 */
661static void
662att_incomplete(const char *msg)
663{
664   if (MESA_DEBUG_FLAGS & DEBUG_INCOMPLETE_FBO) {
665      _mesa_debug(NULL, "attachment incomplete: %s\n", msg);
666   }
667}
668
669
670/**
671 * For debug only.
672 */
673static void
674fbo_incomplete(struct gl_context *ctx, const char *msg, int index)
675{
676   static GLuint msg_id;
677
678   _mesa_gl_debugf(ctx, &msg_id,
679                   MESA_DEBUG_SOURCE_API,
680                   MESA_DEBUG_TYPE_OTHER,
681                   MESA_DEBUG_SEVERITY_MEDIUM,
682                   "FBO incomplete: %s [%d]\n", msg, index);
683
684   if (MESA_DEBUG_FLAGS & DEBUG_INCOMPLETE_FBO) {
685      _mesa_debug(NULL, "FBO Incomplete: %s [%d]\n", msg, index);
686   }
687}
688
689
690/**
691 * Is the given base format a legal format for a color renderbuffer?
692 */
693GLboolean
694_mesa_is_legal_color_format(const struct gl_context *ctx, GLenum baseFormat)
695{
696   switch (baseFormat) {
697   case GL_RGB:
698   case GL_RGBA:
699      return GL_TRUE;
700   case GL_LUMINANCE:
701   case GL_LUMINANCE_ALPHA:
702   case GL_INTENSITY:
703   case GL_ALPHA:
704      return ctx->API == API_OPENGL_COMPAT &&
705             ctx->Extensions.ARB_framebuffer_object;
706   case GL_RED:
707   case GL_RG:
708      return ctx->Extensions.ARB_texture_rg;
709   default:
710      return GL_FALSE;
711   }
712}
713
714
715/**
716 * Is the given base format a legal format for a color renderbuffer?
717 */
718static GLboolean
719is_format_color_renderable(const struct gl_context *ctx, mesa_format format,
720                           GLenum internalFormat)
721{
722   const GLenum baseFormat =
723      _mesa_get_format_base_format(format);
724   GLboolean valid;
725
726   valid = _mesa_is_legal_color_format(ctx, baseFormat);
727   if (!valid || _mesa_is_desktop_gl(ctx)) {
728      return valid;
729   }
730
731   /* Reject additional cases for GLES */
732   switch (internalFormat) {
733   case GL_R8_SNORM:
734   case GL_RG8_SNORM:
735   case GL_RGBA8_SNORM:
736      return _mesa_has_EXT_render_snorm(ctx);
737   case GL_R16_SNORM:
738   case GL_RG16_SNORM:
739   case GL_RGBA16_SNORM:
740      return _mesa_has_EXT_texture_norm16(ctx) &&
741             _mesa_has_EXT_render_snorm(ctx);
742   case GL_RGB32F:
743   case GL_RGB32I:
744   case GL_RGB32UI:
745   case GL_RGB16F:
746   case GL_RGB16I:
747   case GL_RGB16UI:
748   case GL_RGB8_SNORM:
749   case GL_RGB8I:
750   case GL_RGB8UI:
751   case GL_SRGB8:
752   case GL_RGB10:
753   case GL_RGB9_E5:
754   case GL_SR8_EXT:
755      return GL_FALSE;
756   default:
757      break;
758   }
759
760   if (internalFormat != GL_RGB10_A2 &&
761       (format == MESA_FORMAT_B10G10R10A2_UNORM ||
762        format == MESA_FORMAT_B10G10R10X2_UNORM ||
763        format == MESA_FORMAT_R10G10B10A2_UNORM ||
764        format == MESA_FORMAT_R10G10B10X2_UNORM)) {
765      return GL_FALSE;
766   }
767
768   return GL_TRUE;
769}
770
771
772/**
773 * Is the given base format a legal format for a depth/stencil renderbuffer?
774 */
775static GLboolean
776is_legal_depth_format(const struct gl_context *ctx, GLenum baseFormat)
777{
778   switch (baseFormat) {
779   case GL_DEPTH_COMPONENT:
780   case GL_DEPTH_STENCIL_EXT:
781      return GL_TRUE;
782   default:
783      return GL_FALSE;
784   }
785}
786
787
788/**
789 * Test if an attachment point is complete and update its Complete field.
790 * \param format if GL_COLOR, this is a color attachment point,
791 *               if GL_DEPTH, this is a depth component attachment point,
792 *               if GL_STENCIL, this is a stencil component attachment point.
793 */
794static void
795test_attachment_completeness(const struct gl_context *ctx, GLenum format,
796                             struct gl_renderbuffer_attachment *att)
797{
798   assert(format == GL_COLOR || format == GL_DEPTH || format == GL_STENCIL);
799
800   /* assume complete */
801   att->Complete = GL_TRUE;
802
803   /* Look for reasons why the attachment might be incomplete */
804   if (att->Type == GL_TEXTURE) {
805      const struct gl_texture_object *texObj = att->Texture;
806      const struct gl_texture_image *texImage;
807      GLenum baseFormat;
808
809      if (!texObj) {
810         att_incomplete("no texobj");
811         att->Complete = GL_FALSE;
812         return;
813      }
814
815      texImage = texObj->Image[att->CubeMapFace][att->TextureLevel];
816      if (!texImage) {
817         att_incomplete("no teximage");
818         att->Complete = GL_FALSE;
819         return;
820      }
821      if (texImage->Width < 1 || texImage->Height < 1) {
822         att_incomplete("teximage width/height=0");
823         att->Complete = GL_FALSE;
824         return;
825      }
826
827      switch (texObj->Target) {
828      case GL_TEXTURE_3D:
829         if (att->Zoffset >= texImage->Depth) {
830            att_incomplete("bad z offset");
831            att->Complete = GL_FALSE;
832            return;
833         }
834         break;
835      case GL_TEXTURE_1D_ARRAY:
836         if (att->Zoffset >= texImage->Height) {
837            att_incomplete("bad 1D-array layer");
838            att->Complete = GL_FALSE;
839            return;
840         }
841         break;
842      case GL_TEXTURE_2D_ARRAY:
843         if (att->Zoffset >= texImage->Depth) {
844            att_incomplete("bad 2D-array layer");
845            att->Complete = GL_FALSE;
846            return;
847         }
848         break;
849      case GL_TEXTURE_CUBE_MAP_ARRAY:
850         if (att->Zoffset >= texImage->Depth) {
851            att_incomplete("bad cube-array layer");
852            att->Complete = GL_FALSE;
853            return;
854         }
855         break;
856      }
857
858      baseFormat = texImage->_BaseFormat;
859
860      if (format == GL_COLOR) {
861         if (!_mesa_is_legal_color_format(ctx, baseFormat)) {
862            att_incomplete("bad format");
863            att->Complete = GL_FALSE;
864            return;
865         }
866         if (_mesa_is_format_compressed(texImage->TexFormat)) {
867            att_incomplete("compressed internalformat");
868            att->Complete = GL_FALSE;
869            return;
870         }
871
872         /* OES_texture_float allows creation and use of floating point
873          * textures with GL_FLOAT, GL_HALF_FLOAT but it does not allow
874          * these textures to be used as a render target, this is done via
875          * GL_EXT_color_buffer(_half)_float with set of new sized types.
876          */
877         if (_mesa_is_gles(ctx) && (texObj->_IsFloat || texObj->_IsHalfFloat)) {
878            att_incomplete("bad internal format");
879            att->Complete = GL_FALSE;
880            return;
881         }
882      }
883      else if (format == GL_DEPTH) {
884         if (baseFormat == GL_DEPTH_COMPONENT) {
885            /* OK */
886         }
887         else if (ctx->Extensions.ARB_depth_texture &&
888                  baseFormat == GL_DEPTH_STENCIL) {
889            /* OK */
890         }
891         else {
892            att->Complete = GL_FALSE;
893            att_incomplete("bad depth format");
894            return;
895         }
896      }
897      else {
898         assert(format == GL_STENCIL);
899         if (ctx->Extensions.ARB_depth_texture &&
900             baseFormat == GL_DEPTH_STENCIL) {
901            /* OK */
902         } else if (ctx->Extensions.ARB_texture_stencil8 &&
903                    baseFormat == GL_STENCIL_INDEX) {
904            /* OK */
905         } else {
906            /* no such thing as stencil-only textures */
907            att_incomplete("illegal stencil texture");
908            att->Complete = GL_FALSE;
909            return;
910         }
911      }
912   }
913   else if (att->Type == GL_RENDERBUFFER_EXT) {
914      const GLenum baseFormat = att->Renderbuffer->_BaseFormat;
915
916      assert(att->Renderbuffer);
917      if (!att->Renderbuffer->InternalFormat ||
918          att->Renderbuffer->Width < 1 ||
919          att->Renderbuffer->Height < 1) {
920         att_incomplete("0x0 renderbuffer");
921         att->Complete = GL_FALSE;
922         return;
923      }
924      if (format == GL_COLOR) {
925         if (!_mesa_is_legal_color_format(ctx, baseFormat)) {
926            att_incomplete("bad renderbuffer color format");
927            att->Complete = GL_FALSE;
928            return;
929         }
930      }
931      else if (format == GL_DEPTH) {
932         if (baseFormat == GL_DEPTH_COMPONENT) {
933            /* OK */
934         }
935         else if (baseFormat == GL_DEPTH_STENCIL) {
936            /* OK */
937         }
938         else {
939            att_incomplete("bad renderbuffer depth format");
940            att->Complete = GL_FALSE;
941            return;
942         }
943      }
944      else {
945         assert(format == GL_STENCIL);
946         if (baseFormat == GL_STENCIL_INDEX ||
947             baseFormat == GL_DEPTH_STENCIL) {
948            /* OK */
949         }
950         else {
951            att->Complete = GL_FALSE;
952            att_incomplete("bad renderbuffer stencil format");
953            return;
954         }
955      }
956   }
957   else {
958      assert(att->Type == GL_NONE);
959      /* complete */
960      return;
961   }
962}
963
964
965/**
966 * Test if the given framebuffer object is complete and update its
967 * Status field with the results.
968 * Calls the ctx->Driver.ValidateFramebuffer() function to allow the
969 * driver to make hardware-specific validation/completeness checks.
970 * Also update the framebuffer's Width and Height fields if the
971 * framebuffer is complete.
972 */
973void
974_mesa_test_framebuffer_completeness(struct gl_context *ctx,
975                                    struct gl_framebuffer *fb)
976{
977   GLuint numImages;
978   GLenum intFormat = GL_NONE; /* color buffers' internal format */
979   GLuint minWidth = ~0, minHeight = ~0, maxWidth = 0, maxHeight = 0;
980   GLint numColorSamples = -1;
981   GLint numColorStorageSamples = -1;
982   GLint numDepthSamples = -1;
983   GLint fixedSampleLocations = -1;
984   GLint i;
985   GLuint j;
986   /* Covers max_layer_count, is_layered, and layer_tex_target */
987   bool layer_info_valid = false;
988   GLuint max_layer_count = 0, att_layer_count;
989   bool is_layered = false;
990   GLenum layer_tex_target = 0;
991   bool has_depth_attachment = false;
992   bool has_stencil_attachment = false;
993
994   assert(_mesa_is_user_fbo(fb));
995
996   /* we're changing framebuffer fields here */
997   FLUSH_VERTICES(ctx, _NEW_BUFFERS);
998
999   numImages = 0;
1000   fb->Width = 0;
1001   fb->Height = 0;
1002   fb->_AllColorBuffersFixedPoint = GL_TRUE;
1003   fb->_HasSNormOrFloatColorBuffer = GL_FALSE;
1004   fb->_HasAttachments = true;
1005   fb->_IntegerBuffers = 0;
1006   fb->_RGBBuffers = 0;
1007   fb->_FP32Buffers = 0;
1008
1009   /* Start at -2 to more easily loop over all attachment points.
1010    *  -2: depth buffer
1011    *  -1: stencil buffer
1012    * >=0: color buffer
1013    */
1014   for (i = -2; i < (GLint) ctx->Const.MaxColorAttachments; i++) {
1015      struct gl_renderbuffer_attachment *att;
1016      GLenum f;
1017      GLenum baseFormat;
1018      mesa_format attFormat;
1019      GLenum att_tex_target = GL_NONE;
1020
1021      /*
1022       * XXX for ARB_fbo, only check color buffers that are named by
1023       * GL_READ_BUFFER and GL_DRAW_BUFFERi.
1024       */
1025
1026      /* check for attachment completeness
1027       */
1028      if (i == -2) {
1029         att = &fb->Attachment[BUFFER_DEPTH];
1030         test_attachment_completeness(ctx, GL_DEPTH, att);
1031         if (!att->Complete) {
1032            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT;
1033            fbo_incomplete(ctx, "depth attachment incomplete", -1);
1034            return;
1035         } else if (att->Type != GL_NONE) {
1036            has_depth_attachment = true;
1037         }
1038      }
1039      else if (i == -1) {
1040         att = &fb->Attachment[BUFFER_STENCIL];
1041         test_attachment_completeness(ctx, GL_STENCIL, att);
1042         if (!att->Complete) {
1043            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT;
1044            fbo_incomplete(ctx, "stencil attachment incomplete", -1);
1045            return;
1046         } else if (att->Type != GL_NONE) {
1047            has_stencil_attachment = true;
1048         }
1049      }
1050      else {
1051         att = &fb->Attachment[BUFFER_COLOR0 + i];
1052         test_attachment_completeness(ctx, GL_COLOR, att);
1053         if (!att->Complete) {
1054            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT;
1055            fbo_incomplete(ctx, "color attachment incomplete", i);
1056            return;
1057         }
1058      }
1059
1060      /* get width, height, format of the renderbuffer/texture
1061       */
1062      unsigned attNumSamples, attNumStorageSamples;
1063
1064      if (att->Type == GL_TEXTURE) {
1065         const struct gl_texture_image *texImg = att->Renderbuffer->TexImage;
1066         att_tex_target = att->Texture->Target;
1067         minWidth = MIN2(minWidth, texImg->Width);
1068         maxWidth = MAX2(maxWidth, texImg->Width);
1069         minHeight = MIN2(minHeight, texImg->Height);
1070         maxHeight = MAX2(maxHeight, texImg->Height);
1071         f = texImg->_BaseFormat;
1072         baseFormat = f;
1073         attFormat = texImg->TexFormat;
1074         numImages++;
1075
1076         if (!is_format_color_renderable(ctx, attFormat,
1077                                         texImg->InternalFormat) &&
1078             !is_legal_depth_format(ctx, f) &&
1079             f != GL_STENCIL_INDEX) {
1080            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
1081            fbo_incomplete(ctx, "texture attachment incomplete", -1);
1082            return;
1083         }
1084
1085         if (fixedSampleLocations < 0)
1086            fixedSampleLocations = texImg->FixedSampleLocations;
1087         else if (fixedSampleLocations != texImg->FixedSampleLocations) {
1088            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
1089            fbo_incomplete(ctx, "inconsistent fixed sample locations", -1);
1090            return;
1091         }
1092
1093         if (att->NumSamples > 0)
1094            attNumSamples = att->NumSamples;
1095         else
1096            attNumSamples = texImg->NumSamples;
1097         attNumStorageSamples = attNumSamples;
1098      }
1099      else if (att->Type == GL_RENDERBUFFER_EXT) {
1100         minWidth = MIN2(minWidth, att->Renderbuffer->Width);
1101         maxWidth = MAX2(minWidth, att->Renderbuffer->Width);
1102         minHeight = MIN2(minHeight, att->Renderbuffer->Height);
1103         maxHeight = MAX2(minHeight, att->Renderbuffer->Height);
1104         f = att->Renderbuffer->InternalFormat;
1105         baseFormat = att->Renderbuffer->_BaseFormat;
1106         attFormat = att->Renderbuffer->Format;
1107         numImages++;
1108
1109         /* RENDERBUFFER has fixedSampleLocations implicitly true */
1110         if (fixedSampleLocations < 0)
1111            fixedSampleLocations = GL_TRUE;
1112         else if (fixedSampleLocations != GL_TRUE) {
1113            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
1114            fbo_incomplete(ctx, "inconsistent fixed sample locations", -1);
1115            return;
1116         }
1117
1118         attNumSamples = att->Renderbuffer->NumSamples;
1119         attNumStorageSamples = att->Renderbuffer->NumStorageSamples;
1120      }
1121      else {
1122         assert(att->Type == GL_NONE);
1123         continue;
1124      }
1125
1126      if (i >= 0) {
1127         /* Color buffers. */
1128         if (numColorSamples < 0) {
1129            assert(numColorStorageSamples < 0);
1130            numColorSamples = attNumSamples;
1131            numColorStorageSamples = attNumStorageSamples;
1132         } else if (numColorSamples != attNumSamples ||
1133                    numColorStorageSamples != attNumStorageSamples) {
1134            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
1135            fbo_incomplete(ctx, "inconsistent sample counts", -1);
1136            return;
1137         }
1138      } else {
1139         /* Depth/stencil buffers. */
1140         if (numDepthSamples < 0) {
1141            numDepthSamples = attNumSamples;
1142         } else if (numDepthSamples != attNumSamples) {
1143            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
1144            fbo_incomplete(ctx, "inconsistent sample counts", -1);
1145            return;
1146         }
1147      }
1148
1149      /* Update flags describing color buffer datatypes */
1150      if (i >= 0) {
1151         GLenum type = _mesa_get_format_datatype(attFormat);
1152
1153         /* check if integer color */
1154         if (_mesa_is_format_integer_color(attFormat))
1155            fb->_IntegerBuffers |= (1 << i);
1156
1157         if (baseFormat == GL_RGB)
1158            fb->_RGBBuffers |= (1 << i);
1159
1160         if (type == GL_FLOAT && _mesa_get_format_max_bits(attFormat) > 16)
1161            fb->_FP32Buffers |= (1 << i);
1162
1163         fb->_AllColorBuffersFixedPoint =
1164            fb->_AllColorBuffersFixedPoint &&
1165            (type == GL_UNSIGNED_NORMALIZED || type == GL_SIGNED_NORMALIZED);
1166
1167         fb->_HasSNormOrFloatColorBuffer =
1168            fb->_HasSNormOrFloatColorBuffer ||
1169            type == GL_SIGNED_NORMALIZED || type == GL_FLOAT;
1170      }
1171
1172      /* Error-check width, height, format */
1173      if (numImages == 1) {
1174         /* save format */
1175         if (i >= 0) {
1176            intFormat = f;
1177         }
1178      }
1179      else {
1180         if (!ctx->Extensions.ARB_framebuffer_object) {
1181            /* check that width, height, format are same */
1182            if (minWidth != maxWidth || minHeight != maxHeight) {
1183               fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT;
1184               fbo_incomplete(ctx, "width or height mismatch", -1);
1185               return;
1186            }
1187            /* check that all color buffers are the same format */
1188            if (intFormat != GL_NONE && f != intFormat) {
1189               fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT;
1190               fbo_incomplete(ctx, "format mismatch", -1);
1191               return;
1192            }
1193         }
1194      }
1195
1196      /* Check that the format is valid. (MESA_FORMAT_NONE means unsupported)
1197       */
1198      if (att->Type == GL_RENDERBUFFER &&
1199          att->Renderbuffer->Format == MESA_FORMAT_NONE) {
1200         fb->_Status = GL_FRAMEBUFFER_UNSUPPORTED;
1201         fbo_incomplete(ctx, "unsupported renderbuffer format", i);
1202         return;
1203      }
1204
1205      /* Check that layered rendering is consistent. */
1206      if (att->Layered) {
1207         if (att_tex_target == GL_TEXTURE_CUBE_MAP)
1208            att_layer_count = 6;
1209         else if (att_tex_target == GL_TEXTURE_1D_ARRAY)
1210            att_layer_count = att->Renderbuffer->Height;
1211         else
1212            att_layer_count = att->Renderbuffer->Depth;
1213      } else {
1214         att_layer_count = 0;
1215      }
1216      if (!layer_info_valid) {
1217         is_layered = att->Layered;
1218         max_layer_count = att_layer_count;
1219         layer_tex_target = att_tex_target;
1220         layer_info_valid = true;
1221      } else if (max_layer_count > 0 && layer_tex_target != att_tex_target) {
1222         fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS;
1223         fbo_incomplete(ctx, "layered framebuffer has mismatched targets", i);
1224         return;
1225      } else if (is_layered != att->Layered) {
1226         fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS;
1227         fbo_incomplete(ctx,
1228                        "framebuffer attachment layer mode is inconsistent",
1229                        i);
1230         return;
1231      } else if (att_layer_count > max_layer_count) {
1232         max_layer_count = att_layer_count;
1233      }
1234
1235      /*
1236       * The extension GL_ARB_framebuffer_no_attachments places additional
1237       * requirement on each attachment. Those additional requirements are
1238       * tighter that those of previous versions of GL. In interest of better
1239       * compatibility, we will not enforce these restrictions. For the record
1240       * those additional restrictions are quoted below:
1241       *
1242       * "The width and height of image are greater than zero and less than or
1243       *  equal to the values of the implementation-dependent limits
1244       *  MAX_FRAMEBUFFER_WIDTH and MAX_FRAMEBUFFER_HEIGHT, respectively."
1245       *
1246       * "If <image> is a three-dimensional texture or a one- or two-dimensional
1247       *  array texture and the attachment is layered, the depth or layer count
1248       *  of the texture is less than or equal to the implementation-dependent
1249       *  limit MAX_FRAMEBUFFER_LAYERS."
1250       *
1251       * "If image has multiple samples, its sample count is less than or equal
1252       *  to the value of the implementation-dependent limit
1253       *  MAX_FRAMEBUFFER_SAMPLES."
1254       *
1255       * The same requirements are also in place for GL 4.5,
1256       * Section 9.4.1 "Framebuffer Attachment Completeness", pg 310-311
1257       */
1258   }
1259
1260   if (ctx->Extensions.AMD_framebuffer_multisample_advanced) {
1261      /* See if non-matching sample counts are supported. */
1262      if (numColorSamples >= 0 && numDepthSamples >= 0) {
1263         bool found = false;
1264
1265         assert(numColorStorageSamples != -1);
1266
1267         numColorSamples = MAX2(numColorSamples, 1);
1268         numColorStorageSamples = MAX2(numColorStorageSamples, 1);
1269         numDepthSamples = MAX2(numDepthSamples, 1);
1270
1271         if (numColorSamples == 1 && numColorStorageSamples == 1 &&
1272             numDepthSamples == 1) {
1273            found = true;
1274         } else {
1275            for (i = 0; i < ctx->Const.NumSupportedMultisampleModes; i++) {
1276               GLint *counts =
1277                  &ctx->Const.SupportedMultisampleModes[i].NumColorSamples;
1278
1279               if (counts[0] == numColorSamples &&
1280                   counts[1] == numColorStorageSamples &&
1281                   counts[2] == numDepthSamples) {
1282                  found = true;
1283                  break;
1284               }
1285            }
1286         }
1287
1288         if (!found) {
1289            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
1290            fbo_incomplete(ctx, "unsupported sample counts", -1);
1291            return;
1292         }
1293      }
1294   } else {
1295      /* If the extension is unsupported, all sample counts must be equal. */
1296      if (numColorSamples >= 0 &&
1297          (numColorSamples != numColorStorageSamples ||
1298           (numDepthSamples >= 0 && numColorSamples != numDepthSamples))) {
1299         fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
1300         fbo_incomplete(ctx, "inconsistent sample counts", -1);
1301         return;
1302      }
1303   }
1304
1305   fb->MaxNumLayers = max_layer_count;
1306
1307   if (numImages == 0) {
1308      fb->_HasAttachments = false;
1309
1310      if (!ctx->Extensions.ARB_framebuffer_no_attachments) {
1311         fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT;
1312         fbo_incomplete(ctx, "no attachments", -1);
1313         return;
1314      }
1315
1316      if (fb->DefaultGeometry.Width == 0 || fb->DefaultGeometry.Height == 0) {
1317         fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT;
1318         fbo_incomplete(ctx, "no attachments and default width or height is 0", -1);
1319         return;
1320      }
1321   }
1322
1323   if (_mesa_is_desktop_gl(ctx) && !ctx->Extensions.ARB_ES2_compatibility) {
1324      /* Check that all DrawBuffers are present */
1325      for (j = 0; j < ctx->Const.MaxDrawBuffers; j++) {
1326         if (fb->ColorDrawBuffer[j] != GL_NONE) {
1327            const struct gl_renderbuffer_attachment *att
1328               = get_attachment(ctx, fb, fb->ColorDrawBuffer[j], NULL);
1329            assert(att);
1330            if (att->Type == GL_NONE) {
1331               fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT;
1332               fbo_incomplete(ctx, "missing drawbuffer", j);
1333               return;
1334            }
1335         }
1336      }
1337
1338      /* Check that the ReadBuffer is present */
1339      if (fb->ColorReadBuffer != GL_NONE) {
1340         const struct gl_renderbuffer_attachment *att
1341            = get_attachment(ctx, fb, fb->ColorReadBuffer, NULL);
1342         assert(att);
1343         if (att->Type == GL_NONE) {
1344            fb->_Status = GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT;
1345            fbo_incomplete(ctx, "missing readbuffer", -1);
1346            return;
1347         }
1348      }
1349   }
1350
1351   /* The OpenGL ES3 spec, in chapter 9.4. FRAMEBUFFER COMPLETENESS, says:
1352    *
1353    *    "Depth and stencil attachments, if present, are the same image."
1354    *
1355    * This restriction is not present in the OpenGL ES2 spec.
1356    */
1357   if (_mesa_is_gles3(ctx) &&
1358       has_stencil_attachment && has_depth_attachment &&
1359       !_mesa_has_depthstencil_combined(fb)) {
1360      fb->_Status = GL_FRAMEBUFFER_UNSUPPORTED;
1361      fbo_incomplete(ctx, "Depth and stencil attachments must be the same image", -1);
1362      return;
1363   }
1364
1365   /* Provisionally set status = COMPLETE ... */
1366   fb->_Status = GL_FRAMEBUFFER_COMPLETE_EXT;
1367
1368   /* ... but the driver may say the FB is incomplete.
1369    * Drivers will most likely set the status to GL_FRAMEBUFFER_UNSUPPORTED
1370    * if anything.
1371    */
1372   if (ctx->Driver.ValidateFramebuffer) {
1373      ctx->Driver.ValidateFramebuffer(ctx, fb);
1374      if (fb->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
1375         fbo_incomplete(ctx, "driver marked FBO as incomplete", -1);
1376         return;
1377      }
1378   }
1379
1380   /*
1381    * Note that if ARB_framebuffer_object is supported and the attached
1382    * renderbuffers/textures are different sizes, the framebuffer
1383    * width/height will be set to the smallest width/height.
1384    */
1385   if (numImages != 0) {
1386      fb->Width = minWidth;
1387      fb->Height = minHeight;
1388   }
1389
1390   /* finally, update the visual info for the framebuffer */
1391   _mesa_update_framebuffer_visual(ctx, fb);
1392}
1393
1394
1395GLboolean GLAPIENTRY
1396_mesa_IsRenderbuffer(GLuint renderbuffer)
1397{
1398   struct gl_renderbuffer *rb;
1399
1400   GET_CURRENT_CONTEXT(ctx);
1401
1402   ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
1403
1404   rb = _mesa_lookup_renderbuffer(ctx, renderbuffer);
1405   return rb != NULL && rb != &DummyRenderbuffer;
1406}
1407
1408
1409static struct gl_renderbuffer *
1410allocate_renderbuffer_locked(struct gl_context *ctx, GLuint renderbuffer,
1411                             const char *func)
1412{
1413   struct gl_renderbuffer *newRb;
1414
1415   /* create new renderbuffer object */
1416   newRb = ctx->Driver.NewRenderbuffer(ctx, renderbuffer);
1417   if (!newRb) {
1418      _mesa_error(ctx, GL_OUT_OF_MEMORY, "%s", func);
1419      return NULL;
1420   }
1421   assert(newRb->AllocStorage);
1422   _mesa_HashInsertLocked(ctx->Shared->RenderBuffers, renderbuffer, newRb);
1423
1424   return newRb;
1425}
1426
1427
1428static void
1429bind_renderbuffer(GLenum target, GLuint renderbuffer)
1430{
1431   struct gl_renderbuffer *newRb;
1432   GET_CURRENT_CONTEXT(ctx);
1433
1434   if (target != GL_RENDERBUFFER_EXT) {
1435      _mesa_error(ctx, GL_INVALID_ENUM, "glBindRenderbufferEXT(target)");
1436      return;
1437   }
1438
1439   /* No need to flush here since the render buffer binding has no
1440    * effect on rendering state.
1441    */
1442
1443   if (renderbuffer) {
1444      newRb = _mesa_lookup_renderbuffer(ctx, renderbuffer);
1445      if (newRb == &DummyRenderbuffer) {
1446         /* ID was reserved, but no real renderbuffer object made yet */
1447         newRb = NULL;
1448      }
1449      else if (!newRb && ctx->API == API_OPENGL_CORE) {
1450         /* All RB IDs must be Gen'd */
1451         _mesa_error(ctx, GL_INVALID_OPERATION,
1452                     "glBindRenderbuffer(non-gen name)");
1453         return;
1454      }
1455
1456      if (!newRb) {
1457         _mesa_HashLockMutex(ctx->Shared->RenderBuffers);
1458         newRb = allocate_renderbuffer_locked(ctx, renderbuffer,
1459                                              "glBindRenderbufferEXT");
1460         _mesa_HashUnlockMutex(ctx->Shared->RenderBuffers);
1461      }
1462   }
1463   else {
1464      newRb = NULL;
1465   }
1466
1467   assert(newRb != &DummyRenderbuffer);
1468
1469   _mesa_reference_renderbuffer(&ctx->CurrentRenderbuffer, newRb);
1470}
1471
1472void GLAPIENTRY
1473_mesa_BindRenderbuffer(GLenum target, GLuint renderbuffer)
1474{
1475   /* OpenGL ES glBindRenderbuffer and glBindRenderbufferOES use this same
1476    * entry point, but they allow the use of user-generated names.
1477    */
1478   bind_renderbuffer(target, renderbuffer);
1479}
1480
1481void GLAPIENTRY
1482_mesa_BindRenderbufferEXT(GLenum target, GLuint renderbuffer)
1483{
1484   bind_renderbuffer(target, renderbuffer);
1485}
1486
1487/**
1488 * ARB_framebuffer_no_attachment and ARB_sample_locations - Application passes
1489 * requested param's here. NOTE: NumSamples requested need not be _NumSamples
1490 * which is what the hw supports.
1491 */
1492static void
1493framebuffer_parameteri(struct gl_context *ctx, struct gl_framebuffer *fb,
1494                       GLenum pname, GLint param, const char *func)
1495{
1496   bool cannot_be_winsys_fbo = false;
1497
1498   switch (pname) {
1499   case GL_FRAMEBUFFER_DEFAULT_WIDTH:
1500   case GL_FRAMEBUFFER_DEFAULT_HEIGHT:
1501   case GL_FRAMEBUFFER_DEFAULT_LAYERS:
1502   case GL_FRAMEBUFFER_DEFAULT_SAMPLES:
1503   case GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS:
1504      if (!ctx->Extensions.ARB_framebuffer_no_attachments)
1505         goto invalid_pname_enum;
1506      cannot_be_winsys_fbo = true;
1507      break;
1508   case GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB:
1509   case GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB:
1510      if (!ctx->Extensions.ARB_sample_locations)
1511         goto invalid_pname_enum;
1512      break;
1513   case GL_FRAMEBUFFER_FLIP_Y_MESA:
1514      if (!ctx->Extensions.MESA_framebuffer_flip_y)
1515         goto invalid_pname_enum;
1516      cannot_be_winsys_fbo = true;
1517      break;
1518   default:
1519      goto invalid_pname_enum;
1520   }
1521
1522   if (cannot_be_winsys_fbo && _mesa_is_winsys_fbo(fb)) {
1523      _mesa_error(ctx, GL_INVALID_OPERATION,
1524                  "%s(invalid pname=0x%x for default framebuffer)", func, pname);
1525      return;
1526   }
1527
1528   switch (pname) {
1529   case GL_FRAMEBUFFER_DEFAULT_WIDTH:
1530      if (param < 0 || param > ctx->Const.MaxFramebufferWidth)
1531        _mesa_error(ctx, GL_INVALID_VALUE, "%s", func);
1532      else
1533         fb->DefaultGeometry.Width = param;
1534      break;
1535   case GL_FRAMEBUFFER_DEFAULT_HEIGHT:
1536      if (param < 0 || param > ctx->Const.MaxFramebufferHeight)
1537        _mesa_error(ctx, GL_INVALID_VALUE, "%s", func);
1538      else
1539         fb->DefaultGeometry.Height = param;
1540      break;
1541   case GL_FRAMEBUFFER_DEFAULT_LAYERS:
1542     /*
1543      * According to the OpenGL ES 3.1 specification section 9.2.1, the
1544      * GL_FRAMEBUFFER_DEFAULT_LAYERS parameter name is not supported.
1545      */
1546      if (_mesa_is_gles31(ctx) && !ctx->Extensions.OES_geometry_shader) {
1547         _mesa_error(ctx, GL_INVALID_ENUM, "%s(pname=0x%x)", func, pname);
1548         break;
1549      }
1550      if (param < 0 || param > ctx->Const.MaxFramebufferLayers)
1551         _mesa_error(ctx, GL_INVALID_VALUE, "%s", func);
1552      else
1553         fb->DefaultGeometry.Layers = param;
1554      break;
1555   case GL_FRAMEBUFFER_DEFAULT_SAMPLES:
1556      if (param < 0 || param > ctx->Const.MaxFramebufferSamples)
1557        _mesa_error(ctx, GL_INVALID_VALUE, "%s", func);
1558      else
1559        fb->DefaultGeometry.NumSamples = param;
1560      break;
1561   case GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS:
1562      fb->DefaultGeometry.FixedSampleLocations = param;
1563      break;
1564   case GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB:
1565      fb->ProgrammableSampleLocations = !!param;
1566      break;
1567   case GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB:
1568      fb->SampleLocationPixelGrid = !!param;
1569      break;
1570   case GL_FRAMEBUFFER_FLIP_Y_MESA:
1571      fb->FlipY = param;
1572      break;
1573   }
1574
1575   switch (pname) {
1576   case GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB:
1577   case GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB:
1578      if (fb == ctx->DrawBuffer)
1579         ctx->NewDriverState |= ctx->DriverFlags.NewSampleLocations;
1580      break;
1581   default:
1582      invalidate_framebuffer(fb);
1583      ctx->NewState |= _NEW_BUFFERS;
1584      break;
1585   }
1586
1587   return;
1588
1589invalid_pname_enum:
1590   _mesa_error(ctx, GL_INVALID_ENUM, "%s(pname=0x%x)", func, pname);
1591}
1592
1593void GLAPIENTRY
1594_mesa_FramebufferParameteri(GLenum target, GLenum pname, GLint param)
1595{
1596   GET_CURRENT_CONTEXT(ctx);
1597   struct gl_framebuffer *fb;
1598
1599   if (!ctx->Extensions.ARB_framebuffer_no_attachments &&
1600       !ctx->Extensions.ARB_sample_locations) {
1601      _mesa_error(ctx, GL_INVALID_OPERATION,
1602                  "glFramebufferParameteriv not supported "
1603                  "(neither ARB_framebuffer_no_attachments nor ARB_sample_locations"
1604                  " is available)");
1605      return;
1606   }
1607
1608   fb = get_framebuffer_target(ctx, target);
1609   if (!fb) {
1610      _mesa_error(ctx, GL_INVALID_ENUM,
1611                  "glFramebufferParameteri(target=0x%x)", target);
1612      return;
1613   }
1614
1615   framebuffer_parameteri(ctx, fb, pname, param, "glFramebufferParameteri");
1616}
1617
1618static bool
1619validate_get_framebuffer_parameteriv_pname(struct gl_context *ctx,
1620                                           struct gl_framebuffer *fb,
1621                                           GLuint pname, const char *func)
1622{
1623   bool cannot_be_winsys_fbo = true;
1624
1625   switch (pname) {
1626   case GL_FRAMEBUFFER_DEFAULT_LAYERS:
1627      /*
1628       * According to the OpenGL ES 3.1 specification section 9.2.3, the
1629       * GL_FRAMEBUFFER_LAYERS parameter name is not supported.
1630       */
1631      if (_mesa_is_gles31(ctx) && !ctx->Extensions.OES_geometry_shader) {
1632         _mesa_error(ctx, GL_INVALID_ENUM, "%s(pname=0x%x)", func, pname);
1633         return false;
1634      }
1635      break;
1636   case GL_FRAMEBUFFER_DEFAULT_WIDTH:
1637   case GL_FRAMEBUFFER_DEFAULT_HEIGHT:
1638   case GL_FRAMEBUFFER_DEFAULT_SAMPLES:
1639   case GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS:
1640      break;
1641   case GL_DOUBLEBUFFER:
1642   case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1643   case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1644   case GL_SAMPLES:
1645   case GL_SAMPLE_BUFFERS:
1646   case GL_STEREO:
1647      /* From OpenGL 4.5 spec, section 9.2.3 "Framebuffer Object Queries:
1648       *
1649       *    "An INVALID_OPERATION error is generated by GetFramebufferParameteriv
1650       *     if the default framebuffer is bound to target and pname is not one
1651       *     of the accepted values from table 23.73, other than
1652       *     SAMPLE_POSITION."
1653       *
1654       * For OpenGL ES, using default framebuffer raises INVALID_OPERATION
1655       * for any pname.
1656       */
1657      cannot_be_winsys_fbo = !_mesa_is_desktop_gl(ctx);
1658      break;
1659   case GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB:
1660   case GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB:
1661      if (!ctx->Extensions.ARB_sample_locations)
1662         goto invalid_pname_enum;
1663      cannot_be_winsys_fbo = false;
1664      break;
1665   case GL_FRAMEBUFFER_FLIP_Y_MESA:
1666      if (!ctx->Extensions.MESA_framebuffer_flip_y) {
1667         _mesa_error(ctx, GL_INVALID_ENUM, "%s(pname=0x%x)", func, pname);
1668         return false;
1669      }
1670      break;
1671   default:
1672      goto invalid_pname_enum;
1673   }
1674
1675   if (cannot_be_winsys_fbo && _mesa_is_winsys_fbo(fb)) {
1676      _mesa_error(ctx, GL_INVALID_OPERATION,
1677                  "%s(invalid pname=0x%x for default framebuffer)", func, pname);
1678      return false;
1679   }
1680
1681   return true;
1682
1683invalid_pname_enum:
1684   _mesa_error(ctx, GL_INVALID_ENUM, "%s(pname=0x%x)", func, pname);
1685   return false;
1686}
1687
1688static void
1689get_framebuffer_parameteriv(struct gl_context *ctx, struct gl_framebuffer *fb,
1690                            GLenum pname, GLint *params, const char *func)
1691{
1692   if (!validate_get_framebuffer_parameteriv_pname(ctx, fb, pname, func))
1693      return;
1694
1695   switch (pname) {
1696   case GL_FRAMEBUFFER_DEFAULT_WIDTH:
1697      *params = fb->DefaultGeometry.Width;
1698      break;
1699   case GL_FRAMEBUFFER_DEFAULT_HEIGHT:
1700      *params = fb->DefaultGeometry.Height;
1701      break;
1702   case GL_FRAMEBUFFER_DEFAULT_LAYERS:
1703      *params = fb->DefaultGeometry.Layers;
1704      break;
1705   case GL_FRAMEBUFFER_DEFAULT_SAMPLES:
1706      *params = fb->DefaultGeometry.NumSamples;
1707      break;
1708   case GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS:
1709      *params = fb->DefaultGeometry.FixedSampleLocations;
1710      break;
1711   case GL_DOUBLEBUFFER:
1712      *params = fb->Visual.doubleBufferMode;
1713      break;
1714   case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1715      *params = _mesa_get_color_read_format(ctx, fb, func);
1716      break;
1717   case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1718      *params = _mesa_get_color_read_type(ctx, fb, func);
1719      break;
1720   case GL_SAMPLES:
1721      *params = _mesa_geometric_samples(fb);
1722      break;
1723   case GL_SAMPLE_BUFFERS:
1724      *params = _mesa_geometric_samples(fb) > 0;
1725      break;
1726   case GL_STEREO:
1727      *params = fb->Visual.stereoMode;
1728      break;
1729   case GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB:
1730      *params = fb->ProgrammableSampleLocations;
1731      break;
1732   case GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB:
1733      *params = fb->SampleLocationPixelGrid;
1734      break;
1735   case GL_FRAMEBUFFER_FLIP_Y_MESA:
1736      *params = fb->FlipY;
1737      break;
1738   }
1739}
1740
1741void GLAPIENTRY
1742_mesa_GetFramebufferParameteriv(GLenum target, GLenum pname, GLint *params)
1743{
1744   GET_CURRENT_CONTEXT(ctx);
1745   struct gl_framebuffer *fb;
1746
1747   if (!ctx->Extensions.ARB_framebuffer_no_attachments &&
1748       !ctx->Extensions.ARB_sample_locations) {
1749      _mesa_error(ctx, GL_INVALID_OPERATION,
1750                  "glGetFramebufferParameteriv not supported "
1751                  "(neither ARB_framebuffer_no_attachments nor ARB_sample_locations"
1752                  " is available)");
1753      return;
1754   }
1755
1756   fb = get_framebuffer_target(ctx, target);
1757   if (!fb) {
1758      _mesa_error(ctx, GL_INVALID_ENUM,
1759                  "glGetFramebufferParameteriv(target=0x%x)", target);
1760      return;
1761   }
1762
1763   get_framebuffer_parameteriv(ctx, fb, pname, params,
1764                               "glGetFramebufferParameteriv");
1765}
1766
1767
1768/**
1769 * Remove the specified renderbuffer or texture from any attachment point in
1770 * the framebuffer.
1771 *
1772 * \returns
1773 * \c true if the renderbuffer was detached from an attachment point.  \c
1774 * false otherwise.
1775 */
1776bool
1777_mesa_detach_renderbuffer(struct gl_context *ctx,
1778                          struct gl_framebuffer *fb,
1779                          const void *att)
1780{
1781   unsigned i;
1782   bool progress = false;
1783
1784   for (i = 0; i < BUFFER_COUNT; i++) {
1785      if (fb->Attachment[i].Texture == att
1786          || fb->Attachment[i].Renderbuffer == att) {
1787         remove_attachment(ctx, &fb->Attachment[i]);
1788         progress = true;
1789      }
1790   }
1791
1792   /* Section 4.4.4 (Framebuffer Completeness), subsection "Whole Framebuffer
1793    * Completeness," of the OpenGL 3.1 spec says:
1794    *
1795    *     "Performing any of the following actions may change whether the
1796    *     framebuffer is considered complete or incomplete:
1797    *
1798    *     ...
1799    *
1800    *        - Deleting, with DeleteTextures or DeleteRenderbuffers, an object
1801    *          containing an image that is attached to a framebuffer object
1802    *          that is bound to the framebuffer."
1803    */
1804   if (progress)
1805      invalidate_framebuffer(fb);
1806
1807   return progress;
1808}
1809
1810
1811void GLAPIENTRY
1812_mesa_DeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers)
1813{
1814   GLint i;
1815   GET_CURRENT_CONTEXT(ctx);
1816
1817   if (n < 0) {
1818      _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteRenderbuffers(n < 0)");
1819      return;
1820   }
1821
1822   FLUSH_VERTICES(ctx, _NEW_BUFFERS);
1823
1824   for (i = 0; i < n; i++) {
1825      if (renderbuffers[i] > 0) {
1826         struct gl_renderbuffer *rb;
1827         rb = _mesa_lookup_renderbuffer(ctx, renderbuffers[i]);
1828         if (rb) {
1829            /* check if deleting currently bound renderbuffer object */
1830            if (rb == ctx->CurrentRenderbuffer) {
1831               /* bind default */
1832               assert(rb->RefCount >= 2);
1833               _mesa_BindRenderbuffer(GL_RENDERBUFFER_EXT, 0);
1834            }
1835
1836            /* Section 4.4.2 (Attaching Images to Framebuffer Objects),
1837             * subsection "Attaching Renderbuffer Images to a Framebuffer,"
1838             * of the OpenGL 3.1 spec says:
1839             *
1840             *     "If a renderbuffer object is deleted while its image is
1841             *     attached to one or more attachment points in the currently
1842             *     bound framebuffer, then it is as if FramebufferRenderbuffer
1843             *     had been called, with a renderbuffer of 0, for each
1844             *     attachment point to which this image was attached in the
1845             *     currently bound framebuffer. In other words, this
1846             *     renderbuffer image is first detached from all attachment
1847             *     points in the currently bound framebuffer. Note that the
1848             *     renderbuffer image is specifically not detached from any
1849             *     non-bound framebuffers. Detaching the image from any
1850             *     non-bound framebuffers is the responsibility of the
1851             *     application.
1852             */
1853            if (_mesa_is_user_fbo(ctx->DrawBuffer)) {
1854               _mesa_detach_renderbuffer(ctx, ctx->DrawBuffer, rb);
1855            }
1856            if (_mesa_is_user_fbo(ctx->ReadBuffer)
1857                && ctx->ReadBuffer != ctx->DrawBuffer) {
1858               _mesa_detach_renderbuffer(ctx, ctx->ReadBuffer, rb);
1859            }
1860
1861            /* Remove from hash table immediately, to free the ID.
1862             * But the object will not be freed until it's no longer
1863             * referenced anywhere else.
1864             */
1865            _mesa_HashRemove(ctx->Shared->RenderBuffers, renderbuffers[i]);
1866
1867            if (rb != &DummyRenderbuffer) {
1868               /* no longer referenced by hash table */
1869               _mesa_reference_renderbuffer(&rb, NULL);
1870            }
1871         }
1872      }
1873   }
1874}
1875
1876static void
1877create_render_buffers(struct gl_context *ctx, GLsizei n, GLuint *renderbuffers,
1878                      bool dsa)
1879{
1880   const char *func = dsa ? "glCreateRenderbuffers" : "glGenRenderbuffers";
1881   GLuint first;
1882   GLint i;
1883
1884   if (!renderbuffers)
1885      return;
1886
1887   _mesa_HashLockMutex(ctx->Shared->RenderBuffers);
1888
1889   first = _mesa_HashFindFreeKeyBlock(ctx->Shared->RenderBuffers, n);
1890
1891   for (i = 0; i < n; i++) {
1892      GLuint name = first + i;
1893      renderbuffers[i] = name;
1894
1895      if (dsa) {
1896         allocate_renderbuffer_locked(ctx, name, func);
1897      } else {
1898         /* insert a dummy renderbuffer into the hash table */
1899         _mesa_HashInsertLocked(ctx->Shared->RenderBuffers, name,
1900                                &DummyRenderbuffer);
1901      }
1902   }
1903
1904   _mesa_HashUnlockMutex(ctx->Shared->RenderBuffers);
1905}
1906
1907
1908static void
1909create_render_buffers_err(struct gl_context *ctx, GLsizei n,
1910                          GLuint *renderbuffers, bool dsa)
1911{
1912   const char *func = dsa ? "glCreateRenderbuffers" : "glGenRenderbuffers";
1913
1914   if (n < 0) {
1915      _mesa_error(ctx, GL_INVALID_VALUE, "%s(n<0)", func);
1916      return;
1917   }
1918
1919   create_render_buffers(ctx, n, renderbuffers, dsa);
1920}
1921
1922
1923void GLAPIENTRY
1924_mesa_GenRenderbuffers_no_error(GLsizei n, GLuint *renderbuffers)
1925{
1926   GET_CURRENT_CONTEXT(ctx);
1927   create_render_buffers(ctx, n, renderbuffers, false);
1928}
1929
1930
1931void GLAPIENTRY
1932_mesa_GenRenderbuffers(GLsizei n, GLuint *renderbuffers)
1933{
1934   GET_CURRENT_CONTEXT(ctx);
1935   create_render_buffers_err(ctx, n, renderbuffers, false);
1936}
1937
1938
1939void GLAPIENTRY
1940_mesa_CreateRenderbuffers_no_error(GLsizei n, GLuint *renderbuffers)
1941{
1942   GET_CURRENT_CONTEXT(ctx);
1943   create_render_buffers(ctx, n, renderbuffers, true);
1944}
1945
1946
1947void GLAPIENTRY
1948_mesa_CreateRenderbuffers(GLsizei n, GLuint *renderbuffers)
1949{
1950   GET_CURRENT_CONTEXT(ctx);
1951   create_render_buffers_err(ctx, n, renderbuffers, true);
1952}
1953
1954
1955/**
1956 * Given an internal format token for a render buffer, return the
1957 * corresponding base format (one of GL_RGB, GL_RGBA, GL_STENCIL_INDEX,
1958 * GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL_EXT, GL_ALPHA, GL_LUMINANCE,
1959 * GL_LUMINANCE_ALPHA, GL_INTENSITY, etc).
1960 *
1961 * This is similar to _mesa_base_tex_format() but the set of valid
1962 * internal formats is different.
1963 *
1964 * Note that even if a format is determined to be legal here, validation
1965 * of the FBO may fail if the format is not supported by the driver/GPU.
1966 *
1967 * \param internalFormat  as passed to glRenderbufferStorage()
1968 * \return the base internal format, or 0 if internalFormat is illegal
1969 */
1970GLenum
1971_mesa_base_fbo_format(const struct gl_context *ctx, GLenum internalFormat)
1972{
1973   /*
1974    * Notes: some formats such as alpha, luminance, etc. were added
1975    * with GL_ARB_framebuffer_object.
1976    */
1977   switch (internalFormat) {
1978   case GL_ALPHA:
1979   case GL_ALPHA4:
1980   case GL_ALPHA8:
1981   case GL_ALPHA12:
1982   case GL_ALPHA16:
1983      return (ctx->API == API_OPENGL_COMPAT &&
1984              ctx->Extensions.ARB_framebuffer_object) ? GL_ALPHA : 0;
1985   case GL_LUMINANCE:
1986   case GL_LUMINANCE4:
1987   case GL_LUMINANCE8:
1988   case GL_LUMINANCE12:
1989   case GL_LUMINANCE16:
1990      return (ctx->API == API_OPENGL_COMPAT &&
1991              ctx->Extensions.ARB_framebuffer_object) ? GL_LUMINANCE : 0;
1992   case GL_LUMINANCE_ALPHA:
1993   case GL_LUMINANCE4_ALPHA4:
1994   case GL_LUMINANCE6_ALPHA2:
1995   case GL_LUMINANCE8_ALPHA8:
1996   case GL_LUMINANCE12_ALPHA4:
1997   case GL_LUMINANCE12_ALPHA12:
1998   case GL_LUMINANCE16_ALPHA16:
1999      return (ctx->API == API_OPENGL_COMPAT &&
2000              ctx->Extensions.ARB_framebuffer_object) ? GL_LUMINANCE_ALPHA : 0;
2001   case GL_INTENSITY:
2002   case GL_INTENSITY4:
2003   case GL_INTENSITY8:
2004   case GL_INTENSITY12:
2005   case GL_INTENSITY16:
2006      return (ctx->API == API_OPENGL_COMPAT &&
2007              ctx->Extensions.ARB_framebuffer_object) ? GL_INTENSITY : 0;
2008   case GL_RGB8:
2009      return GL_RGB;
2010   case GL_RGB:
2011   case GL_R3_G3_B2:
2012   case GL_RGB4:
2013   case GL_RGB5:
2014   case GL_RGB10:
2015   case GL_RGB12:
2016   case GL_RGB16:
2017      return _mesa_is_desktop_gl(ctx) ? GL_RGB : 0;
2018   case GL_SRGB8_EXT:
2019      return _mesa_is_desktop_gl(ctx) ? GL_RGB : 0;
2020   case GL_RGBA4:
2021   case GL_RGB5_A1:
2022   case GL_RGBA8:
2023      return GL_RGBA;
2024   case GL_RGBA:
2025   case GL_RGBA2:
2026   case GL_RGBA12:
2027      return _mesa_is_desktop_gl(ctx) ? GL_RGBA : 0;
2028   case GL_RGBA16:
2029      return _mesa_is_desktop_gl(ctx) || _mesa_has_EXT_texture_norm16(ctx)
2030         ? GL_RGBA : 0;
2031   case GL_RGB10_A2:
2032   case GL_SRGB8_ALPHA8_EXT:
2033      return _mesa_is_desktop_gl(ctx) || _mesa_is_gles3(ctx) ? GL_RGBA : 0;
2034   case GL_STENCIL_INDEX:
2035   case GL_STENCIL_INDEX1_EXT:
2036   case GL_STENCIL_INDEX4_EXT:
2037   case GL_STENCIL_INDEX16_EXT:
2038      /* There are extensions for GL_STENCIL_INDEX1 and GL_STENCIL_INDEX4 in
2039       * OpenGL ES, but Mesa does not currently support them.
2040       */
2041      return _mesa_is_desktop_gl(ctx) ? GL_STENCIL_INDEX : 0;
2042   case GL_STENCIL_INDEX8_EXT:
2043      return GL_STENCIL_INDEX;
2044   case GL_DEPTH_COMPONENT:
2045   case GL_DEPTH_COMPONENT32:
2046      return _mesa_is_desktop_gl(ctx) ? GL_DEPTH_COMPONENT : 0;
2047   case GL_DEPTH_COMPONENT16:
2048   case GL_DEPTH_COMPONENT24:
2049      return GL_DEPTH_COMPONENT;
2050   case GL_DEPTH_STENCIL:
2051      return _mesa_is_desktop_gl(ctx) ? GL_DEPTH_STENCIL : 0;
2052   case GL_DEPTH24_STENCIL8:
2053      return GL_DEPTH_STENCIL;
2054   case GL_DEPTH_COMPONENT32F:
2055      return ctx->Version >= 30
2056         || (ctx->API == API_OPENGL_COMPAT &&
2057             ctx->Extensions.ARB_depth_buffer_float)
2058         ? GL_DEPTH_COMPONENT : 0;
2059   case GL_DEPTH32F_STENCIL8:
2060      return ctx->Version >= 30
2061         || (ctx->API == API_OPENGL_COMPAT &&
2062             ctx->Extensions.ARB_depth_buffer_float)
2063         ? GL_DEPTH_STENCIL : 0;
2064   case GL_RED:
2065      return _mesa_has_ARB_texture_rg(ctx) ? GL_RED : 0;
2066   case GL_R16:
2067      return _mesa_has_ARB_texture_rg(ctx) || _mesa_has_EXT_texture_norm16(ctx)
2068         ? GL_RED : 0;
2069   case GL_R8:
2070      return ctx->API != API_OPENGLES && ctx->Extensions.ARB_texture_rg
2071         ? GL_RED : 0;
2072   case GL_RG:
2073      return _mesa_has_ARB_texture_rg(ctx) ? GL_RG : 0;
2074   case GL_RG16:
2075      return _mesa_has_ARB_texture_rg(ctx) || _mesa_has_EXT_texture_norm16(ctx)
2076         ? GL_RG : 0;
2077   case GL_RG8:
2078      return ctx->API != API_OPENGLES && ctx->Extensions.ARB_texture_rg
2079         ? GL_RG : 0;
2080   /* signed normalized texture formats */
2081   case GL_R8_SNORM:
2082      return _mesa_has_EXT_texture_snorm(ctx) || _mesa_has_EXT_render_snorm(ctx)
2083         ? GL_RED : 0;
2084   case GL_RED_SNORM:
2085      return _mesa_has_EXT_texture_snorm(ctx) ? GL_RED : 0;
2086   case GL_R16_SNORM:
2087      return _mesa_has_EXT_texture_snorm(ctx) ||
2088             (_mesa_has_EXT_render_snorm(ctx) &&
2089              _mesa_has_EXT_texture_norm16(ctx))
2090         ? GL_RED : 0;
2091   case GL_RG8_SNORM:
2092      return _mesa_has_EXT_texture_snorm(ctx) || _mesa_has_EXT_render_snorm(ctx)
2093         ? GL_RG : 0;
2094   case GL_RG_SNORM:
2095      return _mesa_has_EXT_texture_snorm(ctx) ? GL_RG : 0;
2096   case GL_RG16_SNORM:
2097      return _mesa_has_EXT_texture_snorm(ctx) ||
2098             (_mesa_has_EXT_render_snorm(ctx) &&
2099              _mesa_has_EXT_texture_norm16(ctx))
2100         ? GL_RG : 0;
2101   case GL_RGB_SNORM:
2102   case GL_RGB8_SNORM:
2103   case GL_RGB16_SNORM:
2104      return _mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_snorm
2105         ? GL_RGB : 0;
2106   case GL_RGBA8_SNORM:
2107      return _mesa_has_EXT_texture_snorm(ctx) || _mesa_has_EXT_render_snorm(ctx)
2108         ? GL_RGBA : 0;
2109   case GL_RGBA_SNORM:
2110      return _mesa_has_EXT_texture_snorm(ctx) ? GL_RGBA : 0;
2111   case GL_RGBA16_SNORM:
2112      return _mesa_has_EXT_texture_snorm(ctx) ||
2113             (_mesa_has_EXT_render_snorm(ctx) &&
2114              _mesa_has_EXT_texture_norm16(ctx))
2115         ? GL_RGBA : 0;
2116   case GL_ALPHA_SNORM:
2117   case GL_ALPHA8_SNORM:
2118   case GL_ALPHA16_SNORM:
2119      return ctx->API == API_OPENGL_COMPAT &&
2120             ctx->Extensions.EXT_texture_snorm &&
2121             ctx->Extensions.ARB_framebuffer_object ? GL_ALPHA : 0;
2122   case GL_LUMINANCE_SNORM:
2123   case GL_LUMINANCE8_SNORM:
2124   case GL_LUMINANCE16_SNORM:
2125      return _mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_snorm
2126         ? GL_LUMINANCE : 0;
2127   case GL_LUMINANCE_ALPHA_SNORM:
2128   case GL_LUMINANCE8_ALPHA8_SNORM:
2129   case GL_LUMINANCE16_ALPHA16_SNORM:
2130      return _mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_snorm
2131         ? GL_LUMINANCE_ALPHA : 0;
2132   case GL_INTENSITY_SNORM:
2133   case GL_INTENSITY8_SNORM:
2134   case GL_INTENSITY16_SNORM:
2135      return _mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_snorm
2136         ? GL_INTENSITY : 0;
2137
2138   case GL_R16F:
2139   case GL_R32F:
2140      return ((_mesa_is_desktop_gl(ctx) &&
2141               ctx->Extensions.ARB_texture_rg &&
2142               ctx->Extensions.ARB_texture_float) ||
2143              _mesa_is_gles3(ctx) /* EXT_color_buffer_float */ )
2144         ? GL_RED : 0;
2145   case GL_RG16F:
2146   case GL_RG32F:
2147      return ((_mesa_is_desktop_gl(ctx) &&
2148               ctx->Extensions.ARB_texture_rg &&
2149               ctx->Extensions.ARB_texture_float) ||
2150              _mesa_is_gles3(ctx) /* EXT_color_buffer_float */ )
2151         ? GL_RG : 0;
2152   case GL_RGB16F:
2153   case GL_RGB32F:
2154      return (_mesa_is_desktop_gl(ctx) && ctx->Extensions.ARB_texture_float)
2155         ? GL_RGB : 0;
2156   case GL_RGBA16F:
2157   case GL_RGBA32F:
2158      return ((_mesa_is_desktop_gl(ctx) &&
2159               ctx->Extensions.ARB_texture_float) ||
2160              _mesa_is_gles3(ctx) /* EXT_color_buffer_float */ )
2161         ? GL_RGBA : 0;
2162   case GL_RGB9_E5:
2163      return (_mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_shared_exponent)
2164         ? GL_RGB: 0;
2165   case GL_ALPHA16F_ARB:
2166   case GL_ALPHA32F_ARB:
2167      return ctx->API == API_OPENGL_COMPAT &&
2168             ctx->Extensions.ARB_texture_float &&
2169             ctx->Extensions.ARB_framebuffer_object ? GL_ALPHA : 0;
2170   case GL_LUMINANCE16F_ARB:
2171   case GL_LUMINANCE32F_ARB:
2172      return ctx->API == API_OPENGL_COMPAT &&
2173             ctx->Extensions.ARB_texture_float &&
2174             ctx->Extensions.ARB_framebuffer_object ? GL_LUMINANCE : 0;
2175   case GL_LUMINANCE_ALPHA16F_ARB:
2176   case GL_LUMINANCE_ALPHA32F_ARB:
2177      return ctx->API == API_OPENGL_COMPAT &&
2178             ctx->Extensions.ARB_texture_float &&
2179             ctx->Extensions.ARB_framebuffer_object ? GL_LUMINANCE_ALPHA : 0;
2180   case GL_INTENSITY16F_ARB:
2181   case GL_INTENSITY32F_ARB:
2182      return ctx->API == API_OPENGL_COMPAT &&
2183             ctx->Extensions.ARB_texture_float &&
2184             ctx->Extensions.ARB_framebuffer_object ? GL_INTENSITY : 0;
2185   case GL_R11F_G11F_B10F:
2186      return ((_mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_packed_float) ||
2187              _mesa_is_gles3(ctx) /* EXT_color_buffer_float */ )
2188         ? GL_RGB : 0;
2189
2190   case GL_RGBA8UI_EXT:
2191   case GL_RGBA16UI_EXT:
2192   case GL_RGBA32UI_EXT:
2193   case GL_RGBA8I_EXT:
2194   case GL_RGBA16I_EXT:
2195   case GL_RGBA32I_EXT:
2196      return ctx->Version >= 30
2197         || (_mesa_is_desktop_gl(ctx) &&
2198             ctx->Extensions.EXT_texture_integer) ? GL_RGBA : 0;
2199
2200   case GL_RGB8UI_EXT:
2201   case GL_RGB16UI_EXT:
2202   case GL_RGB32UI_EXT:
2203   case GL_RGB8I_EXT:
2204   case GL_RGB16I_EXT:
2205   case GL_RGB32I_EXT:
2206      return _mesa_is_desktop_gl(ctx) && ctx->Extensions.EXT_texture_integer
2207         ? GL_RGB : 0;
2208   case GL_R8UI:
2209   case GL_R8I:
2210   case GL_R16UI:
2211   case GL_R16I:
2212   case GL_R32UI:
2213   case GL_R32I:
2214      return ctx->Version >= 30
2215         || (_mesa_is_desktop_gl(ctx) &&
2216             ctx->Extensions.ARB_texture_rg &&
2217             ctx->Extensions.EXT_texture_integer) ? GL_RED : 0;
2218
2219   case GL_RG8UI:
2220   case GL_RG8I:
2221   case GL_RG16UI:
2222   case GL_RG16I:
2223   case GL_RG32UI:
2224   case GL_RG32I:
2225      return ctx->Version >= 30
2226         || (_mesa_is_desktop_gl(ctx) &&
2227             ctx->Extensions.ARB_texture_rg &&
2228             ctx->Extensions.EXT_texture_integer) ? GL_RG : 0;
2229
2230   case GL_INTENSITY8I_EXT:
2231   case GL_INTENSITY8UI_EXT:
2232   case GL_INTENSITY16I_EXT:
2233   case GL_INTENSITY16UI_EXT:
2234   case GL_INTENSITY32I_EXT:
2235   case GL_INTENSITY32UI_EXT:
2236      return ctx->API == API_OPENGL_COMPAT &&
2237             ctx->Extensions.EXT_texture_integer &&
2238             ctx->Extensions.ARB_framebuffer_object ? GL_INTENSITY : 0;
2239
2240   case GL_LUMINANCE8I_EXT:
2241   case GL_LUMINANCE8UI_EXT:
2242   case GL_LUMINANCE16I_EXT:
2243   case GL_LUMINANCE16UI_EXT:
2244   case GL_LUMINANCE32I_EXT:
2245   case GL_LUMINANCE32UI_EXT:
2246      return ctx->API == API_OPENGL_COMPAT &&
2247             ctx->Extensions.EXT_texture_integer &&
2248             ctx->Extensions.ARB_framebuffer_object ? GL_LUMINANCE : 0;
2249
2250   case GL_LUMINANCE_ALPHA8I_EXT:
2251   case GL_LUMINANCE_ALPHA8UI_EXT:
2252   case GL_LUMINANCE_ALPHA16I_EXT:
2253   case GL_LUMINANCE_ALPHA16UI_EXT:
2254   case GL_LUMINANCE_ALPHA32I_EXT:
2255   case GL_LUMINANCE_ALPHA32UI_EXT:
2256      return ctx->API == API_OPENGL_COMPAT &&
2257             ctx->Extensions.EXT_texture_integer &&
2258             ctx->Extensions.ARB_framebuffer_object ? GL_LUMINANCE_ALPHA : 0;
2259
2260   case GL_ALPHA8I_EXT:
2261   case GL_ALPHA8UI_EXT:
2262   case GL_ALPHA16I_EXT:
2263   case GL_ALPHA16UI_EXT:
2264   case GL_ALPHA32I_EXT:
2265   case GL_ALPHA32UI_EXT:
2266      return ctx->API == API_OPENGL_COMPAT &&
2267             ctx->Extensions.EXT_texture_integer &&
2268             ctx->Extensions.ARB_framebuffer_object ? GL_ALPHA : 0;
2269
2270   case GL_RGB10_A2UI:
2271      return (_mesa_is_desktop_gl(ctx) &&
2272              ctx->Extensions.ARB_texture_rgb10_a2ui)
2273         || _mesa_is_gles3(ctx) ? GL_RGBA : 0;
2274
2275   case GL_RGB565:
2276      return _mesa_is_gles(ctx) || ctx->Extensions.ARB_ES2_compatibility
2277         ? GL_RGB : 0;
2278   default:
2279      return 0;
2280   }
2281}
2282
2283
2284/**
2285 * Invalidate a renderbuffer attachment.  Called from _mesa_HashWalk().
2286 */
2287static void
2288invalidate_rb(GLuint key, void *data, void *userData)
2289{
2290   struct gl_framebuffer *fb = (struct gl_framebuffer *) data;
2291   struct gl_renderbuffer *rb = (struct gl_renderbuffer *) userData;
2292
2293   /* If this is a user-created FBO */
2294   if (_mesa_is_user_fbo(fb)) {
2295      GLuint i;
2296      for (i = 0; i < BUFFER_COUNT; i++) {
2297         struct gl_renderbuffer_attachment *att = fb->Attachment + i;
2298         if (att->Type == GL_RENDERBUFFER &&
2299             att->Renderbuffer == rb) {
2300            /* Mark fb status as indeterminate to force re-validation */
2301            fb->_Status = 0;
2302            return;
2303         }
2304      }
2305   }
2306}
2307
2308
2309/** sentinal value, see below */
2310#define NO_SAMPLES 1000
2311
2312void
2313_mesa_renderbuffer_storage(struct gl_context *ctx, struct gl_renderbuffer *rb,
2314                           GLenum internalFormat, GLsizei width,
2315                           GLsizei height, GLsizei samples,
2316                           GLsizei storageSamples)
2317{
2318   const GLenum baseFormat = _mesa_base_fbo_format(ctx, internalFormat);
2319
2320   assert(baseFormat != 0);
2321   assert(width >= 0 && width <= (GLsizei) ctx->Const.MaxRenderbufferSize);
2322   assert(height >= 0 && height <= (GLsizei) ctx->Const.MaxRenderbufferSize);
2323   assert(samples != NO_SAMPLES);
2324   if (samples != 0) {
2325      assert(samples > 0);
2326      assert(_mesa_check_sample_count(ctx, GL_RENDERBUFFER,
2327                                      internalFormat, samples,
2328                                      storageSamples) == GL_NO_ERROR);
2329   }
2330
2331   FLUSH_VERTICES(ctx, _NEW_BUFFERS);
2332
2333   if (rb->InternalFormat == internalFormat &&
2334       rb->Width == (GLuint) width &&
2335       rb->Height == (GLuint) height &&
2336       rb->NumSamples == samples &&
2337       rb->NumStorageSamples == storageSamples) {
2338      /* no change in allocation needed */
2339      return;
2340   }
2341
2342   /* These MUST get set by the AllocStorage func */
2343   rb->Format = MESA_FORMAT_NONE;
2344   rb->NumSamples = samples;
2345   rb->NumStorageSamples = storageSamples;
2346
2347   /* Now allocate the storage */
2348   assert(rb->AllocStorage);
2349   if (rb->AllocStorage(ctx, rb, internalFormat, width, height)) {
2350      /* No error - check/set fields now */
2351      /* If rb->Format == MESA_FORMAT_NONE, the format is unsupported. */
2352      assert(rb->Width == (GLuint) width);
2353      assert(rb->Height == (GLuint) height);
2354      rb->InternalFormat = internalFormat;
2355      rb->_BaseFormat = baseFormat;
2356      assert(rb->_BaseFormat != 0);
2357   }
2358   else {
2359      /* Probably ran out of memory - clear the fields */
2360      rb->Width = 0;
2361      rb->Height = 0;
2362      rb->Format = MESA_FORMAT_NONE;
2363      rb->InternalFormat = GL_NONE;
2364      rb->_BaseFormat = GL_NONE;
2365      rb->NumSamples = 0;
2366      rb->NumStorageSamples = 0;
2367   }
2368
2369   /* Invalidate the framebuffers the renderbuffer is attached in. */
2370   if (rb->AttachedAnytime) {
2371      _mesa_HashWalk(ctx->Shared->FrameBuffers, invalidate_rb, rb);
2372   }
2373}
2374
2375/**
2376 * Helper function used by renderbuffer_storage_direct() and
2377 * renderbuffer_storage_target().
2378 * samples will be NO_SAMPLES if called by a non-multisample function.
2379 */
2380static void
2381renderbuffer_storage(struct gl_context *ctx, struct gl_renderbuffer *rb,
2382                     GLenum internalFormat, GLsizei width,
2383                     GLsizei height, GLsizei samples, GLsizei storageSamples,
2384                     const char *func)
2385{
2386   GLenum baseFormat;
2387   GLenum sample_count_error;
2388
2389   baseFormat = _mesa_base_fbo_format(ctx, internalFormat);
2390   if (baseFormat == 0) {
2391      _mesa_error(ctx, GL_INVALID_ENUM, "%s(internalFormat=%s)",
2392                  func, _mesa_enum_to_string(internalFormat));
2393      return;
2394   }
2395
2396   if (width < 0 || width > (GLsizei) ctx->Const.MaxRenderbufferSize) {
2397      _mesa_error(ctx, GL_INVALID_VALUE, "%s(invalid width %d)", func,
2398                  width);
2399      return;
2400   }
2401
2402   if (height < 0 || height > (GLsizei) ctx->Const.MaxRenderbufferSize) {
2403      _mesa_error(ctx, GL_INVALID_VALUE, "%s(invalid height %d)", func,
2404                  height);
2405      return;
2406   }
2407
2408   if (samples == NO_SAMPLES) {
2409      /* NumSamples == 0 indicates non-multisampling */
2410      samples = 0;
2411      storageSamples = 0;
2412   }
2413   else {
2414      /* check the sample count;
2415       * note: driver may choose to use more samples than what's requested
2416       */
2417      sample_count_error = _mesa_check_sample_count(ctx, GL_RENDERBUFFER,
2418            internalFormat, samples, storageSamples);
2419
2420      /* Section 2.5 (GL Errors) of OpenGL 3.0 specification, page 16:
2421       *
2422       * "If a negative number is provided where an argument of type sizei or
2423       * sizeiptr is specified, the error INVALID VALUE is generated."
2424       */
2425      if (samples < 0 || storageSamples < 0) {
2426         sample_count_error = GL_INVALID_VALUE;
2427      }
2428
2429      if (sample_count_error != GL_NO_ERROR) {
2430         _mesa_error(ctx, sample_count_error,
2431                     "%s(samples=%d, storageSamples=%d)", func, samples,
2432                     storageSamples);
2433         return;
2434      }
2435   }
2436
2437   _mesa_renderbuffer_storage(ctx, rb, internalFormat, width, height, samples,
2438                              storageSamples);
2439}
2440
2441/**
2442 * Helper function used by _mesa_NamedRenderbufferStorage*().
2443 * samples will be NO_SAMPLES if called by a non-multisample function.
2444 */
2445static void
2446renderbuffer_storage_named(GLuint renderbuffer, GLenum internalFormat,
2447                           GLsizei width, GLsizei height, GLsizei samples,
2448                           GLsizei storageSamples, const char *func)
2449{
2450   GET_CURRENT_CONTEXT(ctx);
2451
2452   if (MESA_VERBOSE & VERBOSE_API) {
2453      if (samples == NO_SAMPLES)
2454         _mesa_debug(ctx, "%s(%u, %s, %d, %d)\n",
2455                     func, renderbuffer,
2456                     _mesa_enum_to_string(internalFormat),
2457                     width, height);
2458      else
2459         _mesa_debug(ctx, "%s(%u, %s, %d, %d, %d)\n",
2460                     func, renderbuffer,
2461                     _mesa_enum_to_string(internalFormat),
2462                     width, height, samples);
2463   }
2464
2465   struct gl_renderbuffer *rb = _mesa_lookup_renderbuffer(ctx, renderbuffer);
2466   if (!rb || rb == &DummyRenderbuffer) {
2467      /* ID was reserved, but no real renderbuffer object made yet */
2468      _mesa_error(ctx, GL_INVALID_OPERATION, "%s(invalid renderbuffer %u)",
2469                  func, renderbuffer);
2470      return;
2471   }
2472
2473   renderbuffer_storage(ctx, rb, internalFormat, width, height, samples,
2474                        storageSamples, func);
2475}
2476
2477/**
2478 * Helper function used by _mesa_RenderbufferStorage() and
2479 * _mesa_RenderbufferStorageMultisample().
2480 * samples will be NO_SAMPLES if called by _mesa_RenderbufferStorage().
2481 */
2482static void
2483renderbuffer_storage_target(GLenum target, GLenum internalFormat,
2484                            GLsizei width, GLsizei height, GLsizei samples,
2485                            GLsizei storageSamples, const char *func)
2486{
2487   GET_CURRENT_CONTEXT(ctx);
2488
2489   if (MESA_VERBOSE & VERBOSE_API) {
2490      if (samples == NO_SAMPLES)
2491         _mesa_debug(ctx, "%s(%s, %s, %d, %d)\n",
2492                     func,
2493                     _mesa_enum_to_string(target),
2494                     _mesa_enum_to_string(internalFormat),
2495                     width, height);
2496      else
2497         _mesa_debug(ctx, "%s(%s, %s, %d, %d, %d)\n",
2498                     func,
2499                     _mesa_enum_to_string(target),
2500                     _mesa_enum_to_string(internalFormat),
2501                     width, height, samples);
2502   }
2503
2504   if (target != GL_RENDERBUFFER_EXT) {
2505      _mesa_error(ctx, GL_INVALID_ENUM, "%s(target)", func);
2506      return;
2507   }
2508
2509   if (!ctx->CurrentRenderbuffer) {
2510      _mesa_error(ctx, GL_INVALID_OPERATION, "%s(no renderbuffer bound)",
2511                  func);
2512      return;
2513   }
2514
2515   renderbuffer_storage(ctx, ctx->CurrentRenderbuffer, internalFormat, width,
2516                        height, samples, storageSamples, func);
2517}
2518
2519
2520void GLAPIENTRY
2521_mesa_EGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image)
2522{
2523   struct gl_renderbuffer *rb;
2524   GET_CURRENT_CONTEXT(ctx);
2525
2526   if (!ctx->Extensions.OES_EGL_image) {
2527      _mesa_error(ctx, GL_INVALID_OPERATION,
2528                  "glEGLImageTargetRenderbufferStorageOES(unsupported)");
2529      return;
2530   }
2531
2532   if (target != GL_RENDERBUFFER) {
2533      _mesa_error(ctx, GL_INVALID_ENUM,
2534                  "EGLImageTargetRenderbufferStorageOES");
2535      return;
2536   }
2537
2538   rb = ctx->CurrentRenderbuffer;
2539   if (!rb) {
2540      _mesa_error(ctx, GL_INVALID_OPERATION,
2541                  "EGLImageTargetRenderbufferStorageOES");
2542      return;
2543   }
2544
2545   FLUSH_VERTICES(ctx, _NEW_BUFFERS);
2546
2547   ctx->Driver.EGLImageTargetRenderbufferStorage(ctx, rb, image);
2548}
2549
2550
2551/**
2552 * Helper function for _mesa_GetRenderbufferParameteriv() and
2553 * _mesa_GetFramebufferAttachmentParameteriv()
2554 * We have to be careful to respect the base format.  For example, if a
2555 * renderbuffer/texture was created with internalFormat=GL_RGB but the
2556 * driver actually chose a GL_RGBA format, when the user queries ALPHA_SIZE
2557 * we need to return zero.
2558 */
2559static GLint
2560get_component_bits(GLenum pname, GLenum baseFormat, mesa_format format)
2561{
2562   if (_mesa_base_format_has_channel(baseFormat, pname))
2563      return _mesa_get_format_bits(format, pname);
2564   else
2565      return 0;
2566}
2567
2568
2569
2570void GLAPIENTRY
2571_mesa_RenderbufferStorage(GLenum target, GLenum internalFormat,
2572                             GLsizei width, GLsizei height)
2573{
2574   /* GL_ARB_fbo says calling this function is equivalent to calling
2575    * glRenderbufferStorageMultisample() with samples=0.  We pass in
2576    * a token value here just for error reporting purposes.
2577    */
2578   renderbuffer_storage_target(target, internalFormat, width, height,
2579                               NO_SAMPLES, 0, "glRenderbufferStorage");
2580}
2581
2582
2583void GLAPIENTRY
2584_mesa_RenderbufferStorageMultisample(GLenum target, GLsizei samples,
2585                                     GLenum internalFormat,
2586                                     GLsizei width, GLsizei height)
2587{
2588   renderbuffer_storage_target(target, internalFormat, width, height,
2589                               samples, samples,
2590                               "glRenderbufferStorageMultisample");
2591}
2592
2593
2594void GLAPIENTRY
2595_mesa_RenderbufferStorageMultisampleAdvancedAMD(
2596      GLenum target, GLsizei samples, GLsizei storageSamples,
2597      GLenum internalFormat, GLsizei width, GLsizei height)
2598{
2599   renderbuffer_storage_target(target, internalFormat, width, height,
2600                               samples, storageSamples,
2601                               "glRenderbufferStorageMultisampleAdvancedAMD");
2602}
2603
2604
2605/**
2606 * OpenGL ES version of glRenderBufferStorage.
2607 */
2608void GLAPIENTRY
2609_es_RenderbufferStorageEXT(GLenum target, GLenum internalFormat,
2610                           GLsizei width, GLsizei height)
2611{
2612   switch (internalFormat) {
2613   case GL_RGB565:
2614      /* XXX this confuses GL_RENDERBUFFER_INTERNAL_FORMAT_OES */
2615      /* choose a closest format */
2616      internalFormat = GL_RGB5;
2617      break;
2618   default:
2619      break;
2620   }
2621
2622   renderbuffer_storage_target(target, internalFormat, width, height, 0, 0,
2623                               "glRenderbufferStorageEXT");
2624}
2625
2626void GLAPIENTRY
2627_mesa_NamedRenderbufferStorage(GLuint renderbuffer, GLenum internalformat,
2628                               GLsizei width, GLsizei height)
2629{
2630   /* GL_ARB_fbo says calling this function is equivalent to calling
2631    * glRenderbufferStorageMultisample() with samples=0.  We pass in
2632    * a token value here just for error reporting purposes.
2633    */
2634   renderbuffer_storage_named(renderbuffer, internalformat, width, height,
2635                              NO_SAMPLES, 0, "glNamedRenderbufferStorage");
2636}
2637
2638void GLAPIENTRY
2639_mesa_NamedRenderbufferStorageMultisample(GLuint renderbuffer, GLsizei samples,
2640                                          GLenum internalformat,
2641                                          GLsizei width, GLsizei height)
2642{
2643   renderbuffer_storage_named(renderbuffer, internalformat, width, height,
2644                              samples, samples,
2645                              "glNamedRenderbufferStorageMultisample");
2646}
2647
2648
2649void GLAPIENTRY
2650_mesa_NamedRenderbufferStorageMultisampleAdvancedAMD(
2651      GLuint renderbuffer, GLsizei samples, GLsizei storageSamples,
2652      GLenum internalformat, GLsizei width, GLsizei height)
2653{
2654   renderbuffer_storage_named(renderbuffer, internalformat, width, height,
2655                              samples, storageSamples,
2656                              "glNamedRenderbufferStorageMultisampleAdvancedAMD");
2657}
2658
2659
2660static void
2661get_render_buffer_parameteriv(struct gl_context *ctx,
2662                              struct gl_renderbuffer *rb, GLenum pname,
2663                              GLint *params, const char *func)
2664{
2665   /* No need to flush here since we're just quering state which is
2666    * not effected by rendering.
2667    */
2668
2669   switch (pname) {
2670   case GL_RENDERBUFFER_WIDTH_EXT:
2671      *params = rb->Width;
2672      return;
2673   case GL_RENDERBUFFER_HEIGHT_EXT:
2674      *params = rb->Height;
2675      return;
2676   case GL_RENDERBUFFER_INTERNAL_FORMAT_EXT:
2677      *params = rb->InternalFormat;
2678      return;
2679   case GL_RENDERBUFFER_RED_SIZE_EXT:
2680   case GL_RENDERBUFFER_GREEN_SIZE_EXT:
2681   case GL_RENDERBUFFER_BLUE_SIZE_EXT:
2682   case GL_RENDERBUFFER_ALPHA_SIZE_EXT:
2683   case GL_RENDERBUFFER_DEPTH_SIZE_EXT:
2684   case GL_RENDERBUFFER_STENCIL_SIZE_EXT:
2685      *params = get_component_bits(pname, rb->_BaseFormat, rb->Format);
2686      return;
2687   case GL_RENDERBUFFER_SAMPLES:
2688      if ((_mesa_is_desktop_gl(ctx) && ctx->Extensions.ARB_framebuffer_object)
2689          || _mesa_is_gles3(ctx)) {
2690         *params = rb->NumSamples;
2691         return;
2692      }
2693      break;
2694   case GL_RENDERBUFFER_STORAGE_SAMPLES_AMD:
2695      if (ctx->Extensions.AMD_framebuffer_multisample_advanced) {
2696         *params = rb->NumStorageSamples;
2697         return;
2698      }
2699      break;
2700   }
2701
2702   _mesa_error(ctx, GL_INVALID_ENUM, "%s(invalid pname=%s)", func,
2703               _mesa_enum_to_string(pname));
2704}
2705
2706
2707void GLAPIENTRY
2708_mesa_GetRenderbufferParameteriv(GLenum target, GLenum pname, GLint *params)
2709{
2710   GET_CURRENT_CONTEXT(ctx);
2711
2712   if (target != GL_RENDERBUFFER_EXT) {
2713      _mesa_error(ctx, GL_INVALID_ENUM,
2714                  "glGetRenderbufferParameterivEXT(target)");
2715      return;
2716   }
2717
2718   if (!ctx->CurrentRenderbuffer) {
2719      _mesa_error(ctx, GL_INVALID_OPERATION, "glGetRenderbufferParameterivEXT"
2720                  "(no renderbuffer bound)");
2721      return;
2722   }
2723
2724   get_render_buffer_parameteriv(ctx, ctx->CurrentRenderbuffer, pname,
2725                                 params, "glGetRenderbufferParameteriv");
2726}
2727
2728
2729void GLAPIENTRY
2730_mesa_GetNamedRenderbufferParameteriv(GLuint renderbuffer, GLenum pname,
2731                                      GLint *params)
2732{
2733   GET_CURRENT_CONTEXT(ctx);
2734
2735   struct gl_renderbuffer *rb = _mesa_lookup_renderbuffer(ctx, renderbuffer);
2736   if (!rb || rb == &DummyRenderbuffer) {
2737      /* ID was reserved, but no real renderbuffer object made yet */
2738      _mesa_error(ctx, GL_INVALID_OPERATION, "glGetNamedRenderbufferParameteriv"
2739                  "(invalid renderbuffer %i)", renderbuffer);
2740      return;
2741   }
2742
2743   get_render_buffer_parameteriv(ctx, rb, pname, params,
2744                                 "glGetNamedRenderbufferParameteriv");
2745}
2746
2747
2748GLboolean GLAPIENTRY
2749_mesa_IsFramebuffer(GLuint framebuffer)
2750{
2751   GET_CURRENT_CONTEXT(ctx);
2752   ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
2753   if (framebuffer) {
2754      struct gl_framebuffer *rb = _mesa_lookup_framebuffer(ctx, framebuffer);
2755      if (rb != NULL && rb != &DummyFramebuffer)
2756         return GL_TRUE;
2757   }
2758   return GL_FALSE;
2759}
2760
2761
2762/**
2763 * Check if any of the attachments of the given framebuffer are textures
2764 * (render to texture).  Call ctx->Driver.RenderTexture() for such
2765 * attachments.
2766 */
2767static void
2768check_begin_texture_render(struct gl_context *ctx, struct gl_framebuffer *fb)
2769{
2770   GLuint i;
2771   assert(ctx->Driver.RenderTexture);
2772
2773   if (_mesa_is_winsys_fbo(fb))
2774      return; /* can't render to texture with winsys framebuffers */
2775
2776   for (i = 0; i < BUFFER_COUNT; i++) {
2777      struct gl_renderbuffer_attachment *att = fb->Attachment + i;
2778      if (att->Texture && att->Renderbuffer->TexImage
2779          && driver_RenderTexture_is_safe(att)) {
2780         ctx->Driver.RenderTexture(ctx, fb, att);
2781      }
2782   }
2783}
2784
2785
2786/**
2787 * Examine all the framebuffer's attachments to see if any are textures.
2788 * If so, call ctx->Driver.FinishRenderTexture() for each texture to
2789 * notify the device driver that the texture image may have changed.
2790 */
2791static void
2792check_end_texture_render(struct gl_context *ctx, struct gl_framebuffer *fb)
2793{
2794   /* Skip if we know NeedsFinishRenderTexture won't be set. */
2795   if (_mesa_is_winsys_fbo(fb) && !ctx->Driver.BindRenderbufferTexImage)
2796      return;
2797
2798   if (ctx->Driver.FinishRenderTexture) {
2799      GLuint i;
2800      for (i = 0; i < BUFFER_COUNT; i++) {
2801         struct gl_renderbuffer_attachment *att = fb->Attachment + i;
2802         struct gl_renderbuffer *rb = att->Renderbuffer;
2803         if (rb && rb->NeedsFinishRenderTexture) {
2804            ctx->Driver.FinishRenderTexture(ctx, rb);
2805         }
2806      }
2807   }
2808}
2809
2810
2811static void
2812bind_framebuffer(GLenum target, GLuint framebuffer)
2813{
2814   struct gl_framebuffer *newDrawFb, *newReadFb;
2815   GLboolean bindReadBuf, bindDrawBuf;
2816   GET_CURRENT_CONTEXT(ctx);
2817
2818   switch (target) {
2819   case GL_DRAW_FRAMEBUFFER_EXT:
2820      bindDrawBuf = GL_TRUE;
2821      bindReadBuf = GL_FALSE;
2822      break;
2823   case GL_READ_FRAMEBUFFER_EXT:
2824      bindDrawBuf = GL_FALSE;
2825      bindReadBuf = GL_TRUE;
2826      break;
2827   case GL_FRAMEBUFFER_EXT:
2828      bindDrawBuf = GL_TRUE;
2829      bindReadBuf = GL_TRUE;
2830      break;
2831   default:
2832      _mesa_error(ctx, GL_INVALID_ENUM, "glBindFramebufferEXT(target)");
2833      return;
2834   }
2835
2836   if (framebuffer) {
2837      /* Binding a user-created framebuffer object */
2838      newDrawFb = _mesa_lookup_framebuffer(ctx, framebuffer);
2839      if (newDrawFb == &DummyFramebuffer) {
2840         /* ID was reserved, but no real framebuffer object made yet */
2841         newDrawFb = NULL;
2842      }
2843      else if (!newDrawFb && ctx->API == API_OPENGL_CORE) {
2844         /* All FBO IDs must be Gen'd */
2845         _mesa_error(ctx, GL_INVALID_OPERATION,
2846                     "glBindFramebuffer(non-gen name)");
2847         return;
2848      }
2849
2850      if (!newDrawFb) {
2851         /* create new framebuffer object */
2852         newDrawFb = ctx->Driver.NewFramebuffer(ctx, framebuffer);
2853         if (!newDrawFb) {
2854            _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindFramebufferEXT");
2855            return;
2856         }
2857         _mesa_HashInsert(ctx->Shared->FrameBuffers, framebuffer, newDrawFb);
2858      }
2859      newReadFb = newDrawFb;
2860   }
2861   else {
2862      /* Binding the window system framebuffer (which was originally set
2863       * with MakeCurrent).
2864       */
2865      newDrawFb = ctx->WinSysDrawBuffer;
2866      newReadFb = ctx->WinSysReadBuffer;
2867   }
2868
2869   _mesa_bind_framebuffers(ctx,
2870                           bindDrawBuf ? newDrawFb : ctx->DrawBuffer,
2871                           bindReadBuf ? newReadFb : ctx->ReadBuffer);
2872}
2873
2874void
2875_mesa_bind_framebuffers(struct gl_context *ctx,
2876                        struct gl_framebuffer *newDrawFb,
2877                        struct gl_framebuffer *newReadFb)
2878{
2879   struct gl_framebuffer *const oldDrawFb = ctx->DrawBuffer;
2880   struct gl_framebuffer *const oldReadFb = ctx->ReadBuffer;
2881   const bool bindDrawBuf = oldDrawFb != newDrawFb;
2882   const bool bindReadBuf = oldReadFb != newReadFb;
2883
2884   assert(newDrawFb);
2885   assert(newDrawFb != &DummyFramebuffer);
2886
2887   /*
2888    * OK, now bind the new Draw/Read framebuffers, if they're changing.
2889    *
2890    * We also check if we're beginning and/or ending render-to-texture.
2891    * When a framebuffer with texture attachments is unbound, call
2892    * ctx->Driver.FinishRenderTexture().
2893    * When a framebuffer with texture attachments is bound, call
2894    * ctx->Driver.RenderTexture().
2895    *
2896    * Note that if the ReadBuffer has texture attachments we don't consider
2897    * that a render-to-texture case.
2898    */
2899   if (bindReadBuf) {
2900      FLUSH_VERTICES(ctx, _NEW_BUFFERS);
2901
2902      /* check if old readbuffer was render-to-texture */
2903      check_end_texture_render(ctx, oldReadFb);
2904
2905      _mesa_reference_framebuffer(&ctx->ReadBuffer, newReadFb);
2906   }
2907
2908   if (bindDrawBuf) {
2909      FLUSH_VERTICES(ctx, _NEW_BUFFERS);
2910      ctx->NewDriverState |= ctx->DriverFlags.NewSampleLocations;
2911
2912      /* check if old framebuffer had any texture attachments */
2913      if (oldDrawFb)
2914         check_end_texture_render(ctx, oldDrawFb);
2915
2916      /* check if newly bound framebuffer has any texture attachments */
2917      check_begin_texture_render(ctx, newDrawFb);
2918
2919      _mesa_reference_framebuffer(&ctx->DrawBuffer, newDrawFb);
2920   }
2921
2922   if ((bindDrawBuf || bindReadBuf) && ctx->Driver.BindFramebuffer) {
2923      /* The few classic drivers that actually hook this function really only
2924       * want to know if the draw framebuffer changed.
2925       */
2926      ctx->Driver.BindFramebuffer(ctx,
2927                                  bindDrawBuf ? GL_FRAMEBUFFER : GL_READ_FRAMEBUFFER,
2928                                  newDrawFb, newReadFb);
2929   }
2930}
2931
2932void GLAPIENTRY
2933_mesa_BindFramebuffer(GLenum target, GLuint framebuffer)
2934{
2935   /* OpenGL ES glBindFramebuffer and glBindFramebufferOES use this same entry
2936    * point, but they allow the use of user-generated names.
2937    */
2938   bind_framebuffer(target, framebuffer);
2939}
2940
2941
2942void GLAPIENTRY
2943_mesa_BindFramebufferEXT(GLenum target, GLuint framebuffer)
2944{
2945   bind_framebuffer(target, framebuffer);
2946}
2947
2948
2949void GLAPIENTRY
2950_mesa_DeleteFramebuffers(GLsizei n, const GLuint *framebuffers)
2951{
2952   GLint i;
2953   GET_CURRENT_CONTEXT(ctx);
2954
2955   if (n < 0) {
2956      _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteFramebuffers(n < 0)");
2957      return;
2958   }
2959
2960   FLUSH_VERTICES(ctx, _NEW_BUFFERS);
2961
2962   for (i = 0; i < n; i++) {
2963      if (framebuffers[i] > 0) {
2964         struct gl_framebuffer *fb;
2965         fb = _mesa_lookup_framebuffer(ctx, framebuffers[i]);
2966         if (fb) {
2967            assert(fb == &DummyFramebuffer || fb->Name == framebuffers[i]);
2968
2969            /* check if deleting currently bound framebuffer object */
2970            if (fb == ctx->DrawBuffer) {
2971               /* bind default */
2972               assert(fb->RefCount >= 2);
2973               _mesa_BindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
2974            }
2975            if (fb == ctx->ReadBuffer) {
2976               /* bind default */
2977               assert(fb->RefCount >= 2);
2978               _mesa_BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
2979            }
2980
2981            /* remove from hash table immediately, to free the ID */
2982            _mesa_HashRemove(ctx->Shared->FrameBuffers, framebuffers[i]);
2983
2984            if (fb != &DummyFramebuffer) {
2985               /* But the object will not be freed until it's no longer
2986                * bound in any context.
2987                */
2988               _mesa_reference_framebuffer(&fb, NULL);
2989            }
2990         }
2991      }
2992   }
2993}
2994
2995
2996/**
2997 * This is the implementation for glGenFramebuffers and glCreateFramebuffers.
2998 * It is not exposed to the rest of Mesa to encourage the use of
2999 * nameless buffers in driver internals.
3000 */
3001static void
3002create_framebuffers(GLsizei n, GLuint *framebuffers, bool dsa)
3003{
3004   GET_CURRENT_CONTEXT(ctx);
3005   GLuint first;
3006   GLint i;
3007   struct gl_framebuffer *fb;
3008
3009   const char *func = dsa ? "glCreateFramebuffers" : "glGenFramebuffers";
3010
3011   if (n < 0) {
3012      _mesa_error(ctx, GL_INVALID_VALUE, "%s(n < 0)", func);
3013      return;
3014   }
3015
3016   if (!framebuffers)
3017      return;
3018
3019   _mesa_HashLockMutex(ctx->Shared->FrameBuffers);
3020
3021   first = _mesa_HashFindFreeKeyBlock(ctx->Shared->FrameBuffers, n);
3022
3023   for (i = 0; i < n; i++) {
3024      GLuint name = first + i;
3025      framebuffers[i] = name;
3026
3027      if (dsa) {
3028         fb = ctx->Driver.NewFramebuffer(ctx, framebuffers[i]);
3029         if (!fb) {
3030            _mesa_HashUnlockMutex(ctx->Shared->FrameBuffers);
3031            _mesa_error(ctx, GL_OUT_OF_MEMORY, "%s", func);
3032            return;
3033         }
3034      }
3035      else
3036         fb = &DummyFramebuffer;
3037
3038      _mesa_HashInsertLocked(ctx->Shared->FrameBuffers, name, fb);
3039   }
3040
3041   _mesa_HashUnlockMutex(ctx->Shared->FrameBuffers);
3042}
3043
3044
3045void GLAPIENTRY
3046_mesa_GenFramebuffers(GLsizei n, GLuint *framebuffers)
3047{
3048   create_framebuffers(n, framebuffers, false);
3049}
3050
3051
3052void GLAPIENTRY
3053_mesa_CreateFramebuffers(GLsizei n, GLuint *framebuffers)
3054{
3055   create_framebuffers(n, framebuffers, true);
3056}
3057
3058
3059GLenum
3060_mesa_check_framebuffer_status(struct gl_context *ctx,
3061                               struct gl_framebuffer *buffer)
3062{
3063   ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
3064
3065   if (_mesa_is_winsys_fbo(buffer)) {
3066      /* EGL_KHR_surfaceless_context allows the winsys FBO to be incomplete. */
3067      if (buffer != &IncompleteFramebuffer) {
3068         return GL_FRAMEBUFFER_COMPLETE_EXT;
3069      } else {
3070         return GL_FRAMEBUFFER_UNDEFINED;
3071      }
3072   }
3073
3074   /* No need to flush here */
3075
3076   if (buffer->_Status != GL_FRAMEBUFFER_COMPLETE) {
3077      _mesa_test_framebuffer_completeness(ctx, buffer);
3078   }
3079
3080   return buffer->_Status;
3081}
3082
3083
3084GLenum GLAPIENTRY
3085_mesa_CheckFramebufferStatus_no_error(GLenum target)
3086{
3087   GET_CURRENT_CONTEXT(ctx);
3088
3089   struct gl_framebuffer *fb = get_framebuffer_target(ctx, target);
3090   return _mesa_check_framebuffer_status(ctx, fb);
3091}
3092
3093
3094GLenum GLAPIENTRY
3095_mesa_CheckFramebufferStatus(GLenum target)
3096{
3097   struct gl_framebuffer *fb;
3098   GET_CURRENT_CONTEXT(ctx);
3099
3100   if (MESA_VERBOSE & VERBOSE_API)
3101      _mesa_debug(ctx, "glCheckFramebufferStatus(%s)\n",
3102                  _mesa_enum_to_string(target));
3103
3104   fb = get_framebuffer_target(ctx, target);
3105   if (!fb) {
3106      _mesa_error(ctx, GL_INVALID_ENUM,
3107                  "glCheckFramebufferStatus(invalid target %s)",
3108                  _mesa_enum_to_string(target));
3109      return 0;
3110   }
3111
3112   return _mesa_check_framebuffer_status(ctx, fb);
3113}
3114
3115
3116GLenum GLAPIENTRY
3117_mesa_CheckNamedFramebufferStatus(GLuint framebuffer, GLenum target)
3118{
3119   struct gl_framebuffer *fb;
3120   GET_CURRENT_CONTEXT(ctx);
3121
3122   /* Validate the target (for conformance's sake) and grab a reference to the
3123    * default framebuffer in case framebuffer = 0.
3124    * Section 9.4 Framebuffer Completeness of the OpenGL 4.5 core spec
3125    * (30.10.2014, PDF page 336) says:
3126    *    "If framebuffer is zero, then the status of the default read or
3127    *    draw framebuffer (as determined by target) is returned."
3128    */
3129   switch (target) {
3130      case GL_DRAW_FRAMEBUFFER:
3131      case GL_FRAMEBUFFER:
3132         fb = ctx->WinSysDrawBuffer;
3133         break;
3134      case GL_READ_FRAMEBUFFER:
3135         fb = ctx->WinSysReadBuffer;
3136         break;
3137      default:
3138         _mesa_error(ctx, GL_INVALID_ENUM,
3139                     "glCheckNamedFramebufferStatus(invalid target %s)",
3140                     _mesa_enum_to_string(target));
3141         return 0;
3142   }
3143
3144   if (framebuffer) {
3145      fb = _mesa_lookup_framebuffer_err(ctx, framebuffer,
3146                                        "glCheckNamedFramebufferStatus");
3147      if (!fb)
3148         return 0;
3149   }
3150
3151   return _mesa_check_framebuffer_status(ctx, fb);
3152}
3153
3154
3155/**
3156 * Replicate the src attachment point. Used by framebuffer_texture() when
3157 * the same texture is attached at GL_DEPTH_ATTACHMENT and
3158 * GL_STENCIL_ATTACHMENT.
3159 */
3160static void
3161reuse_framebuffer_texture_attachment(struct gl_framebuffer *fb,
3162                                     gl_buffer_index dst,
3163                                     gl_buffer_index src)
3164{
3165   struct gl_renderbuffer_attachment *dst_att = &fb->Attachment[dst];
3166   struct gl_renderbuffer_attachment *src_att = &fb->Attachment[src];
3167
3168   assert(src_att->Texture != NULL);
3169   assert(src_att->Renderbuffer != NULL);
3170
3171   _mesa_reference_texobj(&dst_att->Texture, src_att->Texture);
3172   _mesa_reference_renderbuffer(&dst_att->Renderbuffer, src_att->Renderbuffer);
3173   dst_att->Type = src_att->Type;
3174   dst_att->Complete = src_att->Complete;
3175   dst_att->TextureLevel = src_att->TextureLevel;
3176   dst_att->CubeMapFace = src_att->CubeMapFace;
3177   dst_att->Zoffset = src_att->Zoffset;
3178   dst_att->Layered = src_att->Layered;
3179}
3180
3181
3182static struct gl_texture_object *
3183get_texture_for_framebuffer(struct gl_context *ctx, GLuint texture)
3184{
3185   if (!texture)
3186      return NULL;
3187
3188   return _mesa_lookup_texture(ctx, texture);
3189}
3190
3191
3192/**
3193 * Common code called by gl*FramebufferTexture*() to retrieve the correct
3194 * texture object pointer.
3195 *
3196 * \param texObj where the pointer to the texture object is returned.  Note
3197 * that a successful call may return texObj = NULL.
3198 *
3199 * \return true if no errors, false if errors
3200 */
3201static bool
3202get_texture_for_framebuffer_err(struct gl_context *ctx, GLuint texture,
3203                                bool layered, const char *caller,
3204                                struct gl_texture_object **texObj)
3205{
3206   *texObj = NULL; /* This will get returned if texture = 0. */
3207
3208   if (!texture)
3209      return true;
3210
3211   *texObj = _mesa_lookup_texture(ctx, texture);
3212   if (*texObj == NULL || (*texObj)->Target == 0) {
3213      /* Can't render to a non-existent texture object.
3214       *
3215       * The OpenGL 4.5 core spec (02.02.2015) in Section 9.2 Binding and
3216       * Managing Framebuffer Objects specifies a different error
3217       * depending upon the calling function (PDF pages 325-328).
3218       * *FramebufferTexture (where layered = GL_TRUE) throws invalid
3219       * value, while the other commands throw invalid operation (where
3220       * layered = GL_FALSE).
3221       */
3222      const GLenum error = layered ? GL_INVALID_VALUE :
3223                           GL_INVALID_OPERATION;
3224      _mesa_error(ctx, error,
3225                  "%s(non-existent texture %u)", caller, texture);
3226      return false;
3227   }
3228
3229   return true;
3230}
3231
3232
3233/**
3234 * Common code called by gl*FramebufferTexture() to verify the texture target
3235 * and decide whether or not the attachment should truly be considered
3236 * layered.
3237 *
3238 * \param layered true if attachment should be considered layered, false if
3239 * not
3240 *
3241 * \return true if no errors, false if errors
3242 */
3243static bool
3244check_layered_texture_target(struct gl_context *ctx, GLenum target,
3245                             const char *caller, GLboolean *layered)
3246{
3247   *layered = GL_TRUE;
3248
3249   switch (target) {
3250   case GL_TEXTURE_3D:
3251   case GL_TEXTURE_1D_ARRAY_EXT:
3252   case GL_TEXTURE_2D_ARRAY_EXT:
3253   case GL_TEXTURE_CUBE_MAP:
3254   case GL_TEXTURE_CUBE_MAP_ARRAY:
3255   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
3256      return true;
3257   case GL_TEXTURE_1D:
3258   case GL_TEXTURE_2D:
3259   case GL_TEXTURE_RECTANGLE:
3260   case GL_TEXTURE_2D_MULTISAMPLE:
3261      /* These texture types are valid to pass to
3262       * glFramebufferTexture(), but since they aren't layered, it
3263       * is equivalent to calling glFramebufferTexture{1D,2D}().
3264       */
3265      *layered = GL_FALSE;
3266      return true;
3267   }
3268
3269   _mesa_error(ctx, GL_INVALID_OPERATION,
3270               "%s(invalid texture target %s)", caller,
3271               _mesa_enum_to_string(target));
3272   return false;
3273}
3274
3275
3276/**
3277 * Common code called by gl*FramebufferTextureLayer() to verify the texture
3278 * target.
3279 *
3280 * \return true if no errors, false if errors
3281 */
3282static bool
3283check_texture_target(struct gl_context *ctx, GLenum target,
3284                     const char *caller)
3285{
3286   /* We're being called by glFramebufferTextureLayer().
3287    * The only legal texture types for that function are 3D,
3288    * cube-map, and 1D/2D/cube-map array textures.
3289    *
3290    * We don't need to check for GL_ARB_texture_cube_map_array because the
3291    * application wouldn't have been able to create a texture with a
3292    * GL_TEXTURE_CUBE_MAP_ARRAY target if the extension were not enabled.
3293    */
3294   switch (target) {
3295   case GL_TEXTURE_3D:
3296   case GL_TEXTURE_1D_ARRAY:
3297   case GL_TEXTURE_2D_ARRAY:
3298   case GL_TEXTURE_CUBE_MAP_ARRAY:
3299   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
3300      return true;
3301   case GL_TEXTURE_CUBE_MAP:
3302      /* GL_TEXTURE_CUBE_MAP is only allowed by OpenGL 4.5 here, which
3303       * includes the DSA API.
3304       *
3305       * Because DSA is only enabled for GL 3.1+ and this can be called
3306       * from _mesa_FramebufferTextureLayer in compatibility profile,
3307       * we need to check the version.
3308       */
3309      return _mesa_is_desktop_gl(ctx) && ctx->Version >= 31;
3310   }
3311
3312   _mesa_error(ctx, GL_INVALID_OPERATION,
3313               "%s(invalid texture target %s)", caller,
3314               _mesa_enum_to_string(target));
3315   return false;
3316}
3317
3318
3319/**
3320 * Common code called by glFramebufferTexture*D() to verify the texture
3321 * target.
3322 *
3323 * \return true if no errors, false if errors
3324 */
3325static bool
3326check_textarget(struct gl_context *ctx, int dims, GLenum target,
3327                GLenum textarget, const char *caller)
3328{
3329   bool err = false;
3330
3331   switch (textarget) {
3332   case GL_TEXTURE_1D:
3333      err = dims != 1;
3334      break;
3335   case GL_TEXTURE_1D_ARRAY:
3336      err = dims != 1 || !ctx->Extensions.EXT_texture_array;
3337      break;
3338   case GL_TEXTURE_2D:
3339      err = dims != 2;
3340      break;
3341   case GL_TEXTURE_2D_ARRAY:
3342      err = dims != 2 || !ctx->Extensions.EXT_texture_array ||
3343            (_mesa_is_gles(ctx) && ctx->Version < 30);
3344      break;
3345   case GL_TEXTURE_2D_MULTISAMPLE:
3346   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
3347      err = dims != 2 ||
3348            !ctx->Extensions.ARB_texture_multisample ||
3349            (_mesa_is_gles(ctx) && ctx->Version < 31);
3350      break;
3351   case GL_TEXTURE_RECTANGLE:
3352      err = dims != 2 || _mesa_is_gles(ctx) ||
3353            !ctx->Extensions.NV_texture_rectangle;
3354      break;
3355   case GL_TEXTURE_CUBE_MAP:
3356   case GL_TEXTURE_CUBE_MAP_ARRAY:
3357      err = true;
3358      break;
3359   case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
3360   case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
3361   case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
3362   case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
3363   case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
3364   case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
3365      err = dims != 2 || !ctx->Extensions.ARB_texture_cube_map;
3366      break;
3367   case GL_TEXTURE_3D:
3368      err = dims != 3;
3369      break;
3370   default:
3371      _mesa_error(ctx, GL_INVALID_ENUM,
3372                  "%s(unknown textarget 0x%x)", caller, textarget);
3373      return false;
3374   }
3375
3376   if (err) {
3377      _mesa_error(ctx, GL_INVALID_OPERATION,
3378                  "%s(invalid textarget %s)",
3379                  caller, _mesa_enum_to_string(textarget));
3380      return false;
3381   }
3382
3383   /* Make sure textarget is consistent with the texture's type */
3384   err = (target == GL_TEXTURE_CUBE_MAP) ?
3385          !_mesa_is_cube_face(textarget): (target != textarget);
3386
3387   if (err) {
3388      _mesa_error(ctx, GL_INVALID_OPERATION,
3389                  "%s(mismatched texture target)", caller);
3390      return false;
3391   }
3392
3393   return true;
3394}
3395
3396
3397/**
3398 * Common code called by gl*FramebufferTextureLayer() and
3399 * glFramebufferTexture3D() to validate the layer.
3400 *
3401 * \return true if no errors, false if errors
3402 */
3403static bool
3404check_layer(struct gl_context *ctx, GLenum target, GLint layer,
3405            const char *caller)
3406{
3407   /* Page 306 (page 328 of the PDF) of the OpenGL 4.5 (Core Profile)
3408    * spec says:
3409    *
3410    *    "An INVALID_VALUE error is generated if texture is non-zero
3411    *     and layer is negative."
3412    */
3413   if (layer < 0) {
3414      _mesa_error(ctx, GL_INVALID_VALUE, "%s(layer %d < 0)", caller, layer);
3415      return false;
3416   }
3417
3418   if (target == GL_TEXTURE_3D) {
3419      const GLuint maxSize = 1 << (ctx->Const.Max3DTextureLevels - 1);
3420      if (layer >= maxSize) {
3421         _mesa_error(ctx, GL_INVALID_VALUE,
3422                     "%s(invalid layer %u)", caller, layer);
3423         return false;
3424      }
3425   }
3426   else if ((target == GL_TEXTURE_1D_ARRAY) ||
3427            (target == GL_TEXTURE_2D_ARRAY) ||
3428            (target == GL_TEXTURE_CUBE_MAP_ARRAY) ||
3429            (target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)) {
3430      if (layer >= ctx->Const.MaxArrayTextureLayers) {
3431         _mesa_error(ctx, GL_INVALID_VALUE,
3432                     "%s(layer %u >= GL_MAX_ARRAY_TEXTURE_LAYERS)",
3433                     caller, layer);
3434         return false;
3435      }
3436   }
3437   else if (target == GL_TEXTURE_CUBE_MAP) {
3438      if (layer >= 6) {
3439         _mesa_error(ctx, GL_INVALID_VALUE,
3440                     "%s(layer %u >= 6)", caller, layer);
3441         return false;
3442      }
3443   }
3444
3445   return true;
3446}
3447
3448
3449/**
3450 * Common code called by all gl*FramebufferTexture*() entry points to verify
3451 * the level.
3452 *
3453 * \return true if no errors, false if errors
3454 */
3455static bool
3456check_level(struct gl_context *ctx, struct gl_texture_object *texObj,
3457            GLenum target, GLint level, const char *caller)
3458{
3459   /* Section 9.2.8 of the OpenGL 4.6 specification says:
3460    *
3461    *    "If texture refers to an immutable-format texture, level must be
3462    *     greater than or equal to zero and smaller than the value of
3463    *     TEXTURE_VIEW_NUM_LEVELS for texture."
3464    */
3465   const int max_levels = texObj->Immutable ? texObj->ImmutableLevels :
3466                          _mesa_max_texture_levels(ctx, target);
3467
3468   if (level < 0 || level >= max_levels) {
3469      _mesa_error(ctx, GL_INVALID_VALUE,
3470                  "%s(invalid level %d)", caller, level);
3471      return false;
3472   }
3473
3474   return true;
3475}
3476
3477
3478struct gl_renderbuffer_attachment *
3479_mesa_get_and_validate_attachment(struct gl_context *ctx,
3480                                  struct gl_framebuffer *fb,
3481                                  GLenum attachment, const char *caller)
3482{
3483   /* The window-system framebuffer object is immutable */
3484   if (_mesa_is_winsys_fbo(fb)) {
3485      _mesa_error(ctx, GL_INVALID_OPERATION, "%s(window-system framebuffer)",
3486                  caller);
3487      return NULL;
3488   }
3489
3490   /* Not a hash lookup, so we can afford to get the attachment here. */
3491   bool is_color_attachment;
3492   struct gl_renderbuffer_attachment *att =
3493      get_attachment(ctx, fb, attachment, &is_color_attachment);
3494   if (att == NULL) {
3495      if (is_color_attachment) {
3496         _mesa_error(ctx, GL_INVALID_OPERATION,
3497                     "%s(invalid color attachment %s)", caller,
3498                     _mesa_enum_to_string(attachment));
3499      } else {
3500         _mesa_error(ctx, GL_INVALID_ENUM,
3501                     "%s(invalid attachment %s)", caller,
3502                     _mesa_enum_to_string(attachment));
3503      }
3504      return NULL;
3505   }
3506
3507   return att;
3508}
3509
3510
3511void
3512_mesa_framebuffer_texture(struct gl_context *ctx, struct gl_framebuffer *fb,
3513                          GLenum attachment,
3514                          struct gl_renderbuffer_attachment *att,
3515                          struct gl_texture_object *texObj, GLenum textarget,
3516                          GLint level, GLsizei samples,
3517                          GLuint layer, GLboolean layered)
3518{
3519   FLUSH_VERTICES(ctx, _NEW_BUFFERS);
3520
3521   simple_mtx_lock(&fb->Mutex);
3522   if (texObj) {
3523      if (attachment == GL_DEPTH_ATTACHMENT &&
3524          texObj == fb->Attachment[BUFFER_STENCIL].Texture &&
3525          level == fb->Attachment[BUFFER_STENCIL].TextureLevel &&
3526          _mesa_tex_target_to_face(textarget) ==
3527          fb->Attachment[BUFFER_STENCIL].CubeMapFace &&
3528          samples == fb->Attachment[BUFFER_STENCIL].NumSamples &&
3529          layer == fb->Attachment[BUFFER_STENCIL].Zoffset) {
3530         /* The texture object is already attached to the stencil attachment
3531          * point. Don't create a new renderbuffer; just reuse the stencil
3532          * attachment's. This is required to prevent a GL error in
3533          * glGetFramebufferAttachmentParameteriv(GL_DEPTH_STENCIL).
3534          */
3535         reuse_framebuffer_texture_attachment(fb, BUFFER_DEPTH,
3536                                              BUFFER_STENCIL);
3537      } else if (attachment == GL_STENCIL_ATTACHMENT &&
3538                 texObj == fb->Attachment[BUFFER_DEPTH].Texture &&
3539                 level == fb->Attachment[BUFFER_DEPTH].TextureLevel &&
3540                 _mesa_tex_target_to_face(textarget) ==
3541                 fb->Attachment[BUFFER_DEPTH].CubeMapFace &&
3542                 samples == fb->Attachment[BUFFER_DEPTH].NumSamples &&
3543                 layer == fb->Attachment[BUFFER_DEPTH].Zoffset) {
3544         /* As above, but with depth and stencil transposed. */
3545         reuse_framebuffer_texture_attachment(fb, BUFFER_STENCIL,
3546                                              BUFFER_DEPTH);
3547      } else {
3548         set_texture_attachment(ctx, fb, att, texObj, textarget,
3549                                level, samples, layer, layered);
3550
3551         if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) {
3552            /* Above we created a new renderbuffer and attached it to the
3553             * depth attachment point. Now attach it to the stencil attachment
3554             * point too.
3555             */
3556            assert(att == &fb->Attachment[BUFFER_DEPTH]);
3557            reuse_framebuffer_texture_attachment(fb,BUFFER_STENCIL,
3558                                                 BUFFER_DEPTH);
3559         }
3560      }
3561
3562      /* Set the render-to-texture flag.  We'll check this flag in
3563       * glTexImage() and friends to determine if we need to revalidate
3564       * any FBOs that might be rendering into this texture.
3565       * This flag never gets cleared since it's non-trivial to determine
3566       * when all FBOs might be done rendering to this texture.  That's OK
3567       * though since it's uncommon to render to a texture then repeatedly
3568       * call glTexImage() to change images in the texture.
3569       */
3570      texObj->_RenderToTexture = GL_TRUE;
3571   }
3572   else {
3573      remove_attachment(ctx, att);
3574      if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) {
3575         assert(att == &fb->Attachment[BUFFER_DEPTH]);
3576         remove_attachment(ctx, &fb->Attachment[BUFFER_STENCIL]);
3577      }
3578   }
3579
3580   invalidate_framebuffer(fb);
3581
3582   simple_mtx_unlock(&fb->Mutex);
3583}
3584
3585
3586static void
3587framebuffer_texture_with_dims_no_error(GLenum target, GLenum attachment,
3588                                       GLenum textarget, GLuint texture,
3589                                       GLint level, GLint layer)
3590{
3591   GET_CURRENT_CONTEXT(ctx);
3592
3593   /* Get the framebuffer object */
3594   struct gl_framebuffer *fb = get_framebuffer_target(ctx, target);
3595
3596   /* Get the texture object */
3597   struct gl_texture_object *texObj =
3598      get_texture_for_framebuffer(ctx, texture);
3599
3600   struct gl_renderbuffer_attachment *att =
3601      get_attachment(ctx, fb, attachment, NULL);
3602
3603   _mesa_framebuffer_texture(ctx, fb, attachment, att, texObj, textarget,
3604                             level, 0, layer, GL_FALSE);
3605}
3606
3607
3608static void
3609framebuffer_texture_with_dims(int dims, GLenum target,
3610                              GLenum attachment, GLenum textarget,
3611                              GLuint texture, GLint level, GLsizei samples,
3612                              GLint layer, const char *caller)
3613{
3614   GET_CURRENT_CONTEXT(ctx);
3615   struct gl_framebuffer *fb;
3616   struct gl_texture_object *texObj;
3617
3618   /* Get the framebuffer object */
3619   fb = get_framebuffer_target(ctx, target);
3620   if (!fb) {
3621      _mesa_error(ctx, GL_INVALID_ENUM, "%s(invalid target %s)", caller,
3622                  _mesa_enum_to_string(target));
3623      return;
3624   }
3625
3626   /* Get the texture object */
3627   if (!get_texture_for_framebuffer_err(ctx, texture, false, caller, &texObj))
3628      return;
3629
3630   if (texObj) {
3631      if (!check_textarget(ctx, dims, texObj->Target, textarget, caller))
3632         return;
3633
3634      if ((dims == 3) && !check_layer(ctx, texObj->Target, layer, caller))
3635         return;
3636
3637      if (!check_level(ctx, texObj, textarget, level, caller))
3638         return;
3639   }
3640
3641   struct gl_renderbuffer_attachment *att =
3642      _mesa_get_and_validate_attachment(ctx, fb, attachment, caller);
3643   if (!att)
3644      return;
3645
3646   _mesa_framebuffer_texture(ctx, fb, attachment, att, texObj, textarget,
3647                             level, samples, layer, GL_FALSE);
3648}
3649
3650
3651void GLAPIENTRY
3652_mesa_FramebufferTexture1D_no_error(GLenum target, GLenum attachment,
3653                                    GLenum textarget, GLuint texture,
3654                                    GLint level)
3655{
3656   framebuffer_texture_with_dims_no_error(target, attachment, textarget,
3657                                          texture, level, 0);
3658}
3659
3660
3661void GLAPIENTRY
3662_mesa_FramebufferTexture1D(GLenum target, GLenum attachment,
3663                           GLenum textarget, GLuint texture, GLint level)
3664{
3665   framebuffer_texture_with_dims(1, target, attachment, textarget, texture,
3666                                 level, 0, 0, "glFramebufferTexture1D");
3667}
3668
3669
3670void GLAPIENTRY
3671_mesa_FramebufferTexture2D_no_error(GLenum target, GLenum attachment,
3672                                    GLenum textarget, GLuint texture,
3673                                    GLint level)
3674{
3675   framebuffer_texture_with_dims_no_error(target, attachment, textarget,
3676                                          texture, level, 0);
3677}
3678
3679
3680void GLAPIENTRY
3681_mesa_FramebufferTexture2D(GLenum target, GLenum attachment,
3682                           GLenum textarget, GLuint texture, GLint level)
3683{
3684   framebuffer_texture_with_dims(2, target, attachment, textarget, texture,
3685                                 level, 0, 0, "glFramebufferTexture2D");
3686}
3687
3688
3689void GLAPIENTRY
3690_mesa_FramebufferTexture2DMultisampleEXT(GLenum target, GLenum attachment,
3691                                         GLenum textarget, GLuint texture,
3692                                         GLint level, GLsizei samples)
3693{
3694   framebuffer_texture_with_dims(2, target, attachment, textarget, texture,
3695                                 level, samples, 0, "glFramebufferTexture2DMultisampleEXT");
3696}
3697
3698
3699void GLAPIENTRY
3700_mesa_FramebufferTexture3D_no_error(GLenum target, GLenum attachment,
3701                                    GLenum textarget, GLuint texture,
3702                                    GLint level, GLint layer)
3703{
3704   framebuffer_texture_with_dims_no_error(target, attachment, textarget,
3705                                          texture, level, layer);
3706}
3707
3708
3709void GLAPIENTRY
3710_mesa_FramebufferTexture3D(GLenum target, GLenum attachment,
3711                           GLenum textarget, GLuint texture,
3712                           GLint level, GLint layer)
3713{
3714   framebuffer_texture_with_dims(3, target, attachment, textarget, texture,
3715                                 level, 0, layer, "glFramebufferTexture3D");
3716}
3717
3718
3719static ALWAYS_INLINE void
3720frame_buffer_texture(GLuint framebuffer, GLenum target,
3721                     GLenum attachment, GLuint texture,
3722                     GLint level, GLint layer, const char *func,
3723                     bool dsa, bool no_error, bool check_layered)
3724{
3725   GET_CURRENT_CONTEXT(ctx);
3726   GLboolean layered = GL_FALSE;
3727
3728   if (!no_error && check_layered) {
3729      if (!_mesa_has_geometry_shaders(ctx)) {
3730         _mesa_error(ctx, GL_INVALID_OPERATION,
3731                     "unsupported function (%s) called", func);
3732         return;
3733      }
3734   }
3735
3736   /* Get the framebuffer object */
3737   struct gl_framebuffer *fb;
3738   if (no_error) {
3739      if (dsa) {
3740         fb = _mesa_lookup_framebuffer(ctx, framebuffer);
3741      } else {
3742         fb = get_framebuffer_target(ctx, target);
3743      }
3744   } else {
3745      if (dsa) {
3746         fb = _mesa_lookup_framebuffer_err(ctx, framebuffer, func);
3747         if (!fb)
3748            return;
3749      } else {
3750         fb = get_framebuffer_target(ctx, target);
3751         if (!fb) {
3752            _mesa_error(ctx, GL_INVALID_ENUM, "%s(invalid target %s)",
3753                        func, _mesa_enum_to_string(target));
3754            return;
3755         }
3756      }
3757   }
3758
3759   /* Get the texture object and framebuffer attachment*/
3760   struct gl_renderbuffer_attachment *att;
3761   struct gl_texture_object *texObj;
3762   if (no_error) {
3763      texObj = get_texture_for_framebuffer(ctx, texture);
3764      att = get_attachment(ctx, fb, attachment, NULL);
3765   } else {
3766      if (!get_texture_for_framebuffer_err(ctx, texture, check_layered, func,
3767                                           &texObj))
3768         return;
3769
3770      att = _mesa_get_and_validate_attachment(ctx, fb, attachment, func);
3771      if (!att)
3772         return;
3773   }
3774
3775   GLenum textarget = 0;
3776   if (texObj) {
3777      if (check_layered) {
3778         /* We do this regardless of no_error because this sets layered */
3779         if (!check_layered_texture_target(ctx, texObj->Target, func,
3780                                           &layered))
3781            return;
3782      }
3783
3784      if (!no_error) {
3785         if (!check_layered) {
3786            if (!check_texture_target(ctx, texObj->Target, func))
3787               return;
3788
3789            if (!check_layer(ctx, texObj->Target, layer, func))
3790               return;
3791         }
3792
3793         if (!check_level(ctx, texObj, texObj->Target, level, func))
3794            return;
3795      }
3796
3797      if (!check_layered && texObj->Target == GL_TEXTURE_CUBE_MAP) {
3798         assert(layer >= 0 && layer < 6);
3799         textarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + layer;
3800         layer = 0;
3801      }
3802   }
3803
3804   _mesa_framebuffer_texture(ctx, fb, attachment, att, texObj, textarget,
3805                             level, 0, layer, layered);
3806}
3807
3808void GLAPIENTRY
3809_mesa_FramebufferTextureLayer_no_error(GLenum target, GLenum attachment,
3810                                       GLuint texture, GLint level,
3811                                       GLint layer)
3812{
3813   frame_buffer_texture(0, target, attachment, texture, level, layer,
3814                        "glFramebufferTextureLayer", false, true, false);
3815}
3816
3817
3818void GLAPIENTRY
3819_mesa_FramebufferTextureLayer(GLenum target, GLenum attachment,
3820                              GLuint texture, GLint level, GLint layer)
3821{
3822   frame_buffer_texture(0, target, attachment, texture, level, layer,
3823                        "glFramebufferTextureLayer", false, false, false);
3824}
3825
3826
3827void GLAPIENTRY
3828_mesa_NamedFramebufferTextureLayer_no_error(GLuint framebuffer,
3829                                            GLenum attachment,
3830                                            GLuint texture, GLint level,
3831                                            GLint layer)
3832{
3833   frame_buffer_texture(framebuffer, 0, attachment, texture, level, layer,
3834                        "glNamedFramebufferTextureLayer", true, true, false);
3835}
3836
3837
3838void GLAPIENTRY
3839_mesa_NamedFramebufferTextureLayer(GLuint framebuffer, GLenum attachment,
3840                                   GLuint texture, GLint level, GLint layer)
3841{
3842   frame_buffer_texture(framebuffer, 0, attachment, texture, level, layer,
3843                        "glNamedFramebufferTextureLayer", true, false, false);
3844}
3845
3846
3847void GLAPIENTRY
3848_mesa_FramebufferTexture_no_error(GLenum target, GLenum attachment,
3849                                  GLuint texture, GLint level)
3850{
3851   frame_buffer_texture(0, target, attachment, texture, level, 0,
3852                        "glFramebufferTexture", false, true, true);
3853}
3854
3855
3856void GLAPIENTRY
3857_mesa_FramebufferTexture(GLenum target, GLenum attachment,
3858                         GLuint texture, GLint level)
3859{
3860   frame_buffer_texture(0, target, attachment, texture, level, 0,
3861                        "glFramebufferTexture", false, false, true);
3862}
3863
3864void GLAPIENTRY
3865_mesa_NamedFramebufferTexture_no_error(GLuint framebuffer, GLenum attachment,
3866                                       GLuint texture, GLint level)
3867{
3868   frame_buffer_texture(framebuffer, 0, attachment, texture, level, 0,
3869                        "glNamedFramebufferTexture", true, true, true);
3870}
3871
3872
3873void GLAPIENTRY
3874_mesa_NamedFramebufferTexture(GLuint framebuffer, GLenum attachment,
3875                              GLuint texture, GLint level)
3876{
3877   frame_buffer_texture(framebuffer, 0, attachment, texture, level, 0,
3878                        "glNamedFramebufferTexture", true, false, true);
3879}
3880
3881
3882void
3883_mesa_framebuffer_renderbuffer(struct gl_context *ctx,
3884                               struct gl_framebuffer *fb,
3885                               GLenum attachment,
3886                               struct gl_renderbuffer *rb)
3887{
3888   assert(!_mesa_is_winsys_fbo(fb));
3889
3890   FLUSH_VERTICES(ctx, _NEW_BUFFERS);
3891
3892   assert(ctx->Driver.FramebufferRenderbuffer);
3893   ctx->Driver.FramebufferRenderbuffer(ctx, fb, attachment, rb);
3894
3895   /* Some subsequent GL commands may depend on the framebuffer's visual
3896    * after the binding is updated.  Update visual info now.
3897    */
3898   _mesa_update_framebuffer_visual(ctx, fb);
3899}
3900
3901static ALWAYS_INLINE void
3902framebuffer_renderbuffer(struct gl_context *ctx, struct gl_framebuffer *fb,
3903                         GLenum attachment, GLenum renderbuffertarget,
3904                         GLuint renderbuffer, const char *func, bool no_error)
3905{
3906   struct gl_renderbuffer_attachment *att;
3907   struct gl_renderbuffer *rb;
3908   bool is_color_attachment;
3909
3910   if (!no_error && renderbuffertarget != GL_RENDERBUFFER) {
3911      _mesa_error(ctx, GL_INVALID_ENUM,
3912                  "%s(renderbuffertarget is not GL_RENDERBUFFER)", func);
3913      return;
3914   }
3915
3916   if (renderbuffer) {
3917      if (!no_error) {
3918         rb = _mesa_lookup_renderbuffer_err(ctx, renderbuffer, func);
3919         if (!rb)
3920            return;
3921      } else {
3922         rb = _mesa_lookup_renderbuffer(ctx, renderbuffer);
3923      }
3924   } else {
3925      /* remove renderbuffer attachment */
3926      rb = NULL;
3927   }
3928
3929   if (!no_error) {
3930      if (_mesa_is_winsys_fbo(fb)) {
3931         /* Can't attach new renderbuffers to a window system framebuffer */
3932         _mesa_error(ctx, GL_INVALID_OPERATION,
3933                     "%s(window-system framebuffer)", func);
3934         return;
3935      }
3936
3937      att = get_attachment(ctx, fb, attachment, &is_color_attachment);
3938      if (att == NULL) {
3939         /*
3940          * From OpenGL 4.5 spec, section 9.2.7 "Attaching Renderbuffer Images
3941          * to a Framebuffer":
3942          *
3943          *    "An INVALID_OPERATION error is generated if attachment is
3944          *    COLOR_- ATTACHMENTm where m is greater than or equal to the
3945          *    value of MAX_COLOR_- ATTACHMENTS ."
3946          *
3947          * If we are at this point, is because the attachment is not valid, so
3948          * if is_color_attachment is true, is because of the previous reason.
3949          */
3950         if (is_color_attachment) {
3951            _mesa_error(ctx, GL_INVALID_OPERATION,
3952                        "%s(invalid color attachment %s)", func,
3953                        _mesa_enum_to_string(attachment));
3954         } else {
3955            _mesa_error(ctx, GL_INVALID_ENUM,
3956                        "%s(invalid attachment %s)", func,
3957                        _mesa_enum_to_string(attachment));
3958         }
3959
3960         return;
3961      }
3962
3963      if (attachment == GL_DEPTH_STENCIL_ATTACHMENT &&
3964          rb && rb->Format != MESA_FORMAT_NONE) {
3965         /* make sure the renderbuffer is a depth/stencil format */
3966         const GLenum baseFormat = _mesa_get_format_base_format(rb->Format);
3967         if (baseFormat != GL_DEPTH_STENCIL) {
3968            _mesa_error(ctx, GL_INVALID_OPERATION,
3969                        "%s(renderbuffer is not DEPTH_STENCIL format)", func);
3970            return;
3971         }
3972      }
3973   }
3974
3975   _mesa_framebuffer_renderbuffer(ctx, fb, attachment, rb);
3976}
3977
3978static void
3979framebuffer_renderbuffer_error(struct gl_context *ctx,
3980                               struct gl_framebuffer *fb, GLenum attachment,
3981                               GLenum renderbuffertarget,
3982                               GLuint renderbuffer, const char *func)
3983{
3984   framebuffer_renderbuffer(ctx, fb, attachment, renderbuffertarget,
3985                            renderbuffer, func, false);
3986}
3987
3988static void
3989framebuffer_renderbuffer_no_error(struct gl_context *ctx,
3990                                  struct gl_framebuffer *fb, GLenum attachment,
3991                                  GLenum renderbuffertarget,
3992                                  GLuint renderbuffer, const char *func)
3993{
3994   framebuffer_renderbuffer(ctx, fb, attachment, renderbuffertarget,
3995                            renderbuffer, func, true);
3996}
3997
3998void GLAPIENTRY
3999_mesa_FramebufferRenderbuffer_no_error(GLenum target, GLenum attachment,
4000                                       GLenum renderbuffertarget,
4001                                       GLuint renderbuffer)
4002{
4003   GET_CURRENT_CONTEXT(ctx);
4004
4005   struct gl_framebuffer *fb = get_framebuffer_target(ctx, target);
4006   framebuffer_renderbuffer_no_error(ctx, fb, attachment, renderbuffertarget,
4007                                     renderbuffer, "glFramebufferRenderbuffer");
4008}
4009
4010void GLAPIENTRY
4011_mesa_FramebufferRenderbuffer(GLenum target, GLenum attachment,
4012                              GLenum renderbuffertarget,
4013                              GLuint renderbuffer)
4014{
4015   struct gl_framebuffer *fb;
4016   GET_CURRENT_CONTEXT(ctx);
4017
4018   fb = get_framebuffer_target(ctx, target);
4019   if (!fb) {
4020      _mesa_error(ctx, GL_INVALID_ENUM,
4021                  "glFramebufferRenderbuffer(invalid target %s)",
4022                  _mesa_enum_to_string(target));
4023      return;
4024   }
4025
4026   framebuffer_renderbuffer_error(ctx, fb, attachment, renderbuffertarget,
4027                                  renderbuffer, "glFramebufferRenderbuffer");
4028}
4029
4030void GLAPIENTRY
4031_mesa_NamedFramebufferRenderbuffer_no_error(GLuint framebuffer,
4032                                            GLenum attachment,
4033                                            GLenum renderbuffertarget,
4034                                            GLuint renderbuffer)
4035{
4036   GET_CURRENT_CONTEXT(ctx);
4037
4038   struct gl_framebuffer *fb = _mesa_lookup_framebuffer(ctx, framebuffer);
4039   framebuffer_renderbuffer_no_error(ctx, fb, attachment, renderbuffertarget,
4040                                     renderbuffer,
4041                                     "glNamedFramebufferRenderbuffer");
4042}
4043
4044void GLAPIENTRY
4045_mesa_NamedFramebufferRenderbuffer(GLuint framebuffer, GLenum attachment,
4046                                   GLenum renderbuffertarget,
4047                                   GLuint renderbuffer)
4048{
4049   struct gl_framebuffer *fb;
4050   GET_CURRENT_CONTEXT(ctx);
4051
4052   fb = _mesa_lookup_framebuffer_err(ctx, framebuffer,
4053                                     "glNamedFramebufferRenderbuffer");
4054   if (!fb)
4055      return;
4056
4057   framebuffer_renderbuffer_error(ctx, fb, attachment, renderbuffertarget,
4058                                  renderbuffer,
4059                                  "glNamedFramebufferRenderbuffer");
4060}
4061
4062
4063static void
4064get_framebuffer_attachment_parameter(struct gl_context *ctx,
4065                                     struct gl_framebuffer *buffer,
4066                                     GLenum attachment, GLenum pname,
4067                                     GLint *params, const char *caller)
4068{
4069   const struct gl_renderbuffer_attachment *att;
4070   bool is_color_attachment = false;
4071   GLenum err;
4072
4073   /* The error code for an attachment type of GL_NONE differs between APIs.
4074    *
4075    * From the ES 2.0.25 specification, page 127:
4076    * "If the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is NONE, then
4077    *  querying any other pname will generate INVALID_ENUM."
4078    *
4079    * From the OpenGL 3.0 specification, page 337, or identically,
4080    * the OpenGL ES 3.0.4 specification, page 240:
4081    *
4082    * "If the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is NONE, no
4083    *  framebuffer is bound to target.  In this case querying pname
4084    *  FRAMEBUFFER_ATTACHMENT_OBJECT_NAME will return zero, and all other
4085    *  queries will generate an INVALID_OPERATION error."
4086    */
4087   err = ctx->API == API_OPENGLES2 && ctx->Version < 30 ?
4088      GL_INVALID_ENUM : GL_INVALID_OPERATION;
4089
4090   if (_mesa_is_winsys_fbo(buffer)) {
4091      /* Page 126 (page 136 of the PDF) of the OpenGL ES 2.0.25 spec
4092       * says:
4093       *
4094       *     "If the framebuffer currently bound to target is zero, then
4095       *     INVALID_OPERATION is generated."
4096       *
4097       * The EXT_framebuffer_object spec has the same wording, and the
4098       * OES_framebuffer_object spec refers to the EXT_framebuffer_object
4099       * spec.
4100       */
4101      if ((!_mesa_is_desktop_gl(ctx) ||
4102           !ctx->Extensions.ARB_framebuffer_object)
4103          && !_mesa_is_gles3(ctx)) {
4104         _mesa_error(ctx, GL_INVALID_OPERATION,
4105                     "%s(window-system framebuffer)", caller);
4106         return;
4107      }
4108
4109      if (_mesa_is_gles3(ctx) && attachment != GL_BACK &&
4110          attachment != GL_DEPTH && attachment != GL_STENCIL) {
4111         _mesa_error(ctx, GL_INVALID_ENUM,
4112                     "%s(invalid attachment %s)", caller,
4113                     _mesa_enum_to_string(attachment));
4114         return;
4115      }
4116
4117      /* The specs are not clear about how to handle
4118       * GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME with the default framebuffer,
4119       * but dEQP-GLES3 expects an INVALID_ENUM error. This has also been
4120       * discussed in:
4121       *
4122       * https://cvs.khronos.org/bugzilla/show_bug.cgi?id=12928#c1
4123       * and https://bugs.freedesktop.org/show_bug.cgi?id=31947
4124       */
4125      if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME) {
4126         _mesa_error(ctx, GL_INVALID_ENUM,
4127                     "%s(requesting GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME "
4128                     "when GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is "
4129                     "GL_FRAMEBUFFER_DEFAULT is not allowed)", caller);
4130         return;
4131      }
4132
4133      /* the default / window-system FBO */
4134      att = get_fb0_attachment(ctx, buffer, attachment);
4135   }
4136   else {
4137      /* user-created framebuffer FBO */
4138      att = get_attachment(ctx, buffer, attachment, &is_color_attachment);
4139   }
4140
4141   if (att == NULL) {
4142      /*
4143       * From OpenGL 4.5 spec, section 9.2.3 "Framebuffer Object Queries":
4144       *
4145       *    "An INVALID_OPERATION error is generated if a framebuffer object
4146       *     is bound to target and attachment is COLOR_ATTACHMENTm where m is
4147       *     greater than or equal to the value of MAX_COLOR_ATTACHMENTS."
4148       *
4149       * If we are at this point, is because the attachment is not valid, so
4150       * if is_color_attachment is true, is because of the previous reason.
4151       */
4152      if (is_color_attachment) {
4153         _mesa_error(ctx, GL_INVALID_OPERATION, "%s(invalid color attachment %s)",
4154                     caller, _mesa_enum_to_string(attachment));
4155      } else {
4156         _mesa_error(ctx, GL_INVALID_ENUM, "%s(invalid attachment %s)", caller,
4157                     _mesa_enum_to_string(attachment));
4158      }
4159      return;
4160   }
4161
4162   if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) {
4163      const struct gl_renderbuffer_attachment *depthAtt, *stencilAtt;
4164      if (pname == GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE) {
4165         /* This behavior is first specified in OpenGL 4.4 specification.
4166          *
4167          * From the OpenGL 4.4 spec page 275:
4168          *   "This query cannot be performed for a combined depth+stencil
4169          *    attachment, since it does not have a single format."
4170          */
4171         _mesa_error(ctx, GL_INVALID_OPERATION,
4172                     "%s(GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE"
4173                     " is invalid for depth+stencil attachment)", caller);
4174         return;
4175      }
4176      /* the depth and stencil attachments must point to the same buffer */
4177      depthAtt = get_attachment(ctx, buffer, GL_DEPTH_ATTACHMENT, NULL);
4178      stencilAtt = get_attachment(ctx, buffer, GL_STENCIL_ATTACHMENT, NULL);
4179      if (depthAtt->Renderbuffer != stencilAtt->Renderbuffer) {
4180         _mesa_error(ctx, GL_INVALID_OPERATION,
4181                     "%s(DEPTH/STENCIL attachments differ)", caller);
4182         return;
4183      }
4184   }
4185
4186   /* No need to flush here */
4187
4188   switch (pname) {
4189   case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT:
4190      /* From the OpenGL spec, 9.2. Binding and Managing Framebuffer Objects:
4191       *
4192       * "If the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is NONE, then
4193       *  either no framebuffer is bound to target; or the default framebuffer
4194       *  is bound, attachment is DEPTH or STENCIL, and the number of depth or
4195       *  stencil bits, respectively, is zero."
4196       *
4197       * Note that we don't need explicit checks on DEPTH and STENCIL, because
4198       * on the case the spec is pointing, att->Type is already NONE, so we
4199       * just need to check att->Type.
4200       */
4201      *params = (_mesa_is_winsys_fbo(buffer) && att->Type != GL_NONE) ?
4202         GL_FRAMEBUFFER_DEFAULT : att->Type;
4203      return;
4204   case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT:
4205      if (att->Type == GL_RENDERBUFFER_EXT) {
4206         *params = att->Renderbuffer->Name;
4207      }
4208      else if (att->Type == GL_TEXTURE) {
4209         *params = att->Texture->Name;
4210      }
4211      else {
4212         assert(att->Type == GL_NONE);
4213         if (_mesa_is_desktop_gl(ctx) || _mesa_is_gles3(ctx)) {
4214            *params = 0;
4215         } else {
4216            goto invalid_pname_enum;
4217         }
4218      }
4219      return;
4220   case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT:
4221      if (att->Type == GL_TEXTURE) {
4222         *params = att->TextureLevel;
4223      }
4224      else if (att->Type == GL_NONE) {
4225         _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4226                     _mesa_enum_to_string(pname));
4227      }
4228      else {
4229         goto invalid_pname_enum;
4230      }
4231      return;
4232   case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT:
4233      if (att->Type == GL_TEXTURE) {
4234         if (att->Texture && att->Texture->Target == GL_TEXTURE_CUBE_MAP) {
4235            *params = GL_TEXTURE_CUBE_MAP_POSITIVE_X + att->CubeMapFace;
4236         }
4237         else {
4238            *params = 0;
4239         }
4240      }
4241      else if (att->Type == GL_NONE) {
4242         _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4243                     _mesa_enum_to_string(pname));
4244      }
4245      else {
4246         goto invalid_pname_enum;
4247      }
4248      return;
4249   case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT:
4250      if (ctx->API == API_OPENGLES) {
4251         goto invalid_pname_enum;
4252      } else if (att->Type == GL_NONE) {
4253         _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4254                     _mesa_enum_to_string(pname));
4255      } else if (att->Type == GL_TEXTURE) {
4256         if (att->Texture && (att->Texture->Target == GL_TEXTURE_3D ||
4257             att->Texture->Target == GL_TEXTURE_2D_ARRAY)) {
4258            *params = att->Zoffset;
4259         }
4260         else {
4261            *params = 0;
4262         }
4263      }
4264      else {
4265         goto invalid_pname_enum;
4266      }
4267      return;
4268   case GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:
4269      if ((!_mesa_is_desktop_gl(ctx) ||
4270           !ctx->Extensions.ARB_framebuffer_object)
4271          && !_mesa_is_gles3(ctx)) {
4272         goto invalid_pname_enum;
4273      }
4274      else if (att->Type == GL_NONE) {
4275         if (_mesa_is_winsys_fbo(buffer) &&
4276             (attachment == GL_DEPTH || attachment == GL_STENCIL)) {
4277            *params = GL_LINEAR;
4278         } else {
4279            _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4280                        _mesa_enum_to_string(pname));
4281         }
4282      }
4283      else {
4284         if (ctx->Extensions.EXT_sRGB) {
4285            *params =
4286               _mesa_get_format_color_encoding(att->Renderbuffer->Format);
4287         }
4288         else {
4289            /* According to ARB_framebuffer_sRGB, we should return LINEAR
4290             * if the sRGB conversion is unsupported. */
4291            *params = GL_LINEAR;
4292         }
4293      }
4294      return;
4295   case GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE:
4296      if ((ctx->API != API_OPENGL_COMPAT ||
4297           !ctx->Extensions.ARB_framebuffer_object)
4298          && ctx->API != API_OPENGL_CORE
4299          && !_mesa_is_gles3(ctx)) {
4300         goto invalid_pname_enum;
4301      }
4302      else if (att->Type == GL_NONE) {
4303         _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4304                     _mesa_enum_to_string(pname));
4305      }
4306      else {
4307         mesa_format format = att->Renderbuffer->Format;
4308
4309         /* Page 235 (page 247 of the PDF) in section 6.1.13 of the OpenGL ES
4310          * 3.0.1 spec says:
4311          *
4312          *     "If pname is FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE.... If
4313          *     attachment is DEPTH_STENCIL_ATTACHMENT the query will fail and
4314          *     generate an INVALID_OPERATION error.
4315          */
4316         if (_mesa_is_gles3(ctx) &&
4317             attachment == GL_DEPTH_STENCIL_ATTACHMENT) {
4318            _mesa_error(ctx, GL_INVALID_OPERATION,
4319                        "%s(cannot query "
4320                        "GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE of "
4321                        "GL_DEPTH_STENCIL_ATTACHMENT)", caller);
4322            return;
4323         }
4324
4325         if (format == MESA_FORMAT_S_UINT8) {
4326            /* special cases */
4327            *params = GL_INDEX;
4328         }
4329         else if (format == MESA_FORMAT_Z32_FLOAT_S8X24_UINT) {
4330            /* depends on the attachment parameter */
4331            if (attachment == GL_STENCIL_ATTACHMENT) {
4332               *params = GL_INDEX;
4333            }
4334            else {
4335               *params = GL_FLOAT;
4336            }
4337         }
4338         else {
4339            *params = _mesa_get_format_datatype(format);
4340         }
4341      }
4342      return;
4343   case GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE:
4344   case GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:
4345   case GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE:
4346   case GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE:
4347   case GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE:
4348   case GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE:
4349      if ((!_mesa_is_desktop_gl(ctx) ||
4350           !ctx->Extensions.ARB_framebuffer_object)
4351          && !_mesa_is_gles3(ctx)) {
4352         goto invalid_pname_enum;
4353      }
4354      else if (att->Texture) {
4355         const struct gl_texture_image *texImage =
4356            _mesa_select_tex_image(att->Texture, att->Texture->Target,
4357                                   att->TextureLevel);
4358         if (texImage) {
4359            *params = get_component_bits(pname, texImage->_BaseFormat,
4360                                         texImage->TexFormat);
4361         }
4362         else {
4363            *params = 0;
4364         }
4365      }
4366      else if (att->Renderbuffer) {
4367         *params = get_component_bits(pname, att->Renderbuffer->_BaseFormat,
4368                                      att->Renderbuffer->Format);
4369      }
4370      else {
4371         assert(att->Type == GL_NONE);
4372         _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4373                     _mesa_enum_to_string(pname));
4374      }
4375      return;
4376   case GL_FRAMEBUFFER_ATTACHMENT_LAYERED:
4377      if (!_mesa_has_geometry_shaders(ctx)) {
4378         goto invalid_pname_enum;
4379      } else if (att->Type == GL_TEXTURE) {
4380         *params = att->Layered;
4381      } else if (att->Type == GL_NONE) {
4382         _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4383                     _mesa_enum_to_string(pname));
4384      } else {
4385         goto invalid_pname_enum;
4386      }
4387      return;
4388   case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT:
4389      if (!ctx->Extensions.EXT_multisampled_render_to_texture) {
4390         goto invalid_pname_enum;
4391      } else if (att->Type == GL_TEXTURE) {
4392         *params = att->NumSamples;
4393      } else if (att->Type == GL_NONE) {
4394         _mesa_error(ctx, err, "%s(invalid pname %s)", caller,
4395                     _mesa_enum_to_string(pname));
4396      } else {
4397         goto invalid_pname_enum;
4398      }
4399      return;
4400   default:
4401      goto invalid_pname_enum;
4402   }
4403
4404   return;
4405
4406invalid_pname_enum:
4407   _mesa_error(ctx, GL_INVALID_ENUM, "%s(invalid pname %s)", caller,
4408               _mesa_enum_to_string(pname));
4409   return;
4410}
4411
4412
4413void GLAPIENTRY
4414_mesa_GetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment,
4415                                          GLenum pname, GLint *params)
4416{
4417   GET_CURRENT_CONTEXT(ctx);
4418   struct gl_framebuffer *buffer;
4419
4420   buffer = get_framebuffer_target(ctx, target);
4421   if (!buffer) {
4422      _mesa_error(ctx, GL_INVALID_ENUM,
4423                  "glGetFramebufferAttachmentParameteriv(invalid target %s)",
4424                  _mesa_enum_to_string(target));
4425      return;
4426   }
4427
4428   get_framebuffer_attachment_parameter(ctx, buffer, attachment, pname,
4429                                        params,
4430                                    "glGetFramebufferAttachmentParameteriv");
4431}
4432
4433
4434void GLAPIENTRY
4435_mesa_GetNamedFramebufferAttachmentParameteriv(GLuint framebuffer,
4436                                               GLenum attachment,
4437                                               GLenum pname, GLint *params)
4438{
4439   GET_CURRENT_CONTEXT(ctx);
4440   struct gl_framebuffer *buffer;
4441
4442   if (framebuffer) {
4443      buffer = _mesa_lookup_framebuffer_err(ctx, framebuffer,
4444                              "glGetNamedFramebufferAttachmentParameteriv");
4445      if (!buffer)
4446         return;
4447   }
4448   else {
4449      /*
4450       * Section 9.2 Binding and Managing Framebuffer Objects of the OpenGL
4451       * 4.5 core spec (30.10.2014, PDF page 314):
4452       *    "If framebuffer is zero, then the default draw framebuffer is
4453       *    queried."
4454       */
4455      buffer = ctx->WinSysDrawBuffer;
4456   }
4457
4458   get_framebuffer_attachment_parameter(ctx, buffer, attachment, pname,
4459                                        params,
4460                              "glGetNamedFramebufferAttachmentParameteriv");
4461}
4462
4463
4464void GLAPIENTRY
4465_mesa_NamedFramebufferParameteri(GLuint framebuffer, GLenum pname,
4466                                 GLint param)
4467{
4468   GET_CURRENT_CONTEXT(ctx);
4469   struct gl_framebuffer *fb = NULL;
4470
4471   if (!ctx->Extensions.ARB_framebuffer_no_attachments &&
4472       !ctx->Extensions.ARB_sample_locations) {
4473      _mesa_error(ctx, GL_INVALID_OPERATION,
4474                  "glNamedFramebufferParameteri("
4475                  "neither ARB_framebuffer_no_attachments nor "
4476                  "ARB_sample_locations is available)");
4477      return;
4478   }
4479
4480   if (framebuffer) {
4481      fb = _mesa_lookup_framebuffer_err(ctx, framebuffer,
4482                                        "glNamedFramebufferParameteri");
4483   } else {
4484      fb = ctx->WinSysDrawBuffer;
4485   }
4486
4487   if (fb) {
4488      framebuffer_parameteri(ctx, fb, pname, param,
4489                             "glNamedFramebufferParameteriv");
4490   }
4491}
4492
4493
4494void GLAPIENTRY
4495_mesa_GetNamedFramebufferParameteriv(GLuint framebuffer, GLenum pname,
4496                                     GLint *param)
4497{
4498   GET_CURRENT_CONTEXT(ctx);
4499   struct gl_framebuffer *fb;
4500
4501   if (!ctx->Extensions.ARB_framebuffer_no_attachments) {
4502      _mesa_error(ctx, GL_INVALID_OPERATION,
4503                  "glNamedFramebufferParameteriv("
4504                  "neither ARB_framebuffer_no_attachments nor ARB_sample_locations"
4505                  " is available)");
4506      return;
4507   }
4508
4509   if (framebuffer)
4510      fb = _mesa_lookup_framebuffer_err(ctx, framebuffer,
4511                                        "glGetNamedFramebufferParameteriv");
4512   else
4513      fb = ctx->WinSysDrawBuffer;
4514
4515   if (fb) {
4516      get_framebuffer_parameteriv(ctx, fb, pname, param,
4517                                  "glGetNamedFramebufferParameteriv");
4518   }
4519}
4520
4521
4522static void
4523invalidate_framebuffer_storage(struct gl_context *ctx,
4524                               struct gl_framebuffer *fb,
4525                               GLsizei numAttachments,
4526                               const GLenum *attachments, GLint x, GLint y,
4527                               GLsizei width, GLsizei height, const char *name)
4528{
4529   int i;
4530
4531   /* Section 17.4 Whole Framebuffer Operations of the OpenGL 4.5 Core
4532    * Spec (2.2.2015, PDF page 522) says:
4533    *    "An INVALID_VALUE error is generated if numAttachments, width, or
4534    *    height is negative."
4535    */
4536   if (numAttachments < 0) {
4537      _mesa_error(ctx, GL_INVALID_VALUE,
4538                  "%s(numAttachments < 0)", name);
4539      return;
4540   }
4541
4542   if (width < 0) {
4543      _mesa_error(ctx, GL_INVALID_VALUE,
4544                  "%s(width < 0)", name);
4545      return;
4546   }
4547
4548   if (height < 0) {
4549      _mesa_error(ctx, GL_INVALID_VALUE,
4550                  "%s(height < 0)", name);
4551      return;
4552   }
4553
4554   /* The GL_ARB_invalidate_subdata spec says:
4555    *
4556    *     "If an attachment is specified that does not exist in the
4557    *     framebuffer bound to <target>, it is ignored."
4558    *
4559    * It also says:
4560    *
4561    *     "If <attachments> contains COLOR_ATTACHMENTm and m is greater than
4562    *     or equal to the value of MAX_COLOR_ATTACHMENTS, then the error
4563    *     INVALID_OPERATION is generated."
4564    *
4565    * No mention is made of GL_AUXi being out of range.  Therefore, we allow
4566    * any enum that can be allowed by the API (OpenGL ES 3.0 has a different
4567    * set of retrictions).
4568    */
4569   for (i = 0; i < numAttachments; i++) {
4570      if (_mesa_is_winsys_fbo(fb)) {
4571         switch (attachments[i]) {
4572         case GL_ACCUM:
4573         case GL_AUX0:
4574         case GL_AUX1:
4575         case GL_AUX2:
4576         case GL_AUX3:
4577            /* Accumulation buffers and auxilary buffers were removed in
4578             * OpenGL 3.1, and they never existed in OpenGL ES.
4579             */
4580            if (ctx->API != API_OPENGL_COMPAT)
4581               goto invalid_enum;
4582            break;
4583         case GL_COLOR:
4584         case GL_DEPTH:
4585         case GL_STENCIL:
4586            break;
4587         case GL_BACK_LEFT:
4588         case GL_BACK_RIGHT:
4589         case GL_FRONT_LEFT:
4590         case GL_FRONT_RIGHT:
4591            if (!_mesa_is_desktop_gl(ctx))
4592               goto invalid_enum;
4593            break;
4594         default:
4595            goto invalid_enum;
4596         }
4597      } else {
4598         switch (attachments[i]) {
4599         case GL_DEPTH_ATTACHMENT:
4600         case GL_STENCIL_ATTACHMENT:
4601            break;
4602         case GL_DEPTH_STENCIL_ATTACHMENT:
4603            /* GL_DEPTH_STENCIL_ATTACHMENT is a valid attachment point only
4604             * in desktop and ES 3.0 profiles. Note that OES_packed_depth_stencil
4605             * extension does not make this attachment point valid on ES 2.0.
4606             */
4607            if (_mesa_is_desktop_gl(ctx) || _mesa_is_gles3(ctx))
4608               break;
4609            /* fallthrough */
4610         case GL_COLOR_ATTACHMENT0:
4611         case GL_COLOR_ATTACHMENT1:
4612         case GL_COLOR_ATTACHMENT2:
4613         case GL_COLOR_ATTACHMENT3:
4614         case GL_COLOR_ATTACHMENT4:
4615         case GL_COLOR_ATTACHMENT5:
4616         case GL_COLOR_ATTACHMENT6:
4617         case GL_COLOR_ATTACHMENT7:
4618         case GL_COLOR_ATTACHMENT8:
4619         case GL_COLOR_ATTACHMENT9:
4620         case GL_COLOR_ATTACHMENT10:
4621         case GL_COLOR_ATTACHMENT11:
4622         case GL_COLOR_ATTACHMENT12:
4623         case GL_COLOR_ATTACHMENT13:
4624         case GL_COLOR_ATTACHMENT14:
4625         case GL_COLOR_ATTACHMENT15: {
4626            unsigned k = attachments[i] - GL_COLOR_ATTACHMENT0;
4627            if (k >= ctx->Const.MaxColorAttachments) {
4628               _mesa_error(ctx, GL_INVALID_OPERATION,
4629                           "%s(attachment >= max. color attachments)", name);
4630               return;
4631            }
4632            break;
4633         }
4634         default:
4635            goto invalid_enum;
4636         }
4637      }
4638   }
4639
4640   /* We don't actually do anything for this yet.  Just return after
4641    * validating the parameters and generating the required errors.
4642    */
4643   return;
4644
4645invalid_enum:
4646   _mesa_error(ctx, GL_INVALID_ENUM, "%s(invalid attachment %s)", name,
4647               _mesa_enum_to_string(attachments[i]));
4648   return;
4649}
4650
4651static struct gl_renderbuffer_attachment *
4652get_fb_attachment(struct gl_context *ctx, struct gl_framebuffer *fb,
4653                  const GLenum attachment)
4654{
4655   switch (attachment) {
4656   case GL_COLOR:
4657      return &fb->Attachment[BUFFER_BACK_LEFT];
4658   case GL_COLOR_ATTACHMENT0:
4659   case GL_COLOR_ATTACHMENT1:
4660   case GL_COLOR_ATTACHMENT2:
4661   case GL_COLOR_ATTACHMENT3:
4662   case GL_COLOR_ATTACHMENT4:
4663   case GL_COLOR_ATTACHMENT5:
4664   case GL_COLOR_ATTACHMENT6:
4665   case GL_COLOR_ATTACHMENT7:
4666   case GL_COLOR_ATTACHMENT8:
4667   case GL_COLOR_ATTACHMENT9:
4668   case GL_COLOR_ATTACHMENT10:
4669   case GL_COLOR_ATTACHMENT11:
4670   case GL_COLOR_ATTACHMENT12:
4671   case GL_COLOR_ATTACHMENT13:
4672   case GL_COLOR_ATTACHMENT14:
4673   case GL_COLOR_ATTACHMENT15: {
4674      const unsigned i = attachment - GL_COLOR_ATTACHMENT0;
4675      if (i >= ctx->Const.MaxColorAttachments)
4676         return NULL;
4677      return &fb->Attachment[BUFFER_COLOR0 + i];
4678   }
4679   case GL_DEPTH:
4680   case GL_DEPTH_ATTACHMENT:
4681   case GL_DEPTH_STENCIL_ATTACHMENT:
4682      return &fb->Attachment[BUFFER_DEPTH];
4683   case GL_STENCIL:
4684   case GL_STENCIL_ATTACHMENT:
4685      return &fb->Attachment[BUFFER_STENCIL];
4686   default:
4687      return NULL;
4688   }
4689}
4690
4691static void
4692discard_framebuffer(struct gl_context *ctx, struct gl_framebuffer *fb,
4693                    GLsizei numAttachments, const GLenum *attachments)
4694{
4695   if (!ctx->Driver.DiscardFramebuffer)
4696      return;
4697
4698   for (int i = 0; i < numAttachments; i++) {
4699      struct gl_renderbuffer_attachment *att =
4700            get_fb_attachment(ctx, fb, attachments[i]);
4701
4702      if (!att)
4703         continue;
4704
4705      /* If we're asked to invalidate just depth or just stencil, but the
4706       * attachment is packed depth/stencil, then we can only use
4707       * Driver.DiscardFramebuffer if the attachments list includes both depth
4708       * and stencil and they both point at the same renderbuffer.
4709       */
4710      if ((attachments[i] == GL_DEPTH_ATTACHMENT ||
4711           attachments[i] == GL_STENCIL_ATTACHMENT) &&
4712          (!att->Renderbuffer ||
4713           att->Renderbuffer->_BaseFormat == GL_DEPTH_STENCIL)) {
4714         GLenum other_format = (attachments[i] == GL_DEPTH_ATTACHMENT ?
4715                                GL_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT);
4716         bool has_both = false;
4717         for (int j = 0; j < numAttachments; j++) {
4718            if (attachments[j] == other_format)
4719               has_both = true;
4720            break;
4721         }
4722
4723         if (fb->Attachment[BUFFER_DEPTH].Renderbuffer !=
4724             fb->Attachment[BUFFER_STENCIL].Renderbuffer || !has_both)
4725            continue;
4726      }
4727
4728      ctx->Driver.DiscardFramebuffer(ctx, fb, att);
4729   }
4730}
4731
4732void GLAPIENTRY
4733_mesa_InvalidateSubFramebuffer_no_error(GLenum target, GLsizei numAttachments,
4734                                        const GLenum *attachments, GLint x,
4735                                        GLint y, GLsizei width, GLsizei height)
4736{
4737   /* no-op */
4738}
4739
4740
4741void GLAPIENTRY
4742_mesa_InvalidateSubFramebuffer(GLenum target, GLsizei numAttachments,
4743                               const GLenum *attachments, GLint x, GLint y,
4744                               GLsizei width, GLsizei height)
4745{
4746   struct gl_framebuffer *fb;
4747   GET_CURRENT_CONTEXT(ctx);
4748
4749   fb = get_framebuffer_target(ctx, target);
4750   if (!fb) {
4751      _mesa_error(ctx, GL_INVALID_ENUM,
4752                  "glInvalidateSubFramebuffer(invalid target %s)",
4753                  _mesa_enum_to_string(target));
4754      return;
4755   }
4756
4757   invalidate_framebuffer_storage(ctx, fb, numAttachments, attachments,
4758                                  x, y, width, height,
4759                                  "glInvalidateSubFramebuffer");
4760}
4761
4762
4763void GLAPIENTRY
4764_mesa_InvalidateNamedFramebufferSubData(GLuint framebuffer,
4765                                        GLsizei numAttachments,
4766                                        const GLenum *attachments,
4767                                        GLint x, GLint y,
4768                                        GLsizei width, GLsizei height)
4769{
4770   struct gl_framebuffer *fb;
4771   GET_CURRENT_CONTEXT(ctx);
4772
4773   /* The OpenGL 4.5 core spec (02.02.2015) says (in Section 17.4 Whole
4774    * Framebuffer Operations, PDF page 522): "If framebuffer is zero, the
4775    * default draw framebuffer is affected."
4776    */
4777   if (framebuffer) {
4778      fb = _mesa_lookup_framebuffer_err(ctx, framebuffer,
4779                                        "glInvalidateNamedFramebufferSubData");
4780      if (!fb)
4781         return;
4782   }
4783   else
4784      fb = ctx->WinSysDrawBuffer;
4785
4786   invalidate_framebuffer_storage(ctx, fb, numAttachments, attachments,
4787                                  x, y, width, height,
4788                                  "glInvalidateNamedFramebufferSubData");
4789}
4790
4791void GLAPIENTRY
4792_mesa_InvalidateFramebuffer_no_error(GLenum target, GLsizei numAttachments,
4793                                     const GLenum *attachments)
4794{
4795   struct gl_framebuffer *fb;
4796   GET_CURRENT_CONTEXT(ctx);
4797
4798   fb = get_framebuffer_target(ctx, target);
4799   if (!fb)
4800      return;
4801
4802   discard_framebuffer(ctx, fb, numAttachments, attachments);
4803}
4804
4805
4806void GLAPIENTRY
4807_mesa_InvalidateFramebuffer(GLenum target, GLsizei numAttachments,
4808                            const GLenum *attachments)
4809{
4810   struct gl_framebuffer *fb;
4811   GET_CURRENT_CONTEXT(ctx);
4812
4813   fb = get_framebuffer_target(ctx, target);
4814   if (!fb) {
4815      _mesa_error(ctx, GL_INVALID_ENUM,
4816                  "glInvalidateFramebuffer(invalid target %s)",
4817                  _mesa_enum_to_string(target));
4818      return;
4819   }
4820
4821   /* The GL_ARB_invalidate_subdata spec says:
4822    *
4823    *     "The command
4824    *
4825    *        void InvalidateFramebuffer(enum target,
4826    *                                   sizei numAttachments,
4827    *                                   const enum *attachments);
4828    *
4829    *     is equivalent to the command InvalidateSubFramebuffer with <x>, <y>,
4830    *     <width>, <height> equal to 0, 0, <MAX_VIEWPORT_DIMS[0]>,
4831    *     <MAX_VIEWPORT_DIMS[1]> respectively."
4832    */
4833   invalidate_framebuffer_storage(ctx, fb, numAttachments, attachments,
4834                                  0, 0,
4835                                  ctx->Const.MaxViewportWidth,
4836                                  ctx->Const.MaxViewportHeight,
4837                                  "glInvalidateFramebuffer");
4838
4839   discard_framebuffer(ctx, fb, numAttachments, attachments);
4840}
4841
4842
4843void GLAPIENTRY
4844_mesa_InvalidateNamedFramebufferData(GLuint framebuffer,
4845                                     GLsizei numAttachments,
4846                                     const GLenum *attachments)
4847{
4848   struct gl_framebuffer *fb;
4849   GET_CURRENT_CONTEXT(ctx);
4850
4851   /* The OpenGL 4.5 core spec (02.02.2015) says (in Section 17.4 Whole
4852    * Framebuffer Operations, PDF page 522): "If framebuffer is zero, the
4853    * default draw framebuffer is affected."
4854    */
4855   if (framebuffer) {
4856      fb = _mesa_lookup_framebuffer_err(ctx, framebuffer,
4857                                        "glInvalidateNamedFramebufferData");
4858      if (!fb)
4859         return;
4860   }
4861   else
4862      fb = ctx->WinSysDrawBuffer;
4863
4864   /* The GL_ARB_invalidate_subdata spec says:
4865    *
4866    *     "The command
4867    *
4868    *        void InvalidateFramebuffer(enum target,
4869    *                                   sizei numAttachments,
4870    *                                   const enum *attachments);
4871    *
4872    *     is equivalent to the command InvalidateSubFramebuffer with <x>, <y>,
4873    *     <width>, <height> equal to 0, 0, <MAX_VIEWPORT_DIMS[0]>,
4874    *     <MAX_VIEWPORT_DIMS[1]> respectively."
4875    */
4876   invalidate_framebuffer_storage(ctx, fb, numAttachments, attachments,
4877                                  0, 0,
4878                                  ctx->Const.MaxViewportWidth,
4879                                  ctx->Const.MaxViewportHeight,
4880                                  "glInvalidateNamedFramebufferData");
4881}
4882
4883
4884void GLAPIENTRY
4885_mesa_DiscardFramebufferEXT(GLenum target, GLsizei numAttachments,
4886                            const GLenum *attachments)
4887{
4888   struct gl_framebuffer *fb;
4889   GLint i;
4890
4891   GET_CURRENT_CONTEXT(ctx);
4892
4893   fb = get_framebuffer_target(ctx, target);
4894   if (!fb) {
4895      _mesa_error(ctx, GL_INVALID_ENUM,
4896         "glDiscardFramebufferEXT(target %s)",
4897         _mesa_enum_to_string(target));
4898      return;
4899   }
4900
4901   if (numAttachments < 0) {
4902      _mesa_error(ctx, GL_INVALID_VALUE,
4903                  "glDiscardFramebufferEXT(numAttachments < 0)");
4904      return;
4905   }
4906
4907   for (i = 0; i < numAttachments; i++) {
4908      switch (attachments[i]) {
4909      case GL_COLOR:
4910      case GL_DEPTH:
4911      case GL_STENCIL:
4912         if (_mesa_is_user_fbo(fb))
4913            goto invalid_enum;
4914         break;
4915      case GL_COLOR_ATTACHMENT0:
4916      case GL_DEPTH_ATTACHMENT:
4917      case GL_STENCIL_ATTACHMENT:
4918         if (_mesa_is_winsys_fbo(fb))
4919            goto invalid_enum;
4920         break;
4921      default:
4922         goto invalid_enum;
4923      }
4924   }
4925
4926   discard_framebuffer(ctx, fb, numAttachments, attachments);
4927
4928   return;
4929
4930invalid_enum:
4931   _mesa_error(ctx, GL_INVALID_ENUM,
4932               "glDiscardFramebufferEXT(attachment %s)",
4933              _mesa_enum_to_string(attachments[i]));
4934}
4935
4936static void
4937sample_locations(struct gl_context *ctx, struct gl_framebuffer *fb,
4938                 GLuint start, GLsizei count, const GLfloat *v, bool no_error,
4939                 const char *name)
4940{
4941   GLsizei i;
4942
4943   if (!no_error) {
4944      if (!ctx->Extensions.ARB_sample_locations) {
4945         _mesa_error(ctx, GL_INVALID_OPERATION,
4946                     "%s not supported "
4947                     "(ARB_sample_locations not available)", name);
4948         return;
4949      }
4950
4951      if (start + count > MAX_SAMPLE_LOCATION_TABLE_SIZE) {
4952         _mesa_error(ctx, GL_INVALID_VALUE,
4953                     "%s(start+size > sample location table size)", name);
4954         return;
4955      }
4956   }
4957
4958   if (!fb->SampleLocationTable) {
4959      size_t size = MAX_SAMPLE_LOCATION_TABLE_SIZE * 2 * sizeof(GLfloat);
4960      fb->SampleLocationTable = malloc(size);
4961      if (!fb->SampleLocationTable) {
4962         _mesa_error(ctx, GL_OUT_OF_MEMORY,
4963                     "Cannot allocate sample location table");
4964         return;
4965      }
4966      for (i = 0; i < MAX_SAMPLE_LOCATION_TABLE_SIZE * 2; i++)
4967         fb->SampleLocationTable[i] = 0.5f;
4968   }
4969
4970   for (i = 0; i < count * 2; i++) {
4971      /* The ARB_sample_locations spec says:
4972       *
4973       *    Sample locations outside of [0,1] result in undefined
4974       *    behavior.
4975       *
4976       * To simplify driver implementations, we choose to clamp to
4977       * [0,1] and change NaN into 0.5.
4978       */
4979      if (isnan(v[i]) || v[i] < 0.0f || v[i] > 1.0f) {
4980         static GLuint msg_id = 0;
4981         static const char* msg = "Invalid sample location specified";
4982         _mesa_debug_get_id(&msg_id);
4983
4984         _mesa_log_msg(ctx, MESA_DEBUG_SOURCE_API, MESA_DEBUG_TYPE_UNDEFINED,
4985                       msg_id, MESA_DEBUG_SEVERITY_HIGH, strlen(msg), msg);
4986      }
4987
4988      if (isnan(v[i]))
4989         fb->SampleLocationTable[start * 2 + i] = 0.5f;
4990      else
4991         fb->SampleLocationTable[start * 2 + i] = CLAMP(v[i], 0.0f, 1.0f);
4992   }
4993
4994   if (fb == ctx->DrawBuffer)
4995      ctx->NewDriverState |= ctx->DriverFlags.NewSampleLocations;
4996}
4997
4998void GLAPIENTRY
4999_mesa_FramebufferSampleLocationsfvARB(GLenum target, GLuint start,
5000                                      GLsizei count, const GLfloat *v)
5001{
5002   struct gl_framebuffer *fb;
5003
5004   GET_CURRENT_CONTEXT(ctx);
5005
5006   fb = get_framebuffer_target(ctx, target);
5007   if (!fb) {
5008      _mesa_error(ctx, GL_INVALID_ENUM,
5009                  "glFramebufferSampleLocationsfvARB(target %s)",
5010                  _mesa_enum_to_string(target));
5011      return;
5012   }
5013
5014   sample_locations(ctx, fb, start, count, v, false,
5015                    "glFramebufferSampleLocationsfvARB");
5016}
5017
5018void GLAPIENTRY
5019_mesa_NamedFramebufferSampleLocationsfvARB(GLuint framebuffer, GLuint start,
5020                                           GLsizei count, const GLfloat *v)
5021{
5022   struct gl_framebuffer *fb;
5023
5024   GET_CURRENT_CONTEXT(ctx);
5025
5026   if (framebuffer) {
5027      fb = _mesa_lookup_framebuffer_err(ctx, framebuffer,
5028                                        "glNamedFramebufferSampleLocationsfvARB");
5029      if (!fb)
5030         return;
5031   }
5032   else
5033      fb = ctx->WinSysDrawBuffer;
5034
5035   sample_locations(ctx, fb, start, count, v, false,
5036                    "glNamedFramebufferSampleLocationsfvARB");
5037}
5038
5039void GLAPIENTRY
5040_mesa_FramebufferSampleLocationsfvARB_no_error(GLenum target, GLuint start,
5041                                               GLsizei count, const GLfloat *v)
5042{
5043   GET_CURRENT_CONTEXT(ctx);
5044   sample_locations(ctx, get_framebuffer_target(ctx, target), start,
5045                    count, v, true, "glFramebufferSampleLocationsfvARB");
5046}
5047
5048void GLAPIENTRY
5049_mesa_NamedFramebufferSampleLocationsfvARB_no_error(GLuint framebuffer,
5050                                                    GLuint start, GLsizei count,
5051                                                    const GLfloat *v)
5052{
5053   GET_CURRENT_CONTEXT(ctx);
5054   sample_locations(ctx, _mesa_lookup_framebuffer(ctx, framebuffer), start,
5055                    count, v, true, "glNamedFramebufferSampleLocationsfvARB");
5056}
5057
5058void GLAPIENTRY
5059_mesa_EvaluateDepthValuesARB(void)
5060{
5061   GET_CURRENT_CONTEXT(ctx);
5062
5063   if (!ctx->Extensions.ARB_sample_locations) {
5064      _mesa_error(ctx, GL_INVALID_OPERATION,
5065                  "EvaluateDepthValuesARB not supported (neither "
5066                  "ARB_sample_locations nor NV_sample_locations is available)");
5067      return;
5068   }
5069
5070   if (ctx->Driver.EvaluateDepthValues)
5071      ctx->Driver.EvaluateDepthValues(ctx);
5072}
5073