ImageImPro_OpenCvImpl::ImageImPro_OpenCvImpl(ImSize size, ImageImProDepth depth, int channels){
     createImage(size, depth, channels);
}
Пример #2
0
int main( int argc, const char* argv[] )
{
    setDevice();

    float maxFloat = std::numeric_limits<float>::max();
    // Prepad border bigger than we need for simplicity and profiling (256px border is silly big; we can have an SE length of 512).
    rect2d border = { 256,0 };
    cudaPaddedImage paddedImage = loadPaddedImageToDevice("../images/test.pgm", border, 255.0f);
    rect2d imageSize = getNoBorderSize(paddedImage);
    cudaImage output = createImage(imageSize.width, imageSize.height);

    /*cudaImage test = loadImageToDevice("../images/test.pgm");
    cudaImage test1 = cloneImage(test);
    cudaPaddedImage test2 = createPaddedFromImage(test, border, 255.0f);

    float *host = new float[test2.image.width*test2.image.height];
    copyImageToHost(test2.image, host);
    savePGM("fillTest.pgm", host, test2.image.width, test2.image.height);

    cudaFree(getData(test));
    cudaFree(getData(test1));
    cudaFree(getData(test2));
    */
    /*
    	Diagonal erosion 3x3
    */
    /*
    	unsigned char diag[] = {1,0,0,0,1,0,0,0,1};
    	morphMask diag3x3mask = createTBTMask(diag);
    	testErosion(paddedImage, output, imageSize, diag3x3mask, "diag3x3.pgm", "Diagonal VHGW Test");
    */
    /*
    	VHGW erosion: Horizontal, vertical, diagonal
    */
    morphMask hozMask  = createVHGWMask(43,  HORIZONTAL);
    testErosion(paddedImage, output, imageSize, hozMask, "horizontalVHGW.pgm", "VHGW Horizontal kernel"); // replaced with TVT below
    cudaFree(getData(paddedImage));
    /*morphMask slashMask = createVHGWMask(43, DIAGONAL_SLASH);
    morphMask bsMask = createVHGWMask(51, DIAGONAL_BACKSLASH);
    morphMask vertMask = createVHGWMask(51, VERTICAL);

    testErosion(paddedImage, output, imageSize, slashMask, "slashVHGW.pgm", "VHGW Diagonal kernel");
    //testErosion(paddedImage, output, imageSize, bsMask, "bsVHGW.pgm", "VHGW Backslash kernel");
    cudaPaddedImage paddedOut = createPaddedImage(border, imageSize.width, imageSize.height, 255.0f);
    performErosion(getData(paddedImage), getPitch(paddedImage), getBorderOffsetImagePtr(paddedOut), getPitch(paddedOut), imageSize, slashMask, border);

    float *host_out = copyImageToHost(paddedOut.image);
    printf("output width: %d , height: %d\n", paddedOut.image.width, paddedOut.image.height);
    savePGM("testEdges.pgm", host_out, paddedOut.image.width, paddedOut.image.height);
    freeHost(host_out, PINNED);
    */

    // Horizontal Erosion Test Mark 2: Transpose + Vertical+ Transpose
    /*cudaImage flippedImage = createTransposedImage(paddedImage.image);
    cudaFree(getData(paddedImage));

    rect2d flippedSize = {imageSize.height, imageSize.width};
    cudaImage flippedOut;
    flippedOut.width = flippedSize.width;
    flippedOut.height = flippedSize.height;
    deviceAllocImage(flippedOut);

    rect2d flippedBorder = {border.height, border.width};
    performErosion(getData(flippedImage), getPitch(flippedImage), getData(flippedOut), getPitch(flippedOut), flippedSize, vertMask, flippedBorder);
    exitOnError("VHGW Horizontal Transpose Test");

    cudaFree(getData(flippedImage));
    flippedImage = createTransposedImage(flippedOut);
    float *host_out = copyImageToHost(flippedImage);
    savePGM("horizontalTransposeVHGW.pgm", host_out, flippedImage.width, flippedImage.height);
    freeHost(host_out, PINNED);

    cudaFree(getData(flippedImage));
    cudaFree(getData(flippedOut));
    cudaFree(hozMask.data);*/
    /*cudaFree(vertMask.data);
    cudaFree(slashMask.data);
    cudaFree(bsMask.data);*/
    cudaFree(output.data);

    printf("After:");
    //showMemUsage();
    printf("-------------------\nAll tests Done.");
    return resetDevice();
}
Пример #3
0
void TuiManager::parseControl(Node* container,xml_node<char> *item)
{ 
	int tag = atof(item->first_attribute("tag")->value());
	int x = atof(item->first_attribute("x")->value());
	int y = atof(item->first_attribute("y")->value());
	int w = atoi(item->first_attribute("width")->value());
	int h = atoi(item->first_attribute("height")->value());
	int rotation = atof(item->first_attribute("rotation")->value());

	if(strcmp(item->first_attribute("type")->value(), kTuiContainerPanel) == 0){//panel
		CWidgetWindow* pPanel = createPanel(tag,x,y,w,h,rotation);
		container->addChild(pPanel);
		//recursive
		for( xml_node<char> *iitem = item->first_node( kTuiNodeControl );iitem != NULL; iitem = iitem->next_sibling()){
			parseControl(pPanel,iitem);
		}

	}else if (strcmp(item->first_attribute("type")->value(), kTuiControlCell) == 0){//cell
		//recursive
		for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
			parseControl(container, iitem);
		}

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlImage) == 0){//image
		const char* file = item->first_attribute("image")->value();
		float scaleX = atof(item->first_attribute("scaleX")->value());
		float scaleY = atof(item->first_attribute("scaleY")->value());
		CImageView *pImg = createImage(tag, file, scaleX, scaleY, x, y, rotation);
		container->addChild(pImg);
	
	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlImage9) == 0){//image9
		const char* file = item->first_attribute("image")->value();
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		float up = atof(item->first_attribute("up")->value());
		float down = atof(item->first_attribute("down")->value());
		float left = atof(item->first_attribute("left")->value());
		float right = atof(item->first_attribute("right")->value());
		CImageViewScale9 *pImg = createImage9(tag,file,x,y,w,h,up,down,left,right,rotation);
		container->addChild(pImg);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlButton) == 0){//button
		const char* normal = item->first_attribute("normal")->value();
		const char* select = item->first_attribute("select")->value();
		const char* disable = item->first_attribute("disable")->value();
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		CButton *pBtn = createBtn(tag,normal,select,disable,x,y,w,h,rotation);
		container->addChild(pBtn);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlToggleView) == 0){//toggleView
		const char* normal = item->first_attribute("normal")->value();
		const char* select = item->first_attribute("select")->value();
		const char* disable = item->first_attribute("disable")->value();
		float exclusion = atof(item->first_attribute("exclusion")->value());
		CToggleView* toggle = createToggleView(tag,exclusion,normal,select,disable,x,y,rotation);
		container->addChild(toggle);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlSlider) == 0){//slider
		const char* bg = item->first_attribute("bg")->value();
		const char* progress = item->first_attribute("progress")->value();
		const char* thumb = item->first_attribute("thumb")->value();
		CSlider *pSlider = createSlider(tag,bg,progress,thumb,x,y,rotation);
		container->addChild(pSlider);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlProgress) == 0){//progress
		const char* bg = item->first_attribute("bg")->value();
		const char* progress = item->first_attribute("progress")->value();
		CProgressBar *pProgress = createProgress(tag,bg,progress,x,y,rotation);
		container->addChild(pProgress);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlLabel) == 0){//label
		float size = atof(item->first_attribute("textSize")->value());
		int alignment = atoi(item->first_attribute("alignment")->value());
		const char* text = item->first_attribute("text")->value();
		const char* font = item->first_attribute("textFont")->value();
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		
		int r = atoi(item->first_attribute("red")->value());
		int g = atoi(item->first_attribute("green")->value());
		int b = atoi(item->first_attribute("blue")->value());
		int r2 = atoi(item->first_attribute("strokeRed")->value());
		int g2 = atoi(item->first_attribute("strokeGreen")->value());
		int b2 = atoi(item->first_attribute("strokeBlue")->value());
		int strokeSize = atoi(item->first_attribute("strokeSize")->value());
		int shadowDistance = atoi(item->first_attribute("shadowDistance")->value());
		int shadowBlur = atoi(item->first_attribute("shadowBlur")->value());
		CLabel *pLabel = createLabel(tag, text, font, alignment, size, r, g, b, x, y, w, h,
									r2,g2,b2,strokeSize,shadowDistance,shadowBlur,rotation);
		container->addChild(pLabel);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlLabelAtlas) == 0){//labelAtlas
		const char* imgPath = item->first_attribute("image")->value();
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		CLabelAtlas *pLabAtlas = createLabelAtlas(tag,imgPath,x,y,w,h,rotation);
		container->addChild(pLabAtlas);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlArmature) == 0){//armature
		const char* xml = item->first_attribute("xml")->value();
		const char* png = item->first_attribute("png")->value();
		const char* plist = item->first_attribute("plist")->value();
		const char* name = item->first_attribute("name")->value();
		Armature *pArmature = createArmature(tag,name,png,plist,xml,x,y,rotation);
		container->addChild(pArmature);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlAnim) == 0){//animation
		const char* png = item->first_attribute("png")->value();
		const char* plist = item->first_attribute("plist")->value();
		const char* name = item->first_attribute("name")->value();
		Sprite *pSprite = createAnim(tag,name,png,plist,x,y,rotation);
		container->addChild(pSprite);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlControl) == 0){//controlView
		const char* baseboard = item->first_attribute("baseboard")->value();
		const char* joystick = item->first_attribute("joystick")->value();
		CControlView *pControl = createControl(tag,baseboard,joystick,x,y,rotation);
		container->addChild(pControl);

	}else if (strcmp(item->first_attribute("type")->value(), kTuiContainerScroll) == 0){//scrollView
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		int direction = atof(item->first_attribute("direction")->value());
		int innerWidth = atoi(item->first_attribute("innerWidth")->value());
		int innerHeight = atoi(item->first_attribute("innerHeight")->value());
		CScrollView *pView = createScrollView(tag, direction, innerWidth, innerHeight, x, y, w, h, rotation);
		container->addChild(pView);
		//recursive
		for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
			parseControl(pView->getContainer(), iitem);
		}

	}else if (strcmp(item->first_attribute("type")->value(), kTuiContainerLayout) == 0){//layout
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		CLayout *pLayout = createLayout(tag, x, y, w, h, rotation);
		container->addChild(pLayout);
		//recursive
		for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
			parseControl(pLayout, iitem);
		}
		Vector<Node*> vet = pLayout->getChildren();
		for (Node *pChild : vet){//Offset coordinates Because CLayout zero point in the lower left corner
			pChild->setPosition(pChild->getPosition() + Point(w / 2, h / 2));
		}

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlListView) == 0){//listView
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		const char* img = item->first_attribute("image")->value();
		float num = atof(item->first_attribute("num")->value());
		CListView* pList = createListView(tag,img,x,y,w,h,rotation);
		container->addChild(pList);

		for(int i=0; i<num;i++){//add item
			xml_node<char> *iitem = item->first_node( kTuiNodeControl );
			w = atof(iitem->first_attribute("width")->value());
			h = atof(iitem->first_attribute("height")->value());

			CLayout *pLayout = createLayout(i,0,0,w,h,rotation);
			for( xml_node<char> *iiitem = iitem->first_node( kTuiNodeControl );iiitem!=NULL; iiitem = iiitem->next_sibling()){
				parseControl(pLayout,iiitem);
			}
			Vector<Node*> vet = pLayout->getChildren();
			for(Node *pChild : vet){//Offset coordinates Because CLayout zero point in the lower left corner
				if(pChild->getTag() > 0)
					pChild->setPosition(pChild->getPosition()+Point(w/2,h/2));
			}
			pList->insertNodeAtLast(pLayout);
		}
		pList->reloadData();

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlPageView) == 0){//pageView
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		float num = atoi(item->first_attribute("num")->value());
		int dir = atoi(item->first_attribute("direction")->value());
		const char* img = item->first_attribute("image")->value();
		CPageView *pPageView = createPageView(tag, img, dir, num, x, y, w, h, rotation);
		container->addChild(pPageView);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlCheckBox) == 0){//checkBox
		const char* normal1 = item->first_attribute("normal1")->value();
		const char* normal2 = item->first_attribute("normal2")->value();
		const char* select1 = item->first_attribute("select1")->value();
		const char* select2 = item->first_attribute("select2")->value();
		const char* disable1 = item->first_attribute("disable1")->value();
		const char* disable2 = item->first_attribute("disable2")->value();
		CCheckBox *pCheckBox = createCheckBox(tag,normal1,normal2,select1,select2,disable1,disable2,x,y,rotation);
		container->addChild(pCheckBox);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlArmatureBtn) == 0){//ArmatureBtn
		const char* png = item->first_attribute("png")->value();
		const char* plist = item->first_attribute("plist")->value();
		const char* name = item->first_attribute("name")->value();
		const char* xml = item->first_attribute("xml")->value();
		ArmatureBtn *pArmBtn = createArmatureBtn(tag,name,png,plist,xml,x,y,rotation);
		container->addChild(pArmBtn);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlNumbericStepper) == 0){//NumbericStepper
		const char* lnormal = item->first_attribute("lnormal")->value();
		const char* rnormal = item->first_attribute("rnormal")->value();
		const char* lselect = item->first_attribute("lselect")->value();
		const char* rselect = item->first_attribute("rselect")->value();
		const char* ldisable = item->first_attribute("ldisable")->value();
		const char* rdisable = item->first_attribute("rdisable")->value();
		const char* stepBg = item->first_attribute("stepBg")->value();
		NumericStepper *pNumStep = createNumStep(tag,lnormal,lselect,ldisable,rnormal,rselect,rdisable,stepBg,x,y,rotation);
		container->addChild(pNumStep);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlPaticle) == 0){//Paticle
		const char* plist = item->first_attribute("plist")->value();
		ParticleSystem *pPartical = createParticle(tag,plist,x,y);
		container->addChild(pPartical);

	}else if (strcmp(item->first_attribute("type")->value(), kTuiControlTable) == 0){//TableView
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		float num = atoi(item->first_attribute("num")->value());
		int dir = atoi(item->first_attribute("direction")->value());
		int cellWidth = atoi(item->first_attribute("cellWidth")->value());
		int cellHeight = atoi(item->first_attribute("cellHeight")->value());
		const char* img = item->first_attribute("image")->value();
		CTableView *pView = createTableView(tag, img, dir, num, cellWidth, cellHeight, x, y, w, h, rotation);
		container->addChild(pView);

	}else if (strcmp(item->first_attribute("type")->value(), kTuiControlGridView) == 0){//GridView
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		int cellWidth = atoi(item->first_attribute("cellWidth")->value());
		int cellHeight = atoi(item->first_attribute("cellHeight")->value());
		int column = atoi(item->first_attribute("column")->value());
		int num = atoi(item->first_attribute("num")->value());
		const char* img = item->first_attribute("image")->value();
		CGridView *pView = createGridView(tag, img, column, num, cellWidth, cellHeight, x, y, w, h, rotation);
		container->addChild(pView);
	
	}else if (strcmp(item->first_attribute("type")->value(), kTuiControlGridPageView) == 0){//GridPageView
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		int cellWidth = atoi(item->first_attribute("cellWidth")->value());
		int cellHeight = atoi(item->first_attribute("cellHeight")->value());
		int column = atoi(item->first_attribute("column")->value());
		int row = atoi(item->first_attribute("row")->value());
		int num = atoi(item->first_attribute("num")->value());
		int dir = atoi(item->first_attribute("direction")->value());
		const char* img = item->first_attribute("image")->value();
		CGridPageView *pView = createGridPageView(tag, img, dir, column, row, num, cellWidth, cellHeight, x, y, w, h, rotation);
		container->addChild(pView);

	}else if(strcmp(item->first_attribute("type")->value(),kTuiControlEditBox) == 0){//EditBox
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		const char* img = item->first_attribute("image")->value();
		int inputMode = atoi(item->first_attribute("inputMode")->value());
		int inputFlag = atoi(item->first_attribute("inputFlag")->value());
		EditBox *pEdit = createEditBox(tag, img, inputMode, inputFlag, x, y, w, h, rotation);
		container->addChild(pEdit);

	}else if (strcmp(item->first_attribute("type")->value(), kTuiControlMovieView) == 0){//MovieView
		const char* png = item->first_attribute("png")->value();
		const char* plist = item->first_attribute("plist")->value();
		const char* json = item->first_attribute("json")->value();
		MovieView *pMovieView = createMovieView(tag, json, plist, png, x, y, rotation);
		container->addChild(pMovieView);

	}else if (strcmp(item->first_attribute("type")->value(), kTuiContainerCircleMenu) == 0){//CircleMenu
		float w = atof(item->first_attribute("width")->value());
		float h = atof(item->first_attribute("height")->value());
		CircleMenu *pMenu = createCircleMenu(tag, x, y, w, h, rotation);
		container->addChild(pMenu);
		//recursive
		for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
			parseControl(pMenu, iitem);
		}
		pMenu->reloadData();
	}
}
Пример #4
0
status_t SurfaceTexture::updateTexImage() {
    ST_LOGV("updateTexImage");
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGE("calling updateTexImage() on an abandoned SurfaceTexture");
        return NO_INIT;
    }

    // In asynchronous mode the list is guaranteed to be one buffer
    // deep, while in synchronous mode we use the oldest buffer.
    if (!mQueue.empty()) {
        Fifo::iterator front(mQueue.begin());
        int buf = *front;

        // Update the GL texture object.
        EGLImageKHR image = mSlots[buf].mEglImage;
        EGLDisplay dpy = eglGetCurrentDisplay();
#ifdef QCOM_HARDWARE
	if (isGPUSupportedFormat(mSlots[buf].mGraphicBuffer->format)) {
            // Update the GL texture object.
            EGLImageKHR image = mSlots[buf].mEglImage;
#else
        if (image == EGL_NO_IMAGE_KHR) {
            if (mSlots[buf].mGraphicBuffer == 0) {
                ST_LOGE("buffer at slot %d is null", buf);
                return BAD_VALUE;
            }
            image = createImage(dpy, mSlots[buf].mGraphicBuffer);
            mSlots[buf].mEglImage = image;
            mSlots[buf].mEglDisplay = dpy;
#endif
            if (image == EGL_NO_IMAGE_KHR) {
#ifdef QCOM_HARDWARE
		EGLDisplay dpy = eglGetCurrentDisplay();
                if (mSlots[buf].mGraphicBuffer == 0) {
                    ST_LOGE("buffer at slot %d is null", buf);
                    return BAD_VALUE;
                }
                image = createImage(dpy, mSlots[buf].mGraphicBuffer);
                mSlots[buf].mEglImage = image;
                mSlots[buf].mEglDisplay = dpy;
                if (image == EGL_NO_IMAGE_KHR) {
#endif
                // NOTE: if dpy was invalid, createImage() is guaranteed to
                // fail. so we'd end up here.
                return -EINVAL;
            }
        }

        GLint error;
        while ((error = glGetError()) != GL_NO_ERROR) {
            ST_LOGW("updateTexImage: clearing GL error: %#04x", error);
        }

        glBindTexture(mTexTarget, mTexName);
        glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)image);

        bool failed = false;
        while ((error = glGetError()) != GL_NO_ERROR) {
            ST_LOGE("error binding external texture image %p (slot %d): %#04x",
                    image, buf, error);
            failed = true;
        }
        if (failed) {
            return -EINVAL;
        }
#ifdef QCOM_HARDWARE
      }
