Пример #1
0
//
// Create Bitmap
//
plMipmap *plBitmapCreator::ICreateBitmap(plBitmapData *bd)
{
    hsGuardBegin("hsConverterUtils::CreateBitmap");

    // Load the bitmap
    BitmapInfo bi;
    bi.SetName(bd->fileName.AsString().c_str());

#if 0 // This isn't really an issue since the textures are packed -Colin
    const int kMaxFileNameLength = 30;
    if (strlen(bi.Filename()) > kMaxFileNameLength)
    {
        // Allow to continue, But make it painful
        char errStr[256];
        sprintf(errStr, "File name longer than %d, won't burn to CD (%s)", kMaxFileNameLength, bi.Filename());//bitmapTex->GetName());
        MessageBox(GetActiveWindow(), errStr, bd->fileName, MB_OK|MB_ICONEXCLAMATION);  
    }
#endif

    bool notMipped = (bd->texFlags & plMipmap::kForceOneMipLevel) != 0;
    float sigma = bd->sig;
    
    // Load the bitmap
    Bitmap *bm = TheManager->Load(&bi);
    if (!bm)
    {
        // FIXME
        /*
        if (fErrorMsg->Set(!(fWarned & kWarnedNoMoreBitmapLoadErr), 
            "Error loading bitmap", pathName).CheckAskOrCancel())
        {
            fWarned |= kWarnedNoMoreBitmapLoadErr;
        }
        */
        return nil;
    }
    BitmapStorage *storage = bm->Storage();
    BitmapInfo *bInfo = &storage->bi;

    ICheckOutBitmap(bInfo, bm, bd->fileName);

    //
    // Create a plMipmap 
    //
    plMipmap *hBitmap = new plMipmap;
    if( (bm->Width() ^ (bm->Width() & -bm->Width()))
        ||(bm->Height() ^ (bm->Height() & -bm->Height())) )
    {
        IResampBitmap(bm, *hBitmap);
    }
    else if( ((bm->Width() >> 3) > bm->Height())||((bm->Height() >> 3) > bm->Width()) )
    {
        IResampBitmap(bm, *hBitmap);
    }
    else
    {
Пример #2
0
void
GUI::_DisplayStringCommon(const std::string& text,
			uint16 x, uint16 y, bool centerString, uint32 time)
{
	static uint32 sCurrentId = 0;
	
	const Font* font = FontRoster::GetFont("TOOLFONT");
	uint16 height;
	uint16 stringWidth = font->StringWidth(text, &height);
	Bitmap* bitmap = new Bitmap(stringWidth, height, 8);
	bitmap->Clear(font->TransparentIndex());
	//bitmap->SetColorKey(font->TransparentIndex());
	
	// Pre-render the string to a bitmap
	GFX::rect rect(0, 0, bitmap->Width(), bitmap->Height());
	font->RenderString(text, 0, bitmap, rect);
	
	// Set the position where to  blit the bitmap
	rect.x = x;
	rect.y = y;
	if (centerString) {
		rect.x -= stringWidth / 2;
	}
	string_entry entry = { text, bitmap, rect, sCurrentId};
	fTooltipList.push_back(entry);

	long id = sCurrentId++;
	Timer::AddOneShotTimer((uint32)time, DeleteStringEntry, (void*)id);
}
void ImageCompressorBlockPalette::QuantizeToPalette(const Bitmap &bmp, OutputDataStream &stream)
{
    const UINT width = RoundDown(bmp.Width());
    const UINT height = RoundDown(bmp.Height());

    stream << width << height;
    
    for(UINT x = 0; x < width; x += blockDimension)
    {
        for(UINT y = 0; y < height; y += blockDimension)
        {
            Block32 curBlock;
            for(UINT yOffset = 0; yOffset < blockDimension; yOffset++)
            {
                for(UINT xOffset = 0; xOffset < blockDimension; xOffset++)
                {
                    curBlock.c[yOffset][xOffset] = bmp[y + yOffset][x + xOffset];
                }
            }
            UINT bestPaletteError = 0xFFFFFFFF;
            UINT bestPaletteIndex = 0;
            for(UINT paletteIndex = 0; paletteIndex < paletteSize; paletteIndex++)
            {
                UINT curPaletteError = CompareBlocks(curBlock, _palette.colors[paletteIndex]);
                if(curPaletteError < bestPaletteError)
                {
                    bestPaletteIndex = paletteIndex;
                    bestPaletteError = curPaletteError;
                }
            }
            stream << BYTE(bestPaletteIndex);
            //stream << UINT16(bestPaletteIndex);
        }
    }
}
Пример #4
0
static void BitmapDimensions(int &width, int &height, Texmap * map)
{
//	int h=dim; w=dim;
	if(map == NULL){
		//NH 05-Dec-05 This can happen when submaps are not assigned - in this case simply bail and let
		//the parent texture deal with it.
//		height = width = 0;
		return;
	}

	if(map->ClassID() == GNORMAL_CLASS_ID)
	{
		Texmap * bmap;
		map->GetParamBlock(0)->GetValue(2,0,bmap,FOREVER); // normal map
		BitmapDimensions(width,height,bmap);
		return;
	}
	else if(map->ClassID() == Class_ID(BMTEX_CLASS_ID, 0))
	{
		BitmapTex *pBT;
		Bitmap *pTex;
		pBT = static_cast<BitmapTex *>(map);
		pTex = pBT->GetBitmap(0);
		if (pTex)
		{
			width = getClosestPowerOf2(pTex->Width());
			height = getClosestPowerOf2(pTex->Height());
		}
		return;
	}
	else{
	}
}
Пример #5
0
boolean UStencil::intersects (BoxObj& userb, Graphic* gs) {
    Transformer* t = gs->GetTransformer();
    Bitmap* bitmap = (_mask == nil) ? _image : _mask;
    Coord xmax = bitmap->Width();
    Coord ymax = bitmap->Height();
    Coord tx0, ty0, tx1, ty1;
    
    if (t != nil && t->Rotated()) {
	Coord x[4], tx[5];
	Coord y[4], ty[5];
    
	x[0] = x[3] = y[0] = y[1] = 0;
	x[2] = x[1] = xmax;
	y[2] = y[3] = ymax;
	transformList(x, y, 4, tx, ty, gs);
	tx[4] = tx[0];
	ty[4] = ty[0];
	FillPolygonObj fp (tx, ty, 5);
	return fp.Intersects(userb);
    
    } else if (t != nil) {
	t->Transform(0, 0, tx0, ty0);
	t->Transform(xmax, ymax, tx1, ty1);
	BoxObj b1 (tx0, ty0, tx1, ty1);
	return b1.Intersects(userb);

    } else {
	BoxObj b2 (0, 0, xmax, ymax);
	return b2.Intersects(userb);
    }
}
Пример #6
0
void
UVMapView::DragBy(double dx, double dy)
{
    if (!material || !material->tex_diffuse || selverts.size() < 1)
        return;

    Bitmap*  bmp = material->tex_diffuse;
    double   w   = zoom * bmp->Width();
    double   h   = zoom * bmp->Height();
    float    du  = (float) (dx/w);
    float    dv  = (float) (dy/h);

    for (auto svi = selverts.begin(); svi != selverts.end(); ++svi) {
        DWORD value = *svi;
        DWORD p     = value >> 16;
        DWORD n     = value & 0xffff;

        Poly* poly = polys[p];
        if (poly && n < poly->nverts) {
            VertexSet*  vset = poly->vertex_set;
            int         v    = poly->verts[n];

            vset->tu[v] += du;
            vset->tv[v] += dv;
        }
    }
}
void D3D9RenderTargetTexture::GetData(Bitmap &B, const Rectangle2i &Source, const Rectangle2i &Dest)
{
    D3DAlwaysValidate(_Device->GetRenderTargetData(_Surface, _SurfacePlain), "GetRenderTargetData");

    if(_SurfaceResizing == NULL)
    {
        D3DAlwaysValidate(_Device->CreateOffscreenPlainSurface(_Width, _Height, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &_SurfaceResizing, NULL), "CreateOffscreenPlainSurface");
    }
    D3DAlwaysValidate(_Device->UpdateSurface(_SurfacePlain, NULL, _SurfaceResizing, NULL), "UpdateSurface");

    RECT SourceRect = Source.ToRect();
    RECT DestRect = Rectangle2i(Vec2i::Origin, Dest.Dimensions()).ToRect();
    D3DAlwaysValidate(_Device->StretchRect(_SurfaceResizing, &SourceRect, _Surface, &DestRect, D3DTEXF_LINEAR), "StretchRect");

    D3DAlwaysValidate(_Device->GetRenderTargetData(_Surface, _SurfacePlain), "GetRenderTargetData");

    D3DLOCKED_RECT LockedRect;
    D3DAlwaysValidate(_SurfacePlain->LockRect(&LockedRect, NULL, 0), "LockRect");

    Assert(int(B.Width()) >= Dest.Max.x && int(B.Height()) >= Dest.Max.y, "Bitmap too small");

    RGBColor *SurfData = (RGBColor*)LockedRect.pBits;
    for(int y = Dest.Min.y; y < Dest.Max.y; y++)
    {
        //memcpy(B[_Height - 1 - y], &SurfData[y * LockedRect.Pitch / 4], _Width * 4);
        memcpy(B[y] + Dest.Min.x, &SurfData[(y - Dest.Min.y) * LockedRect.Pitch / 4], Dest.Dimensions().x * 4);
    }

    _SurfacePlain->UnlockRect();
}
Пример #8
0
void BitmapFont::Build() {

    if (isBuilt) return;

    if (!LoadFontMap()) {
        psys->GetLogger("BitmapFont")->Error("Failed to load font map");
        return;
    }

    for(int i=0; i<256; i++) {
        if (chardefs[i]->Used()) {
            BitmapCharDef *character = chardefs[i];

            psys->GetLogger("BitmapFont")->Debug("Char '%c' (X:%d, Y:%d), (W:%d, H:%d)",i,character->X(), character->Y(), character->Width(), character->Height());
            Bitmap *bmpChar = bitmap->CopyToNew(character->X(), character->Y(), character->Width(), character->Height());

            FontChar *fc = new FontChar(i, 0, 0, bmpChar->Width(), bmpChar->Height(), bmpChar);
            //FontChar *fc = new FontChar(i, 0, 0, bitmap->Width(), bitmap->Height(), bitmap);
            fc->GenerateTexture();
            AddChar(i, fc);
        }
    }

    isBuilt = true;
}
Пример #9
0
 // Checks each pixel immediately adjacent to the given pixel in the bitmap. If
 // any of them are not the halo color, returns true. This defines the halo of
 // pixels that will appear around the text. Note that we have to check each
 // pixel against both the halo color and transparent since DrawStringWithHalo
 // will modify the bitmap as it goes, and clears pixels shouldn't count as
 // changed.
 static bool pixelShouldGetHalo(const Bitmap& bitmap,
     int x, int y, const Color& halo_color)
 {
     if(x>0 &&
         bitmap.GetPixel(x-1, y).GetValue()!=halo_color.GetValue() &&
         bitmap.GetPixel(x-1, y).GetValue()!=0)
     {
         return true; // Touched pixel to the left.
     }
     if(x<bitmap.Width()-1 &&
         bitmap.GetPixel(x+1, y).GetValue()!=halo_color.GetValue() &&
         bitmap.GetPixel(x+1, y).GetValue()!=0)
     {
         return true; // Touched pixel to the right.
     }
     if(y>0 &&
         bitmap.GetPixel(x, y-1).GetValue()!=halo_color.GetValue() &&
         bitmap.GetPixel(x, y-1).GetValue()!=0)
     {
         return true; // Touched pixel above.
     }
     if(y<bitmap.Height()-1 &&
         bitmap.GetPixel(x, y+1).GetValue()!=halo_color.GetValue() &&
         bitmap.GetPixel(x, y+1).GetValue()!=0)
     {
         return true; // Touched pixel below.
     }
     return false;
 }
Пример #10
0
boolean UStencil::contains (PointObj& po, Graphic* gs) {
    Bitmap* bitmap = (_mask == nil) ? _image : _mask;
    PointObj pt (&po);

    invTransform(pt._x, pt._y, gs);
    BoxObj b (0, 0, bitmap->Width(), bitmap->Height());
    return b.Contains(pt);
}
Пример #11
0
void Canvas::
SetTo( const Bitmap &image ) {
   ReleaseSurface();
   
   activeSurface = SurfaceInfo( BITMAP_TARGET, image.Width(), image.Height(), &image );
   SelectImage( image );
   
   FinishSurfaceSelection();
}
void ImageCompressorBlockPalette::TrainPalette(const Bitmap &bmp)
{
    Vector<const float*> allBlocks;
    
    const UINT width = bmp.Width();
    const UINT height = bmp.Height();
    for(UINT x = 0; x < width; x += blockDimension)
    {
        for(UINT y = 0; y < height; y += blockDimension)
        {
            float *curBlock = new float[blockSize * 3];
            UINT curDimensionIndex = 0;
            for(UINT yOffset = 0; yOffset < blockDimension; yOffset++)
            {
                for(UINT xOffset = 0; xOffset < blockDimension; xOffset++)
                {
                    RGBColor curColor = bmp[y + yOffset][x + xOffset];
                    curBlock[curDimensionIndex++] = curColor.r;
                    curBlock[curDimensionIndex++] = curColor.g;
                    curBlock[curDimensionIndex++] = curColor.b;
                }
            }
            allBlocks.PushEnd(curBlock);
        }
    }

    KMeansClusteringFloat<blockSize * 3> clustering;
    
    Vector<KMeansClusteringTierEntry> tierInfo(4);
    tierInfo[0] = KMeansClusteringTierEntry(4, 10);
    tierInfo[1] = KMeansClusteringTierEntry(4, 10);
    tierInfo[2] = KMeansClusteringTierEntry(4, 10);
    tierInfo[3] = KMeansClusteringTierEntry(4, 10);

    clustering.Cluster(allBlocks, tierInfo, true);
    //clustering.Cluster(allBlocks, paletteSize);
    //clustering.Cluster(allBlocks, paletteSize, 100);

    for(UINT paletteIndex = 0; paletteIndex < paletteSize; paletteIndex++)
    {
        Block32 &curEntry = _palette.colors[paletteIndex];
        const float *curCluster = clustering.ClusterCentroid(paletteIndex);
        UINT curDimensionIndex = 0;
        for(UINT yOffset = 0; yOffset < blockDimension; yOffset++)
        {
            for(UINT xOffset = 0; xOffset < blockDimension; xOffset++)
            {
                RGBColor &curColor = curEntry.c[yOffset][xOffset];
                curColor.r = BYTE(curCluster[curDimensionIndex++]);
                curColor.g = BYTE(curCluster[curDimensionIndex++]);
                curColor.b = BYTE(curCluster[curDimensionIndex++]);
            }
        }
    }
}
Пример #13
0
void
Scrollbar::_DrawTrough(const GFX::rect& screenRect)
{
	IE::scrollbar* scrollbar = (IE::scrollbar*)fControl;

	Bitmap* frame = const_cast<Bitmap*>(fResource->FrameForCycle(scrollbar->cycle,
					scrollbar->trough));
	GFX::rect destRect(screenRect.x, screenRect.y + 40,
			frame->Width(), frame->Height());
	GraphicsEngine::Get()->BlitToScreen(frame, NULL, &destRect);
}
Пример #14
0
HRESULT
AviFile::AddFrame(const Bitmap& bmp)
{
    HRESULT hr = E_FAIL;

    if (!iserr && !play && bmp.IsHighColor() && bmp.Width() == rect.w && bmp.Height() == rect.h) {
        int      w      = bmp.Width();
        int      h      = bmp.Height();
        BYTE*    buffer = new(__FILE__,__LINE__) BYTE[frame_size];
        BYTE*    dst    = buffer;

        for (int y = 0; y < bmp.Height(); y++) {
            Color* src = bmp.HiPixels()  + (h - 1 - y) * w;

            for (int x = 0; x < bmp.Width(); x++) {
                *dst++ = (BYTE) src->Blue();
                *dst++ = (BYTE) src->Green();
                *dst++ = (BYTE) src->Red();
                src++;
            }
        }

#pragma warning(suppress: 6001)
        hr = AVIStreamWrite(ps_comp, nframe, 1, buffer, frame_size, AVIIF_KEYFRAME, 0, 0);
        
        if (SUCCEEDED(hr)) {
            nframe++;
        }
        else {
            Print("AVIStreamWriteFile failed. %08x\n", hr);
            iserr = true;
        }

        delete [] buffer;
    }

    return hr;
}
Пример #15
0
Bitmap::Bitmap(const Graphics& g, const Bitmap& bitmap)
{
    if (this == &bitmap)
        return;

    m_platformBitmap = ThePlatformFactory->CreatePlatformBitmap(
        g.GetPlatformGraphics(), bitmap.Width(), bitmap.Height(),
        bitmap.BitsPerPixel());

    uchar* bits = new uchar[Height() * BytesPerLine()];
    bitmap.GetBits(g, bits, 0, Height(), BitsPerPixel());
    SetBits(g, bits, 0, Height(), BitsPerPixel());
    delete[] bits;
}
Пример #16
0
void CGraphicsView::OnLButtonUp(UINT nFlags, CPoint point)
{
	// TODO:  在此添加消息处理程序代码和/或调用默认值
	CRect rect;
	GetClientRect(&rect);
	point.x = clamp(point.x, rect.left, rect.right);
	point.y = clamp(point.y, rect.top, rect.bottom);

	m_rcSelected.left = m_MousePoint[0].x;
	m_rcSelected.top = m_MousePoint[0].y;
	m_rcSelected.right = point.x;
	m_rcSelected.bottom = point.y;

	m_rcSelected.NormalizeRect();

	if (m_pSrcBitmap && m_pDstBitmap)
	{
		CGraphicsDoc* pDoc = GetDocument();
		Bitmap* pBitmap = pDoc->GetSrcBitmap();

		int xOffset = (rect.Width() - pBitmap->Width()*2) / 2;
		int yOffset = (rect.Height() - pBitmap->Height()) / 2;

		if (!m_rcSelected.IsRectEmpty())
		{
			int x0 = clamp(m_rcSelected.left - xOffset, 0, (int)pBitmap->biWidth - 1);
			int y0 = clamp(m_rcSelected.top - yOffset, 0, (int)pBitmap->biHeight - 1);
			int x1 = clamp(m_rcSelected.right - xOffset, 0, (int)pBitmap->biWidth - 1);
			int y1 = clamp(m_rcSelected.bottom - yOffset, 0, (int)pBitmap->biHeight - 1);
			//test clone
			pBitmap = pDoc->CloneBitmap(pBitmap, x0, y0, x1, y1);
			assert(pBitmap != 0);
			m_pProcesser->DrawRect(pBitmap, 0, 0, pBitmap->biWidth-1, pBitmap->biHeight-1);
			pBitmap->Save("f:\\clone.bmp");
			delete pBitmap;
		}
		else
		{
			m_rcSelected.SetRect(xOffset, yOffset, xOffset + pBitmap->biWidth, yOffset + pBitmap->biHeight);
		}
	}

	m_bMouseDown = FALSE;

	ReleaseCapture();

	SendMessage(WM_PAINT, 0, 0);

	CView::OnLButtonUp(nFlags, point);
}
void D3D9RenderTargetTexture::SetData(const Bitmap &B)
{
    D3DLOCKED_RECT LockedRect;
    D3DAlwaysValidate(_SurfacePlain->LockRect(&LockedRect, NULL, 0), "LockRect");

    Assert(B.Width() == _Width && B.Height() == _Height, "Invalid bitmap dimensions.");
    RGBColor *SurfData = (RGBColor*)LockedRect.pBits;
    for(UINT y = 0; y < _Height; y++)
    {
        memcpy(&SurfData[y * LockedRect.Pitch / 4], B[_Height - 1 - y], _Width * 4);
    }

    _SurfacePlain->UnlockRect();
    D3DAlwaysValidate(_Device->UpdateSurface(_SurfacePlain, NULL, _Surface, NULL), "UpdateSurface");

    _DataCopy = B;
}
Пример #18
0
int PlateMap::AllocMap(int w, int h) {
	if ( bm && w==bm->Width() && h==bm->Height())
		return 1;
	BitmapInfo bi;
	if (bm) bm->DeleteThis();
	bi.SetName(_T(""));
	bi.SetWidth(w);
	bi.SetHeight(h);
	bi.SetType(BMM_TRUE_32);
	bi.SetCustomFlag(BMM_CUSTOM_GAMMA);
	bi.SetCustomGamma(1.0f);

	bm = TheManager->Create(&bi);

//	bm->CreateChannels(BMM_CHAN_Z); 
	return 1;
	}
Пример #19
0
void VideoCompressor::AddFrame(const Bitmap &Bmp, double TimeInSeconds)
{
    if(_Clock != NULL)
    {
        TimeInSeconds = _Clock->Elapsed();
    }
    _Sample->SetSampleTime( LONGLONG( TimeInSeconds * 10000000.0 ) );
        
    BYTE *BufferData;
    HRESULT hr = _Buffer->Lock(&BufferData, NULL, NULL);
    PersistentAssert(SUCCEEDED(hr), "_Buffer->Lock failed");

    memcpy( BufferData, &(Bmp[0][0]), Bmp.Width() * Bmp.Height() * sizeof(RGBColor) );
    _Buffer->Unlock();

    hr = _Writer->WriteSample(0, _Sample);
    PersistentAssert(SUCCEEDED(hr), "WriteSample failed");
}
Пример #20
0
void D3D9Texture::Load(const Bitmap &Bmp)
{
    Allocate(D3DFMT_A8R8G8B8, Bmp.Width(), Bmp.Height(), false, 0);
    D3DLOCKED_RECT Rect;
    D3DValidate(_Texture->LockRect(0, &Rect, NULL, 0), "LockRect");
    BYTE *Bytes = (BYTE *)Rect.pBits;
    for(UINT y = 0; y < _Height; y++)
    {
        RGBColor *CurRow = (RGBColor *)(Bytes + y * Rect.Pitch);
        for(UINT x = 0; x < _Width; x++)
        {
            RGBColor Color = Bmp[y][x];
            CurRow[x] = RGBColor(Color.b, Color.g, Color.r, Color.a);
        }
    }
    D3DValidate(_Texture->UnlockRect(0), "UnlockRect");
    UpdateMipMapLevels();
}
Пример #21
0
void UStencil::getExtent (
    float& x0, float& y0, float& cx, float& cy, float& tol, Graphic* gs
) {
    Bitmap* bitmap = (_mask == nil) ? _image : _mask;
    float w = float(bitmap->Width());
    float h = float(bitmap->Height());

    if (gs->GetTransformer() == nil) {
	x0 = y0 = 0;
	cx = w/2;
	cy = h/2;
    } else {
	transformRect(0, 0, w, h, x0, y0, cx, cy, gs);
	cx = (cx + x0)/2;
	cy = (cy + y0)/2;
    }
    tol = 0;
}
Пример #22
0
bool
UVMapView::WillSelect(CPoint& p)
{
    if (!material || !material->tex_diffuse)
        return false;

    Bitmap*  bmp = material->tex_diffuse;
    int      w   = bmp->Width();
    int      h   = bmp->Height();

    double   cx  = window->Width()  / 2 + x_offset;
    double   cy  = window->Height() / 2 + y_offset;

    // find first selected vert:
    ListIter<Poly> iter = polys;
    while (++iter) {
        Poly*       poly  = iter.value();
        VertexSet*  vset  = poly->vertex_set;

        for (int i = 0; i < poly->nverts; i++) {
            int    n1   = poly->verts[i];
            double tu1  = vset->tu[n1];
            double tv1  = vset->tv[n1];

            int x1 = (int) (cx + zoom * w * (tu1-0.5));
            int y1 = (int) (cy + zoom * h * (tv1-0.5));

            int dx = abs(p.x - x1);
            int dy = abs(p.y - y1);

            if (dx < 4 && dy < 4) {
                return true;
            }
        }
    }

    return false;
}
Пример #23
0
void D3D10Texture::Load(const Bitmap &Bmp)
{
    PersistentAssert(_GD != NULL, "D3D10Texture::Load on unassociated texture");

    Allocate(Bmp.Width(), Bmp.Height(), true, DXGI_FORMAT_R8G8B8A8_UNORM, Bmp);
}
Пример #24
0
void
UVMapView::End()
{
    active = false;

    // get the model:
    if (!nmarks || !material || !material->tex_diffuse) return;

    // if not adding to selection:
    if (select_mode == SELECT_REPLACE) {
        Clear();
    }

    Bitmap*  bmp = material->tex_diffuse;
    int      w   = bmp->Width();
    int      h   = bmp->Height();

    double   cx  = window->Width()  / 2 + x_offset;
    double   cy  = window->Height() / 2 + y_offset;


    // if only one mark:
    if (nmarks < 2) {
        // find all selected verts:
        ListIter<Poly> iter = polys;
        while (++iter) {
            Poly*       p     = iter.value();
            VertexSet*  vset  = p->vertex_set;

            for (int i = 0; i < p->nverts; i++) {
                int    n1   = p->verts[i];
                double tu1  = vset->tu[n1];
                double tv1  = vset->tv[n1];

                int x1 = (int) (cx + zoom * w * (tu1-0.5));
                int y1 = (int) (cy + zoom * h * (tv1-0.5));

                int dx = abs(marks[0].x - x1);
                int dy = abs(marks[0].y - y1);

                if (dx < 4 && dy < 4) {
                    WORD  p_index = iter.index();
                    DWORD value   = (p_index << 16) | i;

                    if (select_mode == SELECT_REMOVE) {
                        for (auto svi = selverts.begin(); svi != selverts.end(); ++svi) {
                            if (*svi == value) {
                                selverts.erase(svi);
                            }
                        }
                    }
                    else {
                        bool contains = false;
                        for (auto svi = selverts.begin(); svi != selverts.end(); ++svi) {
                            if (*svi == value) {
                                contains = true;
                            }
                        }
                        if (!contains)
                            selverts.push_back(value);
                    }
                }
            }
        }
    }

    // otherwise, build a region:
    else {
        CRgn rgn;
        rgn.CreatePolygonRgn(marks, nmarks, WINDING);

        // find all selected verts:
        ListIter<Poly> iter = polys;
        while (++iter) {
            Poly*       p     = iter.value();
            VertexSet*  vset  = p->vertex_set;

            for (int i = 0; i < p->nverts; i++) {
                int    n1   = p->verts[i];
                double tu1  = vset->tu[n1];
                double tv1  = vset->tv[n1];

                int x1 = (int) (cx + zoom * w * (tu1-0.5));
                int y1 = (int) (cy + zoom * h * (tv1-0.5));

                CPoint p(x1,y1);

                if (rgn.PtInRegion(p)) {
                    WORD  p_index = iter.index();
                    DWORD value   = (p_index << 16) | i;

                    if (select_mode == SELECT_REMOVE) {
                        for (auto svi = selverts.begin(); svi != selverts.end(); ++svi) {
                            if (*svi == value)
                                selverts.erase(svi);
                        }
                    }
                    else {
                        bool contains = false;
                        for (auto svi = selverts.begin(); svi != selverts.end(); ++svi) {
                            if (*svi == value)
                                contains = true;
                        }
                        if (!contains)
                            selverts.push_back(value);
                    }
                }
            }
        }
    }

    nmarks = 0;
}
Пример #25
0
void
UVMapView::Refresh()
{
    video = Video::GetInstance();
    if (!video)
        return;

    window->FillRect(window->GetRect(), Color::LightGray);

    if (material && material->tex_diffuse) {
        Bitmap*  bmp = material->tex_diffuse;
        int      w   = bmp->Width();
        int      h   = bmp->Height();

        double   cx  = window->Width()  / 2 + x_offset;
        double   cy  = window->Height() / 2 + y_offset;

        int      x1  = (int) (cx - (zoom * w/2));
        int      x2  = (int) (cx + (zoom * w/2));
        int      y1  = (int) (cy - (zoom * h/2));
        int      y2  = (int) (cy + (zoom * h/2));

        window->DrawBitmap(x1, y1, x2, y2, bmp);

        ListIter<Poly> iter = polys;
        while (++iter) {
            Poly*       p     = iter.value();
            VertexSet*  vset  = p->vertex_set;

            if (p->material != material)
                continue;

            for (int i = 0; i < p->nverts; i++) {
                int    n1   = p->verts[i];
                int    n2   = p->verts[0];
                if (i < p->nverts-1)
                    n2 = p->verts[i+1];

                double tu1  = vset->tu[n1];
                double tv1  = vset->tv[n1];
                double tu2  = vset->tu[n2];
                double tv2  = vset->tv[n2];

                x1 = (int) (cx + zoom * w * (tu1-0.5));
                x2 = (int) (cx + zoom * w * (tu2-0.5));
                y1 = (int) (cy + zoom * h * (tv1-0.5));
                y2 = (int) (cy + zoom * h * (tv2-0.5));

                window->DrawLine(x1,   y1,   x2,   y2,   Color::Yellow);

                if (IsSelected(p, i))
                    window->FillRect(x1-3, y1-3, x1+3, y1+3, Color::Yellow);
                else
                    window->DrawRect(x1-2, y1-2, x1+2, y1+2, Color::Yellow);
            }
        }
    }

    if (active && nmarks > 1) {
        float points[4*BATCH_SIZE + 4];

        for (int batch = 0; batch < nmarks; batch += BATCH_SIZE) {
            int end = batch + BATCH_SIZE;
            if (end > nmarks-1)
                end = nmarks-1;
            int nlines = end-batch;

            for (int i = 0; i < nlines; i++) {
                points[4*i+0] = (float) marks[batch + i].x;
                points[4*i+1] = (float) marks[batch + i].y;
                points[4*i+2] = (float) marks[batch + i + 1].x;
                points[4*i+3] = (float) marks[batch + i + 1].y;
            }

            video->DrawScreenLines(nlines, points, Color::Cyan);
        }
    }

    const char* title = "UV Editor";

    int  len = strlen(title);
    Rect r(6,4,200,20);

    r.x += window->GetRect().x;
    r.y += window->GetRect().y;

    video->DrawText(title, len, r, DT_LEFT|DT_SINGLELINE, Color::Black);

    r.x--;
    r.y--;

    video->DrawText(title, len, r, DT_LEFT|DT_SINGLELINE, Color::White);
}
Пример #26
0
AWDTexture *
AWDExporter::ExportTexture(AWD *awd, awd_ncache *ncache,Texmap* tex, Class_ID cid, int subNo, AWDMaterial * mat ) {

    AWDTexture *awd_tex;

    const char* name;
    int name_len;
    bool hasAlpha = false;

    MSTR path;

    awd_uint8 * buf;
    int buf_len;



    if (!tex) return NULL;
    if (tex->ClassID() != Class_ID(BMTEX_CLASS_ID, 0x00) ) return NULL;


    // texture already exist in cache
    awd_tex = (AWDTexture *)awd_ncache_get( ncache, tex );
    if( awd_tex ) return awd_tex;

    BitmapTex *bmptex = (BitmapTex*)tex;

    MaxSDK::AssetManagement::AssetUser asset = bmptex->GetMap();

    hasAlpha = bmptex->GetBitmap( GetStaticFrame() )->HasAlpha();

    if( !asset.GetFullFilePath(path) ) {
        fprintf( logfile, " export !asset.GetFullFilePath(path) : %i \n", asset.GetType() );
        fflush( logfile );

        //return NULL;
    }

    fprintf( logfile, " export  : %s \n", path );
    fflush( logfile );

    AWD_tex_type textype = EXTERNAL;

    if( GetIncludeMaps() &&
            asset.GetType() == MaxSDK::AssetManagement::kBitmapAsset
      ) {


        const char * dot;
        dot = strrchr(path,'.');




        if( !strcmp(dot, ".jpg")||
                !strcmp(dot, ".JPG")||
                !strcmp(dot, ".jpeg")||
                !strcmp(dot, ".JPEG")
          ) {
            textype = EMBEDDED_JPEG;
        } else if (
            !strcmp(dot, ".png")||
            !strcmp(dot, ".PNG")
        ) {
            textype = EMBEDDED_PNG;
        }



        if( textype == 0 ) {

            fprintf( logfile, " export texture : %s \n", path );
            fflush( logfile );
            // try to extract data
            Bitmap *bmp = bmptex->GetBitmap( GetStaticFrame() );

            BitmapInfo bi;

            MaxSDK::Util::Path *temppath;

            bi.SetWidth( bmp->Width() );
            bi.SetHeight( bmp->Height() );
            if( hasAlpha ) {
                bi.SetType( BMM_TRUE_32 );
                bi.SetFlags( MAP_HAS_ALPHA );
                path = "C:\\Users\\lepersp\\Desktop\\temp\\awdexporttempjpg.png";
                textype = EMBEDDED_PNG;
            } else {
                bi.SetType( BMM_TRUE_24 );
                path = "C:\\Users\\lepersp\\Desktop\\temp\\awdexporttempjpg.jpg";
                textype = EMBEDDED_JPEG;
            }

            temppath = new MaxSDK::Util::Path( path );
            bi.SetPath( *temppath );

            bmp->OpenOutput( & bi );
            bmp->Write( & bi );
            bmp->Close(& bi);

        }

        if( path != NULL ) {

            size_t result;

            int fd;
            errno_t err = _sopen_s( &fd, path, _O_RDONLY|_O_BINARY, _SH_DENYNO, _S_IREAD );

            if( err == 0 ) {

                struct stat *s;
                s = (struct stat *)malloc(sizeof(struct stat));
                fstat(fd, s);

                buf_len = s->st_size;
                buf = (awd_uint8 *) malloc (buf_len * sizeof( awd_uint8 ) );

                lseek(fd, 0, SEEK_SET);
                result = read(fd, buf, buf_len);


                if (result != buf_len) {
                    textype = EXTERNAL;
                }

                _close( fd );
            } else {
                textype = EXTERNAL;
            }
        }
    }

    name = tex->GetName();
    name_len = strlen( name );
    char* namecpy = (char*) malloc( name_len*sizeof( char ) ) ;
    strcpy( namecpy, name );

    awd_tex = new AWDTexture( textype, namecpy, name_len );

    if( textype != 0 ) {
        awd_tex->set_embed_data(buf, buf_len);
    }



    char * pathcpy = (char *) malloc( (path.length()+1) * sizeof( char ) );
    strcpy( pathcpy, path.data() );


    awd_tex->set_url( pathcpy, strlen( pathcpy ) );

    awd->add_texture( awd_tex );

    awd_ncache_add( ncache, tex, awd_tex );

    if( subNo == ID_DI ) {
        mat->set_texture( awd_tex );
        mat->alpha_blending = hasAlpha;
    }

    return awd_tex;
}
Пример #27
0
LONG BitmapButton::ProcessMessage(HWND hWnd, size_t msg, size_t wParam, LONG lParam)
{
	if (msg == WM_LBUTTONDOWN)
	{
		long res = CallWindowProc(DefaultHandler, hWnd, msg, wParam, lParam);
		SendMessage(hWnd, BM_SETSTATE, (WPARAM)BST_PUSHED, 0);
		InvalidateRect(hWnd, NULL, false);
		return res;
	}
	else if (msg == WM_LBUTTONUP)
	{
		long res = CallWindowProc(DefaultHandler, hWnd, msg, wParam, lParam);
		SendMessage(hWnd, BM_SETSTATE, (WPARAM)0, 0);
		InvalidateRect(hWnd, NULL, false);
		return res;
	}
	else if ((msg == WM_COMMAND) || (msg == BN_CLICKED))
	{
		if (clickHandler)
		{
			clickHandler();
			return true;
		}
		else if (dClickHandler)
		{
			(clickListener->*dClickHandler)();
			return true;
		}
		else 
			return false;
	}
	else if (msg == WM_ERASEBKGND)
	{
/*
		HBRUSH hOldBrush;
		HPEN hOldPen;
		RECT rect;
		HDC hDC;

		hDC = GetDC(hWnd);
		hOldBrush = (HBRUSH)SelectObject(hDC, erasePen);
		hOldPen = (HPEN)SelectObject(hDC, eraseBrush);

		GetUpdateRect(hWnd, &rect, FALSE);
		::Rectangle(hDC, rect.left, rect.top, rect.right, rect.bottom);

		SelectObject(hDC, hOldPen);
		SelectObject(hDC, hOldBrush);

		InvalidateRect(hWnd, NULL, FALSE);
*/
		return true;	
	}
	else if (msg == WM_PAINT)
	{
		HDC tmp = dc;
		PAINTSTRUCT ps;
		RECT rect;

		BeginPaint(hWnd, &ps);

		rect.left = 0; rect.right = Width();
		rect.top = 0; rect.bottom = Height();

		HBRUSH hOldBrush = (HBRUSH)SelectObject(dc, erasePen);
		HPEN hOldPen = (HPEN)SelectObject(dc, eraseBrush);
		::Rectangle(dc, rect.left, rect.top, rect.right, rect.bottom);

		SelectObject(dc, hOldPen);
		SelectObject(dc, hOldBrush);

		int state = SendMessage(hWnd, BM_GETSTATE, 0, 0);
		Bitmap *bit;
		int offset;
		if ((state & BST_PUSHED) == 0)
		{
			DrawEdge(dc, &rect, EDGE_RAISED, BF_ADJUST | BF_RECT);
			if (IsEnabled())
				bit = upBitmap;
			else
				bit = disabledBitmap;
			offset = 0;
		}
		else
		{
			DrawEdge(dc, &rect, EDGE_SUNKEN, BF_ADJUST | BF_RECT);
			bit = downBitmap;
			offset = 1;
		}

		bit->Copy(*this, (Width() - bit->Width()) / 2 + offset, (Height() - bit->Height()) / 2 + offset, bit->Width(), 
				  bit->Height(), 0, 0);

		dc = tmp;
		return false;
	}

	return false;
}
Пример #28
0
bool plDistributor::IFailsProbBitmap(int iFace, const Point3& bary) const
{
    // If we don't have a probability map, or we don't have
    // valid coordinates into it, just return false. That is,
    // with no valid probability map, everything goes.
    int uvwChan = 1;
    Matrix3 uvtrans(true);
    Bitmap* bm = nil;
    UINT filtType = BMM_FILTER_PYRAMID;
    if( fProbBitmapTex )
    {
        uvwChan = fProbBitmapTex->GetMapChannel();
        fProbBitmapTex->GetUVTransform(uvtrans);

        bm = fProbBitmapTex->GetBitmap(TimeValue(0));

        if( bm && !bm->HasFilter() )
        {
            switch( fProbBitmapTex->GetFilterType() )
            {
            default:
            case FILTER_PYR:
                filtType = BMM_FILTER_PYRAMID;
                break;
            case FILTER_SAT:
                filtType = BMM_FILTER_SUM;
                break;
            case FILTER_NADA:
                filtType = BMM_FILTER_NONE;
                break;
            }
        }
    }
    else if( fProbLayerTex )
    {
        uvwChan = fProbLayerTex->GetMapChannel();
        fProbLayerTex->GetUVTransform(uvtrans);

        bm = fProbLayerTex->GetBitmap(TimeValue(0));

    }

    if( !bm )
        return false;

    if( !bm->HasFilter() )
        bm->SetFilter(filtType);

    bm->PrepareGChannels(&bm->Storage()->bi);

    if( !fSurfMesh->mapSupport(uvwChan) )
        return false;

    if( !fSurfMesh->mapFaces(uvwChan) || !fSurfMesh->mapVerts(uvwChan) )
        return false;

    // Lookup the appropriate texel value
    Point3 uvw;
    uvw = fSurfMesh->mapVerts(uvwChan)[fSurfMesh->mapFaces(uvwChan)[iFace].getTVert(0)] * bary[0];
    uvw += fSurfMesh->mapVerts(uvwChan)[fSurfMesh->mapFaces(uvwChan)[iFace].getTVert(1)] * bary[1];
    uvw += fSurfMesh->mapVerts(uvwChan)[fSurfMesh->mapFaces(uvwChan)[iFace].getTVert(2)] * bary[2];

    uvw = uvw * uvtrans;

    float fu = uvw.x - int(uvw.x);
    if( fu < 0 )
        fu += 1.f;
    float fv = 1.0f - (uvw.y - int(uvw.y));
    if( fv < 0 )
        fv += 1.f;
    float du = 1.f / bm->Width();
    float dv = 1.f / bm->Height();

    BMM_Color_fl evCol;
    bm->GetFiltered(fu, fv, du, dv, &evCol);
    
    float frac;
    switch( fProbColorChan )
    {
    case kRed:
        frac = evCol.r;
        break;
    case kGreen:
        frac = evCol.g;
        break;
    case kBlue:
        frac = evCol.b;
        break;
    case kAlpha:
        frac = evCol.a;
        break;
    case kAverageRedGreen:
        frac = (evCol.r + evCol.g) / 2.f;
        break;
    case kAverageRedGreenTimesAlpha:
        frac = (evCol.r + evCol.g) / 2.f * evCol.a;
        break;
    case kAverage:
        frac = (evCol.r + evCol.g + evCol.b ) / 3.f;
        break;
    case kAverageTimesAlpha:
        frac = (evCol.r + evCol.g + evCol.b ) / 3.f * evCol.a;
        break;
    case kMax:
    case kMaxColor:
        frac = hsMaximum(evCol.r, hsMaximum(evCol.g, evCol.b));
        break;
    case kMaxColorTimesAlpha:
        frac = hsMaximum(evCol.r, hsMaximum(evCol.g, evCol.b)) * evCol.a;
        break;
    case kMaxRedGreen:
        frac = hsMaximum(evCol.r, evCol.g);
        break;
    case kMaxRedGreenTimesAlpha:
        frac = hsMaximum(evCol.r, evCol.g) * evCol.a;
        break;
    }

    if( fProbRemapFromHi != fProbRemapFromLo )
        frac = fProbRemapToLo + (frac - fProbRemapFromLo) / (fProbRemapFromHi - fProbRemapFromLo) * (fProbRemapToHi - fProbRemapToLo);
    else
        frac = frac > fProbRemapFromHi ? fProbRemapToHi : fProbRemapToLo;

    return frac < fRand.RandZeroToOne();
}
Пример #29
0
//DIB Methods
Value*
getViewportDib_cf(Value** arg_list, int count)
{
	check_arg_count(getViewportDib, 0, count);
	GraphicsWindow *gw = MAXScript_interface->GetActiveViewExp().getGW();
	BITMAPINFO *bmi = NULL;
	BITMAPINFOHEADER *bmih;
	BitmapInfo bi;
	Bitmap *bmp;
	int size;
	gw->getDIB(NULL, &size);
	bmi  = (BITMAPINFO *)malloc(size);
	bmih = (BITMAPINFOHEADER *)bmi;
	gw->getDIB(bmi, &size);
	bi.SetWidth((WORD)bmih->biWidth);
	bi.SetHeight((WORD)bmih->biHeight);
	bi.SetType(BMM_TRUE_32);

	UWORD  *gammatab = NULL;

	IColorCorrectionMgr* idispGamMgr = (IColorCorrectionMgr*) GetCOREInterface(COLORCORRECTIONMGR_INTERFACE);
	float gamma = 1.0f; // default if off
	if(gammaMgr.IsEnabled() && idispGamMgr)
	{
		gamma = idispGamMgr->GetGamma();
		gammatab = new UWORD[RCOLN];

		// Build gamma correction table
		if (gammatab)
			BuildGammaTab(gammatab, 1.0f/gamma, true);

		// To gamma-correct we need 64 bits resolution
		bi.SetType(BMM_TRUE_64);
	}

	bi.SetGamma(1.0f); // New bitmap will be linear

	bmp = CreateBitmapFromBitmapInfo(bi); // Make new, linear bitmap
	bmp->FromDib(bmi);

	free(bmi);    // JBW 10.7.99: missing free(), elided above I/O, not desired

	// If gamma is on:
	/* EXPLANATION:
		The code that saves a bitmap always assumes the bitmap to be saved comes from the renderer,
		and hence, is linear. Since we are grabbing off the viewport (with an embedded gamma) we
		need to linearize the bitmap first */
	if (gammatab)
	{
		// We still want this to be SAVED with a gamma. What gamma MaxScript will save
		// this with (by default) is defined by the gamma of the BitmapInfo bi's gamma
		// And we intentionally want it to look like it was displayed - hence we use the
		// display gamma!!
		bi.SetGamma(gamma);

		int h = bmp->Height();
		int w = bmp->Width();

		BMM_Color_64 *pixelrow = (BMM_Color_64 *)LocalAlloc(LPTR,w*sizeof(BMM_Color_64));

		if (pixelrow) 
		{
			for (int iy = 0; iy < h; iy++) {
				bmp->GetPixels(0, iy, w, pixelrow);
				for (int ix = 0; ix < w; ix++) {
					
					pixelrow[ix].r = gammatab[UWORD(pixelrow[ix].r) >> RCSH16];
					pixelrow[ix].g = gammatab[UWORD(pixelrow[ix].g) >> RCSH16];
					pixelrow[ix].b = gammatab[UWORD(pixelrow[ix].b) >> RCSH16];
				}
				bmp->PutPixels(0, iy, w, pixelrow);
			}
			LocalFree(pixelrow);
		}

		delete [] gammatab;
	}

	return new MAXBitMap(bi, bmp);
}