Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/windows/classes/sun/java2d/d3d/D3DSurfaceData.java
32288 views
/*1* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.java2d.d3d;2627import java.awt.AlphaComposite;28import java.awt.BufferCapabilities;29import java.awt.Component;30import java.awt.GraphicsConfiguration;31import java.awt.GraphicsDevice;32import java.awt.GraphicsEnvironment;33import java.awt.Image;34import java.awt.Rectangle;35import java.awt.Transparency;36import java.awt.image.ColorModel;37import java.awt.image.DataBuffer;38import java.awt.image.DirectColorModel;39import java.awt.image.Raster;40import java.awt.image.SampleModel;41import java.awt.image.SinglePixelPackedSampleModel;42import sun.awt.SunHints;43import sun.awt.image.DataBufferNative;44import sun.awt.image.PixelConverter;45import sun.awt.image.SurfaceManager;46import sun.awt.image.WritableRasterNative;47import sun.awt.windows.WComponentPeer;48import sun.java2d.pipe.hw.AccelSurface;49import sun.java2d.InvalidPipeException;50import sun.java2d.SunGraphics2D;51import sun.java2d.SurfaceData;52import sun.java2d.loops.GraphicsPrimitive;53import sun.java2d.loops.MaskFill;54import sun.java2d.loops.SurfaceType;55import sun.java2d.loops.CompositeType;56import sun.java2d.pipe.ParallelogramPipe;57import sun.java2d.pipe.PixelToParallelogramConverter;58import sun.java2d.pipe.RenderBuffer;59import sun.java2d.pipe.TextPipe;60import static sun.java2d.pipe.BufferedOpCodes.*;61import static sun.java2d.d3d.D3DContext.D3DContextCaps.*;62import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;63import sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType;64import java.awt.BufferCapabilities.FlipContents;65import java.awt.Window;66import sun.awt.SunToolkit;67import sun.awt.image.SunVolatileImage;68import sun.java2d.ScreenUpdateManager;69import sun.java2d.StateTracker;70import sun.java2d.SurfaceDataProxy;71import sun.java2d.pipe.hw.ExtendedBufferCapabilities;7273/**74* This class describes a D3D "surface", that is, a region of pixels75* managed via D3D. An D3DSurfaceData can be tagged with one of three76* different SurfaceType objects for the purpose of registering loops, etc.77* This diagram shows the hierarchy of D3D SurfaceTypes:78*79* Any80* / \81* D3DSurface D3DTexture82* |83* D3DSurfaceRTT84*85* D3DSurface86* This kind of surface can be rendered to using D3D APIs. It is also87* possible to copy a D3DSurface to another D3DSurface (or to itself).88*89* D3DTexture90* This kind of surface cannot be rendered to using D3D (in the same sense91* as in D3DSurface). However, it is possible to upload a region of pixels92* to a D3DTexture object via Lock/UnlockRect(). One can also copy a93* surface of type D3DTexture to a D3DSurface by binding the texture94* to a quad and then rendering it to the destination surface (this process95* is known as "texture mapping").96*97* D3DSurfaceRTT98* This kind of surface can be thought of as a sort of hybrid between99* D3DSurface and D3DTexture, in that one can render to this kind of100* surface as if it were of type D3DSurface, but the process of copying101* this kind of surface to another is more like a D3DTexture. (Note that102* "RTT" stands for "render-to-texture".)103*104* In addition to these SurfaceType variants, we have also defined some105* constants that describe in more detail the type of underlying D3D106* surface. This table helps explain the relationships between those107* "type" constants and their corresponding SurfaceType:108*109* D3D Type Corresponding SurfaceType110* -------- -------------------------111* RT_PLAIN D3DSurface112* TEXTURE D3DTexture113* FLIP_BACKBUFFER D3DSurface114* RT_TEXTURE D3DSurfaceRTT115*/116public class D3DSurfaceData extends SurfaceData implements AccelSurface {117118/**119* To be used with getNativeResource() only.120* @see #getNativeResource()121*/122public static final int D3D_DEVICE_RESOURCE= 100;123/*124* Surface types.125* We use these surface types when copying from a sw surface126* to a surface or texture.127*/128public static final int ST_INT_ARGB = 0;129public static final int ST_INT_ARGB_PRE = 1;130public static final int ST_INT_ARGB_BM = 2;131public static final int ST_INT_RGB = 3;132public static final int ST_INT_BGR = 4;133public static final int ST_USHORT_565_RGB = 5;134public static final int ST_USHORT_555_RGB = 6;135public static final int ST_BYTE_INDEXED = 7;136public static final int ST_BYTE_INDEXED_BM = 8;137public static final int ST_3BYTE_BGR = 9;138139/** Equals to D3DSWAPEFFECT_DISCARD */140public static final int SWAP_DISCARD = 1;141/** Equals to D3DSWAPEFFECT_FLIP */142public static final int SWAP_FLIP = 2;143/** Equals to D3DSWAPEFFECT_COPY */144public static final int SWAP_COPY = 3;145/*146* SurfaceTypes147*/148private static final String DESC_D3D_SURFACE = "D3D Surface";149private static final String DESC_D3D_SURFACE_RTT =150"D3D Surface (render-to-texture)";151private static final String DESC_D3D_TEXTURE = "D3D Texture";152153// REMIND: regarding ArgbPre??154static final SurfaceType D3DSurface =155SurfaceType.Any.deriveSubType(DESC_D3D_SURFACE,156PixelConverter.ArgbPre.instance);157static final SurfaceType D3DSurfaceRTT =158D3DSurface.deriveSubType(DESC_D3D_SURFACE_RTT);159static final SurfaceType D3DTexture =160SurfaceType.Any.deriveSubType(DESC_D3D_TEXTURE);161162private int type;163private int width, height;164// these fields are set from the native code when the surface is165// initialized166private int nativeWidth, nativeHeight;167protected WComponentPeer peer;168private Image offscreenImage;169protected D3DGraphicsDevice graphicsDevice;170171private int swapEffect;172private VSyncType syncType;173private int backBuffersNum;174175private WritableRasterNative wrn;176177protected static D3DRenderer d3dRenderPipe;178protected static PixelToParallelogramConverter d3dTxRenderPipe;179protected static ParallelogramPipe d3dAAPgramPipe;180protected static D3DTextRenderer d3dTextPipe;181protected static D3DDrawImage d3dImagePipe;182183private native boolean initTexture(long pData, boolean isRTT,184boolean isOpaque);185private native boolean initFlipBackbuffer(long pData, long pPeerData,186int numbuffers,187int swapEffect, int syncType);188private native boolean initRTSurface(long pData, boolean isOpaque);189private native void initOps(int screen, int width, int height);190191static {192D3DRenderQueue rq = D3DRenderQueue.getInstance();193d3dImagePipe = new D3DDrawImage();194d3dTextPipe = new D3DTextRenderer(rq);195d3dRenderPipe = new D3DRenderer(rq);196if (GraphicsPrimitive.tracingEnabled()) {197d3dTextPipe = d3dTextPipe.traceWrap();198d3dRenderPipe = d3dRenderPipe.traceWrap();199//The wrapped d3dRenderPipe will wrap the AA pipe as well...200//d3dAAPgramPipe = d3dRenderPipe.traceWrap();201}202d3dAAPgramPipe = d3dRenderPipe.getAAParallelogramPipe();203d3dTxRenderPipe =204new PixelToParallelogramConverter(d3dRenderPipe, d3dRenderPipe,2051.0, 0.25, true);206207D3DBlitLoops.register();208D3DMaskFill.register();209D3DMaskBlit.register();210}211212protected D3DSurfaceData(WComponentPeer peer, D3DGraphicsConfig gc,213int width, int height, Image image,214ColorModel cm, int numBackBuffers,215int swapEffect, VSyncType vSyncType,216int type)217{218super(getCustomSurfaceType(type), cm);219this.graphicsDevice = gc.getD3DDevice();220this.peer = peer;221this.type = type;222this.width = width;223this.height = height;224this.offscreenImage = image;225this.backBuffersNum = numBackBuffers;226this.swapEffect = swapEffect;227this.syncType = vSyncType;228229initOps(graphicsDevice.getScreen(), width, height);230if (type == WINDOW) {231// we put the surface into the "lost"232// state; it will be restored by the D3DScreenUpdateManager233// prior to rendering to it for the first time. This is done234// so that vram is not wasted for surfaces never rendered to235setSurfaceLost(true);236} else {237initSurface();238}239setBlitProxyKey(gc.getProxyKey());240}241242@Override243public SurfaceDataProxy makeProxyFor(SurfaceData srcData) {244return D3DSurfaceDataProxy.245createProxy(srcData,246(D3DGraphicsConfig)graphicsDevice.getDefaultConfiguration());247}248249/**250* Creates a SurfaceData object representing the back buffer of a251* double-buffered on-screen Window.252*/253public static D3DSurfaceData createData(WComponentPeer peer, Image image) {254D3DGraphicsConfig gc = getGC(peer);255if (gc == null || !peer.isAccelCapable()) {256return null;257}258BufferCapabilities caps = peer.getBackBufferCaps();259VSyncType vSyncType = VSYNC_DEFAULT;260if (caps instanceof ExtendedBufferCapabilities) {261vSyncType = ((ExtendedBufferCapabilities)caps).getVSync();262}263Rectangle r = peer.getBounds();264BufferCapabilities.FlipContents flip = caps.getFlipContents();265int swapEffect;266if (flip == FlipContents.COPIED) {267swapEffect = SWAP_COPY;268} else if (flip == FlipContents.PRIOR) {269swapEffect = SWAP_FLIP;270} else { // flip == FlipContents.UNDEFINED || .BACKGROUND271swapEffect = SWAP_DISCARD;272}273return new D3DSurfaceData(peer, gc, r.width, r.height,274image, peer.getColorModel(),275peer.getBackBuffersNum(),276swapEffect, vSyncType, FLIP_BACKBUFFER);277}278279/**280* Returns a WINDOW type of surface - a281* swap chain which serves as an on-screen surface,282* handled by the D3DScreenUpdateManager.283*284* Note that the native surface is not initialized285* when the surface is created to avoid using excessive286* resources, and the surface is placed into the lost287* state. It will be restored prior to any rendering288* to it.289*290* @param peer peer for which the onscreen surface is to be created291* @return a D3DWindowSurfaceData (flip chain) surface292*/293public static D3DSurfaceData createData(WComponentPeer peer) {294D3DGraphicsConfig gc = getGC(peer);295if (gc == null || !peer.isAccelCapable()) {296return null;297}298return new D3DWindowSurfaceData(peer, gc);299}300301/**302* Creates a SurfaceData object representing an off-screen buffer (either303* a plain surface or Texture).304*/305public static D3DSurfaceData createData(D3DGraphicsConfig gc,306int width, int height,307ColorModel cm,308Image image, int type)309{310if (type == RT_TEXTURE) {311boolean isOpaque = cm.getTransparency() == Transparency.OPAQUE;312int cap = isOpaque ? CAPS_RT_TEXTURE_OPAQUE : CAPS_RT_TEXTURE_ALPHA;313if (!gc.getD3DDevice().isCapPresent(cap)) {314type = RT_PLAIN;315}316}317D3DSurfaceData ret = null;318try {319ret = new D3DSurfaceData(null, gc, width, height,320image, cm, 0, SWAP_DISCARD, VSYNC_DEFAULT,321type);322} catch (InvalidPipeException ipe) {323// try again - we might have ran out of vram, and rt textures324// could take up more than a plain surface, so it might succeed325if (type == RT_TEXTURE) {326// If a RT_TEXTURE was requested do not attempt to create a327// plain surface. (note that RT_TEXTURE can only be requested328// from a VI so the cast is safe)329if (((SunVolatileImage)image).getForcedAccelSurfaceType() !=330RT_TEXTURE)331{332type = RT_PLAIN;333ret = new D3DSurfaceData(null, gc, width, height,334image, cm, 0, SWAP_DISCARD,335VSYNC_DEFAULT, type);336}337}338}339return ret;340}341342/**343* Returns the appropriate SurfaceType corresponding to the given D3D344* surface type constant (e.g. TEXTURE -> D3DTexture).345*/346private static SurfaceType getCustomSurfaceType(int d3dType) {347switch (d3dType) {348case TEXTURE:349return D3DTexture;350case RT_TEXTURE:351return D3DSurfaceRTT;352default:353return D3DSurface;354}355}356357private boolean initSurfaceNow() {358boolean isOpaque = (getTransparency() == Transparency.OPAQUE);359switch (type) {360case RT_PLAIN:361return initRTSurface(getNativeOps(), isOpaque);362case TEXTURE:363return initTexture(getNativeOps(), false/*isRTT*/, isOpaque);364case RT_TEXTURE:365return initTexture(getNativeOps(), true/*isRTT*/, isOpaque);366// REMIND: we may want to pass the exact type to the native367// level here so that we could choose the right presentation368// interval for the frontbuffer (immediate vs v-synced)369case WINDOW:370case FLIP_BACKBUFFER:371return initFlipBackbuffer(getNativeOps(), peer.getData(),372backBuffersNum, swapEffect,373syncType.id());374default:375return false;376}377}378379/**380* Initializes the appropriate D3D offscreen surface based on the value381* of the type parameter. If the surface creation fails for any reason,382* an OutOfMemoryError will be thrown.383*/384protected void initSurface() {385// any time we create or restore the surface, recreate the raster386synchronized (this) {387wrn = null;388}389// REMIND: somewhere a puppy died390class Status {391boolean success = false;392};393final Status status = new Status();394D3DRenderQueue rq = D3DRenderQueue.getInstance();395rq.lock();396try {397rq.flushAndInvokeNow(new Runnable() {398public void run() {399status.success = initSurfaceNow();400}401});402if (!status.success) {403throw new InvalidPipeException("Error creating D3DSurface");404}405} finally {406rq.unlock();407}408}409410/**411* Returns the D3DContext for the GraphicsConfig associated with this412* surface.413*/414public final D3DContext getContext() {415return graphicsDevice.getContext();416}417418/**419* Returns one of the surface type constants defined above.420*/421public final int getType() {422return type;423}424425private static native int dbGetPixelNative(long pData, int x, int y);426private static native void dbSetPixelNative(long pData, int x, int y,427int pixel);428static class D3DDataBufferNative extends DataBufferNative {429int pixel;430protected D3DDataBufferNative(SurfaceData sData,431int type, int w, int h)432{433super(sData, type, w, h);434}435436protected int getElem(final int x, final int y,437final SurfaceData sData)438{439if (sData.isSurfaceLost()) {440return 0;441}442443int retPixel;444D3DRenderQueue rq = D3DRenderQueue.getInstance();445rq.lock();446try {447rq.flushAndInvokeNow(new Runnable() {448public void run() {449pixel = dbGetPixelNative(sData.getNativeOps(), x, y);450}451});452} finally {453retPixel = pixel;454rq.unlock();455}456return retPixel;457}458459protected void setElem(final int x, final int y, final int pixel,460final SurfaceData sData)461{462if (sData.isSurfaceLost()) {463return;464}465466D3DRenderQueue rq = D3DRenderQueue.getInstance();467rq.lock();468try {469rq.flushAndInvokeNow(new Runnable() {470public void run() {471dbSetPixelNative(sData.getNativeOps(), x, y, pixel);472}473});474sData.markDirty();475} finally {476rq.unlock();477}478}479}480481public synchronized Raster getRaster(int x, int y, int w, int h) {482if (wrn == null) {483DirectColorModel dcm = (DirectColorModel)getColorModel();484SampleModel smHw;485int dataType = 0;486int scanStride = width;487488if (dcm.getPixelSize() > 16) {489dataType = DataBuffer.TYPE_INT;490} else {491// 15, 16492dataType = DataBuffer.TYPE_USHORT;493}494495// note that we have to use the surface width and height here,496// not the passed w,h497smHw = new SinglePixelPackedSampleModel(dataType, width, height,498scanStride, dcm.getMasks());499DataBuffer dbn = new D3DDataBufferNative(this, dataType,500width, height);501wrn = WritableRasterNative.createNativeRaster(smHw, dbn);502}503504return wrn;505}506507/**508* For now, we can only render LCD text if:509* - the pixel shaders are available, and510* - blending is disabled, and511* - the source color is opaque512* - and the destination is opaque513*/514public boolean canRenderLCDText(SunGraphics2D sg2d) {515return516graphicsDevice.isCapPresent(CAPS_LCD_SHADER) &&517sg2d.compositeState <= SunGraphics2D.COMP_ISCOPY &&518sg2d.paintState <= SunGraphics2D.PAINT_OPAQUECOLOR &&519sg2d.surfaceData.getTransparency() == Transparency.OPAQUE;520}521522/**523* If acceleration should no longer be used for this surface.524* This implementation flags to the manager that it should no525* longer attempt to re-create a D3DSurface.526*/527void disableAccelerationForSurface() {528if (offscreenImage != null) {529SurfaceManager sm = SurfaceManager.getManager(offscreenImage);530if (sm instanceof D3DVolatileSurfaceManager) {531setSurfaceLost(true);532((D3DVolatileSurfaceManager)sm).setAccelerationEnabled(false);533}534}535}536537public void validatePipe(SunGraphics2D sg2d) {538TextPipe textpipe;539boolean validated = false;540541// REMIND: the D3D pipeline doesn't support XOR!, more542// fixes will be needed below. For now we disable D3D rendering543// for the surface which had any XOR rendering done to.544if (sg2d.compositeState >= sg2d.COMP_XOR) {545super.validatePipe(sg2d);546sg2d.imagepipe = d3dImagePipe;547disableAccelerationForSurface();548return;549}550551// D3DTextRenderer handles both AA and non-AA text, but552// only works with the following modes:553// (Note: For LCD text we only enter this code path if554// canRenderLCDText() has already validated that the mode is555// CompositeType.SrcNoEa (opaque color), which will be subsumed556// by the CompositeType.SrcNoEa (any color) test below.)557558if (/* CompositeType.SrcNoEa (any color) */559(sg2d.compositeState <= sg2d.COMP_ISCOPY &&560sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) ||561562/* CompositeType.SrcOver (any color) */563(sg2d.compositeState == sg2d.COMP_ALPHA &&564sg2d.paintState <= sg2d.PAINT_ALPHACOLOR &&565(((AlphaComposite)sg2d.composite).getRule() ==566AlphaComposite.SRC_OVER)) ||567568/* CompositeType.Xor (any color) */569(sg2d.compositeState == sg2d.COMP_XOR &&570sg2d.paintState <= sg2d.PAINT_ALPHACOLOR))571{572textpipe = d3dTextPipe;573} else {574// do this to initialize textpipe correctly; we will attempt575// to override the non-text pipes below576super.validatePipe(sg2d);577textpipe = sg2d.textpipe;578validated = true;579}580581PixelToParallelogramConverter txPipe = null;582D3DRenderer nonTxPipe = null;583584if (sg2d.antialiasHint != SunHints.INTVAL_ANTIALIAS_ON) {585if (sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) {586if (sg2d.compositeState <= sg2d.COMP_XOR) {587txPipe = d3dTxRenderPipe;588nonTxPipe = d3dRenderPipe;589}590} else if (sg2d.compositeState <= sg2d.COMP_ALPHA) {591if (D3DPaints.isValid(sg2d)) {592txPipe = d3dTxRenderPipe;593nonTxPipe = d3dRenderPipe;594}595// custom paints handled by super.validatePipe() below596}597} else {598if (sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) {599if (graphicsDevice.isCapPresent(CAPS_AA_SHADER) &&600(sg2d.imageComp == CompositeType.SrcOverNoEa ||601sg2d.imageComp == CompositeType.SrcOver))602{603if (!validated) {604super.validatePipe(sg2d);605validated = true;606}607PixelToParallelogramConverter aaConverter =608new PixelToParallelogramConverter(sg2d.shapepipe,609d3dAAPgramPipe,6101.0/8.0, 0.499,611false);612sg2d.drawpipe = aaConverter;613sg2d.fillpipe = aaConverter;614sg2d.shapepipe = aaConverter;615} else if (sg2d.compositeState == sg2d.COMP_XOR) {616// install the solid pipes when AA and XOR are both enabled617txPipe = d3dTxRenderPipe;618nonTxPipe = d3dRenderPipe;619}620}621// other cases handled by super.validatePipe() below622}623624if (txPipe != null) {625if (sg2d.transformState >= sg2d.TRANSFORM_TRANSLATESCALE) {626sg2d.drawpipe = txPipe;627sg2d.fillpipe = txPipe;628} else if (sg2d.strokeState != sg2d.STROKE_THIN) {629sg2d.drawpipe = txPipe;630sg2d.fillpipe = nonTxPipe;631} else {632sg2d.drawpipe = nonTxPipe;633sg2d.fillpipe = nonTxPipe;634}635// Note that we use the transforming pipe here because it636// will examine the shape and possibly perform an optimized637// operation if it can be simplified. The simplifications638// will be valid for all STROKE and TRANSFORM types.639sg2d.shapepipe = txPipe;640} else {641if (!validated) {642super.validatePipe(sg2d);643}644}645646// install the text pipe based on our earlier decision647sg2d.textpipe = textpipe;648649// always override the image pipe with the specialized D3D pipe650sg2d.imagepipe = d3dImagePipe;651}652653@Override654protected MaskFill getMaskFill(SunGraphics2D sg2d) {655if (sg2d.paintState > sg2d.PAINT_ALPHACOLOR) {656/*657* We can only accelerate non-Color MaskFill operations if658* all of the following conditions hold true:659* - there is an implementation for the given paintState660* - the current Paint can be accelerated for this destination661* - multitexturing is available (since we need to modulate662* the alpha mask texture with the paint texture)663*664* In all other cases, we return null, in which case the665* validation code will choose a more general software-based loop.666*/667if (!D3DPaints.isValid(sg2d) ||668!graphicsDevice.isCapPresent(CAPS_MULTITEXTURE))669{670return null;671}672}673return super.getMaskFill(sg2d);674}675676@Override677public boolean copyArea(SunGraphics2D sg2d,678int x, int y, int w, int h, int dx, int dy)679{680if (sg2d.transformState < sg2d.TRANSFORM_TRANSLATESCALE &&681sg2d.compositeState < sg2d.COMP_XOR)682{683x += sg2d.transX;684y += sg2d.transY;685686d3dRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy);687688return true;689}690return false;691}692693@Override694public void flush() {695D3DRenderQueue rq = D3DRenderQueue.getInstance();696rq.lock();697try {698RenderBuffer buf = rq.getBuffer();699rq.ensureCapacityAndAlignment(12, 4);700buf.putInt(FLUSH_SURFACE);701buf.putLong(getNativeOps());702703// this call is expected to complete synchronously, so flush now704rq.flushNow();705} finally {706rq.unlock();707}708}709710/**711* Disposes the native resources associated with the given D3DSurfaceData712* (referenced by the pData parameter). This method is invoked from713* the native Dispose() method from the Disposer thread when the714* Java-level D3DSurfaceData object is about to go away.715*/716static void dispose(long pData) {717D3DRenderQueue rq = D3DRenderQueue.getInstance();718rq.lock();719try {720RenderBuffer buf = rq.getBuffer();721rq.ensureCapacityAndAlignment(12, 4);722buf.putInt(DISPOSE_SURFACE);723buf.putLong(pData);724725// this call is expected to complete synchronously, so flush now726rq.flushNow();727} finally {728rq.unlock();729}730}731732static void swapBuffers(D3DSurfaceData sd,733final int x1, final int y1,734final int x2, final int y2)735{736long pData = sd.getNativeOps();737D3DRenderQueue rq = D3DRenderQueue.getInstance();738// swapBuffers can be called from the toolkit thread by swing, we739// should detect this and prevent the deadlocks740if (rq.isRenderQueueThread()) {741if (!rq.tryLock()) {742// if we could not obtain the lock, repaint the area743// that was supposed to be swapped, and no-op this swap744final Component target = (Component)sd.getPeer().getTarget();745SunToolkit.executeOnEventHandlerThread(target, new Runnable() {746public void run() {747target.repaint(x1, y1, x2, y2);748}749});750return;751}752} else {753rq.lock();754}755try {756RenderBuffer buf = rq.getBuffer();757rq.ensureCapacityAndAlignment(28, 4);758buf.putInt(SWAP_BUFFERS);759buf.putLong(pData);760buf.putInt(x1);761buf.putInt(y1);762buf.putInt(x2);763buf.putInt(y2);764rq.flushNow();765} finally {766rq.unlock();767}768}769770/**771* Returns destination Image associated with this SurfaceData.772*/773public Object getDestination() {774return offscreenImage;775}776777public Rectangle getBounds() {778if (type == FLIP_BACKBUFFER || type == WINDOW) {779Rectangle r = peer.getBounds();780r.x = r.y = 0;781return r;782} else {783return new Rectangle(width, height);784}785}786787public Rectangle getNativeBounds() {788D3DRenderQueue rq = D3DRenderQueue.getInstance();789// need to lock to make sure nativeWidth and Height are consistent790// since they are set from the render thread from the native791// level792rq.lock();793try {794// REMIND: use xyoffsets?795return new Rectangle(nativeWidth, nativeHeight);796} finally {797rq.unlock();798}799}800801802public GraphicsConfiguration getDeviceConfiguration() {803return graphicsDevice.getDefaultConfiguration();804}805806public SurfaceData getReplacement() {807return restoreContents(offscreenImage);808}809810private static D3DGraphicsConfig getGC(WComponentPeer peer) {811GraphicsConfiguration gc;812if (peer != null) {813gc = peer.getGraphicsConfiguration();814} else {815GraphicsEnvironment env =816GraphicsEnvironment.getLocalGraphicsEnvironment();817GraphicsDevice gd = env.getDefaultScreenDevice();818gc = gd.getDefaultConfiguration();819}820return (gc instanceof D3DGraphicsConfig) ? (D3DGraphicsConfig)gc : null;821}822823/**824* Attempts to restore the surface by initializing the native data825*/826void restoreSurface() {827initSurface();828}829830WComponentPeer getPeer() {831return peer;832}833834/**835* We need to let the surface manager know that the surface is lost so836* that for example BufferStrategy.contentsLost() returns correct result.837* Normally the status of contentsLost is set in validate(), but in some838* cases (like Swing's buffer per window) we intentionally don't call839* validate from the toolkit thread but only check for the BS status.840*/841@Override842public void setSurfaceLost(boolean lost) {843super.setSurfaceLost(lost);844if (lost && offscreenImage != null) {845SurfaceManager sm = SurfaceManager.getManager(offscreenImage);846sm.acceleratedSurfaceLost();847}848}849850private static native long getNativeResourceNative(long sdops, int resType);851/**852* Returns a pointer to the native resource of specified {@code resType}853* associated with this surface.854*855* Specifically, for {@code D3DSurfaceData} this method returns pointers of856* the following:857* <pre>858* TEXTURE - (IDirect3DTexture9*)859* RT_TEXTURE, RT_PLAIN - (IDirect3DSurface9*)860* FLIP_BACKBUFFER - (IDirect3DSwapChain9*)861* D3D_DEVICE_RESOURCE - (IDirect3DDevice9*)862* </pre>863*864* Multiple resources may be available for some types (i.e. for render to865* texture one could retrieve both a destination surface by specifying866* RT_TEXTURE, and a texture by using TEXTURE).867*868* Note: the pointer returned by this method is only valid on the rendering869* thread.870*871* @return pointer to the native resource of specified type or 0L if872* such resource doesn't exist or can not be retrieved.873* @see sun.java2d.pipe.hw.AccelSurface#getNativeResource874*/875public long getNativeResource(int resType) {876return getNativeResourceNative(getNativeOps(), resType);877}878879/**880* Class representing an on-screen d3d surface. Since d3d can't881* render to the screen directly, it is implemented as a swap chain,882* controlled by D3DScreenUpdateManager.883*884* @see D3DScreenUpdateManager885*/886public static class D3DWindowSurfaceData extends D3DSurfaceData {887StateTracker dirtyTracker;888889public D3DWindowSurfaceData(WComponentPeer peer,890D3DGraphicsConfig gc)891{892super(peer, gc,893peer.getBounds().width, peer.getBounds().height,894null, peer.getColorModel(), 1, SWAP_COPY, VSYNC_DEFAULT,895WINDOW);896dirtyTracker = getStateTracker();897}898899/**900* {@inheritDoc}901*902* Overridden to use ScreenUpdateManager to obtain the replacement903* surface.904*905* @see sun.java2d.ScreenUpdateManager#getReplacementScreenSurface906*/907@Override908public SurfaceData getReplacement() {909ScreenUpdateManager mgr = ScreenUpdateManager.getInstance();910return mgr.getReplacementScreenSurface(peer, this);911}912913/**914* Returns destination Component associated with this SurfaceData.915*/916@Override917public Object getDestination() {918return peer.getTarget();919}920921@Override922void disableAccelerationForSurface() {923// for on-screen surfaces we need to make sure a backup GDI surface is924// is used until a new one is set (which may happen during a resize). We925// don't want the screen update maanger to replace the surface right way926// because it causes repainting issues in Swing, so we invalidate it,927// this will prevent SUM from issuing a replaceSurfaceData call.928setSurfaceLost(true);929invalidate();930flush();931peer.disableAcceleration();932ScreenUpdateManager.getInstance().dropScreenSurface(this);933}934935@Override936void restoreSurface() {937if (!peer.isAccelCapable()) {938throw new InvalidPipeException("Onscreen acceleration " +939"disabled for this surface");940}941Window fsw = graphicsDevice.getFullScreenWindow();942if (fsw != null && fsw != peer.getTarget()) {943throw new InvalidPipeException("Can't restore onscreen surface"+944" when in full-screen mode");945}946super.restoreSurface();947// if initialization was unsuccessful, an IPE will be thrown948// and the surface will remain lost949setSurfaceLost(false);950951// This is to make sure the render target is reset after this952// surface is restored. The reason for this is that sometimes this953// surface can be restored from multiple threads (the screen update954// manager's thread and app's rendering thread) at the same time,955// and when that happens the second restoration will create the956// native resource which will not be set as render target because957// the BufferedContext's validate method will think that since the958// surface data object didn't change then the current render target959// is correct and no rendering will appear on the screen.960D3DRenderQueue rq = D3DRenderQueue.getInstance();961rq.lock();962try {963getContext().invalidateContext();964} finally {965rq.unlock();966}967}968969public boolean isDirty() {970return !dirtyTracker.isCurrent();971}972973public void markClean() {974dirtyTracker = getStateTracker();975}976}977978/**979* Updates the layered window with the contents of the surface.980*981* @param pd3dsd pointer to the D3DSDOps structure982* @param pData pointer to the AwtWindow peer data983* @param w width of the window984* @param h height of the window985* @see sun.awt.windows.TranslucentWindowPainter986*/987public static native boolean updateWindowAccelImpl(long pd3dsd, long pData,988int w, int h);989}990991992