Esempio n. 1
0
wxBitmap::wxBitmap(const wxImage& image, int depth )
{
    Qt::ImageConversionFlags flags = 0;
    if (depth == 1)
        flags = Qt::MonoOnly;
    m_refData = new wxBitmapRefData(QPixmap::fromImage(ConvertImage(image), flags));
}
Esempio n. 2
0
bool wxStaticBitmap::Create(wxWindow *parent,
                            wxWindowID id,
                            const wxGDIImage& bitmap,
                            const wxPoint& pos,
                            const wxSize& size,
                            long style,
                            const wxString& name)
{
    if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) )
        return false;

    // we may have either bitmap or icon: if a bitmap with mask is passed, we
    // will transform it to an icon ourselves because otherwise the mask will
    // be ignored by Windows
    m_isIcon = bitmap.IsKindOf(CLASSINFO(wxIcon));

    wxGDIImage *image = ConvertImage( bitmap );
    m_isIcon = image->IsKindOf( CLASSINFO(wxIcon) );

    // create the native control
    if ( !MSWCreateControl(_T("STATIC"), wxEmptyString, pos, size) )
    {
        // control creation failed
        return false;
    }

    // no need to delete the new image
    SetImageNoCopy(image);

    // GetBestSize will work properly now, so set the best size if needed
    SetInitialSize(size);

    return true;
}
Esempio n. 3
0
void wxStaticBitmap::SetImage( const wxGDIImage& rBitmap )
{
    int nX = 0;
    int nY = 0;
    int nWidth = 0;
    int nHeight = 0;

    Free();
    ::WinSendMsg( GetHwnd()
                 ,SM_SETHANDLE
                 ,MPFROMHWND(rBitmap.GetHandle())
                 ,NULL
                );
    m_pImage = ConvertImage(rBitmap);

    GetPosition(&nX, &nY);
    GetSize(&nWidth, &nHeight);
    // Convert to OS/2 coordinate system
    nY = wxWindow::GetOS2ParentHeight(GetParent()) - nY - nHeight;

    RECTL                           vRect;

    vRect.xLeft   = nX;
    vRect.yTop    = nY + nHeight;
    vRect.xRight  = nX + nWidth;
    vRect.yBottom = nY;

    ::WinInvalidateRect(GetHwndOf(GetParent()), &vRect, TRUE);
}
Esempio n. 4
0
static image::Image *
getSurfaceImage(IDirect3DDevice8 *pDevice,
                IDirect3DSurface8 *pSurface) {
    image::Image *image = NULL;
    HRESULT hr;

    if (!pSurface) {
        return NULL;
    }

    D3DSURFACE_DESC Desc;
    hr = pSurface->GetDesc(&Desc);
    assert(SUCCEEDED(hr));

    D3DLOCKED_RECT LockedRect;
    hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK);
    if (FAILED(hr)) {
        return NULL;
    }

    image = ConvertImage(Desc.Format, LockedRect.pBits, LockedRect.Pitch, Desc.Width, Desc.Height);

    pSurface->UnlockRect();

    return image;
}
Esempio n. 5
0
static image::Image *
getSurfaceImage(IDirect3DDevice7 *pDevice,
                     IDirectDrawSurface7 *pSurface)
{
    HRESULT hr;

    DDSURFACEDESC2 Desc;
    ZeroMemory(&Desc, sizeof Desc);
    Desc.dwSize = sizeof Desc;

    hr = pSurface->Lock(NULL, &Desc, DDLOCK_WAIT | DDLOCK_READONLY | DDLOCK_SURFACEMEMORYPTR | DDLOCK_NOSYSLOCK, NULL);
    if (FAILED(hr)) {
        std::cerr << "warning: IDirectDrawSurface7::Lock failed\n";
        return NULL;
    }

    image::Image *image = NULL;
    D3DFORMAT Format = convertFormat(Desc.ddpfPixelFormat);
    if (Format == D3DFMT_UNKNOWN) {
        std::cerr << "warning: unsupported DDPIXELFORMAT\n";
    } else {
        image = ConvertImage(Format, Desc.lpSurface, Desc.lPitch, Desc.dwWidth, Desc.dwHeight);
    }

    pSurface->Unlock(NULL);

    return image;
}
Esempio n. 6
0
// ------------------------------------------------------------------------
void OpenCVValve::InitialiseFromValve(const ValveLine<2>::Pointer &input)
{
	ConvertImage(input->GetImage(), m_Image);

	// set the points as the continuous indexs
	m_P1.x = input->GetInd1()[0];
	m_P1.y = input->GetInd1()[1];
	m_P2.x = input->GetInd2()[0];
	m_P2.y = input->GetInd2()[1];
}
Esempio n. 7
0
bool wxStaticBitmap::Create(wxWindow *parent,
                            wxWindowID id,
                            const wxGDIImage& bitmap,
                            const wxPoint& pos,
                            const wxSize& size,
                            long style,
                            const wxString& name)
{
    if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) )
        return false;

    // we may have either bitmap or icon: if a bitmap with mask is passed, we
    // will transform it to an icon ourselves because otherwise the mask will
    // be ignored by Windows
    m_isIcon = bitmap.IsKindOf(CLASSINFO(wxIcon));

    wxGDIImage *image = ConvertImage( bitmap );
    m_isIcon = image->IsKindOf( CLASSINFO(wxIcon) );

    // create the native control
    if ( !MSWCreateControl(wxT("STATIC"), wxEmptyString, pos, size) )
    {
        // control creation failed
        return false;
    }

    // no need to delete the new image
    SetImageNoCopy(image);

    // GetBestSize will work properly now, so set the best size if needed
    SetInitialSize(size);

    // painting manually is reported not to work under Windows CE (see #10093),
    // so don't do it there even if this probably means that alpha is not
    // supported there -- but at least bitmaps without alpha appear correctly
