/*
 * Mesa 3-D graphics library
 *
 * Copyright (C) 1999-2008  Brian Paul   All Rights Reserved.
 * Copyright (C) 2009  VMware, Inc.   All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include "glheader.h"

#include "accum.h"
#include "arrayobj.h"
#include "attrib.h"
#include "blend.h"
#include "buffers.h"
#include "bufferobj.h"
#include "clear.h"
#include "context.h"
#include "depth.h"
#include "enable.h"
#include "enums.h"
#include "fog.h"
#include "hint.h"
#include "light.h"
#include "lines.h"
#include "macros.h"
#include "matrix.h"
#include "multisample.h"
#include "pixelstore.h"
#include "points.h"
#include "polygon.h"
#include "shared.h"
#include "scissor.h"
#include "stencil.h"
#include "texenv.h"
#include "texgen.h"
#include "texobj.h"
#include "texparam.h"
#include "texstate.h"
#include "varray.h"
#include "viewport.h"
#include "mtypes.h"
#include "state.h"
#include "hash.h"
#include <stdbool.h>
#include "util/u_memory.h"


/**
 * glEnable()/glDisable() attribute group (GL_ENABLE_BIT).
 */
struct gl_enable_attrib
{
   GLboolean AlphaTest;
   GLboolean AutoNormal;
   GLboolean Blend;
   GLbitfield ClipPlanes;
   GLboolean ColorMaterial;
   GLboolean CullFace;
   GLboolean DepthClampNear;
   GLboolean DepthClampFar;
   GLboolean DepthTest;
   GLboolean Dither;
   GLboolean Fog;
   GLboolean Light[MAX_LIGHTS];
   GLboolean Lighting;
   GLboolean LineSmooth;
   GLboolean LineStipple;
   GLboolean IndexLogicOp;
   GLboolean ColorLogicOp;

   GLboolean Map1Color4;
   GLboolean Map1Index;
   GLboolean Map1Normal;
   GLboolean Map1TextureCoord1;
   GLboolean Map1TextureCoord2;
   GLboolean Map1TextureCoord3;
   GLboolean Map1TextureCoord4;
   GLboolean Map1Vertex3;
   GLboolean Map1Vertex4;
   GLboolean Map2Color4;
   GLboolean Map2Index;
   GLboolean Map2Normal;
   GLboolean Map2TextureCoord1;
   GLboolean Map2TextureCoord2;
   GLboolean Map2TextureCoord3;
   GLboolean Map2TextureCoord4;
   GLboolean Map2Vertex3;
   GLboolean Map2Vertex4;

   GLboolean Normalize;
   GLboolean PixelTexture;
   GLboolean PointSmooth;
   GLboolean PolygonOffsetPoint;
   GLboolean PolygonOffsetLine;
   GLboolean PolygonOffsetFill;
   GLboolean PolygonSmooth;
   GLboolean PolygonStipple;
   GLboolean RescaleNormals;
   GLbitfield Scissor;
   GLboolean Stencil;
   GLboolean StencilTwoSide;          /* GL_EXT_stencil_two_side */
   GLboolean MultisampleEnabled;      /* GL_ARB_multisample */
   GLboolean SampleAlphaToCoverage;   /* GL_ARB_multisample */
   GLboolean SampleAlphaToOne;        /* GL_ARB_multisample */
   GLboolean SampleCoverage;          /* GL_ARB_multisample */
   GLboolean RasterPositionUnclipped; /* GL_IBM_rasterpos_clip */

   GLbitfield Texture[MAX_TEXTURE_UNITS];
   GLbitfield TexGen[MAX_TEXTURE_UNITS];

   /* GL_ARB_vertex_program */
   GLboolean VertexProgram;
   GLboolean VertexProgramPointSize;
   GLboolean VertexProgramTwoSide;

   /* GL_ARB_fragment_program */
   GLboolean FragmentProgram;

   /* GL_ARB_point_sprite / GL_NV_point_sprite */
   GLboolean PointSprite;
   GLboolean FragmentShaderATI;

   /* GL_ARB_framebuffer_sRGB / GL_EXT_framebuffer_sRGB */
   GLboolean sRGBEnabled;

   /* GL_NV_conservative_raster */
   GLboolean ConservativeRasterization;
};


/**
 * Node for the attribute stack.
 */
struct gl_attrib_node
{
   GLbitfield kind;
   void *data;
   struct gl_attrib_node *next;
};



/**
 * Special struct for saving/restoring texture state (GL_TEXTURE_BIT)
 */
struct texture_state
{
   struct gl_texture_attrib Texture;  /**< The usual context state */

   /** to save per texture object state (wrap modes, filters, etc): */
   struct gl_texture_object SavedObj[MAX_TEXTURE_UNITS][NUM_TEXTURE_TARGETS];

   /**
    * To save references to texture objects (so they don't get accidentally
    * deleted while saved in the attribute stack).
    */
   struct gl_texture_object *SavedTexRef[MAX_TEXTURE_UNITS][NUM_TEXTURE_TARGETS];

   /* We need to keep a reference to the shared state.  That's where the
    * default texture objects are kept.  We don't want that state to be
    * freed while the attribute stack contains pointers to any default
    * texture objects.
    */
   struct gl_shared_state *SharedRef;
};


struct viewport_state
{
   struct gl_viewport_attrib ViewportArray[MAX_VIEWPORTS];
   GLuint SubpixelPrecisionBias[2];
};


/** An unused GL_*_BIT value */
#define DUMMY_BIT 0x10000000


/**
 * Allocate new attribute node of given type/kind.  Attach payload data.
 * Insert it into the linked list named by 'head'.
 */
static bool
save_attrib_data(struct gl_attrib_node **head,
                 GLbitfield kind, void *payload)
{
   struct gl_attrib_node *n = MALLOC_STRUCT(gl_attrib_node);
   if (n) {
      n->kind = kind;
      n->data = payload;
      /* insert at head */
      n->next = *head;
      *head = n;
   }
   else {
      /* out of memory! */
      return false;
   }
   return true;
}


/**
 * Helper function for_mesa_PushAttrib for simple attributes.
 * Allocates memory for attribute data and copies the given attribute data.
 * \param head  head of linked list to insert attribute data into
 * \param attr_bit  one of the GL_<attrib>_BIT flags
 * \param attr_size  number of bytes to allocate for attribute data
 * \param attr_data  the attribute data to copy
 * \return true for success, false for out of memory
 */
static bool
push_attrib(struct gl_context *ctx, struct gl_attrib_node **head,
            GLbitfield attr_bit, GLuint attr_size, const void *attr_data)
{
   void *attribute;

   attribute = malloc(attr_size);
   if (attribute == NULL) {
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
      return false;
   }

   if (save_attrib_data(head, attr_bit, attribute)) {
      memcpy(attribute, attr_data, attr_size);
   }
   else {
      free(attribute);
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
      return false;
   }
   return true;
}