#endif
        if (mCurrentTexture != INVALID_BUFFER_SLOT) {
            if (mUseFenceSync) {
                EGLSyncKHR fence = eglCreateSyncKHR(dpy, EGL_SYNC_FENCE_KHR,
                        NULL);
                if (fence == EGL_NO_SYNC_KHR) {
                    LOGE("updateTexImage: error creating fence: %#x",
                            eglGetError());
                    return -EINVAL;
                }
                glFlush();
                mSlots[mCurrentTexture].mFence = fence;
            }
        }

        ST_LOGV("updateTexImage: (slot=%d buf=%p) -> (slot=%d buf=%p)",
                mCurrentTexture,
                mCurrentTextureBuf != NULL ? mCurrentTextureBuf->handle : 0,
                buf, mSlots[buf].mGraphicBuffer->handle);

        if (mCurrentTexture != INVALID_BUFFER_SLOT) {
            // The current buffer becomes FREE if it was still in the queued
            // state. If it has already been given to the client
            // (synchronous mode), then it stays in DEQUEUED state.
            if (mSlots[mCurrentTexture].mBufferState == BufferSlot::QUEUED) {
                mSlots[mCurrentTexture].mBufferState = BufferSlot::FREE;
            }
        }

        // Update the SurfaceTexture state.
        mCurrentTexture = buf;
        mCurrentTextureBuf = mSlots[buf].mGraphicBuffer;
        mCurrentCrop = mSlots[buf].mCrop;
        mCurrentTransform = mSlots[buf].mTransform;
        mCurrentScalingMode = mSlots[buf].mScalingMode;
        mCurrentTimestamp = mSlots[buf].mTimestamp;
        computeCurrentTransformMatrix();

        // Now that we've passed the point at which failures can happen,
        // it's safe to remove the buffer from the front of the queue.
        mQueue.erase(front);
        mDequeueCondition.signal();
    } else {
        // We always bind the texture even if we don't update its contents.
        glBindTexture(mTexTarget, mTexName);
    }

    return OK;
}

bool SurfaceTexture::isExternalFormat(uint32_t format)
{
    switch (format) {
    // supported YUV formats
    case HAL_PIXEL_FORMAT_YV12:
    // Legacy/deprecated YUV formats
    case HAL_PIXEL_FORMAT_YCbCr_422_SP:
    case HAL_PIXEL_FORMAT_YCrCb_420_SP:
    case HAL_PIXEL_FORMAT_YCbCr_422_I:
        return true;
    }

    // Any OEM format needs to be considered
    if (format>=0x100 && format<=0x1FF)
        return true;

    return false;
}

GLenum SurfaceTexture::getCurrentTextureTarget() const {
    return mTexTarget;
}

