Beispiel #1
0
void UpdateTexture(SDL_Texture *texture, int frame)
{
    SDL_Color *color;
    Uint8 *src;
    Uint32 *dst;
    int row, col;
    void *pixels;
    int pitch;

    if (SDL_LockTexture(texture, NULL, &pixels, &pitch) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't lock texture: %s\n", SDL_GetError());
        quit(5);
    }
    src = MooseFrames[frame];
    for (row = 0; row < MOOSEPIC_H; ++row) {
        dst = (Uint32*)((Uint8*)pixels + row * pitch);
        for (col = 0; col < MOOSEPIC_W; ++col) {
            color = &MooseColors[*src++];
            *dst++ = (0xFF000000|(color->r<<16)|(color->g<<8)|color->b);
        }
    }
    SDL_UnlockTexture(texture);
}
Beispiel #2
0
static int
SDL_UpdateTextureNative(SDL_Texture * texture, const SDL_Rect * rect,
                        const void *pixels, int pitch)
{
    SDL_Texture *native = texture->native;

    if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
        /* We can lock the texture and copy to it */
        void *native_pixels;
        int native_pitch;

        if (SDL_LockTexture(native, rect, &native_pixels, &native_pitch) < 0) {
            return -1;
        }
        SDL_ConvertPixels(rect->w, rect->h,
                          texture->format, pixels, pitch,
                          native->format, native_pixels, native_pitch);
        SDL_UnlockTexture(native);
    } else {
        /* Use a temporary buffer for updating */
        void *temp_pixels;
        int temp_pitch;

        temp_pitch = (((rect->w * SDL_BYTESPERPIXEL(native->format)) + 3) & ~3);
        temp_pixels = SDL_malloc(rect->h * temp_pitch);
        if (!temp_pixels) {
            SDL_OutOfMemory();
            return -1;
        }
        SDL_ConvertPixels(rect->w, rect->h,
                          texture->format, pixels, pitch,
                          native->format, temp_pixels, temp_pitch);
        SDL_UpdateTexture(native, rect, temp_pixels, temp_pitch);
        SDL_free(temp_pixels);
    }
    return 0;
}
Beispiel #3
0
//==============================================================================
bool Texture::Load(SDL_Renderer* Renderer, std::string Filename) {
	if(Renderer == NULL) {
		Log("Bad SDL renderer passed");
		return false;
	}

	this->Renderer = Renderer;
	this->Filename = Filename;

	SDL_Surface* TempSurface = IMG_Load(Filename.c_str());
	if(TempSurface == NULL) {
		Log("Unable to load image : %s : %s", Filename.c_str(), IMG_GetError());
		return false;
	}
	//Log("Surface Loaded");

	// Created to give STREAMING access to texture. This is needed to access
	// pixels to determine its masks
	SDLTexture = SDL_CreateTexture(Renderer, TempSurface->format->format,
		SDL_TEXTUREACCESS_STREAMING, TempSurface->w, TempSurface->h);
	//Log("Texture Created");
	if(SDLTexture == NULL) {
		Log("Unable to create SDL Texture : %s : %s", Filename.c_str(), IMG_GetError());
		return false;
	}

	void* pixels;
	SDL_SetTextureBlendMode(SDLTexture, SDL_BLENDMODE_BLEND);
  SDL_LockTexture(SDLTexture, &TempSurface->clip_rect, &pixels, &pitch);
	memcpy(pixels, TempSurface->pixels, TempSurface->h * TempSurface->pitch);
	SDL_UnlockTexture(SDLTexture);
	// Grab dimensions and pitch
	Width = TempSurface->w;
	Height = TempSurface->h;
	SDL_FreeSurface(TempSurface);
	return true;
}
Beispiel #4
0
void displayYUV_displayPicture(unsigned char *pictureBufferY,
                               unsigned char *pictureBufferU, unsigned char *pictureBufferV,
                               unsigned int   pictureWidth,   unsigned int   pictureHeight) {
	static unsigned int lastWidth = 0;
    static unsigned int lastHeight = 0;
    SDL_Event event;

	if ((pictureHeight != lastHeight) || (pictureWidth != lastWidth)) {
		displayYUV_setSize(pictureWidth, pictureHeight);
		lastHeight = pictureHeight;
		lastWidth = pictureWidth;
	}

    size1 = pictureWidth * pictureHeight;

    SDL_LockTexture(bmpTex1, NULL, (void **)&pixels1, &pitch1);
    memcpy(pixels1,             pictureBufferY, size1  );
    memcpy(pixels1 + size1,     pictureBufferV, size1/4);
    memcpy(pixels1 + size1*5/4, pictureBufferU, size1/4);
    SDL_UnlockTexture(bmpTex1);
    SDL_UpdateTexture(bmpTex1, NULL, pixels1, pitch1);
    // refresh screen
    //    SDL_RenderClear(pRenderer1);
    SDL_RenderCopy(pRenderer1, bmpTex1, NULL, NULL);
    SDL_RenderPresent(pRenderer1);

	/* Grab all the events off the queue. */
	while (SDL_PollEvent(&event)) {
		switch (event.type) {
		case SDL_QUIT:
			exit(0);
			break;
		default:
			break;
		}
	}
}
Beispiel #5
0
void renderBackgroundImage(AppState* state,Uint8* image)
{
    Uint8 *pixels = 0;
    int pitch1;

    if (0 == SDL_LockTexture(state->background, NULL, (void **)&pixels, &pitch1))
    {
        GLboolean isLightingOn = glIsEnabled(GL_LIGHTING);
        GLboolean isDepthTestOn = glIsEnabled(GL_DEPTH_TEST);


        if (isDepthTestOn) glDisable(GL_DEPTH_TEST);
        if (isLightingOn) glDisable(GL_LIGHTING);

        switch(gsBGTextureFormat) {
        case SDL_PIXELFORMAT_YV12:

            //        memcpy(pixels,             image, size1  );
            //        memcpy(pixels + size1,     pFrame_YUV420P->data[2], size1/4);
            //        memcpy(pixels + size1*5/4, pFrame_YUV420P->data[1], size1/4);
            break;
        case SDL_PIXELFORMAT_RGB24:
            memcpy( pixels, image, gsARTImageHeight*gsARTImageWidth*sizeof(Uint8)*3);
            break;
        }

        SDL_UnlockTexture(state->background);
        SDL_UpdateTexture(state->background, NULL, pixels, pitch1);

        float width,height;

        float posX = 0, posY = 0;


        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();
        glOrtho(0.0f, gsARTImageWidth, gsARTImageHeight, 0.0f, -1.0f, 1.0f);

        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glLoadIdentity();

        /* this accounts for Texture2D vs TextureRectangle */
        if (0 == SDL_GL_BindTexture(state->background, &width, &height ))
        {
            glBegin(GL_QUADS);
                glTexCoord2f(0, 0);
                glVertex2f(posX,posY);
                glTexCoord2f(1*width, 0);
                glVertex2f(posX + width, posY);
                glTexCoord2f(1*width, 1*height);
                glVertex2f(posX + width, posY + height);
                glTexCoord2f(0, 1*height);
                glVertex2f(posX, posY + height);
            glEnd();


//            SDL_GL_UnbindTexture(state->background);
        }

        glMatrixMode(GL_PROJECTION);
        glPopMatrix();
        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();

        if (isDepthTestOn) glEnable(GL_DEPTH_TEST);
        if (isLightingOn) glEnable(GL_LIGHTING);

    }
}
Beispiel #6
0
void qtsdl2::Run1()
{
	int w = width();
	int h = height();
	m_Cap->setSize(width(), height());
	unsigned char *pData = NULL;
	int step = 0;
	int width = 0;
	int height = 0;
	int cn = 0;
	SDL_Surface *pRgb  = NULL; 
	void *pixels;
	int pitch;
	//m_Cap->open("rtsp://159.99.251.194/");
	m_Cap->open("r.mp4");

	while(1)
	{
		m_Mutex.lock();
		if (m_UpdateSize == true)
			updateSize();
		
		if (m_Cap->grabFrame() == false)
		{
			delete m_Cap;
			 m_Cap = new CvCapture_FFMPEG;
			//m_Cap->open("rtsp://159.99.251.194/");
			m_Cap->open("r.mp4");
			updateSize();
			m_Mutex.unlock();
			continue;
		}
		m_Cap->retrieveFrame(0, &pData, &step, &width, &height, &cn);
#if 0
		/* Render the Data to Widget */
		pRgb = SDL_CreateRGBSurfaceFrom(pData, width, height, 24, step, 
#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
				 0xff000000, /* Red bit mask. */
				 0x00ff0000, /* Green bit mask. */
				 0x0000ff00, /* Blue bit mask. */
				 0x00000000  /* Alpha bit mask. */
#else
				 0x000000ff, /* Red bit mask. */
				 0x0000ff00, /* Green bit mask. */
				 0x00ff0000, /* Blue bit mask. */
				 0x00000000  /* Alpha bit mask. */
#endif
				);
		pTex = SDL_CreateTextureFromSurface(m_SdlRender, pRgb);
		SDL_FreeSurface(pRgb);
		pRgb = NULL;
		SDL_RenderClear(m_SdlRender);
		SDL_RenderCopy(m_SdlRender, pTex, NULL, NULL);
		SDL_RenderPresent(m_SdlRender);
		SDL_DestroyTexture(pTex);
		pTex = NULL;
#else
		pixels = NULL;
		
		SDL_LockTexture(m_pTex, NULL, &pixels, &pitch);
		if (pixels)
			memcpy(pixels, pData, width * height * cn);
		SDL_UnlockTexture(m_pTex);
		SDL_RenderClear(m_SdlRender);
		SDL_RenderCopy(m_SdlRender, m_pTex, NULL, NULL);
		SDL_RenderPresent(m_SdlRender);
		m_Mutex.unlock();
#endif
		Sleep(20);
	}
}
Beispiel #7
0
	void Texture::LoadTexture_fromSurface(const Surface& input_surface, const ScreenVideo& makerVideo, Rect& area_cut) throw(Error){
		this->Clean();
		if (makerVideo.m_renderer == nullptr)
			throw Error("Texture", "LoadTexture_fromMemoryPage", "Impossibile caricare una texture con uno specifico renderer nullo!");
		if (makerVideo.m_renderer != m_render) m_render = makerVideo.m_renderer;
		if (input_surface.Is_Void()) return;
		if (area_cut.Get_Xcomponent() < 0) area_cut.Set_Xcomponent(0);
		if (area_cut.Get_Ycomponent() < 0) area_cut.Set_Ycomponent(0);
		if (area_cut.Get_Wcomponent() < 0) area_cut.Set_Wcomponent(input_surface.Get_W() - area_cut.Get_Xcomponent());
		if (area_cut.Get_Hcomponent() < 0) area_cut.Set_Hcomponent(input_surface.Get_H() - area_cut.Get_Ycomponent());
		if (area_cut.Get_Wcomponent() + (size_t)area_cut.Get_Xcomponent() > input_surface.Get_W())
			area_cut.Set_Wcomponent(input_surface.Get_W() - area_cut.Get_Xcomponent());
		if (area_cut.Get_Hcomponent() + (size_t)area_cut.Get_Ycomponent() > input_surface.Get_H())
			area_cut.Set_Hcomponent(input_surface.Get_H() - area_cut.Get_Ycomponent());

		this->m_texture = SDL_CreateTexture(m_render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, 
			area_cut.Get_Wcomponent(), area_cut.Get_Hcomponent());
		if (this->m_texture == nullptr)
			throw Error("Texture", "LoadTexture_fromSurface", "Impossibile creare una texture grafica!\n%s", SDL_GetError());

		void* data_texture;
		int pitch_texture;

		if (SDL_LockTexture(m_texture, NULL, &data_texture, &pitch_texture) != 0)
			throw Error("Texture", "LoadTexture_fromSurface", "Impossibile scrivere la texture grafica!\n%s", SDL_GetError());
		if (SDL_LockSurface(input_surface.m_surface) != 0){
			SDL_UnlockTexture(m_texture);
			throw Error("Texture", "LoadTexture_fromSurface", "Impossibile leggere la surface grafica!\n%s", SDL_GetError());
		}
			

		try{
			Uint8* texture_pixelb = static_cast<Uint8*>(data_texture);
			const Uint8* surface_pixelb = static_cast<Uint8*>(input_surface.m_surface->pixels) +
				area_cut.Get_Ycomponent() * input_surface.m_surface->pitch +
				area_cut.Get_Xcomponent() * input_surface.m_surface->format->BytesPerPixel;

			const int row_size = area_cut.Get_Wcomponent() * input_surface.m_surface->format->BytesPerPixel;

			for (register int row = 0; row < area_cut.Get_Hcomponent(); ++row){
				memcpy(texture_pixelb, surface_pixelb, row_size);
				texture_pixelb += pitch_texture;
				surface_pixelb += input_surface.m_surface->pitch;
			}
		}
		catch (const std::exception& err){
			SDL_UnlockTexture(m_texture);
			SDL_UnlockSurface(input_surface.m_surface);
			throw Error("Texture", "LoadTexture_fromSurface", "Impossibile copiare i dati nella destinazione!\n%s", err.what());
		}

		SDL_UnlockSurface(input_surface.m_surface);
		SDL_UnlockTexture(m_texture);
		data_texture = nullptr;

		m_w_size = area_cut.Get_Wcomponent();
		m_h_size = area_cut.Get_Hcomponent();
		m_w_size_scaled = m_w_size;
		m_h_size_scaled = m_h_size;
		m_drawnable_area.Set_AllComponent(0, 0, m_w_size, m_h_size);
		m_alpha_mod = SDL_ALPHA_OPAQUE;

		SDL_SetTextureBlendMode(m_texture, SDL_BLENDMODE_BLEND);
	}
