示例#1
0
static int
GLES_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                   const SDL_Rect * rect, const void *pixels, int pitch)
{
    GLES_RenderData *renderdata = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *data = (GLES_TextureData *) texture->driverdata;
    Uint8 *blob = NULL;
    Uint8 *src;
    int srcPitch;
    int y;

    GLES_ActivateRenderer(renderer);

    /* Bail out if we're supposed to update an empty rectangle */
    if (rect->w <= 0 || rect->h <= 0)
        return 0;

    /* Reformat the texture data into a tightly packed array */
    srcPitch = rect->w * SDL_BYTESPERPIXEL(texture->format);
    src = (Uint8 *)pixels;
    if (pitch != srcPitch)
    {
        blob = (Uint8 *)SDL_malloc(srcPitch * rect->h);
        if (!blob)
        {
            SDL_OutOfMemory();
            return -1;
        }
        src = blob;
        for (y = 0; y < rect->h; ++y)
        {
            SDL_memcpy(src, pixels, srcPitch);
            src += srcPitch;
            pixels = (Uint8 *)pixels + pitch;
        }
        src = blob;
    }

    /* Create a texture subimage with the supplied data */
    renderdata->glGetError();
    renderdata->glEnable(data->type);
    renderdata->glBindTexture(data->type, data->texture);
    renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    renderdata->glTexSubImage2D(data->type,
                    0,
                    rect->x,
                    rect->y,
                    rect->w,
                    rect->h,
                    data->format,
                    data->formattype,
                    src);
    if (blob) {
        SDL_free(blob);
    }

    if (renderdata->glGetError() != GL_NO_ERROR)
    {
        SDL_SetError("Failed to update texture");
        return -1;
    }
    return 0;
}
示例#2
0
static int
GLES_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    GLES_RenderData *renderdata = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *data;
    GLint internalFormat;
    GLenum format, type;
    int texture_w, texture_h;
    GLenum result;

    switch (texture->format) {
    case SDL_PIXELFORMAT_BGR24:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_BYTE;
        break;
#ifdef ANDROID
    case SDL_PIXELFORMAT_ABGR8888:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_BYTE;
        break;
    case SDL_PIXELFORMAT_BGR565:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_SHORT_5_6_5;
        break;
    case SDL_PIXELFORMAT_ABGR1555:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_SHORT_5_5_5_1;
        break;
    case SDL_PIXELFORMAT_ABGR4444:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_SHORT_4_4_4_4;
        break;

    case SDL_PIXELFORMAT_RGB565:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_SHORT_5_6_5;
        break;
#endif
    default:
        SDL_SetError("Unsupported by OpenGL ES texture format");
        return -1;
    }

    data = (GLES_TextureData *) SDL_calloc(1, sizeof(*data));
    if (!data) {
        SDL_OutOfMemory();
        return -1;
    }

    if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
        data->pitch = texture->w * SDL_BYTESPERPIXEL(texture->format);
        data->pixels = SDL_malloc(texture->h * data->pitch);
        if (!data->pixels) {
            SDL_OutOfMemory();
            SDL_free(data);
            return -1;
        }
    }

    texture->driverdata = data;

    renderdata->glGetError();
    renderdata->glEnable(GL_TEXTURE_2D);
    renderdata->glGenTextures(1, &data->texture);

    data->type = GL_TEXTURE_2D;
    /* no NPOV textures allowed in OpenGL ES (yet) */
    texture_w = power_of_2(texture->w);
    texture_h = power_of_2(texture->h);
    data->texw = (GLfloat) texture->w / texture_w;
    data->texh = (GLfloat) texture->h / texture_h;

    data->format = format;
    data->formattype = type;
    renderdata->glBindTexture(data->type, data->texture);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER,
                                GL_NEAREST);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER,
                                GL_NEAREST);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S,
                                GL_CLAMP_TO_EDGE);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T,
                                GL_CLAMP_TO_EDGE);

    renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w,
                             texture_h, 0, format, type, NULL);
    renderdata->glDisable(GL_TEXTURE_2D);

    result = renderdata->glGetError();
    if (result != GL_NO_ERROR) {
        GLES_SetError("glTexImage2D()", result);
        return -1;
    }
    return 0;
}
示例#3
0
static void Audio_DeleteDevice(SDL_AudioDevice *device)
{
	SDL_free(device->hidden);
	SDL_free(device);
	UnloadPulseLibrary();
}
示例#4
0
static void ANDROID_DeleteDevice(SDL_VideoDevice *device) {
	SDL_free(device->hidden);
	SDL_free(device);
}
int
main(int argc, char *argv[])
{
    int i, done;
    SDL_Event event;

	/* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }

    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        // needed vodoo to allow app to launch via OS X Finder
        if (SDL_strncmp(argv[i], "-psn", 4)==0) {
            consumed = 1;
        }
        if (consumed == 0) {
            consumed = -1;
        }
        if (consumed < 0) {
            SDL_Log("Usage: %s %s\n", argv[0], SDLTest_CommonUsage(state));
            quit(1);
        }
        i += consumed;
    }
    if (!SDLTest_CommonInit(state)) {
        quit(2);
    }

    for (i = 0; i < state->num_windows; ++i) {
        SDL_Renderer *renderer = state->renderers[i];
        SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
        SDL_RenderClear(renderer);
        SDL_RenderPresent(renderer);
    }

    SDL_EventState(SDL_DROPFILE, SDL_ENABLE);

    /* Main render loop */
    done = 0;
    while (!done) {
        /* Check for events */
        while (SDL_PollEvent(&event)) {
            SDLTest_CommonEvent(state, &event, &done);

            if (event.type == SDL_DROPFILE) {
                char *dropped_filedir = event.drop.file;
                SDL_Log("File dropped on window: %s", dropped_filedir);
                SDL_free(dropped_filedir);
            }
        }
    }

    quit(0);
    /* keep the compiler happy ... */
    return(0);
}
示例#6
0
static int
GLES_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    GLES_RenderData *renderdata = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *data;
    GLint internalFormat;
    GLenum format, type;
    int texture_w, texture_h;
    GLenum scaleMode;
    GLenum result;

    GLES_ActivateRenderer(renderer);

    switch (texture->format) {
    case SDL_PIXELFORMAT_ABGR8888:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_BYTE;
        break;
    default:
        return SDL_SetError("Texture format not supported");
    }

    data = (GLES_TextureData *) SDL_calloc(1, sizeof(*data));
    if (!data) {
        return SDL_OutOfMemory();
    }

    if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
        data->pitch = texture->w * SDL_BYTESPERPIXEL(texture->format);
        data->pixels = SDL_calloc(1, texture->h * data->pitch);
        if (!data->pixels) {
            SDL_free(data);
            return SDL_OutOfMemory();
        }
    }


    if (texture->access == SDL_TEXTUREACCESS_TARGET) {
        if (!renderdata->GL_OES_framebuffer_object_supported) {
            SDL_free(data);
            return SDL_SetError("GL_OES_framebuffer_object not supported");
        }
        data->fbo = GLES_GetFBO(renderer->driverdata, texture->w, texture->h);
    } else {
        data->fbo = NULL;
    }


    renderdata->glGetError();
    renderdata->glEnable(GL_TEXTURE_2D);
    renderdata->glGenTextures(1, &data->texture);
    result = renderdata->glGetError();
    if (result != GL_NO_ERROR) {
        SDL_free(data);
        return GLES_SetError("glGenTextures()", result);
    }

    data->type = GL_TEXTURE_2D;
    /* no NPOV textures allowed in OpenGL ES (yet) */
    texture_w = power_of_2(texture->w);
    texture_h = power_of_2(texture->h);
    data->texw = (GLfloat) texture->w / texture_w;
    data->texh = (GLfloat) texture->h / texture_h;

    data->format = format;
    data->formattype = type;
    scaleMode = GetScaleQuality();
    renderdata->glBindTexture(data->type, data->texture);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER, scaleMode);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER, scaleMode);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w,
                             texture_h, 0, format, type, NULL);
    renderdata->glDisable(GL_TEXTURE_2D);

    result = renderdata->glGetError();
    if (result != GL_NO_ERROR) {
        SDL_free(data);
        return GLES_SetError("glTexImage2D()", result);
    }

    texture->driverdata = data;
    return 0;
}
示例#7
0
WMcursor *GEM_CreateWMCursor(_THIS,
		Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
{
	WMcursor *cursor;
	MFORM *new_mform;
	int i;

#ifdef DEBUG_VIDEO_GEM
	Uint16 *data1, *mask1;

	printf("sdl:video:gem: create cursor\n");
#endif

	/* Check the size */
	if ( (w > MAXCURWIDTH) || (h > MAXCURHEIGHT) ) {
		SDL_SetError("Only cursors of dimension (%dx%d) are allowed",
							MAXCURWIDTH, MAXCURHEIGHT);
		return(NULL);
	}

	/* Allocate the cursor memory */
	cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor));
	if ( cursor == NULL ) {
		SDL_OutOfMemory();
		return(NULL);
	}

	/* Allocate mform */
	new_mform = (MFORM *)SDL_malloc(sizeof(MFORM));		
	if (new_mform == NULL) {
		SDL_free(cursor);
		SDL_OutOfMemory();
		return(NULL);
	}

	cursor->mform_p = new_mform;

	new_mform->mf_xhot = hot_x;
	new_mform->mf_yhot = hot_y;
	new_mform->mf_nplanes = 1;
	new_mform->mf_fg = 0;
	new_mform->mf_bg = 1;

	for (i=0;i<MAXCURHEIGHT;i++) {
		new_mform->mf_mask[i]=0;
		new_mform->mf_data[i]=0;
#ifdef DEBUG_VIDEO_GEM
		data1 = (Uint16 *) &data[i<<1];
		mask1 = (Uint16 *) &mask[i<<1];
		printf("sdl:video:gem: source: line %d: data=0x%04x, mask=0x%04x\n",
			i, data1[i], mask1[i]);
#endif
	}

	if (w<=8) {
		for (i=0;i<h;i++) {
			new_mform->mf_mask[i]= mask[i]<<8;
			new_mform->mf_data[i]= data[i]<<8;
		}
	} else {
		for (i=0;i<h;i++) {
			new_mform->mf_mask[i]= (mask[i<<1]<<8) | mask[(i<<1)+1];
			new_mform->mf_data[i]= (data[i<<1]<<8) | data[(i<<1)+1];
		}
	}

