示例#1
0
 def PrintScreen(self, *args):
     year, month, weekday, day, hour, minute, second, msec = blue.os.GetTimeParts(
         blue.os.GetWallclockTime())
     date = '%d.%.2d.%.2d.%.2d.%.2d.%.2d' % (year, month, day, hour, minute,
                                             second)
     ext = 'png'
     path = '%s/%s/capture/Screenshots/%s.%s' % (
         blue.sysinfo.GetUserDocumentsDirectory(), boot.appname, date, ext)
     rt = trinity.device.GetRenderContext().GetDefaultBackBuffer()
     if not rt.isReadable:
         readable = trinity.Tr2RenderTarget(rt.width, rt.height, 1,
                                            rt.format)
         rt.Resolve(readable)
         bmp = trinity.Tr2HostBitmap(readable)
     else:
         bmp = trinity.Tr2HostBitmap(rt)
     if bmp.format == trinity.PIXEL_FORMAT.B8G8R8A8_UNORM:
         bmp.ChangeFormat(trinity.PIXEL_FORMAT.B8G8R8X8_UNORM)
     bmp.Save(path)
     return True
示例#2
0
文件: uilib.py 项目: R4M80MrX/eve-1
 def SetCursor(self, cursorIx):
     if self.exclusiveMouseFocusActive:
         return
     cursorName = 'res:/UI/Cursor/cursor{0:02}.dds'.format(cursorIx)
     cursor = self.cursorCache.get(cursorName, None)
     if cursor is None:
         bmp = trinity.Tr2HostBitmap()
         bmp.CreateFromFile(cursorName)
         cursor = trinity.Tr2MouseCursor(bmp, 16, 15)
         self.cursorCache[cursorName] = cursor
     self.SetCursorProperties(cursor)
示例#3
0
 def SetCursor(self, cursorIx):
     if self.exclusiveMouseFocusActive:
         return
     cursorResPath = 'res:/UI/Cursor/cursor{0:02}_{platform}.dds'.format(
         cursorIx, platform=trinity.platform)
     if not blue.paths.exists(cursorResPath):
         cursorResPath = 'res:/UI/Cursor/cursor{0:02}.dds'.format(cursorIx)
     cursor = self.cursorCache.get(cursorResPath, None)
     if cursor is None:
         bmp = trinity.Tr2HostBitmap()
         bmp.CreateFromFile(cursorResPath)
         cursor = trinity.Tr2MouseCursor(bmp, 16, 15)
         self.cursorCache[cursorResPath] = cursor
     self.SetCursorProperties(cursor)
示例#4
0
 def ShowSH(self, sh, scaleIt=True):
     if scaleIt:
         builder.ScaleSH(sh, 1.0 / const.planetResourceMaxValue)
     chart = self.ChartResourceLayer(sh)
     buf = chart.makeChart2(chart.PNG)
     bmp = trinity.Tr2HostBitmap(PLANET_RESOURCE_TEX_WIDTH,
                                 PLANET_RESOURCE_TEX_HEIGHT, 1,
                                 trinity.TRIFMT_X8R8G8B8)
     bmp.LoadFromPngInMemory(buf)
     texture = trinity.TriTextureRes()
     texture.CreateFromHostBitmap(bmp)
     if self.planetTransform is not None:
         self.EnableResourceLayer()
         self.SetResourceTexture(texture)
示例#5
0
 def SaveScreenShot(self, outputPath, rgb = False):
     if rgb:
         clearColors = (('R', (1.0, 0.0, 0.0, 0.0)), ('G', (0.0, 1.0, 0.0, 0.0)), ('B', (0.0, 0.0, 1.0, 0.0)))
     else:
         clearColors = ((None, None),)
     print 'SaveScreenShot', outputPath
     for channel, color in clearColors:
         if color:
             self.renderJob.SetClearColor(color)
         blue.synchro.Yield()
         backBuffer = trinity.device.GetRenderContext().GetDefaultBackBuffer()
         if not backBuffer.isReadable:
             tempRT = trinity.Tr2RenderTarget(backBuffer.width, backBuffer.height, 1, backBuffer.format)
             backBuffer.Resolve(tempRT)
             bmp = trinity.Tr2HostBitmap(tempRT)
         else:
             bmp = trinity.Tr2HostBitmap(backBuffer)
         if bmp.format == trinity.PIXEL_FORMAT.B8G8R8A8_UNORM:
             bmp.ChangeFormat(trinity.PIXEL_FORMAT.B8G8R8X8_UNORM)
         if rgb:
             bmp.Save(outputPath[:-4] + '_' + channel + outputPath[-4:])
         else:
             bmp.Save(outputPath)
示例#6
0
 def GetPortraitTexture(self, portraitID):
     size = 512
     sceneManager = sm.GetService('sceneManager')
     scene = sceneManager.GetActiveScene()
     backdropPath = self.backdropPath
     if backdropPath:
         backdropScene = trinity.Tr2Sprite2dScene()
         backdropScene.displayWidth = size
         backdropScene.displayHeight = size
         sprite = trinity.Tr2Sprite2d()
         sprite.texturePrimary = trinity.Tr2Sprite2dTexture()
         sprite.texturePrimary.resPath = backdropPath
         sprite.displayWidth = size
         sprite.displayHeight = size
         backdropScene.children.append(sprite)
     target = trinity.Tr2RenderTarget(size, size, 1,
                                      trinity.PIXEL_FORMAT.B8G8R8X8_UNORM)
     depth = trinity.Tr2DepthStencil(size, size,
                                     trinity.DEPTH_STENCIL_FORMAT.AUTO)
     renderJob = trinity.CreateRenderJob('TakeSnapShot')
     renderJob.PushRenderTarget(target)
     renderJob.PushDepthStencil(depth)
     projection = trinity.TriProjection()
     projection.PerspectiveFov(self.camera.fieldOfView, 1, 0.1, 5.0)
     view = self.camera.viewMatrix
     renderJob.Clear((0.0, 0.0, 0.0, 1.0), 1.0)
     renderJob.SetProjection(projection)
     renderJob.SetView(view)
     if backdropPath:
         renderJob.Update(backdropScene)
         renderJob.RenderScene(backdropScene)
     renderJob.RenderScene(scene)
     trinity.WaitForResourceLoads()
     renderJob.PopDepthStencil()
     renderJob.PopRenderTarget()
     renderJob.ScheduleOnce()
     renderJob.WaitForFinish()
     filename = self.GetPortraitSnapshotPath(portraitID)
     trinity.Tr2HostBitmap(target).Save(filename)
     path = 'cache:/Pictures/Portraits/PortraitSnapshot_%s_%s.jpg' % (
         portraitID, session.userid)
     blue.motherLode.Delete(path)
     tex = blue.resMan.GetResource(path, 'atlas')
     return tex