Beispiel #8
0
static int display(struct vidisp_st *st, const char *title,
		   const struct vidframe *frame)
{
	void *pixels;
	uint8_t *p;
	int pitch, ret;
	unsigned i, h;

	if (!vidsz_cmp(&st->size, &frame->size)) {
		if (st->size.w && st->size.h) {
			info("sdl: reset size: %u x %u ---> %u x %u\n",
			     st->size.w, st->size.h,
			     frame->size.w, frame->size.h);
		}
		sdl_reset(st);
	}

	if (!st->window) {
		Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_INPUT_FOCUS;
		char capt[256];

		if (st->fullscreen)
			flags |= SDL_WINDOW_FULLSCREEN;

		if (title) {
			re_snprintf(capt, sizeof(capt), "%s - %u x %u",
				    title, frame->size.w, frame->size.h);
		}
		else {
			re_snprintf(capt, sizeof(capt), "%u x %u",
				    frame->size.w, frame->size.h);
		}

		st->window = SDL_CreateWindow(capt,
					      SDL_WINDOWPOS_CENTERED,
					      SDL_WINDOWPOS_CENTERED,
					      frame->size.w, frame->size.h,
					      flags);
		if (!st->window) {
			warning("sdl: unable to create sdl window: %s\n",
				SDL_GetError());
			return ENODEV;
		}

		st->size = frame->size;

		SDL_RaiseWindow(st->window);
		SDL_SetWindowBordered(st->window, true);
		SDL_ShowWindow(st->window);
	}

	if (!st->renderer) {

		Uint32 flags = 0;

		flags |= SDL_RENDERER_ACCELERATED;
		flags |= SDL_RENDERER_PRESENTVSYNC;

		st->renderer = SDL_CreateRenderer(st->window, -1, flags);
		if (!st->renderer) {
			warning("sdl: unable to create renderer: %s\n",
				SDL_GetError());
			return ENOMEM;
		}
	}

	if (!st->texture) {

		st->texture = SDL_CreateTexture(st->renderer,
						SDL_PIXELFORMAT_IYUV,
						SDL_TEXTUREACCESS_STREAMING,
						frame->size.w, frame->size.h);
		if (!st->texture) {
			warning("sdl: unable to create texture: %s\n",
				SDL_GetError());
			return ENODEV;
		}
	}

	ret = SDL_LockTexture(st->texture, NULL, &pixels, &pitch);
	if (ret != 0) {
		warning("sdl: unable to lock texture (ret=%d)\n", ret);
		return ENODEV;
	}

	p = pixels;
	for (i=0; i<3; i++) {

		const uint8_t *s   = frame->data[i];
		const unsigned stp = frame->linesize[0] / frame->linesize[i];
		const unsigned sz  = frame->size.w / stp;

		for (h = 0; h < frame->size.h; h += stp) {

			memcpy(p, s, sz);

			s += frame->linesize[i];
			p += (pitch / stp);
		}
	}

	SDL_UnlockTexture(st->texture);

	/* Blit the sprite onto the screen */
	SDL_RenderCopy(st->renderer, st->texture, NULL, NULL);

	/* Update the screen! */
	SDL_RenderPresent(st->renderer);

	return 0;
}
Beispiel #9
0
	Texture::LockedPixels::LockedPixels(Texture* texture, int x, int y, int width, int height)
		: m_texture(texture), m_x(x), m_y(y), m_width(width), m_height(height)
	{
		SDL_Rect rect{ x, y, width, height };
		SDL_LockTexture(m_texture->m_texture.get(), &rect, &m_pixels, &m_pitch);
	}