#ifdef DEBUG_VIDEO_GEM
	for (i=0; i<h ;i++) {
		printf("sdl:video:gem: cursor: line %d: data=0x%04x, mask=0x%04x\n",
			i, new_mform->mf_data[i], new_mform->mf_mask[i]);
	}

	printf("sdl:video:gem: CreateWMCursor(): done\n");
#endif

	return cursor;
}
SDL_Surface *WIMP_SetVideoMode(_THIS, SDL_Surface *current,
				int width, int height, int bpp, Uint32 flags)
{
   Uint32 Rmask = 0;
   Uint32 Gmask = 0;
   Uint32 Bmask = 0;
   char *buffer = NULL;
   int bytesPerPixel = 1;

   /* Don't support double buffering in Wimp mode */
   flags &= ~SDL_DOUBLEBUF;
   flags &= ~SDL_HWSURFACE;

   switch(bpp)
   {
	case 8:
		/* Emulated palette using ColourTrans */
		flags |= SDL_HWPALETTE;
		break;

	case 15:
	case 16:
		Bmask = 0x00007c00;
		Gmask = 0x000003e0;
		Rmask = 0x0000001f;
		bytesPerPixel = 2;
		break;

	case 32:
		Bmask = 0x00ff0000;
		Gmask = 0x0000ff00;
		Rmask = 0x000000ff;
		bytesPerPixel = 4;
		break;

	default:
		SDL_SetError("Pixel depth not supported");
		return NULL;
		break;
   }

/* 	printf("Setting mode %dx%d\n", width, height);*/

	/* Allocate the new pixel format for the screen */
	if ( ! SDL_ReallocFormat(current, bpp, Rmask, Gmask, Bmask, 0) ) {
		SDL_SetError("Couldn't allocate new pixel format for requested mode");
		return(NULL);
	}

	/* Set up the new mode framebuffer */
	current->w = width;
	this->hidden->height = current->h = height;

	if (bpp == 15) bpp = 16;
	buffer = WIMP_CreateBuffer(width, height, bpp);
	if (buffer == NULL)
	{
		SDL_SetError("Couldn't create sprite for video memory");
		return (NULL);
	}

	this->hidden->bank[0] = buffer + 60; /* Start of sprite data */
	if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */

	this->hidden->bank[1] = buffer;      /* Start of buffer */

	/* Remember sprite buffer so it can be freed later */
	if (this->hidden->alloc_bank) SDL_free(this->hidden->alloc_bank);
	this->hidden->alloc_bank = buffer;

	current->pitch = width * bytesPerPixel;
	if ((current->pitch & 3))
	{
		/* Sprites are 32bit word aligned */
		current->pitch += (4 - (current->pitch & 3));
	}

  	current->flags = flags | SDL_PREALLOC;

	WIMP_ReadModeInfo(this);
	
    SDL_memset(this->hidden->bank[0], 0, height * current->pitch);

	this->hidden->current_bank = 0;
	current->pixels = this->hidden->bank[0];


	if (WIMP_SetupWindow(this, current) == 0)
	{
		SDL_SetError("Unable to create window to display surface");
		return NULL;
	}

	/* Reset device functions for the wimp */
	WIMP_SetDeviceMode(this);

	/* Needs to set up plot info after window has been created */
	/* Not sure why, but plots don't work if I do it earlier */
	WIMP_SetupPlotInfo(this);

	/* Poll until window is shown */
	{
	   /* We wait until it gets the focus, but give up after 5 seconds
	      in case the focus is prevented in any way.
	   */
	   Uint32 now = SDL_GetTicks();
	   while (!hasFocus && SDL_GetTicks() - now < 5000)
	   {
	      WIMP_Poll(this, 0);
	   }
	}

	/* We're done */
	return(current);
}
示例#9
0
static VOID VManUpdateRects(SDL_PrivateVideoData *pPVData,
                             SDL_Rect *pSDLRectWin, // window rectangle on screen
                             SDL_Rect *pSDLRectFrame, // surface rectangle on window
                             int cRects, // number of record to update
                             SDL_Rect *pRects) // records to update
{
  BMAPINFO		bmiSrc;
  BMAPINFO		bmiDst;
  HWREQIN		sHWReqIn;
  BITBLTINFO		sBitbltInfo = { 0 };
  PRECTL		prectlScreenUpdate;
  RECTL			rclItem;
  RECTL			rclSrcBounds;
  RECTL			rclDstBounds;
  PPOINTL		pptlSrcOrg;
  PBLTRECT		pbrDst;
  ULONG			ulIdx;
  PVIDEOMODE		pVideoMode;

  bmiSrc.ulLength = sizeof(BMAPINFO);
  bmiSrc.ulType = BMAP_MEMORY;
  bmiSrc.ulWidth = pPVData->pSDLSurface->w;
  bmiSrc.ulHeight = pPVData->pSDLSurface->h;
  bmiSrc.ulBpp = pPVData->pSDLSurface->format->BitsPerPixel;
  bmiSrc.ulBytesPerLine = pPVData->pSDLSurface->pitch;
  bmiSrc.pBits = (PBYTE)pPVData->pSDLSurface->pixels;

  pVideoMode = pPVData->fFullscreen ?
                 pPVData->pFSVideoMode : pPVData->pDesktopVideoMode;
  bmiDst.ulLength = sizeof(BMAPINFO);
  bmiDst.ulType = BMAP_VRAM;
  bmiDst.pBits = (PBYTE)ulVRAMAddress;
  bmiDst.ulWidth = pVideoMode->sSDLRect.w;
  bmiDst.ulHeight = pVideoMode->sSDLRect.h;
  bmiDst.ulBpp = pVideoMode->uiBPP;
  bmiDst.ulBytesPerLine = pVideoMode->uiScanLineSize;

  // Fill lists: source coordinates (pptlSrcOrg), detination screen rectangles
  // (pbrDst), screen update rectangles (prectlScreenUpdate), calc source bound
  // (rclSrcBounds).

  pptlSrcOrg = SDL_malloc( cRects * sizeof(POINTL) );
  if ( pptlSrcOrg == NULL )
  {
    SDL_NotEnoughMemory();
    return;
  }
  pbrDst = SDL_malloc( cRects * sizeof(BLTRECT) );
  if ( pptlSrcOrg == NULL )
  {
    SDL_NotEnoughMemory();
    SDL_free( pptlSrcOrg );
    return;
  }
  prectlScreenUpdate = SDL_malloc( cRects * sizeof(RECTL) );
  if ( pptlSrcOrg == NULL )
  {
    SDL_NotEnoughMemory();
    SDL_free( pbrDst );
    SDL_free( pptlSrcOrg );
    return;
  }
  WinSetRectEmpty( pPVData->hab, &rclSrcBounds );

  for( ulIdx = 0; ulIdx < cRects; ulIdx++, pRects++ )
  {
    pptlSrcOrg[ulIdx].x = pRects->x;
    pptlSrcOrg[ulIdx].y = pRects->y;
    pbrDst[ulIdx].ulXOrg = pRects->x + pSDLRectWin->x + pSDLRectFrame->x;
    pbrDst[ulIdx].ulYOrg = pRects->y + pSDLRectWin->y + pSDLRectFrame->y;
    pbrDst[ulIdx].ulXExt = pRects->w;
    pbrDst[ulIdx].ulYExt = pRects->h;

    rclItem.xLeft = pRects->x;
    rclItem.xRight = pRects->x + pRects->w - 1;
    rclItem.yTop = bmiSrc.ulHeight - pRects->y;
    rclItem.yBottom = rclItem.yTop - pRects->h + 1;
    WinUnionRect( pPVData->hab, &rclSrcBounds, &rclSrcBounds, &rclItem );

    WinOffsetRect( pPVData->hab, &rclItem, pSDLRectWin->x + pSDLRectFrame->x,
                   bmiDst.ulHeight - (pSDLRectWin->y + pSDLRectFrame->y) );
    WinCopyRect( pPVData->hab, &prectlScreenUpdate[ulIdx], &rclItem );
  }

  if ( WinIsRectEmpty( pPVData->hab, &rclSrcBounds ) )
    return;

  // Detination bounding rectangle
  WinCopyRect( pPVData->hab, &rclDstBounds, &rclSrcBounds );
  WinOffsetRect( pPVData->hab, &rclDstBounds, pSDLRectWin->x + pSDLRectFrame->x,
                 bmiDst.ulHeight - (pSDLRectWin->y + pSDLRectFrame->y) );

  // Request HW
  sHWReqIn.ulLength = sizeof(HWREQIN);
  sHWReqIn.ulFlags = REQUEST_HW;
  sHWReqIn.cScrChangeRects = cRects;
  sHWReqIn.arectlScreen = prectlScreenUpdate;
  if ( pfnVMIEntry( 0, VMI_CMD_REQUESTHW, &sHWReqIn, NULL ) != RC_SUCCESS )
  {
    debug( "pfnVMIEntry(,VMI_CMD_REQUESTHW,,) failed" );
  }
  else
  {
    sBitbltInfo.ulLength = sizeof(BITBLTINFO);
    sBitbltInfo.ulBltFlags = BF_DEFAULT_STATE | BF_ROP_INCL_SRC | BF_PAT_HOLLOW;
    sBitbltInfo.cBlits = cRects;
    sBitbltInfo.ulROP = ROP_SRCCOPY;
    sBitbltInfo.pSrcBmapInfo = &bmiSrc;
    sBitbltInfo.pDstBmapInfo = &bmiDst;
    sBitbltInfo.prclSrcBounds = &rclSrcBounds;
    sBitbltInfo.prclDstBounds = &rclDstBounds;
    sBitbltInfo.aptlSrcOrg = pptlSrcOrg;
    sBitbltInfo.abrDst = pbrDst;

    if ( pfnVMIEntry( 0, VMI_CMD_BITBLT, &sBitbltInfo, NULL ) != RC_SUCCESS )
    {
      debug( "pfnVMIEntry(,VMI_CMD_BITBLT,,) failed" );
    }
    else
    {
      // Release HW
      sHWReqIn.ulFlags = 0;
      if ( pfnVMIEntry( 0, VMI_CMD_REQUESTHW, &sHWReqIn, NULL ) != RC_SUCCESS )
        debug( "pfnVMIEntry(,VMI_CMD_REQUESTHW,,) failed" );
    }
  }

  SDL_free( prectlScreenUpdate );
  SDL_free( pptlSrcOrg );
  SDL_free( pbrDst );
}
示例#10
0
void
Wayland_VideoQuit(_THIS)
{
    SDL_VideoData *data = _this->driverdata;
    int i, j;

    Wayland_FiniMouse ();

    for (i = 0; i < _this->num_displays; ++i) {
        SDL_VideoDisplay *display = &_this->displays[i];
        wl_output_destroy(display->driverdata);
        display->driverdata = NULL;

        for (j = display->num_display_modes; j--;) {
            display->display_modes[j].driverdata = NULL;
        }
        display->desktop_mode.driverdata = NULL;
    }

    Wayland_display_destroy_input(data);
    Wayland_display_destroy_pointer_constraints(data);
    Wayland_display_destroy_relative_pointer_manager(data);

    if (data->xkb_context) {
        WAYLAND_xkb_context_unref(data->xkb_context);
        data->xkb_context = NULL;
    }
#ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
    if (data->windowmanager)
        qt_windowmanager_destroy(data->windowmanager);

    if (data->surface_extension)
        qt_surface_extension_destroy(data->surface_extension);

    Wayland_touch_destroy(data);
#endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */

    if (data->shm)
        wl_shm_destroy(data->shm);

    if (data->cursor_theme)
        WAYLAND_wl_cursor_theme_destroy(data->cursor_theme);

    if (data->shell.wl)
        wl_shell_destroy(data->shell.wl);

    if (data->shell.xdg)
        xdg_wm_base_destroy(data->shell.xdg);

    if (data->shell.zxdg)
        zxdg_shell_v6_destroy(data->shell.zxdg);

    if (data->compositor)
        wl_compositor_destroy(data->compositor);

    if (data->registry)
        wl_registry_destroy(data->registry);

    if (data->display) {
        WAYLAND_wl_display_flush(data->display);
        WAYLAND_wl_display_disconnect(data->display);
    }

    SDL_free(data->classname);
    SDL_free(data);
    _this->driverdata = NULL;
}
示例#11
0
/* Toggle to window from full screen */
int WIMP_ToggleFromFullScreen(_THIS)
{     
   int width = this->screen->w;
   int height = this->screen->h;
   int bpp = this->screen->format->BitsPerPixel;
   char *buffer = NULL;
   char *old_bank[2];
   char *old_alloc_bank;

   /* Ensure flags are OK */
   this->screen->flags &= ~(SDL_DOUBLEBUF|SDL_HWSURFACE);

   if (this->hidden->bank[0] == this->hidden->alloc_bank || riscos_backbuffer == 0)
   {
      /* Need to create a sprite for the screen and copy the data to it */
      char *data;
      buffer = WIMP_CreateBuffer(width, height, bpp);
      data = buffer + 60;         /* Start of sprite data */
      if (bpp == 8) data += 2048;  /* 8bpp sprite have palette first */

      if (buffer == NULL) return 0;
      SDL_memcpy(data, this->hidden->bank[0], width * height * this->screen->format->BytesPerPixel);
   }
   /* else We've switch to full screen before so we already have a sprite */

   old_bank[0] = this->hidden->bank[0];
   old_bank[1] = this->hidden->bank[1];
   old_alloc_bank = this->hidden->alloc_bank;

   if (buffer != NULL) this->hidden->alloc_bank = buffer;

   this->hidden->bank[1] = this->hidden->alloc_bank;
   this->hidden->bank[0] = this->hidden->bank[1] + 60; /* Start of sprite data */
   if (bpp == 8) this->hidden->bank[0] += 2048; /* 8bpp sprite have palette first */

   this->hidden->current_bank = 0;
   this->screen->pixels = this->hidden->bank[0];

   RISCOS_RestoreWimpMode();
   WIMP_ReadModeInfo(this);
   if (WIMP_SetupWindow(this, this->screen))
   {
      WIMP_SetDeviceMode(this);
      WIMP_SetupPlotInfo(this);

      if (riscos_backbuffer == 0) riscos_backbuffer = 1;

      if (buffer && old_alloc_bank) SDL_free(old_alloc_bank);

      return 1;
   } else
   {
      /* Drop back to full screen mode on failure */
      this->hidden->bank[0] = old_bank[0];
      this->hidden->bank[1] = old_bank[1];
      this->hidden->alloc_bank = old_alloc_bank;
      if (buffer) SDL_free(buffer);
      
      RISCOS_StoreWimpMode();
      FULLSCREEN_SetMode(width, height, bpp);
   }

   return 0;
}
示例#12
0
int
KMSDRM_CreateWindow(_THIS, SDL_Window * window)
{
    SDL_WindowData *wdata;
    SDL_VideoDisplay *display;
    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
    Uint32 surface_fmt, surface_flags;

    /* Allocate window internal data */
    wdata = (SDL_WindowData *) SDL_calloc(1, sizeof(SDL_WindowData));
    if (wdata == NULL) {
        SDL_OutOfMemory();
        goto error;
    }

    wdata->waiting_for_flip = SDL_FALSE;
    display = SDL_GetDisplayForWindow(window);

    /* Windows have one size for now */
    window->w = display->desktop_mode.w;
    window->h = display->desktop_mode.h;

    /* Maybe you didn't ask for a fullscreen OpenGL window, but that's what you get */
    window->flags |= (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL);

    surface_fmt = GBM_FORMAT_XRGB8888;
    surface_flags = GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING;

    if (!KMSDRM_gbm_device_is_format_supported(vdata->gbm, surface_fmt, surface_flags)) {
        SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "GBM surface format not supported. Trying anyway.");
    }
    wdata->gs = KMSDRM_gbm_surface_create(vdata->gbm, window->w, window->h, surface_fmt, surface_flags);