示例#7
0
                    def TransferArrayToTexture(cut, mat1, mat2, spec):
                        pixels = []

                        def GetFromArray(array, index, component=0, default=0):
                            if array is None or not hasattr(
                                    array,
                                    'value') or index >= len(array.value):
                                return default
                            v = array.value[index]
                            if type(v) == trinity.TriVector4:
                                return v.data[component]
                            return v

                        OPT_CUTOUT = 8
                        OPT_DOUBLE_MATERIAL = 16
                        for x in xrange(32):
                            infoList = collapsedMeshes.get(mesh, [])
                            infoTuple = infoList[x] if x < len(infoList) else (
                                0, 0, 0, 0)
                            permute = infoTuple[3]
                            table = paperDollPrePassFixup.MATERIAL_ID_TRANSPARENT_HACK_EXACT if infoTuple[
                                1] == 2 else paperDollPrePassFixup.MATERIAL_ID_EXACT
                            r = int(0.5 + 100 * GetFromArray(cut, x))
                            if permute & OPT_CUTOUT:
                                r += 128
                            g = int(GetFromArray(mat1, x))
                            if permute & OPT_DOUBLE_MATERIAL:
                                b = int(GetFromArray(mat2, x))
                            else:
                                b = g
                            a = int(0.5 +
                                    50 * GetFromArray(spec, x, component=2))
                            pixels.append(
                                (x, 0, (a << 24) + (r << 16) + (g << 8) + b))

                        hb = trinity.Tr2HostBitmap(
                            32, 1, 1, trinity.PIXEL_FORMAT.B8G8R8A8_UNORM)
                        hb.SetPixels(0, pixels, 0)
                        lookup = trinity.TriTextureRes()
                        lookup.CreateFromHostBitmap(hb)
                        texParam = trinity.TriTexture2DParameter()
                        texParam.name = 'CollapsedMeshArrayLookup'
                        texParam.SetResource(lookup)
                        return texParam
示例#8
0
def CreateRandomTexture(options):
    randomBitmap = trinity.Tr2HostBitmap(
        options.randomTextureWidth, options.randomTextureWidth, 1,
        trinity.PIXEL_FORMAT.R32G32B32A32_FLOAT)
    data = randomBitmap.GetRawData()
    values = []
    dataFormat = ''
    for i in range(options.randomTextureWidth * options.randomTextureWidth):
        angle = 2.0 * math.pi * random.random() / options.numDirections
        values.append(math.sin(angle))
        values.append(math.cos(angle))
        values.append(random.random())
        values.append(random.random())
        dataFormat += 'ffff'

    struct.pack_into(dataFormat, data[0], 0, *values)
    randomTexture = trinity.TriTextureRes()
    randomTexture.CreateFromHostBitmap(randomBitmap)
    return randomTexture
示例#9
0
 def GetResourceAndRender(self, resourceTypeID):
     self.LogInfo('GetResourceAndRender resourceTypeID', resourceTypeID)
     planet = sm.GetService('planetSvc').GetPlanet(self.planetID)
     inRange, sh = planet.GetResourceData(resourceTypeID)
     self.currSphericalHarmonic = sh
     sh = builder.CopySH(sh)
     builder.ScaleSH(sh, 1.0 / const.planetResourceMaxValue)
     chart = self.ChartResourceLayer(sh)
     buf = chart.makeChart2(chart.PNG)
     if resourceTypeID != self.selectedResourceTypeID:
         raise ResourceRenderAbortedError
     bmp = trinity.Tr2HostBitmap(PLANET_RESOURCE_TEX_WIDTH,
                                 PLANET_RESOURCE_TEX_HEIGHT, 1,
                                 trinity.PIXEL_FORMAT.B8G8R8X8_UNORM)
     bmp.LoadFromPngInMemory(buf)
     texture = trinity.TriTextureRes()
     if resourceTypeID != self.selectedResourceTypeID:
         raise ResourceRenderAbortedError
     texture.CreateFromHostBitmap(bmp)
     if resourceTypeID != self.selectedResourceTypeID:
         raise ResourceRenderAbortedError
     return (inRange, texture)
示例#10
0
def RenderToSurface(view,
                    projection,
                    size=128,
                    scene=None,
                    bgColor=None,
                    transparent=False,
                    backgroundPath=None,
                    overlayPath=None,
                    techPath=None,
                    iconPath=None,
                    postProcessingQuality=2,
                    supersampleQuality=1):
    size *= 2**supersampleQuality
    renderJob = CreateRenderJob(size, view, projection, bgColor, transparent,
                                postProcessingQuality, supersampleQuality)
    if scene:
        renderJob.SetScene(scene)
    else:
        renderJob.SetScene(trinity.EveSpaceScene())
    if backgroundPath:
        if scene:
            scene.backgroundRenderingEnabled = False
        renderJob.backgroundTexture.resPath = backgroundPath
    if iconPath:
        renderJob.iconTexture.resPath = iconPath
    if overlayPath:
        renderJob.overlayTexture.resPath = overlayPath
    if techPath:
        renderJob.techTexture.resPath = techPath
    blue.resMan.Wait()
    renderJob.DoPrepareResources()
    renderJob.ScheduleOnce()
    renderJob.WaitForFinish()
    hostBitmap = trinity.Tr2HostBitmap(renderJob.renderTarget)
    for _ in range(supersampleQuality):
        hostBitmap.Downsample2x2()

    return hostBitmap