void GLAPIENTRY
_mesa_PushAttrib(GLbitfield mask)
{
   struct gl_attrib_node *head;

   GET_CURRENT_CONTEXT(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glPushAttrib %x\n", (int) mask);

   if (ctx->AttribStackDepth >= MAX_ATTRIB_STACK_DEPTH) {
      _mesa_error(ctx, GL_STACK_OVERFLOW, "glPushAttrib");
      return;
   }

   /* Build linked list of attribute nodes which save all attribute */
   /* groups specified by the mask. */
   head = NULL;

   if (mask == 0) {
      /* if mask is zero we still need to push something so that we
       * don't get a GL_STACK_UNDERFLOW error in glPopAttrib().
       */
      GLuint dummy = 0;
      if (!push_attrib(ctx, &head, DUMMY_BIT, sizeof(dummy), &dummy))
         goto end;
   }

   if (mask & GL_ACCUM_BUFFER_BIT) {
      if (!push_attrib(ctx, &head, GL_ACCUM_BUFFER_BIT,
                       sizeof(struct gl_accum_attrib),
                       (void*)&ctx->Accum))
         goto end;
   }

   if (mask & GL_COLOR_BUFFER_BIT) {
      GLuint i;
      struct gl_colorbuffer_attrib *attr;
      attr = MALLOC_STRUCT(gl_colorbuffer_attrib);
      if (attr == NULL) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
         goto end;
      }

    if (save_attrib_data(&head, GL_COLOR_BUFFER_BIT, attr)) {
         memcpy(attr, &ctx->Color, sizeof(struct gl_colorbuffer_attrib));
         /* push the Draw FBO's DrawBuffer[] state, not ctx->Color.DrawBuffer[] */
         for (i = 0; i < ctx->Const.MaxDrawBuffers; i ++)
            attr->DrawBuffer[i] = ctx->DrawBuffer->ColorDrawBuffer[i];
      }
      else {
         free(attr);
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
         goto end;
      }
   }

   if (mask & GL_CURRENT_BIT) {
      FLUSH_CURRENT(ctx, 0);
      if (!push_attrib(ctx, &head, GL_CURRENT_BIT,
                       sizeof(struct gl_current_attrib),
                       (void*)&ctx->Current))
         goto end;
   }

   if (mask & GL_DEPTH_BUFFER_BIT) {
      if (!push_attrib(ctx, &head, GL_DEPTH_BUFFER_BIT,
                       sizeof(struct gl_depthbuffer_attrib),
                       (void*)&ctx->Depth))
         goto end;
   }

   if (mask & GL_ENABLE_BIT) {
      struct gl_enable_attrib *attr;
      GLuint i;
      attr = MALLOC_STRUCT(gl_enable_attrib);
      if (attr == NULL) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
         goto end;
      }

      /* Copy enable flags from all other attributes into the enable struct. */
      attr->AlphaTest = ctx->Color.AlphaEnabled;
      attr->AutoNormal = ctx->Eval.AutoNormal;
      attr->Blend = ctx->Color.BlendEnabled;
      attr->ClipPlanes = ctx->Transform.ClipPlanesEnabled;
      attr->ColorMaterial = ctx->Light.ColorMaterialEnabled;
      attr->CullFace = ctx->Polygon.CullFlag;
      attr->DepthClampNear = ctx->Transform.DepthClampNear;
      attr->DepthClampFar = ctx->Transform.DepthClampFar;
      attr->DepthTest = ctx->Depth.Test;
      attr->Dither = ctx->Color.DitherFlag;
      attr->Fog = ctx->Fog.Enabled;
      for (i = 0; i < ctx->Const.MaxLights; i++) {
         attr->Light[i] = ctx->Light.Light[i].Enabled;
      }
      attr->Lighting = ctx->Light.Enabled;
      attr->LineSmooth = ctx->Line.SmoothFlag;
      attr->LineStipple = ctx->Line.StippleFlag;
      attr->IndexLogicOp = ctx->Color.IndexLogicOpEnabled;
      attr->ColorLogicOp = ctx->Color.ColorLogicOpEnabled;
      attr->Map1Color4 = ctx->Eval.Map1Color4;
      attr->Map1Index = ctx->Eval.Map1Index;
      attr->Map1Normal = ctx->Eval.Map1Normal;
      attr->Map1TextureCoord1 = ctx->Eval.Map1TextureCoord1;
      attr->Map1TextureCoord2 = ctx->Eval.Map1TextureCoord2;
      attr->Map1TextureCoord3 = ctx->Eval.Map1TextureCoord3;
      attr->Map1TextureCoord4 = ctx->Eval.Map1TextureCoord4;
      attr->Map1Vertex3 = ctx->Eval.Map1Vertex3;
      attr->Map1Vertex4 = ctx->Eval.Map1Vertex4;
      attr->Map2Color4 = ctx->Eval.Map2Color4;
      attr->Map2Index = ctx->Eval.Map2Index;
      attr->Map2Normal = ctx->Eval.Map2Normal;
      attr->Map2TextureCoord1 = ctx->Eval.Map2TextureCoord1;
      attr->Map2TextureCoord2 = ctx->Eval.Map2TextureCoord2;
      attr->Map2TextureCoord3 = ctx->Eval.Map2TextureCoord3;
      attr->Map2TextureCoord4 = ctx->Eval.Map2TextureCoord4;
      attr->Map2Vertex3 = ctx->Eval.Map2Vertex3;
      attr->Map2Vertex4 = ctx->Eval.Map2Vertex4;
      attr->Normalize = ctx->Transform.Normalize;
      attr->RasterPositionUnclipped = ctx->Transform.RasterPositionUnclipped;
      attr->PointSmooth = ctx->Point.SmoothFlag;
      attr->PointSprite = ctx->Point.PointSprite;
      attr->PolygonOffsetPoint = ctx->Polygon.OffsetPoint;
      attr->PolygonOffsetLine = ctx->Polygon.OffsetLine;
      attr->PolygonOffsetFill = ctx->Polygon.OffsetFill;
      attr->PolygonSmooth = ctx->Polygon.SmoothFlag;
      attr->PolygonStipple = ctx->Polygon.StippleFlag;
      attr->RescaleNormals = ctx->Transform.RescaleNormals;
      attr->Scissor = ctx->Scissor.EnableFlags;
      attr->Stencil = ctx->Stencil.Enabled;
      attr->StencilTwoSide = ctx->Stencil.TestTwoSide;
      attr->MultisampleEnabled = ctx->Multisample.Enabled;
      attr->SampleAlphaToCoverage = ctx->Multisample.SampleAlphaToCoverage;
      attr->SampleAlphaToOne = ctx->Multisample.SampleAlphaToOne;
      attr->SampleCoverage = ctx->Multisample.SampleCoverage;
      for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
         attr->Texture[i] = ctx->Texture.FixedFuncUnit[i].Enabled;
         attr->TexGen[i] = ctx->Texture.FixedFuncUnit[i].TexGenEnabled;
      }
      /* GL_ARB_vertex_program */
      attr->VertexProgram = ctx->VertexProgram.Enabled;
      attr->VertexProgramPointSize = ctx->VertexProgram.PointSizeEnabled;
      attr->VertexProgramTwoSide = ctx->VertexProgram.TwoSideEnabled;

      /* GL_ARB_fragment_program */
      attr->FragmentProgram = ctx->FragmentProgram.Enabled;

      if (!save_attrib_data(&head, GL_ENABLE_BIT, attr)) {
         free(attr);
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
         goto end;
      }

      /* GL_ARB_framebuffer_sRGB / GL_EXT_framebuffer_sRGB */
      attr->sRGBEnabled = ctx->Color.sRGBEnabled;

      /* GL_NV_conservative_raster */
      attr->ConservativeRasterization = ctx->ConservativeRasterization;
   }

   if (mask & GL_EVAL_BIT) {
      if (!push_attrib(ctx, &head, GL_EVAL_BIT,
                       sizeof(struct gl_eval_attrib),
                       (void*)&ctx->Eval))
         goto end;
   }

   if (mask & GL_FOG_BIT) {
      if (!push_attrib(ctx, &head, GL_FOG_BIT,
                       sizeof(struct gl_fog_attrib),
                       (void*)&ctx->Fog))
         goto end;
   }

   if (mask & GL_HINT_BIT) {
      if (!push_attrib(ctx, &head, GL_HINT_BIT,
                       sizeof(struct gl_hint_attrib),
                       (void*)&ctx->Hint))
         goto end;
   }

   if (mask & GL_LIGHTING_BIT) {
      FLUSH_CURRENT(ctx, 0);   /* flush material changes */
      if (!push_attrib(ctx, &head, GL_LIGHTING_BIT,
                       sizeof(struct gl_light_attrib),
                       (void*)&ctx->Light))
         goto end;
   }

   if (mask & GL_LINE_BIT) {
      if (!push_attrib(ctx, &head, GL_LINE_BIT,
                       sizeof(struct gl_line_attrib),
                       (void*)&ctx->Line))
         goto end;
   }

   if (mask & GL_LIST_BIT) {
      if (!push_attrib(ctx, &head, GL_LIST_BIT,
                       sizeof(struct gl_list_attrib),
                       (void*)&ctx->List))
         goto end;
   }

   if (mask & GL_PIXEL_MODE_BIT) {
      struct gl_pixel_attrib *attr;
      attr = MALLOC_STRUCT(gl_pixel_attrib);
      if (attr == NULL) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
         goto end;
      }

      if (save_attrib_data(&head, GL_PIXEL_MODE_BIT, attr)) {
         memcpy(attr, &ctx->Pixel, sizeof(struct gl_pixel_attrib));
         /* push the Read FBO's ReadBuffer state, not ctx->Pixel.ReadBuffer */
         attr->ReadBuffer = ctx->ReadBuffer->ColorReadBuffer;
      }
      else {
         free(attr);
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib");
         goto end;
      }
   }

   if (mask & GL_POINT_BIT) {
      if (!push_attrib(ctx, &head, GL_POINT_BIT,
                       sizeof(struct gl_point_attrib),
                       (void*)&ctx->Point))
         goto end;
   }

   if (mask & GL_POLYGON_BIT) {
      if (!push_attrib(ctx, &head, GL_POLYGON_BIT,
                       sizeof(struct gl_polygon_attrib),
                       (void*)&ctx->Polygon))
         goto end;
   }

   if (mask & GL_POLYGON_STIPPLE_BIT) {
      if (!push_attrib(ctx, &head, GL_POLYGON_STIPPLE_BIT,
                       sizeof(ctx->PolygonStipple),
                       (void*)&ctx->PolygonStipple))
         goto end;
   }

   if (mask & GL_SCISSOR_BIT) {
      if (!push_attrib(ctx, &head, GL_SCISSOR_BIT,
                       sizeof(struct gl_scissor_attrib),
                       (void*)&ctx->Scissor))
         goto end;
   }

   if (mask & GL_STENCIL_BUFFER_BIT) {
      if (!push_attrib(ctx, &head, GL_STENCIL_BUFFER_BIT,
                       sizeof(struct gl_stencil_attrib),
                       (void*)&ctx->Stencil))
         goto end;
   }

   if (mask & GL_TEXTURE_BIT) {
      struct texture_state *texstate = CALLOC_STRUCT(texture_state);
      GLuint u, tex;

      if (!texstate) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib(GL_TEXTURE_BIT)");
         goto end;
      }

      if (!save_attrib_data(&head, GL_TEXTURE_BIT, texstate)) {
         free(texstate);
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib(GL_TEXTURE_BIT)");
         goto end;
      }

      _mesa_lock_context_textures(ctx);

      /* copy/save the bulk of texture state here */
      memcpy(&texstate->Texture, &ctx->Texture, sizeof(ctx->Texture));

      /* Save references to the currently bound texture objects so they don't
       * accidentally get deleted while referenced in the attribute stack.
       */
      for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
         for (tex = 0; tex < NUM_TEXTURE_TARGETS; tex++) {
            _mesa_reference_texobj(&texstate->SavedTexRef[u][tex],
                                   ctx->Texture.Unit[u].CurrentTex[tex]);
         }
      }

      /* copy state/contents of the currently bound texture objects */
      for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
         for (tex = 0; tex < NUM_TEXTURE_TARGETS; tex++) {
            _mesa_copy_texture_object(&texstate->SavedObj[u][tex],
                                      ctx->Texture.Unit[u].CurrentTex[tex]);
         }
      }

      _mesa_reference_shared_state(ctx, &texstate->SharedRef, ctx->Shared);

      _mesa_unlock_context_textures(ctx);
   }

   if (mask & GL_TRANSFORM_BIT) {
      if (!push_attrib(ctx, &head, GL_TRANSFORM_BIT,
                       sizeof(struct gl_transform_attrib),
                       (void*)&ctx->Transform))
         goto end;
   }

   if (mask & GL_VIEWPORT_BIT) {
      struct viewport_state *viewstate = CALLOC_STRUCT(viewport_state);
      if (!viewstate) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib(GL_VIEWPORT_BIT)");
         goto end;
      }

      if (!save_attrib_data(&head, GL_VIEWPORT_BIT, viewstate)) {
         free(viewstate);
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glPushAttrib(GL_VIEWPORT_BIT)");
         goto end;
      }

      memcpy(&viewstate->ViewportArray, &ctx->ViewportArray,
             sizeof(struct gl_viewport_attrib)*ctx->Const.MaxViewports);

      viewstate->SubpixelPrecisionBias[0] = ctx->SubpixelPrecisionBias[0];
      viewstate->SubpixelPrecisionBias[1] = ctx->SubpixelPrecisionBias[1];
   }

   /* GL_ARB_multisample */
   if (mask & GL_MULTISAMPLE_BIT_ARB) {
      if (!push_attrib(ctx, &head, GL_MULTISAMPLE_BIT_ARB,
                       sizeof(struct gl_multisample_attrib),
                       (void*)&ctx->Multisample))
         goto end;
   }