#if SDL_VIDEO_OPENGL_EGL
    if (!_this->egl_data) {
        if (SDL_GL_LoadLibrary(NULL) < 0) {
            goto error;
        }
    }
    wdata->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) wdata->gs);

    if (wdata->egl_surface == EGL_NO_SURFACE) {
        SDL_SetError("Could not create EGL window surface");
        goto error;
    }
#endif /* SDL_VIDEO_OPENGL_EGL */

    /* In case we want low-latency, double-buffer video, we take note here */
    wdata->double_buffer = SDL_FALSE;
    if (SDL_GetHintBoolean(SDL_HINT_VIDEO_DOUBLE_BUFFER, SDL_FALSE)) {
        wdata->double_buffer = SDL_TRUE;
    }

    /* Window is created, but we have yet to set up CRTC to one of the GBM buffers if we want
       drmModePageFlip to work, and we can't do it until EGL is completely setup, because we
       need to do eglSwapBuffers so we can get a valid GBM buffer object to call
       drmModeSetCrtc on it. */
    wdata->crtc_ready = SDL_FALSE;

    /* Setup driver data for this window */
    window->driverdata = wdata;

    /* One window, it always has focus */
    SDL_SetMouseFocus(window);
    SDL_SetKeyboardFocus(window);

    /* Window has been successfully created */
    return 0;

error:
    if (wdata != NULL) {
#if SDL_VIDEO_OPENGL_EGL
        if (wdata->egl_surface != EGL_NO_SURFACE)
            SDL_EGL_DestroySurface(_this, wdata->egl_surface);
#endif /* SDL_VIDEO_OPENGL_EGL */
        if (wdata->gs != NULL)
            KMSDRM_gbm_surface_destroy(wdata->gs);
        SDL_free(wdata);
    }
    return -1;
}
示例#13
0
int
KMSDRM_VideoInit(_THIS)
{
    int i;
    int ret = 0;
    char *devname;
    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
    drmModeRes *resources = NULL;
    drmModeConnector *connector = NULL;
    drmModeEncoder *encoder = NULL;
    SDL_DisplayMode current_mode;
    SDL_VideoDisplay display;

    /* Allocate display internal data */
    SDL_DisplayData *data = (SDL_DisplayData *) SDL_calloc(1, sizeof(SDL_DisplayData));
    if (data == NULL) {
        return SDL_OutOfMemory();
    }

    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "KMSDRM_VideoInit()");

    /* Open /dev/dri/cardNN */
    devname = (char *) SDL_calloc(1, 16);
    if (devname == NULL) {
        ret = SDL_OutOfMemory();
        goto cleanup;
    }
    SDL_snprintf(devname, 16, "/dev/dri/card%d", vdata->devindex);
    vdata->drm_fd = open(devname, O_RDWR | O_CLOEXEC);
    SDL_free(devname);

    if (vdata->drm_fd < 0) {
        ret = SDL_SetError("Could not open /dev/dri/card%d.", vdata->devindex);
        goto cleanup;
    }
    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Opened DRM FD (%d)", vdata->drm_fd);

    vdata->gbm = KMSDRM_gbm_create_device(vdata->drm_fd);
    if (vdata->gbm == NULL) {
        ret = SDL_SetError("Couldn't create gbm device.");
        goto cleanup;
    }

    /* Find the first available connector with modes */
    resources = KMSDRM_drmModeGetResources(vdata->drm_fd);
    if (!resources) {
        ret = SDL_SetError("drmModeGetResources(%d) failed", vdata->drm_fd);
        goto cleanup;
    }

    for (i = 0; i < resources->count_connectors; i++) {
        connector = KMSDRM_drmModeGetConnector(vdata->drm_fd, resources->connectors[i]);
        if (connector == NULL)
            continue;

        if (connector->connection == DRM_MODE_CONNECTED &&
            connector->count_modes > 0) {
            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Found connector %d with %d modes.",
                         connector->connector_id, connector->count_modes);
            vdata->saved_conn_id = connector->connector_id;
            break;
        }

        KMSDRM_drmModeFreeConnector(connector);
        connector = NULL;
    }

    if (i == resources->count_connectors) {
        ret = SDL_SetError("No currently active connector found.");
        goto cleanup;
    }

    for (i = 0; i < resources->count_encoders; i++) {
        encoder = KMSDRM_drmModeGetEncoder(vdata->drm_fd, resources->encoders[i]);

        if (encoder == NULL)
            continue;

        if (encoder->encoder_id == connector->encoder_id) {
            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Found encoder %d.", encoder->encoder_id);
            data->encoder_id = encoder->encoder_id;
            break;
        }

        KMSDRM_drmModeFreeEncoder(encoder);
        encoder = NULL;
    }

    if (i == resources->count_encoders) {
        ret = SDL_SetError("No connected encoder found.");
        goto cleanup;
    }

    vdata->saved_crtc = KMSDRM_drmModeGetCrtc(vdata->drm_fd, encoder->crtc_id);
    if (vdata->saved_crtc == NULL) {
        ret = SDL_SetError("No CRTC found.");
        goto cleanup;
    }
    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Saved crtc_id %u, fb_id %u, (%u,%u), %ux%u",
                 vdata->saved_crtc->crtc_id, vdata->saved_crtc->buffer_id, vdata->saved_crtc->x,
                 vdata->saved_crtc->y, vdata->saved_crtc->width, vdata->saved_crtc->height);
    data->crtc_id = encoder->crtc_id;
    data->cur_mode = vdata->saved_crtc->mode;
    vdata->crtc_id = encoder->crtc_id;

    SDL_zero(current_mode);

    current_mode.w = vdata->saved_crtc->mode.hdisplay;
    current_mode.h = vdata->saved_crtc->mode.vdisplay;
    current_mode.refresh_rate = vdata->saved_crtc->mode.vrefresh;

    /* FIXME ?
    drmModeFB *fb = drmModeGetFB(vdata->drm_fd, vdata->saved_crtc->buffer_id);
    current_mode.format = drmToSDLPixelFormat(fb->bpp, fb->depth);
    drmModeFreeFB(fb);
    */
    current_mode.format = SDL_PIXELFORMAT_ARGB8888;

    current_mode.driverdata = NULL;

    SDL_zero(display);
    display.desktop_mode = current_mode;
    display.current_mode = current_mode;

    display.driverdata = data;
    /* SDL_VideoQuit will later SDL_free(display.driverdata) */
    SDL_AddVideoDisplay(&display);

    /* Setup page flip handler */
    vdata->drm_pollfd.fd = vdata->drm_fd;
    vdata->drm_pollfd.events = POLLIN;
    vdata->drm_evctx.version = DRM_EVENT_CONTEXT_VERSION;
    vdata->drm_evctx.page_flip_handler = KMSDRM_FlipHandler;