示例#11
0
def RenderToSurface(view,
                    projection,
                    size=128,
                    scene=None,
                    bgColor=None,
                    transparent=False,
                    backgroundPath=None,
                    overlayPath=None,
                    techPath=None,
                    iconPath=None,
                    postProcessingQuality=2,
                    antiAliasingQuality=3):
    """
    Renders a scene and sprites to a surface.
    """
    renderJob = CreateRenderJob(size, view, projection, bgColor, transparent,
                                postProcessingQuality, antiAliasingQuality)
    if scene:
        renderJob.SetScene(scene)
    else:
        renderJob.SetScene(trinity.EveSpaceScene())
    if backgroundPath:
        if scene:
            scene.backgroundRenderingEnabled = False
        renderJob.backgroundTexture.resPath = backgroundPath
    if iconPath:
        renderJob.iconTexture.resPath = iconPath
    if overlayPath:
        renderJob.overlayTexture.resPath = overlayPath
    if techPath:
        renderJob.techTexture.resPath = techPath
    blue.resMan.Wait()
    renderJob.DoPrepareResources()
    renderJob.ScheduleOnce()
    renderJob.WaitForFinish()
    hostBitmap = trinity.Tr2HostBitmap(renderJob.renderTarget)
    return hostBitmap
示例#12
0
 def CreateGraph(self, data, parent):
     l = [(k, v) for k, v in data.iteritems()]
     l.sort(key=lambda x: x[0])
     yData = [x[1] for x in l]
     xData = ['%.1fs' % (x[0] / 1000.0) for x in l]
     fontSize = 7.5
     fontFace = 'arial.ttc'
     width = parent.width
     height = int(parent.height * 0.4)
     c = chart.XYChart(width, height, bgColor=chart.Transparent)
     c.addTitle('Frametime in ms')
     c.setColors(chart.whiteOnBlackPalette)
     c.setBackground(chart.Transparent)
     c.setTransparentColor(-1)
     c.setAntiAlias(1, 1)
     offsX = 60
     offsY = 17
     canvasWidth = width - 1 * offsX - 50
     canvasHeight = height - offsY * 2.5
     c.setPlotArea(offsX, offsY, canvasWidth, canvasHeight, 1711276032, -1,
                   -1, 5592405)
     c.addLegend(85, 18, 0, fontFace,
                 fontSize).setBackground(chart.Transparent)
     c.addLineLayer(yData)
     c.yAxis().setTitle('ms')
     c.xAxis().setLabels(xData)
     c.xAxis().setLabelStep(len(data) / 5)
     buf = c.makeChart2(chart.PNG)
     hostBitmap = trinity.Tr2HostBitmap(width, height, 1,
                                        trinity.PIXEL_FORMAT.B8G8R8A8_UNORM)
     hostBitmap.LoadFromPngInMemory(buf)
     graphSprite = Sprite(parent=parent, align=uiconst.TOALL)
     graphSprite.texture.atlasTexture = uicore.uilib.CreateTexture(
         width, height)
     graphSprite.texture.atlasTexture.CopyFromHostBitmap(hostBitmap)
     return graphSprite
示例#13
0
 def SaveTarget(target, path, isRT = False):
     if type(target) == trinity.Tr2RenderTarget:
         trinity.Tr2HostBitmap(target).Save(path)
     else:
         target.Save(path)
示例#14
0
    def Finalize(self, format, w, h, generateMipmap = False, textureToCopyTo = None, compressionSettings = None, mapType = None):
        isPC = not blue.sysinfo.isTransgaming
        doCompression = compressionSettings is not None and compressionSettings.compressTextures and compressionSettings.AllowCompress(mapType) and isPC
        if doCompression:
            textureToCopyTo = None
        if not self.isReady:
            raise AttributeError('isReady must be true when Finalize() is called.')
        newParams = []
        lastFx = None
        for r in iter(self.texturesWithCutouts):
            cutout = [r[0].cutoutX,
             r[0].cutoutY,
             r[0].cutoutWidth,
             r[0].cutoutHeight]
            if r[4]:
                cutout = r[4]
            if lastFx is not None and r[1] != lastFx:
                lastFx.StartUpdate()
                lastFx.parameters.extend(newParams)
                lastFx.EndUpdate()
                newParams = []
            lastFx = r[1]
            newParams.append(self.CreateParameter(trinity.Tr2Vector4Parameter(), r[2], cutout))

        if lastFx is not None:
            lastFx.StartUpdate()
            lastFx.parameters.extend(newParams)
            lastFx.EndUpdate()

        def FindOrAddFloat(effect, name):
            for r in effect.parameters:
                if r.name == name:
                    return r

            p = trinity.Tr2FloatParameter()
            p.name = name
            effect.parameters.append(p)
            return p

        for step in iter(self.renderJob.steps):
            if type(step) == trinity.TriStepRenderEffect:
                for res in step.effect.resources:
                    mapFormat = res.resource.format
                    if mapFormat == trinity.PIXEL_FORMAT.R8_UNORM:
                        v = FindOrAddFloat(step.effect, res.name.lower() + '_L8')
                        v.value = 1.0
                    elif mapFormat == trinity.PIXEL_FORMAT.R8G8_UNORM:
                        v = FindOrAddFloat(step.effect, res.name.lower() + '_L8A8')
                        v.value = 1.0
                    r = self.texturesByResourceID.get(id(res.resource))
                    if r:
                        mapName = r[3]
                        if mapName == 'N' and mapFormat == trinity.PIXEL_FORMAT.R8G8_UNORM:
                            v = FindOrAddFloat(step.effect, res.name.lower() + '_blitAsNormal')
                            v.value = 1.0

        self.renderJob.PopDepthStencil()
        self.renderJob.PopRenderTarget()
        self.renderJob.GenerateMipMaps(self.renderTarget)
        if textureToCopyTo is not None:
            self.renderJob.CopyRenderTarget(textureToCopyTo, self.renderTarget)
        self.renderJob.ScheduleChained()
        try:
            self.renderJob.WaitForFinish()
        except Exception:
            self.renderJob.CancelChained()
            raise

        self.texturesWithCutouts = []
        self.texturesByResourceID.clear()
        self.isDone = True
        if self.renderJob.status != trinity.RJ_DONE:
            return
        if not doCompression:
            if textureToCopyTo is not None:
                return textureToCopyTo
            tex = trinity.TriTextureRes()
            tex.CreateAndCopyFromRenderTarget(self.renderTarget)
            return tex
        hostBitmap = trinity.Tr2HostBitmap(self.renderTarget)
        tex = trinity.TriTextureRes()
        compressionFormat = COMPRESS_DXT5n if mapType is NORMAL_MAP else COMPRESS_DXT5
        hostBitmap.Compress(compressionFormat, compressionSettings.qualityLevel, tex)
        while not tex.isPrepared:
            blue.synchro.Yield()

        return tex
