code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL_video.h" #include "SDL_blit.h" #include "SDL_blit_slow.h" /* The ONE TRUE BLITTER * This puppy has to handle all the unoptimized cases - yes, it's slow. */ void SDL_Blit_Slow(SDL_BlitInfo * info) { const int flags = info->flags; const Uint32 modulateR = info->r; const Uint32 modulateG = info->g; const Uint32 modulateB = info->b; const Uint32 modulateA = info->a; Uint32 srcpixel; Uint32 srcR, srcG, srcB, srcA; Uint32 dstpixel; Uint32 dstR, dstG, dstB, dstA; int srcy, srcx; int posy, posx; int incy, incx; SDL_PixelFormat *src_fmt = info->src_fmt; SDL_PixelFormat *dst_fmt = info->dst_fmt; int srcbpp = src_fmt->BytesPerPixel; int dstbpp = dst_fmt->BytesPerPixel; Uint32 rgbmask = ~src_fmt->Amask; Uint32 ckey = info->colorkey & rgbmask; srcy = 0; posy = 0; incy = (info->src_h << 16) / info->dst_h; incx = (info->src_w << 16) / info->dst_w; while (info->dst_h--) { Uint8 *src = 0; Uint8 *dst = info->dst; int n = info->dst_w; srcx = -1; posx = 0x10000L; while (posy >= 0x10000L) { ++srcy; posy -= 0x10000L; } while (n--) { if (posx >= 0x10000L) { while (posx >= 0x10000L) { ++srcx; posx -= 0x10000L; } src = (info->src + (srcy * info->src_pitch) + (srcx * srcbpp)); } if (src_fmt->Amask) { DISEMBLE_RGBA(src, srcbpp, src_fmt, srcpixel, srcR, srcG, srcB, srcA); } else { DISEMBLE_RGB(src, srcbpp, src_fmt, srcpixel, srcR, srcG, srcB); srcA = 0xFF; } if (flags & SDL_COPY_COLORKEY) { /* srcpixel isn't set for 24 bpp */ if (srcbpp == 3) { srcpixel = (srcR << src_fmt->Rshift) | (srcG << src_fmt->Gshift) | (srcB << src_fmt->Bshift); } if ((srcpixel & rgbmask) == ckey) { posx += incx; dst += dstbpp; continue; } } if (dst_fmt->Amask) { DISEMBLE_RGBA(dst, dstbpp, dst_fmt, dstpixel, dstR, dstG, dstB, dstA); } else { DISEMBLE_RGB(dst, dstbpp, dst_fmt, dstpixel, dstR, dstG, dstB); dstA = 0xFF; } if (flags & SDL_COPY_MODULATE_COLOR) { srcR = (srcR * modulateR) / 255; srcG = (srcG * modulateG) / 255; srcB = (srcB * modulateB) / 255; } if (flags & SDL_COPY_MODULATE_ALPHA) { srcA = (srcA * modulateA) / 255; } if (flags & (SDL_COPY_BLEND | SDL_COPY_ADD)) { /* This goes away if we ever use premultiplied alpha */ if (srcA < 255) { srcR = (srcR * srcA) / 255; srcG = (srcG * srcA) / 255; srcB = (srcB * srcA) / 255; } } switch (flags & (SDL_COPY_BLEND | SDL_COPY_ADD | SDL_COPY_MOD | SDL_COPY_MUL)) { case 0: dstR = srcR; dstG = srcG; dstB = srcB; dstA = srcA; break; case SDL_COPY_BLEND: dstR = srcR + ((255 - srcA) * dstR) / 255; dstG = srcG + ((255 - srcA) * dstG) / 255; dstB = srcB + ((255 - srcA) * dstB) / 255; dstA = srcA + ((255 - srcA) * dstA) / 255; break; case SDL_COPY_ADD: dstR = srcR + dstR; if (dstR > 255) dstR = 255; dstG = srcG + dstG; if (dstG > 255) dstG = 255; dstB = srcB + dstB; if (dstB > 255) dstB = 255; break; case SDL_COPY_MOD: dstR = (srcR * dstR) / 255; dstG = (srcG * dstG) / 255; dstB = (srcB * dstB) / 255; break; case SDL_COPY_MUL: dstR = ((srcR * dstR) + (dstR * (255 - srcA))) / 255; if (dstR > 255) dstR = 255; dstG = ((srcG * dstG) + (dstG * (255 - srcA))) / 255; if (dstG > 255) dstG = 255; dstB = ((srcB * dstB) + (dstB * (255 - srcA))) / 255; if (dstB > 255) dstB = 255; dstA = ((srcA * dstA) + (dstA * (255 - srcA))) / 255; if (dstA > 255) dstA = 255; break; } if (dst_fmt->Amask) { ASSEMBLE_RGBA(dst, dstbpp, dst_fmt, dstR, dstG, dstB, dstA); } else { ASSEMBLE_RGB(dst, dstbpp, dst_fmt, dstR, dstG, dstB); } posx += incx; dst += dstbpp; } posy += incy; info->dst += info->dst_pitch; } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_blit_slow.c
C
apache-2.0
6,330
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_blit_slow_h_ #define SDL_blit_slow_h_ #include "../SDL_internal.h" extern void SDL_Blit_Slow(SDL_BlitInfo * info); #endif /* SDL_blit_slow_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_blit_slow.h
C
apache-2.0
1,136
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* Code to load and save surfaces in Windows BMP format. Why support BMP format? Well, it's a native format for Windows, and most image processing programs can read and write it. It would be nice to be able to have at least one image format that we can natively load and save, and since PNG is so complex that it would bloat the library, BMP is a good alternative. This code currently supports Win32 DIBs in uncompressed 8 and 24 bpp. */ #include "SDL_hints.h" #include "SDL_video.h" #include "SDL_assert.h" #include "SDL_endian.h" #include "SDL_pixels_c.h" #define SAVE_32BIT_BMP /* Compression encodings for BMP files */ #ifndef BI_RGB #define BI_RGB 0 #define BI_RLE8 1 #define BI_RLE4 2 #define BI_BITFIELDS 3 #endif /* Logical color space values for BMP files */ #ifndef LCS_WINDOWS_COLOR_SPACE /* 0x57696E20 == "Win " */ #define LCS_WINDOWS_COLOR_SPACE 0x57696E20 #endif static int readRlePixels(SDL_Surface * surface, SDL_RWops * src, int isRle8) { /* | Sets the surface pixels from src. A bmp image is upside down. */ int pitch = surface->pitch; int height = surface->h; Uint8 *start = (Uint8 *)surface->pixels; Uint8 *end = start + (height*pitch); Uint8 *bits = end-pitch, *spot; int ofs = 0; Uint8 ch; Uint8 needsPad; #define COPY_PIXEL(x) spot = &bits[ofs++]; if(spot >= start && spot < end) *spot = (x) for (;;) { if (!SDL_RWread(src, &ch, 1, 1)) return 1; /* | encoded mode starts with a run length, and then a byte | with two colour indexes to alternate between for the run */ if (ch) { Uint8 pixel; if (!SDL_RWread(src, &pixel, 1, 1)) return 1; if (isRle8) { /* 256-color bitmap, compressed */ do { COPY_PIXEL(pixel); } while (--ch); } else { /* 16-color bitmap, compressed */ Uint8 pixel0 = pixel >> 4; Uint8 pixel1 = pixel & 0x0F; for (;;) { COPY_PIXEL(pixel0); /* even count, high nibble */ if (!--ch) break; COPY_PIXEL(pixel1); /* odd count, low nibble */ if (!--ch) break; } } } else { /* | A leading zero is an escape; it may signal the end of the bitmap, | a cursor move, or some absolute data. | zero tag may be absolute mode or an escape */ if (!SDL_RWread(src, &ch, 1, 1)) return 1; switch (ch) { case 0: /* end of line */ ofs = 0; bits -= pitch; /* go to previous */ break; case 1: /* end of bitmap */ return 0; /* success! */ case 2: /* delta */ if (!SDL_RWread(src, &ch, 1, 1)) return 1; ofs += ch; if (!SDL_RWread(src, &ch, 1, 1)) return 1; bits -= (ch * pitch); break; default: /* no compression */ if (isRle8) { needsPad = (ch & 1); do { Uint8 pixel; if (!SDL_RWread(src, &pixel, 1, 1)) return 1; COPY_PIXEL(pixel); } while (--ch); } else { needsPad = (((ch+1)>>1) & 1); /* (ch+1)>>1: bytes size */ for (;;) { Uint8 pixel; if (!SDL_RWread(src, &pixel, 1, 1)) return 1; COPY_PIXEL(pixel >> 4); if (!--ch) break; COPY_PIXEL(pixel & 0x0F); if (!--ch) break; } } /* pad at even boundary */ if (needsPad && !SDL_RWread(src, &ch, 1, 1)) return 1; break; } } } } static void CorrectAlphaChannel(SDL_Surface *surface) { /* Check to see if there is any alpha channel data */ SDL_bool hasAlpha = SDL_FALSE; #if SDL_BYTEORDER == SDL_BIG_ENDIAN int alphaChannelOffset = 0; #else int alphaChannelOffset = 3; #endif Uint8 *alpha = ((Uint8*)surface->pixels) + alphaChannelOffset; Uint8 *end = alpha + surface->h * surface->pitch; while (alpha < end) { if (*alpha != 0) { hasAlpha = SDL_TRUE; break; } alpha += 4; } if (!hasAlpha) { alpha = ((Uint8*)surface->pixels) + alphaChannelOffset; while (alpha < end) { *alpha = SDL_ALPHA_OPAQUE; alpha += 4; } } } SDL_Surface * SDL_LoadBMP_RW(SDL_RWops * src, int freesrc) { SDL_bool was_error; Sint64 fp_offset = 0; int bmpPitch; int i, pad; SDL_Surface *surface; Uint32 Rmask = 0; Uint32 Gmask = 0; Uint32 Bmask = 0; Uint32 Amask = 0; SDL_Palette *palette; Uint8 *bits; Uint8 *top, *end; SDL_bool topDown; int ExpandBMP; SDL_bool haveRGBMasks = SDL_FALSE; SDL_bool haveAlphaMask = SDL_FALSE; SDL_bool correctAlpha = SDL_FALSE; /* The Win32 BMP file header (14 bytes) */ char magic[2]; /* Uint32 bfSize; */ /* Uint16 bfReserved1; */ /* Uint16 bfReserved2; */ Uint32 bfOffBits; /* The Win32 BITMAPINFOHEADER struct (40 bytes) */ Uint32 biSize; Sint32 biWidth = 0; Sint32 biHeight = 0; /* Uint16 biPlanes; */ Uint16 biBitCount = 0; Uint32 biCompression = 0; /* Uint32 biSizeImage; */ /* Sint32 biXPelsPerMeter; */ /* Sint32 biYPelsPerMeter; */ Uint32 biClrUsed = 0; /* Uint32 biClrImportant; */ /* Make sure we are passed a valid data source */ surface = NULL; was_error = SDL_FALSE; if (src == NULL) { was_error = SDL_TRUE; goto done; } /* Read in the BMP file header */ fp_offset = SDL_RWtell(src); SDL_ClearError(); if (SDL_RWread(src, magic, 1, 2) != 2) { SDL_Error(SDL_EFREAD); was_error = SDL_TRUE; goto done; } if (SDL_strncmp(magic, "BM", 2) != 0) { SDL_SetError("File is not a Windows BMP file"); was_error = SDL_TRUE; goto done; } /* bfSize = */ SDL_ReadLE32(src); /* bfReserved1 = */ SDL_ReadLE16(src); /* bfReserved2 = */ SDL_ReadLE16(src); bfOffBits = SDL_ReadLE32(src); /* Read the Win32 BITMAPINFOHEADER */ biSize = SDL_ReadLE32(src); if (biSize == 12) { /* really old BITMAPCOREHEADER */ biWidth = (Uint32) SDL_ReadLE16(src); biHeight = (Uint32) SDL_ReadLE16(src); /* biPlanes = */ SDL_ReadLE16(src); biBitCount = SDL_ReadLE16(src); biCompression = BI_RGB; /* biSizeImage = 0; */ /* biXPelsPerMeter = 0; */ /* biYPelsPerMeter = 0; */ biClrUsed = 0; /* biClrImportant = 0; */ } else if (biSize >= 40) { /* some version of BITMAPINFOHEADER */ Uint32 headerSize; biWidth = SDL_ReadLE32(src); biHeight = SDL_ReadLE32(src); /* biPlanes = */ SDL_ReadLE16(src); biBitCount = SDL_ReadLE16(src); biCompression = SDL_ReadLE32(src); /* biSizeImage = */ SDL_ReadLE32(src); /* biXPelsPerMeter = */ SDL_ReadLE32(src); /* biYPelsPerMeter = */ SDL_ReadLE32(src); biClrUsed = SDL_ReadLE32(src); /* biClrImportant = */ SDL_ReadLE32(src); /* 64 == BITMAPCOREHEADER2, an incompatible OS/2 2.x extension. Skip this stuff for now. */ if (biSize != 64) { /* This is complicated. If compression is BI_BITFIELDS, then we have 3 DWORDS that specify the RGB masks. This is either stored here in an BITMAPV2INFOHEADER (which only differs in that it adds these RGB masks) and biSize >= 52, or we've got these masks stored in the exact same place, but strictly speaking, this is the bmiColors field in BITMAPINFO immediately following the legacy v1 info header, just past biSize. */ if (biCompression == BI_BITFIELDS) { haveRGBMasks = SDL_TRUE; Rmask = SDL_ReadLE32(src); Gmask = SDL_ReadLE32(src); Bmask = SDL_ReadLE32(src); /* ...v3 adds an alpha mask. */ if (biSize >= 56) { /* BITMAPV3INFOHEADER; adds alpha mask */ haveAlphaMask = SDL_TRUE; Amask = SDL_ReadLE32(src); } } else { /* the mask fields are ignored for v2+ headers if not BI_BITFIELD. */ if (biSize >= 52) { /* BITMAPV2INFOHEADER; adds RGB masks */ /*Rmask = */ SDL_ReadLE32(src); /*Gmask = */ SDL_ReadLE32(src); /*Bmask = */ SDL_ReadLE32(src); } if (biSize >= 56) { /* BITMAPV3INFOHEADER; adds alpha mask */ /*Amask = */ SDL_ReadLE32(src); } } /* Insert other fields here; Wikipedia and MSDN say we're up to v5 of this header, but we ignore those for now (they add gamma, color spaces, etc). Ignoring the weird OS/2 2.x format, we currently parse up to v3 correctly (hopefully!). */ } /* skip any header bytes we didn't handle... */ headerSize = (Uint32) (SDL_RWtell(src) - (fp_offset + 14)); if (biSize > headerSize) { SDL_RWseek(src, (biSize - headerSize), RW_SEEK_CUR); } } if (biWidth <= 0 || biHeight == 0) { SDL_SetError("BMP file with bad dimensions (%dx%d)", biWidth, biHeight); was_error = SDL_TRUE; goto done; } if (biHeight < 0) { topDown = SDL_TRUE; biHeight = -biHeight; } else { topDown = SDL_FALSE; } /* Check for read error */ if (SDL_strcmp(SDL_GetError(), "") != 0) { was_error = SDL_TRUE; goto done; } /* Expand 1 and 4 bit bitmaps to 8 bits per pixel */ switch (biBitCount) { case 1: case 4: ExpandBMP = biBitCount; biBitCount = 8; break; case 0: case 2: case 3: case 5: case 6: case 7: SDL_SetError("%d-bpp BMP images are not supported", biBitCount); was_error = SDL_TRUE; goto done; default: ExpandBMP = 0; break; } /* RLE4 and RLE8 BMP compression is supported */ switch (biCompression) { case BI_RGB: /* If there are no masks, use the defaults */ SDL_assert(!haveRGBMasks); SDL_assert(!haveAlphaMask); /* Default values for the BMP format */ switch (biBitCount) { case 15: case 16: Rmask = 0x7C00; Gmask = 0x03E0; Bmask = 0x001F; break; case 24: #if SDL_BYTEORDER == SDL_BIG_ENDIAN Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; #else Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; #endif break; case 32: /* We don't know if this has alpha channel or not */ correctAlpha = SDL_TRUE; Amask = 0xFF000000; Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; break; default: break; } break; case BI_BITFIELDS: break; /* we handled this in the info header. */ default: break; } /* Create a compatible surface, note that the colors are RGB ordered */ surface = SDL_CreateRGBSurface(0, biWidth, biHeight, biBitCount, Rmask, Gmask, Bmask, Amask); if (surface == NULL) { was_error = SDL_TRUE; goto done; } /* Load the palette, if any */ palette = (surface->format)->palette; if (palette) { if (SDL_RWseek(src, fp_offset+14+biSize, RW_SEEK_SET) < 0) { SDL_Error(SDL_EFSEEK); was_error = SDL_TRUE; goto done; } /* | guich: always use 1<<bpp b/c some bitmaps can bring wrong information | for colorsUsed */ /* if (biClrUsed == 0) { */ biClrUsed = 1 << biBitCount; /* } */ if (biSize == 12) { for (i = 0; i < (int) biClrUsed; ++i) { SDL_RWread(src, &palette->colors[i].b, 1, 1); SDL_RWread(src, &palette->colors[i].g, 1, 1); SDL_RWread(src, &palette->colors[i].r, 1, 1); palette->colors[i].a = SDL_ALPHA_OPAQUE; } } else { for (i = 0; i < (int) biClrUsed; ++i) { SDL_RWread(src, &palette->colors[i].b, 1, 1); SDL_RWread(src, &palette->colors[i].g, 1, 1); SDL_RWread(src, &palette->colors[i].r, 1, 1); SDL_RWread(src, &palette->colors[i].a, 1, 1); /* According to Microsoft documentation, the fourth element is reserved and must be zero, so we shouldn't treat it as alpha. */ palette->colors[i].a = SDL_ALPHA_OPAQUE; } } palette->ncolors = biClrUsed; } /* Read the surface pixels. Note that the bmp image is upside down */ if (SDL_RWseek(src, fp_offset + bfOffBits, RW_SEEK_SET) < 0) { SDL_Error(SDL_EFSEEK); was_error = SDL_TRUE; goto done; } if ((biCompression == BI_RLE4) || (biCompression == BI_RLE8)) { was_error = (SDL_bool)readRlePixels(surface, src, biCompression == BI_RLE8); if (was_error) SDL_SetError("Error reading from BMP"); goto done; } top = (Uint8 *)surface->pixels; end = (Uint8 *)surface->pixels+(surface->h*surface->pitch); switch (ExpandBMP) { case 1: bmpPitch = (biWidth + 7) >> 3; pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); break; case 4: bmpPitch = (biWidth + 1) >> 1; pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0); break; default: pad = ((surface->pitch % 4) ? (4 - (surface->pitch % 4)) : 0); break; } if (topDown) { bits = top; } else { bits = end - surface->pitch; } while (bits >= top && bits < end) { switch (ExpandBMP) { case 1: case 4:{ Uint8 pixel = 0; int shift = (8 - ExpandBMP); for (i = 0; i < surface->w; ++i) { if (i % (8 / ExpandBMP) == 0) { if (!SDL_RWread(src, &pixel, 1, 1)) { SDL_SetError("Error reading from BMP"); was_error = SDL_TRUE; goto done; } } bits[i] = (pixel >> shift); if (bits[i] >= biClrUsed) { SDL_SetError("A BMP image contains a pixel with a color out of the palette"); was_error = SDL_TRUE; goto done; } pixel <<= ExpandBMP; } } break; default: if (SDL_RWread(src, bits, 1, surface->pitch) != surface->pitch) { SDL_Error(SDL_EFREAD); was_error = SDL_TRUE; goto done; } if (biBitCount == 8 && palette && biClrUsed < (1u << biBitCount)) { for (i = 0; i < surface->w; ++i) { if (bits[i] >= biClrUsed) { SDL_SetError("A BMP image contains a pixel with a color out of the palette"); was_error = SDL_TRUE; goto done; } } } #if SDL_BYTEORDER == SDL_BIG_ENDIAN /* Byte-swap the pixels if needed. Note that the 24bpp case has already been taken care of above. */ switch (biBitCount) { case 15: case 16:{ Uint16 *pix = (Uint16 *) bits; for (i = 0; i < surface->w; i++) pix[i] = SDL_Swap16(pix[i]); break; } case 32:{ Uint32 *pix = (Uint32 *) bits; for (i = 0; i < surface->w; i++) pix[i] = SDL_Swap32(pix[i]); break; } } #endif break; } /* Skip padding bytes, ugh */ if (pad) { Uint8 padbyte; for (i = 0; i < pad; ++i) { SDL_RWread(src, &padbyte, 1, 1); } } if (topDown) { bits += surface->pitch; } else { bits -= surface->pitch; } } if (correctAlpha) { CorrectAlphaChannel(surface); } done: if (was_error) { if (src) { SDL_RWseek(src, fp_offset, RW_SEEK_SET); } if (surface) { SDL_FreeSurface(surface); } surface = NULL; } if (freesrc && src) { SDL_RWclose(src); } return (surface); } int SDL_SaveBMP_RW(SDL_Surface * saveme, SDL_RWops * dst, int freedst) { Sint64 fp_offset; int i, pad; SDL_Surface *surface; Uint8 *bits; SDL_bool save32bit = SDL_FALSE; SDL_bool saveLegacyBMP = SDL_FALSE; /* The Win32 BMP file header (14 bytes) */ char magic[2] = { 'B', 'M' }; Uint32 bfSize; Uint16 bfReserved1; Uint16 bfReserved2; Uint32 bfOffBits; /* The Win32 BITMAPINFOHEADER struct (40 bytes) */ Uint32 biSize; Sint32 biWidth; Sint32 biHeight; Uint16 biPlanes; Uint16 biBitCount; Uint32 biCompression; Uint32 biSizeImage; Sint32 biXPelsPerMeter; Sint32 biYPelsPerMeter; Uint32 biClrUsed; Uint32 biClrImportant; /* The additional header members from the Win32 BITMAPV4HEADER struct (108 bytes in total) */ Uint32 bV4RedMask = 0; Uint32 bV4GreenMask = 0; Uint32 bV4BlueMask = 0; Uint32 bV4AlphaMask = 0; Uint32 bV4CSType = 0; Sint32 bV4Endpoints[3 * 3] = {0}; Uint32 bV4GammaRed = 0; Uint32 bV4GammaGreen = 0; Uint32 bV4GammaBlue = 0; /* Make sure we have somewhere to save */ surface = NULL; if (dst) { #ifdef SAVE_32BIT_BMP /* We can save alpha information in a 32-bit BMP */ if (saveme->format->BitsPerPixel >= 8 && (saveme->format->Amask || saveme->map->info.flags & SDL_COPY_COLORKEY)) { save32bit = SDL_TRUE; } #endif /* SAVE_32BIT_BMP */ if (saveme->format->palette && !save32bit) { if (saveme->format->BitsPerPixel == 8) { surface = saveme; } else { SDL_SetError("%d bpp BMP files not supported", saveme->format->BitsPerPixel); } } else if ((saveme->format->BitsPerPixel == 24) && !save32bit && #if SDL_BYTEORDER == SDL_LIL_ENDIAN (saveme->format->Rmask == 0x00FF0000) && (saveme->format->Gmask == 0x0000FF00) && (saveme->format->Bmask == 0x000000FF) #else (saveme->format->Rmask == 0x000000FF) && (saveme->format->Gmask == 0x0000FF00) && (saveme->format->Bmask == 0x00FF0000) #endif ) { surface = saveme; } else { SDL_PixelFormat format; /* If the surface has a colorkey or alpha channel we'll save a 32-bit BMP with alpha channel, otherwise save a 24-bit BMP. */ if (save32bit) { SDL_InitFormat(&format, SDL_PIXELFORMAT_BGRA32); } else { SDL_InitFormat(&format, SDL_PIXELFORMAT_BGR24); } surface = SDL_ConvertSurface(saveme, &format, 0); if (!surface) { SDL_SetError("Couldn't convert image to %d bpp", format.BitsPerPixel); } } } else { /* Set no error here because it may overwrite a more useful message from SDL_RWFromFile() if SDL_SaveBMP_RW() is called from SDL_SaveBMP(). */ return -1; } if (save32bit) { saveLegacyBMP = SDL_GetHintBoolean(SDL_HINT_BMP_SAVE_LEGACY_FORMAT, SDL_FALSE); } if (surface && (SDL_LockSurface(surface) == 0)) { const int bw = surface->w * surface->format->BytesPerPixel; /* Set the BMP file header values */ bfSize = 0; /* We'll write this when we're done */ bfReserved1 = 0; bfReserved2 = 0; bfOffBits = 0; /* We'll write this when we're done */ /* Write the BMP file header values */ fp_offset = SDL_RWtell(dst); SDL_ClearError(); SDL_RWwrite(dst, magic, 2, 1); SDL_WriteLE32(dst, bfSize); SDL_WriteLE16(dst, bfReserved1); SDL_WriteLE16(dst, bfReserved2); SDL_WriteLE32(dst, bfOffBits); /* Set the BMP info values */ biSize = 40; biWidth = surface->w; biHeight = surface->h; biPlanes = 1; biBitCount = surface->format->BitsPerPixel; biCompression = BI_RGB; biSizeImage = surface->h * surface->pitch; biXPelsPerMeter = 0; biYPelsPerMeter = 0; if (surface->format->palette) { biClrUsed = surface->format->palette->ncolors; } else { biClrUsed = 0; } biClrImportant = 0; /* Set the BMP info values for the version 4 header */ if (save32bit && !saveLegacyBMP) { biSize = 108; biCompression = BI_BITFIELDS; /* The BMP format is always little endian, these masks stay the same */ bV4RedMask = 0x00ff0000; bV4GreenMask = 0x0000ff00; bV4BlueMask = 0x000000ff; bV4AlphaMask = 0xff000000; bV4CSType = LCS_WINDOWS_COLOR_SPACE; bV4GammaRed = 0; bV4GammaGreen = 0; bV4GammaBlue = 0; } /* Write the BMP info values */ SDL_WriteLE32(dst, biSize); SDL_WriteLE32(dst, biWidth); SDL_WriteLE32(dst, biHeight); SDL_WriteLE16(dst, biPlanes); SDL_WriteLE16(dst, biBitCount); SDL_WriteLE32(dst, biCompression); SDL_WriteLE32(dst, biSizeImage); SDL_WriteLE32(dst, biXPelsPerMeter); SDL_WriteLE32(dst, biYPelsPerMeter); SDL_WriteLE32(dst, biClrUsed); SDL_WriteLE32(dst, biClrImportant); /* Write the BMP info values for the version 4 header */ if (save32bit && !saveLegacyBMP) { SDL_WriteLE32(dst, bV4RedMask); SDL_WriteLE32(dst, bV4GreenMask); SDL_WriteLE32(dst, bV4BlueMask); SDL_WriteLE32(dst, bV4AlphaMask); SDL_WriteLE32(dst, bV4CSType); for (i = 0; i < 3 * 3; i++) { SDL_WriteLE32(dst, bV4Endpoints[i]); } SDL_WriteLE32(dst, bV4GammaRed); SDL_WriteLE32(dst, bV4GammaGreen); SDL_WriteLE32(dst, bV4GammaBlue); } /* Write the palette (in BGR color order) */ if (surface->format->palette) { SDL_Color *colors; int ncolors; colors = surface->format->palette->colors; ncolors = surface->format->palette->ncolors; for (i = 0; i < ncolors; ++i) { SDL_RWwrite(dst, &colors[i].b, 1, 1); SDL_RWwrite(dst, &colors[i].g, 1, 1); SDL_RWwrite(dst, &colors[i].r, 1, 1); SDL_RWwrite(dst, &colors[i].a, 1, 1); } } /* Write the bitmap offset */ bfOffBits = (Uint32)(SDL_RWtell(dst) - fp_offset); if (SDL_RWseek(dst, fp_offset + 10, RW_SEEK_SET) < 0) { SDL_Error(SDL_EFSEEK); } SDL_WriteLE32(dst, bfOffBits); if (SDL_RWseek(dst, fp_offset + bfOffBits, RW_SEEK_SET) < 0) { SDL_Error(SDL_EFSEEK); } /* Write the bitmap image upside down */ bits = (Uint8 *) surface->pixels + (surface->h * surface->pitch); pad = ((bw % 4) ? (4 - (bw % 4)) : 0); while (bits > (Uint8 *) surface->pixels) { bits -= surface->pitch; if (SDL_RWwrite(dst, bits, 1, bw) != bw) { SDL_Error(SDL_EFWRITE); break; } if (pad) { const Uint8 padbyte = 0; for (i = 0; i < pad; ++i) { SDL_RWwrite(dst, &padbyte, 1, 1); } } } /* Write the BMP file size */ bfSize = (Uint32)(SDL_RWtell(dst) - fp_offset); if (SDL_RWseek(dst, fp_offset + 2, RW_SEEK_SET) < 0) { SDL_Error(SDL_EFSEEK); } SDL_WriteLE32(dst, bfSize); if (SDL_RWseek(dst, fp_offset + bfSize, RW_SEEK_SET) < 0) { SDL_Error(SDL_EFSEEK); } /* Close it up.. */ SDL_UnlockSurface(surface); if (surface != saveme) { SDL_FreeSurface(surface); } } if (freedst && dst) { SDL_RWclose(dst); } return ((SDL_strcmp(SDL_GetError(), "") == 0) ? 0 : -1); } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_bmp.c
C
apache-2.0
26,894
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL_clipboard.h" #include "SDL_sysvideo.h" int SDL_SetClipboardText(const char *text) { SDL_VideoDevice *_this = SDL_GetVideoDevice(); if (!_this) { return SDL_SetError("Video subsystem must be initialized to set clipboard text"); } if (!text) { text = ""; } if (_this->SetClipboardText) { return _this->SetClipboardText(_this, text); } else { SDL_free(_this->clipboard_text); _this->clipboard_text = SDL_strdup(text); return 0; } } char * SDL_GetClipboardText(void) { SDL_VideoDevice *_this = SDL_GetVideoDevice(); if (!_this) { SDL_SetError("Video subsystem must be initialized to get clipboard text"); return SDL_strdup(""); } if (_this->GetClipboardText) { return _this->GetClipboardText(_this); } else { const char *text = _this->clipboard_text; if (!text) { text = ""; } return SDL_strdup(text); } } SDL_bool SDL_HasClipboardText(void) { SDL_VideoDevice *_this = SDL_GetVideoDevice(); if (!_this) { SDL_SetError("Video subsystem must be initialized to check clipboard text"); return SDL_FALSE; } if (_this->HasClipboardText) { return _this->HasClipboardText(_this); } else { if (_this->clipboard_text && _this->clipboard_text[0] != '\0') { return SDL_TRUE; } else { return SDL_FALSE; } } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_clipboard.c
C
apache-2.0
2,489
/* * Simple DirectMedia Layer * Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #if SDL_VIDEO_OPENGL_EGL #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT #include "../core/windows/SDL_windows.h" #endif #if SDL_VIDEO_DRIVER_ANDROID #include <android/native_window.h> #include "../core/android/SDL_android.h" #endif #include "SDL_sysvideo.h" #include "SDL_egl_c.h" #include "SDL_loadso.h" #include "SDL_hints.h" #ifdef EGL_KHR_create_context /* EGL_OPENGL_ES3_BIT_KHR was added in version 13 of the extension. */ #ifndef EGL_OPENGL_ES3_BIT_KHR #define EGL_OPENGL_ES3_BIT_KHR 0x00000040 #endif #endif /* EGL_KHR_create_context */ #if SDL_VIDEO_DRIVER_RPI /* Raspbian places the OpenGL ES/EGL binaries in a non standard path */ #define DEFAULT_EGL ( vc4 ? "libEGL.so.1" : "libbrcmEGL.so" ) #define DEFAULT_OGL_ES2 ( vc4 ? "libGLESv2.so.2" : "libbrcmGLESv2.so" ) #define ALT_EGL "libEGL.so" #define ALT_OGL_ES2 "libGLESv2.so" #define DEFAULT_OGL_ES_PVR ( vc4 ? "libGLES_CM.so.1" : "libbrcmGLESv2.so" ) #define DEFAULT_OGL_ES ( vc4 ? "libGLESv1_CM.so.1" : "libbrcmGLESv2.so" ) #elif SDL_VIDEO_DRIVER_ANDROID || SDL_VIDEO_DRIVER_VIVANTE /* Android */ #define DEFAULT_EGL "libEGL.so" #define DEFAULT_OGL_ES2 "libGLESv2.so" #define DEFAULT_OGL_ES_PVR "libGLES_CM.so" #define DEFAULT_OGL_ES "libGLESv1_CM.so" #elif SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT /* EGL AND OpenGL ES support via ANGLE */ #define DEFAULT_EGL "libEGL.dll" #define DEFAULT_OGL_ES2 "libGLESv2.dll" #define DEFAULT_OGL_ES_PVR "libGLES_CM.dll" #define DEFAULT_OGL_ES "libGLESv1_CM.dll" #elif SDL_VIDEO_DRIVER_COCOA /* EGL AND OpenGL ES support via ANGLE */ #define DEFAULT_EGL "libEGL.dylib" #define DEFAULT_OGL_ES2 "libGLESv2.dylib" #define DEFAULT_OGL_ES_PVR "libGLES_CM.dylib" //??? #define DEFAULT_OGL_ES "libGLESv1_CM.dylib" //??? #else /* Desktop Linux */ #define DEFAULT_OGL "libGL.so.1" #define DEFAULT_EGL "libEGL.so.1" #define DEFAULT_OGL_ES2 "libGLESv2.so.2" #define DEFAULT_OGL_ES_PVR "libGLES_CM.so.1" #define DEFAULT_OGL_ES "libGLESv1_CM.so.1" #endif /* SDL_VIDEO_DRIVER_RPI */ #if SDL_VIDEO_OPENGL #include "SDL_opengl.h" #endif /** If we happen to not have this defined because of an older EGL version, just define it 0x0 as eglGetPlatformDisplayEXT will most likely be NULL if this is missing */ #ifndef EGL_PLATFORM_DEVICE_EXT #define EGL_PLATFORM_DEVICE_EXT 0x0 #endif #ifdef SDL_VIDEO_STATIC_ANGLE #define LOAD_FUNC(NAME) \ _this->egl_data->NAME = (void *)NAME; #else #define LOAD_FUNC(NAME) \ _this->egl_data->NAME = SDL_LoadFunction(_this->egl_data->dll_handle, #NAME); \ if (!_this->egl_data->NAME) \ { \ return SDL_SetError("Could not retrieve EGL function " #NAME); \ } #endif /* it is allowed to not have some of the EGL extensions on start - attempts to use them will fail later. */ #define LOAD_FUNC_EGLEXT(NAME) \ _this->egl_data->NAME = _this->egl_data->eglGetProcAddress(#NAME); static const char * SDL_EGL_GetErrorName(EGLint eglErrorCode) { #define SDL_EGL_ERROR_TRANSLATE(e) case e: return #e; switch (eglErrorCode) { SDL_EGL_ERROR_TRANSLATE(EGL_SUCCESS); SDL_EGL_ERROR_TRANSLATE(EGL_NOT_INITIALIZED); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ACCESS); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ALLOC); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ATTRIBUTE); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CONTEXT); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CONFIG); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CURRENT_SURFACE); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_DISPLAY); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_SURFACE); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_MATCH); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_PARAMETER); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_NATIVE_PIXMAP); SDL_EGL_ERROR_TRANSLATE(EGL_BAD_NATIVE_WINDOW); SDL_EGL_ERROR_TRANSLATE(EGL_CONTEXT_LOST); } return ""; } int SDL_EGL_SetErrorEx(const char * message, const char * eglFunctionName, EGLint eglErrorCode) { const char * errorText = SDL_EGL_GetErrorName(eglErrorCode); char altErrorText[32]; if (errorText[0] == '\0') { /* An unknown-to-SDL error code was reported. Report its hexadecimal value, instead of its name. */ SDL_snprintf(altErrorText, SDL_arraysize(altErrorText), "0x%x", (unsigned int)eglErrorCode); errorText = altErrorText; } return SDL_SetError("%s (call to %s failed, reporting an error of %s)", message, eglFunctionName, errorText); } /* EGL implementation of SDL OpenGL ES support */ typedef enum { SDL_EGL_DISPLAY_EXTENSION, SDL_EGL_CLIENT_EXTENSION } SDL_EGL_ExtensionType; static SDL_bool SDL_EGL_HasExtension(_THIS, SDL_EGL_ExtensionType type, const char *ext) { size_t ext_len; const char *ext_override; const char *egl_extstr; const char *ext_start; /* Invalid extensions can be rejected early */ if (ext == NULL || *ext == 0 || SDL_strchr(ext, ' ') != NULL) { /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "SDL_EGL_HasExtension: Invalid EGL extension"); */ return SDL_FALSE; } /* Extensions can be masked with an environment variable. * Unlike the OpenGL override, this will use the set bits of an integer * to disable the extension. * Bit Action * 0 If set, the display extension is masked and not present to SDL. * 1 If set, the client extension is masked and not present to SDL. */ ext_override = SDL_getenv(ext); if (ext_override != NULL) { int disable_ext = SDL_atoi(ext_override); if (disable_ext & 0x01 && type == SDL_EGL_DISPLAY_EXTENSION) { return SDL_FALSE; } else if (disable_ext & 0x02 && type == SDL_EGL_CLIENT_EXTENSION) { return SDL_FALSE; } } ext_len = SDL_strlen(ext); switch (type) { case SDL_EGL_DISPLAY_EXTENSION: egl_extstr = _this->egl_data->eglQueryString(_this->egl_data->egl_display, EGL_EXTENSIONS); break; case SDL_EGL_CLIENT_EXTENSION: /* EGL_EXT_client_extensions modifies eglQueryString to return client extensions * if EGL_NO_DISPLAY is passed. Implementations without it are required to return NULL. * This behavior is included in EGL 1.5. */ egl_extstr = _this->egl_data->eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); break; default: /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "SDL_EGL_HasExtension: Invalid extension type"); */ return SDL_FALSE; } if (egl_extstr != NULL) { ext_start = egl_extstr; while (*ext_start) { ext_start = SDL_strstr(ext_start, ext); if (ext_start == NULL) { return SDL_FALSE; } /* Check if the match is not just a substring of one of the extensions */ if (ext_start == egl_extstr || *(ext_start - 1) == ' ') { if (ext_start[ext_len] == ' ' || ext_start[ext_len] == 0) { return SDL_TRUE; } } /* If the search stopped in the middle of an extension, skip to the end of it */ ext_start += ext_len; while (*ext_start != ' ' && *ext_start != 0) { ext_start++; } } } return SDL_FALSE; } void * SDL_EGL_GetProcAddress(_THIS, const char *proc) { const Uint32 eglver = (((Uint32) _this->egl_data->egl_version_major) << 16) | ((Uint32) _this->egl_data->egl_version_minor); const SDL_bool is_egl_15_or_later = eglver >= ((((Uint32) 1) << 16) | 5); void *retval = NULL; /* EGL 1.5 can use eglGetProcAddress() for any symbol. 1.4 and earlier can't use it for core entry points. */ if (!retval && is_egl_15_or_later && _this->egl_data->eglGetProcAddress) { retval = _this->egl_data->eglGetProcAddress(proc); } #ifndef __EMSCRIPTEN__ /* LoadFunction isn't needed on Emscripten and will call dlsym(), causing other problems. */ /* Try SDL_LoadFunction() first for EGL <= 1.4, or as a fallback for >= 1.5. */ if (!retval) { static char procname[64]; retval = SDL_LoadFunction(_this->egl_data->egl_dll_handle, proc); /* just in case you need an underscore prepended... */ if (!retval && (SDL_strlen(proc) < (sizeof (procname) - 1))) { procname[0] = '_'; SDL_strlcpy(procname + 1, proc, sizeof (procname) - 1); retval = SDL_LoadFunction(_this->egl_data->egl_dll_handle, procname); } } #endif /* Try eglGetProcAddress if we're on <= 1.4 and still searching... */ if (!retval && !is_egl_15_or_later && _this->egl_data->eglGetProcAddress) { retval = _this->egl_data->eglGetProcAddress(proc); if (retval) { return retval; } } return retval; } void SDL_EGL_UnloadLibrary(_THIS) { if (_this->egl_data) { if (_this->egl_data->egl_display) { _this->egl_data->eglTerminate(_this->egl_data->egl_display); _this->egl_data->egl_display = NULL; } if (_this->egl_data->dll_handle) { SDL_UnloadObject(_this->egl_data->dll_handle); _this->egl_data->dll_handle = NULL; } if (_this->egl_data->egl_dll_handle) { SDL_UnloadObject(_this->egl_data->egl_dll_handle); _this->egl_data->egl_dll_handle = NULL; } SDL_free(_this->egl_data); _this->egl_data = NULL; } } int SDL_EGL_LoadLibraryOnly(_THIS, const char *egl_path) { void *dll_handle = NULL, *egl_dll_handle = NULL; /* The naming is counter intuitive, but hey, I just work here -- Gabriel */ const char *path = NULL; #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT const char *d3dcompiler; #endif #if SDL_VIDEO_DRIVER_RPI SDL_bool vc4 = (0 == access("/sys/module/vc4/", F_OK)); #endif if (_this->egl_data) { return SDL_SetError("EGL context already created"); } _this->egl_data = (struct SDL_EGL_VideoData *) SDL_calloc(1, sizeof(SDL_EGL_VideoData)); if (!_this->egl_data) { return SDL_OutOfMemory(); } #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT d3dcompiler = SDL_GetHint(SDL_HINT_VIDEO_WIN_D3DCOMPILER); if (d3dcompiler) { if (SDL_strcasecmp(d3dcompiler, "none") != 0) { if (SDL_LoadObject(d3dcompiler) == NULL) { SDL_ClearError(); } } } else { if (WIN_IsWindowsVistaOrGreater()) { /* Try the newer d3d compilers first */ const char *d3dcompiler_list[] = { "d3dcompiler_47.dll", "d3dcompiler_46.dll", }; int i; for (i = 0; i < SDL_arraysize(d3dcompiler_list); ++i) { if (SDL_LoadObject(d3dcompiler_list[i]) != NULL) { break; } SDL_ClearError(); } } else { if (SDL_LoadObject("d3dcompiler_43.dll") == NULL) { SDL_ClearError(); } } } #endif #ifndef SDL_VIDEO_STATIC_ANGLE /* A funny thing, loading EGL.so first does not work on the Raspberry, so we load libGL* first */ path = SDL_getenv("SDL_VIDEO_GL_DRIVER"); if (path != NULL) { egl_dll_handle = SDL_LoadObject(path); } if (egl_dll_handle == NULL) { if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { if (_this->gl_config.major_version > 1) { path = DEFAULT_OGL_ES2; egl_dll_handle = SDL_LoadObject(path); #ifdef ALT_OGL_ES2 if (egl_dll_handle == NULL && !vc4) { path = ALT_OGL_ES2; egl_dll_handle = SDL_LoadObject(path); } #endif } else { path = DEFAULT_OGL_ES; egl_dll_handle = SDL_LoadObject(path); if (egl_dll_handle == NULL) { path = DEFAULT_OGL_ES_PVR; egl_dll_handle = SDL_LoadObject(path); } #ifdef ALT_OGL_ES2 if (egl_dll_handle == NULL && !vc4) { path = ALT_OGL_ES2; egl_dll_handle = SDL_LoadObject(path); } #endif } } #ifdef DEFAULT_OGL else { path = DEFAULT_OGL; egl_dll_handle = SDL_LoadObject(path); } #endif } _this->egl_data->egl_dll_handle = egl_dll_handle; if (egl_dll_handle == NULL) { return SDL_SetError("Could not initialize OpenGL / GLES library"); } /* Loading libGL* in the previous step took care of loading libEGL.so, but we future proof by double checking */ if (egl_path != NULL) { dll_handle = SDL_LoadObject(egl_path); } /* Try loading a EGL symbol, if it does not work try the default library paths */ if (dll_handle == NULL || SDL_LoadFunction(dll_handle, "eglChooseConfig") == NULL) { if (dll_handle != NULL) { SDL_UnloadObject(dll_handle); } path = SDL_getenv("SDL_VIDEO_EGL_DRIVER"); if (path == NULL) { path = DEFAULT_EGL; } dll_handle = SDL_LoadObject(path); #ifdef ALT_EGL if (dll_handle == NULL && !vc4) { path = ALT_EGL; dll_handle = SDL_LoadObject(path); } #endif if (dll_handle == NULL || SDL_LoadFunction(dll_handle, "eglChooseConfig") == NULL) { if (dll_handle != NULL) { SDL_UnloadObject(dll_handle); } return SDL_SetError("Could not load EGL library"); } SDL_ClearError(); } #endif _this->egl_data->dll_handle = dll_handle; /* Load new function pointers */ LOAD_FUNC(eglGetDisplay); LOAD_FUNC(eglInitialize); LOAD_FUNC(eglTerminate); LOAD_FUNC(eglGetProcAddress); LOAD_FUNC(eglChooseConfig); LOAD_FUNC(eglGetConfigAttrib); LOAD_FUNC(eglCreateContext); LOAD_FUNC(eglDestroyContext); LOAD_FUNC(eglCreatePbufferSurface); LOAD_FUNC(eglCreateWindowSurface); LOAD_FUNC(eglDestroySurface); LOAD_FUNC(eglMakeCurrent); LOAD_FUNC(eglSwapBuffers); LOAD_FUNC(eglSwapInterval); LOAD_FUNC(eglWaitNative); LOAD_FUNC(eglWaitGL); LOAD_FUNC(eglBindAPI); LOAD_FUNC(eglQueryAPI); LOAD_FUNC(eglQueryString); LOAD_FUNC(eglGetError); LOAD_FUNC_EGLEXT(eglQueryDevicesEXT); LOAD_FUNC_EGLEXT(eglGetPlatformDisplayEXT); _this->gl_config.driver_loaded = 1; if (path) { SDL_strlcpy(_this->gl_config.driver_path, path, sizeof(_this->gl_config.driver_path) - 1); } else { *_this->gl_config.driver_path = '\0'; } return 0; } static void SDL_EGL_GetVersion(_THIS) { if (_this->egl_data->eglQueryString) { const char *egl_version = _this->egl_data->eglQueryString(_this->egl_data->egl_display, EGL_VERSION); if (egl_version) { int major = 0, minor = 0; if (SDL_sscanf(egl_version, "%d.%d", &major, &minor) == 2) { _this->egl_data->egl_version_major = major; _this->egl_data->egl_version_minor = minor; } else { SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "Could not parse EGL version string: %s", egl_version); } } } } int SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_display, EGLenum platform) { int egl_version_major, egl_version_minor; int library_load_retcode = SDL_EGL_LoadLibraryOnly(_this, egl_path); if (library_load_retcode != 0) { return library_load_retcode; } /* EGL 1.5 allows querying for client version with EGL_NO_DISPLAY */ SDL_EGL_GetVersion(_this); egl_version_major = _this->egl_data->egl_version_major; egl_version_minor = _this->egl_data->egl_version_minor; if (egl_version_major == 1 && egl_version_minor == 5) { LOAD_FUNC(eglGetPlatformDisplay); } _this->egl_data->egl_display = EGL_NO_DISPLAY; #if !defined(__WINRT__) if (platform) { if (egl_version_major == 1 && egl_version_minor == 5) { _this->egl_data->egl_display = _this->egl_data->eglGetPlatformDisplay(platform, (void *)(size_t)native_display, NULL); } else { if (SDL_EGL_HasExtension(_this, SDL_EGL_CLIENT_EXTENSION, "EGL_EXT_platform_base")) { _this->egl_data->eglGetPlatformDisplayEXT = SDL_EGL_GetProcAddress(_this, "eglGetPlatformDisplayEXT"); if (_this->egl_data->eglGetPlatformDisplayEXT) { _this->egl_data->egl_display = _this->egl_data->eglGetPlatformDisplayEXT(platform, (void *)(size_t)native_display, NULL); } } } } /* Try the implementation-specific eglGetDisplay even if eglGetPlatformDisplay fails */ if (_this->egl_data->egl_display == EGL_NO_DISPLAY) { _this->egl_data->egl_display = _this->egl_data->eglGetDisplay(native_display); } if (_this->egl_data->egl_display == EGL_NO_DISPLAY) { _this->gl_config.driver_loaded = 0; *_this->gl_config.driver_path = '\0'; return SDL_SetError("Could not get EGL display"); } if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) { _this->gl_config.driver_loaded = 0; *_this->gl_config.driver_path = '\0'; return SDL_SetError("Could not initialize EGL"); } #endif /* Get the EGL version with a valid egl_display, for EGL <= 1.4 */ SDL_EGL_GetVersion(_this); _this->egl_data->is_offscreen = 0; return 0; } /** On multi GPU machines EGL device 0 is not always the first valid GPU. Container environments can restrict access to some GPUs that are still listed in the EGL device list. If the requested device is a restricted GPU and cannot be used (eglInitialize() will fail) then attempt to automatically and silently select the next valid available GPU for EGL to use. */ int SDL_EGL_InitializeOffscreen(_THIS, int device) { void *egl_devices[SDL_EGL_MAX_DEVICES]; EGLint num_egl_devices = 0; const char *egl_device_hint; if (_this->gl_config.driver_loaded != 1) { return SDL_SetError("SDL_EGL_LoadLibraryOnly() has not been called or has failed."); } /* Check for all extensions that are optional until used and fail if any is missing */ if (_this->egl_data->eglQueryDevicesEXT == NULL) { return SDL_SetError("eglQueryDevicesEXT is missing (EXT_device_enumeration not supported by the drivers?)"); } if (_this->egl_data->eglGetPlatformDisplayEXT == NULL) { return SDL_SetError("eglGetPlatformDisplayEXT is missing (EXT_platform_base not supported by the drivers?)"); } if (_this->egl_data->eglQueryDevicesEXT(SDL_EGL_MAX_DEVICES, egl_devices, &num_egl_devices) != EGL_TRUE) { return SDL_SetError("eglQueryDevicesEXT() failed"); } egl_device_hint = SDL_GetHint("SDL_HINT_EGL_DEVICE"); if (egl_device_hint) { device = SDL_atoi(egl_device_hint); if (device >= num_egl_devices) { return SDL_SetError("Invalid EGL device is requested."); } _this->egl_data->egl_display = _this->egl_data->eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, egl_devices[device], NULL); if (_this->egl_data->egl_display == EGL_NO_DISPLAY) { return SDL_SetError("eglGetPlatformDisplayEXT() failed."); } if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) { return SDL_SetError("Could not initialize EGL"); } } else { int i; SDL_bool found = SDL_FALSE; EGLDisplay attempted_egl_display; /* If no hint is provided lets look for the first device/display that will allow us to eglInit */ for (i = 0; i < num_egl_devices; i++) { attempted_egl_display = _this->egl_data->eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, egl_devices[i], NULL); if (attempted_egl_display == EGL_NO_DISPLAY) { continue; } if (_this->egl_data->eglInitialize(attempted_egl_display, NULL, NULL) != EGL_TRUE) { _this->egl_data->eglTerminate(attempted_egl_display); continue; } /* We did not fail, we'll pick this one! */ _this->egl_data->egl_display = attempted_egl_display; found = SDL_TRUE; break; } if (!found) { return SDL_SetError("Could not find a valid EGL device to initialize"); } } /* Get the EGL version with a valid egl_display, for EGL <= 1.4 */ SDL_EGL_GetVersion(_this); _this->egl_data->is_offscreen = 1; return 0; } void SDL_EGL_SetRequiredVisualId(_THIS, int visual_id) { _this->egl_data->egl_required_visual_id=visual_id; } #ifdef DUMP_EGL_CONFIG #define ATTRIBUTE(_attr) { _attr, #_attr } typedef struct { EGLint attribute; char const* name; } Attribute; Attribute attributes[] = { ATTRIBUTE( EGL_BUFFER_SIZE ), ATTRIBUTE( EGL_ALPHA_SIZE ), ATTRIBUTE( EGL_BLUE_SIZE ), ATTRIBUTE( EGL_GREEN_SIZE ), ATTRIBUTE( EGL_RED_SIZE ), ATTRIBUTE( EGL_DEPTH_SIZE ), ATTRIBUTE( EGL_STENCIL_SIZE ), ATTRIBUTE( EGL_CONFIG_CAVEAT ), ATTRIBUTE( EGL_CONFIG_ID ), ATTRIBUTE( EGL_LEVEL ), ATTRIBUTE( EGL_MAX_PBUFFER_HEIGHT ), ATTRIBUTE( EGL_MAX_PBUFFER_WIDTH ), ATTRIBUTE( EGL_MAX_PBUFFER_PIXELS ), ATTRIBUTE( EGL_NATIVE_RENDERABLE ), ATTRIBUTE( EGL_NATIVE_VISUAL_ID ), ATTRIBUTE( EGL_NATIVE_VISUAL_TYPE ), ATTRIBUTE( EGL_SAMPLES ), ATTRIBUTE( EGL_SAMPLE_BUFFERS ), ATTRIBUTE( EGL_SURFACE_TYPE ), ATTRIBUTE( EGL_TRANSPARENT_TYPE ), ATTRIBUTE( EGL_TRANSPARENT_BLUE_VALUE ), ATTRIBUTE( EGL_TRANSPARENT_GREEN_VALUE ), ATTRIBUTE( EGL_TRANSPARENT_RED_VALUE ), ATTRIBUTE( EGL_BIND_TO_TEXTURE_RGB ), ATTRIBUTE( EGL_BIND_TO_TEXTURE_RGBA ), ATTRIBUTE( EGL_MIN_SWAP_INTERVAL ), ATTRIBUTE( EGL_MAX_SWAP_INTERVAL ), ATTRIBUTE( EGL_LUMINANCE_SIZE ), ATTRIBUTE( EGL_ALPHA_MASK_SIZE ), ATTRIBUTE( EGL_COLOR_BUFFER_TYPE ), ATTRIBUTE( EGL_RENDERABLE_TYPE ), ATTRIBUTE( EGL_MATCH_NATIVE_PIXMAP ), ATTRIBUTE( EGL_CONFORMANT ), }; static void dumpconfig(_THIS, EGLConfig config) { int attr; for (attr = 0 ; attr<sizeof(attributes)/sizeof(Attribute) ; attr++) { EGLint value; _this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display, config, attributes[attr].attribute, &value); SDL_Log("\t%-32s: %10d (0x%08x)\n", attributes[attr].name, value, value); } } #endif /* DUMP_EGL_CONFIG */ int SDL_EGL_ChooseConfig(_THIS) { /* 64 seems nice. */ EGLint attribs[64]; EGLint found_configs = 0, value; /* 128 seems even nicer here */ EGLConfig configs[128]; SDL_bool has_matching_format = SDL_FALSE; int i, j, best_bitdiff = -1, bitdiff; if (!_this->egl_data) { /* The EGL library wasn't loaded, SDL_GetError() should have info */ return -1; } /* Get a valid EGL configuration */ i = 0; attribs[i++] = EGL_RED_SIZE; attribs[i++] = _this->gl_config.red_size; attribs[i++] = EGL_GREEN_SIZE; attribs[i++] = _this->gl_config.green_size; attribs[i++] = EGL_BLUE_SIZE; attribs[i++] = _this->gl_config.blue_size; if (_this->gl_config.alpha_size) { attribs[i++] = EGL_ALPHA_SIZE; attribs[i++] = _this->gl_config.alpha_size; } if (_this->gl_config.buffer_size) { attribs[i++] = EGL_BUFFER_SIZE; attribs[i++] = _this->gl_config.buffer_size; } attribs[i++] = EGL_DEPTH_SIZE; attribs[i++] = _this->gl_config.depth_size; if (_this->gl_config.stencil_size) { attribs[i++] = EGL_STENCIL_SIZE; attribs[i++] = _this->gl_config.stencil_size; } if (_this->gl_config.multisamplebuffers) { attribs[i++] = EGL_SAMPLE_BUFFERS; attribs[i++] = _this->gl_config.multisamplebuffers; } if (_this->gl_config.multisamplesamples) { attribs[i++] = EGL_SAMPLES; attribs[i++] = _this->gl_config.multisamplesamples; } if (_this->egl_data->is_offscreen) { attribs[i++] = EGL_SURFACE_TYPE; attribs[i++] = EGL_PBUFFER_BIT; } attribs[i++] = EGL_RENDERABLE_TYPE; if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { #ifdef EGL_KHR_create_context if (_this->gl_config.major_version >= 3 && SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context")) { attribs[i++] = EGL_OPENGL_ES3_BIT_KHR; } else #endif if (_this->gl_config.major_version >= 2) { attribs[i++] = EGL_OPENGL_ES2_BIT; } else { attribs[i++] = EGL_OPENGL_ES_BIT; } _this->egl_data->eglBindAPI(EGL_OPENGL_ES_API); } else { attribs[i++] = EGL_OPENGL_BIT; _this->egl_data->eglBindAPI(EGL_OPENGL_API); } if (_this->egl_data->egl_surfacetype) { attribs[i++] = EGL_SURFACE_TYPE; attribs[i++] = _this->egl_data->egl_surfacetype; } attribs[i++] = EGL_NONE; if (_this->egl_data->eglChooseConfig(_this->egl_data->egl_display, attribs, configs, SDL_arraysize(configs), &found_configs) == EGL_FALSE || found_configs == 0) { return SDL_EGL_SetError("Couldn't find matching EGL config", "eglChooseConfig"); } /* first ensure that a found config has a matching format, or the function will fall through. */ for (i = 0; i < found_configs; i++ ) { if (_this->egl_data->egl_required_visual_id) { EGLint format; _this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display, configs[i], EGL_NATIVE_VISUAL_ID, &format); if (_this->egl_data->egl_required_visual_id == format) has_matching_format = SDL_TRUE; } } /* eglChooseConfig returns a number of configurations that match or exceed the requested attribs. */ /* From those, we select the one that matches our requirements more closely via a makeshift algorithm */ for (i = 0; i < found_configs; i++ ) { if (has_matching_format && _this->egl_data->egl_required_visual_id) { EGLint format; _this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display, configs[i], EGL_NATIVE_VISUAL_ID, &format); if (_this->egl_data->egl_required_visual_id != format) continue; } bitdiff = 0; for (j = 0; j < SDL_arraysize(attribs) - 1; j += 2) { if (attribs[j] == EGL_NONE) { break; } if ( attribs[j+1] != EGL_DONT_CARE && ( attribs[j] == EGL_RED_SIZE || attribs[j] == EGL_GREEN_SIZE || attribs[j] == EGL_BLUE_SIZE || attribs[j] == EGL_ALPHA_SIZE || attribs[j] == EGL_DEPTH_SIZE || attribs[j] == EGL_STENCIL_SIZE)) { _this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display, configs[i], attribs[j], &value); bitdiff += value - attribs[j + 1]; /* value is always >= attrib */ } } if (bitdiff < best_bitdiff || best_bitdiff == -1) { _this->egl_data->egl_config = configs[i]; best_bitdiff = bitdiff; } if (bitdiff == 0) { break; /* we found an exact match! */ } } #ifdef DUMP_EGL_CONFIG dumpconfig(_this, _this->egl_data->egl_config); #endif return 0; } SDL_GLContext SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface) { /* max 14 values plus terminator. */ EGLint attribs[15]; int attr = 0; EGLContext egl_context, share_context = EGL_NO_CONTEXT; EGLint profile_mask = _this->gl_config.profile_mask; EGLint major_version = _this->gl_config.major_version; EGLint minor_version = _this->gl_config.minor_version; SDL_bool profile_es = (profile_mask == SDL_GL_CONTEXT_PROFILE_ES); if (!_this->egl_data) { /* The EGL library wasn't loaded, SDL_GetError() should have info */ return NULL; } if (_this->gl_config.share_with_current_context) { share_context = (EGLContext)SDL_GL_GetCurrentContext(); } #if SDL_VIDEO_DRIVER_ANDROID if ((_this->gl_config.flags & SDL_GL_CONTEXT_DEBUG_FLAG) != 0) { /* If SDL_GL_CONTEXT_DEBUG_FLAG is set but EGL_KHR_debug unsupported, unset. * This is required because some Android devices like to complain about it * by "silently" failing, logging a hint which could be easily overlooked: * E/libEGL (26984): validate_display:255 error 3008 (EGL_BAD_DISPLAY) * The following explicitly checks for EGL_KHR_debug before EGL 1.5 */ int egl_version_major = _this->egl_data->egl_version_major; int egl_version_minor = _this->egl_data->egl_version_minor; if (((egl_version_major < 1) || (egl_version_major == 1 && egl_version_minor < 5)) && !SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_debug")) { /* SDL profile bits match EGL profile bits. */ _this->gl_config.flags &= ~SDL_GL_CONTEXT_DEBUG_FLAG; } } #endif /* Set the context version and other attributes. */ if ((major_version < 3 || (minor_version == 0 && profile_es)) && _this->gl_config.flags == 0 && (profile_mask == 0 || profile_es)) { /* Create a context without using EGL_KHR_create_context attribs. * When creating a GLES context without EGL_KHR_create_context we can * only specify the major version. When creating a desktop GL context * we can't specify any version, so we only try in that case when the * version is less than 3.0 (matches SDL's GLX/WGL behavior.) */ if (profile_es) { attribs[attr++] = EGL_CONTEXT_CLIENT_VERSION; attribs[attr++] = SDL_max(major_version, 1); } } else { #ifdef EGL_KHR_create_context /* The Major/minor version, context profiles, and context flags can * only be specified when this extension is available. */ if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context")) { attribs[attr++] = EGL_CONTEXT_MAJOR_VERSION_KHR; attribs[attr++] = major_version; attribs[attr++] = EGL_CONTEXT_MINOR_VERSION_KHR; attribs[attr++] = minor_version; /* SDL profile bits match EGL profile bits. */ if (profile_mask != 0 && profile_mask != SDL_GL_CONTEXT_PROFILE_ES) { attribs[attr++] = EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR; attribs[attr++] = profile_mask; } /* SDL flags match EGL flags. */ if (_this->gl_config.flags != 0) { attribs[attr++] = EGL_CONTEXT_FLAGS_KHR; attribs[attr++] = _this->gl_config.flags; } } else #endif /* EGL_KHR_create_context */ { SDL_SetError("Could not create EGL context (context attributes are not supported)"); return NULL; } } if (_this->gl_config.no_error) { #ifdef EGL_KHR_create_context_no_error if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context_no_error")) { attribs[attr++] = EGL_CONTEXT_OPENGL_NO_ERROR_KHR; attribs[attr++] = _this->gl_config.no_error; } else #endif { SDL_SetError("EGL implementation does not support no_error contexts"); return NULL; } } attribs[attr++] = EGL_NONE; /* Bind the API */ if (profile_es) { _this->egl_data->eglBindAPI(EGL_OPENGL_ES_API); } else { _this->egl_data->eglBindAPI(EGL_OPENGL_API); } egl_context = _this->egl_data->eglCreateContext(_this->egl_data->egl_display, _this->egl_data->egl_config, share_context, attribs); if (egl_context == EGL_NO_CONTEXT) { SDL_EGL_SetError("Could not create EGL context", "eglCreateContext"); return NULL; } _this->egl_data->egl_swapinterval = 0; if (SDL_EGL_MakeCurrent(_this, egl_surface, egl_context) < 0) { /* Save the SDL error set by SDL_EGL_MakeCurrent */ char errorText[1024]; SDL_strlcpy(errorText, SDL_GetError(), SDL_arraysize(errorText)); /* Delete the context, which may alter the value returned by SDL_GetError() */ SDL_EGL_DeleteContext(_this, egl_context); /* Restore the SDL error */ SDL_SetError("%s", errorText); return NULL; } /* Check whether making contexts current without a surface is supported. * First condition: EGL must support it. That's the case for EGL 1.5 * or later, or if the EGL_KHR_surfaceless_context extension is present. */ if ((_this->egl_data->egl_version_major > 1) || ((_this->egl_data->egl_version_major == 1) && (_this->egl_data->egl_version_minor >= 5)) || SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_surfaceless_context")) { /* Secondary condition: The client API must support it. */ if (profile_es) { /* On OpenGL ES, the GL_OES_surfaceless_context extension must be * present. */ if (SDL_GL_ExtensionSupported("GL_OES_surfaceless_context")) { _this->gl_allow_no_surface = SDL_TRUE; } #if SDL_VIDEO_OPENGL } else { /* Desktop OpenGL supports it by default from version 3.0 on. */ void (APIENTRY * glGetIntegervFunc) (GLenum pname, GLint * params); glGetIntegervFunc = SDL_GL_GetProcAddress("glGetIntegerv"); if (glGetIntegervFunc) { GLint v = 0; glGetIntegervFunc(GL_MAJOR_VERSION, &v); if (v >= 3) { _this->gl_allow_no_surface = SDL_TRUE; } } #endif } } return (SDL_GLContext) egl_context; } int SDL_EGL_MakeCurrent(_THIS, EGLSurface egl_surface, SDL_GLContext context) { EGLContext egl_context = (EGLContext) context; if (!_this->egl_data) { return SDL_SetError("OpenGL not initialized"); } /* The android emulator crashes badly if you try to eglMakeCurrent * with a valid context and invalid surface, so we have to check for both here. */ if (!egl_context || (!egl_surface && !_this->gl_allow_no_surface)) { _this->egl_data->eglMakeCurrent(_this->egl_data->egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } else { if (!_this->egl_data->eglMakeCurrent(_this->egl_data->egl_display, egl_surface, egl_surface, egl_context)) { return SDL_EGL_SetError("Unable to make EGL context current", "eglMakeCurrent"); } } return 0; } int SDL_EGL_SetSwapInterval(_THIS, int interval) { EGLBoolean status; if (!_this->egl_data) { return SDL_SetError("EGL not initialized"); } status = _this->egl_data->eglSwapInterval(_this->egl_data->egl_display, interval); if (status == EGL_TRUE) { _this->egl_data->egl_swapinterval = interval; return 0; } return SDL_EGL_SetError("Unable to set the EGL swap interval", "eglSwapInterval"); } int SDL_EGL_GetSwapInterval(_THIS) { if (!_this->egl_data) { SDL_SetError("EGL not initialized"); return 0; } return _this->egl_data->egl_swapinterval; } int SDL_EGL_SwapBuffers(_THIS, EGLSurface egl_surface) { if (!_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, egl_surface)) { return SDL_EGL_SetError("unable to show color buffer in an OS-native window", "eglSwapBuffers"); } return 0; } void SDL_EGL_DeleteContext(_THIS, SDL_GLContext context) { EGLContext egl_context = (EGLContext) context; /* Clean up GLES and EGL */ if (!_this->egl_data) { return; } if (egl_context != NULL && egl_context != EGL_NO_CONTEXT) { _this->egl_data->eglDestroyContext(_this->egl_data->egl_display, egl_context); } } EGLSurface * SDL_EGL_CreateSurface(_THIS, NativeWindowType nw) { /* max 2 values plus terminator. */ EGLint attribs[3]; int attr = 0; EGLSurface * surface; if (SDL_EGL_ChooseConfig(_this) != 0) { return EGL_NO_SURFACE; } #if SDL_VIDEO_DRIVER_ANDROID { /* Android docs recommend doing this! * Ref: http://developer.android.com/reference/android/app/NativeActivity.html */ EGLint format; _this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display, _this->egl_data->egl_config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(nw, 0, 0, format); /* Update SurfaceView holder format. * May triggers a sequence surfaceDestroyed(), surfaceCreated(), surfaceChanged(). */ Android_JNI_SetSurfaceViewFormat(format); } #endif if (_this->gl_config.framebuffer_srgb_capable) { #ifdef EGL_KHR_gl_colorspace if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_gl_colorspace")) { attribs[attr++] = EGL_GL_COLORSPACE_KHR; attribs[attr++] = EGL_GL_COLORSPACE_SRGB_KHR; } else #endif { SDL_SetError("EGL implementation does not support sRGB system framebuffers"); return EGL_NO_SURFACE; } } attribs[attr++] = EGL_NONE; surface = _this->egl_data->eglCreateWindowSurface( _this->egl_data->egl_display, _this->egl_data->egl_config, nw, &attribs[0]); if (surface == EGL_NO_SURFACE) { SDL_EGL_SetError("unable to create an EGL window surface", "eglCreateWindowSurface"); } return surface; } EGLSurface SDL_EGL_CreateOffscreenSurface(_THIS, int width, int height) { EGLint attributes[] = { EGL_WIDTH, width, EGL_HEIGHT, height, EGL_NONE }; if (SDL_EGL_ChooseConfig(_this) != 0) { return EGL_NO_SURFACE; } return _this->egl_data->eglCreatePbufferSurface( _this->egl_data->egl_display, _this->egl_data->egl_config, attributes); } void SDL_EGL_DestroySurface(_THIS, EGLSurface egl_surface) { if (!_this->egl_data) { return; } if (egl_surface != EGL_NO_SURFACE) { _this->egl_data->eglDestroySurface(_this->egl_data->egl_display, egl_surface); } } #endif /* SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_egl.c
C
apache-2.0
40,304
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #ifndef SDL_egl_h_ #define SDL_egl_h_ #if SDL_VIDEO_OPENGL_EGL #include "SDL_egl.h" #include "SDL_sysvideo.h" #define SDL_EGL_MAX_DEVICES 8 typedef struct SDL_EGL_VideoData { void *egl_dll_handle, *dll_handle; EGLDisplay egl_display; EGLConfig egl_config; int egl_swapinterval; int egl_surfacetype; int egl_version_major, egl_version_minor; EGLint egl_required_visual_id; EGLDisplay(EGLAPIENTRY *eglGetDisplay) (NativeDisplayType display); EGLDisplay(EGLAPIENTRY *eglGetPlatformDisplay) (EGLenum platform, void *native_display, const EGLint *attrib_list); EGLDisplay(EGLAPIENTRY *eglGetPlatformDisplayEXT) (EGLenum platform, void *native_display, const EGLint *attrib_list); EGLBoolean(EGLAPIENTRY *eglInitialize) (EGLDisplay dpy, EGLint * major, EGLint * minor); EGLBoolean(EGLAPIENTRY *eglTerminate) (EGLDisplay dpy); void *(EGLAPIENTRY *eglGetProcAddress) (const char * procName); EGLBoolean(EGLAPIENTRY *eglChooseConfig) (EGLDisplay dpy, const EGLint * attrib_list, EGLConfig * configs, EGLint config_size, EGLint * num_config); EGLContext(EGLAPIENTRY *eglCreateContext) (EGLDisplay dpy, EGLConfig config, EGLContext share_list, const EGLint * attrib_list); EGLBoolean(EGLAPIENTRY *eglDestroyContext) (EGLDisplay dpy, EGLContext ctx); EGLSurface(EGLAPIENTRY *eglCreatePbufferSurface)(EGLDisplay dpy, EGLConfig config, EGLint const* attrib_list); EGLSurface(EGLAPIENTRY *eglCreateWindowSurface) (EGLDisplay dpy, EGLConfig config, NativeWindowType window, const EGLint * attrib_list); EGLBoolean(EGLAPIENTRY *eglDestroySurface) (EGLDisplay dpy, EGLSurface surface); EGLBoolean(EGLAPIENTRY *eglMakeCurrent) (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); EGLBoolean(EGLAPIENTRY *eglSwapBuffers) (EGLDisplay dpy, EGLSurface draw); EGLBoolean(EGLAPIENTRY *eglSwapInterval) (EGLDisplay dpy, EGLint interval); const char *(EGLAPIENTRY *eglQueryString) (EGLDisplay dpy, EGLint name); EGLenum(EGLAPIENTRY *eglQueryAPI)(void); EGLBoolean(EGLAPIENTRY *eglGetConfigAttrib) (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint * value); EGLBoolean(EGLAPIENTRY *eglWaitNative) (EGLint engine); EGLBoolean(EGLAPIENTRY *eglWaitGL)(void); EGLBoolean(EGLAPIENTRY *eglBindAPI)(EGLenum); EGLint(EGLAPIENTRY *eglGetError)(void); EGLBoolean(EGLAPIENTRY *eglQueryDevicesEXT)(EGLint max_devices, void **devices, EGLint *num_devices); /* whether EGL display was offscreen */ int is_offscreen; } SDL_EGL_VideoData; /* OpenGLES functions */ extern int SDL_EGL_GetAttribute(_THIS, SDL_GLattr attrib, int *value); /* SDL_EGL_LoadLibrary can get a display for a specific platform (EGL_PLATFORM_*) * or, if 0 is passed, let the implementation decide. */ extern int SDL_EGL_LoadLibraryOnly(_THIS, const char *path); extern int SDL_EGL_LoadLibrary(_THIS, const char *path, NativeDisplayType native_display, EGLenum platform); extern void *SDL_EGL_GetProcAddress(_THIS, const char *proc); extern void SDL_EGL_UnloadLibrary(_THIS); extern void SDL_EGL_SetRequiredVisualId(_THIS, int visual_id); extern int SDL_EGL_ChooseConfig(_THIS); extern int SDL_EGL_SetSwapInterval(_THIS, int interval); extern int SDL_EGL_GetSwapInterval(_THIS); extern void SDL_EGL_DeleteContext(_THIS, SDL_GLContext context); extern EGLSurface *SDL_EGL_CreateSurface(_THIS, NativeWindowType nw); extern void SDL_EGL_DestroySurface(_THIS, EGLSurface egl_surface); extern EGLSurface SDL_EGL_CreateOffscreenSurface(_THIS, int width, int height); /* Assumes that LoadLibraryOnly() has succeeded */ extern int SDL_EGL_InitializeOffscreen(_THIS, int device); /* These need to be wrapped to get the surface for the window by the platform GLES implementation */ extern SDL_GLContext SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface); extern int SDL_EGL_MakeCurrent(_THIS, EGLSurface egl_surface, SDL_GLContext context); extern int SDL_EGL_SwapBuffers(_THIS, EGLSurface egl_surface); /* SDL Error-reporting */ extern int SDL_EGL_SetErrorEx(const char * message, const char * eglFunctionName, EGLint eglErrorCode); #define SDL_EGL_SetError(message, eglFunctionName) SDL_EGL_SetErrorEx(message, eglFunctionName, _this->egl_data->eglGetError()) /* A few of useful macros */ #define SDL_EGL_SwapWindow_impl(BACKEND) int \ BACKEND ## _GLES_SwapWindow(_THIS, SDL_Window * window) \ {\ return SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface);\ } #define SDL_EGL_MakeCurrent_impl(BACKEND) int \ BACKEND ## _GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) \ {\ return SDL_EGL_MakeCurrent(_this, window ? ((SDL_WindowData *) window->driverdata)->egl_surface : EGL_NO_SURFACE, context);\ } #define SDL_EGL_CreateContext_impl(BACKEND) SDL_GLContext \ BACKEND ## _GLES_CreateContext(_THIS, SDL_Window * window) \ {\ return SDL_EGL_CreateContext(_this, ((SDL_WindowData *) window->driverdata)->egl_surface);\ } #endif /* SDL_VIDEO_OPENGL_EGL */ #endif /* SDL_egl_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_egl_c.h
C
apache-2.0
6,813
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL_video.h" #include "SDL_blit.h" #include "SDL_cpuinfo.h" #ifdef __SSE__ /* *INDENT-OFF* */ #ifdef _MSC_VER #define SSE_BEGIN \ __m128 c128; \ c128.m128_u32[0] = color; \ c128.m128_u32[1] = color; \ c128.m128_u32[2] = color; \ c128.m128_u32[3] = color; #else #define SSE_BEGIN \ __m128 c128; \ DECLARE_ALIGNED(Uint32, cccc[4], 16); \ cccc[0] = color; \ cccc[1] = color; \ cccc[2] = color; \ cccc[3] = color; \ c128 = *(__m128 *)cccc; #endif #define SSE_WORK \ for (i = n / 64; i--;) { \ _mm_stream_ps((float *)(p+0), c128); \ _mm_stream_ps((float *)(p+16), c128); \ _mm_stream_ps((float *)(p+32), c128); \ _mm_stream_ps((float *)(p+48), c128); \ p += 64; \ } #define SSE_END #define DEFINE_SSE_FILLRECT(bpp, type) \ static void \ SDL_FillRect##bpp##SSE(Uint8 *pixels, int pitch, Uint32 color, int w, int h) \ { \ int i, n; \ Uint8 *p = NULL; \ \ SSE_BEGIN; \ \ while (h--) { \ n = w * bpp; \ p = pixels; \ \ if (n > 63) { \ int adjust = 16 - ((uintptr_t)p & 15); \ if (adjust < 16) { \ n -= adjust; \ adjust /= bpp; \ while (adjust--) { \ *((type *)p) = (type)color; \ p += bpp; \ } \ } \ SSE_WORK; \ } \ if (n & 63) { \ int remainder = (n & 63); \ remainder /= bpp; \ while (remainder--) { \ *((type *)p) = (type)color; \ p += bpp; \ } \ } \ pixels += pitch; \ } \ \ SSE_END; \ } static void SDL_FillRect1SSE(Uint8 *pixels, int pitch, Uint32 color, int w, int h) { int i, n; SSE_BEGIN; while (h--) { Uint8 *p = pixels; n = w; if (n > 63) { int adjust = 16 - ((uintptr_t)p & 15); if (adjust) { n -= adjust; SDL_memset(p, color, adjust); p += adjust; } SSE_WORK; } if (n & 63) { int remainder = (n & 63); SDL_memset(p, color, remainder); } pixels += pitch; } SSE_END; } /* DEFINE_SSE_FILLRECT(1, Uint8) */ DEFINE_SSE_FILLRECT(2, Uint16) DEFINE_SSE_FILLRECT(4, Uint32) /* *INDENT-ON* */ #endif /* __SSE__ */ static void SDL_FillRect1(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { int n; Uint8 *p = NULL; while (h--) { n = w; p = pixels; if (n > 3) { switch ((uintptr_t) p & 3) { case 1: *p++ = (Uint8) color; --n; /* fallthrough */ case 2: *p++ = (Uint8) color; --n; /* fallthrough */ case 3: *p++ = (Uint8) color; --n; /* fallthrough */ } SDL_memset4(p, color, (n >> 2)); } if (n & 3) { p += (n & ~3); switch (n & 3) { case 3: *p++ = (Uint8) color; /* fallthrough */ case 2: *p++ = (Uint8) color; /* fallthrough */ case 1: *p++ = (Uint8) color; /* fallthrough */ } } pixels += pitch; } } static void SDL_FillRect2(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { int n; Uint16 *p = NULL; while (h--) { n = w; p = (Uint16 *) pixels; if (n > 1) { if ((uintptr_t) p & 2) { *p++ = (Uint16) color; --n; } SDL_memset4(p, color, (n >> 1)); } if (n & 1) { p[n - 1] = (Uint16) color; } pixels += pitch; } } static void SDL_FillRect3(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { #if SDL_BYTEORDER == SDL_LIL_ENDIAN Uint8 b1 = (Uint8) (color & 0xFF); Uint8 b2 = (Uint8) ((color >> 8) & 0xFF); Uint8 b3 = (Uint8) ((color >> 16) & 0xFF); #elif SDL_BYTEORDER == SDL_BIG_ENDIAN Uint8 b1 = (Uint8) ((color >> 16) & 0xFF); Uint8 b2 = (Uint8) ((color >> 8) & 0xFF); Uint8 b3 = (Uint8) (color & 0xFF); #endif int n; Uint8 *p = NULL; while (h--) { n = w; p = pixels; while (n--) { *p++ = b1; *p++ = b2; *p++ = b3; } pixels += pitch; } } static void SDL_FillRect4(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { while (h--) { SDL_memset4(pixels, color, w); pixels += pitch; } } /* * This function performs a fast fill of the given rectangle with 'color' */ int SDL_FillRect(SDL_Surface * dst, const SDL_Rect * rect, Uint32 color) { if (!dst) { return SDL_SetError("Passed NULL destination surface"); } /* If 'rect' == NULL, then fill the whole surface */ if (!rect) { rect = &dst->clip_rect; /* Don't attempt to fill if the surface's clip_rect is empty */ if (SDL_RectEmpty(rect)) { return 0; } } return SDL_FillRects(dst, rect, 1, color); } #if SDL_ARM_NEON_BLITTERS void FillRect8ARMNEONAsm(int32_t w, int32_t h, uint8_t *dst, int32_t dst_stride, uint8_t src); void FillRect16ARMNEONAsm(int32_t w, int32_t h, uint16_t *dst, int32_t dst_stride, uint16_t src); void FillRect32ARMNEONAsm(int32_t w, int32_t h, uint32_t *dst, int32_t dst_stride, uint32_t src); static void fill_8_neon(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { FillRect8ARMNEONAsm(w, h, (uint8_t *) pixels, pitch >> 0, color); return; } static void fill_16_neon(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { FillRect16ARMNEONAsm(w, h, (uint16_t *) pixels, pitch >> 1, color); return; } static void fill_32_neon(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { FillRect32ARMNEONAsm(w, h, (uint32_t *) pixels, pitch >> 2, color); return; } #endif #if SDL_ARM_SIMD_BLITTERS void FillRect8ARMSIMDAsm(int32_t w, int32_t h, uint8_t *dst, int32_t dst_stride, uint8_t src); void FillRect16ARMSIMDAsm(int32_t w, int32_t h, uint16_t *dst, int32_t dst_stride, uint16_t src); void FillRect32ARMSIMDAsm(int32_t w, int32_t h, uint32_t *dst, int32_t dst_stride, uint32_t src); static void fill_8_simd(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { FillRect8ARMSIMDAsm(w, h, (uint8_t *) pixels, pitch >> 0, color); return; } static void fill_16_simd(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { FillRect16ARMSIMDAsm(w, h, (uint16_t *) pixels, pitch >> 1, color); return; } static void fill_32_simd(Uint8 * pixels, int pitch, Uint32 color, int w, int h) { FillRect32ARMSIMDAsm(w, h, (uint32_t *) pixels, pitch >> 2, color); return; } #endif int SDL_FillRects(SDL_Surface * dst, const SDL_Rect * rects, int count, Uint32 color) { SDL_Rect clipped; Uint8 *pixels; const SDL_Rect* rect; void (*fill_function)(Uint8 * pixels, int pitch, Uint32 color, int w, int h) = NULL; int i; if (!dst) { return SDL_SetError("Passed NULL destination surface"); } /* This function doesn't work on surfaces < 8 bpp */ if (dst->format->BitsPerPixel < 8) { return SDL_SetError("SDL_FillRect(): Unsupported surface format"); } /* Perform software fill */ if (!dst->pixels) { return SDL_SetError("SDL_FillRect(): You must lock the surface"); } if (!rects) { return SDL_SetError("SDL_FillRects() passed NULL rects"); } #if SDL_ARM_NEON_BLITTERS if (SDL_HasNEON() && dst->format->BytesPerPixel != 3 && fill_function == NULL) { switch (dst->format->BytesPerPixel) { case 1: fill_function = fill_8_neon; break; case 2: fill_function = fill_16_neon; break; case 4: fill_function = fill_32_neon; break; } } #endif #if SDL_ARM_SIMD_BLITTERS if (SDL_HasARMSIMD() && dst->format->BytesPerPixel != 3 && fill_function == NULL) { switch (dst->format->BytesPerPixel) { case 1: fill_function = fill_8_simd; break; case 2: fill_function = fill_16_simd; break; case 4: fill_function = fill_32_simd; break; } } #endif if (fill_function == NULL) { switch (dst->format->BytesPerPixel) { case 1: { color |= (color << 8); color |= (color << 16); #ifdef __SSE__ if (SDL_HasSSE()) { fill_function = SDL_FillRect1SSE; break; } #endif fill_function = SDL_FillRect1; break; } case 2: { color |= (color << 16); #ifdef __SSE__ if (SDL_HasSSE()) { fill_function = SDL_FillRect2SSE; break; } #endif fill_function = SDL_FillRect2; break; } case 3: /* 24-bit RGB is a slow path, at least for now. */ { fill_function = SDL_FillRect3; break; } case 4: { #ifdef __SSE__ if (SDL_HasSSE()) { fill_function = SDL_FillRect4SSE; break; } #endif fill_function = SDL_FillRect4; break; } default: return SDL_SetError("Unsupported pixel format"); } } for (i = 0; i < count; ++i) { rect = &rects[i]; /* Perform clipping */ if (!SDL_IntersectRect(rect, &dst->clip_rect, &clipped)) { continue; } rect = &clipped; pixels = (Uint8 *) dst->pixels + rect->y * dst->pitch + rect->x * dst->format->BytesPerPixel; fill_function(pixels, dst->pitch, color, rect->w, rect->h); } /* We're done! */ return 0; } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_fillrect.c
C
apache-2.0
11,319
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* General (mostly internal) pixel/color manipulation routines for SDL */ #include "SDL_endian.h" #include "SDL_video.h" #include "SDL_sysvideo.h" #include "SDL_blit.h" #include "SDL_pixels_c.h" #include "SDL_RLEaccel_c.h" /* Lookup tables to expand partial bytes to the full 0..255 range */ static Uint8 lookup_0[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; static Uint8 lookup_1[] = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 255 }; static Uint8 lookup_2[] = { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 85, 89, 93, 97, 101, 105, 109, 113, 117, 121, 125, 129, 133, 137, 141, 145, 149, 153, 157, 161, 165, 170, 174, 178, 182, 186, 190, 194, 198, 202, 206, 210, 214, 218, 222, 226, 230, 234, 238, 242, 246, 250, 255 }; static Uint8 lookup_3[] = { 0, 8, 16, 24, 32, 41, 49, 57, 65, 74, 82, 90, 98, 106, 115, 123, 131, 139, 148, 156, 164, 172, 180, 189, 197, 205, 213, 222, 230, 238, 246, 255 }; static Uint8 lookup_4[] = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255 }; static Uint8 lookup_5[] = { 0, 36, 72, 109, 145, 182, 218, 255 }; static Uint8 lookup_6[] = { 0, 85, 170, 255 }; static Uint8 lookup_7[] = { 0, 255 }; static Uint8 lookup_8[] = { 255 }; Uint8* SDL_expand_byte[9] = { lookup_0, lookup_1, lookup_2, lookup_3, lookup_4, lookup_5, lookup_6, lookup_7, lookup_8 }; /* Helper functions */ const char* SDL_GetPixelFormatName(Uint32 format) { switch (format) { #define CASE(X) case X: return #X; CASE(SDL_PIXELFORMAT_INDEX1LSB) CASE(SDL_PIXELFORMAT_INDEX1MSB) CASE(SDL_PIXELFORMAT_INDEX4LSB) CASE(SDL_PIXELFORMAT_INDEX4MSB) CASE(SDL_PIXELFORMAT_INDEX8) CASE(SDL_PIXELFORMAT_RGB332) CASE(SDL_PIXELFORMAT_RGB444) CASE(SDL_PIXELFORMAT_BGR444) CASE(SDL_PIXELFORMAT_RGB555) CASE(SDL_PIXELFORMAT_BGR555) CASE(SDL_PIXELFORMAT_ARGB4444) CASE(SDL_PIXELFORMAT_RGBA4444) CASE(SDL_PIXELFORMAT_ABGR4444) CASE(SDL_PIXELFORMAT_BGRA4444) CASE(SDL_PIXELFORMAT_ARGB1555) CASE(SDL_PIXELFORMAT_RGBA5551) CASE(SDL_PIXELFORMAT_ABGR1555) CASE(SDL_PIXELFORMAT_BGRA5551) CASE(SDL_PIXELFORMAT_RGB565) CASE(SDL_PIXELFORMAT_BGR565) CASE(SDL_PIXELFORMAT_RGB24) CASE(SDL_PIXELFORMAT_BGR24) CASE(SDL_PIXELFORMAT_RGB888) CASE(SDL_PIXELFORMAT_RGBX8888) CASE(SDL_PIXELFORMAT_BGR888) CASE(SDL_PIXELFORMAT_BGRX8888) CASE(SDL_PIXELFORMAT_ARGB8888) CASE(SDL_PIXELFORMAT_RGBA8888) CASE(SDL_PIXELFORMAT_ABGR8888) CASE(SDL_PIXELFORMAT_BGRA8888) CASE(SDL_PIXELFORMAT_ARGB2101010) CASE(SDL_PIXELFORMAT_YV12) CASE(SDL_PIXELFORMAT_IYUV) CASE(SDL_PIXELFORMAT_YUY2) CASE(SDL_PIXELFORMAT_UYVY) CASE(SDL_PIXELFORMAT_YVYU) CASE(SDL_PIXELFORMAT_NV12) CASE(SDL_PIXELFORMAT_NV21) #undef CASE default: return "SDL_PIXELFORMAT_UNKNOWN"; } } SDL_bool SDL_PixelFormatEnumToMasks(Uint32 format, int *bpp, Uint32 * Rmask, Uint32 * Gmask, Uint32 * Bmask, Uint32 * Amask) { Uint32 masks[4]; /* This function doesn't work with FourCC pixel formats */ if (SDL_ISPIXELFORMAT_FOURCC(format)) { SDL_SetError("FOURCC pixel formats are not supported"); return SDL_FALSE; } /* Initialize the values here */ if (SDL_BYTESPERPIXEL(format) <= 2) { *bpp = SDL_BITSPERPIXEL(format); } else { *bpp = SDL_BYTESPERPIXEL(format) * 8; } *Rmask = *Gmask = *Bmask = *Amask = 0; if (format == SDL_PIXELFORMAT_RGB24) { #if SDL_BYTEORDER == SDL_BIG_ENDIAN *Rmask = 0x00FF0000; *Gmask = 0x0000FF00; *Bmask = 0x000000FF; #else *Rmask = 0x000000FF; *Gmask = 0x0000FF00; *Bmask = 0x00FF0000; #endif return SDL_TRUE; } if (format == SDL_PIXELFORMAT_BGR24) { #if SDL_BYTEORDER == SDL_BIG_ENDIAN *Rmask = 0x000000FF; *Gmask = 0x0000FF00; *Bmask = 0x00FF0000; #else *Rmask = 0x00FF0000; *Gmask = 0x0000FF00; *Bmask = 0x000000FF; #endif return SDL_TRUE; } if (SDL_PIXELTYPE(format) != SDL_PIXELTYPE_PACKED8 && SDL_PIXELTYPE(format) != SDL_PIXELTYPE_PACKED16 && SDL_PIXELTYPE(format) != SDL_PIXELTYPE_PACKED32) { /* Not a format that uses masks */ return SDL_TRUE; } switch (SDL_PIXELLAYOUT(format)) { case SDL_PACKEDLAYOUT_332: masks[0] = 0x00000000; masks[1] = 0x000000E0; masks[2] = 0x0000001C; masks[3] = 0x00000003; break; case SDL_PACKEDLAYOUT_4444: masks[0] = 0x0000F000; masks[1] = 0x00000F00; masks[2] = 0x000000F0; masks[3] = 0x0000000F; break; case SDL_PACKEDLAYOUT_1555: masks[0] = 0x00008000; masks[1] = 0x00007C00; masks[2] = 0x000003E0; masks[3] = 0x0000001F; break; case SDL_PACKEDLAYOUT_5551: masks[0] = 0x0000F800; masks[1] = 0x000007C0; masks[2] = 0x0000003E; masks[3] = 0x00000001; break; case SDL_PACKEDLAYOUT_565: masks[0] = 0x00000000; masks[1] = 0x0000F800; masks[2] = 0x000007E0; masks[3] = 0x0000001F; break; case SDL_PACKEDLAYOUT_8888: masks[0] = 0xFF000000; masks[1] = 0x00FF0000; masks[2] = 0x0000FF00; masks[3] = 0x000000FF; break; case SDL_PACKEDLAYOUT_2101010: masks[0] = 0xC0000000; masks[1] = 0x3FF00000; masks[2] = 0x000FFC00; masks[3] = 0x000003FF; break; case SDL_PACKEDLAYOUT_1010102: masks[0] = 0xFFC00000; masks[1] = 0x003FF000; masks[2] = 0x00000FFC; masks[3] = 0x00000003; break; default: SDL_SetError("Unknown pixel format"); return SDL_FALSE; } switch (SDL_PIXELORDER(format)) { case SDL_PACKEDORDER_XRGB: *Rmask = masks[1]; *Gmask = masks[2]; *Bmask = masks[3]; break; case SDL_PACKEDORDER_RGBX: *Rmask = masks[0]; *Gmask = masks[1]; *Bmask = masks[2]; break; case SDL_PACKEDORDER_ARGB: *Amask = masks[0]; *Rmask = masks[1]; *Gmask = masks[2]; *Bmask = masks[3]; break; case SDL_PACKEDORDER_RGBA: *Rmask = masks[0]; *Gmask = masks[1]; *Bmask = masks[2]; *Amask = masks[3]; break; case SDL_PACKEDORDER_XBGR: *Bmask = masks[1]; *Gmask = masks[2]; *Rmask = masks[3]; break; case SDL_PACKEDORDER_BGRX: *Bmask = masks[0]; *Gmask = masks[1]; *Rmask = masks[2]; break; case SDL_PACKEDORDER_BGRA: *Bmask = masks[0]; *Gmask = masks[1]; *Rmask = masks[2]; *Amask = masks[3]; break; case SDL_PACKEDORDER_ABGR: *Amask = masks[0]; *Bmask = masks[1]; *Gmask = masks[2]; *Rmask = masks[3]; break; default: SDL_SetError("Unknown pixel format"); return SDL_FALSE; } return SDL_TRUE; } Uint32 SDL_MasksToPixelFormatEnum(int bpp, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) { switch (bpp) { case 1: /* SDL defaults to MSB ordering */ return SDL_PIXELFORMAT_INDEX1MSB; case 4: /* SDL defaults to MSB ordering */ return SDL_PIXELFORMAT_INDEX4MSB; case 8: if (Rmask == 0) { return SDL_PIXELFORMAT_INDEX8; } if (Rmask == 0xE0 && Gmask == 0x1C && Bmask == 0x03 && Amask == 0x00) { return SDL_PIXELFORMAT_RGB332; } break; case 12: if (Rmask == 0) { return SDL_PIXELFORMAT_RGB444; } if (Rmask == 0x0F00 && Gmask == 0x00F0 && Bmask == 0x000F && Amask == 0x0000) { return SDL_PIXELFORMAT_RGB444; } if (Rmask == 0x000F && Gmask == 0x00F0 && Bmask == 0x0F00 && Amask == 0x0000) { return SDL_PIXELFORMAT_BGR444; } break; case 15: if (Rmask == 0) { return SDL_PIXELFORMAT_RGB555; } /* fallthrough */ case 16: if (Rmask == 0) { return SDL_PIXELFORMAT_RGB565; } if (Rmask == 0x7C00 && Gmask == 0x03E0 && Bmask == 0x001F && Amask == 0x0000) { return SDL_PIXELFORMAT_RGB555; } if (Rmask == 0x001F && Gmask == 0x03E0 && Bmask == 0x7C00 && Amask == 0x0000) { return SDL_PIXELFORMAT_BGR555; } if (Rmask == 0x0F00 && Gmask == 0x00F0 && Bmask == 0x000F && Amask == 0xF000) { return SDL_PIXELFORMAT_ARGB4444; } if (Rmask == 0xF000 && Gmask == 0x0F00 && Bmask == 0x00F0 && Amask == 0x000F) { return SDL_PIXELFORMAT_RGBA4444; } if (Rmask == 0x000F && Gmask == 0x00F0 && Bmask == 0x0F00 && Amask == 0xF000) { return SDL_PIXELFORMAT_ABGR4444; } if (Rmask == 0x00F0 && Gmask == 0x0F00 && Bmask == 0xF000 && Amask == 0x000F) { return SDL_PIXELFORMAT_BGRA4444; } if (Rmask == 0x7C00 && Gmask == 0x03E0 && Bmask == 0x001F && Amask == 0x8000) { return SDL_PIXELFORMAT_ARGB1555; } if (Rmask == 0xF800 && Gmask == 0x07C0 && Bmask == 0x003E && Amask == 0x0001) { return SDL_PIXELFORMAT_RGBA5551; } if (Rmask == 0x001F && Gmask == 0x03E0 && Bmask == 0x7C00 && Amask == 0x8000) { return SDL_PIXELFORMAT_ABGR1555; } if (Rmask == 0x003E && Gmask == 0x07C0 && Bmask == 0xF800 && Amask == 0x0001) { return SDL_PIXELFORMAT_BGRA5551; } if (Rmask == 0xF800 && Gmask == 0x07E0 && Bmask == 0x001F && Amask == 0x0000) { return SDL_PIXELFORMAT_RGB565; } if (Rmask == 0x001F && Gmask == 0x07E0 && Bmask == 0xF800 && Amask == 0x0000) { return SDL_PIXELFORMAT_BGR565; } if (Rmask == 0x003F && Gmask == 0x07C0 && Bmask == 0xF800 && Amask == 0x0000) { /* Technically this would be BGR556, but Witek says this works in bug 3158 */ return SDL_PIXELFORMAT_RGB565; } break; case 24: switch (Rmask) { case 0: case 0x00FF0000: #if SDL_BYTEORDER == SDL_BIG_ENDIAN return SDL_PIXELFORMAT_RGB24; #else return SDL_PIXELFORMAT_BGR24; #endif case 0x000000FF: #if SDL_BYTEORDER == SDL_BIG_ENDIAN return SDL_PIXELFORMAT_BGR24; #else return SDL_PIXELFORMAT_RGB24; #endif } case 32: if (Rmask == 0) { return SDL_PIXELFORMAT_RGB888; } if (Rmask == 0x00FF0000 && Gmask == 0x0000FF00 && Bmask == 0x000000FF && Amask == 0x00000000) { return SDL_PIXELFORMAT_RGB888; } if (Rmask == 0xFF000000 && Gmask == 0x00FF0000 && Bmask == 0x0000FF00 && Amask == 0x00000000) { return SDL_PIXELFORMAT_RGBX8888; } if (Rmask == 0x000000FF && Gmask == 0x0000FF00 && Bmask == 0x00FF0000 && Amask == 0x00000000) { return SDL_PIXELFORMAT_BGR888; } if (Rmask == 0x0000FF00 && Gmask == 0x00FF0000 && Bmask == 0xFF000000 && Amask == 0x00000000) { return SDL_PIXELFORMAT_BGRX8888; } if (Rmask == 0x00FF0000 && Gmask == 0x0000FF00 && Bmask == 0x000000FF && Amask == 0xFF000000) { return SDL_PIXELFORMAT_ARGB8888; } if (Rmask == 0xFF000000 && Gmask == 0x00FF0000 && Bmask == 0x0000FF00 && Amask == 0x000000FF) { return SDL_PIXELFORMAT_RGBA8888; } if (Rmask == 0x000000FF && Gmask == 0x0000FF00 && Bmask == 0x00FF0000 && Amask == 0xFF000000) { return SDL_PIXELFORMAT_ABGR8888; } if (Rmask == 0x0000FF00 && Gmask == 0x00FF0000 && Bmask == 0xFF000000 && Amask == 0x000000FF) { return SDL_PIXELFORMAT_BGRA8888; } if (Rmask == 0x3FF00000 && Gmask == 0x000FFC00 && Bmask == 0x000003FF && Amask == 0xC0000000) { return SDL_PIXELFORMAT_ARGB2101010; } } return SDL_PIXELFORMAT_UNKNOWN; } static SDL_PixelFormat *formats; static SDL_SpinLock formats_lock = 0; SDL_PixelFormat * SDL_AllocFormat(Uint32 pixel_format) { SDL_PixelFormat *format; SDL_AtomicLock(&formats_lock); /* Look it up in our list of previously allocated formats */ for (format = formats; format; format = format->next) { if (pixel_format == format->format) { ++format->refcount; SDL_AtomicUnlock(&formats_lock); return format; } } /* Allocate an empty pixel format structure, and initialize it */ format = SDL_malloc(sizeof(*format)); if (format == NULL) { SDL_AtomicUnlock(&formats_lock); SDL_OutOfMemory(); return NULL; } if (SDL_InitFormat(format, pixel_format) < 0) { SDL_AtomicUnlock(&formats_lock); SDL_free(format); SDL_InvalidParamError("format"); return NULL; } if (!SDL_ISPIXELFORMAT_INDEXED(pixel_format)) { /* Cache the RGB formats */ format->next = formats; formats = format; } SDL_AtomicUnlock(&formats_lock); return format; } int SDL_InitFormat(SDL_PixelFormat * format, Uint32 pixel_format) { int bpp; Uint32 Rmask, Gmask, Bmask, Amask; Uint32 mask; if (!SDL_PixelFormatEnumToMasks(pixel_format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) { return -1; } /* Set up the format */ SDL_zerop(format); format->format = pixel_format; format->BitsPerPixel = bpp; format->BytesPerPixel = (bpp + 7) / 8; format->Rmask = Rmask; format->Rshift = 0; format->Rloss = 8; if (Rmask) { for (mask = Rmask; !(mask & 0x01); mask >>= 1) ++format->Rshift; for (; (mask & 0x01); mask >>= 1) --format->Rloss; } format->Gmask = Gmask; format->Gshift = 0; format->Gloss = 8; if (Gmask) { for (mask = Gmask; !(mask & 0x01); mask >>= 1) ++format->Gshift; for (; (mask & 0x01); mask >>= 1) --format->Gloss; } format->Bmask = Bmask; format->Bshift = 0; format->Bloss = 8; if (Bmask) { for (mask = Bmask; !(mask & 0x01); mask >>= 1) ++format->Bshift; for (; (mask & 0x01); mask >>= 1) --format->Bloss; } format->Amask = Amask; format->Ashift = 0; format->Aloss = 8; if (Amask) { for (mask = Amask; !(mask & 0x01); mask >>= 1) ++format->Ashift; for (; (mask & 0x01); mask >>= 1) --format->Aloss; } format->palette = NULL; format->refcount = 1; format->next = NULL; return 0; } void SDL_FreeFormat(SDL_PixelFormat *format) { SDL_PixelFormat *prev; if (!format) { SDL_InvalidParamError("format"); return; } SDL_AtomicLock(&formats_lock); if (--format->refcount > 0) { SDL_AtomicUnlock(&formats_lock); return; } /* Remove this format from our list */ if (format == formats) { formats = format->next; } else if (formats) { for (prev = formats; prev->next; prev = prev->next) { if (prev->next == format) { prev->next = format->next; break; } } } SDL_AtomicUnlock(&formats_lock); if (format->palette) { SDL_FreePalette(format->palette); } SDL_free(format); } SDL_Palette * SDL_AllocPalette(int ncolors) { SDL_Palette *palette; /* Input validation */ if (ncolors < 1) { SDL_InvalidParamError("ncolors"); return NULL; } palette = (SDL_Palette *) SDL_malloc(sizeof(*palette)); if (!palette) { SDL_OutOfMemory(); return NULL; } palette->colors = (SDL_Color *) SDL_malloc(ncolors * sizeof(*palette->colors)); if (!palette->colors) { SDL_free(palette); return NULL; } palette->ncolors = ncolors; palette->version = 1; palette->refcount = 1; SDL_memset(palette->colors, 0xFF, ncolors * sizeof(*palette->colors)); return palette; } int SDL_SetPixelFormatPalette(SDL_PixelFormat * format, SDL_Palette *palette) { if (!format) { return SDL_SetError("SDL_SetPixelFormatPalette() passed NULL format"); } if (palette && palette->ncolors > (1 << format->BitsPerPixel)) { return SDL_SetError("SDL_SetPixelFormatPalette() passed a palette that doesn't match the format"); } if (format->palette == palette) { return 0; } if (format->palette) { SDL_FreePalette(format->palette); } format->palette = palette; if (format->palette) { ++format->palette->refcount; } return 0; } int SDL_SetPaletteColors(SDL_Palette * palette, const SDL_Color * colors, int firstcolor, int ncolors) { int status = 0; /* Verify the parameters */ if (!palette) { return -1; } if (ncolors > (palette->ncolors - firstcolor)) { ncolors = (palette->ncolors - firstcolor); status = -1; } if (colors != (palette->colors + firstcolor)) { SDL_memcpy(palette->colors + firstcolor, colors, ncolors * sizeof(*colors)); } ++palette->version; if (!palette->version) { palette->version = 1; } return status; } void SDL_FreePalette(SDL_Palette * palette) { if (!palette) { SDL_InvalidParamError("palette"); return; } if (--palette->refcount > 0) { return; } SDL_free(palette->colors); SDL_free(palette); } /* * Calculate an 8-bit (3 red, 3 green, 2 blue) dithered palette of colors */ void SDL_DitherColors(SDL_Color * colors, int bpp) { int i; if (bpp != 8) return; /* only 8bpp supported right now */ for (i = 0; i < 256; i++) { int r, g, b; /* map each bit field to the full [0, 255] interval, so 0 is mapped to (0, 0, 0) and 255 to (255, 255, 255) */ r = i & 0xe0; r |= r >> 3 | r >> 6; colors[i].r = r; g = (i << 3) & 0xe0; g |= g >> 3 | g >> 6; colors[i].g = g; b = i & 0x3; b |= b << 2; b |= b << 4; colors[i].b = b; colors[i].a = SDL_ALPHA_OPAQUE; } } /* * Match an RGB value to a particular palette index */ Uint8 SDL_FindColor(SDL_Palette * pal, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { /* Do colorspace distance matching */ unsigned int smallest; unsigned int distance; int rd, gd, bd, ad; int i; Uint8 pixel = 0; smallest = ~0; for (i = 0; i < pal->ncolors; ++i) { rd = pal->colors[i].r - r; gd = pal->colors[i].g - g; bd = pal->colors[i].b - b; ad = pal->colors[i].a - a; distance = (rd * rd) + (gd * gd) + (bd * bd) + (ad * ad); if (distance < smallest) { pixel = i; if (distance == 0) { /* Perfect match! */ break; } smallest = distance; } } return (pixel); } /* Tell whether palette is opaque, and if it has an alpha_channel */ void SDL_DetectPalette(SDL_Palette *pal, SDL_bool *is_opaque, SDL_bool *has_alpha_channel) { int i; { SDL_bool all_opaque = SDL_TRUE; for (i = 0; i < pal->ncolors; i++) { Uint8 alpha_value = pal->colors[i].a; if (alpha_value != SDL_ALPHA_OPAQUE) { all_opaque = SDL_FALSE; break; } } if (all_opaque) { /* Palette is opaque, with an alpha channel */ *is_opaque = SDL_TRUE; *has_alpha_channel = SDL_TRUE; return; } } { SDL_bool all_transparent = SDL_TRUE; for (i = 0; i < pal->ncolors; i++) { Uint8 alpha_value = pal->colors[i].a; if (alpha_value != SDL_ALPHA_TRANSPARENT) { all_transparent = SDL_FALSE; break; } } if (all_transparent) { /* Palette is opaque, without an alpha channel */ *is_opaque = SDL_TRUE; *has_alpha_channel = SDL_FALSE; return; } } /* Palette has alpha values */ *is_opaque = SDL_FALSE; *has_alpha_channel = SDL_TRUE; } /* Find the opaque pixel value corresponding to an RGB triple */ Uint32 SDL_MapRGB(const SDL_PixelFormat * format, Uint8 r, Uint8 g, Uint8 b) { if (format->palette == NULL) { return (r >> format->Rloss) << format->Rshift | (g >> format->Gloss) << format->Gshift | (b >> format->Bloss) << format->Bshift | format->Amask; } else { return SDL_FindColor(format->palette, r, g, b, SDL_ALPHA_OPAQUE); } } /* Find the pixel value corresponding to an RGBA quadruple */ Uint32 SDL_MapRGBA(const SDL_PixelFormat * format, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { if (format->palette == NULL) { return (r >> format->Rloss) << format->Rshift | (g >> format->Gloss) << format->Gshift | (b >> format->Bloss) << format->Bshift | ((a >> format->Aloss) << format->Ashift & format->Amask); } else { return SDL_FindColor(format->palette, r, g, b, a); } } void SDL_GetRGB(Uint32 pixel, const SDL_PixelFormat * format, Uint8 * r, Uint8 * g, Uint8 * b) { if (format->palette == NULL) { unsigned v; v = (pixel & format->Rmask) >> format->Rshift; *r = SDL_expand_byte[format->Rloss][v]; v = (pixel & format->Gmask) >> format->Gshift; *g = SDL_expand_byte[format->Gloss][v]; v = (pixel & format->Bmask) >> format->Bshift; *b = SDL_expand_byte[format->Bloss][v]; } else { if (pixel < (unsigned)format->palette->ncolors) { *r = format->palette->colors[pixel].r; *g = format->palette->colors[pixel].g; *b = format->palette->colors[pixel].b; } else { *r = *g = *b = 0; } } } void SDL_GetRGBA(Uint32 pixel, const SDL_PixelFormat * format, Uint8 * r, Uint8 * g, Uint8 * b, Uint8 * a) { if (format->palette == NULL) { unsigned v; v = (pixel & format->Rmask) >> format->Rshift; *r = SDL_expand_byte[format->Rloss][v]; v = (pixel & format->Gmask) >> format->Gshift; *g = SDL_expand_byte[format->Gloss][v]; v = (pixel & format->Bmask) >> format->Bshift; *b = SDL_expand_byte[format->Bloss][v]; v = (pixel & format->Amask) >> format->Ashift; *a = SDL_expand_byte[format->Aloss][v]; } else { if (pixel < (unsigned)format->palette->ncolors) { *r = format->palette->colors[pixel].r; *g = format->palette->colors[pixel].g; *b = format->palette->colors[pixel].b; *a = format->palette->colors[pixel].a; } else { *r = *g = *b = *a = 0; } } } /* Map from Palette to Palette */ static Uint8 * Map1to1(SDL_Palette * src, SDL_Palette * dst, int *identical) { Uint8 *map; int i; if (identical) { if (src->ncolors <= dst->ncolors) { /* If an identical palette, no need to map */ if (src == dst || (SDL_memcmp (src->colors, dst->colors, src->ncolors * sizeof(SDL_Color)) == 0)) { *identical = 1; return (NULL); } } *identical = 0; } map = (Uint8 *) SDL_malloc(src->ncolors); if (map == NULL) { SDL_OutOfMemory(); return (NULL); } for (i = 0; i < src->ncolors; ++i) { map[i] = SDL_FindColor(dst, src->colors[i].r, src->colors[i].g, src->colors[i].b, src->colors[i].a); } return (map); } /* Map from Palette to BitField */ static Uint8 * Map1toN(SDL_PixelFormat * src, Uint8 Rmod, Uint8 Gmod, Uint8 Bmod, Uint8 Amod, SDL_PixelFormat * dst) { Uint8 *map; int i; int bpp; SDL_Palette *pal = src->palette; bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel); map = (Uint8 *) SDL_malloc(pal->ncolors * bpp); if (map == NULL) { SDL_OutOfMemory(); return (NULL); } /* We memory copy to the pixel map so the endianness is preserved */ for (i = 0; i < pal->ncolors; ++i) { Uint8 R = (Uint8) ((pal->colors[i].r * Rmod) / 255); Uint8 G = (Uint8) ((pal->colors[i].g * Gmod) / 255); Uint8 B = (Uint8) ((pal->colors[i].b * Bmod) / 255); Uint8 A = (Uint8) ((pal->colors[i].a * Amod) / 255); ASSEMBLE_RGBA(&map[i * bpp], dst->BytesPerPixel, dst, R, G, B, A); } return (map); } /* Map from BitField to Dithered-Palette to Palette */ static Uint8 * MapNto1(SDL_PixelFormat * src, SDL_PixelFormat * dst, int *identical) { /* Generate a 256 color dither palette */ SDL_Palette dithered; SDL_Color colors[256]; SDL_Palette *pal = dst->palette; dithered.ncolors = 256; SDL_DitherColors(colors, 8); dithered.colors = colors; return (Map1to1(&dithered, pal, identical)); } SDL_BlitMap * SDL_AllocBlitMap(void) { SDL_BlitMap *map; /* Allocate the empty map */ map = (SDL_BlitMap *) SDL_calloc(1, sizeof(*map)); if (map == NULL) { SDL_OutOfMemory(); return (NULL); } map->info.r = 0xFF; map->info.g = 0xFF; map->info.b = 0xFF; map->info.a = 0xFF; /* It's ready to go */ return (map); } void SDL_InvalidateMap(SDL_BlitMap * map) { if (!map) { return; } if (map->dst) { /* Release our reference to the surface - see the note below */ if (--map->dst->refcount <= 0) { SDL_FreeSurface(map->dst); } } map->dst = NULL; map->src_palette_version = 0; map->dst_palette_version = 0; SDL_free(map->info.table); map->info.table = NULL; } int SDL_MapSurface(SDL_Surface * src, SDL_Surface * dst) { SDL_PixelFormat *srcfmt; SDL_PixelFormat *dstfmt; SDL_BlitMap *map; /* Clear out any previous mapping */ map = src->map; #if SDL_HAVE_RLE if ((src->flags & SDL_RLEACCEL) == SDL_RLEACCEL) { SDL_UnRLESurface(src, 1); } #endif SDL_InvalidateMap(map); /* Figure out what kind of mapping we're doing */ map->identity = 0; srcfmt = src->format; dstfmt = dst->format; if (SDL_ISPIXELFORMAT_INDEXED(srcfmt->format)) { if (SDL_ISPIXELFORMAT_INDEXED(dstfmt->format)) { /* Palette --> Palette */ map->info.table = Map1to1(srcfmt->palette, dstfmt->palette, &map->identity); if (!map->identity) { if (map->info.table == NULL) { return (-1); } } if (srcfmt->BitsPerPixel != dstfmt->BitsPerPixel) map->identity = 0; } else { /* Palette --> BitField */ map->info.table = Map1toN(srcfmt, src->map->info.r, src->map->info.g, src->map->info.b, src->map->info.a, dstfmt); if (map->info.table == NULL) { return (-1); } } } else { if (SDL_ISPIXELFORMAT_INDEXED(dstfmt->format)) { /* BitField --> Palette */ map->info.table = MapNto1(srcfmt, dstfmt, &map->identity); if (!map->identity) { if (map->info.table == NULL) { return (-1); } } map->identity = 0; /* Don't optimize to copy */ } else { /* BitField --> BitField */ if (srcfmt == dstfmt) { map->identity = 1; } } } map->dst = dst; if (map->dst) { /* Keep a reference to this surface so it doesn't get deleted while we're still pointing at it. A better method would be for the destination surface to keep track of surfaces that are mapped to it and automatically invalidate them when it is freed, but this will do for now. */ ++map->dst->refcount; } if (dstfmt->palette) { map->dst_palette_version = dstfmt->palette->version; } else { map->dst_palette_version = 0; } if (srcfmt->palette) { map->src_palette_version = srcfmt->palette->version; } else { map->src_palette_version = 0; } /* Choose your blitters wisely */ return (SDL_CalculateBlit(src)); } void SDL_FreeBlitMap(SDL_BlitMap * map) { if (map) { SDL_InvalidateMap(map); SDL_free(map); } } void SDL_CalculateGammaRamp(float gamma, Uint16 * ramp) { int i; /* Input validation */ if (gamma < 0.0f ) { SDL_InvalidParamError("gamma"); return; } if (ramp == NULL) { SDL_InvalidParamError("ramp"); return; } /* 0.0 gamma is all black */ if (gamma == 0.0f) { SDL_memset(ramp, 0, 256 * sizeof(Uint16)); return; } else if (gamma == 1.0f) { /* 1.0 gamma is identity */ for (i = 0; i < 256; ++i) { ramp[i] = (i << 8) | i; } return; } else { /* Calculate a real gamma ramp */ int value; gamma = 1.0f / gamma; for (i = 0; i < 256; ++i) { value = (int) (SDL_pow((double) i / 256.0, gamma) * 65535.0 + 0.5); if (value > 65535) { value = 65535; } ramp[i] = (Uint16) value; } } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_pixels.c
C
apache-2.0
33,525
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_pixels_c_h_ #define SDL_pixels_c_h_ #include "../SDL_internal.h" /* Useful functions and variables from SDL_pixel.c */ #include "SDL_blit.h" /* Pixel format functions */ extern int SDL_InitFormat(SDL_PixelFormat * format, Uint32 pixel_format); /* Blit mapping functions */ extern SDL_BlitMap *SDL_AllocBlitMap(void); extern void SDL_InvalidateMap(SDL_BlitMap * map); extern int SDL_MapSurface(SDL_Surface * src, SDL_Surface * dst); extern void SDL_FreeBlitMap(SDL_BlitMap * map); /* Miscellaneous functions */ extern void SDL_DitherColors(SDL_Color * colors, int bpp); extern Uint8 SDL_FindColor(SDL_Palette * pal, Uint8 r, Uint8 g, Uint8 b, Uint8 a); extern void SDL_DetectPalette(SDL_Palette *pal, SDL_bool *is_opaque, SDL_bool *has_alpha_channel); #endif /* SDL_pixels_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_pixels_c.h
C
apache-2.0
1,775
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL_rect.h" #include "SDL_rect_c.h" #include "SDL_assert.h" SDL_bool SDL_HasIntersection(const SDL_Rect * A, const SDL_Rect * B) { int Amin, Amax, Bmin, Bmax; if (!A) { SDL_InvalidParamError("A"); return SDL_FALSE; } if (!B) { SDL_InvalidParamError("B"); return SDL_FALSE; } /* Special cases for empty rects */ if (SDL_RectEmpty(A) || SDL_RectEmpty(B)) { return SDL_FALSE; } /* Horizontal intersection */ Amin = A->x; Amax = Amin + A->w; Bmin = B->x; Bmax = Bmin + B->w; if (Bmin > Amin) Amin = Bmin; if (Bmax < Amax) Amax = Bmax; if (Amax <= Amin) return SDL_FALSE; /* Vertical intersection */ Amin = A->y; Amax = Amin + A->h; Bmin = B->y; Bmax = Bmin + B->h; if (Bmin > Amin) Amin = Bmin; if (Bmax < Amax) Amax = Bmax; if (Amax <= Amin) return SDL_FALSE; return SDL_TRUE; } SDL_bool SDL_IntersectRect(const SDL_Rect * A, const SDL_Rect * B, SDL_Rect * result) { int Amin, Amax, Bmin, Bmax; if (!A) { SDL_InvalidParamError("A"); return SDL_FALSE; } if (!B) { SDL_InvalidParamError("B"); return SDL_FALSE; } if (!result) { SDL_InvalidParamError("result"); return SDL_FALSE; } /* Special cases for empty rects */ if (SDL_RectEmpty(A) || SDL_RectEmpty(B)) { result->w = 0; result->h = 0; return SDL_FALSE; } /* Horizontal intersection */ Amin = A->x; Amax = Amin + A->w; Bmin = B->x; Bmax = Bmin + B->w; if (Bmin > Amin) Amin = Bmin; result->x = Amin; if (Bmax < Amax) Amax = Bmax; result->w = Amax - Amin; /* Vertical intersection */ Amin = A->y; Amax = Amin + A->h; Bmin = B->y; Bmax = Bmin + B->h; if (Bmin > Amin) Amin = Bmin; result->y = Amin; if (Bmax < Amax) Amax = Bmax; result->h = Amax - Amin; return !SDL_RectEmpty(result); } void SDL_UnionRect(const SDL_Rect * A, const SDL_Rect * B, SDL_Rect * result) { int Amin, Amax, Bmin, Bmax; if (!A) { SDL_InvalidParamError("A"); return; } if (!B) { SDL_InvalidParamError("B"); return; } if (!result) { SDL_InvalidParamError("result"); return; } /* Special cases for empty Rects */ if (SDL_RectEmpty(A)) { if (SDL_RectEmpty(B)) { /* A and B empty */ return; } else { /* A empty, B not empty */ *result = *B; return; } } else { if (SDL_RectEmpty(B)) { /* A not empty, B empty */ *result = *A; return; } } /* Horizontal union */ Amin = A->x; Amax = Amin + A->w; Bmin = B->x; Bmax = Bmin + B->w; if (Bmin < Amin) Amin = Bmin; result->x = Amin; if (Bmax > Amax) Amax = Bmax; result->w = Amax - Amin; /* Vertical union */ Amin = A->y; Amax = Amin + A->h; Bmin = B->y; Bmax = Bmin + B->h; if (Bmin < Amin) Amin = Bmin; result->y = Amin; if (Bmax > Amax) Amax = Bmax; result->h = Amax - Amin; } SDL_bool SDL_EnclosePoints(const SDL_Point * points, int count, const SDL_Rect * clip, SDL_Rect * result) { int minx = 0; int miny = 0; int maxx = 0; int maxy = 0; int x, y, i; if (!points) { SDL_InvalidParamError("points"); return SDL_FALSE; } if (count < 1) { SDL_InvalidParamError("count"); return SDL_FALSE; } if (clip) { SDL_bool added = SDL_FALSE; const int clip_minx = clip->x; const int clip_miny = clip->y; const int clip_maxx = clip->x+clip->w-1; const int clip_maxy = clip->y+clip->h-1; /* Special case for empty rectangle */ if (SDL_RectEmpty(clip)) { return SDL_FALSE; } for (i = 0; i < count; ++i) { x = points[i].x; y = points[i].y; if (x < clip_minx || x > clip_maxx || y < clip_miny || y > clip_maxy) { continue; } if (!added) { /* Special case: if no result was requested, we are done */ if (result == NULL) { return SDL_TRUE; } /* First point added */ minx = maxx = x; miny = maxy = y; added = SDL_TRUE; continue; } if (x < minx) { minx = x; } else if (x > maxx) { maxx = x; } if (y < miny) { miny = y; } else if (y > maxy) { maxy = y; } } if (!added) { return SDL_FALSE; } } else { /* Special case: if no result was requested, we are done */ if (result == NULL) { return SDL_TRUE; } /* No clipping, always add the first point */ minx = maxx = points[0].x; miny = maxy = points[0].y; for (i = 1; i < count; ++i) { x = points[i].x; y = points[i].y; if (x < minx) { minx = x; } else if (x > maxx) { maxx = x; } if (y < miny) { miny = y; } else if (y > maxy) { maxy = y; } } } if (result) { result->x = minx; result->y = miny; result->w = (maxx-minx)+1; result->h = (maxy-miny)+1; } return SDL_TRUE; } /* Use the Cohen-Sutherland algorithm for line clipping */ #define CODE_BOTTOM 1 #define CODE_TOP 2 #define CODE_LEFT 4 #define CODE_RIGHT 8 static int ComputeOutCode(const SDL_Rect * rect, int x, int y) { int code = 0; if (y < rect->y) { code |= CODE_TOP; } else if (y >= rect->y + rect->h) { code |= CODE_BOTTOM; } if (x < rect->x) { code |= CODE_LEFT; } else if (x >= rect->x + rect->w) { code |= CODE_RIGHT; } return code; } SDL_bool SDL_IntersectRectAndLine(const SDL_Rect * rect, int *X1, int *Y1, int *X2, int *Y2) { int x = 0; int y = 0; int x1, y1; int x2, y2; int rectx1; int recty1; int rectx2; int recty2; int outcode1, outcode2; if (!rect) { SDL_InvalidParamError("rect"); return SDL_FALSE; } if (!X1) { SDL_InvalidParamError("X1"); return SDL_FALSE; } if (!Y1) { SDL_InvalidParamError("Y1"); return SDL_FALSE; } if (!X2) { SDL_InvalidParamError("X2"); return SDL_FALSE; } if (!Y2) { SDL_InvalidParamError("Y2"); return SDL_FALSE; } /* Special case for empty rect */ if (SDL_RectEmpty(rect)) { return SDL_FALSE; } x1 = *X1; y1 = *Y1; x2 = *X2; y2 = *Y2; rectx1 = rect->x; recty1 = rect->y; rectx2 = rect->x + rect->w - 1; recty2 = rect->y + rect->h - 1; /* Check to see if entire line is inside rect */ if (x1 >= rectx1 && x1 <= rectx2 && x2 >= rectx1 && x2 <= rectx2 && y1 >= recty1 && y1 <= recty2 && y2 >= recty1 && y2 <= recty2) { return SDL_TRUE; } /* Check to see if entire line is to one side of rect */ if ((x1 < rectx1 && x2 < rectx1) || (x1 > rectx2 && x2 > rectx2) || (y1 < recty1 && y2 < recty1) || (y1 > recty2 && y2 > recty2)) { return SDL_FALSE; } if (y1 == y2) { /* Horizontal line, easy to clip */ if (x1 < rectx1) { *X1 = rectx1; } else if (x1 > rectx2) { *X1 = rectx2; } if (x2 < rectx1) { *X2 = rectx1; } else if (x2 > rectx2) { *X2 = rectx2; } return SDL_TRUE; } if (x1 == x2) { /* Vertical line, easy to clip */ if (y1 < recty1) { *Y1 = recty1; } else if (y1 > recty2) { *Y1 = recty2; } if (y2 < recty1) { *Y2 = recty1; } else if (y2 > recty2) { *Y2 = recty2; } return SDL_TRUE; } /* More complicated Cohen-Sutherland algorithm */ outcode1 = ComputeOutCode(rect, x1, y1); outcode2 = ComputeOutCode(rect, x2, y2); while (outcode1 || outcode2) { if (outcode1 & outcode2) { return SDL_FALSE; } if (outcode1) { if (outcode1 & CODE_TOP) { y = recty1; x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1); } else if (outcode1 & CODE_BOTTOM) { y = recty2; x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1); } else if (outcode1 & CODE_LEFT) { x = rectx1; y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1); } else if (outcode1 & CODE_RIGHT) { x = rectx2; y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1); } x1 = x; y1 = y; outcode1 = ComputeOutCode(rect, x, y); } else { if (outcode2 & CODE_TOP) { y = recty1; x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1); } else if (outcode2 & CODE_BOTTOM) { y = recty2; x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1); } else if (outcode2 & CODE_LEFT) { /* If this assertion ever fires, here's the static analysis that warned about it: http://buildbot.libsdl.org/sdl-static-analysis/sdl-macosx-static-analysis/sdl-macosx-static-analysis-1101/report-b0d01a.html#EndPath */ SDL_assert(x2 != x1); /* if equal: division by zero. */ x = rectx1; y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1); } else if (outcode2 & CODE_RIGHT) { /* If this assertion ever fires, here's the static analysis that warned about it: http://buildbot.libsdl.org/sdl-static-analysis/sdl-macosx-static-analysis/sdl-macosx-static-analysis-1101/report-39b114.html#EndPath */ SDL_assert(x2 != x1); /* if equal: division by zero. */ x = rectx2; y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1); } x2 = x; y2 = y; outcode2 = ComputeOutCode(rect, x, y); } } *X1 = x1; *Y1 = y1; *X2 = x2; *Y2 = y2; return SDL_TRUE; } SDL_bool SDL_GetSpanEnclosingRect(int width, int height, int numrects, const SDL_Rect * rects, SDL_Rect *span) { int i; int span_y1, span_y2; int rect_y1, rect_y2; if (width < 1) { SDL_InvalidParamError("width"); return SDL_FALSE; } if (height < 1) { SDL_InvalidParamError("height"); return SDL_FALSE; } if (!rects) { SDL_InvalidParamError("rects"); return SDL_FALSE; } if (!span) { SDL_InvalidParamError("span"); return SDL_FALSE; } if (numrects < 1) { SDL_InvalidParamError("numrects"); return SDL_FALSE; } /* Initialize to empty rect */ span_y1 = height; span_y2 = 0; for (i = 0; i < numrects; ++i) { rect_y1 = rects[i].y; rect_y2 = rect_y1 + rects[i].h; /* Clip out of bounds rectangles, and expand span rect */ if (rect_y1 < 0) { span_y1 = 0; } else if (rect_y1 < span_y1) { span_y1 = rect_y1; } if (rect_y2 > height) { span_y2 = height; } else if (rect_y2 > span_y2) { span_y2 = rect_y2; } } if (span_y2 > span_y1) { span->x = 0; span->y = span_y1; span->w = width; span->h = (span_y2 - span_y1); return SDL_TRUE; } return SDL_FALSE; } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_rect.c
C
apache-2.0
13,143
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_rect_c_h_ #define SDL_rect_c_h_ #include "../SDL_internal.h" extern SDL_bool SDL_GetSpanEnclosingRect(int width, int height, int numrects, const SDL_Rect * rects, SDL_Rect *span); #endif /* SDL_rect_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_rect_c.h
C
apache-2.0
1,198
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL.h" #include "SDL_assert.h" #include "SDL_video.h" #include "SDL_sysvideo.h" #include "SDL_pixels.h" #include "SDL_surface.h" #include "SDL_shape.h" #include "SDL_shape_internals.h" SDL_Window* SDL_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags) { SDL_Window *result = NULL; result = SDL_CreateWindow(title,-1000,-1000,w,h,(flags | SDL_WINDOW_BORDERLESS) & (~SDL_WINDOW_FULLSCREEN) & (~SDL_WINDOW_RESIZABLE) /* & (~SDL_WINDOW_SHOWN) */); if(result != NULL) { if (SDL_GetVideoDevice()->shape_driver.CreateShaper == NULL) { SDL_DestroyWindow(result); return NULL; } result->shaper = SDL_GetVideoDevice()->shape_driver.CreateShaper(result); if(result->shaper != NULL) { result->shaper->userx = x; result->shaper->usery = y; result->shaper->mode.mode = ShapeModeDefault; result->shaper->mode.parameters.binarizationCutoff = 1; result->shaper->hasshape = SDL_FALSE; return result; } else { SDL_DestroyWindow(result); return NULL; } } else return NULL; } SDL_bool SDL_IsShapedWindow(const SDL_Window *window) { if(window == NULL) return SDL_FALSE; else return (SDL_bool)(window->shaper != NULL); } /* REQUIRES that bitmap point to a w-by-h bitmap with ppb pixels-per-byte. */ void SDL_CalculateShapeBitmap(SDL_WindowShapeMode mode,SDL_Surface *shape,Uint8* bitmap,Uint8 ppb) { int x = 0; int y = 0; Uint8 r = 0,g = 0,b = 0,alpha = 0; Uint8* pixel = NULL; Uint32 pixel_value = 0,mask_value = 0; int bytes_per_scanline = (shape->w + (ppb - 1)) / ppb; Uint8 *bitmap_scanline; SDL_Color key; if(SDL_MUSTLOCK(shape)) SDL_LockSurface(shape); for(y = 0;y<shape->h;y++) { bitmap_scanline = bitmap + y * bytes_per_scanline; for(x=0;x<shape->w;x++) { alpha = 0; pixel_value = 0; pixel = (Uint8 *)(shape->pixels) + (y*shape->pitch) + (x*shape->format->BytesPerPixel); switch(shape->format->BytesPerPixel) { case(1): pixel_value = *pixel; break; case(2): pixel_value = *(Uint16*)pixel; break; case(3): pixel_value = *(Uint32*)pixel & (~shape->format->Amask); break; case(4): pixel_value = *(Uint32*)pixel; break; } SDL_GetRGBA(pixel_value,shape->format,&r,&g,&b,&alpha); switch(mode.mode) { case(ShapeModeDefault): mask_value = (alpha >= 1 ? 1 : 0); break; case(ShapeModeBinarizeAlpha): mask_value = (alpha >= mode.parameters.binarizationCutoff ? 1 : 0); break; case(ShapeModeReverseBinarizeAlpha): mask_value = (alpha <= mode.parameters.binarizationCutoff ? 1 : 0); break; case(ShapeModeColorKey): key = mode.parameters.colorKey; mask_value = ((key.r != r || key.g != g || key.b != b) ? 1 : 0); break; } bitmap_scanline[x / ppb] |= mask_value << (x % ppb); } } if(SDL_MUSTLOCK(shape)) SDL_UnlockSurface(shape); } static SDL_ShapeTree* RecursivelyCalculateShapeTree(SDL_WindowShapeMode mode,SDL_Surface* mask,SDL_Rect dimensions) { int x = 0,y = 0; Uint8* pixel = NULL; Uint32 pixel_value = 0; Uint8 r = 0,g = 0,b = 0,a = 0; SDL_bool pixel_opaque = SDL_FALSE; int last_opaque = -1; SDL_Color key; SDL_ShapeTree* result = (SDL_ShapeTree*)SDL_malloc(sizeof(SDL_ShapeTree)); SDL_Rect next = {0,0,0,0}; for(y=dimensions.y;y<dimensions.y + dimensions.h;y++) { for(x=dimensions.x;x<dimensions.x + dimensions.w;x++) { pixel_value = 0; pixel = (Uint8 *)(mask->pixels) + (y*mask->pitch) + (x*mask->format->BytesPerPixel); switch(mask->format->BytesPerPixel) { case(1): pixel_value = *pixel; break; case(2): pixel_value = *(Uint16*)pixel; break; case(3): pixel_value = *(Uint32*)pixel & (~mask->format->Amask); break; case(4): pixel_value = *(Uint32*)pixel; break; } SDL_GetRGBA(pixel_value,mask->format,&r,&g,&b,&a); switch(mode.mode) { case(ShapeModeDefault): pixel_opaque = (a >= 1 ? SDL_TRUE : SDL_FALSE); break; case(ShapeModeBinarizeAlpha): pixel_opaque = (a >= mode.parameters.binarizationCutoff ? SDL_TRUE : SDL_FALSE); break; case(ShapeModeReverseBinarizeAlpha): pixel_opaque = (a <= mode.parameters.binarizationCutoff ? SDL_TRUE : SDL_FALSE); break; case(ShapeModeColorKey): key = mode.parameters.colorKey; pixel_opaque = ((key.r != r || key.g != g || key.b != b) ? SDL_TRUE : SDL_FALSE); break; } if(last_opaque == -1) last_opaque = pixel_opaque; if(last_opaque != pixel_opaque) { const int halfwidth = dimensions.w / 2; const int halfheight = dimensions.h / 2; result->kind = QuadShape; next.x = dimensions.x; next.y = dimensions.y; next.w = halfwidth; next.h = halfheight; result->data.children.upleft = (struct SDL_ShapeTree *)RecursivelyCalculateShapeTree(mode,mask,next); next.x = dimensions.x + halfwidth; next.w = dimensions.w - halfwidth; result->data.children.upright = (struct SDL_ShapeTree *)RecursivelyCalculateShapeTree(mode,mask,next); next.x = dimensions.x; next.w = halfwidth; next.y = dimensions.y + halfheight; next.h = dimensions.h - halfheight; result->data.children.downleft = (struct SDL_ShapeTree *)RecursivelyCalculateShapeTree(mode,mask,next); next.x = dimensions.x + halfwidth; next.w = dimensions.w - halfwidth; result->data.children.downright = (struct SDL_ShapeTree *)RecursivelyCalculateShapeTree(mode,mask,next); return result; } } } /* If we never recursed, all the pixels in this quadrant have the same "value". */ result->kind = (last_opaque == SDL_TRUE ? OpaqueShape : TransparentShape); result->data.shape = dimensions; return result; } SDL_ShapeTree* SDL_CalculateShapeTree(SDL_WindowShapeMode mode,SDL_Surface* shape) { SDL_Rect dimensions; SDL_ShapeTree* result = NULL; dimensions.x = 0; dimensions.y = 0; dimensions.w = shape->w; dimensions.h = shape->h; if(SDL_MUSTLOCK(shape)) SDL_LockSurface(shape); result = RecursivelyCalculateShapeTree(mode,shape,dimensions); if(SDL_MUSTLOCK(shape)) SDL_UnlockSurface(shape); return result; } void SDL_TraverseShapeTree(SDL_ShapeTree *tree,SDL_TraversalFunction function,void* closure) { SDL_assert(tree != NULL); if(tree->kind == QuadShape) { SDL_TraverseShapeTree((SDL_ShapeTree *)tree->data.children.upleft,function,closure); SDL_TraverseShapeTree((SDL_ShapeTree *)tree->data.children.upright,function,closure); SDL_TraverseShapeTree((SDL_ShapeTree *)tree->data.children.downleft,function,closure); SDL_TraverseShapeTree((SDL_ShapeTree *)tree->data.children.downright,function,closure); } else function(tree,closure); } void SDL_FreeShapeTree(SDL_ShapeTree** shape_tree) { if((*shape_tree)->kind == QuadShape) { SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.upleft); SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.upright); SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.downleft); SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.downright); } SDL_free(*shape_tree); *shape_tree = NULL; } int SDL_SetWindowShape(SDL_Window *window,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode) { int result; if(window == NULL || !SDL_IsShapedWindow(window)) /* The window given was not a shapeable window. */ return SDL_NONSHAPEABLE_WINDOW; if(shape == NULL) /* Invalid shape argument. */ return SDL_INVALID_SHAPE_ARGUMENT; if(shape_mode != NULL) window->shaper->mode = *shape_mode; result = SDL_GetVideoDevice()->shape_driver.SetWindowShape(window->shaper,shape,shape_mode); window->shaper->hasshape = SDL_TRUE; if(window->shaper->userx != 0 && window->shaper->usery != 0) { SDL_SetWindowPosition(window,window->shaper->userx,window->shaper->usery); window->shaper->userx = 0; window->shaper->usery = 0; } return result; } static SDL_bool SDL_WindowHasAShape(SDL_Window *window) { if (window == NULL || !SDL_IsShapedWindow(window)) return SDL_FALSE; return window->shaper->hasshape; } int SDL_GetShapedWindowMode(SDL_Window *window,SDL_WindowShapeMode *shape_mode) { if(window != NULL && SDL_IsShapedWindow(window)) { if(shape_mode == NULL) { if(SDL_WindowHasAShape(window)) /* The window given has a shape. */ return 0; else /* The window given is shapeable but lacks a shape. */ return SDL_WINDOW_LACKS_SHAPE; } else { *shape_mode = window->shaper->mode; return 0; } } else /* The window given is not a valid shapeable window. */ return SDL_NONSHAPEABLE_WINDOW; }
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_shape.c
C
apache-2.0
11,333
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #ifndef SDL_shape_internals_h_ #define SDL_shape_internals_h_ #include "SDL_rect.h" #include "SDL_shape.h" #include "SDL_surface.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus /* *INDENT-OFF* */ extern "C" { /* *INDENT-ON* */ #endif typedef struct { struct SDL_ShapeTree *upleft,*upright,*downleft,*downright; } SDL_QuadTreeChildren; typedef union { SDL_QuadTreeChildren children; SDL_Rect shape; } SDL_ShapeUnion; typedef enum { QuadShape,TransparentShape,OpaqueShape } SDL_ShapeKind; typedef struct { SDL_ShapeKind kind; SDL_ShapeUnion data; } SDL_ShapeTree; typedef void(*SDL_TraversalFunction)(SDL_ShapeTree*,void*); extern void SDL_CalculateShapeBitmap(SDL_WindowShapeMode mode,SDL_Surface *shape,Uint8* bitmap,Uint8 ppb); extern SDL_ShapeTree* SDL_CalculateShapeTree(SDL_WindowShapeMode mode,SDL_Surface* shape); extern void SDL_TraverseShapeTree(SDL_ShapeTree *tree,SDL_TraversalFunction function,void* closure); extern void SDL_FreeShapeTree(SDL_ShapeTree** shape_tree); /* Ends C function definitions when using C++ */ #ifdef __cplusplus /* *INDENT-OFF* */ } /* *INDENT-ON* */ #endif #include "close_code.h" #endif
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_shape_internals.h
C
apache-2.0
2,183
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* This a stretch blit implementation based on ideas given to me by Tomasz Cejner - thanks! :) April 27, 2000 - Sam Lantinga */ #include "SDL_video.h" #include "SDL_blit.h" /* This isn't ready for general consumption yet - it should be folded into the general blitting mechanism. */ #if ((defined(_MSC_VER) && defined(_M_IX86)) || \ (defined(__WATCOMC__) && defined(__386__)) || \ (defined(__GNUC__) && defined(__i386__))) && SDL_ASSEMBLY_ROUTINES /* There's a bug with gcc 4.4.1 and -O2 where srcp doesn't get the correct * value after the first scanline. FIXME? */ /* #define USE_ASM_STRETCH */ #endif #ifdef USE_ASM_STRETCH #ifdef HAVE_MPROTECT #include <sys/types.h> #include <sys/mman.h> #endif #ifdef __GNUC__ #define PAGE_ALIGNED __attribute__((__aligned__(4096))) #else #define PAGE_ALIGNED #endif #if defined(_M_IX86) || defined(__i386__) || defined(__386__) #define PREFIX16 0x66 #define STORE_BYTE 0xAA #define STORE_WORD 0xAB #define LOAD_BYTE 0xAC #define LOAD_WORD 0xAD #define RETURN 0xC3 #else #error Need assembly opcodes for this architecture #endif static unsigned char copy_row[4096] PAGE_ALIGNED; static int generate_rowbytes(int src_w, int dst_w, int bpp) { static struct { int bpp; int src_w; int dst_w; int status; } last; int i; int pos, inc; unsigned char *eip, *fence; unsigned char load, store; /* See if we need to regenerate the copy buffer */ if ((src_w == last.src_w) && (dst_w == last.dst_w) && (bpp == last.bpp)) { return (last.status); } last.bpp = bpp; last.src_w = src_w; last.dst_w = dst_w; last.status = -1; switch (bpp) { case 1: load = LOAD_BYTE; store = STORE_BYTE; break; case 2: case 4: load = LOAD_WORD; store = STORE_WORD; break; default: return SDL_SetError("ASM stretch of %d bytes isn't supported", bpp); } #ifdef HAVE_MPROTECT /* Make the code writeable */ if (mprotect(copy_row, sizeof(copy_row), PROT_READ | PROT_WRITE) < 0) { return SDL_SetError("Couldn't make copy buffer writeable"); } #endif pos = 0x10000; inc = (src_w << 16) / dst_w; eip = copy_row; fence = copy_row + sizeof(copy_row)-2; for (i = 0; i < dst_w; ++i) { while (pos >= 0x10000L) { if (eip == fence) { return -1; } if (bpp == 2) { *eip++ = PREFIX16; } *eip++ = load; pos -= 0x10000L; } if (eip == fence) { return -1; } if (bpp == 2) { *eip++ = PREFIX16; } *eip++ = store; pos += inc; } *eip++ = RETURN; #ifdef HAVE_MPROTECT /* Make the code executable but not writeable */ if (mprotect(copy_row, sizeof(copy_row), PROT_READ | PROT_EXEC) < 0) { return SDL_SetError("Couldn't make copy buffer executable"); } #endif last.status = 0; return (0); } #endif /* USE_ASM_STRETCH */ #define DEFINE_COPY_ROW(name, type) \ static void name(type *src, int src_w, type *dst, int dst_w) \ { \ int i; \ int pos, inc; \ type pixel = 0; \ \ pos = 0x10000; \ inc = (src_w << 16) / dst_w; \ for ( i=dst_w; i>0; --i ) { \ while ( pos >= 0x10000L ) { \ pixel = *src++; \ pos -= 0x10000L; \ } \ *dst++ = pixel; \ pos += inc; \ } \ } /* *INDENT-OFF* */ DEFINE_COPY_ROW(copy_row1, Uint8) DEFINE_COPY_ROW(copy_row2, Uint16) DEFINE_COPY_ROW(copy_row4, Uint32) /* *INDENT-ON* */ /* The ASM code doesn't handle 24-bpp stretch blits */ static void copy_row3(Uint8 * src, int src_w, Uint8 * dst, int dst_w) { int i; int pos, inc; Uint8 pixel[3] = { 0, 0, 0 }; pos = 0x10000; inc = (src_w << 16) / dst_w; for (i = dst_w; i > 0; --i) { while (pos >= 0x10000L) { pixel[0] = *src++; pixel[1] = *src++; pixel[2] = *src++; pos -= 0x10000L; } *dst++ = pixel[0]; *dst++ = pixel[1]; *dst++ = pixel[2]; pos += inc; } } /* Perform a stretch blit between two surfaces of the same format. NOTE: This function is not safe to call from multiple threads! */ int SDL_SoftStretch(SDL_Surface * src, const SDL_Rect * srcrect, SDL_Surface * dst, const SDL_Rect * dstrect) { int src_locked; int dst_locked; int pos, inc; int dst_maxrow; int src_row, dst_row; Uint8 *srcp = NULL; Uint8 *dstp; SDL_Rect full_src; SDL_Rect full_dst; #ifdef USE_ASM_STRETCH SDL_bool use_asm = SDL_TRUE; #ifdef __GNUC__ int u1, u2; #endif #endif /* USE_ASM_STRETCH */ const int bpp = dst->format->BytesPerPixel; if (src->format->format != dst->format->format) { return SDL_SetError("Only works with same format surfaces"); } /* Verify the blit rectangles */ if (srcrect) { if ((srcrect->x < 0) || (srcrect->y < 0) || ((srcrect->x + srcrect->w) > src->w) || ((srcrect->y + srcrect->h) > src->h)) { return SDL_SetError("Invalid source blit rectangle"); } } else { full_src.x = 0; full_src.y = 0; full_src.w = src->w; full_src.h = src->h; srcrect = &full_src; } if (dstrect) { if ((dstrect->x < 0) || (dstrect->y < 0) || ((dstrect->x + dstrect->w) > dst->w) || ((dstrect->y + dstrect->h) > dst->h)) { return SDL_SetError("Invalid destination blit rectangle"); } } else { full_dst.x = 0; full_dst.y = 0; full_dst.w = dst->w; full_dst.h = dst->h; dstrect = &full_dst; } /* Lock the destination if it's in hardware */ dst_locked = 0; if (SDL_MUSTLOCK(dst)) { if (SDL_LockSurface(dst) < 0) { return SDL_SetError("Unable to lock destination surface"); } dst_locked = 1; } /* Lock the source if it's in hardware */ src_locked = 0; if (SDL_MUSTLOCK(src)) { if (SDL_LockSurface(src) < 0) { if (dst_locked) { SDL_UnlockSurface(dst); } return SDL_SetError("Unable to lock source surface"); } src_locked = 1; } /* Set up the data... */ pos = 0x10000; inc = (srcrect->h << 16) / dstrect->h; src_row = srcrect->y; dst_row = dstrect->y; #ifdef USE_ASM_STRETCH /* Write the opcodes for this stretch */ if ((bpp == 3) || (generate_rowbytes(srcrect->w, dstrect->w, bpp) < 0)) { use_asm = SDL_FALSE; } #endif /* Perform the stretch blit */ for (dst_maxrow = dst_row + dstrect->h; dst_row < dst_maxrow; ++dst_row) { dstp = (Uint8 *) dst->pixels + (dst_row * dst->pitch) + (dstrect->x * bpp); while (pos >= 0x10000L) { srcp = (Uint8 *) src->pixels + (src_row * src->pitch) + (srcrect->x * bpp); ++src_row; pos -= 0x10000L; } #ifdef USE_ASM_STRETCH if (use_asm) { #ifdef __GNUC__ __asm__ __volatile__("call *%4":"=&D"(u1), "=&S"(u2) :"0"(dstp), "1"(srcp), "r"(copy_row) :"memory"); #elif defined(_MSC_VER) || defined(__WATCOMC__) /* *INDENT-OFF* */ { void *code = copy_row; __asm { push edi push esi mov edi, dstp mov esi, srcp call dword ptr code pop esi pop edi } } /* *INDENT-ON* */ #else #error Need inline assembly for this compiler #endif } else #endif switch (bpp) { case 1: copy_row1(srcp, srcrect->w, dstp, dstrect->w); break; case 2: copy_row2((Uint16 *) srcp, srcrect->w, (Uint16 *) dstp, dstrect->w); break; case 3: copy_row3(srcp, srcrect->w, dstp, dstrect->w); break; case 4: copy_row4((Uint32 *) srcp, srcrect->w, (Uint32 *) dstp, dstrect->w); break; } pos += inc; } /* We need to unlock the surfaces if they're locked */ if (dst_locked) { SDL_UnlockSurface(dst); } if (src_locked) { SDL_UnlockSurface(src); } return (0); } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_stretch.c
C
apache-2.0
10,076
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL_video.h" #include "SDL_sysvideo.h" #include "SDL_blit.h" #include "SDL_RLEaccel_c.h" #include "SDL_pixels_c.h" #include "SDL_yuv_c.h" /* Check to make sure we can safely check multiplication of surface w and pitch and it won't overflow size_t */ SDL_COMPILE_TIME_ASSERT(surface_size_assumptions, sizeof(int) == sizeof(Sint32) && sizeof(size_t) >= sizeof(Sint32)); /* Public routines */ /* * Calculate the pad-aligned scanline width of a surface */ static Sint64 SDL_CalculatePitch(Uint32 format, int width) { Sint64 pitch; if (SDL_ISPIXELFORMAT_FOURCC(format) || SDL_BITSPERPIXEL(format) >= 8) { pitch = ((Sint64)width * SDL_BYTESPERPIXEL(format)); } else { pitch = (((Sint64)width * SDL_BITSPERPIXEL(format)) + 7) / 8; } pitch = (pitch + 3) & ~3; /* 4-byte aligning for speed */ return pitch; } /* * Create an empty RGB surface of the appropriate depth using the given * enum SDL_PIXELFORMAT_* format */ SDL_Surface * SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth, Uint32 format) { Sint64 pitch; SDL_Surface *surface; /* The flags are no longer used, make the compiler happy */ (void)flags; pitch = SDL_CalculatePitch(format, width); if (pitch < 0 || pitch > SDL_MAX_SINT32) { /* Overflow... */ SDL_OutOfMemory(); return NULL; } /* Allocate the surface */ surface = (SDL_Surface *) SDL_calloc(1, sizeof(*surface)); if (surface == NULL) { SDL_OutOfMemory(); return NULL; } surface->format = SDL_AllocFormat(format); if (!surface->format) { SDL_FreeSurface(surface); return NULL; } surface->w = width; surface->h = height; surface->pitch = (int)pitch; SDL_SetClipRect(surface, NULL); if (SDL_ISPIXELFORMAT_INDEXED(surface->format->format)) { SDL_Palette *palette = SDL_AllocPalette((1 << surface->format->BitsPerPixel)); if (!palette) { SDL_FreeSurface(surface); return NULL; } if (palette->ncolors == 2) { /* Create a black and white bitmap palette */ palette->colors[0].r = 0xFF; palette->colors[0].g = 0xFF; palette->colors[0].b = 0xFF; palette->colors[1].r = 0x00; palette->colors[1].g = 0x00; palette->colors[1].b = 0x00; } SDL_SetSurfacePalette(surface, palette); SDL_FreePalette(palette); } /* Get the pixels */ if (surface->w && surface->h) { /* Assumptions checked in surface_size_assumptions assert above */ Sint64 size = ((Sint64)surface->h * surface->pitch); if (size < 0 || size > SDL_MAX_SINT32) { /* Overflow... */ SDL_FreeSurface(surface); SDL_OutOfMemory(); return NULL; } surface->pixels = SDL_SIMDAlloc((size_t)size); if (!surface->pixels) { SDL_FreeSurface(surface); SDL_OutOfMemory(); return NULL; } surface->flags |= SDL_SIMD_ALIGNED; /* This is important for bitmaps */ SDL_memset(surface->pixels, 0, surface->h * surface->pitch); } /* Allocate an empty mapping */ surface->map = SDL_AllocBlitMap(); if (!surface->map) { SDL_FreeSurface(surface); return NULL; } /* By default surface with an alpha mask are set up for blending */ if (surface->format->Amask) { SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND); } /* The surface is ready to go */ surface->refcount = 1; return surface; } /* * Create an empty RGB surface of the appropriate depth */ SDL_Surface * SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) { Uint32 format; /* Get the pixel format */ format = SDL_MasksToPixelFormatEnum(depth, Rmask, Gmask, Bmask, Amask); if (format == SDL_PIXELFORMAT_UNKNOWN) { SDL_SetError("Unknown pixel format"); return NULL; } return SDL_CreateRGBSurfaceWithFormat(flags, width, height, depth, format); } /* * Create an RGB surface from an existing memory buffer */ SDL_Surface * SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) { SDL_Surface *surface; surface = SDL_CreateRGBSurface(0, 0, 0, depth, Rmask, Gmask, Bmask, Amask); if (surface != NULL) { surface->flags |= SDL_PREALLOC; surface->pixels = pixels; surface->w = width; surface->h = height; surface->pitch = pitch; SDL_SetClipRect(surface, NULL); } return surface; } /* * Create an RGB surface from an existing memory buffer using the given given * enum SDL_PIXELFORMAT_* format */ SDL_Surface * SDL_CreateRGBSurfaceWithFormatFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 format) { SDL_Surface *surface; surface = SDL_CreateRGBSurfaceWithFormat(0, 0, 0, depth, format); if (surface != NULL) { surface->flags |= SDL_PREALLOC; surface->pixels = pixels; surface->w = width; surface->h = height; surface->pitch = pitch; SDL_SetClipRect(surface, NULL); } return surface; } int SDL_SetSurfacePalette(SDL_Surface * surface, SDL_Palette * palette) { if (!surface) { return SDL_SetError("SDL_SetSurfacePalette() passed a NULL surface"); } if (SDL_SetPixelFormatPalette(surface->format, palette) < 0) { return -1; } SDL_InvalidateMap(surface->map); return 0; } int SDL_SetSurfaceRLE(SDL_Surface * surface, int flag) { int flags; if (!surface) { return -1; } flags = surface->map->info.flags; if (flag) { surface->map->info.flags |= SDL_COPY_RLE_DESIRED; } else { surface->map->info.flags &= ~SDL_COPY_RLE_DESIRED; } if (surface->map->info.flags != flags) { SDL_InvalidateMap(surface->map); } return 0; } int SDL_SetColorKey(SDL_Surface * surface, int flag, Uint32 key) { int flags; if (!surface) { return SDL_InvalidParamError("surface"); } if (surface->format->palette && key >= ((Uint32) surface->format->palette->ncolors)) { return SDL_InvalidParamError("key"); } if (flag & SDL_RLEACCEL) { SDL_SetSurfaceRLE(surface, 1); } flags = surface->map->info.flags; if (flag) { surface->map->info.flags |= SDL_COPY_COLORKEY; surface->map->info.colorkey = key; } else { surface->map->info.flags &= ~SDL_COPY_COLORKEY; } if (surface->map->info.flags != flags) { SDL_InvalidateMap(surface->map); } return 0; } SDL_bool SDL_HasColorKey(SDL_Surface * surface) { if (!surface) { return SDL_FALSE; } if (!(surface->map->info.flags & SDL_COPY_COLORKEY)) { return SDL_FALSE; } return SDL_TRUE; } int SDL_GetColorKey(SDL_Surface * surface, Uint32 * key) { if (!surface) { return SDL_InvalidParamError("surface"); } if (!(surface->map->info.flags & SDL_COPY_COLORKEY)) { return SDL_SetError("Surface doesn't have a colorkey"); } if (key) { *key = surface->map->info.colorkey; } return 0; } /* This is a fairly slow function to switch from colorkey to alpha */ static void SDL_ConvertColorkeyToAlpha(SDL_Surface * surface, SDL_bool ignore_alpha) { int x, y; if (!surface) { return; } if (!(surface->map->info.flags & SDL_COPY_COLORKEY) || !surface->format->Amask) { return; } SDL_LockSurface(surface); switch (surface->format->BytesPerPixel) { case 2: { Uint16 *row, *spot; Uint16 ckey = (Uint16) surface->map->info.colorkey; Uint16 mask = (Uint16) (~surface->format->Amask); /* Ignore, or not, alpha in colorkey comparison */ if (ignore_alpha) { ckey &= mask; row = (Uint16 *) surface->pixels; for (y = surface->h; y--;) { spot = row; for (x = surface->w; x--;) { if ((*spot & mask) == ckey) { *spot &= mask; } ++spot; } row += surface->pitch / 2; } } else { row = (Uint16 *) surface->pixels; for (y = surface->h; y--;) { spot = row; for (x = surface->w; x--;) { if (*spot == ckey) { *spot &= mask; } ++spot; } row += surface->pitch / 2; } } } break; case 3: /* FIXME */ break; case 4: { Uint32 *row, *spot; Uint32 ckey = surface->map->info.colorkey; Uint32 mask = ~surface->format->Amask; /* Ignore, or not, alpha in colorkey comparison */ if (ignore_alpha) { ckey &= mask; row = (Uint32 *) surface->pixels; for (y = surface->h; y--;) { spot = row; for (x = surface->w; x--;) { if ((*spot & mask) == ckey) { *spot &= mask; } ++spot; } row += surface->pitch / 4; } } else { row = (Uint32 *) surface->pixels; for (y = surface->h; y--;) { spot = row; for (x = surface->w; x--;) { if (*spot == ckey) { *spot &= mask; } ++spot; } row += surface->pitch / 4; } } } break; } SDL_UnlockSurface(surface); SDL_SetColorKey(surface, 0, 0); SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND); } int SDL_SetSurfaceColorMod(SDL_Surface * surface, Uint8 r, Uint8 g, Uint8 b) { int flags; if (!surface) { return -1; } surface->map->info.r = r; surface->map->info.g = g; surface->map->info.b = b; flags = surface->map->info.flags; if (r != 0xFF || g != 0xFF || b != 0xFF) { surface->map->info.flags |= SDL_COPY_MODULATE_COLOR; } else { surface->map->info.flags &= ~SDL_COPY_MODULATE_COLOR; } if (surface->map->info.flags != flags) { SDL_InvalidateMap(surface->map); } return 0; } int SDL_GetSurfaceColorMod(SDL_Surface * surface, Uint8 * r, Uint8 * g, Uint8 * b) { if (!surface) { return -1; } if (r) { *r = surface->map->info.r; } if (g) { *g = surface->map->info.g; } if (b) { *b = surface->map->info.b; } return 0; } int SDL_SetSurfaceAlphaMod(SDL_Surface * surface, Uint8 alpha) { int flags; if (!surface) { return -1; } surface->map->info.a = alpha; flags = surface->map->info.flags; if (alpha != 0xFF) { surface->map->info.flags |= SDL_COPY_MODULATE_ALPHA; } else { surface->map->info.flags &= ~SDL_COPY_MODULATE_ALPHA; } if (surface->map->info.flags != flags) { SDL_InvalidateMap(surface->map); } return 0; } int SDL_GetSurfaceAlphaMod(SDL_Surface * surface, Uint8 * alpha) { if (!surface) { return -1; } if (alpha) { *alpha = surface->map->info.a; } return 0; } int SDL_SetSurfaceBlendMode(SDL_Surface * surface, SDL_BlendMode blendMode) { int flags, status; if (!surface) { return -1; } status = 0; flags = surface->map->info.flags; surface->map->info.flags &= ~(SDL_COPY_BLEND | SDL_COPY_ADD | SDL_COPY_MOD | SDL_COPY_MUL); switch (blendMode) { case SDL_BLENDMODE_NONE: break; case SDL_BLENDMODE_BLEND: surface->map->info.flags |= SDL_COPY_BLEND; break; case SDL_BLENDMODE_ADD: surface->map->info.flags |= SDL_COPY_ADD; break; case SDL_BLENDMODE_MOD: surface->map->info.flags |= SDL_COPY_MOD; break; case SDL_BLENDMODE_MUL: surface->map->info.flags |= SDL_COPY_MUL; break; default: status = SDL_Unsupported(); break; } if (surface->map->info.flags != flags) { SDL_InvalidateMap(surface->map); } return status; } int SDL_GetSurfaceBlendMode(SDL_Surface * surface, SDL_BlendMode *blendMode) { if (!surface) { return -1; } if (!blendMode) { return 0; } switch (surface->map-> info.flags & (SDL_COPY_BLEND | SDL_COPY_ADD | SDL_COPY_MOD | SDL_COPY_MUL)) { case SDL_COPY_BLEND: *blendMode = SDL_BLENDMODE_BLEND; break; case SDL_COPY_ADD: *blendMode = SDL_BLENDMODE_ADD; break; case SDL_COPY_MOD: *blendMode = SDL_BLENDMODE_MOD; break; case SDL_COPY_MUL: *blendMode = SDL_BLENDMODE_MUL; break; default: *blendMode = SDL_BLENDMODE_NONE; break; } return 0; } SDL_bool SDL_SetClipRect(SDL_Surface * surface, const SDL_Rect * rect) { SDL_Rect full_rect; /* Don't do anything if there's no surface to act on */ if (!surface) { return SDL_FALSE; } /* Set up the full surface rectangle */ full_rect.x = 0; full_rect.y = 0; full_rect.w = surface->w; full_rect.h = surface->h; /* Set the clipping rectangle */ if (!rect) { surface->clip_rect = full_rect; return SDL_TRUE; } return SDL_IntersectRect(rect, &full_rect, &surface->clip_rect); } void SDL_GetClipRect(SDL_Surface * surface, SDL_Rect * rect) { if (surface && rect) { *rect = surface->clip_rect; } } /* * Set up a blit between two surfaces -- split into three parts: * The upper part, SDL_UpperBlit(), performs clipping and rectangle * verification. The lower part is a pointer to a low level * accelerated blitting function. * * These parts are separated out and each used internally by this * library in the optimimum places. They are exported so that if * you know exactly what you are doing, you can optimize your code * by calling the one(s) you need. */ int SDL_LowerBlit(SDL_Surface * src, SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect) { /* Check to make sure the blit mapping is valid */ if ((src->map->dst != dst) || (dst->format->palette && src->map->dst_palette_version != dst->format->palette->version) || (src->format->palette && src->map->src_palette_version != src->format->palette->version)) { if (SDL_MapSurface(src, dst) < 0) { return (-1); } /* just here for debugging */ /* printf */ /* ("src = 0x%08X src->flags = %08X src->map->info.flags = %08x\ndst = 0x%08X dst->flags = %08X dst->map->info.flags = %08X\nsrc->map->blit = 0x%08x\n", */ /* src, dst->flags, src->map->info.flags, dst, dst->flags, */ /* dst->map->info.flags, src->map->blit); */ } return (src->map->blit(src, srcrect, dst, dstrect)); } int SDL_UpperBlit(SDL_Surface * src, const SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect) { SDL_Rect fulldst; int srcx, srcy, w, h; /* Make sure the surfaces aren't locked */ if (!src || !dst) { return SDL_SetError("SDL_UpperBlit: passed a NULL surface"); } if (src->locked || dst->locked) { return SDL_SetError("Surfaces must not be locked during blit"); } /* If the destination rectangle is NULL, use the entire dest surface */ if (dstrect == NULL) { fulldst.x = fulldst.y = 0; fulldst.w = dst->w; fulldst.h = dst->h; dstrect = &fulldst; } /* clip the source rectangle to the source surface */ if (srcrect) { int maxw, maxh; srcx = srcrect->x; w = srcrect->w; if (srcx < 0) { w += srcx; dstrect->x -= srcx; srcx = 0; } maxw = src->w - srcx; if (maxw < w) w = maxw; srcy = srcrect->y; h = srcrect->h; if (srcy < 0) { h += srcy; dstrect->y -= srcy; srcy = 0; } maxh = src->h - srcy; if (maxh < h) h = maxh; } else { srcx = srcy = 0; w = src->w; h = src->h; } /* clip the destination rectangle against the clip rectangle */ { SDL_Rect *clip = &dst->clip_rect; int dx, dy; dx = clip->x - dstrect->x; if (dx > 0) { w -= dx; dstrect->x += dx; srcx += dx; } dx = dstrect->x + w - clip->x - clip->w; if (dx > 0) w -= dx; dy = clip->y - dstrect->y; if (dy > 0) { h -= dy; dstrect->y += dy; srcy += dy; } dy = dstrect->y + h - clip->y - clip->h; if (dy > 0) h -= dy; } /* Switch back to a fast blit if we were previously stretching */ if (src->map->info.flags & SDL_COPY_NEAREST) { src->map->info.flags &= ~SDL_COPY_NEAREST; SDL_InvalidateMap(src->map); } if (w > 0 && h > 0) { SDL_Rect sr; sr.x = srcx; sr.y = srcy; sr.w = dstrect->w = w; sr.h = dstrect->h = h; return SDL_LowerBlit(src, &sr, dst, dstrect); } dstrect->w = dstrect->h = 0; return 0; } int SDL_UpperBlitScaled(SDL_Surface * src, const SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect) { double src_x0, src_y0, src_x1, src_y1; double dst_x0, dst_y0, dst_x1, dst_y1; SDL_Rect final_src, final_dst; double scaling_w, scaling_h; int src_w, src_h; int dst_w, dst_h; /* Make sure the surfaces aren't locked */ if (!src || !dst) { return SDL_SetError("SDL_UpperBlitScaled: passed a NULL surface"); } if (src->locked || dst->locked) { return SDL_SetError("Surfaces must not be locked during blit"); } if (NULL == srcrect) { src_w = src->w; src_h = src->h; } else { src_w = srcrect->w; src_h = srcrect->h; } if (NULL == dstrect) { dst_w = dst->w; dst_h = dst->h; } else { dst_w = dstrect->w; dst_h = dstrect->h; } if (dst_w == src_w && dst_h == src_h) { /* No scaling, defer to regular blit */ return SDL_BlitSurface(src, srcrect, dst, dstrect); } scaling_w = (double)dst_w / src_w; scaling_h = (double)dst_h / src_h; if (NULL == dstrect) { dst_x0 = 0; dst_y0 = 0; dst_x1 = dst_w - 1; dst_y1 = dst_h - 1; } else { dst_x0 = dstrect->x; dst_y0 = dstrect->y; dst_x1 = dst_x0 + dst_w - 1; dst_y1 = dst_y0 + dst_h - 1; } if (NULL == srcrect) { src_x0 = 0; src_y0 = 0; src_x1 = src_w - 1; src_y1 = src_h - 1; } else { src_x0 = srcrect->x; src_y0 = srcrect->y; src_x1 = src_x0 + src_w - 1; src_y1 = src_y0 + src_h - 1; /* Clip source rectangle to the source surface */ if (src_x0 < 0) { dst_x0 -= src_x0 * scaling_w; src_x0 = 0; } if (src_x1 >= src->w) { dst_x1 -= (src_x1 - src->w + 1) * scaling_w; src_x1 = src->w - 1; } if (src_y0 < 0) { dst_y0 -= src_y0 * scaling_h; src_y0 = 0; } if (src_y1 >= src->h) { dst_y1 -= (src_y1 - src->h + 1) * scaling_h; src_y1 = src->h - 1; } } /* Clip destination rectangle to the clip rectangle */ /* Translate to clip space for easier calculations */ dst_x0 -= dst->clip_rect.x; dst_x1 -= dst->clip_rect.x; dst_y0 -= dst->clip_rect.y; dst_y1 -= dst->clip_rect.y; if (dst_x0 < 0) { src_x0 -= dst_x0 / scaling_w; dst_x0 = 0; } if (dst_x1 >= dst->clip_rect.w) { src_x1 -= (dst_x1 - dst->clip_rect.w + 1) / scaling_w; dst_x1 = dst->clip_rect.w - 1; } if (dst_y0 < 0) { src_y0 -= dst_y0 / scaling_h; dst_y0 = 0; } if (dst_y1 >= dst->clip_rect.h) { src_y1 -= (dst_y1 - dst->clip_rect.h + 1) / scaling_h; dst_y1 = dst->clip_rect.h - 1; } /* Translate back to surface coordinates */ dst_x0 += dst->clip_rect.x; dst_x1 += dst->clip_rect.x; dst_y0 += dst->clip_rect.y; dst_y1 += dst->clip_rect.y; final_src.x = (int)SDL_floor(src_x0 + 0.5); final_src.y = (int)SDL_floor(src_y0 + 0.5); final_src.w = (int)SDL_floor(src_x1 + 1 + 0.5) - (int)SDL_floor(src_x0 + 0.5); final_src.h = (int)SDL_floor(src_y1 + 1 + 0.5) - (int)SDL_floor(src_y0 + 0.5); final_dst.x = (int)SDL_floor(dst_x0 + 0.5); final_dst.y = (int)SDL_floor(dst_y0 + 0.5); final_dst.w = (int)SDL_floor(dst_x1 - dst_x0 + 1.5); final_dst.h = (int)SDL_floor(dst_y1 - dst_y0 + 1.5); if (final_dst.w < 0) final_dst.w = 0; if (final_dst.h < 0) final_dst.h = 0; if (dstrect) *dstrect = final_dst; if (final_dst.w == 0 || final_dst.h == 0 || final_src.w <= 0 || final_src.h <= 0) { /* No-op. */ return 0; } return SDL_LowerBlitScaled(src, &final_src, dst, &final_dst); } /** * This is a semi-private blit function and it performs low-level surface * scaled blitting only. */ int SDL_LowerBlitScaled(SDL_Surface * src, SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect) { static const Uint32 complex_copy_flags = ( SDL_COPY_MODULATE_COLOR | SDL_COPY_MODULATE_ALPHA | SDL_COPY_BLEND | SDL_COPY_ADD | SDL_COPY_MOD | SDL_COPY_MUL | SDL_COPY_COLORKEY ); if (!(src->map->info.flags & SDL_COPY_NEAREST)) { src->map->info.flags |= SDL_COPY_NEAREST; SDL_InvalidateMap(src->map); } if ( !(src->map->info.flags & complex_copy_flags) && src->format->format == dst->format->format && !SDL_ISPIXELFORMAT_INDEXED(src->format->format) ) { return SDL_SoftStretch( src, srcrect, dst, dstrect ); } else { return SDL_LowerBlit( src, srcrect, dst, dstrect ); } } /* * Lock a surface to directly access the pixels */ int SDL_LockSurface(SDL_Surface * surface) { if (!surface->locked) { #if SDL_HAVE_RLE /* Perform the lock */ if (surface->flags & SDL_RLEACCEL) { SDL_UnRLESurface(surface, 1); surface->flags |= SDL_RLEACCEL; /* save accel'd state */ } #endif } /* Increment the surface lock count, for recursive locks */ ++surface->locked; /* Ready to go.. */ return (0); } /* * Unlock a previously locked surface */ void SDL_UnlockSurface(SDL_Surface * surface) { /* Only perform an unlock if we are locked */ if (!surface->locked || (--surface->locked > 0)) { return; } #if SDL_HAVE_RLE /* Update RLE encoded surface with new data */ if ((surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL) { surface->flags &= ~SDL_RLEACCEL; /* stop lying */ SDL_RLESurface(surface); } #endif } /* * Creates a new surface identical to the existing surface */ SDL_Surface * SDL_DuplicateSurface(SDL_Surface * surface) { return SDL_ConvertSurface(surface, surface->format, surface->flags); } /* * Convert a surface into the specified pixel format. */ SDL_Surface * SDL_ConvertSurface(SDL_Surface * surface, const SDL_PixelFormat * format, Uint32 flags) { SDL_Surface *convert; Uint32 copy_flags; SDL_Color copy_color; SDL_Rect bounds; int ret; SDL_bool palette_ck_transform = SDL_FALSE; int palette_ck_value = 0; SDL_bool palette_has_alpha = SDL_FALSE; Uint8 *palette_saved_alpha = NULL; if (!surface) { SDL_InvalidParamError("surface"); return NULL; } if (!format) { SDL_InvalidParamError("format"); return NULL; } /* Check for empty destination palette! (results in empty image) */ if (format->palette != NULL) { int i; for (i = 0; i < format->palette->ncolors; ++i) { if ((format->palette->colors[i].r != 0xFF) || (format->palette->colors[i].g != 0xFF) || (format->palette->colors[i].b != 0xFF)) break; } if (i == format->palette->ncolors) { SDL_SetError("Empty destination palette"); return (NULL); } } /* Create a new surface with the desired format */ convert = SDL_CreateRGBSurface(flags, surface->w, surface->h, format->BitsPerPixel, format->Rmask, format->Gmask, format->Bmask, format->Amask); if (convert == NULL) { return (NULL); } /* Copy the palette if any */ if (format->palette && convert->format->palette) { SDL_memcpy(convert->format->palette->colors, format->palette->colors, format->palette->ncolors * sizeof(SDL_Color)); convert->format->palette->ncolors = format->palette->ncolors; } /* Save the original copy flags */ copy_flags = surface->map->info.flags; copy_color.r = surface->map->info.r; copy_color.g = surface->map->info.g; copy_color.b = surface->map->info.b; copy_color.a = surface->map->info.a; surface->map->info.r = 0xFF; surface->map->info.g = 0xFF; surface->map->info.b = 0xFF; surface->map->info.a = 0xFF; surface->map->info.flags = 0; SDL_InvalidateMap(surface->map); /* Copy over the image data */ bounds.x = 0; bounds.y = 0; bounds.w = surface->w; bounds.h = surface->h; /* Source surface has a palette with no real alpha (0 or OPAQUE). * Destination format has alpha. * -> set alpha channel to be opaque */ if (surface->format->palette && format->Amask) { SDL_bool set_opaque = SDL_FALSE; SDL_bool is_opaque, has_alpha_channel; SDL_DetectPalette(surface->format->palette, &is_opaque, &has_alpha_channel); if (is_opaque) { if (!has_alpha_channel) { set_opaque = SDL_TRUE; } } else { palette_has_alpha = SDL_TRUE; } /* Set opaque and backup palette alpha values */ if (set_opaque) { int i; palette_saved_alpha = SDL_stack_alloc(Uint8, surface->format->palette->ncolors); for (i = 0; i < surface->format->palette->ncolors; i++) { palette_saved_alpha[i] = surface->format->palette->colors[i].a; surface->format->palette->colors[i].a = SDL_ALPHA_OPAQUE; } } } /* Transform colorkey to alpha. for cases where source palette has duplicate values, and colorkey is one of them */ if (copy_flags & SDL_COPY_COLORKEY) { if (surface->format->palette && !format->palette) { palette_ck_transform = SDL_TRUE; palette_has_alpha = SDL_TRUE; palette_ck_value = surface->format->palette->colors[surface->map->info.colorkey].a; surface->format->palette->colors[surface->map->info.colorkey].a = SDL_ALPHA_TRANSPARENT; } } ret = SDL_LowerBlit(surface, &bounds, convert, &bounds); /* Restore colorkey alpha value */ if (palette_ck_transform) { surface->format->palette->colors[surface->map->info.colorkey].a = palette_ck_value; } /* Restore palette alpha values */ if (palette_saved_alpha) { int i; for (i = 0; i < surface->format->palette->ncolors; i++) { surface->format->palette->colors[i].a = palette_saved_alpha[i]; } SDL_stack_free(palette_saved_alpha); } /* Clean up the original surface, and update converted surface */ convert->map->info.r = copy_color.r; convert->map->info.g = copy_color.g; convert->map->info.b = copy_color.b; convert->map->info.a = copy_color.a; convert->map->info.flags = (copy_flags & ~(SDL_COPY_COLORKEY | SDL_COPY_BLEND | SDL_COPY_RLE_DESIRED | SDL_COPY_RLE_COLORKEY | SDL_COPY_RLE_ALPHAKEY)); surface->map->info.r = copy_color.r; surface->map->info.g = copy_color.g; surface->map->info.b = copy_color.b; surface->map->info.a = copy_color.a; surface->map->info.flags = copy_flags; SDL_InvalidateMap(surface->map); /* SDL_LowerBlit failed, and so the conversion */ if (ret < 0) { SDL_FreeSurface(convert); return NULL; } if (copy_flags & SDL_COPY_COLORKEY) { SDL_bool set_colorkey_by_color = SDL_FALSE; SDL_bool convert_colorkey = SDL_TRUE; if (surface->format->palette) { if (format->palette && surface->format->palette->ncolors <= format->palette->ncolors && (SDL_memcmp(surface->format->palette->colors, format->palette->colors, surface->format->palette->ncolors * sizeof(SDL_Color)) == 0)) { /* The palette is identical, just set the same colorkey */ SDL_SetColorKey(convert, 1, surface->map->info.colorkey); } else if (!format->palette) { if (format->Amask) { /* No need to add the colorkey, transparency is in the alpha channel*/ } else { /* Only set the colorkey information */ set_colorkey_by_color = SDL_TRUE; convert_colorkey = SDL_FALSE; } } else { set_colorkey_by_color = SDL_TRUE; } } else { set_colorkey_by_color = SDL_TRUE; } if (set_colorkey_by_color) { SDL_Surface *tmp; SDL_Surface *tmp2; int converted_colorkey = 0; /* Create a dummy surface to get the colorkey converted */ tmp = SDL_CreateRGBSurface(0, 1, 1, surface->format->BitsPerPixel, surface->format->Rmask, surface->format->Gmask, surface->format->Bmask, surface->format->Amask); /* Share the palette, if any */ if (surface->format->palette) { SDL_SetSurfacePalette(tmp, surface->format->palette); } SDL_FillRect(tmp, NULL, surface->map->info.colorkey); tmp->map->info.flags &= ~SDL_COPY_COLORKEY; /* Convertion of the colorkey */ tmp2 = SDL_ConvertSurface(tmp, format, 0); /* Get the converted colorkey */ SDL_memcpy(&converted_colorkey, tmp2->pixels, tmp2->format->BytesPerPixel); SDL_FreeSurface(tmp); SDL_FreeSurface(tmp2); /* Set the converted colorkey on the new surface */ SDL_SetColorKey(convert, 1, converted_colorkey); /* This is needed when converting for 3D texture upload */ if (convert_colorkey) { SDL_ConvertColorkeyToAlpha(convert, SDL_TRUE); } } } SDL_SetClipRect(convert, &surface->clip_rect); /* Enable alpha blending by default if the new surface has an * alpha channel or alpha modulation */ if ((surface->format->Amask && format->Amask) || (palette_has_alpha && format->Amask) || (copy_flags & SDL_COPY_MODULATE_ALPHA)) { SDL_SetSurfaceBlendMode(convert, SDL_BLENDMODE_BLEND); } if ((copy_flags & SDL_COPY_RLE_DESIRED) || (flags & SDL_RLEACCEL)) { SDL_SetSurfaceRLE(convert, SDL_RLEACCEL); } /* We're ready to go! */ return (convert); } SDL_Surface * SDL_ConvertSurfaceFormat(SDL_Surface * surface, Uint32 pixel_format, Uint32 flags) { SDL_PixelFormat *fmt; SDL_Surface *convert = NULL; fmt = SDL_AllocFormat(pixel_format); if (fmt) { convert = SDL_ConvertSurface(surface, fmt, flags); SDL_FreeFormat(fmt); } return convert; } /* * Create a surface on the stack for quick blit operations */ static SDL_INLINE SDL_bool SDL_CreateSurfaceOnStack(int width, int height, Uint32 pixel_format, void * pixels, int pitch, SDL_Surface * surface, SDL_PixelFormat * format, SDL_BlitMap * blitmap) { if (SDL_ISPIXELFORMAT_INDEXED(pixel_format)) { SDL_SetError("Indexed pixel formats not supported"); return SDL_FALSE; } if (SDL_InitFormat(format, pixel_format) < 0) { return SDL_FALSE; } SDL_zerop(surface); surface->flags = SDL_PREALLOC; surface->format = format; surface->pixels = pixels; surface->w = width; surface->h = height; surface->pitch = pitch; /* We don't actually need to set up the clip rect for our purposes */ /* SDL_SetClipRect(surface, NULL); */ /* Allocate an empty mapping */ SDL_zerop(blitmap); blitmap->info.r = 0xFF; blitmap->info.g = 0xFF; blitmap->info.b = 0xFF; blitmap->info.a = 0xFF; surface->map = blitmap; /* The surface is ready to go */ surface->refcount = 1; return SDL_TRUE; } /* * Copy a block of pixels of one format to another format */ int SDL_ConvertPixels(int width, int height, Uint32 src_format, const void * src, int src_pitch, Uint32 dst_format, void * dst, int dst_pitch) { SDL_Surface src_surface, dst_surface; SDL_PixelFormat src_fmt, dst_fmt; SDL_BlitMap src_blitmap, dst_blitmap; SDL_Rect rect; void *nonconst_src = (void *) src; /* Check to make sure we are blitting somewhere, so we don't crash */ if (!dst) { return SDL_InvalidParamError("dst"); } if (!dst_pitch) { return SDL_InvalidParamError("dst_pitch"); } #if SDL_HAVE_YUV if (SDL_ISPIXELFORMAT_FOURCC(src_format) && SDL_ISPIXELFORMAT_FOURCC(dst_format)) { return SDL_ConvertPixels_YUV_to_YUV(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch); } else if (SDL_ISPIXELFORMAT_FOURCC(src_format)) { return SDL_ConvertPixels_YUV_to_RGB(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch); } else if (SDL_ISPIXELFORMAT_FOURCC(dst_format)) { return SDL_ConvertPixels_RGB_to_YUV(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch); } #else if (SDL_ISPIXELFORMAT_FOURCC(src_format) || SDL_ISPIXELFORMAT_FOURCC(dst_format)) { SDL_SetError("SDL not built with YUV support"); return -1; } #endif /* Fast path for same format copy */ if (src_format == dst_format) { int i; const int bpp = SDL_BYTESPERPIXEL(src_format); width *= bpp; for (i = height; i--;) { SDL_memcpy(dst, src, width); src = (const Uint8*)src + src_pitch; dst = (Uint8*)dst + dst_pitch; } return 0; } if (!SDL_CreateSurfaceOnStack(width, height, src_format, nonconst_src, src_pitch, &src_surface, &src_fmt, &src_blitmap)) { return -1; } if (!SDL_CreateSurfaceOnStack(width, height, dst_format, dst, dst_pitch, &dst_surface, &dst_fmt, &dst_blitmap)) { return -1; } /* Set up the rect and go! */ rect.x = 0; rect.y = 0; rect.w = width; rect.h = height; return SDL_LowerBlit(&src_surface, &rect, &dst_surface, &rect); } /* * Free a surface created by the above function. */ void SDL_FreeSurface(SDL_Surface * surface) { if (surface == NULL) { return; } if (surface->flags & SDL_DONTFREE) { return; } SDL_InvalidateMap(surface->map); if (--surface->refcount > 0) { return; } while (surface->locked > 0) { SDL_UnlockSurface(surface); } #if SDL_HAVE_RLE if (surface->flags & SDL_RLEACCEL) { SDL_UnRLESurface(surface, 0); } #endif if (surface->format) { SDL_SetSurfacePalette(surface, NULL); SDL_FreeFormat(surface->format); surface->format = NULL; } if (surface->flags & SDL_PREALLOC) { /* Don't free */ } else if (surface->flags & SDL_SIMD_ALIGNED) { /* Free aligned */ SDL_SIMDFree(surface->pixels); } else { /* Normal */ SDL_free(surface->pixels); } if (surface->map) { SDL_FreeBlitMap(surface->map); } SDL_free(surface); } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_surface.c
C
apache-2.0
38,546
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #ifndef SDL_sysvideo_h_ #define SDL_sysvideo_h_ #include "SDL_messagebox.h" #include "SDL_shape.h" #include "SDL_thread.h" #include "SDL_metal.h" #include "SDL_vulkan_internal.h" /* The SDL video driver */ typedef struct SDL_WindowShaper SDL_WindowShaper; typedef struct SDL_ShapeDriver SDL_ShapeDriver; typedef struct SDL_VideoDisplay SDL_VideoDisplay; typedef struct SDL_VideoDevice SDL_VideoDevice; /* Define the SDL window-shaper structure */ struct SDL_WindowShaper { /* The window associated with the shaper */ SDL_Window *window; /* The user's specified coordinates for the window, for once we give it a shape. */ Uint32 userx,usery; /* The parameters for shape calculation. */ SDL_WindowShapeMode mode; /* Has this window been assigned a shape? */ SDL_bool hasshape; void *driverdata; }; /* Define the SDL shape driver structure */ struct SDL_ShapeDriver { SDL_WindowShaper *(*CreateShaper)(SDL_Window * window); int (*SetWindowShape)(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode); int (*ResizeWindowShape)(SDL_Window *window); }; typedef struct SDL_WindowUserData { char *name; void *data; struct SDL_WindowUserData *next; } SDL_WindowUserData; /* Define the SDL window structure, corresponding to toplevel windows */ struct SDL_Window { const void *magic; Uint32 id; char *title; SDL_Surface *icon; int x, y; int w, h; int min_w, min_h; int max_w, max_h; Uint32 flags; Uint32 last_fullscreen_flags; /* Stored position and size for windowed mode */ SDL_Rect windowed; SDL_DisplayMode fullscreen_mode; float opacity; float brightness; Uint16 *gamma; Uint16 *saved_gamma; /* (just offset into gamma) */ SDL_Surface *surface; SDL_bool surface_valid; SDL_bool is_hiding; SDL_bool is_destroying; SDL_bool is_dropping; /* drag/drop in progress, expecting SDL_SendDropComplete(). */ SDL_WindowShaper *shaper; SDL_HitTest hit_test; void *hit_test_data; SDL_WindowUserData *data; void *driverdata; SDL_Window *prev; SDL_Window *next; }; #define FULLSCREEN_VISIBLE(W) \ (((W)->flags & SDL_WINDOW_FULLSCREEN) && \ ((W)->flags & SDL_WINDOW_SHOWN) && \ !((W)->flags & SDL_WINDOW_MINIMIZED)) /* * Define the SDL display structure. * This corresponds to physical monitors attached to the system. */ struct SDL_VideoDisplay { char *name; int max_display_modes; int num_display_modes; SDL_DisplayMode *display_modes; SDL_DisplayMode desktop_mode; SDL_DisplayMode current_mode; SDL_DisplayOrientation orientation; SDL_Window *fullscreen_window; SDL_VideoDevice *device; void *driverdata; }; /* Forward declaration */ struct SDL_SysWMinfo; /* Define the SDL video driver structure */ #define _THIS SDL_VideoDevice *_this struct SDL_VideoDevice { /* * * */ /* The name of this video driver */ const char *name; /* * * */ /* Initialization/Query functions */ /* * Initialize the native video subsystem, filling in the list of * displays for this driver, returning 0 or -1 if there's an error. */ int (*VideoInit) (_THIS); /* * Reverse the effects VideoInit() -- called if VideoInit() fails or * if the application is shutting down the video subsystem. */ void (*VideoQuit) (_THIS); /* * Reinitialize the touch devices -- called if an unknown touch ID occurs. */ void (*ResetTouch) (_THIS); /* * * */ /* * Display functions */ /* * Get the bounds of a display */ int (*GetDisplayBounds) (_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); /* * Get the usable bounds of a display (bounds minus menubar or whatever) */ int (*GetDisplayUsableBounds) (_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); /* * Get the dots/pixels-per-inch of a display */ int (*GetDisplayDPI) (_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi); /* * Get a list of the available display modes for a display. */ void (*GetDisplayModes) (_THIS, SDL_VideoDisplay * display); /* * Setting the display mode is independent of creating windows, so * when the display mode is changed, all existing windows should have * their data updated accordingly, including the display surfaces * associated with them. */ int (*SetDisplayMode) (_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); /* * * */ /* * Window functions */ int (*CreateSDLWindow) (_THIS, SDL_Window * window); int (*CreateSDLWindowFrom) (_THIS, SDL_Window * window, const void *data); void (*SetWindowTitle) (_THIS, SDL_Window * window); void (*SetWindowIcon) (_THIS, SDL_Window * window, SDL_Surface * icon); void (*SetWindowPosition) (_THIS, SDL_Window * window); void (*SetWindowSize) (_THIS, SDL_Window * window); void (*SetWindowMinimumSize) (_THIS, SDL_Window * window); void (*SetWindowMaximumSize) (_THIS, SDL_Window * window); int (*GetWindowBordersSize) (_THIS, SDL_Window * window, int *top, int *left, int *bottom, int *right); int (*SetWindowOpacity) (_THIS, SDL_Window * window, float opacity); int (*SetWindowModalFor) (_THIS, SDL_Window * modal_window, SDL_Window * parent_window); int (*SetWindowInputFocus) (_THIS, SDL_Window * window); void (*ShowWindow) (_THIS, SDL_Window * window); void (*HideWindow) (_THIS, SDL_Window * window); void (*RaiseWindow) (_THIS, SDL_Window * window); void (*MaximizeWindow) (_THIS, SDL_Window * window); void (*MinimizeWindow) (_THIS, SDL_Window * window); void (*RestoreWindow) (_THIS, SDL_Window * window); void (*SetWindowBordered) (_THIS, SDL_Window * window, SDL_bool bordered); void (*SetWindowResizable) (_THIS, SDL_Window * window, SDL_bool resizable); void (*SetWindowFullscreen) (_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen); int (*SetWindowGammaRamp) (_THIS, SDL_Window * window, const Uint16 * ramp); int (*GetWindowGammaRamp) (_THIS, SDL_Window * window, Uint16 * ramp); void (*SetWindowGrab) (_THIS, SDL_Window * window, SDL_bool grabbed); void (*DestroyWindow) (_THIS, SDL_Window * window); int (*CreateWindowFramebuffer) (_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch); int (*UpdateWindowFramebuffer) (_THIS, SDL_Window * window, const SDL_Rect * rects, int numrects); void (*DestroyWindowFramebuffer) (_THIS, SDL_Window * window); void (*OnWindowEnter) (_THIS, SDL_Window * window); /* * * */ /* * Shaped-window functions */ SDL_ShapeDriver shape_driver; /* Get some platform dependent window information */ SDL_bool(*GetWindowWMInfo) (_THIS, SDL_Window * window, struct SDL_SysWMinfo * info); /* * * */ /* * OpenGL support */ int (*GL_LoadLibrary) (_THIS, const char *path); void *(*GL_GetProcAddress) (_THIS, const char *proc); void (*GL_UnloadLibrary) (_THIS); SDL_GLContext(*GL_CreateContext) (_THIS, SDL_Window * window); int (*GL_MakeCurrent) (_THIS, SDL_Window * window, SDL_GLContext context); void (*GL_GetDrawableSize) (_THIS, SDL_Window * window, int *w, int *h); int (*GL_SetSwapInterval) (_THIS, int interval); int (*GL_GetSwapInterval) (_THIS); int (*GL_SwapWindow) (_THIS, SDL_Window * window); void (*GL_DeleteContext) (_THIS, SDL_GLContext context); void (*GL_DefaultProfileConfig) (_THIS, int *mask, int *major, int *minor); /* * * */ /* * Vulkan support */ int (*Vulkan_LoadLibrary) (_THIS, const char *path); void (*Vulkan_UnloadLibrary) (_THIS); SDL_bool (*Vulkan_GetInstanceExtensions) (_THIS, SDL_Window *window, unsigned *count, const char **names); SDL_bool (*Vulkan_CreateSurface) (_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface); void (*Vulkan_GetDrawableSize) (_THIS, SDL_Window * window, int *w, int *h); /* * * */ /* * Metal support */ SDL_MetalView (*Metal_CreateView) (_THIS, SDL_Window * window); void (*Metal_DestroyView) (_THIS, SDL_MetalView view); void *(*Metal_GetLayer) (_THIS, SDL_MetalView view); void (*Metal_GetDrawableSize) (_THIS, SDL_Window * window, int *w, int *h); /* * * */ /* * Event manager functions */ void (*PumpEvents) (_THIS); /* Suspend the screensaver */ void (*SuspendScreenSaver) (_THIS); /* Text input */ void (*StartTextInput) (_THIS); void (*StopTextInput) (_THIS); void (*SetTextInputRect) (_THIS, SDL_Rect *rect); /* Screen keyboard */ SDL_bool (*HasScreenKeyboardSupport) (_THIS); void (*ShowScreenKeyboard) (_THIS, SDL_Window *window); void (*HideScreenKeyboard) (_THIS, SDL_Window *window); SDL_bool (*IsScreenKeyboardShown) (_THIS, SDL_Window *window); /* Clipboard */ int (*SetClipboardText) (_THIS, const char *text); char * (*GetClipboardText) (_THIS); SDL_bool (*HasClipboardText) (_THIS); /* MessageBox */ int (*ShowMessageBox) (_THIS, const SDL_MessageBoxData *messageboxdata, int *buttonid); /* Hit-testing */ int (*SetWindowHitTest)(SDL_Window * window, SDL_bool enabled); /* Tell window that app enabled drag'n'drop events */ void (*AcceptDragAndDrop)(SDL_Window * window, SDL_bool accept); /* * * */ /* Data common to all drivers */ SDL_bool is_dummy; SDL_bool suspend_screensaver; int num_displays; SDL_VideoDisplay *displays; SDL_Window *windows; SDL_Window *grabbed_window; Uint8 window_magic; Uint32 next_object_id; char *clipboard_text; /* * * */ /* Data used by the GL drivers */ struct { int red_size; int green_size; int blue_size; int alpha_size; int depth_size; int buffer_size; int stencil_size; int double_buffer; int accum_red_size; int accum_green_size; int accum_blue_size; int accum_alpha_size; int stereo; int multisamplebuffers; int multisamplesamples; int accelerated; int major_version; int minor_version; int flags; int profile_mask; int share_with_current_context; int release_behavior; int reset_notification; int framebuffer_srgb_capable; int no_error; int retained_backing; int driver_loaded; char driver_path[256]; void *dll_handle; } gl_config; /* * * */ /* Cache current GL context; don't call the OS when it hasn't changed. */ /* We have the global pointers here so Cocoa continues to work the way it always has, and the thread-local storage for the general case. */ SDL_Window *current_glwin; SDL_GLContext current_glctx; SDL_TLSID current_glwin_tls; SDL_TLSID current_glctx_tls; /* Flag that stores whether it's allowed to call SDL_GL_MakeCurrent() * with a NULL window, but a non-NULL context. (Not allowed in most cases, * except on EGL under some circumstances.) */ SDL_bool gl_allow_no_surface; /* * * */ /* Data used by the Vulkan drivers */ struct { PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; int loader_loaded; char loader_path[256]; void *loader_handle; } vulkan_config; /* * * */ /* Data private to this driver */ void *driverdata; struct SDL_GLDriverData *gl_data; #if SDL_VIDEO_OPENGL_EGL struct SDL_EGL_VideoData *egl_data; #endif #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 struct SDL_PrivateGLESData *gles_data; #endif /* * * */ /* The function used to dispose of this structure */ void (*free) (_THIS); }; typedef struct VideoBootStrap { const char *name; const char *desc; int (*available) (void); SDL_VideoDevice *(*create) (int devindex); } VideoBootStrap; /* Not all of these are available in a given build. Use #ifdefs, etc. */ extern VideoBootStrap COCOA_bootstrap; extern VideoBootStrap X11_bootstrap; extern VideoBootStrap DirectFB_bootstrap; extern VideoBootStrap WINDOWS_bootstrap; extern VideoBootStrap WINRT_bootstrap; extern VideoBootStrap HAIKU_bootstrap; extern VideoBootStrap PND_bootstrap; extern VideoBootStrap UIKIT_bootstrap; extern VideoBootStrap Android_bootstrap; extern VideoBootStrap PSP_bootstrap; extern VideoBootStrap RPI_bootstrap; extern VideoBootStrap KMSDRM_bootstrap; extern VideoBootStrap DUMMY_bootstrap; extern VideoBootStrap Wayland_bootstrap; extern VideoBootStrap NACL_bootstrap; extern VideoBootStrap VIVANTE_bootstrap; extern VideoBootStrap Emscripten_bootstrap; extern VideoBootStrap QNX_bootstrap; extern VideoBootStrap OFFSCREEN_bootstrap; extern VideoBootStrap AliOS_bootstrap; extern SDL_VideoDevice *SDL_GetVideoDevice(void); extern int SDL_AddBasicVideoDisplay(const SDL_DisplayMode * desktop_mode); extern int SDL_AddVideoDisplay(const SDL_VideoDisplay * display); extern SDL_bool SDL_AddDisplayMode(SDL_VideoDisplay *display, const SDL_DisplayMode * mode); extern int SDL_GetIndexOfDisplay(SDL_VideoDisplay *display); extern SDL_VideoDisplay *SDL_GetDisplay(int displayIndex); extern SDL_VideoDisplay *SDL_GetDisplayForWindow(SDL_Window *window); extern void *SDL_GetDisplayDriverData( int displayIndex ); extern SDL_bool SDL_IsVideoContextExternal(void); extern void SDL_GL_DeduceMaxSupportedESProfile(int* major, int* minor); extern int SDL_RecreateWindow(SDL_Window * window, Uint32 flags); extern SDL_bool SDL_HasWindows(void); extern void SDL_OnWindowShown(SDL_Window * window); extern void SDL_OnWindowHidden(SDL_Window * window); extern void SDL_OnWindowResized(SDL_Window * window); extern void SDL_OnWindowMinimized(SDL_Window * window); extern void SDL_OnWindowRestored(SDL_Window * window); extern void SDL_OnWindowEnter(SDL_Window * window); extern void SDL_OnWindowLeave(SDL_Window * window); extern void SDL_OnWindowFocusGained(SDL_Window * window); extern void SDL_OnWindowFocusLost(SDL_Window * window); extern void SDL_UpdateWindowGrab(SDL_Window * window); extern SDL_Window * SDL_GetFocusWindow(void); extern SDL_bool SDL_ShouldAllowTopmost(void); extern float SDL_ComputeDiagonalDPI(int hpix, int vpix, float hinches, float vinches); extern void SDL_ToggleDragAndDropSupport(void); #endif /* SDL_sysvideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_sysvideo.h
C
apache-2.0
15,683
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* The high-level video driver subsystem */ #include "SDL.h" #include "SDL_video.h" #include "SDL_sysvideo.h" #include "SDL_blit.h" #include "SDL_pixels_c.h" #include "SDL_rect_c.h" #include "../events/SDL_events_c.h" #include "../timer/SDL_timer_c.h" #include "SDL_syswm.h" #if SDL_VIDEO_OPENGL #include "SDL_opengl.h" #endif /* SDL_VIDEO_OPENGL */ #if SDL_VIDEO_OPENGL_ES && !SDL_VIDEO_OPENGL #include "SDL_opengles.h" #endif /* SDL_VIDEO_OPENGL_ES && !SDL_VIDEO_OPENGL */ /* GL and GLES2 headers conflict on Linux 32 bits */ #if SDL_VIDEO_OPENGL_ES2 && !SDL_VIDEO_OPENGL #include "SDL_opengles2.h" #endif /* SDL_VIDEO_OPENGL_ES2 && !SDL_VIDEO_OPENGL */ #if !SDL_VIDEO_OPENGL #ifndef GL_CONTEXT_RELEASE_BEHAVIOR_KHR #define GL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x82FB #endif #endif #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif /* Available video drivers */ static VideoBootStrap *bootstrap[] = { #if SDL_VIDEO_DRIVER_COCOA &COCOA_bootstrap, #endif #if SDL_VIDEO_DRIVER_X11 &X11_bootstrap, #endif #if SDL_VIDEO_DRIVER_WAYLAND &Wayland_bootstrap, #endif #if SDL_VIDEO_DRIVER_VIVANTE &VIVANTE_bootstrap, #endif #if SDL_VIDEO_DRIVER_DIRECTFB &DirectFB_bootstrap, #endif #if SDL_VIDEO_DRIVER_WINDOWS &WINDOWS_bootstrap, #endif #if SDL_VIDEO_DRIVER_WINRT &WINRT_bootstrap, #endif #if SDL_VIDEO_DRIVER_HAIKU &HAIKU_bootstrap, #endif #if SDL_VIDEO_DRIVER_PANDORA &PND_bootstrap, #endif #if SDL_VIDEO_DRIVER_UIKIT &UIKIT_bootstrap, #endif #if SDL_VIDEO_DRIVER_ANDROID &Android_bootstrap, #endif #if SDL_VIDEO_DRIVER_PSP &PSP_bootstrap, #endif #if SDL_VIDEO_DRIVER_KMSDRM &KMSDRM_bootstrap, #endif #if SDL_VIDEO_DRIVER_RPI &RPI_bootstrap, #endif #if SDL_VIDEO_DRIVER_NACL &NACL_bootstrap, #endif #if SDL_VIDEO_DRIVER_EMSCRIPTEN &Emscripten_bootstrap, #endif #if SDL_VIDEO_DRIVER_QNX &QNX_bootstrap, #endif #if SDL_VIDEO_DRIVER_OFFSCREEN &OFFSCREEN_bootstrap, #endif #if SDL_VIDEO_DRIVER_DUMMY &DUMMY_bootstrap, #endif #ifdef SDL_VIDEO_DRIVER_ALIOS &AliOS_bootstrap, #endif NULL }; static SDL_VideoDevice *_this = NULL; #define CHECK_WINDOW_MAGIC(window, retval) \ if (!_this) { \ SDL_UninitializedVideo(); \ return retval; \ } \ SDL_assert(window && window->magic == &_this->window_magic); \ if (!window || window->magic != &_this->window_magic) { \ SDL_SetError("Invalid window"); \ return retval; \ } #define CHECK_DISPLAY_INDEX(displayIndex, retval) \ if (!_this) { \ SDL_UninitializedVideo(); \ return retval; \ } \ SDL_assert(_this->displays != NULL); \ SDL_assert(displayIndex >= 0 && displayIndex < _this->num_displays); \ if (displayIndex < 0 || displayIndex >= _this->num_displays) { \ SDL_SetError("displayIndex must be in the range 0 - %d", \ _this->num_displays - 1); \ return retval; \ } #define FULLSCREEN_MASK (SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN) #ifdef __MACOSX__ /* Support for Mac OS X fullscreen spaces */ extern SDL_bool Cocoa_IsWindowInFullscreenSpace(SDL_Window * window); extern SDL_bool Cocoa_SetWindowFullscreenSpace(SDL_Window * window, SDL_bool state); #endif /* Support for framebuffer emulation using an accelerated renderer */ #define SDL_WINDOWTEXTUREDATA "_SDL_WindowTextureData" typedef struct { SDL_Renderer *renderer; SDL_Texture *texture; void *pixels; int pitch; int bytes_per_pixel; } SDL_WindowTextureData; static SDL_bool ShouldUseTextureFramebuffer() { const char *hint; /* If there's no native framebuffer support then there's no option */ if (!_this->CreateWindowFramebuffer) { return SDL_TRUE; } /* If this is the dummy driver there is no texture support */ if (_this->is_dummy) { return SDL_FALSE; } /* If the user has specified a software renderer we can't use a texture framebuffer, or renderer creation will go recursive. */ hint = SDL_GetHint(SDL_HINT_RENDER_DRIVER); if (hint && SDL_strcasecmp(hint, "software") == 0) { return SDL_FALSE; } /* See if the user or application wants a specific behavior */ hint = SDL_GetHint(SDL_HINT_FRAMEBUFFER_ACCELERATION); if (hint) { if (*hint == '0' || SDL_strcasecmp(hint, "false") == 0) { return SDL_FALSE; } else { return SDL_TRUE; } } /* Each platform has different performance characteristics */ #if defined(__WIN32__) /* GDI BitBlt() is way faster than Direct3D dynamic textures right now. */ return SDL_FALSE; #elif defined(__MACOSX__) /* Mac OS X uses OpenGL as the native fast path (for cocoa and X11) */ return SDL_TRUE; #elif defined(__LINUX__) /* Properly configured OpenGL drivers are faster than MIT-SHM */ #if SDL_VIDEO_OPENGL /* Ugh, find a way to cache this value! */ { SDL_Window *window; SDL_GLContext context; SDL_bool hasAcceleratedOpenGL = SDL_FALSE; window = SDL_CreateWindow("OpenGL test", -32, -32, 32, 32, SDL_WINDOW_OPENGL|SDL_WINDOW_HIDDEN); if (window) { context = SDL_GL_CreateContext(window); if (context) { const GLubyte *(APIENTRY * glGetStringFunc) (GLenum); const char *vendor = NULL; glGetStringFunc = SDL_GL_GetProcAddress("glGetString"); if (glGetStringFunc) { vendor = (const char *) glGetStringFunc(GL_VENDOR); } /* Add more vendors here at will... */ if (vendor && (SDL_strstr(vendor, "ATI Technologies") || SDL_strstr(vendor, "NVIDIA"))) { hasAcceleratedOpenGL = SDL_TRUE; } SDL_GL_DeleteContext(context); } SDL_DestroyWindow(window); } return hasAcceleratedOpenGL; } #elif SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 /* Let's be optimistic about this! */ return SDL_TRUE; #else return SDL_FALSE; #endif #else /* Play it safe, assume that if there is a framebuffer driver that it's optimized for the current platform. */ return SDL_FALSE; #endif } static int SDL_CreateWindowTexture(SDL_VideoDevice *unused, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch) { SDL_WindowTextureData *data; data = SDL_GetWindowData(window, SDL_WINDOWTEXTUREDATA); if (!data) { SDL_Renderer *renderer = NULL; int i; const char *hint = SDL_GetHint(SDL_HINT_FRAMEBUFFER_ACCELERATION); /* Check to see if there's a specific driver requested */ if (hint && *hint != '0' && *hint != '1' && SDL_strcasecmp(hint, "true") != 0 && SDL_strcasecmp(hint, "false") != 0 && SDL_strcasecmp(hint, "software") != 0) { for (i = 0; i < SDL_GetNumRenderDrivers(); ++i) { SDL_RendererInfo info; SDL_GetRenderDriverInfo(i, &info); if (SDL_strcasecmp(info.name, hint) == 0) { renderer = SDL_CreateRenderer(window, i, 0); break; } } } if (!renderer) { for (i = 0; i < SDL_GetNumRenderDrivers(); ++i) { SDL_RendererInfo info; SDL_GetRenderDriverInfo(i, &info); if (SDL_strcmp(info.name, "software") != 0) { renderer = SDL_CreateRenderer(window, i, 0); if (renderer) { break; } } } } if (!renderer) { return SDL_SetError("No hardware accelerated renderers available"); } /* Create the data after we successfully create the renderer (bug #1116) */ data = (SDL_WindowTextureData *)SDL_calloc(1, sizeof(*data)); if (!data) { SDL_DestroyRenderer(renderer); return SDL_OutOfMemory(); } SDL_SetWindowData(window, SDL_WINDOWTEXTUREDATA, data); data->renderer = renderer; } /* Free any old texture and pixel data */ if (data->texture) { SDL_DestroyTexture(data->texture); data->texture = NULL; } SDL_free(data->pixels); data->pixels = NULL; { SDL_RendererInfo info; Uint32 i; if (SDL_GetRendererInfo(data->renderer, &info) < 0) { return -1; } /* Find the first format without an alpha channel */ *format = info.texture_formats[0]; for (i = 0; i < info.num_texture_formats; ++i) { if (!SDL_ISPIXELFORMAT_FOURCC(info.texture_formats[i]) && !SDL_ISPIXELFORMAT_ALPHA(info.texture_formats[i])) { *format = info.texture_formats[i]; break; } } } data->texture = SDL_CreateTexture(data->renderer, *format, SDL_TEXTUREACCESS_STREAMING, window->w, window->h); if (!data->texture) { return -1; } /* Create framebuffer data */ data->bytes_per_pixel = SDL_BYTESPERPIXEL(*format); data->pitch = (((window->w * data->bytes_per_pixel) + 3) & ~3); { /* Make static analysis happy about potential malloc(0) calls. */ const size_t allocsize = window->h * data->pitch; data->pixels = SDL_malloc((allocsize > 0) ? allocsize : 1); if (!data->pixels) { return SDL_OutOfMemory(); } } *pixels = data->pixels; *pitch = data->pitch; /* Make sure we're not double-scaling the viewport */ SDL_RenderSetViewport(data->renderer, NULL); return 0; } static int SDL_UpdateWindowTexture(SDL_VideoDevice *unused, SDL_Window * window, const SDL_Rect * rects, int numrects) { SDL_WindowTextureData *data; SDL_Rect rect; void *src; data = SDL_GetWindowData(window, SDL_WINDOWTEXTUREDATA); if (!data || !data->texture) { return SDL_SetError("No window texture data"); } /* Update a single rect that contains subrects for best DMA performance */ if (SDL_GetSpanEnclosingRect(window->w, window->h, numrects, rects, &rect)) { src = (void *)((Uint8 *)data->pixels + rect.y * data->pitch + rect.x * data->bytes_per_pixel); if (SDL_UpdateTexture(data->texture, &rect, src, data->pitch) < 0) { return -1; } if (SDL_RenderCopy(data->renderer, data->texture, NULL, NULL) < 0) { return -1; } SDL_RenderPresent(data->renderer); } return 0; } static void SDL_DestroyWindowTexture(SDL_VideoDevice *unused, SDL_Window * window) { SDL_WindowTextureData *data; data = SDL_SetWindowData(window, SDL_WINDOWTEXTUREDATA, NULL); if (!data) { return; } if (data->texture) { SDL_DestroyTexture(data->texture); } if (data->renderer) { SDL_DestroyRenderer(data->renderer); } SDL_free(data->pixels); SDL_free(data); } static int cmpmodes(const void *A, const void *B) { const SDL_DisplayMode *a = (const SDL_DisplayMode *) A; const SDL_DisplayMode *b = (const SDL_DisplayMode *) B; if (a == b) { return 0; } else if (a->w != b->w) { return b->w - a->w; } else if (a->h != b->h) { return b->h - a->h; } else if (SDL_BITSPERPIXEL(a->format) != SDL_BITSPERPIXEL(b->format)) { return SDL_BITSPERPIXEL(b->format) - SDL_BITSPERPIXEL(a->format); } else if (SDL_PIXELLAYOUT(a->format) != SDL_PIXELLAYOUT(b->format)) { return SDL_PIXELLAYOUT(b->format) - SDL_PIXELLAYOUT(a->format); } else if (a->refresh_rate != b->refresh_rate) { return b->refresh_rate - a->refresh_rate; } return 0; } static int SDL_UninitializedVideo() { return SDL_SetError("Video subsystem has not been initialized"); } int SDL_GetNumVideoDrivers(void) { return SDL_arraysize(bootstrap) - 1; } const char * SDL_GetVideoDriver(int index) { if (index >= 0 && index < SDL_GetNumVideoDrivers()) { return bootstrap[index]->name; } return NULL; } /* * Initialize the video and event subsystems -- determine native pixel format */ int SDL_VideoInit(const char *driver_name) { SDL_VideoDevice *video; int index; int i; /* Check to make sure we don't overwrite '_this' */ if (_this != NULL) { SDL_VideoQuit(); } #if !SDL_TIMERS_DISABLED SDL_TicksInit(); #endif /* Start the event loop */ if (SDL_InitSubSystem(SDL_INIT_EVENTS) < 0 || SDL_KeyboardInit() < 0 || SDL_MouseInit() < 0 || SDL_TouchInit() < 0) { return -1; } /* Select the proper video driver */ index = 0; video = NULL; if (driver_name == NULL) { driver_name = SDL_getenv("SDL_VIDEODRIVER"); } if (driver_name != NULL) { for (i = 0; bootstrap[i]; ++i) { if (SDL_strncasecmp(bootstrap[i]->name, driver_name, SDL_strlen(driver_name)) == 0) { if (bootstrap[i]->available()) { video = bootstrap[i]->create(index); break; } } } } else { for (i = 0; bootstrap[i]; ++i) { if (bootstrap[i]->available()) { video = bootstrap[i]->create(index); if (video != NULL) { break; } } } } if (video == NULL) { if (driver_name) { return SDL_SetError("%s not available", driver_name); } return SDL_SetError("No available video device"); } _this = video; _this->name = bootstrap[i]->name; _this->next_object_id = 1; /* Set some very sane GL defaults */ _this->gl_config.driver_loaded = 0; _this->gl_config.dll_handle = NULL; SDL_GL_ResetAttributes(); _this->current_glwin_tls = SDL_TLSCreate(); _this->current_glctx_tls = SDL_TLSCreate(); /* Initialize the video subsystem */ if (_this->VideoInit(_this) < 0) { SDL_VideoQuit(); return -1; } /* Make sure some displays were added */ if (_this->num_displays == 0) { SDL_VideoQuit(); return SDL_SetError("The video driver did not add any displays"); } /* Add the renderer framebuffer emulation if desired */ if (ShouldUseTextureFramebuffer()) { _this->CreateWindowFramebuffer = SDL_CreateWindowTexture; _this->UpdateWindowFramebuffer = SDL_UpdateWindowTexture; _this->DestroyWindowFramebuffer = SDL_DestroyWindowTexture; } /* Disable the screen saver by default. This is a change from <= 2.0.1, but most things using SDL are games or media players; you wouldn't want a screensaver to trigger if you're playing exclusively with a joystick, or passively watching a movie. Things that use SDL but function more like a normal desktop app should explicitly reenable the screensaver. */ if (!SDL_GetHintBoolean(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, SDL_FALSE)) { SDL_DisableScreenSaver(); } /* If we don't use a screen keyboard, turn on text input by default, otherwise programs that expect to get text events without enabling UNICODE input won't get any events. Actually, come to think of it, you needed to call SDL_EnableUNICODE(1) in SDL 1.2 before you got text input events. Hmm... */ if (!SDL_HasScreenKeyboardSupport()) { SDL_StartTextInput(); } /* We're ready to go! */ return 0; } const char * SDL_GetCurrentVideoDriver() { if (!_this) { SDL_UninitializedVideo(); return NULL; } return _this->name; } SDL_VideoDevice * SDL_GetVideoDevice(void) { return _this; } int SDL_AddBasicVideoDisplay(const SDL_DisplayMode * desktop_mode) { SDL_VideoDisplay display; SDL_zero(display); if (desktop_mode) { display.desktop_mode = *desktop_mode; } display.current_mode = display.desktop_mode; return SDL_AddVideoDisplay(&display); } int SDL_AddVideoDisplay(const SDL_VideoDisplay * display) { SDL_VideoDisplay *displays; int index = -1; displays = SDL_realloc(_this->displays, (_this->num_displays + 1) * sizeof(*displays)); if (displays) { index = _this->num_displays++; displays[index] = *display; displays[index].device = _this; _this->displays = displays; if (display->name) { displays[index].name = SDL_strdup(display->name); } else { char name[32]; SDL_itoa(index, name, 10); displays[index].name = SDL_strdup(name); } } else { SDL_OutOfMemory(); } return index; } int SDL_GetNumVideoDisplays(void) { if (!_this) { SDL_UninitializedVideo(); return 0; } return _this->num_displays; } int SDL_GetIndexOfDisplay(SDL_VideoDisplay *display) { int displayIndex; for (displayIndex = 0; displayIndex < _this->num_displays; ++displayIndex) { if (display == &_this->displays[displayIndex]) { return displayIndex; } } /* Couldn't find the display, just use index 0 */ return 0; } void * SDL_GetDisplayDriverData(int displayIndex) { CHECK_DISPLAY_INDEX(displayIndex, NULL); return _this->displays[displayIndex].driverdata; } SDL_bool SDL_IsVideoContextExternal(void) { return SDL_GetHintBoolean(SDL_HINT_VIDEO_EXTERNAL_CONTEXT, SDL_FALSE); } const char * SDL_GetDisplayName(int displayIndex) { CHECK_DISPLAY_INDEX(displayIndex, NULL); return _this->displays[displayIndex].name; } int SDL_GetDisplayBounds(int displayIndex, SDL_Rect * rect) { CHECK_DISPLAY_INDEX(displayIndex, -1); if (rect) { SDL_VideoDisplay *display = &_this->displays[displayIndex]; if (_this->GetDisplayBounds) { if (_this->GetDisplayBounds(_this, display, rect) == 0) { return 0; } } /* Assume that the displays are left to right */ if (displayIndex == 0) { rect->x = 0; rect->y = 0; } else { SDL_GetDisplayBounds(displayIndex-1, rect); rect->x += rect->w; } rect->w = display->current_mode.w; rect->h = display->current_mode.h; } return 0; /* !!! FIXME: should this be an error if (rect==NULL) ? */ } static int ParseDisplayUsableBoundsHint(SDL_Rect *rect) { const char *hint = SDL_GetHint(SDL_HINT_DISPLAY_USABLE_BOUNDS); return hint && (SDL_sscanf(hint, "%d,%d,%d,%d", &rect->x, &rect->y, &rect->w, &rect->h) == 4); } int SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect * rect) { CHECK_DISPLAY_INDEX(displayIndex, -1); if (rect) { SDL_VideoDisplay *display = &_this->displays[displayIndex]; if ((displayIndex == 0) && ParseDisplayUsableBoundsHint(rect)) { return 0; } if (_this->GetDisplayUsableBounds) { if (_this->GetDisplayUsableBounds(_this, display, rect) == 0) { return 0; } } /* Oh well, just give the entire display bounds. */ return SDL_GetDisplayBounds(displayIndex, rect); } return 0; /* !!! FIXME: should this be an error if (rect==NULL) ? */ } int SDL_GetDisplayDPI(int displayIndex, float * ddpi, float * hdpi, float * vdpi) { SDL_VideoDisplay *display; CHECK_DISPLAY_INDEX(displayIndex, -1); display = &_this->displays[displayIndex]; if (_this->GetDisplayDPI) { if (_this->GetDisplayDPI(_this, display, ddpi, hdpi, vdpi) == 0) { return 0; } } else { return SDL_Unsupported(); } return -1; } SDL_DisplayOrientation SDL_GetDisplayOrientation(int displayIndex) { SDL_VideoDisplay *display; CHECK_DISPLAY_INDEX(displayIndex, SDL_ORIENTATION_UNKNOWN); display = &_this->displays[displayIndex]; return display->orientation; } SDL_bool SDL_AddDisplayMode(SDL_VideoDisplay * display, const SDL_DisplayMode * mode) { SDL_DisplayMode *modes; int i, nmodes; /* Make sure we don't already have the mode in the list */ modes = display->display_modes; nmodes = display->num_display_modes; for (i = 0; i < nmodes; ++i) { if (cmpmodes(mode, &modes[i]) == 0) { return SDL_FALSE; } } /* Go ahead and add the new mode */ if (nmodes == display->max_display_modes) { modes = SDL_realloc(modes, (display->max_display_modes + 32) * sizeof(*modes)); if (!modes) { return SDL_FALSE; } display->display_modes = modes; display->max_display_modes += 32; } modes[nmodes] = *mode; display->num_display_modes++; /* Re-sort video modes */ SDL_qsort(display->display_modes, display->num_display_modes, sizeof(SDL_DisplayMode), cmpmodes); return SDL_TRUE; } static int SDL_GetNumDisplayModesForDisplay(SDL_VideoDisplay * display) { if (!display->num_display_modes && _this->GetDisplayModes) { _this->GetDisplayModes(_this, display); SDL_qsort(display->display_modes, display->num_display_modes, sizeof(SDL_DisplayMode), cmpmodes); } return display->num_display_modes; } int SDL_GetNumDisplayModes(int displayIndex) { CHECK_DISPLAY_INDEX(displayIndex, -1); return SDL_GetNumDisplayModesForDisplay(&_this->displays[displayIndex]); } int SDL_GetDisplayMode(int displayIndex, int index, SDL_DisplayMode * mode) { SDL_VideoDisplay *display; CHECK_DISPLAY_INDEX(displayIndex, -1); display = &_this->displays[displayIndex]; if (index < 0 || index >= SDL_GetNumDisplayModesForDisplay(display)) { return SDL_SetError("index must be in the range of 0 - %d", SDL_GetNumDisplayModesForDisplay(display) - 1); } if (mode) { *mode = display->display_modes[index]; } return 0; } int SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode) { SDL_VideoDisplay *display; CHECK_DISPLAY_INDEX(displayIndex, -1); display = &_this->displays[displayIndex]; if (mode) { *mode = display->desktop_mode; } return 0; } int SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode) { SDL_VideoDisplay *display; CHECK_DISPLAY_INDEX(displayIndex, -1); display = &_this->displays[displayIndex]; if (mode) { *mode = display->current_mode; } return 0; } static SDL_DisplayMode * SDL_GetClosestDisplayModeForDisplay(SDL_VideoDisplay * display, const SDL_DisplayMode * mode, SDL_DisplayMode * closest) { Uint32 target_format; int target_refresh_rate; int i; SDL_DisplayMode *current, *match; if (!mode || !closest) { SDL_SetError("Missing desired mode or closest mode parameter"); return NULL; } /* Default to the desktop format */ if (mode->format) { target_format = mode->format; } else { target_format = display->desktop_mode.format; } /* Default to the desktop refresh rate */ if (mode->refresh_rate) { target_refresh_rate = mode->refresh_rate; } else { target_refresh_rate = display->desktop_mode.refresh_rate; } match = NULL; for (i = 0; i < SDL_GetNumDisplayModesForDisplay(display); ++i) { current = &display->display_modes[i]; if (current->w && (current->w < mode->w)) { /* Out of sorted modes large enough here */ break; } if (current->h && (current->h < mode->h)) { if (current->w && (current->w == mode->w)) { /* Out of sorted modes large enough here */ break; } /* Wider, but not tall enough, due to a different aspect ratio. This mode must be skipped, but closer modes may still follow. */ continue; } if (!match || current->w < match->w || current->h < match->h) { match = current; continue; } if (current->format != match->format) { /* Sorted highest depth to lowest */ if (current->format == target_format || (SDL_BITSPERPIXEL(current->format) >= SDL_BITSPERPIXEL(target_format) && SDL_PIXELTYPE(current->format) == SDL_PIXELTYPE(target_format))) { match = current; } continue; } if (current->refresh_rate != match->refresh_rate) { /* Sorted highest refresh to lowest */ if (current->refresh_rate >= target_refresh_rate) { match = current; } } } if (match) { if (match->format) { closest->format = match->format; } else { closest->format = mode->format; } if (match->w && match->h) { closest->w = match->w; closest->h = match->h; } else { closest->w = mode->w; closest->h = mode->h; } if (match->refresh_rate) { closest->refresh_rate = match->refresh_rate; } else { closest->refresh_rate = mode->refresh_rate; } closest->driverdata = match->driverdata; /* * Pick some reasonable defaults if the app and driver don't * care */ if (!closest->format) { closest->format = SDL_PIXELFORMAT_RGB888; } if (!closest->w) { closest->w = 640; } if (!closest->h) { closest->h = 480; } return closest; } return NULL; } SDL_DisplayMode * SDL_GetClosestDisplayMode(int displayIndex, const SDL_DisplayMode * mode, SDL_DisplayMode * closest) { SDL_VideoDisplay *display; CHECK_DISPLAY_INDEX(displayIndex, NULL); display = &_this->displays[displayIndex]; return SDL_GetClosestDisplayModeForDisplay(display, mode, closest); } static int SDL_SetDisplayModeForDisplay(SDL_VideoDisplay * display, const SDL_DisplayMode * mode) { SDL_DisplayMode display_mode; SDL_DisplayMode current_mode; if (mode) { display_mode = *mode; /* Default to the current mode */ if (!display_mode.format) { display_mode.format = display->current_mode.format; } if (!display_mode.w) { display_mode.w = display->current_mode.w; } if (!display_mode.h) { display_mode.h = display->current_mode.h; } if (!display_mode.refresh_rate) { display_mode.refresh_rate = display->current_mode.refresh_rate; } /* Get a good video mode, the closest one possible */ if (!SDL_GetClosestDisplayModeForDisplay(display, &display_mode, &display_mode)) { return SDL_SetError("No video mode large enough for %dx%d", display_mode.w, display_mode.h); } } else { display_mode = display->desktop_mode; } /* See if there's anything left to do */ current_mode = display->current_mode; if (SDL_memcmp(&display_mode, &current_mode, sizeof(display_mode)) == 0) { return 0; } /* Actually change the display mode */ if (!_this->SetDisplayMode) { return SDL_SetError("SDL video driver doesn't support changing display mode"); } if (_this->SetDisplayMode(_this, display, &display_mode) < 0) { return -1; } display->current_mode = display_mode; return 0; } SDL_VideoDisplay * SDL_GetDisplay(int displayIndex) { CHECK_DISPLAY_INDEX(displayIndex, NULL); return &_this->displays[displayIndex]; } int SDL_GetWindowDisplayIndex(SDL_Window * window) { int displayIndex; int i, dist; int closest = -1; int closest_dist = 0x7FFFFFFF; SDL_Point center; SDL_Point delta; SDL_Rect rect; CHECK_WINDOW_MAGIC(window, -1); if (SDL_WINDOWPOS_ISUNDEFINED(window->x) || SDL_WINDOWPOS_ISCENTERED(window->x)) { displayIndex = (window->x & 0xFFFF); if (displayIndex >= _this->num_displays) { displayIndex = 0; } return displayIndex; } if (SDL_WINDOWPOS_ISUNDEFINED(window->y) || SDL_WINDOWPOS_ISCENTERED(window->y)) { displayIndex = (window->y & 0xFFFF); if (displayIndex >= _this->num_displays) { displayIndex = 0; } return displayIndex; } /* Find the display containing the window */ for (i = 0; i < _this->num_displays; ++i) { SDL_VideoDisplay *display = &_this->displays[i]; if (display->fullscreen_window == window) { return i; } } center.x = window->x + window->w / 2; center.y = window->y + window->h / 2; for (i = 0; i < _this->num_displays; ++i) { SDL_GetDisplayBounds(i, &rect); if (SDL_EnclosePoints(&center, 1, &rect, NULL)) { return i; } delta.x = center.x - (rect.x + rect.w / 2); delta.y = center.y - (rect.y + rect.h / 2); dist = (delta.x*delta.x + delta.y*delta.y); if (dist < closest_dist) { closest = i; closest_dist = dist; } } if (closest < 0) { SDL_SetError("Couldn't find any displays"); } return closest; } SDL_VideoDisplay * SDL_GetDisplayForWindow(SDL_Window *window) { int displayIndex = SDL_GetWindowDisplayIndex(window); if (displayIndex >= 0) { return &_this->displays[displayIndex]; } else { return NULL; } } int SDL_SetWindowDisplayMode(SDL_Window * window, const SDL_DisplayMode * mode) { CHECK_WINDOW_MAGIC(window, -1); if (mode) { window->fullscreen_mode = *mode; } else { SDL_zero(window->fullscreen_mode); } if (FULLSCREEN_VISIBLE(window) && (window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP) { SDL_DisplayMode fullscreen_mode; if (SDL_GetWindowDisplayMode(window, &fullscreen_mode) == 0) { SDL_SetDisplayModeForDisplay(SDL_GetDisplayForWindow(window), &fullscreen_mode); } } return 0; } int SDL_GetWindowDisplayMode(SDL_Window * window, SDL_DisplayMode * mode) { SDL_DisplayMode fullscreen_mode; SDL_VideoDisplay *display; CHECK_WINDOW_MAGIC(window, -1); if (!mode) { return SDL_InvalidParamError("mode"); } fullscreen_mode = window->fullscreen_mode; if (!fullscreen_mode.w) { fullscreen_mode.w = window->windowed.w; } if (!fullscreen_mode.h) { fullscreen_mode.h = window->windowed.h; } display = SDL_GetDisplayForWindow(window); /* if in desktop size mode, just return the size of the desktop */ if ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) { fullscreen_mode = display->desktop_mode; } else if (!SDL_GetClosestDisplayModeForDisplay(SDL_GetDisplayForWindow(window), &fullscreen_mode, &fullscreen_mode)) { return SDL_SetError("Couldn't find display mode match"); } if (mode) { *mode = fullscreen_mode; } return 0; } Uint32 SDL_GetWindowPixelFormat(SDL_Window * window) { SDL_VideoDisplay *display; CHECK_WINDOW_MAGIC(window, SDL_PIXELFORMAT_UNKNOWN); display = SDL_GetDisplayForWindow(window); return display->current_mode.format; } static void SDL_RestoreMousePosition(SDL_Window *window) { int x, y; if (window == SDL_GetMouseFocus()) { SDL_GetMouseState(&x, &y); SDL_WarpMouseInWindow(window, x, y); } } #if __WINRT__ extern Uint32 WINRT_DetectWindowFlags(SDL_Window * window); #endif static int SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen) { SDL_VideoDisplay *display; SDL_Window *other; CHECK_WINDOW_MAGIC(window,-1); /* if we are in the process of hiding don't go back to fullscreen */ if (window->is_hiding && fullscreen) { return 0; } #ifdef __MACOSX__ /* if the window is going away and no resolution change is necessary, do nothing, or else we may trigger an ugly double-transition */ if (SDL_strcmp(_this->name, "cocoa") == 0) { /* don't do this for X11, etc */ if (window->is_destroying && (window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP) return 0; /* If we're switching between a fullscreen Space and "normal" fullscreen, we need to get back to normal first. */ if (fullscreen && ((window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP) && ((window->flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN)) { if (!Cocoa_SetWindowFullscreenSpace(window, SDL_FALSE)) { return -1; } } else if (fullscreen && ((window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN) && ((window->flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP)) { display = SDL_GetDisplayForWindow(window); SDL_SetDisplayModeForDisplay(display, NULL); if (_this->SetWindowFullscreen) { _this->SetWindowFullscreen(_this, window, display, SDL_FALSE); } } if (Cocoa_SetWindowFullscreenSpace(window, fullscreen)) { if (Cocoa_IsWindowInFullscreenSpace(window) != fullscreen) { return -1; } window->last_fullscreen_flags = window->flags; return 0; } } #elif __WINRT__ && (NTDDI_VERSION < NTDDI_WIN10) /* HACK: WinRT 8.x apps can't choose whether or not they are fullscreen or not. The user can choose this, via OS-provided UI, but this can't be set programmatically. Just look at what SDL's WinRT video backend code detected with regards to fullscreen (being active, or not), and figure out a return/error code from that. */ if (fullscreen == !(WINRT_DetectWindowFlags(window) & FULLSCREEN_MASK)) { /* Uh oh, either: 1. fullscreen was requested, and we're already windowed 2. windowed-mode was requested, and we're already fullscreen WinRT 8.x can't resolve either programmatically, so we're giving up. */ return -1; } else { /* Whatever was requested, fullscreen or windowed mode, is already in-place. */ return 0; } #endif display = SDL_GetDisplayForWindow(window); if (fullscreen) { /* Hide any other fullscreen windows */ if (display->fullscreen_window && display->fullscreen_window != window) { SDL_MinimizeWindow(display->fullscreen_window); } } /* See if anything needs to be done now */ if ((display->fullscreen_window == window) == fullscreen) { if ((window->last_fullscreen_flags & FULLSCREEN_MASK) == (window->flags & FULLSCREEN_MASK)) { return 0; } } /* See if there are any fullscreen windows */ for (other = _this->windows; other; other = other->next) { SDL_bool setDisplayMode = SDL_FALSE; if (other == window) { setDisplayMode = fullscreen; } else if (FULLSCREEN_VISIBLE(other) && SDL_GetDisplayForWindow(other) == display) { setDisplayMode = SDL_TRUE; } if (setDisplayMode) { SDL_DisplayMode fullscreen_mode; SDL_zero(fullscreen_mode); if (SDL_GetWindowDisplayMode(other, &fullscreen_mode) == 0) { SDL_bool resized = SDL_TRUE; if (other->w == fullscreen_mode.w && other->h == fullscreen_mode.h) { resized = SDL_FALSE; } /* only do the mode change if we want exclusive fullscreen */ if ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP) { if (SDL_SetDisplayModeForDisplay(display, &fullscreen_mode) < 0) { return -1; } } else { if (SDL_SetDisplayModeForDisplay(display, NULL) < 0) { return -1; } } if (_this->SetWindowFullscreen) { _this->SetWindowFullscreen(_this, other, display, SDL_TRUE); } display->fullscreen_window = other; /* Generate a mode change event here */ if (resized) { #ifndef ANDROID // Android may not resize the window to exactly what our fullscreen mode is, especially on // windowed Android environments like the Chromebook or Samsung DeX. Given this, we shouldn't // use fullscreen_mode.w and fullscreen_mode.h, but rather get our current native size. As such, // Android's SetWindowFullscreen will generate the window event for us with the proper final size. SDL_SendWindowEvent(other, SDL_WINDOWEVENT_RESIZED, fullscreen_mode.w, fullscreen_mode.h); #endif } else { SDL_OnWindowResized(other); } SDL_RestoreMousePosition(other); window->last_fullscreen_flags = window->flags; return 0; } } } /* Nope, restore the desktop mode */ SDL_SetDisplayModeForDisplay(display, NULL); if (_this->SetWindowFullscreen) { _this->SetWindowFullscreen(_this, window, display, SDL_FALSE); } display->fullscreen_window = NULL; /* Generate a mode change event here */ SDL_OnWindowResized(window); /* Restore the cursor position */ SDL_RestoreMousePosition(window); window->last_fullscreen_flags = window->flags; return 0; } #define CREATE_FLAGS \ (SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_SKIP_TASKBAR | SDL_WINDOW_POPUP_MENU | SDL_WINDOW_UTILITY | SDL_WINDOW_TOOLTIP | SDL_WINDOW_VULKAN | SDL_WINDOW_MINIMIZED | SDL_WINDOW_METAL) static SDL_INLINE SDL_bool IsAcceptingDragAndDrop(void) { if ((SDL_GetEventState(SDL_DROPFILE) == SDL_ENABLE) || (SDL_GetEventState(SDL_DROPTEXT) == SDL_ENABLE)) { return SDL_TRUE; } return SDL_FALSE; } /* prepare a newly-created window */ static SDL_INLINE void PrepareDragAndDropSupport(SDL_Window *window) { if (_this->AcceptDragAndDrop) { _this->AcceptDragAndDrop(window, IsAcceptingDragAndDrop()); } } /* toggle d'n'd for all existing windows. */ void SDL_ToggleDragAndDropSupport(void) { if (_this && _this->AcceptDragAndDrop) { const SDL_bool enable = IsAcceptingDragAndDrop(); SDL_Window *window; for (window = _this->windows; window; window = window->next) { _this->AcceptDragAndDrop(window, enable); } } } static void SDL_FinishWindowCreation(SDL_Window *window, Uint32 flags) { PrepareDragAndDropSupport(window); if (flags & SDL_WINDOW_MAXIMIZED) { SDL_MaximizeWindow(window); } if (flags & SDL_WINDOW_MINIMIZED) { SDL_MinimizeWindow(window); } if (flags & SDL_WINDOW_FULLSCREEN) { SDL_SetWindowFullscreen(window, flags); } if (flags & SDL_WINDOW_INPUT_GRABBED) { SDL_SetWindowGrab(window, SDL_TRUE); } if (!(flags & SDL_WINDOW_HIDDEN)) { SDL_ShowWindow(window); } } SDL_Window * SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags) { SDL_Window *window; if (!_this) { /* Initialize the video system if needed */ if (SDL_Init(SDL_INIT_VIDEO) < 0) { return NULL; } } if ((((flags & SDL_WINDOW_UTILITY) != 0) + ((flags & SDL_WINDOW_TOOLTIP) != 0) + ((flags & SDL_WINDOW_POPUP_MENU) != 0)) > 1) { SDL_SetError("Conflicting window flags specified"); return NULL; } /* Some platforms can't create zero-sized windows */ if (w < 1) { w = 1; } if (h < 1) { h = 1; } /* Some platforms blow up if the windows are too large. Raise it later? */ if ((w > 16384) || (h > 16384)) { SDL_SetError("Window is too large."); return NULL; } /* Some platforms have OpenGL enabled by default */ #if (SDL_VIDEO_OPENGL && __MACOSX__) || __IPHONEOS__ || __ANDROID__ || __NACL__ if (!_this->is_dummy && !(flags & SDL_WINDOW_VULKAN) && !(flags & SDL_WINDOW_METAL) && !SDL_IsVideoContextExternal()) { flags |= SDL_WINDOW_OPENGL; } #endif if (flags & SDL_WINDOW_OPENGL) { if (!_this->GL_CreateContext) { SDL_SetError("OpenGL support is either not configured in SDL " "or not available in current SDL video driver " "(%s) or platform", _this->name); return NULL; } if (SDL_GL_LoadLibrary(NULL) < 0) { return NULL; } } if (flags & SDL_WINDOW_VULKAN) { if (!_this->Vulkan_CreateSurface) { SDL_SetError("Vulkan support is either not configured in SDL " "or not available in current SDL video driver " "(%s) or platform", _this->name); return NULL; } if (flags & SDL_WINDOW_OPENGL) { SDL_SetError("Vulkan and OpenGL not supported on same window"); return NULL; } if (SDL_Vulkan_LoadLibrary(NULL) < 0) { return NULL; } } if (flags & SDL_WINDOW_METAL) { if (!_this->Metal_CreateView) { SDL_SetError("Metal support is either not configured in SDL " "or not available in current SDL video driver " "(%s) or platform", _this->name); return NULL; } if (flags & SDL_WINDOW_OPENGL) { SDL_SetError("Metal and OpenGL not supported on same window"); return NULL; } if (flags & SDL_WINDOW_VULKAN) { SDL_SetError("Metal and Vulkan not supported on same window. " "To use MoltenVK, set SDL_WINDOW_VULKAN only."); return NULL; } } /* Unless the user has specified the high-DPI disabling hint, respect the * SDL_WINDOW_ALLOW_HIGHDPI flag. */ if (flags & SDL_WINDOW_ALLOW_HIGHDPI) { if (SDL_GetHintBoolean(SDL_HINT_VIDEO_HIGHDPI_DISABLED, SDL_FALSE)) { flags &= ~SDL_WINDOW_ALLOW_HIGHDPI; } } window = (SDL_Window *)SDL_calloc(1, sizeof(*window)); if (!window) { SDL_OutOfMemory(); return NULL; } window->magic = &_this->window_magic; window->id = _this->next_object_id++; window->x = x; window->y = y; window->w = w; window->h = h; if (SDL_WINDOWPOS_ISUNDEFINED(x) || SDL_WINDOWPOS_ISUNDEFINED(y) || SDL_WINDOWPOS_ISCENTERED(x) || SDL_WINDOWPOS_ISCENTERED(y)) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); int displayIndex; SDL_Rect bounds; displayIndex = SDL_GetIndexOfDisplay(display); SDL_GetDisplayBounds(displayIndex, &bounds); if (SDL_WINDOWPOS_ISUNDEFINED(x) || SDL_WINDOWPOS_ISCENTERED(x)) { window->x = bounds.x + (bounds.w - w) / 2; } if (SDL_WINDOWPOS_ISUNDEFINED(y) || SDL_WINDOWPOS_ISCENTERED(y)) { window->y = bounds.y + (bounds.h - h) / 2; } } window->windowed.x = window->x; window->windowed.y = window->y; window->windowed.w = window->w; window->windowed.h = window->h; if (flags & SDL_WINDOW_FULLSCREEN) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); int displayIndex; SDL_Rect bounds; displayIndex = SDL_GetIndexOfDisplay(display); SDL_GetDisplayBounds(displayIndex, &bounds); window->x = bounds.x; window->y = bounds.y; window->w = bounds.w; window->h = bounds.h; } window->flags = ((flags & CREATE_FLAGS) | SDL_WINDOW_HIDDEN); window->last_fullscreen_flags = window->flags; window->opacity = 1.0f; window->brightness = 1.0f; window->next = _this->windows; window->is_destroying = SDL_FALSE; if (_this->windows) { _this->windows->prev = window; } _this->windows = window; if (_this->CreateSDLWindow && _this->CreateSDLWindow(_this, window) < 0) { SDL_DestroyWindow(window); return NULL; } /* Clear minimized if not on windows, only windows handles it at create rather than FinishWindowCreation, * but it's important or window focus will get broken on windows! */ #if !defined(__WIN32__) if (window->flags & SDL_WINDOW_MINIMIZED) { window->flags &= ~SDL_WINDOW_MINIMIZED; } #endif #if __WINRT__ && (NTDDI_VERSION < NTDDI_WIN10) /* HACK: WinRT 8.x apps can't choose whether or not they are fullscreen or not. The user can choose this, via OS-provided UI, but this can't be set programmatically. Just look at what SDL's WinRT video backend code detected with regards to fullscreen (being active, or not), and figure out a return/error code from that. */ flags = window->flags; #endif if (title) { SDL_SetWindowTitle(window, title); } SDL_FinishWindowCreation(window, flags); /* If the window was created fullscreen, make sure the mode code matches */ SDL_UpdateFullscreenMode(window, FULLSCREEN_VISIBLE(window)); return window; } SDL_Window * SDL_CreateWindowFrom(const void *data) { SDL_Window *window; if (!_this) { SDL_UninitializedVideo(); return NULL; } if (!_this->CreateSDLWindowFrom) { SDL_Unsupported(); return NULL; } window = (SDL_Window *)SDL_calloc(1, sizeof(*window)); if (!window) { SDL_OutOfMemory(); return NULL; } window->magic = &_this->window_magic; window->id = _this->next_object_id++; window->flags = SDL_WINDOW_FOREIGN; window->last_fullscreen_flags = window->flags; window->is_destroying = SDL_FALSE; window->opacity = 1.0f; window->brightness = 1.0f; window->next = _this->windows; if (_this->windows) { _this->windows->prev = window; } _this->windows = window; if (_this->CreateSDLWindowFrom(_this, window, data) < 0) { SDL_DestroyWindow(window); return NULL; } PrepareDragAndDropSupport(window); return window; } int SDL_RecreateWindow(SDL_Window * window, Uint32 flags) { SDL_bool loaded_opengl = SDL_FALSE; if ((flags & SDL_WINDOW_OPENGL) && !_this->GL_CreateContext) { return SDL_SetError("OpenGL support is either not configured in SDL " "or not available in current SDL video driver " "(%s) or platform", _this->name); } if (window->flags & SDL_WINDOW_FOREIGN) { /* Can't destroy and re-create foreign windows, hrm */ flags |= SDL_WINDOW_FOREIGN; } else { flags &= ~SDL_WINDOW_FOREIGN; } /* Restore video mode, etc. */ SDL_HideWindow(window); /* Tear down the old native window */ if (window->surface) { window->surface->flags &= ~SDL_DONTFREE; SDL_FreeSurface(window->surface); window->surface = NULL; window->surface_valid = SDL_FALSE; } if (_this->DestroyWindowFramebuffer) { _this->DestroyWindowFramebuffer(_this, window); } if (_this->DestroyWindow && !(flags & SDL_WINDOW_FOREIGN)) { _this->DestroyWindow(_this, window); } if ((window->flags & SDL_WINDOW_OPENGL) != (flags & SDL_WINDOW_OPENGL)) { if (flags & SDL_WINDOW_OPENGL) { if (SDL_GL_LoadLibrary(NULL) < 0) { return -1; } loaded_opengl = SDL_TRUE; } else { SDL_GL_UnloadLibrary(); } } else if (window->flags & SDL_WINDOW_OPENGL) { SDL_GL_UnloadLibrary(); if (SDL_GL_LoadLibrary(NULL) < 0) { return -1; } loaded_opengl = SDL_TRUE; } if ((window->flags & SDL_WINDOW_VULKAN) != (flags & SDL_WINDOW_VULKAN)) { SDL_SetError("Can't change SDL_WINDOW_VULKAN window flag"); return -1; } /* if ((window->flags & SDL_WINDOW_METAL) != (flags & SDL_WINDOW_METAL)) { SDL_SetError("Can't change SDL_WINDOW_METAL window flag"); return -1; } */ if ((window->flags & SDL_WINDOW_VULKAN) && (flags & SDL_WINDOW_OPENGL)) { SDL_SetError("Vulkan and OpenGL not supported on same window"); return -1; } if ((window->flags & SDL_WINDOW_METAL) && (flags & SDL_WINDOW_OPENGL)) { SDL_SetError("Metal and OpenGL not supported on same window"); return -1; } if ((window->flags & SDL_WINDOW_METAL) && (flags & SDL_WINDOW_VULKAN)) { SDL_SetError("Metal and Vulkan not supported on same window"); return -1; } window->flags = ((flags & CREATE_FLAGS) | SDL_WINDOW_HIDDEN); window->last_fullscreen_flags = window->flags; window->is_destroying = SDL_FALSE; if (_this->CreateSDLWindow && !(flags & SDL_WINDOW_FOREIGN)) { if (_this->CreateSDLWindow(_this, window) < 0) { if (loaded_opengl) { SDL_GL_UnloadLibrary(); window->flags &= ~SDL_WINDOW_OPENGL; } return -1; } } if (flags & SDL_WINDOW_FOREIGN) { window->flags |= SDL_WINDOW_FOREIGN; } if (_this->SetWindowTitle && window->title) { _this->SetWindowTitle(_this, window); } if (_this->SetWindowIcon && window->icon) { _this->SetWindowIcon(_this, window, window->icon); } if (window->hit_test) { _this->SetWindowHitTest(window, SDL_TRUE); } SDL_FinishWindowCreation(window, flags); return 0; } SDL_bool SDL_HasWindows(void) { return (_this && _this->windows != NULL); } Uint32 SDL_GetWindowID(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, 0); return window->id; } SDL_Window * SDL_GetWindowFromID(Uint32 id) { SDL_Window *window; if (!_this) { return NULL; } for (window = _this->windows; window; window = window->next) { if (window->id == id) { return window; } } return NULL; } Uint32 SDL_GetWindowFlags(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, 0); return window->flags; } void SDL_SetWindowTitle(SDL_Window * window, const char *title) { CHECK_WINDOW_MAGIC(window,); if (title == window->title) { return; } SDL_free(window->title); window->title = SDL_strdup(title ? title : ""); if (_this->SetWindowTitle) { _this->SetWindowTitle(_this, window); } } const char * SDL_GetWindowTitle(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, ""); return window->title ? window->title : ""; } void SDL_SetWindowIcon(SDL_Window * window, SDL_Surface * icon) { CHECK_WINDOW_MAGIC(window,); if (!icon) { return; } SDL_FreeSurface(window->icon); /* Convert the icon into ARGB8888 */ window->icon = SDL_ConvertSurfaceFormat(icon, SDL_PIXELFORMAT_ARGB8888, 0); if (!window->icon) { return; } if (_this->SetWindowIcon) { _this->SetWindowIcon(_this, window, window->icon); } } void* SDL_SetWindowData(SDL_Window * window, const char *name, void *userdata) { SDL_WindowUserData *prev, *data; CHECK_WINDOW_MAGIC(window, NULL); /* Input validation */ if (name == NULL || name[0] == '\0') { SDL_InvalidParamError("name"); return NULL; } /* See if the named data already exists */ prev = NULL; for (data = window->data; data; prev = data, data = data->next) { if (data->name && SDL_strcmp(data->name, name) == 0) { void *last_value = data->data; if (userdata) { /* Set the new value */ data->data = userdata; } else { /* Delete this value */ if (prev) { prev->next = data->next; } else { window->data = data->next; } SDL_free(data->name); SDL_free(data); } return last_value; } } /* Add new data to the window */ if (userdata) { data = (SDL_WindowUserData *)SDL_malloc(sizeof(*data)); data->name = SDL_strdup(name); data->data = userdata; data->next = window->data; window->data = data; } return NULL; } void * SDL_GetWindowData(SDL_Window * window, const char *name) { SDL_WindowUserData *data; CHECK_WINDOW_MAGIC(window, NULL); /* Input validation */ if (name == NULL || name[0] == '\0') { SDL_InvalidParamError("name"); return NULL; } for (data = window->data; data; data = data->next) { if (data->name && SDL_strcmp(data->name, name) == 0) { return data->data; } } return NULL; } void SDL_SetWindowPosition(SDL_Window * window, int x, int y) { CHECK_WINDOW_MAGIC(window,); if (SDL_WINDOWPOS_ISCENTERED(x) || SDL_WINDOWPOS_ISCENTERED(y)) { int displayIndex = (x & 0xFFFF); SDL_Rect bounds; if (displayIndex >= _this->num_displays) { displayIndex = 0; } SDL_zero(bounds); SDL_GetDisplayBounds(displayIndex, &bounds); if (SDL_WINDOWPOS_ISCENTERED(x)) { x = bounds.x + (bounds.w - window->w) / 2; } if (SDL_WINDOWPOS_ISCENTERED(y)) { y = bounds.y + (bounds.h - window->h) / 2; } } if ((window->flags & SDL_WINDOW_FULLSCREEN)) { if (!SDL_WINDOWPOS_ISUNDEFINED(x)) { window->windowed.x = x; } if (!SDL_WINDOWPOS_ISUNDEFINED(y)) { window->windowed.y = y; } } else { if (!SDL_WINDOWPOS_ISUNDEFINED(x)) { window->x = x; } if (!SDL_WINDOWPOS_ISUNDEFINED(y)) { window->y = y; } if (_this->SetWindowPosition) { _this->SetWindowPosition(_this, window); } } } void SDL_GetWindowPosition(SDL_Window * window, int *x, int *y) { CHECK_WINDOW_MAGIC(window,); /* Fullscreen windows are always at their display's origin */ if (window->flags & SDL_WINDOW_FULLSCREEN) { int displayIndex; if (x) { *x = 0; } if (y) { *y = 0; } /* Find the window's monitor and update to the monitor offset. */ displayIndex = SDL_GetWindowDisplayIndex(window); if (displayIndex >= 0) { SDL_Rect bounds; SDL_zero(bounds); SDL_GetDisplayBounds(displayIndex, &bounds); if (x) { *x = bounds.x; } if (y) { *y = bounds.y; } } } else { if (x) { *x = window->x; } if (y) { *y = window->y; } } } void SDL_SetWindowBordered(SDL_Window * window, SDL_bool bordered) { CHECK_WINDOW_MAGIC(window,); if (!(window->flags & SDL_WINDOW_FULLSCREEN)) { const int want = (bordered != SDL_FALSE); /* normalize the flag. */ const int have = ((window->flags & SDL_WINDOW_BORDERLESS) == 0); if ((want != have) && (_this->SetWindowBordered)) { if (want) { window->flags &= ~SDL_WINDOW_BORDERLESS; } else { window->flags |= SDL_WINDOW_BORDERLESS; } _this->SetWindowBordered(_this, window, (SDL_bool) want); } } } void SDL_SetWindowResizable(SDL_Window * window, SDL_bool resizable) { CHECK_WINDOW_MAGIC(window,); if (!(window->flags & SDL_WINDOW_FULLSCREEN)) { const int want = (resizable != SDL_FALSE); /* normalize the flag. */ const int have = ((window->flags & SDL_WINDOW_RESIZABLE) != 0); if ((want != have) && (_this->SetWindowResizable)) { if (want) { window->flags |= SDL_WINDOW_RESIZABLE; } else { window->flags &= ~SDL_WINDOW_RESIZABLE; } _this->SetWindowResizable(_this, window, (SDL_bool) want); } } } void SDL_SetWindowSize(SDL_Window * window, int w, int h) { CHECK_WINDOW_MAGIC(window,); if (w <= 0) { SDL_InvalidParamError("w"); return; } if (h <= 0) { SDL_InvalidParamError("h"); return; } /* Make sure we don't exceed any window size limits */ if (window->min_w && w < window->min_w) { w = window->min_w; } if (window->max_w && w > window->max_w) { w = window->max_w; } if (window->min_h && h < window->min_h) { h = window->min_h; } if (window->max_h && h > window->max_h) { h = window->max_h; } window->windowed.w = w; window->windowed.h = h; if (window->flags & SDL_WINDOW_FULLSCREEN) { if (FULLSCREEN_VISIBLE(window) && (window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP) { window->last_fullscreen_flags = 0; SDL_UpdateFullscreenMode(window, SDL_TRUE); } } else { window->w = w; window->h = h; if (_this->SetWindowSize) { _this->SetWindowSize(_this, window); } if (window->w == w && window->h == h) { /* We didn't get a SDL_WINDOWEVENT_RESIZED event (by design) */ SDL_OnWindowResized(window); } } } void SDL_GetWindowSize(SDL_Window * window, int *w, int *h) { CHECK_WINDOW_MAGIC(window,); if (w) { *w = window->w; } if (h) { *h = window->h; } } int SDL_GetWindowBordersSize(SDL_Window * window, int *top, int *left, int *bottom, int *right) { int dummy = 0; if (!top) { top = &dummy; } if (!left) { left = &dummy; } if (!right) { right = &dummy; } if (!bottom) { bottom = &dummy; } /* Always initialize, so applications don't have to care */ *top = *left = *bottom = *right = 0; CHECK_WINDOW_MAGIC(window, -1); if (!_this->GetWindowBordersSize) { return SDL_Unsupported(); } return _this->GetWindowBordersSize(_this, window, top, left, bottom, right); } void SDL_SetWindowMinimumSize(SDL_Window * window, int min_w, int min_h) { CHECK_WINDOW_MAGIC(window,); if (min_w <= 0) { SDL_InvalidParamError("min_w"); return; } if (min_h <= 0) { SDL_InvalidParamError("min_h"); return; } if ((window->max_w && min_w >= window->max_w) || (window->max_h && min_h >= window->max_h)) { SDL_SetError("SDL_SetWindowMinimumSize(): Tried to set minimum size larger than maximum size"); return; } window->min_w = min_w; window->min_h = min_h; if (!(window->flags & SDL_WINDOW_FULLSCREEN)) { if (_this->SetWindowMinimumSize) { _this->SetWindowMinimumSize(_this, window); } /* Ensure that window is not smaller than minimal size */ SDL_SetWindowSize(window, SDL_max(window->w, window->min_w), SDL_max(window->h, window->min_h)); } } void SDL_GetWindowMinimumSize(SDL_Window * window, int *min_w, int *min_h) { CHECK_WINDOW_MAGIC(window,); if (min_w) { *min_w = window->min_w; } if (min_h) { *min_h = window->min_h; } } void SDL_SetWindowMaximumSize(SDL_Window * window, int max_w, int max_h) { CHECK_WINDOW_MAGIC(window,); if (max_w <= 0) { SDL_InvalidParamError("max_w"); return; } if (max_h <= 0) { SDL_InvalidParamError("max_h"); return; } if (max_w <= window->min_w || max_h <= window->min_h) { SDL_SetError("SDL_SetWindowMaximumSize(): Tried to set maximum size smaller than minimum size"); return; } window->max_w = max_w; window->max_h = max_h; if (!(window->flags & SDL_WINDOW_FULLSCREEN)) { if (_this->SetWindowMaximumSize) { _this->SetWindowMaximumSize(_this, window); } /* Ensure that window is not larger than maximal size */ SDL_SetWindowSize(window, SDL_min(window->w, window->max_w), SDL_min(window->h, window->max_h)); } } void SDL_GetWindowMaximumSize(SDL_Window * window, int *max_w, int *max_h) { CHECK_WINDOW_MAGIC(window,); if (max_w) { *max_w = window->max_w; } if (max_h) { *max_h = window->max_h; } } void SDL_ShowWindow(SDL_Window * window) { CHECK_WINDOW_MAGIC(window,); if (window->flags & SDL_WINDOW_SHOWN) { return; } if (_this->ShowWindow) { _this->ShowWindow(_this, window); } SDL_SendWindowEvent(window, SDL_WINDOWEVENT_SHOWN, 0, 0); } void SDL_HideWindow(SDL_Window * window) { CHECK_WINDOW_MAGIC(window,); if (!(window->flags & SDL_WINDOW_SHOWN)) { return; } window->is_hiding = SDL_TRUE; SDL_UpdateFullscreenMode(window, SDL_FALSE); if (_this->HideWindow) { _this->HideWindow(_this, window); } window->is_hiding = SDL_FALSE; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_HIDDEN, 0, 0); } void SDL_RaiseWindow(SDL_Window * window) { CHECK_WINDOW_MAGIC(window,); if (!(window->flags & SDL_WINDOW_SHOWN)) { return; } if (_this->RaiseWindow) { _this->RaiseWindow(_this, window); } } void SDL_MaximizeWindow(SDL_Window * window) { CHECK_WINDOW_MAGIC(window,); if (window->flags & SDL_WINDOW_MAXIMIZED) { return; } /* !!! FIXME: should this check if the window is resizable? */ if (_this->MaximizeWindow) { _this->MaximizeWindow(_this, window); } } static SDL_bool CanMinimizeWindow(SDL_Window * window) { if (!_this->MinimizeWindow) { return SDL_FALSE; } return SDL_TRUE; } void SDL_MinimizeWindow(SDL_Window * window) { CHECK_WINDOW_MAGIC(window,); if (window->flags & SDL_WINDOW_MINIMIZED) { return; } if (!CanMinimizeWindow(window)) { return; } SDL_UpdateFullscreenMode(window, SDL_FALSE); if (_this->MinimizeWindow) { _this->MinimizeWindow(_this, window); } } void SDL_RestoreWindow(SDL_Window * window) { CHECK_WINDOW_MAGIC(window,); if (!(window->flags & (SDL_WINDOW_MAXIMIZED | SDL_WINDOW_MINIMIZED))) { return; } if (_this->RestoreWindow) { _this->RestoreWindow(_this, window); } } int SDL_SetWindowFullscreen(SDL_Window * window, Uint32 flags) { Uint32 oldflags; CHECK_WINDOW_MAGIC(window, -1); flags &= FULLSCREEN_MASK; if (flags == (window->flags & FULLSCREEN_MASK)) { return 0; } /* clear the previous flags and OR in the new ones */ oldflags = window->flags & FULLSCREEN_MASK; window->flags &= ~FULLSCREEN_MASK; window->flags |= flags; if (SDL_UpdateFullscreenMode(window, FULLSCREEN_VISIBLE(window)) == 0) { return 0; } window->flags &= ~FULLSCREEN_MASK; window->flags |= oldflags; return -1; } static SDL_Surface * SDL_CreateWindowFramebuffer(SDL_Window * window) { Uint32 format; void *pixels; int pitch; int bpp; Uint32 Rmask, Gmask, Bmask, Amask; if (!_this->CreateWindowFramebuffer || !_this->UpdateWindowFramebuffer) { return NULL; } if (_this->CreateWindowFramebuffer(_this, window, &format, &pixels, &pitch) < 0) { return NULL; } if (window->surface) { return window->surface; } if (!SDL_PixelFormatEnumToMasks(format, &bpp, &Rmask, &Gmask, &Bmask, &Amask)) { return NULL; } return SDL_CreateRGBSurfaceFrom(pixels, window->w, window->h, bpp, pitch, Rmask, Gmask, Bmask, Amask); } SDL_Surface * SDL_GetWindowSurface(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, NULL); if (!window->surface_valid) { if (window->surface) { window->surface->flags &= ~SDL_DONTFREE; SDL_FreeSurface(window->surface); window->surface = NULL; } window->surface = SDL_CreateWindowFramebuffer(window); if (window->surface) { window->surface_valid = SDL_TRUE; window->surface->flags |= SDL_DONTFREE; } } return window->surface; } int SDL_UpdateWindowSurface(SDL_Window * window) { SDL_Rect full_rect; CHECK_WINDOW_MAGIC(window, -1); full_rect.x = 0; full_rect.y = 0; full_rect.w = window->w; full_rect.h = window->h; return SDL_UpdateWindowSurfaceRects(window, &full_rect, 1); } int SDL_UpdateWindowSurfaceRects(SDL_Window * window, const SDL_Rect * rects, int numrects) { CHECK_WINDOW_MAGIC(window, -1); if (!window->surface_valid) { return SDL_SetError("Window surface is invalid, please call SDL_GetWindowSurface() to get a new surface"); } return _this->UpdateWindowFramebuffer(_this, window, rects, numrects); } int SDL_SetWindowBrightness(SDL_Window * window, float brightness) { Uint16 ramp[256]; int status; CHECK_WINDOW_MAGIC(window, -1); SDL_CalculateGammaRamp(brightness, ramp); status = SDL_SetWindowGammaRamp(window, ramp, ramp, ramp); if (status == 0) { window->brightness = brightness; } return status; } float SDL_GetWindowBrightness(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, 1.0f); return window->brightness; } int SDL_SetWindowOpacity(SDL_Window * window, float opacity) { int retval; CHECK_WINDOW_MAGIC(window, -1); if (!_this->SetWindowOpacity) { return SDL_Unsupported(); } if (opacity < 0.0f) { opacity = 0.0f; } else if (opacity > 1.0f) { opacity = 1.0f; } retval = _this->SetWindowOpacity(_this, window, opacity); if (retval == 0) { window->opacity = opacity; } return retval; } int SDL_GetWindowOpacity(SDL_Window * window, float * out_opacity) { CHECK_WINDOW_MAGIC(window, -1); if (out_opacity) { *out_opacity = window->opacity; } return 0; } int SDL_SetWindowModalFor(SDL_Window * modal_window, SDL_Window * parent_window) { CHECK_WINDOW_MAGIC(modal_window, -1); CHECK_WINDOW_MAGIC(parent_window, -1); if (!_this->SetWindowModalFor) { return SDL_Unsupported(); } return _this->SetWindowModalFor(_this, modal_window, parent_window); } int SDL_SetWindowInputFocus(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, -1); if (!_this->SetWindowInputFocus) { return SDL_Unsupported(); } return _this->SetWindowInputFocus(_this, window); } int SDL_SetWindowGammaRamp(SDL_Window * window, const Uint16 * red, const Uint16 * green, const Uint16 * blue) { CHECK_WINDOW_MAGIC(window, -1); if (!_this->SetWindowGammaRamp) { return SDL_Unsupported(); } if (!window->gamma) { if (SDL_GetWindowGammaRamp(window, NULL, NULL, NULL) < 0) { return -1; } SDL_assert(window->gamma != NULL); } if (red) { SDL_memcpy(&window->gamma[0*256], red, 256*sizeof(Uint16)); } if (green) { SDL_memcpy(&window->gamma[1*256], green, 256*sizeof(Uint16)); } if (blue) { SDL_memcpy(&window->gamma[2*256], blue, 256*sizeof(Uint16)); } if (window->flags & SDL_WINDOW_INPUT_FOCUS) { return _this->SetWindowGammaRamp(_this, window, window->gamma); } else { return 0; } } int SDL_GetWindowGammaRamp(SDL_Window * window, Uint16 * red, Uint16 * green, Uint16 * blue) { CHECK_WINDOW_MAGIC(window, -1); if (!window->gamma) { int i; window->gamma = (Uint16 *)SDL_malloc(256*6*sizeof(Uint16)); if (!window->gamma) { return SDL_OutOfMemory(); } window->saved_gamma = window->gamma + 3*256; if (_this->GetWindowGammaRamp) { if (_this->GetWindowGammaRamp(_this, window, window->gamma) < 0) { return -1; } } else { /* Create an identity gamma ramp */ for (i = 0; i < 256; ++i) { Uint16 value = (Uint16)((i << 8) | i); window->gamma[0*256+i] = value; window->gamma[1*256+i] = value; window->gamma[2*256+i] = value; } } SDL_memcpy(window->saved_gamma, window->gamma, 3*256*sizeof(Uint16)); } if (red) { SDL_memcpy(red, &window->gamma[0*256], 256*sizeof(Uint16)); } if (green) { SDL_memcpy(green, &window->gamma[1*256], 256*sizeof(Uint16)); } if (blue) { SDL_memcpy(blue, &window->gamma[2*256], 256*sizeof(Uint16)); } return 0; } void SDL_UpdateWindowGrab(SDL_Window * window) { SDL_Window *grabbed_window; SDL_bool grabbed; if ((SDL_GetMouse()->relative_mode || (window->flags & SDL_WINDOW_INPUT_GRABBED)) && (window->flags & SDL_WINDOW_INPUT_FOCUS)) { grabbed = SDL_TRUE; } else { grabbed = SDL_FALSE; } grabbed_window = _this->grabbed_window; if (grabbed) { if (grabbed_window && (grabbed_window != window)) { /* stealing a grab from another window! */ grabbed_window->flags &= ~SDL_WINDOW_INPUT_GRABBED; if (_this->SetWindowGrab) { _this->SetWindowGrab(_this, grabbed_window, SDL_FALSE); } } _this->grabbed_window = window; } else if (grabbed_window == window) { _this->grabbed_window = NULL; /* ungrabbing. */ } if (_this->SetWindowGrab) { _this->SetWindowGrab(_this, window, grabbed); } } void SDL_SetWindowGrab(SDL_Window * window, SDL_bool grabbed) { CHECK_WINDOW_MAGIC(window,); if (!!grabbed == !!(window->flags & SDL_WINDOW_INPUT_GRABBED)) { return; } if (grabbed) { window->flags |= SDL_WINDOW_INPUT_GRABBED; } else { window->flags &= ~SDL_WINDOW_INPUT_GRABBED; } SDL_UpdateWindowGrab(window); } SDL_bool SDL_GetWindowGrab(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, SDL_FALSE); SDL_assert(!_this->grabbed_window || ((_this->grabbed_window->flags & SDL_WINDOW_INPUT_GRABBED) != 0)); return window == _this->grabbed_window; } SDL_Window * SDL_GetGrabbedWindow(void) { SDL_assert(!_this->grabbed_window || ((_this->grabbed_window->flags & SDL_WINDOW_INPUT_GRABBED) != 0)); return _this->grabbed_window; } void SDL_OnWindowShown(SDL_Window * window) { SDL_OnWindowRestored(window); } void SDL_OnWindowHidden(SDL_Window * window) { SDL_UpdateFullscreenMode(window, SDL_FALSE); } void SDL_OnWindowResized(SDL_Window * window) { window->surface_valid = SDL_FALSE; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_SIZE_CHANGED, window->w, window->h); } void SDL_OnWindowMinimized(SDL_Window * window) { SDL_UpdateFullscreenMode(window, SDL_FALSE); } void SDL_OnWindowRestored(SDL_Window * window) { /* * FIXME: Is this fine to just remove this, or should it be preserved just * for the fullscreen case? In principle it seems like just hiding/showing * windows shouldn't affect the stacking order; maybe the right fix is to * re-decouple OnWindowShown and OnWindowRestored. */ /*SDL_RaiseWindow(window);*/ if (FULLSCREEN_VISIBLE(window)) { SDL_UpdateFullscreenMode(window, SDL_TRUE); } } void SDL_OnWindowEnter(SDL_Window * window) { if (_this->OnWindowEnter) { _this->OnWindowEnter(_this, window); } } void SDL_OnWindowLeave(SDL_Window * window) { } void SDL_OnWindowFocusGained(SDL_Window * window) { SDL_Mouse *mouse = SDL_GetMouse(); if (window->gamma && _this->SetWindowGammaRamp) { _this->SetWindowGammaRamp(_this, window, window->gamma); } if (mouse && mouse->relative_mode) { SDL_SetMouseFocus(window); SDL_WarpMouseInWindow(window, window->w/2, window->h/2); } SDL_UpdateWindowGrab(window); } static SDL_bool ShouldMinimizeOnFocusLoss(SDL_Window * window) { if (!(window->flags & SDL_WINDOW_FULLSCREEN) || window->is_destroying) { return SDL_FALSE; } #ifdef __MACOSX__ if (SDL_strcmp(_this->name, "cocoa") == 0) { /* don't do this for X11, etc */ if (Cocoa_IsWindowInFullscreenSpace(window)) { return SDL_FALSE; } } #endif #ifdef __ANDROID__ { extern SDL_bool Android_JNI_ShouldMinimizeOnFocusLoss(void); if (! Android_JNI_ShouldMinimizeOnFocusLoss()) { return SDL_FALSE; } } #endif return SDL_GetHintBoolean(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, SDL_FALSE); } void SDL_OnWindowFocusLost(SDL_Window * window) { if (window->gamma && _this->SetWindowGammaRamp) { _this->SetWindowGammaRamp(_this, window, window->saved_gamma); } SDL_UpdateWindowGrab(window); if (ShouldMinimizeOnFocusLoss(window)) { SDL_MinimizeWindow(window); } } /* !!! FIXME: is this different than SDL_GetKeyboardFocus()? !!! FIXME: Also, SDL_GetKeyboardFocus() is O(1), this isn't. */ SDL_Window * SDL_GetFocusWindow(void) { SDL_Window *window; if (!_this) { return NULL; } for (window = _this->windows; window; window = window->next) { if (window->flags & SDL_WINDOW_INPUT_FOCUS) { return window; } } return NULL; } void SDL_DestroyWindow(SDL_Window * window) { SDL_VideoDisplay *display; CHECK_WINDOW_MAGIC(window,); window->is_destroying = SDL_TRUE; /* Restore video mode, etc. */ SDL_HideWindow(window); /* Make sure this window no longer has focus */ if (SDL_GetKeyboardFocus() == window) { SDL_SetKeyboardFocus(NULL); } if (SDL_GetMouseFocus() == window) { SDL_SetMouseFocus(NULL); } /* make no context current if this is the current context window. */ if (window->flags & SDL_WINDOW_OPENGL) { if (_this->current_glwin == window) { SDL_GL_MakeCurrent(window, NULL); } } if (window->surface) { window->surface->flags &= ~SDL_DONTFREE; SDL_FreeSurface(window->surface); window->surface = NULL; window->surface_valid = SDL_FALSE; } if (_this->DestroyWindowFramebuffer) { _this->DestroyWindowFramebuffer(_this, window); } if (_this->DestroyWindow) { _this->DestroyWindow(_this, window); } if (window->flags & SDL_WINDOW_OPENGL) { SDL_GL_UnloadLibrary(); } if (window->flags & SDL_WINDOW_VULKAN) { SDL_Vulkan_UnloadLibrary(); } display = SDL_GetDisplayForWindow(window); if (display->fullscreen_window == window) { display->fullscreen_window = NULL; } /* Now invalidate magic */ window->magic = NULL; /* Free memory associated with the window */ SDL_free(window->title); SDL_FreeSurface(window->icon); SDL_free(window->gamma); while (window->data) { SDL_WindowUserData *data = window->data; window->data = data->next; SDL_free(data->name); SDL_free(data); } /* Unlink the window from the list */ if (window->next) { window->next->prev = window->prev; } if (window->prev) { window->prev->next = window->next; } else { _this->windows = window->next; } SDL_free(window); } SDL_bool SDL_IsScreenSaverEnabled() { if (!_this) { return SDL_TRUE; } return _this->suspend_screensaver ? SDL_FALSE : SDL_TRUE; } void SDL_EnableScreenSaver() { if (!_this) { return; } if (!_this->suspend_screensaver) { return; } _this->suspend_screensaver = SDL_FALSE; if (_this->SuspendScreenSaver) { _this->SuspendScreenSaver(_this); } } void SDL_DisableScreenSaver() { if (!_this) { return; } if (_this->suspend_screensaver) { return; } _this->suspend_screensaver = SDL_TRUE; if (_this->SuspendScreenSaver) { _this->SuspendScreenSaver(_this); } } void SDL_VideoQuit(void) { int i, j; if (!_this) { return; } /* Halt event processing before doing anything else */ SDL_TouchQuit(); SDL_MouseQuit(); SDL_KeyboardQuit(); SDL_QuitSubSystem(SDL_INIT_EVENTS); SDL_EnableScreenSaver(); /* Clean up the system video */ while (_this->windows) { SDL_DestroyWindow(_this->windows); } _this->VideoQuit(_this); for (i = 0; i < _this->num_displays; ++i) { SDL_VideoDisplay *display = &_this->displays[i]; for (j = display->num_display_modes; j--;) { SDL_free(display->display_modes[j].driverdata); display->display_modes[j].driverdata = NULL; } SDL_free(display->display_modes); display->display_modes = NULL; SDL_free(display->desktop_mode.driverdata); display->desktop_mode.driverdata = NULL; SDL_free(display->driverdata); display->driverdata = NULL; } if (_this->displays) { for (i = 0; i < _this->num_displays; ++i) { SDL_free(_this->displays[i].name); } SDL_free(_this->displays); _this->displays = NULL; _this->num_displays = 0; } SDL_free(_this->clipboard_text); _this->clipboard_text = NULL; _this->free(_this); _this = NULL; } int SDL_GL_LoadLibrary(const char *path) { int retval; if (!_this) { return SDL_UninitializedVideo(); } if (_this->gl_config.driver_loaded) { if (path && SDL_strcmp(path, _this->gl_config.driver_path) != 0) { return SDL_SetError("OpenGL library already loaded"); } retval = 0; } else { if (!_this->GL_LoadLibrary) { return SDL_SetError("No dynamic GL support in current SDL video driver (%s)", _this->name); } retval = _this->GL_LoadLibrary(_this, path); } if (retval == 0) { ++_this->gl_config.driver_loaded; } else { if (_this->GL_UnloadLibrary) { _this->GL_UnloadLibrary(_this); } } return (retval); } void * SDL_GL_GetProcAddress(const char *proc) { void *func; if (!_this) { SDL_UninitializedVideo(); return NULL; } func = NULL; if (_this->GL_GetProcAddress) { if (_this->gl_config.driver_loaded) { func = _this->GL_GetProcAddress(_this, proc); } else { SDL_SetError("No GL driver has been loaded"); } } else { SDL_SetError("No dynamic GL support in current SDL video driver (%s)", _this->name); } return func; } void SDL_GL_UnloadLibrary(void) { if (!_this) { SDL_UninitializedVideo(); return; } if (_this->gl_config.driver_loaded > 0) { if (--_this->gl_config.driver_loaded > 0) { return; } if (_this->GL_UnloadLibrary) { _this->GL_UnloadLibrary(_this); } } } #if SDL_VIDEO_OPENGL || SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 static SDL_INLINE SDL_bool isAtLeastGL3(const char *verstr) { return (verstr && (SDL_atoi(verstr) >= 3)); } #endif SDL_bool SDL_GL_ExtensionSupported(const char *extension) { #if SDL_VIDEO_OPENGL || SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 const GLubyte *(APIENTRY * glGetStringFunc) (GLenum); const char *extensions; const char *start; const char *where, *terminator; /* Extension names should not have spaces. */ where = SDL_strchr(extension, ' '); if (where || *extension == '\0') { return SDL_FALSE; } /* See if there's an environment variable override */ start = SDL_getenv(extension); if (start && *start == '0') { return SDL_FALSE; } /* Lookup the available extensions */ glGetStringFunc = SDL_GL_GetProcAddress("glGetString"); if (!glGetStringFunc) { return SDL_FALSE; } if (isAtLeastGL3((const char *) glGetStringFunc(GL_VERSION))) { const GLubyte *(APIENTRY * glGetStringiFunc) (GLenum, GLuint); void (APIENTRY * glGetIntegervFunc) (GLenum pname, GLint * params); GLint num_exts = 0; GLint i; glGetStringiFunc = SDL_GL_GetProcAddress("glGetStringi"); glGetIntegervFunc = SDL_GL_GetProcAddress("glGetIntegerv"); if ((!glGetStringiFunc) || (!glGetIntegervFunc)) { return SDL_FALSE; } #ifndef GL_NUM_EXTENSIONS #define GL_NUM_EXTENSIONS 0x821D #endif glGetIntegervFunc(GL_NUM_EXTENSIONS, &num_exts); for (i = 0; i < num_exts; i++) { const char *thisext = (const char *) glGetStringiFunc(GL_EXTENSIONS, i); if (SDL_strcmp(thisext, extension) == 0) { return SDL_TRUE; } } return SDL_FALSE; } /* Try the old way with glGetString(GL_EXTENSIONS) ... */ extensions = (const char *) glGetStringFunc(GL_EXTENSIONS); if (!extensions) { return SDL_FALSE; } /* * It takes a bit of care to be fool-proof about parsing the OpenGL * extensions string. Don't be fooled by sub-strings, etc. */ start = extensions; for (;;) { where = SDL_strstr(start, extension); if (!where) break; terminator = where + SDL_strlen(extension); if (where == extensions || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return SDL_TRUE; start = terminator; } return SDL_FALSE; #else return SDL_FALSE; #endif } /* Deduce supported ES profile versions from the supported ARB_ES*_compatibility extensions. There is no direct query. This is normally only called when the OpenGL driver supports {GLX,WGL}_EXT_create_context_es2_profile. */ void SDL_GL_DeduceMaxSupportedESProfile(int* major, int* minor) { /* THIS REQUIRES AN EXISTING GL CONTEXT THAT HAS BEEN MADE CURRENT. */ /* Please refer to https://bugzilla.libsdl.org/show_bug.cgi?id=3725 for discussion. */ #if SDL_VIDEO_OPENGL || SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 /* XXX This is fragile; it will break in the event of release of * new versions of OpenGL ES. */ if (SDL_GL_ExtensionSupported("GL_ARB_ES3_2_compatibility")) { *major = 3; *minor = 2; } else if (SDL_GL_ExtensionSupported("GL_ARB_ES3_1_compatibility")) { *major = 3; *minor = 1; } else if (SDL_GL_ExtensionSupported("GL_ARB_ES3_compatibility")) { *major = 3; *minor = 0; } else { *major = 2; *minor = 0; } #endif } void SDL_GL_ResetAttributes() { if (!_this) { return; } _this->gl_config.red_size = 3; _this->gl_config.green_size = 3; _this->gl_config.blue_size = 2; _this->gl_config.alpha_size = 0; _this->gl_config.buffer_size = 0; _this->gl_config.depth_size = 16; _this->gl_config.stencil_size = 0; _this->gl_config.double_buffer = 1; _this->gl_config.accum_red_size = 0; _this->gl_config.accum_green_size = 0; _this->gl_config.accum_blue_size = 0; _this->gl_config.accum_alpha_size = 0; _this->gl_config.stereo = 0; _this->gl_config.multisamplebuffers = 0; _this->gl_config.multisamplesamples = 0; _this->gl_config.retained_backing = 1; _this->gl_config.accelerated = -1; /* accelerated or not, both are fine */ if (_this->GL_DefaultProfileConfig) { _this->GL_DefaultProfileConfig(_this, &_this->gl_config.profile_mask, &_this->gl_config.major_version, &_this->gl_config.minor_version); } else { #if SDL_VIDEO_OPENGL _this->gl_config.major_version = 2; _this->gl_config.minor_version = 1; _this->gl_config.profile_mask = 0; #elif SDL_VIDEO_OPENGL_ES2 _this->gl_config.major_version = 2; _this->gl_config.minor_version = 0; _this->gl_config.profile_mask = SDL_GL_CONTEXT_PROFILE_ES; #elif SDL_VIDEO_OPENGL_ES _this->gl_config.major_version = 1; _this->gl_config.minor_version = 1; _this->gl_config.profile_mask = SDL_GL_CONTEXT_PROFILE_ES; #endif } _this->gl_config.flags = 0; _this->gl_config.framebuffer_srgb_capable = 0; _this->gl_config.no_error = 0; _this->gl_config.release_behavior = SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH; _this->gl_config.reset_notification = SDL_GL_CONTEXT_RESET_NO_NOTIFICATION; _this->gl_config.share_with_current_context = 0; } int SDL_GL_SetAttribute(SDL_GLattr attr, int value) { #if SDL_VIDEO_OPENGL || SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 int retval; if (!_this) { return SDL_UninitializedVideo(); } retval = 0; switch (attr) { case SDL_GL_RED_SIZE: _this->gl_config.red_size = value; break; case SDL_GL_GREEN_SIZE: _this->gl_config.green_size = value; break; case SDL_GL_BLUE_SIZE: _this->gl_config.blue_size = value; break; case SDL_GL_ALPHA_SIZE: _this->gl_config.alpha_size = value; break; case SDL_GL_DOUBLEBUFFER: _this->gl_config.double_buffer = value; break; case SDL_GL_BUFFER_SIZE: _this->gl_config.buffer_size = value; break; case SDL_GL_DEPTH_SIZE: _this->gl_config.depth_size = value; break; case SDL_GL_STENCIL_SIZE: _this->gl_config.stencil_size = value; break; case SDL_GL_ACCUM_RED_SIZE: _this->gl_config.accum_red_size = value; break; case SDL_GL_ACCUM_GREEN_SIZE: _this->gl_config.accum_green_size = value; break; case SDL_GL_ACCUM_BLUE_SIZE: _this->gl_config.accum_blue_size = value; break; case SDL_GL_ACCUM_ALPHA_SIZE: _this->gl_config.accum_alpha_size = value; break; case SDL_GL_STEREO: _this->gl_config.stereo = value; break; case SDL_GL_MULTISAMPLEBUFFERS: _this->gl_config.multisamplebuffers = value; break; case SDL_GL_MULTISAMPLESAMPLES: _this->gl_config.multisamplesamples = value; break; case SDL_GL_ACCELERATED_VISUAL: _this->gl_config.accelerated = value; break; case SDL_GL_RETAINED_BACKING: _this->gl_config.retained_backing = value; break; case SDL_GL_CONTEXT_MAJOR_VERSION: _this->gl_config.major_version = value; break; case SDL_GL_CONTEXT_MINOR_VERSION: _this->gl_config.minor_version = value; break; case SDL_GL_CONTEXT_EGL: /* FIXME: SDL_GL_CONTEXT_EGL to be deprecated in SDL 2.1 */ if (value != 0) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); } else { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0); }; break; case SDL_GL_CONTEXT_FLAGS: if (value & ~(SDL_GL_CONTEXT_DEBUG_FLAG | SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG | SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG | SDL_GL_CONTEXT_RESET_ISOLATION_FLAG)) { retval = SDL_SetError("Unknown OpenGL context flag %d", value); break; } _this->gl_config.flags = value; break; case SDL_GL_CONTEXT_PROFILE_MASK: if (value != 0 && value != SDL_GL_CONTEXT_PROFILE_CORE && value != SDL_GL_CONTEXT_PROFILE_COMPATIBILITY && value != SDL_GL_CONTEXT_PROFILE_ES) { retval = SDL_SetError("Unknown OpenGL context profile %d", value); break; } _this->gl_config.profile_mask = value; break; case SDL_GL_SHARE_WITH_CURRENT_CONTEXT: _this->gl_config.share_with_current_context = value; break; case SDL_GL_FRAMEBUFFER_SRGB_CAPABLE: _this->gl_config.framebuffer_srgb_capable = value; break; case SDL_GL_CONTEXT_RELEASE_BEHAVIOR: _this->gl_config.release_behavior = value; break; case SDL_GL_CONTEXT_RESET_NOTIFICATION: _this->gl_config.reset_notification = value; break; case SDL_GL_CONTEXT_NO_ERROR: _this->gl_config.no_error = value; break; default: retval = SDL_SetError("Unknown OpenGL attribute"); break; } return retval; #else return SDL_Unsupported(); #endif /* SDL_VIDEO_OPENGL */ } int SDL_GL_GetAttribute(SDL_GLattr attr, int *value) { #if SDL_VIDEO_OPENGL || SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 GLenum (APIENTRY *glGetErrorFunc) (void); GLenum attrib = 0; GLenum error = 0; /* * Some queries in Core Profile desktop OpenGL 3+ contexts require * glGetFramebufferAttachmentParameteriv instead of glGetIntegerv. Note that * the enums we use for the former function don't exist in OpenGL ES 2, and * the function itself doesn't exist prior to OpenGL 3 and OpenGL ES 2. */ #if SDL_VIDEO_OPENGL const GLubyte *(APIENTRY *glGetStringFunc) (GLenum name); void (APIENTRY *glGetFramebufferAttachmentParameterivFunc) (GLenum target, GLenum attachment, GLenum pname, GLint* params); GLenum attachment = GL_BACK_LEFT; GLenum attachmentattrib = 0; #endif if (!value) { return SDL_InvalidParamError("value"); } /* Clear value in any case */ *value = 0; if (!_this) { return SDL_UninitializedVideo(); } switch (attr) { case SDL_GL_RED_SIZE: #if SDL_VIDEO_OPENGL attachmentattrib = GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE; #endif attrib = GL_RED_BITS; break; case SDL_GL_BLUE_SIZE: #if SDL_VIDEO_OPENGL attachmentattrib = GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE; #endif attrib = GL_BLUE_BITS; break; case SDL_GL_GREEN_SIZE: #if SDL_VIDEO_OPENGL attachmentattrib = GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE; #endif attrib = GL_GREEN_BITS; break; case SDL_GL_ALPHA_SIZE: #if SDL_VIDEO_OPENGL attachmentattrib = GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE; #endif attrib = GL_ALPHA_BITS; break; case SDL_GL_DOUBLEBUFFER: #if SDL_VIDEO_OPENGL attrib = GL_DOUBLEBUFFER; break; #else /* OpenGL ES 1.0 and above specifications have EGL_SINGLE_BUFFER */ /* parameter which switches double buffer to single buffer. OpenGL ES */ /* SDL driver must set proper value after initialization */ *value = _this->gl_config.double_buffer; return 0; #endif case SDL_GL_DEPTH_SIZE: #if SDL_VIDEO_OPENGL attachment = GL_DEPTH; attachmentattrib = GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE; #endif attrib = GL_DEPTH_BITS; break; case SDL_GL_STENCIL_SIZE: #if SDL_VIDEO_OPENGL attachment = GL_STENCIL; attachmentattrib = GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE; #endif attrib = GL_STENCIL_BITS; break; #if SDL_VIDEO_OPENGL case SDL_GL_ACCUM_RED_SIZE: attrib = GL_ACCUM_RED_BITS; break; case SDL_GL_ACCUM_GREEN_SIZE: attrib = GL_ACCUM_GREEN_BITS; break; case SDL_GL_ACCUM_BLUE_SIZE: attrib = GL_ACCUM_BLUE_BITS; break; case SDL_GL_ACCUM_ALPHA_SIZE: attrib = GL_ACCUM_ALPHA_BITS; break; case SDL_GL_STEREO: attrib = GL_STEREO; break; #else case SDL_GL_ACCUM_RED_SIZE: case SDL_GL_ACCUM_GREEN_SIZE: case SDL_GL_ACCUM_BLUE_SIZE: case SDL_GL_ACCUM_ALPHA_SIZE: case SDL_GL_STEREO: /* none of these are supported in OpenGL ES */ *value = 0; return 0; #endif case SDL_GL_MULTISAMPLEBUFFERS: attrib = GL_SAMPLE_BUFFERS; break; case SDL_GL_MULTISAMPLESAMPLES: attrib = GL_SAMPLES; break; case SDL_GL_CONTEXT_RELEASE_BEHAVIOR: #if SDL_VIDEO_OPENGL attrib = GL_CONTEXT_RELEASE_BEHAVIOR; #else attrib = GL_CONTEXT_RELEASE_BEHAVIOR_KHR; #endif break; case SDL_GL_BUFFER_SIZE: { int rsize = 0, gsize = 0, bsize = 0, asize = 0; /* There doesn't seem to be a single flag in OpenGL for this! */ if (SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &rsize) < 0) { return -1; } if (SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &gsize) < 0) { return -1; } if (SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &bsize) < 0) { return -1; } if (SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &asize) < 0) { return -1; } *value = rsize + gsize + bsize + asize; return 0; } case SDL_GL_ACCELERATED_VISUAL: { /* FIXME: How do we get this information? */ *value = (_this->gl_config.accelerated != 0); return 0; } case SDL_GL_RETAINED_BACKING: { *value = _this->gl_config.retained_backing; return 0; } case SDL_GL_CONTEXT_MAJOR_VERSION: { *value = _this->gl_config.major_version; return 0; } case SDL_GL_CONTEXT_MINOR_VERSION: { *value = _this->gl_config.minor_version; return 0; } case SDL_GL_CONTEXT_EGL: /* FIXME: SDL_GL_CONTEXT_EGL to be deprecated in SDL 2.1 */ { if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { *value = 1; } else { *value = 0; } return 0; } case SDL_GL_CONTEXT_FLAGS: { *value = _this->gl_config.flags; return 0; } case SDL_GL_CONTEXT_PROFILE_MASK: { *value = _this->gl_config.profile_mask; return 0; } case SDL_GL_SHARE_WITH_CURRENT_CONTEXT: { *value = _this->gl_config.share_with_current_context; return 0; } case SDL_GL_FRAMEBUFFER_SRGB_CAPABLE: { *value = _this->gl_config.framebuffer_srgb_capable; return 0; } case SDL_GL_CONTEXT_NO_ERROR: { *value = _this->gl_config.no_error; return 0; } default: return SDL_SetError("Unknown OpenGL attribute"); } #if SDL_VIDEO_OPENGL glGetStringFunc = SDL_GL_GetProcAddress("glGetString"); if (!glGetStringFunc) { return -1; } if (attachmentattrib && isAtLeastGL3((const char *) glGetStringFunc(GL_VERSION))) { glGetFramebufferAttachmentParameterivFunc = SDL_GL_GetProcAddress("glGetFramebufferAttachmentParameteriv"); if (glGetFramebufferAttachmentParameterivFunc) { glGetFramebufferAttachmentParameterivFunc(GL_FRAMEBUFFER, attachment, attachmentattrib, (GLint *) value); } else { return -1; } } else #endif { void (APIENTRY *glGetIntegervFunc) (GLenum pname, GLint * params); glGetIntegervFunc = SDL_GL_GetProcAddress("glGetIntegerv"); if (glGetIntegervFunc) { glGetIntegervFunc(attrib, (GLint *) value); } else { return -1; } } glGetErrorFunc = SDL_GL_GetProcAddress("glGetError"); if (!glGetErrorFunc) { return -1; } error = glGetErrorFunc(); if (error != GL_NO_ERROR) { if (error == GL_INVALID_ENUM) { return SDL_SetError("OpenGL error: GL_INVALID_ENUM"); } else if (error == GL_INVALID_VALUE) { return SDL_SetError("OpenGL error: GL_INVALID_VALUE"); } return SDL_SetError("OpenGL error: %08X", error); } return 0; #else return SDL_Unsupported(); #endif /* SDL_VIDEO_OPENGL */ } SDL_GLContext SDL_GL_CreateContext(SDL_Window * window) { SDL_GLContext ctx = NULL; CHECK_WINDOW_MAGIC(window, NULL); if (!(window->flags & SDL_WINDOW_OPENGL)) { SDL_SetError("The specified window isn't an OpenGL window"); return NULL; } ctx = _this->GL_CreateContext(_this, window); /* Creating a context is assumed to make it current in the SDL driver. */ if (ctx) { _this->current_glwin = window; _this->current_glctx = ctx; SDL_TLSSet(_this->current_glwin_tls, window, NULL); SDL_TLSSet(_this->current_glctx_tls, ctx, NULL); } return ctx; } int SDL_GL_MakeCurrent(SDL_Window * window, SDL_GLContext ctx) { int retval; if (window == SDL_GL_GetCurrentWindow() && ctx == SDL_GL_GetCurrentContext()) { /* We're already current. */ return 0; } if (!ctx) { window = NULL; } else if (window) { CHECK_WINDOW_MAGIC(window, -1); if (!(window->flags & SDL_WINDOW_OPENGL)) { return SDL_SetError("The specified window isn't an OpenGL window"); } } else if (!_this->gl_allow_no_surface) { return SDL_SetError("Use of OpenGL without a window is not supported on this platform"); } retval = _this->GL_MakeCurrent(_this, window, ctx); if (retval == 0) { _this->current_glwin = window; _this->current_glctx = ctx; SDL_TLSSet(_this->current_glwin_tls, window, NULL); SDL_TLSSet(_this->current_glctx_tls, ctx, NULL); } return retval; } SDL_Window * SDL_GL_GetCurrentWindow(void) { if (!_this) { SDL_UninitializedVideo(); return NULL; } return (SDL_Window *)SDL_TLSGet(_this->current_glwin_tls); } SDL_GLContext SDL_GL_GetCurrentContext(void) { if (!_this) { SDL_UninitializedVideo(); return NULL; } return (SDL_GLContext)SDL_TLSGet(_this->current_glctx_tls); } void SDL_GL_GetDrawableSize(SDL_Window * window, int *w, int *h) { CHECK_WINDOW_MAGIC(window,); if (_this->GL_GetDrawableSize) { _this->GL_GetDrawableSize(_this, window, w, h); } else { SDL_GetWindowSize(window, w, h); } } int SDL_GL_SetSwapInterval(int interval) { if (!_this) { return SDL_UninitializedVideo(); } else if (SDL_GL_GetCurrentContext() == NULL) { return SDL_SetError("No OpenGL context has been made current"); } else if (_this->GL_SetSwapInterval) { return _this->GL_SetSwapInterval(_this, interval); } else { return SDL_SetError("Setting the swap interval is not supported"); } } int SDL_GL_GetSwapInterval(void) { if (!_this) { return 0; } else if (SDL_GL_GetCurrentContext() == NULL) { return 0; } else if (_this->GL_GetSwapInterval) { return _this->GL_GetSwapInterval(_this); } else { return 0; } } void SDL_GL_SwapWindow(SDL_Window * window) { CHECK_WINDOW_MAGIC(window,); if (!(window->flags & SDL_WINDOW_OPENGL)) { SDL_SetError("The specified window isn't an OpenGL window"); return; } if (SDL_GL_GetCurrentWindow() != window) { SDL_SetError("The specified window has not been made current"); return; } _this->GL_SwapWindow(_this, window); } void SDL_GL_DeleteContext(SDL_GLContext context) { if (!_this || !context) { return; } if (SDL_GL_GetCurrentContext() == context) { SDL_GL_MakeCurrent(NULL, NULL); } _this->GL_DeleteContext(_this, context); } #if 0 /* FIXME */ /* * Utility function used by SDL_WM_SetIcon(); flags & 1 for color key, flags * & 2 for alpha channel. */ static void CreateMaskFromColorKeyOrAlpha(SDL_Surface * icon, Uint8 * mask, int flags) { int x, y; Uint32 colorkey; #define SET_MASKBIT(icon, x, y, mask) \ mask[(y*((icon->w+7)/8))+(x/8)] &= ~(0x01<<(7-(x%8))) colorkey = icon->format->colorkey; switch (icon->format->BytesPerPixel) { case 1: { Uint8 *pixels; for (y = 0; y < icon->h; ++y) { pixels = (Uint8 *) icon->pixels + y * icon->pitch; for (x = 0; x < icon->w; ++x) { if (*pixels++ == colorkey) { SET_MASKBIT(icon, x, y, mask); } } } } break; case 2: { Uint16 *pixels; for (y = 0; y < icon->h; ++y) { pixels = (Uint16 *) icon->pixels + y * icon->pitch / 2; for (x = 0; x < icon->w; ++x) { if ((flags & 1) && *pixels == colorkey) { SET_MASKBIT(icon, x, y, mask); } else if ((flags & 2) && (*pixels & icon->format->Amask) == 0) { SET_MASKBIT(icon, x, y, mask); } pixels++; } } } break; case 4: { Uint32 *pixels; for (y = 0; y < icon->h; ++y) { pixels = (Uint32 *) icon->pixels + y * icon->pitch / 4; for (x = 0; x < icon->w; ++x) { if ((flags & 1) && *pixels == colorkey) { SET_MASKBIT(icon, x, y, mask); } else if ((flags & 2) && (*pixels & icon->format->Amask) == 0) { SET_MASKBIT(icon, x, y, mask); } pixels++; } } } break; } } /* * Sets the window manager icon for the display window. */ void SDL_WM_SetIcon(SDL_Surface * icon, Uint8 * mask) { if (icon && _this->SetIcon) { /* Generate a mask if necessary, and create the icon! */ if (mask == NULL) { int mask_len = icon->h * (icon->w + 7) / 8; int flags = 0; mask = (Uint8 *) SDL_malloc(mask_len); if (mask == NULL) { return; } SDL_memset(mask, ~0, mask_len); if (icon->flags & SDL_SRCCOLORKEY) flags |= 1; if (icon->flags & SDL_SRCALPHA) flags |= 2; if (flags) { CreateMaskFromColorKeyOrAlpha(icon, mask, flags); } _this->SetIcon(_this, icon, mask); SDL_free(mask); } else { _this->SetIcon(_this, icon, mask); } } } #endif SDL_bool SDL_GetWindowWMInfo(SDL_Window * window, struct SDL_SysWMinfo *info) { CHECK_WINDOW_MAGIC(window, SDL_FALSE); if (!info) { SDL_InvalidParamError("info"); return SDL_FALSE; } info->subsystem = SDL_SYSWM_UNKNOWN; if (!_this->GetWindowWMInfo) { SDL_Unsupported(); return SDL_FALSE; } return (_this->GetWindowWMInfo(_this, window, info)); } void SDL_StartTextInput(void) { SDL_Window *window; /* First, enable text events */ SDL_EventState(SDL_TEXTINPUT, SDL_ENABLE); SDL_EventState(SDL_TEXTEDITING, SDL_ENABLE); /* Then show the on-screen keyboard, if any */ window = SDL_GetFocusWindow(); if (window && _this && _this->ShowScreenKeyboard) { _this->ShowScreenKeyboard(_this, window); } /* Finally start the text input system */ if (_this && _this->StartTextInput) { _this->StartTextInput(_this); } } SDL_bool SDL_IsTextInputActive(void) { return (SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE); } void SDL_StopTextInput(void) { SDL_Window *window; /* Stop the text input system */ if (_this && _this->StopTextInput) { _this->StopTextInput(_this); } /* Hide the on-screen keyboard, if any */ window = SDL_GetFocusWindow(); if (window && _this && _this->HideScreenKeyboard) { _this->HideScreenKeyboard(_this, window); } /* Finally disable text events */ SDL_EventState(SDL_TEXTINPUT, SDL_DISABLE); SDL_EventState(SDL_TEXTEDITING, SDL_DISABLE); } void SDL_SetTextInputRect(SDL_Rect *rect) { if (_this && _this->SetTextInputRect) { _this->SetTextInputRect(_this, rect); } } SDL_bool SDL_HasScreenKeyboardSupport(void) { if (_this && _this->HasScreenKeyboardSupport) { return _this->HasScreenKeyboardSupport(_this); } return SDL_FALSE; } SDL_bool SDL_IsScreenKeyboardShown(SDL_Window *window) { if (window && _this && _this->IsScreenKeyboardShown) { return _this->IsScreenKeyboardShown(_this, window); } return SDL_FALSE; } #if SDL_VIDEO_DRIVER_ANDROID #include "android/SDL_androidmessagebox.h" #endif #if SDL_VIDEO_DRIVER_WINDOWS #include "windows/SDL_windowsmessagebox.h" #endif #if SDL_VIDEO_DRIVER_WINRT #include "winrt/SDL_winrtmessagebox.h" #endif #if SDL_VIDEO_DRIVER_COCOA #include "cocoa/SDL_cocoamessagebox.h" #endif #if SDL_VIDEO_DRIVER_UIKIT #include "uikit/SDL_uikitmessagebox.h" #endif #if SDL_VIDEO_DRIVER_X11 #include "x11/SDL_x11messagebox.h" #endif #if SDL_VIDEO_DRIVER_HAIKU #include "haiku/SDL_bmessagebox.h" #endif #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT || SDL_VIDEO_DRIVER_COCOA || SDL_VIDEO_DRIVER_UIKIT || SDL_VIDEO_DRIVER_X11 || SDL_VIDEO_DRIVER_HAIKU static SDL_bool SDL_MessageboxValidForDriver(const SDL_MessageBoxData *messageboxdata, SDL_SYSWM_TYPE drivertype) { SDL_SysWMinfo info; SDL_Window *window = messageboxdata->window; if (!window) { return SDL_TRUE; } SDL_VERSION(&info.version); if (!SDL_GetWindowWMInfo(window, &info)) { return SDL_TRUE; } else { return (info.subsystem == drivertype); } } #endif int SDL_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) { int dummybutton; int retval = -1; SDL_bool relative_mode; int show_cursor_prev; SDL_bool mouse_captured; SDL_Window *current_window; if (!messageboxdata) { return SDL_InvalidParamError("messageboxdata"); } else if (messageboxdata->numbuttons < 0) { return SDL_SetError("Invalid number of buttons"); } current_window = SDL_GetKeyboardFocus(); mouse_captured = current_window && ((SDL_GetWindowFlags(current_window) & SDL_WINDOW_MOUSE_CAPTURE) != 0); relative_mode = SDL_GetRelativeMouseMode(); SDL_CaptureMouse(SDL_FALSE); SDL_SetRelativeMouseMode(SDL_FALSE); show_cursor_prev = SDL_ShowCursor(1); SDL_ResetKeyboard(); if (!buttonid) { buttonid = &dummybutton; } if (_this && _this->ShowMessageBox) { retval = _this->ShowMessageBox(_this, messageboxdata, buttonid); } /* It's completely fine to call this function before video is initialized */ #if SDL_VIDEO_DRIVER_ANDROID if (retval == -1 && Android_ShowMessageBox(messageboxdata, buttonid) == 0) { retval = 0; } #endif #if SDL_VIDEO_DRIVER_WINDOWS if (retval == -1 && SDL_MessageboxValidForDriver(messageboxdata, SDL_SYSWM_WINDOWS) && WIN_ShowMessageBox(messageboxdata, buttonid) == 0) { retval = 0; } #endif #if SDL_VIDEO_DRIVER_WINRT if (retval == -1 && SDL_MessageboxValidForDriver(messageboxdata, SDL_SYSWM_WINRT) && WINRT_ShowMessageBox(messageboxdata, buttonid) == 0) { retval = 0; } #endif #if SDL_VIDEO_DRIVER_COCOA if (retval == -1 && SDL_MessageboxValidForDriver(messageboxdata, SDL_SYSWM_COCOA) && Cocoa_ShowMessageBox(messageboxdata, buttonid) == 0) { retval = 0; } #endif #if SDL_VIDEO_DRIVER_UIKIT if (retval == -1 && SDL_MessageboxValidForDriver(messageboxdata, SDL_SYSWM_UIKIT) && UIKit_ShowMessageBox(messageboxdata, buttonid) == 0) { retval = 0; } #endif #if SDL_VIDEO_DRIVER_X11 if (retval == -1 && SDL_MessageboxValidForDriver(messageboxdata, SDL_SYSWM_X11) && X11_ShowMessageBox(messageboxdata, buttonid) == 0) { retval = 0; } #endif #if SDL_VIDEO_DRIVER_HAIKU if (retval == -1 && SDL_MessageboxValidForDriver(messageboxdata, SDL_SYSWM_HAIKU) && HAIKU_ShowMessageBox(messageboxdata, buttonid) == 0) { retval = 0; } #endif if (retval == -1) { SDL_SetError("No message system available"); } if (current_window) { SDL_RaiseWindow(current_window); if (mouse_captured) { SDL_CaptureMouse(SDL_TRUE); } } SDL_ShowCursor(show_cursor_prev); SDL_SetRelativeMouseMode(relative_mode); return retval; } int SDL_ShowSimpleMessageBox(Uint32 flags, const char *title, const char *message, SDL_Window *window) { #ifdef __EMSCRIPTEN__ /* !!! FIXME: propose a browser API for this, get this #ifdef out of here? */ /* Web browsers don't (currently) have an API for a custom message box that can block, but for the most common case (SDL_ShowSimpleMessageBox), we can use the standard Javascript alert() function. */ EM_ASM_({ alert(UTF8ToString($0) + "\n\n" + UTF8ToString($1)); }, title, message); return 0; #else SDL_MessageBoxData data; SDL_MessageBoxButtonData button; SDL_zero(data); data.flags = flags; data.title = title; data.message = message; data.numbuttons = 1; data.buttons = &button; data.window = window; SDL_zero(button); button.flags |= SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT; button.flags |= SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT; button.text = "OK"; return SDL_ShowMessageBox(&data, NULL); #endif } SDL_bool SDL_ShouldAllowTopmost(void) { return SDL_GetHintBoolean(SDL_HINT_ALLOW_TOPMOST, SDL_TRUE); } int SDL_SetWindowHitTest(SDL_Window * window, SDL_HitTest callback, void *userdata) { CHECK_WINDOW_MAGIC(window, -1); if (!_this->SetWindowHitTest) { return SDL_Unsupported(); } else if (_this->SetWindowHitTest(window, callback != NULL) == -1) { return -1; } window->hit_test = callback; window->hit_test_data = userdata; return 0; } float SDL_ComputeDiagonalDPI(int hpix, int vpix, float hinches, float vinches) { float den2 = hinches * hinches + vinches * vinches; if (den2 <= 0.0f) { return 0.0f; } return (float)(SDL_sqrt((double)hpix * (double)hpix + (double)vpix * (double)vpix) / SDL_sqrt((double)den2)); } /* * Functions used by iOS application delegates */ void SDL_OnApplicationWillTerminate(void) { SDL_SendAppEvent(SDL_APP_TERMINATING); } void SDL_OnApplicationDidReceiveMemoryWarning(void) { SDL_SendAppEvent(SDL_APP_LOWMEMORY); } void SDL_OnApplicationWillResignActive(void) { if (_this) { SDL_Window *window; for (window = _this->windows; window != NULL; window = window->next) { SDL_SendWindowEvent(window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0); SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MINIMIZED, 0, 0); } } SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND); } void SDL_OnApplicationDidEnterBackground(void) { SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND); } void SDL_OnApplicationWillEnterForeground(void) { SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND); } void SDL_OnApplicationDidBecomeActive(void) { SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND); if (_this) { SDL_Window *window; for (window = _this->windows; window != NULL; window = window->next) { SDL_SendWindowEvent(window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0); SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESTORED, 0, 0); } } } #define NOT_A_VULKAN_WINDOW "The specified window isn't a Vulkan window" int SDL_Vulkan_LoadLibrary(const char *path) { int retval; if (!_this) { SDL_UninitializedVideo(); return -1; } if (_this->vulkan_config.loader_loaded) { if (path && SDL_strcmp(path, _this->vulkan_config.loader_path) != 0) { return SDL_SetError("Vulkan loader library already loaded"); } retval = 0; } else { if (!_this->Vulkan_LoadLibrary) { return SDL_SetError("Vulkan support is either not configured in SDL " "or not available in current SDL video driver " "(%s) or platform", _this->name); } retval = _this->Vulkan_LoadLibrary(_this, path); } if (retval == 0) { _this->vulkan_config.loader_loaded++; } return retval; } void *SDL_Vulkan_GetVkGetInstanceProcAddr(void) { if (!_this) { SDL_UninitializedVideo(); return NULL; } if (!_this->vulkan_config.loader_loaded) { SDL_SetError("No Vulkan loader has been loaded"); return NULL; } return _this->vulkan_config.vkGetInstanceProcAddr; } void SDL_Vulkan_UnloadLibrary(void) { if (!_this) { SDL_UninitializedVideo(); return; } if (_this->vulkan_config.loader_loaded > 0) { if (--_this->vulkan_config.loader_loaded > 0) { return; } if (_this->Vulkan_UnloadLibrary) { _this->Vulkan_UnloadLibrary(_this); } } } SDL_bool SDL_Vulkan_GetInstanceExtensions(SDL_Window *window, unsigned *count, const char **names) { if (window) { CHECK_WINDOW_MAGIC(window, SDL_FALSE); if (!(window->flags & SDL_WINDOW_VULKAN)) { SDL_SetError(NOT_A_VULKAN_WINDOW); return SDL_FALSE; } } if (!count) { SDL_InvalidParamError("count"); return SDL_FALSE; } return _this->Vulkan_GetInstanceExtensions(_this, window, count, names); } SDL_bool SDL_Vulkan_CreateSurface(SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { CHECK_WINDOW_MAGIC(window, SDL_FALSE); if (!(window->flags & SDL_WINDOW_VULKAN)) { SDL_SetError(NOT_A_VULKAN_WINDOW); return SDL_FALSE; } if (!instance) { SDL_InvalidParamError("instance"); return SDL_FALSE; } if (!surface) { SDL_InvalidParamError("surface"); return SDL_FALSE; } return _this->Vulkan_CreateSurface(_this, window, instance, surface); } void SDL_Vulkan_GetDrawableSize(SDL_Window * window, int *w, int *h) { CHECK_WINDOW_MAGIC(window,); if (_this->Vulkan_GetDrawableSize) { _this->Vulkan_GetDrawableSize(_this, window, w, h); } else { SDL_GetWindowSize(window, w, h); } } SDL_MetalView SDL_Metal_CreateView(SDL_Window * window) { CHECK_WINDOW_MAGIC(window, NULL); if (!(window->flags & SDL_WINDOW_METAL)) { SDL_SetError("The specified window isn't a Metal window"); return NULL; } if (_this->Metal_CreateView) { return _this->Metal_CreateView(_this, window); } else { SDL_SetError("Metal is not supported."); return NULL; } } void SDL_Metal_DestroyView(SDL_MetalView view) { if (_this && view && _this->Metal_DestroyView) { _this->Metal_DestroyView(_this, view); } } void * SDL_Metal_GetLayer(SDL_MetalView view) { if (_this && _this->Metal_GetLayer) { if (view) { return _this->Metal_GetLayer(_this, view); } else { SDL_InvalidParamError("view"); return NULL; } } else { SDL_SetError("Metal is not supported."); return NULL; } } void SDL_Metal_GetDrawableSize(SDL_Window * window, int *w, int *h) { CHECK_WINDOW_MAGIC(window,); if (_this->Metal_GetDrawableSize) { _this->Metal_GetDrawableSize(_this, window, w, h); } else { SDL_GetWindowSize(window, w, h); } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_video.c
C
apache-2.0
118,051
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_vulkan_internal_h_ #define SDL_vulkan_internal_h_ #include "../SDL_internal.h" #include "SDL_stdinc.h" #if defined(SDL_LOADSO_DISABLED) #undef SDL_VIDEO_VULKAN #define SDL_VIDEO_VULKAN 0 #endif #if SDL_VIDEO_VULKAN #if SDL_VIDEO_DRIVER_ANDROID #define VK_USE_PLATFORM_ANDROID_KHR #endif #if SDL_VIDEO_DRIVER_COCOA #define VK_USE_PLATFORM_MACOS_MVK #endif #if SDL_VIDEO_DRIVER_UIKIT #define VK_USE_PLATFORM_IOS_MVK #endif #if SDL_VIDEO_DRIVER_WAYLAND #define VK_USE_PLATFORM_WAYLAND_KHR #include "wayland/SDL_waylanddyn.h" #endif #if SDL_VIDEO_DRIVER_WINDOWS #define VK_USE_PLATFORM_WIN32_KHR #include "../core/windows/SDL_windows.h" #endif #if SDL_VIDEO_DRIVER_X11 #define VK_USE_PLATFORM_XLIB_KHR #define VK_USE_PLATFORM_XCB_KHR #endif #define VK_NO_PROTOTYPES #include "./khronos/vulkan/vulkan.h" #include "SDL_vulkan.h" extern const char *SDL_Vulkan_GetResultString(VkResult result); extern VkExtensionProperties *SDL_Vulkan_CreateInstanceExtensionsList( PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties, Uint32 *extensionCount); /* free returned list with SDL_free */ /* Implements functionality of SDL_Vulkan_GetInstanceExtensions for a list of * names passed in nameCount and names. */ extern SDL_bool SDL_Vulkan_GetInstanceExtensions_Helper(unsigned *userCount, const char **userNames, unsigned nameCount, const char *const *names); /* Create a surface directly from a display connected to a physical device * using the DisplayKHR extension. * This needs to be passed an instance that was created with the VK_KHR_DISPLAY_EXTENSION_NAME * exension. */ extern SDL_bool SDL_Vulkan_Display_CreateSurface(void *vkGetInstanceProcAddr, VkInstance instance, VkSurfaceKHR *surface); #else /* No SDL Vulkan support, just include the header for typedefs */ #include "SDL_vulkan.h" typedef void (*PFN_vkGetInstanceProcAddr) (void); typedef int (*PFN_vkEnumerateInstanceExtensionProperties) (void); #endif /* SDL_VIDEO_VULKAN */ #endif /* SDL_vulkan_internal_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_vulkan_internal.h
C
apache-2.0
3,274
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL_vulkan_internal.h" #include "SDL_error.h" /* !!! FIXME: this file doesn't match coding standards for SDL (brace position, etc). */ #if SDL_VIDEO_VULKAN const char *SDL_Vulkan_GetResultString(VkResult result) { switch((int)result) { case VK_SUCCESS: return "VK_SUCCESS"; case VK_NOT_READY: return "VK_NOT_READY"; case VK_TIMEOUT: return "VK_TIMEOUT"; case VK_EVENT_SET: return "VK_EVENT_SET"; case VK_EVENT_RESET: return "VK_EVENT_RESET"; case VK_INCOMPLETE: return "VK_INCOMPLETE"; case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL"; case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR"; case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR"; case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR"; case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; case VK_ERROR_VALIDATION_FAILED_EXT: return "VK_ERROR_VALIDATION_FAILED_EXT"; case VK_ERROR_OUT_OF_POOL_MEMORY_KHR: return "VK_ERROR_OUT_OF_POOL_MEMORY_KHR"; case VK_ERROR_INVALID_SHADER_NV: return "VK_ERROR_INVALID_SHADER_NV"; case VK_RESULT_MAX_ENUM: case VK_RESULT_RANGE_SIZE: break; } if(result < 0) return "VK_ERROR_<Unknown>"; return "VK_<Unknown>"; } VkExtensionProperties *SDL_Vulkan_CreateInstanceExtensionsList( PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties, Uint32 *extensionCount) { Uint32 count = 0; VkResult result = vkEnumerateInstanceExtensionProperties(NULL, &count, NULL); VkExtensionProperties *retval; if(result == VK_ERROR_INCOMPATIBLE_DRIVER) { /* Avoid the ERR_MAX_STRLEN limit by passing part of the message * as a string argument. */ SDL_SetError( "You probably don't have a working Vulkan driver installed. %s %s %s(%d)", "Getting Vulkan extensions failed:", "vkEnumerateInstanceExtensionProperties returned", SDL_Vulkan_GetResultString(result), (int)result); return NULL; } else if(result != VK_SUCCESS) { SDL_SetError( "Getting Vulkan extensions failed: vkEnumerateInstanceExtensionProperties returned " "%s(%d)", SDL_Vulkan_GetResultString(result), (int)result); return NULL; } if(count == 0) { retval = SDL_calloc(1, sizeof(VkExtensionProperties)); // so we can return non-null } else { retval = SDL_calloc(count, sizeof(VkExtensionProperties)); } if(!retval) { SDL_OutOfMemory(); return NULL; } result = vkEnumerateInstanceExtensionProperties(NULL, &count, retval); if(result != VK_SUCCESS) { SDL_SetError( "Getting Vulkan extensions failed: vkEnumerateInstanceExtensionProperties returned " "%s(%d)", SDL_Vulkan_GetResultString(result), (int)result); SDL_free(retval); return NULL; } *extensionCount = count; return retval; } SDL_bool SDL_Vulkan_GetInstanceExtensions_Helper(unsigned *userCount, const char **userNames, unsigned nameCount, const char *const *names) { if (userNames) { unsigned i; if (*userCount < nameCount) { SDL_SetError("Output array for SDL_Vulkan_GetInstanceExtensions needs to be at least %d big", nameCount); return SDL_FALSE; } for (i = 0; i < nameCount; i++) { userNames[i] = names[i]; } } *userCount = nameCount; return SDL_TRUE; } /* Alpha modes, in order of preference */ static const VkDisplayPlaneAlphaFlagBitsKHR alphaModes[4] = { VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR, VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR, VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR, VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR, }; SDL_bool SDL_Vulkan_Display_CreateSurface(void *vkGetInstanceProcAddr_, VkInstance instance, VkSurfaceKHR *surface) { PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)vkGetInstanceProcAddr_; #define VULKAN_INSTANCE_FUNCTION(name) \ PFN_##name name = (PFN_##name)vkGetInstanceProcAddr((VkInstance)instance, #name) VULKAN_INSTANCE_FUNCTION(vkEnumeratePhysicalDevices); VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceDisplayPropertiesKHR); VULKAN_INSTANCE_FUNCTION(vkGetDisplayModePropertiesKHR); VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceDisplayPlanePropertiesKHR); VULKAN_INSTANCE_FUNCTION(vkGetDisplayPlaneCapabilitiesKHR); VULKAN_INSTANCE_FUNCTION(vkGetDisplayPlaneSupportedDisplaysKHR); VULKAN_INSTANCE_FUNCTION(vkCreateDisplayPlaneSurfaceKHR); #undef VULKAN_INSTANCE_FUNCTION VkDisplaySurfaceCreateInfoKHR createInfo; VkResult result; uint32_t physicalDeviceCount = 0; VkPhysicalDevice *physicalDevices = NULL; uint32_t physicalDeviceIndex; const char *chosenDisplayId; int displayId = 0; /* Counting from physical device 0, display 0 */ if(!vkEnumeratePhysicalDevices || !vkGetPhysicalDeviceDisplayPropertiesKHR || !vkGetDisplayModePropertiesKHR || !vkGetPhysicalDeviceDisplayPlanePropertiesKHR || !vkGetDisplayPlaneCapabilitiesKHR || !vkGetDisplayPlaneSupportedDisplaysKHR || !vkCreateDisplayPlaneSurfaceKHR) { SDL_SetError(VK_KHR_DISPLAY_EXTENSION_NAME " extension is not enabled in the Vulkan instance."); goto error; } if ((chosenDisplayId = SDL_getenv("SDL_VULKAN_DISPLAY")) != NULL) { displayId = SDL_atoi(chosenDisplayId); } /* Enumerate physical devices */ result = vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, NULL); if(result != VK_SUCCESS) { SDL_SetError("Could not enumerate Vulkan physical devices"); goto error; } if(physicalDeviceCount == 0) { SDL_SetError("No Vulkan physical devices"); goto error; } physicalDevices = SDL_malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount); if(!physicalDevices) { SDL_OutOfMemory(); goto error; } result = vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices); if(result != VK_SUCCESS) { SDL_SetError("Error enumerating physical devices"); goto error; } for(physicalDeviceIndex = 0; physicalDeviceIndex < physicalDeviceCount; physicalDeviceIndex++) { VkPhysicalDevice physicalDevice = physicalDevices[physicalDeviceIndex]; uint32_t displayPropertiesCount = 0; VkDisplayPropertiesKHR *displayProperties = NULL; uint32_t displayModePropertiesCount = 0; VkDisplayModePropertiesKHR *displayModeProperties = NULL; int bestMatchIndex = -1; uint32_t refreshRate = 0; uint32_t i; uint32_t displayPlanePropertiesCount = 0; int planeIndex = -1; VkDisplayKHR display; VkDisplayPlanePropertiesKHR *displayPlaneProperties = NULL; VkExtent2D extent; VkDisplayPlaneCapabilitiesKHR planeCaps; /* Get information about the physical displays */ result = vkGetPhysicalDeviceDisplayPropertiesKHR(physicalDevice, &displayPropertiesCount, NULL); if (result != VK_SUCCESS || displayPropertiesCount == 0) { /* This device has no physical device display properties, move on to next. */ continue; } SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Number of display properties for device %u: %u", physicalDeviceIndex, displayPropertiesCount); if ( (displayId < 0) || (((uint32_t) displayId) >= displayPropertiesCount) ) { /* Display id specified was higher than number of available displays, move to next physical device. */ displayId -= displayPropertiesCount; continue; } displayProperties = SDL_malloc(sizeof(VkDisplayPropertiesKHR) * displayPropertiesCount); if(!displayProperties) { SDL_OutOfMemory(); goto error; } result = vkGetPhysicalDeviceDisplayPropertiesKHR(physicalDevice, &displayPropertiesCount, displayProperties); if (result != VK_SUCCESS || displayPropertiesCount == 0) { SDL_free(displayProperties); SDL_SetError("Error enumerating physical device displays"); goto error; } display = displayProperties[displayId].display; extent = displayProperties[displayId].physicalResolution; SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Display: %s Native resolution: %ux%u", displayProperties[displayId].displayName, extent.width, extent.height); SDL_free(displayProperties); displayProperties = NULL; /* Get display mode properties for the chosen display */ result = vkGetDisplayModePropertiesKHR(physicalDevice, display, &displayModePropertiesCount, NULL); if (result != VK_SUCCESS || displayModePropertiesCount == 0) { SDL_SetError("Error enumerating display modes"); goto error; } SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Number of display modes: %u", displayModePropertiesCount); displayModeProperties = SDL_malloc(sizeof(VkDisplayModePropertiesKHR) * displayModePropertiesCount); if(!displayModeProperties) { SDL_OutOfMemory(); goto error; } result = vkGetDisplayModePropertiesKHR(physicalDevice, display, &displayModePropertiesCount, displayModeProperties); if (result != VK_SUCCESS || displayModePropertiesCount == 0) { SDL_SetError("Error enumerating display modes"); SDL_free(displayModeProperties); goto error; } /* Try to find a display mode that matches the native resolution */ for (i = 0; i < displayModePropertiesCount; ++i) { if (displayModeProperties[i].parameters.visibleRegion.width == extent.width && displayModeProperties[i].parameters.visibleRegion.height == extent.height && displayModeProperties[i].parameters.refreshRate > refreshRate) { bestMatchIndex = i; refreshRate = displayModeProperties[i].parameters.refreshRate; } } if (bestMatchIndex < 0) { SDL_SetError("Found no matching display mode"); SDL_free(displayModeProperties); goto error; } SDL_zero(createInfo); createInfo.displayMode = displayModeProperties[bestMatchIndex].displayMode; SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Matching mode %ux%u with refresh rate %u", displayModeProperties[bestMatchIndex].parameters.visibleRegion.width, displayModeProperties[bestMatchIndex].parameters.visibleRegion.height, refreshRate); SDL_free(displayModeProperties); displayModeProperties = NULL; /* Try to find a plane index that supports our display */ result = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(physicalDevice, &displayPlanePropertiesCount, NULL); if (result != VK_SUCCESS || displayPlanePropertiesCount == 0) { SDL_SetError("Error enumerating display planes"); goto error; } SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Number of display planes: %u", displayPlanePropertiesCount); displayPlaneProperties = SDL_malloc(sizeof(VkDisplayPlanePropertiesKHR) * displayPlanePropertiesCount); if(!displayPlaneProperties) { SDL_OutOfMemory(); goto error; } result = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(physicalDevice, &displayPlanePropertiesCount, displayPlaneProperties); if (result != VK_SUCCESS || displayPlanePropertiesCount == 0) { SDL_SetError("Error enumerating display plane properties"); SDL_free(displayPlaneProperties); goto error; } for (i = 0; i < displayPlanePropertiesCount; ++i) { uint32_t planeSupportedDisplaysCount = 0; VkDisplayKHR *planeSupportedDisplays = NULL; uint32_t j; /* Check if plane is attached to a display, if not, continue. */ if (displayPlaneProperties[i].currentDisplay == VK_NULL_HANDLE) continue; /* Check supported displays for this plane. */ result = vkGetDisplayPlaneSupportedDisplaysKHR(physicalDevice, i, &planeSupportedDisplaysCount, NULL); if (result != VK_SUCCESS || planeSupportedDisplaysCount == 0) { continue; /* No supported displays, on to next plane. */ } SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Number of supported displays for plane %u: %u", i, planeSupportedDisplaysCount); planeSupportedDisplays = SDL_malloc(sizeof(VkDisplayKHR) * planeSupportedDisplaysCount); if(!planeSupportedDisplays) { SDL_free(displayPlaneProperties); SDL_OutOfMemory(); goto error; } result = vkGetDisplayPlaneSupportedDisplaysKHR(physicalDevice, i, &planeSupportedDisplaysCount, planeSupportedDisplays); if (result != VK_SUCCESS || planeSupportedDisplaysCount == 0) { SDL_SetError("Error enumerating supported displays, or no supported displays"); SDL_free(planeSupportedDisplays); SDL_free(displayPlaneProperties); goto error; } for (j = 0; j < planeSupportedDisplaysCount && planeSupportedDisplays[j] != display; ++j) ; SDL_free(planeSupportedDisplays); planeSupportedDisplays = NULL; if (j == planeSupportedDisplaysCount) { /* This display is not supported for this plane, move on. */ continue; } result = vkGetDisplayPlaneCapabilitiesKHR(physicalDevice, createInfo.displayMode, i, &planeCaps); if (result != VK_SUCCESS) { SDL_SetError("Error getting display plane capabilities"); SDL_free(displayPlaneProperties); goto error; } /* Check if plane fulfills extent requirements. */ if (extent.width >= planeCaps.minDstExtent.width && extent.height >= planeCaps.minDstExtent.height && extent.width <= planeCaps.maxDstExtent.width && extent.height <= planeCaps.maxDstExtent.height) { /* If it does, choose this plane. */ SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Choosing plane %d, minimum extent %dx%d maximum extent %dx%d", i, planeCaps.minDstExtent.width, planeCaps.minDstExtent.height, planeCaps.maxDstExtent.width, planeCaps.maxDstExtent.height); planeIndex = i; break; } } if (planeIndex < 0) { SDL_SetError("No plane supports the selected resolution"); SDL_free(displayPlaneProperties); goto error; } createInfo.planeIndex = planeIndex; createInfo.planeStackIndex = displayPlaneProperties[planeIndex].currentStackIndex; SDL_free(displayPlaneProperties); displayPlaneProperties = NULL; /* Find a supported alpha mode. Not all planes support OPAQUE */ createInfo.alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR; for (i = 0; i < SDL_arraysize(alphaModes); i++) { if (planeCaps.supportedAlpha & alphaModes[i]) { createInfo.alphaMode = alphaModes[i]; break; } } SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Chose alpha mode 0x%x", createInfo.alphaMode); /* Found a match, finally! Fill in extent, and break from loop */ createInfo.imageExtent = extent; break; } SDL_free(physicalDevices); physicalDevices = NULL; if (physicalDeviceIndex == physicalDeviceCount) { SDL_SetError("No usable displays found or requested display out of range"); return SDL_FALSE; } createInfo.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR; createInfo.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; createInfo.globalAlpha = 1.0f; result = vkCreateDisplayPlaneSurfaceKHR(instance, &createInfo, NULL, surface); if(result != VK_SUCCESS) { SDL_SetError("vkCreateDisplayPlaneSurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result)); return SDL_FALSE; } SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "vulkandisplay: Created surface"); return SDL_TRUE; error: SDL_free(physicalDevices); return SDL_FALSE; } #endif /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_vulkan_utils.c
C
apache-2.0
19,761
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" #include "SDL_endian.h" #include "SDL_video.h" #include "SDL_pixels_c.h" #include "SDL_yuv_c.h" #include "yuv2rgb/yuv_rgb.h" #define SDL_YUV_SD_THRESHOLD 576 static SDL_YUV_CONVERSION_MODE SDL_YUV_ConversionMode = SDL_YUV_CONVERSION_BT601; void SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_MODE mode) { SDL_YUV_ConversionMode = mode; } SDL_YUV_CONVERSION_MODE SDL_GetYUVConversionMode() { return SDL_YUV_ConversionMode; } SDL_YUV_CONVERSION_MODE SDL_GetYUVConversionModeForResolution(int width, int height) { SDL_YUV_CONVERSION_MODE mode = SDL_GetYUVConversionMode(); if (mode == SDL_YUV_CONVERSION_AUTOMATIC) { if (height <= SDL_YUV_SD_THRESHOLD) { mode = SDL_YUV_CONVERSION_BT601; } else { mode = SDL_YUV_CONVERSION_BT709; } } return mode; } #if SDL_HAVE_YUV static int GetYUVConversionType(int width, int height, YCbCrType *yuv_type) { switch (SDL_GetYUVConversionModeForResolution(width, height)) { case SDL_YUV_CONVERSION_JPEG: *yuv_type = YCBCR_JPEG; break; case SDL_YUV_CONVERSION_BT601: *yuv_type = YCBCR_601; break; case SDL_YUV_CONVERSION_BT709: *yuv_type = YCBCR_709; break; default: return SDL_SetError("Unexpected YUV conversion mode"); } return 0; } static SDL_bool IsPlanar2x2Format(Uint32 format) { return (format == SDL_PIXELFORMAT_YV12 || format == SDL_PIXELFORMAT_IYUV || format == SDL_PIXELFORMAT_NV12 || format == SDL_PIXELFORMAT_NV21); } static SDL_bool IsPacked4Format(Uint32 format) { return (format == SDL_PIXELFORMAT_YUY2 || format == SDL_PIXELFORMAT_UYVY || format == SDL_PIXELFORMAT_YVYU); } static int GetYUVPlanes(int width, int height, Uint32 format, const void *yuv, int yuv_pitch, const Uint8 **y, const Uint8 **u, const Uint8 **v, Uint32 *y_stride, Uint32 *uv_stride) { const Uint8 *planes[3] = { NULL, NULL, NULL }; int pitches[3] = { 0, 0, 0 }; switch (format) { case SDL_PIXELFORMAT_YV12: case SDL_PIXELFORMAT_IYUV: pitches[0] = yuv_pitch; pitches[1] = (pitches[0] + 1) / 2; pitches[2] = (pitches[0] + 1) / 2; planes[0] = (const Uint8 *)yuv; planes[1] = planes[0] + pitches[0] * height; planes[2] = planes[1] + pitches[1] * ((height + 1) / 2); break; case SDL_PIXELFORMAT_YUY2: case SDL_PIXELFORMAT_UYVY: case SDL_PIXELFORMAT_YVYU: pitches[0] = yuv_pitch; planes[0] = (const Uint8 *)yuv; break; case SDL_PIXELFORMAT_NV12: case SDL_PIXELFORMAT_NV21: pitches[0] = yuv_pitch; pitches[1] = 2 * ((pitches[0] + 1) / 2); planes[0] = (const Uint8 *)yuv; planes[1] = planes[0] + pitches[0] * height; break; default: return SDL_SetError("GetYUVPlanes(): Unsupported YUV format: %s", SDL_GetPixelFormatName(format)); } switch (format) { case SDL_PIXELFORMAT_YV12: *y = planes[0]; *y_stride = pitches[0]; *v = planes[1]; *u = planes[2]; *uv_stride = pitches[1]; break; case SDL_PIXELFORMAT_IYUV: *y = planes[0]; *y_stride = pitches[0]; *v = planes[2]; *u = planes[1]; *uv_stride = pitches[1]; break; case SDL_PIXELFORMAT_YUY2: *y = planes[0]; *y_stride = pitches[0]; *v = *y + 3; *u = *y + 1; *uv_stride = pitches[0]; break; case SDL_PIXELFORMAT_UYVY: *y = planes[0] + 1; *y_stride = pitches[0]; *v = *y + 1; *u = *y - 1; *uv_stride = pitches[0]; break; case SDL_PIXELFORMAT_YVYU: *y = planes[0]; *y_stride = pitches[0]; *v = *y + 1; *u = *y + 3; *uv_stride = pitches[0]; break; case SDL_PIXELFORMAT_NV12: *y = planes[0]; *y_stride = pitches[0]; *u = planes[1]; *v = *u + 1; *uv_stride = pitches[1]; break; case SDL_PIXELFORMAT_NV21: *y = planes[0]; *y_stride = pitches[0]; *v = planes[1]; *u = *v + 1; *uv_stride = pitches[1]; break; default: /* Should have caught this above */ return SDL_SetError("GetYUVPlanes[2]: Unsupported YUV format: %s", SDL_GetPixelFormatName(format)); } return 0; } static SDL_bool yuv_rgb_sse( Uint32 src_format, Uint32 dst_format, Uint32 width, Uint32 height, const Uint8 *y, const Uint8 *u, const Uint8 *v, Uint32 y_stride, Uint32 uv_stride, Uint8 *rgb, Uint32 rgb_stride, YCbCrType yuv_type) { #ifdef __SSE2__ if (!SDL_HasSSE2()) { return SDL_FALSE; } if (src_format == SDL_PIXELFORMAT_YV12 || src_format == SDL_PIXELFORMAT_IYUV) { switch (dst_format) { case SDL_PIXELFORMAT_RGB565: yuv420_rgb565_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB24: yuv420_rgb24_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGBX8888: case SDL_PIXELFORMAT_RGBA8888: yuv420_rgba_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGRX8888: case SDL_PIXELFORMAT_BGRA8888: yuv420_bgra_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB888: case SDL_PIXELFORMAT_ARGB8888: yuv420_argb_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGR888: case SDL_PIXELFORMAT_ABGR8888: yuv420_abgr_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; default: break; } } if (src_format == SDL_PIXELFORMAT_YUY2 || src_format == SDL_PIXELFORMAT_UYVY || src_format == SDL_PIXELFORMAT_YVYU) { switch (dst_format) { case SDL_PIXELFORMAT_RGB565: yuv422_rgb565_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB24: yuv422_rgb24_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGBX8888: case SDL_PIXELFORMAT_RGBA8888: yuv422_rgba_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGRX8888: case SDL_PIXELFORMAT_BGRA8888: yuv422_bgra_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB888: case SDL_PIXELFORMAT_ARGB8888: yuv422_argb_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGR888: case SDL_PIXELFORMAT_ABGR8888: yuv422_abgr_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; default: break; } } if (src_format == SDL_PIXELFORMAT_NV12 || src_format == SDL_PIXELFORMAT_NV21) { switch (dst_format) { case SDL_PIXELFORMAT_RGB565: yuvnv12_rgb565_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB24: yuvnv12_rgb24_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGBX8888: case SDL_PIXELFORMAT_RGBA8888: yuvnv12_rgba_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGRX8888: case SDL_PIXELFORMAT_BGRA8888: yuvnv12_bgra_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB888: case SDL_PIXELFORMAT_ARGB8888: yuvnv12_argb_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGR888: case SDL_PIXELFORMAT_ABGR8888: yuvnv12_abgr_sseu(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; default: break; } } #endif return SDL_FALSE; } static SDL_bool yuv_rgb_std( Uint32 src_format, Uint32 dst_format, Uint32 width, Uint32 height, const Uint8 *y, const Uint8 *u, const Uint8 *v, Uint32 y_stride, Uint32 uv_stride, Uint8 *rgb, Uint32 rgb_stride, YCbCrType yuv_type) { if (src_format == SDL_PIXELFORMAT_YV12 || src_format == SDL_PIXELFORMAT_IYUV) { switch (dst_format) { case SDL_PIXELFORMAT_RGB565: yuv420_rgb565_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB24: yuv420_rgb24_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGBX8888: case SDL_PIXELFORMAT_RGBA8888: yuv420_rgba_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGRX8888: case SDL_PIXELFORMAT_BGRA8888: yuv420_bgra_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB888: case SDL_PIXELFORMAT_ARGB8888: yuv420_argb_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGR888: case SDL_PIXELFORMAT_ABGR8888: yuv420_abgr_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; default: break; } } if (src_format == SDL_PIXELFORMAT_YUY2 || src_format == SDL_PIXELFORMAT_UYVY || src_format == SDL_PIXELFORMAT_YVYU) { switch (dst_format) { case SDL_PIXELFORMAT_RGB565: yuv422_rgb565_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB24: yuv422_rgb24_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGBX8888: case SDL_PIXELFORMAT_RGBA8888: yuv422_rgba_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGRX8888: case SDL_PIXELFORMAT_BGRA8888: yuv422_bgra_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB888: case SDL_PIXELFORMAT_ARGB8888: yuv422_argb_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGR888: case SDL_PIXELFORMAT_ABGR8888: yuv422_abgr_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; default: break; } } if (src_format == SDL_PIXELFORMAT_NV12 || src_format == SDL_PIXELFORMAT_NV21) { switch (dst_format) { case SDL_PIXELFORMAT_RGB565: yuvnv12_rgb565_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB24: yuvnv12_rgb24_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGBX8888: case SDL_PIXELFORMAT_RGBA8888: yuvnv12_rgba_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGRX8888: case SDL_PIXELFORMAT_BGRA8888: yuvnv12_bgra_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_RGB888: case SDL_PIXELFORMAT_ARGB8888: yuvnv12_argb_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; case SDL_PIXELFORMAT_BGR888: case SDL_PIXELFORMAT_ABGR8888: yuvnv12_abgr_std(width, height, y, u, v, y_stride, uv_stride, rgb, rgb_stride, yuv_type); return SDL_TRUE; default: break; } } return SDL_FALSE; } int SDL_ConvertPixels_YUV_to_RGB(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { const Uint8 *y = NULL; const Uint8 *u = NULL; const Uint8 *v = NULL; Uint32 y_stride = 0; Uint32 uv_stride = 0; YCbCrType yuv_type = YCBCR_601; if (GetYUVPlanes(width, height, src_format, src, src_pitch, &y, &u, &v, &y_stride, &uv_stride) < 0) { return -1; } if (GetYUVConversionType(width, height, &yuv_type) < 0) { return -1; } if (yuv_rgb_sse(src_format, dst_format, width, height, y, u, v, y_stride, uv_stride, (Uint8*)dst, dst_pitch, yuv_type)) { return 0; } if (yuv_rgb_std(src_format, dst_format, width, height, y, u, v, y_stride, uv_stride, (Uint8*)dst, dst_pitch, yuv_type)) { return 0; } /* No fast path for the RGB format, instead convert using an intermediate buffer */ if (dst_format != SDL_PIXELFORMAT_ARGB8888) { int ret; void *tmp; int tmp_pitch = (width * sizeof(Uint32)); tmp = SDL_malloc(tmp_pitch * height); if (tmp == NULL) { return SDL_OutOfMemory(); } /* convert src/src_format to tmp/ARGB8888 */ ret = SDL_ConvertPixels_YUV_to_RGB(width, height, src_format, src, src_pitch, SDL_PIXELFORMAT_ARGB8888, tmp, tmp_pitch); if (ret < 0) { SDL_free(tmp); return ret; } /* convert tmp/ARGB8888 to dst/RGB */ ret = SDL_ConvertPixels(width, height, SDL_PIXELFORMAT_ARGB8888, tmp, tmp_pitch, dst_format, dst, dst_pitch); SDL_free(tmp); return ret; } return SDL_SetError("Unsupported YUV conversion"); } struct RGB2YUVFactors { int y_offset; float y[3]; /* Rfactor, Gfactor, Bfactor */ float u[3]; /* Rfactor, Gfactor, Bfactor */ float v[3]; /* Rfactor, Gfactor, Bfactor */ }; static int SDL_ConvertPixels_ARGB8888_to_YUV(int width, int height, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { const int src_pitch_x_2 = src_pitch * 2; const int height_half = height / 2; const int height_remainder = (height & 0x1); const int width_half = width / 2; const int width_remainder = (width & 0x1); int i, j; static struct RGB2YUVFactors RGB2YUVFactorTables[SDL_YUV_CONVERSION_BT709 + 1] = { /* ITU-T T.871 (JPEG) */ { 0, { 0.2990f, 0.5870f, 0.1140f }, { -0.1687f, -0.3313f, 0.5000f }, { 0.5000f, -0.4187f, -0.0813f }, }, /* ITU-R BT.601-7 */ { 16, { 0.2568f, 0.5041f, 0.0979f }, { -0.1482f, -0.2910f, 0.4392f }, { 0.4392f, -0.3678f, -0.0714f }, }, /* ITU-R BT.709-6 */ { 16, { 0.1826f, 0.6142f, 0.0620f }, {-0.1006f, -0.3386f, 0.4392f }, { 0.4392f, -0.3989f, -0.0403f }, }, }; const struct RGB2YUVFactors *cvt = &RGB2YUVFactorTables[SDL_GetYUVConversionModeForResolution(width, height)]; #define MAKE_Y(r, g, b) (Uint8)((int)(cvt->y[0] * (r) + cvt->y[1] * (g) + cvt->y[2] * (b) + 0.5f) + cvt->y_offset) #define MAKE_U(r, g, b) (Uint8)((int)(cvt->u[0] * (r) + cvt->u[1] * (g) + cvt->u[2] * (b) + 0.5f) + 128) #define MAKE_V(r, g, b) (Uint8)((int)(cvt->v[0] * (r) + cvt->v[1] * (g) + cvt->v[2] * (b) + 0.5f) + 128) #define READ_2x2_PIXELS \ const Uint32 p1 = ((const Uint32 *)curr_row)[2 * i]; \ const Uint32 p2 = ((const Uint32 *)curr_row)[2 * i + 1]; \ const Uint32 p3 = ((const Uint32 *)next_row)[2 * i]; \ const Uint32 p4 = ((const Uint32 *)next_row)[2 * i + 1]; \ const Uint32 r = ((p1 & 0x00ff0000) + (p2 & 0x00ff0000) + (p3 & 0x00ff0000) + (p4 & 0x00ff0000)) >> 18; \ const Uint32 g = ((p1 & 0x0000ff00) + (p2 & 0x0000ff00) + (p3 & 0x0000ff00) + (p4 & 0x0000ff00)) >> 10; \ const Uint32 b = ((p1 & 0x000000ff) + (p2 & 0x000000ff) + (p3 & 0x000000ff) + (p4 & 0x000000ff)) >> 2; \ #define READ_2x1_PIXELS \ const Uint32 p1 = ((const Uint32 *)curr_row)[2 * i]; \ const Uint32 p2 = ((const Uint32 *)next_row)[2 * i]; \ const Uint32 r = ((p1 & 0x00ff0000) + (p2 & 0x00ff0000)) >> 17; \ const Uint32 g = ((p1 & 0x0000ff00) + (p2 & 0x0000ff00)) >> 9; \ const Uint32 b = ((p1 & 0x000000ff) + (p2 & 0x000000ff)) >> 1; \ #define READ_1x2_PIXELS \ const Uint32 p1 = ((const Uint32 *)curr_row)[2 * i]; \ const Uint32 p2 = ((const Uint32 *)curr_row)[2 * i + 1]; \ const Uint32 r = ((p1 & 0x00ff0000) + (p2 & 0x00ff0000)) >> 17; \ const Uint32 g = ((p1 & 0x0000ff00) + (p2 & 0x0000ff00)) >> 9; \ const Uint32 b = ((p1 & 0x000000ff) + (p2 & 0x000000ff)) >> 1; \ #define READ_1x1_PIXEL \ const Uint32 p = ((const Uint32 *)curr_row)[2 * i]; \ const Uint32 r = (p & 0x00ff0000) >> 16; \ const Uint32 g = (p & 0x0000ff00) >> 8; \ const Uint32 b = (p & 0x000000ff); \ #define READ_TWO_RGB_PIXELS \ const Uint32 p = ((const Uint32 *)curr_row)[2 * i]; \ const Uint32 r = (p & 0x00ff0000) >> 16; \ const Uint32 g = (p & 0x0000ff00) >> 8; \ const Uint32 b = (p & 0x000000ff); \ const Uint32 p1 = ((const Uint32 *)curr_row)[2 * i + 1]; \ const Uint32 r1 = (p1 & 0x00ff0000) >> 16; \ const Uint32 g1 = (p1 & 0x0000ff00) >> 8; \ const Uint32 b1 = (p1 & 0x000000ff); \ const Uint32 R = (r + r1)/2; \ const Uint32 G = (g + g1)/2; \ const Uint32 B = (b + b1)/2; \ #define READ_ONE_RGB_PIXEL READ_1x1_PIXEL switch (dst_format) { case SDL_PIXELFORMAT_YV12: case SDL_PIXELFORMAT_IYUV: case SDL_PIXELFORMAT_NV12: case SDL_PIXELFORMAT_NV21: { const Uint8 *curr_row, *next_row; Uint8 *plane_y; Uint8 *plane_u; Uint8 *plane_v; Uint8 *plane_interleaved_uv; Uint32 y_stride, uv_stride, y_skip, uv_skip; GetYUVPlanes(width, height, dst_format, dst, dst_pitch, (const Uint8 **)&plane_y, (const Uint8 **)&plane_u, (const Uint8 **)&plane_v, &y_stride, &uv_stride); plane_interleaved_uv = (plane_y + height * y_stride); y_skip = (y_stride - width); curr_row = (const Uint8*)src; /* Write Y plane */ for (j = 0; j < height; j++) { for (i = 0; i < width; i++) { const Uint32 p1 = ((const Uint32 *)curr_row)[i]; const Uint32 r = (p1 & 0x00ff0000) >> 16; const Uint32 g = (p1 & 0x0000ff00) >> 8; const Uint32 b = (p1 & 0x000000ff); *plane_y++ = MAKE_Y(r, g, b); } plane_y += y_skip; curr_row += src_pitch; } curr_row = (const Uint8*)src; next_row = (const Uint8*)src; next_row += src_pitch; if (dst_format == SDL_PIXELFORMAT_YV12 || dst_format == SDL_PIXELFORMAT_IYUV) { /* Write UV planes, not interleaved */ uv_skip = (uv_stride - (width + 1)/2); for (j = 0; j < height_half; j++) { for (i = 0; i < width_half; i++) { READ_2x2_PIXELS; *plane_u++ = MAKE_U(r, g, b); *plane_v++ = MAKE_V(r, g, b); } if (width_remainder) { READ_2x1_PIXELS; *plane_u++ = MAKE_U(r, g, b); *plane_v++ = MAKE_V(r, g, b); } plane_u += uv_skip; plane_v += uv_skip; curr_row += src_pitch_x_2; next_row += src_pitch_x_2; } if (height_remainder) { for (i = 0; i < width_half; i++) { READ_1x2_PIXELS; *plane_u++ = MAKE_U(r, g, b); *plane_v++ = MAKE_V(r, g, b); } if (width_remainder) { READ_1x1_PIXEL; *plane_u++ = MAKE_U(r, g, b); *plane_v++ = MAKE_V(r, g, b); } plane_u += uv_skip; plane_v += uv_skip; } } else if (dst_format == SDL_PIXELFORMAT_NV12) { uv_skip = (uv_stride - ((width + 1)/2)*2); for (j = 0; j < height_half; j++) { for (i = 0; i < width_half; i++) { READ_2x2_PIXELS; *plane_interleaved_uv++ = MAKE_U(r, g, b); *plane_interleaved_uv++ = MAKE_V(r, g, b); } if (width_remainder) { READ_2x1_PIXELS; *plane_interleaved_uv++ = MAKE_U(r, g, b); *plane_interleaved_uv++ = MAKE_V(r, g, b); } plane_interleaved_uv += uv_skip; curr_row += src_pitch_x_2; next_row += src_pitch_x_2; } if (height_remainder) { for (i = 0; i < width_half; i++) { READ_1x2_PIXELS; *plane_interleaved_uv++ = MAKE_U(r, g, b); *plane_interleaved_uv++ = MAKE_V(r, g, b); } if (width_remainder) { READ_1x1_PIXEL; *plane_interleaved_uv++ = MAKE_U(r, g, b); *plane_interleaved_uv++ = MAKE_V(r, g, b); } } } else /* dst_format == SDL_PIXELFORMAT_NV21 */ { uv_skip = (uv_stride - ((width + 1)/2)*2); for (j = 0; j < height_half; j++) { for (i = 0; i < width_half; i++) { READ_2x2_PIXELS; *plane_interleaved_uv++ = MAKE_V(r, g, b); *plane_interleaved_uv++ = MAKE_U(r, g, b); } if (width_remainder) { READ_2x1_PIXELS; *plane_interleaved_uv++ = MAKE_V(r, g, b); *plane_interleaved_uv++ = MAKE_U(r, g, b); } plane_interleaved_uv += uv_skip; curr_row += src_pitch_x_2; next_row += src_pitch_x_2; } if (height_remainder) { for (i = 0; i < width_half; i++) { READ_1x2_PIXELS; *plane_interleaved_uv++ = MAKE_V(r, g, b); *plane_interleaved_uv++ = MAKE_U(r, g, b); } if (width_remainder) { READ_1x1_PIXEL; *plane_interleaved_uv++ = MAKE_V(r, g, b); *plane_interleaved_uv++ = MAKE_U(r, g, b); } } } } break; case SDL_PIXELFORMAT_YUY2: case SDL_PIXELFORMAT_UYVY: case SDL_PIXELFORMAT_YVYU: { const Uint8 *curr_row = (const Uint8*) src; Uint8 *plane = (Uint8*) dst; const int row_size = (4 * ((width + 1) / 2)); int plane_skip; if (dst_pitch < row_size) { return SDL_SetError("Destination pitch is too small, expected at least %d\n", row_size); } plane_skip = (dst_pitch - row_size); /* Write YUV plane, packed */ if (dst_format == SDL_PIXELFORMAT_YUY2) { for (j = 0; j < height; j++) { for (i = 0; i < width_half; i++) { READ_TWO_RGB_PIXELS; /* Y U Y1 V */ *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_U(R, G, B); *plane++ = MAKE_Y(r1, g1, b1); *plane++ = MAKE_V(R, G, B); } if (width_remainder) { READ_ONE_RGB_PIXEL; /* Y U Y V */ *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_U(r, g, b); *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_V(r, g, b); } plane += plane_skip; curr_row += src_pitch; } } else if (dst_format == SDL_PIXELFORMAT_UYVY) { for (j = 0; j < height; j++) { for (i = 0; i < width_half; i++) { READ_TWO_RGB_PIXELS; /* U Y V Y1 */ *plane++ = MAKE_U(R, G, B); *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_V(R, G, B); *plane++ = MAKE_Y(r1, g1, b1); } if (width_remainder) { READ_ONE_RGB_PIXEL; /* U Y V Y */ *plane++ = MAKE_U(r, g, b); *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_V(r, g, b); *plane++ = MAKE_Y(r, g, b); } plane += plane_skip; curr_row += src_pitch; } } else if (dst_format == SDL_PIXELFORMAT_YVYU) { for (j = 0; j < height; j++) { for (i = 0; i < width_half; i++) { READ_TWO_RGB_PIXELS; /* Y V Y1 U */ *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_V(R, G, B); *plane++ = MAKE_Y(r1, g1, b1); *plane++ = MAKE_U(R, G, B); } if (width_remainder) { READ_ONE_RGB_PIXEL; /* Y V Y U */ *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_V(r, g, b); *plane++ = MAKE_Y(r, g, b); *plane++ = MAKE_U(r, g, b); } plane += plane_skip; curr_row += src_pitch; } } } break; default: return SDL_SetError("Unsupported YUV destination format: %s", SDL_GetPixelFormatName(dst_format)); } #undef MAKE_Y #undef MAKE_U #undef MAKE_V #undef READ_2x2_PIXELS #undef READ_2x1_PIXELS #undef READ_1x2_PIXELS #undef READ_1x1_PIXEL #undef READ_TWO_RGB_PIXELS #undef READ_ONE_RGB_PIXEL return 0; } int SDL_ConvertPixels_RGB_to_YUV(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { #if 0 /* Doesn't handle odd widths */ /* RGB24 to FOURCC */ if (src_format == SDL_PIXELFORMAT_RGB24) { Uint8 *y; Uint8 *u; Uint8 *v; Uint32 y_stride; Uint32 uv_stride; YCbCrType yuv_type; if (GetYUVPlanes(width, height, dst_format, dst, dst_pitch, (const Uint8 **)&y, (const Uint8 **)&u, (const Uint8 **)&v, &y_stride, &uv_stride) < 0) { return -1; } if (GetYUVConversionType(width, height, &yuv_type) < 0) { return -1; } rgb24_yuv420_std(width, height, src, src_pitch, y, u, v, y_stride, uv_stride, yuv_type); return 0; } #endif /* ARGB8888 to FOURCC */ if (src_format == SDL_PIXELFORMAT_ARGB8888) { return SDL_ConvertPixels_ARGB8888_to_YUV(width, height, src, src_pitch, dst_format, dst, dst_pitch); } /* not ARGB8888 to FOURCC : need an intermediate conversion */ { int ret; void *tmp; int tmp_pitch = (width * sizeof(Uint32)); tmp = SDL_malloc(tmp_pitch * height); if (tmp == NULL) { return SDL_OutOfMemory(); } /* convert src/src_format to tmp/ARGB8888 */ ret = SDL_ConvertPixels(width, height, src_format, src, src_pitch, SDL_PIXELFORMAT_ARGB8888, tmp, tmp_pitch); if (ret == -1) { SDL_free(tmp); return ret; } /* convert tmp/ARGB8888 to dst/FOURCC */ ret = SDL_ConvertPixels_ARGB8888_to_YUV(width, height, tmp, tmp_pitch, dst_format, dst, dst_pitch); SDL_free(tmp); return ret; } } static int SDL_ConvertPixels_YUV_to_YUV_Copy(int width, int height, Uint32 format, const void *src, int src_pitch, void *dst, int dst_pitch) { int i; if (IsPlanar2x2Format(format)) { /* Y plane */ for (i = height; i--;) { SDL_memcpy(dst, src, width); src = (const Uint8*)src + src_pitch; dst = (Uint8*)dst + dst_pitch; } if (format == SDL_PIXELFORMAT_YV12 || format == SDL_PIXELFORMAT_IYUV) { /* U and V planes are a quarter the size of the Y plane, rounded up */ width = (width + 1) / 2; height = (height + 1) / 2; src_pitch = (src_pitch + 1) / 2; dst_pitch = (dst_pitch + 1) / 2; for (i = height * 2; i--;) { SDL_memcpy(dst, src, width); src = (const Uint8*)src + src_pitch; dst = (Uint8*)dst + dst_pitch; } } else if (format == SDL_PIXELFORMAT_NV12 || format == SDL_PIXELFORMAT_NV21) { /* U/V plane is half the height of the Y plane, rounded up */ height = (height + 1) / 2; width = ((width + 1) / 2)*2; src_pitch = ((src_pitch + 1) / 2)*2; dst_pitch = ((dst_pitch + 1) / 2)*2; for (i = height; i--;) { SDL_memcpy(dst, src, width); src = (const Uint8*)src + src_pitch; dst = (Uint8*)dst + dst_pitch; } } return 0; } if (IsPacked4Format(format)) { /* Packed planes */ width = 4 * ((width + 1) / 2); for (i = height; i--;) { SDL_memcpy(dst, src, width); src = (const Uint8*)src + src_pitch; dst = (Uint8*)dst + dst_pitch; } return 0; } return SDL_SetError("SDL_ConvertPixels_YUV_to_YUV_Copy: Unsupported YUV format: %s", SDL_GetPixelFormatName(format)); } static int SDL_ConvertPixels_SwapUVPlanes(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int y; const int UVwidth = (width + 1)/2; const int UVheight = (height + 1)/2; /* Skip the Y plane */ src = (const Uint8 *)src + height * src_pitch; dst = (Uint8 *)dst + height * dst_pitch; if (src == dst) { int UVpitch = (dst_pitch + 1)/2; Uint8 *tmp; Uint8 *row1 = dst; Uint8 *row2 = (Uint8 *)dst + UVheight * UVpitch; /* Allocate a temporary row for the swap */ tmp = (Uint8 *)SDL_malloc(UVwidth); if (!tmp) { return SDL_OutOfMemory(); } for (y = 0; y < UVheight; ++y) { SDL_memcpy(tmp, row1, UVwidth); SDL_memcpy(row1, row2, UVwidth); SDL_memcpy(row2, tmp, UVwidth); row1 += UVpitch; row2 += UVpitch; } SDL_free(tmp); } else { const Uint8 *srcUV; Uint8 *dstUV; int srcUVPitch = ((src_pitch + 1)/2); int dstUVPitch = ((dst_pitch + 1)/2); /* Copy the first plane */ srcUV = (const Uint8 *)src; dstUV = (Uint8 *)dst + UVheight * dstUVPitch; for (y = 0; y < UVheight; ++y) { SDL_memcpy(dstUV, srcUV, UVwidth); srcUV += srcUVPitch; dstUV += dstUVPitch; } /* Copy the second plane */ dstUV = (Uint8 *)dst; for (y = 0; y < UVheight; ++y) { SDL_memcpy(dstUV, srcUV, UVwidth); srcUV += srcUVPitch; dstUV += dstUVPitch; } } return 0; } static int SDL_ConvertPixels_PackUVPlanes_to_NV(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch, SDL_bool reverseUV) { int x, y; const int UVwidth = (width + 1)/2; const int UVheight = (height + 1)/2; const int srcUVPitch = ((src_pitch + 1)/2); const int srcUVPitchLeft = srcUVPitch - UVwidth; const int dstUVPitch = ((dst_pitch + 1)/2)*2; const int dstUVPitchLeft = dstUVPitch - UVwidth*2; const Uint8 *src1, *src2; Uint8 *dstUV; Uint8 *tmp = NULL; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif /* Skip the Y plane */ src = (const Uint8 *)src + height * src_pitch; dst = (Uint8 *)dst + height * dst_pitch; if (src == dst) { /* Need to make a copy of the buffer so we don't clobber it while converting */ tmp = (Uint8 *)SDL_malloc(2*UVheight*srcUVPitch); if (!tmp) { return SDL_OutOfMemory(); } SDL_memcpy(tmp, src, 2*UVheight*srcUVPitch); src = tmp; } if (reverseUV) { src2 = (const Uint8 *)src; src1 = src2 + UVheight * srcUVPitch; } else { src1 = (const Uint8 *)src; src2 = src1 + UVheight * srcUVPitch; } dstUV = (Uint8 *)dst; y = UVheight; while (y--) { x = UVwidth; #ifdef __SSE2__ if (use_SSE2) { while (x >= 16) { __m128i u = _mm_loadu_si128((__m128i *)src1); __m128i v = _mm_loadu_si128((__m128i *)src2); __m128i uv1 = _mm_unpacklo_epi8(u, v); __m128i uv2 = _mm_unpackhi_epi8(u, v); _mm_storeu_si128((__m128i*)dstUV, uv1); _mm_storeu_si128((__m128i*)(dstUV + 16), uv2); src1 += 16; src2 += 16; dstUV += 32; x -= 16; } } #endif while (x--) { *dstUV++ = *src1++; *dstUV++ = *src2++; } src1 += srcUVPitchLeft; src2 += srcUVPitchLeft; dstUV += dstUVPitchLeft; } if (tmp) { SDL_free(tmp); } return 0; } static int SDL_ConvertPixels_SplitNV_to_UVPlanes(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch, SDL_bool reverseUV) { int x, y; const int UVwidth = (width + 1)/2; const int UVheight = (height + 1)/2; const int srcUVPitch = ((src_pitch + 1)/2)*2; const int srcUVPitchLeft = srcUVPitch - UVwidth*2; const int dstUVPitch = ((dst_pitch + 1)/2); const int dstUVPitchLeft = dstUVPitch - UVwidth; const Uint8 *srcUV; Uint8 *dst1, *dst2; Uint8 *tmp = NULL; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif /* Skip the Y plane */ src = (const Uint8 *)src + height * src_pitch; dst = (Uint8 *)dst + height * dst_pitch; if (src == dst) { /* Need to make a copy of the buffer so we don't clobber it while converting */ tmp = (Uint8 *)SDL_malloc(UVheight*srcUVPitch); if (!tmp) { return SDL_OutOfMemory(); } SDL_memcpy(tmp, src, UVheight*srcUVPitch); src = tmp; } if (reverseUV) { dst2 = (Uint8 *)dst; dst1 = dst2 + UVheight * dstUVPitch; } else { dst1 = (Uint8 *)dst; dst2 = dst1 + UVheight * dstUVPitch; } srcUV = (const Uint8 *)src; y = UVheight; while (y--) { x = UVwidth; #ifdef __SSE2__ if (use_SSE2) { __m128i mask = _mm_set1_epi16(0x00FF); while (x >= 16) { __m128i uv1 = _mm_loadu_si128((__m128i*)srcUV); __m128i uv2 = _mm_loadu_si128((__m128i*)(srcUV+16)); __m128i u1 = _mm_and_si128(uv1, mask); __m128i u2 = _mm_and_si128(uv2, mask); __m128i u = _mm_packus_epi16(u1, u2); __m128i v1 = _mm_srli_epi16(uv1, 8); __m128i v2 = _mm_srli_epi16(uv2, 8); __m128i v = _mm_packus_epi16(v1, v2); _mm_storeu_si128((__m128i*)dst1, u); _mm_storeu_si128((__m128i*)dst2, v); srcUV += 32; dst1 += 16; dst2 += 16; x -= 16; } } #endif while (x--) { *dst1++ = *srcUV++; *dst2++ = *srcUV++; } srcUV += srcUVPitchLeft; dst1 += dstUVPitchLeft; dst2 += dstUVPitchLeft; } if (tmp) { SDL_free(tmp); } return 0; } static int SDL_ConvertPixels_SwapNV(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int x, y; const int UVwidth = (width + 1)/2; const int UVheight = (height + 1)/2; const int srcUVPitch = ((src_pitch + 1)/2)*2; const int srcUVPitchLeft = (srcUVPitch - UVwidth*2)/sizeof(Uint16); const int dstUVPitch = ((dst_pitch + 1)/2)*2; const int dstUVPitchLeft = (dstUVPitch - UVwidth*2)/sizeof(Uint16); const Uint16 *srcUV; Uint16 *dstUV; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif /* Skip the Y plane */ src = (const Uint8 *)src + height * src_pitch; dst = (Uint8 *)dst + height * dst_pitch; srcUV = (const Uint16 *)src; dstUV = (Uint16 *)dst; y = UVheight; while (y--) { x = UVwidth; #ifdef __SSE2__ if (use_SSE2) { while (x >= 8) { __m128i uv = _mm_loadu_si128((__m128i*)srcUV); __m128i v = _mm_slli_epi16(uv, 8); __m128i u = _mm_srli_epi16(uv, 8); __m128i vu = _mm_or_si128(v, u); _mm_storeu_si128((__m128i*)dstUV, vu); srcUV += 8; dstUV += 8; x -= 8; } } #endif while (x--) { *dstUV++ = SDL_Swap16(*srcUV++); } srcUV += srcUVPitchLeft; dstUV += dstUVPitchLeft; } return 0; } static int SDL_ConvertPixels_Planar2x2_to_Planar2x2(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { if (src != dst) { /* Copy Y plane */ int i; const Uint8 *srcY = (const Uint8 *)src; Uint8 *dstY = (Uint8 *)dst; for (i = height; i--; ) { SDL_memcpy(dstY, srcY, width); srcY += src_pitch; dstY += dst_pitch; } } switch (src_format) { case SDL_PIXELFORMAT_YV12: switch (dst_format) { case SDL_PIXELFORMAT_IYUV: return SDL_ConvertPixels_SwapUVPlanes(width, height, src, src_pitch, dst, dst_pitch); case SDL_PIXELFORMAT_NV12: return SDL_ConvertPixels_PackUVPlanes_to_NV(width, height, src, src_pitch, dst, dst_pitch, SDL_TRUE); case SDL_PIXELFORMAT_NV21: return SDL_ConvertPixels_PackUVPlanes_to_NV(width, height, src, src_pitch, dst, dst_pitch, SDL_FALSE); default: break; } break; case SDL_PIXELFORMAT_IYUV: switch (dst_format) { case SDL_PIXELFORMAT_YV12: return SDL_ConvertPixels_SwapUVPlanes(width, height, src, src_pitch, dst, dst_pitch); case SDL_PIXELFORMAT_NV12: return SDL_ConvertPixels_PackUVPlanes_to_NV(width, height, src, src_pitch, dst, dst_pitch, SDL_FALSE); case SDL_PIXELFORMAT_NV21: return SDL_ConvertPixels_PackUVPlanes_to_NV(width, height, src, src_pitch, dst, dst_pitch, SDL_TRUE); default: break; } break; case SDL_PIXELFORMAT_NV12: switch (dst_format) { case SDL_PIXELFORMAT_YV12: return SDL_ConvertPixels_SplitNV_to_UVPlanes(width, height, src, src_pitch, dst, dst_pitch, SDL_TRUE); case SDL_PIXELFORMAT_IYUV: return SDL_ConvertPixels_SplitNV_to_UVPlanes(width, height, src, src_pitch, dst, dst_pitch, SDL_FALSE); case SDL_PIXELFORMAT_NV21: return SDL_ConvertPixels_SwapNV(width, height, src, src_pitch, dst, dst_pitch); default: break; } break; case SDL_PIXELFORMAT_NV21: switch (dst_format) { case SDL_PIXELFORMAT_YV12: return SDL_ConvertPixels_SplitNV_to_UVPlanes(width, height, src, src_pitch, dst, dst_pitch, SDL_FALSE); case SDL_PIXELFORMAT_IYUV: return SDL_ConvertPixels_SplitNV_to_UVPlanes(width, height, src, src_pitch, dst, dst_pitch, SDL_TRUE); case SDL_PIXELFORMAT_NV12: return SDL_ConvertPixels_SwapNV(width, height, src, src_pitch, dst, dst_pitch); default: break; } break; default: break; } return SDL_SetError("SDL_ConvertPixels_Planar2x2_to_Planar2x2: Unsupported YUV conversion: %s -> %s", SDL_GetPixelFormatName(src_format), SDL_GetPixelFormatName(dst_format)); } #ifdef __SSE2__ #define PACKED4_TO_PACKED4_ROW_SSE2(shuffle) \ while (x >= 4) { \ __m128i yuv = _mm_loadu_si128((__m128i*)srcYUV); \ __m128i lo = _mm_unpacklo_epi8(yuv, _mm_setzero_si128()); \ __m128i hi = _mm_unpackhi_epi8(yuv, _mm_setzero_si128()); \ lo = _mm_shufflelo_epi16(lo, shuffle); \ lo = _mm_shufflehi_epi16(lo, shuffle); \ hi = _mm_shufflelo_epi16(hi, shuffle); \ hi = _mm_shufflehi_epi16(hi, shuffle); \ yuv = _mm_packus_epi16(lo, hi); \ _mm_storeu_si128((__m128i*)dstYUV, yuv); \ srcYUV += 16; \ dstYUV += 16; \ x -= 4; \ } \ #endif static int SDL_ConvertPixels_YUY2_to_UYVY(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int x, y; const int YUVwidth = (width + 1)/2; const int srcYUVPitchLeft = (src_pitch - YUVwidth*4); const int dstYUVPitchLeft = (dst_pitch - YUVwidth*4); const Uint8 *srcYUV = (const Uint8 *)src; Uint8 *dstYUV = (Uint8 *)dst; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif y = height; while (y--) { x = YUVwidth; #ifdef __SSE2__ if (use_SSE2) { PACKED4_TO_PACKED4_ROW_SSE2(_MM_SHUFFLE(2, 3, 0, 1)); } #endif while (x--) { Uint8 Y1, U, Y2, V; Y1 = srcYUV[0]; U = srcYUV[1]; Y2 = srcYUV[2]; V = srcYUV[3]; srcYUV += 4; dstYUV[0] = U; dstYUV[1] = Y1; dstYUV[2] = V; dstYUV[3] = Y2; dstYUV += 4; } srcYUV += srcYUVPitchLeft; dstYUV += dstYUVPitchLeft; } return 0; } static int SDL_ConvertPixels_YUY2_to_YVYU(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int x, y; const int YUVwidth = (width + 1)/2; const int srcYUVPitchLeft = (src_pitch - YUVwidth*4); const int dstYUVPitchLeft = (dst_pitch - YUVwidth*4); const Uint8 *srcYUV = (const Uint8 *)src; Uint8 *dstYUV = (Uint8 *)dst; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif y = height; while (y--) { x = YUVwidth; #ifdef __SSE2__ if (use_SSE2) { PACKED4_TO_PACKED4_ROW_SSE2(_MM_SHUFFLE(1, 2, 3, 0)); } #endif while (x--) { Uint8 Y1, U, Y2, V; Y1 = srcYUV[0]; U = srcYUV[1]; Y2 = srcYUV[2]; V = srcYUV[3]; srcYUV += 4; dstYUV[0] = Y1; dstYUV[1] = V; dstYUV[2] = Y2; dstYUV[3] = U; dstYUV += 4; } srcYUV += srcYUVPitchLeft; dstYUV += dstYUVPitchLeft; } return 0; } static int SDL_ConvertPixels_UYVY_to_YUY2(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int x, y; const int YUVwidth = (width + 1)/2; const int srcYUVPitchLeft = (src_pitch - YUVwidth*4); const int dstYUVPitchLeft = (dst_pitch - YUVwidth*4); const Uint8 *srcYUV = (const Uint8 *)src; Uint8 *dstYUV = (Uint8 *)dst; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif y = height; while (y--) { x = YUVwidth; #ifdef __SSE2__ if (use_SSE2) { PACKED4_TO_PACKED4_ROW_SSE2(_MM_SHUFFLE(2, 3, 0, 1)); } #endif while (x--) { Uint8 Y1, U, Y2, V; U = srcYUV[0]; Y1 = srcYUV[1]; V = srcYUV[2]; Y2 = srcYUV[3]; srcYUV += 4; dstYUV[0] = Y1; dstYUV[1] = U; dstYUV[2] = Y2; dstYUV[3] = V; dstYUV += 4; } srcYUV += srcYUVPitchLeft; dstYUV += dstYUVPitchLeft; } return 0; } static int SDL_ConvertPixels_UYVY_to_YVYU(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int x, y; const int YUVwidth = (width + 1)/2; const int srcYUVPitchLeft = (src_pitch - YUVwidth*4); const int dstYUVPitchLeft = (dst_pitch - YUVwidth*4); const Uint8 *srcYUV = (const Uint8 *)src; Uint8 *dstYUV = (Uint8 *)dst; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif y = height; while (y--) { x = YUVwidth; #ifdef __SSE2__ if (use_SSE2) { PACKED4_TO_PACKED4_ROW_SSE2(_MM_SHUFFLE(0, 3, 2, 1)); } #endif while (x--) { Uint8 Y1, U, Y2, V; U = srcYUV[0]; Y1 = srcYUV[1]; V = srcYUV[2]; Y2 = srcYUV[3]; srcYUV += 4; dstYUV[0] = Y1; dstYUV[1] = V; dstYUV[2] = Y2; dstYUV[3] = U; dstYUV += 4; } srcYUV += srcYUVPitchLeft; dstYUV += dstYUVPitchLeft; } return 0; } static int SDL_ConvertPixels_YVYU_to_YUY2(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int x, y; const int YUVwidth = (width + 1)/2; const int srcYUVPitchLeft = (src_pitch - YUVwidth*4); const int dstYUVPitchLeft = (dst_pitch - YUVwidth*4); const Uint8 *srcYUV = (const Uint8 *)src; Uint8 *dstYUV = (Uint8 *)dst; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif y = height; while (y--) { x = YUVwidth; #ifdef __SSE2__ if (use_SSE2) { PACKED4_TO_PACKED4_ROW_SSE2(_MM_SHUFFLE(1, 2, 3, 0)); } #endif while (x--) { Uint8 Y1, U, Y2, V; Y1 = srcYUV[0]; V = srcYUV[1]; Y2 = srcYUV[2]; U = srcYUV[3]; srcYUV += 4; dstYUV[0] = Y1; dstYUV[1] = U; dstYUV[2] = Y2; dstYUV[3] = V; dstYUV += 4; } srcYUV += srcYUVPitchLeft; dstYUV += dstYUVPitchLeft; } return 0; } static int SDL_ConvertPixels_YVYU_to_UYVY(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch) { int x, y; const int YUVwidth = (width + 1)/2; const int srcYUVPitchLeft = (src_pitch - YUVwidth*4); const int dstYUVPitchLeft = (dst_pitch - YUVwidth*4); const Uint8 *srcYUV = (const Uint8 *)src; Uint8 *dstYUV = (Uint8 *)dst; #ifdef __SSE2__ const SDL_bool use_SSE2 = SDL_HasSSE2(); #endif y = height; while (y--) { x = YUVwidth; #ifdef __SSE2__ if (use_SSE2) { PACKED4_TO_PACKED4_ROW_SSE2(_MM_SHUFFLE(2, 1, 0, 3)); } #endif while (x--) { Uint8 Y1, U, Y2, V; Y1 = srcYUV[0]; V = srcYUV[1]; Y2 = srcYUV[2]; U = srcYUV[3]; srcYUV += 4; dstYUV[0] = U; dstYUV[1] = Y1; dstYUV[2] = V; dstYUV[3] = Y2; dstYUV += 4; } srcYUV += srcYUVPitchLeft; dstYUV += dstYUVPitchLeft; } return 0; } static int SDL_ConvertPixels_Packed4_to_Packed4(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { switch (src_format) { case SDL_PIXELFORMAT_YUY2: switch (dst_format) { case SDL_PIXELFORMAT_UYVY: return SDL_ConvertPixels_YUY2_to_UYVY(width, height, src, src_pitch, dst, dst_pitch); case SDL_PIXELFORMAT_YVYU: return SDL_ConvertPixels_YUY2_to_YVYU(width, height, src, src_pitch, dst, dst_pitch); default: break; } break; case SDL_PIXELFORMAT_UYVY: switch (dst_format) { case SDL_PIXELFORMAT_YUY2: return SDL_ConvertPixels_UYVY_to_YUY2(width, height, src, src_pitch, dst, dst_pitch); case SDL_PIXELFORMAT_YVYU: return SDL_ConvertPixels_UYVY_to_YVYU(width, height, src, src_pitch, dst, dst_pitch); default: break; } break; case SDL_PIXELFORMAT_YVYU: switch (dst_format) { case SDL_PIXELFORMAT_YUY2: return SDL_ConvertPixels_YVYU_to_YUY2(width, height, src, src_pitch, dst, dst_pitch); case SDL_PIXELFORMAT_UYVY: return SDL_ConvertPixels_YVYU_to_UYVY(width, height, src, src_pitch, dst, dst_pitch); default: break; } break; default: break; } return SDL_SetError("SDL_ConvertPixels_Packed4_to_Packed4: Unsupported YUV conversion: %s -> %s", SDL_GetPixelFormatName(src_format), SDL_GetPixelFormatName(dst_format)); } static int SDL_ConvertPixels_Planar2x2_to_Packed4(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { int x, y; const Uint8 *srcY1, *srcY2, *srcU, *srcV; Uint32 srcY_pitch, srcUV_pitch; Uint32 srcY_pitch_left, srcUV_pitch_left, srcUV_pixel_stride; Uint8 *dstY1, *dstY2, *dstU1, *dstU2, *dstV1, *dstV2; Uint32 dstY_pitch, dstUV_pitch; Uint32 dst_pitch_left; if (src == dst) { return SDL_SetError("Can't change YUV plane types in-place"); } if (GetYUVPlanes(width, height, src_format, src, src_pitch, &srcY1, &srcU, &srcV, &srcY_pitch, &srcUV_pitch) < 0) { return -1; } srcY2 = srcY1 + srcY_pitch; srcY_pitch_left = (srcY_pitch - width); if (src_format == SDL_PIXELFORMAT_NV12 || src_format == SDL_PIXELFORMAT_NV21) { srcUV_pixel_stride = 2; srcUV_pitch_left = (srcUV_pitch - 2*((width + 1)/2)); } else { srcUV_pixel_stride = 1; srcUV_pitch_left = (srcUV_pitch - ((width + 1)/2)); } if (GetYUVPlanes(width, height, dst_format, dst, dst_pitch, (const Uint8 **)&dstY1, (const Uint8 **)&dstU1, (const Uint8 **)&dstV1, &dstY_pitch, &dstUV_pitch) < 0) { return -1; } dstY2 = dstY1 + dstY_pitch; dstU2 = dstU1 + dstUV_pitch; dstV2 = dstV1 + dstUV_pitch; dst_pitch_left = (dstY_pitch - 4*((width + 1)/2)); /* Copy 2x2 blocks of pixels at a time */ for (y = 0; y < (height - 1); y += 2) { for (x = 0; x < (width - 1); x += 2) { /* Row 1 */ *dstY1 = *srcY1++; dstY1 += 2; *dstY1 = *srcY1++; dstY1 += 2; *dstU1 = *srcU; *dstV1 = *srcV; /* Row 2 */ *dstY2 = *srcY2++; dstY2 += 2; *dstY2 = *srcY2++; dstY2 += 2; *dstU2 = *srcU; *dstV2 = *srcV; srcU += srcUV_pixel_stride; srcV += srcUV_pixel_stride; dstU1 += 4; dstU2 += 4; dstV1 += 4; dstV2 += 4; } /* Last column */ if (x == (width - 1)) { /* Row 1 */ *dstY1 = *srcY1; dstY1 += 2; *dstY1 = *srcY1++; dstY1 += 2; *dstU1 = *srcU; *dstV1 = *srcV; /* Row 2 */ *dstY2 = *srcY2; dstY2 += 2; *dstY2 = *srcY2++; dstY2 += 2; *dstU2 = *srcU; *dstV2 = *srcV; srcU += srcUV_pixel_stride; srcV += srcUV_pixel_stride; dstU1 += 4; dstU2 += 4; dstV1 += 4; dstV2 += 4; } srcY1 += srcY_pitch_left + srcY_pitch; srcY2 += srcY_pitch_left + srcY_pitch; srcU += srcUV_pitch_left; srcV += srcUV_pitch_left; dstY1 += dst_pitch_left + dstY_pitch; dstY2 += dst_pitch_left + dstY_pitch; dstU1 += dst_pitch_left + dstUV_pitch; dstU2 += dst_pitch_left + dstUV_pitch; dstV1 += dst_pitch_left + dstUV_pitch; dstV2 += dst_pitch_left + dstUV_pitch; } /* Last row */ if (y == (height - 1)) { for (x = 0; x < (width - 1); x += 2) { /* Row 1 */ *dstY1 = *srcY1++; dstY1 += 2; *dstY1 = *srcY1++; dstY1 += 2; *dstU1 = *srcU; *dstV1 = *srcV; srcU += srcUV_pixel_stride; srcV += srcUV_pixel_stride; dstU1 += 4; dstV1 += 4; } /* Last column */ if (x == (width - 1)) { /* Row 1 */ *dstY1 = *srcY1; dstY1 += 2; *dstY1 = *srcY1++; dstY1 += 2; *dstU1 = *srcU; *dstV1 = *srcV; srcU += srcUV_pixel_stride; srcV += srcUV_pixel_stride; dstU1 += 4; dstV1 += 4; } } return 0; } static int SDL_ConvertPixels_Packed4_to_Planar2x2(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { int x, y; const Uint8 *srcY1, *srcY2, *srcU1, *srcU2, *srcV1, *srcV2; Uint32 srcY_pitch, srcUV_pitch; Uint32 src_pitch_left; Uint8 *dstY1, *dstY2, *dstU, *dstV; Uint32 dstY_pitch, dstUV_pitch; Uint32 dstY_pitch_left, dstUV_pitch_left, dstUV_pixel_stride; if (src == dst) { return SDL_SetError("Can't change YUV plane types in-place"); } if (GetYUVPlanes(width, height, src_format, src, src_pitch, &srcY1, &srcU1, &srcV1, &srcY_pitch, &srcUV_pitch) < 0) { return -1; } srcY2 = srcY1 + srcY_pitch; srcU2 = srcU1 + srcUV_pitch; srcV2 = srcV1 + srcUV_pitch; src_pitch_left = (srcY_pitch - 4*((width + 1)/2)); if (GetYUVPlanes(width, height, dst_format, dst, dst_pitch, (const Uint8 **)&dstY1, (const Uint8 **)&dstU, (const Uint8 **)&dstV, &dstY_pitch, &dstUV_pitch) < 0) { return -1; } dstY2 = dstY1 + dstY_pitch; dstY_pitch_left = (dstY_pitch - width); if (dst_format == SDL_PIXELFORMAT_NV12 || dst_format == SDL_PIXELFORMAT_NV21) { dstUV_pixel_stride = 2; dstUV_pitch_left = (dstUV_pitch - 2*((width + 1)/2)); } else { dstUV_pixel_stride = 1; dstUV_pitch_left = (dstUV_pitch - ((width + 1)/2)); } /* Copy 2x2 blocks of pixels at a time */ for (y = 0; y < (height - 1); y += 2) { for (x = 0; x < (width - 1); x += 2) { /* Row 1 */ *dstY1++ = *srcY1; srcY1 += 2; *dstY1++ = *srcY1; srcY1 += 2; /* Row 2 */ *dstY2++ = *srcY2; srcY2 += 2; *dstY2++ = *srcY2; srcY2 += 2; *dstU = (Uint8)(((Uint32)*srcU1 + *srcU2)/2); *dstV = (Uint8)(((Uint32)*srcV1 + *srcV2)/2); srcU1 += 4; srcU2 += 4; srcV1 += 4; srcV2 += 4; dstU += dstUV_pixel_stride; dstV += dstUV_pixel_stride; } /* Last column */ if (x == (width - 1)) { /* Row 1 */ *dstY1 = *srcY1; srcY1 += 2; *dstY1++ = *srcY1; srcY1 += 2; /* Row 2 */ *dstY2 = *srcY2; srcY2 += 2; *dstY2++ = *srcY2; srcY2 += 2; *dstU = (Uint8)(((Uint32)*srcU1 + *srcU2)/2); *dstV = (Uint8)(((Uint32)*srcV1 + *srcV2)/2); srcU1 += 4; srcU2 += 4; srcV1 += 4; srcV2 += 4; dstU += dstUV_pixel_stride; dstV += dstUV_pixel_stride; } srcY1 += src_pitch_left + srcY_pitch; srcY2 += src_pitch_left + srcY_pitch; srcU1 += src_pitch_left + srcUV_pitch; srcU2 += src_pitch_left + srcUV_pitch; srcV1 += src_pitch_left + srcUV_pitch; srcV2 += src_pitch_left + srcUV_pitch; dstY1 += dstY_pitch_left + dstY_pitch; dstY2 += dstY_pitch_left + dstY_pitch; dstU += dstUV_pitch_left; dstV += dstUV_pitch_left; } /* Last row */ if (y == (height - 1)) { for (x = 0; x < (width - 1); x += 2) { *dstY1++ = *srcY1; srcY1 += 2; *dstY1++ = *srcY1; srcY1 += 2; *dstU = *srcU1; *dstV = *srcV1; srcU1 += 4; srcV1 += 4; dstU += dstUV_pixel_stride; dstV += dstUV_pixel_stride; } /* Last column */ if (x == (width - 1)) { *dstY1 = *srcY1; *dstU = *srcU1; *dstV = *srcV1; } } return 0; } #endif /* SDL_HAVE_YUV */ int SDL_ConvertPixels_YUV_to_YUV(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch) { #if SDL_HAVE_YUV if (src_format == dst_format) { if (src == dst) { /* Nothing to do */ return 0; } return SDL_ConvertPixels_YUV_to_YUV_Copy(width, height, src_format, src, src_pitch, dst, dst_pitch); } if (IsPlanar2x2Format(src_format) && IsPlanar2x2Format(dst_format)) { return SDL_ConvertPixels_Planar2x2_to_Planar2x2(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch); } else if (IsPacked4Format(src_format) && IsPacked4Format(dst_format)) { return SDL_ConvertPixels_Packed4_to_Packed4(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch); } else if (IsPlanar2x2Format(src_format) && IsPacked4Format(dst_format)) { return SDL_ConvertPixels_Planar2x2_to_Packed4(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch); } else if (IsPacked4Format(src_format) && IsPlanar2x2Format(dst_format)) { return SDL_ConvertPixels_Packed4_to_Planar2x2(width, height, src_format, src, src_pitch, dst_format, dst, dst_pitch); } else { return SDL_SetError("SDL_ConvertPixels_YUV_to_YUV: Unsupported YUV conversion: %s -> %s", SDL_GetPixelFormatName(src_format), SDL_GetPixelFormatName(dst_format)); } #else return SDL_SetError("SDL not built with YUV support"); #endif } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_yuv.c
C
apache-2.0
64,750
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_yuv_c_h_ #define SDL_yuv_c_h_ #include "../SDL_internal.h" /* YUV conversion functions */ extern int SDL_ConvertPixels_YUV_to_RGB(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch); extern int SDL_ConvertPixels_RGB_to_YUV(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch); extern int SDL_ConvertPixels_YUV_to_YUV(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch); #endif /* SDL_yuv_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/SDL_yuv_c.h
C
apache-2.0
1,589
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ALIOS /* Being a alios driver, there's no event stream. We just define stubs for most of the API. */ #include "../../events/SDL_events_c.h" #include "SDL_AliOS_video.h" #include "SDL_AliOS_events_c.h" void AliOS_PumpEvents(_THIS) { #ifdef SDL_INPUT_LINUXEV SDL_EVDEV_Poll(); #endif /* do nothing. */ } #endif /* SDL_VIDEO_DRIVER_ALIOS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_events.c
C
apache-2.0
1,383
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_alio_events_c_h_ #define SDL_alios_events_c_h_ #include "../../SDL_internal.h" #include "SDL_AliOS_video.h" extern void AliOS_PumpEvents(_THIS); #endif /* SDL_alios_events_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_events_c.h
C
apache-2.0
1,172
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ALIOS #ifdef AOS_COMP_UDISPLAY #include "udisplay.h" #endif #include "../SDL_sysvideo.h" #include "SDL_AliOS_framebuffer_c.h" #define ALIOS_SURFACE "_SDL_AliOSSurface" int SDL_AliOS_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch) { SDL_Surface *surface; const Uint32 surface_format = SDL_PIXELFORMAT_RGB565; int w, h; int bpp; Uint32 Rmask, Gmask, Bmask, Amask; /* Free the old framebuffer surface */ surface = (SDL_Surface *) SDL_GetWindowData(window, ALIOS_SURFACE); SDL_FreeSurface(surface); /* Create a new one */ SDL_PixelFormatEnumToMasks(surface_format, &bpp, &Rmask, &Gmask, &Bmask, &Amask); SDL_GetWindowSize(window, &w, &h); surface = SDL_CreateRGBSurface(0, w, h, bpp, Rmask, Gmask, Bmask, Amask); if (!surface) { return -1; } /* Save the info and return! */ SDL_SetWindowData(window, ALIOS_SURFACE, surface); *format = surface_format; *pixels = surface->pixels; *pitch = surface->pitch; return 0; } int SDL_AliOS_UpdateWindowFramebuffer(_THIS, SDL_Window * window, const SDL_Rect * rects, int numrects) { static int frame_number; SDL_Surface *surface; surface = (SDL_Surface *) SDL_GetWindowData(window, ALIOS_SURFACE); if (!surface) { return SDL_SetError("Couldn't find alios surface for window"); } #ifdef AOS_COMP_LCD hal_lcd_t *hal_lcd = get_hal_lcd(); hal_lcd->lcd_frame_draw(surface->pixels); #endif #ifdef AOS_COMP_UDISPLAY udisplay_show_rect(surface->pixels, 0, 0, surface->w, surface->h, false); #endif return 0; } void SDL_AliOS_DestroyWindowFramebuffer(_THIS, SDL_Window * window) { SDL_Surface *surface; surface = (SDL_Surface *) SDL_SetWindowData(window, ALIOS_SURFACE, NULL); SDL_FreeSurface(surface); } #endif /* SDL_VIDEO_DRIVER_ALIOS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_framebuffer.c
C
apache-2.0
2,903
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_alios_framebuffer_c_h_ #define SDL_alios_framebuffer_c_h_ #include "../../SDL_internal.h" #ifdef AOS_COMP_LCD #include "hal_lcd.h" #endif extern int SDL_AliOS_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch); extern int SDL_AliOS_UpdateWindowFramebuffer(_THIS, SDL_Window * window, const SDL_Rect * rects, int numrects); extern void SDL_AliOS_DestroyWindowFramebuffer(_THIS, SDL_Window * window); #ifdef AOS_COMP_LCD extern hal_lcd_t *get_hal_lcd(void); #endif #endif /* SDL_alios_framebuffer_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_framebuffer_c.h
C
apache-2.0
1,538
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ALIOS /*We don't use it anymore since our driver doesn't not support cursor*/ #include "SDL_assert.h" #include "SDL_AliOS_video.h" #include "SDL_AliOS_mouse.h" #include "SDL_touch.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_mouse_c.h" #include "../../events/default_cursor.h" static SDL_Cursor *AliOS_CreateDefaultCursor(void); static SDL_Cursor *AliOS_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y); static int AliOS_ShowCursor(SDL_Cursor * cursor); static void AliOS_FreeCursor(SDL_Cursor * cursor); static void AliOS_WarpMouse(SDL_Window * window, int x, int y); static SDL_Cursor * AliOS_CreateDefaultCursor(void) { return SDL_CreateCursor(default_cdata, default_cmask, DEFAULT_CWIDTH, DEFAULT_CHEIGHT, DEFAULT_CHOTX, DEFAULT_CHOTY); } /* Create a cursor from a surface */ static SDL_Cursor * AliOS_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y) { AliOS_CursorData *curdata; SDL_Cursor *cursor; int pitch, i; cursor = SDL_malloc(sizeof(SDL_Cursor)); curdata = SDL_malloc(sizeof(AliOS_CursorData)); curdata->hotx = hot_x; curdata->hoty = hot_y; curdata->surface = surface; cursor->driverdata = curdata; printf("AliOS_CreateCursor done\n"); return cursor; } static SDL_Cursor * AliOS_CreateSystemCursor(SDL_Surface * surface, int hot_x, int hot_y) { return NULL; } /* Show the specified cursor, or hide if cursor is NULL */ static int AliOS_ShowCursor(SDL_Cursor * cursor) { SDL_Mouse *mouse; SDL_VideoDisplay *display; SDL_Window *window; SDL_Surface *surface; if (cursor) { surface = ((AliOS_CursorData *)cursor->driverdata)->surface; window = SDL_GetFocusWindow(); if (!window) return -1; else { SDL_Surface *w_surface; w_surface = SDL_GetWindowSurface(window); SDL_BlitSurface(surface, NULL, w_surface, NULL); SDL_UpdateWindowSurface(window); printf("show cursor done\n"); } printf("ShowCursor done\n"); } return 0; } /* Free a window manager cursor */ static void AliOS_FreeCursor(SDL_Cursor * cursor) { } /* Warp the mouse to (x,y) */ static void AliOS_WarpMouse(SDL_Window * window, int x, int y) { printf("AliOS_WarpMouse done\n"); return; } /* move cursor to (x,y) */ static void AliOS_MoveCursor(SDL_Cursor *cursor) { printf("AliOS_WarpMouse done\n"); return; } void AliOS_InitMouse(_THIS) { SDL_Mouse *mouse = SDL_GetMouse(); mouse->CreateCursor = NULL; mouse->CreateSystemCursor = NULL; mouse->ShowCursor = NULL; mouse->WarpMouse = NULL; mouse->FreeCursor = NULL; mouse->MoveCursor = NULL; SDL_SetDefaultCursor(AliOS_CreateDefaultCursor()); //SDL_AddTouch(1, SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE, "alios_touch"); printf("AliOS_InitMouse done\n"); } void AliOS_QuitMouse(_THIS) { return; } #endif /* SDL_VIDEO_DRIVER_ALIOS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_mouse.c
C
apache-2.0
4,026
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_alios_modes_h_ #define SDL_alios_modes_h_ #include "../SDL_sysvideo.h" typedef struct _AliOS_CursorData AliOS_CursorData; struct _AliOS_CursorData { SDL_Surface * surface; int hotx; int hoty; }; extern void RPI_InitMouse(_THIS); extern void RPI_QuitMouse(_THIS); #endif /* SDL_alios_modes_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_mouse.h
C
apache-2.0
1,323
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ALIOS /* Dummy SDL video driver implementation; this is just enough to make an * SDL-based application THINK it's got a working video driver, for * applications that call SDL_Init(SDL_INIT_VIDEO) when they don't need it, * and also for use as a collection of stubs when porting SDL to a new * platform for which you haven't yet written a valid video driver. * * This is also a great way to determine bottlenecks: if you think that SDL * is a performance problem for a given platform, enable this driver, and * then see if your application runs faster without video overhead. * * Initial work by Ryan C. Gordon (icculus@icculus.org). A good portion * of this was cut-and-pasted from Stephane Peter's work in the AAlib * SDL video driver. Renamed to "AliOS" by Sam Lantinga. */ #include "SDL_video.h" #include "SDL_mouse.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "../../events/SDL_events_c.h" #include "SDL_AliOS_video.h" #include "SDL_AliOS_events_c.h" #include "SDL_AliOS_framebuffer_c.h" #define ALIOSVID_DRIVER_NAME "alios" /* Initialization/Query functions */ static int AliOS_VideoInit(_THIS); static int AliOS_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); static void AliOS_VideoQuit(_THIS); /* AliOS driver bootstrap functions */ static int AliOS_Available(void) { #ifdef __ALIOS__ return (1); #else const char *envr = SDL_getenv("SDL_VIDEODRIVER"); if ((envr) && (SDL_strcmp(envr, ALIOSVID_DRIVER_NAME) == 0)) { return (1); } return (0); #endif } static void AliOS_DeleteDevice(SDL_VideoDevice * device) { SDL_free(device); } static SDL_VideoDevice * AliOS_CreateDevice(int devindex) { SDL_VideoDevice *device; /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (!device) { SDL_OutOfMemory(); return (0); } device->is_dummy = SDL_TRUE; /* Set the function pointers */ device->VideoInit = AliOS_VideoInit; device->VideoQuit = AliOS_VideoQuit; device->SetDisplayMode = AliOS_SetDisplayMode; device->PumpEvents = AliOS_PumpEvents; device->CreateWindowFramebuffer = SDL_AliOS_CreateWindowFramebuffer; device->UpdateWindowFramebuffer = SDL_AliOS_UpdateWindowFramebuffer; device->DestroyWindowFramebuffer = SDL_AliOS_DestroyWindowFramebuffer; device->free = AliOS_DeleteDevice; return device; } VideoBootStrap AliOS_bootstrap = { ALIOSVID_DRIVER_NAME, "SDL alios video driver", AliOS_Available, AliOS_CreateDevice }; int AliOS_VideoInit(_THIS) { SDL_DisplayMode mode; /* Use a fake 32-bpp desktop mode */ #ifdef AOS_COMP_LCD #ifdef AOS_APP_GAME_DEMO hal_lcd_t *hal_lcd = get_hal_lcd(); uint8_t *frame; mode.format = SDL_PIXELFORMAT_RGB565; mode.w = 240; mode.h = 320; frame = malloc(mode.w*mode.h*2); #else hal_lcd_t *hal_lcd = get_hal_lcd(); uint8_t *frame; mode.format = SDL_PIXELFORMAT_BGR565; mode.w = 320; mode.h = 240; frame = malloc(mode.w*mode.h*2); #endif #endif #ifdef AOS_COMP_UDISPLAY mode.format = SDL_PIXELFORMAT_BGR565; mode.w = 320; mode.h = 240; #endif mode.refresh_rate = 0; mode.driverdata = NULL; if (SDL_AddBasicVideoDisplay(&mode) < 0) { return -1; } SDL_zero(mode); SDL_AddDisplayMode(&_this->displays[0], &mode); #ifdef SDL_INPUT_LINUXEV SDL_EVDEV_Init(); #endif #ifdef AOS_COMP_LCD #ifdef AOS_APP_GAME_DEMO hal_lcd->lcd_init(); hal_lcd->lcd_rotation_set(HAL_LCD_ROTATE_0); memset(frame, 0xffff, mode.w*mode.h*2); hal_lcd->lcd_frame_draw(frame); free(frame); #else hal_lcd->lcd_init(); hal_lcd->lcd_rotation_set(HAL_LCD_ROTATE_90); memset(frame, 0xffff, mode.w*mode.h*2); hal_lcd->lcd_frame_draw(frame); free(frame); #endif #endif //AliOS_InitMouse(_this); #ifdef AOS_COMP_UDISPLAY udisplay_init(); #endif /* We're done! */ return 0; } static int AliOS_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { return 0; } void AliOS_VideoQuit(_THIS) { } #endif /* SDL_VIDEO_DRIVER_ALIOS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_video.c
C
apache-2.0
5,229
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_alios_video_h_ #define SDL_alios_video_h_ #include "../SDL_sysvideo.h" #endif /* SDL_alios_video_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/alios/SDL_AliOS_video.h
C
apache-2.0
1,125
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include "SDL_androidvideo.h" #include "SDL_androidclipboard.h" #include "../../core/android/SDL_android.h" int Android_SetClipboardText(_THIS, const char *text) { return Android_JNI_SetClipboardText(text); } char * Android_GetClipboardText(_THIS) { return Android_JNI_GetClipboardText(); } SDL_bool Android_HasClipboardText(_THIS) { return Android_JNI_HasClipboardText(); } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidclipboard.c
C
apache-2.0
1,467
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_androidclipboard_h_ #define SDL_androidclipboard_h_ extern int Android_SetClipboardText(_THIS, const char *text); extern char *Android_GetClipboardText(_THIS); extern SDL_bool Android_HasClipboardText(_THIS); #endif /* SDL_androidclipboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidclipboard.h
C
apache-2.0
1,268
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include "SDL_androidevents.h" #include "SDL_events.h" #include "SDL_androidkeyboard.h" #include "SDL_androidwindow.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_events_c.h" /* Can't include sysaudio "../../audio/android/SDL_androidaudio.h" * because of THIS redefinition */ #if !SDL_AUDIO_DISABLED && SDL_AUDIO_DRIVER_ANDROID extern void ANDROIDAUDIO_ResumeDevices(void); extern void ANDROIDAUDIO_PauseDevices(void); #else static void ANDROIDAUDIO_ResumeDevices(void) {} static void ANDROIDAUDIO_PauseDevices(void) {} #endif #if !SDL_AUDIO_DISABLED && SDL_AUDIO_DRIVER_OPENSLES extern void openslES_ResumeDevices(void); extern void openslES_PauseDevices(void); #else static void openslES_ResumeDevices(void) {} static void openslES_PauseDevices(void) {} #endif /* Number of 'type' events in the event queue */ static int SDL_NumberOfEvents(Uint32 type) { return SDL_PeepEvents(NULL, 0, SDL_PEEKEVENT, type, type); } static void android_egl_context_restore(SDL_Window *window) { if (window) { SDL_Event event; SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (SDL_GL_MakeCurrent(window, (SDL_GLContext) data->egl_context) < 0) { /* The context is no longer valid, create a new one */ data->egl_context = (EGLContext) SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, (SDL_GLContext) data->egl_context); event.type = SDL_RENDER_DEVICE_RESET; SDL_PushEvent(&event); } data->backup_done = 0; } } static void android_egl_context_backup(SDL_Window *window) { if (window) { /* Keep a copy of the EGL Context so we can try to restore it when we resume */ SDL_WindowData *data = (SDL_WindowData *) window->driverdata; data->egl_context = SDL_GL_GetCurrentContext(); /* We need to do this so the EGLSurface can be freed */ SDL_GL_MakeCurrent(window, NULL); data->backup_done = 1; } } /* * Android_ResumeSem and Android_PauseSem are signaled from Java_org_libsdl_app_SDLActivity_nativePause and Java_org_libsdl_app_SDLActivity_nativeResume * When the pause semaphore is signaled, if Android_PumpEvents_Blocking is used, the event loop will block until the resume signal is emitted. * * No polling necessary */ void Android_PumpEvents_Blocking(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; if (videodata->isPaused) { SDL_bool isContextExternal = SDL_IsVideoContextExternal(); /* Make sure this is the last thing we do before pausing */ if (!isContextExternal) { SDL_LockMutex(Android_ActivityMutex); android_egl_context_backup(Android_Window); SDL_UnlockMutex(Android_ActivityMutex); } ANDROIDAUDIO_PauseDevices(); openslES_PauseDevices(); if (SDL_SemWait(Android_ResumeSem) == 0) { videodata->isPaused = 0; /* Android_ResumeSem was signaled */ SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND); SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND); SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0); ANDROIDAUDIO_ResumeDevices(); openslES_ResumeDevices(); /* Restore the GL Context from here, as this operation is thread dependent */ if (!isContextExternal && !SDL_HasEvent(SDL_QUIT)) { SDL_LockMutex(Android_ActivityMutex); android_egl_context_restore(Android_Window); SDL_UnlockMutex(Android_ActivityMutex); } /* Make sure SW Keyboard is restored when an app becomes foreground */ if (SDL_IsTextInputActive()) { Android_StartTextInput(_this); /* Only showTextInput */ } } } else { if (videodata->isPausing || SDL_SemTryWait(Android_PauseSem) == 0) { /* Android_PauseSem was signaled */ if (videodata->isPausing == 0) { SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0); SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND); SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND); } /* We've been signaled to pause (potentially several times), but before we block ourselves, * we need to make sure that the very last event (of the first pause sequence, if several) * has reached the app */ if (SDL_NumberOfEvents(SDL_APP_DIDENTERBACKGROUND) > SDL_SemValue(Android_PauseSem)) { videodata->isPausing = 1; } else { videodata->isPausing = 0; videodata->isPaused = 1; } } } } void Android_PumpEvents_NonBlocking(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; static int backup_context = 0; if (videodata->isPaused) { SDL_bool isContextExternal = SDL_IsVideoContextExternal(); if (backup_context) { if (!isContextExternal) { SDL_LockMutex(Android_ActivityMutex); android_egl_context_backup(Android_Window); SDL_UnlockMutex(Android_ActivityMutex); } ANDROIDAUDIO_PauseDevices(); openslES_PauseDevices(); backup_context = 0; } if (SDL_SemTryWait(Android_ResumeSem) == 0) { videodata->isPaused = 0; /* Android_ResumeSem was signaled */ SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND); SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND); SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0); ANDROIDAUDIO_ResumeDevices(); openslES_ResumeDevices(); /* Restore the GL Context from here, as this operation is thread dependent */ if (!isContextExternal && !SDL_HasEvent(SDL_QUIT)) { SDL_LockMutex(Android_ActivityMutex); android_egl_context_restore(Android_Window); SDL_UnlockMutex(Android_ActivityMutex); } /* Make sure SW Keyboard is restored when an app becomes foreground */ if (SDL_IsTextInputActive()) { Android_StartTextInput(_this); /* Only showTextInput */ } } } else { if (videodata->isPausing || SDL_SemTryWait(Android_PauseSem) == 0) { /* Android_PauseSem was signaled */ if (videodata->isPausing == 0) { SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0); SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND); SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND); } /* We've been signaled to pause (potentially several times), but before we block ourselves, * we need to make sure that the very last event (of the first pause sequence, if several) * has reached the app */ if (SDL_NumberOfEvents(SDL_APP_DIDENTERBACKGROUND) > SDL_SemValue(Android_PauseSem)) { videodata->isPausing = 1; } else { videodata->isPausing = 0; videodata->isPaused = 1; backup_context = 1; } } } } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidevents.c
C
apache-2.0
8,439
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_androidvideo.h" extern void Android_PumpEvents_Blocking(_THIS); extern void Android_PumpEvents_NonBlocking(_THIS); /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidevents.h
C
apache-2.0
1,138
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID /* Android SDL video driver implementation */ #include "SDL_video.h" #include "../SDL_egl_c.h" #include "SDL_androidwindow.h" #include "SDL_androidvideo.h" #include "SDL_androidgl.h" #include "../../core/android/SDL_android.h" #include <android/log.h> #include <dlfcn.h> int Android_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) { if (window && context) { return SDL_EGL_MakeCurrent(_this, ((SDL_WindowData *) window->driverdata)->egl_surface, context); } else { return SDL_EGL_MakeCurrent(_this, NULL, NULL); } } SDL_GLContext Android_GLES_CreateContext(_THIS, SDL_Window * window) { SDL_GLContext ret; Android_ActivityMutex_Lock_Running(); ret = SDL_EGL_CreateContext(_this, ((SDL_WindowData *) window->driverdata)->egl_surface); SDL_UnlockMutex(Android_ActivityMutex); return ret; } int Android_GLES_SwapWindow(_THIS, SDL_Window * window) { int retval; SDL_LockMutex(Android_ActivityMutex); /* The following two calls existed in the original Java code * If you happen to have a device that's affected by their removal, * please report to Bugzilla. -- Gabriel */ /*_this->egl_data->eglWaitNative(EGL_CORE_NATIVE_ENGINE); _this->egl_data->eglWaitGL();*/ retval = SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface); SDL_UnlockMutex(Android_ActivityMutex); return retval; } int Android_GLES_LoadLibrary(_THIS, const char *path) { return SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) 0, 0); } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidgl.c
C
apache-2.0
2,643
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_androidgl_h_ #define SDL_androidgl_h_ SDL_GLContext Android_GLES_CreateContext(_THIS, SDL_Window * window); int Android_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); int Android_GLES_SwapWindow(_THIS, SDL_Window * window); int Android_GLES_LoadLibrary(_THIS, const char *path); #endif /* SDL_androidgl_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidgl.h
C
apache-2.0
1,354
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include <android/log.h> #include "../../events/SDL_events_c.h" #include "SDL_androidkeyboard.h" #include "../../core/android/SDL_android.h" void Android_InitKeyboard(void) { SDL_Keycode keymap[SDL_NUM_SCANCODES]; /* Add default scancode to key mapping */ SDL_GetDefaultKeymap(keymap); SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES); } static SDL_Scancode Android_Keycodes[] = { SDL_SCANCODE_UNKNOWN, /* AKEYCODE_UNKNOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SOFT_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SOFT_RIGHT */ SDL_SCANCODE_AC_HOME, /* AKEYCODE_HOME */ SDL_SCANCODE_AC_BACK, /* AKEYCODE_BACK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CALL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ENDCALL */ SDL_SCANCODE_0, /* AKEYCODE_0 */ SDL_SCANCODE_1, /* AKEYCODE_1 */ SDL_SCANCODE_2, /* AKEYCODE_2 */ SDL_SCANCODE_3, /* AKEYCODE_3 */ SDL_SCANCODE_4, /* AKEYCODE_4 */ SDL_SCANCODE_5, /* AKEYCODE_5 */ SDL_SCANCODE_6, /* AKEYCODE_6 */ SDL_SCANCODE_7, /* AKEYCODE_7 */ SDL_SCANCODE_8, /* AKEYCODE_8 */ SDL_SCANCODE_9, /* AKEYCODE_9 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STAR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_POUND */ SDL_SCANCODE_UP, /* AKEYCODE_DPAD_UP */ SDL_SCANCODE_DOWN, /* AKEYCODE_DPAD_DOWN */ SDL_SCANCODE_LEFT, /* AKEYCODE_DPAD_LEFT */ SDL_SCANCODE_RIGHT, /* AKEYCODE_DPAD_RIGHT */ SDL_SCANCODE_SELECT, /* AKEYCODE_DPAD_CENTER */ SDL_SCANCODE_VOLUMEUP, /* AKEYCODE_VOLUME_UP */ SDL_SCANCODE_VOLUMEDOWN, /* AKEYCODE_VOLUME_DOWN */ SDL_SCANCODE_POWER, /* AKEYCODE_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CAMERA */ SDL_SCANCODE_CLEAR, /* AKEYCODE_CLEAR */ SDL_SCANCODE_A, /* AKEYCODE_A */ SDL_SCANCODE_B, /* AKEYCODE_B */ SDL_SCANCODE_C, /* AKEYCODE_C */ SDL_SCANCODE_D, /* AKEYCODE_D */ SDL_SCANCODE_E, /* AKEYCODE_E */ SDL_SCANCODE_F, /* AKEYCODE_F */ SDL_SCANCODE_G, /* AKEYCODE_G */ SDL_SCANCODE_H, /* AKEYCODE_H */ SDL_SCANCODE_I, /* AKEYCODE_I */ SDL_SCANCODE_J, /* AKEYCODE_J */ SDL_SCANCODE_K, /* AKEYCODE_K */ SDL_SCANCODE_L, /* AKEYCODE_L */ SDL_SCANCODE_M, /* AKEYCODE_M */ SDL_SCANCODE_N, /* AKEYCODE_N */ SDL_SCANCODE_O, /* AKEYCODE_O */ SDL_SCANCODE_P, /* AKEYCODE_P */ SDL_SCANCODE_Q, /* AKEYCODE_Q */ SDL_SCANCODE_R, /* AKEYCODE_R */ SDL_SCANCODE_S, /* AKEYCODE_S */ SDL_SCANCODE_T, /* AKEYCODE_T */ SDL_SCANCODE_U, /* AKEYCODE_U */ SDL_SCANCODE_V, /* AKEYCODE_V */ SDL_SCANCODE_W, /* AKEYCODE_W */ SDL_SCANCODE_X, /* AKEYCODE_X */ SDL_SCANCODE_Y, /* AKEYCODE_Y */ SDL_SCANCODE_Z, /* AKEYCODE_Z */ SDL_SCANCODE_COMMA, /* AKEYCODE_COMMA */ SDL_SCANCODE_PERIOD, /* AKEYCODE_PERIOD */ SDL_SCANCODE_LALT, /* AKEYCODE_ALT_LEFT */ SDL_SCANCODE_RALT, /* AKEYCODE_ALT_RIGHT */ SDL_SCANCODE_LSHIFT, /* AKEYCODE_SHIFT_LEFT */ SDL_SCANCODE_RSHIFT, /* AKEYCODE_SHIFT_RIGHT */ SDL_SCANCODE_TAB, /* AKEYCODE_TAB */ SDL_SCANCODE_SPACE, /* AKEYCODE_SPACE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SYM */ SDL_SCANCODE_WWW, /* AKEYCODE_EXPLORER */ SDL_SCANCODE_MAIL, /* AKEYCODE_ENVELOPE */ SDL_SCANCODE_RETURN, /* AKEYCODE_ENTER */ SDL_SCANCODE_BACKSPACE, /* AKEYCODE_DEL */ SDL_SCANCODE_GRAVE, /* AKEYCODE_GRAVE */ SDL_SCANCODE_MINUS, /* AKEYCODE_MINUS */ SDL_SCANCODE_EQUALS, /* AKEYCODE_EQUALS */ SDL_SCANCODE_LEFTBRACKET, /* AKEYCODE_LEFT_BRACKET */ SDL_SCANCODE_RIGHTBRACKET, /* AKEYCODE_RIGHT_BRACKET */ SDL_SCANCODE_BACKSLASH, /* AKEYCODE_BACKSLASH */ SDL_SCANCODE_SEMICOLON, /* AKEYCODE_SEMICOLON */ SDL_SCANCODE_APOSTROPHE, /* AKEYCODE_APOSTROPHE */ SDL_SCANCODE_SLASH, /* AKEYCODE_SLASH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NUM */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_HEADSETHOOK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_FOCUS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PLUS */ SDL_SCANCODE_MENU, /* AKEYCODE_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NOTIFICATION */ SDL_SCANCODE_AC_SEARCH, /* AKEYCODE_SEARCH */ SDL_SCANCODE_AUDIOPLAY, /* AKEYCODE_MEDIA_PLAY_PAUSE */ SDL_SCANCODE_AUDIOSTOP, /* AKEYCODE_MEDIA_STOP */ SDL_SCANCODE_AUDIONEXT, /* AKEYCODE_MEDIA_NEXT */ SDL_SCANCODE_AUDIOPREV, /* AKEYCODE_MEDIA_PREVIOUS */ SDL_SCANCODE_AUDIOREWIND, /* AKEYCODE_MEDIA_REWIND */ SDL_SCANCODE_AUDIOFASTFORWARD, /* AKEYCODE_MEDIA_FAST_FORWARD */ SDL_SCANCODE_MUTE, /* AKEYCODE_MUTE */ SDL_SCANCODE_PAGEUP, /* AKEYCODE_PAGE_UP */ SDL_SCANCODE_PAGEDOWN, /* AKEYCODE_PAGE_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PICTSYMBOLS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SWITCH_CHARSET */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_A */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_B */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_C */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_X */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_Y */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_Z */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_L1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_R1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_L2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_R2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_THUMBL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_THUMBR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_START */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_SELECT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_MODE */ SDL_SCANCODE_ESCAPE, /* AKEYCODE_ESCAPE */ SDL_SCANCODE_DELETE, /* AKEYCODE_FORWARD_DEL */ SDL_SCANCODE_LCTRL, /* AKEYCODE_CTRL_LEFT */ SDL_SCANCODE_RCTRL, /* AKEYCODE_CTRL_RIGHT */ SDL_SCANCODE_CAPSLOCK, /* AKEYCODE_CAPS_LOCK */ SDL_SCANCODE_SCROLLLOCK, /* AKEYCODE_SCROLL_LOCK */ SDL_SCANCODE_LGUI, /* AKEYCODE_META_LEFT */ SDL_SCANCODE_RGUI, /* AKEYCODE_META_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_FUNCTION */ SDL_SCANCODE_PRINTSCREEN, /* AKEYCODE_SYSRQ */ SDL_SCANCODE_PAUSE, /* AKEYCODE_BREAK */ SDL_SCANCODE_HOME, /* AKEYCODE_MOVE_HOME */ SDL_SCANCODE_END, /* AKEYCODE_MOVE_END */ SDL_SCANCODE_INSERT, /* AKEYCODE_INSERT */ SDL_SCANCODE_AC_FORWARD, /* AKEYCODE_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_PLAY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_PAUSE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_CLOSE */ SDL_SCANCODE_EJECT, /* AKEYCODE_MEDIA_EJECT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_RECORD */ SDL_SCANCODE_F1, /* AKEYCODE_F1 */ SDL_SCANCODE_F2, /* AKEYCODE_F2 */ SDL_SCANCODE_F3, /* AKEYCODE_F3 */ SDL_SCANCODE_F4, /* AKEYCODE_F4 */ SDL_SCANCODE_F5, /* AKEYCODE_F5 */ SDL_SCANCODE_F6, /* AKEYCODE_F6 */ SDL_SCANCODE_F7, /* AKEYCODE_F7 */ SDL_SCANCODE_F8, /* AKEYCODE_F8 */ SDL_SCANCODE_F9, /* AKEYCODE_F9 */ SDL_SCANCODE_F10, /* AKEYCODE_F10 */ SDL_SCANCODE_F11, /* AKEYCODE_F11 */ SDL_SCANCODE_F12, /* AKEYCODE_F12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NUM_LOCK */ SDL_SCANCODE_KP_0, /* AKEYCODE_NUMPAD_0 */ SDL_SCANCODE_KP_1, /* AKEYCODE_NUMPAD_1 */ SDL_SCANCODE_KP_2, /* AKEYCODE_NUMPAD_2 */ SDL_SCANCODE_KP_3, /* AKEYCODE_NUMPAD_3 */ SDL_SCANCODE_KP_4, /* AKEYCODE_NUMPAD_4 */ SDL_SCANCODE_KP_5, /* AKEYCODE_NUMPAD_5 */ SDL_SCANCODE_KP_6, /* AKEYCODE_NUMPAD_6 */ SDL_SCANCODE_KP_7, /* AKEYCODE_NUMPAD_7 */ SDL_SCANCODE_KP_8, /* AKEYCODE_NUMPAD_8 */ SDL_SCANCODE_KP_9, /* AKEYCODE_NUMPAD_9 */ SDL_SCANCODE_KP_DIVIDE, /* AKEYCODE_NUMPAD_DIVIDE */ SDL_SCANCODE_KP_MULTIPLY, /* AKEYCODE_NUMPAD_MULTIPLY */ SDL_SCANCODE_KP_MINUS, /* AKEYCODE_NUMPAD_SUBTRACT */ SDL_SCANCODE_KP_PLUS, /* AKEYCODE_NUMPAD_ADD */ SDL_SCANCODE_KP_PERIOD, /* AKEYCODE_NUMPAD_DOT */ SDL_SCANCODE_KP_COMMA, /* AKEYCODE_NUMPAD_COMMA */ SDL_SCANCODE_KP_ENTER, /* AKEYCODE_NUMPAD_ENTER */ SDL_SCANCODE_KP_EQUALS, /* AKEYCODE_NUMPAD_EQUALS */ SDL_SCANCODE_KP_LEFTPAREN, /* AKEYCODE_NUMPAD_LEFT_PAREN */ SDL_SCANCODE_KP_RIGHTPAREN, /* AKEYCODE_NUMPAD_RIGHT_PAREN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_VOLUME_MUTE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_INFO */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CHANNEL_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CHANNEL_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ZOOM_IN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ZOOM_OUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_WINDOW */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_GUIDE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DVR */ SDL_SCANCODE_AC_BOOKMARKS, /* AKEYCODE_BOOKMARK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CAPTIONS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SETTINGS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STB_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STB_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AVR_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AVR_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_RED */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_GREEN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_YELLOW */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_BLUE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_APP_SWITCH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_4 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_5 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_6 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_7 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_8 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_9 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_10 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_11 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_13 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_14 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_15 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_16 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_LANGUAGE_SWITCH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MANNER_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_3D_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CONTACTS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CALENDAR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MUSIC */ SDL_SCANCODE_CALCULATOR, /* AKEYCODE_CALCULATOR */ SDL_SCANCODE_LANG5, /* AKEYCODE_ZENKAKU_HANKAKU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_EISU */ SDL_SCANCODE_INTERNATIONAL5, /* AKEYCODE_MUHENKAN */ SDL_SCANCODE_INTERNATIONAL4, /* AKEYCODE_HENKAN */ SDL_SCANCODE_LANG3, /* AKEYCODE_KATAKANA_HIRAGANA */ SDL_SCANCODE_INTERNATIONAL3, /* AKEYCODE_YEN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_RO */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_KANA */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ASSIST */ SDL_SCANCODE_BRIGHTNESSDOWN, /* AKEYCODE_BRIGHTNESS_DOWN */ SDL_SCANCODE_BRIGHTNESSUP, /* AKEYCODE_BRIGHTNESS_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_AUDIO_TRACK */ SDL_SCANCODE_SLEEP, /* AKEYCODE_SLEEP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_WAKEUP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PAIRING */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_TOP_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_11 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_LAST_CHANNEL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_DATA_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_VOICE_ASSIST */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_RADIO_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TELETEXT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_NUMBER_ENTRY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TERRESTRIAL_ANALOG */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TERRESTRIAL_DIGITAL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_BS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_CS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_NETWORK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_ANTENNA_CABLE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_4 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPOSITE_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPOSITE_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPONENT_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPONENT_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_VGA_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_ZOOM_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_CONTENTS_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_MEDIA_CONTEXT_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TIMER_PROGRAMMING */ SDL_SCANCODE_HELP, /* AKEYCODE_HELP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_PREVIOUS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_NEXT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_IN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_OUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_PRIMARY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_UP_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_DOWN_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_UP_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_DOWN_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_SKIP_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_SKIP_BACKWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_STEP_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_STEP_BACKWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SOFT_SLEEP */ SDL_SCANCODE_CUT, /* AKEYCODE_CUT */ SDL_SCANCODE_COPY, /* AKEYCODE_COPY */ SDL_SCANCODE_PASTE, /* AKEYCODE_PASTE */ }; static SDL_Scancode TranslateKeycode(int keycode) { SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; if (keycode < SDL_arraysize(Android_Keycodes)) { scancode = Android_Keycodes[keycode]; } if (scancode == SDL_SCANCODE_UNKNOWN) { __android_log_print(ANDROID_LOG_INFO, "SDL", "Unknown keycode %d", keycode); } return scancode; } int Android_OnKeyDown(int keycode) { return SDL_SendKeyboardKey(SDL_PRESSED, TranslateKeycode(keycode)); } int Android_OnKeyUp(int keycode) { return SDL_SendKeyboardKey(SDL_RELEASED, TranslateKeycode(keycode)); } SDL_bool Android_HasScreenKeyboardSupport(_THIS) { return SDL_TRUE; } SDL_bool Android_IsScreenKeyboardShown(_THIS, SDL_Window * window) { return Android_JNI_IsScreenKeyboardShown(); } void Android_StartTextInput(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; Android_JNI_ShowTextInput(&videodata->textRect); } void Android_StopTextInput(_THIS) { Android_JNI_HideTextInput(); } void Android_SetTextInputRect(_THIS, SDL_Rect *rect) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; if (!rect) { SDL_InvalidParamError("rect"); return; } videodata->textRect = *rect; } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidkeyboard.c
C
apache-2.0
16,574
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_androidvideo.h" extern void Android_InitKeyboard(void); extern int Android_OnKeyDown(int keycode); extern int Android_OnKeyUp(int keycode); extern SDL_bool Android_HasScreenKeyboardSupport(_THIS); extern SDL_bool Android_IsScreenKeyboardShown(_THIS, SDL_Window * window); extern void Android_StartTextInput(_THIS); extern void Android_StopTextInput(_THIS); extern void Android_SetTextInputRect(_THIS, SDL_Rect *rect); /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidkeyboard.h
C
apache-2.0
1,443
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include "SDL_messagebox.h" #include "SDL_androidmessagebox.h" #include "../../core/android/SDL_android.h" int Android_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) { return Android_JNI_ShowMessageBox(messageboxdata, buttonid); } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidmessagebox.c
C
apache-2.0
1,338
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID extern int Android_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid); #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidmessagebox.h
C
apache-2.0
1,169
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include "SDL_androidmouse.h" #include "SDL_events.h" #include "../../events/SDL_mouse_c.h" #include "../../core/android/SDL_android.h" /* See Android's MotionEvent class for constants */ #define ACTION_DOWN 0 #define ACTION_UP 1 #define ACTION_MOVE 2 #define ACTION_HOVER_MOVE 7 #define ACTION_SCROLL 8 #define BUTTON_PRIMARY 1 #define BUTTON_SECONDARY 2 #define BUTTON_TERTIARY 4 #define BUTTON_BACK 8 #define BUTTON_FORWARD 16 typedef struct { int custom_cursor; int system_cursor; } SDL_AndroidCursorData; /* Last known Android mouse button state (includes all buttons) */ static int last_state; /* Blank cursor */ static SDL_Cursor *empty_cursor; static SDL_Cursor * Android_WrapCursor(int custom_cursor, int system_cursor) { SDL_Cursor *cursor; cursor = SDL_calloc(1, sizeof(*cursor)); if (cursor) { SDL_AndroidCursorData *data = (SDL_AndroidCursorData *)SDL_calloc(1, sizeof(*data)); if (data) { data->custom_cursor = custom_cursor; data->system_cursor = system_cursor; cursor->driverdata = data; } else { SDL_free(cursor); cursor = NULL; SDL_OutOfMemory(); } } else { SDL_OutOfMemory(); } return cursor; } static SDL_Cursor * Android_CreateDefaultCursor() { return Android_WrapCursor(0, SDL_SYSTEM_CURSOR_ARROW); } static SDL_Cursor * Android_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y) { int custom_cursor; SDL_Surface *converted; converted = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ARGB8888, 0); if (!converted) { return NULL; } custom_cursor = Android_JNI_CreateCustomCursor(converted, hot_x, hot_y); SDL_FreeSurface(converted); if (!custom_cursor) { SDL_Unsupported(); return NULL; } return Android_WrapCursor(custom_cursor, 0); } static SDL_Cursor * Android_CreateSystemCursor(SDL_SystemCursor id) { return Android_WrapCursor(0, id); } static void Android_FreeCursor(SDL_Cursor * cursor) { SDL_free(cursor->driverdata); SDL_free(cursor); } static SDL_Cursor * Android_CreateEmptyCursor() { if (!empty_cursor) { SDL_Surface *empty_surface = SDL_CreateRGBSurfaceWithFormat(0, 1, 1, 32, SDL_PIXELFORMAT_ARGB8888); if (empty_surface) { SDL_memset(empty_surface->pixels, 0, empty_surface->h * empty_surface->pitch); empty_cursor = Android_CreateCursor(empty_surface, 0, 0); SDL_FreeSurface(empty_surface); } } return empty_cursor; } static void Android_DestroyEmptyCursor() { if (empty_cursor) { Android_FreeCursor(empty_cursor); empty_cursor = NULL; } } static int Android_ShowCursor(SDL_Cursor *cursor) { if (!cursor) { cursor = Android_CreateEmptyCursor(); } if (cursor) { SDL_AndroidCursorData *data = (SDL_AndroidCursorData *)cursor->driverdata; if (data->custom_cursor) { if (!Android_JNI_SetCustomCursor(data->custom_cursor)) { return SDL_Unsupported(); } } else { if (!Android_JNI_SetSystemCursor(data->system_cursor)) { return SDL_Unsupported(); } } return 0; } else { /* SDL error set inside Android_CreateEmptyCursor() */ return -1; } } static int Android_SetRelativeMouseMode(SDL_bool enabled) { if (!Android_JNI_SupportsRelativeMouse()) { return SDL_Unsupported(); } if (!Android_JNI_SetRelativeMouseEnabled(enabled)) { return SDL_Unsupported(); } return 0; } void Android_InitMouse(void) { SDL_Mouse *mouse = SDL_GetMouse(); mouse->CreateCursor = Android_CreateCursor; mouse->CreateSystemCursor = Android_CreateSystemCursor; mouse->ShowCursor = Android_ShowCursor; mouse->FreeCursor = Android_FreeCursor; mouse->SetRelativeMouseMode = Android_SetRelativeMouseMode; SDL_SetDefaultCursor(Android_CreateDefaultCursor()); last_state = 0; } void Android_QuitMouse(void) { Android_DestroyEmptyCursor(); } /* Translate Android mouse button state to SDL mouse button */ static Uint8 TranslateButton(int state) { if (state & BUTTON_PRIMARY) { return SDL_BUTTON_LEFT; } else if (state & BUTTON_SECONDARY) { return SDL_BUTTON_RIGHT; } else if (state & BUTTON_TERTIARY) { return SDL_BUTTON_MIDDLE; } else if (state & BUTTON_FORWARD) { return SDL_BUTTON_X1; } else if (state & BUTTON_BACK) { return SDL_BUTTON_X2; } else { return 0; } } void Android_OnMouse(SDL_Window *window, int state, int action, float x, float y, SDL_bool relative) { int changes; Uint8 button; if (!window) { return; } switch(action) { case ACTION_DOWN: changes = state & ~last_state; button = TranslateButton(changes); last_state = state; SDL_SendMouseMotion(window, 0, relative, (int)x, (int)y); SDL_SendMouseButton(window, 0, SDL_PRESSED, button); break; case ACTION_UP: changes = last_state & ~state; button = TranslateButton(changes); last_state = state; SDL_SendMouseMotion(window, 0, relative, (int)x, (int)y); SDL_SendMouseButton(window, 0, SDL_RELEASED, button); break; case ACTION_MOVE: case ACTION_HOVER_MOVE: SDL_SendMouseMotion(window, 0, relative, (int)x, (int)y); break; case ACTION_SCROLL: SDL_SendMouseWheel(window, 0, x, y, SDL_MOUSEWHEEL_NORMAL); break; default: break; } } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidmouse.c
C
apache-2.0
6,828
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_androidmouse_h_ #define SDL_androidmouse_h_ #include "SDL_androidvideo.h" extern void Android_InitMouse(void); extern void Android_OnMouse(SDL_Window *window, int button, int action, float x, float y, SDL_bool relative); extern void Android_QuitMouse(void); #endif /* SDL_androidmouse_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidmouse.h
C
apache-2.0
1,282
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include <android/log.h> #include "SDL_hints.h" #include "SDL_events.h" #include "SDL_androidtouch.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_touch_c.h" #include "../../core/android/SDL_android.h" #define ACTION_DOWN 0 #define ACTION_UP 1 #define ACTION_MOVE 2 /* #define ACTION_CANCEL 3 */ /* #define ACTION_OUTSIDE 4 */ #define ACTION_POINTER_DOWN 5 #define ACTION_POINTER_UP 6 void Android_InitTouch(void) { /* Add all touch devices */ Android_JNI_InitTouch(); } void Android_QuitTouch(void) { } void Android_OnTouch(SDL_Window *window, int touch_device_id_in, int pointer_finger_id_in, int action, float x, float y, float p) { SDL_TouchID touchDeviceId = 0; SDL_FingerID fingerId = 0; if (!window) { return; } touchDeviceId = (SDL_TouchID)touch_device_id_in; if (SDL_AddTouch(touchDeviceId, SDL_TOUCH_DEVICE_DIRECT, "") < 0) { SDL_Log("error: can't add touch %s, %d", __FILE__, __LINE__); } fingerId = (SDL_FingerID)pointer_finger_id_in; switch (action) { case ACTION_DOWN: case ACTION_POINTER_DOWN: SDL_SendTouch(touchDeviceId, fingerId, window, SDL_TRUE, x, y, p); break; case ACTION_MOVE: SDL_SendTouchMotion(touchDeviceId, fingerId, window, x, y, p); break; case ACTION_UP: case ACTION_POINTER_UP: SDL_SendTouch(touchDeviceId, fingerId, window, SDL_FALSE, x, y, p); break; default: break; } } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidtouch.c
C
apache-2.0
2,610
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_androidvideo.h" extern void Android_InitTouch(void); extern void Android_QuitTouch(void); extern void Android_OnTouch(SDL_Window *window, int touch_device_id_in, int pointer_finger_id_in, int action, float x, float y, float p); /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidtouch.h
C
apache-2.0
1,251
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID /* Android SDL video driver implementation */ #include "SDL_video.h" #include "SDL_mouse.h" #include "SDL_hints.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "../../events/SDL_events_c.h" #include "../../events/SDL_windowevents_c.h" #include "SDL_androidvideo.h" #include "SDL_androidgl.h" #include "SDL_androidclipboard.h" #include "SDL_androidevents.h" #include "SDL_androidkeyboard.h" #include "SDL_androidmouse.h" #include "SDL_androidtouch.h" #include "SDL_androidwindow.h" #include "SDL_androidvulkan.h" #define ANDROID_VID_DRIVER_NAME "Android" /* Initialization/Query functions */ static int Android_VideoInit(_THIS); static void Android_VideoQuit(_THIS); int Android_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi); #include "../SDL_egl_c.h" #define Android_GLES_GetProcAddress SDL_EGL_GetProcAddress #define Android_GLES_UnloadLibrary SDL_EGL_UnloadLibrary #define Android_GLES_SetSwapInterval SDL_EGL_SetSwapInterval #define Android_GLES_GetSwapInterval SDL_EGL_GetSwapInterval #define Android_GLES_DeleteContext SDL_EGL_DeleteContext /* Android driver bootstrap functions */ /* These are filled in with real values in Android_SetScreenResolution on init (before SDL_main()) */ int Android_SurfaceWidth = 0; int Android_SurfaceHeight = 0; static int Android_DeviceWidth = 0; static int Android_DeviceHeight = 0; static Uint32 Android_ScreenFormat = SDL_PIXELFORMAT_UNKNOWN; static int Android_ScreenRate = 0; SDL_sem *Android_PauseSem = NULL; SDL_sem *Android_ResumeSem = NULL; SDL_mutex *Android_ActivityMutex = NULL; static int Android_Available(void) { return 1; } static void Android_SuspendScreenSaver(_THIS) { Android_JNI_SuspendScreenSaver(_this->suspend_screensaver); } static void Android_DeleteDevice(SDL_VideoDevice *device) { SDL_free(device->driverdata); SDL_free(device); } static SDL_VideoDevice * Android_CreateDevice(int devindex) { SDL_VideoDevice *device; SDL_VideoData *data; SDL_bool block_on_pause; /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (!device) { SDL_OutOfMemory(); return NULL; } data = (SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); if (!data) { SDL_OutOfMemory(); SDL_free(device); return NULL; } device->driverdata = data; /* Set the function pointers */ device->VideoInit = Android_VideoInit; device->VideoQuit = Android_VideoQuit; block_on_pause = SDL_GetHintBoolean(SDL_HINT_ANDROID_BLOCK_ON_PAUSE, SDL_TRUE); if (block_on_pause) { device->PumpEvents = Android_PumpEvents_Blocking; } else { device->PumpEvents = Android_PumpEvents_NonBlocking; } device->GetDisplayDPI = Android_GetDisplayDPI; device->CreateSDLWindow = Android_CreateWindow; device->SetWindowTitle = Android_SetWindowTitle; device->SetWindowFullscreen = Android_SetWindowFullscreen; device->MinimizeWindow = Android_MinimizeWindow; device->DestroyWindow = Android_DestroyWindow; device->GetWindowWMInfo = Android_GetWindowWMInfo; device->free = Android_DeleteDevice; /* GL pointers */ device->GL_LoadLibrary = Android_GLES_LoadLibrary; device->GL_GetProcAddress = Android_GLES_GetProcAddress; device->GL_UnloadLibrary = Android_GLES_UnloadLibrary; device->GL_CreateContext = Android_GLES_CreateContext; device->GL_MakeCurrent = Android_GLES_MakeCurrent; device->GL_SetSwapInterval = Android_GLES_SetSwapInterval; device->GL_GetSwapInterval = Android_GLES_GetSwapInterval; device->GL_SwapWindow = Android_GLES_SwapWindow; device->GL_DeleteContext = Android_GLES_DeleteContext; #if SDL_VIDEO_VULKAN device->Vulkan_LoadLibrary = Android_Vulkan_LoadLibrary; device->Vulkan_UnloadLibrary = Android_Vulkan_UnloadLibrary; device->Vulkan_GetInstanceExtensions = Android_Vulkan_GetInstanceExtensions; device->Vulkan_CreateSurface = Android_Vulkan_CreateSurface; #endif /* Screensaver */ device->SuspendScreenSaver = Android_SuspendScreenSaver; /* Text input */ device->StartTextInput = Android_StartTextInput; device->StopTextInput = Android_StopTextInput; device->SetTextInputRect = Android_SetTextInputRect; /* Screen keyboard */ device->HasScreenKeyboardSupport = Android_HasScreenKeyboardSupport; device->IsScreenKeyboardShown = Android_IsScreenKeyboardShown; /* Clipboard */ device->SetClipboardText = Android_SetClipboardText; device->GetClipboardText = Android_GetClipboardText; device->HasClipboardText = Android_HasClipboardText; return device; } VideoBootStrap Android_bootstrap = { ANDROID_VID_DRIVER_NAME, "SDL Android video driver", Android_Available, Android_CreateDevice }; int Android_VideoInit(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; int display_index; SDL_VideoDisplay *display; SDL_DisplayMode mode; videodata->isPaused = SDL_FALSE; videodata->isPausing = SDL_FALSE; mode.format = Android_ScreenFormat; mode.w = Android_DeviceWidth; mode.h = Android_DeviceHeight; mode.refresh_rate = Android_ScreenRate; mode.driverdata = NULL; display_index = SDL_AddBasicVideoDisplay(&mode); if (display_index < 0) { return -1; } display = SDL_GetDisplay(display_index); display->orientation = Android_JNI_GetDisplayOrientation(); SDL_AddDisplayMode(&_this->displays[0], &mode); Android_InitKeyboard(); Android_InitTouch(); Android_InitMouse(); /* We're done! */ return 0; } void Android_VideoQuit(_THIS) { Android_QuitMouse(); Android_QuitTouch(); } int Android_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi) { return Android_JNI_GetDisplayDPI(ddpi, hdpi, vdpi); } void Android_SetScreenResolution(int surfaceWidth, int surfaceHeight, int deviceWidth, int deviceHeight, Uint32 format, float rate) { Android_SurfaceWidth = surfaceWidth; Android_SurfaceHeight = surfaceHeight; Android_DeviceWidth = deviceWidth; Android_DeviceHeight = deviceHeight; Android_ScreenFormat = format; Android_ScreenRate = (int)rate; } void Android_SendResize(SDL_Window *window) { /* Update the resolution of the desktop mode, so that the window can be properly resized. The screen resolution change can for example happen when the Activity enters or exits immersive mode, which can happen after VideoInit(). */ SDL_VideoDevice *device = SDL_GetVideoDevice(); if (device && device->num_displays > 0) { SDL_VideoDisplay *display = &device->displays[0]; display->desktop_mode.format = Android_ScreenFormat; display->desktop_mode.w = Android_DeviceWidth; display->desktop_mode.h = Android_DeviceHeight; display->desktop_mode.refresh_rate = Android_ScreenRate; } if (window) { /* Force the current mode to match the resize otherwise the SDL_WINDOWEVENT_RESTORED event * will fall back to the old mode */ SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); display->display_modes[0].format = Android_ScreenFormat; display->display_modes[0].w = Android_DeviceWidth; display->display_modes[0].h = Android_DeviceHeight; display->display_modes[0].refresh_rate = Android_ScreenRate; display->current_mode = display->display_modes[0]; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, Android_SurfaceWidth, Android_SurfaceHeight); } } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidvideo.c
C
apache-2.0
8,972
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_androidvideo_h_ #define SDL_androidvideo_h_ #include "SDL_mutex.h" #include "SDL_rect.h" #include "../SDL_sysvideo.h" /* Called by the JNI layer when the screen changes size or format */ extern void Android_SetScreenResolution(int surfaceWidth, int surfaceHeight, int deviceWidth, int deviceHeight, Uint32 format, float rate); extern void Android_SendResize(SDL_Window *window); /* Private display data */ typedef struct SDL_VideoData { SDL_Rect textRect; int isPaused; int isPausing; } SDL_VideoData; extern int Android_SurfaceWidth; extern int Android_SurfaceHeight; extern SDL_sem *Android_PauseSem, *Android_ResumeSem; extern SDL_mutex *Android_ActivityMutex; #endif /* SDL_androidvideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidvideo.h
C
apache-2.0
1,745
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.c. */ #include "../../SDL_internal.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_ANDROID #include "SDL_androidvideo.h" #include "SDL_androidwindow.h" #include "SDL_assert.h" #include "SDL_loadso.h" #include "SDL_androidvulkan.h" #include "SDL_syswm.h" int Android_Vulkan_LoadLibrary(_THIS, const char *path) { VkExtensionProperties *extensions = NULL; Uint32 i, extensionCount = 0; SDL_bool hasSurfaceExtension = SDL_FALSE; SDL_bool hasAndroidSurfaceExtension = SDL_FALSE; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL; if(_this->vulkan_config.loader_handle) return SDL_SetError("Vulkan already loaded"); /* Load the Vulkan loader library */ if(!path) path = SDL_getenv("SDL_VULKAN_LIBRARY"); if(!path) path = "libvulkan.so"; _this->vulkan_config.loader_handle = SDL_LoadObject(path); if(!_this->vulkan_config.loader_handle) return -1; SDL_strlcpy(_this->vulkan_config.loader_path, path, SDL_arraysize(_this->vulkan_config.loader_path)); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr"); if(!vkGetInstanceProcAddr) goto fail; _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr; _this->vulkan_config.vkEnumerateInstanceExtensionProperties = (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) goto fail; extensions = SDL_Vulkan_CreateInstanceExtensionsList( (PFN_vkEnumerateInstanceExtensionProperties) _this->vulkan_config.vkEnumerateInstanceExtensionProperties, &extensionCount); if(!extensions) goto fail; for(i = 0; i < extensionCount; i++) { if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) hasSurfaceExtension = SDL_TRUE; else if(SDL_strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) hasAndroidSurfaceExtension = SDL_TRUE; } SDL_free(extensions); if(!hasSurfaceExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if(!hasAndroidSurfaceExtension) { SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME "extension"); goto fail; } return 0; fail: SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; return -1; } void Android_Vulkan_UnloadLibrary(_THIS) { if(_this->vulkan_config.loader_handle) { SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; } } SDL_bool Android_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names) { static const char *const extensionsForAndroid[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_ANDROID_SURFACE_EXTENSION_NAME }; if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } return SDL_Vulkan_GetInstanceExtensions_Helper( count, names, SDL_arraysize(extensionsForAndroid), extensionsForAndroid); } SDL_bool Android_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr( instance, "vkCreateAndroidSurfaceKHR"); VkAndroidSurfaceCreateInfoKHR createInfo; VkResult result; if(!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } if(!vkCreateAndroidSurfaceKHR) { SDL_SetError(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME " extension is not enabled in the Vulkan instance."); return SDL_FALSE; } SDL_zero(createInfo); createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.window = windowData->native_window; result = vkCreateAndroidSurfaceKHR(instance, &createInfo, NULL, surface); if(result != VK_SUCCESS) { SDL_SetError("vkCreateAndroidSurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result)); return SDL_FALSE; } return SDL_TRUE; } #endif /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidvulkan.c
C
apache-2.0
6,347
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.h. */ #include "../../SDL_internal.h" #ifndef SDL_androidvulkan_h_ #define SDL_androidvulkan_h_ #include "../SDL_vulkan_internal.h" #include "../SDL_sysvideo.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_ANDROID int Android_Vulkan_LoadLibrary(_THIS, const char *path); void Android_Vulkan_UnloadLibrary(_THIS); SDL_bool Android_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names); SDL_bool Android_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface); #endif #endif /* SDL_androidvulkan_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidvulkan.h
C
apache-2.0
1,881
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include "SDL_syswm.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_windowevents_c.h" #include "../../core/android/SDL_android.h" #include "SDL_androidvideo.h" #include "SDL_androidwindow.h" #include "SDL_hints.h" /* Currently only one window */ SDL_Window *Android_Window = NULL; int Android_CreateWindow(_THIS, SDL_Window * window) { SDL_WindowData *data; int retval = 0; Android_ActivityMutex_Lock_Running(); if (Android_Window) { retval = SDL_SetError("Android only supports one window"); goto endfunction; } /* Set orientation */ Android_JNI_SetOrientation(window->w, window->h, window->flags & SDL_WINDOW_RESIZABLE, SDL_GetHint(SDL_HINT_ORIENTATIONS)); /* Adjust the window data to match the screen */ window->x = 0; window->y = 0; window->w = Android_SurfaceWidth; window->h = Android_SurfaceHeight; window->flags &= ~SDL_WINDOW_HIDDEN; window->flags |= SDL_WINDOW_SHOWN; /* only one window on Android */ /* One window, it always has focus */ SDL_SetMouseFocus(window); SDL_SetKeyboardFocus(window); data = (SDL_WindowData *) SDL_calloc(1, sizeof(*data)); if (!data) { retval = SDL_OutOfMemory(); goto endfunction; } data->native_window = Android_JNI_GetNativeWindow(); if (!data->native_window) { SDL_free(data); retval = SDL_SetError("Could not fetch native window"); goto endfunction; } /* Do not create EGLSurface for Vulkan window since it will then make the window incompatible with vkCreateAndroidSurfaceKHR */ if ((window->flags & SDL_WINDOW_OPENGL) != 0) { data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) data->native_window); if (data->egl_surface == EGL_NO_SURFACE) { ANativeWindow_release(data->native_window); SDL_free(data); retval = -1; goto endfunction; } } window->driverdata = data; Android_Window = window; endfunction: SDL_UnlockMutex(Android_ActivityMutex); return retval; } void Android_SetWindowTitle(_THIS, SDL_Window *window) { Android_JNI_SetActivityTitle(window->title); } void Android_SetWindowFullscreen(_THIS, SDL_Window *window, SDL_VideoDisplay *display, SDL_bool fullscreen) { SDL_LockMutex(Android_ActivityMutex); if (window == Android_Window) { /* If the window is being destroyed don't change visible state */ if (!window->is_destroying) { Android_JNI_SetWindowStyle(fullscreen); } /* Ensure our size matches reality after we've executed the window style change. * * It is possible that we've set width and height to the full-size display, but on * Samsung DeX or Chromebooks or other windowed Android environemtns, our window may * still not be the full display size. */ if (!SDL_IsDeXMode() && !SDL_IsChromebook()) { goto endfunction; } SDL_WindowData *data = (SDL_WindowData *)window->driverdata; if (!data || !data->native_window) { if (data && !data->native_window) { SDL_SetError("Missing native window"); } goto endfunction; } int old_w = window->w; int old_h = window->h; int new_w = ANativeWindow_getWidth(data->native_window); int new_h = ANativeWindow_getHeight(data->native_window); if (new_w < 0 || new_h < 0) { SDL_SetError("ANativeWindow_getWidth/Height() fails"); } if (old_w != new_w || old_h != new_h) { SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, new_w, new_h); } } endfunction: SDL_UnlockMutex(Android_ActivityMutex); } void Android_MinimizeWindow(_THIS, SDL_Window *window) { Android_JNI_MinizeWindow(); } void Android_DestroyWindow(_THIS, SDL_Window *window) { SDL_LockMutex(Android_ActivityMutex); if (window == Android_Window) { Android_Window = NULL; if (window->driverdata) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (data->egl_surface != EGL_NO_SURFACE) { SDL_EGL_DestroySurface(_this, data->egl_surface); } if (data->native_window) { ANativeWindow_release(data->native_window); } SDL_free(window->driverdata); window->driverdata = NULL; } } SDL_UnlockMutex(Android_ActivityMutex); } SDL_bool Android_GetWindowWMInfo(_THIS, SDL_Window *window, SDL_SysWMinfo *info) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (info->version.major == SDL_MAJOR_VERSION && info->version.minor == SDL_MINOR_VERSION) { info->subsystem = SDL_SYSWM_ANDROID; info->info.android.window = data->native_window; info->info.android.surface = data->egl_surface; return SDL_TRUE; } else { SDL_SetError("Application not compiled with SDL %d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return SDL_FALSE; } } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidwindow.c
C
apache-2.0
6,344
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_androidwindow_h_ #define SDL_androidwindow_h_ #include "../../core/android/SDL_android.h" #include "../SDL_egl_c.h" extern int Android_CreateWindow(_THIS, SDL_Window *window); extern void Android_SetWindowTitle(_THIS, SDL_Window *window); extern void Android_SetWindowFullscreen(_THIS, SDL_Window *window, SDL_VideoDisplay *display, SDL_bool fullscreen); extern void Android_MinimizeWindow(_THIS, SDL_Window *window); extern void Android_DestroyWindow(_THIS, SDL_Window *window); extern SDL_bool Android_GetWindowWMInfo(_THIS, SDL_Window *window, struct SDL_SysWMinfo *info); extern SDL_Window *Android_Window; typedef struct { EGLSurface egl_surface; EGLContext egl_context; /* We use this to preserve the context when losing focus */ SDL_bool backup_done; ANativeWindow *native_window; } SDL_WindowData; #endif /* SDL_androidwindow_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/android/SDL_androidwindow.h
C
apache-2.0
1,888
/* * Copyright © 2010 Nokia Corporation * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Mozilla Corporation not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Mozilla Corporation makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * * Author: Siarhei Siamashka (siarhei.siamashka@nokia.com) * */ /* Supplementary macro for setting function attributes */ .macro pixman_asm_function fname .func fname .global fname #ifdef __ELF__ .hidden fname .type fname, %function #endif fname: .endm
YifuLiu/AliOS-Things
components/SDL2/src/video/arm/pixman-arm-asm.h
C
apache-2.0
1,454
/* * Copyright © 2009 Nokia Corporation * * 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 (including the next * paragraph) 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. * * Author: Siarhei Siamashka (siarhei.siamashka@nokia.com) */ /* * Copyright (c) 2018 RISC OS Open Ltd * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* Prevent the stack from becoming executable for no reason... */ #if defined(__linux__) && defined(__ELF__) .section .note.GNU-stack,"",%progbits #endif .text .fpu neon .arch armv7a .object_arch armv4 .eabi_attribute 10, 0 /* suppress Tag_FP_arch */ .eabi_attribute 12, 0 /* suppress Tag_Advanced_SIMD_arch */ .arm .altmacro .p2align 2 #include "pixman-arm-asm.h" #include "pixman-arm-neon-asm.h" /* Global configuration options and preferences */ /* * The code can optionally make use of unaligned memory accesses to improve * performance of handling leading/trailing pixels for each scanline. * Configuration variable RESPECT_STRICT_ALIGNMENT can be set to 0 for * example in linux if unaligned memory accesses are not configured to * generate.exceptions. */ .set RESPECT_STRICT_ALIGNMENT, 1 /* * Set default prefetch type. There is a choice between the following options: * * PREFETCH_TYPE_NONE (may be useful for the ARM cores where PLD is set to work * as NOP to workaround some HW bugs or for whatever other reason) * * PREFETCH_TYPE_SIMPLE (may be useful for simple single-issue ARM cores where * advanced prefetch intruduces heavy overhead) * * PREFETCH_TYPE_ADVANCED (useful for superscalar cores such as ARM Cortex-A8 * which can run ARM and NEON instructions simultaneously so that extra ARM * instructions do not add (many) extra cycles, but improve prefetch efficiency) * * Note: some types of function can't support advanced prefetch and fallback * to simple one (those which handle 24bpp pixels) */ .set PREFETCH_TYPE_DEFAULT, PREFETCH_TYPE_ADVANCED /* Prefetch distance in pixels for simple prefetch */ .set PREFETCH_DISTANCE_SIMPLE, 64 /******************************************************************************/ /* We can actually do significantly better than the Pixman macros, at least for * the case of fills, by using a carefully scheduled inner loop. Cortex-A53 * shows an improvement of up to 78% in ideal cases (large fills to L1 cache). */ .macro generate_fillrect_function name, bpp, log2Bpp /* * void name(int32_t w, int32_t h, uint8_t *dst, int32_t dst_stride, uint8_t src); * On entry: * a1 = width, pixels * a2 = height, rows * a3 = pointer to top-left destination pixel * a4 = stride, pixels * [sp] = pixel value to fill with * Within the function: * v1 = width remaining * v2 = vst offset * v3 = alternate pointer * ip = data ARM register */ pixman_asm_function name vld1.\bpp {d0[],d1[]}, [sp] sub a4, a1 vld1.\bpp {d2[],d3[]}, [sp] cmp a1, #(15+64) >> \log2Bpp push {v1-v3,lr} vmov ip, s0 blo 51f /* Long-row case */ mov v2, #64 1: mov v1, a1 ands v3, a3, #15 beq 2f /* Leading pixels */ rsb v3, v3, #16 /* number of leading bytes until 16-byte aligned */ sub v1, v1, v3, lsr #\log2Bpp rbit v3, v3 .if bpp <= 16 .if bpp == 8 tst a3, #1 /* bit 0 unaffected by rsb so can avoid register interlock */ strneb ip, [a3], #1 tst v3, #1<<30 .else tst a3, #2 /* bit 1 unaffected by rsb (assuming halfword alignment) so can avoid register interlock */ .endif strneh ip, [a3], #2 .endif movs v3, v3, lsl #3 vstmcs a3!, {s0} vstmmi a3!, {d0} 2: sub v1, v1, #64 >> \log2Bpp /* simplifies inner loop termination */ add v3, a3, #32 /* Inner loop */ 3: vst1.\bpp {q0-q1}, [a3 :128], v2 subs v1, v1, #64 >> \log2Bpp vst1.\bpp {q0-q1}, [v3 :128], v2 bhs 3b /* Trailing pixels */ 4: movs v1, v1, lsl #27 + \log2Bpp bcc 5f vst1.\bpp {q0-q1}, [a3 :128]! 5: bpl 6f vst1.\bpp {q0}, [a3 :128]! 6: movs v1, v1, lsl #2 vstmcs a3!, {d0} vstmmi a3!, {s0} .if bpp <= 16 movs v1, v1, lsl #2 strcsh ip, [a3], #2 .if bpp == 8 strmib ip, [a3], #1 .endif .endif subs a2, a2, #1 add a3, a3, a4, lsl #\log2Bpp bhi 1b pop {v1-v3,pc} /* Short-row case */ 51: movs v1, a1 .if bpp == 8 tst a3, #3 beq 53f 52: subs v1, v1, #1 blo 57f strb ip, [a3], #1 tst a3, #3 bne 52b .elseif bpp == 16 tstne a3, #2 subne v1, v1, #1 strneh ip, [a3], #2 .endif 53: cmp v1, #32 >> \log2Bpp bcc 54f vst1.\bpp {q0-q1}, [a3]! sub v1, v1, #32 >> \log2Bpp /* Trailing pixels */ 54: movs v1, v1, lsl #27 + \log2Bpp bcc 55f vst1.\bpp {q0-q1}, [a3]! 55: bpl 56f vst1.\bpp {q0}, [a3]! 56: movs v1, v1, lsl #2 vstmcs a3!, {d0} vstmmi a3!, {s0} .if bpp <= 16 movs v1, v1, lsl #2 strcsh ip, [a3], #2 .if bpp == 8 strmib ip, [a3], #1 .endif .endif subs a2, a2, #1 add a3, a3, a4, lsl #\log2Bpp bhi 51b 57: pop {v1-v3,pc} .endfunc .endm generate_fillrect_function FillRect32ARMNEONAsm, 32, 2 generate_fillrect_function FillRect16ARMNEONAsm, 16, 1 generate_fillrect_function FillRect8ARMNEONAsm, 8, 0 /******************************************************************************/ .macro RGBtoRGBPixelAlpha_process_pixblock_head vmvn d30, d3 /* get inverted source alpha */ vmov d31, d7 /* dest alpha is always unchanged */ vmull.u8 q14, d0, d3 vmlal.u8 q14, d4, d30 vmull.u8 q0, d1, d3 vmlal.u8 q0, d5, d30 vmull.u8 q1, d2, d3 vmlal.u8 q1, d6, d30 vrshr.u16 q2, q14, #8 vrshr.u16 q3, q0, #8 vraddhn.u16 d28, q14, q2 vrshr.u16 q2, q1, #8 vraddhn.u16 d29, q0, q3 vraddhn.u16 d30, q1, q2 .endm .macro RGBtoRGBPixelAlpha_process_pixblock_tail /* nothing */ .endm .macro RGBtoRGBPixelAlpha_process_pixblock_tail_head vld4.8 {d0-d3}, [SRC]! PF add PF_X, PF_X, #8 vst4.8 {d28-d31}, [DST_W :128]! PF tst PF_CTL, #0xF vld4.8 {d4-d7}, [DST_R :128]! PF addne PF_X, PF_X, #8 vmvn d30, d3 /* get inverted source alpha */ vmov d31, d7 /* dest alpha is always unchanged */ vmull.u8 q14, d0, d3 PF subne PF_CTL, PF_CTL, #1 vmlal.u8 q14, d4, d30 PF cmp PF_X, ORIG_W vmull.u8 q0, d1, d3 PF pld, [PF_SRC, PF_X, lsl #src_bpp_shift] vmlal.u8 q0, d5, d30 PF pld, [PF_DST, PF_X, lsl #dst_bpp_shift] vmull.u8 q1, d2, d3 PF subge PF_X, PF_X, ORIG_W vmlal.u8 q1, d6, d30 PF subges PF_CTL, PF_CTL, #0x10 vrshr.u16 q2, q14, #8 PF ldrgeb DUMMY, [PF_SRC, SRC_STRIDE, lsl #src_bpp_shift]! vrshr.u16 q3, q0, #8 PF ldrgeb DUMMY, [PF_DST, DST_STRIDE, lsl #dst_bpp_shift]! vraddhn.u16 d28, q14, q2 vrshr.u16 q2, q1, #8 vraddhn.u16 d29, q0, q3 vraddhn.u16 d30, q1, q2 .endm generate_composite_function \ BlitRGBtoRGBPixelAlphaARMNEONAsm, 32, 0, 32, \ FLAG_DST_READWRITE | FLAG_DEINTERLEAVE_32BPP, \ 8, /* number of pixels, processed in a single block */ \ 5, /* prefetch distance */ \ default_init, \ default_cleanup, \ RGBtoRGBPixelAlpha_process_pixblock_head, \ RGBtoRGBPixelAlpha_process_pixblock_tail, \ RGBtoRGBPixelAlpha_process_pixblock_tail_head /******************************************************************************/ .macro ARGBto565PixelAlpha_process_pixblock_head vmvn d6, d3 vshr.u8 d1, #2 vshr.u8 d3, #3 vshr.u8 d0, #3 vshrn.u16 d7, q2, #3 vshrn.u16 d25, q2, #8 vbic.i16 q2, #0xe0 vshr.u8 d6, #3 vshr.u8 d7, #2 vshr.u8 d2, #3 vmovn.u16 d24, q2 vshr.u8 d25, #3 vmull.u8 q13, d1, d3 vmlal.u8 q13, d7, d6 vmull.u8 q14, d0, d3 vmlal.u8 q14, d24, d6 vmull.u8 q15, d2, d3 vmlal.u8 q15, d25, d6 .endm .macro ARGBto565PixelAlpha_process_pixblock_tail vsra.u16 q13, #5 vsra.u16 q14, #5 vsra.u16 q15, #5 vrshr.u16 q13, #5 vrshr.u16 q14, #5 vrshr.u16 q15, #5 vsli.u16 q14, q13, #5 vsli.u16 q14, q15, #11 .endm .macro ARGBto565PixelAlpha_process_pixblock_tail_head vld4.8 {d0-d3}, [SRC]! PF add PF_X, PF_X, #8 vsra.u16 q13, #5 PF tst PF_CTL, #0xF vsra.u16 q14, #5 PF addne PF_X, PF_X, #8 vsra.u16 q15, #5 PF subne PF_CTL, PF_CTL, #1 vrshr.u16 q13, #5 PF cmp PF_X, ORIG_W vrshr.u16 q14, #5 PF pld, [PF_SRC, PF_X, lsl #src_bpp_shift] vrshr.u16 q15, #5 PF pld, [PF_DST, PF_X, lsl #dst_bpp_shift] vld1.8 {d4-d5}, [DST_R]! PF subge PF_X, PF_X, ORIG_W vsli.u16 q14, q13, #5 PF subges PF_CTL, PF_CTL, #0x10 vsli.u16 q14, q15, #11 PF ldrgeb DUMMY, [PF_SRC, SRC_STRIDE, lsl #src_bpp_shift]! vst1.8 {q14}, [DST_W :128]! vmvn d6, d3 vshr.u8 d1, #2 vshr.u8 d3, #3 vshr.u8 d0, #3 vshrn.u16 d7, q2, #3 vshrn.u16 d25, q2, #8 vbic.i16 q2, #0xe0 PF ldrgeb DUMMY, [PF_DST, DST_STRIDE, lsl #dst_bpp_shift]! vshr.u8 d6, #3 vshr.u8 d7, #2 vshr.u8 d2, #3 vmovn.u16 d24, q2 vshr.u8 d25, #3 vmull.u8 q13, d1, d3 vmlal.u8 q13, d7, d6 vmull.u8 q14, d0, d3 vmlal.u8 q14, d24, d6 vmull.u8 q15, d2, d3 vmlal.u8 q15, d25, d6 .endm generate_composite_function \ BlitARGBto565PixelAlphaARMNEONAsm, 32, 0, 16, \ FLAG_DST_READWRITE | FLAG_DEINTERLEAVE_32BPP, \ 8, /* number of pixels, processed in a single block */ \ 6, /* prefetch distance */ \ default_init, \ default_cleanup, \ ARGBto565PixelAlpha_process_pixblock_head, \ ARGBto565PixelAlpha_process_pixblock_tail, \ ARGBto565PixelAlpha_process_pixblock_tail_head
YifuLiu/AliOS-Things
components/SDL2/src/video/arm/pixman-arm-neon-asm.S
Motorola 68K Assembly
apache-2.0
12,847
/* * Copyright © 2009 Nokia Corporation * * 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 (including the next * paragraph) 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. * * Author: Siarhei Siamashka (siarhei.siamashka@nokia.com) */ /* * This file contains a macro ('generate_composite_function') which can * construct 2D image processing functions, based on a common template. * Any combinations of source, destination and mask images with 8bpp, * 16bpp, 24bpp, 32bpp color formats are supported. * * This macro takes care of: * - handling of leading and trailing unaligned pixels * - doing most of the work related to L2 cache preload * - encourages the use of software pipelining for better instructions * scheduling * * The user of this macro has to provide some configuration parameters * (bit depths for the images, prefetch distance, etc.) and a set of * macros, which should implement basic code chunks responsible for * pixels processing. See 'pixman-arm-neon-asm.S' file for the usage * examples. * * TODO: * - try overlapped pixel method (from Ian Rickards) when processing * exactly two blocks of pixels * - maybe add an option to do reverse scanline processing */ /* * Bit flags for 'generate_composite_function' macro which are used * to tune generated functions behavior. */ .set FLAG_DST_WRITEONLY, 0 .set FLAG_DST_READWRITE, 1 .set FLAG_DEINTERLEAVE_32BPP, 2 /* * Offset in stack where mask and source pointer/stride can be accessed * from 'init' macro. This is useful for doing special handling for solid mask. */ .set ARGS_STACK_OFFSET, 40 /* * Constants for selecting preferable prefetch type. */ .set PREFETCH_TYPE_NONE, 0 /* No prefetch at all */ .set PREFETCH_TYPE_SIMPLE, 1 /* A simple, fixed-distance-ahead prefetch */ .set PREFETCH_TYPE_ADVANCED, 2 /* Advanced fine-grained prefetch */ /* * Definitions of supplementary pixld/pixst macros (for partial load/store of * pixel data). */ .macro pixldst1 op, elem_size, reg1, mem_operand, abits .if abits > 0 op&.&elem_size {d&reg1}, [&mem_operand&, :&abits&]! .else op&.&elem_size {d&reg1}, [&mem_operand&]! .endif .endm .macro pixldst2 op, elem_size, reg1, reg2, mem_operand, abits .if abits > 0 op&.&elem_size {d&reg1, d&reg2}, [&mem_operand&, :&abits&]! .else op&.&elem_size {d&reg1, d&reg2}, [&mem_operand&]! .endif .endm .macro pixldst4 op, elem_size, reg1, reg2, reg3, reg4, mem_operand, abits .if abits > 0 op&.&elem_size {d&reg1, d&reg2, d&reg3, d&reg4}, [&mem_operand&, :&abits&]! .else op&.&elem_size {d&reg1, d&reg2, d&reg3, d&reg4}, [&mem_operand&]! .endif .endm .macro pixldst0 op, elem_size, reg1, idx, mem_operand, abits op&.&elem_size {d&reg1[idx]}, [&mem_operand&]! .endm .macro pixldst3 op, elem_size, reg1, reg2, reg3, mem_operand op&.&elem_size {d&reg1, d&reg2, d&reg3}, [&mem_operand&]! .endm .macro pixldst30 op, elem_size, reg1, reg2, reg3, idx, mem_operand op&.&elem_size {d&reg1[idx], d&reg2[idx], d&reg3[idx]}, [&mem_operand&]! .endm .macro pixldst numbytes, op, elem_size, basereg, mem_operand, abits .if numbytes == 32 pixldst4 op, elem_size, %(basereg+4), %(basereg+5), \ %(basereg+6), %(basereg+7), mem_operand, abits .elseif numbytes == 16 pixldst2 op, elem_size, %(basereg+2), %(basereg+3), mem_operand, abits .elseif numbytes == 8 pixldst1 op, elem_size, %(basereg+1), mem_operand, abits .elseif numbytes == 4 .if !RESPECT_STRICT_ALIGNMENT || (elem_size == 32) pixldst0 op, 32, %(basereg+0), 1, mem_operand, abits .elseif elem_size == 16 pixldst0 op, 16, %(basereg+0), 2, mem_operand, abits pixldst0 op, 16, %(basereg+0), 3, mem_operand, abits .else pixldst0 op, 8, %(basereg+0), 4, mem_operand, abits pixldst0 op, 8, %(basereg+0), 5, mem_operand, abits pixldst0 op, 8, %(basereg+0), 6, mem_operand, abits pixldst0 op, 8, %(basereg+0), 7, mem_operand, abits .endif .elseif numbytes == 2 .if !RESPECT_STRICT_ALIGNMENT || (elem_size == 16) pixldst0 op, 16, %(basereg+0), 1, mem_operand, abits .else pixldst0 op, 8, %(basereg+0), 2, mem_operand, abits pixldst0 op, 8, %(basereg+0), 3, mem_operand, abits .endif .elseif numbytes == 1 pixldst0 op, 8, %(basereg+0), 1, mem_operand, abits .else .error "unsupported size: numbytes" .endif .endm .macro pixld numpix, bpp, basereg, mem_operand, abits=0 .if bpp > 0 .if (bpp == 32) && (numpix == 8) && (DEINTERLEAVE_32BPP_ENABLED != 0) pixldst4 vld4, 8, %(basereg+4), %(basereg+5), \ %(basereg+6), %(basereg+7), mem_operand, abits .elseif (bpp == 24) && (numpix == 8) pixldst3 vld3, 8, %(basereg+3), %(basereg+4), %(basereg+5), mem_operand .elseif (bpp == 24) && (numpix == 4) pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 4, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 5, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 6, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 7, mem_operand .elseif (bpp == 24) && (numpix == 2) pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 2, mem_operand pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 3, mem_operand .elseif (bpp == 24) && (numpix == 1) pixldst30 vld3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 1, mem_operand .else pixldst %(numpix * bpp / 8), vld1, %(bpp), basereg, mem_operand, abits .endif .endif .endm .macro pixst numpix, bpp, basereg, mem_operand, abits=0 .if bpp > 0 .if (bpp == 32) && (numpix == 8) && (DEINTERLEAVE_32BPP_ENABLED != 0) pixldst4 vst4, 8, %(basereg+4), %(basereg+5), \ %(basereg+6), %(basereg+7), mem_operand, abits .elseif (bpp == 24) && (numpix == 8) pixldst3 vst3, 8, %(basereg+3), %(basereg+4), %(basereg+5), mem_operand .elseif (bpp == 24) && (numpix == 4) pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 4, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 5, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 6, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 7, mem_operand .elseif (bpp == 24) && (numpix == 2) pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 2, mem_operand pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 3, mem_operand .elseif (bpp == 24) && (numpix == 1) pixldst30 vst3, 8, %(basereg+0), %(basereg+1), %(basereg+2), 1, mem_operand .else pixldst %(numpix * bpp / 8), vst1, %(bpp), basereg, mem_operand, abits .endif .endif .endm .macro pixld_a numpix, bpp, basereg, mem_operand .if (bpp * numpix) <= 128 pixld numpix, bpp, basereg, mem_operand, %(bpp * numpix) .else pixld numpix, bpp, basereg, mem_operand, 128 .endif .endm .macro pixst_a numpix, bpp, basereg, mem_operand .if (bpp * numpix) <= 128 pixst numpix, bpp, basereg, mem_operand, %(bpp * numpix) .else pixst numpix, bpp, basereg, mem_operand, 128 .endif .endm /* * Pixel fetcher for nearest scaling (needs TMP1, TMP2, VX, UNIT_X register * aliases to be defined) */ .macro pixld1_s elem_size, reg1, mem_operand .if elem_size == 16 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #1 mov TMP2, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP2, mem_operand, TMP2, asl #1 vld1.16 {d&reg1&[0]}, [TMP1, :16] mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #1 vld1.16 {d&reg1&[1]}, [TMP2, :16] mov TMP2, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP2, mem_operand, TMP2, asl #1 vld1.16 {d&reg1&[2]}, [TMP1, :16] vld1.16 {d&reg1&[3]}, [TMP2, :16] .elseif elem_size == 32 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #2 mov TMP2, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP2, mem_operand, TMP2, asl #2 vld1.32 {d&reg1&[0]}, [TMP1, :32] vld1.32 {d&reg1&[1]}, [TMP2, :32] .else .error "unsupported" .endif .endm .macro pixld2_s elem_size, reg1, reg2, mem_operand .if 0 /* elem_size == 32 */ mov TMP1, VX, asr #16 add VX, VX, UNIT_X, asl #1 add TMP1, mem_operand, TMP1, asl #2 mov TMP2, VX, asr #16 sub VX, VX, UNIT_X add TMP2, mem_operand, TMP2, asl #2 vld1.32 {d&reg1&[0]}, [TMP1, :32] mov TMP1, VX, asr #16 add VX, VX, UNIT_X, asl #1 add TMP1, mem_operand, TMP1, asl #2 vld1.32 {d&reg2&[0]}, [TMP2, :32] mov TMP2, VX, asr #16 add VX, VX, UNIT_X add TMP2, mem_operand, TMP2, asl #2 vld1.32 {d&reg1&[1]}, [TMP1, :32] vld1.32 {d&reg2&[1]}, [TMP2, :32] .else pixld1_s elem_size, reg1, mem_operand pixld1_s elem_size, reg2, mem_operand .endif .endm .macro pixld0_s elem_size, reg1, idx, mem_operand .if elem_size == 16 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #1 vld1.16 {d&reg1&[idx]}, [TMP1, :16] .elseif elem_size == 32 mov TMP1, VX, asr #16 adds VX, VX, UNIT_X 5: subpls VX, VX, SRC_WIDTH_FIXED bpl 5b add TMP1, mem_operand, TMP1, asl #2 vld1.32 {d&reg1&[idx]}, [TMP1, :32] .endif .endm .macro pixld_s_internal numbytes, elem_size, basereg, mem_operand .if numbytes == 32 pixld2_s elem_size, %(basereg+4), %(basereg+5), mem_operand pixld2_s elem_size, %(basereg+6), %(basereg+7), mem_operand pixdeinterleave elem_size, %(basereg+4) .elseif numbytes == 16 pixld2_s elem_size, %(basereg+2), %(basereg+3), mem_operand .elseif numbytes == 8 pixld1_s elem_size, %(basereg+1), mem_operand .elseif numbytes == 4 .if elem_size == 32 pixld0_s elem_size, %(basereg+0), 1, mem_operand .elseif elem_size == 16 pixld0_s elem_size, %(basereg+0), 2, mem_operand pixld0_s elem_size, %(basereg+0), 3, mem_operand .else pixld0_s elem_size, %(basereg+0), 4, mem_operand pixld0_s elem_size, %(basereg+0), 5, mem_operand pixld0_s elem_size, %(basereg+0), 6, mem_operand pixld0_s elem_size, %(basereg+0), 7, mem_operand .endif .elseif numbytes == 2 .if elem_size == 16 pixld0_s elem_size, %(basereg+0), 1, mem_operand .else pixld0_s elem_size, %(basereg+0), 2, mem_operand pixld0_s elem_size, %(basereg+0), 3, mem_operand .endif .elseif numbytes == 1 pixld0_s elem_size, %(basereg+0), 1, mem_operand .else .error "unsupported size: numbytes" .endif .endm .macro pixld_s numpix, bpp, basereg, mem_operand .if bpp > 0 pixld_s_internal %(numpix * bpp / 8), %(bpp), basereg, mem_operand .endif .endm .macro vuzp8 reg1, reg2 vuzp.8 d&reg1, d&reg2 .endm .macro vzip8 reg1, reg2 vzip.8 d&reg1, d&reg2 .endm /* deinterleave B, G, R, A channels for eight 32bpp pixels in 4 registers */ .macro pixdeinterleave bpp, basereg .if (bpp == 32) && (DEINTERLEAVE_32BPP_ENABLED != 0) vuzp8 %(basereg+0), %(basereg+1) vuzp8 %(basereg+2), %(basereg+3) vuzp8 %(basereg+1), %(basereg+3) vuzp8 %(basereg+0), %(basereg+2) .endif .endm /* interleave B, G, R, A channels for eight 32bpp pixels in 4 registers */ .macro pixinterleave bpp, basereg .if (bpp == 32) && (DEINTERLEAVE_32BPP_ENABLED != 0) vzip8 %(basereg+0), %(basereg+2) vzip8 %(basereg+1), %(basereg+3) vzip8 %(basereg+2), %(basereg+3) vzip8 %(basereg+0), %(basereg+1) .endif .endm /* * This is a macro for implementing cache preload. The main idea is that * cache preload logic is mostly independent from the rest of pixels * processing code. It starts at the top left pixel and moves forward * across pixels and can jump across scanlines. Prefetch distance is * handled in an 'incremental' way: it starts from 0 and advances to the * optimal distance over time. After reaching optimal prefetch distance, * it is kept constant. There are some checks which prevent prefetching * unneeded pixel lines below the image (but it still can prefetch a bit * more data on the right side of the image - not a big issue and may * be actually helpful when rendering text glyphs). Additional trick is * the use of LDR instruction for prefetch instead of PLD when moving to * the next line, the point is that we have a high chance of getting TLB * miss in this case, and PLD would be useless. * * This sounds like it may introduce a noticeable overhead (when working with * fully cached data). But in reality, due to having a separate pipeline and * instruction queue for NEON unit in ARM Cortex-A8, normal ARM code can * execute simultaneously with NEON and be completely shadowed by it. Thus * we get no performance overhead at all (*). This looks like a very nice * feature of Cortex-A8, if used wisely. We don't have a hardware prefetcher, * but still can implement some rather advanced prefetch logic in software * for almost zero cost! * * (*) The overhead of the prefetcher is visible when running some trivial * pixels processing like simple copy. Anyway, having prefetch is a must * when working with the graphics data. */ .macro PF a, x:vararg .if (PREFETCH_TYPE_CURRENT == PREFETCH_TYPE_ADVANCED) a x .endif .endm .macro cache_preload std_increment, boost_increment .if (src_bpp_shift >= 0) || (dst_r_bpp != 0) || (mask_bpp_shift >= 0) .if regs_shortage PF ldr ORIG_W, [sp] /* If we are short on regs, ORIG_W is kept on stack */ .endif .if std_increment != 0 PF add PF_X, PF_X, #std_increment .endif PF tst PF_CTL, #0xF PF addne PF_X, PF_X, #boost_increment PF subne PF_CTL, PF_CTL, #1 PF cmp PF_X, ORIG_W .if src_bpp_shift >= 0 PF pld, [PF_SRC, PF_X, lsl #src_bpp_shift] .endif .if dst_r_bpp != 0 PF pld, [PF_DST, PF_X, lsl #dst_bpp_shift] .endif .if mask_bpp_shift >= 0 PF pld, [PF_MASK, PF_X, lsl #mask_bpp_shift] .endif PF subge PF_X, PF_X, ORIG_W PF subges PF_CTL, PF_CTL, #0x10 .if src_bpp_shift >= 0 PF ldrgeb DUMMY, [PF_SRC, SRC_STRIDE, lsl #src_bpp_shift]! .endif .if dst_r_bpp != 0 PF ldrgeb DUMMY, [PF_DST, DST_STRIDE, lsl #dst_bpp_shift]! .endif .if mask_bpp_shift >= 0 PF ldrgeb DUMMY, [PF_MASK, MASK_STRIDE, lsl #mask_bpp_shift]! .endif .endif .endm .macro cache_preload_simple .if (PREFETCH_TYPE_CURRENT == PREFETCH_TYPE_SIMPLE) .if src_bpp > 0 pld [SRC, #(PREFETCH_DISTANCE_SIMPLE * src_bpp / 8)] .endif .if dst_r_bpp > 0 pld [DST_R, #(PREFETCH_DISTANCE_SIMPLE * dst_r_bpp / 8)] .endif .if mask_bpp > 0 pld [MASK, #(PREFETCH_DISTANCE_SIMPLE * mask_bpp / 8)] .endif .endif .endm .macro fetch_mask_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK .endm /* * Macro which is used to process leading pixels until destination * pointer is properly aligned (at 16 bytes boundary). When destination * buffer uses 16bpp format, this is unnecessary, or even pointless. */ .macro ensure_destination_ptr_alignment process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head .if dst_w_bpp != 24 tst DST_R, #0xF beq 2f .irp lowbit, 1, 2, 4, 8, 16 local skip1 .if (dst_w_bpp <= (lowbit * 8)) && ((lowbit * 8) < (pixblock_size * dst_w_bpp)) .if lowbit < 16 /* we don't need more than 16-byte alignment */ tst DST_R, #lowbit beq 1f .endif pixld_src (lowbit * 8 / dst_w_bpp), src_bpp, src_basereg, SRC pixld (lowbit * 8 / dst_w_bpp), mask_bpp, mask_basereg, MASK .if dst_r_bpp > 0 pixld_a (lowbit * 8 / dst_r_bpp), dst_r_bpp, dst_r_basereg, DST_R .else add DST_R, DST_R, #lowbit .endif PF add PF_X, PF_X, #(lowbit * 8 / dst_w_bpp) sub W, W, #(lowbit * 8 / dst_w_bpp) 1: .endif .endr pixdeinterleave src_bpp, src_basereg pixdeinterleave mask_bpp, mask_basereg pixdeinterleave dst_r_bpp, dst_r_basereg process_pixblock_head cache_preload 0, pixblock_size cache_preload_simple process_pixblock_tail pixinterleave dst_w_bpp, dst_w_basereg .irp lowbit, 1, 2, 4, 8, 16 .if (dst_w_bpp <= (lowbit * 8)) && ((lowbit * 8) < (pixblock_size * dst_w_bpp)) .if lowbit < 16 /* we don't need more than 16-byte alignment */ tst DST_W, #lowbit beq 1f .endif pixst_a (lowbit * 8 / dst_w_bpp), dst_w_bpp, dst_w_basereg, DST_W 1: .endif .endr .endif 2: .endm /* * Special code for processing up to (pixblock_size - 1) remaining * trailing pixels. As SIMD processing performs operation on * pixblock_size pixels, anything smaller than this has to be loaded * and stored in a special way. Loading and storing of pixel data is * performed in such a way that we fill some 'slots' in the NEON * registers (some slots naturally are unused), then perform compositing * operation as usual. In the end, the data is taken from these 'slots' * and saved to memory. * * cache_preload_flag - allows to suppress prefetch if * set to 0 * dst_aligned_flag - selects whether destination buffer * is aligned */ .macro process_trailing_pixels cache_preload_flag, \ dst_aligned_flag, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head tst W, #(pixblock_size - 1) beq 2f .irp chunk_size, 16, 8, 4, 2, 1 .if pixblock_size > chunk_size tst W, #chunk_size beq 1f pixld_src chunk_size, src_bpp, src_basereg, SRC pixld chunk_size, mask_bpp, mask_basereg, MASK .if dst_aligned_flag != 0 pixld_a chunk_size, dst_r_bpp, dst_r_basereg, DST_R .else pixld chunk_size, dst_r_bpp, dst_r_basereg, DST_R .endif .if cache_preload_flag != 0 PF add PF_X, PF_X, #chunk_size .endif 1: .endif .endr pixdeinterleave src_bpp, src_basereg pixdeinterleave mask_bpp, mask_basereg pixdeinterleave dst_r_bpp, dst_r_basereg process_pixblock_head .if cache_preload_flag != 0 cache_preload 0, pixblock_size cache_preload_simple .endif process_pixblock_tail pixinterleave dst_w_bpp, dst_w_basereg .irp chunk_size, 16, 8, 4, 2, 1 .if pixblock_size > chunk_size tst W, #chunk_size beq 1f .if dst_aligned_flag != 0 pixst_a chunk_size, dst_w_bpp, dst_w_basereg, DST_W .else pixst chunk_size, dst_w_bpp, dst_w_basereg, DST_W .endif 1: .endif .endr 2: .endm /* * Macro, which performs all the needed operations to switch to the next * scanline and start the next loop iteration unless all the scanlines * are already processed. */ .macro advance_to_next_scanline start_of_loop_label .if regs_shortage ldrd W, [sp] /* load W and H (width and height) from stack */ .else mov W, ORIG_W .endif add DST_W, DST_W, DST_STRIDE, lsl #dst_bpp_shift .if src_bpp != 0 add SRC, SRC, SRC_STRIDE, lsl #src_bpp_shift .endif .if mask_bpp != 0 add MASK, MASK, MASK_STRIDE, lsl #mask_bpp_shift .endif .if (dst_w_bpp != 24) sub DST_W, DST_W, W, lsl #dst_bpp_shift .endif .if (src_bpp != 24) && (src_bpp != 0) sub SRC, SRC, W, lsl #src_bpp_shift .endif .if (mask_bpp != 24) && (mask_bpp != 0) sub MASK, MASK, W, lsl #mask_bpp_shift .endif subs H, H, #1 mov DST_R, DST_W .if regs_shortage str H, [sp, #4] /* save updated height to stack */ .endif bge start_of_loop_label .endm /* * Registers are allocated in the following way by default: * d0, d1, d2, d3 - reserved for loading source pixel data * d4, d5, d6, d7 - reserved for loading destination pixel data * d24, d25, d26, d27 - reserved for loading mask pixel data * d28, d29, d30, d31 - final destination pixel data for writeback to memory */ .macro generate_composite_function fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags, \ pixblock_size_, \ prefetch_distance, \ init, \ cleanup, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head, \ dst_w_basereg_ = 28, \ dst_r_basereg_ = 4, \ src_basereg_ = 0, \ mask_basereg_ = 24 pixman_asm_function fname push {r4-r12, lr} /* save all registers */ /* * Select prefetch type for this function. If prefetch distance is * set to 0 or one of the color formats is 24bpp, SIMPLE prefetch * has to be used instead of ADVANCED. */ .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_DEFAULT .if prefetch_distance == 0 .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_NONE .elseif (PREFETCH_TYPE_CURRENT > PREFETCH_TYPE_SIMPLE) && \ ((src_bpp_ == 24) || (mask_bpp_ == 24) || (dst_w_bpp_ == 24)) .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_SIMPLE .endif /* * Make some macro arguments globally visible and accessible * from other macros */ .set src_bpp, src_bpp_ .set mask_bpp, mask_bpp_ .set dst_w_bpp, dst_w_bpp_ .set pixblock_size, pixblock_size_ .set dst_w_basereg, dst_w_basereg_ .set dst_r_basereg, dst_r_basereg_ .set src_basereg, src_basereg_ .set mask_basereg, mask_basereg_ .macro pixld_src x:vararg pixld x .endm .macro fetch_src_pixblock pixld_src pixblock_size, src_bpp, \ (src_basereg - pixblock_size * src_bpp / 64), SRC .endm /* * Assign symbolic names to registers */ W .req r0 /* width (is updated during processing) */ H .req r1 /* height (is updated during processing) */ DST_W .req r2 /* destination buffer pointer for writes */ DST_STRIDE .req r3 /* destination image stride */ SRC .req r4 /* source buffer pointer */ SRC_STRIDE .req r5 /* source image stride */ DST_R .req r6 /* destination buffer pointer for reads */ MASK .req r7 /* mask pointer */ MASK_STRIDE .req r8 /* mask stride */ PF_CTL .req r9 /* combined lines counter and prefetch */ /* distance increment counter */ PF_X .req r10 /* pixel index in a scanline for current */ /* pretetch position */ PF_SRC .req r11 /* pointer to source scanline start */ /* for prefetch purposes */ PF_DST .req r12 /* pointer to destination scanline start */ /* for prefetch purposes */ PF_MASK .req r14 /* pointer to mask scanline start */ /* for prefetch purposes */ /* * Check whether we have enough registers for all the local variables. * If we don't have enough registers, original width and height are * kept on top of stack (and 'regs_shortage' variable is set to indicate * this for the rest of code). Even if there are enough registers, the * allocation scheme may be a bit different depending on whether source * or mask is not used. */ .if (PREFETCH_TYPE_CURRENT < PREFETCH_TYPE_ADVANCED) ORIG_W .req r10 /* saved original width */ DUMMY .req r12 /* temporary register */ .set regs_shortage, 0 .elseif mask_bpp == 0 ORIG_W .req r7 /* saved original width */ DUMMY .req r8 /* temporary register */ .set regs_shortage, 0 .elseif src_bpp == 0 ORIG_W .req r4 /* saved original width */ DUMMY .req r5 /* temporary register */ .set regs_shortage, 0 .else ORIG_W .req r1 /* saved original width */ DUMMY .req r1 /* temporary register */ .set regs_shortage, 1 .endif .set mask_bpp_shift, -1 .if src_bpp == 32 .set src_bpp_shift, 2 .elseif src_bpp == 24 .set src_bpp_shift, 0 .elseif src_bpp == 16 .set src_bpp_shift, 1 .elseif src_bpp == 8 .set src_bpp_shift, 0 .elseif src_bpp == 0 .set src_bpp_shift, -1 .else .error "requested src bpp (src_bpp) is not supported" .endif .if mask_bpp == 32 .set mask_bpp_shift, 2 .elseif mask_bpp == 24 .set mask_bpp_shift, 0 .elseif mask_bpp == 8 .set mask_bpp_shift, 0 .elseif mask_bpp == 0 .set mask_bpp_shift, -1 .else .error "requested mask bpp (mask_bpp) is not supported" .endif .if dst_w_bpp == 32 .set dst_bpp_shift, 2 .elseif dst_w_bpp == 24 .set dst_bpp_shift, 0 .elseif dst_w_bpp == 16 .set dst_bpp_shift, 1 .elseif dst_w_bpp == 8 .set dst_bpp_shift, 0 .else .error "requested dst bpp (dst_w_bpp) is not supported" .endif .if (((flags) & FLAG_DST_READWRITE) != 0) .set dst_r_bpp, dst_w_bpp .else .set dst_r_bpp, 0 .endif .if (((flags) & FLAG_DEINTERLEAVE_32BPP) != 0) .set DEINTERLEAVE_32BPP_ENABLED, 1 .else .set DEINTERLEAVE_32BPP_ENABLED, 0 .endif .if prefetch_distance < 0 || prefetch_distance > 15 .error "invalid prefetch distance (prefetch_distance)" .endif .if src_bpp > 0 ldr SRC, [sp, #40] .endif .if mask_bpp > 0 ldr MASK, [sp, #48] .endif PF mov PF_X, #0 .if src_bpp > 0 ldr SRC_STRIDE, [sp, #44] .endif .if mask_bpp > 0 ldr MASK_STRIDE, [sp, #52] .endif mov DST_R, DST_W .if src_bpp == 24 sub SRC_STRIDE, SRC_STRIDE, W sub SRC_STRIDE, SRC_STRIDE, W, lsl #1 .endif .if mask_bpp == 24 sub MASK_STRIDE, MASK_STRIDE, W sub MASK_STRIDE, MASK_STRIDE, W, lsl #1 .endif .if dst_w_bpp == 24 sub DST_STRIDE, DST_STRIDE, W sub DST_STRIDE, DST_STRIDE, W, lsl #1 .endif /* * Setup advanced prefetcher initial state */ PF mov PF_SRC, SRC PF mov PF_DST, DST_R PF mov PF_MASK, MASK /* PF_CTL = prefetch_distance | ((h - 1) << 4) */ PF mov PF_CTL, H, lsl #4 PF add PF_CTL, #(prefetch_distance - 0x10) init .if regs_shortage push {r0, r1} .endif subs H, H, #1 .if regs_shortage str H, [sp, #4] /* save updated height to stack */ .else mov ORIG_W, W .endif blt 9f cmp W, #(pixblock_size * 2) blt 8f /* * This is the start of the pipelined loop, which if optimized for * long scanlines */ 0: ensure_destination_ptr_alignment process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head /* Implement "head (tail_head) ... (tail_head) tail" loop pattern */ pixld_a pixblock_size, dst_r_bpp, \ (dst_r_basereg - pixblock_size * dst_r_bpp / 64), DST_R fetch_src_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK PF add PF_X, PF_X, #pixblock_size process_pixblock_head cache_preload 0, pixblock_size cache_preload_simple subs W, W, #(pixblock_size * 2) blt 2f 1: process_pixblock_tail_head cache_preload_simple subs W, W, #pixblock_size bge 1b 2: process_pixblock_tail pixst_a pixblock_size, dst_w_bpp, \ (dst_w_basereg - pixblock_size * dst_w_bpp / 64), DST_W /* Process the remaining trailing pixels in the scanline */ process_trailing_pixels 1, 1, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head advance_to_next_scanline 0b .if regs_shortage pop {r0, r1} .endif cleanup pop {r4-r12, pc} /* exit */ /* * This is the start of the loop, designed to process images with small width * (less than pixblock_size * 2 pixels). In this case neither pipelining * nor prefetch are used. */ 8: /* Process exactly pixblock_size pixels if needed */ tst W, #pixblock_size beq 1f pixld pixblock_size, dst_r_bpp, \ (dst_r_basereg - pixblock_size * dst_r_bpp / 64), DST_R fetch_src_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK process_pixblock_head process_pixblock_tail pixst pixblock_size, dst_w_bpp, \ (dst_w_basereg - pixblock_size * dst_w_bpp / 64), DST_W 1: /* Process the remaining trailing pixels in the scanline */ process_trailing_pixels 0, 0, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head advance_to_next_scanline 8b 9: .if regs_shortage pop {r0, r1} .endif cleanup pop {r4-r12, pc} /* exit */ .purgem fetch_src_pixblock .purgem pixld_src .unreq SRC .unreq MASK .unreq DST_R .unreq DST_W .unreq ORIG_W .unreq W .unreq H .unreq SRC_STRIDE .unreq DST_STRIDE .unreq MASK_STRIDE .unreq PF_CTL .unreq PF_X .unreq PF_SRC .unreq PF_DST .unreq PF_MASK .unreq DUMMY .endfunc .endm /* * A simplified variant of function generation template for a single * scanline processing (for implementing pixman combine functions) */ .macro generate_composite_function_scanline use_nearest_scaling, \ fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags, \ pixblock_size_, \ init, \ cleanup, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head, \ dst_w_basereg_ = 28, \ dst_r_basereg_ = 4, \ src_basereg_ = 0, \ mask_basereg_ = 24 pixman_asm_function fname .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_NONE /* * Make some macro arguments globally visible and accessible * from other macros */ .set src_bpp, src_bpp_ .set mask_bpp, mask_bpp_ .set dst_w_bpp, dst_w_bpp_ .set pixblock_size, pixblock_size_ .set dst_w_basereg, dst_w_basereg_ .set dst_r_basereg, dst_r_basereg_ .set src_basereg, src_basereg_ .set mask_basereg, mask_basereg_ .if use_nearest_scaling != 0 /* * Assign symbolic names to registers for nearest scaling */ W .req r0 DST_W .req r1 SRC .req r2 VX .req r3 UNIT_X .req ip MASK .req lr TMP1 .req r4 TMP2 .req r5 DST_R .req r6 SRC_WIDTH_FIXED .req r7 .macro pixld_src x:vararg pixld_s x .endm ldr UNIT_X, [sp] push {r4-r8, lr} ldr SRC_WIDTH_FIXED, [sp, #(24 + 4)] .if mask_bpp != 0 ldr MASK, [sp, #(24 + 8)] .endif .else /* * Assign symbolic names to registers */ W .req r0 /* width (is updated during processing) */ DST_W .req r1 /* destination buffer pointer for writes */ SRC .req r2 /* source buffer pointer */ DST_R .req ip /* destination buffer pointer for reads */ MASK .req r3 /* mask pointer */ .macro pixld_src x:vararg pixld x .endm .endif .if (((flags) & FLAG_DST_READWRITE) != 0) .set dst_r_bpp, dst_w_bpp .else .set dst_r_bpp, 0 .endif .if (((flags) & FLAG_DEINTERLEAVE_32BPP) != 0) .set DEINTERLEAVE_32BPP_ENABLED, 1 .else .set DEINTERLEAVE_32BPP_ENABLED, 0 .endif .macro fetch_src_pixblock pixld_src pixblock_size, src_bpp, \ (src_basereg - pixblock_size * src_bpp / 64), SRC .endm init mov DST_R, DST_W cmp W, #pixblock_size blt 8f ensure_destination_ptr_alignment process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head subs W, W, #pixblock_size blt 7f /* Implement "head (tail_head) ... (tail_head) tail" loop pattern */ pixld_a pixblock_size, dst_r_bpp, \ (dst_r_basereg - pixblock_size * dst_r_bpp / 64), DST_R fetch_src_pixblock pixld pixblock_size, mask_bpp, \ (mask_basereg - pixblock_size * mask_bpp / 64), MASK process_pixblock_head subs W, W, #pixblock_size blt 2f 1: process_pixblock_tail_head subs W, W, #pixblock_size bge 1b 2: process_pixblock_tail pixst_a pixblock_size, dst_w_bpp, \ (dst_w_basereg - pixblock_size * dst_w_bpp / 64), DST_W 7: /* Process the remaining trailing pixels in the scanline (dst aligned) */ process_trailing_pixels 0, 1, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head cleanup .if use_nearest_scaling != 0 pop {r4-r8, pc} /* exit */ .else bx lr /* exit */ .endif 8: /* Process the remaining trailing pixels in the scanline (dst unaligned) */ process_trailing_pixels 0, 0, \ process_pixblock_head, \ process_pixblock_tail, \ process_pixblock_tail_head cleanup .if use_nearest_scaling != 0 pop {r4-r8, pc} /* exit */ .unreq DST_R .unreq SRC .unreq W .unreq VX .unreq UNIT_X .unreq TMP1 .unreq TMP2 .unreq DST_W .unreq MASK .unreq SRC_WIDTH_FIXED .else bx lr /* exit */ .unreq SRC .unreq MASK .unreq DST_R .unreq DST_W .unreq W .endif .purgem fetch_src_pixblock .purgem pixld_src .endfunc .endm .macro generate_composite_function_single_scanline x:vararg generate_composite_function_scanline 0, x .endm .macro generate_composite_function_nearest_scanline x:vararg generate_composite_function_scanline 1, x .endm /* Default prologue/epilogue, nothing special needs to be done */ .macro default_init .endm .macro default_cleanup .endm /* * Prologue/epilogue variant which additionally saves/restores d8-d15 * registers (they need to be saved/restored by callee according to ABI). * This is required if the code needs to use all the NEON registers. */ .macro default_init_need_all_regs vpush {d8-d15} .endm .macro default_cleanup_need_all_regs vpop {d8-d15} .endm /******************************************************************************/ /* * Conversion of 8 r5g6b6 pixels packed in 128-bit register (in) * into a planar a8r8g8b8 format (with a, r, g, b color components * stored into 64-bit registers out_a, out_r, out_g, out_b respectively). * * Warning: the conversion is destructive and the original * value (in) is lost. */ .macro convert_0565_to_8888 in, out_a, out_r, out_g, out_b vshrn.u16 out_r, in, #8 vshrn.u16 out_g, in, #3 vsli.u16 in, in, #5 vmov.u8 out_a, #255 vsri.u8 out_r, out_r, #5 vsri.u8 out_g, out_g, #6 vshrn.u16 out_b, in, #2 .endm .macro convert_0565_to_x888 in, out_r, out_g, out_b vshrn.u16 out_r, in, #8 vshrn.u16 out_g, in, #3 vsli.u16 in, in, #5 vsri.u8 out_r, out_r, #5 vsri.u8 out_g, out_g, #6 vshrn.u16 out_b, in, #2 .endm /* * Conversion from planar a8r8g8b8 format (with a, r, g, b color components * in 64-bit registers in_a, in_r, in_g, in_b respectively) into 8 r5g6b6 * pixels packed in 128-bit register (out). Requires two temporary 128-bit * registers (tmp1, tmp2) */ .macro convert_8888_to_0565 in_r, in_g, in_b, out, tmp1, tmp2 vshll.u8 tmp1, in_g, #8 vshll.u8 out, in_r, #8 vshll.u8 tmp2, in_b, #8 vsri.u16 out, tmp1, #5 vsri.u16 out, tmp2, #11 .endm /* * Conversion of four r5g6b5 pixels (in) to four x8r8g8b8 pixels * returned in (out0, out1) registers pair. Requires one temporary * 64-bit register (tmp). 'out1' and 'in' may overlap, the original * value from 'in' is lost */ .macro convert_four_0565_to_x888_packed in, out0, out1, tmp vshl.u16 out0, in, #5 /* G top 6 bits */ vshl.u16 tmp, in, #11 /* B top 5 bits */ vsri.u16 in, in, #5 /* R is ready in top bits */ vsri.u16 out0, out0, #6 /* G is ready in top bits */ vsri.u16 tmp, tmp, #5 /* B is ready in top bits */ vshr.u16 out1, in, #8 /* R is in place */ vsri.u16 out0, tmp, #8 /* G & B is in place */ vzip.u16 out0, out1 /* everything is in place */ .endm
YifuLiu/AliOS-Things
components/SDL2/src/video/arm/pixman-arm-neon-asm.h
C
apache-2.0
39,728
/* * Copyright (c) 2016 RISC OS Open Ltd * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* Prevent the stack from becoming executable */ #if defined(__linux__) && defined(__ELF__) .section .note.GNU-stack,"",%progbits #endif .text .arch armv6 .object_arch armv4 .arm .altmacro .p2align 2 #include "pixman-arm-asm.h" #include "pixman-arm-simd-asm.h" /* A head macro should do all processing which results in an output of up to * 16 bytes, as far as the final load instruction. The corresponding tail macro * should complete the processing of the up-to-16 bytes. The calling macro will * sometimes choose to insert a preload or a decrement of X between them. * cond ARM condition code for code block * numbytes Number of output bytes that should be generated this time * firstreg First WK register in which to place output * unaligned_src Whether to use non-wordaligned loads of source image * unaligned_mask Whether to use non-wordaligned loads of mask image * preload If outputting 16 bytes causes 64 bytes to be read, whether an extra preload should be output */ /******************************************************************************/ .macro FillRect32_init ldr SRC, [sp, #ARGS_STACK_OFFSET] mov STRIDE_S, SRC mov MASK, SRC mov STRIDE_M, SRC .endm .macro FillRect16_init ldrh SRC, [sp, #ARGS_STACK_OFFSET] orr SRC, SRC, lsl #16 mov STRIDE_S, SRC mov MASK, SRC mov STRIDE_M, SRC .endm .macro FillRect8_init ldrb SRC, [sp, #ARGS_STACK_OFFSET] orr SRC, SRC, lsl #8 orr SRC, SRC, lsl #16 mov STRIDE_S, SRC mov MASK, SRC mov STRIDE_M, SRC .endm .macro FillRect_process_tail cond, numbytes, firstreg WK4 .req SRC WK5 .req STRIDE_S WK6 .req MASK WK7 .req STRIDE_M pixst cond, numbytes, 4, DST .unreq WK4 .unreq WK5 .unreq WK6 .unreq WK7 .endm generate_composite_function \ FillRect32ARMSIMDAsm, 0, 0, 32, \ FLAG_DST_WRITEONLY | FLAG_COND_EXEC | FLAG_PROCESS_PRESERVES_PSR | FLAG_PROCESS_DOES_STORE | FLAG_PROCESS_PRESERVES_SCRATCH \ 0, /* prefetch distance doesn't apply */ \ FillRect32_init \ nop_macro, /* newline */ \ nop_macro /* cleanup */ \ nop_macro /* process head */ \ FillRect_process_tail generate_composite_function \ FillRect16ARMSIMDAsm, 0, 0, 16, \ FLAG_DST_WRITEONLY | FLAG_COND_EXEC | FLAG_PROCESS_PRESERVES_PSR | FLAG_PROCESS_DOES_STORE | FLAG_PROCESS_PRESERVES_SCRATCH \ 0, /* prefetch distance doesn't apply */ \ FillRect16_init \ nop_macro, /* newline */ \ nop_macro /* cleanup */ \ nop_macro /* process head */ \ FillRect_process_tail generate_composite_function \ FillRect8ARMSIMDAsm, 0, 0, 8, \ FLAG_DST_WRITEONLY | FLAG_COND_EXEC | FLAG_PROCESS_PRESERVES_PSR | FLAG_PROCESS_DOES_STORE | FLAG_PROCESS_PRESERVES_SCRATCH \ 0, /* prefetch distance doesn't apply */ \ FillRect8_init \ nop_macro, /* newline */ \ nop_macro /* cleanup */ \ nop_macro /* process head */ \ FillRect_process_tail /******************************************************************************/ /* This differs from the over_8888_8888 routine in Pixman in that the destination * alpha component is always left unchanged, and RGB components are not * premultiplied by alpha. It differs from BlitRGBtoRGBPixelAlpha in that * renormalisation is done by multiplying by 257/256 (with rounding) rather than * simply shifting right by 8 bits - removing the need to special-case alpha=0xff. */ .macro RGBtoRGBPixelAlpha_init line_saved_regs STRIDE_S, ORIG_W mov MASK, #0x80 .endm .macro RGBtoRGBPixelAlpha_1pixel_translucent s, d, tmp0, tmp1, tmp2, tmp3, half uxtb tmp3, s uxtb tmp0, d sub tmp0, tmp3, tmp0 uxtb tmp3, s, ror #16 uxtb tmp1, d, ror #16 sub tmp1, tmp3, tmp1 uxtb tmp3, s, ror #8 mov s, s, lsr #24 uxtb tmp2, d, ror #8 sub tmp2, tmp3, tmp2 smlabb tmp0, tmp0, s, half smlabb tmp1, tmp1, s, half smlabb tmp2, tmp2, s, half add tmp0, tmp0, asr #8 add tmp1, tmp1, asr #8 add tmp2, tmp2, asr #8 pkhbt tmp0, tmp0, tmp1, lsl #16 and tmp2, tmp2, #0xff00 uxtb16 tmp0, tmp0, ror #8 orr tmp0, tmp0, tmp2 uadd8 d, d, tmp0 .endm .macro RGBtoRGBPixelAlpha_1pixel_opaque s, d and d, d, #0xff000000 bic s, s, #0xff000000 orr d, d, s .endm .macro RGBtoRGBPixelAlpha_process_head cond, numbytes, firstreg, unaligned_src, unaligned_mask, preload .if numbytes == 16 ldm SRC!, {WK0, WK1} ldm SRC!, {STRIDE_S, STRIDE_M} ldrd WK2, WK3, [DST], #16 orr SCRATCH, WK0, WK1 and ORIG_W, WK0, WK1 orr SCRATCH, SCRATCH, STRIDE_S and ORIG_W, ORIG_W, STRIDE_S orr SCRATCH, SCRATCH, STRIDE_M and ORIG_W, ORIG_W, STRIDE_M tst SCRATCH, #0xff000000 .elseif numbytes == 8 ldm SRC!, {WK0, WK1} ldm DST!, {WK2, WK3} orr SCRATCH, WK0, WK1 and ORIG_W, WK0, WK1 tst SCRATCH, #0xff000000 .else // numbytes == 4 ldr WK0, [SRC], #4 ldr WK2, [DST], #4 tst WK0, #0xff000000 .endif .endm .macro RGBtoRGBPixelAlpha_process_tail cond, numbytes, firstreg beq 20f @ all transparent .if numbytes == 16 cmp ORIG_W, #0xff000000 bhs 10f @ all opaque RGBtoRGBPixelAlpha_1pixel_translucent WK0, WK2, STRIDE_S, STRIDE_M, SCRATCH, ORIG_W, MASK RGBtoRGBPixelAlpha_1pixel_translucent WK1, WK3, STRIDE_S, STRIDE_M, SCRATCH, ORIG_W, MASK strd WK2, WK3, [DST, #-16] ldrd WK0, WK1, [SRC, #-8] ldrd WK2, WK3, [DST, #-8] RGBtoRGBPixelAlpha_1pixel_translucent WK0, WK2, STRIDE_S, STRIDE_M, SCRATCH, ORIG_W, MASK RGBtoRGBPixelAlpha_1pixel_translucent WK1, WK3, STRIDE_S, STRIDE_M, SCRATCH, ORIG_W, MASK b 19f 10: RGBtoRGBPixelAlpha_1pixel_opaque WK0, WK2 RGBtoRGBPixelAlpha_1pixel_opaque WK1, WK3 strd WK2, WK3, [DST, #-16] ldrd WK0, WK1, [SRC, #-8] ldrd WK2, WK3, [DST, #-8] RGBtoRGBPixelAlpha_1pixel_opaque WK0, WK2 RGBtoRGBPixelAlpha_1pixel_opaque WK1, WK3 19: strd WK2, WK3, [DST, #-8] .elseif numbytes == 8 cmp ORIG_W, #0xff000000 bhs 10f @ all opaque RGBtoRGBPixelAlpha_1pixel_translucent WK0, WK2, STRIDE_S, STRIDE_M, SCRATCH, ORIG_W, MASK RGBtoRGBPixelAlpha_1pixel_translucent WK1, WK3, STRIDE_S, STRIDE_M, SCRATCH, ORIG_W, MASK b 19f 10: RGBtoRGBPixelAlpha_1pixel_opaque WK0, WK2 RGBtoRGBPixelAlpha_1pixel_opaque WK1, WK3 19: strd WK2, WK3, [DST, #-8] .else // numbytes == 4 cmp WK0, #0xff000000 bhs 10f @ opaque RGBtoRGBPixelAlpha_1pixel_translucent WK0, WK2, STRIDE_S, STRIDE_M, SCRATCH, ORIG_W, MASK b 19f 10: RGBtoRGBPixelAlpha_1pixel_opaque WK0, WK2 19: str WK2, [DST, #-4] .endif 20: .endm generate_composite_function \ BlitRGBtoRGBPixelAlphaARMSIMDAsm, 32, 0, 32, \ FLAG_DST_READWRITE | FLAG_BRANCH_OVER | FLAG_PROCESS_CORRUPTS_PSR | FLAG_PROCESS_DOES_STORE | FLAG_SPILL_LINE_VARS | FLAG_PROCESS_CORRUPTS_WK0, \ 2, /* prefetch distance */ \ RGBtoRGBPixelAlpha_init, \ nop_macro, /* newline */ \ nop_macro, /* cleanup */ \ RGBtoRGBPixelAlpha_process_head, \ RGBtoRGBPixelAlpha_process_tail /******************************************************************************/ .macro ARGBto565PixelAlpha_init line_saved_regs STRIDE_D, STRIDE_S, ORIG_W mov MASK, #0x001f mov STRIDE_M, #0x0010 orr MASK, MASK, MASK, lsl #16 orr STRIDE_M, STRIDE_M, STRIDE_M, lsl #16 .endm .macro ARGBto565PixelAlpha_newline mov STRIDE_S, #0x0200 .endm /* On entry: * s1 holds 1 32bpp source pixel * d holds 1 16bpp destination pixel * rbmask, rbhalf, ghalf hold 0x001f001f, 0x00100010, 0x00000200 respectively * other registers are temporaries * On exit: * Constant registers preserved */ .macro ARGBto565PixelAlpha_1pixel_translucent s, d, rbmask, rbhalf, ghalf, alpha, rb, g, misc mov alpha, s, lsr #27 and misc, s, #0xfc00 and g, d, #0x07e0 pkhbt rb, d, d, lsl #5 rsb misc, g, misc, lsr #5 and s, rbmask, s, lsr #3 and rb, rbmask, rb sub s, s, rb smlabb misc, misc, alpha, ghalf mla s, s, alpha, rbhalf add misc, misc, misc, lsl #5 add g, g, misc, asr #10 add s, s, s, lsl #5 and g, g, #0x07e0 add rb, rb, s, asr #10 and rb, rb, rbmask pkhbt rb, rb, rb, lsl #11 orr d, rb, g orr d, d, rb, lsr #16 .endm /* On entry: * s1 holds 1 32bpp source pixel * d holds 1 16bpp destination pixel * rbmask holds 0x001f001f * On exit: * Constant registers preserved */ .macro ARGBto565PixelAlpha_1pixel_opaque s, d, rbmask and d, rbmask, s, lsr #3 and s, s, #0xfc00 orr d, d, d, lsr #5 orr d, d, s, lsr #5 .endm /* On entry: * s1, s2 hold 2 32bpp source pixels * d holds 2 16bpp destination pixels * rbmask, rbhalf, ghalf hold 0x001f001f, 0x00100010, 0x00000200 respectively * other registers are temporaries * On exit: * Constant registers preserved * Blended results have been written through destination pointer */ .macro ARGBto565PixelAlpha_2pixels_translucent s1, s2, d, rbmask, rbhalf, ghalf, alpha, rb, g, misc mov alpha, s1, lsr #27 and misc, s1, #0xfc00 and g, d, #0x07e0 pkhbt rb, d, d, lsl #5 rsb misc, g, misc, lsr #5 and s1, rbmask, s1, lsr #3 and rb, rbmask, rb sub s1, s1, rb smlabb misc, misc, alpha, ghalf mla s1, s1, alpha, rbhalf uxth d, d, ror #16 add misc, misc, misc, lsl #5 mov alpha, s2, lsr #27 add g, g, misc, asr #10 add s1, s1, s1, lsl #5 and g, g, #0x07e0 add rb, rb, s1, asr #10 and rb, rb, rbmask and misc, s2, #0xfc00 pkhbt rb, rb, rb, lsl #11 and s1, d, #0x07e0 pkhbt d, d, d, lsl #5 rsb misc, s1, misc, lsr #5 and s2, rbmask, s2, lsr #3 and d, rbmask, d sub s2, s2, d smlabb misc, misc, alpha, ghalf mla s2, s2, alpha, rbhalf orr alpha, rb, g add misc, misc, misc, lsl #5 orr alpha, alpha, rb, lsr #16 add s1, s1, misc, asr #10 add s2, s2, s2, lsl #5 and s1, s1, #0x07e0 add d, d, s2, asr #10 and d, d, rbmask strh alpha, [DST, #-4] pkhbt d, d, d, lsl #11 orr alpha, d, s1 orr alpha, alpha, d, lsr #16 strh alpha, [DST, #-2] .endm /* On entry: * s1, s2 hold 2 32bpp source pixels * rbmask holds 0x001f001f * other registers are temporaries * On exit: * Constant registers preserved * Blended results have been written through destination pointer */ .macro ARGBto565PixelAlpha_2pixels_opaque s1, s2, d, rbmask, g and g, s1, #0xfc00 and d, rbmask, s1, lsr #3 and s1, rbmask, s2, lsr #3 orr d, d, d, lsr #5 orr d, d, g, lsr #5 and g, s2, #0xfc00 strh d, [DST, #-4] orr s1, s1, s1, lsr #5 orr s1, s1, g, lsr #5 strh s1, [DST, #-2] .endm .macro ARGBto565PixelAlpha_2pixels_head ldrd WK0, WK1, [SRC], #8 ldr WK2, [DST], #4 orr SCRATCH, WK0, WK1 and ORIG_W, WK0, WK1 tst SCRATCH, #0xff000000 .endm .macro ARGBto565PixelAlpha_2pixels_tail beq 20f @ all transparent cmp ORIG_W, #0xff000000 bhs 10f @ all opaque ARGBto565PixelAlpha_2pixels_translucent WK0, WK1, WK2, MASK, STRIDE_M, STRIDE_S, STRIDE_D, WK3, SCRATCH, ORIG_W b 20f 10: ARGBto565PixelAlpha_2pixels_opaque WK0, WK1, WK2, MASK, SCRATCH 20: .endm .macro ARGBto565PixelAlpha_process_head cond, numbytes, firstreg, unaligned_src, unaligned_mask, preload .if numbytes == 16 ARGBto565PixelAlpha_2pixels_head ARGBto565PixelAlpha_2pixels_tail ARGBto565PixelAlpha_2pixels_head ARGBto565PixelAlpha_2pixels_tail .endif .if numbytes >= 8 ARGBto565PixelAlpha_2pixels_head ARGBto565PixelAlpha_2pixels_tail .endif .if numbytes >= 4 ARGBto565PixelAlpha_2pixels_head .else // numbytes == 2 ldr WK0, [SRC], #4 ldrh WK2, [DST], #2 tst WK0, #0xff000000 .endif .endm .macro ARGBto565PixelAlpha_process_tail cond, numbytes, firstreg .if numbytes >= 4 ARGBto565PixelAlpha_2pixels_tail .else // numbytes == 2 beq 20f @ all transparent cmp WK0, #0xff000000 bhs 10f @ opaque ARGBto565PixelAlpha_1pixel_translucent WK0, WK2, MASK, STRIDE_M, STRIDE_S, STRIDE_D, WK3, SCRATCH, ORIG_W b 19f 10: ARGBto565PixelAlpha_1pixel_opaque WK0, WK2, MASK 19: strh WK2, [DST, #-2] 20: .endif .endm generate_composite_function \ BlitARGBto565PixelAlphaARMSIMDAsm, 32, 0, 16, \ FLAG_DST_READWRITE | FLAG_BRANCH_OVER | FLAG_PROCESS_CORRUPTS_PSR | FLAG_PROCESS_DOES_STORE | FLAG_SPILL_LINE_VARS | FLAG_PROCESS_CORRUPTS_WK0, \ 2, /* prefetch distance */ \ ARGBto565PixelAlpha_init, \ ARGBto565PixelAlpha_newline, \ nop_macro, /* cleanup */ \ ARGBto565PixelAlpha_process_head, \ ARGBto565PixelAlpha_process_tail /******************************************************************************/ .macro BGR888toRGB888_1pixel cond, reg, tmp uxtb16&cond tmp, WK&reg, ror #8 uxtb16&cond WK&reg, WK&reg, ror #16 orr&cond WK&reg, WK&reg, tmp, lsl #8 .endm .macro BGR888toRGB888_2pixels cond, reg1, reg2, tmp1, tmp2 uxtb16&cond tmp1, WK&reg1, ror #8 uxtb16&cond WK&reg1, WK&reg1, ror #16 uxtb16&cond tmp2, WK&reg2, ror #8 uxtb16&cond WK&reg2, WK&reg2, ror #16 orr&cond WK&reg1, WK&reg1, tmp1, lsl #8 orr&cond WK&reg2, WK&reg2, tmp2, lsl #8 .endm .macro BGR888toRGB888_process_head cond, numbytes, firstreg, unaligned_src, unaligned_mask, preload pixld cond, numbytes, firstreg, SRC, unaligned_src .endm .macro BGR888toRGB888_process_tail cond, numbytes, firstreg .if numbytes >= 8 BGR888toRGB888_2pixels cond, %(firstreg+0), %(firstreg+1), MASK, STRIDE_M .if numbytes == 16 BGR888toRGB888_2pixels cond, %(firstreg+2), %(firstreg+3), MASK, STRIDE_M .endif .else @ numbytes == 4 BGR888toRGB888_1pixel cond, %(firstreg+0), MASK .endif .endm generate_composite_function \ Blit_BGR888_RGB888ARMSIMDAsm, 32, 0, 32, \ FLAG_DST_WRITEONLY | FLAG_COND_EXEC | FLAG_PROCESS_PRESERVES_SCRATCH, \ 2, /* prefetch distance */ \ nop_macro, /* init */ \ nop_macro, /* newline */ \ nop_macro, /* cleanup */ \ BGR888toRGB888_process_head, \ BGR888toRGB888_process_tail /******************************************************************************/ .macro RGB444toRGB888_init ldr MASK, =0x0f0f0f0f /* Set GE[3:0] to 0101 so SEL instructions do what we want */ msr CPSR_s, #0x50000 .endm .macro RGB444toRGB888_1pixel reg, mask, tmp pkhbt WK&reg, WK&reg, WK&reg, lsl #12 @ 0000aaaarrrrggggaaaarrrrggggbbbb and WK&reg, mask, WK&reg @ 0000aaaa0000gggg0000rrrr0000bbbb orr WK&reg, WK&reg, WK&reg, lsl #4 @ aaaaaaaaggggggggrrrrrrrrbbbbbbbb pkhtb tmp, WK&reg, WK&reg, asr #8 @ aaaaaaaaggggggggggggggggrrrrrrrr pkhbt WK&reg, WK&reg, WK&reg, lsl #8 @ ggggggggrrrrrrrrrrrrrrrrbbbbbbbb sel WK&reg, WK&reg, tmp @ aaaaaaaarrrrrrrrggggggggbbbbbbbb .endm .macro RGB444toRGB888_2pixels in, out1, out2, mask, tmp1, tmp2 and tmp1, mask, WK&in @ 0000RRRR0000BBBB0000rrrr0000bbbb and tmp2, mask, WK&in, lsr #4 @ 0000AAAA0000GGGG0000aaaa0000gggg orr tmp1, tmp1, tmp1, lsl #4 @ RRRRRRRRBBBBBBBBrrrrrrrrbbbbbbbb orr tmp2, tmp2, tmp2, lsl #4 @ AAAAAAAAGGGGGGGGaaaaaaaagggggggg pkhtb WK&out2, tmp2, tmp1, asr #16 @ AAAAAAAAGGGGGGGGRRRRRRRRBBBBBBBB pkhbt WK&out1, tmp1, tmp2, lsl #16 @ aaaaaaaaggggggggrrrrrrrrbbbbbbbb pkhtb tmp2, WK&out2, WK&out2, asr #8 @ AAAAAAAAGGGGGGGGGGGGGGGGRRRRRRRR pkhtb tmp1, WK&out1, WK&out1, asr #8 @ aaaaaaaaggggggggggggggggrrrrrrrr pkhbt WK&out1, WK&out1, WK&out1, lsl #8 @ ggggggggrrrrrrrrrrrrrrrrbbbbbbbb pkhbt WK&out2, WK&out2, WK&out2, lsl #8 @ GGGGGGGGRRRRRRRRRRRRRRRRBBBBBBBB sel WK&out1, WK&out1, tmp1 @ aaaaaaaarrrrrrrrggggggggbbbbbbbb sel WK&out2, WK&out2, tmp2 @ AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB .endm .macro RGB444toRGB888_process_head cond, numbytes, firstreg, unaligned_src, unaligned_mask, preload pixld cond, numbytes/2, firstreg, SRC, unaligned_src .endm .macro RGB444toRGB888_process_tail cond, numbytes, firstreg .if numbytes >= 8 .if numbytes == 16 RGB444toRGB888_2pixels %(firstreg+1), %(firstreg+2), %(firstreg+3), MASK, STRIDE_M, SCRATCH .endif RGB444toRGB888_2pixels %(firstreg+0), %(firstreg+0), %(firstreg+1), MASK, STRIDE_M, SCRATCH .else @ numbytes == 4 RGB444toRGB888_1pixel %(firstreg+0), MASK, SCRATCH .endif .endm generate_composite_function \ Blit_RGB444_RGB888ARMSIMDAsm, 16, 0, 32, \ FLAG_DST_WRITEONLY | FLAG_BRANCH_OVER, \ 2, /* prefetch distance */ \ RGB444toRGB888_init, \ nop_macro, /* newline */ \ nop_macro, /* cleanup */ \ RGB444toRGB888_process_head, \ RGB444toRGB888_process_tail
YifuLiu/AliOS-Things
components/SDL2/src/video/arm/pixman-arm-simd-asm.S
Motorola 68K Assembly
apache-2.0
19,392
/* * Copyright (c) 2012 Raspberry Pi Foundation * Copyright (c) 2012 RISC OS Open Ltd * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* * Because the alignment of pixel data to cachelines, and even the number of * cachelines per row can vary from row to row, and because of the need to * preload each scanline once and only once, this prefetch strategy treats * each row of pixels independently. When a pixel row is long enough, there * are three distinct phases of prefetch: * * an inner loop section, where each time a cacheline of data is * processed, another cacheline is preloaded (the exact distance ahead is * determined empirically using profiling results from lowlevel-blt-bench) * * a leading section, where enough cachelines are preloaded to ensure no * cachelines escape being preloaded when the inner loop starts * * a trailing section, where a limited number (0 or more) of cachelines * are preloaded to deal with data (if any) that hangs off the end of the * last iteration of the inner loop, plus any trailing bytes that were not * enough to make up one whole iteration of the inner loop * * There are (in general) three distinct code paths, selected between * depending upon how long the pixel row is. If it is long enough that there * is at least one iteration of the inner loop (as described above) then * this is described as the "wide" case. If it is shorter than that, but * there are still enough bytes output that there is at least one 16-byte- * long, 16-byte-aligned write to the destination (the optimum type of * write), then this is the "medium" case. If it is not even this long, then * this is the "narrow" case, and there is no attempt to align writes to * 16-byte boundaries. In the "medium" and "narrow" cases, all the * cachelines containing data from the pixel row are prefetched up-front. */ /* * Determine whether we put the arguments on the stack for debugging. */ #undef DEBUG_PARAMS /* * Bit flags for 'generate_composite_function' macro which are used * to tune generated functions behavior. */ .set FLAG_DST_WRITEONLY, 0 .set FLAG_DST_READWRITE, 1 .set FLAG_COND_EXEC, 0 .set FLAG_BRANCH_OVER, 2 .set FLAG_PROCESS_PRESERVES_PSR, 0 .set FLAG_PROCESS_CORRUPTS_PSR, 4 .set FLAG_PROCESS_DOESNT_STORE, 0 .set FLAG_PROCESS_DOES_STORE, 8 /* usually because it needs to conditionally skip it */ .set FLAG_NO_SPILL_LINE_VARS, 0 .set FLAG_SPILL_LINE_VARS_WIDE, 16 .set FLAG_SPILL_LINE_VARS_NON_WIDE, 32 .set FLAG_SPILL_LINE_VARS, 48 .set FLAG_PROCESS_CORRUPTS_SCRATCH, 0 .set FLAG_PROCESS_PRESERVES_SCRATCH, 64 .set FLAG_PROCESS_PRESERVES_WK0, 0 .set FLAG_PROCESS_CORRUPTS_WK0, 128 /* if possible, use the specified register(s) instead so WK0 can hold number of leading pixels */ .set FLAG_PRELOAD_DST, 0 .set FLAG_NO_PRELOAD_DST, 256 /* * Number of bytes by which to adjust preload offset of destination * buffer (allows preload instruction to be moved before the load(s)) */ .set DST_PRELOAD_BIAS, 0 /* * Offset into stack where mask and source pointer/stride can be accessed. */ #ifdef DEBUG_PARAMS .set ARGS_STACK_OFFSET, (9*4+9*4) #else .set ARGS_STACK_OFFSET, (9*4) #endif /* * Offset into stack where space allocated during init macro can be accessed. */ .set LOCALS_STACK_OFFSET, 0 /* * Constants for selecting preferable prefetch type. */ .set PREFETCH_TYPE_NONE, 0 .set PREFETCH_TYPE_STANDARD, 1 /* * Definitions of macros for load/store of pixel data. */ .macro pixldst op, cond=al, numbytes, reg0, reg1, reg2, reg3, base, unaligned=0 .if numbytes == 16 .if unaligned == 1 op&r&cond WK&reg0, [base], #4 op&r&cond WK&reg1, [base], #4 op&r&cond WK&reg2, [base], #4 op&r&cond WK&reg3, [base], #4 .else op&m&cond&ia base!, {WK&reg0,WK&reg1,WK&reg2,WK&reg3} .endif .elseif numbytes == 8 .if unaligned == 1 op&r&cond WK&reg0, [base], #4 op&r&cond WK&reg1, [base], #4 .else op&m&cond&ia base!, {WK&reg0,WK&reg1} .endif .elseif numbytes == 4 op&r&cond WK&reg0, [base], #4 .elseif numbytes == 2 op&r&cond&h WK&reg0, [base], #2 .elseif numbytes == 1 op&r&cond&b WK&reg0, [base], #1 .else .error "unsupported size: numbytes" .endif .endm .macro pixst_baseupdated cond, numbytes, reg0, reg1, reg2, reg3, base .if numbytes == 16 stm&cond&db base, {WK&reg0,WK&reg1,WK&reg2,WK&reg3} .elseif numbytes == 8 stm&cond&db base, {WK&reg0,WK&reg1} .elseif numbytes == 4 str&cond WK&reg0, [base, #-4] .elseif numbytes == 2 str&cond&h WK&reg0, [base, #-2] .elseif numbytes == 1 str&cond&b WK&reg0, [base, #-1] .else .error "unsupported size: numbytes" .endif .endm .macro pixld cond, numbytes, firstreg, base, unaligned pixldst ld, cond, numbytes, %(firstreg+0), %(firstreg+1), %(firstreg+2), %(firstreg+3), base, unaligned .endm .macro pixst cond, numbytes, firstreg, base .if (flags) & FLAG_DST_READWRITE pixst_baseupdated cond, numbytes, %(firstreg+0), %(firstreg+1), %(firstreg+2), %(firstreg+3), base .else pixldst st, cond, numbytes, %(firstreg+0), %(firstreg+1), %(firstreg+2), %(firstreg+3), base .endif .endm .macro PF a, x:vararg .if (PREFETCH_TYPE_CURRENT == PREFETCH_TYPE_STANDARD) a x .endif .endm .macro preload_leading_step1 bpp, ptr, base /* If the destination is already 16-byte aligned, then we need to preload * between 0 and prefetch_distance (inclusive) cache lines ahead so there * are no gaps when the inner loop starts. */ .if bpp > 0 PF bic, ptr, base, #31 .set OFFSET, 0 .rept prefetch_distance+1 PF pld, [ptr, #OFFSET] .set OFFSET, OFFSET+32 .endr .endif .endm .macro preload_leading_step2 bpp, bpp_shift, ptr, base /* However, if the destination is not 16-byte aligned, we may need to * preload more cache lines than that. The question we need to ask is: * are the bytes corresponding to the leading pixels more than the amount * by which the source pointer will be rounded down for preloading, and if * so, by how many cache lines? Effectively, we want to calculate * leading_bytes = ((-dst)&15)*src_bpp/dst_bpp * inner_loop_offset = (src+leading_bytes)&31 * extra_needed = leading_bytes - inner_loop_offset * and test if extra_needed is <= 0, <= 32, or > 32 (where > 32 is only * possible when there are 4 src bytes for every 1 dst byte). */ .if bpp > 0 .ifc base,DST /* The test can be simplified further when preloading the destination */ PF tst, base, #16 PF beq, 61f .else .if bpp/dst_w_bpp == 4 PF add, SCRATCH, base, WK0, lsl #bpp_shift-dst_bpp_shift PF and, SCRATCH, SCRATCH, #31 PF rsb, SCRATCH, SCRATCH, WK0, lsl #bpp_shift-dst_bpp_shift PF sub, SCRATCH, SCRATCH, #1 /* so now ranges are -16..-1 / 0..31 / 32..63 */ PF movs, SCRATCH, SCRATCH, lsl #32-6 /* so this sets NC / nc / Nc */ PF bcs, 61f PF bpl, 60f PF pld, [ptr, #32*(prefetch_distance+2)] .else PF mov, SCRATCH, base, lsl #32-5 PF add, SCRATCH, SCRATCH, WK0, lsl #32-5+bpp_shift-dst_bpp_shift PF rsbs, SCRATCH, SCRATCH, WK0, lsl #32-5+bpp_shift-dst_bpp_shift PF bls, 61f .endif .endif 60: PF pld, [ptr, #32*(prefetch_distance+1)] 61: .endif .endm #define IS_END_OF_GROUP(INDEX,SIZE) ((SIZE) < 2 || ((INDEX) & ~((INDEX)+1)) & ((SIZE)/2)) .macro preload_middle bpp, base, scratch_holds_offset .if bpp > 0 /* prefetch distance = 256/bpp, stm distance = 128/dst_w_bpp */ .if IS_END_OF_GROUP(SUBBLOCK,256/128*dst_w_bpp/bpp) .if scratch_holds_offset PF pld, [base, SCRATCH] .else PF bic, SCRATCH, base, #31 PF pld, [SCRATCH, #32*prefetch_distance] .endif .endif .endif .endm .macro preload_trailing bpp, bpp_shift, base .if bpp > 0 .if bpp*pix_per_block > 256 /* Calculations are more complex if more than one fetch per block */ PF and, WK1, base, #31 PF add, WK1, WK1, WK0, lsl #bpp_shift PF add, WK1, WK1, #32*(bpp*pix_per_block/256-1)*(prefetch_distance+1) PF bic, SCRATCH, base, #31 80: PF pld, [SCRATCH, #32*(prefetch_distance+1)] PF add, SCRATCH, SCRATCH, #32 PF subs, WK1, WK1, #32 PF bhi, 80b .else /* If exactly one fetch per block, then we need either 0, 1 or 2 extra preloads */ PF mov, SCRATCH, base, lsl #32-5 PF adds, SCRATCH, SCRATCH, X, lsl #32-5+bpp_shift PF adceqs, SCRATCH, SCRATCH, #0 /* The instruction above has two effects: ensures Z is only * set if C was clear (so Z indicates that both shifted quantities * were 0), and clears C if Z was set (so C indicates that the sum * of the shifted quantities was greater and not equal to 32) */ PF beq, 82f PF bic, SCRATCH, base, #31 PF bcc, 81f PF pld, [SCRATCH, #32*(prefetch_distance+2)] 81: PF pld, [SCRATCH, #32*(prefetch_distance+1)] 82: .endif .endif .endm .macro preload_line narrow_case, bpp, bpp_shift, base /* "narrow_case" - just means that the macro was invoked from the "narrow" * code path rather than the "medium" one - because in the narrow case, * the row of pixels is known to output no more than 30 bytes, then * (assuming the source pixels are no wider than the the destination * pixels) they cannot possibly straddle more than 2 32-byte cachelines, * meaning there's no need for a loop. * "bpp" - number of bits per pixel in the channel (source, mask or * destination) that's being preloaded, or 0 if this channel is not used * for reading * "bpp_shift" - log2 of ("bpp"/8) (except if "bpp"=0 of course) * "base" - base address register of channel to preload (SRC, MASK or DST) */ .if bpp > 0 .if narrow_case && (bpp <= dst_w_bpp) /* In these cases, each line for each channel is in either 1 or 2 cache lines */ PF bic, WK0, base, #31 PF pld, [WK0] PF add, WK1, base, X, LSL #bpp_shift PF sub, WK1, WK1, #1 PF bic, WK1, WK1, #31 PF cmp, WK1, WK0 PF beq, 90f PF pld, [WK1] 90: .else PF bic, WK0, base, #31 PF pld, [WK0] PF add, WK1, base, X, lsl #bpp_shift PF sub, WK1, WK1, #1 PF bic, WK1, WK1, #31 PF cmp, WK1, WK0 PF beq, 92f 91: PF add, WK0, WK0, #32 PF cmp, WK0, WK1 PF pld, [WK0] PF bne, 91b 92: .endif .endif .endm .macro conditional_process1_helper cond, process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx process_head cond, numbytes, firstreg, unaligned_src, unaligned_mask, 0 .if decrementx sub&cond X, X, #8*numbytes/dst_w_bpp .endif process_tail cond, numbytes, firstreg .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst cond, numbytes, firstreg, DST .endif .endm .macro conditional_process1 cond, process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx .if (flags) & FLAG_BRANCH_OVER .ifc cond,mi bpl 100f .endif .ifc cond,cs bcc 100f .endif .ifc cond,ne beq 100f .endif conditional_process1_helper , process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx 100: .else conditional_process1_helper cond, process_head, process_tail, numbytes, firstreg, unaligned_src, unaligned_mask, decrementx .endif .endm .macro conditional_process2 test, cond1, cond2, process_head, process_tail, numbytes1, numbytes2, firstreg1, firstreg2, unaligned_src, unaligned_mask, decrementx .if (flags) & (FLAG_DST_READWRITE | FLAG_BRANCH_OVER | FLAG_PROCESS_CORRUPTS_PSR | FLAG_PROCESS_DOES_STORE) /* Can't interleave reads and writes */ test conditional_process1 cond1, process_head, process_tail, numbytes1, firstreg1, unaligned_src, unaligned_mask, decrementx .if (flags) & FLAG_PROCESS_CORRUPTS_PSR test .endif conditional_process1 cond2, process_head, process_tail, numbytes2, firstreg2, unaligned_src, unaligned_mask, decrementx .else /* Can interleave reads and writes for better scheduling */ test process_head cond1, numbytes1, firstreg1, unaligned_src, unaligned_mask, 0 process_head cond2, numbytes2, firstreg2, unaligned_src, unaligned_mask, 0 .if decrementx sub&cond1 X, X, #8*numbytes1/dst_w_bpp sub&cond2 X, X, #8*numbytes2/dst_w_bpp .endif process_tail cond1, numbytes1, firstreg1 process_tail cond2, numbytes2, firstreg2 pixst cond1, numbytes1, firstreg1, DST pixst cond2, numbytes2, firstreg2, DST .endif .endm .macro test_bits_1_0_ptr .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 movs SCRATCH, X, lsl #32-1 /* C,N = bits 1,0 of DST */ .else movs SCRATCH, WK0, lsl #32-1 /* C,N = bits 1,0 of DST */ .endif .endm .macro test_bits_3_2_ptr .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 movs SCRATCH, X, lsl #32-3 /* C,N = bits 3, 2 of DST */ .else movs SCRATCH, WK0, lsl #32-3 /* C,N = bits 3, 2 of DST */ .endif .endm .macro leading_15bytes process_head, process_tail /* On entry, WK0 bits 0-3 = number of bytes until destination is 16-byte aligned */ .set DECREMENT_X, 1 .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 .set DECREMENT_X, 0 sub X, X, WK0, lsr #dst_bpp_shift str X, [sp, #LINE_SAVED_REG_COUNT*4] mov X, WK0 .endif /* Use unaligned loads in all cases for simplicity */ .if dst_w_bpp == 8 conditional_process2 test_bits_1_0_ptr, mi, cs, process_head, process_tail, 1, 2, 1, 2, 1, 1, DECREMENT_X .elseif dst_w_bpp == 16 test_bits_1_0_ptr conditional_process1 cs, process_head, process_tail, 2, 2, 1, 1, DECREMENT_X .endif conditional_process2 test_bits_3_2_ptr, mi, cs, process_head, process_tail, 4, 8, 1, 2, 1, 1, DECREMENT_X .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 ldr X, [sp, #LINE_SAVED_REG_COUNT*4] .endif .endm .macro test_bits_3_2_pix movs SCRATCH, X, lsl #dst_bpp_shift+32-3 .endm .macro test_bits_1_0_pix .if dst_w_bpp == 8 movs SCRATCH, X, lsl #dst_bpp_shift+32-1 .else movs SCRATCH, X, lsr #1 .endif .endm .macro trailing_15bytes process_head, process_tail, unaligned_src, unaligned_mask conditional_process2 test_bits_3_2_pix, cs, mi, process_head, process_tail, 8, 4, 0, 2, unaligned_src, unaligned_mask, 0 .if dst_w_bpp == 16 test_bits_1_0_pix conditional_process1 cs, process_head, process_tail, 2, 0, unaligned_src, unaligned_mask, 0 .elseif dst_w_bpp == 8 conditional_process2 test_bits_1_0_pix, cs, mi, process_head, process_tail, 2, 1, 0, 1, unaligned_src, unaligned_mask, 0 .endif .endm .macro wide_case_inner_loop process_head, process_tail, unaligned_src, unaligned_mask, dst_alignment 110: .set SUBBLOCK, 0 /* this is a count of STMs; there can be up to 8 STMs per block */ .rept pix_per_block*dst_w_bpp/128 process_head , 16, 0, unaligned_src, unaligned_mask, 1 .if (src_bpp > 0) && (mask_bpp == 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) preload_middle src_bpp, SRC, 1 .elseif (src_bpp == 0) && (mask_bpp > 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) preload_middle mask_bpp, MASK, 1 .else preload_middle src_bpp, SRC, 0 preload_middle mask_bpp, MASK, 0 .endif .if (dst_r_bpp > 0) && ((SUBBLOCK % 2) == 0) && (((flags) & FLAG_NO_PRELOAD_DST) == 0) /* Because we know that writes are 16-byte aligned, it's relatively easy to ensure that * destination prefetches are 32-byte aligned. It's also the easiest channel to offset * preloads for, to achieve staggered prefetches for multiple channels, because there are * always two STMs per prefetch, so there is always an opposite STM on which to put the * preload. Note, no need to BIC the base register here */ PF pld, [DST, #32*prefetch_distance - dst_alignment] .endif process_tail , 16, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 16, 0, DST .endif .set SUBBLOCK, SUBBLOCK+1 .endr subs X, X, #pix_per_block bhs 110b .endm .macro wide_case_inner_loop_and_trailing_pixels process_head, process_tail, process_inner_loop, exit_label, unaligned_src, unaligned_mask /* Destination now 16-byte aligned; we have at least one block before we have to stop preloading */ .if dst_r_bpp > 0 tst DST, #16 bne 111f process_inner_loop process_head, process_tail, unaligned_src, unaligned_mask, 16 + DST_PRELOAD_BIAS b 112f 111: .endif process_inner_loop process_head, process_tail, unaligned_src, unaligned_mask, 0 + DST_PRELOAD_BIAS 112: /* Just before the final (prefetch_distance+1) 32-byte blocks, deal with final preloads */ .if (src_bpp*pix_per_block > 256) || (mask_bpp*pix_per_block > 256) || (dst_r_bpp*pix_per_block > 256) PF and, WK0, X, #pix_per_block-1 .endif preload_trailing src_bpp, src_bpp_shift, SRC preload_trailing mask_bpp, mask_bpp_shift, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_trailing dst_r_bpp, dst_bpp_shift, DST .endif add X, X, #(prefetch_distance+2)*pix_per_block - 128/dst_w_bpp /* The remainder of the line is handled identically to the medium case */ medium_case_inner_loop_and_trailing_pixels process_head, process_tail,, exit_label, unaligned_src, unaligned_mask .endm .macro medium_case_inner_loop_and_trailing_pixels process_head, process_tail, unused, exit_label, unaligned_src, unaligned_mask 120: process_head , 16, 0, unaligned_src, unaligned_mask, 0 process_tail , 16, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 16, 0, DST .endif subs X, X, #128/dst_w_bpp bhs 120b /* Trailing pixels */ tst X, #128/dst_w_bpp - 1 beq exit_label trailing_15bytes process_head, process_tail, unaligned_src, unaligned_mask .endm .macro narrow_case_inner_loop_and_trailing_pixels process_head, process_tail, unused, exit_label, unaligned_src, unaligned_mask tst X, #16*8/dst_w_bpp conditional_process1 ne, process_head, process_tail, 16, 0, unaligned_src, unaligned_mask, 0 /* Trailing pixels */ /* In narrow case, it's relatively unlikely to be aligned, so let's do without a branch here */ trailing_15bytes process_head, process_tail, unaligned_src, unaligned_mask .endm .macro switch_on_alignment action, process_head, process_tail, process_inner_loop, exit_label /* Note that if we're reading the destination, it's already guaranteed to be aligned at this point */ .if mask_bpp == 8 || mask_bpp == 16 tst MASK, #3 bne 141f .endif .if src_bpp == 8 || src_bpp == 16 tst SRC, #3 bne 140f .endif action process_head, process_tail, process_inner_loop, exit_label, 0, 0 .if src_bpp == 8 || src_bpp == 16 b exit_label 140: action process_head, process_tail, process_inner_loop, exit_label, 1, 0 .endif .if mask_bpp == 8 || mask_bpp == 16 b exit_label 141: .if src_bpp == 8 || src_bpp == 16 tst SRC, #3 bne 142f .endif action process_head, process_tail, process_inner_loop, exit_label, 0, 1 .if src_bpp == 8 || src_bpp == 16 b exit_label 142: action process_head, process_tail, process_inner_loop, exit_label, 1, 1 .endif .endif .endm .macro end_of_line restore_x, vars_spilled, loop_label, last_one .if SINGLE_SCANLINE .ifc "last_one","" b 198f .endif .else .if vars_spilled /* Sadly, GAS doesn't seem have an equivalent of the DCI directive? */ /* This is ldmia sp,{} */ .word 0xE89D0000 | LINE_SAVED_REGS .endif subs Y, Y, #1 .if vars_spilled .if (LINE_SAVED_REGS) & (1<<1) str Y, [sp] .endif .endif add DST, DST, STRIDE_D .if src_bpp > 0 add SRC, SRC, STRIDE_S .endif .if mask_bpp > 0 add MASK, MASK, STRIDE_M .endif .if restore_x mov X, ORIG_W .endif bhs loop_label .ifc "last_one","" .if vars_spilled b 197f .else b 198f .endif .else .if (!vars_spilled) && ((flags) & FLAG_SPILL_LINE_VARS) b 198f .endif .endif .endif .endm .macro generate_composite_function_common fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags_, \ prefetch_distance_, \ init, \ newline, \ cleanup, \ process_head, \ process_tail, \ process_inner_loop pixman_asm_function fname /* * Make some macro arguments globally visible and accessible * from other macros */ .set src_bpp, src_bpp_ .set mask_bpp, mask_bpp_ .set dst_w_bpp, dst_w_bpp_ .set flags, flags_ .set prefetch_distance, prefetch_distance_ /* * Select prefetch type for this function. */ .if prefetch_distance == 0 .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_NONE .else .set PREFETCH_TYPE_CURRENT, PREFETCH_TYPE_STANDARD .endif .if src_bpp == 32 .set src_bpp_shift, 2 .elseif src_bpp == 24 .set src_bpp_shift, 0 .elseif src_bpp == 16 .set src_bpp_shift, 1 .elseif src_bpp == 8 .set src_bpp_shift, 0 .elseif src_bpp == 0 .set src_bpp_shift, -1 .else .error "requested src bpp (src_bpp) is not supported" .endif .if mask_bpp == 32 .set mask_bpp_shift, 2 .elseif mask_bpp == 24 .set mask_bpp_shift, 0 .elseif mask_bpp == 8 .set mask_bpp_shift, 0 .elseif mask_bpp == 0 .set mask_bpp_shift, -1 .else .error "requested mask bpp (mask_bpp) is not supported" .endif .if dst_w_bpp == 32 .set dst_bpp_shift, 2 .elseif dst_w_bpp == 24 .set dst_bpp_shift, 0 .elseif dst_w_bpp == 16 .set dst_bpp_shift, 1 .elseif dst_w_bpp == 8 .set dst_bpp_shift, 0 .else .error "requested dst bpp (dst_w_bpp) is not supported" .endif .if (((flags) & FLAG_DST_READWRITE) != 0) .set dst_r_bpp, dst_w_bpp .else .set dst_r_bpp, 0 .endif .set pix_per_block, 16*8/dst_w_bpp .if src_bpp != 0 .if 32*8/src_bpp > pix_per_block .set pix_per_block, 32*8/src_bpp .endif .endif .if mask_bpp != 0 .if 32*8/mask_bpp > pix_per_block .set pix_per_block, 32*8/mask_bpp .endif .endif .if dst_r_bpp != 0 .if 32*8/dst_r_bpp > pix_per_block .set pix_per_block, 32*8/dst_r_bpp .endif .endif /* The standard entry conditions set up by pixman-arm-common.h are: * r0 = width (pixels) * r1 = height (rows) * r2 = pointer to top-left pixel of destination * r3 = destination stride (pixels) * [sp] = source pixel value, or pointer to top-left pixel of source * [sp,#4] = 0 or source stride (pixels) * The following arguments are unused for non-mask operations * [sp,#8] = mask pixel value, or pointer to top-left pixel of mask * [sp,#12] = 0 or mask stride (pixels) * * or in the single-scanline case: * r0 = width (pixels) * r1 = pointer to top-left pixel of destination * r2 = pointer to top-left pixel of source * The following argument is unused for non-mask operations * r3 = pointer to top-left pixel of mask */ /* * Assign symbolic names to registers */ X .req r0 /* pixels to go on this line */ .if SINGLE_SCANLINE DST .req r1 /* destination pixel pointer */ SRC .req r2 /* source pixel pointer */ MASK .req r3 /* mask pixel pointer (if applicable) */ Y .req r4 /* temporary */ STRIDE_D .req r5 /* temporary */ STRIDE_S .req r6 /* temporary */ STRIDE_M .req r7 /* temporary */ .else Y .req r1 /* lines to go */ DST .req r2 /* destination pixel pointer */ STRIDE_D .req r3 /* destination stride (bytes, minus width) */ SRC .req r4 /* source pixel pointer */ STRIDE_S .req r5 /* source stride (bytes, minus width) */ MASK .req r6 /* mask pixel pointer (if applicable) */ STRIDE_M .req r7 /* mask stride (bytes, minus width) */ .endif WK0 .req r8 /* pixel data registers */ WK1 .req r9 WK2 .req r10 WK3 .req r11 SCRATCH .req r12 ORIG_W .req r14 /* width (pixels) */ push {r4-r11, lr} /* save all registers */ .if !SINGLE_SCANLINE subs Y, Y, #1 blo 199f .endif #ifdef DEBUG_PARAMS sub sp, sp, #9*4 #endif .if !SINGLE_SCANLINE .if src_bpp > 0 ldr SRC, [sp, #ARGS_STACK_OFFSET] ldr STRIDE_S, [sp, #ARGS_STACK_OFFSET+4] .endif .if mask_bpp > 0 ldr MASK, [sp, #ARGS_STACK_OFFSET+8] ldr STRIDE_M, [sp, #ARGS_STACK_OFFSET+12] .endif .endif #ifdef DEBUG_PARAMS add Y, Y, #1 stmia sp, {r0-r7,pc} sub Y, Y, #1 #endif init .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 /* Reserve a word in which to store X during leading pixels */ sub sp, sp, #4 .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET+4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET+4 .endif .if !SINGLE_SCANLINE lsl STRIDE_D, #dst_bpp_shift /* stride in bytes */ sub STRIDE_D, STRIDE_D, X, lsl #dst_bpp_shift .if src_bpp > 0 lsl STRIDE_S, #src_bpp_shift sub STRIDE_S, STRIDE_S, X, lsl #src_bpp_shift .endif .if mask_bpp > 0 lsl STRIDE_M, #mask_bpp_shift sub STRIDE_M, STRIDE_M, X, lsl #mask_bpp_shift .endif .endif /* Are we not even wide enough to have one 16-byte aligned 16-byte block write? */ cmp X, #2*16*8/dst_w_bpp - 1 blo 170f .if src_bpp || mask_bpp || dst_r_bpp /* Wide and medium cases are the same for fill */ /* To preload ahead on the current line, we need at least (prefetch_distance+2) 32-byte blocks on all prefetch channels */ cmp X, #(prefetch_distance+3)*pix_per_block - 1 blo 160f /* Wide case */ /* Adjust X so that the decrement instruction can also test for * inner loop termination. We want it to stop when there are * (prefetch_distance+1) complete blocks to go. */ sub X, X, #(prefetch_distance+2)*pix_per_block .if !SINGLE_SCANLINE mov ORIG_W, X .if (flags) & FLAG_SPILL_LINE_VARS_WIDE /* This is stmdb sp!,{} */ .word 0xE92D0000 | LINE_SAVED_REGS .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .endif .endif 151: /* New line */ newline preload_leading_step1 src_bpp, WK1, SRC preload_leading_step1 mask_bpp, WK2, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_leading_step1 dst_r_bpp, WK3, DST .endif ands WK0, DST, #15 beq 154f rsb WK0, WK0, #16 /* number of leading bytes until destination aligned */ preload_leading_step2 src_bpp, src_bpp_shift, WK1, SRC preload_leading_step2 mask_bpp, mask_bpp_shift, WK2, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_leading_step2 dst_r_bpp, dst_bpp_shift, WK3, DST .endif leading_15bytes process_head, process_tail 154: /* Destination now 16-byte aligned; we have at least one prefetch on each channel as well as at least one 16-byte output block */ .if (src_bpp > 0) && (mask_bpp == 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) and SCRATCH, SRC, #31 rsb SCRATCH, SCRATCH, #32*prefetch_distance .elseif (src_bpp == 0) && (mask_bpp > 0) && ((flags) & FLAG_PROCESS_PRESERVES_SCRATCH) and SCRATCH, MASK, #31 rsb SCRATCH, SCRATCH, #32*prefetch_distance .endif .ifc "process_inner_loop","" switch_on_alignment wide_case_inner_loop_and_trailing_pixels, process_head, process_tail, wide_case_inner_loop, 157f .else switch_on_alignment wide_case_inner_loop_and_trailing_pixels, process_head, process_tail, process_inner_loop, 157f .endif 157: /* Check for another line */ end_of_line 1, %((flags) & FLAG_SPILL_LINE_VARS_WIDE), 151b .if (!SINGLE_SCANLINE) && ((flags) & FLAG_SPILL_LINE_VARS_WIDE) .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .endif .endif .ltorg 160: /* Medium case */ .if !SINGLE_SCANLINE mov ORIG_W, X .if (flags) & FLAG_SPILL_LINE_VARS_NON_WIDE /* This is stmdb sp!,{} */ .word 0xE92D0000 | LINE_SAVED_REGS .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET + LINE_SAVED_REG_COUNT*4 .endif .endif 161: /* New line */ newline preload_line 0, src_bpp, src_bpp_shift, SRC /* in: X, corrupts: WK0-WK1 */ preload_line 0, mask_bpp, mask_bpp_shift, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_line 0, dst_r_bpp, dst_bpp_shift, DST .endif sub X, X, #128/dst_w_bpp /* simplifies inner loop termination */ ands WK0, DST, #15 beq 164f rsb WK0, WK0, #16 /* number of leading bytes until destination aligned */ leading_15bytes process_head, process_tail 164: /* Destination now 16-byte aligned; we have at least one 16-byte output block */ switch_on_alignment medium_case_inner_loop_and_trailing_pixels, process_head, process_tail,, 167f 167: /* Check for another line */ end_of_line 1, %((flags) & FLAG_SPILL_LINE_VARS_NON_WIDE), 161b .ltorg 170: /* Narrow case, less than 31 bytes, so no guarantee of at least one 16-byte block */ .if !SINGLE_SCANLINE .if dst_w_bpp < 32 mov ORIG_W, X .endif .if (flags) & FLAG_SPILL_LINE_VARS_NON_WIDE /* This is stmdb sp!,{} */ .word 0xE92D0000 | LINE_SAVED_REGS .endif .endif 171: /* New line */ newline preload_line 1, src_bpp, src_bpp_shift, SRC /* in: X, corrupts: WK0-WK1 */ preload_line 1, mask_bpp, mask_bpp_shift, MASK .if ((flags) & FLAG_NO_PRELOAD_DST) == 0 preload_line 1, dst_r_bpp, dst_bpp_shift, DST .endif .if dst_w_bpp == 8 tst DST, #3 beq 174f 172: subs X, X, #1 blo 177f process_head , 1, 0, 1, 1, 0 process_tail , 1, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 1, 0, DST .endif tst DST, #3 bne 172b .elseif dst_w_bpp == 16 tst DST, #2 beq 174f subs X, X, #1 blo 177f process_head , 2, 0, 1, 1, 0 process_tail , 2, 0 .if !((flags) & FLAG_PROCESS_DOES_STORE) pixst , 2, 0, DST .endif .endif 174: /* Destination now 4-byte aligned; we have 0 or more output bytes to go */ switch_on_alignment narrow_case_inner_loop_and_trailing_pixels, process_head, process_tail,, 177f 177: /* Check for another line */ end_of_line %(dst_w_bpp < 32), %((flags) & FLAG_SPILL_LINE_VARS_NON_WIDE), 171b, last_one .if (!SINGLE_SCANLINE) && ((flags) & FLAG_SPILL_LINE_VARS_NON_WIDE) .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET - LINE_SAVED_REG_COUNT*4 .endif 197: .if (!SINGLE_SCANLINE) && ((flags) & FLAG_SPILL_LINE_VARS) add sp, sp, #LINE_SAVED_REG_COUNT*4 .endif 198: .if (flags) & FLAG_PROCESS_CORRUPTS_WK0 .set ARGS_STACK_OFFSET, ARGS_STACK_OFFSET-4 .set LOCALS_STACK_OFFSET, LOCALS_STACK_OFFSET-4 add sp, sp, #4 .endif cleanup #ifdef DEBUG_PARAMS add sp, sp, #9*4 /* junk the debug copy of arguments */ #endif 199: pop {r4-r11, pc} /* exit */ .ltorg .unreq X .unreq Y .unreq DST .unreq STRIDE_D .unreq SRC .unreq STRIDE_S .unreq MASK .unreq STRIDE_M .unreq WK0 .unreq WK1 .unreq WK2 .unreq WK3 .unreq SCRATCH .unreq ORIG_W .endfunc .endm .macro generate_composite_function fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags_, \ prefetch_distance_, \ init, \ newline, \ cleanup, \ process_head, \ process_tail, \ process_inner_loop .set SINGLE_SCANLINE, 0 generate_composite_function_common \ fname, src_bpp_, mask_bpp_, dst_w_bpp_, flags_, prefetch_distance_, \ init, newline, cleanup, process_head, process_tail, process_inner_loop .endm .macro generate_composite_function_single_scanline fname, \ src_bpp_, \ mask_bpp_, \ dst_w_bpp_, \ flags_, \ prefetch_distance_, \ init, \ newline, \ cleanup, \ process_head, \ process_tail, \ process_inner_loop .set SINGLE_SCANLINE, 1 generate_composite_function_common \ fname, src_bpp_, mask_bpp_, dst_w_bpp_, flags_, prefetch_distance_, \ init, newline, cleanup, process_head, process_tail, process_inner_loop .endm .macro line_saved_regs x:vararg .set LINE_SAVED_REGS, 0 .set LINE_SAVED_REG_COUNT, 0 .irp SAVED_REG,x .ifc "SAVED_REG","Y" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<1) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","STRIDE_D" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<3) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","STRIDE_S" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<5) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","STRIDE_M" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<7) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .ifc "SAVED_REG","ORIG_W" .set LINE_SAVED_REGS, LINE_SAVED_REGS | (1<<14) .set LINE_SAVED_REG_COUNT, LINE_SAVED_REG_COUNT + 1 .endif .endr .if SINGLE_SCANLINE .set LINE_SAVED_REG_COUNT, 0 .endif .endm .macro nop_macro x:vararg .endm
YifuLiu/AliOS-Things
components/SDL2/src/video/arm/pixman-arm-simd-asm.h
C
apache-2.0
36,837
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoaclipboard_h_ #define SDL_cocoaclipboard_h_ /* Forward declaration */ struct SDL_VideoData; extern int Cocoa_SetClipboardText(_THIS, const char *text); extern char *Cocoa_GetClipboardText(_THIS); extern SDL_bool Cocoa_HasClipboardText(_THIS); extern void Cocoa_CheckClipboardUpdate(struct SDL_VideoData * data); #endif /* SDL_cocoaclipboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaclipboard.h
C
apache-2.0
1,374
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_cocoavideo.h" #include "../../events/SDL_clipboardevents_c.h" int Cocoa_SetClipboardText(_THIS, const char *text) { @autoreleasepool { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; NSPasteboard *pasteboard; NSString *format = NSPasteboardTypeString; pasteboard = [NSPasteboard generalPasteboard]; data->clipboard_count = [pasteboard declareTypes:[NSArray arrayWithObject:format] owner:nil]; [pasteboard setString:[NSString stringWithUTF8String:text] forType:format]; return 0; }} char * Cocoa_GetClipboardText(_THIS) { @autoreleasepool { NSPasteboard *pasteboard; NSString *format = NSPasteboardTypeString; NSString *available; char *text; pasteboard = [NSPasteboard generalPasteboard]; available = [pasteboard availableTypeFromArray:[NSArray arrayWithObject:format]]; if ([available isEqualToString:format]) { NSString* string; const char *utf8; string = [pasteboard stringForType:format]; if (string == nil) { utf8 = ""; } else { utf8 = [string UTF8String]; } text = SDL_strdup(utf8); } else { text = SDL_strdup(""); } return text; }} SDL_bool Cocoa_HasClipboardText(_THIS) { SDL_bool result = SDL_FALSE; char *text = Cocoa_GetClipboardText(_this); if (text) { result = text[0] != '\0' ? SDL_TRUE : SDL_FALSE; SDL_free(text); } return result; } void Cocoa_CheckClipboardUpdate(struct SDL_VideoData * data) { @autoreleasepool { NSPasteboard *pasteboard; NSInteger count; pasteboard = [NSPasteboard generalPasteboard]; count = [pasteboard changeCount]; if (count != data->clipboard_count) { if (data->clipboard_count) { SDL_SendClipboardUpdate(); } data->clipboard_count = count; } }} #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaclipboard.m
Objective-C
apache-2.0
2,947
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoaevents_h_ #define SDL_cocoaevents_h_ extern void Cocoa_RegisterApp(void); extern void Cocoa_PumpEvents(_THIS); extern void Cocoa_SuspendScreenSaver(_THIS); #endif /* SDL_cocoaevents_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaevents.h
C
apache-2.0
1,215
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_timer.h" #include "SDL_cocoavideo.h" #include "../../events/SDL_events_c.h" #include "SDL_assert.h" #include "SDL_hints.h" /* This define was added in the 10.9 SDK. */ #ifndef kIOPMAssertPreventUserIdleDisplaySleep #define kIOPMAssertPreventUserIdleDisplaySleep kIOPMAssertionTypePreventUserIdleDisplaySleep #endif @interface SDLApplication : NSApplication - (void)terminate:(id)sender; - (void)sendEvent:(NSEvent *)theEvent; + (void)registerUserDefaults; @end @implementation SDLApplication // Override terminate to handle Quit and System Shutdown smoothly. - (void)terminate:(id)sender { SDL_SendQuit(); } static SDL_bool s_bShouldHandleEventsInSDLApplication = SDL_FALSE; static void Cocoa_DispatchEvent(NSEvent *theEvent) { SDL_VideoDevice *_this = SDL_GetVideoDevice(); switch ([theEvent type]) { case NSEventTypeLeftMouseDown: case NSEventTypeOtherMouseDown: case NSEventTypeRightMouseDown: case NSEventTypeLeftMouseUp: case NSEventTypeOtherMouseUp: case NSEventTypeRightMouseUp: case NSEventTypeLeftMouseDragged: case NSEventTypeRightMouseDragged: case NSEventTypeOtherMouseDragged: /* usually middle mouse dragged */ case NSEventTypeMouseMoved: case NSEventTypeScrollWheel: Cocoa_HandleMouseEvent(_this, theEvent); break; case NSEventTypeKeyDown: case NSEventTypeKeyUp: case NSEventTypeFlagsChanged: Cocoa_HandleKeyEvent(_this, theEvent); break; default: break; } } // Dispatch events here so that we can handle events caught by // nextEventMatchingMask in SDL, as well as events caught by other // processes (such as CEF) that are passed down to NSApp. - (void)sendEvent:(NSEvent *)theEvent { if (s_bShouldHandleEventsInSDLApplication) { Cocoa_DispatchEvent(theEvent); } [super sendEvent:theEvent]; } + (void)registerUserDefaults { NSDictionary *appDefaults = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithBool:NO], @"AppleMomentumScrollSupported", [NSNumber numberWithBool:NO], @"ApplePressAndHoldEnabled", [NSNumber numberWithBool:YES], @"ApplePersistenceIgnoreState", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; [appDefaults release]; } @end // SDLApplication /* setAppleMenu disappeared from the headers in 10.4 */ @interface NSApplication(NSAppleMenu) - (void)setAppleMenu:(NSMenu *)menu; @end @interface SDLAppDelegate : NSObject <NSApplicationDelegate> { @public BOOL seenFirstActivate; } - (id)init; - (void)localeDidChange:(NSNotification *)notification; @end @implementation SDLAppDelegate : NSObject - (id)init { self = [super init]; if (self) { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; seenFirstActivate = NO; [center addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:nil]; [center addObserver:self selector:@selector(focusSomeWindow:) name:NSApplicationDidBecomeActiveNotification object:nil]; [center addObserver:self selector:@selector(localeDidChange:) name:NSCurrentLocaleDidChangeNotification object:nil]; } return self; } - (void)dealloc { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center removeObserver:self name:NSWindowWillCloseNotification object:nil]; [center removeObserver:self name:NSApplicationDidBecomeActiveNotification object:nil]; [center removeObserver:self name:NSCurrentLocaleDidChangeNotification object:nil]; [super dealloc]; } - (void)windowWillClose:(NSNotification *)notification; { NSWindow *win = (NSWindow*)[notification object]; if (![win isKeyWindow]) { return; } /* HACK: Make the next window in the z-order key when the key window is * closed. The custom event loop and/or windowing code we have seems to * prevent the normal behavior: https://bugzilla.libsdl.org/show_bug.cgi?id=1825 */ /* +[NSApp orderedWindows] never includes the 'About' window, but we still * want to try its list first since the behavior in other apps is to only * make the 'About' window key if no other windows are on-screen. */ for (NSWindow *window in [NSApp orderedWindows]) { if (window != win && [window canBecomeKeyWindow]) { if (![window isOnActiveSpace]) { continue; } [window makeKeyAndOrderFront:self]; return; } } /* If a window wasn't found above, iterate through all visible windows in * the active Space in z-order (including the 'About' window, if it's shown) * and make the first one key. */ for (NSNumber *num in [NSWindow windowNumbersWithOptions:0]) { NSWindow *window = [NSApp windowWithWindowNumber:[num integerValue]]; if (window && window != win && [window canBecomeKeyWindow]) { [window makeKeyAndOrderFront:self]; return; } } } - (void)focusSomeWindow:(NSNotification *)aNotification { /* HACK: Ignore the first call. The application gets a * applicationDidBecomeActive: a little bit after the first window is * created, and if we don't ignore it, a window that has been created with * SDL_WINDOW_MINIMIZED will ~immediately be restored. */ if (!seenFirstActivate) { seenFirstActivate = YES; return; } SDL_VideoDevice *device = SDL_GetVideoDevice(); if (device && device->windows) { SDL_Window *window = device->windows; int i; for (i = 0; i < device->num_displays; ++i) { SDL_Window *fullscreen_window = device->displays[i].fullscreen_window; if (fullscreen_window) { if (fullscreen_window->flags & SDL_WINDOW_MINIMIZED) { SDL_RestoreWindow(fullscreen_window); } return; } } if (window->flags & SDL_WINDOW_MINIMIZED) { SDL_RestoreWindow(window); } else { SDL_RaiseWindow(window); } } } - (void)localeDidChange:(NSNotification *)notification; { SDL_SendLocaleChangedEvent(); } - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename { return (BOOL)SDL_SendDropFile(NULL, [filename UTF8String]) && SDL_SendDropComplete(NULL); } - (void)applicationDidFinishLaunching:(NSNotification *)notification { /* The menu bar of SDL apps which don't have the typical .app bundle * structure fails to work the first time a window is created (until it's * de-focused and re-focused), if this call is in Cocoa_RegisterApp instead * of here. https://bugzilla.libsdl.org/show_bug.cgi?id=3051 */ if (!SDL_GetHintBoolean(SDL_HINT_MAC_BACKGROUND_APP, SDL_FALSE)) { /* Get more aggressive for Catalina: activate the Dock first so we definitely reset all activation state. */ for (NSRunningApplication *i in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.dock"]) { [i activateWithOptions:NSApplicationActivateIgnoringOtherApps]; break; } SDL_Delay(300); /* !!! FIXME: this isn't right. */ [NSApp activateIgnoringOtherApps:YES]; } [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(handleURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; /* If we call this before NSApp activation, macOS might print a complaint * about ApplePersistenceIgnoreState. */ [SDLApplication registerUserDefaults]; } - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { NSString* path = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; SDL_SendDropFile(NULL, [path UTF8String]); SDL_SendDropComplete(NULL); } @end static SDLAppDelegate *appDelegate = nil; static NSString * GetApplicationName(void) { NSString *appName; /* Determine the application name */ appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]; if (!appName) { appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]; } if (![appName length]) { appName = [[NSProcessInfo processInfo] processName]; } return appName; } static bool LoadMainMenuNibIfAvailable(void) { NSDictionary *infoDict; NSString *mainNibFileName; bool success = false; infoDict = [[NSBundle mainBundle] infoDictionary]; if (infoDict) { mainNibFileName = [infoDict valueForKey:@"NSMainNibFile"]; if (mainNibFileName) { success = [[NSBundle mainBundle] loadNibNamed:mainNibFileName owner:[NSApplication sharedApplication] topLevelObjects:nil]; } } return success; } static void CreateApplicationMenus(void) { NSString *appName; NSString *title; NSMenu *appleMenu; NSMenu *serviceMenu; NSMenu *windowMenu; NSMenuItem *menuItem; NSMenu *mainMenu; if (NSApp == nil) { return; } mainMenu = [[NSMenu alloc] init]; /* Create the main menu bar */ [NSApp setMainMenu:mainMenu]; [mainMenu release]; /* we're done with it, let NSApp own it. */ mainMenu = nil; /* Create the application menu */ appName = GetApplicationName(); appleMenu = [[NSMenu alloc] initWithTitle:@""]; /* Add menu items */ title = [@"About " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; [appleMenu addItem:[NSMenuItem separatorItem]]; [appleMenu addItemWithTitle:@"Preferences…" action:nil keyEquivalent:@","]; [appleMenu addItem:[NSMenuItem separatorItem]]; serviceMenu = [[NSMenu alloc] initWithTitle:@""]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Services" action:nil keyEquivalent:@""]; [menuItem setSubmenu:serviceMenu]; [NSApp setServicesMenu:serviceMenu]; [serviceMenu release]; [appleMenu addItem:[NSMenuItem separatorItem]]; title = [@"Hide " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; [appleMenu addItem:[NSMenuItem separatorItem]]; title = [@"Quit " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; /* Put menu into the menubar */ menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; [menuItem setSubmenu:appleMenu]; [[NSApp mainMenu] addItem:menuItem]; [menuItem release]; /* Tell the application object that this is now the application menu */ [NSApp setAppleMenu:appleMenu]; [appleMenu release]; /* Create the window menu */ windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; /* Add menu items */ [windowMenu addItemWithTitle:@"Close" action:@selector(performClose:) keyEquivalent:@"w"]; [windowMenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [windowMenu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; /* Add the fullscreen toggle menu option, if supported */ if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) { /* Cocoa should update the title to Enter or Exit Full Screen automatically. * But if not, then just fallback to Toggle Full Screen. */ menuItem = [[NSMenuItem alloc] initWithTitle:@"Toggle Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"]; [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagControl | NSEventModifierFlagCommand]; [windowMenu addItem:menuItem]; [menuItem release]; } /* Put menu into the menubar */ menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; [menuItem setSubmenu:windowMenu]; [[NSApp mainMenu] addItem:menuItem]; [menuItem release]; /* Tell the application object that this is now the window menu */ [NSApp setWindowsMenu:windowMenu]; [windowMenu release]; } void Cocoa_RegisterApp(void) { @autoreleasepool { /* This can get called more than once! Be careful what you initialize! */ if (NSApp == nil) { [SDLApplication sharedApplication]; SDL_assert(NSApp != nil); s_bShouldHandleEventsInSDLApplication = SDL_TRUE; if (!SDL_GetHintBoolean(SDL_HINT_MAC_BACKGROUND_APP, SDL_FALSE)) { [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; } /* If there aren't already menus in place, look to see if there's * a nib we should use. If not, then manually create the basic * menus we meed. */ if ([NSApp mainMenu] == nil) { bool nibLoaded; nibLoaded = LoadMainMenuNibIfAvailable(); if (!nibLoaded) { CreateApplicationMenus(); } } [NSApp finishLaunching]; if ([NSApp delegate]) { /* The SDL app delegate calls this in didFinishLaunching if it's * attached to the NSApp, otherwise we need to call it manually. */ [SDLApplication registerUserDefaults]; } } if (NSApp && !appDelegate) { appDelegate = [[SDLAppDelegate alloc] init]; /* If someone else has an app delegate, it means we can't turn a * termination into SDL_Quit, and we can't handle application:openFile: */ if (![NSApp delegate]) { [(NSApplication *)NSApp setDelegate:appDelegate]; } else { appDelegate->seenFirstActivate = YES; } } }} void Cocoa_PumpEvents(_THIS) { @autoreleasepool { #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 /* Update activity every 30 seconds to prevent screensaver */ SDL_VideoData *data = (SDL_VideoData *)_this->driverdata; if (_this->suspend_screensaver && !data->screensaver_use_iopm) { Uint32 now = SDL_GetTicks(); if (!data->screensaver_activity || SDL_TICKS_PASSED(now, data->screensaver_activity + 30000)) { UpdateSystemActivity(UsrActivity); data->screensaver_activity = now; } } #endif for ( ; ; ) { NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES ]; if ( event == nil ) { break; } if (!s_bShouldHandleEventsInSDLApplication) { Cocoa_DispatchEvent(event); } // Pass events down to SDLApplication to be handled in sendEvent: [NSApp sendEvent:event]; } }} void Cocoa_SuspendScreenSaver(_THIS) { @autoreleasepool { SDL_VideoData *data = (SDL_VideoData *)_this->driverdata; if (!data->screensaver_use_iopm) { return; } if (data->screensaver_assertion) { IOPMAssertionRelease(data->screensaver_assertion); data->screensaver_assertion = 0; } if (_this->suspend_screensaver) { /* FIXME: this should ideally describe the real reason why the game * called SDL_DisableScreenSaver. Note that the name is only meant to be * seen by OS X power users. there's an additional optional human-readable * (localized) reason parameter which we don't set. */ NSString *name = [GetApplicationName() stringByAppendingString:@" using SDL_DisableScreenSaver"]; IOPMAssertionCreateWithDescription(kIOPMAssertPreventUserIdleDisplaySleep, (CFStringRef) name, NULL, NULL, NULL, 0, NULL, &data->screensaver_assertion); } }} #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaevents.m
Objective-C
apache-2.0
17,830
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoakeyboard_h_ #define SDL_cocoakeyboard_h_ extern void Cocoa_InitKeyboard(_THIS); extern void Cocoa_HandleKeyEvent(_THIS, NSEvent * event); extern void Cocoa_QuitKeyboard(_THIS); extern void Cocoa_StartTextInput(_THIS); extern void Cocoa_StopTextInput(_THIS); extern void Cocoa_SetTextInputRect(_THIS, SDL_Rect *rect); #endif /* SDL_cocoakeyboard_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoakeyboard.h
C
apache-2.0
1,379
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_cocoavideo.h" #include "../../events/SDL_events_c.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/scancodes_darwin.h" #include <Carbon/Carbon.h> /*#define DEBUG_IME NSLog */ #define DEBUG_IME(...) @interface SDLTranslatorResponder : NSView <NSTextInputClient> { NSString *_markedText; NSRange _markedRange; NSRange _selectedRange; SDL_Rect _inputRect; } - (void)doCommandBySelector:(SEL)myselector; - (void)setInputRect:(SDL_Rect *)rect; @end @implementation SDLTranslatorResponder - (void)setInputRect:(SDL_Rect *)rect { _inputRect = *rect; } - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange { /* TODO: Make use of replacementRange? */ const char *str; DEBUG_IME(@"insertText: %@", aString); /* Could be NSString or NSAttributedString, so we have * to test and convert it before return as SDL event */ if ([aString isKindOfClass: [NSAttributedString class]]) { str = [[aString string] UTF8String]; } else { str = [aString UTF8String]; } SDL_SendKeyboardText(str); } - (void)doCommandBySelector:(SEL)myselector { /* No need to do anything since we are not using Cocoa selectors to handle special keys, instead we use SDL key events to do the same job. */ } - (BOOL)hasMarkedText { return _markedText != nil; } - (NSRange)markedRange { return _markedRange; } - (NSRange)selectedRange { return _selectedRange; } - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange { if ([aString isKindOfClass:[NSAttributedString class]]) { aString = [aString string]; } if ([aString length] == 0) { [self unmarkText]; return; } if (_markedText != aString) { [_markedText release]; _markedText = [aString retain]; } _selectedRange = selectedRange; _markedRange = NSMakeRange(0, [aString length]); SDL_SendEditingText([aString UTF8String], (int) selectedRange.location, (int) selectedRange.length); DEBUG_IME(@"setMarkedText: %@, (%d, %d)", _markedText, selRange.location, selRange.length); } - (void)unmarkText { [_markedText release]; _markedText = nil; SDL_SendEditingText("", 0, 0); } - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange { NSWindow *window = [self window]; NSRect contentRect = [window contentRectForFrameRect:[window frame]]; float windowHeight = contentRect.size.height; NSRect rect = NSMakeRect(_inputRect.x, windowHeight - _inputRect.y - _inputRect.h, _inputRect.w, _inputRect.h); if (actualRange) { *actualRange = aRange; } DEBUG_IME(@"firstRectForCharacterRange: (%d, %d): windowHeight = %g, rect = %@", aRange.location, aRange.length, windowHeight, NSStringFromRect(rect)); #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 if (![window respondsToSelector:@selector(convertRectToScreen:)]) { rect.origin = [window convertBaseToScreen:rect.origin]; } else #endif { rect = [window convertRectToScreen:rect]; } return rect; } - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange { DEBUG_IME(@"attributedSubstringFromRange: (%d, %d)", aRange.location, aRange.length); return nil; } - (NSInteger)conversationIdentifier { return (NSInteger) self; } /* This method returns the index for character that is * nearest to thePoint. thPoint is in screen coordinate system. */ - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint { DEBUG_IME(@"characterIndexForPoint: (%g, %g)", thePoint.x, thePoint.y); return 0; } /* This method is the key to attribute extension. * We could add new attributes through this method. * NSInputServer examines the return value of this * method & constructs appropriate attributed string. */ - (NSArray *)validAttributesForMarkedText { return [NSArray array]; } @end /* This is a helper function for HandleModifierSide. This * function reverts back to behavior before the distinction between * sides was made. */ static void HandleNonDeviceModifier(unsigned int device_independent_mask, unsigned int oldMods, unsigned int newMods, SDL_Scancode scancode) { unsigned int oldMask, newMask; /* Isolate just the bits we care about in the depedent bits so we can * figure out what changed */ oldMask = oldMods & device_independent_mask; newMask = newMods & device_independent_mask; if (oldMask && oldMask != newMask) { SDL_SendKeyboardKey(SDL_RELEASED, scancode); } else if (newMask && oldMask != newMask) { SDL_SendKeyboardKey(SDL_PRESSED, scancode); } } /* This is a helper function for HandleModifierSide. * This function sets the actual SDL_PrivateKeyboard event. */ static void HandleModifierOneSide(unsigned int oldMods, unsigned int newMods, SDL_Scancode scancode, unsigned int sided_device_dependent_mask) { unsigned int old_dep_mask, new_dep_mask; /* Isolate just the bits we care about in the depedent bits so we can * figure out what changed */ old_dep_mask = oldMods & sided_device_dependent_mask; new_dep_mask = newMods & sided_device_dependent_mask; /* We now know that this side bit flipped. But we don't know if * it went pressed to released or released to pressed, so we must * find out which it is. */ if (new_dep_mask && old_dep_mask != new_dep_mask) { SDL_SendKeyboardKey(SDL_PRESSED, scancode); } else { SDL_SendKeyboardKey(SDL_RELEASED, scancode); } } /* This is a helper function for DoSidedModifiers. * This function will figure out if the modifier key is the left or right side, * e.g. left-shift vs right-shift. */ static void HandleModifierSide(int device_independent_mask, unsigned int oldMods, unsigned int newMods, SDL_Scancode left_scancode, SDL_Scancode right_scancode, unsigned int left_device_dependent_mask, unsigned int right_device_dependent_mask) { unsigned int device_dependent_mask = (left_device_dependent_mask | right_device_dependent_mask); unsigned int diff_mod; /* On the basis that the device independent mask is set, but there are * no device dependent flags set, we'll assume that we can't detect this * keyboard and revert to the unsided behavior. */ if ((device_dependent_mask & newMods) == 0) { /* Revert to the old behavior */ HandleNonDeviceModifier(device_independent_mask, oldMods, newMods, left_scancode); return; } /* XOR the previous state against the new state to see if there's a change */ diff_mod = (device_dependent_mask & oldMods) ^ (device_dependent_mask & newMods); if (diff_mod) { /* A change in state was found. Isolate the left and right bits * to handle them separately just in case the values can simulataneously * change or if the bits don't both exist. */ if (left_device_dependent_mask & diff_mod) { HandleModifierOneSide(oldMods, newMods, left_scancode, left_device_dependent_mask); } if (right_device_dependent_mask & diff_mod) { HandleModifierOneSide(oldMods, newMods, right_scancode, right_device_dependent_mask); } } } /* This is a helper function for DoSidedModifiers. * This function will release a key press in the case that * it is clear that the modifier has been released (i.e. one side * can't still be down). */ static void ReleaseModifierSide(unsigned int device_independent_mask, unsigned int oldMods, unsigned int newMods, SDL_Scancode left_scancode, SDL_Scancode right_scancode, unsigned int left_device_dependent_mask, unsigned int right_device_dependent_mask) { unsigned int device_dependent_mask = (left_device_dependent_mask | right_device_dependent_mask); /* On the basis that the device independent mask is set, but there are * no device dependent flags set, we'll assume that we can't detect this * keyboard and revert to the unsided behavior. */ if ((device_dependent_mask & oldMods) == 0) { /* In this case, we can't detect the keyboard, so use the left side * to represent both, and release it. */ SDL_SendKeyboardKey(SDL_RELEASED, left_scancode); return; } /* * This could have been done in an if-else case because at this point, * we know that all keys have been released when calling this function. * But I'm being paranoid so I want to handle each separately, * so I hope this doesn't cause other problems. */ if ( left_device_dependent_mask & oldMods ) { SDL_SendKeyboardKey(SDL_RELEASED, left_scancode); } if ( right_device_dependent_mask & oldMods ) { SDL_SendKeyboardKey(SDL_RELEASED, right_scancode); } } /* This function will handle the modifier keys and also determine the * correct side of the key. */ static void DoSidedModifiers(unsigned short scancode, unsigned int oldMods, unsigned int newMods) { /* Set up arrays for the key syms for the left and right side. */ const SDL_Scancode left_mapping[] = { SDL_SCANCODE_LSHIFT, SDL_SCANCODE_LCTRL, SDL_SCANCODE_LALT, SDL_SCANCODE_LGUI }; const SDL_Scancode right_mapping[] = { SDL_SCANCODE_RSHIFT, SDL_SCANCODE_RCTRL, SDL_SCANCODE_RALT, SDL_SCANCODE_RGUI }; /* Set up arrays for the device dependent masks with indices that * correspond to the _mapping arrays */ const unsigned int left_device_mapping[] = { NX_DEVICELSHIFTKEYMASK, NX_DEVICELCTLKEYMASK, NX_DEVICELALTKEYMASK, NX_DEVICELCMDKEYMASK }; const unsigned int right_device_mapping[] = { NX_DEVICERSHIFTKEYMASK, NX_DEVICERCTLKEYMASK, NX_DEVICERALTKEYMASK, NX_DEVICERCMDKEYMASK }; unsigned int i, bit; /* Iterate through the bits, testing each against the old modifiers */ for (i = 0, bit = NSEventModifierFlagShift; bit <= NSEventModifierFlagCommand; bit <<= 1, ++i) { unsigned int oldMask, newMask; oldMask = oldMods & bit; newMask = newMods & bit; /* If the bit is set, we must always examine it because the left * and right side keys may alternate or both may be pressed. */ if (newMask) { HandleModifierSide(bit, oldMods, newMods, left_mapping[i], right_mapping[i], left_device_mapping[i], right_device_mapping[i]); } /* If the state changed from pressed to unpressed, we must examine * the device dependent bits to release the correct keys. */ else if (oldMask && oldMask != newMask) { ReleaseModifierSide(bit, oldMods, newMods, left_mapping[i], right_mapping[i], left_device_mapping[i], right_device_mapping[i]); } } } static void HandleModifiers(_THIS, unsigned short scancode, unsigned int modifierFlags) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; if (modifierFlags == data->modifierFlags) { return; } DoSidedModifiers(scancode, data->modifierFlags, modifierFlags); data->modifierFlags = modifierFlags; } static void UpdateKeymap(SDL_VideoData *data, SDL_bool send_event) { TISInputSourceRef key_layout; const void *chr_data; int i; SDL_Scancode scancode; SDL_Keycode keymap[SDL_NUM_SCANCODES]; /* See if the keymap needs to be updated */ key_layout = TISCopyCurrentKeyboardLayoutInputSource(); if (key_layout == data->key_layout) { return; } data->key_layout = key_layout; SDL_GetDefaultKeymap(keymap); /* Try Unicode data first */ CFDataRef uchrDataRef = TISGetInputSourceProperty(key_layout, kTISPropertyUnicodeKeyLayoutData); if (uchrDataRef) { chr_data = CFDataGetBytePtr(uchrDataRef); } else { goto cleanup; } if (chr_data) { UInt32 keyboard_type = LMGetKbdType(); OSStatus err; for (i = 0; i < SDL_arraysize(darwin_scancode_table); i++) { UniChar s[8]; UniCharCount len; UInt32 dead_key_state; /* Make sure this scancode is a valid character scancode */ scancode = darwin_scancode_table[i]; if (scancode == SDL_SCANCODE_UNKNOWN || (keymap[scancode] & SDLK_SCANCODE_MASK)) { continue; } dead_key_state = 0; err = UCKeyTranslate ((UCKeyboardLayout *) chr_data, i, kUCKeyActionDown, 0, keyboard_type, kUCKeyTranslateNoDeadKeysMask, &dead_key_state, 8, &len, s); if (err != noErr) { continue; } if (len > 0 && s[0] != 0x10) { keymap[scancode] = s[0]; } } SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES); if (send_event) { SDL_SendKeymapChangedEvent(); } return; } cleanup: CFRelease(key_layout); } void Cocoa_InitKeyboard(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; UpdateKeymap(data, SDL_FALSE); /* Set our own names for the platform-dependent but layout-independent keys */ /* This key is NumLock on the MacBook keyboard. :) */ /*SDL_SetScancodeName(SDL_SCANCODE_NUMLOCKCLEAR, "Clear");*/ SDL_SetScancodeName(SDL_SCANCODE_LALT, "Left Option"); SDL_SetScancodeName(SDL_SCANCODE_LGUI, "Left Command"); SDL_SetScancodeName(SDL_SCANCODE_RALT, "Right Option"); SDL_SetScancodeName(SDL_SCANCODE_RGUI, "Right Command"); data->modifierFlags = (unsigned int)[NSEvent modifierFlags]; SDL_ToggleModState(KMOD_CAPS, (data->modifierFlags & NSEventModifierFlagCapsLock) != 0); } void Cocoa_StartTextInput(_THIS) { @autoreleasepool { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; SDL_Window *window = SDL_GetKeyboardFocus(); NSWindow *nswindow = nil; if (window) { nswindow = ((SDL_WindowData*)window->driverdata)->nswindow; } NSView *parentView = [nswindow contentView]; /* We only keep one field editor per process, since only the front most * window can receive text input events, so it make no sense to keep more * than one copy. When we switched to another window and requesting for * text input, simply remove the field editor from its superview then add * it to the front most window's content view */ if (!data->fieldEdit) { data->fieldEdit = [[SDLTranslatorResponder alloc] initWithFrame: NSMakeRect(0.0, 0.0, 0.0, 0.0)]; } if (![[data->fieldEdit superview] isEqual:parentView]) { /* DEBUG_IME(@"add fieldEdit to window contentView"); */ [data->fieldEdit removeFromSuperview]; [parentView addSubview: data->fieldEdit]; [nswindow makeFirstResponder: data->fieldEdit]; } }} void Cocoa_StopTextInput(_THIS) { @autoreleasepool { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; if (data && data->fieldEdit) { [data->fieldEdit removeFromSuperview]; [data->fieldEdit release]; data->fieldEdit = nil; } }} void Cocoa_SetTextInputRect(_THIS, SDL_Rect *rect) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; if (!rect) { SDL_InvalidParamError("rect"); return; } [data->fieldEdit setInputRect:rect]; } void Cocoa_HandleKeyEvent(_THIS, NSEvent *event) { SDL_VideoData *data = _this ? ((SDL_VideoData *) _this->driverdata) : NULL; if (!data) { return; /* can happen when returning from fullscreen Space on shutdown */ } unsigned short scancode = [event keyCode]; SDL_Scancode code; #if 0 const char *text; #endif if ((scancode == 10 || scancode == 50) && KBGetLayoutType(LMGetKbdType()) == kKeyboardISO) { /* see comments in SDL_cocoakeys.h */ scancode = 60 - scancode; } if (scancode < SDL_arraysize(darwin_scancode_table)) { code = darwin_scancode_table[scancode]; } else { /* Hmm, does this ever happen? If so, need to extend the keymap... */ code = SDL_SCANCODE_UNKNOWN; } switch ([event type]) { case NSEventTypeKeyDown: if (![event isARepeat]) { /* See if we need to rebuild the keyboard layout */ UpdateKeymap(data, SDL_TRUE); } SDL_SendKeyboardKey(SDL_PRESSED, code); #if 1 if (code == SDL_SCANCODE_UNKNOWN) { fprintf(stderr, "The key you just pressed is not recognized by SDL. To help get this fixed, report this to the SDL forums/mailing list <https://discourse.libsdl.org/> or to Christian Walther <cwalther@gmx.ch>. Mac virtual key code is %d.\n", scancode); } #endif if (SDL_EventState(SDL_TEXTINPUT, SDL_QUERY)) { /* FIXME CW 2007-08-16: only send those events to the field editor for which we actually want text events, not e.g. esc or function keys. Arrow keys in particular seem to produce crashes sometimes. */ [data->fieldEdit interpretKeyEvents:[NSArray arrayWithObject:event]]; #if 0 text = [[event characters] UTF8String]; if(text && *text) { SDL_SendKeyboardText(text); [data->fieldEdit setString:@""]; } #endif } break; case NSEventTypeKeyUp: SDL_SendKeyboardKey(SDL_RELEASED, code); break; case NSEventTypeFlagsChanged: /* FIXME CW 2007-08-14: check if this whole mess that takes up half of this file is really necessary */ HandleModifiers(_this, scancode, (unsigned int)[event modifierFlags]); break; default: /* just to avoid compiler warnings */ break; } } void Cocoa_QuitKeyboard(_THIS) { } #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoakeyboard.m
Objective-C
apache-2.0
19,700
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA extern int Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid); #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamessagebox.h
C
apache-2.0
1,163
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_events.h" #include "SDL_timer.h" #include "SDL_messagebox.h" #include "SDL_cocoavideo.h" @interface SDLMessageBoxPresenter : NSObject { @public NSInteger clicked; NSWindow *nswindow; } - (id) initWithParentWindow:(SDL_Window *)window; - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; @end @implementation SDLMessageBoxPresenter - (id) initWithParentWindow:(SDL_Window *)window { self = [super init]; if (self) { clicked = -1; /* Retain the NSWindow because we'll show the alert later on the main thread */ if (window) { nswindow = [((SDL_WindowData *) window->driverdata)->nswindow retain]; } else { nswindow = NULL; } } return self; } - (void)showAlert:(NSAlert*)alert { if (nswindow) { #ifdef MAC_OS_X_VERSION_10_9 if ([alert respondsToSelector:@selector(beginSheetModalForWindow:completionHandler:)]) { [alert beginSheetModalForWindow:nswindow completionHandler:^(NSModalResponse returnCode) { clicked = returnCode; }]; } else #endif { #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090 [alert beginSheetModalForWindow:nswindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil]; #endif } while (clicked < 0) { SDL_PumpEvents(); SDL_Delay(100); } [nswindow release]; } else { clicked = [alert runModal]; } } - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo { clicked = returnCode; } @end /* Display a Cocoa message box */ int Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) { @autoreleasepool { Cocoa_RegisterApp(); NSAlert* alert = [[[NSAlert alloc] init] autorelease]; if (messageboxdata->flags & SDL_MESSAGEBOX_ERROR) { [alert setAlertStyle:NSAlertStyleCritical]; } else if (messageboxdata->flags & SDL_MESSAGEBOX_WARNING) { [alert setAlertStyle:NSAlertStyleWarning]; } else { [alert setAlertStyle:NSAlertStyleInformational]; } [alert setMessageText:[NSString stringWithUTF8String:messageboxdata->title]]; [alert setInformativeText:[NSString stringWithUTF8String:messageboxdata->message]]; const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons; int i; for (i = 0; i < messageboxdata->numbuttons; ++i) { const SDL_MessageBoxButtonData *sdlButton; NSButton *button; if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT) { sdlButton = &messageboxdata->buttons[messageboxdata->numbuttons - 1 - i]; } else { sdlButton = &messageboxdata->buttons[i]; } button = [alert addButtonWithTitle:[NSString stringWithUTF8String:sdlButton->text]]; if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) { [button setKeyEquivalent:@"\r"]; } else if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT) { [button setKeyEquivalent:@"\033"]; } else { [button setKeyEquivalent:@""]; } } SDLMessageBoxPresenter* presenter = [[[SDLMessageBoxPresenter alloc] initWithParentWindow:messageboxdata->window] autorelease]; [presenter performSelectorOnMainThread:@selector(showAlert:) withObject:alert waitUntilDone:YES]; int returnValue = 0; NSInteger clicked = presenter->clicked; if (clicked >= NSAlertFirstButtonReturn) { clicked -= NSAlertFirstButtonReturn; if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT) { clicked = messageboxdata->numbuttons - 1 - clicked; } *buttonid = buttons[clicked].buttonid; } else { returnValue = SDL_SetError("Did not get a valid `clicked button' id: %ld", (long)clicked); } return returnValue; }} #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamessagebox.m
Objective-C
apache-2.0
5,129
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * @author Mark Callow, www.edgewise-consulting.com. * * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing * how to add a CAMetalLayer backed view. */ #include "../../SDL_internal.h" #ifndef SDL_cocoametalview_h_ #define SDL_cocoametalview_h_ #if SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) #import "../SDL_sysvideo.h" #import "SDL_cocoawindow.h" #import <Cocoa/Cocoa.h> #import <Metal/Metal.h> #import <QuartzCore/CAMetalLayer.h> #define METALVIEW_TAG 255 @interface SDL_cocoametalview : NSView - (instancetype)initWithFrame:(NSRect)frame highDPI:(BOOL)highDPI windowID:(Uint32)windowID; - (void)updateDrawableSize; /* Override superclass tag so this class can set it. */ @property (assign, readonly) NSInteger tag; @property (nonatomic) BOOL highDPI; @property (nonatomic) Uint32 sdlWindowID; @end SDL_MetalView Cocoa_Metal_CreateView(_THIS, SDL_Window * window); void Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view); void *Cocoa_Metal_GetLayer(_THIS, SDL_MetalView view); void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h); #endif /* SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */ #endif /* SDL_cocoametalview_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoametalview.h
Objective-C
apache-2.0
2,249
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * @author Mark Callow, www.edgewise-consulting.com. * * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing * how to add a CAMetalLayer backed view. */ #import "SDL_cocoametalview.h" #if SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) #include "SDL_assert.h" #include "SDL_events.h" static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event) { /* Update the drawable size when SDL receives a size changed event for * the window that contains the metal view. It would be nice to use * - (void)resizeWithOldSuperviewSize:(NSSize)oldSize and * - (void)viewDidChangeBackingProperties instead, but SDL's size change * events don't always happen in the same frame (for example when a * resizable window exits a fullscreen Space via the user pressing the OS * exit-space button). */ if (event->type == SDL_WINDOWEVENT && event->window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { @autoreleasepool { SDL_cocoametalview *view = (__bridge SDL_cocoametalview *)userdata; if (view.sdlWindowID == event->window.windowID) { [view updateDrawableSize]; } } } return 0; } @implementation SDL_cocoametalview /* Return a Metal-compatible layer. */ + (Class)layerClass { return NSClassFromString(@"CAMetalLayer"); } /* Indicate the view wants to draw using a backing layer instead of drawRect. */ - (BOOL)wantsUpdateLayer { return YES; } /* When the wantsLayer property is set to YES, this method will be invoked to * return a layer instance. */ - (CALayer*)makeBackingLayer { return [self.class.layerClass layer]; } - (instancetype)initWithFrame:(NSRect)frame highDPI:(BOOL)highDPI windowID:(Uint32)windowID; { if ((self = [super initWithFrame:frame])) { self.highDPI = highDPI; self.sdlWindowID = windowID; self.wantsLayer = YES; /* Allow resize. */ self.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; SDL_AddEventWatch(SDL_MetalViewEventWatch, self); [self updateDrawableSize]; } return self; } - (void)dealloc { SDL_DelEventWatch(SDL_MetalViewEventWatch, self); [super dealloc]; } - (NSInteger)tag { return METALVIEW_TAG; } - (void)updateDrawableSize { CAMetalLayer *metalLayer = (CAMetalLayer *)self.layer; NSSize size = self.bounds.size; NSSize backingSize = size; if (self.highDPI) { /* Note: NSHighResolutionCapable must be set to true in the app's * Info.plist in order for the backing size to be high res. */ backingSize = [self convertSizeToBacking:size]; } metalLayer.contentsScale = backingSize.height / size.height; metalLayer.drawableSize = NSSizeToCGSize(backingSize); } @end SDL_MetalView Cocoa_Metal_CreateView(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData* data = (__bridge SDL_WindowData *)window->driverdata; NSView *view = data->nswindow.contentView; BOOL highDPI = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; Uint32 windowID = SDL_GetWindowID(window); SDL_cocoametalview *newview; SDL_MetalView metalview; newview = [[SDL_cocoametalview alloc] initWithFrame:view.frame highDPI:highDPI windowID:windowID]; if (newview == nil) { return NULL; } [view addSubview:newview]; metalview = (SDL_MetalView)CFBridgingRetain(newview); [newview release]; return metalview; }} void Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view) { @autoreleasepool { SDL_cocoametalview *metalview = CFBridgingRelease(view); [metalview removeFromSuperview]; }} void * Cocoa_Metal_GetLayer(_THIS, SDL_MetalView view) { @autoreleasepool { SDL_cocoametalview *cocoaview = (__bridge SDL_cocoametalview *)view; return (__bridge void *)cocoaview.layer; }} void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; NSView *view = data->nswindow.contentView; SDL_cocoametalview* metalview = [view viewWithTag:METALVIEW_TAG]; if (metalview) { CAMetalLayer *layer = (CAMetalLayer*)metalview.layer; SDL_assert(layer != NULL); if (w) { *w = layer.drawableSize.width; } if (h) { *h = layer.drawableSize.height; } } else { SDL_GetWindowSize(window, w, h); } }} #endif /* SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoametalview.m
Objective-C
apache-2.0
5,696
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoamodes_h_ #define SDL_cocoamodes_h_ typedef struct { CGDirectDisplayID display; } SDL_DisplayData; typedef struct { CFMutableArrayRef modes; } SDL_DisplayModeData; extern void Cocoa_InitModes(_THIS); extern int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); extern int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); extern void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display); extern int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hpdi, float * vdpi); extern int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); extern void Cocoa_QuitModes(_THIS); #endif /* SDL_cocoamodes_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamodes.h
C
apache-2.0
1,754
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "SDL_assert.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_cocoavideo.h" /* We need this for IODisplayCreateInfoDictionary and kIODisplayOnlyPreferredName */ #include <IOKit/graphics/IOGraphicsLib.h> /* We need this for CVDisplayLinkGetNominalOutputVideoRefreshPeriod */ #include <CoreVideo/CVBase.h> #include <CoreVideo/CVDisplayLink.h> /* we need this for ShowMenuBar() and HideMenuBar(). */ #include <Carbon/Carbon.h> /* This gets us MAC_OS_X_VERSION_MIN_REQUIRED... */ #include <AvailabilityMacros.h> #ifndef MAC_OS_X_VERSION_10_13 #define NSAppKitVersionNumber10_12 1504 #endif static void Cocoa_ToggleMenuBar(const BOOL show) { /* !!! FIXME: keep an eye on this. * ShowMenuBar/HideMenuBar is officially unavailable for 64-bit binaries. * It happens to work, as of 10.7, but we're going to see if * we can just simply do without it on newer OSes... */ #if (MAC_OS_X_VERSION_MIN_REQUIRED < 1070) && !defined(__LP64__) if (show) { ShowMenuBar(); } else { HideMenuBar(); } #endif } static int CG_SetError(const char *prefix, CGDisplayErr result) { const char *error; switch (result) { case kCGErrorFailure: error = "kCGErrorFailure"; break; case kCGErrorIllegalArgument: error = "kCGErrorIllegalArgument"; break; case kCGErrorInvalidConnection: error = "kCGErrorInvalidConnection"; break; case kCGErrorInvalidContext: error = "kCGErrorInvalidContext"; break; case kCGErrorCannotComplete: error = "kCGErrorCannotComplete"; break; case kCGErrorNotImplemented: error = "kCGErrorNotImplemented"; break; case kCGErrorRangeCheck: error = "kCGErrorRangeCheck"; break; case kCGErrorTypeCheck: error = "kCGErrorTypeCheck"; break; case kCGErrorInvalidOperation: error = "kCGErrorInvalidOperation"; break; case kCGErrorNoneAvailable: error = "kCGErrorNoneAvailable"; break; default: error = "Unknown Error"; break; } return SDL_SetError("%s: %s", prefix, error); } static int GetDisplayModeRefreshRate(CGDisplayModeRef vidmode, CVDisplayLinkRef link) { int refreshRate = (int) (CGDisplayModeGetRefreshRate(vidmode) + 0.5); /* CGDisplayModeGetRefreshRate can return 0 (eg for built-in displays). */ if (refreshRate == 0 && link != NULL) { CVTime time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link); if ((time.flags & kCVTimeIsIndefinite) == 0 && time.timeValue != 0) { refreshRate = (int) ((time.timeScale / (double) time.timeValue) + 0.5); } } return refreshRate; } static SDL_bool HasValidDisplayModeFlags(CGDisplayModeRef vidmode) { uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode); /* Filter out modes which have flags that we don't want. */ if (ioflags & (kDisplayModeNeverShowFlag | kDisplayModeNotGraphicsQualityFlag)) { return SDL_FALSE; } /* Filter out modes which don't have flags that we want. */ if (!(ioflags & kDisplayModeValidFlag) || !(ioflags & kDisplayModeSafeFlag)) { return SDL_FALSE; } return SDL_TRUE; } static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode) { /* This API is deprecated in 10.11 with no good replacement (as of 10.15). */ CFStringRef fmt = CGDisplayModeCopyPixelEncoding(vidmode); Uint32 pixelformat = SDL_PIXELFORMAT_UNKNOWN; if (CFStringCompare(fmt, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) { pixelformat = SDL_PIXELFORMAT_ARGB8888; } else if (CFStringCompare(fmt, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) { pixelformat = SDL_PIXELFORMAT_ARGB1555; } else if (CFStringCompare(fmt, CFSTR(kIO30BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) { pixelformat = SDL_PIXELFORMAT_ARGB2101010; } else { /* ignore 8-bit and such for now. */ } CFRelease(fmt); return pixelformat; } static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, CFArrayRef modelist, CVDisplayLinkRef link, SDL_DisplayMode *mode) { SDL_DisplayModeData *data; bool usableForGUI = CGDisplayModeIsUsableForDesktopGUI(vidmode); int width = (int) CGDisplayModeGetWidth(vidmode); int height = (int) CGDisplayModeGetHeight(vidmode); uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode); int refreshrate = GetDisplayModeRefreshRate(vidmode, link); Uint32 format = GetDisplayModePixelFormat(vidmode); bool interlaced = (ioflags & kDisplayModeInterlacedFlag) != 0; CFMutableArrayRef modes; if (format == SDL_PIXELFORMAT_UNKNOWN) { return SDL_FALSE; } if (!HasValidDisplayModeFlags(vidmode)) { return SDL_FALSE; } modes = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); CFArrayAppendValue(modes, vidmode); /* If a list of possible diplay modes is passed in, use it to filter out * modes that have duplicate sizes. We don't just rely on SDL's higher level * duplicate filtering because this code can choose what properties are * prefered, and it can add CGDisplayModes to the DisplayModeData's list of * modes to try (see comment below for why that's necessary). * CGDisplayModeGetPixelWidth and friends are only available in 10.8+. */ #ifdef MAC_OS_X_VERSION_10_8 if (modelist != NULL && floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) { int pixelW = (int) CGDisplayModeGetPixelWidth(vidmode); int pixelH = (int) CGDisplayModeGetPixelHeight(vidmode); CFIndex modescount = CFArrayGetCount(modelist); for (int i = 0; i < modescount; i++) { CGDisplayModeRef othermode = (CGDisplayModeRef) CFArrayGetValueAtIndex(modelist, i); uint32_t otherioflags = CGDisplayModeGetIOFlags(othermode); if (CFEqual(vidmode, othermode)) { continue; } if (!HasValidDisplayModeFlags(othermode)) { continue; } int otherW = (int) CGDisplayModeGetWidth(othermode); int otherH = (int) CGDisplayModeGetHeight(othermode); int otherpixelW = (int) CGDisplayModeGetPixelWidth(othermode); int otherpixelH = (int) CGDisplayModeGetPixelHeight(othermode); int otherrefresh = GetDisplayModeRefreshRate(othermode, link); Uint32 otherformat = GetDisplayModePixelFormat(othermode); bool otherGUI = CGDisplayModeIsUsableForDesktopGUI(othermode); /* Ignore this mode if it's low-dpi (@1x) and we have a high-dpi * mode in the list with the same size in points. */ if (width == pixelW && height == pixelH && width == otherW && height == otherH && refreshrate == otherrefresh && format == otherformat && (otherpixelW != otherW || otherpixelH != otherH)) { CFRelease(modes); return SDL_FALSE; } /* Ignore this mode if it's interlaced and there's a non-interlaced * mode in the list with the same properties. */ if (interlaced && ((otherioflags & kDisplayModeInterlacedFlag) == 0) && width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && refreshrate == otherrefresh && format == otherformat && usableForGUI == otherGUI) { CFRelease(modes); return SDL_FALSE; } /* Ignore this mode if it's not usable for desktop UI and its * properties are equal to another GUI-capable mode in the list. */ if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && !usableForGUI && otherGUI && refreshrate == otherrefresh && format == otherformat) { CFRelease(modes); return SDL_FALSE; } /* If multiple modes have the exact same properties, they'll all * go in the list of modes to try when SetDisplayMode is called. * This is needed because kCGDisplayShowDuplicateLowResolutionModes * (which is used to expose highdpi display modes) can make the * list of modes contain duplicates (according to their properties * obtained via public APIs) which don't work with SetDisplayMode. * Those duplicate non-functional modes *do* have different pixel * formats according to their internal data structure viewed with * NSLog, but currently no public API can detect that. * https://bugzilla.libsdl.org/show_bug.cgi?id=4822 * * As of macOS 10.15.0, those duplicates have the exact same * properties via public APIs in every way (even their IO flags and * CGDisplayModeGetIODisplayModeID is the same), so we could test * those for equality here too, but I'm intentionally not doing that * in case there are duplicate modes with different IO flags or IO * display mode IDs in the future. In that case I think it's better * to try them all in SetDisplayMode than to risk one of them being * correct but it being filtered out by SDL_AddDisplayMode as being * a duplicate. */ if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && usableForGUI == otherGUI && refreshrate == otherrefresh && format == otherformat) { CFArrayAppendValue(modes, othermode); } } } #endif data = (SDL_DisplayModeData *) SDL_malloc(sizeof(*data)); if (!data) { CFRelease(modes); return SDL_FALSE; } data->modes = modes; mode->format = format; mode->w = width; mode->h = height; mode->refresh_rate = refreshrate; mode->driverdata = data; return SDL_TRUE; } static const char * Cocoa_GetDisplayName(CGDirectDisplayID displayID) { /* This API is deprecated in 10.9 with no good replacement (as of 10.15). */ io_service_t servicePort = CGDisplayIOServicePort(displayID); CFDictionaryRef deviceInfo = IODisplayCreateInfoDictionary(servicePort, kIODisplayOnlyPreferredName); NSDictionary *localizedNames = [(NSDictionary *)deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]]; const char* displayName = NULL; if ([localizedNames count] > 0) { displayName = SDL_strdup([[localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]] UTF8String]); } CFRelease(deviceInfo); return displayName; } void Cocoa_InitModes(_THIS) { @autoreleasepool { CGDisplayErr result; CGDirectDisplayID *displays; CGDisplayCount numDisplays; SDL_bool isstack; int pass, i; result = CGGetOnlineDisplayList(0, NULL, &numDisplays); if (result != kCGErrorSuccess) { CG_SetError("CGGetOnlineDisplayList()", result); return; } displays = SDL_small_alloc(CGDirectDisplayID, numDisplays, &isstack); result = CGGetOnlineDisplayList(numDisplays, displays, &numDisplays); if (result != kCGErrorSuccess) { CG_SetError("CGGetOnlineDisplayList()", result); SDL_small_free(displays, isstack); return; } /* Pick up the primary display in the first pass, then get the rest */ for (pass = 0; pass < 2; ++pass) { for (i = 0; i < numDisplays; ++i) { SDL_VideoDisplay display; SDL_DisplayData *displaydata; SDL_DisplayMode mode; CGDisplayModeRef moderef = NULL; CVDisplayLinkRef link = NULL; if (pass == 0) { if (!CGDisplayIsMain(displays[i])) { continue; } } else { if (CGDisplayIsMain(displays[i])) { continue; } } if (CGDisplayMirrorsDisplay(displays[i]) != kCGNullDirectDisplay) { continue; } moderef = CGDisplayCopyDisplayMode(displays[i]); if (!moderef) { continue; } displaydata = (SDL_DisplayData *) SDL_malloc(sizeof(*displaydata)); if (!displaydata) { CGDisplayModeRelease(moderef); continue; } displaydata->display = displays[i]; CVDisplayLinkCreateWithCGDisplay(displays[i], &link); SDL_zero(display); /* this returns a stddup'ed string */ display.name = (char *)Cocoa_GetDisplayName(displays[i]); if (!GetDisplayMode(_this, moderef, NULL, link, &mode)) { CVDisplayLinkRelease(link); CGDisplayModeRelease(moderef); SDL_free(display.name); SDL_free(displaydata); continue; } CVDisplayLinkRelease(link); CGDisplayModeRelease(moderef); display.desktop_mode = mode; display.current_mode = mode; display.driverdata = displaydata; SDL_AddVideoDisplay(&display); SDL_free(display.name); } } SDL_small_free(displays, isstack); }} int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; CGRect cgrect; cgrect = CGDisplayBounds(displaydata->display); rect->x = (int)cgrect.origin.x; rect->y = (int)cgrect.origin.y; rect->w = (int)cgrect.size.width; rect->h = (int)cgrect.size.height; return 0; } int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; const CGDirectDisplayID cgdisplay = displaydata->display; NSArray *screens = [NSScreen screens]; NSScreen *screen = nil; /* !!! FIXME: maybe track the NSScreen in SDL_DisplayData? */ for (NSScreen *i in screens) { const CGDirectDisplayID thisDisplay = (CGDirectDisplayID) [[[i deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; if (thisDisplay == cgdisplay) { screen = i; break; } } SDL_assert(screen != nil); /* didn't find it?! */ if (screen == nil) { return -1; } const NSRect frame = [screen visibleFrame]; rect->x = (int)frame.origin.x; rect->y = (int)(CGDisplayPixelsHigh(kCGDirectMainDisplay) - frame.origin.y - frame.size.height); rect->w = (int)frame.size.width; rect->h = (int)frame.size.height; return 0; } int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi) { @autoreleasepool { const float MM_IN_INCH = 25.4f; SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata; /* we need the backingScaleFactor for Retina displays, which is only exposed through NSScreen, not CGDisplay, afaik, so find our screen... */ CGFloat scaleFactor = 1.0f; NSArray *screens = [NSScreen screens]; for (NSScreen *screen in screens) { const CGDirectDisplayID dpyid = (const CGDirectDisplayID ) [[[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; if (dpyid == data->display) { if ([screen respondsToSelector:@selector(backingScaleFactor)]) { // Mac OS X 10.7 and later scaleFactor = [screen backingScaleFactor]; break; } } } const CGSize displaySize = CGDisplayScreenSize(data->display); const int pixelWidth = (int) CGDisplayPixelsWide(data->display); const int pixelHeight = (int) CGDisplayPixelsHigh(data->display); if (ddpi) { *ddpi = (SDL_ComputeDiagonalDPI(pixelWidth, pixelHeight, displaySize.width / MM_IN_INCH, displaySize.height / MM_IN_INCH)) * scaleFactor; } if (hdpi) { *hdpi = (pixelWidth * MM_IN_INCH / displaySize.width) * scaleFactor; } if (vdpi) { *vdpi = (pixelHeight * MM_IN_INCH / displaySize.height) * scaleFactor; } return 0; }} void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata; CVDisplayLinkRef link = NULL; CGDisplayModeRef desktopmoderef; SDL_DisplayMode desktopmode; CFArrayRef modes; CFDictionaryRef dict = NULL; CVDisplayLinkCreateWithCGDisplay(data->display, &link); desktopmoderef = CGDisplayCopyDisplayMode(data->display); /* CopyAllDisplayModes won't always contain the desktop display mode (if * NULL is passed in) - for example on a retina 15" MBP, System Preferences * allows choosing 1920x1200 but it's not in the list. AddDisplayMode makes * sure there are no duplicates so it's safe to always add the desktop mode * even in cases where it is in the CopyAllDisplayModes list. */ if (desktopmoderef && GetDisplayMode(_this, desktopmoderef, NULL, link, &desktopmode)) { if (!SDL_AddDisplayMode(display, &desktopmode)) { CFRelease(((SDL_DisplayModeData*)desktopmode.driverdata)->modes); SDL_free(desktopmode.driverdata); } } CGDisplayModeRelease(desktopmoderef); /* By default, CGDisplayCopyAllDisplayModes will only get a subset of the * system's available modes. For example on a 15" 2016 MBP, users can * choose 1920x1080@2x in System Preferences but it won't show up here, * unless we specify the option below. * The display modes returned by CGDisplayCopyAllDisplayModes are also not * high dpi-capable unless this option is set. * macOS 10.15 also seems to have a bug where entering, exiting, and * re-entering exclusive fullscreen with a low dpi display mode can cause * the content of the screen to move up, which this setting avoids: * https://bugzilla.libsdl.org/show_bug.cgi?id=4822 */ #ifdef MAC_OS_X_VERSION_10_8 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) { const CFStringRef dictkeys[] = {kCGDisplayShowDuplicateLowResolutionModes}; const CFBooleanRef dictvalues[] = {kCFBooleanTrue}; dict = CFDictionaryCreate(NULL, (const void **)dictkeys, (const void **)dictvalues, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } #endif modes = CGDisplayCopyAllDisplayModes(data->display, dict); if (dict) { CFRelease(dict); } if (modes) { CFIndex i; const CFIndex count = CFArrayGetCount(modes); for (i = 0; i < count; i++) { CGDisplayModeRef moderef = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i); SDL_DisplayMode mode; if (GetDisplayMode(_this, moderef, modes, link, &mode)) { if (!SDL_AddDisplayMode(display, &mode)) { CFRelease(((SDL_DisplayModeData*)mode.driverdata)->modes); SDL_free(mode.driverdata); } } } CFRelease(modes); } CVDisplayLinkRelease(link); } static CGError SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayModeData *data) { /* SDL_DisplayModeData can contain multiple CGDisplayModes to try (with * identical properties), some of which might not work. See GetDisplayMode. */ CGError result = kCGErrorFailure; for (CFIndex i = 0; i < CFArrayGetCount(data->modes); i++) { CGDisplayModeRef moderef = (CGDisplayModeRef)CFArrayGetValueAtIndex(data->modes, i); result = CGDisplaySetDisplayMode(display, moderef, NULL); if (result == kCGErrorSuccess) { /* If this mode works, try it first next time. */ CFArrayExchangeValuesAtIndices(data->modes, i, 0); break; } } return result; } int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; SDL_DisplayModeData *data = (SDL_DisplayModeData *) mode->driverdata; CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken; CGError result; /* Fade to black to hide resolution-switching flicker */ if (CGAcquireDisplayFadeReservation(5, &fade_token) == kCGErrorSuccess) { CGDisplayFade(fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE); } if (data == display->desktop_mode.driverdata) { /* Restoring desktop mode */ SetDisplayModeForDisplay(displaydata->display, data); if (CGDisplayIsMain(displaydata->display)) { CGReleaseAllDisplays(); } else { CGDisplayRelease(displaydata->display); } if (CGDisplayIsMain(displaydata->display)) { Cocoa_ToggleMenuBar(YES); } } else { /* Put up the blanking window (a window above all other windows) */ if (CGDisplayIsMain(displaydata->display)) { /* If we don't capture all displays, Cocoa tries to rearrange windows... *sigh* */ result = CGCaptureAllDisplays(); } else { result = CGDisplayCapture(displaydata->display); } if (result != kCGErrorSuccess) { CG_SetError("CGDisplayCapture()", result); goto ERR_NO_CAPTURE; } /* Do the physical switch */ result = SetDisplayModeForDisplay(displaydata->display, data); if (result != kCGErrorSuccess) { CG_SetError("CGDisplaySwitchToMode()", result); goto ERR_NO_SWITCH; } /* Hide the menu bar so it doesn't intercept events */ if (CGDisplayIsMain(displaydata->display)) { Cocoa_ToggleMenuBar(NO); } } /* Fade in again (asynchronously) */ if (fade_token != kCGDisplayFadeReservationInvalidToken) { CGDisplayFade(fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); CGReleaseDisplayFadeReservation(fade_token); } return 0; /* Since the blanking window covers *all* windows (even force quit) correct recovery is crucial */ ERR_NO_SWITCH: if (CGDisplayIsMain(displaydata->display)) { CGReleaseAllDisplays(); } else { CGDisplayRelease(displaydata->display); } ERR_NO_CAPTURE: if (fade_token != kCGDisplayFadeReservationInvalidToken) { CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); CGReleaseDisplayFadeReservation(fade_token); } return -1; } void Cocoa_QuitModes(_THIS) { int i, j; for (i = 0; i < _this->num_displays; ++i) { SDL_VideoDisplay *display = &_this->displays[i]; SDL_DisplayModeData *mode; if (display->current_mode.driverdata != display->desktop_mode.driverdata) { Cocoa_SetDisplayMode(_this, display, &display->desktop_mode); } mode = (SDL_DisplayModeData *) display->desktop_mode.driverdata; CFRelease(mode->modes); for (j = 0; j < display->num_display_modes; j++) { mode = (SDL_DisplayModeData*) display->display_modes[j].driverdata; CFRelease(mode->modes); } } Cocoa_ToggleMenuBar(YES); } #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamodes.m
Objective-C
apache-2.0
24,981
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoamouse_h_ #define SDL_cocoamouse_h_ #include "SDL_cocoavideo.h" extern int Cocoa_InitMouse(_THIS); extern void Cocoa_HandleMouseEvent(_THIS, NSEvent * event); extern void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent * event); extern void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y); extern void Cocoa_QuitMouse(_THIS); typedef struct { /* Wether we've seen a cursor warp since the last move event. */ SDL_bool seenWarp; /* What location our last cursor warp was to. */ CGFloat lastWarpX; CGFloat lastWarpY; /* What location we last saw the cursor move to. */ CGFloat lastMoveX; CGFloat lastMoveY; void *tapdata; } SDL_MouseData; @interface NSCursor (InvisibleCursor) + (NSCursor *)invisibleCursor; @end #endif /* SDL_cocoamouse_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamouse.h
Objective-C
apache-2.0
1,805
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_assert.h" #include "SDL_events.h" #include "SDL_cocoamouse.h" #include "SDL_cocoamousetap.h" #include "SDL_cocoavideo.h" #include "../../events/SDL_mouse_c.h" /* #define DEBUG_COCOAMOUSE */ #ifdef DEBUG_COCOAMOUSE #define DLog(fmt, ...) printf("%s: " fmt "\n", __func__, ##__VA_ARGS__) #else #define DLog(...) do { } while (0) #endif @implementation NSCursor (InvisibleCursor) + (NSCursor *)invisibleCursor { static NSCursor *invisibleCursor = NULL; if (!invisibleCursor) { /* RAW 16x16 transparent GIF */ static unsigned char cursorBytes[] = { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x10, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x01, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0E, 0x8C, 0x8F, 0xA9, 0xCB, 0xED, 0x0F, 0xA3, 0x9C, 0xB4, 0xDA, 0x8B, 0xB3, 0x3E, 0x05, 0x00, 0x3B }; NSData *cursorData = [NSData dataWithBytesNoCopy:&cursorBytes[0] length:sizeof(cursorBytes) freeWhenDone:NO]; NSImage *cursorImage = [[[NSImage alloc] initWithData:cursorData] autorelease]; invisibleCursor = [[NSCursor alloc] initWithImage:cursorImage hotSpot:NSZeroPoint]; } return invisibleCursor; } @end static SDL_Cursor * Cocoa_CreateDefaultCursor() { @autoreleasepool { NSCursor *nscursor; SDL_Cursor *cursor = NULL; nscursor = [NSCursor arrowCursor]; if (nscursor) { cursor = SDL_calloc(1, sizeof(*cursor)); if (cursor) { cursor->driverdata = nscursor; [nscursor retain]; } } return cursor; }} static SDL_Cursor * Cocoa_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y) { @autoreleasepool { NSImage *nsimage; NSCursor *nscursor = NULL; SDL_Cursor *cursor = NULL; nsimage = Cocoa_CreateImage(surface); if (nsimage) { nscursor = [[NSCursor alloc] initWithImage: nsimage hotSpot: NSMakePoint(hot_x, hot_y)]; } if (nscursor) { cursor = SDL_calloc(1, sizeof(*cursor)); if (cursor) { cursor->driverdata = nscursor; } else { [nscursor release]; } } return cursor; }} static SDL_Cursor * Cocoa_CreateSystemCursor(SDL_SystemCursor id) { @autoreleasepool { NSCursor *nscursor = NULL; SDL_Cursor *cursor = NULL; switch(id) { case SDL_SYSTEM_CURSOR_ARROW: nscursor = [NSCursor arrowCursor]; break; case SDL_SYSTEM_CURSOR_IBEAM: nscursor = [NSCursor IBeamCursor]; break; case SDL_SYSTEM_CURSOR_WAIT: nscursor = [NSCursor arrowCursor]; break; case SDL_SYSTEM_CURSOR_CROSSHAIR: nscursor = [NSCursor crosshairCursor]; break; case SDL_SYSTEM_CURSOR_WAITARROW: nscursor = [NSCursor arrowCursor]; break; case SDL_SYSTEM_CURSOR_SIZENWSE: case SDL_SYSTEM_CURSOR_SIZENESW: nscursor = [NSCursor closedHandCursor]; break; case SDL_SYSTEM_CURSOR_SIZEWE: nscursor = [NSCursor resizeLeftRightCursor]; break; case SDL_SYSTEM_CURSOR_SIZENS: nscursor = [NSCursor resizeUpDownCursor]; break; case SDL_SYSTEM_CURSOR_SIZEALL: nscursor = [NSCursor closedHandCursor]; break; case SDL_SYSTEM_CURSOR_NO: nscursor = [NSCursor operationNotAllowedCursor]; break; case SDL_SYSTEM_CURSOR_HAND: nscursor = [NSCursor pointingHandCursor]; break; default: SDL_assert(!"Unknown system cursor"); return NULL; } if (nscursor) { cursor = SDL_calloc(1, sizeof(*cursor)); if (cursor) { /* We'll free it later, so retain it here */ [nscursor retain]; cursor->driverdata = nscursor; } } return cursor; }} static void Cocoa_FreeCursor(SDL_Cursor * cursor) { @autoreleasepool { NSCursor *nscursor = (NSCursor *)cursor->driverdata; [nscursor release]; SDL_free(cursor); }} static int Cocoa_ShowCursor(SDL_Cursor * cursor) { @autoreleasepool { SDL_VideoDevice *device = SDL_GetVideoDevice(); SDL_Window *window = (device ? device->windows : NULL); for (; window != NULL; window = window->next) { SDL_WindowData *driverdata = (SDL_WindowData *)window->driverdata; if (driverdata) { [driverdata->nswindow performSelectorOnMainThread:@selector(invalidateCursorRectsForView:) withObject:[driverdata->nswindow contentView] waitUntilDone:NO]; } } return 0; }} static SDL_Window * SDL_FindWindowAtPoint(const int x, const int y) { const SDL_Point pt = { x, y }; SDL_Window *i; for (i = SDL_GetVideoDevice()->windows; i; i = i->next) { const SDL_Rect r = { i->x, i->y, i->w, i->h }; if (SDL_PointInRect(&pt, &r)) { return i; } } return NULL; } static int Cocoa_WarpMouseGlobal(int x, int y) { SDL_Mouse *mouse = SDL_GetMouse(); if (mouse->focus) { SDL_WindowData *data = (SDL_WindowData *) mouse->focus->driverdata; if ([data->listener isMoving]) { DLog("Postponing warp, window being moved."); [data->listener setPendingMoveX:x Y:y]; return 0; } } const CGPoint point = CGPointMake((float)x, (float)y); Cocoa_HandleMouseWarp(point.x, point.y); CGWarpMouseCursorPosition(point); /* CGWarpMouse causes a short delay by default, which is preventable by * Calling this directly after. CGSetLocalEventsSuppressionInterval can also * prevent it, but it's deprecated as of OS X 10.6. */ if (!mouse->relative_mode) { CGAssociateMouseAndMouseCursorPosition(YES); } /* CGWarpMouseCursorPosition doesn't generate a window event, unlike our * other implementations' APIs. Send what's appropriate. */ if (!mouse->relative_mode) { SDL_Window *win = SDL_FindWindowAtPoint(x, y); SDL_SetMouseFocus(win); if (win) { SDL_assert(win == mouse->focus); SDL_SendMouseMotion(win, mouse->mouseID, 0, x - win->x, y - win->y); } } return 0; } static void Cocoa_WarpMouse(SDL_Window * window, int x, int y) { Cocoa_WarpMouseGlobal(x + window->x, y + window->y); } static int Cocoa_SetRelativeMouseMode(SDL_bool enabled) { /* We will re-apply the relative mode when the window gets focus, if it * doesn't have focus right now. */ SDL_Window *window = SDL_GetMouseFocus(); if (!window) { return 0; } /* We will re-apply the relative mode when the window finishes being moved, * if it is being moved right now. */ SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if ([data->listener isMoving]) { return 0; } CGError result; if (enabled) { DLog("Turning on."); result = CGAssociateMouseAndMouseCursorPosition(NO); } else { DLog("Turning off."); result = CGAssociateMouseAndMouseCursorPosition(YES); } if (result != kCGErrorSuccess) { return SDL_SetError("CGAssociateMouseAndMouseCursorPosition() failed"); } /* The hide/unhide calls are redundant most of the time, but they fix * https://bugzilla.libsdl.org/show_bug.cgi?id=2550 */ if (enabled) { [NSCursor hide]; } else { [NSCursor unhide]; } return 0; } static int Cocoa_CaptureMouse(SDL_Window *window) { /* our Cocoa event code already tracks the mouse outside the window, so all we have to do here is say "okay" and do what we always do. */ return 0; } static Uint32 Cocoa_GetGlobalMouseState(int *x, int *y) { const NSUInteger cocoaButtons = [NSEvent pressedMouseButtons]; const NSPoint cocoaLocation = [NSEvent mouseLocation]; Uint32 retval = 0; *x = (int) cocoaLocation.x; *y = (int) (CGDisplayPixelsHigh(kCGDirectMainDisplay) - cocoaLocation.y); retval |= (cocoaButtons & (1 << 0)) ? SDL_BUTTON_LMASK : 0; retval |= (cocoaButtons & (1 << 1)) ? SDL_BUTTON_RMASK : 0; retval |= (cocoaButtons & (1 << 2)) ? SDL_BUTTON_MMASK : 0; retval |= (cocoaButtons & (1 << 3)) ? SDL_BUTTON_X1MASK : 0; retval |= (cocoaButtons & (1 << 4)) ? SDL_BUTTON_X2MASK : 0; return retval; } int Cocoa_InitMouse(_THIS) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_MouseData *driverdata = (SDL_MouseData*) SDL_calloc(1, sizeof(SDL_MouseData)); if (driverdata == NULL) { return SDL_OutOfMemory(); } mouse->driverdata = driverdata; mouse->CreateCursor = Cocoa_CreateCursor; mouse->CreateSystemCursor = Cocoa_CreateSystemCursor; mouse->ShowCursor = Cocoa_ShowCursor; mouse->FreeCursor = Cocoa_FreeCursor; mouse->WarpMouse = Cocoa_WarpMouse; mouse->WarpMouseGlobal = Cocoa_WarpMouseGlobal; mouse->SetRelativeMouseMode = Cocoa_SetRelativeMouseMode; mouse->CaptureMouse = Cocoa_CaptureMouse; mouse->GetGlobalMouseState = Cocoa_GetGlobalMouseState; SDL_SetDefaultCursor(Cocoa_CreateDefaultCursor()); Cocoa_InitMouseEventTap(driverdata); const NSPoint location = [NSEvent mouseLocation]; driverdata->lastMoveX = location.x; driverdata->lastMoveY = location.y; return 0; } void Cocoa_HandleMouseEvent(_THIS, NSEvent *event) { switch ([event type]) { case NSEventTypeMouseMoved: case NSEventTypeLeftMouseDragged: case NSEventTypeRightMouseDragged: case NSEventTypeOtherMouseDragged: break; default: /* Ignore any other events. */ return; } SDL_Mouse *mouse = SDL_GetMouse(); SDL_MouseData *driverdata = (SDL_MouseData*)mouse->driverdata; if (!driverdata) { return; /* can happen when returning from fullscreen Space on shutdown */ } SDL_MouseID mouseID = mouse ? mouse->mouseID : 0; const SDL_bool seenWarp = driverdata->seenWarp; driverdata->seenWarp = NO; const NSPoint location = [NSEvent mouseLocation]; const CGFloat lastMoveX = driverdata->lastMoveX; const CGFloat lastMoveY = driverdata->lastMoveY; driverdata->lastMoveX = location.x; driverdata->lastMoveY = location.y; DLog("Last seen mouse: (%g, %g)", location.x, location.y); /* Non-relative movement is handled in -[Cocoa_WindowListener mouseMoved:] */ if (!mouse->relative_mode) { return; } /* Ignore events that aren't inside the client area (i.e. title bar.) */ if ([event window]) { NSRect windowRect = [[[event window] contentView] frame]; if (!NSMouseInRect([event locationInWindow], windowRect, NO)) { return; } } float deltaX = [event deltaX]; float deltaY = [event deltaY]; if (seenWarp) { deltaX += (lastMoveX - driverdata->lastWarpX); deltaY += ((CGDisplayPixelsHigh(kCGDirectMainDisplay) - lastMoveY) - driverdata->lastWarpY); DLog("Motion was (%g, %g), offset to (%g, %g)", [event deltaX], [event deltaY], deltaX, deltaY); } SDL_SendMouseMotion(mouse->focus, mouseID, 1, (int)deltaX, (int)deltaY); } void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event) { SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse) { return; } SDL_MouseID mouseID = mouse->mouseID; CGFloat x = -[event deltaX]; CGFloat y = [event deltaY]; SDL_MouseWheelDirection direction = SDL_MOUSEWHEEL_NORMAL; if ([event respondsToSelector:@selector(isDirectionInvertedFromDevice)]) { if ([event isDirectionInvertedFromDevice] == YES) { direction = SDL_MOUSEWHEEL_FLIPPED; } } if (x > 0) { x = SDL_ceil(x); } else if (x < 0) { x = SDL_floor(x); } if (y > 0) { y = SDL_ceil(y); } else if (y < 0) { y = SDL_floor(y); } SDL_SendMouseWheel(window, mouseID, x, y, direction); } void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y) { /* This makes Cocoa_HandleMouseEvent ignore the delta caused by the warp, * since it gets included in the next movement event. */ SDL_MouseData *driverdata = (SDL_MouseData*)SDL_GetMouse()->driverdata; driverdata->lastWarpX = x; driverdata->lastWarpY = y; driverdata->seenWarp = SDL_TRUE; DLog("(%g, %g)", x, y); } void Cocoa_QuitMouse(_THIS) { SDL_Mouse *mouse = SDL_GetMouse(); if (mouse) { if (mouse->driverdata) { Cocoa_QuitMouseEventTap(((SDL_MouseData*)mouse->driverdata)); SDL_free(mouse->driverdata); mouse->driverdata = NULL; } } } #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamouse.m
Objective-C
apache-2.0
14,000
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoamousetap_h_ #define SDL_cocoamousetap_h_ #include "SDL_cocoamouse.h" extern void Cocoa_InitMouseEventTap(SDL_MouseData *driverdata); extern void Cocoa_EnableMouseEventTap(SDL_MouseData *driverdata, SDL_bool enabled); extern void Cocoa_QuitMouseEventTap(SDL_MouseData *driverdata); #endif /* SDL_cocoamousetap_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamousetap.h
C
apache-2.0
1,343
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_cocoamousetap.h" /* Event taps are forbidden in the Mac App Store, so we can only enable this * code if your app doesn't need to ship through the app store. * This code makes it so that a grabbed cursor cannot "leak" a mouse click * past the edge of the window if moving the cursor too fast. */ #if SDL_MAC_NO_SANDBOX #include "SDL_keyboard.h" #include "SDL_cocoavideo.h" #include "../../thread/SDL_systhread.h" #include "../../events/SDL_mouse_c.h" typedef struct { CFMachPortRef tap; CFRunLoopRef runloop; CFRunLoopSourceRef runloopSource; SDL_Thread *thread; SDL_sem *runloopStartedSemaphore; } SDL_MouseEventTapData; static const CGEventMask movementEventsMask = CGEventMaskBit(kCGEventLeftMouseDragged) | CGEventMaskBit(kCGEventRightMouseDragged) | CGEventMaskBit(kCGEventMouseMoved); static const CGEventMask allGrabbedEventsMask = CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp) | CGEventMaskBit(kCGEventRightMouseDown) | CGEventMaskBit(kCGEventRightMouseUp) | CGEventMaskBit(kCGEventOtherMouseDown) | CGEventMaskBit(kCGEventOtherMouseUp) | CGEventMaskBit(kCGEventLeftMouseDragged) | CGEventMaskBit(kCGEventRightMouseDragged) | CGEventMaskBit(kCGEventMouseMoved); static CGEventRef Cocoa_MouseTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { SDL_MouseEventTapData *tapdata = (SDL_MouseEventTapData*)refcon; SDL_Mouse *mouse = SDL_GetMouse(); SDL_Window *window = SDL_GetKeyboardFocus(); NSWindow *nswindow; NSRect windowRect; CGPoint eventLocation; switch (type) { case kCGEventTapDisabledByTimeout: { CGEventTapEnable(tapdata->tap, true); return NULL; } case kCGEventTapDisabledByUserInput: { return NULL; } default: break; } if (!window || !mouse) { return event; } if (mouse->relative_mode) { return event; } if (!(window->flags & SDL_WINDOW_INPUT_GRABBED)) { return event; } /* This is the same coordinate system as Cocoa uses. */ nswindow = ((SDL_WindowData *) window->driverdata)->nswindow; eventLocation = CGEventGetUnflippedLocation(event); windowRect = [nswindow contentRectForFrameRect:[nswindow frame]]; if (!NSMouseInRect(NSPointFromCGPoint(eventLocation), windowRect, NO)) { /* This is in CGs global screenspace coordinate system, which has a * flipped Y. */ CGPoint newLocation = CGEventGetLocation(event); if (eventLocation.x < NSMinX(windowRect)) { newLocation.x = NSMinX(windowRect); } else if (eventLocation.x >= NSMaxX(windowRect)) { newLocation.x = NSMaxX(windowRect) - 1.0; } if (eventLocation.y <= NSMinY(windowRect)) { newLocation.y -= (NSMinY(windowRect) - eventLocation.y + 1); } else if (eventLocation.y > NSMaxY(windowRect)) { newLocation.y += (eventLocation.y - NSMaxY(windowRect)); } CGWarpMouseCursorPosition(newLocation); CGAssociateMouseAndMouseCursorPosition(YES); if ((CGEventMaskBit(type) & movementEventsMask) == 0) { /* For click events, we just constrain the event to the window, so * no other app receives the click event. We can't due the same to * movement events, since they mean that our warp cursor above * behaves strangely. */ CGEventSetLocation(event, newLocation); } } return event; } static void SemaphorePostCallback(CFRunLoopTimerRef timer, void *info) { SDL_SemPost((SDL_sem*)info); } static int Cocoa_MouseTapThread(void *data) { SDL_MouseEventTapData *tapdata = (SDL_MouseEventTapData*)data; /* Tap was created on main thread but we own it now. */ CFMachPortRef eventTap = tapdata->tap; if (eventTap) { /* Try to create a runloop source we can schedule. */ CFRunLoopSourceRef runloopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0); if (runloopSource) { tapdata->runloopSource = runloopSource; } else { CFRelease(eventTap); SDL_SemPost(tapdata->runloopStartedSemaphore); /* TODO: Both here and in the return below, set some state in * tapdata to indicate that initialization failed, which we should * check in InitMouseEventTap, after we move the semaphore check * from Quit to Init. */ return 1; } } else { SDL_SemPost(tapdata->runloopStartedSemaphore); return 1; } tapdata->runloop = CFRunLoopGetCurrent(); CFRunLoopAddSource(tapdata->runloop, tapdata->runloopSource, kCFRunLoopCommonModes); CFRunLoopTimerContext context = {.info = tapdata->runloopStartedSemaphore}; /* We signal the runloop started semaphore *after* the run loop has started, indicating it's safe to CFRunLoopStop it. */ CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), 0, 0, 0, &SemaphorePostCallback, &context); CFRunLoopAddTimer(tapdata->runloop, timer, kCFRunLoopCommonModes); CFRelease(timer); /* Run the event loop to handle events in the event tap. */ CFRunLoopRun(); /* Make sure this is signaled so that SDL_QuitMouseEventTap knows it can safely SDL_WaitThread for us. */ if (SDL_SemValue(tapdata->runloopStartedSemaphore) < 1) { SDL_SemPost(tapdata->runloopStartedSemaphore); } CFRunLoopRemoveSource(tapdata->runloop, tapdata->runloopSource, kCFRunLoopCommonModes); /* Clean up. */ CGEventTapEnable(tapdata->tap, false); CFRelease(tapdata->runloopSource); CFRelease(tapdata->tap); tapdata->runloopSource = NULL; tapdata->tap = NULL; return 0; } void Cocoa_InitMouseEventTap(SDL_MouseData* driverdata) { SDL_MouseEventTapData *tapdata; driverdata->tapdata = SDL_calloc(1, sizeof(SDL_MouseEventTapData)); tapdata = (SDL_MouseEventTapData*)driverdata->tapdata; tapdata->runloopStartedSemaphore = SDL_CreateSemaphore(0); if (tapdata->runloopStartedSemaphore) { tapdata->tap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, allGrabbedEventsMask, &Cocoa_MouseTapCallback, tapdata); if (tapdata->tap) { /* Tap starts disabled, until app requests mouse grab */ CGEventTapEnable(tapdata->tap, false); tapdata->thread = SDL_CreateThreadInternal(&Cocoa_MouseTapThread, "Event Tap Loop", 512 * 1024, tapdata); if (tapdata->thread) { /* Success - early out. Ownership transferred to thread. */ return; } CFRelease(tapdata->tap); } SDL_DestroySemaphore(tapdata->runloopStartedSemaphore); } SDL_free(driverdata->tapdata); driverdata->tapdata = NULL; } void Cocoa_EnableMouseEventTap(SDL_MouseData *driverdata, SDL_bool enabled) { SDL_MouseEventTapData *tapdata = (SDL_MouseEventTapData*)driverdata->tapdata; if (tapdata && tapdata->tap) { CGEventTapEnable(tapdata->tap, !!enabled); } } void Cocoa_QuitMouseEventTap(SDL_MouseData *driverdata) { SDL_MouseEventTapData *tapdata = (SDL_MouseEventTapData*)driverdata->tapdata; int status; if (tapdata == NULL) { /* event tap was already cleaned up (possibly due to CGEventTapCreate * returning null.) */ return; } /* Ensure that the runloop has been started first. * TODO: Move this to InitMouseEventTap, check for error conditions that can * happen in Cocoa_MouseTapThread, and fall back to the non-EventTap way of * grabbing the mouse if it fails to Init. */ status = SDL_SemWaitTimeout(tapdata->runloopStartedSemaphore, 5000); if (status > -1) { /* Then stop it, which will cause Cocoa_MouseTapThread to return. */ CFRunLoopStop(tapdata->runloop); /* And then wait for Cocoa_MouseTapThread to finish cleaning up. It * releases some of the pointers in tapdata. */ SDL_WaitThread(tapdata->thread, &status); } SDL_free(driverdata->tapdata); driverdata->tapdata = NULL; } #else /* SDL_MAC_NO_SANDBOX */ void Cocoa_InitMouseEventTap(SDL_MouseData *unused) { } void Cocoa_EnableMouseEventTap(SDL_MouseData *driverdata, SDL_bool enabled) { } void Cocoa_QuitMouseEventTap(SDL_MouseData *driverdata) { } #endif /* !SDL_MAC_NO_SANDBOX */ #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoamousetap.m
Objective-C
apache-2.0
9,842
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoaopengl_h_ #define SDL_cocoaopengl_h_ #if SDL_VIDEO_OPENGL_CGL #include "SDL_atomic.h" #import <Cocoa/Cocoa.h> /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif struct SDL_GLDriverData { int initialized; }; @interface SDLOpenGLContext : NSOpenGLContext { SDL_atomic_t dirty; SDL_Window *window; } - (id)initWithFormat:(NSOpenGLPixelFormat *)format shareContext:(NSOpenGLContext *)share; - (void)scheduleUpdate; - (void)updateIfNeeded; - (void)setWindow:(SDL_Window *)window; - (SDL_Window*)window; - (void)explicitUpdate; @end /* OpenGL functions */ extern int Cocoa_GL_LoadLibrary(_THIS, const char *path); extern void *Cocoa_GL_GetProcAddress(_THIS, const char *proc); extern void Cocoa_GL_UnloadLibrary(_THIS); extern SDL_GLContext Cocoa_GL_CreateContext(_THIS, SDL_Window * window); extern int Cocoa_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern void Cocoa_GL_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h); extern int Cocoa_GL_SetSwapInterval(_THIS, int interval); extern int Cocoa_GL_GetSwapInterval(_THIS); extern int Cocoa_GL_SwapWindow(_THIS, SDL_Window * window); extern void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context); #ifdef __clang__ #pragma clang diagnostic pop #endif #endif /* SDL_VIDEO_OPENGL_CGL */ #endif /* SDL_cocoaopengl_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaopengl.h
Objective-C
apache-2.0
2,610
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" /* NSOpenGL implementation of SDL OpenGL support */ #if SDL_VIDEO_OPENGL_CGL #include "SDL_cocoavideo.h" #include "SDL_cocoaopengl.h" #include "SDL_cocoaopengles.h" #include <OpenGL/CGLTypes.h> #include <OpenGL/OpenGL.h> #include <OpenGL/CGLRenderers.h> #include "SDL_loadso.h" #include "SDL_opengl.h" #define DEFAULT_OPENGL "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib" /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif @implementation SDLOpenGLContext : NSOpenGLContext - (id)initWithFormat:(NSOpenGLPixelFormat *)format shareContext:(NSOpenGLContext *)share { self = [super initWithFormat:format shareContext:share]; if (self) { SDL_AtomicSet(&self->dirty, 0); self->window = NULL; } return self; } - (void)scheduleUpdate { SDL_AtomicAdd(&self->dirty, 1); } /* This should only be called on the thread on which a user is using the context. */ - (void)updateIfNeeded { const int value = SDL_AtomicSet(&self->dirty, 0); if (value > 0) { /* We call the real underlying update here, since -[SDLOpenGLContext update] just calls us. */ [self explicitUpdate]; } } /* This should only be called on the thread on which a user is using the context. */ - (void)update { /* This ensures that regular 'update' calls clear the atomic dirty flag. */ [self scheduleUpdate]; [self updateIfNeeded]; } /* Updates the drawable for the contexts and manages related state. */ - (void)setWindow:(SDL_Window *)newWindow { if (self->window) { SDL_WindowData *oldwindowdata = (SDL_WindowData *)self->window->driverdata; /* Make sure to remove us from the old window's context list, or we'll get scheduled updates from it too. */ NSMutableArray *contexts = oldwindowdata->nscontexts; @synchronized (contexts) { [contexts removeObject:self]; } } self->window = newWindow; if (newWindow) { SDL_WindowData *windowdata = (SDL_WindowData *)newWindow->driverdata; NSView *contentview = windowdata->sdlContentView; /* Now sign up for scheduled updates for the new window. */ NSMutableArray *contexts = windowdata->nscontexts; @synchronized (contexts) { [contexts addObject:self]; } if ([self view] != contentview) { if ([NSThread isMainThread]) { [self setView:contentview]; } else { dispatch_sync(dispatch_get_main_queue(), ^{ [self setView:contentview]; }); } if (self == [NSOpenGLContext currentContext]) { [self explicitUpdate]; } else { [self scheduleUpdate]; } } } else { [self clearDrawable]; if (self == [NSOpenGLContext currentContext]) { [self explicitUpdate]; } else { [self scheduleUpdate]; } } } - (SDL_Window*)window { return self->window; } - (void)explicitUpdate { if ([NSThread isMainThread]) { [super update]; } else { dispatch_sync(dispatch_get_main_queue(), ^{ [super update]; }); } } @end int Cocoa_GL_LoadLibrary(_THIS, const char *path) { /* Load the OpenGL library */ if (path == NULL) { path = SDL_getenv("SDL_OPENGL_LIBRARY"); } if (path == NULL) { path = DEFAULT_OPENGL; } _this->gl_config.dll_handle = SDL_LoadObject(path); if (!_this->gl_config.dll_handle) { return -1; } SDL_strlcpy(_this->gl_config.driver_path, path, SDL_arraysize(_this->gl_config.driver_path)); return 0; } void * Cocoa_GL_GetProcAddress(_THIS, const char *proc) { return SDL_LoadFunction(_this->gl_config.dll_handle, proc); } void Cocoa_GL_UnloadLibrary(_THIS) { SDL_UnloadObject(_this->gl_config.dll_handle); _this->gl_config.dll_handle = NULL; } SDL_GLContext Cocoa_GL_CreateContext(_THIS, SDL_Window * window) { @autoreleasepool { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata; SDL_bool lion_or_later = floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6; NSOpenGLPixelFormatAttribute attr[32]; NSOpenGLPixelFormat *fmt; SDLOpenGLContext *context; NSOpenGLContext *share_context = nil; int i = 0; const char *glversion; int glversion_major; int glversion_minor; if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { #if SDL_VIDEO_OPENGL_EGL /* Switch to EGL based functions */ Cocoa_GL_UnloadLibrary(_this); _this->GL_LoadLibrary = Cocoa_GLES_LoadLibrary; _this->GL_GetProcAddress = Cocoa_GLES_GetProcAddress; _this->GL_UnloadLibrary = Cocoa_GLES_UnloadLibrary; _this->GL_CreateContext = Cocoa_GLES_CreateContext; _this->GL_MakeCurrent = Cocoa_GLES_MakeCurrent; _this->GL_SetSwapInterval = Cocoa_GLES_SetSwapInterval; _this->GL_GetSwapInterval = Cocoa_GLES_GetSwapInterval; _this->GL_SwapWindow = Cocoa_GLES_SwapWindow; _this->GL_DeleteContext = Cocoa_GLES_DeleteContext; if (Cocoa_GLES_LoadLibrary(_this, NULL) != 0) { return NULL; } return Cocoa_GLES_CreateContext(_this, window); #else SDL_SetError("SDL not configured with EGL support"); return NULL; #endif } if ((_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_CORE) && !lion_or_later) { SDL_SetError ("OpenGL Core Profile is not supported on this platform version"); return NULL; } attr[i++] = NSOpenGLPFAAllowOfflineRenderers; /* specify a profile if we're on Lion (10.7) or later. */ if (lion_or_later) { NSOpenGLPixelFormatAttribute profile = NSOpenGLProfileVersionLegacy; if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_CORE) { profile = NSOpenGLProfileVersion3_2Core; } attr[i++] = NSOpenGLPFAOpenGLProfile; attr[i++] = profile; } attr[i++] = NSOpenGLPFAColorSize; attr[i++] = SDL_BYTESPERPIXEL(display->current_mode.format)*8; attr[i++] = NSOpenGLPFADepthSize; attr[i++] = _this->gl_config.depth_size; if (_this->gl_config.double_buffer) { attr[i++] = NSOpenGLPFADoubleBuffer; } if (_this->gl_config.stereo) { attr[i++] = NSOpenGLPFAStereo; } if (_this->gl_config.stencil_size) { attr[i++] = NSOpenGLPFAStencilSize; attr[i++] = _this->gl_config.stencil_size; } if ((_this->gl_config.accum_red_size + _this->gl_config.accum_green_size + _this->gl_config.accum_blue_size + _this->gl_config.accum_alpha_size) > 0) { attr[i++] = NSOpenGLPFAAccumSize; attr[i++] = _this->gl_config.accum_red_size + _this->gl_config.accum_green_size + _this->gl_config.accum_blue_size + _this->gl_config.accum_alpha_size; } if (_this->gl_config.multisamplebuffers) { attr[i++] = NSOpenGLPFASampleBuffers; attr[i++] = _this->gl_config.multisamplebuffers; } if (_this->gl_config.multisamplesamples) { attr[i++] = NSOpenGLPFASamples; attr[i++] = _this->gl_config.multisamplesamples; attr[i++] = NSOpenGLPFANoRecovery; } if (_this->gl_config.accelerated >= 0) { if (_this->gl_config.accelerated) { attr[i++] = NSOpenGLPFAAccelerated; } else { attr[i++] = NSOpenGLPFARendererID; attr[i++] = kCGLRendererGenericFloatID; } } attr[i++] = NSOpenGLPFAScreenMask; attr[i++] = CGDisplayIDToOpenGLDisplayMask(displaydata->display); attr[i] = 0; fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr]; if (fmt == nil) { SDL_SetError("Failed creating OpenGL pixel format"); return NULL; } if (_this->gl_config.share_with_current_context) { share_context = (NSOpenGLContext*)SDL_GL_GetCurrentContext(); } context = [[SDLOpenGLContext alloc] initWithFormat:fmt shareContext:share_context]; [fmt release]; if (context == nil) { SDL_SetError("Failed creating OpenGL context"); return NULL; } if ( Cocoa_GL_MakeCurrent(_this, window, context) < 0 ) { Cocoa_GL_DeleteContext(_this, context); SDL_SetError("Failed making OpenGL context current"); return NULL; } if (_this->gl_config.major_version < 3 && _this->gl_config.profile_mask == 0 && _this->gl_config.flags == 0) { /* This is a legacy profile, so to match other backends, we're done. */ } else { const GLubyte *(APIENTRY * glGetStringFunc)(GLenum); glGetStringFunc = (const GLubyte *(APIENTRY *)(GLenum)) SDL_GL_GetProcAddress("glGetString"); if (!glGetStringFunc) { Cocoa_GL_DeleteContext(_this, context); SDL_SetError ("Failed getting OpenGL glGetString entry point"); return NULL; } glversion = (const char *)glGetStringFunc(GL_VERSION); if (glversion == NULL) { Cocoa_GL_DeleteContext(_this, context); SDL_SetError ("Failed getting OpenGL context version"); return NULL; } if (SDL_sscanf(glversion, "%d.%d", &glversion_major, &glversion_minor) != 2) { Cocoa_GL_DeleteContext(_this, context); SDL_SetError ("Failed parsing OpenGL context version"); return NULL; } if ((glversion_major < _this->gl_config.major_version) || ((glversion_major == _this->gl_config.major_version) && (glversion_minor < _this->gl_config.minor_version))) { Cocoa_GL_DeleteContext(_this, context); SDL_SetError ("Failed creating OpenGL context at version requested"); return NULL; } /* In the future we'll want to do this, but to match other platforms we'll leave the OpenGL version the way it is for now */ /*_this->gl_config.major_version = glversion_major;*/ /*_this->gl_config.minor_version = glversion_minor;*/ } return context; }} int Cocoa_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) { @autoreleasepool { if (context) { SDLOpenGLContext *nscontext = (SDLOpenGLContext *)context; if ([nscontext window] != window) { [nscontext setWindow:window]; [nscontext updateIfNeeded]; } [nscontext makeCurrentContext]; } else { [NSOpenGLContext clearCurrentContext]; } return 0; }} void Cocoa_GL_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) { SDL_WindowData *windata = (SDL_WindowData *) window->driverdata; NSView *contentView = windata->sdlContentView; NSRect viewport = [contentView bounds]; if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { /* This gives us the correct viewport for a Retina-enabled view, only * supported on 10.7+. */ if ([contentView respondsToSelector:@selector(convertRectToBacking:)]) { viewport = [contentView convertRectToBacking:viewport]; } } if (w) { *w = viewport.size.width; } if (h) { *h = viewport.size.height; } } int Cocoa_GL_SetSwapInterval(_THIS, int interval) { @autoreleasepool { NSOpenGLContext *nscontext; GLint value; int status; if (interval < 0) { /* no extension for this on Mac OS X at the moment. */ return SDL_SetError("Late swap tearing currently unsupported"); } nscontext = (NSOpenGLContext*)SDL_GL_GetCurrentContext(); if (nscontext != nil) { value = interval; [nscontext setValues:&value forParameter:NSOpenGLCPSwapInterval]; status = 0; } else { status = SDL_SetError("No current OpenGL context"); } return status; }} int Cocoa_GL_GetSwapInterval(_THIS) { @autoreleasepool { NSOpenGLContext *nscontext; GLint value; int status = 0; nscontext = (NSOpenGLContext*)SDL_GL_GetCurrentContext(); if (nscontext != nil) { [nscontext getValues:&value forParameter:NSOpenGLCPSwapInterval]; status = (int)value; } return status; }} int Cocoa_GL_SwapWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDLOpenGLContext* nscontext = (SDLOpenGLContext*)SDL_GL_GetCurrentContext(); SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata; /* on 10.14 ("Mojave") and later, this deadlocks if two contexts in two threads try to swap at the same time, so put a mutex around it. */ SDL_LockMutex(videodata->swaplock); [nscontext flushBuffer]; [nscontext updateIfNeeded]; SDL_UnlockMutex(videodata->swaplock); return 0; }} void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context) { @autoreleasepool { SDLOpenGLContext *nscontext = (SDLOpenGLContext *)context; [nscontext setWindow:NULL]; [nscontext release]; }} /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ #pragma clang diagnostic pop #endif #endif /* SDL_VIDEO_OPENGL_CGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaopengl.m
Objective-C
apache-2.0
14,427
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoaopengles_h_ #define SDL_cocoaopengles_h_ #if SDL_VIDEO_OPENGL_EGL #include "../SDL_sysvideo.h" #include "../SDL_egl_c.h" /* OpenGLES functions */ #define Cocoa_GLES_GetAttribute SDL_EGL_GetAttribute #define Cocoa_GLES_GetProcAddress SDL_EGL_GetProcAddress #define Cocoa_GLES_UnloadLibrary SDL_EGL_UnloadLibrary #define Cocoa_GLES_GetSwapInterval SDL_EGL_GetSwapInterval #define Cocoa_GLES_SetSwapInterval SDL_EGL_SetSwapInterval extern int Cocoa_GLES_LoadLibrary(_THIS, const char *path); extern SDL_GLContext Cocoa_GLES_CreateContext(_THIS, SDL_Window * window); extern int Cocoa_GLES_SwapWindow(_THIS, SDL_Window * window); extern int Cocoa_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern void Cocoa_GLES_DeleteContext(_THIS, SDL_GLContext context); extern int Cocoa_GLES_SetupWindow(_THIS, SDL_Window * window); #endif /* SDL_VIDEO_OPENGL_EGL */ #endif /* SDL_cocoaopengles_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaopengles.h
C
apache-2.0
1,942
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA && SDL_VIDEO_OPENGL_EGL #include "SDL_cocoavideo.h" #include "SDL_cocoaopengles.h" #include "SDL_cocoaopengl.h" /* EGL implementation of SDL OpenGL support */ int Cocoa_GLES_LoadLibrary(_THIS, const char *path) { /* If the profile requested is not GL ES, switch over to WIN_GL functions */ if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) { #if SDL_VIDEO_OPENGL_CGL Cocoa_GLES_UnloadLibrary(_this); _this->GL_LoadLibrary = Cocoa_GL_LoadLibrary; _this->GL_GetProcAddress = Cocoa_GL_GetProcAddress; _this->GL_UnloadLibrary = Cocoa_GL_UnloadLibrary; _this->GL_CreateContext = Cocoa_GL_CreateContext; _this->GL_MakeCurrent = Cocoa_GL_MakeCurrent; _this->GL_SetSwapInterval = Cocoa_GL_SetSwapInterval; _this->GL_GetSwapInterval = Cocoa_GL_GetSwapInterval; _this->GL_SwapWindow = Cocoa_GL_SwapWindow; _this->GL_DeleteContext = Cocoa_GL_DeleteContext; return Cocoa_GL_LoadLibrary(_this, path); #else return SDL_SetError("SDL not configured with OpenGL/CGL support"); #endif } if (_this->egl_data == NULL) { return SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0); } return 0; } SDL_GLContext Cocoa_GLES_CreateContext(_THIS, SDL_Window * window) { SDL_GLContext context; SDL_WindowData *data = (SDL_WindowData *)window->driverdata; #if SDL_VIDEO_OPENGL_CGL if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) { /* Switch to CGL based functions */ Cocoa_GLES_UnloadLibrary(_this); _this->GL_LoadLibrary = Cocoa_GL_LoadLibrary; _this->GL_GetProcAddress = Cocoa_GL_GetProcAddress; _this->GL_UnloadLibrary = Cocoa_GL_UnloadLibrary; _this->GL_CreateContext = Cocoa_GL_CreateContext; _this->GL_MakeCurrent = Cocoa_GL_MakeCurrent; _this->GL_SetSwapInterval = Cocoa_GL_SetSwapInterval; _this->GL_GetSwapInterval = Cocoa_GL_GetSwapInterval; _this->GL_SwapWindow = Cocoa_GL_SwapWindow; _this->GL_DeleteContext = Cocoa_GL_DeleteContext; if (Cocoa_GL_LoadLibrary(_this, NULL) != 0) { return NULL; } return Cocoa_GL_CreateContext(_this, window); } #endif context = SDL_EGL_CreateContext(_this, data->egl_surface); return context; } void Cocoa_GLES_DeleteContext(_THIS, SDL_GLContext context) { SDL_EGL_DeleteContext(_this, context); Cocoa_GLES_UnloadLibrary(_this); } SDL_EGL_SwapWindow_impl(Cocoa) SDL_EGL_MakeCurrent_impl(Cocoa) int Cocoa_GLES_SetupWindow(_THIS, SDL_Window * window) { /* The current context is lost in here; save it and reset it. */ SDL_WindowData *windowdata = (SDL_WindowData *) window->driverdata; SDL_Window *current_win = SDL_GL_GetCurrentWindow(); SDL_GLContext current_ctx = SDL_GL_GetCurrentContext(); if (_this->egl_data == NULL) { if (SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0) < 0) { SDL_EGL_UnloadLibrary(_this); return -1; } } /* Create the GLES window surface */ NSView* v = windowdata->nswindow.contentView; windowdata->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType)[v layer]); if (windowdata->egl_surface == EGL_NO_SURFACE) { return SDL_SetError("Could not create GLES window surface"); } return Cocoa_GLES_MakeCurrent(_this, current_win, current_ctx); } #endif /* SDL_VIDEO_DRIVER_COCOA && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoaopengles.m
Objective-C
apache-2.0
4,536
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoashape_h_ #define SDL_cocoashape_h_ #include "SDL_stdinc.h" #include "SDL_video.h" #include "SDL_shape.h" #include "../SDL_shape_internals.h" typedef struct { NSGraphicsContext* context; SDL_bool saved; SDL_ShapeTree* shape; } SDL_ShapeData; extern SDL_WindowShaper* Cocoa_CreateShaper(SDL_Window* window); extern int Cocoa_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode); extern int Cocoa_ResizeWindowShape(SDL_Window *window); #endif /* SDL_cocoashape_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoashape.h
C
apache-2.0
1,546
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL_cocoavideo.h" #include "SDL_shape.h" #include "SDL_cocoashape.h" #include "../SDL_sysvideo.h" #include "SDL_assert.h" SDL_WindowShaper* Cocoa_CreateShaper(SDL_Window* window) { SDL_WindowData* windata = (SDL_WindowData*)window->driverdata; [windata->nswindow setOpaque:NO]; [windata->nswindow setStyleMask:NSWindowStyleMaskBorderless]; SDL_WindowShaper* result = result = malloc(sizeof(SDL_WindowShaper)); result->window = window; result->mode.mode = ShapeModeDefault; result->mode.parameters.binarizationCutoff = 1; result->userx = result->usery = 0; window->shaper = result; SDL_ShapeData* data = malloc(sizeof(SDL_ShapeData)); result->driverdata = data; data->context = [windata->nswindow graphicsContext]; data->saved = SDL_FALSE; data->shape = NULL; int resized_properly = Cocoa_ResizeWindowShape(window); SDL_assert(resized_properly == 0); return result; } typedef struct { NSView* view; NSBezierPath* path; SDL_Window* window; } SDL_CocoaClosure; void ConvertRects(SDL_ShapeTree* tree, void* closure) { SDL_CocoaClosure* data = (SDL_CocoaClosure*)closure; if(tree->kind == OpaqueShape) { NSRect rect = NSMakeRect(tree->data.shape.x,data->window->h - tree->data.shape.y,tree->data.shape.w,tree->data.shape.h); [data->path appendBezierPathWithRect:[data->view convertRect:rect toView:nil]]; } } int Cocoa_SetWindowShape(SDL_WindowShaper *shaper, SDL_Surface *shape, SDL_WindowShapeMode *shape_mode) { @autoreleasepool { SDL_ShapeData* data = (SDL_ShapeData*)shaper->driverdata; SDL_WindowData* windata = (SDL_WindowData*)shaper->window->driverdata; SDL_CocoaClosure closure; if(data->saved == SDL_TRUE) { [data->context restoreGraphicsState]; data->saved = SDL_FALSE; } /*[data->context saveGraphicsState];*/ /*data->saved = SDL_TRUE;*/ [NSGraphicsContext setCurrentContext:data->context]; [[NSColor clearColor] set]; NSRectFill([windata->sdlContentView frame]); data->shape = SDL_CalculateShapeTree(*shape_mode,shape); closure.view = windata->sdlContentView; closure.path = [NSBezierPath bezierPath]; closure.window = shaper->window; SDL_TraverseShapeTree(data->shape,&ConvertRects,&closure); [closure.path addClip]; return 0; }} int Cocoa_ResizeWindowShape(SDL_Window *window) { SDL_ShapeData* data = window->shaper->driverdata; SDL_assert(data != NULL); return 0; } #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoashape.m
Objective-C
apache-2.0
3,579
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoavideo_h_ #define SDL_cocoavideo_h_ #include "SDL_opengl.h" #include <ApplicationServices/ApplicationServices.h> #include <IOKit/pwr_mgt/IOPMLib.h> #include <Cocoa/Cocoa.h> #include "SDL_keycode.h" #include "../SDL_sysvideo.h" #include "SDL_cocoaclipboard.h" #include "SDL_cocoaevents.h" #include "SDL_cocoakeyboard.h" #include "SDL_cocoamodes.h" #include "SDL_cocoamouse.h" #include "SDL_cocoaopengl.h" #include "SDL_cocoawindow.h" #ifndef MAC_OS_X_VERSION_10_12 #define DECLARE_EVENT(name) static const NSEventType NSEventType##name = NS##name DECLARE_EVENT(LeftMouseDown); DECLARE_EVENT(LeftMouseUp); DECLARE_EVENT(RightMouseDown); DECLARE_EVENT(RightMouseUp); DECLARE_EVENT(OtherMouseDown); DECLARE_EVENT(OtherMouseUp); DECLARE_EVENT(MouseMoved); DECLARE_EVENT(LeftMouseDragged); DECLARE_EVENT(RightMouseDragged); DECLARE_EVENT(OtherMouseDragged); DECLARE_EVENT(ScrollWheel); DECLARE_EVENT(KeyDown); DECLARE_EVENT(KeyUp); DECLARE_EVENT(FlagsChanged); #undef DECLARE_EVENT static const NSEventMask NSEventMaskAny = NSAnyEventMask; #define DECLARE_MODIFIER_FLAG(name) static const NSUInteger NSEventModifierFlag##name = NS##name##KeyMask DECLARE_MODIFIER_FLAG(Shift); DECLARE_MODIFIER_FLAG(Control); DECLARE_MODIFIER_FLAG(Command); DECLARE_MODIFIER_FLAG(NumericPad); DECLARE_MODIFIER_FLAG(Help); DECLARE_MODIFIER_FLAG(Function); #undef DECLARE_MODIFIER_FLAG static const NSUInteger NSEventModifierFlagCapsLock = NSAlphaShiftKeyMask; static const NSUInteger NSEventModifierFlagOption = NSAlternateKeyMask; #define DECLARE_WINDOW_MASK(name) static const unsigned int NSWindowStyleMask##name = NS##name##WindowMask DECLARE_WINDOW_MASK(Borderless); DECLARE_WINDOW_MASK(Titled); DECLARE_WINDOW_MASK(Closable); DECLARE_WINDOW_MASK(Miniaturizable); DECLARE_WINDOW_MASK(Resizable); DECLARE_WINDOW_MASK(TexturedBackground); DECLARE_WINDOW_MASK(UnifiedTitleAndToolbar); DECLARE_WINDOW_MASK(FullScreen); /*DECLARE_WINDOW_MASK(FullSizeContentView);*/ /* Not used, fails compile on older SDKs */ static const unsigned int NSWindowStyleMaskUtilityWindow = NSUtilityWindowMask; static const unsigned int NSWindowStyleMaskDocModalWindow = NSDocModalWindowMask; static const unsigned int NSWindowStyleMaskHUDWindow = NSHUDWindowMask; #undef DECLARE_WINDOW_MASK #define DECLARE_ALERT_STYLE(name) static const NSUInteger NSAlertStyle##name = NS##name##AlertStyle DECLARE_ALERT_STYLE(Warning); DECLARE_ALERT_STYLE(Informational); DECLARE_ALERT_STYLE(Critical); #undef DECLARE_ALERT_STYLE #endif /* Private display data */ @class SDLTranslatorResponder; typedef struct SDL_VideoData { int allow_spaces; unsigned int modifierFlags; void *key_layout; SDLTranslatorResponder *fieldEdit; NSInteger clipboard_count; Uint32 screensaver_activity; BOOL screensaver_use_iopm; IOPMAssertionID screensaver_assertion; SDL_mutex *swaplock; } SDL_VideoData; /* Utility functions */ extern NSImage * Cocoa_CreateImage(SDL_Surface * surface); /* Fix build with the 10.11 SDK */ #if MAC_OS_X_VERSION_MAX_ALLOWED < 101200 #define NSEventSubtypeMouseEvent NSMouseEventSubtype #endif #endif /* SDL_cocoavideo_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoavideo.h
Objective-C
apache-2.0
4,151
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #include "SDL.h" #include "SDL_endian.h" #include "SDL_cocoavideo.h" #include "SDL_cocoashape.h" #include "SDL_cocoavulkan.h" #include "SDL_cocoametalview.h" #include "SDL_assert.h" /* Initialization/Query functions */ static int Cocoa_VideoInit(_THIS); static void Cocoa_VideoQuit(_THIS); /* Cocoa driver bootstrap functions */ static int Cocoa_Available(void) { return (1); } static void Cocoa_DeleteDevice(SDL_VideoDevice * device) { SDL_free(device->driverdata); SDL_free(device); } static SDL_VideoDevice * Cocoa_CreateDevice(int devindex) { SDL_VideoDevice *device; SDL_VideoData *data; Cocoa_RegisterApp(); /* Initialize all variables that we clean on shutdown */ device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device) { data = (struct SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData)); } else { data = NULL; } if (!data) { SDL_OutOfMemory(); SDL_free(device); return NULL; } device->driverdata = data; /* Set the function pointers */ device->VideoInit = Cocoa_VideoInit; device->VideoQuit = Cocoa_VideoQuit; device->GetDisplayBounds = Cocoa_GetDisplayBounds; device->GetDisplayUsableBounds = Cocoa_GetDisplayUsableBounds; device->GetDisplayDPI = Cocoa_GetDisplayDPI; device->GetDisplayModes = Cocoa_GetDisplayModes; device->SetDisplayMode = Cocoa_SetDisplayMode; device->PumpEvents = Cocoa_PumpEvents; device->SuspendScreenSaver = Cocoa_SuspendScreenSaver; device->CreateSDLWindow = Cocoa_CreateWindow; device->CreateSDLWindowFrom = Cocoa_CreateWindowFrom; device->SetWindowTitle = Cocoa_SetWindowTitle; device->SetWindowIcon = Cocoa_SetWindowIcon; device->SetWindowPosition = Cocoa_SetWindowPosition; device->SetWindowSize = Cocoa_SetWindowSize; device->SetWindowMinimumSize = Cocoa_SetWindowMinimumSize; device->SetWindowMaximumSize = Cocoa_SetWindowMaximumSize; device->SetWindowOpacity = Cocoa_SetWindowOpacity; device->ShowWindow = Cocoa_ShowWindow; device->HideWindow = Cocoa_HideWindow; device->RaiseWindow = Cocoa_RaiseWindow; device->MaximizeWindow = Cocoa_MaximizeWindow; device->MinimizeWindow = Cocoa_MinimizeWindow; device->RestoreWindow = Cocoa_RestoreWindow; device->SetWindowBordered = Cocoa_SetWindowBordered; device->SetWindowResizable = Cocoa_SetWindowResizable; device->SetWindowFullscreen = Cocoa_SetWindowFullscreen; device->SetWindowGammaRamp = Cocoa_SetWindowGammaRamp; device->GetWindowGammaRamp = Cocoa_GetWindowGammaRamp; device->SetWindowGrab = Cocoa_SetWindowGrab; device->DestroyWindow = Cocoa_DestroyWindow; device->GetWindowWMInfo = Cocoa_GetWindowWMInfo; device->SetWindowHitTest = Cocoa_SetWindowHitTest; device->AcceptDragAndDrop = Cocoa_AcceptDragAndDrop; device->shape_driver.CreateShaper = Cocoa_CreateShaper; device->shape_driver.SetWindowShape = Cocoa_SetWindowShape; device->shape_driver.ResizeWindowShape = Cocoa_ResizeWindowShape; #if SDL_VIDEO_OPENGL_CGL device->GL_LoadLibrary = Cocoa_GL_LoadLibrary; device->GL_GetProcAddress = Cocoa_GL_GetProcAddress; device->GL_UnloadLibrary = Cocoa_GL_UnloadLibrary; device->GL_CreateContext = Cocoa_GL_CreateContext; device->GL_MakeCurrent = Cocoa_GL_MakeCurrent; device->GL_GetDrawableSize = Cocoa_GL_GetDrawableSize; device->GL_SetSwapInterval = Cocoa_GL_SetSwapInterval; device->GL_GetSwapInterval = Cocoa_GL_GetSwapInterval; device->GL_SwapWindow = Cocoa_GL_SwapWindow; device->GL_DeleteContext = Cocoa_GL_DeleteContext; #elif SDL_VIDEO_OPENGL_EGL device->GL_LoadLibrary = Cocoa_GLES_LoadLibrary; device->GL_GetProcAddress = Cocoa_GLES_GetProcAddress; device->GL_UnloadLibrary = Cocoa_GLES_UnloadLibrary; device->GL_CreateContext = Cocoa_GLES_CreateContext; device->GL_MakeCurrent = Cocoa_GLES_MakeCurrent; device->GL_SetSwapInterval = Cocoa_GLES_SetSwapInterval; device->GL_GetSwapInterval = Cocoa_GLES_GetSwapInterval; device->GL_SwapWindow = Cocoa_GLES_SwapWindow; device->GL_DeleteContext = Cocoa_GLES_DeleteContext; #endif #if SDL_VIDEO_VULKAN device->Vulkan_LoadLibrary = Cocoa_Vulkan_LoadLibrary; device->Vulkan_UnloadLibrary = Cocoa_Vulkan_UnloadLibrary; device->Vulkan_GetInstanceExtensions = Cocoa_Vulkan_GetInstanceExtensions; device->Vulkan_CreateSurface = Cocoa_Vulkan_CreateSurface; device->Vulkan_GetDrawableSize = Cocoa_Vulkan_GetDrawableSize; #endif #if SDL_VIDEO_METAL device->Metal_CreateView = Cocoa_Metal_CreateView; device->Metal_DestroyView = Cocoa_Metal_DestroyView; device->Metal_GetLayer = Cocoa_Metal_GetLayer; device->Metal_GetDrawableSize = Cocoa_Metal_GetDrawableSize; #endif device->StartTextInput = Cocoa_StartTextInput; device->StopTextInput = Cocoa_StopTextInput; device->SetTextInputRect = Cocoa_SetTextInputRect; device->SetClipboardText = Cocoa_SetClipboardText; device->GetClipboardText = Cocoa_GetClipboardText; device->HasClipboardText = Cocoa_HasClipboardText; device->free = Cocoa_DeleteDevice; return device; } VideoBootStrap COCOA_bootstrap = { "cocoa", "SDL Cocoa video driver", Cocoa_Available, Cocoa_CreateDevice }; int Cocoa_VideoInit(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; Cocoa_InitModes(_this); Cocoa_InitKeyboard(_this); if (Cocoa_InitMouse(_this) < 0) { return -1; } data->allow_spaces = ((floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) && SDL_GetHintBoolean(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, SDL_TRUE)); /* The IOPM assertion API can disable the screensaver as of 10.7. */ data->screensaver_use_iopm = floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6; data->swaplock = SDL_CreateMutex(); if (!data->swaplock) { return -1; } return 0; } void Cocoa_VideoQuit(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; Cocoa_QuitModes(_this); Cocoa_QuitKeyboard(_this); Cocoa_QuitMouse(_this); SDL_DestroyMutex(data->swaplock); data->swaplock = NULL; } /* This function assumes that it's called from within an autorelease pool */ NSImage * Cocoa_CreateImage(SDL_Surface * surface) { SDL_Surface *converted; NSBitmapImageRep *imgrep; Uint8 *pixels; int i; NSImage *img; converted = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGBA32, 0); if (!converted) { return nil; } imgrep = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL pixelsWide: converted->w pixelsHigh: converted->h bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar: NO colorSpaceName: NSDeviceRGBColorSpace bytesPerRow: converted->pitch bitsPerPixel: converted->format->BitsPerPixel] autorelease]; if (imgrep == nil) { SDL_FreeSurface(converted); return nil; } /* Copy the pixels */ pixels = [imgrep bitmapData]; SDL_memcpy(pixels, converted->pixels, converted->h * converted->pitch); SDL_FreeSurface(converted); /* Premultiply the alpha channel */ for (i = (surface->h * surface->w); i--; ) { Uint8 alpha = pixels[3]; pixels[0] = (Uint8)(((Uint16)pixels[0] * alpha) / 255); pixels[1] = (Uint8)(((Uint16)pixels[1] * alpha) / 255); pixels[2] = (Uint8)(((Uint16)pixels[2] * alpha) / 255); pixels += 4; } img = [[[NSImage alloc] initWithSize: NSMakeSize(surface->w, surface->h)] autorelease]; if (img != nil) { [img addRepresentation: imgrep]; } return img; } /* * Mac OS X log support. * * This doesn't really have aything to do with the interfaces of the SDL video * subsystem, but we need to stuff this into an Objective-C source code file. * * NOTE: This is copypasted in src/video/uikit/SDL_uikitvideo.m! Be sure both * versions remain identical! */ void SDL_NSLog(const char *text) { NSLog(@"%s", text); } #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vim: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoavideo.m
Objective-C
apache-2.0
9,283
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.h. */ #include "../../SDL_internal.h" #ifndef SDL_cocoavulkan_h_ #define SDL_cocoavulkan_h_ #include "../SDL_vulkan_internal.h" #include "../SDL_sysvideo.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path); void Cocoa_Vulkan_UnloadLibrary(_THIS); SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names); SDL_bool Cocoa_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface); void Cocoa_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h); #endif #endif /* SDL_cocoavulkan_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoavulkan.h
C
apache-2.0
1,945
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's * SDL_x11vulkan.c. */ #include "../../SDL_internal.h" #if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA #include "SDL_cocoavideo.h" #include "SDL_cocoawindow.h" #include "SDL_assert.h" #include "SDL_loadso.h" #include "SDL_cocoametalview.h" #include "SDL_cocoavulkan.h" #include "SDL_syswm.h" #include <dlfcn.h> const char* defaultPaths[] = { "vulkan.framework/vulkan", "libvulkan.1.dylib", "libvulkan.dylib", "MoltenVK.framework/MoltenVK", "libMoltenVK.dylib" }; /* Since libSDL is most likely a .dylib, need RTLD_DEFAULT not RTLD_SELF. */ #define DEFAULT_HANDLE RTLD_DEFAULT int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path) { VkExtensionProperties *extensions = NULL; Uint32 extensionCount = 0; SDL_bool hasSurfaceExtension = SDL_FALSE; SDL_bool hasMacOSSurfaceExtension = SDL_FALSE; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL; if (_this->vulkan_config.loader_handle) { return SDL_SetError("Vulkan Portability library is already loaded."); } /* Load the Vulkan loader library */ if (!path) { path = SDL_getenv("SDL_VULKAN_LIBRARY"); } if (!path) { /* Handle the case where Vulkan Portability is linked statically. */ vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE, "vkGetInstanceProcAddr"); } if (vkGetInstanceProcAddr) { _this->vulkan_config.loader_handle = DEFAULT_HANDLE; } else { const char** paths; const char *foundPath = NULL; int numPaths; int i; if (path) { paths = &path; numPaths = 1; } else { /* Look for framework or .dylib packaged with the application * instead. */ paths = defaultPaths; numPaths = SDL_arraysize(defaultPaths); } for (i = 0; i < numPaths && _this->vulkan_config.loader_handle == NULL; i++) { foundPath = paths[i]; _this->vulkan_config.loader_handle = SDL_LoadObject(foundPath); } if (_this->vulkan_config.loader_handle == NULL) { return SDL_SetError("Failed to load Vulkan Portability library"); } SDL_strlcpy(_this->vulkan_config.loader_path, foundPath, SDL_arraysize(_this->vulkan_config.loader_path)); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr"); } if (!vkGetInstanceProcAddr) { SDL_SetError("Failed to find %s in either executable or %s: %s", "vkGetInstanceProcAddr", _this->vulkan_config.loader_path, (const char *) dlerror()); goto fail; } _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr; _this->vulkan_config.vkEnumerateInstanceExtensionProperties = (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); if (!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) { goto fail; } extensions = SDL_Vulkan_CreateInstanceExtensionsList( (PFN_vkEnumerateInstanceExtensionProperties) _this->vulkan_config.vkEnumerateInstanceExtensionProperties, &extensionCount); if (!extensions) { goto fail; } for (Uint32 i = 0; i < extensionCount; i++) { if (SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) { hasSurfaceExtension = SDL_TRUE; } else if (SDL_strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) { hasMacOSSurfaceExtension = SDL_TRUE; } } SDL_free(extensions); if (!hasSurfaceExtension) { SDL_SetError("Installed Vulkan Portability library doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if (!hasMacOSSurfaceExtension) { SDL_SetError("Installed Vulkan Portability library doesn't implement the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME "extension"); goto fail; } return 0; fail: SDL_UnloadObject(_this->vulkan_config.loader_handle); _this->vulkan_config.loader_handle = NULL; return -1; } void Cocoa_Vulkan_UnloadLibrary(_THIS) { if (_this->vulkan_config.loader_handle) { if (_this->vulkan_config.loader_handle != DEFAULT_HANDLE) { SDL_UnloadObject(_this->vulkan_config.loader_handle); } _this->vulkan_config.loader_handle = NULL; } } SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS, SDL_Window *window, unsigned *count, const char **names) { static const char *const extensionsForCocoa[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_MVK_MACOS_SURFACE_EXTENSION_NAME }; if (!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } return SDL_Vulkan_GetInstanceExtensions_Helper( count, names, SDL_arraysize(extensionsForCocoa), extensionsForCocoa); } SDL_bool Cocoa_Vulkan_CreateSurface(_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface) { PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK = (PFN_vkCreateMacOSSurfaceMVK)vkGetInstanceProcAddr( (VkInstance)instance, "vkCreateMacOSSurfaceMVK"); VkMacOSSurfaceCreateInfoMVK createInfo = {}; VkResult result; SDL_MetalView metalview; if (!_this->vulkan_config.loader_handle) { SDL_SetError("Vulkan is not loaded"); return SDL_FALSE; } if (!vkCreateMacOSSurfaceMVK) { SDL_SetError(VK_MVK_MACOS_SURFACE_EXTENSION_NAME " extension is not enabled in the Vulkan instance."); return SDL_FALSE; } metalview = Cocoa_Metal_CreateView(_this, window); if (metalview == NULL) { return SDL_FALSE; } createInfo.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.pView = (const void *)metalview; result = vkCreateMacOSSurfaceMVK(instance, &createInfo, NULL, surface); if (result != VK_SUCCESS) { Cocoa_Metal_DestroyView(_this, metalview); SDL_SetError("vkCreateMacOSSurfaceMVK failed: %s", SDL_Vulkan_GetResultString(result)); return SDL_FALSE; } /* Unfortunately there's no SDL_Vulkan_DestroySurface function we can call * Metal_DestroyView from. Right now the metal view's ref count is +2 (one * from returning a new view object in CreateView, and one because it's * a subview of the window.) If we release the view here to make it +1, it * will be destroyed when the window is destroyed. */ CFBridgingRelease(metalview); return SDL_TRUE; } void Cocoa_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h) { Cocoa_Metal_GetDrawableSize(_this, window, w, h); } #endif /* vim: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoavulkan.m
Objective-C
apache-2.0
8,670
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_cocoawindow_h_ #define SDL_cocoawindow_h_ #import <Cocoa/Cocoa.h> #if SDL_VIDEO_OPENGL_EGL #include "../SDL_egl_c.h" #endif typedef struct SDL_WindowData SDL_WindowData; typedef enum { PENDING_OPERATION_NONE, PENDING_OPERATION_ENTER_FULLSCREEN, PENDING_OPERATION_LEAVE_FULLSCREEN, PENDING_OPERATION_MINIMIZE } PendingWindowOperation; @interface Cocoa_WindowListener : NSResponder <NSWindowDelegate> { SDL_WindowData *_data; BOOL observingVisible; BOOL wasCtrlLeft; BOOL wasVisible; BOOL isFullscreenSpace; BOOL inFullscreenTransition; PendingWindowOperation pendingWindowOperation; BOOL isMoving; int pendingWindowWarpX, pendingWindowWarpY; BOOL isDragAreaRunning; } -(void) listen:(SDL_WindowData *) data; -(void) pauseVisibleObservation; -(void) resumeVisibleObservation; -(BOOL) setFullscreenSpace:(BOOL) state; -(BOOL) isInFullscreenSpace; -(BOOL) isInFullscreenSpaceTransition; -(void) addPendingWindowOperation:(PendingWindowOperation) operation; -(void) close; -(BOOL) isMoving; -(void) setPendingMoveX:(int)x Y:(int)y; -(void) windowDidFinishMoving; /* Window delegate functionality */ -(BOOL) windowShouldClose:(id) sender; -(void) windowDidExpose:(NSNotification *) aNotification; -(void) windowDidMove:(NSNotification *) aNotification; -(void) windowDidResize:(NSNotification *) aNotification; -(void) windowDidMiniaturize:(NSNotification *) aNotification; -(void) windowDidDeminiaturize:(NSNotification *) aNotification; -(void) windowDidBecomeKey:(NSNotification *) aNotification; -(void) windowDidResignKey:(NSNotification *) aNotification; -(void) windowDidChangeBackingProperties:(NSNotification *) aNotification; -(void) windowWillEnterFullScreen:(NSNotification *) aNotification; -(void) windowDidEnterFullScreen:(NSNotification *) aNotification; -(void) windowWillExitFullScreen:(NSNotification *) aNotification; -(void) windowDidExitFullScreen:(NSNotification *) aNotification; -(NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions; /* See if event is in a drag area, toggle on window dragging. */ -(BOOL) processHitTest:(NSEvent *)theEvent; /* Window event handling */ -(void) mouseDown:(NSEvent *) theEvent; -(void) rightMouseDown:(NSEvent *) theEvent; -(void) otherMouseDown:(NSEvent *) theEvent; -(void) mouseUp:(NSEvent *) theEvent; -(void) rightMouseUp:(NSEvent *) theEvent; -(void) otherMouseUp:(NSEvent *) theEvent; -(void) mouseMoved:(NSEvent *) theEvent; -(void) mouseDragged:(NSEvent *) theEvent; -(void) rightMouseDragged:(NSEvent *) theEvent; -(void) otherMouseDragged:(NSEvent *) theEvent; -(void) scrollWheel:(NSEvent *) theEvent; -(void) touchesBeganWithEvent:(NSEvent *) theEvent; -(void) touchesMovedWithEvent:(NSEvent *) theEvent; -(void) touchesEndedWithEvent:(NSEvent *) theEvent; -(void) touchesCancelledWithEvent:(NSEvent *) theEvent; /* Touch event handling */ -(void) handleTouches:(NSTouchPhase) phase withEvent:(NSEvent*) theEvent; @end /* *INDENT-ON* */ @class SDLOpenGLContext; struct SDL_WindowData { SDL_Window *window; NSWindow *nswindow; NSView *sdlContentView; NSMutableArray *nscontexts; SDL_bool created; SDL_bool inWindowFullscreenTransition; Cocoa_WindowListener *listener; struct SDL_VideoData *videodata; #if SDL_VIDEO_OPENGL_EGL EGLSurface egl_surface; #endif }; extern int Cocoa_CreateWindow(_THIS, SDL_Window * window); extern int Cocoa_CreateWindowFrom(_THIS, SDL_Window * window, const void *data); extern void Cocoa_SetWindowTitle(_THIS, SDL_Window * window); extern void Cocoa_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon); extern void Cocoa_SetWindowPosition(_THIS, SDL_Window * window); extern void Cocoa_SetWindowSize(_THIS, SDL_Window * window); extern void Cocoa_SetWindowMinimumSize(_THIS, SDL_Window * window); extern void Cocoa_SetWindowMaximumSize(_THIS, SDL_Window * window); extern int Cocoa_SetWindowOpacity(_THIS, SDL_Window * window, float opacity); extern void Cocoa_ShowWindow(_THIS, SDL_Window * window); extern void Cocoa_HideWindow(_THIS, SDL_Window * window); extern void Cocoa_RaiseWindow(_THIS, SDL_Window * window); extern void Cocoa_MaximizeWindow(_THIS, SDL_Window * window); extern void Cocoa_MinimizeWindow(_THIS, SDL_Window * window); extern void Cocoa_RestoreWindow(_THIS, SDL_Window * window); extern void Cocoa_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered); extern void Cocoa_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable); extern void Cocoa_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen); extern int Cocoa_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp); extern int Cocoa_GetWindowGammaRamp(_THIS, SDL_Window * window, Uint16 * ramp); extern void Cocoa_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed); extern void Cocoa_DestroyWindow(_THIS, SDL_Window * window); extern SDL_bool Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info); extern int Cocoa_SetWindowHitTest(SDL_Window *window, SDL_bool enabled); extern void Cocoa_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept); #endif /* SDL_cocoawindow_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoawindow.h
Objective-C
apache-2.0
6,330
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_COCOA #if MAC_OS_X_VERSION_MAX_ALLOWED < 1070 # error SDL for Mac OS X must be built with a 10.7 SDK or above. #endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1070 */ #include "SDL_syswm.h" #include "SDL_timer.h" /* For SDL_GetTicks() */ #include "SDL_hints.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_touch_c.h" #include "../../events/SDL_windowevents_c.h" #include "../../events/SDL_dropevents_c.h" #include "SDL_cocoavideo.h" #include "SDL_cocoashape.h" #include "SDL_cocoamouse.h" #include "SDL_cocoamousetap.h" #include "SDL_cocoaopengl.h" #include "SDL_cocoaopengles.h" #include "SDL_assert.h" /* #define DEBUG_COCOAWINDOW */ #ifdef DEBUG_COCOAWINDOW #define DLog(fmt, ...) printf("%s: " fmt "\n", __func__, ##__VA_ARGS__) #else #define DLog(...) do { } while (0) #endif #define FULLSCREEN_MASK (SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN) #ifndef MAC_OS_X_VERSION_10_12 #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask #endif @interface SDLWindow : NSWindow <NSDraggingDestination> /* These are needed for borderless/fullscreen windows */ - (BOOL)canBecomeKeyWindow; - (BOOL)canBecomeMainWindow; - (void)sendEvent:(NSEvent *)event; - (void)doCommandBySelector:(SEL)aSelector; /* Handle drag-and-drop of files onto the SDL window. */ - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender; - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender; - (BOOL)wantsPeriodicDraggingUpdates; - (BOOL)validateMenuItem:(NSMenuItem *)menuItem; - (SDL_Window*)findSDLWindow; @end @implementation SDLWindow - (BOOL)validateMenuItem:(NSMenuItem *)menuItem { /* Only allow using the macOS native fullscreen toggle menubar item if the * window is resizable and not in a SDL fullscreen mode. */ if ([menuItem action] == @selector(toggleFullScreen:)) { SDL_Window *window = [self findSDLWindow]; if (window == NULL) { return NO; } else if ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_FULLSCREEN_DESKTOP)) != 0) { return NO; } else if ((window->flags & SDL_WINDOW_RESIZABLE) == 0) { return NO; } } return [super validateMenuItem:menuItem]; } - (BOOL)canBecomeKeyWindow { return YES; } - (BOOL)canBecomeMainWindow { return YES; } - (void)sendEvent:(NSEvent *)event { [super sendEvent:event]; if ([event type] != NSEventTypeLeftMouseUp) { return; } id delegate = [self delegate]; if (![delegate isKindOfClass:[Cocoa_WindowListener class]]) { return; } if ([delegate isMoving]) { [delegate windowDidFinishMoving]; } } /* We'll respond to selectors by doing nothing so we don't beep. * The escape key gets converted to a "cancel" selector, etc. */ - (void)doCommandBySelector:(SEL)aSelector { /*NSLog(@"doCommandBySelector: %@\n", NSStringFromSelector(aSelector));*/ } - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender { if (([sender draggingSourceOperationMask] & NSDragOperationGeneric) == NSDragOperationGeneric) { return NSDragOperationGeneric; } return NSDragOperationNone; /* no idea what to do with this, reject it. */ } - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender { @autoreleasepool { NSPasteboard *pasteboard = [sender draggingPasteboard]; NSArray *types = [NSArray arrayWithObject:NSFilenamesPboardType]; NSString *desiredType = [pasteboard availableTypeFromArray:types]; SDL_Window *sdlwindow = [self findSDLWindow]; if (desiredType == nil) { return NO; /* can't accept anything that's being dropped here. */ } NSData *data = [pasteboard dataForType:desiredType]; if (data == nil) { return NO; } SDL_assert([desiredType isEqualToString:NSFilenamesPboardType]); NSArray *array = [pasteboard propertyListForType:@"NSFilenamesPboardType"]; for (NSString *path in array) { NSURL *fileURL = [NSURL fileURLWithPath:path]; NSNumber *isAlias = nil; [fileURL getResourceValue:&isAlias forKey:NSURLIsAliasFileKey error:nil]; /* If the URL is an alias, resolve it. */ if ([isAlias boolValue]) { NSURLBookmarkResolutionOptions opts = NSURLBookmarkResolutionWithoutMounting | NSURLBookmarkResolutionWithoutUI; NSData *bookmark = [NSURL bookmarkDataWithContentsOfURL:fileURL error:nil]; if (bookmark != nil) { NSURL *resolvedURL = [NSURL URLByResolvingBookmarkData:bookmark options:opts relativeToURL:nil bookmarkDataIsStale:nil error:nil]; if (resolvedURL != nil) { fileURL = resolvedURL; } } } if (!SDL_SendDropFile(sdlwindow, [[fileURL path] UTF8String])) { return NO; } } SDL_SendDropComplete(sdlwindow); return YES; }} - (BOOL)wantsPeriodicDraggingUpdates { return NO; } - (SDL_Window*)findSDLWindow { SDL_Window *sdlwindow = NULL; SDL_VideoDevice *_this = SDL_GetVideoDevice(); /* !!! FIXME: is there a better way to do this? */ if (_this) { for (sdlwindow = _this->windows; sdlwindow; sdlwindow = sdlwindow->next) { NSWindow *nswindow = ((SDL_WindowData *) sdlwindow->driverdata)->nswindow; if (nswindow == self) { break; } } } return sdlwindow; } @end static Uint32 s_moveHack; static void ConvertNSRect(NSScreen *screen, BOOL fullscreen, NSRect *r) { r->origin.y = CGDisplayPixelsHigh(kCGDirectMainDisplay) - r->origin.y - r->size.height; } static void ScheduleContextUpdates(SDL_WindowData *data) { if (!data || !data->nscontexts) { return; } /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif NSOpenGLContext *currentContext = [NSOpenGLContext currentContext]; NSMutableArray *contexts = data->nscontexts; @synchronized (contexts) { for (SDLOpenGLContext *context in contexts) { if (context == currentContext) { [context update]; } else { [context scheduleUpdate]; } } } #ifdef __clang__ #pragma clang diagnostic pop #endif } /* !!! FIXME: this should use a hint callback. */ static int GetHintCtrlClickEmulateRightClick() { return SDL_GetHintBoolean(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, SDL_FALSE); } static NSUInteger GetWindowWindowedStyle(SDL_Window * window) { NSUInteger style = 0; if (window->flags & SDL_WINDOW_BORDERLESS) { style = NSWindowStyleMaskBorderless; } else { style = (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable); } if (window->flags & SDL_WINDOW_RESIZABLE) { style |= NSWindowStyleMaskResizable; } return style; } static NSUInteger GetWindowStyle(SDL_Window * window) { NSUInteger style = 0; if (window->flags & SDL_WINDOW_FULLSCREEN) { style = NSWindowStyleMaskBorderless; } else { style = GetWindowWindowedStyle(window); } return style; } static SDL_bool SetWindowStyle(SDL_Window * window, NSUInteger style) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; NSWindow *nswindow = data->nswindow; /* The view responder chain gets messed with during setStyleMask */ if ([data->sdlContentView nextResponder] == data->listener) { [data->sdlContentView setNextResponder:nil]; } [nswindow setStyleMask:style]; /* The view responder chain gets messed with during setStyleMask */ if ([data->sdlContentView nextResponder] != data->listener) { [data->sdlContentView setNextResponder:data->listener]; } return SDL_TRUE; } @implementation Cocoa_WindowListener - (void)listen:(SDL_WindowData *)data { NSNotificationCenter *center; NSWindow *window = data->nswindow; NSView *view = data->sdlContentView; _data = data; observingVisible = YES; wasCtrlLeft = NO; wasVisible = [window isVisible]; isFullscreenSpace = NO; inFullscreenTransition = NO; pendingWindowOperation = PENDING_OPERATION_NONE; isMoving = NO; isDragAreaRunning = NO; center = [NSNotificationCenter defaultCenter]; if ([window delegate] != nil) { [center addObserver:self selector:@selector(windowDidExpose:) name:NSWindowDidExposeNotification object:window]; [center addObserver:self selector:@selector(windowDidMove:) name:NSWindowDidMoveNotification object:window]; [center addObserver:self selector:@selector(windowDidResize:) name:NSWindowDidResizeNotification object:window]; [center addObserver:self selector:@selector(windowDidMiniaturize:) name:NSWindowDidMiniaturizeNotification object:window]; [center addObserver:self selector:@selector(windowDidDeminiaturize:) name:NSWindowDidDeminiaturizeNotification object:window]; [center addObserver:self selector:@selector(windowDidBecomeKey:) name:NSWindowDidBecomeKeyNotification object:window]; [center addObserver:self selector:@selector(windowDidResignKey:) name:NSWindowDidResignKeyNotification object:window]; [center addObserver:self selector:@selector(windowDidChangeBackingProperties:) name:NSWindowDidChangeBackingPropertiesNotification object:window]; [center addObserver:self selector:@selector(windowWillEnterFullScreen:) name:NSWindowWillEnterFullScreenNotification object:window]; [center addObserver:self selector:@selector(windowDidEnterFullScreen:) name:NSWindowDidEnterFullScreenNotification object:window]; [center addObserver:self selector:@selector(windowWillExitFullScreen:) name:NSWindowWillExitFullScreenNotification object:window]; [center addObserver:self selector:@selector(windowDidExitFullScreen:) name:NSWindowDidExitFullScreenNotification object:window]; [center addObserver:self selector:@selector(windowDidFailToEnterFullScreen:) name:@"NSWindowDidFailToEnterFullScreenNotification" object:window]; [center addObserver:self selector:@selector(windowDidFailToExitFullScreen:) name:@"NSWindowDidFailToExitFullScreenNotification" object:window]; } else { [window setDelegate:self]; } /* Haven't found a delegate / notification that triggers when the window is * ordered out (is not visible any more). You can be ordered out without * minimizing, so DidMiniaturize doesn't work. (e.g. -[NSWindow orderOut:]) */ [window addObserver:self forKeyPath:@"visible" options:NSKeyValueObservingOptionNew context:NULL]; [window setNextResponder:self]; [window setAcceptsMouseMovedEvents:YES]; [view setNextResponder:self]; [view setAcceptsTouchEvents:YES]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (!observingVisible) { return; } if (object == _data->nswindow && [keyPath isEqualToString:@"visible"]) { int newVisibility = [[change objectForKey:@"new"] intValue]; if (newVisibility) { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_SHOWN, 0, 0); } else { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIDDEN, 0, 0); } } } -(void) pauseVisibleObservation { observingVisible = NO; wasVisible = [_data->nswindow isVisible]; } -(void) resumeVisibleObservation { BOOL isVisible = [_data->nswindow isVisible]; observingVisible = YES; if (wasVisible != isVisible) { if (isVisible) { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_SHOWN, 0, 0); } else { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIDDEN, 0, 0); } wasVisible = isVisible; } } -(BOOL) setFullscreenSpace:(BOOL) state { SDL_Window *window = _data->window; NSWindow *nswindow = _data->nswindow; SDL_VideoData *videodata = ((SDL_WindowData *) window->driverdata)->videodata; if (!videodata->allow_spaces) { return NO; /* Spaces are forcibly disabled. */ } else if (state && ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP)) { return NO; /* we only allow you to make a Space on FULLSCREEN_DESKTOP windows. */ } else if (!state && ((window->last_fullscreen_flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP)) { return NO; /* we only handle leaving the Space on windows that were previously FULLSCREEN_DESKTOP. */ } else if (state == isFullscreenSpace) { return YES; /* already there. */ } if (inFullscreenTransition) { if (state) { [self addPendingWindowOperation:PENDING_OPERATION_ENTER_FULLSCREEN]; } else { [self addPendingWindowOperation:PENDING_OPERATION_LEAVE_FULLSCREEN]; } return YES; } inFullscreenTransition = YES; /* you need to be FullScreenPrimary, or toggleFullScreen doesn't work. Unset it again in windowDidExitFullScreen. */ [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; [nswindow performSelectorOnMainThread: @selector(toggleFullScreen:) withObject:nswindow waitUntilDone:NO]; return YES; } -(BOOL) isInFullscreenSpace { return isFullscreenSpace; } -(BOOL) isInFullscreenSpaceTransition { return inFullscreenTransition; } -(void) addPendingWindowOperation:(PendingWindowOperation) operation { pendingWindowOperation = operation; } - (void)close { NSNotificationCenter *center; NSWindow *window = _data->nswindow; NSView *view = [window contentView]; center = [NSNotificationCenter defaultCenter]; if ([window delegate] != self) { [center removeObserver:self name:NSWindowDidExposeNotification object:window]; [center removeObserver:self name:NSWindowDidMoveNotification object:window]; [center removeObserver:self name:NSWindowDidResizeNotification object:window]; [center removeObserver:self name:NSWindowDidMiniaturizeNotification object:window]; [center removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window]; [center removeObserver:self name:NSWindowDidBecomeKeyNotification object:window]; [center removeObserver:self name:NSWindowDidResignKeyNotification object:window]; [center removeObserver:self name:NSWindowDidChangeBackingPropertiesNotification object:window]; [center removeObserver:self name:NSWindowWillEnterFullScreenNotification object:window]; [center removeObserver:self name:NSWindowDidEnterFullScreenNotification object:window]; [center removeObserver:self name:NSWindowWillExitFullScreenNotification object:window]; [center removeObserver:self name:NSWindowDidExitFullScreenNotification object:window]; [center removeObserver:self name:@"NSWindowDidFailToEnterFullScreenNotification" object:window]; [center removeObserver:self name:@"NSWindowDidFailToExitFullScreenNotification" object:window]; } else { [window setDelegate:nil]; } [window removeObserver:self forKeyPath:@"visible"]; if ([window nextResponder] == self) { [window setNextResponder:nil]; } if ([view nextResponder] == self) { [view setNextResponder:nil]; } } - (BOOL)isMoving { return isMoving; } -(void) setPendingMoveX:(int)x Y:(int)y { pendingWindowWarpX = x; pendingWindowWarpY = y; } - (void)windowDidFinishMoving { if ([self isMoving]) { isMoving = NO; SDL_Mouse *mouse = SDL_GetMouse(); if (pendingWindowWarpX != INT_MAX && pendingWindowWarpY != INT_MAX) { mouse->WarpMouseGlobal(pendingWindowWarpX, pendingWindowWarpY); pendingWindowWarpX = pendingWindowWarpY = INT_MAX; } if (mouse->relative_mode && !mouse->relative_mode_warp && mouse->focus == _data->window) { mouse->SetRelativeMouseMode(SDL_TRUE); } } } - (BOOL)windowShouldClose:(id)sender { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_CLOSE, 0, 0); return NO; } - (void)windowDidExpose:(NSNotification *)aNotification { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_EXPOSED, 0, 0); } - (void)windowWillMove:(NSNotification *)aNotification { if ([_data->nswindow isKindOfClass:[SDLWindow class]]) { pendingWindowWarpX = pendingWindowWarpY = INT_MAX; isMoving = YES; } } - (void)windowDidMove:(NSNotification *)aNotification { int x, y; SDL_Window *window = _data->window; NSWindow *nswindow = _data->nswindow; BOOL fullscreen = window->flags & FULLSCREEN_MASK; NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]]; ConvertNSRect([nswindow screen], fullscreen, &rect); if (inFullscreenTransition) { /* We'll take care of this at the end of the transition */ return; } if (s_moveHack) { SDL_bool blockMove = ((SDL_GetTicks() - s_moveHack) < 500); s_moveHack = 0; if (blockMove) { /* Cocoa is adjusting the window in response to a mode change */ rect.origin.x = window->x; rect.origin.y = window->y; ConvertNSRect([nswindow screen], fullscreen, &rect); [nswindow setFrameOrigin:rect.origin]; return; } } x = (int)rect.origin.x; y = (int)rect.origin.y; ScheduleContextUpdates(_data); SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MOVED, x, y); } - (void)windowDidResize:(NSNotification *)aNotification { if (inFullscreenTransition) { /* We'll take care of this at the end of the transition */ return; } SDL_Window *window = _data->window; NSWindow *nswindow = _data->nswindow; int x, y, w, h; NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]]; ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); x = (int)rect.origin.x; y = (int)rect.origin.y; w = (int)rect.size.width; h = (int)rect.size.height; if (SDL_IsShapedWindow(window)) { Cocoa_ResizeWindowShape(window); } ScheduleContextUpdates(_data); /* The window can move during a resize event, such as when maximizing or resizing from a corner */ SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MOVED, x, y); SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, w, h); const BOOL zoomed = [nswindow isZoomed]; if (!zoomed) { SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESTORED, 0, 0); } else if (zoomed) { SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MAXIMIZED, 0, 0); } } - (void)windowDidMiniaturize:(NSNotification *)aNotification { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_MINIMIZED, 0, 0); } - (void)windowDidDeminiaturize:(NSNotification *)aNotification { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_RESTORED, 0, 0); } - (void)windowDidBecomeKey:(NSNotification *)aNotification { SDL_Window *window = _data->window; SDL_Mouse *mouse = SDL_GetMouse(); /* We're going to get keyboard events, since we're key. */ /* This needs to be done before restoring the relative mouse mode. */ SDL_SetKeyboardFocus(window); if (mouse->relative_mode && !mouse->relative_mode_warp && ![self isMoving]) { mouse->SetRelativeMouseMode(SDL_TRUE); } /* If we just gained focus we need the updated mouse position */ if (!mouse->relative_mode) { NSPoint point; int x, y; point = [_data->nswindow mouseLocationOutsideOfEventStream]; x = (int)point.x; y = (int)(window->h - point.y); if (x >= 0 && x < window->w && y >= 0 && y < window->h) { SDL_SendMouseMotion(window, mouse->mouseID, 0, x, y); } } /* Check to see if someone updated the clipboard */ Cocoa_CheckClipboardUpdate(_data->videodata); if ((isFullscreenSpace) && ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP)) { [NSMenu setMenuBarVisible:NO]; } const unsigned int newflags = [NSEvent modifierFlags] & NSEventModifierFlagCapsLock; _data->videodata->modifierFlags = (_data->videodata->modifierFlags & ~NSEventModifierFlagCapsLock) | newflags; SDL_ToggleModState(KMOD_CAPS, newflags != 0); } - (void)windowDidResignKey:(NSNotification *)aNotification { SDL_Mouse *mouse = SDL_GetMouse(); if (mouse->relative_mode && !mouse->relative_mode_warp) { mouse->SetRelativeMouseMode(SDL_FALSE); } /* Some other window will get mouse events, since we're not key. */ if (SDL_GetMouseFocus() == _data->window) { SDL_SetMouseFocus(NULL); } /* Some other window will get keyboard events, since we're not key. */ if (SDL_GetKeyboardFocus() == _data->window) { SDL_SetKeyboardFocus(NULL); } if (isFullscreenSpace) { [NSMenu setMenuBarVisible:YES]; } } - (void)windowDidChangeBackingProperties:(NSNotification *)aNotification { NSNumber *oldscale = [[aNotification userInfo] objectForKey:NSBackingPropertyOldScaleFactorKey]; if (inFullscreenTransition) { return; } if ([oldscale doubleValue] != [_data->nswindow backingScaleFactor]) { /* Force a resize event when the backing scale factor changes. */ _data->window->w = 0; _data->window->h = 0; [self windowDidResize:aNotification]; } } - (void)windowWillEnterFullScreen:(NSNotification *)aNotification { SDL_Window *window = _data->window; SetWindowStyle(window, (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable)); isFullscreenSpace = YES; inFullscreenTransition = YES; } - (void)windowDidFailToEnterFullScreen:(NSNotification *)aNotification { SDL_Window *window = _data->window; if (window->is_destroying) { return; } SetWindowStyle(window, GetWindowStyle(window)); isFullscreenSpace = NO; inFullscreenTransition = NO; [self windowDidExitFullScreen:nil]; } - (void)windowDidEnterFullScreen:(NSNotification *)aNotification { SDL_Window *window = _data->window; SDL_WindowData *data = (SDL_WindowData *) window->driverdata; NSWindow *nswindow = data->nswindow; inFullscreenTransition = NO; if (pendingWindowOperation == PENDING_OPERATION_LEAVE_FULLSCREEN) { pendingWindowOperation = PENDING_OPERATION_NONE; [self setFullscreenSpace:NO]; } else { /* Unset the resizable flag. This is a workaround for https://bugzilla.libsdl.org/show_bug.cgi?id=3697 */ SetWindowStyle(window, [nswindow styleMask] & (~NSWindowStyleMaskResizable)); if ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) { [NSMenu setMenuBarVisible:NO]; } pendingWindowOperation = PENDING_OPERATION_NONE; /* Force the size change event in case it was delivered earlier while the window was still animating into place. */ window->w = 0; window->h = 0; [self windowDidMove:aNotification]; [self windowDidResize:aNotification]; } } - (void)windowWillExitFullScreen:(NSNotification *)aNotification { SDL_Window *window = _data->window; isFullscreenSpace = NO; inFullscreenTransition = YES; /* As of macOS 10.11, the window seems to need to be resizable when exiting a Space, in order for it to resize back to its windowed-mode size. As of macOS 10.15, the window decorations can go missing sometimes after certain fullscreen-desktop->exlusive-fullscreen->windowed mode flows sometimes. Making sure the style mask always uses the windowed mode style when returning to windowed mode from a space (instead of using a pending fullscreen mode style mask) seems to work around that issue. */ SetWindowStyle(window, GetWindowWindowedStyle(window) | NSWindowStyleMaskResizable); } - (void)windowDidFailToExitFullScreen:(NSNotification *)aNotification { SDL_Window *window = _data->window; if (window->is_destroying) { return; } SetWindowStyle(window, (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable)); isFullscreenSpace = YES; inFullscreenTransition = NO; [self windowDidEnterFullScreen:nil]; } - (void)windowDidExitFullScreen:(NSNotification *)aNotification { SDL_Window *window = _data->window; NSWindow *nswindow = _data->nswindow; NSButton *button = nil; inFullscreenTransition = NO; /* As of macOS 10.15, the window decorations can go missing sometimes after certain fullscreen-desktop->exlusive-fullscreen->windowed mode flows sometimes. Making sure the style mask always uses the windowed mode style when returning to windowed mode from a space (instead of using a pending fullscreen mode style mask) seems to work around that issue. */ SetWindowStyle(window, GetWindowWindowedStyle(window)); if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { [nswindow setLevel:NSFloatingWindowLevel]; } else { [nswindow setLevel:kCGNormalWindowLevel]; } if (pendingWindowOperation == PENDING_OPERATION_ENTER_FULLSCREEN) { pendingWindowOperation = PENDING_OPERATION_NONE; [self setFullscreenSpace:YES]; } else if (pendingWindowOperation == PENDING_OPERATION_MINIMIZE) { pendingWindowOperation = PENDING_OPERATION_NONE; [nswindow miniaturize:nil]; } else { /* Adjust the fullscreen toggle button and readd menu now that we're here. */ if (window->flags & SDL_WINDOW_RESIZABLE) { /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */ [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; } else { [nswindow setCollectionBehavior:NSWindowCollectionBehaviorManaged]; } [NSMenu setMenuBarVisible:YES]; pendingWindowOperation = PENDING_OPERATION_NONE; #if 0 /* This fixed bug 3719, which is that changing window size while fullscreen doesn't take effect when leaving fullscreen, but introduces bug 3809, which is that a maximized window doesn't go back to normal size when restored, so this code is disabled until we can properly handle the beginning and end of maximize and restore. */ /* Restore windowed size and position in case it changed while fullscreen */ { NSRect rect; rect.origin.x = window->windowed.x; rect.origin.y = window->windowed.y; rect.size.width = window->windowed.w; rect.size.height = window->windowed.h; ConvertNSRect([nswindow screen], NO, &rect); s_moveHack = 0; [nswindow setContentSize:rect.size]; [nswindow setFrameOrigin:rect.origin]; s_moveHack = SDL_GetTicks(); } #endif /* 0 */ /* Force the size change event in case it was delivered earlier while the window was still animating into place. */ window->w = 0; window->h = 0; [self windowDidMove:aNotification]; [self windowDidResize:aNotification]; /* FIXME: Why does the window get hidden? */ if (window->flags & SDL_WINDOW_SHOWN) { Cocoa_ShowWindow(SDL_GetVideoDevice(), window); } } /* There's some state that isn't quite back to normal when windowDidExitFullScreen triggers. For example, the minimize button on the titlebar doesn't actually enable for another 200 milliseconds or so on this MacBook. Camp here and wait for that to happen before going on, in case we're exiting fullscreen to minimize, which need that window state to be normal before it will work. */ button = [nswindow standardWindowButton:NSWindowMiniaturizeButton]; if (button) { int iterations = 0; while (![button isEnabled] && (iterations < 100)) { SDL_Delay(10); SDL_PumpEvents(); iterations++; } } } -(NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions { if ((_data->window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) { return NSApplicationPresentationFullScreen | NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar; } else { return proposedOptions; } } /* We'll respond to key events by mostly doing nothing so we don't beep. * We could handle key messages here, but we lose some in the NSApp dispatch, * where they get converted to action messages, etc. */ - (void)flagsChanged:(NSEvent *)theEvent { /*Cocoa_HandleKeyEvent(SDL_GetVideoDevice(), theEvent);*/ /* Catch capslock in here as a special case: https://developer.apple.com/library/archive/qa/qa1519/_index.html Note that technote's check of keyCode doesn't work. At least on the 10.15 beta, capslock comes through here as keycode 255, but it's safe to send duplicate key events; SDL filters them out quickly in SDL_SendKeyboardKey(). */ /* Also note that SDL_SendKeyboardKey expects all capslock events to be keypresses; it won't toggle the mod state if you send a keyrelease. */ const SDL_bool osenabled = ([theEvent modifierFlags] & NSEventModifierFlagCapsLock) ? SDL_TRUE : SDL_FALSE; const SDL_bool sdlenabled = (SDL_GetModState() & KMOD_CAPS) ? SDL_TRUE : SDL_FALSE; if (osenabled ^ sdlenabled) { SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_CAPSLOCK); SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_CAPSLOCK); } } - (void)keyDown:(NSEvent *)theEvent { /*Cocoa_HandleKeyEvent(SDL_GetVideoDevice(), theEvent);*/ } - (void)keyUp:(NSEvent *)theEvent { /*Cocoa_HandleKeyEvent(SDL_GetVideoDevice(), theEvent);*/ } /* We'll respond to selectors by doing nothing so we don't beep. * The escape key gets converted to a "cancel" selector, etc. */ - (void)doCommandBySelector:(SEL)aSelector { /*NSLog(@"doCommandBySelector: %@\n", NSStringFromSelector(aSelector));*/ } - (BOOL)processHitTest:(NSEvent *)theEvent { SDL_assert(isDragAreaRunning == [_data->nswindow isMovableByWindowBackground]); if (_data->window->hit_test) { /* if no hit-test, skip this. */ const NSPoint location = [theEvent locationInWindow]; const SDL_Point point = { (int) location.x, _data->window->h - (((int) location.y)-1) }; const SDL_HitTestResult rc = _data->window->hit_test(_data->window, &point, _data->window->hit_test_data); if (rc == SDL_HITTEST_DRAGGABLE) { if (!isDragAreaRunning) { isDragAreaRunning = YES; [_data->nswindow setMovableByWindowBackground:YES]; } return YES; /* dragging! */ } } if (isDragAreaRunning) { isDragAreaRunning = NO; [_data->nswindow setMovableByWindowBackground:NO]; return YES; /* was dragging, drop event. */ } return NO; /* not a special area, carry on. */ } - (void)mouseDown:(NSEvent *)theEvent { const SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse) { return; } const SDL_MouseID mouseID = mouse->mouseID; int button; int clicks; /* Ignore events that aren't inside the client area (i.e. title bar.) */ if ([theEvent window]) { NSRect windowRect = [[[theEvent window] contentView] frame]; if (!NSMouseInRect([theEvent locationInWindow], windowRect, NO)) { return; } } if ([self processHitTest:theEvent]) { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIT_TEST, 0, 0); return; /* dragging, drop event. */ } switch ([theEvent buttonNumber]) { case 0: if (([theEvent modifierFlags] & NSEventModifierFlagControl) && GetHintCtrlClickEmulateRightClick()) { wasCtrlLeft = YES; button = SDL_BUTTON_RIGHT; } else { wasCtrlLeft = NO; button = SDL_BUTTON_LEFT; } break; case 1: button = SDL_BUTTON_RIGHT; break; case 2: button = SDL_BUTTON_MIDDLE; break; default: button = (int) [theEvent buttonNumber] + 1; break; } clicks = (int) [theEvent clickCount]; SDL_SendMouseButtonClicks(_data->window, mouseID, SDL_PRESSED, button, clicks); } - (void)rightMouseDown:(NSEvent *)theEvent { [self mouseDown:theEvent]; } - (void)otherMouseDown:(NSEvent *)theEvent { [self mouseDown:theEvent]; } - (void)mouseUp:(NSEvent *)theEvent { const SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse) { return; } const SDL_MouseID mouseID = mouse->mouseID; int button; int clicks; if ([self processHitTest:theEvent]) { SDL_SendWindowEvent(_data->window, SDL_WINDOWEVENT_HIT_TEST, 0, 0); return; /* stopped dragging, drop event. */ } switch ([theEvent buttonNumber]) { case 0: if (wasCtrlLeft) { button = SDL_BUTTON_RIGHT; wasCtrlLeft = NO; } else { button = SDL_BUTTON_LEFT; } break; case 1: button = SDL_BUTTON_RIGHT; break; case 2: button = SDL_BUTTON_MIDDLE; break; default: button = (int) [theEvent buttonNumber] + 1; break; } clicks = (int) [theEvent clickCount]; SDL_SendMouseButtonClicks(_data->window, mouseID, SDL_RELEASED, button, clicks); } - (void)rightMouseUp:(NSEvent *)theEvent { [self mouseUp:theEvent]; } - (void)otherMouseUp:(NSEvent *)theEvent { [self mouseUp:theEvent]; } - (void)mouseMoved:(NSEvent *)theEvent { SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse) { return; } const SDL_MouseID mouseID = mouse->mouseID; SDL_Window *window = _data->window; NSPoint point; int x, y; if ([self processHitTest:theEvent]) { SDL_SendWindowEvent(window, SDL_WINDOWEVENT_HIT_TEST, 0, 0); return; /* dragging, drop event. */ } if (mouse->relative_mode) { return; } point = [theEvent locationInWindow]; x = (int)point.x; y = (int)(window->h - point.y); if (window->flags & SDL_WINDOW_INPUT_GRABBED) { if (x < 0 || x >= window->w || y < 0 || y >= window->h) { if (x < 0) { x = 0; } else if (x >= window->w) { x = window->w - 1; } if (y < 0) { y = 0; } else if (y >= window->h) { y = window->h - 1; } #if !SDL_MAC_NO_SANDBOX CGPoint cgpoint; /* When SDL_MAC_NO_SANDBOX is set, this is handled by * SDL_cocoamousetap.m. */ cgpoint.x = window->x + x; cgpoint.y = window->y + y; CGDisplayMoveCursorToPoint(kCGDirectMainDisplay, cgpoint); CGAssociateMouseAndMouseCursorPosition(YES); Cocoa_HandleMouseWarp(cgpoint.x, cgpoint.y); #endif } } SDL_SendMouseMotion(window, mouseID, 0, x, y); } - (void)mouseDragged:(NSEvent *)theEvent { [self mouseMoved:theEvent]; } - (void)rightMouseDragged:(NSEvent *)theEvent { [self mouseMoved:theEvent]; } - (void)otherMouseDragged:(NSEvent *)theEvent { [self mouseMoved:theEvent]; } - (void)scrollWheel:(NSEvent *)theEvent { Cocoa_HandleMouseWheel(_data->window, theEvent); } - (void)touchesBeganWithEvent:(NSEvent *) theEvent { /* probably a MacBook trackpad; make this look like a synthesized event. This is backwards from reality, but better matches user expectations. */ const BOOL istrackpad = ([theEvent subtype] == NSEventSubtypeMouseEvent); NSSet *touches = [theEvent touchesMatchingPhase:NSTouchPhaseAny inView:nil]; const SDL_TouchID touchID = istrackpad ? SDL_MOUSE_TOUCHID : (SDL_TouchID)(intptr_t)[[touches anyObject] device]; int existingTouchCount = 0; for (NSTouch* touch in touches) { if ([touch phase] != NSTouchPhaseBegan) { existingTouchCount++; } } if (existingTouchCount == 0) { int numFingers = SDL_GetNumTouchFingers(touchID); DLog("Reset Lost Fingers: %d", numFingers); for (--numFingers; numFingers >= 0; --numFingers) { SDL_Finger* finger = SDL_GetTouchFinger(touchID, numFingers); /* trackpad touches have no window. If we really wanted one we could * use the window that has mouse or keyboard focus. * Sending a null window currently also prevents synthetic mouse * events from being generated from touch events. */ SDL_Window *window = NULL; SDL_SendTouch(touchID, finger->id, window, SDL_FALSE, 0, 0, 0); } } DLog("Began Fingers: %lu .. existing: %d", (unsigned long)[touches count], existingTouchCount); [self handleTouches:NSTouchPhaseBegan withEvent:theEvent]; } - (void)touchesMovedWithEvent:(NSEvent *) theEvent { [self handleTouches:NSTouchPhaseMoved withEvent:theEvent]; } - (void)touchesEndedWithEvent:(NSEvent *) theEvent { [self handleTouches:NSTouchPhaseEnded withEvent:theEvent]; } - (void)touchesCancelledWithEvent:(NSEvent *) theEvent { [self handleTouches:NSTouchPhaseCancelled withEvent:theEvent]; } - (void)handleTouches:(NSTouchPhase) phase withEvent:(NSEvent *) theEvent { NSSet *touches = [theEvent touchesMatchingPhase:phase inView:nil]; /* probably a MacBook trackpad; make this look like a synthesized event. This is backwards from reality, but better matches user expectations. */ const BOOL istrackpad = ([theEvent subtype] == NSEventSubtypeMouseEvent); for (NSTouch *touch in touches) { const SDL_TouchID touchId = istrackpad ? SDL_MOUSE_TOUCHID : (SDL_TouchID)(intptr_t)[touch device]; SDL_TouchDeviceType devtype = SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE; /* trackpad touches have no window. If we really wanted one we could * use the window that has mouse or keyboard focus. * Sending a null window currently also prevents synthetic mouse events * from being generated from touch events. */ SDL_Window *window = NULL; #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101202 /* Added in the 10.12.2 SDK. */ if ([touch respondsToSelector:@selector(type)]) { /* TODO: Before implementing direct touch support here, we need to * figure out whether the OS generates mouse events from them on its * own. If it does, we should prevent SendTouch from generating * synthetic mouse events for these touches itself (while also * sending a window.) It will also need to use normalized window- * relative coordinates via [touch locationInView:]. */ if ([touch type] == NSTouchTypeDirect) { continue; } } #endif if (SDL_AddTouch(touchId, devtype, "") < 0) { return; } const SDL_FingerID fingerId = (SDL_FingerID)(intptr_t)[touch identity]; float x = [touch normalizedPosition].x; float y = [touch normalizedPosition].y; /* Make the origin the upper left instead of the lower left */ y = 1.0f - y; switch (phase) { case NSTouchPhaseBegan: SDL_SendTouch(touchId, fingerId, window, SDL_TRUE, x, y, 1.0f); break; case NSTouchPhaseEnded: case NSTouchPhaseCancelled: SDL_SendTouch(touchId, fingerId, window, SDL_FALSE, x, y, 1.0f); break; case NSTouchPhaseMoved: SDL_SendTouchMotion(touchId, fingerId, window, x, y, 1.0f); break; default: break; } } } @end @interface SDLView : NSView { SDL_Window *_sdlWindow; } - (void)setSDLWindow:(SDL_Window*)window; /* The default implementation doesn't pass rightMouseDown to responder chain */ - (void)rightMouseDown:(NSEvent *)theEvent; - (BOOL)mouseDownCanMoveWindow; - (void)drawRect:(NSRect)dirtyRect; - (BOOL)acceptsFirstMouse:(NSEvent *)theEvent; - (BOOL)wantsUpdateLayer; - (void)updateLayer; @end @implementation SDLView - (void)setSDLWindow:(SDL_Window*)window { _sdlWindow = window; } /* this is used on older macOS revisions, and newer ones which emulate old NSOpenGLContext behaviour while still using a layer under the hood. 10.8 and later use updateLayer, up until 10.14.2 or so, which uses drawRect without a GraphicsContext and with a layer active instead (for OpenGL contexts). */ - (void)drawRect:(NSRect)dirtyRect { /* Force the graphics context to clear to black so we don't get a flash of white until the app is ready to draw. In practice on modern macOS, this only gets called for window creation and other extraordinary events. */ if ([NSGraphicsContext currentContext]) { [[NSColor blackColor] setFill]; NSRectFill(dirtyRect); } else if (self.layer) { self.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack); } SDL_SendWindowEvent(_sdlWindow, SDL_WINDOWEVENT_EXPOSED, 0, 0); } - (BOOL)wantsUpdateLayer { return YES; } /* This is also called when a Metal layer is active. */ - (void)updateLayer { /* Force the graphics context to clear to black so we don't get a flash of white until the app is ready to draw. In practice on modern macOS, this only gets called for window creation and other extraordinary events. */ self.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack); ScheduleContextUpdates((SDL_WindowData *) _sdlWindow->driverdata); SDL_SendWindowEvent(_sdlWindow, SDL_WINDOWEVENT_EXPOSED, 0, 0); } - (void)rightMouseDown:(NSEvent *)theEvent { [[self nextResponder] rightMouseDown:theEvent]; } - (BOOL)mouseDownCanMoveWindow { /* Always say YES, but this doesn't do anything until we call -[NSWindow setMovableByWindowBackground:YES], which we ninja-toggle during mouse events when we're using a drag area. */ return YES; } - (void)resetCursorRects { [super resetCursorRects]; SDL_Mouse *mouse = SDL_GetMouse(); if (mouse->cursor_shown && mouse->cur_cursor && !mouse->relative_mode) { [self addCursorRect:[self bounds] cursor:mouse->cur_cursor->driverdata]; } else { [self addCursorRect:[self bounds] cursor:[NSCursor invisibleCursor]]; } } - (BOOL)acceptsFirstMouse:(NSEvent *)theEvent { if (SDL_GetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH)) { return SDL_GetHintBoolean(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, SDL_FALSE); } else { return SDL_GetHintBoolean("SDL_MAC_MOUSE_FOCUS_CLICKTHROUGH", SDL_FALSE); } } @end static int SetupWindowData(_THIS, SDL_Window * window, NSWindow *nswindow, NSView *nsview, SDL_bool created) { @autoreleasepool { SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata; SDL_WindowData *data; /* Allocate the window data */ window->driverdata = data = (SDL_WindowData *) SDL_calloc(1, sizeof(*data)); if (!data) { return SDL_OutOfMemory(); } data->window = window; data->nswindow = nswindow; data->created = created; data->videodata = videodata; data->nscontexts = [[NSMutableArray alloc] init]; data->sdlContentView = nsview; /* Create an event listener for the window */ data->listener = [[Cocoa_WindowListener alloc] init]; /* Fill in the SDL window with the window data */ { NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]]; ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); window->x = (int)rect.origin.x; window->y = (int)rect.origin.y; window->w = (int)rect.size.width; window->h = (int)rect.size.height; } /* Set up the listener after we create the view */ [data->listener listen:data]; if ([nswindow isVisible]) { window->flags |= SDL_WINDOW_SHOWN; } else { window->flags &= ~SDL_WINDOW_SHOWN; } { unsigned long style = [nswindow styleMask]; if (style == NSWindowStyleMaskBorderless) { window->flags |= SDL_WINDOW_BORDERLESS; } else { window->flags &= ~SDL_WINDOW_BORDERLESS; } if (style & NSWindowStyleMaskResizable) { window->flags |= SDL_WINDOW_RESIZABLE; } else { window->flags &= ~SDL_WINDOW_RESIZABLE; } } /* isZoomed always returns true if the window is not resizable */ if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) { window->flags |= SDL_WINDOW_MAXIMIZED; } else { window->flags &= ~SDL_WINDOW_MAXIMIZED; } if ([nswindow isMiniaturized]) { window->flags |= SDL_WINDOW_MINIMIZED; } else { window->flags &= ~SDL_WINDOW_MINIMIZED; } if ([nswindow isKeyWindow]) { window->flags |= SDL_WINDOW_INPUT_FOCUS; SDL_SetKeyboardFocus(data->window); } /* Prevents the window's "window device" from being destroyed when it is * hidden. See http://www.mikeash.com/pyblog/nsopenglcontext-and-one-shot.html */ [nswindow setOneShot:NO]; /* All done! */ window->driverdata = data; return 0; }} int Cocoa_CreateWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata; NSWindow *nswindow; SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); NSRect rect; SDL_Rect bounds; NSUInteger style; NSArray *screens = [NSScreen screens]; Cocoa_GetDisplayBounds(_this, display, &bounds); rect.origin.x = window->x; rect.origin.y = window->y; rect.size.width = window->w; rect.size.height = window->h; ConvertNSRect([screens objectAtIndex:0], (window->flags & FULLSCREEN_MASK), &rect); style = GetWindowStyle(window); /* Figure out which screen to place this window */ NSScreen *screen = nil; for (NSScreen *candidate in screens) { NSRect screenRect = [candidate frame]; if (rect.origin.x >= screenRect.origin.x && rect.origin.x < screenRect.origin.x + screenRect.size.width && rect.origin.y >= screenRect.origin.y && rect.origin.y < screenRect.origin.y + screenRect.size.height) { screen = candidate; rect.origin.x -= screenRect.origin.x; rect.origin.y -= screenRect.origin.y; } } @try { nswindow = [[SDLWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:NO screen:screen]; } @catch (NSException *e) { return SDL_SetError("%s", [[e reason] UTF8String]); } #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 /* Added in the 10.12.0 SDK. */ /* By default, don't allow users to make our window tabbed in 10.12 or later */ if ([nswindow respondsToSelector:@selector(setTabbingMode:)]) { [nswindow setTabbingMode:NSWindowTabbingModeDisallowed]; } #endif if (videodata->allow_spaces) { SDL_assert(floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6); SDL_assert([nswindow respondsToSelector:@selector(toggleFullScreen:)]); /* we put FULLSCREEN_DESKTOP windows in their own Space, without a toggle button or menubar, later */ if (window->flags & SDL_WINDOW_RESIZABLE) { /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */ [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; } } if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { [nswindow setLevel:NSFloatingWindowLevel]; } /* Create a default view for this window */ rect = [nswindow contentRectForFrameRect:[nswindow frame]]; SDLView *contentView = [[SDLView alloc] initWithFrame:rect]; [contentView setSDLWindow:window]; /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif /* Note: as of the macOS 10.15 SDK, this defaults to YES instead of NO when * the NSHighResolutionCapable boolean is set in Info.plist. */ if ([contentView respondsToSelector:@selector(setWantsBestResolutionOpenGLSurface:)]) { BOOL highdpi = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; [contentView setWantsBestResolutionOpenGLSurface:highdpi]; } #ifdef __clang__ #pragma clang diagnostic pop #endif #if SDL_VIDEO_OPENGL_ES2 #if SDL_VIDEO_OPENGL_EGL if ((window->flags & SDL_WINDOW_OPENGL) && _this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { [contentView setWantsLayer:TRUE]; } #endif /* SDL_VIDEO_OPENGL_EGL */ #endif /* SDL_VIDEO_OPENGL_ES2 */ [nswindow setContentView:contentView]; [contentView release]; if (SetupWindowData(_this, window, nswindow, contentView, SDL_TRUE) < 0) { [nswindow release]; return -1; } if (!(window->flags & SDL_WINDOW_OPENGL)) { return 0; } /* The rest of this macro mess is for OpenGL or OpenGL ES windows */ #if SDL_VIDEO_OPENGL_ES2 if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { #if SDL_VIDEO_OPENGL_EGL if (Cocoa_GLES_SetupWindow(_this, window) < 0) { Cocoa_DestroyWindow(_this, window); return -1; } return 0; #else return SDL_SetError("Could not create GLES window surface (EGL support not configured)"); #endif /* SDL_VIDEO_OPENGL_EGL */ } #endif /* SDL_VIDEO_OPENGL_ES2 */ return 0; }} int Cocoa_CreateWindowFrom(_THIS, SDL_Window * window, const void *data) { @autoreleasepool { NSView* nsview = nil; NSWindow *nswindow = nil; if ([(id)data isKindOfClass:[NSWindow class]]) { nswindow = (NSWindow*)data; nsview = [nswindow contentView]; } else if ([(id)data isKindOfClass:[NSView class]]) { nsview = (NSView*)data; nswindow = [nsview window]; } else { SDL_assert(false); } NSString *title; /* Query the title from the existing window */ title = [nswindow title]; if (title) { window->title = SDL_strdup([title UTF8String]); } /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif /* Note: as of the macOS 10.15 SDK, this defaults to YES instead of NO when * the NSHighResolutionCapable boolean is set in Info.plist. */ if ([nsview respondsToSelector:@selector(setWantsBestResolutionOpenGLSurface:)]) { BOOL highdpi = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; [nsview setWantsBestResolutionOpenGLSurface:highdpi]; } #ifdef __clang__ #pragma clang diagnostic pop #endif return SetupWindowData(_this, window, nswindow, nsview, SDL_FALSE); }} void Cocoa_SetWindowTitle(_THIS, SDL_Window * window) { @autoreleasepool { const char *title = window->title ? window->title : ""; NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow; NSString *string = [[NSString alloc] initWithUTF8String:title]; [nswindow setTitle:string]; [string release]; }} void Cocoa_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon) { @autoreleasepool { NSImage *nsimage = Cocoa_CreateImage(icon); if (nsimage) { [NSApp setApplicationIconImage:nsimage]; } }} void Cocoa_SetWindowPosition(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *windata = (SDL_WindowData *) window->driverdata; NSWindow *nswindow = windata->nswindow; NSRect rect; Uint32 moveHack; rect.origin.x = window->x; rect.origin.y = window->y; rect.size.width = window->w; rect.size.height = window->h; ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); moveHack = s_moveHack; s_moveHack = 0; [nswindow setFrameOrigin:rect.origin]; s_moveHack = moveHack; ScheduleContextUpdates(windata); }} void Cocoa_SetWindowSize(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *windata = (SDL_WindowData *) window->driverdata; NSWindow *nswindow = windata->nswindow; NSRect rect; Uint32 moveHack; /* Cocoa will resize the window from the bottom-left rather than the * top-left when -[nswindow setContentSize:] is used, so we must set the * entire frame based on the new size, in order to preserve the position. */ rect.origin.x = window->x; rect.origin.y = window->y; rect.size.width = window->w; rect.size.height = window->h; ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); moveHack = s_moveHack; s_moveHack = 0; [nswindow setFrame:[nswindow frameRectForContentRect:rect] display:YES]; s_moveHack = moveHack; ScheduleContextUpdates(windata); }} void Cocoa_SetWindowMinimumSize(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *windata = (SDL_WindowData *) window->driverdata; NSSize minSize; minSize.width = window->min_w; minSize.height = window->min_h; [windata->nswindow setContentMinSize:minSize]; }} void Cocoa_SetWindowMaximumSize(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *windata = (SDL_WindowData *) window->driverdata; NSSize maxSize; maxSize.width = window->max_w; maxSize.height = window->max_h; [windata->nswindow setContentMaxSize:maxSize]; }} void Cocoa_ShowWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *windowData = ((SDL_WindowData *) window->driverdata); NSWindow *nswindow = windowData->nswindow; if (![nswindow isMiniaturized]) { [windowData->listener pauseVisibleObservation]; [nswindow makeKeyAndOrderFront:nil]; [windowData->listener resumeVisibleObservation]; } }} void Cocoa_HideWindow(_THIS, SDL_Window * window) { @autoreleasepool { NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow; [nswindow orderOut:nil]; }} void Cocoa_RaiseWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *windowData = ((SDL_WindowData *) window->driverdata); NSWindow *nswindow = windowData->nswindow; /* makeKeyAndOrderFront: has the side-effect of deminiaturizing and showing a minimized or hidden window, so check for that before showing it. */ [windowData->listener pauseVisibleObservation]; if (![nswindow isMiniaturized] && [nswindow isVisible]) { [NSApp activateIgnoringOtherApps:YES]; [nswindow makeKeyAndOrderFront:nil]; } [windowData->listener resumeVisibleObservation]; }} void Cocoa_MaximizeWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *windata = (SDL_WindowData *) window->driverdata; NSWindow *nswindow = windata->nswindow; [nswindow zoom:nil]; ScheduleContextUpdates(windata); }} void Cocoa_MinimizeWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; NSWindow *nswindow = data->nswindow; if ([data->listener isInFullscreenSpaceTransition]) { [data->listener addPendingWindowOperation:PENDING_OPERATION_MINIMIZE]; } else { [nswindow miniaturize:nil]; } }} void Cocoa_RestoreWindow(_THIS, SDL_Window * window) { @autoreleasepool { NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow; if ([nswindow isMiniaturized]) { [nswindow deminiaturize:nil]; } else if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) { [nswindow zoom:nil]; } }} void Cocoa_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered) { @autoreleasepool { if (SetWindowStyle(window, GetWindowStyle(window))) { if (bordered) { Cocoa_SetWindowTitle(_this, window); /* this got blanked out. */ } } }} void Cocoa_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable) { @autoreleasepool { /* Don't set this if we're in a space! * The window will get permanently stuck if resizable is false. * -flibit */ SDL_WindowData *data = (SDL_WindowData *) window->driverdata; Cocoa_WindowListener *listener = data->listener; if (![listener isInFullscreenSpace]) { SetWindowStyle(window, GetWindowStyle(window)); } }} void Cocoa_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen) { @autoreleasepool { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; NSWindow *nswindow = data->nswindow; NSRect rect; /* The view responder chain gets messed with during setStyleMask */ if ([data->sdlContentView nextResponder] == data->listener) { [data->sdlContentView setNextResponder:nil]; } if (fullscreen) { SDL_Rect bounds; Cocoa_GetDisplayBounds(_this, display, &bounds); rect.origin.x = bounds.x; rect.origin.y = bounds.y; rect.size.width = bounds.w; rect.size.height = bounds.h; ConvertNSRect([nswindow screen], fullscreen, &rect); /* Hack to fix origin on Mac OS X 10.4 This is no longer needed as of Mac OS X 10.15, according to bug 4822. */ NSProcessInfo *processInfo = [NSProcessInfo processInfo]; #if MAC_OS_X_VERSION_MAX_ALLOWED < 101000 /* NSOperatingSystemVersion added in the 10.10 SDK */ typedef struct { NSInteger majorVersion; NSInteger minorVersion; NSInteger patchVersion; } NSOperatingSystemVersion; #endif NSOperatingSystemVersion version = { 10, 15, 0 }; if (![processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] || ![processInfo isOperatingSystemAtLeastVersion:version]) { NSRect screenRect = [[nswindow screen] frame]; if (screenRect.size.height >= 1.0f) { rect.origin.y += (screenRect.size.height - rect.size.height); } } [nswindow setStyleMask:NSWindowStyleMaskBorderless]; } else { rect.origin.x = window->windowed.x; rect.origin.y = window->windowed.y; rect.size.width = window->windowed.w; rect.size.height = window->windowed.h; ConvertNSRect([nswindow screen], fullscreen, &rect); /* The window is not meant to be fullscreen, but its flags might have a * fullscreen bit set if it's scheduled to go fullscreen immediately * after. Always using the windowed mode style here works around bugs in * macOS 10.15 where the window doesn't properly restore the windowed * mode decorations after exiting fullscreen-desktop, when the window * was created as fullscreen-desktop. */ [nswindow setStyleMask:GetWindowWindowedStyle(window)]; /* Hack to restore window decorations on Mac OS X 10.10 */ NSRect frameRect = [nswindow frame]; [nswindow setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO]; [nswindow setFrame:frameRect display:NO]; } /* The view responder chain gets messed with during setStyleMask */ if ([data->sdlContentView nextResponder] != data->listener) { [data->sdlContentView setNextResponder:data->listener]; } s_moveHack = 0; [nswindow setContentSize:rect.size]; [nswindow setFrameOrigin:rect.origin]; s_moveHack = SDL_GetTicks(); /* When the window style changes the title is cleared */ if (!fullscreen) { Cocoa_SetWindowTitle(_this, window); } if (SDL_ShouldAllowTopmost() && fullscreen) { /* OpenGL is rendering to the window, so make it visible! */ [nswindow setLevel:CGShieldingWindowLevel()]; } else if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { [nswindow setLevel:NSFloatingWindowLevel]; } else { [nswindow setLevel:kCGNormalWindowLevel]; } if ([nswindow isVisible] || fullscreen) { [data->listener pauseVisibleObservation]; [nswindow makeKeyAndOrderFront:nil]; [data->listener resumeVisibleObservation]; } ScheduleContextUpdates(data); }} int Cocoa_SetWindowGammaRamp(_THIS, SDL_Window * window, const Uint16 * ramp) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); CGDirectDisplayID display_id = ((SDL_DisplayData *)display->driverdata)->display; const uint32_t tableSize = 256; CGGammaValue redTable[tableSize]; CGGammaValue greenTable[tableSize]; CGGammaValue blueTable[tableSize]; uint32_t i; float inv65535 = 1.0f / 65535.0f; /* Extract gamma values into separate tables, convert to floats between 0.0 and 1.0 */ for (i = 0; i < 256; i++) { redTable[i] = ramp[0*256+i] * inv65535; greenTable[i] = ramp[1*256+i] * inv65535; blueTable[i] = ramp[2*256+i] * inv65535; } if (CGSetDisplayTransferByTable(display_id, tableSize, redTable, greenTable, blueTable) != CGDisplayNoErr) { return SDL_SetError("CGSetDisplayTransferByTable()"); } return 0; } int Cocoa_GetWindowGammaRamp(_THIS, SDL_Window * window, Uint16 * ramp) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); CGDirectDisplayID display_id = ((SDL_DisplayData *)display->driverdata)->display; const uint32_t tableSize = 256; CGGammaValue redTable[tableSize]; CGGammaValue greenTable[tableSize]; CGGammaValue blueTable[tableSize]; uint32_t i, tableCopied; if (CGGetDisplayTransferByTable(display_id, tableSize, redTable, greenTable, blueTable, &tableCopied) != CGDisplayNoErr) { return SDL_SetError("CGGetDisplayTransferByTable()"); } for (i = 0; i < tableCopied; i++) { ramp[0*256+i] = (Uint16)(redTable[i] * 65535.0f); ramp[1*256+i] = (Uint16)(greenTable[i] * 65535.0f); ramp[2*256+i] = (Uint16)(blueTable[i] * 65535.0f); } return 0; } void Cocoa_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_WindowData *data = (SDL_WindowData *) window->driverdata; /* Enable or disable the event tap as necessary */ Cocoa_EnableMouseEventTap(mouse->driverdata, grabbed); /* Move the cursor to the nearest point in the window */ if (grabbed && data && ![data->listener isMoving]) { int x, y; CGPoint cgpoint; SDL_GetMouseState(&x, &y); cgpoint.x = window->x + x; cgpoint.y = window->y + y; Cocoa_HandleMouseWarp(cgpoint.x, cgpoint.y); DLog("Returning cursor to (%g, %g)", cgpoint.x, cgpoint.y); CGDisplayMoveCursorToPoint(kCGDirectMainDisplay, cgpoint); } if ( data && (window->flags & SDL_WINDOW_FULLSCREEN) ) { if (SDL_ShouldAllowTopmost() && (window->flags & SDL_WINDOW_INPUT_FOCUS) && ![data->listener isInFullscreenSpace]) { /* OpenGL is rendering to the window, so make it visible! */ /* Doing this in 10.11 while in a Space breaks things (bug #3152) */ [data->nswindow setLevel:CGShieldingWindowLevel()]; } else if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { [data->nswindow setLevel:NSFloatingWindowLevel]; } else { [data->nswindow setLevel:kCGNormalWindowLevel]; } } } void Cocoa_DestroyWindow(_THIS, SDL_Window * window) { @autoreleasepool { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (data) { if ([data->listener isInFullscreenSpace]) { [NSMenu setMenuBarVisible:YES]; } [data->listener close]; [data->listener release]; if (data->created) { /* Release the content view to avoid further updateLayer callbacks */ [data->nswindow setContentView:nil]; [data->nswindow close]; } NSArray *contexts = [[data->nscontexts copy] autorelease]; for (SDLOpenGLContext *context in contexts) { /* Calling setWindow:NULL causes the context to remove itself from the context list. */ [context setWindow:NULL]; } [data->nscontexts release]; SDL_free(data); } window->driverdata = NULL; }} SDL_bool Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info) { NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow; if (info->version.major <= SDL_MAJOR_VERSION) { info->subsystem = SDL_SYSWM_COCOA; info->info.cocoa.window = nswindow; return SDL_TRUE; } else { SDL_SetError("Application not compiled with SDL %d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION); return SDL_FALSE; } } SDL_bool Cocoa_IsWindowInFullscreenSpace(SDL_Window * window) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if ([data->listener isInFullscreenSpace]) { return SDL_TRUE; } else { return SDL_FALSE; } } SDL_bool Cocoa_SetWindowFullscreenSpace(SDL_Window * window, SDL_bool state) { @autoreleasepool { SDL_bool succeeded = SDL_FALSE; SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (data->inWindowFullscreenTransition) { return SDL_FALSE; } data->inWindowFullscreenTransition = SDL_TRUE; if ([data->listener setFullscreenSpace:(state ? YES : NO)]) { const int maxattempts = 3; int attempt = 0; while (++attempt <= maxattempts) { /* Wait for the transition to complete, so application changes take effect properly (e.g. setting the window size, etc.) */ const int limit = 10000; int count = 0; while ([data->listener isInFullscreenSpaceTransition]) { if ( ++count == limit ) { /* Uh oh, transition isn't completing. Should we assert? */ break; } SDL_Delay(1); SDL_PumpEvents(); } if ([data->listener isInFullscreenSpace] == (state ? YES : NO)) break; /* Try again, the last attempt was interrupted by user gestures */ if (![data->listener setFullscreenSpace:(state ? YES : NO)]) break; /* ??? */ } /* Return TRUE to prevent non-space fullscreen logic from running */ succeeded = SDL_TRUE; } data->inWindowFullscreenTransition = SDL_FALSE; return succeeded; }} int Cocoa_SetWindowHitTest(SDL_Window * window, SDL_bool enabled) { return 0; /* just succeed, the real work is done elsewhere. */ } void Cocoa_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; if (accept) { [data->nswindow registerForDraggedTypes:[NSArray arrayWithObject:(NSString *)kUTTypeFileURL]]; } else { [data->nswindow unregisterDraggedTypes]; } } int Cocoa_SetWindowOpacity(_THIS, SDL_Window * window, float opacity) { SDL_WindowData *data = (SDL_WindowData *) window->driverdata; [data->nswindow setAlphaValue:opacity]; return 0; } #endif /* SDL_VIDEO_DRIVER_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/cocoa/SDL_cocoawindow.m
Objective-C
apache-2.0
69,943
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_window.h" #include "../../events/SDL_windowevents_c.h" #define COLOR_EXPAND(col) col.r, col.g, col.b, col.a static DFB_Theme theme_std = { 4, 4, 8, 8, {255, 200, 200, 200}, 24, {255, 0, 0, 255}, 16, {255, 255, 255, 255}, "/usr/share/fonts/truetype/freefont/FreeSans.ttf", {255, 255, 0, 0}, {255, 255, 255, 0}, }; static DFB_Theme theme_none = { 0, 0, 0, 0, {0, 0, 0, 0}, 0, {0, 0, 0, 0}, 0, {0, 0, 0, 0}, NULL }; static void DrawTriangle(IDirectFBSurface * s, int down, int x, int y, int w) { int x1, x2, x3; int y1, y2, y3; if (down) { x1 = x + w / 2; x2 = x; x3 = x + w; y1 = y + w; y2 = y; y3 = y; } else { x1 = x + w / 2; x2 = x; x3 = x + w; y1 = y; y2 = y + w; y3 = y + w; } s->FillTriangle(s, x1, y1, x2, y2, x3, y3); } static void LoadFont(_THIS, SDL_Window * window) { SDL_DFB_DEVICEDATA(_this); SDL_DFB_WINDOWDATA(window); if (windata->font != NULL) { SDL_DFB_RELEASE(windata->font); windata->font = NULL; SDL_DFB_CHECK(windata->window_surface->SetFont(windata->window_surface, windata->font)); } if (windata->theme.font != NULL) { DFBFontDescription fdesc; SDL_zero(fdesc); fdesc.flags = DFDESC_HEIGHT; fdesc.height = windata->theme.font_size; SDL_DFB_CHECK(devdata-> dfb->CreateFont(devdata->dfb, windata->theme.font, &fdesc, &windata->font)); SDL_DFB_CHECK(windata->window_surface->SetFont(windata->window_surface, windata->font)); } } static void DrawCraption(_THIS, IDirectFBSurface * s, int x, int y, char *text) { DFBSurfaceTextFlags flags; flags = DSTF_CENTER | DSTF_TOP; s->DrawString(s, text, -1, x, y, flags); } void DirectFB_WM_RedrawLayout(_THIS, SDL_Window * window) { SDL_DFB_WINDOWDATA(window); IDirectFBSurface *s = windata->window_surface; DFB_Theme *t = &windata->theme; int i; int d = (t->caption_size - t->font_size) / 2; int x, y, w; if (!windata->is_managed || (window->flags & SDL_WINDOW_FULLSCREEN)) return; SDL_DFB_CHECK(s->SetSrcBlendFunction(s, DSBF_ONE)); SDL_DFB_CHECK(s->SetDstBlendFunction(s, DSBF_ZERO)); SDL_DFB_CHECK(s->SetDrawingFlags(s, DSDRAW_NOFX)); SDL_DFB_CHECK(s->SetBlittingFlags(s, DSBLIT_NOFX)); LoadFont(_this, window); /* s->SetDrawingFlags(s, DSDRAW_BLEND); */ s->SetColor(s, COLOR_EXPAND(t->frame_color)); /* top */ for (i = 0; i < t->top_size; i++) s->DrawLine(s, 0, i, windata->size.w, i); /* bottom */ for (i = windata->size.h - t->bottom_size; i < windata->size.h; i++) s->DrawLine(s, 0, i, windata->size.w, i); /* left */ for (i = 0; i < t->left_size; i++) s->DrawLine(s, i, 0, i, windata->size.h); /* right */ for (i = windata->size.w - t->right_size; i < windata->size.w; i++) s->DrawLine(s, i, 0, i, windata->size.h); /* Caption */ s->SetColor(s, COLOR_EXPAND(t->caption_color)); s->FillRectangle(s, t->left_size, t->top_size, windata->client.w, t->caption_size); /* Close Button */ w = t->caption_size; x = windata->size.w - t->right_size - w + d; y = t->top_size + d; s->SetColor(s, COLOR_EXPAND(t->close_color)); DrawTriangle(s, 1, x, y, w - 2 * d); /* Max Button */ s->SetColor(s, COLOR_EXPAND(t->max_color)); DrawTriangle(s, window->flags & SDL_WINDOW_MAXIMIZED ? 1 : 0, x - w, y, w - 2 * d); /* Caption */ if (*window->title) { s->SetColor(s, COLOR_EXPAND(t->font_color)); DrawCraption(_this, s, (x - w) / 2, t->top_size + d, window->title); } /* Icon */ if (windata->icon) { DFBRectangle dr; dr.x = t->left_size + d; dr.y = t->top_size + d; dr.w = w - 2 * d; dr.h = w - 2 * d; s->SetBlittingFlags(s, DSBLIT_BLEND_ALPHACHANNEL); s->StretchBlit(s, windata->icon, NULL, &dr); } windata->wm_needs_redraw = 0; } DFBResult DirectFB_WM_GetClientSize(_THIS, SDL_Window * window, int *cw, int *ch) { SDL_DFB_WINDOWDATA(window); IDirectFBWindow *dfbwin = windata->dfbwin; SDL_DFB_CHECK(dfbwin->GetSize(dfbwin, cw, ch)); dfbwin->GetSize(dfbwin, cw, ch); *cw -= windata->theme.left_size + windata->theme.right_size; *ch -= windata->theme.top_size + windata->theme.caption_size + windata->theme.bottom_size; return DFB_OK; } void DirectFB_WM_AdjustWindowLayout(SDL_Window * window, int flags, int w, int h) { SDL_DFB_WINDOWDATA(window); if (!windata->is_managed) windata->theme = theme_none; else if (flags & SDL_WINDOW_BORDERLESS) /* desc.caps |= DWCAPS_NODECORATION;) */ windata->theme = theme_none; else if (flags & SDL_WINDOW_FULLSCREEN) { windata->theme = theme_none; } else if (flags & SDL_WINDOW_MAXIMIZED) { windata->theme = theme_std; windata->theme.left_size = 0; windata->theme.right_size = 0; windata->theme.top_size = 0; windata->theme.bottom_size = 0; } else { windata->theme = theme_std; } windata->client.x = windata->theme.left_size; windata->client.y = windata->theme.top_size + windata->theme.caption_size; windata->client.w = w; windata->client.h = h; windata->size.w = w + windata->theme.left_size + windata->theme.right_size; windata->size.h = h + windata->theme.top_size + windata->theme.caption_size + windata->theme.bottom_size; } enum { WM_POS_NONE = 0x00, WM_POS_CAPTION = 0x01, WM_POS_CLOSE = 0x02, WM_POS_MAX = 0x04, WM_POS_LEFT = 0x08, WM_POS_RIGHT = 0x10, WM_POS_TOP = 0x20, WM_POS_BOTTOM = 0x40, }; static int WMIsClient(DFB_WindowData * p, int x, int y) { x -= p->client.x; y -= p->client.y; if (x < 0 || y < 0) return 0; if (x >= p->client.w || y >= p->client.h) return 0; return 1; } static int WMPos(DFB_WindowData * p, int x, int y) { int pos = WM_POS_NONE; if (!WMIsClient(p, x, y)) { if (y < p->theme.top_size) { pos |= WM_POS_TOP; } else if (y < p->client.y) { if (x < p->size.w - p->theme.right_size - 2 * p->theme.caption_size) { pos |= WM_POS_CAPTION; } else if (x < p->size.w - p->theme.right_size - p->theme.caption_size) { pos |= WM_POS_MAX; } else { pos |= WM_POS_CLOSE; } } else if (y >= p->size.h - p->theme.bottom_size) { pos |= WM_POS_BOTTOM; } if (x < p->theme.left_size) { pos |= WM_POS_LEFT; } else if (x >= p->size.w - p->theme.right_size) { pos |= WM_POS_RIGHT; } } return pos; } int DirectFB_WM_ProcessEvent(_THIS, SDL_Window * window, DFBWindowEvent * evt) { SDL_DFB_DEVICEDATA(_this); SDL_DFB_WINDOWDATA(window); DFB_WindowData *gwindata = ((devdata->grabbed_window) ? (DFB_WindowData *) ((devdata->grabbed_window)->driverdata) : NULL); IDirectFBWindow *dfbwin = windata->dfbwin; DFBWindowOptions wopts; if (!windata->is_managed) return 0; SDL_DFB_CHECK(dfbwin->GetOptions(dfbwin, &wopts)); switch (evt->type) { case DWET_BUTTONDOWN: if (evt->buttons & DIBM_LEFT) { int pos = WMPos(windata, evt->x, evt->y); switch (pos) { case WM_POS_NONE: return 0; case WM_POS_CLOSE: windata->wm_grab = WM_POS_NONE; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_CLOSE, 0, 0); return 1; case WM_POS_MAX: windata->wm_grab = WM_POS_NONE; if (window->flags & SDL_WINDOW_MAXIMIZED) { SDL_RestoreWindow(window); } else { SDL_MaximizeWindow(window); } return 1; case WM_POS_CAPTION: if (!(wopts & DWOP_KEEP_STACKING)) { DirectFB_RaiseWindow(_this, window); } if (window->flags & SDL_WINDOW_MAXIMIZED) return 1; /* fall through */ default: windata->wm_grab = pos; if (gwindata != NULL) SDL_DFB_CHECK(gwindata->dfbwin->UngrabPointer(gwindata->dfbwin)); SDL_DFB_CHECK(dfbwin->GrabPointer(dfbwin)); windata->wm_lastx = evt->cx; windata->wm_lasty = evt->cy; } } return 1; case DWET_BUTTONUP: if (!windata->wm_grab) return 0; if (!(evt->buttons & DIBM_LEFT)) { if (windata->wm_grab & (WM_POS_RIGHT | WM_POS_BOTTOM)) { int dx = evt->cx - windata->wm_lastx; int dy = evt->cy - windata->wm_lasty; if (!(wopts & DWOP_KEEP_SIZE)) { int cw, ch; if ((windata->wm_grab & (WM_POS_BOTTOM | WM_POS_RIGHT)) == WM_POS_BOTTOM) dx = 0; else if ((windata->wm_grab & (WM_POS_BOTTOM | WM_POS_RIGHT)) == WM_POS_RIGHT) dy = 0; SDL_DFB_CHECK(dfbwin->GetSize(dfbwin, &cw, &ch)); /* necessary to trigger an event - ugly */ SDL_DFB_CHECK(dfbwin->DisableEvents(dfbwin, DWET_ALL)); SDL_DFB_CHECK(dfbwin->Resize(dfbwin, cw + dx + 1, ch + dy)); SDL_DFB_CHECK(dfbwin->EnableEvents(dfbwin, DWET_ALL)); SDL_DFB_CHECK(dfbwin->Resize(dfbwin, cw + dx, ch + dy)); } } SDL_DFB_CHECK(dfbwin->UngrabPointer(dfbwin)); if (gwindata != NULL) SDL_DFB_CHECK(gwindata->dfbwin->GrabPointer(gwindata->dfbwin)); windata->wm_grab = WM_POS_NONE; return 1; } break; case DWET_MOTION: if (!windata->wm_grab) return 0; if (evt->buttons & DIBM_LEFT) { int dx = evt->cx - windata->wm_lastx; int dy = evt->cy - windata->wm_lasty; if (windata->wm_grab & WM_POS_CAPTION) { if (!(wopts & DWOP_KEEP_POSITION)) SDL_DFB_CHECK(dfbwin->Move(dfbwin, dx, dy)); } if (windata->wm_grab & (WM_POS_RIGHT | WM_POS_BOTTOM)) { if (!(wopts & DWOP_KEEP_SIZE)) { int cw, ch; /* Make sure all events are disabled for this operation ! */ SDL_DFB_CHECK(dfbwin->DisableEvents(dfbwin, DWET_ALL)); if ((windata->wm_grab & (WM_POS_BOTTOM | WM_POS_RIGHT)) == WM_POS_BOTTOM) dx = 0; else if ((windata->wm_grab & (WM_POS_BOTTOM | WM_POS_RIGHT)) == WM_POS_RIGHT) dy = 0; SDL_DFB_CHECK(dfbwin->GetSize(dfbwin, &cw, &ch)); SDL_DFB_CHECK(dfbwin->Resize(dfbwin, cw + dx, ch + dy)); SDL_DFB_CHECK(dfbwin->EnableEvents(dfbwin, DWET_ALL)); } } windata->wm_lastx = evt->cx; windata->wm_lasty = evt->cy; return 1; } break; case DWET_KEYDOWN: break; case DWET_KEYUP: break; default: ; } return 0; } #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_WM.c
C
apache-2.0
12,840
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_directfb_wm_h_ #define SDL_directfb_wm_h_ #include "SDL_DirectFB_video.h" typedef struct _DFB_Theme DFB_Theme; struct _DFB_Theme { int left_size; int right_size; int top_size; int bottom_size; DFBColor frame_color; int caption_size; DFBColor caption_color; int font_size; DFBColor font_color; char *font; DFBColor close_color; DFBColor max_color; }; extern void DirectFB_WM_AdjustWindowLayout(SDL_Window * window, int flags, int w, int h); extern void DirectFB_WM_RedrawLayout(_THIS, SDL_Window * window); extern int DirectFB_WM_ProcessEvent(_THIS, SDL_Window * window, DFBWindowEvent * evt); extern DFBResult DirectFB_WM_GetClientSize(_THIS, SDL_Window * window, int *cw, int *ch); #endif /* SDL_directfb_wm_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_WM.h
C
apache-2.0
1,837
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_dyn.h" #ifdef SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC #include "SDL_name.h" #include "SDL_loadso.h" #define DFB_SYM(ret, name, args, al, func) ret (*name) args; static struct _SDL_DirectFB_Symbols { DFB_SYMS const unsigned int *directfb_major_version; const unsigned int *directfb_minor_version; const unsigned int *directfb_micro_version; } SDL_DirectFB_Symbols; #undef DFB_SYM #define DFB_SYM(ret, name, args, al, func) ret name args { func SDL_DirectFB_Symbols.name al ; } DFB_SYMS #undef DFB_SYM static void *handle = NULL; int SDL_DirectFB_LoadLibrary(void) { int retval = 0; if (handle == NULL) { handle = SDL_LoadObject(SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC); if (handle != NULL) { retval = 1; #define DFB_SYM(ret, name, args, al, func) if (!(SDL_DirectFB_Symbols.name = SDL_LoadFunction(handle, # name))) retval = 0; DFB_SYMS #undef DFB_SYM if (! (SDL_DirectFB_Symbols.directfb_major_version = SDL_LoadFunction(handle, "directfb_major_version"))) retval = 0; if (! (SDL_DirectFB_Symbols.directfb_minor_version = SDL_LoadFunction(handle, "directfb_minor_version"))) retval = 0; if (! (SDL_DirectFB_Symbols.directfb_micro_version = SDL_LoadFunction(handle, "directfb_micro_version"))) retval = 0; } } if (retval) { const char *stemp = DirectFBCheckVersion(DIRECTFB_MAJOR_VERSION, DIRECTFB_MINOR_VERSION, DIRECTFB_MICRO_VERSION); /* Version Check */ if (stemp != NULL) { fprintf(stderr, "DirectFB Lib: Version mismatch. Compiled: %d.%d.%d Library %d.%d.%d\n", DIRECTFB_MAJOR_VERSION, DIRECTFB_MINOR_VERSION, DIRECTFB_MICRO_VERSION, *SDL_DirectFB_Symbols.directfb_major_version, *SDL_DirectFB_Symbols.directfb_minor_version, *SDL_DirectFB_Symbols.directfb_micro_version); retval = 0; } } if (!retval) SDL_DirectFB_UnLoadLibrary(); return retval; } void SDL_DirectFB_UnLoadLibrary(void) { if (handle != NULL) { SDL_UnloadObject(handle); handle = NULL; } } #else int SDL_DirectFB_LoadLibrary(void) { return 1; } void SDL_DirectFB_UnLoadLibrary(void) { } #endif #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_dyn.c
C
apache-2.0
3,654
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_DirectFB_dyn_h_ #define SDL_DirectFB_dyn_h_ #define DFB_SYMS \ DFB_SYM(DFBResult, DirectFBError, (const char *msg, DFBResult result), (msg, result), return) \ DFB_SYM(DFBResult, DirectFBErrorFatal, (const char *msg, DFBResult result), (msg, result), return) \ DFB_SYM(const char *, DirectFBErrorString, (DFBResult result), (result), return) \ DFB_SYM(const char *, DirectFBUsageString, ( void ), (), return) \ DFB_SYM(DFBResult, DirectFBInit, (int *argc, char *(*argv[]) ), (argc, argv), return) \ DFB_SYM(DFBResult, DirectFBSetOption, (const char *name, const char *value), (name, value), return) \ DFB_SYM(DFBResult, DirectFBCreate, (IDirectFB **interface), (interface), return) \ DFB_SYM(const char *, DirectFBCheckVersion, (unsigned int required_major, unsigned int required_minor, unsigned int required_micro), \ (required_major, required_minor, required_micro), return) int SDL_DirectFB_LoadLibrary(void); void SDL_DirectFB_UnLoadLibrary(void); #endif /* SDL_DirectFB_dyn_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_dyn.h
C
apache-2.0
2,023
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB /* Handle the event stream, converting DirectFB input events into SDL events */ #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_window.h" #include "SDL_DirectFB_modes.h" #include "SDL_syswm.h" #include "../../events/SDL_mouse_c.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/SDL_windowevents_c.h" #include "../../events/SDL_events_c.h" #include "../../events/scancodes_linux.h" #include "../../events/scancodes_xfree86.h" #include "SDL_DirectFB_events.h" #if USE_MULTI_API #define SDL_SendMouseMotion_ex(w, id, relative, x, y, p) SDL_SendMouseMotion(w, id, relative, x, y, p) #define SDL_SendMouseButton_ex(w, id, state, button) SDL_SendMouseButton(w, id, state, button) #define SDL_SendKeyboardKey_ex(id, state, scancode) SDL_SendKeyboardKey(id, state, scancode) #define SDL_SendKeyboardText_ex(id, text) SDL_SendKeyboardText(id, text) #else #define SDL_SendMouseMotion_ex(w, id, relative, x, y, p) SDL_SendMouseMotion(w, id, relative, x, y) #define SDL_SendMouseButton_ex(w, id, state, button) SDL_SendMouseButton(w, id, state, button) #define SDL_SendKeyboardKey_ex(id, state, scancode) SDL_SendKeyboardKey(state, scancode) #define SDL_SendKeyboardText_ex(id, text) SDL_SendKeyboardText(text) #endif typedef struct _cb_data cb_data; struct _cb_data { DFB_DeviceData *devdata; int sys_ids; int sys_kbd; }; /* The translation tables from a DirectFB keycode to a SDL keysym */ static SDL_Scancode oskeymap[256]; static SDL_Keysym *DirectFB_TranslateKey(_THIS, DFBWindowEvent * evt, SDL_Keysym * keysym, Uint32 *unicode); static SDL_Keysym *DirectFB_TranslateKeyInputEvent(_THIS, DFBInputEvent * evt, SDL_Keysym * keysym, Uint32 *unicode); static void DirectFB_InitOSKeymap(_THIS, SDL_Scancode * keypmap, int numkeys); static int DirectFB_TranslateButton(DFBInputDeviceButtonIdentifier button); static void UnicodeToUtf8( Uint16 w , char *utf8buf) { unsigned char *utf8s = (unsigned char *) utf8buf; if ( w < 0x0080 ) { utf8s[0] = ( unsigned char ) w; utf8s[1] = 0; } else if ( w < 0x0800 ) { utf8s[0] = 0xc0 | (( w ) >> 6 ); utf8s[1] = 0x80 | (( w ) & 0x3f ); utf8s[2] = 0; } else { utf8s[0] = 0xe0 | (( w ) >> 12 ); utf8s[1] = 0x80 | (( ( w ) >> 6 ) & 0x3f ); utf8s[2] = 0x80 | (( w ) & 0x3f ); utf8s[3] = 0; } } static void FocusAllMice(_THIS, SDL_Window *window) { #if USE_MULTI_API SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_mice; index++) SDL_SetMouseFocus(devdata->mouse_id[index], id); #else SDL_SetMouseFocus(window); #endif } static void FocusAllKeyboards(_THIS, SDL_Window *window) { #if USE_MULTI_API SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_keyboard; index++) SDL_SetKeyboardFocus(index, id); #else SDL_SetKeyboardFocus(window); #endif } static void MotionAllMice(_THIS, int x, int y) { #if USE_MULTI_API SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_mice; index++) { SDL_Mouse *mouse = SDL_GetMouse(index); mouse->x = mouse->last_x = x; mouse->y = mouse->last_y = y; /* SDL_SendMouseMotion(devdata->mouse_id[index], 0, x, y, 0); */ } #endif } static int KbdIndex(_THIS, int id) { SDL_DFB_DEVICEDATA(_this); int index; for (index = 0; index < devdata->num_keyboard; index++) { if (devdata->keyboard[index].id == id) return index; } return -1; } static int ClientXY(DFB_WindowData * p, int *x, int *y) { int cx, cy; cx = *x; cy = *y; cx -= p->client.x; cy -= p->client.y; if (cx < 0 || cy < 0) return 0; if (cx >= p->client.w || cy >= p->client.h) return 0; *x = cx; *y = cy; return 1; } static void ProcessWindowEvent(_THIS, SDL_Window *sdlwin, DFBWindowEvent * evt) { SDL_DFB_DEVICEDATA(_this); SDL_DFB_WINDOWDATA(sdlwin); SDL_Keysym keysym; Uint32 unicode; char text[SDL_TEXTINPUTEVENT_TEXT_SIZE]; if (evt->clazz == DFEC_WINDOW) { switch (evt->type) { case DWET_BUTTONDOWN: if (ClientXY(windata, &evt->x, &evt->y)) { if (!devdata->use_linux_input) { SDL_SendMouseMotion_ex(sdlwin, devdata->mouse_id[0], 0, evt->x, evt->y, 0); SDL_SendMouseButton_ex(sdlwin, devdata->mouse_id[0], SDL_PRESSED, DirectFB_TranslateButton (evt->button)); } else { MotionAllMice(_this, evt->x, evt->y); } } break; case DWET_BUTTONUP: if (ClientXY(windata, &evt->x, &evt->y)) { if (!devdata->use_linux_input) { SDL_SendMouseMotion_ex(sdlwin, devdata->mouse_id[0], 0, evt->x, evt->y, 0); SDL_SendMouseButton_ex(sdlwin, devdata->mouse_id[0], SDL_RELEASED, DirectFB_TranslateButton (evt->button)); } else { MotionAllMice(_this, evt->x, evt->y); } } break; case DWET_MOTION: if (ClientXY(windata, &evt->x, &evt->y)) { if (!devdata->use_linux_input) { if (!(sdlwin->flags & SDL_WINDOW_INPUT_GRABBED)) SDL_SendMouseMotion_ex(sdlwin, devdata->mouse_id[0], 0, evt->x, evt->y, 0); } else { /* relative movements are not exact! * This code should limit the number of events sent. * However it kills MAME axis recognition ... */ static int cnt = 0; if (1 && ++cnt > 20) { MotionAllMice(_this, evt->x, evt->y); cnt = 0; } } if (!(sdlwin->flags & SDL_WINDOW_MOUSE_FOCUS)) SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_ENTER, 0, 0); } break; case DWET_KEYDOWN: if (!devdata->use_linux_input) { DirectFB_TranslateKey(_this, evt, &keysym, &unicode); /* printf("Scancode %d %d %d\n", keysym.scancode, evt->key_code, evt->key_id); */ SDL_SendKeyboardKey_ex(0, SDL_PRESSED, keysym.scancode); if (SDL_EventState(SDL_TEXTINPUT, SDL_QUERY)) { SDL_zeroa(text); UnicodeToUtf8(unicode, text); if (*text) { SDL_SendKeyboardText_ex(0, text); } } } break; case DWET_KEYUP: if (!devdata->use_linux_input) { DirectFB_TranslateKey(_this, evt, &keysym, &unicode); SDL_SendKeyboardKey_ex(0, SDL_RELEASED, keysym.scancode); } break; case DWET_POSITION: if (ClientXY(windata, &evt->x, &evt->y)) { SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_MOVED, evt->x, evt->y); } break; case DWET_POSITION_SIZE: if (ClientXY(windata, &evt->x, &evt->y)) { SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_MOVED, evt->x, evt->y); } /* fall throught */ case DWET_SIZE: /* FIXME: what about < 0 */ evt->w -= (windata->theme.right_size + windata->theme.left_size); evt->h -= (windata->theme.top_size + windata->theme.bottom_size + windata->theme.caption_size); SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_RESIZED, evt->w, evt->h); break; case DWET_CLOSE: SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_CLOSE, 0, 0); break; case DWET_GOTFOCUS: DirectFB_SetContext(_this, sdlwin); FocusAllKeyboards(_this, sdlwin); SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0); break; case DWET_LOSTFOCUS: SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0); FocusAllKeyboards(_this, 0); break; case DWET_ENTER: /* SDL_DirectFB_ReshowCursor(_this, 0); */ FocusAllMice(_this, sdlwin); /* FIXME: when do we really enter ? */ if (ClientXY(windata, &evt->x, &evt->y)) MotionAllMice(_this, evt->x, evt->y); SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_ENTER, 0, 0); break; case DWET_LEAVE: SDL_SendWindowEvent(sdlwin, SDL_WINDOWEVENT_LEAVE, 0, 0); FocusAllMice(_this, 0); /* SDL_DirectFB_ReshowCursor(_this, 1); */ break; default: ; } } else printf("Event Clazz %d\n", evt->clazz); } static void ProcessInputEvent(_THIS, DFBInputEvent * ievt) { SDL_DFB_DEVICEDATA(_this); SDL_Keysym keysym; int kbd_idx; Uint32 unicode; char text[SDL_TEXTINPUTEVENT_TEXT_SIZE]; if (!devdata->use_linux_input) { if (ievt->type == DIET_AXISMOTION) { if ((devdata->grabbed_window != NULL) && (ievt->flags & DIEF_AXISREL)) { if (ievt->axis == DIAI_X) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, ievt->axisrel, 0, 0); else if (ievt->axis == DIAI_Y) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, 0, ievt->axisrel, 0); } } } else { static int last_x, last_y; switch (ievt->type) { case DIET_AXISMOTION: if (ievt->flags & DIEF_AXISABS) { if (ievt->axis == DIAI_X) last_x = ievt->axisabs; else if (ievt->axis == DIAI_Y) last_y = ievt->axisabs; if (!(ievt->flags & DIEF_FOLLOW)) { #if USE_MULTI_API SDL_Mouse *mouse = SDL_GetMouse(ievt->device_id); SDL_Window *window = SDL_GetWindowFromID(mouse->focus); #else SDL_Window *window = devdata->grabbed_window; #endif if (window) { DFB_WindowData *windata = (DFB_WindowData *) window->driverdata; int x, y; windata->dfbwin->GetPosition(windata->dfbwin, &x, &y); SDL_SendMouseMotion_ex(window, ievt->device_id, 0, last_x - (x + windata->client.x), last_y - (y + windata->client.y), 0); } else { SDL_SendMouseMotion_ex(window, ievt->device_id, 0, last_x, last_y, 0); } } } else if (ievt->flags & DIEF_AXISREL) { if (ievt->axis == DIAI_X) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, ievt->axisrel, 0, 0); else if (ievt->axis == DIAI_Y) SDL_SendMouseMotion_ex(devdata->grabbed_window, ievt->device_id, 1, 0, ievt->axisrel, 0); } break; case DIET_KEYPRESS: kbd_idx = KbdIndex(_this, ievt->device_id); DirectFB_TranslateKeyInputEvent(_this, ievt, &keysym, &unicode); /* printf("Scancode %d %d %d\n", keysym.scancode, evt->key_code, evt->key_id); */ SDL_SendKeyboardKey_ex(kbd_idx, SDL_PRESSED, keysym.scancode); if (SDL_EventState(SDL_TEXTINPUT, SDL_QUERY)) { SDL_zeroa(text); UnicodeToUtf8(unicode, text); if (*text) { SDL_SendKeyboardText_ex(kbd_idx, text); } } break; case DIET_KEYRELEASE: kbd_idx = KbdIndex(_this, ievt->device_id); DirectFB_TranslateKeyInputEvent(_this, ievt, &keysym, &unicode); SDL_SendKeyboardKey_ex(kbd_idx, SDL_RELEASED, keysym.scancode); break; case DIET_BUTTONPRESS: if (ievt->buttons & DIBM_LEFT) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_PRESSED, 1); if (ievt->buttons & DIBM_MIDDLE) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_PRESSED, 2); if (ievt->buttons & DIBM_RIGHT) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_PRESSED, 3); break; case DIET_BUTTONRELEASE: if (!(ievt->buttons & DIBM_LEFT)) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_RELEASED, 1); if (!(ievt->buttons & DIBM_MIDDLE)) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_RELEASED, 2); if (!(ievt->buttons & DIBM_RIGHT)) SDL_SendMouseButton_ex(devdata->grabbed_window, ievt->device_id, SDL_RELEASED, 3); break; default: break; /* please gcc */ } } } void DirectFB_PumpEventsWindow(_THIS) { SDL_DFB_DEVICEDATA(_this); DFBInputEvent ievt; SDL_Window *w; for (w = devdata->firstwin; w != NULL; w = w->next) { SDL_DFB_WINDOWDATA(w); DFBWindowEvent evt; while (windata->eventbuffer->GetEvent(windata->eventbuffer, DFB_EVENT(&evt)) == DFB_OK) { if (!DirectFB_WM_ProcessEvent(_this, w, &evt)) { /* Send a SDL_SYSWMEVENT if the application wants them */ if (SDL_GetEventState(SDL_SYSWMEVENT) == SDL_ENABLE) { SDL_SysWMmsg wmmsg; SDL_VERSION(&wmmsg.version); wmmsg.subsystem = SDL_SYSWM_DIRECTFB; wmmsg.msg.dfb.event.window = evt; SDL_SendSysWMEvent(&wmmsg); } ProcessWindowEvent(_this, w, &evt); } } } /* Now get relative events in case we need them */ while (devdata->events->GetEvent(devdata->events, DFB_EVENT(&ievt)) == DFB_OK) { if (SDL_GetEventState(SDL_SYSWMEVENT) == SDL_ENABLE) { SDL_SysWMmsg wmmsg; SDL_VERSION(&wmmsg.version); wmmsg.subsystem = SDL_SYSWM_DIRECTFB; wmmsg.msg.dfb.event.input = ievt; SDL_SendSysWMEvent(&wmmsg); } ProcessInputEvent(_this, &ievt); } } void DirectFB_InitOSKeymap(_THIS, SDL_Scancode * keymap, int numkeys) { int i; /* Initialize the DirectFB key translation table */ for (i = 0; i < numkeys; ++i) keymap[i] = SDL_SCANCODE_UNKNOWN; keymap[DIKI_A - DIKI_UNKNOWN] = SDL_SCANCODE_A; keymap[DIKI_B - DIKI_UNKNOWN] = SDL_SCANCODE_B; keymap[DIKI_C - DIKI_UNKNOWN] = SDL_SCANCODE_C; keymap[DIKI_D - DIKI_UNKNOWN] = SDL_SCANCODE_D; keymap[DIKI_E - DIKI_UNKNOWN] = SDL_SCANCODE_E; keymap[DIKI_F - DIKI_UNKNOWN] = SDL_SCANCODE_F; keymap[DIKI_G - DIKI_UNKNOWN] = SDL_SCANCODE_G; keymap[DIKI_H - DIKI_UNKNOWN] = SDL_SCANCODE_H; keymap[DIKI_I - DIKI_UNKNOWN] = SDL_SCANCODE_I; keymap[DIKI_J - DIKI_UNKNOWN] = SDL_SCANCODE_J; keymap[DIKI_K - DIKI_UNKNOWN] = SDL_SCANCODE_K; keymap[DIKI_L - DIKI_UNKNOWN] = SDL_SCANCODE_L; keymap[DIKI_M - DIKI_UNKNOWN] = SDL_SCANCODE_M; keymap[DIKI_N - DIKI_UNKNOWN] = SDL_SCANCODE_N; keymap[DIKI_O - DIKI_UNKNOWN] = SDL_SCANCODE_O; keymap[DIKI_P - DIKI_UNKNOWN] = SDL_SCANCODE_P; keymap[DIKI_Q - DIKI_UNKNOWN] = SDL_SCANCODE_Q; keymap[DIKI_R - DIKI_UNKNOWN] = SDL_SCANCODE_R; keymap[DIKI_S - DIKI_UNKNOWN] = SDL_SCANCODE_S; keymap[DIKI_T - DIKI_UNKNOWN] = SDL_SCANCODE_T; keymap[DIKI_U - DIKI_UNKNOWN] = SDL_SCANCODE_U; keymap[DIKI_V - DIKI_UNKNOWN] = SDL_SCANCODE_V; keymap[DIKI_W - DIKI_UNKNOWN] = SDL_SCANCODE_W; keymap[DIKI_X - DIKI_UNKNOWN] = SDL_SCANCODE_X; keymap[DIKI_Y - DIKI_UNKNOWN] = SDL_SCANCODE_Y; keymap[DIKI_Z - DIKI_UNKNOWN] = SDL_SCANCODE_Z; keymap[DIKI_0 - DIKI_UNKNOWN] = SDL_SCANCODE_0; keymap[DIKI_1 - DIKI_UNKNOWN] = SDL_SCANCODE_1; keymap[DIKI_2 - DIKI_UNKNOWN] = SDL_SCANCODE_2; keymap[DIKI_3 - DIKI_UNKNOWN] = SDL_SCANCODE_3; keymap[DIKI_4 - DIKI_UNKNOWN] = SDL_SCANCODE_4; keymap[DIKI_5 - DIKI_UNKNOWN] = SDL_SCANCODE_5; keymap[DIKI_6 - DIKI_UNKNOWN] = SDL_SCANCODE_6; keymap[DIKI_7 - DIKI_UNKNOWN] = SDL_SCANCODE_7; keymap[DIKI_8 - DIKI_UNKNOWN] = SDL_SCANCODE_8; keymap[DIKI_9 - DIKI_UNKNOWN] = SDL_SCANCODE_9; keymap[DIKI_F1 - DIKI_UNKNOWN] = SDL_SCANCODE_F1; keymap[DIKI_F2 - DIKI_UNKNOWN] = SDL_SCANCODE_F2; keymap[DIKI_F3 - DIKI_UNKNOWN] = SDL_SCANCODE_F3; keymap[DIKI_F4 - DIKI_UNKNOWN] = SDL_SCANCODE_F4; keymap[DIKI_F5 - DIKI_UNKNOWN] = SDL_SCANCODE_F5; keymap[DIKI_F6 - DIKI_UNKNOWN] = SDL_SCANCODE_F6; keymap[DIKI_F7 - DIKI_UNKNOWN] = SDL_SCANCODE_F7; keymap[DIKI_F8 - DIKI_UNKNOWN] = SDL_SCANCODE_F8; keymap[DIKI_F9 - DIKI_UNKNOWN] = SDL_SCANCODE_F9; keymap[DIKI_F10 - DIKI_UNKNOWN] = SDL_SCANCODE_F10; keymap[DIKI_F11 - DIKI_UNKNOWN] = SDL_SCANCODE_F11; keymap[DIKI_F12 - DIKI_UNKNOWN] = SDL_SCANCODE_F12; keymap[DIKI_ESCAPE - DIKI_UNKNOWN] = SDL_SCANCODE_ESCAPE; keymap[DIKI_LEFT - DIKI_UNKNOWN] = SDL_SCANCODE_LEFT; keymap[DIKI_RIGHT - DIKI_UNKNOWN] = SDL_SCANCODE_RIGHT; keymap[DIKI_UP - DIKI_UNKNOWN] = SDL_SCANCODE_UP; keymap[DIKI_DOWN - DIKI_UNKNOWN] = SDL_SCANCODE_DOWN; keymap[DIKI_CONTROL_L - DIKI_UNKNOWN] = SDL_SCANCODE_LCTRL; keymap[DIKI_CONTROL_R - DIKI_UNKNOWN] = SDL_SCANCODE_RCTRL; keymap[DIKI_SHIFT_L - DIKI_UNKNOWN] = SDL_SCANCODE_LSHIFT; keymap[DIKI_SHIFT_R - DIKI_UNKNOWN] = SDL_SCANCODE_RSHIFT; keymap[DIKI_ALT_L - DIKI_UNKNOWN] = SDL_SCANCODE_LALT; keymap[DIKI_ALT_R - DIKI_UNKNOWN] = SDL_SCANCODE_RALT; keymap[DIKI_META_L - DIKI_UNKNOWN] = SDL_SCANCODE_LGUI; keymap[DIKI_META_R - DIKI_UNKNOWN] = SDL_SCANCODE_RGUI; keymap[DIKI_SUPER_L - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; keymap[DIKI_SUPER_R - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; /* FIXME:Do we read hyper keys ? * keymap[DIKI_HYPER_L - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; * keymap[DIKI_HYPER_R - DIKI_UNKNOWN] = SDL_SCANCODE_APPLICATION; */ keymap[DIKI_TAB - DIKI_UNKNOWN] = SDL_SCANCODE_TAB; keymap[DIKI_ENTER - DIKI_UNKNOWN] = SDL_SCANCODE_RETURN; keymap[DIKI_SPACE - DIKI_UNKNOWN] = SDL_SCANCODE_SPACE; keymap[DIKI_BACKSPACE - DIKI_UNKNOWN] = SDL_SCANCODE_BACKSPACE; keymap[DIKI_INSERT - DIKI_UNKNOWN] = SDL_SCANCODE_INSERT; keymap[DIKI_DELETE - DIKI_UNKNOWN] = SDL_SCANCODE_DELETE; keymap[DIKI_HOME - DIKI_UNKNOWN] = SDL_SCANCODE_HOME; keymap[DIKI_END - DIKI_UNKNOWN] = SDL_SCANCODE_END; keymap[DIKI_PAGE_UP - DIKI_UNKNOWN] = SDL_SCANCODE_PAGEUP; keymap[DIKI_PAGE_DOWN - DIKI_UNKNOWN] = SDL_SCANCODE_PAGEDOWN; keymap[DIKI_CAPS_LOCK - DIKI_UNKNOWN] = SDL_SCANCODE_CAPSLOCK; keymap[DIKI_NUM_LOCK - DIKI_UNKNOWN] = SDL_SCANCODE_NUMLOCKCLEAR; keymap[DIKI_SCROLL_LOCK - DIKI_UNKNOWN] = SDL_SCANCODE_SCROLLLOCK; keymap[DIKI_PRINT - DIKI_UNKNOWN] = SDL_SCANCODE_PRINTSCREEN; keymap[DIKI_PAUSE - DIKI_UNKNOWN] = SDL_SCANCODE_PAUSE; keymap[DIKI_KP_EQUAL - DIKI_UNKNOWN] = SDL_SCANCODE_KP_EQUALS; keymap[DIKI_KP_DECIMAL - DIKI_UNKNOWN] = SDL_SCANCODE_KP_PERIOD; keymap[DIKI_KP_0 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_0; keymap[DIKI_KP_1 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_1; keymap[DIKI_KP_2 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_2; keymap[DIKI_KP_3 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_3; keymap[DIKI_KP_4 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_4; keymap[DIKI_KP_5 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_5; keymap[DIKI_KP_6 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_6; keymap[DIKI_KP_7 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_7; keymap[DIKI_KP_8 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_8; keymap[DIKI_KP_9 - DIKI_UNKNOWN] = SDL_SCANCODE_KP_9; keymap[DIKI_KP_DIV - DIKI_UNKNOWN] = SDL_SCANCODE_KP_DIVIDE; keymap[DIKI_KP_MULT - DIKI_UNKNOWN] = SDL_SCANCODE_KP_MULTIPLY; keymap[DIKI_KP_MINUS - DIKI_UNKNOWN] = SDL_SCANCODE_KP_MINUS; keymap[DIKI_KP_PLUS - DIKI_UNKNOWN] = SDL_SCANCODE_KP_PLUS; keymap[DIKI_KP_ENTER - DIKI_UNKNOWN] = SDL_SCANCODE_KP_ENTER; keymap[DIKI_QUOTE_LEFT - DIKI_UNKNOWN] = SDL_SCANCODE_GRAVE; /* TLDE */ keymap[DIKI_MINUS_SIGN - DIKI_UNKNOWN] = SDL_SCANCODE_MINUS; /* AE11 */ keymap[DIKI_EQUALS_SIGN - DIKI_UNKNOWN] = SDL_SCANCODE_EQUALS; /* AE12 */ keymap[DIKI_BRACKET_LEFT - DIKI_UNKNOWN] = SDL_SCANCODE_RIGHTBRACKET; /* AD11 */ keymap[DIKI_BRACKET_RIGHT - DIKI_UNKNOWN] = SDL_SCANCODE_LEFTBRACKET; /* AD12 */ keymap[DIKI_BACKSLASH - DIKI_UNKNOWN] = SDL_SCANCODE_BACKSLASH; /* BKSL */ keymap[DIKI_SEMICOLON - DIKI_UNKNOWN] = SDL_SCANCODE_SEMICOLON; /* AC10 */ keymap[DIKI_QUOTE_RIGHT - DIKI_UNKNOWN] = SDL_SCANCODE_APOSTROPHE; /* AC11 */ keymap[DIKI_COMMA - DIKI_UNKNOWN] = SDL_SCANCODE_COMMA; /* AB08 */ keymap[DIKI_PERIOD - DIKI_UNKNOWN] = SDL_SCANCODE_PERIOD; /* AB09 */ keymap[DIKI_SLASH - DIKI_UNKNOWN] = SDL_SCANCODE_SLASH; /* AB10 */ keymap[DIKI_LESS_SIGN - DIKI_UNKNOWN] = SDL_SCANCODE_NONUSBACKSLASH; /* 103rd */ } static SDL_Keysym * DirectFB_TranslateKey(_THIS, DFBWindowEvent * evt, SDL_Keysym * keysym, Uint32 *unicode) { SDL_DFB_DEVICEDATA(_this); int kbd_idx = 0; /* Window events lag the device source KbdIndex(_this, evt->device_id); */ DFB_KeyboardData *kbd = &devdata->keyboard[kbd_idx]; keysym->scancode = SDL_SCANCODE_UNKNOWN; if (kbd->map && evt->key_code >= kbd->map_adjust && evt->key_code < kbd->map_size + kbd->map_adjust) keysym->scancode = kbd->map[evt->key_code - kbd->map_adjust]; if (keysym->scancode == SDL_SCANCODE_UNKNOWN || devdata->keyboard[kbd_idx].is_generic) { if (evt->key_id - DIKI_UNKNOWN < SDL_arraysize(oskeymap)) keysym->scancode = oskeymap[evt->key_id - DIKI_UNKNOWN]; else keysym->scancode = SDL_SCANCODE_UNKNOWN; } *unicode = (DFB_KEY_TYPE(evt->key_symbol) == DIKT_UNICODE) ? evt->key_symbol : 0; if (*unicode == 0 && (evt->key_symbol > 0 && evt->key_symbol < 255)) *unicode = evt->key_symbol; return keysym; } static SDL_Keysym * DirectFB_TranslateKeyInputEvent(_THIS, DFBInputEvent * evt, SDL_Keysym * keysym, Uint32 *unicode) { SDL_DFB_DEVICEDATA(_this); int kbd_idx = KbdIndex(_this, evt->device_id); DFB_KeyboardData *kbd = &devdata->keyboard[kbd_idx]; keysym->scancode = SDL_SCANCODE_UNKNOWN; if (kbd->map && evt->key_code >= kbd->map_adjust && evt->key_code < kbd->map_size + kbd->map_adjust) keysym->scancode = kbd->map[evt->key_code - kbd->map_adjust]; if (keysym->scancode == SDL_SCANCODE_UNKNOWN || devdata->keyboard[kbd_idx].is_generic) { if (evt->key_id - DIKI_UNKNOWN < SDL_arraysize(oskeymap)) keysym->scancode = oskeymap[evt->key_id - DIKI_UNKNOWN]; else keysym->scancode = SDL_SCANCODE_UNKNOWN; } *unicode = (DFB_KEY_TYPE(evt->key_symbol) == DIKT_UNICODE) ? evt->key_symbol : 0; if (*unicode == 0 && (evt->key_symbol > 0 && evt->key_symbol < 255)) *unicode = evt->key_symbol; return keysym; } static int DirectFB_TranslateButton(DFBInputDeviceButtonIdentifier button) { switch (button) { case DIBI_LEFT: return 1; case DIBI_MIDDLE: return 2; case DIBI_RIGHT: return 3; default: return 0; } } static DFBEnumerationResult EnumKeyboards(DFBInputDeviceID device_id, DFBInputDeviceDescription desc, void *callbackdata) { cb_data *cb = callbackdata; DFB_DeviceData *devdata = cb->devdata; #if USE_MULTI_API SDL_Keyboard keyboard; #endif SDL_Keycode keymap[SDL_NUM_SCANCODES]; if (!cb->sys_kbd) { if (cb->sys_ids) { if (device_id >= 0x10) return DFENUM_OK; } else { if (device_id < 0x10) return DFENUM_OK; } } else { if (device_id != DIDID_KEYBOARD) return DFENUM_OK; } if ((desc.caps & DIDTF_KEYBOARD)) { #if USE_MULTI_API SDL_zero(keyboard); SDL_AddKeyboard(&keyboard, devdata->num_keyboard); #endif devdata->keyboard[devdata->num_keyboard].id = device_id; devdata->keyboard[devdata->num_keyboard].is_generic = 0; if (!strncmp("X11", desc.name, 3)) { devdata->keyboard[devdata->num_keyboard].map = xfree86_scancode_table2; devdata->keyboard[devdata->num_keyboard].map_size = SDL_arraysize(xfree86_scancode_table2); devdata->keyboard[devdata->num_keyboard].map_adjust = 8; } else { devdata->keyboard[devdata->num_keyboard].map = linux_scancode_table; devdata->keyboard[devdata->num_keyboard].map_size = SDL_arraysize(linux_scancode_table); devdata->keyboard[devdata->num_keyboard].map_adjust = 0; } SDL_DFB_LOG("Keyboard %d - %s\n", device_id, desc.name); SDL_GetDefaultKeymap(keymap); #if USE_MULTI_API SDL_SetKeymap(devdata->num_keyboard, 0, keymap, SDL_NUM_SCANCODES); #else SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES); #endif devdata->num_keyboard++; if (cb->sys_kbd) return DFENUM_CANCEL; } return DFENUM_OK; } void DirectFB_InitKeyboard(_THIS) { SDL_DFB_DEVICEDATA(_this); cb_data cb; DirectFB_InitOSKeymap(_this, &oskeymap[0], SDL_arraysize(oskeymap)); devdata->num_keyboard = 0; cb.devdata = devdata; if (devdata->use_linux_input) { cb.sys_kbd = 0; cb.sys_ids = 0; SDL_DFB_CHECK(devdata->dfb-> EnumInputDevices(devdata->dfb, EnumKeyboards, &cb)); if (devdata->num_keyboard == 0) { cb.sys_ids = 1; SDL_DFB_CHECK(devdata->dfb->EnumInputDevices(devdata->dfb, EnumKeyboards, &cb)); } } else { cb.sys_kbd = 1; SDL_DFB_CHECK(devdata->dfb->EnumInputDevices(devdata->dfb, EnumKeyboards, &cb)); } } void DirectFB_QuitKeyboard(_THIS) { /* SDL_DFB_DEVICEDATA(_this); */ } #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_events.c
C
apache-2.0
28,773
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_DirectFB_events_h_ #define SDL_DirectFB_events_h_ #include "../SDL_sysvideo.h" /* Functions to be exported */ extern void DirectFB_InitKeyboard(_THIS); extern void DirectFB_QuitKeyboard(_THIS); extern void DirectFB_PumpEventsWindow(_THIS); #endif /* SDL_DirectFB_events_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_events.h
C
apache-2.0
1,267
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_modes.h" #define DFB_MAX_MODES 200 struct screen_callback_t { int numscreens; DFBScreenID screenid[DFB_MAX_SCREENS]; DFBDisplayLayerID gralayer[DFB_MAX_SCREENS]; DFBDisplayLayerID vidlayer[DFB_MAX_SCREENS]; int aux; /* auxiliary integer for callbacks */ }; struct modes_callback_t { int nummodes; SDL_DisplayMode *modelist; }; static DFBEnumerationResult EnumModesCallback(int width, int height, int bpp, void *data) { struct modes_callback_t *modedata = (struct modes_callback_t *) data; SDL_DisplayMode mode; mode.w = width; mode.h = height; mode.refresh_rate = 0; mode.driverdata = NULL; mode.format = SDL_PIXELFORMAT_UNKNOWN; if (modedata->nummodes < DFB_MAX_MODES) { modedata->modelist[modedata->nummodes++] = mode; } return DFENUM_OK; } static DFBEnumerationResult EnumScreensCallback(DFBScreenID screen_id, DFBScreenDescription desc, void *callbackdata) { struct screen_callback_t *devdata = (struct screen_callback_t *) callbackdata; devdata->screenid[devdata->numscreens++] = screen_id; return DFENUM_OK; } static DFBEnumerationResult EnumLayersCallback(DFBDisplayLayerID layer_id, DFBDisplayLayerDescription desc, void *callbackdata) { struct screen_callback_t *devdata = (struct screen_callback_t *) callbackdata; if (desc.caps & DLCAPS_SURFACE) { if ((desc.type & DLTF_GRAPHICS) && (desc.type & DLTF_VIDEO)) { if (devdata->vidlayer[devdata->aux] == -1) devdata->vidlayer[devdata->aux] = layer_id; } else if (desc.type & DLTF_GRAPHICS) { if (devdata->gralayer[devdata->aux] == -1) devdata->gralayer[devdata->aux] = layer_id; } } return DFENUM_OK; } static void CheckSetDisplayMode(_THIS, SDL_VideoDisplay * display, DFB_DisplayData * data, SDL_DisplayMode * mode) { SDL_DFB_DEVICEDATA(_this); DFBDisplayLayerConfig config; DFBDisplayLayerConfigFlags failed; SDL_DFB_CHECKERR(data->layer->SetCooperativeLevel(data->layer, DLSCL_ADMINISTRATIVE)); config.width = mode->w; config.height = mode->h; config.pixelformat = DirectFB_SDLToDFBPixelFormat(mode->format); config.flags = DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT; if (devdata->use_yuv_underlays) { config.flags |= DLCONF_OPTIONS; config.options = DLOP_ALPHACHANNEL; } failed = 0; data->layer->TestConfiguration(data->layer, &config, &failed); SDL_DFB_CHECKERR(data->layer->SetCooperativeLevel(data->layer, DLSCL_SHARED)); if (failed == 0) { SDL_AddDisplayMode(display, mode); SDL_DFB_LOG("Mode %d x %d Added\n", mode->w, mode->h); } else SDL_DFB_ERR("Mode %d x %d not available: %x\n", mode->w, mode->h, failed); return; error: return; } void DirectFB_SetContext(_THIS, SDL_Window *window) { #if (DFB_VERSION_ATLEAST(1,0,0)) /* FIXME: does not work on 1.0/1.2 with radeon driver * the approach did work with the matrox driver * This has simply no effect. */ SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; /* FIXME: should we handle the error */ if (dispdata->vidIDinuse) SDL_DFB_CHECK(dispdata->vidlayer->SwitchContext(dispdata->vidlayer, DFB_TRUE)); #endif } void DirectFB_InitModes(_THIS) { SDL_DFB_DEVICEDATA(_this); IDirectFBDisplayLayer *layer = NULL; SDL_VideoDisplay display; DFB_DisplayData *dispdata = NULL; SDL_DisplayMode mode; DFBGraphicsDeviceDescription caps; DFBDisplayLayerConfig dlc; struct screen_callback_t *screencbdata; int tcw[DFB_MAX_SCREENS]; int tch[DFB_MAX_SCREENS]; int i; DFBResult ret; SDL_DFB_ALLOC_CLEAR(screencbdata, sizeof(*screencbdata)); screencbdata->numscreens = 0; for (i = 0; i < DFB_MAX_SCREENS; i++) { screencbdata->gralayer[i] = -1; screencbdata->vidlayer[i] = -1; } SDL_DFB_CHECKERR(devdata->dfb->EnumScreens(devdata->dfb, &EnumScreensCallback, screencbdata)); for (i = 0; i < screencbdata->numscreens; i++) { IDirectFBScreen *screen; SDL_DFB_CHECKERR(devdata->dfb->GetScreen(devdata->dfb, screencbdata->screenid [i], &screen)); screencbdata->aux = i; SDL_DFB_CHECKERR(screen->EnumDisplayLayers(screen, &EnumLayersCallback, screencbdata)); screen->GetSize(screen, &tcw[i], &tch[i]); screen->Release(screen); } /* Query card capabilities */ devdata->dfb->GetDeviceDescription(devdata->dfb, &caps); for (i = 0; i < screencbdata->numscreens; i++) { SDL_DFB_CHECKERR(devdata->dfb->GetDisplayLayer(devdata->dfb, screencbdata->gralayer [i], &layer)); SDL_DFB_CHECKERR(layer->SetCooperativeLevel(layer, DLSCL_ADMINISTRATIVE)); layer->EnableCursor(layer, 1); SDL_DFB_CHECKERR(layer->SetCursorOpacity(layer, 0xC0)); if (devdata->use_yuv_underlays) { dlc.flags = DLCONF_PIXELFORMAT | DLCONF_OPTIONS; dlc.pixelformat = DSPF_ARGB; dlc.options = DLOP_ALPHACHANNEL; ret = layer->SetConfiguration(layer, &dlc); if (ret != DFB_OK) { /* try AiRGB if the previous failed */ dlc.pixelformat = DSPF_AiRGB; SDL_DFB_CHECKERR(layer->SetConfiguration(layer, &dlc)); } } /* Query layer configuration to determine the current mode and pixelformat */ dlc.flags = DLCONF_ALL; SDL_DFB_CHECKERR(layer->GetConfiguration(layer, &dlc)); mode.format = DirectFB_DFBToSDLPixelFormat(dlc.pixelformat); if (mode.format == SDL_PIXELFORMAT_UNKNOWN) { SDL_DFB_ERR("Unknown dfb pixelformat %x !\n", dlc.pixelformat); goto error; } mode.w = dlc.width; mode.h = dlc.height; mode.refresh_rate = 0; mode.driverdata = NULL; SDL_DFB_ALLOC_CLEAR(dispdata, sizeof(*dispdata)); dispdata->layer = layer; dispdata->pixelformat = dlc.pixelformat; dispdata->cw = tcw[i]; dispdata->ch = tch[i]; /* YUV - Video layer */ dispdata->vidID = screencbdata->vidlayer[i]; dispdata->vidIDinuse = 0; SDL_zero(display); display.desktop_mode = mode; display.current_mode = mode; display.driverdata = dispdata; #if (DFB_VERSION_ATLEAST(1,2,0)) dlc.flags = DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT | DLCONF_OPTIONS; ret = layer->SetConfiguration(layer, &dlc); #endif SDL_DFB_CHECKERR(layer->SetCooperativeLevel(layer, DLSCL_SHARED)); SDL_AddVideoDisplay(&display); } SDL_DFB_FREE(screencbdata); return; error: /* FIXME: Cleanup not complete, Free existing displays */ SDL_DFB_FREE(dispdata); SDL_DFB_RELEASE(layer); return; } void DirectFB_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { SDL_DFB_DEVICEDATA(_this); DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; SDL_DisplayMode mode; struct modes_callback_t data; int i; data.nummodes = 0; /* Enumerate the available fullscreen modes */ SDL_DFB_CALLOC(data.modelist, DFB_MAX_MODES, sizeof(SDL_DisplayMode)); SDL_DFB_CHECKERR(devdata->dfb->EnumVideoModes(devdata->dfb, EnumModesCallback, &data)); for (i = 0; i < data.nummodes; ++i) { mode = data.modelist[i]; mode.format = SDL_PIXELFORMAT_ARGB8888; CheckSetDisplayMode(_this, display, dispdata, &mode); mode.format = SDL_PIXELFORMAT_RGB888; CheckSetDisplayMode(_this, display, dispdata, &mode); mode.format = SDL_PIXELFORMAT_RGB24; CheckSetDisplayMode(_this, display, dispdata, &mode); mode.format = SDL_PIXELFORMAT_RGB565; CheckSetDisplayMode(_this, display, dispdata, &mode); mode.format = SDL_PIXELFORMAT_INDEX8; CheckSetDisplayMode(_this, display, dispdata, &mode); } SDL_DFB_FREE(data.modelist); error: return; } int DirectFB_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { /* * FIXME: video mode switch is currently broken for 1.2.0 * */ SDL_DFB_DEVICEDATA(_this); DFB_DisplayData *data = (DFB_DisplayData *) display->driverdata; DFBDisplayLayerConfig config, rconfig; DFBDisplayLayerConfigFlags fail = 0; SDL_DFB_CHECKERR(data->layer->SetCooperativeLevel(data->layer, DLSCL_ADMINISTRATIVE)); SDL_DFB_CHECKERR(data->layer->GetConfiguration(data->layer, &config)); config.flags = DLCONF_WIDTH | DLCONF_HEIGHT; if (mode->format != SDL_PIXELFORMAT_UNKNOWN) { config.flags |= DLCONF_PIXELFORMAT; config.pixelformat = DirectFB_SDLToDFBPixelFormat(mode->format); data->pixelformat = config.pixelformat; } config.width = mode->w; config.height = mode->h; if (devdata->use_yuv_underlays) { config.flags |= DLCONF_OPTIONS; config.options = DLOP_ALPHACHANNEL; } data->layer->TestConfiguration(data->layer, &config, &fail); if (fail & (DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT | DLCONF_OPTIONS)) { SDL_DFB_ERR("Error setting mode %dx%d-%x\n", mode->w, mode->h, mode->format); return -1; } config.flags &= ~fail; SDL_DFB_CHECKERR(data->layer->SetConfiguration(data->layer, &config)); #if (DFB_VERSION_ATLEAST(1,2,0)) /* Need to call this twice ! */ SDL_DFB_CHECKERR(data->layer->SetConfiguration(data->layer, &config)); #endif /* Double check */ SDL_DFB_CHECKERR(data->layer->GetConfiguration(data->layer, &rconfig)); SDL_DFB_CHECKERR(data-> layer->SetCooperativeLevel(data->layer, DLSCL_SHARED)); if ((config.width != rconfig.width) || (config.height != rconfig.height) || ((mode->format != SDL_PIXELFORMAT_UNKNOWN) && (config.pixelformat != rconfig.pixelformat))) { SDL_DFB_ERR("Error setting mode %dx%d-%x\n", mode->w, mode->h, mode->format); return -1; } data->pixelformat = rconfig.pixelformat; data->cw = config.width; data->ch = config.height; display->current_mode = *mode; return 0; error: return -1; } void DirectFB_QuitModes(_THIS) { SDL_DisplayMode tmode; int i; for (i = 0; i < _this->num_displays; ++i) { SDL_VideoDisplay *display = &_this->displays[i]; DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; SDL_GetDesktopDisplayMode(i, &tmode); tmode.format = SDL_PIXELFORMAT_UNKNOWN; DirectFB_SetDisplayMode(_this, display, &tmode); SDL_GetDesktopDisplayMode(i, &tmode); DirectFB_SetDisplayMode(_this, display, &tmode); if (dispdata->layer) { SDL_DFB_CHECK(dispdata-> layer->SetCooperativeLevel(dispdata->layer, DLSCL_ADMINISTRATIVE)); SDL_DFB_CHECK(dispdata-> layer->SetCursorOpacity(dispdata->layer, 0x00)); SDL_DFB_CHECK(dispdata-> layer->SetCooperativeLevel(dispdata->layer, DLSCL_SHARED)); } SDL_DFB_RELEASE(dispdata->layer); SDL_DFB_RELEASE(dispdata->vidlayer); } } #endif /* SDL_VIDEO_DRIVER_DIRECTFB */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_modes.c
C
apache-2.0
13,336
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_directfb_modes_h_ #define SDL_directfb_modes_h_ #include <directfb.h> #include "../SDL_sysvideo.h" #define SDL_DFB_DISPLAYDATA(win) DFB_DisplayData *dispdata = ((win) ? (DFB_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata : NULL) typedef struct _DFB_DisplayData DFB_DisplayData; struct _DFB_DisplayData { IDirectFBDisplayLayer *layer; DFBSurfacePixelFormat pixelformat; /* FIXME: support for multiple video layer. * However, I do not know any card supporting * more than one */ DFBDisplayLayerID vidID; IDirectFBDisplayLayer *vidlayer; int vidIDinuse; int cw; int ch; }; extern void DirectFB_InitModes(_THIS); extern void DirectFB_GetDisplayModes(_THIS, SDL_VideoDisplay * display); extern int DirectFB_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); extern void DirectFB_QuitModes(_THIS); extern void DirectFB_SetContext(_THIS, SDL_Window *window); #endif /* SDL_directfb_modes_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_modes.h
C
apache-2.0
2,041
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_assert.h" #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_mouse.h" #include "SDL_DirectFB_modes.h" #include "SDL_DirectFB_window.h" #include "../SDL_sysvideo.h" #include "../../events/SDL_mouse_c.h" static SDL_Cursor *DirectFB_CreateDefaultCursor(void); static SDL_Cursor *DirectFB_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y); static int DirectFB_ShowCursor(SDL_Cursor * cursor); static void DirectFB_FreeCursor(SDL_Cursor * cursor); static void DirectFB_WarpMouse(SDL_Window * window, int x, int y); static const char *arrow[] = { /* pixels */ "X ", "XX ", "X.X ", "X..X ", "X...X ", "X....X ", "X.....X ", "X......X ", "X.......X ", "X........X ", "X.....XXXXX ", "X..X..X ", "X.X X..X ", "XX X..X ", "X X..X ", " X..X ", " X..X ", " X..X ", " XX ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", }; static SDL_Cursor * DirectFB_CreateDefaultCursor(void) { SDL_VideoDevice *dev = SDL_GetVideoDevice(); SDL_DFB_DEVICEDATA(dev); DFB_CursorData *curdata; DFBSurfaceDescription dsc; SDL_Cursor *cursor; Uint32 *dest; int pitch, i, j; SDL_DFB_ALLOC_CLEAR( cursor, sizeof(*cursor)); SDL_DFB_ALLOC_CLEAR(curdata, sizeof(*curdata)); dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS; dsc.caps = DSCAPS_VIDEOONLY; dsc.width = 32; dsc.height = 32; dsc.pixelformat = DSPF_ARGB; SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc, &curdata->surf)); curdata->hotx = 0; curdata->hoty = 0; cursor->driverdata = curdata; SDL_DFB_CHECKERR(curdata->surf->Lock(curdata->surf, DSLF_WRITE, (void *) &dest, &pitch)); /* Relies on the fact that this is only called with ARGB surface. */ for (i = 0; i < 32; i++) { for (j = 0; j < 32; j++) { switch (arrow[i][j]) { case ' ': dest[j] = 0x00000000; break; case '.': dest[j] = 0xffffffff; break; case 'X': dest[j] = 0xff000000; break; } } dest += (pitch >> 2); } curdata->surf->Unlock(curdata->surf); return cursor; error: return NULL; } /* Create a cursor from a surface */ static SDL_Cursor * DirectFB_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y) { SDL_VideoDevice *dev = SDL_GetVideoDevice(); SDL_DFB_DEVICEDATA(dev); DFB_CursorData *curdata; DFBSurfaceDescription dsc; SDL_Cursor *cursor; Uint32 *dest; Uint32 *p; int pitch, i; SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888); SDL_assert(surface->pitch == surface->w * 4); SDL_DFB_ALLOC_CLEAR( cursor, sizeof(*cursor)); SDL_DFB_ALLOC_CLEAR(curdata, sizeof(*curdata)); dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS; dsc.caps = DSCAPS_VIDEOONLY; dsc.width = surface->w; dsc.height = surface->h; dsc.pixelformat = DSPF_ARGB; SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc, &curdata->surf)); curdata->hotx = hot_x; curdata->hoty = hot_y; cursor->driverdata = curdata; SDL_DFB_CHECKERR(curdata->surf->Lock(curdata->surf, DSLF_WRITE, (void *) &dest, &pitch)); p = surface->pixels; for (i = 0; i < surface->h; i++) memcpy((char *) dest + i * pitch, (char *) p + i * surface->pitch, 4 * surface->w); curdata->surf->Unlock(curdata->surf); return cursor; error: return NULL; } /* Show the specified cursor, or hide if cursor is NULL */ static int DirectFB_ShowCursor(SDL_Cursor * cursor) { SDL_DFB_CURSORDATA(cursor); SDL_Window *window; window = SDL_GetFocusWindow(); if (!window) return -1; else { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); if (display) { DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; DFB_WindowData *windata = (DFB_WindowData *) window->driverdata; if (cursor) SDL_DFB_CHECKERR(windata->dfbwin-> SetCursorShape(windata->dfbwin, curdata->surf, curdata->hotx, curdata->hoty)); SDL_DFB_CHECKERR(dispdata->layer-> SetCooperativeLevel(dispdata->layer, DLSCL_ADMINISTRATIVE)); SDL_DFB_CHECKERR(dispdata->layer-> SetCursorOpacity(dispdata->layer, cursor ? 0xC0 : 0x00)); SDL_DFB_CHECKERR(dispdata->layer-> SetCooperativeLevel(dispdata->layer, DLSCL_SHARED)); } } return 0; error: return -1; } /* Free a window manager cursor */ static void DirectFB_FreeCursor(SDL_Cursor * cursor) { SDL_DFB_CURSORDATA(cursor); SDL_DFB_RELEASE(curdata->surf); SDL_DFB_FREE(cursor->driverdata); SDL_DFB_FREE(cursor); } /* Warp the mouse to (x,y) */ static void DirectFB_WarpMouse(SDL_Window * window, int x, int y) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; DFB_WindowData *windata = (DFB_WindowData *) window->driverdata; int cx, cy; SDL_DFB_CHECKERR(windata->dfbwin->GetPosition(windata->dfbwin, &cx, &cy)); SDL_DFB_CHECKERR(dispdata->layer->WarpCursor(dispdata->layer, cx + x + windata->client.x, cy + y + windata->client.y)); error: return; } #if USE_MULTI_API static void DirectFB_MoveCursor(SDL_Cursor * cursor); static void DirectFB_WarpMouse(SDL_Mouse * mouse, SDL_Window * window, int x, int y); static void DirectFB_FreeMouse(SDL_Mouse * mouse); static int id_mask; static DFBEnumerationResult EnumMice(DFBInputDeviceID device_id, DFBInputDeviceDescription desc, void *callbackdata) { DFB_DeviceData *devdata = callbackdata; if ((desc.type & DIDTF_MOUSE) && (device_id & id_mask)) { SDL_Mouse mouse; SDL_zero(mouse); mouse.id = device_id; mouse.CreateCursor = DirectFB_CreateCursor; mouse.ShowCursor = DirectFB_ShowCursor; mouse.MoveCursor = DirectFB_MoveCursor; mouse.FreeCursor = DirectFB_FreeCursor; mouse.WarpMouse = DirectFB_WarpMouse; mouse.FreeMouse = DirectFB_FreeMouse; mouse.cursor_shown = 1; SDL_AddMouse(&mouse, desc.name, 0, 0, 1); devdata->mouse_id[devdata->num_mice++] = device_id; } return DFENUM_OK; } void DirectFB_InitMouse(_THIS) { SDL_DFB_DEVICEDATA(_this); devdata->num_mice = 0; if (devdata->use_linux_input) { /* try non-core devices first */ id_mask = 0xF0; devdata->dfb->EnumInputDevices(devdata->dfb, EnumMice, devdata); if (devdata->num_mice == 0) { /* try core devices */ id_mask = 0x0F; devdata->dfb->EnumInputDevices(devdata->dfb, EnumMice, devdata); } } if (devdata->num_mice == 0) { SDL_Mouse mouse; SDL_zero(mouse); mouse.CreateCursor = DirectFB_CreateCursor; mouse.ShowCursor = DirectFB_ShowCursor; mouse.MoveCursor = DirectFB_MoveCursor; mouse.FreeCursor = DirectFB_FreeCursor; mouse.WarpMouse = DirectFB_WarpMouse; mouse.FreeMouse = DirectFB_FreeMouse; mouse.cursor_shown = 1; SDL_AddMouse(&mouse, "Mouse", 0, 0, 1); devdata->num_mice = 1; } } void DirectFB_QuitMouse(_THIS) { SDL_DFB_DEVICEDATA(_this); if (devdata->use_linux_input) { SDL_MouseQuit(); } else { SDL_DelMouse(0); } } /* This is called when a mouse motion event occurs */ static void DirectFB_MoveCursor(SDL_Cursor * cursor) { } /* Warp the mouse to (x,y) */ static void DirectFB_WarpMouse(SDL_Mouse * mouse, SDL_Window * window, int x, int y) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; DFB_WindowData *windata = (DFB_WindowData *) window->driverdata; DFBResult ret; int cx, cy; SDL_DFB_CHECKERR(windata->dfbwin->GetPosition(windata->dfbwin, &cx, &cy)); SDL_DFB_CHECKERR(dispdata->layer->WarpCursor(dispdata->layer, cx + x + windata->client.x, cy + y + windata->client.y)); error: return; } /* Free the mouse when it's time */ static void DirectFB_FreeMouse(SDL_Mouse * mouse) { /* nothing yet */ } #else /* USE_MULTI_API */ void DirectFB_InitMouse(_THIS) { SDL_DFB_DEVICEDATA(_this); SDL_Mouse *mouse = SDL_GetMouse(); mouse->CreateCursor = DirectFB_CreateCursor; mouse->ShowCursor = DirectFB_ShowCursor; mouse->WarpMouse = DirectFB_WarpMouse; mouse->FreeCursor = DirectFB_FreeCursor; SDL_SetDefaultCursor(DirectFB_CreateDefaultCursor()); devdata->num_mice = 1; } void DirectFB_QuitMouse(_THIS) { } #endif #endif /* SDL_VIDEO_DRIVER_DIRECTFB */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_mouse.c
C
apache-2.0
11,616
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_DirectFB_mouse_h_ #define SDL_DirectFB_mouse_h_ #include <directfb.h> #include "../SDL_sysvideo.h" typedef struct _DFB_CursorData DFB_CursorData; struct _DFB_CursorData { IDirectFBSurface *surf; int hotx; int hoty; }; #define SDL_DFB_CURSORDATA(curs) DFB_CursorData *curdata = (DFB_CursorData *) ((curs) ? (curs)->driverdata : NULL) extern void DirectFB_InitMouse(_THIS); extern void DirectFB_QuitMouse(_THIS); #endif /* SDL_DirectFB_mouse_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_mouse.h
C
apache-2.0
1,477
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_DirectFB_video.h" #if SDL_DIRECTFB_OPENGL #include "SDL_DirectFB_opengl.h" #include "SDL_DirectFB_window.h" #include <directfbgl.h> #include "SDL_loadso.h" #endif #if SDL_DIRECTFB_OPENGL struct SDL_GLDriverData { int gl_active; /* to stop switching drivers while we have a valid context */ int initialized; DirectFB_GLContext *firstgl; /* linked list */ /* OpenGL */ void (*glFinish) (void); void (*glFlush) (void); }; #define OPENGL_REQUIRS_DLOPEN #if defined(OPENGL_REQUIRS_DLOPEN) && defined(SDL_LOADSO_DLOPEN) #include <dlfcn.h> #define GL_LoadObject(X) dlopen(X, (RTLD_NOW|RTLD_GLOBAL)) #define GL_LoadFunction dlsym #define GL_UnloadObject dlclose #else #define GL_LoadObject SDL_LoadObject #define GL_LoadFunction SDL_LoadFunction #define GL_UnloadObject SDL_UnloadObject #endif static void DirectFB_GL_UnloadLibrary(_THIS); int DirectFB_GL_Initialize(_THIS) { if (_this->gl_data) { return 0; } _this->gl_data = (struct SDL_GLDriverData *) SDL_calloc(1, sizeof(struct SDL_GLDriverData)); if (!_this->gl_data) { return SDL_OutOfMemory(); } _this->gl_data->initialized = 0; ++_this->gl_data->initialized; _this->gl_data->firstgl = NULL; if (DirectFB_GL_LoadLibrary(_this, NULL) < 0) { return -1; } /* Initialize extensions */ /* FIXME needed? * X11_GL_InitExtensions(_this); */ return 0; } void DirectFB_GL_Shutdown(_THIS) { if (!_this->gl_data || (--_this->gl_data->initialized > 0)) { return; } DirectFB_GL_UnloadLibrary(_this); SDL_free(_this->gl_data); _this->gl_data = NULL; } int DirectFB_GL_LoadLibrary(_THIS, const char *path) { void *handle = NULL; SDL_DFB_DEBUG("Loadlibrary : %s\n", path); if (_this->gl_data->gl_active) { return SDL_SetError("OpenGL context already created"); } if (path == NULL) { path = SDL_getenv("SDL_OPENGL_LIBRARY"); if (path == NULL) { path = "libGL.so.1"; } } handle = GL_LoadObject(path); if (handle == NULL) { SDL_DFB_ERR("Library not found: %s\n", path); /* SDL_LoadObject() will call SDL_SetError() for us. */ return -1; } SDL_DFB_DEBUG("Loaded library: %s\n", path); _this->gl_config.dll_handle = handle; if (path) { SDL_strlcpy(_this->gl_config.driver_path, path, SDL_arraysize(_this->gl_config.driver_path)); } else { *_this->gl_config.driver_path = '\0'; } _this->gl_data->glFinish = DirectFB_GL_GetProcAddress(_this, "glFinish"); _this->gl_data->glFlush = DirectFB_GL_GetProcAddress(_this, "glFlush"); return 0; } static void DirectFB_GL_UnloadLibrary(_THIS) { #if 0 int ret = GL_UnloadObject(_this->gl_config.dll_handle); if (ret) SDL_DFB_ERR("Error #%d trying to unload library.\n", ret); _this->gl_config.dll_handle = NULL; #endif /* Free OpenGL memory */ SDL_free(_this->gl_data); _this->gl_data = NULL; } void * DirectFB_GL_GetProcAddress(_THIS, const char *proc) { void *handle; handle = _this->gl_config.dll_handle; return GL_LoadFunction(handle, proc); } SDL_GLContext DirectFB_GL_CreateContext(_THIS, SDL_Window * window) { SDL_DFB_WINDOWDATA(window); DirectFB_GLContext *context; SDL_DFB_ALLOC_CLEAR(context, sizeof(DirectFB_GLContext)); SDL_DFB_CHECKERR(windata->surface->GetGL(windata->surface, &context->context)); if (!context->context) return NULL; context->is_locked = 0; context->sdl_window = window; context->next = _this->gl_data->firstgl; _this->gl_data->firstgl = context; SDL_DFB_CHECK(context->context->Unlock(context->context)); if (DirectFB_GL_MakeCurrent(_this, window, context) < 0) { DirectFB_GL_DeleteContext(_this, context); return NULL; } return context; error: return NULL; } int DirectFB_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) { DirectFB_GLContext *ctx = (DirectFB_GLContext *) context; DirectFB_GLContext *p; for (p = _this->gl_data->firstgl; p; p = p->next) { if (p->is_locked) { SDL_DFB_CHECKERR(p->context->Unlock(p->context)); p->is_locked = 0; } } if (ctx != NULL) { SDL_DFB_CHECKERR(ctx->context->Lock(ctx->context)); ctx->is_locked = 1; } return 0; error: return -1; } int DirectFB_GL_SetSwapInterval(_THIS, int interval) { return SDL_Unsupported(); } int DirectFB_GL_GetSwapInterval(_THIS) { return 0; } int DirectFB_GL_SwapWindow(_THIS, SDL_Window * window) { SDL_DFB_WINDOWDATA(window); DirectFB_GLContext *p; #if 0 if (devdata->glFinish) devdata->glFinish(); else if (devdata->glFlush) devdata->glFlush(); #endif for (p = _this->gl_data->firstgl; p != NULL; p = p->next) if (p->sdl_window == window && p->is_locked) { SDL_DFB_CHECKERR(p->context->Unlock(p->context)); p->is_locked = 0; } SDL_DFB_CHECKERR(windata->window_surface->Flip(windata->window_surface,NULL, DSFLIP_PIPELINE |DSFLIP_BLIT | DSFLIP_ONSYNC )); return 0; error: return -1; } void DirectFB_GL_DeleteContext(_THIS, SDL_GLContext context) { DirectFB_GLContext *ctx = (DirectFB_GLContext *) context; DirectFB_GLContext *p; if (ctx->is_locked) SDL_DFB_CHECK(ctx->context->Unlock(ctx->context)); SDL_DFB_RELEASE(ctx->context); for (p = _this->gl_data->firstgl; p && p->next != ctx; p = p->next) ; if (p) p->next = ctx->next; else _this->gl_data->firstgl = ctx->next; SDL_DFB_FREE(ctx); } void DirectFB_GL_FreeWindowContexts(_THIS, SDL_Window * window) { DirectFB_GLContext *p; for (p = _this->gl_data->firstgl; p != NULL; p = p->next) if (p->sdl_window == window) { if (p->is_locked) SDL_DFB_CHECK(p->context->Unlock(p->context)); SDL_DFB_RELEASE(p->context); } } void DirectFB_GL_ReAllocWindowContexts(_THIS, SDL_Window * window) { DirectFB_GLContext *p; for (p = _this->gl_data->firstgl; p != NULL; p = p->next) if (p->sdl_window == window) { SDL_DFB_WINDOWDATA(window); SDL_DFB_CHECK(windata->surface->GetGL(windata->surface, &p->context)); if (p->is_locked) SDL_DFB_CHECK(p->context->Lock(p->context)); } } void DirectFB_GL_DestroyWindowContexts(_THIS, SDL_Window * window) { DirectFB_GLContext *p; for (p = _this->gl_data->firstgl; p != NULL; p = p->next) if (p->sdl_window == window) DirectFB_GL_DeleteContext(_this, p); } #endif #endif /* SDL_VIDEO_DRIVER_DIRECTFB */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_opengl.c
C
apache-2.0
8,091
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_directfb_opengl_h_ #define SDL_directfb_opengl_h_ #include "SDL_DirectFB_video.h" #if SDL_DIRECTFB_OPENGL #include "SDL_opengl.h" typedef struct _DirectFB_GLContext DirectFB_GLContext; struct _DirectFB_GLContext { IDirectFBGL *context; DirectFB_GLContext *next; SDL_Window *sdl_window; int is_locked; }; /* OpenGL functions */ extern int DirectFB_GL_Initialize(_THIS); extern void DirectFB_GL_Shutdown(_THIS); extern int DirectFB_GL_LoadLibrary(_THIS, const char *path); extern void *DirectFB_GL_GetProcAddress(_THIS, const char *proc); extern SDL_GLContext DirectFB_GL_CreateContext(_THIS, SDL_Window * window); extern int DirectFB_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern int DirectFB_GL_SetSwapInterval(_THIS, int interval); extern int DirectFB_GL_GetSwapInterval(_THIS); extern int DirectFB_GL_SwapWindow(_THIS, SDL_Window * window); extern void DirectFB_GL_DeleteContext(_THIS, SDL_GLContext context); extern void DirectFB_GL_FreeWindowContexts(_THIS, SDL_Window * window); extern void DirectFB_GL_ReAllocWindowContexts(_THIS, SDL_Window * window); extern void DirectFB_GL_DestroyWindowContexts(_THIS, SDL_Window * window); #endif /* SDL_DIRECTFB_OPENGL */ #endif /* SDL_directfb_opengl_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_opengl.h
C
apache-2.0
2,315
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_DirectFB_window.h" #include "SDL_DirectFB_modes.h" #include "SDL_syswm.h" #include "SDL_DirectFB_shape.h" #include "../SDL_sysvideo.h" #include "../../render/SDL_sysrender.h" #ifndef DFB_VERSION_ATLEAST #define DFB_VERSIONNUM(X, Y, Z) \ ((X)*1000 + (Y)*100 + (Z)) #define DFB_COMPILEDVERSION \ DFB_VERSIONNUM(DIRECTFB_MAJOR_VERSION, DIRECTFB_MINOR_VERSION, DIRECTFB_MICRO_VERSION) #define DFB_VERSION_ATLEAST(X, Y, Z) \ (DFB_COMPILEDVERSION >= DFB_VERSIONNUM(X, Y, Z)) #define SDL_DFB_CHECK(x) x #endif /* the following is not yet tested ... */ #define USE_DISPLAY_PALETTE (0) #define SDL_DFB_RENDERERDATA(rend) DirectFB_RenderData *renddata = ((rend) ? (DirectFB_RenderData *) (rend)->driverdata : NULL) #define SDL_DFB_WINDOWSURFACE(win) IDirectFBSurface *destsurf = ((DFB_WindowData *) ((win)->driverdata))->surface; typedef struct { SDL_Window *window; DFBSurfaceFlipFlags flipflags; int size_changed; int lastBlendMode; DFBSurfaceBlittingFlags blitFlags; DFBSurfaceDrawingFlags drawFlags; IDirectFBSurface* target; } DirectFB_RenderData; typedef struct { IDirectFBSurface *surface; Uint32 format; void *pixels; int pitch; IDirectFBPalette *palette; int isDirty; SDL_VideoDisplay *display; /* only for yuv textures */ #if (DFB_VERSION_ATLEAST(1,2,0)) DFBSurfaceRenderOptions render_options; #endif } DirectFB_TextureData; static SDL_INLINE void SDLtoDFBRect(const SDL_Rect * sr, DFBRectangle * dr) { dr->x = sr->x; dr->y = sr->y; dr->h = sr->h; dr->w = sr->w; } static SDL_INLINE void SDLtoDFBRect_Float(const SDL_FRect * sr, DFBRectangle * dr) { dr->x = sr->x; dr->y = sr->y; dr->h = sr->h; dr->w = sr->w; } static int TextureHasAlpha(DirectFB_TextureData * data) { /* Drawing primitive ? */ if (!data) return 0; return (DFB_PIXELFORMAT_HAS_ALPHA(DirectFB_SDLToDFBPixelFormat(data->format)) ? 1 : 0); #if 0 switch (data->format) { case SDL_PIXELFORMAT_INDEX4LSB: case SDL_PIXELFORMAT_INDEX4MSB: case SDL_PIXELFORMAT_ARGB4444: case SDL_PIXELFORMAT_ARGB1555: case SDL_PIXELFORMAT_ARGB8888: case SDL_PIXELFORMAT_RGBA8888: case SDL_PIXELFORMAT_ABGR8888: case SDL_PIXELFORMAT_BGRA8888: case SDL_PIXELFORMAT_ARGB2101010: return 1; default: return 0; } #endif } static SDL_INLINE IDirectFBSurface *get_dfb_surface(SDL_Window *window) { SDL_SysWMinfo wm_info; SDL_memset(&wm_info, 0, sizeof(SDL_SysWMinfo)); SDL_VERSION(&wm_info.version); if (!SDL_GetWindowWMInfo(window, &wm_info)) { return NULL; } return wm_info.info.dfb.surface; } static SDL_INLINE IDirectFBWindow *get_dfb_window(SDL_Window *window) { SDL_SysWMinfo wm_info; SDL_memset(&wm_info, 0, sizeof(SDL_SysWMinfo)); SDL_VERSION(&wm_info.version); if (!SDL_GetWindowWMInfo(window, &wm_info)) { return NULL; } return wm_info.info.dfb.window; } static void SetBlendMode(DirectFB_RenderData * data, int blendMode, DirectFB_TextureData * source) { IDirectFBSurface *destsurf = data->target; /* FIXME: check for format change */ if (1 || data->lastBlendMode != blendMode) { switch (blendMode) { case SDL_BLENDMODE_NONE: /**< No blending */ data->blitFlags = DSBLIT_NOFX; data->drawFlags = DSDRAW_NOFX; SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_ONE)); SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_ZERO)); break; #if 0 case SDL_BLENDMODE_MASK: data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL; data->drawFlags = DSDRAW_BLEND; SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_SRCALPHA)); SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_INVSRCALPHA)); break; #endif case SDL_BLENDMODE_BLEND: data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL; data->drawFlags = DSDRAW_BLEND; SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_SRCALPHA)); SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_INVSRCALPHA)); break; case SDL_BLENDMODE_ADD: data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL; data->drawFlags = DSDRAW_BLEND; /* FIXME: SRCALPHA kills performance on radeon ... * It will be cheaper to copy the surface to a temporary surface and premultiply */ if (source && TextureHasAlpha(source)) SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_SRCALPHA)); else SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_ONE)); SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_ONE)); break; case SDL_BLENDMODE_MOD: data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL; data->drawFlags = DSDRAW_BLEND; SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_ZERO)); SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_SRCCOLOR)); break; case SDL_BLENDMODE_MUL: data->blitFlags = DSBLIT_BLEND_ALPHACHANNEL; data->drawFlags = DSDRAW_BLEND; SDL_DFB_CHECK(destsurf->SetSrcBlendFunction(destsurf, DSBF_DESTCOLOR)); SDL_DFB_CHECK(destsurf->SetDstBlendFunction(destsurf, DSBF_INVSRCALPHA)); break; } data->lastBlendMode = blendMode; } } static int PrepareDraw(SDL_Renderer * renderer, const SDL_RenderCommand *cmd) { DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata; IDirectFBSurface *destsurf = data->target; Uint8 r = cmd->data.draw.r; Uint8 g = cmd->data.draw.g; Uint8 b = cmd->data.draw.b; Uint8 a = cmd->data.draw.a; SetBlendMode(data, cmd->data.draw.blend, NULL); SDL_DFB_CHECKERR(destsurf->SetDrawingFlags(destsurf, data->drawFlags)); switch (renderer->blendMode) { case SDL_BLENDMODE_NONE: /* case SDL_BLENDMODE_MASK: */ case SDL_BLENDMODE_BLEND: break; case SDL_BLENDMODE_ADD: case SDL_BLENDMODE_MOD: case SDL_BLENDMODE_MUL: r = ((int) r * (int) a) / 255; g = ((int) g * (int) a) / 255; b = ((int) b * (int) a) / 255; a = 255; break; case SDL_BLENDMODE_INVALID: break; } SDL_DFB_CHECKERR(destsurf->SetColor(destsurf, r, g, b, a)); return 0; error: return -1; } static void DirectFB_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event) { SDL_DFB_RENDERERDATA(renderer); if (event->event == SDL_WINDOWEVENT_SIZE_CHANGED) { /* Rebind the context to the window area and update matrices */ /* SDL_CurrentContext = NULL; */ /* data->updateSize = SDL_TRUE; */ renddata->size_changed = SDL_TRUE; } } static void DirectFB_ActivateRenderer(SDL_Renderer * renderer) { SDL_DFB_RENDERERDATA(renderer); if (renddata->size_changed /* || windata->wm_needs_redraw */) { renddata->size_changed = SDL_FALSE; } } static int DirectFB_AcquireVidLayer(SDL_Renderer * renderer, SDL_Texture * texture) { SDL_Window *window = renderer->window; SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DFB_DEVICEDATA(display->device); DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; DirectFB_TextureData *data = texture->driverdata; DFBDisplayLayerConfig layconf; DFBResult ret; if (devdata->use_yuv_direct && (dispdata->vidID >= 0) && (!dispdata->vidIDinuse) && SDL_ISPIXELFORMAT_FOURCC(data->format)) { layconf.flags = DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT | DLCONF_SURFACE_CAPS; layconf.width = texture->w; layconf.height = texture->h; layconf.pixelformat = DirectFB_SDLToDFBPixelFormat(data->format); layconf.surface_caps = DSCAPS_VIDEOONLY | DSCAPS_DOUBLE; SDL_DFB_CHECKERR(devdata->dfb->GetDisplayLayer(devdata->dfb, dispdata->vidID, &dispdata->vidlayer)); SDL_DFB_CHECKERR(dispdata-> vidlayer->SetCooperativeLevel(dispdata->vidlayer, DLSCL_EXCLUSIVE)); if (devdata->use_yuv_underlays) { ret = dispdata->vidlayer->SetLevel(dispdata->vidlayer, -1); if (ret != DFB_OK) SDL_DFB_DEBUG("Underlay Setlevel not supported\n"); } SDL_DFB_CHECKERR(dispdata-> vidlayer->SetConfiguration(dispdata->vidlayer, &layconf)); SDL_DFB_CHECKERR(dispdata-> vidlayer->GetSurface(dispdata->vidlayer, &data->surface)); dispdata->vidIDinuse = 1; data->display = display; return 0; } return 1; error: if (dispdata->vidlayer) { SDL_DFB_RELEASE(data->surface); SDL_DFB_CHECKERR(dispdata-> vidlayer->SetCooperativeLevel(dispdata->vidlayer, DLSCL_ADMINISTRATIVE)); SDL_DFB_RELEASE(dispdata->vidlayer); } return 1; } static int DirectFB_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture) { SDL_Window *window = renderer->window; SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); SDL_DFB_DEVICEDATA(display->device); DirectFB_TextureData *data; DFBSurfaceDescription dsc; DFBSurfacePixelFormat pixelformat; DirectFB_ActivateRenderer(renderer); SDL_DFB_ALLOC_CLEAR(data, sizeof(*data)); texture->driverdata = data; /* find the right pixelformat */ pixelformat = DirectFB_SDLToDFBPixelFormat(texture->format); if (pixelformat == DSPF_UNKNOWN) { SDL_SetError("Unknown pixel format %d", data->format); goto error; } data->format = texture->format; data->pitch = texture->w * DFB_BYTES_PER_PIXEL(pixelformat); if (DirectFB_AcquireVidLayer(renderer, texture) != 0) { /* fill surface description */ dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS; dsc.width = texture->w; dsc.height = texture->h; if(texture->format == SDL_PIXELFORMAT_YV12 || texture->format == SDL_PIXELFORMAT_IYUV) { /* dfb has problems with odd sizes -make them even internally */ dsc.width += (dsc.width % 2); dsc.height += (dsc.height % 2); } /* <1.2 Never use DSCAPS_VIDEOONLY here. It kills performance * No DSCAPS_SYSTEMONLY either - let dfb decide * 1.2: DSCAPS_SYSTEMONLY boosts performance by factor ~8 * Depends on other settings as well. Let dfb decide. */ dsc.caps = DSCAPS_PREMULTIPLIED; #if 0 if (texture->access == SDL_TEXTUREACCESS_STREAMING) dsc.caps |= DSCAPS_SYSTEMONLY; else dsc.caps |= DSCAPS_VIDEOONLY; #endif dsc.pixelformat = pixelformat; data->pixels = NULL; /* Create the surface */ SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc, &data->surface)); if (SDL_ISPIXELFORMAT_INDEXED(data->format) && !SDL_ISPIXELFORMAT_FOURCC(data->format)) { #if 1 SDL_DFB_CHECKERR(data->surface->GetPalette(data->surface, &data->palette)); #else /* DFB has issues with blitting LUT8 surfaces. * Creating a new palette does not help. */ DFBPaletteDescription pal_desc; pal_desc.flags = DPDESC_SIZE; /* | DPDESC_ENTRIES */ pal_desc.size = 256; SDL_DFB_CHECKERR(devdata->dfb->CreatePalette(devdata->dfb, &pal_desc,&data->palette)); SDL_DFB_CHECKERR(data->surface->SetPalette(data->surface, data->palette)); #endif } } #if (DFB_VERSION_ATLEAST(1,2,0)) data->render_options = DSRO_NONE; #endif if (texture->access == SDL_TEXTUREACCESS_STREAMING) { /* 3 plane YUVs return 1 bpp, but we need more space for other planes */ if(texture->format == SDL_PIXELFORMAT_YV12 || texture->format == SDL_PIXELFORMAT_IYUV) { SDL_DFB_ALLOC_CLEAR(data->pixels, (texture->h * data->pitch + ((texture->h + texture->h % 2) * (data->pitch + data->pitch % 2) * 2) / 4)); } else { SDL_DFB_ALLOC_CLEAR(data->pixels, texture->h * data->pitch); } } return 0; error: SDL_DFB_RELEASE(data->palette); SDL_DFB_RELEASE(data->surface); SDL_DFB_FREE(texture->driverdata); return -1; } #if 0 static int DirectFB_SetTextureScaleMode(SDL_Renderer * renderer, SDL_Texture * texture) { #if (DFB_VERSION_ATLEAST(1,2,0)) DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata; switch (texture->scaleMode) { case SDL_SCALEMODE_NONE: case SDL_SCALEMODE_FAST: data->render_options = DSRO_NONE; break; case SDL_SCALEMODE_SLOW: data->render_options = DSRO_SMOOTH_UPSCALE | DSRO_SMOOTH_DOWNSCALE; break; case SDL_SCALEMODE_BEST: data->render_options = DSRO_SMOOTH_UPSCALE | DSRO_SMOOTH_DOWNSCALE | DSRO_ANTIALIAS; break; default: data->render_options = DSRO_NONE; texture->scaleMode = SDL_SCALEMODE_NONE; return SDL_Unsupported(); } #endif return 0; } #endif static int DirectFB_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, const void *pixels, int pitch) { DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata; Uint8 *dpixels; int dpitch; Uint8 *src, *dst; int row; size_t length; int bpp = DFB_BYTES_PER_PIXEL(DirectFB_SDLToDFBPixelFormat(texture->format)); /* FIXME: SDL_BYTESPERPIXEL(texture->format) broken for yuv yv12 3 planes */ DirectFB_ActivateRenderer(renderer); if ((texture->format == SDL_PIXELFORMAT_YV12) || (texture->format == SDL_PIXELFORMAT_IYUV)) { bpp = 1; } SDL_DFB_CHECKERR(data->surface->Lock(data->surface, DSLF_WRITE | DSLF_READ, ((void **) &dpixels), &dpitch)); src = (Uint8 *) pixels; dst = (Uint8 *) dpixels + rect->y * dpitch + rect->x * bpp; length = rect->w * bpp; for (row = 0; row < rect->h; ++row) { SDL_memcpy(dst, src, length); src += pitch; dst += dpitch; } /* copy other planes for 3 plane formats */ if ((texture->format == SDL_PIXELFORMAT_YV12) || (texture->format == SDL_PIXELFORMAT_IYUV)) { src = (Uint8 *) pixels + texture->h * pitch; dst = (Uint8 *) dpixels + texture->h * dpitch + rect->y * dpitch / 4 + rect->x * bpp / 2; for (row = 0; row < rect->h / 2 + (rect->h & 1); ++row) { SDL_memcpy(dst, src, length / 2); src += pitch / 2; dst += dpitch / 2; } src = (Uint8 *) pixels + texture->h * pitch + texture->h * pitch / 4; dst = (Uint8 *) dpixels + texture->h * dpitch + texture->h * dpitch / 4 + rect->y * dpitch / 4 + rect->x * bpp / 2; for (row = 0; row < rect->h / 2 + (rect->h & 1); ++row) { SDL_memcpy(dst, src, length / 2); src += pitch / 2; dst += dpitch / 2; } } SDL_DFB_CHECKERR(data->surface->Unlock(data->surface)); data->isDirty = 0; return 0; error: return 1; } static int DirectFB_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, void **pixels, int *pitch) { DirectFB_TextureData *texturedata = (DirectFB_TextureData *) texture->driverdata; DirectFB_ActivateRenderer(renderer); #if 0 if (markDirty) { SDL_AddDirtyRect(&texturedata->dirty, rect); } #endif if (texturedata->display) { void *fdata; int fpitch; SDL_DFB_CHECKERR(texturedata->surface->Lock(texturedata->surface, DSLF_WRITE | DSLF_READ, &fdata, &fpitch)); *pitch = fpitch; *pixels = fdata; } else { *pixels = (void *) ((Uint8 *) texturedata->pixels + rect->y * texturedata->pitch + rect->x * DFB_BYTES_PER_PIXEL(DirectFB_SDLToDFBPixelFormat(texture->format))); *pitch = texturedata->pitch; texturedata->isDirty = 1; } return 0; error: return -1; } static void DirectFB_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture) { DirectFB_TextureData *texturedata = (DirectFB_TextureData *) texture->driverdata; DirectFB_ActivateRenderer(renderer); if (texturedata->display) { SDL_DFB_CHECK(texturedata->surface->Unlock(texturedata->surface)); texturedata->pixels = NULL; } } static void DirectFB_SetTextureScaleMode() { } #if 0 static void DirectFB_DirtyTexture(SDL_Renderer * renderer, SDL_Texture * texture, int numrects, const SDL_Rect * rects) { DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata; int i; for (i = 0; i < numrects; ++i) { SDL_AddDirtyRect(&data->dirty, &rects[i]); } } #endif static int DirectFB_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture) { DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata; DirectFB_TextureData *tex_data = NULL; DirectFB_ActivateRenderer(renderer); if (texture) { tex_data = (DirectFB_TextureData *) texture->driverdata; data->target = tex_data->surface; } else { data->target = get_dfb_surface(data->window); } data->lastBlendMode = 0; return 0; } static int DirectFB_QueueSetViewport(SDL_Renderer * renderer, SDL_RenderCommand *cmd) { return 0; /* nothing to do in this backend. */ } static int DirectFB_QueueDrawPoints(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FPoint *points, int count) { const size_t len = count * sizeof (SDL_FPoint); SDL_FPoint *verts = (SDL_FPoint *) SDL_AllocateRenderVertices(renderer, len, 0, &cmd->data.draw.first); if (!verts) { return -1; } cmd->data.draw.count = count; SDL_memcpy(verts, points, len); return 0; } static int DirectFB_QueueFillRects(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FRect * rects, int count) { const size_t len = count * sizeof (SDL_FRect); SDL_FRect *verts = (SDL_FRect *) SDL_AllocateRenderVertices(renderer, len, 0, &cmd->data.draw.first); if (!verts) { return -1; } cmd->data.draw.count = count; SDL_memcpy(verts, rects, len); return 0; } static int DirectFB_QueueCopy(SDL_Renderer * renderer, SDL_RenderCommand *cmd, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect) { DFBRectangle *verts = (DFBRectangle *) SDL_AllocateRenderVertices(renderer, 2 * sizeof (DFBRectangle), 0, &cmd->data.draw.first); if (!verts) { return -1; } cmd->data.draw.count = 1; SDLtoDFBRect(srcrect, verts++); SDLtoDFBRect_Float(dstrect, verts); return 0; } static int DirectFB_QueueCopyEx(SDL_Renderer * renderer, SDL_RenderCommand *cmd, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect, const double angle, const SDL_FPoint *center, const SDL_RendererFlip flip) { return SDL_Unsupported(); } static int DirectFB_RunCommandQueue(SDL_Renderer * renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize) { /* !!! FIXME: there are probably some good optimization wins in here if someone wants to look it over. */ DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata; IDirectFBSurface *destsurf = data->target; DFBRegion clip_region; size_t i; DirectFB_ActivateRenderer(renderer); SDL_zero(clip_region); /* in theory, this always gets set before use. */ while (cmd) { switch (cmd->command) { case SDL_RENDERCMD_SETDRAWCOLOR: break; /* not used here */ case SDL_RENDERCMD_SETVIEWPORT: { const SDL_Rect *viewport = &cmd->data.viewport.rect; clip_region.x1 = viewport->x; clip_region.y1 = viewport->y; clip_region.x2 = clip_region.x1 + viewport->w - 1; clip_region.y2 = clip_region.y1 + viewport->h - 1; destsurf->SetClip(destsurf, &clip_region); break; } case SDL_RENDERCMD_SETCLIPRECT: { /* !!! FIXME: how does this SetClip interact with the one in SETVIEWPORT? */ if (cmd->data.cliprect.enabled) { const SDL_Rect *rect = &cmd->data.cliprect.rect; clip_region.x1 = rect->x; clip_region.x2 = rect->x + rect->w; clip_region.y1 = rect->y; clip_region.y2 = rect->y + rect->h; destsurf->SetClip(destsurf, &clip_region); } break; } case SDL_RENDERCMD_CLEAR: { const Uint8 r = cmd->data.color.r; const Uint8 g = cmd->data.color.g; const Uint8 b = cmd->data.color.b; const Uint8 a = cmd->data.color.a; destsurf->Clear(destsurf, r, g, b, a); break; } case SDL_RENDERCMD_DRAW_POINTS: { const size_t count = cmd->data.draw.count; const SDL_FPoint *points = (SDL_FPoint *) (((Uint8 *) vertices) + cmd->data.draw.first); PrepareDraw(renderer, cmd); for (i = 0; i < count; i++) { const int x = points[i].x + clip_region.x1; const int y = points[i].y + clip_region.y1; destsurf->DrawLine(destsurf, x, y, x, y); } break; } case SDL_RENDERCMD_DRAW_LINES: { const SDL_FPoint *points = (SDL_FPoint *) (((Uint8 *) vertices) + cmd->data.draw.first); const size_t count = cmd->data.draw.count; PrepareDraw(renderer, cmd); #if (DFB_VERSION_ATLEAST(1,2,0)) /* !!! FIXME: should this be set once, somewhere else? */ destsurf->SetRenderOptions(destsurf, DSRO_ANTIALIAS); #endif for (i = 0; i < count - 1; i++) { const int x1 = points[i].x + clip_region.x1; const int y1 = points[i].y + clip_region.y1; const int x2 = points[i + 1].x + clip_region.x1; const int y2 = points[i + 1].y + clip_region.y1; destsurf->DrawLine(destsurf, x1, y1, x2, y2); } break; } case SDL_RENDERCMD_FILL_RECTS: { const SDL_FRect *rects = (SDL_FRect *) (((Uint8 *) vertices) + cmd->data.draw.first); const size_t count = cmd->data.draw.count; PrepareDraw(renderer, cmd); for (i = 0; i < count; i++, rects++) { destsurf->FillRectangle(destsurf, rects->x + clip_region.x1, rects->y + clip_region.y1, rects->w, rects->h); } break; } case SDL_RENDERCMD_COPY: { SDL_Texture *texture = cmd->data.draw.texture; const Uint8 r = cmd->data.draw.r; const Uint8 g = cmd->data.draw.g; const Uint8 b = cmd->data.draw.b; const Uint8 a = cmd->data.draw.a; DFBRectangle *verts = (DFBRectangle *) (((Uint8 *) vertices) + cmd->data.draw.first); DirectFB_TextureData *texturedata = (DirectFB_TextureData *) texture->driverdata; DFBRectangle *sr = verts++; DFBRectangle *dr = verts; dr->x += clip_region.x1; dr->y += clip_region.y1; if (texturedata->display) { int px, py; SDL_Window *window = renderer->window; IDirectFBWindow *dfbwin = get_dfb_window(window); SDL_DFB_WINDOWDATA(window); SDL_VideoDisplay *display = texturedata->display; DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata; dispdata->vidlayer->SetSourceRectangle(dispdata->vidlayer, sr->x, sr->y, sr->w, sr->h); dfbwin->GetPosition(dfbwin, &px, &py); px += windata->client.x; py += windata->client.y; dispdata->vidlayer->SetScreenRectangle(dispdata->vidlayer, px + dr->x, py + dr->y, dr->w, dr->h); } else { DFBSurfaceBlittingFlags flags = 0; if (texturedata->isDirty) { const SDL_Rect rect = { 0, 0, texture->w, texture->h }; DirectFB_UpdateTexture(renderer, texture, &rect, texturedata->pixels, texturedata->pitch); } if (a != 0xFF) { flags |= DSBLIT_BLEND_COLORALPHA; } if ((r & g & b) != 0xFF) { flags |= DSBLIT_COLORIZE; } destsurf->SetColor(destsurf, r, g, b, a); /* ???? flags |= DSBLIT_SRC_PREMULTCOLOR; */ SetBlendMode(data, texture->blendMode, texturedata); destsurf->SetBlittingFlags(destsurf, data->blitFlags | flags); #if (DFB_VERSION_ATLEAST(1,2,0)) destsurf->SetRenderOptions(destsurf, texturedata->render_options); #endif if (sr->w == dr->w && sr->h == dr->h) { destsurf->Blit(destsurf, texturedata->surface, sr, dr->x, dr->y); } else { destsurf->StretchBlit(destsurf, texturedata->surface, sr, dr); } } break; } case SDL_RENDERCMD_COPY_EX: break; /* unsupported */ case SDL_RENDERCMD_NO_OP: break; } cmd = cmd->next; } return 0; } static void DirectFB_RenderPresent(SDL_Renderer * renderer) { DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata; SDL_Window *window = renderer->window; SDL_DFB_WINDOWDATA(window); SDL_ShapeData *shape_data = (window->shaper ? window->shaper->driverdata : NULL); DirectFB_ActivateRenderer(renderer); if (shape_data && shape_data->surface) { /* saturate the window surface alpha channel */ SDL_DFB_CHECK(windata->window_surface->SetSrcBlendFunction(windata->window_surface, DSBF_ONE)); SDL_DFB_CHECK(windata->window_surface->SetDstBlendFunction(windata->window_surface, DSBF_ONE)); SDL_DFB_CHECK(windata->window_surface->SetDrawingFlags(windata->window_surface, DSDRAW_BLEND)); SDL_DFB_CHECK(windata->window_surface->SetColor(windata->window_surface, 0, 0, 0, 0xff)); SDL_DFB_CHECK(windata->window_surface->FillRectangle(windata->window_surface, 0,0, windata->size.w, windata->size.h)); /* blit the mask */ SDL_DFB_CHECK(windata->surface->SetSrcBlendFunction(windata->surface, DSBF_DESTCOLOR)); SDL_DFB_CHECK(windata->surface->SetDstBlendFunction(windata->surface, DSBF_ZERO)); SDL_DFB_CHECK(windata->surface->SetBlittingFlags(windata->surface, DSBLIT_BLEND_ALPHACHANNEL)); #if (DFB_VERSION_ATLEAST(1,2,0)) SDL_DFB_CHECK(windata->surface->SetRenderOptions(windata->surface, DSRO_NONE)); #endif SDL_DFB_CHECK(windata->surface->Blit(windata->surface, shape_data->surface, NULL, 0, 0)); } /* Send the data to the display */ SDL_DFB_CHECK(windata->window_surface->Flip(windata->window_surface, NULL, data->flipflags)); } static void DirectFB_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture) { DirectFB_TextureData *data = (DirectFB_TextureData *) texture->driverdata; DirectFB_ActivateRenderer(renderer); if (!data) { return; } SDL_DFB_RELEASE(data->palette); SDL_DFB_RELEASE(data->surface); if (data->display) { DFB_DisplayData *dispdata = (DFB_DisplayData *) data->display->driverdata; dispdata->vidIDinuse = 0; /* FIXME: Shouldn't we reset the cooperative level */ SDL_DFB_CHECK(dispdata->vidlayer->SetCooperativeLevel(dispdata->vidlayer, DLSCL_ADMINISTRATIVE)); SDL_DFB_RELEASE(dispdata->vidlayer); } SDL_DFB_FREE(data->pixels); SDL_free(data); texture->driverdata = NULL; } static void DirectFB_DestroyRenderer(SDL_Renderer * renderer) { DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata; #if 0 SDL_VideoDisplay *display = SDL_GetDisplayForWindow(data->window); if (display->palette) { SDL_DelPaletteWatch(display->palette, DisplayPaletteChanged, data); } #endif SDL_free(data); SDL_free(renderer); } static int DirectFB_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect, Uint32 format, void * pixels, int pitch) { Uint32 sdl_format; unsigned char* laypixels; int laypitch; DFBSurfacePixelFormat dfb_format; DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata; IDirectFBSurface *winsurf = data->target; DirectFB_ActivateRenderer(renderer); winsurf->GetPixelFormat(winsurf, &dfb_format); sdl_format = DirectFB_DFBToSDLPixelFormat(dfb_format); winsurf->Lock(winsurf, DSLF_READ, (void **) &laypixels, &laypitch); laypixels += (rect->y * laypitch + rect->x * SDL_BYTESPERPIXEL(sdl_format) ); SDL_ConvertPixels(rect->w, rect->h, sdl_format, laypixels, laypitch, format, pixels, pitch); winsurf->Unlock(winsurf); return 0; } #if 0 static int DirectFB_RenderWritePixels(SDL_Renderer * renderer, const SDL_Rect * rect, Uint32 format, const void * pixels, int pitch) { SDL_Window *window = renderer->window; SDL_DFB_WINDOWDATA(window); Uint32 sdl_format; unsigned char* laypixels; int laypitch; DFBSurfacePixelFormat dfb_format; SDL_DFB_CHECK(windata->surface->GetPixelFormat(windata->surface, &dfb_format)); sdl_format = DirectFB_DFBToSDLPixelFormat(dfb_format); SDL_DFB_CHECK(windata->surface->Lock(windata->surface, DSLF_WRITE, (void **) &laypixels, &laypitch)); laypixels += (rect->y * laypitch + rect->x * SDL_BYTESPERPIXEL(sdl_format) ); SDL_ConvertPixels(rect->w, rect->h, format, pixels, pitch, sdl_format, laypixels, laypitch); SDL_DFB_CHECK(windata->surface->Unlock(windata->surface)); return 0; } #endif SDL_Renderer * DirectFB_CreateRenderer(SDL_Window * window, Uint32 flags) { IDirectFBSurface *winsurf = get_dfb_surface(window); /*SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);*/ SDL_Renderer *renderer = NULL; DirectFB_RenderData *data = NULL; DFBSurfaceCapabilities scaps; if (!winsurf) { return NULL; } SDL_DFB_ALLOC_CLEAR(renderer, sizeof(*renderer)); SDL_DFB_ALLOC_CLEAR(data, sizeof(*data)); renderer->WindowEvent = DirectFB_WindowEvent; renderer->CreateTexture = DirectFB_CreateTexture; renderer->UpdateTexture = DirectFB_UpdateTexture; renderer->LockTexture = DirectFB_LockTexture; renderer->UnlockTexture = DirectFB_UnlockTexture; renderer->SetTextureScaleMode = DirectFB_SetTextureScaleMode; renderer->QueueSetViewport = DirectFB_QueueSetViewport; renderer->QueueSetDrawColor = DirectFB_QueueSetViewport; /* SetViewport and SetDrawColor are (currently) no-ops. */ renderer->QueueDrawPoints = DirectFB_QueueDrawPoints; renderer->QueueDrawLines = DirectFB_QueueDrawPoints; /* lines and points queue vertices the same way. */ renderer->QueueFillRects = DirectFB_QueueFillRects; renderer->QueueCopy = DirectFB_QueueCopy; renderer->QueueCopyEx = DirectFB_QueueCopyEx; renderer->RunCommandQueue = DirectFB_RunCommandQueue; renderer->RenderPresent = DirectFB_RenderPresent; /* FIXME: Yet to be tested */ renderer->RenderReadPixels = DirectFB_RenderReadPixels; /* renderer->RenderWritePixels = DirectFB_RenderWritePixels; */ renderer->DestroyTexture = DirectFB_DestroyTexture; renderer->DestroyRenderer = DirectFB_DestroyRenderer; renderer->SetRenderTarget = DirectFB_SetRenderTarget; renderer->info = DirectFB_RenderDriver.info; renderer->window = window; /* SDL window */ renderer->driverdata = data; renderer->info.flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE; data->window = window; data->target = winsurf; data->flipflags = DSFLIP_PIPELINE | DSFLIP_BLIT; if (flags & SDL_RENDERER_PRESENTVSYNC) { data->flipflags |= DSFLIP_WAITFORSYNC | DSFLIP_ONSYNC; renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; } else data->flipflags |= DSFLIP_ONSYNC; SDL_DFB_CHECKERR(winsurf->GetCapabilities(winsurf, &scaps)); #if 0 if (scaps & DSCAPS_DOUBLE) renderer->info.flags |= SDL_RENDERER_PRESENTFLIP2; else if (scaps & DSCAPS_TRIPLE) renderer->info.flags |= SDL_RENDERER_PRESENTFLIP3; else renderer->info.flags |= SDL_RENDERER_SINGLEBUFFER; #endif DirectFB_SetSupportedPixelFormats(&renderer->info); #if 0 /* Set up a palette watch on the display palette */ if (display-> palette) { SDL_AddPaletteWatch(display->palette, DisplayPaletteChanged, data); } #endif return renderer; error: SDL_DFB_FREE(renderer); SDL_DFB_FREE(data); return NULL; } SDL_RenderDriver DirectFB_RenderDriver = { DirectFB_CreateRenderer, { "directfb", (SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED), /* (SDL_TEXTUREMODULATE_NONE | SDL_TEXTUREMODULATE_COLOR | SDL_TEXTUREMODULATE_ALPHA), (SDL_BLENDMODE_NONE | SDL_BLENDMODE_MASK | SDL_BLENDMODE_BLEND | SDL_BLENDMODE_ADD | SDL_BLENDMODE_MOD), (SDL_SCALEMODE_NONE | SDL_SCALEMODE_FAST | SDL_SCALEMODE_SLOW | SDL_SCALEMODE_BEST), */ 0, { /* formats filled in later */ }, 0, 0} }; #endif /* SDL_VIDEO_DRIVER_DIRECTFB */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_render.c
C
apache-2.0
36,348
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* SDL surface based renderer implementation */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_render.h
C
apache-2.0
1,025
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_assert.h" #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_shape.h" #include "SDL_DirectFB_window.h" #include "../SDL_shape_internals.h" SDL_WindowShaper* DirectFB_CreateShaper(SDL_Window* window) { SDL_WindowShaper* result = NULL; SDL_ShapeData* data; int resized_properly; result = malloc(sizeof(SDL_WindowShaper)); result->window = window; result->mode.mode = ShapeModeDefault; result->mode.parameters.binarizationCutoff = 1; result->userx = result->usery = 0; data = SDL_malloc(sizeof(SDL_ShapeData)); result->driverdata = data; data->surface = NULL; window->shaper = result; resized_properly = DirectFB_ResizeWindowShape(window); SDL_assert(resized_properly == 0); return result; } int DirectFB_ResizeWindowShape(SDL_Window* window) { SDL_ShapeData* data = window->shaper->driverdata; SDL_assert(data != NULL); if (window->x != -1000) { window->shaper->userx = window->x; window->shaper->usery = window->y; } SDL_SetWindowPosition(window,-1000,-1000); return 0; } int DirectFB_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode) { if(shaper == NULL || shape == NULL || shaper->driverdata == NULL) return -1; if(shape->format->Amask == 0 && SDL_SHAPEMODEALPHA(shape_mode->mode)) return -2; if(shape->w != shaper->window->w || shape->h != shaper->window->h) return -3; { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(shaper->window); SDL_DFB_DEVICEDATA(display->device); Uint32 *pixels; Sint32 pitch; Uint32 h,w; Uint8 *src, *bitmap; DFBSurfaceDescription dsc; SDL_ShapeData *data = shaper->driverdata; SDL_DFB_RELEASE(data->surface); dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS; dsc.width = shape->w; dsc.height = shape->h; dsc.caps = DSCAPS_PREMULTIPLIED; dsc.pixelformat = DSPF_ARGB; SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc, &data->surface)); /* Assume that shaper->alphacutoff already has a value, because SDL_SetWindowShape() should have given it one. */ SDL_DFB_ALLOC_CLEAR(bitmap, shape->w * shape->h); SDL_CalculateShapeBitmap(shaper->mode,shape,bitmap,1); src = bitmap; SDL_DFB_CHECK(data->surface->Lock(data->surface, DSLF_WRITE | DSLF_READ, (void **) &pixels, &pitch)); h = shaper->window->h; while (h--) { for (w = 0; w < shaper->window->w; w++) { if (*src) pixels[w] = 0xFFFFFFFF; else pixels[w] = 0; src++; } pixels += (pitch >> 2); } SDL_DFB_CHECK(data->surface->Unlock(data->surface)); SDL_DFB_FREE(bitmap); /* FIXME: Need to call this here - Big ?? */ DirectFB_WM_RedrawLayout(SDL_GetDisplayForWindow(shaper->window)->device, shaper->window); } return 0; error: return -1; } #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_shape.c
C
apache-2.0
4,178
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_DirectFB_shape_h_ #define SDL_DirectFB_shape_h_ #include <directfb.h> #include "../SDL_sysvideo.h" #include "SDL_shape.h" typedef struct { IDirectFBSurface *surface; } SDL_ShapeData; extern SDL_WindowShaper* DirectFB_CreateShaper(SDL_Window* window); extern int DirectFB_ResizeWindowShape(SDL_Window* window); extern int DirectFB_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shapeMode); #endif /* SDL_DirectFB_shape_h_ */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_shape.h
C
apache-2.0
1,418
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB /* * #include "SDL_DirectFB_keyboard.h" */ #include "SDL_DirectFB_modes.h" #include "SDL_DirectFB_opengl.h" #include "SDL_DirectFB_window.h" #include "SDL_DirectFB_WM.h" /* DirectFB video driver implementation. */ #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <directfb.h> #include <directfb_version.h> #include <directfb_strings.h> #include "SDL_video.h" #include "SDL_mouse.h" #include "../SDL_sysvideo.h" #include "../SDL_pixels_c.h" #include "../../events/SDL_events_c.h" #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_events.h" #include "SDL_DirectFB_render.h" #include "SDL_DirectFB_mouse.h" #include "SDL_DirectFB_shape.h" #include "SDL_DirectFB_dyn.h" /* Initialization/Query functions */ static int DirectFB_VideoInit(_THIS); static void DirectFB_VideoQuit(_THIS); static int DirectFB_Available(void); static SDL_VideoDevice *DirectFB_CreateDevice(int devindex); VideoBootStrap DirectFB_bootstrap = { "directfb", "DirectFB", DirectFB_Available, DirectFB_CreateDevice }; static const DirectFBSurfaceDrawingFlagsNames(drawing_flags); static const DirectFBSurfaceBlittingFlagsNames(blitting_flags); static const DirectFBAccelerationMaskNames(acceleration_mask); /* DirectFB driver bootstrap functions */ static int DirectFB_Available(void) { if (!SDL_DirectFB_LoadLibrary()) return 0; SDL_DirectFB_UnLoadLibrary(); return 1; } static void DirectFB_DeleteDevice(SDL_VideoDevice * device) { SDL_DirectFB_UnLoadLibrary(); SDL_DFB_FREE(device->driverdata); SDL_DFB_FREE(device); } static SDL_VideoDevice * DirectFB_CreateDevice(int devindex) { SDL_VideoDevice *device; if (!SDL_DirectFB_LoadLibrary()) { return NULL; } /* Initialize all variables that we clean on shutdown */ SDL_DFB_ALLOC_CLEAR(device, sizeof(SDL_VideoDevice)); /* Set the function pointers */ device->VideoInit = DirectFB_VideoInit; device->VideoQuit = DirectFB_VideoQuit; device->GetDisplayModes = DirectFB_GetDisplayModes; device->SetDisplayMode = DirectFB_SetDisplayMode; device->PumpEvents = DirectFB_PumpEventsWindow; device->CreateSDLWindow = DirectFB_CreateWindow; device->CreateSDLWindowFrom = DirectFB_CreateWindowFrom; device->SetWindowTitle = DirectFB_SetWindowTitle; device->SetWindowIcon = DirectFB_SetWindowIcon; device->SetWindowPosition = DirectFB_SetWindowPosition; device->SetWindowSize = DirectFB_SetWindowSize; device->SetWindowOpacity = DirectFB_SetWindowOpacity; device->ShowWindow = DirectFB_ShowWindow; device->HideWindow = DirectFB_HideWindow; device->RaiseWindow = DirectFB_RaiseWindow; device->MaximizeWindow = DirectFB_MaximizeWindow; device->MinimizeWindow = DirectFB_MinimizeWindow; device->RestoreWindow = DirectFB_RestoreWindow; device->SetWindowGrab = DirectFB_SetWindowGrab; device->DestroyWindow = DirectFB_DestroyWindow; device->GetWindowWMInfo = DirectFB_GetWindowWMInfo; /* !!! FIXME: implement SetWindowBordered */ #if SDL_DIRECTFB_OPENGL device->GL_LoadLibrary = DirectFB_GL_LoadLibrary; device->GL_GetProcAddress = DirectFB_GL_GetProcAddress; device->GL_MakeCurrent = DirectFB_GL_MakeCurrent; device->GL_CreateContext = DirectFB_GL_CreateContext; device->GL_SetSwapInterval = DirectFB_GL_SetSwapInterval; device->GL_GetSwapInterval = DirectFB_GL_GetSwapInterval; device->GL_SwapWindow = DirectFB_GL_SwapWindow; device->GL_DeleteContext = DirectFB_GL_DeleteContext; #endif /* Shaped window support */ device->shape_driver.CreateShaper = DirectFB_CreateShaper; device->shape_driver.SetWindowShape = DirectFB_SetWindowShape; device->shape_driver.ResizeWindowShape = DirectFB_ResizeWindowShape; device->free = DirectFB_DeleteDevice; return device; error: if (device) SDL_free(device); return (0); } static void DirectFB_DeviceInformation(IDirectFB * dfb) { DFBGraphicsDeviceDescription desc; int n; dfb->GetDeviceDescription(dfb, &desc); SDL_DFB_LOG( "DirectFB Device Information"); SDL_DFB_LOG( "==========================="); SDL_DFB_LOG( "Name: %s", desc.name); SDL_DFB_LOG( "Vendor: %s", desc.vendor); SDL_DFB_LOG( "Driver Name: %s", desc.driver.name); SDL_DFB_LOG( "Driver Vendor: %s", desc.driver.vendor); SDL_DFB_LOG( "Driver Version: %d.%d", desc.driver.major, desc.driver.minor); SDL_DFB_LOG( "Video memory: %d", desc.video_memory); SDL_DFB_LOG( "Blitting flags:"); for (n = 0; blitting_flags[n].flag; n++) { if (desc.blitting_flags & blitting_flags[n].flag) SDL_DFB_LOG( " %s", blitting_flags[n].name); } SDL_DFB_LOG( "Drawing flags:"); for (n = 0; drawing_flags[n].flag; n++) { if (desc.drawing_flags & drawing_flags[n].flag) SDL_DFB_LOG( " %s", drawing_flags[n].name); } SDL_DFB_LOG( "Acceleration flags:"); for (n = 0; acceleration_mask[n].mask; n++) { if (desc.acceleration_mask & acceleration_mask[n].mask) SDL_DFB_LOG( " %s", acceleration_mask[n].name); } } static int readBoolEnv(const char *env_name, int def_val) { char *stemp; stemp = SDL_getenv(env_name); if (stemp) return atoi(stemp); else return def_val; } static int DirectFB_VideoInit(_THIS) { IDirectFB *dfb = NULL; DFB_DeviceData *devdata = NULL; DFBResult ret; SDL_DFB_ALLOC_CLEAR(devdata, sizeof(*devdata)); SDL_DFB_CHECKERR(DirectFBInit(NULL, NULL)); /* avoid switching to the framebuffer when we * are running X11 */ ret = readBoolEnv(DFBENV_USE_X11_CHECK , 1); if (ret) { if (SDL_getenv("DISPLAY")) DirectFBSetOption("system", "x11"); else DirectFBSetOption("disable-module", "x11input"); } devdata->use_linux_input = readBoolEnv(DFBENV_USE_LINUX_INPUT, 1); /* default: on */ if (!devdata->use_linux_input) { SDL_DFB_LOG("Disabling linux input\n"); DirectFBSetOption("disable-module", "linux_input"); } SDL_DFB_CHECKERR(DirectFBCreate(&dfb)); DirectFB_DeviceInformation(dfb); devdata->use_yuv_underlays = readBoolEnv(DFBENV_USE_YUV_UNDERLAY, 0); /* default: off */ devdata->use_yuv_direct = readBoolEnv(DFBENV_USE_YUV_DIRECT, 0); /* default is off! */ /* Create global Eventbuffer for axis events */ if (devdata->use_linux_input) { SDL_DFB_CHECKERR(dfb->CreateInputEventBuffer(dfb, DICAPS_ALL, DFB_TRUE, &devdata->events)); } else { SDL_DFB_CHECKERR(dfb->CreateInputEventBuffer(dfb, DICAPS_AXES /* DICAPS_ALL */ , DFB_TRUE, &devdata->events)); } /* simple window manager support */ devdata->has_own_wm = readBoolEnv(DFBENV_USE_WM, 0); devdata->initialized = 1; devdata->dfb = dfb; devdata->firstwin = NULL; devdata->grabbed_window = NULL; _this->driverdata = devdata; DirectFB_InitModes(_this); #if SDL_DIRECTFB_OPENGL DirectFB_GL_Initialize(_this); #endif DirectFB_InitMouse(_this); DirectFB_InitKeyboard(_this); return 0; error: SDL_DFB_FREE(devdata); SDL_DFB_RELEASE(dfb); return -1; } static void DirectFB_VideoQuit(_THIS) { DFB_DeviceData *devdata = (DFB_DeviceData *) _this->driverdata; DirectFB_QuitModes(_this); DirectFB_QuitKeyboard(_this); DirectFB_QuitMouse(_this); devdata->events->Reset(devdata->events); SDL_DFB_RELEASE(devdata->events); SDL_DFB_RELEASE(devdata->dfb); #if SDL_DIRECTFB_OPENGL DirectFB_GL_Shutdown(_this); #endif devdata->initialized = 0; } /* DirectFB driver general support functions */ static const struct { DFBSurfacePixelFormat dfb; Uint32 sdl; } pixelformat_tab[] = { { DSPF_RGB32, SDL_PIXELFORMAT_RGB888 }, /* 24 bit RGB (4 byte, nothing@24, red 8@16, green 8@8, blue 8@0) */ { DSPF_ARGB, SDL_PIXELFORMAT_ARGB8888 }, /* 32 bit ARGB (4 byte, alpha 8@24, red 8@16, green 8@8, blue 8@0) */ { DSPF_RGB16, SDL_PIXELFORMAT_RGB565 }, /* 16 bit RGB (2 byte, red 5@11, green 6@5, blue 5@0) */ { DSPF_RGB332, SDL_PIXELFORMAT_RGB332 }, /* 8 bit RGB (1 byte, red 3@5, green 3@2, blue 2@0) */ { DSPF_ARGB4444, SDL_PIXELFORMAT_ARGB4444 }, /* 16 bit ARGB (2 byte, alpha 4@12, red 4@8, green 4@4, blue 4@0) */ { DSPF_ARGB1555, SDL_PIXELFORMAT_ARGB1555 }, /* 16 bit ARGB (2 byte, alpha 1@15, red 5@10, green 5@5, blue 5@0) */ { DSPF_RGB24, SDL_PIXELFORMAT_RGB24 }, /* 24 bit RGB (3 byte, red 8@16, green 8@8, blue 8@0) */ { DSPF_RGB444, SDL_PIXELFORMAT_RGB444 }, /* 16 bit RGB (2 byte, nothing @12, red 4@8, green 4@4, blue 4@0) */ { DSPF_YV12, SDL_PIXELFORMAT_YV12 }, /* 12 bit YUV (8 bit Y plane followed by 8 bit quarter size V/U planes) */ { DSPF_I420,SDL_PIXELFORMAT_IYUV }, /* 12 bit YUV (8 bit Y plane followed by 8 bit quarter size U/V planes) */ { DSPF_YUY2, SDL_PIXELFORMAT_YUY2 }, /* 16 bit YUV (4 byte/ 2 pixel, macropixel contains CbYCrY [31:0]) */ { DSPF_UYVY, SDL_PIXELFORMAT_UYVY }, /* 16 bit YUV (4 byte/ 2 pixel, macropixel contains YCbYCr [31:0]) */ { DSPF_RGB555, SDL_PIXELFORMAT_RGB555 }, /* 16 bit RGB (2 byte, nothing @15, red 5@10, green 5@5, blue 5@0) */ { DSPF_ABGR, SDL_PIXELFORMAT_ABGR8888 }, /* 32 bit ABGR (4 byte, alpha 8@24, blue 8@16, green 8@8, red 8@0) */ #if (ENABLE_LUT8) { DSPF_LUT8, SDL_PIXELFORMAT_INDEX8 }, /* 8 bit LUT (8 bit color and alpha lookup from palette) */ #endif #if (DFB_VERSION_ATLEAST(1,2,0)) { DSPF_BGR555, SDL_PIXELFORMAT_BGR555 }, /* 16 bit BGR (2 byte, nothing @15, blue 5@10, green 5@5, red 5@0) */ #else { DSPF_UNKNOWN, SDL_PIXELFORMAT_BGR555 }, #endif /* Pfff ... nonmatching formats follow */ { DSPF_ALUT44, SDL_PIXELFORMAT_UNKNOWN }, /* 8 bit ALUT (1 byte, alpha 4@4, color lookup 4@0) */ { DSPF_A8, SDL_PIXELFORMAT_UNKNOWN }, /* 8 bit alpha (1 byte, alpha 8@0), e.g. anti-aliased glyphs */ { DSPF_AiRGB, SDL_PIXELFORMAT_UNKNOWN }, /* 32 bit ARGB (4 byte, inv. alpha 8@24, red 8@16, green 8@8, blue 8@0) */ { DSPF_A1, SDL_PIXELFORMAT_UNKNOWN }, /* 1 bit alpha (1 byte/ 8 pixel, most significant bit used first) */ { DSPF_NV12, SDL_PIXELFORMAT_UNKNOWN }, /* 12 bit YUV (8 bit Y plane followed by one 16 bit quarter size CbCr [15:0] plane) */ { DSPF_NV16, SDL_PIXELFORMAT_UNKNOWN }, /* 16 bit YUV (8 bit Y plane followed by one 16 bit half width CbCr [15:0] plane) */ { DSPF_ARGB2554, SDL_PIXELFORMAT_UNKNOWN }, /* 16 bit ARGB (2 byte, alpha 2@14, red 5@9, green 5@4, blue 4@0) */ { DSPF_NV21, SDL_PIXELFORMAT_UNKNOWN }, /* 12 bit YUV (8 bit Y plane followed by one 16 bit quarter size CrCb [15:0] plane) */ { DSPF_AYUV, SDL_PIXELFORMAT_UNKNOWN }, /* 32 bit AYUV (4 byte, alpha 8@24, Y 8@16, Cb 8@8, Cr 8@0) */ { DSPF_A4, SDL_PIXELFORMAT_UNKNOWN }, /* 4 bit alpha (1 byte/ 2 pixel, more significant nibble used first) */ { DSPF_ARGB1666, SDL_PIXELFORMAT_UNKNOWN }, /* 1 bit alpha (3 byte/ alpha 1@18, red 6@16, green 6@6, blue 6@0) */ { DSPF_ARGB6666, SDL_PIXELFORMAT_UNKNOWN }, /* 6 bit alpha (3 byte/ alpha 6@18, red 6@16, green 6@6, blue 6@0) */ { DSPF_RGB18, SDL_PIXELFORMAT_UNKNOWN }, /* 6 bit RGB (3 byte/ red 6@16, green 6@6, blue 6@0) */ { DSPF_LUT2, SDL_PIXELFORMAT_UNKNOWN }, /* 2 bit LUT (1 byte/ 4 pixel, 2 bit color and alpha lookup from palette) */ #if (DFB_VERSION_ATLEAST(1,3,0)) { DSPF_RGBA4444, SDL_PIXELFORMAT_UNKNOWN }, /* 16 bit RGBA (2 byte, red 4@12, green 4@8, blue 4@4, alpha 4@0) */ #endif #if (DFB_VERSION_ATLEAST(1,4,3)) { DSPF_RGBA5551, SDL_PIXELFORMAT_UNKNOWN }, /* 16 bit RGBA (2 byte, red 5@11, green 5@6, blue 5@1, alpha 1@0) */ { DSPF_YUV444P, SDL_PIXELFORMAT_UNKNOWN }, /* 24 bit full YUV planar (8 bit Y plane followed by an 8 bit Cb and an 8 bit Cr plane) */ { DSPF_ARGB8565, SDL_PIXELFORMAT_UNKNOWN }, /* 24 bit ARGB (3 byte, alpha 8@16, red 5@11, green 6@5, blue 5@0) */ { DSPF_AVYU, SDL_PIXELFORMAT_UNKNOWN }, /* 32 bit AVYU 4:4:4 (4 byte, alpha 8@24, Cr 8@16, Y 8@8, Cb 8@0) */ { DSPF_VYU, SDL_PIXELFORMAT_UNKNOWN }, /* 24 bit VYU 4:4:4 (3 byte, Cr 8@16, Y 8@8, Cb 8@0) */ #endif { DSPF_UNKNOWN, SDL_PIXELFORMAT_INDEX1LSB }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_INDEX1MSB }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_INDEX4LSB }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_INDEX4MSB }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_BGR24 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_BGR888 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_RGBA8888 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_BGRA8888 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_ARGB2101010 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_ABGR4444 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_ABGR1555 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_BGR565 }, { DSPF_UNKNOWN, SDL_PIXELFORMAT_YVYU }, /**< Packed mode: Y0+V0+Y1+U0 (1 pla */ }; Uint32 DirectFB_DFBToSDLPixelFormat(DFBSurfacePixelFormat pixelformat) { int i; for (i=0; pixelformat_tab[i].dfb != DSPF_UNKNOWN; i++) if (pixelformat_tab[i].dfb == pixelformat) { return pixelformat_tab[i].sdl; } return SDL_PIXELFORMAT_UNKNOWN; } DFBSurfacePixelFormat DirectFB_SDLToDFBPixelFormat(Uint32 format) { int i; for (i=0; pixelformat_tab[i].dfb != DSPF_UNKNOWN; i++) if (pixelformat_tab[i].sdl == format) { return pixelformat_tab[i].dfb; } return DSPF_UNKNOWN; } void DirectFB_SetSupportedPixelFormats(SDL_RendererInfo* ri) { int i, j; for (i=0, j=0; pixelformat_tab[i].dfb != DSPF_UNKNOWN; i++) if (pixelformat_tab[i].sdl != SDL_PIXELFORMAT_UNKNOWN) ri->texture_formats[j++] = pixelformat_tab[i].sdl; ri->num_texture_formats = j; } #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_video.c
C
apache-2.0
15,481
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #ifndef SDL_DirectFB_video_h_ #define SDL_DirectFB_video_h_ #include <directfb.h> #include <directfb_version.h> #include "../SDL_sysvideo.h" #include "SDL_scancode.h" #include "SDL_render.h" #define DFB_VERSIONNUM(X, Y, Z) \ ((X)*1000 + (Y)*100 + (Z)) #define DFB_COMPILEDVERSION \ DFB_VERSIONNUM(DIRECTFB_MAJOR_VERSION, DIRECTFB_MINOR_VERSION, DIRECTFB_MICRO_VERSION) #define DFB_VERSION_ATLEAST(X, Y, Z) \ (DFB_COMPILEDVERSION >= DFB_VERSIONNUM(X, Y, Z)) #if (DFB_VERSION_ATLEAST(1,0,0)) #ifdef SDL_VIDEO_OPENGL #define SDL_DIRECTFB_OPENGL 1 #endif #else #error "SDL_DIRECTFB: Please compile against libdirectfb version >= 1.0.0" #endif /* Set below to 1 to compile with (old) multi mice/keyboard api. Code left in * in case we see this again ... */ #define USE_MULTI_API (0) /* Support for LUT8/INDEX8 pixel format. * This is broken in DirectFB 1.4.3. It works in 1.4.0 and 1.4.5 * occurred. */ #if (DFB_COMPILEDVERSION == DFB_VERSIONNUM(1, 4, 3)) #define ENABLE_LUT8 (0) #else #define ENABLE_LUT8 (1) #endif #define DIRECTFB_DEBUG 1 #define DFBENV_USE_YUV_UNDERLAY "SDL_DIRECTFB_YUV_UNDERLAY" /* Default: off */ #define DFBENV_USE_YUV_DIRECT "SDL_DIRECTFB_YUV_DIRECT" /* Default: off */ #define DFBENV_USE_X11_CHECK "SDL_DIRECTFB_X11_CHECK" /* Default: on */ #define DFBENV_USE_LINUX_INPUT "SDL_DIRECTFB_LINUX_INPUT" /* Default: on */ #define DFBENV_USE_WM "SDL_DIRECTFB_WM" /* Default: off */ #define SDL_DFB_RELEASE(x) do { if ( (x) != NULL ) { SDL_DFB_CHECK(x->Release(x)); x = NULL; } } while (0) #define SDL_DFB_FREE(x) do { SDL_free((x)); (x) = NULL; } while (0) #define SDL_DFB_UNLOCK(x) do { if ( (x) != NULL ) { x->Unlock(x); } } while (0) #define SDL_DFB_CONTEXT "SDL_DirectFB" #define SDL_DFB_ERR(x...) SDL_LogError(SDL_LOG_CATEGORY_ERROR, x) #if (DIRECTFB_DEBUG) #define SDL_DFB_LOG(x...) SDL_LogInfo(SDL_LOG_CATEGORY_VIDEO, x) #define SDL_DFB_DEBUG(x...) SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, x) static SDL_INLINE DFBResult sdl_dfb_check(DFBResult ret, const char *src_file, int src_line) { if (ret != DFB_OK) { SDL_DFB_LOG("%s (%d):%s", src_file, src_line, DirectFBErrorString (ret) ); SDL_SetError("%s:%s", SDL_DFB_CONTEXT, DirectFBErrorString (ret) ); } return ret; } #define SDL_DFB_CHECK(x...) do { sdl_dfb_check( x, __FILE__, __LINE__); } while (0) #define SDL_DFB_CHECKERR(x...) do { if ( sdl_dfb_check( x, __FILE__, __LINE__) != DFB_OK ) goto error; } while (0) #else #define SDL_DFB_CHECK(x...) x #define SDL_DFB_CHECKERR(x...) do { if (x != DFB_OK ) goto error; } while (0) #define SDL_DFB_LOG(x...) do {} while (0) #define SDL_DFB_DEBUG(x...) do {} while (0) #endif #define SDL_DFB_CALLOC(r, n, s) \ do { \ r = SDL_calloc (n, s); \ if (!(r)) { \ SDL_DFB_ERR("Out of memory"); \ SDL_OutOfMemory(); \ goto error; \ } \ } while (0) #define SDL_DFB_ALLOC_CLEAR(r, s) SDL_DFB_CALLOC(r, 1, s) /* Private display data */ #define SDL_DFB_DEVICEDATA(dev) DFB_DeviceData *devdata = (dev ? (DFB_DeviceData *) ((dev)->driverdata) : NULL) #define DFB_MAX_SCREENS 10 typedef struct _DFB_KeyboardData DFB_KeyboardData; struct _DFB_KeyboardData { const SDL_Scancode *map; /* keyboard scancode map */ int map_size; /* size of map */ int map_adjust; /* index adjust */ int is_generic; /* generic keyboard */ int id; }; typedef struct _DFB_DeviceData DFB_DeviceData; struct _DFB_DeviceData { int initialized; IDirectFB *dfb; int num_mice; int mouse_id[0x100]; int num_keyboard; DFB_KeyboardData keyboard[10]; SDL_Window *firstwin; int use_yuv_underlays; int use_yuv_direct; int use_linux_input; int has_own_wm; /* window grab */ SDL_Window *grabbed_window; /* global events */ IDirectFBEventBuffer *events; }; Uint32 DirectFB_DFBToSDLPixelFormat(DFBSurfacePixelFormat pixelformat); DFBSurfacePixelFormat DirectFB_SDLToDFBPixelFormat(Uint32 format); void DirectFB_SetSupportedPixelFormats(SDL_RendererInfo *ri); #endif /* SDL_DirectFB_video_h_ */
YifuLiu/AliOS-Things
components/SDL2/src/video/directfb/SDL_DirectFB_video.h
C
apache-2.0
5,543