#ifdef SDL_INPUT_LINUXEV
    SDL_EVDEV_Init();
#endif

    KMSDRM_InitMouse(_this);

cleanup:
    if (encoder != NULL)
        KMSDRM_drmModeFreeEncoder(encoder);
    if (connector != NULL)
        KMSDRM_drmModeFreeConnector(connector);
    if (resources != NULL)
        KMSDRM_drmModeFreeResources(resources);

    if (ret != 0) {
        /* Error (complete) cleanup */
        SDL_free(data);
        if(vdata->saved_crtc != NULL) {
            KMSDRM_drmModeFreeCrtc(vdata->saved_crtc);
            vdata->saved_crtc = NULL;
        }
        if (vdata->gbm != NULL) {
            KMSDRM_gbm_device_destroy(vdata->gbm);
            vdata->gbm = NULL;
        }
        if (vdata->drm_fd >= 0) {
            close(vdata->drm_fd);
            vdata->drm_fd = -1;
        }
    }
    return ret;
}
示例#14
0
static SDL_VideoDevice *
KMSDRM_Create(int devindex)
{
    SDL_VideoDevice *device;
    SDL_VideoData *vdata;

    if (!devindex || (devindex > 99)) {
        devindex = get_driindex();
    }

    if (devindex < 0) {
        SDL_SetError("devindex (%d) must be between 0 and 99.\n", devindex);
        return NULL;
    }

    if (!SDL_KMSDRM_LoadSymbols()) {
        return NULL;
    }

    /* Initialize SDL_VideoDevice structure */
    device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice));
    if (device == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    /* Initialize internal data */
    vdata = (SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData));
    if (vdata == NULL) {
        SDL_OutOfMemory();
        goto cleanup;
    }
    vdata->devindex = devindex;
    vdata->drm_fd = -1;

    device->driverdata = vdata;

    /* Setup amount of available displays and current display */
    device->num_displays = 0;

    /* Set device free function */
    device->free = KMSDRM_Destroy;

    /* Setup all functions which we can handle */
    device->VideoInit = KMSDRM_VideoInit;
    device->VideoQuit = KMSDRM_VideoQuit;
    device->GetDisplayModes = KMSDRM_GetDisplayModes;
    device->SetDisplayMode = KMSDRM_SetDisplayMode;
    device->CreateSDLWindow = KMSDRM_CreateWindow;
    device->CreateSDLWindowFrom = KMSDRM_CreateWindowFrom;
    device->SetWindowTitle = KMSDRM_SetWindowTitle;
    device->SetWindowIcon = KMSDRM_SetWindowIcon;
    device->SetWindowPosition = KMSDRM_SetWindowPosition;
    device->SetWindowSize = KMSDRM_SetWindowSize;
    device->ShowWindow = KMSDRM_ShowWindow;
    device->HideWindow = KMSDRM_HideWindow;
    device->RaiseWindow = KMSDRM_RaiseWindow;
    device->MaximizeWindow = KMSDRM_MaximizeWindow;
    device->MinimizeWindow = KMSDRM_MinimizeWindow;
    device->RestoreWindow = KMSDRM_RestoreWindow;
    device->SetWindowGrab = KMSDRM_SetWindowGrab;
    device->DestroyWindow = KMSDRM_DestroyWindow;
    device->GetWindowWMInfo = KMSDRM_GetWindowWMInfo;
#if SDL_VIDEO_OPENGL_EGL
    device->GL_LoadLibrary = KMSDRM_GLES_LoadLibrary;
    device->GL_GetProcAddress = KMSDRM_GLES_GetProcAddress;
    device->GL_UnloadLibrary = KMSDRM_GLES_UnloadLibrary;
    device->GL_CreateContext = KMSDRM_GLES_CreateContext;
    device->GL_MakeCurrent = KMSDRM_GLES_MakeCurrent;
    device->GL_SetSwapInterval = KMSDRM_GLES_SetSwapInterval;
    device->GL_GetSwapInterval = KMSDRM_GLES_GetSwapInterval;
    device->GL_SwapWindow = KMSDRM_GLES_SwapWindow;
    device->GL_DeleteContext = KMSDRM_GLES_DeleteContext;
#endif

    device->PumpEvents = KMSDRM_PumpEvents;

    return device;