示例#15
0
 def PreloadZoneMaps(self, doll):
     textureRoot = 'R:/'
     textureSuffix = '.tga'
     if not legacy_r_drive.loadFromContent:
         textureRoot = 'res:/'
         textureSuffix = '.png'
     self.zoneMaps = {}
     self.highlightMaps = {}
     for each in ('hair', 'makeup', 'bodyselect', 'animation', 'default'):
         zonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/SculptZones' + textureSuffix
         headGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/male_head_fx' + textureSuffix
         bodyGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/male_body_fx' + textureSuffix
         if doll.gender == 'female':
             headGridPath = headGridPath.replace('male_', 'female_')
             bodyGridPath = bodyGridPath.replace('male_', 'female_')
         if headGridPath not in self.highlightMaps:
             self.highlightMaps[headGridPath] = blue.resMan.GetResource(headGridPath)
         if bodyGridPath not in self.highlightMaps:
             self.highlightMaps[bodyGridPath] = blue.resMan.GetResource(bodyGridPath)
         bodyZonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/BodySculptZones' + textureSuffix
         headTiling = 1
         bodyTiling = 1
         if each == 'hair':
             zonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/HairZones' + textureSuffix
             bodyZonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/EmptyZone' + textureSuffix
             headGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/SelectGrid' + textureSuffix
             bodyGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/SelectGrid' + textureSuffix
             headTiling = 40
             bodyTiling = 40
         elif each == 'makeup':
             zonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/MakeupZones' + textureSuffix
             bodyZonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/EmptyZone' + textureSuffix
             headGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/SelectGrid' + textureSuffix
             bodyGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/SelectGrid' + textureSuffix
             headTiling = 40
             bodyTiling = 40
         elif each == 'bodyselect':
             zonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/EmptyZone' + textureSuffix
             bodyZonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/BodySelectZones' + textureSuffix
             headGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/SelectGrid' + textureSuffix
             bodyGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/SelectGrid' + textureSuffix
             headTiling = 40
             bodyTiling = 40
         elif each == 'animation':
             zonePath = textureRoot + 'Graphics/Character/Global/FaceSetup/AnimZones' + textureSuffix
             headGridPath = textureRoot + 'Graphics/Character/Global/FaceSetup/male_head_Profile_fx' + textureSuffix
             if doll.gender == 'female':
                 headGridPath = headGridPath.replace('male_', 'female_')
             headTiling = 1
         zoneMap = trinity.Tr2HostBitmap()
         zoneMap.CreateFromFile(zonePath)
         bodyZoneMap = trinity.Tr2HostBitmap()
         bodyZoneMap.CreateFromFile(bodyZonePath)
         zoneSize = (0, 0)
         bodyZoneSize = (0, 0)
         self.zoneMaps[each] = (zonePath,
          headGridPath,
          bodyGridPath,
          headTiling,
          bodyTiling,
          bodyZonePath,
          zoneMap,
          zoneSize,
          bodyZoneMap,
          bodyZoneSize)