end:
   if (head != NULL) {
       ctx->AttribStack[ctx->AttribStackDepth] = head;
       ctx->AttribStackDepth++;
   }
}



static void
pop_enable_group(struct gl_context *ctx, const struct gl_enable_attrib *enable)
{
   const GLuint curTexUnitSave = ctx->Texture.CurrentUnit;
   GLuint i;

#define TEST_AND_UPDATE(VALUE, NEWVALUE, ENUM)                \
        if ((VALUE) != (NEWVALUE)) {                        \
           _mesa_set_enable(ctx, ENUM, (NEWVALUE));        \
        }

   TEST_AND_UPDATE(ctx->Color.AlphaEnabled, enable->AlphaTest, GL_ALPHA_TEST);
   if (ctx->Color.BlendEnabled != enable->Blend) {
      if (ctx->Extensions.EXT_draw_buffers2) {
         GLuint i;
         for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
            _mesa_set_enablei(ctx, GL_BLEND, i, (enable->Blend >> i) & 1);
         }
      }
      else {
         _mesa_set_enable(ctx, GL_BLEND, (enable->Blend & 1));
      }
   }

   for (i=0;i<ctx->Const.MaxClipPlanes;i++) {
      const GLuint mask = 1 << i;
      if ((ctx->Transform.ClipPlanesEnabled & mask) != (enable->ClipPlanes & mask))
          _mesa_set_enable(ctx, (GLenum) (GL_CLIP_PLANE0 + i),
                           !!(enable->ClipPlanes & mask));
   }

   TEST_AND_UPDATE(ctx->Light.ColorMaterialEnabled, enable->ColorMaterial,
                   GL_COLOR_MATERIAL);
   TEST_AND_UPDATE(ctx->Polygon.CullFlag, enable->CullFace, GL_CULL_FACE);

   if (!ctx->Extensions.AMD_depth_clamp_separate) {
      TEST_AND_UPDATE(ctx->Transform.DepthClampNear && ctx->Transform.DepthClampFar,
                      enable->DepthClampNear && enable->DepthClampFar,
                      GL_DEPTH_CLAMP);
   } else {
      TEST_AND_UPDATE(ctx->Transform.DepthClampNear, enable->DepthClampNear,
                      GL_DEPTH_CLAMP_NEAR_AMD);
      TEST_AND_UPDATE(ctx->Transform.DepthClampFar, enable->DepthClampFar,
                      GL_DEPTH_CLAMP_FAR_AMD);
   }

   TEST_AND_UPDATE(ctx->Depth.Test, enable->DepthTest, GL_DEPTH_TEST);
   TEST_AND_UPDATE(ctx->Color.DitherFlag, enable->Dither, GL_DITHER);
   TEST_AND_UPDATE(ctx->Fog.Enabled, enable->Fog, GL_FOG);
   TEST_AND_UPDATE(ctx->Light.Enabled, enable->Lighting, GL_LIGHTING);
   TEST_AND_UPDATE(ctx->Line.SmoothFlag, enable->LineSmooth, GL_LINE_SMOOTH);
   TEST_AND_UPDATE(ctx->Line.StippleFlag, enable->LineStipple,
                   GL_LINE_STIPPLE);
   TEST_AND_UPDATE(ctx->Color.IndexLogicOpEnabled, enable->IndexLogicOp,
                   GL_INDEX_LOGIC_OP);
   TEST_AND_UPDATE(ctx->Color.ColorLogicOpEnabled, enable->ColorLogicOp,
                   GL_COLOR_LOGIC_OP);

   TEST_AND_UPDATE(ctx->Eval.Map1Color4, enable->Map1Color4, GL_MAP1_COLOR_4);
   TEST_AND_UPDATE(ctx->Eval.Map1Index, enable->Map1Index, GL_MAP1_INDEX);
   TEST_AND_UPDATE(ctx->Eval.Map1Normal, enable->Map1Normal, GL_MAP1_NORMAL);
   TEST_AND_UPDATE(ctx->Eval.Map1TextureCoord1, enable->Map1TextureCoord1,
                   GL_MAP1_TEXTURE_COORD_1);
   TEST_AND_UPDATE(ctx->Eval.Map1TextureCoord2, enable->Map1TextureCoord2,
                   GL_MAP1_TEXTURE_COORD_2);
   TEST_AND_UPDATE(ctx->Eval.Map1TextureCoord3, enable->Map1TextureCoord3,
                   GL_MAP1_TEXTURE_COORD_3);
   TEST_AND_UPDATE(ctx->Eval.Map1TextureCoord4, enable->Map1TextureCoord4,
                   GL_MAP1_TEXTURE_COORD_4);
   TEST_AND_UPDATE(ctx->Eval.Map1Vertex3, enable->Map1Vertex3,
                   GL_MAP1_VERTEX_3);
   TEST_AND_UPDATE(ctx->Eval.Map1Vertex4, enable->Map1Vertex4,
                   GL_MAP1_VERTEX_4);

   TEST_AND_UPDATE(ctx->Eval.Map2Color4, enable->Map2Color4, GL_MAP2_COLOR_4);
   TEST_AND_UPDATE(ctx->Eval.Map2Index, enable->Map2Index, GL_MAP2_INDEX);
   TEST_AND_UPDATE(ctx->Eval.Map2Normal, enable->Map2Normal, GL_MAP2_NORMAL);
   TEST_AND_UPDATE(ctx->Eval.Map2TextureCoord1, enable->Map2TextureCoord1,
                   GL_MAP2_TEXTURE_COORD_1);
   TEST_AND_UPDATE(ctx->Eval.Map2TextureCoord2, enable->Map2TextureCoord2,
                   GL_MAP2_TEXTURE_COORD_2);
   TEST_AND_UPDATE(ctx->Eval.Map2TextureCoord3, enable->Map2TextureCoord3,
                   GL_MAP2_TEXTURE_COORD_3);
   TEST_AND_UPDATE(ctx->Eval.Map2TextureCoord4, enable->Map2TextureCoord4,
                   GL_MAP2_TEXTURE_COORD_4);
   TEST_AND_UPDATE(ctx->Eval.Map2Vertex3, enable->Map2Vertex3,
                   GL_MAP2_VERTEX_3);
   TEST_AND_UPDATE(ctx->Eval.Map2Vertex4, enable->Map2Vertex4,
                   GL_MAP2_VERTEX_4);

   TEST_AND_UPDATE(ctx->Eval.AutoNormal, enable->AutoNormal, GL_AUTO_NORMAL);
   TEST_AND_UPDATE(ctx->Transform.Normalize, enable->Normalize, GL_NORMALIZE);
   TEST_AND_UPDATE(ctx->Transform.RescaleNormals, enable->RescaleNormals,
                   GL_RESCALE_NORMAL_EXT);
   TEST_AND_UPDATE(ctx->Transform.RasterPositionUnclipped,
                   enable->RasterPositionUnclipped,
                   GL_RASTER_POSITION_UNCLIPPED_IBM);
   TEST_AND_UPDATE(ctx->Point.SmoothFlag, enable->PointSmooth,
                   GL_POINT_SMOOTH);
   if (ctx->Extensions.NV_point_sprite || ctx->Extensions.ARB_point_sprite) {
      TEST_AND_UPDATE(ctx->Point.PointSprite, enable->PointSprite,
                      GL_POINT_SPRITE_NV);
   }
   TEST_AND_UPDATE(ctx->Polygon.OffsetPoint, enable->PolygonOffsetPoint,
                   GL_POLYGON_OFFSET_POINT);
   TEST_AND_UPDATE(ctx->Polygon.OffsetLine, enable->PolygonOffsetLine,
                   GL_POLYGON_OFFSET_LINE);
   TEST_AND_UPDATE(ctx->Polygon.OffsetFill, enable->PolygonOffsetFill,
                   GL_POLYGON_OFFSET_FILL);
   TEST_AND_UPDATE(ctx->Polygon.SmoothFlag, enable->PolygonSmooth,
                   GL_POLYGON_SMOOTH);
   TEST_AND_UPDATE(ctx->Polygon.StippleFlag, enable->PolygonStipple,
                   GL_POLYGON_STIPPLE);
   if (ctx->Scissor.EnableFlags != enable->Scissor) {
      unsigned i;

      for (i = 0; i < ctx->Const.MaxViewports; i++) {
         _mesa_set_enablei(ctx, GL_SCISSOR_TEST, i, (enable->Scissor >> i) & 1);
      }
   }
   TEST_AND_UPDATE(ctx->Stencil.Enabled, enable->Stencil, GL_STENCIL_TEST);
   if (ctx->Extensions.EXT_stencil_two_side) {
      TEST_AND_UPDATE(ctx->Stencil.TestTwoSide, enable->StencilTwoSide, GL_STENCIL_TEST_TWO_SIDE_EXT);
   }
   TEST_AND_UPDATE(ctx->Multisample.Enabled, enable->MultisampleEnabled,
                   GL_MULTISAMPLE_ARB);
   TEST_AND_UPDATE(ctx->Multisample.SampleAlphaToCoverage,
                   enable->SampleAlphaToCoverage,
                   GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
   TEST_AND_UPDATE(ctx->Multisample.SampleAlphaToOne,
                   enable->SampleAlphaToOne,
                   GL_SAMPLE_ALPHA_TO_ONE_ARB);
   TEST_AND_UPDATE(ctx->Multisample.SampleCoverage,
                   enable->SampleCoverage,
                   GL_SAMPLE_COVERAGE_ARB);
   /* GL_ARB_vertex_program */
   TEST_AND_UPDATE(ctx->VertexProgram.Enabled,
                   enable->VertexProgram,
                   GL_VERTEX_PROGRAM_ARB);
   TEST_AND_UPDATE(ctx->VertexProgram.PointSizeEnabled,
                   enable->VertexProgramPointSize,
                   GL_VERTEX_PROGRAM_POINT_SIZE_ARB);
   TEST_AND_UPDATE(ctx->VertexProgram.TwoSideEnabled,
                   enable->VertexProgramTwoSide,
                   GL_VERTEX_PROGRAM_TWO_SIDE_ARB);

   /* GL_ARB_fragment_program */
   TEST_AND_UPDATE(ctx->FragmentProgram.Enabled,
                   enable->FragmentProgram,
                   GL_FRAGMENT_PROGRAM_ARB);

   /* GL_ARB_framebuffer_sRGB / GL_EXT_framebuffer_sRGB */
   TEST_AND_UPDATE(ctx->Color.sRGBEnabled, enable->sRGBEnabled,
                   GL_FRAMEBUFFER_SRGB);

   /* GL_NV_conservative_raster */
   if (ctx->Extensions.NV_conservative_raster) {
      TEST_AND_UPDATE(ctx->ConservativeRasterization,
                      enable->ConservativeRasterization,
                      GL_CONSERVATIVE_RASTERIZATION_NV);
   }

   /* texture unit enables */
   for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
      const GLbitfield enabled = enable->Texture[i];
      const GLbitfield genEnabled = enable->TexGen[i];

      if (ctx->Texture.FixedFuncUnit[i].Enabled != enabled) {
         _mesa_ActiveTexture(GL_TEXTURE0 + i);

         _mesa_set_enable(ctx, GL_TEXTURE_1D, !!(enabled & TEXTURE_1D_BIT));
         _mesa_set_enable(ctx, GL_TEXTURE_2D, !!(enabled & TEXTURE_2D_BIT));
         _mesa_set_enable(ctx, GL_TEXTURE_3D, !!(enabled & TEXTURE_3D_BIT));
         if (ctx->Extensions.NV_texture_rectangle) {
            _mesa_set_enable(ctx, GL_TEXTURE_RECTANGLE_ARB,
                             !!(enabled & TEXTURE_RECT_BIT));
         }
         if (ctx->Extensions.ARB_texture_cube_map) {
            _mesa_set_enable(ctx, GL_TEXTURE_CUBE_MAP,
                             !!(enabled & TEXTURE_CUBE_BIT));
         }
      }

      if (ctx->Texture.FixedFuncUnit[i].TexGenEnabled != genEnabled) {
         _mesa_ActiveTexture(GL_TEXTURE0 + i);
         _mesa_set_enable(ctx, GL_TEXTURE_GEN_S, !!(genEnabled & S_BIT));
         _mesa_set_enable(ctx, GL_TEXTURE_GEN_T, !!(genEnabled & T_BIT));
         _mesa_set_enable(ctx, GL_TEXTURE_GEN_R, !!(genEnabled & R_BIT));
         _mesa_set_enable(ctx, GL_TEXTURE_GEN_Q, !!(genEnabled & Q_BIT));
      }
   }

   _mesa_ActiveTexture(GL_TEXTURE0 + curTexUnitSave);
}