#ifndef __WXWINCE__
    // Windows versions before XP (and even XP if the application has no
    // manifest and so the old comctl32.dll is used) don't draw correctly the
    // images with alpha channel so we need to draw them ourselves and it's
    // easier to just always do it rather than check if we have an image with
    // alpha or not
    if ( wxTheApp->GetComCtl32Version() < 600 )
    {
        Connect(wxEVT_PAINT, wxPaintEventHandler(wxStaticBitmap::DoPaintManually));
    }
#endif // !__WXWINCE__

    return true;
}
Esempio n. 8
0
SoftBitmap::SoftBitmap(const uint8* data, uint bytes, bool transparent, uint32 flags) {
	format = transparent ? pixel_format : opaque_pixel_format;

	int width, height;
	void* pixels;

	if (bytes > 4 && strncmp((char*) data, "XYZ1", 4) == 0)
		ImageXYZ::ReadXYZ(data, bytes, transparent, width, height, pixels);
	else if (bytes > 2 && strncmp((char*) data, "BM", 2) == 0)
		ImageBMP::ReadBMP(data, bytes, transparent, width, height, pixels);
	else
		ImagePNG::ReadPNG((FILE*) NULL, (const void*) data, transparent, width, height, pixels);

	ConvertImage(width, height, pixels, transparent);

	CheckPixels(flags);
}
Esempio n. 9
0
PixmanBitmap::PixmanBitmap(const uint8* data, uint bytes, bool transparent, uint32 flags) {
	format = (transparent ? pixel_format : opaque_pixel_format);
	pixman_format = find_format(format);

	int w, h;
	void* pixels;

	if (bytes > 4 && strncmp((char*) data, "XYZ1", 4) == 0)
		ImageXYZ::ReadXYZ(data, bytes, transparent, w, h, pixels);
	else if (bytes > 2 && strncmp((char*) data, "BM", 4) == 0)
		ImageBMP::ReadBMP(data, bytes, transparent, w, h, pixels);
	else
		ImagePNG::ReadPNG((FILE*) NULL, (const void*) data, transparent, w, h, pixels);

	Init(w, h, (void *) NULL);
	ConvertImage(w, h, pixels, transparent);

	CheckPixels(flags);
}
Esempio n. 10
0
bool wxStaticBitmap::Create(wxWindow *parent,
                            wxWindowID id,
                            const wxGDIImage& bitmap,
                            const wxPoint& pos,
                            const wxSize& size,
                            long style,
                            const wxString& name)
{
    if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) )
        return false;

    // we may have either bitmap or icon: if a bitmap with mask is passed, we
    // will transform it to an icon ourselves because otherwise the mask will
    // be ignored by Windows
    m_isIcon = bitmap.IsKindOf(CLASSINFO(wxIcon));

    wxGDIImage *image = ConvertImage( bitmap );
    m_isIcon = image->IsKindOf( CLASSINFO(wxIcon) );

    // create the native control
    if ( !MSWCreateControl(_T("STATIC"), wxEmptyString, pos, size) )
    {
        // control creation failed
        return false;
    }

    // no need to delete the new image
    SetImageNoCopy(image);

    // GetBestSize will work properly now, so set the best size if needed
    SetInitialSize(size);

    // Win9x and 2000 don't draw correctly the images with alpha channel so we
    // need to draw them ourselves and it's easier to just always do it rather
    // than check if we have an image with alpha or not
    if ( wxGetWinVersion() <= wxWinVersion_2000 )
    {
	Connect(wxEVT_PAINT, wxPaintEventHandler(wxStaticBitmap::DoPaintManually));
    }

    return true;
}
Esempio n. 11
0
bool cGame::loadTexture(char *filepath, int identifier) {
	int img_width, img_height = 0;
	corona::Image *img = corona::OpenImage(filepath);

	if (img) {
		img = ConvertImage(img, corona::PF_R8G8B8A8);

		img_width = img->getWidth();
		img_height = img->getHeight();

		glGenTextures(1, &img_id[identifier]);
		glBindTexture(GL_TEXTURE_2D, img_id[identifier]);

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

		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img_width, img_height, 0, GL_RGBA, GL_UNSIGNED_BYTE
			, img->getPixels());
	}
	return true;
}
Esempio n. 12
0
PixmanBitmap::PixmanBitmap(const std::string filename, bool transparent, uint32 flags) {
	format = (transparent ? pixel_format : opaque_pixel_format);
	pixman_format = find_format(format);

	int namelen = (int) filename.size();
	if (namelen < 5 || filename[namelen - 4] != '.') {
		Output::Error("Invalid extension for image file %s", filename.c_str());
		return;
	}

	std::string ext = Utils::LowerCase(filename.substr(namelen - 3, 3));
	if (ext != "png" && ext != "xyz" && ext != "bmp") {
		Output::Error("Unsupported image file %s", filename.c_str());
		return;
	}

	FILE* stream = FileFinder::fopenUTF8(filename, "rb");
	if (!stream) {
		Output::Error("Couldn't open image file %s", filename.c_str());
		return;
	}

	int w, h;
	void* pixels;

	if (ext == "png")
		ImagePNG::ReadPNG(stream, (void*) NULL, transparent, w, h, pixels);
	else if (ext == "xyz")
		ImageXYZ::ReadXYZ(stream, transparent, w, h, pixels);
	else if (ext == "bmp")
		ImageBMP::ReadBMP(stream, transparent, w, h, pixels);

	fclose(stream);

	Init(w, h, (void *) NULL);
	ConvertImage(w, h, pixels, transparent);

	CheckPixels(flags);
}
Esempio n. 13
0
void wxStaticBitmap::SetImage( const wxGDIImage* image )
{
    wxGDIImage* convertedImage = ConvertImage( *image );
    SetImageNoCopy( convertedImage );
    InvalidateBestSize();
}
Esempio n. 14
0
bool wxStaticBitmap::Create( wxWindow*         pParent,
                             wxWindowID        nId,
                             const wxGDIImage& rBitmap,
                             const wxPoint&    rPos,
                             const wxSize&     WXUNUSED(rSize),
                             long              lStyle,
                             const wxString&   rName )
{
    ERRORID                         vError;
    wxString                        sError;

    Init();

    SetName(rName);
    if (pParent)
        pParent->AddChild(this);

    if (nId == -1)
        m_windowId = (int)NewControlId();
    else
        m_windowId = nId;

    m_windowStyle = lStyle;

    int                             nX= rPos.x;
    int                             nY = rPos.y;
    char                            zId[16];

    m_windowStyle = lStyle;

    m_bIsIcon = rBitmap.IsKindOf(CLASSINFO(wxIcon));

    //
    // For now we only support an ICON
    //
    int                             nWinstyle = SS_ICON;

    m_hWnd = (WXHWND)::WinCreateWindow( pParent->GetHWND()
                                       ,(PSZ)wxCanvasClassName
                                       ,zId
                                       ,nWinstyle | WS_VISIBLE
                                       ,0,0,0,0
                                       ,pParent->GetHWND()
                                       ,HWND_TOP
                                       ,m_windowId
                                       ,NULL
                                       ,NULL
                                      );
    if (!m_hWnd)
    {
        vError = ::WinGetLastError(wxGetInstance());
        sError = wxPMErrorToStr(vError);
        return false;
    }
    wxCHECK_MSG( m_hWnd, false, wxT("Failed to create static bitmap") );
    m_pImage = ConvertImage(rBitmap);
    ::WinSendMsg(   m_hWnd,
                    SM_SETHANDLE,
                    MPFROMHWND(rBitmap.GetHandle()),
                    (MPARAM)0);

    // Subclass again for purposes of dialog editing mode
    SubclassWin(m_hWnd);
    SetSize(nX, nY, m_pImage->GetWidth(), m_pImage->GetHeight());

    return true;
} // end of wxStaticBitmap::Create
Esempio n. 15
0
void wxStaticBitmap::SetImage( const wxGDIImage* image )
{
    wxGDIImage* convertedImage = ConvertImage( *image );
    SetImageNoCopy( convertedImage );
}
Esempio n. 16
0
wxImage wxBitmap::ConvertToImage() const
{
    return ConvertImage(M_PIXDATA.toImage());
}
Esempio n. 17
0
image::Image *
getSubResourceImage(ID3D10Device *pDevice,
                    ID3D10Resource *pResource,
                    DXGI_FORMAT Format,
                    UINT ArraySlice,
                    UINT MipSlice)
{
    image::Image *image = NULL;
    UINT SubResource;
    D3D10_MAPPED_TEXTURE3D MappedSubResource;
    HRESULT hr;

    if (!pResource) {
        return NULL;
    }

    ResourceDesc Desc;
    getResourceDesc(pResource, &Desc);
    assert(ArraySlice < Desc.ArraySize);
    assert(MipSlice < Desc.MipLevels);
    assert(Desc.SampleDesc.Count > 0);

    SubResource = ArraySlice*Desc.MipLevels + MipSlice;

    /*
     * Resolve the subresource.
     */

    ResourceDesc ResolvedDesc = Desc;
    ResolvedDesc.Width  = std::max(Desc.Width  >> MipSlice, 1U);
    ResolvedDesc.Height = std::max(Desc.Height >> MipSlice, 1U);
    ResolvedDesc.Depth  = std::max(Desc.Depth  >> MipSlice, 1U);
    ResolvedDesc.ArraySize = 1;
    ResolvedDesc.MipLevels = 1;
    ResolvedDesc.SampleDesc.Count = 1;
    ResolvedDesc.SampleDesc.Quality = 0;
    ResolvedDesc.Usage = D3D10_USAGE_DEFAULT;
    ResolvedDesc.BindFlags = 0;
    ResolvedDesc.CPUAccessFlags = 0;
    ResolvedDesc.MiscFlags = 0;

    com_ptr<ID3D10Resource> pResolvedResource;
    if (Desc.SampleDesc.Count == 1) {
        pResolvedResource = pResource;
    } else {
        hr = createResource(pDevice, &ResolvedDesc, &pResolvedResource);
        if (FAILED(hr)) {
            return NULL;
        }

        pDevice->ResolveSubresource(pResolvedResource, 0, pResource, SubResource, Format);
        SubResource = 0;
    }

    /*
     * Stage the subresource.
     */

    ResourceDesc StagingDesc = ResolvedDesc;
    StagingDesc.Usage = D3D10_USAGE_STAGING;
    StagingDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;

    com_ptr<ID3D10Resource> pStagingResource;
    hr = createResource(pDevice, &StagingDesc, &pStagingResource);
    if (FAILED(hr)) {
        return NULL;
    }

    pDevice->CopySubresourceRegion(pStagingResource, 0, 0, 0, 0, pResolvedResource, SubResource, NULL);

    /*
     * Map and read the subresource.
     */

    hr = mapResource(pStagingResource, 0, D3D10_MAP_READ, 0, &MappedSubResource);
    if (FAILED(hr)) {
        goto no_map;
    }

    image = ConvertImage(Format,
                         MappedSubResource.pData,
                         MappedSubResource.RowPitch,
                         StagingDesc.Width, StagingDesc.Height);

    unmapResource(pStagingResource, 0);
no_map:
    return image;
}
Esempio n. 18
0
void
TexUnpackBytes::TexOrSubImage(bool isSubImage, bool needsRespec, const char* funcName,
                              WebGLTexture* tex, TexImageTarget target, GLint level,
                              const webgl::DriverUnpackInfo* dui, GLint xOffset,
                              GLint yOffset, GLint zOffset, GLenum* const out_glError)
{
    WebGLContext* webgl = tex->mContext;
    gl::GLContext* gl = webgl->gl;

    const void* uploadBytes = mBytes;
    UniqueBuffer tempBuffer;

    do {
        if (!webgl->mPixelStore_FlipY && !webgl->mPixelStore_PremultiplyAlpha)
            break;

        if (!mBytes || !mWidth || !mHeight || !mDepth)
            break;

        if (webgl->IsWebGL2())
            break;
        MOZ_ASSERT(mDepth == 1);

        // This is literally the worst.
        webgl->GenerateWarning("%s: Uploading ArrayBuffers with FLIP_Y or"
                               " PREMULTIPLY_ALPHA is slow.",
                               funcName);

        tempBuffer = malloc(mByteCount);
        if (!tempBuffer) {
            *out_glError = LOCAL_GL_OUT_OF_MEMORY;
            return;
        }

        const webgl::PackingInfo pi = { dui->unpackFormat, dui->unpackType };

        const auto bytesPerPixel           = webgl::BytesPerPixel(pi);
        const auto rowByteAlignment        = webgl->mPixelStore_UnpackAlignment;

        const size_t bytesPerRow = bytesPerPixel * mWidth;
        const size_t rowStride = RoundUpToMultipleOf(bytesPerRow, rowByteAlignment);

        const bool needsYFlip = webgl->mPixelStore_FlipY;

        bool needsAlphaPremult = webgl->mPixelStore_PremultiplyAlpha;
        if (!UnpackFormatHasAlpha(pi.format))
            needsAlphaPremult = false;

        if (!needsAlphaPremult) {
            if (!webgl->mPixelStore_FlipY)
                break;

            const uint8_t* src = (const uint8_t*)mBytes;
            const uint8_t* const srcEnd = src + rowStride * mHeight;

            uint8_t* dst = (uint8_t*)tempBuffer.get() + rowStride * (mHeight - 1);

            while (src != srcEnd) {
                memcpy(dst, src, bytesPerRow);
                src += rowStride;
                dst -= rowStride;
            }

            uploadBytes = tempBuffer.get();
            break;
        }

        const auto texelFormat = FormatFromPacking(pi);
        if (texelFormat == WebGLTexelFormat::FormatNotSupportingAnyConversion) {
            MOZ_ASSERT(false, "Bad texelFormat from pi.");
            *out_glError = LOCAL_GL_OUT_OF_MEMORY;
            return;
        }

        const auto srcOrigin = gl::OriginPos::BottomLeft;
        const auto dstOrigin = (needsYFlip ? gl::OriginPos::TopLeft
                                           : gl::OriginPos::BottomLeft);

        const bool srcPremultiplied = false;
        const bool dstPremultiplied = needsAlphaPremult; // Always true here.
        // And go!:
        if (!ConvertImage(mWidth, mHeight,
                          mBytes, rowStride, srcOrigin, texelFormat, srcPremultiplied,
                          tempBuffer.get(), rowStride, dstOrigin, texelFormat,
                          dstPremultiplied))
        {
            MOZ_ASSERT(false, "ConvertImage failed unexpectedly.");
            *out_glError = LOCAL_GL_OUT_OF_MEMORY;
            return;
        }

        uploadBytes = tempBuffer.get();
    } while (false);

    GLenum error = DoTexOrSubImage(isSubImage, gl, target, level, dui, xOffset, yOffset,
                                   zOffset, mWidth, mHeight, mDepth, uploadBytes);
    *out_glError = error;
}
Esempio n. 19
0
bool
TexUnpackBlob::ConvertIfNeeded(WebGLContext* webgl, const char* funcName,
                               const uint32_t rowLength, const uint32_t rowCount,
                               WebGLTexelFormat srcFormat,
                               const uint8_t* const srcBegin, const ptrdiff_t srcStride,
                               WebGLTexelFormat dstFormat, const ptrdiff_t dstStride,
                               const uint8_t** const out_begin,
                               UniqueBuffer* const out_anchoredBuffer) const
{
    MOZ_ASSERT(srcFormat != WebGLTexelFormat::FormatNotSupportingAnyConversion);
    MOZ_ASSERT(dstFormat != WebGLTexelFormat::FormatNotSupportingAnyConversion);

    *out_begin = srcBegin;

    if (!rowLength || !rowCount)
        return true;

    const auto srcIsPremult = (mSrcAlphaType == gfxAlphaType::Premult);
    const auto& dstIsPremult = webgl->mPixelStore_PremultiplyAlpha;
    const auto fnHasPremultMismatch = [&]() {
        if (mSrcAlphaType == gfxAlphaType::Opaque)
            return false;

        if (!HasColorAndAlpha(srcFormat))
            return false;

        return srcIsPremult != dstIsPremult;
    };

    const auto srcOrigin = (webgl->mPixelStore_FlipY ? gl::OriginPos::TopLeft
                                                     : gl::OriginPos::BottomLeft);
    const auto dstOrigin = gl::OriginPos::BottomLeft;

    if (srcFormat != dstFormat) {
        webgl->GeneratePerfWarning("%s: Conversion requires pixel reformatting. (%u->%u)",
                                   funcName, uint32_t(srcFormat),
                                   uint32_t(dstFormat));
    } else if (fnHasPremultMismatch()) {
        webgl->GeneratePerfWarning("%s: Conversion requires change in"
                                   " alpha-premultiplication.",
                                   funcName);
    } else if (srcOrigin != dstOrigin) {
        webgl->GeneratePerfWarning("%s: Conversion requires y-flip.", funcName);
    } else if (srcStride != dstStride) {
        webgl->GeneratePerfWarning("%s: Conversion requires change in stride. (%u->%u)",
                                   funcName, uint32_t(srcStride), uint32_t(dstStride));
    } else {
        return true;
    }

    ////

    const auto dstTotalBytes = CheckedUint32(rowCount) * dstStride;
    if (!dstTotalBytes.isValid()) {
        webgl->ErrorOutOfMemory("%s: Calculation failed.", funcName);
        return false;
    }

    UniqueBuffer dstBuffer = calloc(1, dstTotalBytes.value());
    if (!dstBuffer.get()) {
        webgl->ErrorOutOfMemory("%s: Failed to allocate dest buffer.", funcName);
        return false;
    }
    const auto dstBegin = static_cast<uint8_t*>(dstBuffer.get());

    ////

    // And go!:
    bool wasTrivial;
    if (!ConvertImage(rowLength, rowCount,
                      srcBegin, srcStride, srcOrigin, srcFormat, srcIsPremult,
                      dstBegin, dstStride, dstOrigin, dstFormat, dstIsPremult,
                      &wasTrivial))
    {
        webgl->ErrorImplementationBug("%s: ConvertImage failed.", funcName);
        return false;
    }

    *out_begin = dstBegin;
    *out_anchoredBuffer = Move(dstBuffer);
    return true;
}
Esempio n. 20
0
/*static*/ bool
TexUnpackSurface::ConvertSurface(WebGLContext* webgl, const webgl::DriverUnpackInfo* dui,
                                 gfx::DataSourceSurface* surf, bool isSurfAlphaPremult,
                                 UniqueBuffer* const out_convertedBuffer,
                                 uint8_t* const out_convertedAlignment,
                                 bool* const out_outOfMemory)
{
    *out_outOfMemory = false;

    const size_t width = surf->GetSize().width;
    const size_t height = surf->GetSize().height;

    // Source args:

    // After we call this, on OSX, our GLContext will no longer be current.
    gfx::DataSourceSurface::ScopedMap srcMap(surf, gfx::DataSourceSurface::MapType::READ);
    if (!srcMap.IsMapped())
        return false;

    const void* const srcBegin = srcMap.GetData();
    const size_t srcStride = srcMap.GetStride();

    WebGLTexelFormat srcFormat;
    if (!GetFormatForSurf(surf, &srcFormat))
        return false;

    const bool srcPremultiplied = isSurfAlphaPremult;

    // Dest args:

    WebGLTexelFormat dstFormat;
    if (!GetFormatForPackingTuple(dui->unpackFormat, dui->unpackType, &dstFormat))
        return false;

    const auto bytesPerPixel = webgl::BytesPerPixel({dui->unpackFormat, dui->unpackType});
    const size_t dstRowBytes = bytesPerPixel * width;

    const size_t dstAlignment = 8; // Just use the max!
    const size_t dstStride = RoundUpToMultipleOf(dstRowBytes, dstAlignment);

    CheckedUint32 checkedDstSize = dstStride;
    checkedDstSize *= height;
    if (!checkedDstSize.isValid()) {
        *out_outOfMemory = true;
        return false;
    }

    const size_t dstSize = checkedDstSize.value();

    UniqueBuffer dstBuffer = malloc(dstSize);
    if (!dstBuffer) {
        *out_outOfMemory = true;
        return false;
    }
    void* const dstBegin = dstBuffer.get();

    gl::OriginPos srcOrigin, dstOrigin;
    OriginsForDOM(webgl, &srcOrigin, &dstOrigin);

    const bool dstPremultiplied = webgl->mPixelStore_PremultiplyAlpha;

    // And go!:
    if (!ConvertImage(width, height,
                      srcBegin, srcStride, srcOrigin, srcFormat, srcPremultiplied,
                      dstBegin, dstStride, dstOrigin, dstFormat, dstPremultiplied))
    {
        MOZ_ASSERT(false, "ConvertImage failed unexpectedly.");
        NS_ERROR("ConvertImage failed unexpectedly.");
        *out_outOfMemory = true;
        return false;
    }

    *out_convertedBuffer = Move(dstBuffer);
    *out_convertedAlignment = dstAlignment;
    return true;
}
Esempio n. 21
0
bool
TexUnpackBlob::ConvertIfNeeded(WebGLContext* webgl, const char* funcName,
                               const uint8_t* srcBytes, uint32_t srcStride,
                               uint8_t srcBPP, WebGLTexelFormat srcFormat,
                               const webgl::DriverUnpackInfo* dstDUI,
                               const uint8_t** const out_bytes,
                               UniqueBuffer* const out_anchoredBuffer) const
{
    *out_bytes = srcBytes;

    if (!HasData() || !mWidth || !mHeight || !mDepth)
        return true;

    //////

    const auto totalSkipRows = mSkipRows + CheckedUint32(mSkipImages) * mImageHeight;
    const auto offset = mSkipPixels * CheckedUint32(srcBPP) + totalSkipRows * srcStride;
    if (!offset.isValid()) {
        webgl->ErrorOutOfMemory("%s: Invalid offset calculation during conversion.",
                                funcName);
        return false;
    }
    const uint32_t skipBytes = offset.value();

    auto const srcBegin = srcBytes + skipBytes;

    //////

    const auto srcOrigin = (webgl->mPixelStore_FlipY ? gl::OriginPos::TopLeft
                                                     : gl::OriginPos::BottomLeft);
    const auto dstOrigin = gl::OriginPos::BottomLeft;
    const bool isDstPremult = webgl->mPixelStore_PremultiplyAlpha;

    const auto pi = dstDUI->ToPacking();

    const auto dstBPP = webgl::BytesPerPixel(pi);
    const auto dstWidthBytes = CheckedUint32(dstBPP) * mWidth;
    const auto dstRowLengthBytes = CheckedUint32(dstBPP) * mRowLength;

    const auto dstAlignment = mAlignment;
    const auto dstStride = RoundUpToMultipleOf(dstRowLengthBytes, dstAlignment);

    //////

    const auto dstTotalRows = CheckedUint32(mDepth - 1) * mImageHeight + mHeight;
    const auto dstUsedSizeExceptLastRow = (dstTotalRows - 1) * dstStride;

    const auto dstSize = skipBytes + dstUsedSizeExceptLastRow + dstWidthBytes;
    if (!dstSize.isValid()) {
        webgl->ErrorOutOfMemory("%s: Invalid dstSize calculation during conversion.",
                                funcName);
        return false;
    }

    //////

    const auto dstFormat = FormatForPackingInfo(pi);

    bool premultMatches = (mIsSrcPremult == isDstPremult);
    if (!UnpackFormatHasColorAndAlpha(dstDUI->unpackFormat)) {
        premultMatches = true;
    }

    const bool needsPixelConversion = (srcFormat != dstFormat || !premultMatches);
    const bool originsMatch = (srcOrigin == dstOrigin);

    MOZ_ASSERT_IF(!needsPixelConversion, srcBPP == dstBPP);

    if (!needsPixelConversion &&
        originsMatch &&
        srcStride == dstStride.value())
    {
        // No conversion needed!
        return true;
    }

    //////
    // We need some sort of conversion, so create the dest buffer.

    *out_anchoredBuffer = calloc(1, dstSize.value());
    const auto dstBytes = (uint8_t*)out_anchoredBuffer->get();

    if (!dstBytes) {
        webgl->ErrorOutOfMemory("%s: Unable to allocate buffer during conversion.",
                                funcName);
        return false;
    }
    *out_bytes = dstBytes;
    const auto dstBegin = dstBytes + skipBytes;

    //////
    // Row conversion

    if (!needsPixelConversion) {
        webgl->GenerateWarning("%s: Incurred CPU row conversion, which is slow.",
                               funcName);

        const uint8_t* srcRow = srcBegin;
        uint8_t* dstRow = dstBegin;
        const auto widthBytes = dstWidthBytes.value();
        ptrdiff_t dstCopyStride = dstStride.value();

        if (!originsMatch) {
            dstRow += dstUsedSizeExceptLastRow.value();
            dstCopyStride = -dstCopyStride;
        }

        for (uint32_t i = 0; i < dstTotalRows.value(); i++) {
            memcpy(dstRow, srcRow, widthBytes);
            srcRow += srcStride;
            dstRow += dstCopyStride;
        }
        return true;
    }

    ////////////
    // Pixel conversion.

    MOZ_ASSERT(srcFormat != WebGLTexelFormat::FormatNotSupportingAnyConversion);
    MOZ_ASSERT(dstFormat != WebGLTexelFormat::FormatNotSupportingAnyConversion);

    webgl->GenerateWarning("%s: Incurred CPU pixel conversion, which is very slow.",
                           funcName);

    //////

    // And go!:
    bool wasTrivial;
    if (!ConvertImage(mWidth, dstTotalRows.value(),
                      srcBegin, srcStride, srcOrigin, srcFormat, mIsSrcPremult,
                      dstBegin, dstStride.value(), dstOrigin, dstFormat, isDstPremult,
                      &wasTrivial))
    {
        webgl->ErrorImplementationBug("%s: ConvertImage failed.", funcName);
        return false;
    }

    if (!wasTrivial) {
        webgl->GenerateWarning("%s: Chosen format/type incurred an expensive reformat:"
                               " 0x%04x/0x%04x",
                               funcName, dstDUI->unpackFormat, dstDUI->unpackType);
    }

    return true;
}
int UnicapCamera::GetColorImage(cv::Mat* img, char* FileName )
{
	unsigned char *image_buffer = NULL;
	unicap_data_buffer_t buffer;
	unicap_data_buffer_t *returned_buffer;
	int error = 0;

	// Initialize IPL image
	CV_Assert(img != 0);
	img->create(m_Format->size.height, m_Format->size.width, CV_8UC3);

	
	// Initialize the image buffer
	memset( &buffer, 0x0, sizeof( unicap_data_buffer_t ) );
	
	if (!m_Format)
	{
		printf("UnicapCamera::Acquire: No format set!\n");
		error =  ERROR_NO_FORMAT_SET;
	}

	if ((error == 0) && (!m_Handle))
	{
		printf("UnicapCamera::Acquire: No Camera handle available.\n");
		error =   ERROR_NOT_OPENED;
	}
	
	// Allocate memory for the image buffer
	if (error == 0)
	{
		if( !( image_buffer = (unsigned char *)malloc( m_Format->buffer_size ) ) )
		{
			printf("UnicapCamera::Acquire: Failed to allocate %d bytes\n" );
			error =   ERROR_NO_MEMORY;
		}

		buffer.data = image_buffer;
		buffer.buffer_size = m_Format->buffer_size;
	}
	
	// Start the capture process on the device
	// Queue the buffer
	// The buffer now gets filled with image data by the capture device
	if (error == 0)
	{
		if( !SUCCESS( unicap_queue_buffer( *m_Handle, &buffer ) ) )
		{
			printf("UnicapCamera::Acquire: Failed to queue a buffer on device: %s\n", m_Device->identifier );
			error =   UNSPECIFIED_ERROR;
		}
	}
	
	// Wait until the image buffer is ready
	if (error == 0)
	{
		if( !SUCCESS( unicap_wait_buffer( *m_Handle, &returned_buffer ) ) )
		{
			printf("UnicapCamera::Acquire: Failed to wait for buffer on device: %s\n", m_Device->identifier );
			error =   UNSPECIFIED_ERROR;
		}
	}

	// Stop the device
	if (error == 0)
	{
		if( !returned_buffer->buffer_size )
		{
			printf("UnicapCamera::Acquire: Returned a buffer size of 0!\n" );
			error = UNSPECIFIED_ERROR;
		}
	}
	if (error == 0)
	{
		ConvertImage(img, returned_buffer);
	}

	if ((error==0) && (FileName)) cvSaveImage(FileName, Img);
	if (image_buffer)
	{
		free( image_buffer );
	}
		
	return error;
}