示例#16
0
def CreateAlpha(outPath, sourcePaths, backgroundPath=None):
    rBmp = trinity.Tr2HostBitmap()
    rBmp.CreateFromFile(sourcePaths[0])
    gBmp = trinity.Tr2HostBitmap()
    gBmp.CreateFromFile(sourcePaths[1])
    bBmp = trinity.Tr2HostBitmap()
    bBmp.CreateFromFile(sourcePaths[2])
    outputBmp = trinity.Tr2HostBitmap(rBmp.width, rBmp.height, 1,
                                      trinity.PIXEL_FORMAT.B8G8R8A8_UNORM)
    rTriCol = trinity.TriColor()
    gTriCol = trinity.TriColor()
    bTriCol = trinity.TriColor()
    BLACKALPHA0 = 0
    HUERANGE = 60
    REDHUE = 0
    GREENHUE = 120
    BLUEHUE = 240
    addBackground = not backgroundPath == None
    if addBackground:
        myBg = trinity.Tr2HostBitmap()
        myBg.CreateFromFile(backgroundPath)
        bgTriCol = trinity.TriColor()
    for px in range(rBmp.width):
        for py in range(rBmp.height):
            if addBackground:
                bgPixelValue = myBg.GetPixel(px, py)
                bgTriCol.FromInt(bgPixelValue)
            rPixelValue = rBmp.GetPixel(px, py)
            gPixelValue = gBmp.GetPixel(px, py)
            bPixelValue = bBmp.GetPixel(px, py)
            rTriCol.FromInt(rPixelValue)
            gTriCol.FromInt(gPixelValue)
            bTriCol.FromInt(bPixelValue)
            rh, rs, rv = rTriCol.GetHSV()
            gh, gs, gv = gTriCol.GetHSV()
            bh, bs, bv = bTriCol.GetHSV()
            if (rTriCol.r, rTriCol.g, rTriCol.b) == (1.0, 0.0, 0.0) and (
                    gTriCol.r, gTriCol.g, gTriCol.b) == (0.0, 1.0, 0.0) and (
                        bTriCol.r, bTriCol.g, bTriCol.b) == (0.0, 0.0, 1.0):
                if addBackground:
                    outputBmp.SetPixel(px, py, bgTriCol.AsInt())
                else:
                    outputBmp.SetPixel(px, py, BLACKALPHA0)
            elif GREENHUE - HUERANGE < gh < GREENHUE + HUERANGE and (
                    360 - HUERANGE < rh <= 360 or REDHUE <= rh < REDHUE +
                    HUERANGE) and BLUEHUE - HUERANGE < bh < BLUEHUE + HUERANGE:
                if gv == 1.0 and bv == 1.0 and rv == 1.0:
                    gTriCol.SetRGB(gTriCol.r, rTriCol.g, gTriCol.b, 1.0)
                    ch, cs, cv = gTriCol.GetHSV()
                    gTriCol.a = cv
                    gTriCol.r = min(1.0, gTriCol.r * 1.0 / cv)
                    gTriCol.g = min(1.0, gTriCol.g * 1.0 / cv)
                    gTriCol.b = min(1.0, gTriCol.b * 1.0 / cv)
                    outputBmp.SetPixel(px, py, gTriCol.AsInt())
                elif addBackground:
                    alpha = 1.0 - gv
                    invAlpha = 1 - alpha
                    redColor = gTriCol.r * alpha + bgTriCol.r * invAlpha
                    greenColor = rTriCol.g * alpha + bgTriCol.g * invAlpha
                    blueColor = gTriCol.b * alpha + bgTriCol.b * invAlpha
                    newAlpha = gTriCol.a * alpha + bgTriCol.a * invAlpha
                    gTriCol.SetRGB(redColor, greenColor, blueColor, newAlpha)
                else:
                    gTriCol.SetRGB(gTriCol.r, rTriCol.g, gTriCol.b, 1.0 - gv)
                    outputBmp.SetPixel(px, py, gTriCol.AsInt())
            else:
                gTriCol.a = 1.0
                outputBmp.SetPixel(px, py, gTriCol.AsInt())

    outputBmp.Save(outPath)
示例#17
0
    def GetTextureFromURL(self,
                          path,
                          currentURL=None,
                          ignoreCache=0,
                          dontcache=0,
                          fromWhere=None,
                          sizeonly=0,
                          retry=1):
        if path.endswith('.blue'):
            return self.GetPic_blue(path)
        fullPath = corebrowserutil.ParseURL(path, currentURL)[0]
        if path.startswith('res:'):
            try:
                surface = trinity.Tr2HostBitmap()
                surface.CreateFromFile(path)
                w, h = surface.width, surface.height
                bw, bh = uiutil.GetBuffersize(w), uiutil.GetBuffersize(h)
                if sizeonly:
                    return (path, w, h, bw, bh)
                return self.ReturnTexture(path, w, h, bw, bh)
            except:
                self.LogError('Failed to load image', path)
                if self.urlloading.has_key(fullPath):
                    del self.urlloading[fullPath]
                sys.exc_clear()
                return self.ErrorPic(sizeonly)

        if ignoreCache:
            sm.GetService('browserCache').InvalidateImage(fullPath)
        while self.urlloading.has_key(fullPath):
            blue.pyos.BeNice()

        if not dontcache:
            cacheData = sm.GetService('browserCache').GetFromCache(fullPath)
            if cacheData and os.path.exists(cacheData[0].replace(
                    'cache:/', blue.paths.ResolvePath(u'cache:/'))):
                if sizeonly:
                    return cacheData
                return self.ReturnTexture(*cacheData)
        try:
            self.urlloading[fullPath] = 1
            ret = corebrowserutil.GetStringFromURL(fullPath)
            cacheID = int(
                str(blue.os.GetWallclockTime()) +
                str(uthread.uniqueId() or uthread.uniqueId()))
            imagestream = ret.read()
            ext = None
            if 'content-type' in ret.headers.keys(
            ) and ret.headers['content-type'].startswith('image/'):
                ext = ret.headers['content-type'][6:]
            if ext == None or ext == 'png':
                header = imagestream[:16]
                for sig, sext in [('PNG', 'PNG'), ('GIF', 'GIF'),
                                  ('JFI', 'JPEG'), ('BM8', 'BMP')]:
                    for i in xrange(0, 12):
                        if header[i:i + 3] == sig:
                            ext = sext
                            break

                if not ext:
                    header = imagestream[-16:]
                    for sig, sext in [('XFILE', 'TGA')]:
                        for i in xrange(0, 10):
                            if header[i:i + 5] == sig:
                                ext = sext
                                break

            if ext:
                filename = '%sBrowser/Img/%s.%s' % (
                    blue.paths.ResolvePath(u'cache:/'), cacheID, ext)
                resfile = blue.classes.CreateInstance('blue.ResFile')
                if not resfile.Open(filename, 0):
                    resfile.Create(filename)
                resfile.Write(imagestream)
                resfile.Close()
                if ext.upper() == 'GIF':
                    g = DrawArea()
                    g.setBgColor(Transparent)
                    g.loadGIF(filename.replace(u'/', u'\\').encode('utf8'))
                    ext = 'PNG'
                    filename = u'%sBrowser/Img/%s.%s' % (
                        blue.paths.ResolvePath(u'cache:/'), cacheID, ext)
                    g.outPNG(filename.replace(u'/', u'\\').encode('utf8'))
                surface = trinity.Tr2HostBitmap()
                surface.CreateFromFile(filename)
                w, h = surface.width, surface.height
                bw, bh = uiutil.GetBuffersize(w), uiutil.GetBuffersize(h)
                cachePath = 'cache:/Browser/Img/%s.%s' % (cacheID, ext)
                if 'pragma' not in ret.headers.keys(
                ) or ret.headers['Pragma'].find('no-cache') == -1:
                    sm.GetService('browserCache').Cache(
                        fullPath, (cachePath, w, h, bw, bh))
                del self.urlloading[fullPath]
                if sizeonly:
                    return (cachePath, w, h, bw, bh)
                return self.ReturnTexture(cachePath, w, h, bw, bh)
            del self.urlloading[fullPath]
            return self.ErrorPic(sizeonly)
        except Exception as e:
            if retry:
                sys.exc_clear()
                if self.urlloading.has_key(fullPath):
                    del self.urlloading[fullPath]
                return self.GetTextureFromURL(path, currentURL, ignoreCache,
                                              dontcache, fromWhere, sizeonly,
                                              0)
            self.LogError(e, 'Failed to load image', repr(path))
            if self.urlloading.has_key(fullPath):
                del self.urlloading[fullPath]
            sys.exc_clear()
            return self.ErrorPic(sizeonly)