Beispiel #10
0
int main(int argc, char *argv[])
{
    coordinates coord;                   // Coodinates Structure
    depth depth;
    color  colorsIn[2048];               // Colors array
    int    numColors = 0;                // Number of colors to use in color array
    float  colorPower = .3;              // Power exponent to use for color selection
    int    colorStart = 0xFF0000, colorEnd = 0xFFFF00; // Default color gradient settings
    char   *filename = "mandelbrot.png"; // Default PNG output name
    int    i;                            // Misc variables
    bool   noWindow = false;             // Default flag for no-window mode

    // Set default coordinates before reading in args
    coord.x = -2;          // Default Start Coordinates
    coord.y = 2;
    coord.xR = 4;          // Default Range Coordinates
    coord.yR = 4;
    coord.width = -1;      // Invalid pixel size, to be set later
    coord.height = -1;
    depth.d = 100;         // Default Depth level of Mandelbrot Calculation
    depth.automatic = true;

    // Generate default gradient first
    genGradient(colorsIn, &numColors, colorStart, colorEnd);

    // Parse Arguments
    for (i=1; i<argc; i++)
     {
        if (strcmp(argv[i], "--width") == 0)
        {
            coord.width = arg_check_int(argc, argv, i, 1, 10);
            i++;
        }
        else if (strcmp(argv[i], "--height") == 0)
        {
            coord.height = arg_check_int(argc, argv, i, 1, 10);
            i++;
        }
        else if (strcmp(argv[i], "--depth") == 0)
        {
            depth.automatic = false;
            depth.d = arg_check_int(argc, argv, i, 1, 10);
            i++;
        }
        else if (strcmp(argv[i], "--coords") == 0)
        {
            coord.x  = arg_check_float(argc, argv, i, 1);
            coord.y  = arg_check_float(argc, argv, i, 2);
            coord.xR = arg_check_float(argc, argv, i, 3);
            coord.yR = arg_check_float(argc, argv, i, 4);
            i+=4;
        }
        else if (strcmp(argv[i], "--spectrum") == 0)
        {
            genSpectrum(colorsIn, &numColors);
	    colorPower = .7;
        }
        else if (strcmp(argv[i], "--random") == 0)
        {
            genRandom(colorsIn, &numColors);
	    colorPower = 1;
        }
        else if (strcmp(argv[i], "--gradient") == 0)
        {
            colorStart = arg_check_int(argc, argv, i, 1, 16);
            colorEnd = arg_check_int(argc, argv, i, 2, 16);
            genGradient(colorsIn, &numColors, colorStart, colorEnd);
            i+=2;
        }
        else if (strcmp(argv[i], "-o") == 0)
        {
            filename = argv[i+1];
            i++;
        }
        else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0 )
        {
            help();
        }
        else if (strcmp(argv[i], "-nw") == 0 )
        {
            noWindow = true;
        }
        else
        {
            errx(EXIT_FAILURE, "Unknown argument, \"%s\".", argv[i]);
        }
     }

    // Make proportional image if only one dimension is specified
    // Set to default width and height if not specified
    if      (coord.height < 0 && coord.width > 0) coord.height = coord.width  / coord.xR * coord.yR;
    else if (coord.height > 0 && coord.width < 0) coord.width  = coord.height / coord.yR * coord.xR;
    else if (coord.height < 0 && coord.width < 0) coord.width  = coord.height = 1024;

    coord.xS = coord.xR/coord.width;  // X Step Value
    coord.yS = coord.yR/coord.height; // Y Step Value

    // Create final array of colors to use that is scaled to the depth that is selected
    color colors[2048];
    scaleColor(colorsIn, colors, numColors, depth.d, colorPower);

    // If no window mode, just output file and exit
    if (noWindow)
    {
        generate_png(coord, depth.d, filename, colors, numColors);
        return 0;
    }

    // Set up SDL
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* Main_Window;
    SDL_Renderer* Main_Renderer;
    Main_Window = SDL_CreateWindow("Mandelbrot", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, coord.width, coord.height, SDL_WINDOW_RESIZABLE);
    Main_Renderer = SDL_CreateRenderer(Main_Window, -1, SDL_RENDERER_ACCELERATED);
    SDL_Texture *texture = SDL_CreateTexture(Main_Renderer, SDL_PIXELFORMAT_RGBX8888, SDL_TEXTUREACCESS_STREAMING, coord.width, coord.height);
    int pitch;
    void *pixels;
    if (SDL_LockTexture(texture, NULL, &pixels, &pitch) != 0)
        errx(EXIT_FAILURE, "SDL_LockTexture: %s", SDL_GetError());
    //uint32_t (*pixel)[coord.height][pitch/sizeof(uint32_t)] = pixels;

    // Set up struct for tracking mouse movement
    mouse mouseTracker;
    mouseTracker.down = false;

    //Main Loop
    int maxRender = 2;
    int needsRender = maxRender;
    while (1)
    {
        // Render Loop
        if (needsRender > 0)
        {
            uint32_t (*pixel)[coord.height][pitch/sizeof(uint32_t)] = pixels;

            //unsigned long long timer = utime(); //DEBUG - Start Timer
            float pixelSize = pow(2, --needsRender);
            //printf("%d %d\n", needsRender, pixelSize);

            coordinates scaledCoord;
            scaledCoord.width = coord.width / pixelSize;
            scaledCoord.height = coord.height / pixelSize;
            scaledCoord.x  = coord.x;
            scaledCoord.xR = coord.xR;
            scaledCoord.xS = scaledCoord.xR/scaledCoord.width;
            scaledCoord.y  = coord.y;
            scaledCoord.yR = coord.yR;
            scaledCoord.yS = scaledCoord.yR/scaledCoord.height;     // y step value
            SDL_Rect srcrect = {0, 0, scaledCoord.width, scaledCoord.height};

            for (int y=0; y<scaledCoord.height; y++)
                for (int x=0; x<scaledCoord.width; x++)
                {
                    double xValue = scaledCoord.x + (x * scaledCoord.xS);
                    double yValue = scaledCoord.y - (y * scaledCoord.yS);
                    int result = mandel(xValue, yValue, depth.d);

                    int finalColor = 0;
                    if (result != -1)
                        finalColor = colors[result].hex << 8;

                    (*pixel)[y][x] = finalColor;
                }

            SDL_UnlockTexture(texture);
            SDL_RenderCopy(Main_Renderer, texture, &srcrect, NULL);

            //printf("%llu - Finish Render\n", utime()-timer); //DEBUG - End Timer

            SDL_RenderPresent(Main_Renderer);
        }

        SDL_Event e;
        //SDL_WaitEvent(&e);
        if (SDL_WaitEventTimeout(&e, 10) == 0) continue;
        if (e.type == SDL_MOUSEWHEEL)
        {
            if (e.wheel.y > 0)
                coord_zoom(&coord, 1);
            else
                coord_zoom(&coord, -1);
            if (depth.automatic == true)
            {
                adjust_depth(&coord, &depth);
                scaleColor(colorsIn, colors, numColors, depth.d, colorPower);
            }
            needsRender = maxRender;
        }

        if (e.type == SDL_WINDOWEVENT)
            if (e.window.event == SDL_WINDOWEVENT_RESIZED)
            {
                // Adjust view to new size
                coord.width = e.window.data1;
                coord.height = e.window.data2;
                coord.xR = coord.width * coord.xS;
                coord.yR = coord.height * coord.yS;

                // Destroy old texture
                SDL_DestroyTexture(texture);

                // Make New Texture
                texture = SDL_CreateTexture(Main_Renderer, SDL_PIXELFORMAT_RGBX8888, SDL_TEXTUREACCESS_STREAMING, coord.width, coord.height);

                // Lock with new texture
                if (SDL_LockTexture(texture, NULL, &pixels, &pitch) != 0)
                    errx(EXIT_FAILURE, "SDL_LockTexture: %s", SDL_GetError());

                // Rerender
                needsRender = maxRender;
            }

        if (e.type == SDL_MOUSEBUTTONDOWN)
            if (e.button.state == SDL_PRESSED)
            {
                mouseTracker.mouseX = e.motion.x;
                mouseTracker.mouseY = e.motion.y;
                mouseTracker.coordX = coord.x;
                mouseTracker.coordY = coord.y;
                mouseTracker.down = true;
            }

        if (e.type == SDL_MOUSEBUTTONUP)
            if (e.button.state == SDL_RELEASED)
                mouseTracker.down = false;

        if (e.type == SDL_MOUSEMOTION && mouseTracker.down == true)
        {
            coord.x = mouseTracker.coordX + ((mouseTracker.mouseX - e.motion.x) * coord.xS);
            coord.y = mouseTracker.coordY - ((mouseTracker.mouseY - e.motion.y) * coord.yS);
            needsRender = maxRender;
        }

        if (e.type == SDL_KEYUP)
        {
            if (e.key.keysym.sym == SDLK_p)
                print_coords(&coord, &depth);
            if (e.key.keysym.sym == SDLK_s)
                generate_png(coord, depth.d, filename, colors, numColors);
            if (e.key.keysym.sym == SDLK_EQUALS || e.key.keysym.sym == SDLK_MINUS)
            {
                depth.automatic = false;
                if (e.key.keysym.sym == SDLK_EQUALS)
                    depth.d += 5;
                if (e.key.keysym.sym == SDLK_MINUS)
                    if (depth.d > 5) depth.d -= 5;
                scaleColor(colorsIn, colors, numColors, depth.d, colorPower);
                needsRender = maxRender;
            }
        }

        if (e.type == SDL_QUIT)
        {
            SDL_Log("Program quit after %i ticks", e.quit.timestamp);
            break;
        }
    }

    return 0;
}
Beispiel #11
0
int
main(int argc, char *argv[])
{
    ps3eye_context ctx(640, 480, 30);
    if (!ctx.hasDevices()) {
        printf("No PS3 Eye camera connected\n");
        return EXIT_FAILURE;
    }

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("Failed to initialize SDL: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    SDL_Window *window = SDL_CreateWindow(
            "PS3 Eye - SDL 2", SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    if (window == NULL) {
        printf("Failed to create window: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1,
                                                SDL_RENDERER_PRESENTVSYNC);
    if (renderer == NULL) {
        printf("Failed to create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return EXIT_FAILURE;
    }
    SDL_RenderSetLogicalSize(renderer, ctx.frame_width, ctx.frame_height);
    print_renderer_info(renderer);

    SDL_Texture *video_tex = SDL_CreateTexture(
            renderer, SDL_PIXELFORMAT_YUY2, SDL_TEXTUREACCESS_STREAMING,
			ctx.frame_width, ctx.frame_height);
    if (video_tex == NULL) {
        printf("Failed to create video texture: %s\n", SDL_GetError());
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        return EXIT_FAILURE;
    }

	ctx.eye = ps3eye_open(0, ctx.frame_width, ctx.frame_height, ctx.frame_rate);
	if (ctx.eye == NULL)
	{
		printf("Failed to initialize camera: %s\n");
		SDL_DestroyRenderer(renderer);
		SDL_DestroyWindow(window);
		return EXIT_FAILURE;
	}

	ps3eye_set_flip(ctx.eye, true, false);

	printf("Camera mode: %dx%d@%d\n", ctx.frame_width, ctx.frame_height, ctx.frame_rate);


    SDL_Event e;
    void *video_tex_pixels;
    int pitch;
    while (ctx.running) {
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                ctx.running = false;
            }
        }

        // TODO: Proper thread signalling to wait for next available buffer
        SDL_Delay(10);
		int row_bytes = 0;
		uint8_t *frame_data = ps3eye_grab_frame(ctx.eye, &row_bytes);
		int frame_data_size = row_bytes * ctx.frame_height;

		if (frame_data != NULL)
		{
			SDL_LockTexture(video_tex, NULL, &video_tex_pixels, &pitch);
			memcpy(video_tex_pixels, frame_data, frame_data_size);
			SDL_UnlockTexture(video_tex);
		}

        SDL_RenderCopy(renderer, video_tex, NULL, NULL);
        SDL_RenderPresent(renderer);
    }

	ps3eye_close(ctx.eye);

    SDL_DestroyTexture(video_tex);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    return EXIT_SUCCESS;
}
Beispiel #12
0
int
main(int argc, char *argv[])
{
    ps3eye_context ctx(320, 240, 187);
    if (!ctx.hasDevices()) {
        printf("No PS3 Eye camera connected\n");
        return EXIT_FAILURE;
    }
    ctx.eye->setFlip(true); /* mirrored left-right */

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("Failed to initialize SDL: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    SDL_Window *window = SDL_CreateWindow(
            "PS3 Eye - SDL 2", SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    if (window == NULL) {
        printf("Failed to create window: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1,
                                                SDL_RENDERER_PRESENTVSYNC);
    if (renderer == NULL) {
        printf("Failed to create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return EXIT_FAILURE;
    }
    SDL_RenderSetLogicalSize(renderer, ctx.eye->getWidth(),
                             ctx.eye->getHeight());
    print_renderer_info(renderer);

    SDL_Texture *video_tex = SDL_CreateTexture(
            renderer, SDL_PIXELFORMAT_YUY2, SDL_TEXTUREACCESS_STREAMING,
            ctx.eye->getWidth(), ctx.eye->getHeight());
    if (video_tex == NULL) {
        printf("Failed to create video texture: %s\n", SDL_GetError());
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        return EXIT_FAILURE;
    }

    SDL_Thread *thread = SDL_CreateThread(ps3eye_cam_thread, "ps3eye_cam",
                                          (void *)&ctx);

    SDL_Event e;
    yuv422_buffer_t *last;
    void *video_tex_pixels;
    int pitch;
    while (ctx.running) {
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                ctx.running = false;
            }
        }

        // TODO: Proper thread signalling to wait for next available buffer
        SDL_Delay(10);
        last = ctx.buffers.read();

        SDL_LockTexture(video_tex, NULL, &video_tex_pixels, &pitch);
        memcpy(video_tex_pixels, last->pixels, last->size);
        SDL_UnlockTexture(video_tex);

        SDL_RenderCopy(renderer, video_tex, NULL, NULL);
        SDL_RenderPresent(renderer);
    }

    SDL_WaitThread(thread, NULL);

    SDL_DestroyTexture(video_tex);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    return EXIT_SUCCESS;
}
Beispiel #13
0
static int display(struct vidisp_st *st, const char *title,
		   const struct vidframe *frame)
{
	void *pixels;
	uint8_t *d;
	int dpitch, ret;
	unsigned i, h;
	uint32_t format;

	if (!st || !frame)
		return EINVAL;

	format = match_fmt(frame->fmt);
	if (format == SDL_PIXELFORMAT_UNKNOWN) {
		warning("sdl2: pixel format not supported (%s)\n",
			vidfmt_name(frame->fmt));
		return ENOTSUP;
	}

	if (!vidsz_cmp(&st->size, &frame->size) || frame->fmt != st->fmt) {
		if (st->size.w && st->size.h) {
			info("sdl: reset size:"
			     " %s %u x %u ---> %s %u x %u\n",
			     vidfmt_name(st->fmt), st->size.w, st->size.h,
			     vidfmt_name(frame->fmt),
			     frame->size.w, frame->size.h);
		}
		sdl_reset(st);
	}

	if (!st->window) {
		char capt[256];

		st->flags = SDL_WINDOW_SHOWN | SDL_WINDOW_INPUT_FOCUS;

		if (st->fullscreen)
			st->flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;

		if (title) {
			re_snprintf(capt, sizeof(capt), "%s - %u x %u",
				    title, frame->size.w, frame->size.h);
		}
		else {
			re_snprintf(capt, sizeof(capt), "%u x %u",
				    frame->size.w, frame->size.h);
		}

		st->window = SDL_CreateWindow(capt,
					      SDL_WINDOWPOS_CENTERED,
					      SDL_WINDOWPOS_CENTERED,
					      frame->size.w, frame->size.h,
					      st->flags);
		if (!st->window) {
			warning("sdl: unable to create sdl window: %s\n",
				SDL_GetError());
			return ENODEV;
		}

		st->size = frame->size;
		st->fmt = frame->fmt;

		SDL_RaiseWindow(st->window);
		SDL_SetWindowBordered(st->window, true);
		SDL_ShowWindow(st->window);
	}

	if (!st->renderer) {

		Uint32 flags = 0;

		flags |= SDL_RENDERER_ACCELERATED;
		flags |= SDL_RENDERER_PRESENTVSYNC;

		st->renderer = SDL_CreateRenderer(st->window, -1, flags);
		if (!st->renderer) {
			warning("sdl: unable to create renderer: %s\n",
				SDL_GetError());
			return ENOMEM;
		}
	}

	if (!st->texture) {

		st->texture = SDL_CreateTexture(st->renderer,
						format,
						SDL_TEXTUREACCESS_STREAMING,
						frame->size.w, frame->size.h);
		if (!st->texture) {
			warning("sdl: unable to create texture: %s\n",
				SDL_GetError());
			return ENODEV;
		}
	}

	ret = SDL_LockTexture(st->texture, NULL, &pixels, &dpitch);
	if (ret != 0) {
		warning("sdl: unable to lock texture (ret=%d)\n", ret);
		return ENODEV;
	}

	d = pixels;
	for (i=0; i<3; i++) {

		const uint8_t *s = frame->data[i];
		unsigned sz, dsz, hstep, wstep;

		if (!frame->data[i] || !frame->linesize[i])
			break;

		hstep = i==0 ? 1 : 2;
		wstep = i==0 ? 1 : chroma_step(frame->fmt);

		dsz = dpitch / wstep;
		sz  = min(frame->linesize[i], dsz);

		for (h = 0; h < frame->size.h; h += hstep) {

			memcpy(d, s, sz);

			s += frame->linesize[i];
			d += dsz;
		}
	}

	SDL_UnlockTexture(st->texture);

	/* Blit the sprite onto the screen */
	SDL_RenderCopy(st->renderer, st->texture, NULL, NULL);

	/* Update the screen! */
	SDL_RenderPresent(st->renderer);

	return 0;
}
int main(int argc, char *argv[]) {

  const unsigned int cameraIndex = 0u;
  const unsigned int numImagesPerFPSMeasurement = 240u;
  const int windowWidth = 1440;
  const int windowHeight = 900;
  const char cascadeFilename[] = "haarcascade_frontalface_alt.xml";
  const double detectionScaleFactor = 1.25;
  const int detectionMinNeighbours = 4;
  const int detectionFlags = CV_HAAR_SCALE_IMAGE;
  const cv::Size detectionMinSize(120, 120);
  const cv::Size detectionMaxSize;
  const cv::Scalar detectionDrawColor(255.0, 0.0, 255.0);
  char strBuffer[256u];
  const size_t strBufferSize = 256u;

  int matType;
  cv::Mat equalizedGrayMat;

#ifdef _WIN32
  snprintf(strBuffer, strBufferSize, "%s/../%s", argv[0], cascadeFilename);
  cv::CascadeClassifier detector(strBuffer);
#else
  cv::CascadeClassifier detector(cascadeFilename);
#endif
  if (detector.empty()) {
    snprintf(strBuffer, strBufferSize, "%s could not be loaded.",
              cascadeFilename);
    SDL_ShowSimpleMessageBox(
      SDL_MESSAGEBOX_ERROR, "Failed to Load Cascade File", strBuffer, NULL);
    return EXIT_FAILURE;
  }
  std::vector<cv::Rect> detectionRects;

  fc2Error error;

  fc2Image image;
  error = fc2CreateImage(&image);
  if (error != FC2_ERROR_OK) {
    showFC2Error(error);
    return EXIT_FAILURE;
  }

  fc2Context context;
  error = fc2CreateContext(&context);
  if (error != FC2_ERROR_OK) {
    showFC2Error(error);
    return EXIT_FAILURE;
  }
  
  fc2PGRGuid cameraGUID;
  error = fc2GetCameraFromIndex(context, cameraIndex, &cameraGUID);
  if (error != FC2_ERROR_OK) {
    showFC2Error(error);
    return EXIT_FAILURE;
  }
  
  error = fc2Connect(context, &cameraGUID);
  if (error != FC2_ERROR_OK) {
    showFC2Error(error);
    return EXIT_FAILURE;
  }

  error = fc2StartCapture(context);
  if (error != FC2_ERROR_OK) {
    fc2Disconnect(context);
    showFC2Error(error);
    return EXIT_FAILURE;
  }

  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    fc2StopCapture(context);
    fc2Disconnect(context);
    showSDLError();
    return EXIT_FAILURE;
  }

  SDL_Window *window = SDL_CreateWindow(
      "LookSpry", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
      windowWidth, windowHeight, 0u);
  if (window == NULL) {
    fc2StopCapture(context);
    fc2Disconnect(context);
    showSDLError();
    return EXIT_FAILURE;
  }

  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0u);
  if (renderer == NULL) {
    fc2StopCapture(context);
    fc2Disconnect(context);
    SDL_DestroyWindow(window);
    showSDLError();
    return EXIT_FAILURE;
  }
  
  SDL_RendererInfo rendererInfo;
  SDL_GetRendererInfo(renderer, &rendererInfo);

  if (strcmp(rendererInfo.name, "direct3d") == 0) {
    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  } else if (strcmp(rendererInfo.name, "opengl") == 0) {
    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  }

  snprintf(strBuffer, strBufferSize, "LookSpry | %s", rendererInfo.name);
  SDL_SetWindowTitle(window, strBuffer);

  SDL_Texture *videoTex = NULL;
  void *videoTexPixels;
  int pitch;

  clock_t startTicks = clock();
  clock_t endTicks;
  unsigned int numImagesCaptured = 0u;

  bool running = true;
  bool detecting = true;
  bool mirroring = true;
  SDL_Event event;
  while (running) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        running = false;
        break;
      } else if (event.type == SDL_KEYUP) {
        switch(event.key.keysym.sym) {
        // When 'd' is pressed, start or stop [d]etection.
        case SDLK_d:
          detecting = !detecting;
          break;
        // When 'm' is pressed, [m]irror or un-mirror the video.
        case SDLK_m:
          mirroring = !mirroring;
          break;
        default:
          break;
        }
      }
    }

    error = fc2RetrieveBuffer(context, &image);
    if (error != FC2_ERROR_OK) {
       fc2Disconnect(context);
       SDL_DestroyTexture(videoTex);
       SDL_DestroyRenderer(renderer);
       SDL_DestroyWindow(window);
       showFC2Error(error);
       return EXIT_FAILURE;
    }

    if (videoTex == NULL) {
      equalizedGrayMat.create(image.rows, image.cols, CV_8UC1);
      SDL_RenderSetLogicalSize(renderer, image.cols, image.rows);
      Uint32 videoTexPixelFormat;
      switch (image.format) {
        // For monochrome capture modes, plan to render captured data to the Y
        // plane of a planar YUV texture.
        case FC2_PIXEL_FORMAT_RAW8:
        case FC2_PIXEL_FORMAT_MONO8:
          videoTexPixelFormat = SDL_PIXELFORMAT_YV12;
          matType = CV_8UC1;
          break;
        // For color capture modes, plan to render captured data to the entire
        // space of a texture in a matching color format.
        case FC2_PIXEL_FORMAT_422YUV8:
          videoTexPixelFormat = SDL_PIXELFORMAT_UYVY;
          matType = CV_8UC2;
          break;
        case FC2_PIXEL_FORMAT_RGB:
          videoTexPixelFormat = SDL_PIXELFORMAT_RGB24;
          matType = CV_8UC3;
          break;
        case FC2_PIXEL_FORMAT_BGR:
          videoTexPixelFormat = SDL_PIXELFORMAT_BGR24;
          matType = CV_8UC3;
          break;
        default:
          fc2StopCapture(context);
          fc2Disconnect(context);
          SDL_DestroyTexture(videoTex);
          SDL_DestroyRenderer(renderer);
          SDL_DestroyWindow(window);
          SDL_ShowSimpleMessageBox(
              SDL_MESSAGEBOX_ERROR, "Unsupported FlyCapture2 Pixel Format",
              "LookSpry supports RAW8, MONO8, 422YUV8, RGB, and BGR.", NULL);
          return EXIT_FAILURE;
      }
      videoTex = SDL_CreateTexture(
          renderer, videoTexPixelFormat, SDL_TEXTUREACCESS_STREAMING,
          image.cols, image.rows);
      if (videoTex == NULL) {
        fc2StopCapture(context);
        fc2Disconnect(context);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        showSDLError();
        return EXIT_FAILURE;
      }
      snprintf(
          strBuffer, strBufferSize, "LookSpry | %s | %dx%d --> %dx%d",
          rendererInfo.name, image.cols, image.rows, windowWidth,
          windowHeight);
      SDL_SetWindowTitle(window, strBuffer);
    }

    cv::Mat srcMat(image.rows, image.cols, matType, image.pData, image.stride);
    if (detecting) {
      switch (image.format) {
        // For monochrome capture modes, just equalize.
        case FC2_PIXEL_FORMAT_RAW8:
        case FC2_PIXEL_FORMAT_MONO8:
          cv::equalizeHist(srcMat, equalizedGrayMat);
          break;
        // For color capture modes, convert to gray and equalize.
        case FC2_PIXEL_FORMAT_422YUV8:
          cv::cvtColor(srcMat, equalizedGrayMat, cv::COLOR_YUV2GRAY_UYVY);
          cv::equalizeHist(equalizedGrayMat, equalizedGrayMat);
          break;
        case FC2_PIXEL_FORMAT_RGB:
          cv::cvtColor(srcMat, equalizedGrayMat, cv::COLOR_RGB2GRAY);
          cv::equalizeHist(equalizedGrayMat, equalizedGrayMat);
          break;
        case FC2_PIXEL_FORMAT_BGR:
          cv::cvtColor(srcMat, equalizedGrayMat, cv::COLOR_BGR2GRAY);
          cv::equalizeHist(equalizedGrayMat, equalizedGrayMat);
          break;
        default:
          break;
      }
      // Run the detector on the equalized image.
      detector.detectMultiScale(
          equalizedGrayMat, detectionRects, detectionScaleFactor,
          detectionMinNeighbours, detectionFlags, detectionMinSize,
          detectionMaxSize);
      // Draw the resulting detection rectangles on the original image.
      for (cv::Rect detectionRect : detectionRects) {
        cv::rectangle(srcMat, detectionRect, detectionDrawColor);
      }
    }

    SDL_LockTexture(videoTex, NULL, &videoTexPixels, &pitch);

    switch (image.format) {
    case FC2_PIXEL_FORMAT_RAW8:
    case FC2_PIXEL_FORMAT_MONO8:
      // Make the planar YUV video gray by setting all bytes in its U and V
      // planes to 128 (the middle of the range).
      memset(((unsigned char *)videoTexPixels + image.dataSize), 128,
             image.dataSize / 2u);
      break;
    default:
      break;
    }

    if (mirroring) {
      // Flip the image data while copying it to the texture.
      cv::Mat dstMat(image.rows, image.cols, matType, videoTexPixels,
                     image.stride);
      cv::flip(srcMat, dstMat, 1);
    } else {
      // Copy the image data, as-is, to the texture.
      // Note that the PointGrey image and srcMat have pointers to the same
      // data, so the following code does reference the data that we modified
      // earlier via srcMat.
      memcpy(videoTexPixels, image.pData, image.dataSize);
    }

    SDL_UnlockTexture(videoTex);
    SDL_RenderCopy(renderer, videoTex, NULL, NULL);
    SDL_RenderPresent(renderer);

    numImagesCaptured++;
    if (numImagesCaptured >= numImagesPerFPSMeasurement) {
      endTicks = clock();
      snprintf(
          strBuffer, strBufferSize, "LookSpry | %s | %dx%d --> %dx%d | %ld FPS",
          rendererInfo.name, image.cols, image.rows, windowWidth,
          windowHeight,
          numImagesCaptured * CLOCKS_PER_SEC / (endTicks - startTicks));
      SDL_SetWindowTitle(window, strBuffer);
      startTicks = endTicks;
      numImagesCaptured = 0u;
    }
  }

  fc2StopCapture(context);
  fc2Disconnect(context);
  SDL_DestroyTexture(videoTex);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  return EXIT_SUCCESS;
}
void
Draw(const unsigned char* aImage, int size, int aWidth, int aHeight)
{
  if (!sState) {
    return;
  }

  if (!sState->window) {
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
      return;
    }

    sState->window = SDL_CreateWindow("WebRTC Player",
                                      SDL_WINDOWPOS_UNDEFINED,
                                      SDL_WINDOWPOS_UNDEFINED,
                                      aWidth, aHeight,
                                      0);
                                    // SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL);
    if (!sState->window) {
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create window: %s\n", SDL_GetError());
      quit(3);
    }

    sState->renderer = SDL_CreateRenderer(sState->window, -1, 0);
    if (!sState->renderer) {
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create renderer: %s\n", SDL_GetError());
      quit(4);
    }

    sState->width = aWidth;
    sState->height = aHeight;
  }

  if (!sState->texture) {
    sState->texture = SDL_CreateTexture(sState->renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, aWidth, aHeight);
    if (!sState->texture) {
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create texture: %s\n", SDL_GetError());
      quit(5);
    }
  }

  if ((sState->width != aWidth) || (sState->height != aHeight)) {
    if (sState->texture) {
      SDL_DestroyTexture(sState->texture); sState->texture = 0;
    }

    sState->texture = SDL_CreateTexture(sState->renderer,
                                        SDL_PIXELFORMAT_IYUV,
                                        SDL_TEXTUREACCESS_STREAMING,
                                        aWidth, aHeight);
    SDL_SetWindowSize(sState->window, aWidth, aHeight);
    sState->width = aWidth;
    sState->height = aHeight;
  }

  Uint8* dst = nullptr;
  void* pixels = nullptr;
  int pitch = 0;

  if (SDL_LockTexture(sState->texture, NULL, &pixels, &pitch) < 0) {
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't lock texture: %s\n", SDL_GetError());
    quit(5);
  }

  dst = (Uint8*)pixels;
  memcpy(dst, aImage, size);
  SDL_UnlockTexture(sState->texture);

  SDL_RenderClear(sState->renderer);
  SDL_RenderCopy(sState->renderer, sState->texture, NULL, NULL);
  SDL_RenderPresent(sState->renderer);
}
Beispiel #16
0
//-----------------------------------------------------------------------------
int SDL_main(int argc, char *argv[]) {
	// NOTE: check for the correct number of arguements
	if(argc<2) {
		fprintf(stderr, "Error: need a level name.\n");
		return -1;
	}

	// NOTE: add the sqlite db to the levels directory
	char filename[0xFF];
	sprintf(filename, "levels/%s.db", argv[1]);

	// NOTE: open database connection
	if(sqlite3_open_v2(filename, &db, SQLITE_OPEN_READONLY, NULL)) {
		fprintf(stderr, "sqlite3_open: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return -1;
	}

	/* === */

	start();

	/* === */

	int wallSprite00Inds[2*3] = {
		03, 04,
		35, 36,
		67, 68
	};

	SDL_Color wall00Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *wallSprite00 = buildSprite(2, 3, wall00Color, wallSprite00Inds);

	int floorSprite00Inds[2*3] = {
		17, 18,
		49, 50,
		81, 82
	};

	SDL_Color floorSprite00Color = {0x33,0x33,0x33,0xFF};
	SDL_Surface *floorSprite00 = buildSprite(2, 3, floorSprite00Color, floorSprite00Inds);

	int doorSprite00Inds[2*3] = {
		29, 30,
		61, 62,
		93, 94
	};

	SDL_Color doorSprite00Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *doorSprite00 = buildSprite(2, 3, doorSprite00Color, doorSprite00Inds);

	int wallSprite01Inds[2*3] = {
		 97,  98,
		129, 130,
		161, 162
	};

	SDL_Color wall01Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *wallSprite01 = buildSprite(2, 3, wall01Color, wallSprite01Inds);

	int wallSprite02Inds[2*3] = {
		105, 106,
		137, 138,
		169, 170
	};

	SDL_Color wallSprite02Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *wallSprite02 = buildSprite(2, 3, wallSprite02Color, wallSprite02Inds);

	/* === */

	while(running) {
		/* === */

		pollInput();

		SDL_RenderClear(renderer);
		SDL_FillRect(screen, 0, 0x00);

		/* === */

		loadTiles();

		SDL_Rect tempRect = {
			0, 0, SPRITE_W*2, SPRITE_H*3
		};

		int i, j;
		for(j=0; j<12; j++) {
			for(i=0; i<30; i++) {
				tempRect.x = SPRITE_W*2*i;
				tempRect.y = SPRITE_H*3*j;

				switch(lvl.tiles[j][i]) {
					case 0x01: {
						SDL_BlitSurface(wallSprite00, NULL, screen, &tempRect);
					} break;
					case 0x02: {
						SDL_BlitSurface(doorSprite00, NULL, screen, &tempRect);
					} break;
					case 0x03: {
						SDL_BlitSurface(wallSprite01, NULL, screen, &tempRect);
					} break;
					case 0x04: {
						SDL_BlitSurface(wallSprite02, NULL, screen, &tempRect);
					} break;
					default: {
						SDL_BlitSurface(floorSprite00, NULL, screen, &tempRect);
					} break;
				}
			}
		}

		/* === */

		int pitch;
		void *pixels;

		// NOTE: get the pixels for the screen texture
		SDL_LockTexture(texture, NULL, &pixels, &pitch);

		// NOTE: set the pixels for the screen texture
		SDL_ConvertPixels(
			screen->w,
			screen->h,
			screen->format->format,
			screen->pixels,
			screen->pitch,
			SDL_PIXELFORMAT_RGBA8888,
			pixels, pitch
		);

		// NOTE: lock the texture so that it may be presented
		SDL_UnlockTexture(texture);

		// NOTE: present the texture
		SDL_RenderCopy(renderer, texture, NULL, NULL);
		SDL_RenderPresent(renderer);

		SDL_Delay(10);

		/* === */
	}

	/* === */

	SDL_FreeSurface(wallSprite00);
	wallSprite00 = NULL;

	SDL_FreeSurface(floorSprite00);
	floorSprite00 = NULL;

	SDL_FreeSurface(doorSprite00);
	doorSprite00 = NULL;

	SDL_FreeSurface(wallSprite01);
	wallSprite01 = NULL;

	SDL_FreeSurface(wallSprite02);
	wallSprite02 = NULL;

	/* === */

	quit();

	/* === */

	// NTOE: close the database connection
	sqlite3_close(db);
	db = NULL;

	fclose(stderr);
	return 0;
}
Beispiel #17
0
int main(void) {
#if SDL
    SDL_Event event;
    SDL_Rect rect;
    SDL_Renderer *renderer;
    SDL_Window *window;
# if STREAMING
    SDL_Texture *texture = NULL;
    void *pixels;
    Uint8 *base;
    /* TODO: is it mandatory to use this? Maybe SDL_LockTexture
     * will make the array non continuous to improve alignment? */
    int pitch;
# endif
#else
    double sum;
#endif
    const unsigned int WINDOW_WIDTH = 600;
    const unsigned int WINDOW_HEIGHT = WINDOW_WIDTH;
    const double SPEED = (WINDOW_WIDTH / 10.0);
    const double CENTER_X = WINDOW_WIDTH / 2.0;
    const double CENTER_Y = WINDOW_HEIGHT / 2.0;
    const double PERIOD = (WINDOW_WIDTH / 10.0);
    const double PI2 = 2.0 * acos(-1.0);
    double dt;
    double fps_dt;
    double fps_last_time;
    double initial_time;
    double t;
    int nframes;
    float z;
    unsigned int x;
    unsigned int xc;
    unsigned int y;
    unsigned int yc;

#if SDL
    SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
    SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_WIDTH, 0, &window, &renderer);
# if STREAMING
    texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, WINDOW_WIDTH, WINDOW_HEIGHT);