cleanup:
    if (device != NULL)
        SDL_free(device);
    if (vdata != NULL)
        SDL_free(vdata);
    return NULL;
}
示例#15
0
static void
DUMMY_DeleteDevice(SDL_VideoDevice * device)
{
    SDL_free(device);
}
static void
Wayland_DeleteDevice(SDL_VideoDevice *device)
{
    SDL_free(device);
    SDL_WAYLAND_UnloadSymbols();
}
示例#17
0
static SDL_Surface *PZM_SetVideoMode(_THIS, SDL_Surface *current,
				     int width, int height, int bpp, Uint32 flags)
{
	Uint32 rmask = 0, gmask = 0, bmask = 0;

	width = ( width > SCREEN_WIDTH ) ? SCREEN_WIDTH : width;
	height = ( height > SCREEN_HEIGHT ) ? SCREEN_HEIGHT : height;
	bpp = ( bpp < 16 ) ? 8 : 16;

	PZM_DPRINT("Initializing display (%dx%dx%d)", width, height, bpp);

	this->info.current_w = width;
	this->info.current_h = height;

	if ( width < SCREEN_WIDTH || height < SCREEN_HEIGHT ) {
		int offset_x = (SCREEN_WIDTH - width) / 2;
		int offset_y = (SCREEN_HEIGHT - height) / 2;
		/*this->hidden->offset = this->hidden->cx
				     ? (int)PZM_PIXEL_ADDR(0, offset_x, offset_y, 2 * SCREEN_WIDTH, 2)
				     : (int)PZM_PIXEL_ADDR(0, offset_x / 2, offset_y, SCREEN_WIDTH / 2, 1);
		this->hidden->offset_x = offset_x;
		memset(VRAM, 0, SCREEN_BYTES_SIZE);
	} else
		this->hidden->offset = this->hidden->offset_x = 0;*/
		rmask = PZM_RMASK16;
		gmask = PZM_GMASK16;
		bmask = PZM_BMASK16;
	}

	if ( this->hidden->buffer ) {
		SDL_free( this->hidden->buffer );
	}

	this->hidden->buffer = SDL_malloc((bpp / 8) * width * height);
	if ( ! this->hidden->buffer ) {
		SDL_SetError("Couldn't allocate buffer for requested mode");
		return(NULL);
	}

	memset(this->hidden->buffer, 0, (bpp / 8) * width * height);

	/* Allocate the new pixel format for the screen */
	if ( ! SDL_ReallocFormat(current, bpp, rmask, gmask, bmask, 0) ) {
		SDL_free(this->hidden->buffer);
		this->hidden->buffer = NULL;
		SDL_SetError("Couldn't allocate new pixel format for requested mode");
		return(NULL);
	}

	/* Set up the new mode framebuffer */
	current->flags = flags;
	this->hidden->w = current->w = width;
	this->hidden->h = current->h = height;
	current->pitch = (bpp / 8) * current->w;
	current->pixels = this->hidden->buffer;

	PZM_DPRINT("Done (0x%p)", current);

	/* We're done */
	return(current);
}
示例#18
0
static int SDLCALL
windows_file_open(SDL_RWops * context, const char *filename, const char *mode)
{
    UINT old_error_mode;
    HANDLE h;
    DWORD r_right, w_right;
    DWORD must_exist, truncate;
    int a_mode;

    if (!context)
        return -1;              /* failed (invalid call) */

    context->hidden.windowsio.h = INVALID_HANDLE_VALUE;   /* mark this as unusable */
    context->hidden.windowsio.buffer.data = NULL;
    context->hidden.windowsio.buffer.size = 0;
    context->hidden.windowsio.buffer.left = 0;

    /* "r" = reading, file must exist */
    /* "w" = writing, truncate existing, file may not exist */
    /* "r+"= reading or writing, file must exist            */
    /* "a" = writing, append file may not exist             */
    /* "a+"= append + read, file may not exist              */
    /* "w+" = read, write, truncate. file may not exist    */

    must_exist = (SDL_strchr(mode, 'r') != NULL) ? OPEN_EXISTING : 0;
    truncate = (SDL_strchr(mode, 'w') != NULL) ? CREATE_ALWAYS : 0;
    r_right = (SDL_strchr(mode, '+') != NULL
               || must_exist) ? GENERIC_READ : 0;
    a_mode = (SDL_strchr(mode, 'a') != NULL) ? OPEN_ALWAYS : 0;
    w_right = (a_mode || SDL_strchr(mode, '+')
               || truncate) ? GENERIC_WRITE : 0;

    if (!r_right && !w_right)   /* inconsistent mode */
        return -1;              /* failed (invalid call) */

    context->hidden.windowsio.buffer.data =
        (char *) SDL_malloc(READAHEAD_BUFFER_SIZE);
    if (!context->hidden.windowsio.buffer.data) {
        return SDL_OutOfMemory();
    }
    /* Do not open a dialog box if failure */
    old_error_mode =
        SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

    {
        LPTSTR tstr = WIN_UTF8ToString(filename);
        h = CreateFile(tstr, (w_right | r_right),
                       (w_right) ? 0 : FILE_SHARE_READ, NULL,
                       (must_exist | truncate | a_mode),
                       FILE_ATTRIBUTE_NORMAL, NULL);
        SDL_free(tstr);
    }

    /* restore old behavior */
    SetErrorMode(old_error_mode);

    if (h == INVALID_HANDLE_VALUE) {
        SDL_free(context->hidden.windowsio.buffer.data);
        context->hidden.windowsio.buffer.data = NULL;
        SDL_SetError("Couldn't open %s", filename);
        return -2;              /* failed (CreateFile) */
    }
    context->hidden.windowsio.h = h;
    context->hidden.windowsio.append = a_mode ? SDL_TRUE : SDL_FALSE;

    return 0;                   /* ok */
}
/* Function to close a joystick after use */
void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
{
	if(joystick->hwdata)
		SDL_free(joystick->hwdata);
	return;
}
示例#20
0
void
SDL_FreeRW(SDL_RWops * area)
{
    SDL_free(area);
}
示例#21
0
static void
DSOUND_FreeDeviceHandle(void *handle)
{
    SDL_free(handle);
}
示例#22
0
static void Audio_DeleteDevice(SDL_AudioDevice *device)
{
	SDL_free(device->hidden);
	SDL_free(device);
}
示例#23
0
/* Call to render the next GL frame */
extern void JAVA_EXPORT_NAME(DemoRenderer_nativeRender)(JNIEnv* env, jobject thiz) {
	// Set up an array of values to use as the sprite vertices.
	static GLfloat vertices[] = { 0, 0, 1, 0, 0, 1, 1, 1, };

	// Set up an array of values for the texture coordinates.
	static GLfloat texcoords[] = { 0, 0, 1, 0, 0, 1, 1, 1, };

	static GLint texcoordsCrop[] = { 0, 0, 0, 0, };

	static float clearColor = 0.0f;
	static int clearColorDir = 1;
	int textX, textY;
	void * memBufferTemp;

	if (memBuffer && openglInitialized != GL_State_Uninit2) {
		if (openglInitialized == GL_State_Init) {

			__android_log_print(ANDROID_LOG_INFO, "libSDL", " sWindowWidth=%i, sWindowHeight=%i, memX=%i, memY=%i", sWindowWidth,
					sWindowHeight, memX, memY);

			openglInitialized = GL_State_Ready;

			// Texture sizes should be 2^n
			textX = memX;
			textY = memY;

			if (textX <= 256)
				textX = 256;
			else if (textX <= 512)
				textX = 512;
			else
				textX = 1024;

			if (textY <= 256)
				textY = 256;
			else if (textY <= 512)
				textY = 512;
			else
				textY = 1024;

			//glViewport(0, 0, textX, textY);
			glViewport(0, 0, sWindowWidth, sWindowHeight);

			glClearColor(0, 0, 0, 0);
			// Set projection
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
#if defined(GL_VERSION_ES_CM_1_0)
#define glOrtho glOrthof
#endif
			glOrtho(0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f);
			//glOrthof(0.0f, sWindowWidth, sWindowHeight, 0.0f, -1.0f, 1.0f);

			// Now Initialize modelview matrix
			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();

			glDisable(GL_DEPTH_TEST);
			glDisable(GL_CULL_FACE);
			glDisable(GL_DITHER);
			glDisable(GL_MULTISAMPLE);

			glEnable(GL_TEXTURE_2D);

			glGenTextures(1, &texture);

			glBindTexture(GL_TEXTURE_2D, texture);

			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

			void * textBuffer = SDL_malloc(textX * textY * 2);
			SDL_memset(textBuffer, 0, textX * textY * 2);

			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textX, textY, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textBuffer);

			glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

			glEnableClientState(GL_VERTEX_ARRAY);
			glEnableClientState(GL_TEXTURE_COORD_ARRAY);

			// Make the texture fit the device screen if required
			if (autoResizingActivated) {
				GLfloat ratioX = 1.0f;
				GLfloat ratioY = 1.0f;
				//if (memX > sWindowWidth) {
					ratioX = ((GLfloat) memX) / ((GLfloat) textX);
				//}
				//if (memY > sWindowHeight) {
					ratioY = ((GLfloat) memY) / ((GLfloat) textY);
				//}
				texcoords[0] *= ratioX;
				texcoords[1] *= ratioY;
				texcoords[2] *= ratioX;
				texcoords[3] *= ratioY;
				texcoords[4] *= ratioX;
				texcoords[5] *= ratioY;
				texcoords[6] *= ratioX;
				texcoords[7] *= ratioY;
				//__android_log_print(ANDROID_LOG_INFO, "libSDL", "textX=%i textY=%i, ratioX=%f ratioY=%f", textX, textY, ratioX , ratioY);
			}

			glVertexPointer(2, GL_FLOAT, 0, vertices);
			glTexCoordPointer(2, GL_FLOAT, 0, texcoords);

			glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

			// GLES extension (should be faster)
			//			texcoordsCrop[0] = 0;
			//			texcoordsCrop[1] = memY;
			//			texcoordsCrop[2] = memX;
			//			texcoordsCrop[3] = -memY;
			//			glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, texcoordsCrop);

			glFinish();

			SDL_free(textBuffer);
		} else if (openglInitialized == GL_State_Uninit) {
			openglInitialized = GL_State_Uninit2;

			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
			glDisableClientState(GL_VERTEX_ARRAY);

			glDeleteTextures(1, &texture);

			return;
		}

//		if (WaitForNativeRender) {
//			SDL_mutexP(WaitForNativeRender);
//
//			WaitForNativeRenderState = Render_State_Finished;
//			SDL_CondSignal(WaitForNativeRender1);
//
//			while (WaitForNativeRenderState != Render_State_Started) {
//				if (SDL_CondWaitTimeout(WaitForNativeRender1, WaitForNativeRender, 1000) != 0) {
//					__android_log_print(ANDROID_LOG_INFO, "libSDL", "Frame failed to render");
//					SDL_mutexV(WaitForNativeRender);
//					return;
//				}
//			}
//
//			memBufferTemp = memBuffer;
//
//			WaitForNativeRenderState = Render_State_Processing;
//
//			SDL_CondSignal(WaitForNativeRender1);
//
//			SDL_mutexV(WaitForNativeRender);
//		} else {
			memBufferTemp = memBuffer;
//		}

		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, memX, memY, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, memBufferTemp);

		//glClearColor(0, 1.0f, 0, 1.0f);
		//glClear(GL_COLOR_BUFFER_BIT);

		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