示例#18
0
    def RenderType(self,
                   typeID,
                   folder='testing',
                   save=1,
                   iconsize=64,
                   recursive=0):
        folder = folder.replace(' ', '')
        dev = trinity.device
        triapp = trinity.app
        root = blue.win32.SHGetFolderPath(
            blue.win32.CSIDL_PERSONAL) + '/EVE/capture/Screenshots'
        filePath = blue.win32.SHGetFolderPath(
            blue.win32.CSIDL_PERSONAL) + '/EVE/capture/Screenshots/Renders/'
        dr = DirectoryRoutines()
        dr.GenericCheckCreateDirectory(filePath)
        typeinfo = cfg.invtypes.Get(typeID)
        group = typeinfo.Group()
        categoryID = group.categoryID
        if not typeinfo.GraphicFile():
            return
        fullpath = ''
        path_current = 'cache:/Pictures/Gids/' + sm.GetService(
            'photo').GetPictureFileName(typeinfo, iconsize)
        fullpath_current = sm.GetService('photo').CheckAvail(path_current)
        if fullpath_current:
            fullpath = path_current
        targetFile = filePath + '%s.%s' % (typeID, self.exportExtension)
        if os.path.isfile(targetFile):
            print 'render for typeID %d already exists' % typeID
            return
        file = blue.ResFile()
        if not file.Open(fullpath):
            if categoryID == const.categoryPlanetaryInteraction:
                if group.id not in (const.groupPlanetaryLinks, ):
                    sm.GetService('photo').GetPinPhoto(typeID,
                                                       typeinfo=typeinfo,
                                                       size=iconsize)
                else:
                    return
            elif categoryID == const.categoryModule and group.groupID in const.turretModuleGroups:
                sm.GetService('photo').GetTurretPhoto(
                    typeID,
                    typeinfo,
                    size=iconsize,
                    transparentBackground=False,
                    usePreviewScene=True)
            else:
                sm.GetService('photo').GetPhoto(typeID,
                                                typeinfo,
                                                size=iconsize)
            if not recursive:
                del file
                self.RenderType(typeID,
                                folder=folder.split('_')[0],
                                save=save,
                                iconsize=iconsize,
                                recursive=1)
                return
        if file:
            del file
        bmp = trinity.Tr2HostBitmap()
        try:
            bmp.CreateFromFile(fullpath)
        except:
            print 'failed Rendering typeID: %s, size: %s %s' % (
                typeID, iconsize, fullpath)

        bmp.Save(targetFile)