/**
 * Pop/restore texture attribute/group state.
 */
static void
pop_texture_group(struct gl_context *ctx, struct texture_state *texstate)
{
   GLuint u;

   _mesa_lock_context_textures(ctx);

   for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
      const struct gl_fixedfunc_texture_unit *unit =
         &texstate->Texture.FixedFuncUnit[u];
      GLuint tgt;

      _mesa_ActiveTexture(GL_TEXTURE0_ARB + u);
      _mesa_set_enable(ctx, GL_TEXTURE_1D, !!(unit->Enabled & TEXTURE_1D_BIT));
      _mesa_set_enable(ctx, GL_TEXTURE_2D, !!(unit->Enabled & TEXTURE_2D_BIT));
      _mesa_set_enable(ctx, GL_TEXTURE_3D, !!(unit->Enabled & TEXTURE_3D_BIT));
      if (ctx->Extensions.ARB_texture_cube_map) {
         _mesa_set_enable(ctx, GL_TEXTURE_CUBE_MAP,
                          !!(unit->Enabled & TEXTURE_CUBE_BIT));
      }
      if (ctx->Extensions.NV_texture_rectangle) {
         _mesa_set_enable(ctx, GL_TEXTURE_RECTANGLE_NV,
                          !!(unit->Enabled & TEXTURE_RECT_BIT));
      }
      _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->EnvMode);
      _mesa_TexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, unit->EnvColor);
      _mesa_TexGeni(GL_S, GL_TEXTURE_GEN_MODE, unit->GenS.Mode);
      _mesa_TexGeni(GL_T, GL_TEXTURE_GEN_MODE, unit->GenT.Mode);
      _mesa_TexGeni(GL_R, GL_TEXTURE_GEN_MODE, unit->GenR.Mode);
      _mesa_TexGeni(GL_Q, GL_TEXTURE_GEN_MODE, unit->GenQ.Mode);
      _mesa_TexGenfv(GL_S, GL_OBJECT_PLANE, unit->GenS.ObjectPlane);
      _mesa_TexGenfv(GL_T, GL_OBJECT_PLANE, unit->GenT.ObjectPlane);
      _mesa_TexGenfv(GL_R, GL_OBJECT_PLANE, unit->GenR.ObjectPlane);
      _mesa_TexGenfv(GL_Q, GL_OBJECT_PLANE, unit->GenQ.ObjectPlane);
      /* Eye plane done differently to avoid re-transformation */
      {
         struct gl_fixedfunc_texture_unit *destUnit =
            &ctx->Texture.FixedFuncUnit[u];

         COPY_4FV(destUnit->GenS.EyePlane, unit->GenS.EyePlane);
         COPY_4FV(destUnit->GenT.EyePlane, unit->GenT.EyePlane);
         COPY_4FV(destUnit->GenR.EyePlane, unit->GenR.EyePlane);
         COPY_4FV(destUnit->GenQ.EyePlane, unit->GenQ.EyePlane);
         if (ctx->Driver.TexGen) {
            ctx->Driver.TexGen(ctx, GL_S, GL_EYE_PLANE, unit->GenS.EyePlane);
            ctx->Driver.TexGen(ctx, GL_T, GL_EYE_PLANE, unit->GenT.EyePlane);
            ctx->Driver.TexGen(ctx, GL_R, GL_EYE_PLANE, unit->GenR.EyePlane);
            ctx->Driver.TexGen(ctx, GL_Q, GL_EYE_PLANE, unit->GenQ.EyePlane);
         }
      }
      _mesa_set_enable(ctx, GL_TEXTURE_GEN_S, !!(unit->TexGenEnabled & S_BIT));
      _mesa_set_enable(ctx, GL_TEXTURE_GEN_T, !!(unit->TexGenEnabled & T_BIT));
      _mesa_set_enable(ctx, GL_TEXTURE_GEN_R, !!(unit->TexGenEnabled & R_BIT));
      _mesa_set_enable(ctx, GL_TEXTURE_GEN_Q, !!(unit->TexGenEnabled & Q_BIT));
      _mesa_TexEnvf(GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS,
		    texstate->Texture.Unit[u].LodBias);
      _mesa_TexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB,
                    unit->Combine.ModeRGB);
      _mesa_TexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA,
                    unit->Combine.ModeA);
      {
         const GLuint n = ctx->Extensions.NV_texture_env_combine4 ? 4 : 3;
         GLuint i;
         for (i = 0; i < n; i++) {
            _mesa_TexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB + i,
                          unit->Combine.SourceRGB[i]);
            _mesa_TexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA + i,
                          unit->Combine.SourceA[i]);
            _mesa_TexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB + i,
                          unit->Combine.OperandRGB[i]);
            _mesa_TexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA + i,
                          unit->Combine.OperandA[i]);
         }
      }
      _mesa_TexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE,
                    1 << unit->Combine.ScaleShiftRGB);
      _mesa_TexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE,
                    1 << unit->Combine.ScaleShiftA);

      /* Restore texture object state for each target */
      for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
         const struct gl_texture_object *obj = NULL;
         const struct gl_sampler_object *samp;
         GLenum target;

         obj = &texstate->SavedObj[u][tgt];

         /* don't restore state for unsupported targets to prevent
          * raising GL errors.
          */
         if (obj->Target == GL_TEXTURE_CUBE_MAP &&
             !ctx->Extensions.ARB_texture_cube_map) {
            continue;
         }
         else if (obj->Target == GL_TEXTURE_RECTANGLE_NV &&
                  !ctx->Extensions.NV_texture_rectangle) {
            continue;
         }
         else if ((obj->Target == GL_TEXTURE_1D_ARRAY_EXT ||
                   obj->Target == GL_TEXTURE_2D_ARRAY_EXT) &&
                  !ctx->Extensions.EXT_texture_array) {
            continue;
         }
         else if (obj->Target == GL_TEXTURE_CUBE_MAP_ARRAY &&
             !ctx->Extensions.ARB_texture_cube_map_array) {
            continue;
         } else if (obj->Target == GL_TEXTURE_BUFFER)
            continue;
         else if (obj->Target == GL_TEXTURE_EXTERNAL_OES)
            continue;
         else if (obj->Target == GL_TEXTURE_2D_MULTISAMPLE ||
                  obj->Target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
            continue;

         target = obj->Target;

         _mesa_BindTexture(target, obj->Name);

         samp = &obj->Sampler;

         _mesa_TexParameterfv(target, GL_TEXTURE_BORDER_COLOR, samp->BorderColor.f);
         _mesa_TexParameteri(target, GL_TEXTURE_WRAP_S, samp->WrapS);
         _mesa_TexParameteri(target, GL_TEXTURE_WRAP_T, samp->WrapT);
         _mesa_TexParameteri(target, GL_TEXTURE_WRAP_R, samp->WrapR);
         _mesa_TexParameteri(target, GL_TEXTURE_MIN_FILTER, samp->MinFilter);
         _mesa_TexParameteri(target, GL_TEXTURE_MAG_FILTER, samp->MagFilter);
         _mesa_TexParameterf(target, GL_TEXTURE_MIN_LOD, samp->MinLod);
         _mesa_TexParameterf(target, GL_TEXTURE_MAX_LOD, samp->MaxLod);
         _mesa_TexParameterf(target, GL_TEXTURE_LOD_BIAS, samp->LodBias);
         _mesa_TexParameterf(target, GL_TEXTURE_PRIORITY, obj->Priority);
         _mesa_TexParameteri(target, GL_TEXTURE_BASE_LEVEL, obj->BaseLevel);
         if (target != GL_TEXTURE_RECTANGLE_ARB)
            _mesa_TexParameteri(target, GL_TEXTURE_MAX_LEVEL, obj->MaxLevel);
         if (ctx->Extensions.EXT_texture_filter_anisotropic) {
            _mesa_TexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT,
                                samp->MaxAnisotropy);
         }
         if (ctx->Extensions.ARB_shadow) {
            _mesa_TexParameteri(target, GL_TEXTURE_COMPARE_MODE,
                                samp->CompareMode);
            _mesa_TexParameteri(target, GL_TEXTURE_COMPARE_FUNC,
                                samp->CompareFunc);
         }
         if (ctx->Extensions.ARB_depth_texture)
            _mesa_TexParameteri(target, GL_DEPTH_TEXTURE_MODE, obj->DepthMode);
      }

      /* remove saved references to the texture objects */
      for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
         _mesa_reference_texobj(&texstate->SavedTexRef[u][tgt], NULL);
      }
   }

   _mesa_ActiveTexture(GL_TEXTURE0_ARB + texstate->Texture.CurrentUnit);

   _mesa_reference_shared_state(ctx, &texstate->SharedRef, NULL);

   _mesa_unlock_context_textures(ctx);
}


