Path: blob/21.2-virgl/src/gallium/frontends/glx/xlib/xm_api.c
4561 views
/*1* Mesa 3-D graphics library2*3* Copyright (C) 1999-2007 Brian Paul All Rights Reserved.4*5* Permission is hereby granted, free of charge, to any person obtaining a6* copy of this software and associated documentation files (the "Software"),7* to deal in the Software without restriction, including without limitation8* the rights to use, copy, modify, merge, publish, distribute, sublicense,9* and/or sell copies of the Software, and to permit persons to whom the10* Software is furnished to do so, subject to the following conditions:11*12* The above copyright notice and this permission notice shall be included13* in all copies or substantial portions of the Software.14*15* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS16* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL18* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR19* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,20* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR21* OTHER DEALINGS IN THE SOFTWARE.22*/2324/**25* \file xm_api.c26*27* All the XMesa* API functions.28*29*30* NOTES:31*32* The window coordinate system origin (0,0) is in the lower-left corner33* of the window. X11's window coordinate origin is in the upper-left34* corner of the window. Therefore, most drawing functions in this35* file have to flip Y coordinates.36*37*38* Byte swapping: If the Mesa host and the X display use a different39* byte order then there's some trickiness to be aware of when using40* XImages. The byte ordering used for the XImage is that of the X41* display, not the Mesa host.42* The color-to-pixel encoding for True/DirectColor must be done43* according to the display's visual red_mask, green_mask, and blue_mask.44* If XPutPixel is used to put a pixel into an XImage then XPutPixel will45* do byte swapping if needed. If one wants to directly "poke" the pixel46* into the XImage's buffer then the pixel must be byte swapped first.47*48*/4950#ifdef __CYGWIN__51#undef WIN3252#undef __WIN32__53#endif5455#include <stdio.h>56#include "xm_api.h"57#include "xm_st.h"5859#include "pipe/p_context.h"60#include "pipe/p_defines.h"61#include "pipe/p_screen.h"62#include "pipe/p_state.h"63#include "frontend/api.h"6465#include "util/u_atomic.h"66#include "util/u_inlines.h"67#include "util/u_math.h"68#include "util/u_memory.h"6970#include "hud/hud_context.h"7172#include "main/errors.h"7374#include "xm_public.h"75#include <GL/glx.h>767778/* Driver interface routines, set up by xlib backend on library79* _init(). These are global in the same way that function names are80* global.81*/82static struct xm_driver driver;83static struct st_api *stapi;8485/* Default strict invalidate to false. This means we will not call86* XGetGeometry after every swapbuffers, which allows swapbuffers to87* remain asynchronous. For apps running at 100fps with synchronous88* swapping, a 10% boost is typical. For gears, I see closer to 20%89* speedup.90*91* Note that the work of copying data on swapbuffers doesn't disappear92* - this change just allows the X server to execute the PutImage93* asynchronously without us effectively blocked until its completion.94*95* This speeds up even llvmpipe's threaded rasterization as the96* swapbuffers operation was a large part of the serial component of97* an llvmpipe frame.98*99* The downside of this is correctness - applications which don't call100* glViewport on window resizes will get incorrect rendering. A101* better solution would be to have per-frame but asynchronous102* invalidation. Xcb almost looks as if it could provide this, but103* the API doesn't seem to quite be there.104*/105boolean xmesa_strict_invalidate = FALSE;106107void xmesa_set_driver( const struct xm_driver *templ )108{109driver = *templ;110stapi = driver.create_st_api();111112xmesa_strict_invalidate =113debug_get_bool_option("XMESA_STRICT_INVALIDATE", FALSE);114}115116117static int118xmesa_get_param(struct st_manager *smapi,119enum st_manager_param param)120{121switch(param) {122case ST_MANAGER_BROKEN_INVALIDATE:123return !xmesa_strict_invalidate;124default:125return 0;126}127}128129/* linked list of XMesaDisplay hooks per display */130typedef struct _XMesaExtDisplayInfo {131struct _XMesaExtDisplayInfo *next;132Display *display;133struct xmesa_display mesaDisplay;134} XMesaExtDisplayInfo;135136typedef struct _XMesaExtInfo {137XMesaExtDisplayInfo *head;138int ndisplays;139} XMesaExtInfo;140141static XMesaExtInfo MesaExtInfo;142143/* hook to delete XMesaDisplay on XDestroyDisplay */144extern void145xmesa_close_display(Display *display)146{147XMesaExtDisplayInfo *info, *prev;148149/* These assertions are not valid since screen creation can fail and result150* in an empty list151assert(MesaExtInfo.ndisplays > 0);152assert(MesaExtInfo.head);153*/154155_XLockMutex(_Xglobal_lock);156/* first find display */157prev = NULL;158for (info = MesaExtInfo.head; info; info = info->next) {159if (info->display == display) {160prev = info;161break;162}163}164165if (info == NULL) {166/* no display found */167_XUnlockMutex(_Xglobal_lock);168return;169}170171/* remove display entry from list */172if (prev != MesaExtInfo.head) {173prev->next = info->next;174} else {175MesaExtInfo.head = info->next;176}177MesaExtInfo.ndisplays--;178179_XUnlockMutex(_Xglobal_lock);180181/* don't forget to clean up mesaDisplay */182XMesaDisplay xmdpy = &info->mesaDisplay;183184/**185* XXX: Don't destroy the screens here, since there may still186* be some dangling screen pointers that are used after this point187* if (xmdpy->screen) {188* xmdpy->screen->destroy(xmdpy->screen);189* }190*/191192if (xmdpy->smapi->destroy)193xmdpy->smapi->destroy(xmdpy->smapi);194free(xmdpy->smapi);195196XFree((char *) info);197}198199static XMesaDisplay200xmesa_init_display( Display *display )201{202static mtx_t init_mutex = _MTX_INITIALIZER_NP;203XMesaDisplay xmdpy;204XMesaExtDisplayInfo *info;205206if (display == NULL) {207return NULL;208}209210mtx_lock(&init_mutex);211212/* Look for XMesaDisplay which corresponds to this display */213info = MesaExtInfo.head;214while(info) {215if (info->display == display) {216/* Found it */217mtx_unlock(&init_mutex);218return &info->mesaDisplay;219}220info = info->next;221}222223/* Not found. Create new XMesaDisplay */224/* first allocate X-related resources and hook destroy callback */225226/* allocate mesa display info */227info = (XMesaExtDisplayInfo *) Xmalloc(sizeof(XMesaExtDisplayInfo));228if (info == NULL) {229mtx_unlock(&init_mutex);230return NULL;231}232info->display = display;233234xmdpy = &info->mesaDisplay; /* to be filled out below */235xmdpy->display = display;236xmdpy->pipe = NULL;237238xmdpy->smapi = CALLOC_STRUCT(st_manager);239if (!xmdpy->smapi) {240Xfree(info);241mtx_unlock(&init_mutex);242return NULL;243}244245xmdpy->screen = driver.create_pipe_screen(display);246if (!xmdpy->screen) {247free(xmdpy->smapi);248Xfree(info);249mtx_unlock(&init_mutex);250return NULL;251}252253/* At this point, both smapi and screen are known to be valid */254xmdpy->smapi->screen = xmdpy->screen;255xmdpy->smapi->get_param = xmesa_get_param;256(void) mtx_init(&xmdpy->mutex, mtx_plain);257258/* chain to the list of displays */259_XLockMutex(_Xglobal_lock);260info->next = MesaExtInfo.head;261MesaExtInfo.head = info;262MesaExtInfo.ndisplays++;263_XUnlockMutex(_Xglobal_lock);264265mtx_unlock(&init_mutex);266267return xmdpy;268}269270271/**********************************************************************/272/***** X Utility Functions *****/273/**********************************************************************/274275276/**277* Return the host's byte order as LSBFirst or MSBFirst ala X.278*/279static int host_byte_order( void )280{281int i = 1;282char *cptr = (char *) &i;283return (*cptr==1) ? LSBFirst : MSBFirst;284}285286287288289/**290* Return the true number of bits per pixel for XImages.291* For example, if we request a 24-bit deep visual we may actually need/get292* 32bpp XImages. This function returns the appropriate bpp.293* Input: dpy - the X display294* visinfo - desribes the visual to be used for XImages295* Return: true number of bits per pixel for XImages296*/297static int298bits_per_pixel( XMesaVisual xmv )299{300Display *dpy = xmv->display;301XVisualInfo * visinfo = xmv->visinfo;302XImage *img;303int bitsPerPixel;304/* Create a temporary XImage */305img = XCreateImage( dpy, visinfo->visual, visinfo->depth,306ZPixmap, 0, /*format, offset*/307malloc(8), /*data*/3081, 1, /*width, height*/30932, /*bitmap_pad*/3100 /*bytes_per_line*/311);312assert(img);313/* grab the bits/pixel value */314bitsPerPixel = img->bits_per_pixel;315/* free the XImage */316free( img->data );317img->data = NULL;318XDestroyImage( img );319return bitsPerPixel;320}321322323324/*325* Determine if a given X window ID is valid (window exists).326* Do this by calling XGetWindowAttributes() for the window and327* checking if we catch an X error.328* Input: dpy - the display329* win - the window to check for existence330* Return: GL_TRUE - window exists331* GL_FALSE - window doesn't exist332*/333static GLboolean WindowExistsFlag;334335static int window_exists_err_handler( Display* dpy, XErrorEvent* xerr )336{337(void) dpy;338if (xerr->error_code == BadWindow) {339WindowExistsFlag = GL_FALSE;340}341return 0;342}343344static GLboolean window_exists( Display *dpy, Window win )345{346XWindowAttributes wa;347int (*old_handler)( Display*, XErrorEvent* );348WindowExistsFlag = GL_TRUE;349old_handler = XSetErrorHandler(window_exists_err_handler);350XGetWindowAttributes( dpy, win, &wa ); /* dummy request */351XSetErrorHandler(old_handler);352return WindowExistsFlag;353}354355static Status356get_drawable_size( Display *dpy, Drawable d, uint *width, uint *height )357{358Window root;359Status stat;360int xpos, ypos;361unsigned int w, h, bw, depth;362stat = XGetGeometry(dpy, d, &root, &xpos, &ypos, &w, &h, &bw, &depth);363*width = w;364*height = h;365return stat;366}367368369/**370* Return the size of the window (or pixmap) that corresponds to the371* given XMesaBuffer.372* \param width returns width in pixels373* \param height returns height in pixels374*/375void376xmesa_get_window_size(Display *dpy, XMesaBuffer b,377GLuint *width, GLuint *height)378{379XMesaDisplay xmdpy = xmesa_init_display(dpy);380Status stat;381382mtx_lock(&xmdpy->mutex);383stat = get_drawable_size(dpy, b->ws.drawable, width, height);384mtx_unlock(&xmdpy->mutex);385386if (!stat) {387/* probably querying a window that's recently been destroyed */388_mesa_warning(NULL, "XGetGeometry failed!\n");389*width = *height = 1;390}391}392393#define GET_REDMASK(__v) __v->mesa_visual.redMask394#define GET_GREENMASK(__v) __v->mesa_visual.greenMask395#define GET_BLUEMASK(__v) __v->mesa_visual.blueMask396397398/**399* Choose the pixel format for the given visual.400* This will tell the gallium driver how to pack pixel data into401* drawing surfaces.402*/403static GLuint404choose_pixel_format(XMesaVisual v)405{406boolean native_byte_order = (host_byte_order() ==407ImageByteOrder(v->display));408409if ( GET_REDMASK(v) == 0x0000ff410&& GET_GREENMASK(v) == 0x00ff00411&& GET_BLUEMASK(v) == 0xff0000412&& v->BitsPerPixel == 32) {413if (native_byte_order) {414/* no byteswapping needed */415return PIPE_FORMAT_RGBA8888_UNORM;416}417else {418return PIPE_FORMAT_ABGR8888_UNORM;419}420}421else if ( GET_REDMASK(v) == 0xff0000422&& GET_GREENMASK(v) == 0x00ff00423&& GET_BLUEMASK(v) == 0x0000ff424&& v->BitsPerPixel == 32) {425if (native_byte_order) {426/* no byteswapping needed */427return PIPE_FORMAT_BGRA8888_UNORM;428}429else {430return PIPE_FORMAT_ARGB8888_UNORM;431}432}433else if ( GET_REDMASK(v) == 0x0000ff00434&& GET_GREENMASK(v) == 0x00ff0000435&& GET_BLUEMASK(v) == 0xff000000436&& v->BitsPerPixel == 32) {437if (native_byte_order) {438/* no byteswapping needed */439return PIPE_FORMAT_ARGB8888_UNORM;440}441else {442return PIPE_FORMAT_BGRA8888_UNORM;443}444}445else if ( GET_REDMASK(v) == 0xf800446&& GET_GREENMASK(v) == 0x07e0447&& GET_BLUEMASK(v) == 0x001f448&& native_byte_order449&& v->BitsPerPixel == 16) {450/* 5-6-5 RGB */451return PIPE_FORMAT_B5G6R5_UNORM;452}453454return PIPE_FORMAT_NONE;455}456457458/**459* Choose a depth/stencil format that satisfies the given depth and460* stencil sizes.461*/462static enum pipe_format463choose_depth_stencil_format(XMesaDisplay xmdpy, int depth, int stencil,464int sample_count)465{466const enum pipe_texture_target target = PIPE_TEXTURE_2D;467const unsigned tex_usage = PIPE_BIND_DEPTH_STENCIL;468enum pipe_format formats[8], fmt;469int count, i;470471count = 0;472473if (depth <= 16 && stencil == 0) {474formats[count++] = PIPE_FORMAT_Z16_UNORM;475}476if (depth <= 24 && stencil == 0) {477formats[count++] = PIPE_FORMAT_X8Z24_UNORM;478formats[count++] = PIPE_FORMAT_Z24X8_UNORM;479}480if (depth <= 24 && stencil <= 8) {481formats[count++] = PIPE_FORMAT_S8_UINT_Z24_UNORM;482formats[count++] = PIPE_FORMAT_Z24_UNORM_S8_UINT;483}484if (depth <= 32 && stencil == 0) {485formats[count++] = PIPE_FORMAT_Z32_UNORM;486}487488fmt = PIPE_FORMAT_NONE;489for (i = 0; i < count; i++) {490if (xmdpy->screen->is_format_supported(xmdpy->screen, formats[i],491target, sample_count,492sample_count, tex_usage)) {493fmt = formats[i];494break;495}496}497498return fmt;499}500501502503/**********************************************************************/504/***** Linked list of XMesaBuffers *****/505/**********************************************************************/506507static XMesaBuffer XMesaBufferList = NULL;508509510/**511* Allocate a new XMesaBuffer object which corresponds to the given drawable.512* Note that XMesaBuffer is derived from struct gl_framebuffer.513* The new XMesaBuffer will not have any size (Width=Height=0).514*515* \param d the corresponding X drawable (window or pixmap)516* \param type either WINDOW, PIXMAP or PBUFFER, describing d517* \param vis the buffer's visual518* \param cmap the window's colormap, if known.519* \return new XMesaBuffer or NULL if any problem520*/521static XMesaBuffer522create_xmesa_buffer(Drawable d, BufferType type,523XMesaVisual vis, Colormap cmap)524{525XMesaDisplay xmdpy = xmesa_init_display(vis->display);526XMesaBuffer b;527528assert(type == WINDOW || type == PIXMAP || type == PBUFFER);529530if (!xmdpy)531return NULL;532533b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);534if (!b)535return NULL;536537b->ws.drawable = d;538b->ws.visual = vis->visinfo->visual;539b->ws.depth = vis->visinfo->depth;540541b->xm_visual = vis;542b->type = type;543b->cmap = cmap;544545get_drawable_size(vis->display, d, &b->width, &b->height);546547/*548* Create framebuffer, but we'll plug in our own renderbuffers below.549*/550b->stfb = xmesa_create_st_framebuffer(xmdpy, b);551552/* GLX_EXT_texture_from_pixmap */553b->TextureTarget = 0;554b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;555b->TextureMipmap = 0;556557/* insert buffer into linked list */558b->Next = XMesaBufferList;559XMesaBufferList = b;560561return b;562}563564565/**566* Find an XMesaBuffer by matching X display and colormap but NOT matching567* the notThis buffer.568*/569XMesaBuffer570xmesa_find_buffer(Display *dpy, Colormap cmap, XMesaBuffer notThis)571{572XMesaBuffer b;573for (b = XMesaBufferList; b; b = b->Next) {574if (b->xm_visual->display == dpy &&575b->cmap == cmap &&576b != notThis) {577return b;578}579}580return NULL;581}582583584/**585* Remove buffer from linked list, delete if no longer referenced.586*/587static void588xmesa_free_buffer(XMesaBuffer buffer)589{590XMesaBuffer prev = NULL, b;591592for (b = XMesaBufferList; b; b = b->Next) {593if (b == buffer) {594/* unlink buffer from list */595if (prev)596prev->Next = buffer->Next;597else598XMesaBufferList = buffer->Next;599600/* Since the X window for the XMesaBuffer is going away, we don't601* want to dereference this pointer in the future.602*/603b->ws.drawable = 0;604605/* Notify the st manager that the associated framebuffer interface606* object is no longer valid.607*/608stapi->destroy_drawable(stapi, buffer->stfb);609610/* XXX we should move the buffer to a delete-pending list and destroy611* the buffer until it is no longer current.612*/613xmesa_destroy_st_framebuffer(buffer->stfb);614615free(buffer);616617return;618}619/* continue search */620prev = b;621}622/* buffer not found in XMesaBufferList */623_mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");624}625626627628/**********************************************************************/629/***** Misc Private Functions *****/630/**********************************************************************/631632633/**634* When a context is bound for the first time, we can finally finish635* initializing the context's visual and buffer information.636* \param v the XMesaVisual to initialize637* \param b the XMesaBuffer to initialize (may be NULL)638* \param window the window/pixmap we're rendering into639* \param cmap the colormap associated with the window/pixmap640* \return GL_TRUE=success, GL_FALSE=failure641*/642static GLboolean643initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,644Drawable window, Colormap cmap)645{646assert(!b || b->xm_visual == v);647648/* Save true bits/pixel */649v->BitsPerPixel = bits_per_pixel(v);650assert(v->BitsPerPixel > 0);651652/* RGB WINDOW:653* We support RGB rendering into almost any kind of visual.654*/655const int xclass = v->visualType;656if (xclass != GLX_TRUE_COLOR && xclass != GLX_DIRECT_COLOR) {657_mesa_warning(NULL,658"XMesa: RGB mode rendering not supported in given visual.\n");659return GL_FALSE;660}661662if (v->BitsPerPixel == 32) {663/* We use XImages for all front/back buffers. If an X Window or664* X Pixmap is 32bpp, there's no guarantee that the alpha channel665* will be preserved. For XImages we're in luck.666*/667v->mesa_visual.alphaBits = 8;668}669670/*671* If MESA_INFO env var is set print out some debugging info672* which can help Brian figure out what's going on when a user673* reports bugs.674*/675if (getenv("MESA_INFO")) {676printf("X/Mesa visual = %p\n", (void *) v);677printf("X/Mesa depth = %d\n", v->visinfo->depth);678printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);679}680681return GL_TRUE;682}683684685686#define NUM_VISUAL_TYPES 6687688/**689* Convert an X visual type to a GLX visual type.690*691* \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)692* to be converted.693* \return If \c visualType is a valid X visual type, a GLX visual type will694* be returned. Otherwise \c GLX_NONE will be returned.695*696* \note697* This code was lifted directly from lib/GL/glx/glcontextmodes.c in the698* DRI CVS tree.699*/700static GLint701xmesa_convert_from_x_visual_type( int visualType )702{703static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {704GLX_STATIC_GRAY, GLX_GRAY_SCALE,705GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,706GLX_TRUE_COLOR, GLX_DIRECT_COLOR707};708709return ( (unsigned) visualType < NUM_VISUAL_TYPES )710? glx_visual_types[ visualType ] : GLX_NONE;711}712713714/**********************************************************************/715/***** Public Functions *****/716/**********************************************************************/717718719/*720* Create a new X/Mesa visual.721* Input: display - X11 display722* visinfo - an XVisualInfo pointer723* rgb_flag - GL_TRUE = RGB mode,724* GL_FALSE = color index mode725* alpha_flag - alpha buffer requested?726* db_flag - GL_TRUE = double-buffered,727* GL_FALSE = single buffered728* stereo_flag - stereo visual?729* ximage_flag - GL_TRUE = use an XImage for back buffer,730* GL_FALSE = use an off-screen pixmap for back buffer731* depth_size - requested bits/depth values, or zero732* stencil_size - requested bits/stencil values, or zero733* accum_red_size - requested bits/red accum values, or zero734* accum_green_size - requested bits/green accum values, or zero735* accum_blue_size - requested bits/blue accum values, or zero736* accum_alpha_size - requested bits/alpha accum values, or zero737* num_samples - number of samples/pixel if multisampling, or zero738* level - visual level, usually 0739* visualCaveat - ala the GLX extension, usually GLX_NONE740* Return; a new XMesaVisual or 0 if error.741*/742PUBLIC743XMesaVisual XMesaCreateVisual( Display *display,744XVisualInfo * visinfo,745GLboolean rgb_flag,746GLboolean alpha_flag,747GLboolean db_flag,748GLboolean stereo_flag,749GLboolean ximage_flag,750GLint depth_size,751GLint stencil_size,752GLint accum_red_size,753GLint accum_green_size,754GLint accum_blue_size,755GLint accum_alpha_size,756GLint num_samples,757GLint level,758GLint visualCaveat )759{760XMesaDisplay xmdpy = xmesa_init_display(display);761XMesaVisual v;762GLint red_bits, green_bits, blue_bits, alpha_bits;763764if (!xmdpy)765return NULL;766767if (!rgb_flag)768return NULL;769770/* For debugging only */771if (getenv("MESA_XSYNC")) {772/* This makes debugging X easier.773* In your debugger, set a breakpoint on _XError to stop when an774* X protocol error is generated.775*/776XSynchronize( display, 1 );777}778779v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);780if (!v) {781return NULL;782}783784v->display = display;785786/* Save a copy of the XVisualInfo struct because the user may Xfree()787* the struct but we may need some of the information contained in it788* at a later time.789*/790v->visinfo = malloc(sizeof(*visinfo));791if (!v->visinfo) {792free(v);793return NULL;794}795memcpy(v->visinfo, visinfo, sizeof(*visinfo));796797v->ximage_flag = ximage_flag;798799v->mesa_visual.redMask = visinfo->red_mask;800v->mesa_visual.greenMask = visinfo->green_mask;801v->mesa_visual.blueMask = visinfo->blue_mask;802v->visualID = visinfo->visualid;803v->screen = visinfo->screen;804805#if !(defined(__cplusplus) || defined(c_plusplus))806v->visualType = xmesa_convert_from_x_visual_type(visinfo->class);807#else808v->visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);809#endif810811if (alpha_flag)812v->mesa_visual.alphaBits = 8;813814(void) initialize_visual_and_buffer( v, NULL, 0, 0 );815816{817const int xclass = v->visualType;818if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {819red_bits = util_bitcount(GET_REDMASK(v));820green_bits = util_bitcount(GET_GREENMASK(v));821blue_bits = util_bitcount(GET_BLUEMASK(v));822}823else {824/* this is an approximation */825int depth;826depth = v->visinfo->depth;827red_bits = depth / 3;828depth -= red_bits;829green_bits = depth / 2;830depth -= green_bits;831blue_bits = depth;832alpha_bits = 0;833assert( red_bits + green_bits + blue_bits == v->visinfo->depth );834}835alpha_bits = v->mesa_visual.alphaBits;836}837838/* initialize visual */839{840struct gl_config *vis = &v->mesa_visual;841842vis->doubleBufferMode = db_flag;843vis->stereoMode = stereo_flag;844845vis->redBits = red_bits;846vis->greenBits = green_bits;847vis->blueBits = blue_bits;848vis->alphaBits = alpha_bits;849vis->rgbBits = red_bits + green_bits + blue_bits;850851vis->depthBits = depth_size;852vis->stencilBits = stencil_size;853854vis->accumRedBits = accum_red_size;855vis->accumGreenBits = accum_green_size;856vis->accumBlueBits = accum_blue_size;857vis->accumAlphaBits = accum_alpha_size;858859vis->samples = num_samples;860}861862v->stvis.buffer_mask = ST_ATTACHMENT_FRONT_LEFT_MASK;863if (db_flag)864v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_LEFT_MASK;865if (stereo_flag) {866v->stvis.buffer_mask |= ST_ATTACHMENT_FRONT_RIGHT_MASK;867if (db_flag)868v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_RIGHT_MASK;869}870871v->stvis.color_format = choose_pixel_format(v);872873/* Check format support at requested num_samples (for multisample) */874if (!xmdpy->screen->is_format_supported(xmdpy->screen,875v->stvis.color_format,876PIPE_TEXTURE_2D, num_samples,877num_samples,878PIPE_BIND_RENDER_TARGET))879v->stvis.color_format = PIPE_FORMAT_NONE;880881if (v->stvis.color_format == PIPE_FORMAT_NONE) {882free(v->visinfo);883free(v);884return NULL;885}886887v->stvis.depth_stencil_format =888choose_depth_stencil_format(xmdpy, depth_size, stencil_size,889num_samples);890891v->stvis.accum_format = (accum_red_size +892accum_green_size + accum_blue_size + accum_alpha_size) ?893PIPE_FORMAT_R16G16B16A16_SNORM : PIPE_FORMAT_NONE;894895v->stvis.samples = num_samples;896897return v;898}899900901PUBLIC902void XMesaDestroyVisual( XMesaVisual v )903{904free(v->visinfo);905free(v);906}907908909/**910* Return the informative name.911*/912const char *913xmesa_get_name(void)914{915return stapi->name;916}917918919/**920* Do per-display initializations.921*/922int923xmesa_init( Display *display )924{925return xmesa_init_display(display) ? 0 : 1;926}927928929/**930* Create a new XMesaContext.931* \param v the XMesaVisual932* \param share_list another XMesaContext with which to share display933* lists or NULL if no sharing is wanted.934* \return an XMesaContext or NULL if error.935*/936PUBLIC937XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list,938GLuint major, GLuint minor,939GLuint profileMask, GLuint contextFlags)940{941XMesaDisplay xmdpy = xmesa_init_display(v->display);942struct st_context_attribs attribs;943enum st_context_error ctx_err = 0;944XMesaContext c;945946if (!xmdpy)947goto no_xmesa_context;948949/* Note: the XMesaContext contains a Mesa struct gl_context struct (inheritance) */950c = (XMesaContext) CALLOC_STRUCT(xmesa_context);951if (!c)952goto no_xmesa_context;953954c->xm_visual = v;955c->xm_buffer = NULL; /* set later by XMesaMakeCurrent */956c->xm_read_buffer = NULL;957958memset(&attribs, 0, sizeof(attribs));959attribs.visual = v->stvis;960attribs.major = major;961attribs.minor = minor;962if (contextFlags & GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)963attribs.flags |= ST_CONTEXT_FLAG_FORWARD_COMPATIBLE;964if (contextFlags & GLX_CONTEXT_DEBUG_BIT_ARB)965attribs.flags |= ST_CONTEXT_FLAG_DEBUG;966if (contextFlags & GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB)967attribs.flags |= ST_CONTEXT_FLAG_ROBUST_ACCESS;968969switch (profileMask) {970case GLX_CONTEXT_CORE_PROFILE_BIT_ARB:971/* There are no profiles before OpenGL 3.2. The972* GLX_ARB_create_context_profile spec says:973*974* "If the requested OpenGL version is less than 3.2,975* GLX_CONTEXT_PROFILE_MASK_ARB is ignored and the functionality976* of the context is determined solely by the requested version."977*/978if (major > 3 || (major == 3 && minor >= 2)) {979attribs.profile = ST_PROFILE_OPENGL_CORE;980break;981}982FALLTHROUGH;983case GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB:984/*985* The spec also says:986*987* "If version 3.1 is requested, the context returned may implement988* any of the following versions:989*990* * Version 3.1. The GL_ARB_compatibility extension may or may not991* be implemented, as determined by the implementation.992* * The core profile of version 3.2 or greater."993*994* and because Mesa doesn't support GL_ARB_compatibility, the only chance to995* honour a 3.1 context is through core profile.996*/997if (major == 3 && minor == 1) {998attribs.profile = ST_PROFILE_OPENGL_CORE;999} else {1000attribs.profile = ST_PROFILE_DEFAULT;1001}1002break;1003case GLX_CONTEXT_ES_PROFILE_BIT_EXT:1004if (major >= 2) {1005attribs.profile = ST_PROFILE_OPENGL_ES2;1006} else {1007attribs.profile = ST_PROFILE_OPENGL_ES1;1008}1009break;1010default:1011assert(0);1012goto no_st;1013}10141015c->st = stapi->create_context(stapi, xmdpy->smapi, &attribs,1016&ctx_err, (share_list) ? share_list->st : NULL);1017if (c->st == NULL)1018goto no_st;10191020c->st->st_manager_private = (void *) c;10211022c->hud = hud_create(c->st->cso_context, c->st, NULL);10231024return c;10251026no_st:1027free(c);1028no_xmesa_context:1029return NULL;1030}1031103210331034PUBLIC1035void XMesaDestroyContext( XMesaContext c )1036{1037if (c->hud) {1038hud_destroy(c->hud, NULL);1039}10401041c->st->destroy(c->st);10421043/* FIXME: We should destroy the screen here, but if we do so, surfaces may1044* outlive it, causing segfaults1045struct pipe_screen *screen = c->st->pipe->screen;1046screen->destroy(screen);1047*/10481049free(c);1050}1051105210531054/**1055* Private function for creating an XMesaBuffer which corresponds to an1056* X window or pixmap.1057* \param v the window's XMesaVisual1058* \param w the window we're wrapping1059* \return new XMesaBuffer or NULL if error1060*/1061PUBLIC XMesaBuffer1062XMesaCreateWindowBuffer(XMesaVisual v, Window w)1063{1064XWindowAttributes attr;1065XMesaBuffer b;1066Colormap cmap;1067int depth;10681069assert(v);1070assert(w);10711072/* Check that window depth matches visual depth */1073XGetWindowAttributes( v->display, w, &attr );1074depth = attr.depth;1075if (v->visinfo->depth != depth) {1076_mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",1077v->visinfo->depth, depth);1078return NULL;1079}10801081/* Find colormap */1082if (attr.colormap) {1083cmap = attr.colormap;1084}1085else {1086_mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);1087/* this is weird, a window w/out a colormap!? */1088/* OK, let's just allocate a new one and hope for the best */1089cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);1090}10911092b = create_xmesa_buffer((Drawable) w, WINDOW, v, cmap);1093if (!b)1094return NULL;10951096if (!initialize_visual_and_buffer( v, b, (Drawable) w, cmap )) {1097xmesa_free_buffer(b);1098return NULL;1099}11001101return b;1102}1103110411051106/**1107* Create a new XMesaBuffer from an X pixmap.1108*1109* \param v the XMesaVisual1110* \param p the pixmap1111* \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or1112* \c GLX_DIRECT_COLOR visual for the pixmap1113* \returns new XMesaBuffer or NULL if error1114*/1115PUBLIC XMesaBuffer1116XMesaCreatePixmapBuffer(XMesaVisual v, Pixmap p, Colormap cmap)1117{1118XMesaBuffer b;11191120assert(v);11211122b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);1123if (!b)1124return NULL;11251126if (!initialize_visual_and_buffer(v, b, (Drawable) p, cmap)) {1127xmesa_free_buffer(b);1128return NULL;1129}11301131return b;1132}113311341135/**1136* For GLX_EXT_texture_from_pixmap1137*/1138XMesaBuffer1139XMesaCreatePixmapTextureBuffer(XMesaVisual v, Pixmap p,1140Colormap cmap,1141int format, int target, int mipmap)1142{1143GET_CURRENT_CONTEXT(ctx);1144XMesaBuffer b;11451146assert(v);11471148b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);1149if (!b)1150return NULL;11511152/* get pixmap size */1153xmesa_get_window_size(v->display, b, &b->width, &b->height);11541155if (target == 0) {1156/* examine dims */1157if (ctx->Extensions.ARB_texture_non_power_of_two) {1158target = GLX_TEXTURE_2D_EXT;1159}1160else if ( util_bitcount(b->width) == 11161&& util_bitcount(b->height) == 1) {1162/* power of two size */1163if (b->height == 1) {1164target = GLX_TEXTURE_1D_EXT;1165}1166else {1167target = GLX_TEXTURE_2D_EXT;1168}1169}1170else if (ctx->Extensions.NV_texture_rectangle) {1171target = GLX_TEXTURE_RECTANGLE_EXT;1172}1173else {1174/* non power of two textures not supported */1175XMesaDestroyBuffer(b);1176return 0;1177}1178}11791180b->TextureTarget = target;1181b->TextureFormat = format;1182b->TextureMipmap = mipmap;11831184if (!initialize_visual_and_buffer(v, b, (Drawable) p, cmap)) {1185xmesa_free_buffer(b);1186return NULL;1187}11881189return b;1190}1191119211931194XMesaBuffer1195XMesaCreatePBuffer(XMesaVisual v, Colormap cmap,1196unsigned int width, unsigned int height)1197{1198Window root;1199Drawable drawable; /* X Pixmap Drawable */1200XMesaBuffer b;12011202/* allocate pixmap for front buffer */1203root = RootWindow( v->display, v->visinfo->screen );1204drawable = XCreatePixmap(v->display, root, width, height,1205v->visinfo->depth);1206if (!drawable)1207return NULL;12081209b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);1210if (!b)1211return NULL;12121213if (!initialize_visual_and_buffer(v, b, drawable, cmap)) {1214xmesa_free_buffer(b);1215return NULL;1216}12171218return b;1219}1220122112221223/*1224* Deallocate an XMesaBuffer structure and all related info.1225*/1226PUBLIC void1227XMesaDestroyBuffer(XMesaBuffer b)1228{1229xmesa_free_buffer(b);1230}123112321233/**1234* Notify the binding context to validate the buffer.1235*/1236void1237xmesa_notify_invalid_buffer(XMesaBuffer b)1238{1239p_atomic_inc(&b->stfb->stamp);1240}124112421243/**1244* Query the current drawable size and notify the binding context.1245*/1246void1247xmesa_check_buffer_size(XMesaBuffer b)1248{1249GLuint old_width, old_height;12501251if (!b)1252return;12531254if (b->type == PBUFFER)1255return;12561257old_width = b->width;1258old_height = b->height;12591260xmesa_get_window_size(b->xm_visual->display, b, &b->width, &b->height);12611262if (b->width != old_width || b->height != old_height)1263xmesa_notify_invalid_buffer(b);1264}126512661267/*1268* Bind buffer b to context c and make c the current rendering context.1269*/1270PUBLIC1271GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,1272XMesaBuffer readBuffer )1273{1274XMesaContext old_ctx = XMesaGetCurrentContext();12751276if (old_ctx && old_ctx != c) {1277XMesaFlush(old_ctx);1278old_ctx->xm_buffer = NULL;1279old_ctx->xm_read_buffer = NULL;1280}12811282if (c) {1283if (!drawBuffer != !readBuffer) {1284return GL_FALSE; /* must specify zero or two buffers! */1285}12861287if (c == old_ctx &&1288c->xm_buffer == drawBuffer &&1289c->xm_read_buffer == readBuffer)1290return GL_TRUE;12911292xmesa_check_buffer_size(drawBuffer);1293if (readBuffer != drawBuffer)1294xmesa_check_buffer_size(readBuffer);12951296c->xm_buffer = drawBuffer;1297c->xm_read_buffer = readBuffer;12981299stapi->make_current(stapi, c->st,1300drawBuffer ? drawBuffer->stfb : NULL,1301readBuffer ? readBuffer->stfb : NULL);13021303/* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */1304if (drawBuffer)1305drawBuffer->wasCurrent = GL_TRUE;1306}1307else {1308/* Detach */1309stapi->make_current(stapi, NULL, NULL, NULL);13101311}1312return GL_TRUE;1313}131413151316/*1317* Unbind the context c from its buffer.1318*/1319GLboolean XMesaUnbindContext( XMesaContext c )1320{1321/* A no-op for XFree86 integration purposes */1322return GL_TRUE;1323}132413251326XMesaContext XMesaGetCurrentContext( void )1327{1328struct st_context_iface *st = stapi->get_current(stapi);1329return (XMesaContext) (st) ? st->st_manager_private : NULL;1330}1331133213331334/**1335* Swap front and back color buffers and have winsys display front buffer.1336* If there's no front color buffer no swap actually occurs.1337*/1338PUBLIC1339void XMesaSwapBuffers( XMesaBuffer b )1340{1341XMesaContext xmctx = XMesaGetCurrentContext();13421343/* Need to draw HUD before flushing */1344if (xmctx && xmctx->hud) {1345struct pipe_resource *back =1346xmesa_get_framebuffer_resource(b->stfb, ST_ATTACHMENT_BACK_LEFT);1347hud_run(xmctx->hud, NULL, back);1348}13491350if (xmctx && xmctx->xm_buffer == b) {1351xmctx->st->flush( xmctx->st, ST_FLUSH_FRONT, NULL, NULL, NULL);1352}13531354xmesa_swap_st_framebuffer(b->stfb);1355}1356135713581359/*1360* Copy sub-region of back buffer to front buffer1361*/1362void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )1363{1364XMesaContext xmctx = XMesaGetCurrentContext();13651366xmctx->st->flush( xmctx->st, ST_FLUSH_FRONT, NULL, NULL, NULL);13671368xmesa_copy_st_framebuffer(b->stfb,1369ST_ATTACHMENT_BACK_LEFT, ST_ATTACHMENT_FRONT_LEFT,1370x, b->height - y - height, width, height);1371}1372137313741375void XMesaFlush( XMesaContext c )1376{1377if (c && c->xm_visual->display) {1378XMesaDisplay xmdpy = xmesa_init_display(c->xm_visual->display);1379struct pipe_fence_handle *fence = NULL;13801381c->st->flush(c->st, ST_FLUSH_FRONT, &fence, NULL, NULL);1382if (fence) {1383xmdpy->screen->fence_finish(xmdpy->screen, NULL, fence,1384PIPE_TIMEOUT_INFINITE);1385xmdpy->screen->fence_reference(xmdpy->screen, &fence, NULL);1386}1387XFlush( c->xm_visual->display );1388}1389}139013911392139313941395XMesaBuffer XMesaFindBuffer( Display *dpy, Drawable d )1396{1397XMesaBuffer b;1398for (b = XMesaBufferList; b; b = b->Next) {1399if (b->ws.drawable == d && b->xm_visual->display == dpy) {1400return b;1401}1402}1403return NULL;1404}140514061407/**1408* Free/destroy all XMesaBuffers associated with given display.1409*/1410void xmesa_destroy_buffers_on_display(Display *dpy)1411{1412XMesaBuffer b, next;1413for (b = XMesaBufferList; b; b = next) {1414next = b->Next;1415if (b->xm_visual->display == dpy) {1416xmesa_free_buffer(b);1417/* delete head of list? */1418if (XMesaBufferList == b) {1419XMesaBufferList = next;1420}1421}1422}1423}142414251426/*1427* Look for XMesaBuffers whose X window has been destroyed.1428* Deallocate any such XMesaBuffers.1429*/1430void XMesaGarbageCollect( void )1431{1432XMesaBuffer b, next;1433for (b=XMesaBufferList; b; b=next) {1434next = b->Next;1435if (b->xm_visual &&1436b->xm_visual->display &&1437b->ws.drawable &&1438b->type == WINDOW) {1439XSync(b->xm_visual->display, False);1440if (!window_exists( b->xm_visual->display, b->ws.drawable )) {1441/* found a dead window, free the ancillary info */1442XMesaDestroyBuffer( b );1443}1444}1445}1446}144714481449static enum st_attachment_type xmesa_attachment_type(int glx_attachment)1450{1451switch(glx_attachment) {1452case GLX_FRONT_LEFT_EXT:1453return ST_ATTACHMENT_FRONT_LEFT;1454case GLX_FRONT_RIGHT_EXT:1455return ST_ATTACHMENT_FRONT_RIGHT;1456case GLX_BACK_LEFT_EXT:1457return ST_ATTACHMENT_BACK_LEFT;1458case GLX_BACK_RIGHT_EXT:1459return ST_ATTACHMENT_BACK_RIGHT;1460default:1461assert(0);1462return ST_ATTACHMENT_FRONT_LEFT;1463}1464}146514661467PUBLIC void1468XMesaBindTexImage(Display *dpy, XMesaBuffer drawable, int buffer,1469const int *attrib_list)1470{1471struct st_context_iface *st = stapi->get_current(stapi);1472struct st_framebuffer_iface* stfbi = drawable->stfb;1473struct pipe_resource *res;1474int x, y, w, h;1475enum st_attachment_type st_attachment = xmesa_attachment_type(buffer);14761477x = 0;1478y = 0;1479w = drawable->width;1480h = drawable->height;14811482/* We need to validate our attachments before using them,1483* in case the texture doesn't exist yet. */1484xmesa_st_framebuffer_validate_textures(stfbi, w, h, 1 << st_attachment);1485res = xmesa_get_attachment(stfbi, st_attachment);14861487if (res) {1488struct pipe_context* pipe = xmesa_get_context(stfbi);1489enum pipe_format internal_format = res->format;1490struct pipe_transfer *tex_xfer;1491char *map;1492int line, byte_width;1493XImage *img;14941495internal_format = choose_pixel_format(drawable->xm_visual);14961497map = pipe_texture_map(pipe, res,14980, 0, /* level, layer */1499PIPE_MAP_WRITE,1500x, y,1501w, h, &tex_xfer);1502if (!map)1503return;15041505/* Grab the XImage that we want to turn into a texture. */1506img = XGetImage(dpy,1507drawable->ws.drawable,1508x, y,1509w, h,1510AllPlanes,1511ZPixmap);15121513if (!img) {1514pipe_texture_unmap(pipe, tex_xfer);1515return;1516}15171518/* The pipe transfer has a pitch rounded up to the nearest 64 pixels. */1519byte_width = w * ((img->bits_per_pixel + 7) / 8);15201521for (line = 0; line < h; line++)1522memcpy(&map[line * tex_xfer->stride],1523&img->data[line * img->bytes_per_line],1524byte_width);15251526pipe_texture_unmap(pipe, tex_xfer);15271528st->teximage(st,1529ST_TEXTURE_2D,15300, /* level */1531internal_format,1532res,1533FALSE /* no mipmap */);15341535}1536}1537153815391540PUBLIC void1541XMesaReleaseTexImage(Display *dpy, XMesaBuffer drawable, int buffer)1542{1543}154415451546void1547XMesaCopyContext(XMesaContext src, XMesaContext dst, unsigned long mask)1548{1549if (dst->st->copy)1550dst->st->copy(dst->st, src->st, mask);1551}155215531554