void SurfaceTexture::getTransformMatrix(float mtx[16]) {
    Mutex::Autolock lock(mMutex);
    memcpy(mtx, mCurrentTransformMatrix, sizeof(mCurrentTransformMatrix));
}
status_t SurfaceTexture::updateTexImage(BufferRejecter* rejecter) {
    ATRACE_CALL();
    ST_LOGV("updateTexImage");
    Mutex::Autolock lock(mMutex);

    status_t err = NO_ERROR;

    if (mAbandoned) {
        ST_LOGE("updateTexImage: SurfaceTexture is abandoned!");
        return NO_INIT;
    }

    if (!mAttached) {
        ST_LOGE("updateTexImage: SurfaceTexture is not attached to an OpenGL "
                "ES context");
        return INVALID_OPERATION;
    }

    EGLDisplay dpy = eglGetCurrentDisplay();
    EGLContext ctx = eglGetCurrentContext();

    if ((mEglDisplay != dpy && mEglDisplay != EGL_NO_DISPLAY) ||
            dpy == EGL_NO_DISPLAY) {
        ST_LOGE("updateTexImage: invalid current EGLDisplay");
        return INVALID_OPERATION;
    }

    if ((mEglContext != ctx && mEglContext != EGL_NO_CONTEXT) ||
            ctx == EGL_NO_CONTEXT) {
        ST_LOGE("updateTexImage: invalid current EGLContext");
        return INVALID_OPERATION;
    }

    mEglDisplay = dpy;
    mEglContext = ctx;

    BufferQueue::BufferItem item;

    // In asynchronous mode the list is guaranteed to be one buffer
    // deep, while in synchronous mode we use the oldest buffer.
    err = mBufferQueue->acquireBuffer(&item);
    if (err == NO_ERROR) {
        int buf = item.mBuf;
        // This buffer was newly allocated, so we need to clean up on our side
        if (item.mGraphicBuffer != NULL) {
            mEGLSlots[buf].mGraphicBuffer = 0;
            if (mEGLSlots[buf].mEglImage != EGL_NO_IMAGE_KHR) {
                eglDestroyImageKHR(dpy, mEGLSlots[buf].mEglImage);
                mEGLSlots[buf].mEglImage = EGL_NO_IMAGE_KHR;
            }
            mEGLSlots[buf].mGraphicBuffer = item.mGraphicBuffer;
        }

        // we call the rejecter here, in case the caller has a reason to
        // not accept this buffer. this is used by SurfaceFlinger to
        // reject buffers which have the wrong size
        if (rejecter && rejecter->reject(mEGLSlots[buf].mGraphicBuffer, item)) {
            mBufferQueue->releaseBuffer(buf, dpy, mEGLSlots[buf].mFence);
            mEGLSlots[buf].mFence = EGL_NO_SYNC_KHR;
            glBindTexture(mTexTarget, mTexName);
            return NO_ERROR;
        }

        // Update the GL texture object. We may have to do this even when
        // item.mGraphicBuffer == NULL, if we destroyed the EGLImage when
        // detaching from a context but the buffer has not been re-allocated.
        EGLImageKHR image = mEGLSlots[buf].mEglImage;
        if (image == EGL_NO_IMAGE_KHR) {
            if (mEGLSlots[buf].mGraphicBuffer == NULL) {
                ST_LOGE("updateTexImage: buffer at slot %d is null", buf);
                err = BAD_VALUE;
            } else {
                image = createImage(dpy, mEGLSlots[buf].mGraphicBuffer);
                mEGLSlots[buf].mEglImage = image;
                if (image == EGL_NO_IMAGE_KHR) {
                    // NOTE: if dpy was invalid, createImage() is guaranteed to
                    // fail. so we'd end up here.
                    err = UNKNOWN_ERROR;
                }
            }
        }

        if (err == NO_ERROR) {
            GLint error;
            while ((error = glGetError()) != GL_NO_ERROR) {
                ST_LOGW("updateTexImage: clearing GL error: %#04x", error);
            }

            glBindTexture(mTexTarget, mTexName);
            glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)image);

            while ((error = glGetError()) != GL_NO_ERROR) {
                ST_LOGE("updateTexImage: error binding external texture image %p "
                        "(slot %d): %#04x", image, buf, error);
                err = UNKNOWN_ERROR;
            }

            if (err == NO_ERROR) {
                err = syncForReleaseLocked(dpy);
            }
        }

        if (err != NO_ERROR) {
            // Release the buffer we just acquired.  It's not safe to
            // release the old buffer, so instead we just drop the new frame.
            mBufferQueue->releaseBuffer(buf, dpy, mEGLSlots[buf].mFence);
            mEGLSlots[buf].mFence = EGL_NO_SYNC_KHR;
            return err;
        }

        ST_LOGV("updateTexImage: (slot=%d buf=%p) -> (slot=%d buf=%p)",
                mCurrentTexture,
                mCurrentTextureBuf != NULL ? mCurrentTextureBuf->handle : 0,
                buf, item.mGraphicBuffer != NULL ? item.mGraphicBuffer->handle : 0);

        // release old buffer
        if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
            status_t status = mBufferQueue->releaseBuffer(mCurrentTexture, dpy,
                    mEGLSlots[mCurrentTexture].mFence);

            mEGLSlots[mCurrentTexture].mFence = EGL_NO_SYNC_KHR;
            if (status == BufferQueue::STALE_BUFFER_SLOT) {
                freeBufferLocked(mCurrentTexture);
            } else if (status != NO_ERROR) {
                ST_LOGE("updateTexImage: released invalid buffer");
                err = status;
            }
        }

        // Update the SurfaceTexture state.
        mCurrentTexture = buf;
        mCurrentTextureBuf = mEGLSlots[buf].mGraphicBuffer;
        mCurrentCrop = item.mCrop;
        mCurrentTransform = item.mTransform;
        mCurrentScalingMode = item.mScalingMode;
        mCurrentTimestamp = item.mTimestamp;
        computeCurrentTransformMatrix();
    } else  {
        if (err < 0) {
            ALOGE("updateTexImage failed on acquire %d", err);
        }
        // We always bind the texture even if we don't update its contents.
        glBindTexture(mTexTarget, mTexName);
        return OK;
    }

    return err;
}
static Image*
readGif ( GifFileType *gf )
{
  Image*          firstImg = 0;
  Image*	  img = 0;
  int             i, extCode, width, height, row, cmapSize;
  int             trans = -1, nFrames = 0, delay = 0;
  GifRecordType   rec;
  GifByteType     *ext;
  ColorMapObject  *cmap;
  GifColorType    *clrs;
  GifPixelType    *rowBuf = (GifPixelType*) AWT_MALLOC( gf->SWidth * sizeof( GifPixelType) );

  do {
	CHECK( DGifGetRecordType( gf, &rec));

	switch ( rec ) {
	case IMAGE_DESC_RECORD_TYPE:
	  CHECK( DGifGetImageDesc( gf));

	  width    = gf->Image.Width;
	  height   = gf->Image.Height;

      cmap     = (gf->Image.ColorMap) ? gf->Image.ColorMap : gf->SColorMap;
	  clrs     = cmap->Colors;
      cmapSize = cmap->ColorCount;

	  /*
	   * create our image objects and keep track of frames 
	   */
	  if ( !firstImg ) {     /* this is the first (maybe only) frame */
		firstImg = img = createImage( width, height);
	  }
	  else {                 /* this is a subsequent gif-movie frame, link it in */
		img->next = createImage( width, height);
		img = img->next;
	  }

	  /*
	   * The trans index might have been cached by a preceeding extension record. Now
	   * that we have the Image object, it's time to store it in img and to create the
	   * mask
	   */
	  if ( trans != -1 ) {
		img->trans = trans;
		createXMaskImage( X, img);
		trans = -1;
	  }

	  /*
	   * Some browsers seem to assume minimal values, and some animations
	   * seem to rely on this. But there's no safe guess, so we
	   * skip it completely
	   */
/*
	  if ( delay == 0 )
		delay = 1000;
	  else if ( delay < 100 )
		delay = 100;
*/

	  img->latency = delay;
	  img->left = gf->Image.Left;
	  img->top = gf->Image.Top;
	  img->frame = nFrames;

	  nFrames++;
	  createXImage( X, img);

	  /*
	   * start reading in the image data
	   */
	  if ( gf->Image.Interlace ) {
		/* Need to perform 4 passes on the images: */
		for ( i = 0; i < 4; i++ ) {
		  for (row = iOffset[i]; row < height; row += iJumps[i]) {
			memset( rowBuf, gf->SBackGroundColor, width);
			CHECK( DGifGetLine( gf, rowBuf, width));

			writeRow( img, rowBuf, clrs, row);
		  }
		}
	  }
	  else {
		for ( row = 0; row < height; row++) {
		  memset( rowBuf, gf->SBackGroundColor, width);
		  CHECK( DGifGetLine(gf, rowBuf, width));

		  writeRow( img, rowBuf, clrs, row);
		}
	  }
	  break;

	case EXTENSION_RECORD_TYPE:
	  CHECK( DGifGetExtension( gf, &extCode, &ext));

	  if ( extCode == 0xf9 ) {   /* graphics extension */
		/*
		 * extension record with transparency spec are preceeding description records
		 * (which create new Images), so just cache the transp index, here
		 */
		if ( ext[1] & 1 ) {      /* transparent index following */
		  trans = ext[4];
		}
		delay = ((ext[3] << 8) | ext[2]) * 10; /* delay in 1/100 secs */
	  }
	  else if ( extCode == 0xff ) {  /* application extension block */
	  }

	  while ( ext != NULL ) {
		CHECK( DGifGetExtensionNext( gf, &ext));
	  }
	  break;

	case TERMINATE_RECORD_TYPE:
	  break;

	default:                /* Should be traps by DGifGetRecordType. */
	  break;
	}
  } while ( rec != TERMINATE_RECORD_TYPE );

  if ( firstImg && (img != firstImg) ){
	img->next = firstImg;   /* link it together (as a ring) */
  }

  return firstImg;
}
Пример #7
0
/* MapEntryPanel::onBtnSaveImage
 * Called when the 'Save Map Image' button is clicked
 *******************************************************************/
void MapEntryPanel::onBtnSaveImage(wxCommandEvent& e)
{
	createImage();
}
Пример #8
0
QVBoxLayout* ColormapEditWidget::createButtonPanel()
{
    QVBoxLayout* vLayout = new QVBoxLayout();

    QHBoxLayout* hLayout = new QHBoxLayout();
    m_cLabel = new QLabel( this );
    m_sliders.clear();

    QImage* image;
    image = createImage( this->width() - 20 );
    QPixmap pix( this->width() - 20, 20 );
    pix.convertFromImage( *image );
    m_cLabel->setPixmap( pix );
    hLayout->addStretch();
    hLayout->addWidget( m_cLabel );
    hLayout->addStretch();
    vLayout->addLayout( hLayout );
    vLayout->addSpacing( 5 );

    int i = 0;
    {
        QHBoxLayout* hLayout2 = new QHBoxLayout();
        PushButtonWithId* insertButton = new PushButtonWithId( "+", i );
        insertButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( insertButton, SIGNAL( signalClicked( int ) ), this, SLOT( newEntry( int ) ) );
        insertButton->setDisabled( true );

        PushButtonWithId* deleteButton = new PushButtonWithId( "-", i );
        deleteButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( deleteButton, SIGNAL( signalClicked( int ) ), this, SLOT( removeEntry( int ) ) );
        deleteButton->setDisabled( true );

        PushButtonWithId* upButton = new PushButtonWithId( "^", i );
        upButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        upButton->setDisabled( true );
        //connect( upButton, SIGNAL( signalClicked( int ) ), this, SLOT( moveUp( int ) ) );

        PushButtonWithId* downButton = new PushButtonWithId( "v", i );
        downButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( downButton, SIGNAL( signalClicked( int ) ), this, SLOT( moveDown( int ) ) );

        SliderWithEdit* slider = new SliderWithEdit( tr(""), Fn::Position::EAST, i );
        m_sliders.push_back( slider );
        slider->setMin( 0.0f );
        slider->setMax( m_colormap.get( i + 1 ).value );
        slider->setValue( m_colormap.get( i ).value );
        connect( slider, SIGNAL( valueChanged( float, int ) ), this, SLOT( sliderChanged( float, int ) ) );


        ColorWidgetWithLabel* colorWidget = new ColorWidgetWithLabel( QString::number( i ), i );
        colorWidget->setValue( m_colormap.get( i ).color );
        connect( colorWidget, SIGNAL( colorChanged( QColor, int ) ), this, SLOT( colorChanged( QColor, int ) ) );

        hLayout2->addWidget( insertButton );
        hLayout2->addWidget( deleteButton );
        hLayout2->addWidget( upButton );
        hLayout2->addWidget( downButton );
        hLayout2->addWidget( slider );
        hLayout2->addWidget( colorWidget );
        vLayout->addLayout( hLayout2 );
    }


    for ( int i = 1; i < m_colormap.size() - 1; ++i )
    {
        QHBoxLayout* hLayout4 = new QHBoxLayout();
        PushButtonWithId* insertButton = new PushButtonWithId( "+", i );
        hLayout4->addWidget( insertButton );
        insertButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( insertButton, SIGNAL( signalClicked( int ) ), this, SLOT( newEntry( int ) ) );

        PushButtonWithId* deleteButton = new PushButtonWithId( "-", i );
        hLayout4->addWidget( deleteButton );
        deleteButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( deleteButton, SIGNAL( signalClicked( int ) ), this, SLOT( removeEntry( int ) ) );

        PushButtonWithId* upButton = new PushButtonWithId( "^", i );
        hLayout4->addWidget( upButton );
        upButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( upButton, SIGNAL( signalClicked( int ) ), this, SLOT( moveUp( int ) ) );

        PushButtonWithId* downButton = new PushButtonWithId( "v", i );
        hLayout4->addWidget( downButton );
        downButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( downButton, SIGNAL( signalClicked( int ) ), this, SLOT( moveDown( int ) ) );

        SliderWithEdit* slider = new SliderWithEdit( tr(""), Fn::Position::EAST, i );
        m_sliders.push_back( slider );
        slider->setMin( m_colormap.get( i - 1 ).value );
        slider->setMax( m_colormap.get( i + 1 ).value );
        slider->setValue( m_colormap.get( i ).value );
        connect( slider, SIGNAL( valueChanged( float, int ) ), this, SLOT( sliderChanged( float, int ) ) );
        hLayout4->addWidget( slider );

        ColorWidgetWithLabel* colorWidget = new ColorWidgetWithLabel( QString::number( i ), i );
        colorWidget->setValue( m_colormap.get( i ).color );
        connect( colorWidget, SIGNAL( colorChanged( QColor, int ) ), this, SLOT( colorChanged( QColor, int ) ) );
        hLayout4->addWidget( colorWidget );

        vLayout->addLayout( hLayout4 );
    }

    {
        i = m_colormap.size() - 1;
        QHBoxLayout* hLayout2 = new QHBoxLayout();
        PushButtonWithId* insertButton = new PushButtonWithId( "+", i );
        insertButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( insertButton, SIGNAL( signalClicked( int ) ), this, SLOT( newEntry( int ) ) );

        PushButtonWithId* deleteButton = new PushButtonWithId( "-", i );
        deleteButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( deleteButton, SIGNAL( signalClicked( int ) ), this, SLOT( removeEntry( int ) ) );
        deleteButton->setDisabled( true );

        PushButtonWithId* upButton = new PushButtonWithId( "^", i );
        upButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        connect( upButton, SIGNAL( signalClicked( int ) ), this, SLOT( moveUp( int ) ) );

        PushButtonWithId* downButton = new PushButtonWithId( "v", i );
        downButton->setStyleSheet( "QPushButton { font:  bold 12px; max-width: 14px; max-height: 14px; } ");
        downButton->setDisabled( true );
        //connect( downButton, SIGNAL( signalClicked( int ) ), this, SLOT( moveDown( int ) ) );

        SliderWithEdit* slider = new SliderWithEdit( tr(""), Fn::Position::EAST, i );
        m_sliders.push_back( slider );
        slider->setMin( m_colormap.get( i - 1 ).value );
        slider->setMax( 1.0f );
        slider->setValue( m_colormap.get( i ).value );
        connect( slider, SIGNAL( valueChanged( float, int ) ), this, SLOT( sliderChanged( float, int ) ) );


        ColorWidgetWithLabel* colorWidget = new ColorWidgetWithLabel( QString::number( i ), i );
        colorWidget->setValue( m_colormap.get( i ).color );
        connect( colorWidget, SIGNAL( colorChanged( QColor, int ) ), this, SLOT( colorChanged( QColor, int ) ) );

        hLayout2->addWidget( insertButton );
        hLayout2->addWidget( deleteButton );
        hLayout2->addWidget( upButton );
        hLayout2->addWidget( downButton );
        hLayout2->addWidget( slider );
        hLayout2->addWidget( colorWidget );
        vLayout->addLayout( hLayout2 );
    }

    vLayout->addStretch();
    return vLayout;
}
Пример #9
0
 //% weight=74 help=images/create-big-image
 //% blockId=device_build_big_image block="create big image" imageLiteral=2
 //% parts="ledmatrix"
 Image createBigImage(ImageLiteral leds) {
     return createImage(leds);
 }