# endif
#endif
    initial_time = get_secs();
    fps_last_time = initial_time;
    nframes = 0;
    while (1) {
        t = get_secs();
        dt = t - initial_time;
#if STREAMING
        SDL_LockTexture(texture, NULL, &pixels, &pitch);
#endif
        for (x = 0; x < WINDOW_WIDTH; x++) {
            for (y = 0; y < WINDOW_HEIGHT; y++) {
                xc = CENTER_X - x;
                yc = CENTER_Y - y;
                z = COLOR_MAX * 0.5 * (1.0 + (sin(PI2 * (sqrt(xc*xc + yc*yc) - SPEED * dt) / PERIOD)));
#if SDL
# if STREAMING
                base = ((Uint8 *)pixels) + (4 * (x * WINDOW_WIDTH + y));
                base[0] = 0;
                base[1] = 0;
                base[2] = z;
                base[3] = COLOR_MAX;
# else
                SDL_SetRenderDrawColor(renderer, z, 0, 0, COLOR_MAX);
                SDL_RenderDrawPoint(renderer, x, y);
# endif
#else
                sum += z;
#endif
            }
        }
#if SDL
# if STREAMING
        SDL_UnlockTexture(texture);
        SDL_RenderCopy(renderer, texture, NULL, NULL);
# endif
        SDL_RenderPresent(renderer);
#endif
        nframes++;
        fps_dt = t - fps_last_time;
        if (fps_dt > 0.25) {
            /* Produce a side-effect for the non-SDL version so that
             * it does not get optimized away. */
            printf("FPS = %f\n", nframes / fps_dt);
            fps_last_time = t;
            nframes = 0;
#if !SDL
            printf("%f\n", sum);
#endif
        }
#if SDL
        if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
            break;
#endif
    }