//		glDrawTexiOES(0, sWindowHeight-memY, 1, memX, memY); // GLES extension (should be faster)
		//__android_log_print(ANDROID_LOG_INFO, "libSDL", "glDrawTexiOES(%i, 1, %i, %i)", sWindowHeight-memY ,memX, memY);
		glFinish(); //glFlush();

	} else {
		/*
		 // Flash the screen
		 if( clearColor >= 1.0f )
		 clearColorDir = -1;
		 else if( clearColor <= 0.0f )
		 clearColorDir = 1;

		 clearColor += (float)clearColorDir * 0.01f;
		 glClearColor(clearColor,clearColor,clearColor,0);
		 glClear(GL_COLOR_BUFFER_BIT);
		 SDL_Delay(50);
		 */
	}
}
示例#24
0
int
SDL_setenv(const char *name, const char *value, int overwrite)
{
    int added;
    int len, i;
    char **new_env;
    char *new_variable;

    /* A little error checking */
    if (!name || !value) {
        return (-1);
    }

    /* See if it already exists */
    if (!overwrite && SDL_getenv(name)) {
        return 0;
    }

    /* Allocate memory for the variable */
    len = SDL_strlen(name) + SDL_strlen(value) + 2;
    new_variable = (char *) SDL_malloc(len);
    if (!new_variable) {
        return (-1);
    }

    SDL_snprintf(new_variable, len, "%s=%s", name, value);
    value = new_variable + SDL_strlen(name) + 1;
    name = new_variable;

    /* Actually put it into the environment */
    added = 0;
    i = 0;
    if (SDL_env) {
        /* Check to see if it's already there... */
        len = (value - name);
        for (; SDL_env[i]; ++i) {
            if (SDL_strncmp(SDL_env[i], name, len) == 0) {
                break;
            }
        }
        /* If we found it, just replace the entry */
        if (SDL_env[i]) {
            SDL_free(SDL_env[i]);
            SDL_env[i] = new_variable;
            added = 1;
        }
    }

    /* Didn't find it in the environment, expand and add */
    if (!added) {
        new_env = SDL_realloc(SDL_env, (i + 2) * sizeof(char *));
        if (new_env) {
            SDL_env = new_env;
            SDL_env[i++] = new_variable;
            SDL_env[i++] = (char *) 0;
            added = 1;
        } else {
            SDL_free(new_variable);
        }
    }
    return (added ? 0 : -1);
}
示例#25
0
SDL_AudioSpec *Mix_LoadMP3_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
{
	/* note: spec is initialized to mixer spec */

#if defined(MP3_MUSIC)
	SMPEG* mp3 = 0;
	SMPEG_Info info;
#elif defined(MP3_MAD_MUSIC)
	mad_data *mp3_mad;
#endif
	long samplesize;
	int read_len;
	const Uint32 chunk_len = 4096;
	int err = 0;

	if ((!src) || (!spec) || (!audio_buf) || (!audio_len))
	{
		return NULL;
	}

	if (!err)
	{
		*audio_len = 0;
		*audio_buf = (Uint8*) SDL_malloc(chunk_len);
		err = (*audio_buf == NULL);
	}

	if (!err)
	{
		err = ((Mix_Init(MIX_INIT_MP3) & MIX_INIT_MP3) == 0);
	}

	if (!err)
	{
#if defined(MP3_MUSIC)
		mp3 = smpeg.SMPEG_new_rwops(src, &info, freesrc, 0);
		err = (mp3 == NULL);
#elif defined(MP3_MAD_MUSIC)
        mp3_mad = mad_openFileRW(src, spec, freesrc);
		err = (mp3_mad == NULL);
#endif
	}

#if defined(MP3_MUSIC)
	if (!err)
	{
		err = !info.has_audio;
	}
#endif

	if (!err)
	{
#if defined(MP3_MUSIC)

		smpeg.SMPEG_actualSpec(mp3, spec);

		smpeg.SMPEG_enableaudio(mp3, 1);
		smpeg.SMPEG_enablevideo(mp3, 0);

		smpeg.SMPEG_play(mp3);

		/* read once for audio length */
		while ((read_len = smpeg.SMPEG_playAudio(mp3, *audio_buf, chunk_len)) > 0)
		{
			*audio_len += read_len;
		}

		smpeg.SMPEG_stop(mp3);

#elif defined(MP3_MAD_MUSIC)

        mad_start(mp3_mad);

		/* read once for audio length */
		while ((read_len = mad_getSamples(mp3_mad, *audio_buf, chunk_len)) > 0)
		{
			*audio_len += read_len;
		}

		mad_stop(mp3_mad);

#endif

		err = (read_len < 0);
	}

	if (!err)
	{
		/* reallocate, if needed */
		if ((*audio_len > 0) && (*audio_len != chunk_len))
		{
			*audio_buf = (Uint8*) SDL_realloc(*audio_buf, *audio_len);
			err = (*audio_buf == NULL);
		}
	}

	if (!err)
	{
		/* read again for audio buffer, if needed */
		if (*audio_len > chunk_len)
		{
#if defined(MP3_MUSIC)
			smpeg.SMPEG_rewind(mp3);
			smpeg.SMPEG_play(mp3);
			err = (*audio_len != smpeg.SMPEG_playAudio(mp3, *audio_buf, *audio_len));
			smpeg.SMPEG_stop(mp3);
#elif defined(MP3_MAD_MUSIC)
			mad_seek(mp3_mad, 0);
			mad_start(mp3_mad);
			err = (*audio_len != mad_getSamples(mp3_mad, *audio_buf, *audio_len));
			mad_stop(mp3_mad);
#endif
		}
	}

	if (!err)
	{
		/* Don't return a buffer that isn't a multiple of samplesize */
		samplesize = ((spec->format & 0xFF)/8)*spec->channels;
		*audio_len &= ~(samplesize-1);
	}

#if defined(MP3_MUSIC)
	if (mp3)
	{
		smpeg.SMPEG_delete(mp3); mp3 = NULL;
		/* Deleting the MP3 closed the source if desired */
		freesrc = SDL_FALSE;
	}
#elif defined(MP3_MAD_MUSIC)
	if (mp3_mad)
	{
		mad_closeFile(mp3_mad); mp3_mad = NULL;
		/* Deleting the MP3 closed the source if desired */
		freesrc = SDL_FALSE;
	}
#endif

	if (freesrc)
	{
		SDL_RWclose(src); src = NULL;
	}

	/* handle error */
	if (err)
	{
		if (*audio_buf != NULL)
		{
			SDL_free(*audio_buf); *audio_buf = NULL;
		}
		*audio_len = 0;
		spec = NULL;
	}

	return spec;
}
示例#26
0
/*
===============
GLimp_DetectAvailableModes
===============
*/
static void GLimp_DetectAvailableModes(void)
{
	int i, j;
	char buf[ MAX_STRING_CHARS ] = { 0 };
	int numSDLModes;
	SDL_Rect *modes;
	int numModes = 0;

	SDL_DisplayMode windowMode;
	int display = SDL_GetWindowDisplayIndex( SDL_window );
	if( display < 0 )
	{
		ri.Printf( PRINT_WARNING, "Couldn't get window display index, no resolutions detected: %s\n", SDL_GetError() );
		return;
	}
	numSDLModes = SDL_GetNumDisplayModes( display );

	if( SDL_GetWindowDisplayMode( SDL_window, &windowMode ) < 0 || numSDLModes <= 0 )
	{
		ri.Printf( PRINT_WARNING, "Couldn't get window display mode, no resolutions detected: %s\n", SDL_GetError() );
		return;
	}

	modes = SDL_calloc( (size_t)numSDLModes, sizeof( SDL_Rect ) );
	if ( !modes )
	{
		ri.Error( ERR_FATAL, "Out of memory" );
	}

	for( i = 0; i < numSDLModes; i++ )
	{
		SDL_DisplayMode mode;

		if( SDL_GetDisplayMode( display, i, &mode ) < 0 )
			continue;

		if( !mode.w || !mode.h )
		{
			ri.Printf( PRINT_ALL, "Display supports any resolution\n" );
			SDL_free( modes );
			return;
		}

		if( windowMode.format != mode.format )
			continue;

		// SDL can give the same resolution with different refresh rates.
		// Only list resolution once.
		for( j = 0; j < numModes; j++ )
		{
			if( mode.w == modes[ j ].w && mode.h == modes[ j ].h )
				break;
		}

		if( j != numModes )
			continue;

		modes[ numModes ].w = mode.w;
		modes[ numModes ].h = mode.h;
		numModes++;
	}

	if( numModes > 1 )
		qsort( modes, numModes, sizeof( SDL_Rect ), GLimp_CompareModes );

	for( i = 0; i < numModes; i++ )
	{
		const char *newModeString = va( "%ux%u ", modes[ i ].w, modes[ i ].h );

		if( strlen( newModeString ) < (int)sizeof( buf ) - strlen( buf ) )
			Q_strcat( buf, sizeof( buf ), newModeString );
		else
			ri.Printf( PRINT_WARNING, "Skipping mode %ux%u, buffer too small\n", modes[ i ].w, modes[ i ].h );
	}

	if( *buf )
	{
		buf[ strlen( buf ) - 1 ] = 0;
		ri.Printf( PRINT_ALL, "Available modes: '%s'\n", buf );
		ri.Cvar_Set( "r_availableModes", buf );
	}
	SDL_free( modes );
}
示例#27
0
static int
GLES_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
                const SDL_Rect * srcrect, const SDL_Rect * dstrect)
{

    GLES_RenderData *data = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *texturedata = (GLES_TextureData *) texture->driverdata;
    int minx, miny, maxx, maxy;
    GLfloat minu, maxu, minv, maxv;
    int i;
    void *temp_buffer;          /* used for reformatting dirty rect pixels */
    void *temp_ptr;

    data->glEnable(GL_TEXTURE_2D);

    if (texturedata->dirty.list) {
        SDL_DirtyRect *dirty;
        void *pixels;
        int bpp = SDL_BYTESPERPIXEL(texture->format);
        int pitch = texturedata->pitch;

        SetupTextureUpdate(data, texture, pitch);

        data->glBindTexture(texturedata->type, texturedata->texture);
        for (dirty = texturedata->dirty.list; dirty; dirty = dirty->next) {
            SDL_Rect *rect = &dirty->rect;
            pixels =
                (void *) ((Uint8 *) texturedata->pixels + rect->y * pitch +
                          rect->x * bpp);
            /*      There is no GL_UNPACK_ROW_LENGTH in OpenGLES 
               we must do this reformatting ourselves(!)

               maybe it'd be a good idea to keep a temp buffer around
               for this purpose rather than allocating it each time
             */
            temp_buffer = SDL_malloc(rect->w * rect->h * bpp);
            temp_ptr = temp_buffer;
            for (i = 0; i < rect->h; i++) {
                SDL_memcpy(temp_ptr, pixels, rect->w * bpp);
                temp_ptr += rect->w * bpp;
                pixels += pitch;
            }

            data->glTexSubImage2D(texturedata->type, 0, rect->x, rect->y,
                                  rect->w, rect->h, texturedata->format,
                                  texturedata->formattype, temp_buffer);

            SDL_free(temp_buffer);

        }
        SDL_ClearDirtyRects(&texturedata->dirty);
    }

    data->glBindTexture(texturedata->type, texturedata->texture);

    if (texture->modMode) {
        data->glColor4f((GLfloat) texture->r * inv255f,
                        (GLfloat) texture->g * inv255f,
                        (GLfloat) texture->b * inv255f,
                        (GLfloat) texture->a * inv255f);
    } else {
        data->glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    }

    GLES_SetBlendMode(data, texture->blendMode, 0);

    switch (texture->scaleMode) {
    case SDL_TEXTURESCALEMODE_NONE:
    case SDL_TEXTURESCALEMODE_FAST:
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MIN_FILTER,
                              GL_NEAREST);
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MAG_FILTER,
                              GL_NEAREST);
        break;
    case SDL_TEXTURESCALEMODE_SLOW:
    case SDL_TEXTURESCALEMODE_BEST:
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MIN_FILTER,
                              GL_LINEAR);
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MAG_FILTER,
                              GL_LINEAR);
        break;
    }

    if (data->GL_OES_draw_texture_supported && data->useDrawTexture) {
        /* this code is a little funny because the viewport is upside down vs SDL's coordinate system */
        SDL_Window *window = renderer->window;
        GLint cropRect[4];
        cropRect[0] = srcrect->x;
        cropRect[1] = srcrect->y + srcrect->h;
        cropRect[2] = srcrect->w;
        cropRect[3] = -srcrect->h;
        data->glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES,
                               cropRect);
        data->glDrawTexiOES(dstrect->x, window->h - dstrect->y - dstrect->h,
                            0, dstrect->w, dstrect->h);
    } else {

        minx = dstrect->x;
        miny = dstrect->y;
        maxx = dstrect->x + dstrect->w;
        maxy = dstrect->y + dstrect->h;

        minu = (GLfloat) srcrect->x / texture->w;
        minu *= texturedata->texw;
        maxu = (GLfloat) (srcrect->x + srcrect->w) / texture->w;
        maxu *= texturedata->texw;
        minv = (GLfloat) srcrect->y / texture->h;
        minv *= texturedata->texh;
        maxv = (GLfloat) (srcrect->y + srcrect->h) / texture->h;
        maxv *= texturedata->texh;

        GLshort vertices[8];
        GLfloat texCoords[8];

        vertices[0] = minx;
        vertices[1] = miny;
        vertices[2] = maxx;
        vertices[3] = miny;
        vertices[4] = minx;
        vertices[5] = maxy;
        vertices[6] = maxx;
        vertices[7] = maxy;

        texCoords[0] = minu;
        texCoords[1] = minv;
        texCoords[2] = maxu;
        texCoords[3] = minv;
        texCoords[4] = minu;
        texCoords[5] = maxv;
        texCoords[6] = maxu;
        texCoords[7] = maxv;

        data->glVertexPointer(2, GL_SHORT, 0, vertices);
        data->glEnableClientState(GL_VERTEX_ARRAY);
        data->glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
        data->glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        data->glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        data->glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        data->glDisableClientState(GL_VERTEX_ARRAY);
    }

    data->glDisable(GL_TEXTURE_2D);

    return 0;
}
示例#28
0
/**
* \brief Execute a test suite using the given run seed and execution key.
*
* The filter string is matched to the suite name (full comparison) to select a single suite,
* or if no suite matches, it is matched to the test names (full comparison) to select a single test.
*
* \param testSuites Suites containing the test case.
* \param userRunSeed Custom run seed provided by user, or NULL to autogenerate one.
* \param userExecKey Custom execution key provided by user, or 0 to autogenerate one.
* \param filter Filter specification. NULL disables. Case sensitive.
* \param testIterations Number of iterations to run each test case.
*
* \returns Test run result; 0 when all tests passed, 1 if any tests failed.
*/
int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *userRunSeed, Uint64 userExecKey, const char *filter, int testIterations)
{
    int totalNumberOfTests = 0;
    int failedNumberOfTests = 0;
    int suiteCounter;
    int testCounter;
    int iterationCounter;
    SDLTest_TestSuiteReference *testSuite;
    SDLTest_TestCaseReference *testCase;
    const char *runSeed = NULL;
    char *currentSuiteName;
    char *currentTestName;
    Uint64 execKey;
    float runStartSeconds;
    float suiteStartSeconds;
    float testStartSeconds;
    float runEndSeconds;
    float suiteEndSeconds;
    float testEndSeconds;
    float runtime;
    int suiteFilter = 0;
    char *suiteFilterName = NULL;
    int testFilter = 0;
    char *testFilterName = NULL;
	SDL_bool forceTestRun = SDL_FALSE;
    int testResult = 0;
    int runResult = 0;
    Uint32 totalTestFailedCount = 0;
    Uint32 totalTestPassedCount = 0;
    Uint32 totalTestSkippedCount = 0;
    Uint32 testFailedCount = 0;
    Uint32 testPassedCount = 0;
    Uint32 testSkippedCount = 0;
    Uint32 countSum = 0;
    char *logFormat = (char *)SDLTest_LogSummaryFormat;
    SDLTest_TestCaseReference **failedTests;

    /* Sanitize test iterations */
    if (testIterations < 1) {
        testIterations = 1;
    }

    /* Generate run see if we don't have one already */
    if (userRunSeed == NULL || userRunSeed[0] == '\0') {
        runSeed = SDLTest_GenerateRunSeed(16);
        if (runSeed == NULL) {
            SDLTest_LogError("Generating a random seed failed");
            return 2;
        }
    } else {
        runSeed = userRunSeed;
    }


    /* Reset per-run counters */
    totalTestFailedCount = 0;
    totalTestPassedCount = 0;
    totalTestSkippedCount = 0;

    /* Take time - run start */
    runStartSeconds = GetClock();

    /* Log run with fuzzer parameters */
    SDLTest_Log("::::: Test Run /w seed '%s' started\n", runSeed);

	/* Count the total number of tests */
    suiteCounter = 0;
    while (testSuites[suiteCounter]) {
        testSuite=(SDLTest_TestSuiteReference *)testSuites[suiteCounter];
        suiteCounter++;
        testCounter = 0;
        while (testSuite->testCases[testCounter])
        {
            testCounter++;
			totalNumberOfTests++;
		}
	}

	/* Pre-allocate an array for tracking failed tests (potentially all test cases) */
	failedTests = (SDLTest_TestCaseReference **)SDL_malloc(totalNumberOfTests * sizeof(SDLTest_TestCaseReference *));
	if (failedTests == NULL) {	
	   SDLTest_LogError("Unable to allocate cache for failed tests");
           SDL_Error(SDL_ENOMEM);	   
           return -1;
	}

    /* Initialize filtering */
    if (filter != NULL && filter[0] != '\0') {
        /* Loop over all suites to check if we have a filter match */
        suiteCounter = 0;
        while (testSuites[suiteCounter] && suiteFilter == 0) {
            testSuite=(SDLTest_TestSuiteReference *)testSuites[suiteCounter];
            suiteCounter++;
            if (testSuite->name != NULL && SDL_strcmp(filter, testSuite->name) == 0) {
                /* Matched a suite name */
                suiteFilter = 1;
                suiteFilterName = testSuite->name;
                SDLTest_Log("Filtering: running only suite '%s'", suiteFilterName);
                break;
            }

            /* Within each suite, loop over all test cases to check if we have a filter match */
            testCounter = 0;
            while (testSuite->testCases[testCounter] && testFilter == 0)
            {
                testCase=(SDLTest_TestCaseReference *)testSuite->testCases[testCounter];
                testCounter++;
                if (testCase->name != NULL && SDL_strcmp(filter, testCase->name) == 0) {
                    /* Matched a test name */
                    suiteFilter = 1;
                    suiteFilterName = testSuite->name;
                    testFilter = 1;
                    testFilterName = testCase->name;
                    SDLTest_Log("Filtering: running only test '%s' in suite '%s'", testFilterName, suiteFilterName);
                    break;
                }
            }
        }

        if (suiteFilter == 0 && testFilter == 0) {
            SDLTest_LogError("Filter '%s' did not match any test suite/case.", filter);
            SDLTest_Log("Exit code: 2");
            SDL_free(failedTests);
            return 2;
        }
    }

    /* Loop over all suites */
    suiteCounter = 0;
    while(testSuites[suiteCounter]) {
        testSuite=(SDLTest_TestSuiteReference *)testSuites[suiteCounter];
        currentSuiteName = (char *)((testSuite->name) ? testSuite->name : SDLTest_InvalidNameFormat);
        suiteCounter++;

        /* Filter suite if flag set and we have a name */
        if (suiteFilter == 1 && suiteFilterName != NULL && testSuite->name != NULL &&
            SDL_strcmp(suiteFilterName, testSuite->name) != 0) {
                /* Skip suite */
                SDLTest_Log("===== Test Suite %i: '%s' skipped\n",
                    suiteCounter,
                    currentSuiteName);
        } else {

            /* Reset per-suite counters */
            testFailedCount = 0;
            testPassedCount = 0;
            testSkippedCount = 0;

            /* Take time - suite start */
            suiteStartSeconds = GetClock();

            /* Log suite started */
            SDLTest_Log("===== Test Suite %i: '%s' started\n",
                suiteCounter,
                currentSuiteName);

            /* Loop over all test cases */
            testCounter = 0;
            while(testSuite->testCases[testCounter])
            {
                testCase=(SDLTest_TestCaseReference *)testSuite->testCases[testCounter];
                currentTestName = (char *)((testCase->name) ? testCase->name : SDLTest_InvalidNameFormat);
                testCounter++;

                /* Filter tests if flag set and we have a name */
                if (testFilter == 1 && testFilterName != NULL && testCase->name != NULL &&
                    SDL_strcmp(testFilterName, testCase->name) != 0) {
                        /* Skip test */
                        SDLTest_Log("===== Test Case %i.%i: '%s' skipped\n",
                            suiteCounter,
                            testCounter,
                            currentTestName);
                } else {
                    /* Override 'disabled' flag if we specified a test filter (i.e. force run for debugging) */
                    if (testFilter == 1 && !testCase->enabled) {
                        SDLTest_Log("Force run of disabled test since test filter was set");
						forceTestRun = SDL_TRUE;
                    }

                    /* Take time - test start */
                    testStartSeconds = GetClock();

                    /* Log test started */
                    SDLTest_Log("----- Test Case %i.%i: '%s' started",
                        suiteCounter,
                        testCounter,
                        currentTestName);
                    if (testCase->description != NULL && testCase->description[0] != '\0') {
                        SDLTest_Log("Test Description: '%s'",
                            (testCase->description) ? testCase->description : SDLTest_InvalidNameFormat);
                    }

                    /* Loop over all iterations */
                    iterationCounter = 0;
                    while(iterationCounter < testIterations)
                    {
                        iterationCounter++;

                        if (userExecKey != 0) {
                            execKey = userExecKey;
                        } else {
                            execKey = SDLTest_GenerateExecKey((char *)runSeed, testSuite->name, testCase->name, iterationCounter);
                        }

                        SDLTest_Log("Test Iteration %i: execKey %" SDL_PRIu64, iterationCounter, execKey);
						testResult = SDLTest_RunTest(testSuite, testCase, execKey, forceTestRun);

                        if (testResult == TEST_RESULT_PASSED) {
                            testPassedCount++;
                            totalTestPassedCount++;
                        } else if (testResult == TEST_RESULT_SKIPPED) {
                            testSkippedCount++;
                            totalTestSkippedCount++;
                        } else {
                            testFailedCount++;
                            totalTestFailedCount++;
                        }
                    }

                    /* Take time - test end */
                    testEndSeconds = GetClock();
                    runtime = testEndSeconds - testStartSeconds;
                    if (runtime < 0.0f) runtime = 0.0f;

                    if (testIterations > 1) {
                        /* Log test runtime */
                        SDLTest_Log("Runtime of %i iterations: %.1f sec", testIterations, runtime);
                        SDLTest_Log("Average Test runtime: %.5f sec", runtime / (float)testIterations);
                    } else {
                        /* Log test runtime */
                        SDLTest_Log("Total Test runtime: %.1f sec", runtime);
                    }

                    /* Log final test result */
                    switch (testResult) {
                    case TEST_RESULT_PASSED:
                        SDLTest_Log((char *)SDLTest_FinalResultFormat, "Test", currentTestName, "Passed");
                        break;
                    case TEST_RESULT_FAILED:
                        SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Test", currentTestName, "Failed");
                        break;
                    case TEST_RESULT_NO_ASSERT:
                        SDLTest_LogError((char *)SDLTest_FinalResultFormat,"Test", currentTestName, "No Asserts");
                        break;
                    }

                    /* Collect failed test case references for repro-step display */
                    if (testResult == TEST_RESULT_FAILED) {
                        failedTests[failedNumberOfTests] = testCase;
                        failedNumberOfTests++;
                    }
                }
            }

            /* Take time - suite end */
            suiteEndSeconds = GetClock();
            runtime = suiteEndSeconds - suiteStartSeconds;
            if (runtime < 0.0f) runtime = 0.0f;

            /* Log suite runtime */
            SDLTest_Log("Total Suite runtime: %.1f sec", runtime);

            /* Log summary and final Suite result */
            countSum = testPassedCount + testFailedCount + testSkippedCount;
            if (testFailedCount == 0)
            {
                SDLTest_Log(logFormat, "Suite", countSum, testPassedCount, testFailedCount, testSkippedCount);
                SDLTest_Log((char *)SDLTest_FinalResultFormat, "Suite", currentSuiteName, "Passed");
            }
            else
            {
                SDLTest_LogError(logFormat, "Suite", countSum, testPassedCount, testFailedCount, testSkippedCount);
                SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Suite", currentSuiteName, "Failed");
            }

        }
    }

    /* Take time - run end */
    runEndSeconds = GetClock();
    runtime = runEndSeconds - runStartSeconds;
    if (runtime < 0.0f) runtime = 0.0f;

    /* Log total runtime */
    SDLTest_Log("Total Run runtime: %.1f sec", runtime);

    /* Log summary and final run result */
    countSum = totalTestPassedCount + totalTestFailedCount + totalTestSkippedCount;
    if (totalTestFailedCount == 0)
    {
        runResult = 0;
        SDLTest_Log(logFormat, "Run", countSum, totalTestPassedCount, totalTestFailedCount, totalTestSkippedCount);
        SDLTest_Log((char *)SDLTest_FinalResultFormat, "Run /w seed", runSeed, "Passed");
    }
    else
    {
        runResult = 1;
        SDLTest_LogError(logFormat, "Run", countSum, totalTestPassedCount, totalTestFailedCount, totalTestSkippedCount);
        SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Run /w seed", runSeed, "Failed");
    }

    /* Print repro steps for failed tests */
    if (failedNumberOfTests > 0) {
        SDLTest_Log("Harness input to repro failures:");
        for (testCounter = 0; testCounter < failedNumberOfTests; testCounter++) {
          SDLTest_Log(" --seed %s --filter %s", runSeed, failedTests[testCounter]->name);
        }
    }
    SDL_free(failedTests);

    SDLTest_Log("Exit code: %d", runResult);
    return runResult;
}
示例#29
0
/*
 * Open a joystick for use - the index passed as an argument refers to
 * the N'th joystick on the system.  This index is the value which will
 * identify this joystick in future joystick events.
 *
 * This function returns a joystick identifier, or NULL if an error occurred.
 */