示例#19
0
def TakeScreenshot(filename, tilesAcross):
    successful = False
    performanceOverlayRJ = 0
    camera = TrinityPanelWrapper.GetCamera()
    dev = trinity.device
    fov = camera.fieldOfView
    aspect = camera.aspectRatio
    zNear = camera.frontClip
    zFar = camera.backClip
    height = 2.0 * zNear * math.tan(fov / 2.0)
    width = height * aspect
    disabledJobsStates = {}
    sceneRenderJobs = []
    for rj in trinity.renderJobs.recurring:
        legalRenderJob = False
        if issubclass(rj, trinity.sceneRenderJobBase.SceneRenderJobBase):
            sceneRenderJobs.append(rj)
        else:
            disabledJobsStates[rj] = rj.enabled
            rj.enabled = False

    BackupAllProjectionsAndViewports(sceneRenderJobs)
    flarePreviousState = FreezeInteriorFlares()
    try:
        if filename == None or filename == '':
            raise ValueError('No filename given')
        if not tilesAcross or tilesAcross == 0:
            raise ValueError('tilesAcross must be greater than 0')
        tilesAcross = int(tilesAcross)
        heightSlice = height / tilesAcross
        widthSlice = width / tilesAcross
        backBuffer = TrinityPanelWrapper.GetBackBuffer()
        tileWidth = backBuffer.width
        tileHeight = backBuffer.height
        twd4 = math.floor(tileWidth / 4)
        thd4 = math.floor(tileHeight / 4)
        diffW = tileWidth - twd4 * 4
        diffH = tileHeight - thd4 * 4
        if not backBuffer.isReadable:
            tempRT = trinity.Tr2RenderTarget(tileWidth, tileHeight, 1, backBuffer.format, 1, 0)
        screenShot = trinity.Tr2HostBitmap(tileWidth * tilesAcross, tileHeight * tilesAcross, 1, backBuffer.format)
        info = wx.BusyInfo('Hold on, generating snazzy snapshot ...')
        tileOffset = trinity.TriPoint()
        halfAcross = tilesAcross / 2.0
        for x in range(tilesAcross):
            left = (x - halfAcross) * widthSlice
            right = left + widthSlice
            tileOffset.x = x * tileWidth
            for y in range(tilesAcross):
                top = (halfAcross - y) * heightSlice
                bottom = top - heightSlice
                tileOffset.y = y * tileHeight
                for x_off in [(-widthSlice / 4, -twd4, 0), (widthSlice / 4, twd4, diffW)]:
                    for y_off in [(heightSlice / 4, -thd4, 0), (-heightSlice / 4, thd4, diffH)]:
                        newProj = trinity.TriProjection()
                        newProj.PerspectiveOffCenter(left + x_off[0], right + x_off[0], bottom + y_off[0], top + y_off[0], zNear, zFar)
                        newViewport = trinity.TriViewport()
                        newViewport.x = 0
                        newViewport.y = 0
                        newViewport.width = tileWidth
                        newViewport.height = tileHeight
                        newViewport.minZ = 0.0
                        newViewport.maxZ = 1.0
                        OverrideAllProjectionsAndViewports(sceneRenderJobs, newProj, newViewport)
                        OverrideInteriorFlareViewports(flarePreviousState, int(x_off[1] + tileOffset.x), int(y_off[1] + tileOffset.y), tileWidth * tilesAcross, tileHeight * tilesAcross)
                        dev.Render()
                        dev.Render()
                        offset = trinity.TriPoint(int(x_off[1] + tileOffset.x), int(y_off[1] + tileOffset.y))
                        rect = trinity.TriRect(int(twd4), int(thd4), int(3 * twd4 + x_off[2]), int(3 * thd4 + y_off[2]))
                        if not backBuffer.isReadable:
                            backBuffer.Resolve(tempRT)
                            screenShot.CopyFromRenderTargetRegion(tempRT, rect.left, rect.top, rect.right, rect.bottom, offset.x, offset.y)
                        else:
                            screenShot.CopyFromRenderTargetRegion(backBuffer, rect.left, rect.top, rect.right, rect.bottom, offset.x, offset.y)

            RestoreAllProjectionsAndViewports()

        baseDir = os.path.dirname(filename)
        if not os.path.exists(baseDir):
            os.makedirs(baseDir)
        screenShot.Save(filename)
        del info
        successful = True
    except Exception:
        import traceback
        traceback.print_exc()

    RestoreInteriorFlares(flarePreviousState)
    for rj, state in disabledJobsStates.iteritems():
        rj.enabled = state

    return successful
示例#20
0
    def RenderStaticEnvironment(self):
        alphaFill = trinity.Tr2Effect()
        alphaFill.effectFilePath = 'res:/Graphics/Effect/Utility/Compositing/AlphaFill.fx'
        trinity.WaitForResourceLoads()
        if self.staticEnvResource is None:
            self.staticEnvResource = StaticEnvironmentResource(self)
        dev = trinity.device
        self.hangarScene.display = True
        self.hangarScene.update = True
        depthTexture = self.hangarScene.depthTexture
        distortionTexture = self.hangarScene.distortionTexture
        self.hangarScene.depthTexture = None
        self.hangarScene.distortionTexture = None
        clientWidth = trinity.device.width
        clientHeight = trinity.device.height
        renderTarget = trinity.Tr2RenderTarget(
            clientWidth, clientHeight, 1, trinity.PIXEL_FORMAT.B8G8R8A8_UNORM)
        depthStencil = trinity.Tr2DepthStencil(
            clientWidth, clientHeight, trinity.DEPTH_STENCIL_FORMAT.AUTO)
        self.SetupCamera()
        camera = self.sceneManager.GetRegisteredCamera(self.name)
        camera.idleMove = False
        updateJob = trinity.CreateRenderJob('UpdateScene')
        updateJob.SetView(None)
        updateJob.Update(self.hangarScene)
        while updateJob.status != trinity.RJ_DONE:
            updateJob.ScheduleOnce()
            updateJob.WaitForFinish()

        view = trinity.TriView()
        view.SetLookAtPosition(camera.pos, camera.intr, (0.0, 1.0, 0.0))
        projection = trinity.TriProjection()
        fov = camera.fieldOfView
        aspectRatio = float(clientWidth) / clientHeight
        projection.PerspectiveFov(fov, aspectRatio, 1.0, 350000.0)
        renderJob = trinity.CreateRenderJob('StaticScene')
        renderJob.PushRenderTarget(renderTarget)
        renderJob.SetProjection(projection)
        renderJob.SetView(view)
        renderJob.PushDepthStencil(depthStencil)
        renderJob.Clear((0.0, 0.0, 0.0, 0.0), 1.0)
        renderJob.RenderScene(self.hangarScene)
        renderJob.SetStdRndStates(trinity.RM_FULLSCREEN)
        renderJob.RenderEffect(alphaFill)
        renderJob.PopDepthStencil()
        renderJob.PopRenderTarget()
        while renderJob.status != trinity.RJ_DONE:
            renderJob.ScheduleOnce()
            renderJob.WaitForFinish()

        self.hangarScene.display = False
        self.hangarScene.update = False
        try:
            rgbSource = trinity.Tr2HostBitmap(renderTarget)
        except Exception:
            log.LogException()
            sys.exc_clear()
            return

        self.RemoveFullScreenSprite()
        self.sprite = uicls.Sprite(parent=uicore.uilib.desktop,
                                   width=uicore.uilib.desktop.width,
                                   height=uicore.uilib.desktop.height,
                                   left=0,
                                   top=0)
        self.sprite.name = 'fullScreenSprite'
        self.sprite.texture.atlasTexture = uicore.uilib.CreateTexture(
            rgbSource.width, rgbSource.height)
        self.sprite.texture.atlasTexture.CopyFromHostBitmap(rgbSource)
        self.hangarScene.display = False
        self.hangarScene.update = False
        self.hangarScene.depthTexture = depthTexture
        self.hangarScene.distortionTexture = distortionTexture