#if SDL
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
#endif
    return EXIT_SUCCESS;
}
Beispiel #18
0
 void run() {
     std::cout << "[DIS] Initializing Video Display System.\n";
     pCodecCtx = media->decode->getpCodecCtx();
     pFrame = media->decode->getpFrame();
     pFrame_BGR24 = media->opencv->getpFrame_BGR24();
     // 2.1.1. Prepare format conversion for diplaying with SDL
     // Allocate an AVFrame structure
     pFrame_YUV420P = avcodec_alloc_frame();
     if (pFrame_YUV420P == NULL) {
         std::cout << "[DIS] Could not allocate pFrame_YUV420P\n";
         exit(1);
     }
     // Determine required buffer size and allocate buffer
     buffer_YUV420P = (uint8_t *) malloc(avpicture_get_size(PIX_FMT_YUV420P,
             pCodecCtx->width, pCodecCtx->height));
     // Assign buffer to image planes
     avpicture_fill((AVPicture *) pFrame_YUV420P, buffer_YUV420P,
             PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
     // format conversion context
     pConvertCtx_YUV420P = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
             pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P,
             SWS_SPLINE, NULL, NULL, NULL);
     // 3.1.1 prepare SDL for YUV
     // allocate window, renderer, texture
     pWindow1 = SDL_CreateWindow("YUV", 0, 0, pCodecCtx->width, pCodecCtx->height, SDL_WINDOW_SHOWN);
     pRenderer1 = SDL_CreateRenderer(pWindow1, -1, SDL_RENDERER_ACCELERATED);
     bmpTex1 = SDL_CreateTexture(pRenderer1, SDL_PIXELFORMAT_YV12,
             SDL_TEXTUREACCESS_STREAMING, pCodecCtx->width, pCodecCtx->height);
     size1 = pCodecCtx->width * pCodecCtx->height;
     if (pWindow1 == NULL | pRenderer1 == NULL | bmpTex1 == NULL) {
         std::cout << "[DIS] Could not open window1: " << SDL_GetError() << std::endl;
         exit(1);
     }
     // 3.2.1 prepare SDL for BGR
     // allocate window, renderer, texture
     pWindow2 = SDL_CreateWindow("BGR", pCodecCtx->width + 5, 0, pCodecCtx->width, pCodecCtx->height, SDL_WINDOW_SHOWN);
     pRenderer2 = SDL_CreateRenderer(pWindow2, -1, SDL_RENDERER_ACCELERATED);
     bmpTex2 = SDL_CreateTexture(pRenderer2, SDL_PIXELFORMAT_BGR24,
             SDL_TEXTUREACCESS_STREAMING, pCodecCtx->width, pCodecCtx->height);
     size2 = pCodecCtx->width * pCodecCtx->height * 3;
     if (pWindow2 == NULL | pRenderer2 == NULL | bmpTex2 == NULL) {
         std::cout << "[DIS] Could not open window2: " << SDL_GetError() << std::endl;
         exit(1);
     }
     // 1.6. get video frames
     while (!terminated) {
         if (media->decode->frameDecoded) {
             // 2.1.2. convert frame to YUV for Displaying
             sws_scale(pConvertCtx_YUV420P, (const uint8_t * const*) pFrame->data, pFrame->linesize, 0,
                     pCodecCtx->height, pFrame_YUV420P->data, pFrame_YUV420P->linesize);
             // 3.1.2. copy converted YUV to SDL 2.0 texture
             SDL_LockTexture(bmpTex1, NULL, (void **) &pixels1, &pitch1);
             memcpy(pixels1, pFrame_YUV420P->data[0], size1);
             memcpy(pixels1 + size1, pFrame_YUV420P->data[2], size1 / 4);
             memcpy(pixels1 + size1 * 5 / 4, pFrame_YUV420P->data[1], size1 / 4);
             SDL_UnlockTexture(bmpTex1);
             SDL_UpdateTexture(bmpTex1, NULL, pixels1, pitch1);
             // refresh screen
             SDL_RenderClear(pRenderer1);
             SDL_RenderCopy(pRenderer1, bmpTex1, NULL, NULL);
             SDL_RenderPresent(pRenderer1);
             // 3.2.2. copy converted BGR to SDL 2.0 texture
             SDL_LockTexture(bmpTex2, NULL, (void **) &pixels2, &pitch2);
             memcpy(pixels2, pFrame_BGR24->data[0], size2);
             SDL_UnlockTexture(bmpTex2);
             SDL_UpdateTexture(bmpTex2, NULL, pixels2, pitch2);
             // refresh screen
             SDL_RenderClear(pRenderer2);
             SDL_RenderCopy(pRenderer2, bmpTex2, NULL, NULL);
             SDL_RenderPresent(pRenderer2);
         }
         // process user input
         SDL_PollEvent(&event);
         switch (event.type) {
             case SDL_KEYDOWN:
                 // check for the keyboard state
                 switch (event.key.keysym.sym) {
                         // quit
                     case SDLK_ESCAPE:
                         media->display->terminated = true;
                         break;
                         // reset emergency
                     case SDLK_r:
                         media->command->flag_reset = true;
                         break;
                         // decode qr code from image
                     case SDLK_g:
                         media->opencv->save_image = true;
                         break;
                     case SDLK_h:
                         media->opencv->send_data = true;
                         break;
                         // trim sensors
                     case SDLK_BACKSPACE:
                         media->command->flag_trim = true;
                         break;
                         // land
                     case SDLK_SPACE:
                         media->command->flag_land = true;
                         break;
                         // toggle absolute control mode
                     case SDLK_t:
                         media->command->flag_absl = !(media->command->flag_absl);
                         break;
                         // toggle combined yaw mode
                     case SDLK_y:
                         media->command->flag_cYaw = !(media->command->flag_cYaw);
                         break;
                         // calibrate magnetometer
                     case SDLK_c:
                         media->command->flag_mgnt = true;
                         break;
                         // take off
                     case SDLK_RETURN:
                         media->command->flag_takeoff = true;
                         break;
                     default:
                         break;
                 }
                 break;
         }
         // check for the keyboard state for moving keys
         Uint8 *state = SDL_GetKeyboardState(NULL);
         if (state[SDL_SCANCODE_I] || state[SDL_SCANCODE_J] ||
                 state[SDL_SCANCODE_K] || state[SDL_SCANCODE_L] ||
                 state[SDL_SCANCODE_W] || state[SDL_SCANCODE_S] ||
                 state[SDL_SCANCODE_A] || state[SDL_SCANCODE_D] ||
                 state[SDL_SCANCODE_LSHIFT] || state[SDL_SCANCODE_RSHIFT]
                 ) {
             float mult;
             float base = 0.015;
             if (state[SDL_SCANCODE_LSHIFT] || state[SDL_SCANCODE_RSHIFT]) {
                 mult = 6;
             } else {
                 mult = 1;
             }
             // W for ascend
             if (state[SDL_SCANCODE_W]) {
                 if (media->command->arg3 < 0)
                     media->command->arg3 = 0;
                 media->command->arg3 += 2 * mult*base;
                 if (media->command->arg3 > 1)
                     media->command->arg3 = 1;
             }
             // S for descend
             if (state[SDL_SCANCODE_S]) {
                 if (media->command->arg3 > 0)
                     media->command->arg3 = 0;
                 media->command->arg3 -= 2 * mult*base;
                 if (media->command->arg3 < -1)
                     media->command->arg3 = -1;
             }
             // D for move right
             if (state[SDL_SCANCODE_D]) {
                 if (media->command->arg1 < 0)
                     media->command->arg1 = 0;
                 media->command->arg1 += mult*base;
                 if (media->command->arg1 > 1)
                     media->command->arg1 = 1;
             }
             // A for move left
             if (state[SDL_SCANCODE_A]) {
                 if (media->command->arg1 > 0)
                     media->command->arg1 = 0;
                 media->command->arg1 -= mult*base;
                 if (media->command->arg1 < -1)
                     media->command->arg1 = -1;
             }
             // K for move backword
             if (state[SDL_SCANCODE_K]) {
                 if (media->command->arg2 < 0)
                     media->command->arg2 = 0;
                 media->command->arg2 += mult*base;
                 if (media->command->arg2 > 1)
                     media->command->arg2 = 1;
             }
             // I for move forward
             if (state[SDL_SCANCODE_I]) {
                 if (media->command->arg2 > 0)
                     media->command->arg2 = 0;
                 media->command->arg2 -= mult*base;
                 if (media->command->arg2 < -1)
                     media->command->arg2 = -1;
             }
             // L for turn right
             if (state[SDL_SCANCODE_L]) {
                 if (media->command->arg4 < 0)
                     media->command->arg4 = 0;
                 media->command->arg4 += mult*base;
                 if (media->command->arg4 > 1)
                     media->command->arg4 = 1;
             }
             // J for turn left
             if (state[SDL_SCANCODE_J]) {
                 if (media->command->arg4 > 0)
                     media->command->arg4 = 0;
                 media->command->arg4 -= mult*base;
                 if (media->command->arg4 < -1)
                     media->command->arg4 = -1;
             }
             media->command->flag_PCMD = true;
         }
         boost::this_thread::sleep(boost::posix_time::microseconds(300));
     }
     // release
     // *note SDL objects have to be freed before closing avcodec.
     // otherwise it causes segmentation fault for some reason.
     SDL_DestroyTexture(bmpTex1);
     SDL_DestroyTexture(bmpTex2);
     SDL_DestroyRenderer(pRenderer1);
     SDL_DestroyRenderer(pRenderer2);
     SDL_DestroyWindow(pWindow1);
     SDL_DestroyWindow(pWindow2);
     free(pFrame_YUV420P);
     free(buffer_YUV420P);
     sws_freeContext(pConvertCtx_YUV420P);
 }