/*
 * This function is kind of long just because we have to call a lot
 * of device driver functions to update device driver state.
 *
 * XXX As it is now, most of the pop-code calls immediate-mode Mesa functions
 * in order to restore GL state.  This isn't terribly efficient but it
 * ensures that dirty flags and any derived state gets updated correctly.
 * We could at least check if the value to restore equals the current value
 * and then skip the Mesa call.
 */
void GLAPIENTRY
_mesa_PopAttrib(void)
{
   struct gl_attrib_node *attr, *next;
   GET_CURRENT_CONTEXT(ctx);
   FLUSH_VERTICES(ctx, 0);

   if (ctx->AttribStackDepth == 0) {
      _mesa_error(ctx, GL_STACK_UNDERFLOW, "glPopAttrib");
      return;
   }

   ctx->AttribStackDepth--;
   attr = ctx->AttribStack[ctx->AttribStackDepth];

   while (attr) {

      if (MESA_VERBOSE & VERBOSE_API) {
         _mesa_debug(ctx, "glPopAttrib %s\n",
                     _mesa_enum_to_string(attr->kind));
      }

      switch (attr->kind) {
         case DUMMY_BIT:
            /* do nothing */
            break;

         case GL_ACCUM_BUFFER_BIT:
            {
               const struct gl_accum_attrib *accum;
               accum = (const struct gl_accum_attrib *) attr->data;
               _mesa_ClearAccum(accum->ClearColor[0],
                                accum->ClearColor[1],
                                accum->ClearColor[2],
                                accum->ClearColor[3]);
            }
            break;
         case GL_COLOR_BUFFER_BIT:
            {
               const struct gl_colorbuffer_attrib *color;

               color = (const struct gl_colorbuffer_attrib *) attr->data;
               _mesa_ClearIndex((GLfloat) color->ClearIndex);
               _mesa_ClearColor(color->ClearColor.f[0],
                                color->ClearColor.f[1],
                                color->ClearColor.f[2],
                                color->ClearColor.f[3]);
               _mesa_IndexMask(color->IndexMask);
               if (!ctx->Extensions.EXT_draw_buffers2) {
                  _mesa_ColorMask(GET_COLORMASK_BIT(color->ColorMask, 0, 0),
                                  GET_COLORMASK_BIT(color->ColorMask, 0, 1),
                                  GET_COLORMASK_BIT(color->ColorMask, 0, 2),
                                  GET_COLORMASK_BIT(color->ColorMask, 0, 3));
               }
               else {
                  GLuint i;
                  for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
                     _mesa_ColorMaski(i,
                                      GET_COLORMASK_BIT(color->ColorMask, i, 0),
                                      GET_COLORMASK_BIT(color->ColorMask, i, 1),
                                      GET_COLORMASK_BIT(color->ColorMask, i, 2),
                                      GET_COLORMASK_BIT(color->ColorMask, i, 3));
                  }
               }
               {
                  /* Need to determine if more than one color output is
                   * specified.  If so, call glDrawBuffersARB, else call
                   * glDrawBuffer().  This is a subtle, but essential point
                   * since GL_FRONT (for example) is illegal for the former
                   * function, but legal for the later.
                   */
                  GLboolean multipleBuffers = GL_FALSE;
                  GLuint i;

                  for (i = 1; i < ctx->Const.MaxDrawBuffers; i++) {
                     if (color->DrawBuffer[i] != GL_NONE) {
                        multipleBuffers = GL_TRUE;
                        break;
                     }
                  }
                  /* Call the API_level functions, not _mesa_drawbuffers()
                   * since we need to do error checking on the pop'd
                   * GL_DRAW_BUFFER.
                   * Ex: if GL_FRONT were pushed, but we're popping with a
                   * user FBO bound, GL_FRONT will be illegal and we'll need
                   * to record that error.  Per OpenGL ARB decision.
                   */
                  if (multipleBuffers) {
                     GLenum buffers[MAX_DRAW_BUFFERS];

                     for (unsigned i = 0; i < ctx->Const.MaxDrawBuffers; i++)
                        buffers[i] = color->DrawBuffer[i];

                     _mesa_DrawBuffers(ctx->Const.MaxDrawBuffers, buffers);
                  } else {
                     _mesa_DrawBuffer(color->DrawBuffer[0]);
                  }
               }
               _mesa_set_enable(ctx, GL_ALPHA_TEST, color->AlphaEnabled);
               _mesa_AlphaFunc(color->AlphaFunc, color->AlphaRefUnclamped);
               if (ctx->Color.BlendEnabled != color->BlendEnabled) {
                  if (ctx->Extensions.EXT_draw_buffers2) {
                     GLuint i;
                     for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
                        _mesa_set_enablei(ctx, GL_BLEND, i,
                                          (color->BlendEnabled >> i) & 1);
                     }
                  }
                  else {
                     _mesa_set_enable(ctx, GL_BLEND, (color->BlendEnabled & 1));
                  }
               }
               if (ctx->Color._BlendFuncPerBuffer ||
                   ctx->Color._BlendEquationPerBuffer) {
                  /* set blend per buffer */
                  GLuint buf;
                  for (buf = 0; buf < ctx->Const.MaxDrawBuffers; buf++) {
                     _mesa_BlendFuncSeparateiARB(buf, color->Blend[buf].SrcRGB,
                                              color->Blend[buf].DstRGB,
                                              color->Blend[buf].SrcA,
                                              color->Blend[buf].DstA);
                     _mesa_BlendEquationSeparateiARB(buf,
                                                  color->Blend[buf].EquationRGB,
                                                  color->Blend[buf].EquationA);
                  }
               }
               else {
                  /* set same blend modes for all buffers */
                  _mesa_BlendFuncSeparate(color->Blend[0].SrcRGB,
                                             color->Blend[0].DstRGB,
                                             color->Blend[0].SrcA,
                                             color->Blend[0].DstA);
                  /* This special case is because glBlendEquationSeparateEXT
                   * cannot take GL_LOGIC_OP as a parameter.
                   */
                  if (color->Blend[0].EquationRGB ==
                      color->Blend[0].EquationA) {
                     _mesa_BlendEquation(color->Blend[0].EquationRGB);
                  }
                  else {
                     _mesa_BlendEquationSeparate(
                                                 color->Blend[0].EquationRGB,
                                                 color->Blend[0].EquationA);
                  }
               }
               _mesa_BlendColor(color->BlendColorUnclamped[0],
                                color->BlendColorUnclamped[1],
                                color->BlendColorUnclamped[2],
                                color->BlendColorUnclamped[3]);
               _mesa_LogicOp(color->LogicOp);
               _mesa_set_enable(ctx, GL_COLOR_LOGIC_OP,
                                color->ColorLogicOpEnabled);
               _mesa_set_enable(ctx, GL_INDEX_LOGIC_OP,
                                color->IndexLogicOpEnabled);
               _mesa_set_enable(ctx, GL_DITHER, color->DitherFlag);
               if (ctx->Extensions.ARB_color_buffer_float)
                  _mesa_ClampColor(GL_CLAMP_FRAGMENT_COLOR_ARB,
                                   color->ClampFragmentColor);
               if (ctx->Extensions.ARB_color_buffer_float || ctx->Version >= 30)
                  _mesa_ClampColor(GL_CLAMP_READ_COLOR_ARB, color->ClampReadColor);

               /* GL_ARB_framebuffer_sRGB / GL_EXT_framebuffer_sRGB */
               if (ctx->Extensions.EXT_framebuffer_sRGB)
                  _mesa_set_enable(ctx, GL_FRAMEBUFFER_SRGB, color->sRGBEnabled);
            }
            break;
         case GL_CURRENT_BIT:
            FLUSH_CURRENT(ctx, 0);
            memcpy(&ctx->Current, attr->data,
                    sizeof(struct gl_current_attrib));
            break;
         case GL_DEPTH_BUFFER_BIT:
            {
               const struct gl_depthbuffer_attrib *depth;
               depth = (const struct gl_depthbuffer_attrib *) attr->data;
               _mesa_DepthFunc(depth->Func);
               _mesa_ClearDepth(depth->Clear);
               _mesa_set_enable(ctx, GL_DEPTH_TEST, depth->Test);
               _mesa_DepthMask(depth->Mask);
               if (ctx->Extensions.EXT_depth_bounds_test) {
                  _mesa_set_enable(ctx, GL_DEPTH_BOUNDS_TEST_EXT,
                                   depth->BoundsTest);
                  _mesa_DepthBoundsEXT(depth->BoundsMin, depth->BoundsMax);
               }
            }
            break;
         case GL_ENABLE_BIT:
            {
               const struct gl_enable_attrib *enable;
               enable = (const struct gl_enable_attrib *) attr->data;
               pop_enable_group(ctx, enable);
               ctx->NewState |= _NEW_ALL;
               ctx->NewDriverState |= ctx->DriverFlags.NewAlphaTest |
                                      ctx->DriverFlags.NewBlend |
                                      ctx->DriverFlags.NewClipPlaneEnable |
                                      ctx->DriverFlags.NewDepth |
                                      ctx->DriverFlags.NewDepthClamp |
                                      ctx->DriverFlags.NewFramebufferSRGB |
                                      ctx->DriverFlags.NewLineState |
                                      ctx->DriverFlags.NewLogicOp |
                                      ctx->DriverFlags.NewMultisampleEnable |
                                      ctx->DriverFlags.NewPolygonState |
                                      ctx->DriverFlags.NewSampleAlphaToXEnable |
                                      ctx->DriverFlags.NewSampleMask |
                                      ctx->DriverFlags.NewScissorTest |
                                      ctx->DriverFlags.NewStencil |
                                      ctx->DriverFlags.NewNvConservativeRasterization;
            }
            break;
         case GL_EVAL_BIT:
            memcpy(&ctx->Eval, attr->data, sizeof(struct gl_eval_attrib));
            vbo_exec_update_eval_maps(ctx);
            break;
         case GL_FOG_BIT:
            {
               const struct gl_fog_attrib *fog;
               fog = (const struct gl_fog_attrib *) attr->data;
               _mesa_set_enable(ctx, GL_FOG, fog->Enabled);
               _mesa_Fogfv(GL_FOG_COLOR, fog->Color);
               _mesa_Fogf(GL_FOG_DENSITY, fog->Density);
               _mesa_Fogf(GL_FOG_START, fog->Start);
               _mesa_Fogf(GL_FOG_END, fog->End);
               _mesa_Fogf(GL_FOG_INDEX, fog->Index);
               _mesa_Fogi(GL_FOG_MODE, fog->Mode);
            }
            break;
         case GL_HINT_BIT:
            {
               const struct gl_hint_attrib *hint;
               hint = (const struct gl_hint_attrib *) attr->data;
               _mesa_Hint(GL_PERSPECTIVE_CORRECTION_HINT,
                          hint->PerspectiveCorrection);
               _mesa_Hint(GL_POINT_SMOOTH_HINT, hint->PointSmooth);
               _mesa_Hint(GL_LINE_SMOOTH_HINT, hint->LineSmooth);
               _mesa_Hint(GL_POLYGON_SMOOTH_HINT, hint->PolygonSmooth);
               _mesa_Hint(GL_FOG_HINT, hint->Fog);
               _mesa_Hint(GL_TEXTURE_COMPRESSION_HINT_ARB,
                          hint->TextureCompression);
            }
            break;
         case GL_LIGHTING_BIT:
            {
               GLuint i;
               const struct gl_light_attrib *light;
               light = (const struct gl_light_attrib *) attr->data;
               /* lighting enable */
               _mesa_set_enable(ctx, GL_LIGHTING, light->Enabled);
               /* per-light state */
               if (_math_matrix_is_dirty(ctx->ModelviewMatrixStack.Top))
                  _math_matrix_analyse(ctx->ModelviewMatrixStack.Top);

               for (i = 0; i < ctx->Const.MaxLights; i++) {
                  const struct gl_light *l = &light->Light[i];
                  _mesa_set_enable(ctx, GL_LIGHT0 + i, l->Enabled);
                  _mesa_light(ctx, i, GL_AMBIENT, l->Ambient);
                  _mesa_light(ctx, i, GL_DIFFUSE, l->Diffuse);
                  _mesa_light(ctx, i, GL_SPECULAR, l->Specular);
                  _mesa_light(ctx, i, GL_POSITION, l->EyePosition);
                  _mesa_light(ctx, i, GL_SPOT_DIRECTION, l->SpotDirection);
                  {
                     GLfloat p[4] = { 0 };
                     p[0] = l->SpotExponent;
                     _mesa_light(ctx, i, GL_SPOT_EXPONENT, p);
                  }
                  {
                     GLfloat p[4] = { 0 };
                     p[0] = l->SpotCutoff;
                     _mesa_light(ctx, i, GL_SPOT_CUTOFF, p);
                  }
                  {
                     GLfloat p[4] = { 0 };
                     p[0] = l->ConstantAttenuation;
                     _mesa_light(ctx, i, GL_CONSTANT_ATTENUATION, p);
                  }
                  {
                     GLfloat p[4] = { 0 };
                     p[0] = l->LinearAttenuation;
                     _mesa_light(ctx, i, GL_LINEAR_ATTENUATION, p);
                  }
                  {
                     GLfloat p[4] = { 0 };
                     p[0] = l->QuadraticAttenuation;
                     _mesa_light(ctx, i, GL_QUADRATIC_ATTENUATION, p);
                  }
               }
               /* light model */
               _mesa_LightModelfv(GL_LIGHT_MODEL_AMBIENT,
                                  light->Model.Ambient);
               _mesa_LightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER,
                                 (GLfloat) light->Model.LocalViewer);
               _mesa_LightModelf(GL_LIGHT_MODEL_TWO_SIDE,
                                 (GLfloat) light->Model.TwoSide);
               _mesa_LightModelf(GL_LIGHT_MODEL_COLOR_CONTROL,
                                 (GLfloat) light->Model.ColorControl);
               /* shade model */
               _mesa_ShadeModel(light->ShadeModel);
               /* color material */
               _mesa_ColorMaterial(light->ColorMaterialFace,
                                   light->ColorMaterialMode);
               _mesa_set_enable(ctx, GL_COLOR_MATERIAL,
                                light->ColorMaterialEnabled);
               /* materials */
               memcpy(&ctx->Light.Material, &light->Material,
                      sizeof(struct gl_material));
               if (ctx->Extensions.ARB_color_buffer_float) {
                  _mesa_ClampColor(GL_CLAMP_VERTEX_COLOR_ARB,
                                   light->ClampVertexColor);
               }
            }
            break;
         case GL_LINE_BIT:
            {
               const struct gl_line_attrib *line;
               line = (const struct gl_line_attrib *) attr->data;
               _mesa_set_enable(ctx, GL_LINE_SMOOTH, line->SmoothFlag);
               _mesa_set_enable(ctx, GL_LINE_STIPPLE, line->StippleFlag);
               _mesa_LineStipple(line->StippleFactor, line->StipplePattern);
               _mesa_LineWidth(line->Width);
            }
            break;
         case GL_LIST_BIT:
            memcpy(&ctx->List, attr->data, sizeof(struct gl_list_attrib));
            break;
         case GL_PIXEL_MODE_BIT:
            memcpy(&ctx->Pixel, attr->data, sizeof(struct gl_pixel_attrib));
            /* XXX what other pixel state needs to be set by function calls? */
            _mesa_ReadBuffer(ctx->Pixel.ReadBuffer);
            ctx->NewState |= _NEW_PIXEL;
            break;
         case GL_POINT_BIT:
            {
               const struct gl_point_attrib *point;
               point = (const struct gl_point_attrib *) attr->data;
               _mesa_PointSize(point->Size);
               _mesa_set_enable(ctx, GL_POINT_SMOOTH, point->SmoothFlag);
               if (ctx->Extensions.EXT_point_parameters) {
                  _mesa_PointParameterfv(GL_DISTANCE_ATTENUATION_EXT,
                                         point->Params);
                  _mesa_PointParameterf(GL_POINT_SIZE_MIN_EXT,
                                        point->MinSize);
                  _mesa_PointParameterf(GL_POINT_SIZE_MAX_EXT,
                                        point->MaxSize);
                  _mesa_PointParameterf(GL_POINT_FADE_THRESHOLD_SIZE_EXT,
                                        point->Threshold);
               }
               if (ctx->Extensions.NV_point_sprite
                   || ctx->Extensions.ARB_point_sprite) {
                  GLuint u;
                  for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
                     _mesa_TexEnvi(GL_POINT_SPRITE_NV, GL_COORD_REPLACE_NV,
                                   !!(point->CoordReplace & (1u << u)));
                  }
                  _mesa_set_enable(ctx, GL_POINT_SPRITE_NV,point->PointSprite);
                  if (ctx->Extensions.NV_point_sprite)
                     _mesa_PointParameteri(GL_POINT_SPRITE_R_MODE_NV,
                                           ctx->Point.SpriteRMode);

                  if ((ctx->API == API_OPENGL_COMPAT && ctx->Version >= 20)
                      || ctx->API == API_OPENGL_CORE)
                     _mesa_PointParameterf(GL_POINT_SPRITE_COORD_ORIGIN,
                                           (GLfloat)ctx->Point.SpriteOrigin);
               }
            }
            break;
         case GL_POLYGON_BIT:
            {
               const struct gl_polygon_attrib *polygon;
               polygon = (const struct gl_polygon_attrib *) attr->data;
               _mesa_CullFace(polygon->CullFaceMode);
               _mesa_FrontFace(polygon->FrontFace);
               _mesa_PolygonMode(GL_FRONT, polygon->FrontMode);
               _mesa_PolygonMode(GL_BACK, polygon->BackMode);
               _mesa_polygon_offset_clamp(ctx,
                                          polygon->OffsetFactor,
                                          polygon->OffsetUnits,
                                          polygon->OffsetClamp);
               _mesa_set_enable(ctx, GL_POLYGON_SMOOTH, polygon->SmoothFlag);
               _mesa_set_enable(ctx, GL_POLYGON_STIPPLE, polygon->StippleFlag);
               _mesa_set_enable(ctx, GL_CULL_FACE, polygon->CullFlag);
               _mesa_set_enable(ctx, GL_POLYGON_OFFSET_POINT,
                                polygon->OffsetPoint);
               _mesa_set_enable(ctx, GL_POLYGON_OFFSET_LINE,
                                polygon->OffsetLine);
               _mesa_set_enable(ctx, GL_POLYGON_OFFSET_FILL,
                                polygon->OffsetFill);
            }
            break;
         case GL_POLYGON_STIPPLE_BIT:
            memcpy(ctx->PolygonStipple, attr->data, 32*sizeof(GLuint));

            if (ctx->DriverFlags.NewPolygonStipple)
               ctx->NewDriverState |= ctx->DriverFlags.NewPolygonStipple;
            else
               ctx->NewState |= _NEW_POLYGONSTIPPLE;

            if (ctx->Driver.PolygonStipple)
               ctx->Driver.PolygonStipple(ctx, (const GLubyte *) attr->data);
            break;
         case GL_SCISSOR_BIT:
            {
               unsigned i;
               const struct gl_scissor_attrib *scissor;
               scissor = (const struct gl_scissor_attrib *) attr->data;

               for (i = 0; i < ctx->Const.MaxViewports; i++) {
                  _mesa_set_scissor(ctx, i,
                                    scissor->ScissorArray[i].X,
                                    scissor->ScissorArray[i].Y,
                                    scissor->ScissorArray[i].Width,
                                    scissor->ScissorArray[i].Height);
                  _mesa_set_enablei(ctx, GL_SCISSOR_TEST, i,
                                    (scissor->EnableFlags >> i) & 1);
               }
               if (ctx->Extensions.EXT_window_rectangles) {
                  STATIC_ASSERT(sizeof(struct gl_scissor_rect) ==
                                4 * sizeof(GLint));
                  _mesa_WindowRectanglesEXT(
                        scissor->WindowRectMode, scissor->NumWindowRects,
                        (const GLint *)scissor->WindowRects);
               }
            }
            break;
         case GL_STENCIL_BUFFER_BIT:
            {
               const struct gl_stencil_attrib *stencil;
               stencil = (const struct gl_stencil_attrib *) attr->data;
               _mesa_set_enable(ctx, GL_STENCIL_TEST, stencil->Enabled);
               _mesa_ClearStencil(stencil->Clear);
               if (ctx->Extensions.EXT_stencil_two_side) {
                  _mesa_set_enable(ctx, GL_STENCIL_TEST_TWO_SIDE_EXT,
                                   stencil->TestTwoSide);
                  _mesa_ActiveStencilFaceEXT(stencil->ActiveFace
                                             ? GL_BACK : GL_FRONT);
               }
               /* front state */
               _mesa_StencilFuncSeparate(GL_FRONT,
                                         stencil->Function[0],
                                         stencil->Ref[0],
                                         stencil->ValueMask[0]);
               _mesa_StencilMaskSeparate(GL_FRONT, stencil->WriteMask[0]);
               _mesa_StencilOpSeparate(GL_FRONT, stencil->FailFunc[0],
                                       stencil->ZFailFunc[0],
                                       stencil->ZPassFunc[0]);
               /* back state */
               _mesa_StencilFuncSeparate(GL_BACK,
                                         stencil->Function[1],
                                         stencil->Ref[1],
                                         stencil->ValueMask[1]);
               _mesa_StencilMaskSeparate(GL_BACK, stencil->WriteMask[1]);
               _mesa_StencilOpSeparate(GL_BACK, stencil->FailFunc[1],
                                       stencil->ZFailFunc[1],
                                       stencil->ZPassFunc[1]);
            }
            break;
         case GL_TRANSFORM_BIT:
            {
               GLuint i;
               const struct gl_transform_attrib *xform;
               xform = (const struct gl_transform_attrib *) attr->data;
               _mesa_MatrixMode(xform->MatrixMode);
               if (_math_matrix_is_dirty(ctx->ProjectionMatrixStack.Top))
                  _math_matrix_analyse(ctx->ProjectionMatrixStack.Top);

               /* restore clip planes */
               for (i = 0; i < ctx->Const.MaxClipPlanes; i++) {
                  const GLuint mask = 1 << i;
                  const GLfloat *eyePlane = xform->EyeUserPlane[i];
                  COPY_4V(ctx->Transform.EyeUserPlane[i], eyePlane);
                  _mesa_set_enable(ctx, GL_CLIP_PLANE0 + i,
                                   !!(xform->ClipPlanesEnabled & mask));
                  if (ctx->Driver.ClipPlane)
                     ctx->Driver.ClipPlane(ctx, GL_CLIP_PLANE0 + i, eyePlane);
               }

               /* normalize/rescale */
               if (xform->Normalize != ctx->Transform.Normalize)
                  _mesa_set_enable(ctx, GL_NORMALIZE,ctx->Transform.Normalize);
               if (xform->RescaleNormals != ctx->Transform.RescaleNormals)
                  _mesa_set_enable(ctx, GL_RESCALE_NORMAL_EXT,
                                   ctx->Transform.RescaleNormals);

               if (!ctx->Extensions.AMD_depth_clamp_separate) {
                  if (xform->DepthClampNear != ctx->Transform.DepthClampNear &&
                      xform->DepthClampFar != ctx->Transform.DepthClampFar) {
                     _mesa_set_enable(ctx, GL_DEPTH_CLAMP,
                                      ctx->Transform.DepthClampNear &&
                                      ctx->Transform.DepthClampFar);
                  }
               } else {
                  if (xform->DepthClampNear != ctx->Transform.DepthClampNear)
                     _mesa_set_enable(ctx, GL_DEPTH_CLAMP_NEAR_AMD,
                                      ctx->Transform.DepthClampNear);
                  if (xform->DepthClampFar != ctx->Transform.DepthClampFar)
                     _mesa_set_enable(ctx, GL_DEPTH_CLAMP_FAR_AMD,
                                      ctx->Transform.DepthClampFar);
               }

               if (ctx->Extensions.ARB_clip_control)
                  _mesa_ClipControl(xform->ClipOrigin, xform->ClipDepthMode);
            }
            break;
         case GL_TEXTURE_BIT:
            {
               struct texture_state *texstate
                  = (struct texture_state *) attr->data;
               pop_texture_group(ctx, texstate);
               ctx->NewState |= _NEW_TEXTURE_OBJECT | _NEW_TEXTURE_STATE;
            }
            break;
         case GL_VIEWPORT_BIT:
            {
               unsigned i;
               const struct viewport_state *viewstate;
               viewstate = (const struct viewport_state *) attr->data;

               for (i = 0; i < ctx->Const.MaxViewports; i++) {
                  const struct gl_viewport_attrib *vp = &viewstate->ViewportArray[i];
                  _mesa_set_viewport(ctx, i, vp->X, vp->Y, vp->Width,
                                     vp->Height);
                  _mesa_set_depth_range(ctx, i, vp->Near, vp->Far);
               }

               if (ctx->Extensions.NV_conservative_raster) {
                  GLuint biasx = viewstate->SubpixelPrecisionBias[0];
                  GLuint biasy = viewstate->SubpixelPrecisionBias[1];
                  _mesa_SubpixelPrecisionBiasNV(biasx, biasy);
               }
            }
            break;
         case GL_MULTISAMPLE_BIT_ARB:
            {
               const struct gl_multisample_attrib *ms;
               ms = (const struct gl_multisample_attrib *) attr->data;

               TEST_AND_UPDATE(ctx->Multisample.Enabled,
                               ms->Enabled,
                               GL_MULTISAMPLE);

               TEST_AND_UPDATE(ctx->Multisample.SampleCoverage,
                               ms->SampleCoverage,
                               GL_SAMPLE_COVERAGE);

               TEST_AND_UPDATE(ctx->Multisample.SampleAlphaToCoverage,
                               ms->SampleAlphaToCoverage,
                               GL_SAMPLE_ALPHA_TO_COVERAGE);

               TEST_AND_UPDATE(ctx->Multisample.SampleAlphaToOne,
                               ms->SampleAlphaToOne,
                               GL_SAMPLE_ALPHA_TO_ONE);

               _mesa_SampleCoverage(ms->SampleCoverageValue,
                                       ms->SampleCoverageInvert);

               _mesa_AlphaToCoverageDitherControlNV(ms->SampleAlphaToCoverageDitherControl);
            }
            break;

         default:
            unreachable("Bad attrib flag in PopAttrib");
      }

      next = attr->next;
      free(attr->data);
      free(attr);
      attr = next;
   }
}