示例#21
0
    def GetGraph(self):
        isPerf = False
        if self.GetGraphType() == GRAPH_PERFORMANCE:
            isPerf = True
        fontSize = 7.5
        fontFace = 'arial.ttc'
        wnd = self.GetWnd()
        wnd.sr.graph.Flush()
        w, h = wnd.sr.graph.absoluteRight - wnd.sr.graph.absoluteLeft, wnd.sr.graph.absoluteBottom - wnd.sr.graph.absoluteTop
        minutes = settings.user.ui.Get('monitor_setting_memory_time', 60)
        trend = blue.pyos.cpuUsage[-minutes * 60 / 10:]
        memCounters = {}
        perfCounters = {}
        mega = 1.0 / 1024.0 / 1024.0
        timeData = []
        memData = []
        pymemData = []
        bluememData = []
        othermemData = []
        workingsetData = []
        ppsData = []
        fpsData = []
        threadCpuData = []
        procCpuData = []
        lastT = lastpf = 0
        t1 = 0
        if len(trend) > 1:
            t, cpu, mem, sched = trend[0]
            lastT = t
            lastpf = mem[-1]
            t1 = trend[0][0]
        benice = blue.pyos.BeNice
        for t, cpu, mem, sched in trend:
            benice()
            elap = t - t1
            t1 = t
            mem, pymem, workingset, pagefaults, bluemem = mem
            fps, nr_1, ny, ns, dur, nr_2 = sched
            fpsData.append(fps)
            memData.append(mem * mega)
            pymemData.append(pymem * mega)
            bluememData.append(bluemem * mega)
            othermem = (mem - bluemem) * mega
            if othermem < 0:
                othermem = 0
            othermemData.append(othermem)
            workingsetData.append(workingset * mega)
            thread_u, proc_u, kernel_u, process_kernel_u = cpu
            if elap:
                thread_cpupct = thread_u / float(elap) * 100.0
                proc_cpupct = proc_u / float(elap) * 100.0
            else:
                thread_cpupct = proc_cpupct = 0.0
            threadCpuData.append(thread_cpupct)
            procCpuData.append(proc_cpupct)
            dt = t - lastT
            lastT = t
            pf = pagefaults - lastpf
            lastpf = pagefaults
            pps = pf / (dt * 1e-07) if dt else 0
            ppsData.append(pps)
            year, month, wd, day, hour, minutes, sec, ms = util.GetTimeParts(t)
            timeData.append(
                chart.chartTime(year, month, day, hour, minutes, sec))

        if len(ppsData) > 1:
            ppsData[0] = ppsData[1]
        memCounters['blue_memory'] = (False, bluememData, 3377390, 1, False)
        memCounters['other_memory'] = (False, othermemData, 16776960, 1, False)
        memCounters['python_memory'] = (False, pymemData, 65280, 1, False)
        memCounters['total_memory'] = (False, memData, 16711680, 2, False)
        memCounters['working_set'] = (False, workingsetData, 65535, 1, False)
        memCounters['thread_cpu'] = (True, threadCpuData, 6749952, 1, True)
        memCounters['fps'] = (True, fpsData, 16711680, 1, False)
        width = w
        height = h
        c = chart.XYChart(width, height, bgColor=chart.Transparent)
        c.setColors(chart.whiteOnBlackPalette)
        c.setBackground(chart.Transparent)
        c.setTransparentColor(-1)
        c.setAntiAlias(1, 1)
        offsX = 60
        offsY = 17
        canvasWidth = width - 1 * offsX - 50
        canvasHeight = height - offsY * 2.5
        plotArea = c.setPlotArea(offsX, offsY, canvasWidth, canvasHeight,
                                 1711276032, -1, -1, 5592405)
        c.addLegend(85, 18, 0, fontFace,
                    fontSize).setBackground(chart.Transparent)
        if len(timeData) > 1:
            c.xAxis().setDateScale3('{value|hh:nn}')
        lines = c.addLineLayer()
        lines2 = c.addLineLayer2()
        lines2.setUseYAxis2()
        leftAxis = c.yAxis()
        rightAxis = c.yAxis2()
        if isPerf:
            leftAxis.setTitle('Frames per second')
            rightAxis.setTitle('CPU (%)')
        else:
            leftAxis.setTitle('Memory (MB)')
        for i, k in enumerate(memCounters.keys()):
            if settings.user.ui.Get('monitor_setting_%s' % k, 1):
                title = k.replace('_', ' ').capitalize()
                if isPerf == memCounters[k][0]:
                    data = memCounters[k][1]
                    col = memCounters[k][2]
                    lineWidth = memCounters[k][3]
                    if not memCounters[k][4]:
                        l = lines
                    else:
                        l = lines2
                    l.addDataSet(data, col, title).setLineWidth(lineWidth)

        lines.setXData(timeData)
        lines2.setXData(timeData)
        if trend:
            pf = trend[-1][2][-1]
            label = 'Working set: %iMB, Virtual mem: %iMB, Page faults: %s' % (
                workingsetData[-1], memData[-1], util.FmtAmt(pf))
            c.addText(offsX, 2, label)
        buf = c.makeChart2(chart.PNG)
        hostBitmap = trinity.Tr2HostBitmap(w, h, 1,
                                           trinity.PIXEL_FORMAT.B8G8R8A8_UNORM)
        hostBitmap.LoadFromPngInMemory(buf)
        linegr = uicls.Sprite(parent=wnd.sr.graph, align=uiconst.TOALL)
        linegr.GetMenu = self.GetGraphMenu
        linegr.texture.atlasTexture = uicore.uilib.CreateTexture(width, height)
        linegr.texture.atlasTexture.CopyFromHostBitmap(hostBitmap)
示例#22
0
def KillOldCursor():
    import trinity
    bmp = trinity.Tr2HostBitmap()
    bmp.CreateFromFile('res:/uicore/cursors/cursor10.dds')
    cursor = trinity.Tr2MouseCursor(bmp, 16, 15)
    uicore.uilib.SetCursorProperties(cursor)