Пример #10
0
void DemoState::valueUpdate(ComboBox& comboBox, const std::string& selectedValue) {
	if (comboBox == "imageCombo") {
		if (selectedValue == "Bat-smiley") {
			createImage("demo/images/batsmiley.tga");
		}
		if (selectedValue == "Derby") {
			createImage("demo/images/derby.tga");
		}
		if (selectedValue == "Rage") {
			createImage("demo/images/rage.tga");
		}
		if (selectedValue == "Red John") {
			createImage("demo/images/redjohn.tga");
		}
		if (selectedValue == "You tried") {
			createImage("demo/images/youtried.tga");
		}
	}
	if (comboBox == "cursorCombo") {
		if (selectedValue == "Standard") {
			p_gui->setCursor("");
		}
		if (selectedValue == "Arrow") {
			p_gui->setCursor("images/cursor/arrow.tga");
		}
		if (selectedValue == "Diamond sword") {
			p_gui->setCursor("images/cursor/minesword.tga");
		}
		if (selectedValue == "Dragon scimitar") {
			p_gui->setCursor("images/cursor/runescim.tga");
		}
		if (selectedValue == "Sonic screwdriver") {
			p_gui->setCursor("images/cursor/dwsonic.tga");
		}
		if (selectedValue == "Portal gun") {
			p_gui->setAnimatedCursor("images/cursor/portalgun.tga", 2, 500, false);
		}
	}
	if (comboBox == "setGeneralEffect") {
		image->addEffect(GENERIC, getEffectForName(selectedValue));
	}
	if (comboBox == "setOnHoverEffect") {
		image->addEffect(TRIG_HOVER, getEffectForName(selectedValue));
	}
	if (comboBox == "setOnHoverOffEffect") {
		image->addEffect(TRIG_HOVER_OFF, getEffectForName(selectedValue));
	}
	if (comboBox == "gradiantCombo") {
		if (selectedValue == "To bottom") {
			plainWindow->setGradiant(TO_BOTTOM, 4.0f);
		}
		if (selectedValue == "To top") {
			plainWindow->setGradiant(TO_TOP, 4.0f);
		}
		if (selectedValue == "To left") {
			plainWindow->setGradiant(TO_LEFT, 4.0f);
		}
		if (selectedValue == "To right") {
			plainWindow->setGradiant(TO_RIGHT, 4.0f);
		}
		if (selectedValue == "None") {
			plainWindow->setGradiant(NO_GRADIANT);
		}
	}
}
Пример #11
0
Scene createScene(char* filename){
    Scene scene = {};
    scene.max_depth = 10;
    scene.num_samples = 100;

    scene.image = createImage(500, 500);

    Vector position = {278, 273, -800};
    Vector look_at = {278, 273, 0};
    Vector up = {0, 1, 0};
    scene.camera = createCamera(position, look_at, up, 39, (float)(scene.image.width/scene.image.height));

    scene.num_materials = 4;
    scene.materials = malloc(scene.num_materials * sizeof(Material));

    scene.materials[0] = createMaterial(createColor(.95, .25, .25), .6, .4, false);
    scene.materials[1] = createMaterial(createColor(.25, .95, .25), .6, .4, false);
    scene.materials[2] = createMaterial(createColor(.95, .95, .85), .6, .4, false);
    scene.materials[3] = createMaterial(createColor(.9, .9, .9), .6, .4, true);

    scene.num_triangles = 32;
    scene.triangles = malloc(scene.num_triangles * sizeof(Triangle));

    // Right Wall
    scene.triangles[0] = createTriangle(&scene.materials[1], createVector(0.0, 0.0, 559.2), createVector(0.0, 0.0, 0.0), createVector(0.0, 548.8, 0.0));
    scene.triangles[1] = createTriangle(&scene.materials[1], createVector(0.0, 0.0, 559.2), createVector(0.0, 548.8, 0.0), createVector(0.0, 548.8, 559.2));

    // Floor
    scene.triangles[2] = createTriangle(&scene.materials[2], createVector(556.0, 0.0, 0.0), createVector(0.0, 0.0, 0.0), createVector(0.0, 0.0, 559.2));
    scene.triangles[3] = createTriangle(&scene.materials[2], createVector(556.0, 0.0, 0.0), createVector(0.0, 0.0, 559.2), createVector(556.0, 0.0, 559.2));

    // Left Wall
    scene.triangles[4] = createTriangle(&scene.materials[0], createVector(556.0, 0.0, 0.0), createVector(556.0, 0.0, 559.2), createVector(556.0, 548.8, 559.2));
    scene.triangles[5] = createTriangle(&scene.materials[0], createVector(556.0, 0.0, 0.0), createVector(556.0, 548.8, 559.2), createVector(556.0, 548.8, 0.0));

    // Ceiling
    scene.triangles[6] = createTriangle(&scene.materials[2], createVector(556.0, 548.8, 0.0), createVector(0.0, 548.8, 559.2), createVector(0.0, 548.8, 0.0));
    scene.triangles[7] = createTriangle(&scene.materials[2], createVector(556.0, 548.8, 0.0), createVector(556.0, 548.8, 559.2), createVector(0.0, 548.8, 559.2));

    // Backwall
    scene.triangles[8] = createTriangle(&scene.materials[2], createVector(556.0, 0.0, 559.2), createVector(0.0, 0.0, 559.2), createVector(0.0, 548.8, 559.2));
    scene.triangles[9] = createTriangle(&scene.materials[2], createVector(556.0, 0.0, 559.2), createVector(0.0, 548.8, 559.2), createVector(556.0, 548.8, 559.2));

    // Short Block
    scene.triangles[10] = createTriangle(&scene.materials[2], createVector(130.0, 165.0, 65.0), createVector(82.0, 165.0, 225.0), createVector(240.0, 165.0, 272.0));
    scene.triangles[11] = createTriangle(&scene.materials[2], createVector(130.0, 165.0, 65.0), createVector(240.0, 165.0, 272.0), createVector(290.0, 165.0, 114.0));
    scene.triangles[12] = createTriangle(&scene.materials[2], createVector(290.0, 0.0, 114.0), createVector(290.0, 165.0, 114.0), createVector(240.0, 165.0, 272.0));
    scene.triangles[13] = createTriangle(&scene.materials[2], createVector(290.0, 0.0, 114.0), createVector(240.0, 165.0, 272.0), createVector(240.0, 0.0, 272.0));
    scene.triangles[14] = createTriangle(&scene.materials[2], createVector(130.0, 0.0, 65.0), createVector(130.0, 165.0, 65.0), createVector(290.0, 165.0, 114.0));
    scene.triangles[15] = createTriangle(&scene.materials[2], createVector(130.0, 0.0, 65.0), createVector(290.0, 165.0, 114.0), createVector(290.0, 0.0, 114.0));
    scene.triangles[16] = createTriangle(&scene.materials[2], createVector(82.0, 0.0, 225.0), createVector(82.0, 165.0, 225.0), createVector(130.0, 165.0, 65.0));
    scene.triangles[17] = createTriangle(&scene.materials[2], createVector(82.0, 0.0, 225.0), createVector(130.0, 165.0, 65.0), createVector(130.0, 0.0, 65.0));
    scene.triangles[18] = createTriangle(&scene.materials[2], createVector(240.0, 0.0, 272.0), createVector(240.0, 165.0, 272.0), createVector(82.0, 165.0, 225.0));
    scene.triangles[19] = createTriangle(&scene.materials[2], createVector(240.0, 0.0, 272.0), createVector(82.0, 165.0, 225.0), createVector(82.0, 0.0, 225.0));

    // Tall Block
    scene.triangles[20] = createTriangle(&scene.materials[2], createVector(423.0, 330.0, 247.0), createVector(265.0, 330.0, 296.0), createVector(314.0, 330.0, 456.0));
    scene.triangles[21] = createTriangle(&scene.materials[2], createVector(423.0, 330.0, 247.0), createVector(314.0, 330.0, 456.0), createVector(472.0, 330.0, 406.0));
    scene.triangles[22] = createTriangle(&scene.materials[2], createVector(423.0, 0.0, 247.0), createVector(423.0, 330.0, 247.0), createVector(472.0, 330.0, 406.0));
    scene.triangles[23] = createTriangle(&scene.materials[2], createVector(423.0, 0.0, 247.0), createVector(472.0, 330.0, 406.0), createVector(472.0, 0.0, 406.0));
    scene.triangles[24] = createTriangle(&scene.materials[2], createVector(472.0, 0.0, 406.0), createVector(472.0, 330.0, 406.0), createVector(314.0, 330.0, 456.0));
    scene.triangles[25] = createTriangle(&scene.materials[2], createVector(472.0, 0.0, 406.0), createVector(314.0, 330.0, 456.0), createVector(314.0, 0.0, 456.0));
    scene.triangles[26] = createTriangle(&scene.materials[2], createVector(314.0, 0.0, 456.0), createVector(314.0, 330.0, 456.0), createVector(265.0, 330.0, 296.0));
    scene.triangles[27] = createTriangle(&scene.materials[2], createVector(314.0, 0.0, 456.0), createVector(265.0, 330.0, 296.0), createVector(265.0, 0.0, 296.0));
    scene.triangles[28] = createTriangle(&scene.materials[2], createVector(265.0, 0.0, 296.0), createVector(265.0, 330.0, 296.0), createVector(423.0, 330.0, 247.0));
    scene.triangles[29] = createTriangle(&scene.materials[2], createVector(265.0, 0.0, 296.0), createVector(423.0, 330.0, 247.0), createVector(423.0, 0.0, 247.0));

    // Area Light
    scene.triangles[30] = createTriangle(&scene.materials[3], createVector(343.0, 548.7, 227.0), createVector(343.0, 548.7, 332.0), createVector(213.0, 548.7, 332.0));
    scene.triangles[31] = createTriangle(&scene.materials[3], createVector(343.0, 548.7, 227.0), createVector(213.0, 548.7, 332.0), createVector(213.0, 548.7, 227.0));

    scene.num_lights = 2;
    scene.lights = malloc(scene.num_lights * sizeof(Triangle));
    scene.lights[0] = createTriangle(&scene.materials[3], createVector(343.0, 548.7, 227.0), createVector(343.0, 548.7, 332.0), createVector(213.0, 548.7, 332.0));
    scene.lights[1] = createTriangle(&scene.materials[3], createVector(343.0, 548.7, 227.0), createVector(213.0, 548.7, 332.0), createVector(213.0, 548.7, 227.0));

    return scene;
}
// 1.
// CreateAndRunWithSequenceGrabber
void QuicktimeLiveImageStream::createAndRunWithSequenceGrabber(std::string fileName)
{
    std::string::size_type idx = fileName.find(':');

    if (idx == std::string::npos)
    {
        OSG_FATAL << "Error while parsing deviceID:deviceInputID.live path : " << fileName << std::endl;
    }

    // Better c++ code is to use istrstream
    std::string deviceIDStr      = fileName.substr(0, idx);
    std::string deviceInputIDStr = fileName.substr(idx + 1);
    m_videoDeviceID      = static_cast<short>(atoi(deviceIDStr.c_str()));
    m_videoDeviceInputID = static_cast<short>(atoi(deviceInputIDStr.c_str()));
    // Get Video Digitizer Rectangle bounds from a Sequence Grabber proxy (using IDs)
    get_video_device_bounds_idstr(m_videoDeviceID, m_videoDeviceInputID, m_videoRectWidth, m_videoRectHeight, m_videoDeviceIDStr);
    // Sound
    m_soundDeviceID = 2; m_soundDeviceInputID = 0;
    // get_sound_device_idstr(m_soundDeviceID, m_soundDeviceInputID, m_soundDeviceIDStr);
    // Create the Image
    createImage();
    // Create the offscreen GWorld (using Image  as target memory)
    createGWorld();
    // Create the Sequence Grabber (using GWorld as target memory)
    createSequenceGrabber();
    // Create the Sequence Grabber Video Channel
    createSequenceGrabberVideoChannel();
    if (g_s_use_sg_record)
    {
        // Create the Sequence Grabber DataProc setup for Record
        createSequenceGrabberDataProc();
    }

    // Create the Sequence Grabber Audio Channel
    createSequenceGrabberAudioChannel();
    // Start the engine Jack!
    // Callbacks
    createSequenceGrabberVideoBottlenecks();

    ComponentResult result = noErr;
    result = SGPrepare(m_gSeqGrabber, TRUE, FALSE);
    if (result != noErr)
    {
        OSG_FATAL << "SGPrepare : error" << std::endl;
    }

    if (g_s_use_sg_record)
    {
        result = SGStartRecord(m_gSeqGrabber);
        if (result != noErr)
        {
            OSG_FATAL << "SGStartRecord : error" << std::endl;
        }
    }
    else
    {
        result = SGStartPreview(m_gSeqGrabber);
        if (result != noErr)
        {
            OSG_FATAL << "SGStartPreview : error" << std::endl;
        }
    }

    _status = ImageStream::PLAYING;
    // Ticker
    start();
}
Пример #13
0
// conversion function should format by format, chip by chip
// currently input is MTK_I420, and output is IMG_YV12/ABGR
status_t SurfaceTexture::convertToAuxSlotLocked(bool isForce) {
    // check invalid buffer
    if (BufferQueue::INVALID_BUFFER_SLOT == mCurrentTexture) {
        mAuxSlotConvert = false;
        return INVALID_OPERATION;
    }

    ATRACE_CALL();

    // 1) normal BufferQueue needs conversion now
    // 2) SurfaceTextureLayer neesd conversion after HWC
    bool isNeedConversionNow =
        (BufferQueue::TYPE_BufferQueue == mBufferQueue->getType()) ||
        ((true == isForce) && (BufferQueue::TYPE_SurfaceTextureLayer == mBufferQueue->getType()));

    //if ((true == isNeedConversionNow) && (BufferQueue::NO_CONNECTED_API != getConnectedApi())) {
    if (true == isNeedConversionNow) {
        XLOGI("do convertToAuxSlot...");

        Slot &src = mSlots[mCurrentTexture];
        AuxSlot &dst = *mBackAuxSlot;

        // fence sync here for buffer not used by G3D
        EGLSyncKHR fence = mFrontAuxSlot->eglSlot.mEglFence;
        if (fence != EGL_NO_SYNC_KHR) {
            EGLint result = eglClientWaitSyncKHR(mEglDisplay, fence, 0, 1000000000);
            if (result == EGL_FALSE) {
                XLOGW("[%s] FAILED waiting for front fence: %#x, tearing risk", __func__, eglGetError());
            } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
                XLOGW("[%s] TIMEOUT waiting for front fence, tearing risk", __func__);
            }
            eglDestroySyncKHR(mEglDisplay, fence);
            mFrontAuxSlot->eglSlot.mEglFence = EGL_NO_SYNC_KHR;
        }

#ifdef USE_MDP
        uint32_t hal_out_fmt;
        uint32_t mdp_in_fmt;
        uint32_t mdp_out_fmt;

        //if (NATIVE_WINDOW_API_CAMERA == getConnectedApi()) {
        hal_out_fmt = HAL_PIXEL_FORMAT_RGBA_8888;
        // camera path needs RGBA for MDP resource
        mdp_out_fmt = MHAL_FORMAT_ABGR_8888;
        //} else {
        //    hal_out_fmt = HAL_PIXEL_FORMAT_YV12;
        //    mdp_out_fmt = MHAL_FORMAT_IMG_YV12;
        //}
        // !!! only convert for I420 now !!!
        mdp_in_fmt = MHAL_FORMAT_YUV_420;

        // source graphic buffer
        sp<GraphicBuffer> sg = src.mGraphicBuffer;

        // destination graphic buffer
        sp<GraphicBuffer> dg = dst.slot.mGraphicBuffer;

        // free if current aux slot exist and not fit
        if ((EGL_NO_IMAGE_KHR != dst.eglSlot.mEglImage && dg != NULL) &&
                ((sg->width != dg->width) || (sg->height != dg->height) || (hal_out_fmt != (uint32_t)dg->format))) {

            XLOGI("[%s] free old aux slot ", __func__);
            XLOGI("    src[w:%d, h:%d, f:0x%x] dst[w:%d, h:%d, f:0x%x] required format:0x%x",
                  sg->width, sg->height, sg->format,
                  dg->width, dg->height, dg->format,
                  hal_out_fmt);

            freeAuxSlotLocked(dst);
        }

        // create aux buffer if current is NULL
        if ((EGL_NO_IMAGE_KHR == dst.eglSlot.mEglImage) && (dst.slot.mGraphicBuffer == NULL)) {
            XLOGI("[%s] create dst buffer and image", __func__);

            XLOGI("    before create new aux buffer: %p", __func__, dg.get());
            dg = dst.slot.mGraphicBuffer = new GraphicBuffer(sg->width,
                    sg->height,
                    hal_out_fmt,
                    sg->usage);
            if (dg == NULL) {
                XLOGE("    create aux GraphicBuffer FAILED", __func__);
                freeAuxSlotLocked(dst);
                return BAD_VALUE;
            } else {
                XLOGI("    create aux GraphicBuffer: %p", __func__, dg.get());
            }

            dst.eglSlot.mEglImage = createImage(mEglDisplay, dg);
            if (EGL_NO_IMAGE_KHR == dst.eglSlot.mEglImage) {
                XLOGE("[%s] create aux eglImage FAILED", __func__);
                freeAuxSlotLocked(dst);
                return BAD_VALUE;
            }

            XLOGI("[%s] create aux slot success", __func__);
            XLOGI("    src[w:%d, h:%d, f:0x%x], dst[w:%d, h:%d, f:0x%x]",
                  sg->width, sg->height, sg->format,
                  dg->width, dg->height, dg->format);

            dst.mMva = registerMva(dg);
        }

        status_t lockret;
        uint8_t *src_yp, *dst_yp;

        lockret = sg->lock(LOCK_FOR_MDP, (void**)&src_yp);
        if (NO_ERROR != lockret) {
            XLOGE("[%s] buffer lock fail: %s", __func__, strerror(lockret));
            return INVALID_OPERATION;
        }
        lockret = dg->lock(LOCK_FOR_MDP, (void**)&dst_yp);
        if (NO_ERROR != lockret) {
            XLOGE("[%s] buffer lock fail: %s", __func__, strerror(lockret));
            return INVALID_OPERATION;
        }
        {
            mHalBltParam_t bltParam;
            memset(&bltParam, 0, sizeof(bltParam));

            bltParam.srcAddr    = (MUINT32)src_yp;
            bltParam.srcX       = 0;
            bltParam.srcY       = 0;
            bltParam.srcW       = sg->width;
            // !!! I420 content is forced 16 align !!!
            bltParam.srcWStride = ALIGN(sg->width, 16);
            bltParam.srcH       = sg->height;
            bltParam.srcHStride = sg->height;
            bltParam.srcFormat  = mdp_in_fmt;

            bltParam.dstAddr   = (MUINT32)dst_yp;
            bltParam.dstW      = dg->width;
            // already 32 align
            bltParam.pitch     = dg->stride;
            bltParam.dstH      = dg->height;
            bltParam.dstFormat = mdp_out_fmt;

#ifdef MTK_75DISPLAY_ENHANCEMENT_SUPPORT
            bltParam.doImageProcess = (NATIVE_WINDOW_API_MEDIA == getConnectedApi()) ? 1 : 0;
#endif

            // mdp bitblt and check
            if (MHAL_NO_ERROR != ipcBitBlt(&bltParam)) {
                if (1 == bltParam.doImageProcess) {
                    XLOGW("[%s] bitblt FAILED with PQ, disable and try again", __func__);
                    bltParam.doImageProcess = 0;
                    if (MHAL_NO_ERROR != ipcBitBlt(&bltParam)) {
                        XLOGE("[%s] bitblt FAILED, unlock buffer and return", __func__);
                        dst.slot.mGraphicBuffer->unlock();
                        src.mGraphicBuffer->unlock();
                        return INVALID_OPERATION;
                    }
                } else {
                    XLOGE("[%s] bitblt FAILED, unlock buffer and return", __func__);
                    dst.slot.mGraphicBuffer->unlock();
                    src.mGraphicBuffer->unlock();
                    return INVALID_OPERATION;
                }
            } else {
                // for drawing debug line
                if (true == mLine) {
                    int _stride = bltParam.pitch;
                    uint8_t *_ptr = (uint8_t*)bltParam.dstAddr;
                    static uint32_t offset = bltParam.dstH / 4;
                    //ST_XLOGI("!!!!! draw line, ptr: %p, offset: %d, stride: %d, height: %d", _ptr, offset, _stride, bltParam.dstH);
                    if (NULL != _ptr) {
                        memset((void*)(_ptr + offset * _stride * 3 / 2), 0xFF, _stride * 20 * 3 / 2);
                    }
                    offset += 20;
                    if (offset >= bltParam.dstH * 3 / 4)
                        offset = bltParam.dstH / 4;
                }
            }
        }
        dg->unlock();
        sg->unlock();

#else // ! USE_MDP
        status_t err = swConversionLocked(src, dst);
        if (NO_ERROR != err)
            return err;
#endif // USE_MDP

        mAuxSlotConvert = false;
        mAuxSlotDirty = true;
    }

    return NO_ERROR;
}
Пример #14
0
void * QgsSingleBandGrayRenderer::readBlock( int bandNo, QgsRectangle  const & extent, int width, int height )
{
  Q_UNUSED( bandNo );
  if ( !mInput )
  {
    return 0;
  }

  QgsRasterInterface::DataType rasterType = ( QgsRasterInterface::DataType )mInput->dataType( mGrayBand );
  QgsRasterInterface::DataType alphaType = QgsRasterInterface::UnknownDataType;
  if ( mAlphaBand > 0 )
  {
    alphaType = ( QgsRasterInterface::DataType )mInput->dataType( mAlphaBand );
  }

  void* rasterData = mInput->block( mGrayBand, extent, width, height );
  if ( !rasterData ) return 0;

  void* alphaData = 0;
  double currentAlpha = mOpacity;
  int grayVal;
  QRgb myDefaultColor = qRgba( 0, 0, 0, 0 );

  if ( mAlphaBand > 0 && mGrayBand != mAlphaBand )
  {
    alphaData = mInput->block( mAlphaBand, extent, width, height );
    if ( !alphaData )
    {
      free( rasterData );
      return 0;
    }
  }
  else if ( mAlphaBand > 0 )
  {
    alphaData = rasterData;
  }

  QImage *img = createImage( width, height, QImage::Format_ARGB32_Premultiplied );
  QRgb* imageScanLine = 0;
  int currentRasterPos = 0;

  for ( int i = 0; i < height; ++i )
  {
    imageScanLine = ( QRgb* )( img->scanLine( i ) );
    for ( int j = 0; j < width; ++j )
    {
      grayVal = readValue( rasterData, rasterType, currentRasterPos );

      //alpha
      currentAlpha = mOpacity;
      if ( mRasterTransparency )
      {
        currentAlpha = mRasterTransparency->alphaValue( grayVal, mOpacity * 255 ) / 255.0;
      }
      if ( mAlphaBand > 0 )
      {
        currentAlpha *= ( readValue( alphaData, alphaType, currentRasterPos ) / 255.0 );
      }

      if ( mContrastEnhancement )
      {
        if ( !mContrastEnhancement->isValueInDisplayableRange( grayVal ) )
        {
          imageScanLine[ j ] = myDefaultColor;
          ++currentRasterPos;
          continue;
        }
        grayVal = mContrastEnhancement->enhanceContrast( grayVal );
      }

      if ( mInvertColor )
      {
        grayVal = 255 - grayVal;
      }

      if ( doubleNear( currentAlpha, 1.0 ) )
      {
        imageScanLine[j] = qRgba( grayVal, grayVal, grayVal, 255 );
      }
      else
      {
        imageScanLine[j] = qRgba( currentAlpha * grayVal, currentAlpha * grayVal, currentAlpha * grayVal, currentAlpha * 255 );
      }
      ++currentRasterPos;
    }
  }

  free( rasterData );
  if ( mAlphaBand > 0 && mGrayBand != mAlphaBand )
  {
    free( alphaData );
  }

  void * data = ( void * )img->bits();
  delete img;
  return data; // OK, the image was created with extraneous data
}
void ScreenWidget::setImage(QImage &image)
{
    originalImage = image;
    createImage();
    invertButton->setEnabled(true);
}
Пример #16
0
bool ResJPEG::init(const std::string& name)
{  

	rstream f;
	
	path = name;

	if(!f.open(name, "jpg"))
	{
		//log_msg("warning res image tga", std::string("Res/Image/TGA: cannot open file ")+ name.c_str());
		return false;
	}

	struct jpeg_decompress_struct cinfo;

	my_error_mgr jerr;

	cinfo.err = jpeg_std_error(&jerr.pub);
	jerr.pub.error_exit = my_error_exit;

	if (setjmp(jerr.setjmp_buffer))
	{
		jpeg_destroy_decompress(&cinfo);
		return false;
	}

	jpeg_create_decompress(&cinfo);
	jpeg_stdio_src(&cinfo, &f);
	jpeg_read_header(&cinfo, TRUE);
	jpeg_start_decompress(&cinfo);

	int stride = cinfo.output_width * cinfo.output_components;
	unsigned char** buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, stride, 1);

	if(createImage(cinfo.output_width, cinfo.output_height, 24) == false)
	{
		f.close();
		return false;
	}

	unsigned char* pBitmap = (unsigned char*)bitmap;
	const int a = 255;
	while (cinfo.output_scanline < cinfo.output_height)
	{
		jpeg_read_scanlines(&cinfo, buffer, 1);
		unsigned char* pcomp = *buffer;

		// in first implementation we move all bytes manually. if this will work, we will replace with memcpy
		for (unsigned int i = 0; i < cinfo.output_width; i++)
		{
			for(int c = 0; c < 3; c++){
				*pBitmap=*pcomp;
				pBitmap++;
				pcomp++;
			}
		}
	}

	jpeg_finish_decompress(&cinfo);
	jpeg_destroy_decompress(&cinfo);

	dimension	= IMAGE_2D;
	format = IMAGE_RGB;

	flipV();
	return true;
}
Пример #17
0
void PHIEllipseItem::html( const PHIRequest *req, QByteArray &out, QByteArray &script, const QByteArray &indent ) const
{
    if ( dirtyFlags() & DFColor || dirtyFlags() & DFBackgroundColor || dirtyFlags() & DFDoNotCache )
        setImagePath( PHIDataParser::createImage( req, this, createImage(), PHIData::c(), -1 ) );
    PHIAbstractShapeItem::html( req, out, script, indent );
}
Пример #18
0
EntityCEGUITexture::EntityCEGUITexture(const std::string& imageSetName, int width, int height)
: mImage(0), mImageSet(0), mWidth(width), mHeight(height), mRenderContext(new SimpleRenderContext(imageSetName, width, height)), mCeguiTexture(0)
{
	createImage(imageSetName);
}
inline vk::Move<vk::VkImage> makeImage (const vk::DeviceInterface& vk, const vk::VkDevice device, const vk::VkImageCreateInfo& createInfo)
{
	return createImage(vk, device, &createInfo);
}
Пример #20
0
//-------------------------------------------------
void ImageWriter::saveAllImages ()
{
	GriddedPlotter  *plotter = terre->getGriddedPlotter ();
	if (!plotter || !plotter->isReaderOk()) {
		return;
	}
	
	int W = Util::getSetting("imageSaveWidth",  640).toInt();
	int H = Util::getSetting("imageSaveHeight", 480).toInt();
	int Q = Util::getSetting("imageSaveQuality", 90).toInt();
	int Winit = terre->getProjection()->getW();
	int Hinit = terre->getProjection()->getH();
	bool rsz  = Util::getSetting("imageSaveResizeAfter", false).toBool();
	
	ImageWriterDialog dial (parent, W,H,Q,rsz, Winit,Hinit);
	dial.exec ();
	
	if (dial.isAccepted()) 
	{
		QString filename = Util::getSetting("imageSaveFilename", "").toString();
		filename = QFileDialog::getSaveFileName (terre,
					tr("Save all images (JPEG)"),
					filename, 
					tr("Images (*.jpg *.jpeg)") );
		if (filename != "") 
		{
			QRegExp reg ("(.jpeg$|.jpg$)");
			reg.setCaseSensitivity(Qt::CaseInsensitive);
			QString prefix = filename.replace(reg, "");
			reg.setPattern ("(_$|_\\d\\d\\d$)");
			prefix = filename.replace(reg, "");
			
			int nb = plotter->getNumberOfDates ();
			QString nom1 = createAnimImageFilename (prefix, 1);
			QString nom2 = createAnimImageFilename (prefix, nb);
			
			if ( QMessageBox::question (terre,
					tr("Save all images"),
					tr("This operation will create %1 files :").arg(nb)
						+ "\n\n"
						+ QString("%1\n...\n%2").arg(nom1).arg(nom2)
						+ "\n\n"
						+ tr("Warning: existing files will be deleted !")
					,
					QMessageBox::Ok|QMessageBox::Cancel
				)
				== QMessageBox::Ok )
			{	
				QCursor oldcursor = terre->cursor();
				saveSettings (dial, filename);
				terre->setCursor(Qt::WaitCursor);
				std::set<time_t>::iterator iter;
				int num=1;
				for (iter=plotter->getListDates()->begin();
							iter!=plotter->getListDates()->end();   iter++, num++)
				{
					time_t date = *iter;
					QImage * image = createImage (date, dial, Winit,Hinit);
					if (image)
					{
						QString filename = createAnimImageFilename (prefix, num);
						image->save (filename, "JPEG", Q);
						delete image;
					}
				}
				terre->setCursor(oldcursor);
			}
		}
	}
}
Пример #21
0
// List1-6
// BMPデータをファイルより読み込む
int readBMPfile(char *fname, ImageData **img)
{
	int i, c;
	int errcode = 0;
	BITMAPFILEHEADER BMPFile;
	int	fsize;
	BITMAPINFOHEADER BMPInfo;
	BITMAPCOREHEADER BMPCore;
	int	colors;
	int	colorTableSize;
	int	bitsSize;
	int	BISize;
	int x, y;
	int mx, my, depth;
	int pad;
	int mxb, myb;
	int isPM = FALSE;	// BMPの形式を記録するフラグ
	FILE *fp;

	WORD    HEAD_bfType;
	DWORD   HEAD_bfSize;
	WORD    HEAD_bfReserved1;
	WORD    HEAD_bfReserved2;
	DWORD   HEAD_bfOffBits;
	DWORD   INFO_bfSize;
	Pixel palet[MAXCOLORS];
	Pixel setcolor;

	errno_t error;
	if(error=fopen_s(&fp, fname, "rb") != 0){
		return -1;
	}

	// BMPファイルは必ず'BM(0x4d42)'で始まる.それ以外の場合はBMPではないので,中止する
	if (!freadWORD(&HEAD_bfType, fp)) {
		errcode = -2;
		goto $ABORT;
	}
	if (HEAD_bfType != 0x4d42) {
		errcode = -10;
		goto $ABORT;
	}
	// ヘッダ部のサイズ(Byte)
	if (!freadDWORD(&HEAD_bfSize, fp)) {
		errcode = -10;
		goto $ABORT;
	}
	// 予約用領域(未使用)
	if (!freadWORD(&HEAD_bfReserved1, fp)) {
		errcode = -10;
		goto $ABORT;
	}
	// 予約用領域(未使用)
	if (!freadWORD(&HEAD_bfReserved2, fp)) {
		errcode = -10;
		goto $ABORT;
	}
	// オフセット
	if (!freadDWORD(&HEAD_bfOffBits, fp)) {
		errcode = -10;
		goto $ABORT;
	}
	// ヘッダ部のサイズ
	if (!freadDWORD(&INFO_bfSize, fp)) {
		errcode = -10;
		goto $ABORT;
	}

	// ヘッダ部のサイズが規定外ならばエラーとする
	if (INFO_bfSize == 40/*sizeof(BITMAPINFOHEADER)*/ || INFO_bfSize == 12/*sizeof(BITMAPCOREHEADER)*/) {
		BMPInfo.biSize = INFO_bfSize;
		// BITMAPCOREHEADER形式の場合
		if (INFO_bfSize == sizeof(BITMAPCOREHEADER)) {
			WORD tmp;
			isPM = TRUE;
			// 画像の横幅
			if (!freadWORD(&tmp, fp)) {
				errcode = -10;
				goto $ABORT;
			}
			BMPInfo.biWidth = tmp;
			// 画像の縦幅
			if (!freadWORD(&tmp, fp)) {
				errcode = -10;
				goto $ABORT;
			}
			BMPInfo.biHeight = tmp;
			// 画像のプレーン数
			if (!freadWORD(&(BMPInfo.biPlanes), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// 1画素あたりのビット数
			if (!freadWORD(&(BMPInfo.biBitCount), fp)) {
				errcode = -10;
				goto $ABORT;
			}
		}
		else {		// BITMAPINFOHEADER形式の場合
					// 画像の横幅
			if (!freadDWORD(&(BMPInfo.biWidth), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// 画像の縦幅
			if (!freadDWORD(&(BMPInfo.biHeight), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// 画像のプレーン数
			if (!freadWORD(&(BMPInfo.biPlanes), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// 1画素あたりのビット数
			if (!freadWORD(&(BMPInfo.biBitCount), fp)) {
				errcode = -10;
				goto $ABORT;
			}
		}
		// BITMAPINFOHEADERの場合のみ存在する情報を読み込む
		if (!isPM) {
			// 圧縮形式
			if (!freadDWORD(&(BMPInfo.biCompression), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// 画像データ部のサイズ
			if (!freadDWORD(&(BMPInfo.biSizeImage), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// X方向の解像度
			if (!freadDWORD(&(BMPInfo.biXPelsPerMeter), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// Y方向の解像度
			if (!freadDWORD(&(BMPInfo.biYPelsPerMeter), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// 格納されているパレットの色数
			if (!freadDWORD(&(BMPInfo.biClrUsed), fp)) {
				errcode = -10;
				goto $ABORT;
			}
			// 重要なパレットのインデックス
			if (!freadDWORD(&(BMPInfo.biClrImportant), fp)) {
				errcode = -10;
				goto $ABORT;
			}
		}
	}
	else {
		errcode = -10;
		goto $ABORT;
	}
	mx = BMPInfo.biWidth;
	my = BMPInfo.biHeight;
	depth = BMPInfo.biBitCount;
	// 256色,フルカラー以外サポート外
	if (depth != 8 && depth != 24) {
		errcode = -3;
		goto $ABORT;
	}
	// 非圧縮形式以外はサポート外
	if (BMPInfo.biCompression != BI_RGB) {
		errcode = -20;
		goto $ABORT;
	}
	// ヘッダ部にパレットサイズの情報がない場合は1画素あたりのビット数から求める
	if (BMPInfo.biClrUsed == 0) {
		colors = countOfDIBColorEntries(BMPInfo.biBitCount);
	}
	else {
		colors = BMPInfo.biClrUsed;
	}

	// パレット情報の読み込み
	// BMPの種類によってフォーマットが異なるので処理をわける
	if (!isPM) {
		for (i = 0; i<colors; i++) {
			// Blue成分
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -10;
				goto $ABORT;
			}
			palet[i].b = c;
			// Green成分
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -10;
				goto $ABORT;
			}
			palet[i].g = c;
			// Red成分
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -10;
				goto $ABORT;
			}
			palet[i].r = c;
			// あまり
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -10;
				goto $ABORT;
			}
		}
	}
	else {
		for (i = 0; i<colors; i++) {
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -10;
				goto $ABORT;
			}
			palet[i].b = c;
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -10;
				goto $ABORT;
			}
			palet[i].g = c;
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -10;
				goto $ABORT;
			}
			palet[i].r = c;
		}
	}
	// フルカラーで画像データを作成
	*img = createImage(mx, my, 24);
	mxb = getDIBxmax(mx, depth);
	pad = mxb - mx*depth / 8;
	// 画像データ読み込み
	for (y = my - 1; y >= 0; y--) {
		for (x = 0; x<mx; x++) {
			if (depth == 8) {	// 256色形式の場合はパレットからRGB値を求める
				c = fgetc(fp);
				if (c == EOF) {
					errcode = -20;
					goto $ABORT;
				}
				setcolor.r = palet[c].r;
				setcolor.g = palet[c].g;
				setcolor.b = palet[c].b;
			}
			else if (depth == 24) {
				c = fgetc(fp);
				if (c == EOF) {
					errcode = -20;
					goto $ABORT;
				}
				setcolor.b = c;
				c = fgetc(fp);
				if (c == EOF) {
					errcode = -20;
					goto $ABORT;
				}
				setcolor.g = c;
				c = fgetc(fp);
				if (c == EOF) {
					errcode = -20;
					goto $ABORT;
				}
				setcolor.r = c;
			}
			setPixel(*img, x, y, &setcolor);
		}
		// Padding部の読み飛ばし
		for (i = 0; i<pad; i++) {
			c = fgetc(fp);
			if (c == EOF) {
				errcode = -20;
				goto $ABORT;
			}
		}
	}
$ABORT:	// エラー時の飛び先
	fclose(fp);
	return errcode;
}
Пример #22
0
status_t GLConsumer::updateAndReleaseLocked(const BufferQueue::BufferItem& item)
{
    status_t err = NO_ERROR;

    if (!mAttached) {
        ST_LOGE("updateAndRelease: GLConsumer is not attached to an OpenGL "
                "ES context");
        return INVALID_OPERATION;
    }

    // Confirm state.
    err = checkAndUpdateEglStateLocked();
    if (err != NO_ERROR) {
        return err;
    }

    int buf = item.mBuf;

    // If the mEglSlot entry is empty, create an EGLImage for the gralloc
    // buffer currently in the slot in ConsumerBase.
    //
    // We may have to do this even when item.mGraphicBuffer == NULL (which
    // means the buffer was previously acquired), if we destroyed the
    // EGLImage when detaching from a context but the buffer has not been
    // re-allocated.
    if (mEglSlots[buf].mEglImage == EGL_NO_IMAGE_KHR) {
        EGLImageKHR image = createImage(mEglDisplay,
                mSlots[buf].mGraphicBuffer, item.mCrop);
        if (image == EGL_NO_IMAGE_KHR) {
            ST_LOGW("updateAndRelease: unable to createImage on display=%p slot=%d",
                  mEglDisplay, buf);
            return UNKNOWN_ERROR;
        }
        mEglSlots[buf].mEglImage = image;
        mEglSlots[buf].mCropRect = item.mCrop;
    }

    // Do whatever sync ops we need to do before releasing the old slot.
    err = syncForReleaseLocked(mEglDisplay);
    if (err != NO_ERROR) {
        // Release the buffer we just acquired.  It's not safe to
        // release the old buffer, so instead we just drop the new frame.
        // As we are still under lock since acquireBuffer, it is safe to
        // release by slot.
        releaseBufferLocked(buf, mSlots[buf].mGraphicBuffer,
                mEglDisplay, EGL_NO_SYNC_KHR);
        return err;
    }

    ST_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)",
            mCurrentTexture,
            mCurrentTextureBuf != NULL ? mCurrentTextureBuf->handle : 0,
            buf, mSlots[buf].mGraphicBuffer->handle);

    // release old buffer
    if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
        status_t status = releaseBufferLocked(
                mCurrentTexture, mCurrentTextureBuf, mEglDisplay,
                mEglSlots[mCurrentTexture].mEglFence);
        if (status < NO_ERROR) {
            ST_LOGE("updateAndRelease: failed to release buffer: %s (%d)",
                   strerror(-status), status);
            err = status;
            // keep going, with error raised [?]
        }
    }

    // Update the GLConsumer state.
    mCurrentTexture = buf;
    mCurrentTextureBuf = mSlots[buf].mGraphicBuffer;
    mCurrentCrop = item.mCrop;
    mCurrentTransform = item.mTransform;
    mCurrentScalingMode = item.mScalingMode;
    mCurrentTimestamp = item.mTimestamp;
    mCurrentFence = item.mFence;
    mCurrentFrameNumber = item.mFrameNumber;

    computeCurrentTransformMatrixLocked();

    return err;
}
Пример #23
0
constexpr int max_i = 64;

template <int i = 0>
void run_perlin() {
	//not sure how to automatically test perlin noise, so just dump an image for now and manually check it
	const int width = 1024;
	const int height = 1024;
	const int min = 0;
	const int max = 255;

	auto noise = get_perlin_noise<float, width, height, i>(0, 255);
	auto render_device = irr::createDevice(irr::video::EDT_OPENGL, irr::core::dimension2du(800, 600), 32, false, false, true, nullptr);
	ON_SCOPE_EXIT(render_device->drop(););
	auto video_driver = render_device->getVideoDriver();
	auto image = video_driver->createImage(irr::video::ECOLOR_FORMAT::ECF_R8G8B8, {width, height});
	ON_SCOPE_EXIT(image->drop(););
	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			auto &value = noise[x][y];
			assert(value >= min);
			assert(value <= max);
			image->setPixel(x, y, {value, value, value});
		}
	}
	bool success = video_driver->writeImageToFile(image, "media/perlin.png");
	assert(success);
}

template <int i = 0>
void multi_test_perlin() {
Пример #24
0
HipaccImage hipaccCreateMemory(T *host_mem, size_t width, size_t height) {
    T *mem = new T[width*height];
    return createImage(host_mem, (void *)mem, width, height, width, 0);
}
status_t SurfaceTexture::attachToContext(GLuint tex) {
    ATRACE_CALL();
    ST_LOGV("attachToContext");
    Mutex::Autolock lock(mMutex);

    if (mAbandoned) {
        ST_LOGE("attachToContext: abandoned SurfaceTexture");
        return NO_INIT;
    }

    if (mAttached) {
        ST_LOGE("attachToContext: SurfaceTexture is already attached to a "
                "context");
        return INVALID_OPERATION;
    }

    EGLDisplay dpy = eglGetCurrentDisplay();
    EGLContext ctx = eglGetCurrentContext();

    if (dpy == EGL_NO_DISPLAY) {
        ST_LOGE("attachToContext: invalid current EGLDisplay");
        return INVALID_OPERATION;
    }

    if (ctx == EGL_NO_CONTEXT) {
        ST_LOGE("attachToContext: invalid current EGLContext");
        return INVALID_OPERATION;
    }

    // We need to bind the texture regardless of whether there's a current
    // buffer.
    glBindTexture(mTexTarget, tex);

    if (mCurrentTextureBuf != NULL) {
        // The EGLImageKHR that was associated with the slot was destroyed when
        // the SurfaceTexture was detached from the old context, so we need to
        // recreate it here.
        EGLImageKHR image = createImage(dpy, mCurrentTextureBuf);
        if (image == EGL_NO_IMAGE_KHR) {
            return UNKNOWN_ERROR;
        }

        // Attach the current buffer to the GL texture.
        glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)image);

        GLint error;
        status_t err = OK;
        while ((error = glGetError()) != GL_NO_ERROR) {
            ST_LOGE("attachToContext: error binding external texture image %p "
                    "(slot %d): %#04x", image, mCurrentTexture, error);
            err = UNKNOWN_ERROR;
        }

        // We destroy the EGLImageKHR here because the current buffer may no
        // longer be associated with one of the buffer slots, so we have
        // nowhere to to store it.  If the buffer is still associated with a
        // slot then another EGLImageKHR will be created next time that buffer
        // gets acquired in updateTexImage.
        eglDestroyImageKHR(dpy, image);

        if (err != OK) {
            return err;
        }
    }

    mEglDisplay = dpy;
    mEglContext = ctx;
    mTexName = tex;
    mAttached = true;

    return OK;
}
Пример #26
0
int main(int argc, char *argv[])
{
	
    /* pixels per worker */
    int ppw = 0;
	
	/* number of workers */
	int num_worker;
	
	/* pixels of the entire image */
	int dim;
	
    /* dimension of the entire image */
    int width,height;
	
    /* time variables */
    struct timeval tv1, tv2;
	
    /* Dimension of the partitioned image */
    int dimx = 0, dimy = 0;
	
    /* fit of the Gaussian */
    double fit[DIM_FIT];
	
    /* image representing Gaussian fit */
    unsigned char *image = NULL;
	
#ifdef PADDED
	/* buffer for the padded image */
	unsigned char *padded = NULL;
#endif	

#ifdef MODULE
	/* socket for the camera */
	int new_sock;
#endif
	
    /* local partition of the image*/
    unsigned char *partition;
	
	/* size of reduce buffer */
	int buffer_size = DIM_FIT * (DIM_FIT + 1);
	
    /* indexes */
    int i = 0;
	
    /* buffer for fit procedure */
    double *data = (double *) malloc( sizeof(double) * buffer_size );
    gsl_matrix_view matrice = gsl_matrix_view_array(data, DIM_FIT, DIM_FIT);
    gsl_vector_view vettore = gsl_vector_view_array(data + (DIM_FIT * DIM_FIT), DIM_FIT);
	
    /* output buffer of reduce */
    double *ret = (double *) malloc( sizeof(double) * buffer_size );
    gsl_matrix_view r_matrice = gsl_matrix_view_array(ret, DIM_FIT, DIM_FIT);
    gsl_vector_view r_vettore = gsl_vector_view_array(ret + (DIM_FIT * DIM_FIT), DIM_FIT);
	
	/*********************************************************************
	 INIT
	 *********************************************************************/	
	
	srand(time(NULL));
	/* in order to recover from an error */
	gsl_set_error_handler_off();
	
    /* Initialize of MPI */
    MPI_Init(&argc, &argv);
	
	/* Check the input parameters */
    if (argc != 3) {
		fprintf(stderr, "Invalid number of parameters: %d\n",argc);
		MPI_Abort(MPI_COMM_WORLD,MPI_ERR_ARG);
    }
    
    /* Every process takes their own rank */
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	
    /* Total number of processes */
    MPI_Comm_size(MPI_COMM_WORLD, &p);
	
	/* Number of workers */ 
	num_worker = p - PS;
	
    if (my_rank == EMITTER) {
#if DEBUG
		printf("Emitter with rank %d\n", my_rank);
#endif
		
#ifdef MODULE
		new_sock = Connect();
		
		if (Read(new_sock, &width, sizeof(int)) < 0)
			error("Error reading the integers");
		if (Read(new_sock, &height, sizeof(int)) < 0)
			error("Error reading the integers");
		
		dim = width * height;
		image = (unsigned char *) malloc (dim);
		/* read from the socket */
		if (Read(new_sock, image, dim) < 0)
			error("Error reading from socket");
#else		
		/* an image representing the gaussian is created and returned
		 as a unsigned char matrix */
		width = atoi(argv[1]);
		height = atoi(argv[2]);
		/* y dimension of the image is adjusted (if needed) */
		while (height % num_worker != 0) height++;
		/* image is created */
		image = createImage(width, height);
#endif		
		/* parameters of the gaussian are estimated */
		initialization(image, width, height,fit);
		
#if DEBUG
		printf("Emitter survived init\n");
#endif	
		
    } 
	
	/* broadcast data of the image */
	MPI_Bcast(&width,1,MPI_INT,EMITTER,MPI_COMM_WORLD);
	MPI_Bcast(&height,1,MPI_INT,EMITTER,MPI_COMM_WORLD);
	MPI_Bcast(&fit,DIM_FIT,MPI_DOUBLE,EMITTER,MPI_COMM_WORLD);
	
	/* dimension of the local partition are determined and relative buffers
	 are initialized */  
	
	dim = width * height;
	dimx = width;
	dimy = height / num_worker;
    ppw = dimx * dimy;
    partition = (unsigned char *) malloc(sizeof(unsigned char) * ppw);
    initBuffers(ppw);
	
    /* if I am the emitter I take the time */
    if (my_rank == EMITTER)
		gettimeofday(&tv1, NULL);
	
#ifdef PADDED
	if (my_rank == EMITTER){
		padded =(unsigned char*) malloc(sizeof(unsigned char) * ppw * p);
		for (i=0; i < dim; i++){
			padded[i + ppw] = image[i];
		}
		for(i=0;i<DIM_FIT * (DIM_FIT + 1);i++){
			ret[i] = 0;
		}		
		free(image);
		image = padded;
	}	
#endif	
	
    /*********************************************************************
	 LOOP on ELEMENTS
     *********************************************************************/		
	
    for (i = 0; i < STREAMLENGTH; i++) {
		
		/* the emitter executes the scatter */
		MPI_Scatter(image, ppw, MPI_UNSIGNED_CHAR, partition, ppw, MPI_UNSIGNED_CHAR, EMITTER, MPI_COMM_WORLD);
		/* execute the procedure over my partition */		
		if(my_rank >= PS){
			procedure(partition, dimx, dimy , fit, matrice, vettore, dimy*(my_rank-PS));
		}
	
		/* execute the reduce of matrix and vector */
		MPI_Reduce(data, ret, buffer_size , MPI_DOUBLE, MPI_SUM, EMITTER, MPI_COMM_WORLD);
		
		if (my_rank == EMITTER) {
			/* adjust fit results */			
			postProcedure(r_matrice,r_vettore,fit);	
		}
		
		/* broadcast of the result */
		MPI_Bcast(fit, DIM_FIT, MPI_DOUBLE, EMITTER, MPI_COMM_WORLD);
		
#ifdef DEBUG
		if (my_rank == EMITTER) {
			printf("Image %d: %f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n", i, fit[PAR_A], fit[PAR_X],
				   fit[PAR_Y], fit[PAR_SX], fit[PAR_SY], fit[PAR_a], fit[PAR_b], fit[PAR_c]);
		}
#endif
		
#ifdef MODULE
		if (my_rank == EMITTER && i < STREAMLENGTH - 1) {		
			/* new image is stored in buffer image of the emitter*/
#ifdef PADDED
			if (Read(new_sock, image + ppw, dim) < 0)
				error("Error reading from socket");
#else			
			if (Read(new_sock, image, dim) < 0)
				error("Error reading from socket");
#endif				
		}
#endif			
    }
	
    if (my_rank == EMITTER) {
		gettimeofday(&tv2, NULL);
		/* print the parallelism degree, data size and the completion time */
		printf("%d\t%d\t%ld\n", p, dim,  (tv2.tv_sec - tv1.tv_sec) * 1000000 + tv2.tv_usec - tv1.tv_usec);
    }
    
	freeBuffers();
    /* Finalize of MPI */
    MPI_Finalize();
    
    return 0;
}
Пример #27
0
                        std::string op = options->getOptionString();
                        size_t i = op.find("x");

                        std::stringstream ss1(op.substr(0, i));
                        std::stringstream ss2(op.substr(i+1, op.size()));
                        ss1 >> w;
                        ss2 >> h;
                        if (w==0 || h==0){
                                image = createImage(handle, dimensionData.width, dimensionData.height);
                        }
                        else{
                                image = createImage(handle, w, h);
                        }
                }
                else{
                        image = createImage(handle, dimensionData.width, dimensionData.height);
                }
                rsvg_handle_free(handle);
                image->setFileName(file);
                return image;
        }

        osg::Image* createImage(RsvgHandle *handle, unsigned int width, unsigned int height) const
        {
                RsvgDimensionData dimensionData;
                rsvg_handle_get_dimensions( handle, &dimensionData);
                // If image resollution < 128, cairo produces some artifacts.
                // I don't know why, but we check the size...
                if (width < 128) width = 128;
                if (height < 128) height = 128;
                width = osg::Image::computeNearestPowerOfTwo(width);
Пример #28
0
Image *resample(Image *source, unsigned int target_width, unsigned int target_height) {
	Image *destination = createImage(target_width, target_height);
	gdResample(destination, source, 0, 0, 0, 0, target_width, target_height, source->width, source->height);
	return destination;
}
Пример #29
0
void StereoExhaustiveBM(const IplImage* left,const IplImage* right,IplImage* dst,IplImage* xdst,IplImage* ydst,const int blocksize,const float threshold,const int xlimit,const int ylimit)
{
	int il,jl;
	int ir,jr;
	int i;
	int irtempf,jrtempf;
	int irtempt,jrtempt;
	int ircorr,jrcorr;
	int xshift,yshift;
	float msosd;
	float fsosd;
	double arraycorr[10000];
	int arraycount=0;
	IplImage *leftm;
    IplImage *rightm;
    int stat[10000];
    
    leftm=createImage(left->width,left->height,3);
    rightm=createImage(right->width,right->height,3);
	//printf("******done\n\n\n");
	//cvNamedWindow("Disp",CV_WINDOW_NORMAL);
	//printf("******done\n\n\n");
	//cvNamedWindow("XDisp",CV_WINDOW_AUTOSIZE);
	//cvNamedWindow("YDisp",CV_WINDOW_AUTOSIZE);
	//cvNamedWindow("Position on Left",CV_WINDOW_AUTOSIZE);
	//cvNamedWindow("Position on Right",CV_WINDOW_AUTOSIZE);
	double min,max;
	for(i=0;i<1000;i++)
	{
		arraycorr[i]=0;
	}
	for(i=0;i<1000;i++)
	{
		stat[i]=0;
	}
	for(il=0;il<=left->width-blocksize;il+=blocksize)
	{	
		for(jl=0;jl<=left->height-blocksize;jl+=blocksize)
		{
			//msosd=100000000;
			msosd=-5;
			//printf("\n %d %d",il,jl);
			//for(ir=0;ir<right->width-blocksize;ir++)
			
			irtempf=il-xlimit;
			jrtempf=jl-ylimit;
			irtempt=il+xlimit;
			jrtempt=jl+ylimit;
			if(irtempf<0)
			{
				irtempf=0;
			}
			if(jrtempf<0)
			{
				jrtempf=0;
			}
			if(irtempt>left->width-blocksize)
			{
				irtempt=left->width-blocksize;
			}
			if(jrtempt>left->height-blocksize)
			{
				jrtempt=left->height-blocksize;
			}
			
			for(ir=irtempf;ir<irtempt;ir++)
			//for(ir=0;ir<=right->width-blocksize;ir++)
			{
				//printf("\n Block In Right Image %d %d",ir,jr);
				for(jr=jrtempf;jr<jrtempt;jr++)
				//for(jr=0;jr<right->height-blocksize;jr++)
				{
					fsosd=newcorr(left,right,il,jl,ir,jr,blocksize);
					//fsosd=ncorrelation(left,right,il,jl,ir,jr,blocksize);
					//fsosd=sumofsquaredifference(left,right,il,jl,ir,jr,blocksize);
					//printf("\n CORRELATON ~ %f",fsosd );
					if(fsosd>msosd)
					{
						ircorr=ir;
						jrcorr=jr;
						//printf("\n FSOSD %f",fsosd);
						//printf("\n Mininimum msosd %d",msosd);
						msosd=fsosd;
						xshift=abs(ir-il);
						yshift=abs(jr-jl);
						//printf("\nSHIFT~ %d %d  ICORR~ %d JCORR~ %d",xshift,yshift,ircorr,jrcorr);
						//cvWaitKey(100);
						//assignDisparity(xdst,il,jl,blocksize,xshift,0);
						//assignDisparity(ydst,il,jl,blocksize,yshift,0);
					}
				}
			}

			//cvWaitKey(10);
			//printf("\nCORRELATON is %f",msosd);
			arraycorr[arraycount]=msosd;
			arraycount++;
			//printf("\nCORRELATON ~ %f".msosd);
			//cvDrawRectangle(left,leftm,blocksize,il,jl,1);
            //cvDrawRectangle(right,rightm,blocksize,ircorr,jrcorr,2);
            //cvShowImage("Position on Left",leftm);
			//cvShowImage("Position on Right",rightm);
			if(msosd>threshold)
			{
				assignDisparity(xdst,il,jl,blocksize,4*xshift,0);
				assignDisparity(ydst,il,jl,blocksize,4*yshift,0);
				//printf("\n Now at ~ %d %d",il,jl);
				//cvWaitKey(100);
				//cvShowImage("XDisp",xdst);
				//cvShowImage("YDisp",ydst);
			}
			else{
				//printf("\n  Below Threshold");
				assignDisparity(xdst,il,jl,blocksize,0,0);
				assignDisparity(ydst,il,jl,blocksize,0,0);
				//cvShowImage("XDisp",xdst);
				//cvShowImage("YDisp",ydst);
			}
		}
		//assignDisparity(dst,il,jl,blocksize,xshift,0);//B
		//assignDisparity(dst,il,jl,blocksize,yshift,2);//R
		//cvWaitKey(500);
		
	}
	cvNamedWindow("XDisp",CV_WINDOW_AUTOSIZE);
	cvNamedWindow("YDisp",CV_WINDOW_AUTOSIZE);
	cvShowImage("XDisp",xdst);
	cvShowImage("YDisp",ydst);
	printf("\nPress Escape TO Show Statistics for CORRELATON");
	cvWaitKey(0);
	
	min=1;
	max=-1;
	
	for(i=0;i<arraycount;i++)
	{
		//arraycorr[i]*1000;
		if(arraycorr[i]>max)
		{
			max=arraycorr[i];
		}
		if(arraycorr[i]<min)
		{
			min=arraycorr[i];
		}
		//stat[(int)(arraycorr[i]*1000)]=stat[(int)(arraycorr[i]*1000)]+1;
	}
	printf("\nMAXIMUM nCORRELATON~ %lf \nMINIMUM nCORRELATON %lf \n",max,min);
	/*
	printf("\n ********STATISTICS******** \n");
	for(i=0;i<1000;i++)
	{
		if(stat[i]!=0)
		{
			printf("\nCORRELATION IN RANGE [%lf,%lf]--> %d",(double)i/1000,(double)(i+1)/1000,stat[i]);
		}
	}
	*/
	cvWaitKey(0);
    /*
    cvNormalize(xdst,xdst,0,255, CV_MINMAX );
    cvNormalize(ydst,ydst,0,255, CV_MINMAX );	
	cvShowImage("XDisp",xdst);
	cvShowImage("YDisp",ydst);
	cvWaitKey(0);
	cvSmooth(xdst,xdst,CV_GAUSSIAN,5,0,0,0);
	cvSmooth(ydst,ydst,CV_GAUSSIAN,5,0,0,0);
	cvShowImage("XDisp",xdst);
	cvShowImage("YDisp",ydst);
	cvWaitKey(0);
	*/
}
Пример #30
0
void
CaptionObject::load(fstream& fin)
{
  clear();

  int len;
  bool done = false;
  char keyword[100];
  while (!done)
    {
      fin.getline(keyword, 100, 0);

      if (strcmp(keyword, "captionobjectend") == 0)
	done = true;
      else if (strcmp(keyword, "position") == 0)
	{
	  float x, y;
	  fin.read((char*)&x, sizeof(float));
	  fin.read((char*)&y, sizeof(float));
	  m_pos = QPointF(x,y);
	}
      else if (strcmp(keyword, "text") == 0)
	{
	  fin.read((char*)&len, sizeof(int));
	  char *str = new char[len];
	  fin.read((char*)str, len*sizeof(char));
	  m_text = QString(str);
	  delete [] str;
	}
      else if (strcmp(keyword, "font") == 0)
	{
	  fin.read((char*)&len, sizeof(int));
	  char *str = new char[len];
	  fin.read((char*)str, len*sizeof(char));
	  QString fontStr = QString(str);
	  m_font.fromString(fontStr); 
	  delete [] str;
	}
      else if (strcmp(keyword, "color") == 0)
	{
	  unsigned char r, g, b, a;
	  fin.read((char*)&r, sizeof(unsigned char));
	  fin.read((char*)&g, sizeof(unsigned char));
	  fin.read((char*)&b, sizeof(unsigned char));
	  fin.read((char*)&a, sizeof(unsigned char));
	  m_color = QColor(r,g,b,a);
	}
      else if (strcmp(keyword, "halocolor") == 0)
	{
	  unsigned char r, g, b, a;
	  fin.read((char*)&r, sizeof(unsigned char));
	  fin.read((char*)&g, sizeof(unsigned char));
	  fin.read((char*)&b, sizeof(unsigned char));
	  fin.read((char*)&a, sizeof(unsigned char));
	  m_haloColor = QColor(r,g,b,a);
	}
      else if (strcmp(keyword, "angle") == 0)
	{
	  fin.read((char*)&m_angle, sizeof(float));
	}
    }

  QFontMetrics metric(m_font);
  m_height = metric.height();
  m_width = metric.width(m_text);

  createImage();
}