/**
 * Copy gl_pixelstore_attrib from src to dst, updating buffer
 * object refcounts.
 */
static void
copy_pixelstore(struct gl_context *ctx,
                struct gl_pixelstore_attrib *dst,
                const struct gl_pixelstore_attrib *src)
{
   dst->Alignment = src->Alignment;
   dst->RowLength = src->RowLength;
   dst->SkipPixels = src->SkipPixels;
   dst->SkipRows = src->SkipRows;
   dst->ImageHeight = src->ImageHeight;
   dst->SkipImages = src->SkipImages;
   dst->SwapBytes = src->SwapBytes;
   dst->LsbFirst = src->LsbFirst;
   dst->Invert = src->Invert;
   _mesa_reference_buffer_object(ctx, &dst->BufferObj, src->BufferObj);
}


#define GL_CLIENT_PACK_BIT (1<<20)
#define GL_CLIENT_UNPACK_BIT (1<<21)

/**
 * Copy gl_vertex_array_object from src to dest.
 * 'dest' must be in an initialized state.
 */
static void
copy_array_object(struct gl_context *ctx,
                  struct gl_vertex_array_object *dest,
                  struct gl_vertex_array_object *src)
{
   GLuint i;

   /* skip Name */
   /* skip RefCount */

   for (i = 0; i < ARRAY_SIZE(src->VertexAttrib); i++) {
      _mesa_copy_vertex_attrib_array(ctx, &dest->VertexAttrib[i], &src->VertexAttrib[i]);
      _mesa_copy_vertex_buffer_binding(ctx, &dest->BufferBinding[i], &src->BufferBinding[i]);
   }