Beispiel #19
0
bool mSDLSWInit(struct mSDLRenderer* renderer) {
#if !SDL_VERSION_ATLEAST(2, 0, 0)
#ifdef COLOR_16_BIT
	SDL_SetVideoMode(renderer->viewportWidth, renderer->viewportHeight, 16, SDL_DOUBLEBUF | SDL_HWSURFACE);
#else
	SDL_SetVideoMode(renderer->viewportWidth, renderer->viewportHeight, 32, SDL_DOUBLEBUF | SDL_HWSURFACE);
#endif
#endif

	unsigned width, height;
	renderer->core->desiredVideoDimensions(renderer->core, &width, &height);
#if SDL_VERSION_ATLEAST(2, 0, 0)
	renderer->window = SDL_CreateWindow(projectName, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, renderer->viewportWidth, renderer->viewportHeight, SDL_WINDOW_OPENGL | (SDL_WINDOW_FULLSCREEN_DESKTOP * renderer->player.fullscreen));
	SDL_GetWindowSize(renderer->window, &renderer->viewportWidth, &renderer->viewportHeight);
	renderer->player.window = renderer->window;
	renderer->sdlRenderer = SDL_CreateRenderer(renderer->window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
#ifdef COLOR_16_BIT
#ifdef COLOR_5_6_5
	renderer->sdlTex = SDL_CreateTexture(renderer->sdlRenderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, width, height);
#else
	renderer->sdlTex = SDL_CreateTexture(renderer->sdlRenderer, SDL_PIXELFORMAT_ABGR1555, SDL_TEXTUREACCESS_STREAMING, width, height);
#endif
#else
	renderer->sdlTex = SDL_CreateTexture(renderer->sdlRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, width, height);
#endif

	int stride;
	SDL_LockTexture(renderer->sdlTex, 0, (void**) &renderer->outputBuffer, &stride);
	renderer->core->setVideoBuffer(renderer->core, renderer->outputBuffer, stride / BYTES_PER_PIXEL);
#else
	SDL_Surface* surface = SDL_GetVideoSurface();
	SDL_LockSurface(surface);

	if (renderer->ratio == 1) {
		renderer->core->setVideoBuffer(renderer->core, surface->pixels, surface->pitch / BYTES_PER_PIXEL);
	} else {
#ifdef USE_PIXMAN
		renderer->outputBuffer = malloc(width * height * BYTES_PER_PIXEL);
		renderer->core->setVideoBuffer(renderer->core, renderer->outputBuffer, width);
#ifdef COLOR_16_BIT
#ifdef COLOR_5_6_5
		pixman_format_code_t format = PIXMAN_r5g6b5;
#else
		pixman_format_code_t format = PIXMAN_x1b5g5r5;
#endif
#else
		pixman_format_code_t format = PIXMAN_x8b8g8r8;
#endif
		renderer->pix = pixman_image_create_bits(format, width, height,
		    renderer->outputBuffer, width * BYTES_PER_PIXEL);
		renderer->screenpix = pixman_image_create_bits(format, renderer->viewportWidth, renderer->viewportHeight, surface->pixels, surface->pitch);

		pixman_transform_t transform;
		pixman_transform_init_identity(&transform);
		pixman_transform_scale(0, &transform, pixman_int_to_fixed(renderer->ratio), pixman_int_to_fixed(renderer->ratio));
		pixman_image_set_transform(renderer->pix, &transform);
		pixman_image_set_filter(renderer->pix, PIXMAN_FILTER_NEAREST, 0, 0);
#else
		return false;
#endif
	}
#endif

	return true;
}
Beispiel #20
0
int main(int argc, char* args[])
{
	//The window we'll be rendering to
	SDL_Window* window = NULL;

	//The surface contained by the window
	SDL_Surface* screenSurface = NULL;

	//Initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
	}
	else
	{
		//Create window
		window = SDL_CreateWindow("ChiPP8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
		if (window == NULL)
		{
			printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
		}
		else
		{
			//Get window surface
			screenSurface = SDL_GetWindowSurface(window);
			SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
			SDL_Texture * texture = SDL_CreateTexture(renderer,
				SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, 64, 64);
			uint32_t* pixels = new uint32_t[ 2048 ];
			int pitch;  // Pitch = 256 bytes (64 pixels * 4 bytes per pixel)
			FILE* rom;
			errno_t ferror;
			chip8* chip;
			if ((ferror = fopen_s(&rom, "pong2.c8", "rb")) != 0) {
				printf("Unable to open ROM");
				return 1;
			}
			else {


				chip = new chip8(rom);
			}
			fclose(rom);
			int returnStat;
				while ((returnStat = chip->stepCycle()) != 99) {


					SDL_LockTexture(texture, NULL, (void**)&pixels, &pitch);
					//chip->debugRender();
					
					for (int i = 0; i < 2048; i++)
					{
						if (!chip->getgfx()[i])
						{
							pixels[i] = 0000;
						}
						else
						{
							pixels[i] = 0b00101011;
						}
					}

					SDL_UnlockTexture(texture);

					SDL_RenderClear(renderer);

					SDL_RenderCopy(renderer, texture, NULL, NULL);

					SDL_RenderPresent(renderer);
				}
			
			delete[] pixels;
			SDL_DestroyTexture(texture);
			SDL_DestroyRenderer(renderer);

			

		}
	}

	//Destroy window
	SDL_DestroyWindow(window);

	//Quit SDL subsystems
	SDL_Quit();

	return 0;
}
void Video::WriteNextFrame()
{
    int frameFinished = 0;
    AVPacket packet;

    if (texturesRecreatedCount != gTexturesRecreatedCount)
    {
        texturesRecreatedCount = gTexturesRecreatedCount;

        SDL_DestroyTexture(pTexture);
        pTexture =
            SDL_CreateTexture(
                gpRenderer,
                IsYUVFormat(pCodecContext->pix_fmt) ? SDL_PIXELFORMAT_YV12 : SDL_PIXELFORMAT_ARGB8888,
                SDL_TEXTUREACCESS_STREAMING,
                width,
                height);
        SDL_SetTextureBlendMode(pTexture, SDL_BLENDMODE_BLEND);

        unsigned char *pPixels = NULL;
        int pitch = 0;

        SDL_LockTexture(pTexture, NULL, reinterpret_cast<void **>(&pPixels), &pitch);
        memcpy(pPixels, pCachedTexturePixels, pitch * height);
        SDL_UnlockTexture(pTexture);
    }

    while (!frameFinished)
    {
        if (av_read_frame(pFormatContext, &packet) != 0)
        {
            break;
        }

        if (packet.stream_index == videoStream && avcodec_decode_video2(pCodecContext, pFrame, &frameFinished, &packet) >= 0)
        {
            if (frameFinished)
            {
                AVPicture picture;
                unsigned char *pPixels = NULL;
                int pitch = 0;

                SDL_LockTexture(pTexture, NULL, reinterpret_cast<void **>(&pPixels), &pitch);

                if (IsYUVFormat(pCodecContext->pix_fmt))
                {
                    picture.data[0] = pFrame->data[0];
                    picture.data[1] = pFrame->data[1];
                    picture.data[2] = pFrame->data[2];
                    picture.linesize[0] = pFrame->linesize[0];
                    picture.linesize[1] = pFrame->linesize[1];
                    picture.linesize[2] = pFrame->linesize[2];
                }
                else
                {
                    picture.data[0] = pPixels;
                    picture.linesize[0] = pitch;
                }

                sws_scale(pImageConvertContext, pFrame->data, pFrame->linesize, 0, pFrame->height, picture.data, picture.linesize);

                if (IsYUVFormat(pCodecContext->pix_fmt))
                {
                    if (pitch == picture.linesize[0])
                    {
                        int size = pitch * pFrame->height;

                        memcpy(pPixels, picture.data[0], size);
                        memcpy(pPixels + size, picture.data[2], size / 4);
                        memcpy(pPixels + size * 5 / 4, picture.data[1], size / 4);
                    }
                    else
                    {
                        unsigned char *y1, *y2, *y3, *i1, *i2, *i3;
                        y1 = pPixels;
                        y3 = pPixels + pitch * pFrame->height;
                        y2 = pPixels + pitch * pFrame->height * 5 / 4;

                        i1 = picture.data[0];
                        i2 = picture.data[1];
                        i3 = picture.data[2];

                        for (int i = 0; i < pFrame->height / 2; i++)
                        {
                            memcpy(y1, i1, pitch);
                            i1 += picture.linesize[0];
                            y1 += pitch;
                            memcpy(y1, i1, pitch);

                            memcpy(y2, i2, pitch / 2);
                            memcpy(y3, i3, pitch / 2);

                            y1 += pitch;
                            y2 += pitch / 2;
                            y3 += pitch / 2;
                            i1 += picture.linesize[0];
                            i2 += picture.linesize[1];
                            i3 += picture.linesize[2];
                        }
                    }
                }

                memcpy(pCachedTexturePixels, pPixels, pitch * height);
                SDL_UnlockTexture(pTexture);
            }
        }

        av_free_packet(&packet);
    }
}
    //------------------------------------------------------------------------
    bool platform_support::init(unsigned width, unsigned height, unsigned flags)
    {
        ERROR_PRINT("platform_support::init %d,%d\n", width, height);
        m_window_flags = flags;
        int wflags = 0;

        if(m_specific->m_texture) SDL_DestroyTexture(m_specific->m_texture);
        if(m_specific->m_renderer) SDL_DestroyRenderer(m_specific->m_renderer);
        if(m_specific->m_surface) SDL_FreeSurface(m_specific->m_surface);
        //if(m_specific->m_mwindow) SDL_DestroyWindow(m_specific->m_mwindow);
        m_specific->m_texture = 0;
        m_specific->m_renderer = 0;
        m_specific->m_surface = 0;
        //m_specific->m_mwindow = 0;

        if(m_window_flags & window_resize)
        {
            wflags |= SDL_WINDOW_RESIZABLE;
        }
        if(m_window_flags & window_fullscreen)
        {
            wflags |= SDL_WINDOW_FULLSCREEN;
#ifdef __ANDROID__DISABLED
            width = Android_ScreenWidth;
            height = Android_ScreenHeight;
#endif

#ifdef __ANDROID__
            if (m_window_flags & window_keep_aspect_ratio)
            {
               width = (double)Android_ScreenWidth/Android_ScreenHeight*height;
               width_factor = (double)width/Android_ScreenWidth;
               hight_factor = (double)height/Android_ScreenHeight;
            }
#endif
        }
        DEBUG_PRINT("platform_support::init %d,%d,%d", width, height, wflags);

        int numRendDrv = SDL_GetNumRenderDrivers();
        DEBUG_PRINT("num rend drv %d\n", numRendDrv);

        for (int i = 0; i < numRendDrv; i++)
        {
           SDL_RendererInfo info;
           SDL_GetRenderDriverInfo(i, &info);
           DEBUG_PRINT("index %i, %s, flags %x, texture formats %x\n", i, info.name, info.flags,
                 info.texture_formats[0]);
        }

        if (!m_specific->m_mwindow)
        {
           m_specific->m_mwindow = SDL_CreateWindow(m_caption,
                 SDL_WINDOWPOS_UNDEFINED,
                 SDL_WINDOWPOS_UNDEFINED,
                 width, height,
                 wflags);
        }

        if (m_specific->m_mwindow == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create %dx%d %d bpp window: %s\n", 
                    width, 
                    height, 
                    m_bpp, 
                    SDL_GetError());
            return false;
        }

        m_specific->m_surface = SDL_CreateRGBSurface(0, width, height,
              m_bpp,
              m_specific->m_rmask, 
              m_specific->m_gmask, 
              m_specific->m_bmask, 
              m_specific->m_amask);
        DEBUG_PRINT("surface at %p", m_specific->m_surface);

        if(m_specific->m_surface == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create image buffer %dx%d %d bpp: %s\n", 
                    width, 
                    height, 
                    m_bpp, 
                    SDL_GetError());
            return false;
        }

        m_specific->m_renderer = SDL_CreateRenderer(m_specific->m_mwindow,
              -1, 0);
        if(m_specific->m_renderer == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create renderer: %s\n", 
                    SDL_GetError());
            return false;
        }

        {
           SDL_RendererInfo info;
           SDL_GetRendererInfo(m_specific->m_renderer, &info);
           DEBUG_PRINT("Current, %s, flags %x, texture formats %x, %x\n", info.name, info.flags,
                 SDL_PIXELFORMAT_ARGB8888, info.texture_formats[0]);
        }

        m_specific->m_texture = SDL_CreateTexture(
              m_specific->m_renderer,
              m_specific->m_pformat,
              SDL_TEXTUREACCESS_STREAMING, width, height);
        if(m_specific->m_renderer == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create texture: %s\n", 
                    SDL_GetError());
            return false;
        }

        void* pixels;
        int pitch;
        if (SDL_LockTexture(m_specific->m_texture, NULL, &pixels, &pitch) < 0)
        {
           SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                 "Couldn't lock texture: %s\n",
                 SDL_GetError());
        }

        m_rbuf_window.attach((unsigned char*)pixels, 
                             width, height, 
                             m_flip_y ? -pitch : pitch);


        if (!m_specific->m_initialized)
        {
            m_initial_width = width;
            m_initial_height = height;
            on_init();
            m_specific->m_initialized = true;
        }
        on_resize(m_rbuf_window.width(), m_rbuf_window.height());
        m_specific->m_update_flag = true;
        return true;
    }