SDL_Joystick *
SDL_JoystickOpen(int device_index)
{
    SDL_Joystick *joystick;
    SDL_Joystick *joysticklist;
    const char *joystickname = NULL;

    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
        SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
        return (NULL);
    }

    joysticklist = SDL_joysticks;
    /* If the joystick is already open, return it
    * it is important that we have a single joystick * for each instance id
    */
    while (joysticklist) {
        if (SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == joysticklist->instance_id) {
                joystick = joysticklist;
                ++joystick->ref_count;
                return (joystick);
        }
        joysticklist = joysticklist->next;
    }

    /* Create and initialize the joystick */
    joystick = (SDL_Joystick *) SDL_malloc((sizeof *joystick));
    if (joystick == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    SDL_memset(joystick, 0, (sizeof *joystick));
    if (SDL_SYS_JoystickOpen(joystick, device_index) < 0) {
        SDL_free(joystick);
        return NULL;
    }

    joystickname = SDL_SYS_JoystickNameForDeviceIndex(device_index);
    if (joystickname)
        joystick->name = SDL_strdup(joystickname);
    else
        joystick->name = NULL;

    if (joystick->naxes > 0) {
        joystick->axes = (Sint16 *) SDL_malloc
            (joystick->naxes * sizeof(Sint16));
    }
    if (joystick->nhats > 0) {
        joystick->hats = (Uint8 *) SDL_malloc
            (joystick->nhats * sizeof(Uint8));
    }
    if (joystick->nballs > 0) {
        joystick->balls = (struct balldelta *) SDL_malloc
            (joystick->nballs * sizeof(*joystick->balls));
    }
    if (joystick->nbuttons > 0) {
        joystick->buttons = (Uint8 *) SDL_malloc
            (joystick->nbuttons * sizeof(Uint8));
    }
    if (((joystick->naxes > 0) && !joystick->axes)
        || ((joystick->nhats > 0) && !joystick->hats)
        || ((joystick->nballs > 0) && !joystick->balls)
        || ((joystick->nbuttons > 0) && !joystick->buttons)) {
        SDL_OutOfMemory();
        SDL_JoystickClose(joystick);
        return NULL;
    }
    if (joystick->axes) {
        SDL_memset(joystick->axes, 0, joystick->naxes * sizeof(Sint16));
    }
    if (joystick->hats) {
        SDL_memset(joystick->hats, 0, joystick->nhats * sizeof(Uint8));
    }
    if (joystick->balls) {
        SDL_memset(joystick->balls, 0,
            joystick->nballs * sizeof(*joystick->balls));
    }
    if (joystick->buttons) {
        SDL_memset(joystick->buttons, 0, joystick->nbuttons * sizeof(Uint8));
    }
    joystick->epowerlevel = SDL_JOYSTICK_POWER_UNKNOWN;

    /* Add joystick to list */
    ++joystick->ref_count;
    /* Link the joystick in the list */
    joystick->next = SDL_joysticks;
    SDL_joysticks = joystick;

    SDL_SYS_JoystickUpdate(joystick);

    return (joystick);
}
示例#30
0
static void
SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
              const char *message)
{
#if defined(__WIN32__) || defined(__WINRT__)
    /* Way too many allocations here, urgh */
    /* Note: One can't call SDL_SetError here, since that function itself logs. */
    {
        char *output;
        size_t length;
        LPTSTR tstr;

#ifndef __WINRT__
        BOOL attachResult;
        DWORD attachError;
        unsigned long charsWritten;

        /* Maybe attach console and get stderr handle */
        if (consoleAttached == 0) {
            attachResult = AttachConsole(ATTACH_PARENT_PROCESS);
            if (!attachResult) {
                attachError = GetLastError();
                if (attachError == ERROR_INVALID_HANDLE) {
                    OutputDebugString(TEXT("Parent process has no console\r\n"));
                    consoleAttached = -1;
                } else if (attachError == ERROR_GEN_FAILURE) {
                    OutputDebugString(TEXT("Could not attach to console of parent process\r\n"));
                    consoleAttached = -1;
                } else if (attachError == ERROR_ACCESS_DENIED) {
                    /* Already attached */
                    consoleAttached = 1;
                } else {
                    OutputDebugString(TEXT("Error attaching console\r\n"));
                    consoleAttached = -1;
                }
            } else {
                /* Newly attached */
                consoleAttached = 1;
            }

            if (consoleAttached == 1) {
                stderrHandle = GetStdHandle(STD_ERROR_HANDLE);
            }
        }
#endif /* ifndef __WINRT__ */

        length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1 + 1 + 1;
        output = SDL_stack_alloc(char, length);
        SDL_snprintf(output, length, "%s: %s\r\n", SDL_priority_prefixes[priority], message);
        tstr = WIN_UTF8ToString(output);

        /* Output to debugger */
        OutputDebugString(tstr);

#ifndef __WINRT__
        /* Screen output to stderr, if console was attached. */
        if (consoleAttached == 1) {
            if (!WriteConsole(stderrHandle, tstr, lstrlen(tstr), &charsWritten, NULL)) {
                OutputDebugString(TEXT("Error calling WriteConsole\r\n"));
                if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY) {
                    OutputDebugString(TEXT("Insufficient heap memory to write message\r\n"));
                }
            }
        }
#endif /* ifndef __WINRT__ */

        SDL_free(tstr);
        SDL_stack_free(output);
    }
#elif defined(__ANDROID__)
    {
        char tag[32];

        SDL_snprintf(tag, SDL_arraysize(tag), "SDL/%s", GetCategoryPrefix(category));
        __android_log_write(SDL_android_priority[priority], tag, message);
    }
#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
    /* Technically we don't need SDL_VIDEO_DRIVER_COCOA, but that's where this function is defined for now.
    */
    extern void SDL_NSLog(const char *text);
    {
        char *text;

        text = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE);
        if (text) {
            SDL_snprintf(text, SDL_MAX_LOG_MESSAGE, "%s: %s", SDL_priority_prefixes[priority], message);
            SDL_NSLog(text);
            SDL_stack_free(text);
            return;
        }
    }
#elif defined(__PSP__)
    {
        FILE*        pFile;
        pFile = fopen ("SDL_Log.txt", "a");
        fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message);
        fclose (pFile);
    }
#endif
#if HAVE_STDIO_H
    fprintf(stderr, "%s: %s\n", SDL_priority_prefixes[priority], message);
#if __NACL__
    fflush(stderr);
#endif
#endif
}