   /* Enabled must be the same than on push */
   dest->Enabled = src->Enabled;
   dest->_EffEnabledVBO = src->_EffEnabledVBO;
   dest->_EffEnabledNonZeroDivisor = src->_EffEnabledNonZeroDivisor;
   /* The bitmask of bound VBOs needs to match the VertexBinding array */
   dest->VertexAttribBufferMask = src->VertexAttribBufferMask;
   dest->NonZeroDivisorMask = src->NonZeroDivisorMask;
   dest->_AttributeMapMode = src->_AttributeMapMode;
   dest->NewArrays = src->NewArrays;
   dest->NumUpdates = src->NumUpdates;
   dest->IsDynamic = src->IsDynamic;
}

/**
 * Copy gl_array_attrib from src to dest.
 * 'dest' must be in an initialized state.
 */
static void
copy_array_attrib(struct gl_context *ctx,
                  struct gl_array_attrib *dest,
                  struct gl_array_attrib *src,
                  bool vbo_deleted)
{
   /* skip ArrayObj */
   /* skip DefaultArrayObj, Objects */
   dest->ActiveTexture = src->ActiveTexture;
   dest->LockFirst = src->LockFirst;
   dest->LockCount = src->LockCount;
   dest->PrimitiveRestart = src->PrimitiveRestart;
   dest->PrimitiveRestartFixedIndex = src->PrimitiveRestartFixedIndex;
   dest->_PrimitiveRestart = src->_PrimitiveRestart;
   dest->RestartIndex = src->RestartIndex;
   memcpy(dest->_RestartIndex, src->_RestartIndex, sizeof(src->_RestartIndex));
   /* skip NewState */
   /* skip RebindArrays */

   if (!vbo_deleted)
      copy_array_object(ctx, dest->VAO, src->VAO);

   /* skip ArrayBufferObj */
   /* skip IndexBufferObj */

   /* Invalidate array state. It will be updated during the next draw. */
   _mesa_set_draw_vao(ctx, ctx->Array._EmptyVAO, 0);
}