Beispiel #23
0
bool LTexture::loadFromFile( std::string path )
{
	//Get rid of preexisting texture
	free();

	//The final texture
	SDL_Texture* newTexture = NULL;

	//Load image at specified path
	SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
	if( loadedSurface == NULL )
	{
		printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
	}
	else
	{
		//Convert surface to display format
		SDL_Surface* formattedSurface = SDL_ConvertSurfaceFormat( loadedSurface, SDL_PIXELFORMAT_RGBA8888, NULL );
		if( formattedSurface == NULL )
		{
			printf( "Unable to convert loaded surface to display format! %s\n", SDL_GetError() );
		}
		else
		{
			//Create blank streamable texture
			newTexture = SDL_CreateTexture( gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, formattedSurface->w, formattedSurface->h );
			if( newTexture == NULL )
			{
				printf( "Unable to create blank texture! SDL Error: %s\n", SDL_GetError() );
			}
			else
			{
				//Enable blending on texture
				SDL_SetTextureBlendMode( newTexture, SDL_BLENDMODE_BLEND );

				//Lock texture for manipulation
				SDL_LockTexture( newTexture, &formattedSurface->clip_rect, &mPixels, &mPitch );

				//Copy loaded/formatted surface pixels
				memcpy( mPixels, formattedSurface->pixels, formattedSurface->pitch * formattedSurface->h );

				//Get image dimensions
				mWidth = formattedSurface->w;
				mHeight = formattedSurface->h;

				//Get pixel data in editable format
				Uint32* pixels = (Uint32*)mPixels;
				int pixelCount = ( mPitch / 4 ) * mHeight;

				//Map colors				
				Uint32 colorKey = SDL_MapRGB( formattedSurface->format, 0, 0xFF, 0xFF );
				Uint32 transparent = SDL_MapRGBA( formattedSurface->format, 0x00, 0xFF, 0xFF, 0x00 );

				//Color key pixels
				for( int i = 0; i < pixelCount; ++i )
				{
					if( pixels[ i ] == colorKey )
					{
						pixels[ i ] = transparent;
					}
				}

				//Unlock texture to update
				SDL_UnlockTexture( newTexture );
				mPixels = NULL;
			}

			//Get rid of old formatted surface
			SDL_FreeSurface( formattedSurface );
		}	
		
		//Get rid of old loaded surface
		SDL_FreeSurface( loadedSurface );
	}

	//Return success
	mTexture = newTexture;
	return mTexture != NULL;
}
Beispiel #24
0
void ttexture_lock::lock()
{
	if (SDL_LockTexture(texture_, NULL, &pixels, &pitch) != 0) {
		throw texception("Could not lock a texture", true);
	}
}