/**
 * Save the content of src to dest.
 */
static void
save_array_attrib(struct gl_context *ctx,
                  struct gl_array_attrib *dest,
                  struct gl_array_attrib *src)
{
   /* Set the Name, needed for restore, but do never overwrite.
    * Needs to match value in the object hash. */
   dest->VAO->Name = src->VAO->Name;
   /* And copy all of the rest. */
   copy_array_attrib(ctx, dest, src, false);

   /* Just reference them here */
   _mesa_reference_buffer_object(ctx, &dest->ArrayBufferObj,
                                 src->ArrayBufferObj);
   _mesa_reference_buffer_object(ctx, &dest->VAO->IndexBufferObj,
                                 src->VAO->IndexBufferObj);
}

/**
 * Restore the content of src to dest.
 */
static void
restore_array_attrib(struct gl_context *ctx,
                     struct gl_array_attrib *dest,
                     struct gl_array_attrib *src)
{
   bool is_vao_name_zero = src->VAO->Name == 0;

   /* The ARB_vertex_array_object spec says:
    *
    *     "BindVertexArray fails and an INVALID_OPERATION error is generated
    *     if array is not a name returned from a previous call to
    *     GenVertexArrays, or if such a name has since been deleted with
    *     DeleteVertexArrays."
    *
    * Therefore popping a deleted VAO cannot magically recreate it.
    */
   if (!is_vao_name_zero && !_mesa_IsVertexArray(src->VAO->Name))
      return;

   _mesa_BindVertexArray(src->VAO->Name);

   /* Restore or recreate the buffer objects by the names ... */
   if (is_vao_name_zero || !src->ArrayBufferObj ||
       _mesa_IsBuffer(src->ArrayBufferObj->Name)) {
      /* ... and restore its content */
      copy_array_attrib(ctx, dest, src, false);

      _mesa_BindBuffer(GL_ARRAY_BUFFER_ARB,
                       src->ArrayBufferObj ?
                          src->ArrayBufferObj->Name : 0);
   } else {
      copy_array_attrib(ctx, dest, src, true);
   }

   if (is_vao_name_zero || !src->VAO->IndexBufferObj ||
       _mesa_IsBuffer(src->VAO->IndexBufferObj->Name)) {
      _mesa_BindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB,
                       src->VAO->IndexBufferObj ?
                          src->VAO->IndexBufferObj->Name : 0);
   }
}


void GLAPIENTRY
_mesa_PushClientAttrib(GLbitfield mask)
{
   struct gl_client_attrib_node *head;

   GET_CURRENT_CONTEXT(ctx);

   if (ctx->ClientAttribStackDepth >= MAX_CLIENT_ATTRIB_STACK_DEPTH) {
      _mesa_error(ctx, GL_STACK_OVERFLOW, "glPushClientAttrib");
      return;
   }

   head = &ctx->ClientAttribStack[ctx->ClientAttribStackDepth];
   head->Mask = mask;

   if (mask & GL_CLIENT_PIXEL_STORE_BIT) {
      copy_pixelstore(ctx, &head->Pack, &ctx->Pack);
      copy_pixelstore(ctx, &head->Unpack, &ctx->Unpack);
   }

   if (mask & GL_CLIENT_VERTEX_ARRAY_BIT) {
      _mesa_initialize_vao(ctx, &head->VAO, 0);
      /* Use the VAO declared within the node instead of allocating it. */
      head->Array.VAO = &head->VAO;
      save_array_attrib(ctx, &head->Array, &ctx->Array);
   }

   ctx->ClientAttribStackDepth++;
}


void GLAPIENTRY
_mesa_PopClientAttrib(void)
{
   struct gl_client_attrib_node *head;

   GET_CURRENT_CONTEXT(ctx);
   FLUSH_VERTICES(ctx, 0);

   if (ctx->ClientAttribStackDepth == 0) {
      _mesa_error(ctx, GL_STACK_UNDERFLOW, "glPopClientAttrib");
      return;
   }

   ctx->ClientAttribStackDepth--;
   head = &ctx->ClientAttribStack[ctx->ClientAttribStackDepth];

   if (head->Mask & GL_CLIENT_PIXEL_STORE_BIT) {
      copy_pixelstore(ctx, &ctx->Pack, &head->Pack);
      _mesa_reference_buffer_object(ctx, &head->Pack.BufferObj, NULL);

      copy_pixelstore(ctx, &ctx->Unpack, &head->Unpack);
      _mesa_reference_buffer_object(ctx, &head->Unpack.BufferObj, NULL);
   }

   if (head->Mask & GL_CLIENT_VERTEX_ARRAY_BIT) {
      restore_array_attrib(ctx, &ctx->Array, &head->Array);
      _mesa_unbind_array_object_vbos(ctx, &head->VAO);
      _mesa_reference_buffer_object(ctx, &head->VAO.IndexBufferObj, NULL);
      _mesa_reference_buffer_object(ctx, &head->Array.ArrayBufferObj, NULL);
   }
}

void GLAPIENTRY
_mesa_ClientAttribDefaultEXT( GLbitfield mask )
{
   if (mask & GL_CLIENT_PIXEL_STORE_BIT) {
      _mesa_PixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
      _mesa_PixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
      _mesa_PixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
      _mesa_PixelStorei(GL_UNPACK_SKIP_IMAGES, 0);
      _mesa_PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
      _mesa_PixelStorei(GL_UNPACK_SKIP_ROWS, 0);
      _mesa_PixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
      _mesa_PixelStorei(GL_UNPACK_ALIGNMENT, 4);
      _mesa_PixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE);
      _mesa_PixelStorei(GL_PACK_LSB_FIRST, GL_FALSE);
      _mesa_PixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
      _mesa_PixelStorei(GL_PACK_SKIP_IMAGES, 0);
      _mesa_PixelStorei(GL_PACK_ROW_LENGTH, 0);
      _mesa_PixelStorei(GL_PACK_SKIP_ROWS, 0);
      _mesa_PixelStorei(GL_PACK_SKIP_PIXELS, 0);
      _mesa_PixelStorei(GL_PACK_ALIGNMENT, 4);

      _mesa_BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
      _mesa_BindBuffer(GL_PIXEL_PACK_BUFFER, 0);
   }
   if (mask & GL_CLIENT_VERTEX_ARRAY_BIT) {
      GET_CURRENT_CONTEXT(ctx);
      int i;

      _mesa_BindBuffer(GL_ARRAY_BUFFER, 0);
      _mesa_BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

      _mesa_DisableClientState(GL_EDGE_FLAG_ARRAY);
      _mesa_EdgeFlagPointer(0, 0);

      _mesa_DisableClientState(GL_INDEX_ARRAY);
      _mesa_IndexPointer(GL_FLOAT, 0, 0);

      _mesa_DisableClientState(GL_SECONDARY_COLOR_ARRAY);
      _mesa_SecondaryColorPointer(4, GL_FLOAT, 0, 0);

      _mesa_DisableClientState(GL_FOG_COORD_ARRAY);
      _mesa_FogCoordPointer(GL_FLOAT, 0, 0);

      for (i = 0; i < ctx->Const.MaxTextureCoordUnits; i++) {
         _mesa_ClientActiveTexture(GL_TEXTURE0 + i);
         _mesa_DisableClientState(GL_TEXTURE_COORD_ARRAY);
         _mesa_TexCoordPointer(4, GL_FLOAT, 0, 0);
      }

      _mesa_DisableClientState(GL_COLOR_ARRAY);
      _mesa_ColorPointer(4, GL_FLOAT, 0, 0);

      _mesa_DisableClientState(GL_NORMAL_ARRAY);
      _mesa_NormalPointer(GL_FLOAT, 0, 0);

      _mesa_DisableClientState(GL_VERTEX_ARRAY);
      _mesa_VertexPointer(4, GL_FLOAT, 0, 0);

      for (i = 0; i < ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs; i++) {
         _mesa_DisableVertexAttribArray(i);
         _mesa_VertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, 0, 0);
      }

      _mesa_ClientActiveTexture(GL_TEXTURE0);

      _mesa_PrimitiveRestartIndex_no_error(0);
      if (ctx->Version >= 31)
         _mesa_Disable(GL_PRIMITIVE_RESTART);
      else if (_mesa_has_NV_primitive_restart(ctx))
         _mesa_DisableClientState(GL_PRIMITIVE_RESTART_NV);

      if (_mesa_has_ARB_ES3_compatibility(ctx))
         _mesa_Disable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
   }
}

void GLAPIENTRY
_mesa_PushClientAttribDefaultEXT( GLbitfield mask )
{
   _mesa_PushClientAttrib(mask);
   _mesa_ClientAttribDefaultEXT(mask);
}


/**
 * Free any attribute state data that might be attached to the context.
 */
void
_mesa_free_attrib_data(struct gl_context *ctx)
{
   while (ctx->AttribStackDepth > 0) {
      struct gl_attrib_node *attr, *next;

      ctx->AttribStackDepth--;
      attr = ctx->AttribStack[ctx->AttribStackDepth];

      while (attr) {
         if (attr->kind == GL_TEXTURE_BIT) {
            struct texture_state *texstate = (struct texture_state*)attr->data;
            GLuint u, tgt;
            /* clear references to the saved texture objects */
            for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
               for (tgt = 0; tgt < NUM_TEXTURE_TARGETS; tgt++) {
                  _mesa_reference_texobj(&texstate->SavedTexRef[u][tgt], NULL);
               }
            }
            _mesa_reference_shared_state(ctx, &texstate->SharedRef, NULL);
         }
         else {
            /* any other chunks of state that requires special handling? */
         }

         next = attr->next;
         free(attr->data);
         free(attr);
         attr = next;
      }
   }
}


void
_mesa_init_attrib(struct gl_context *ctx)
{
   /* Renderer and client attribute stacks */
   ctx->AttribStackDepth = 0;
   ctx->ClientAttribStackDepth = 0;
}
