Path: blob/master/src/java.desktop/windows/classes/sun/java2d/d3d/D3DSurfaceData.java
41159 views
/*1* Copyright (c) 2007, 2014, 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 sun.java2d.pipe.Region;61import static sun.java2d.pipe.BufferedOpCodes.*;62import static sun.java2d.d3d.D3DContext.D3DContextCaps.*;63import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;64import sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType;65import java.awt.BufferCapabilities.FlipContents;66import java.awt.Dimension;67import java.awt.Window;68import java.awt.geom.AffineTransform;69import sun.awt.SunToolkit;70import sun.awt.image.SunVolatileImage;71import sun.awt.windows.WWindowPeer;72import sun.java2d.ScreenUpdateManager;73import sun.java2d.StateTracker;74import sun.java2d.SurfaceDataProxy;75import sun.java2d.pipe.hw.ExtendedBufferCapabilities;7677/**78* This class describes a D3D "surface", that is, a region of pixels79* managed via D3D. An D3DSurfaceData can be tagged with one of three80* different SurfaceType objects for the purpose of registering loops, etc.81* This diagram shows the hierarchy of D3D SurfaceTypes:82*83* Any84* / \85* D3DSurface D3DTexture86* |87* D3DSurfaceRTT88*89* D3DSurface90* This kind of surface can be rendered to using D3D APIs. It is also91* possible to copy a D3DSurface to another D3DSurface (or to itself).92*93* D3DTexture94* This kind of surface cannot be rendered to using D3D (in the same sense95* as in D3DSurface). However, it is possible to upload a region of pixels96* to a D3DTexture object via Lock/UnlockRect(). One can also copy a97* surface of type D3DTexture to a D3DSurface by binding the texture98* to a quad and then rendering it to the destination surface (this process99* is known as "texture mapping").100*101* D3DSurfaceRTT102* This kind of surface can be thought of as a sort of hybrid between103* D3DSurface and D3DTexture, in that one can render to this kind of104* surface as if it were of type D3DSurface, but the process of copying105* this kind of surface to another is more like a D3DTexture. (Note that106* "RTT" stands for "render-to-texture".)107*108* In addition to these SurfaceType variants, we have also defined some109* constants that describe in more detail the type of underlying D3D110* surface. This table helps explain the relationships between those111* "type" constants and their corresponding SurfaceType:112*113* D3D Type Corresponding SurfaceType114* -------- -------------------------115* RT_PLAIN D3DSurface116* TEXTURE D3DTexture117* FLIP_BACKBUFFER D3DSurface118* RT_TEXTURE D3DSurfaceRTT119*/120public class D3DSurfaceData extends SurfaceData implements AccelSurface {121122/**123* To be used with getNativeResource() only.124* @see #getNativeResource125*/126public static final int D3D_DEVICE_RESOURCE= 100;127/*128* Surface types.129* We use these surface types when copying from a sw surface130* to a surface or texture.131*/132public static final int ST_INT_ARGB = 0;133public static final int ST_INT_ARGB_PRE = 1;134public static final int ST_INT_ARGB_BM = 2;135public static final int ST_INT_RGB = 3;136public static final int ST_INT_BGR = 4;137public static final int ST_USHORT_565_RGB = 5;138public static final int ST_USHORT_555_RGB = 6;139public static final int ST_BYTE_INDEXED = 7;140public static final int ST_BYTE_INDEXED_BM = 8;141public static final int ST_3BYTE_BGR = 9;142143/** Equals to D3DSWAPEFFECT_DISCARD */144public static final int SWAP_DISCARD = 1;145/** Equals to D3DSWAPEFFECT_FLIP */146public static final int SWAP_FLIP = 2;147/** Equals to D3DSWAPEFFECT_COPY */148public static final int SWAP_COPY = 3;149/*150* SurfaceTypes151*/152private static final String DESC_D3D_SURFACE = "D3D Surface";153private static final String DESC_D3D_SURFACE_RTT =154"D3D Surface (render-to-texture)";155private static final String DESC_D3D_TEXTURE = "D3D Texture";156157// REMIND: regarding ArgbPre??158static final SurfaceType D3DSurface =159SurfaceType.Any.deriveSubType(DESC_D3D_SURFACE,160PixelConverter.ArgbPre.instance);161static final SurfaceType D3DSurfaceRTT =162D3DSurface.deriveSubType(DESC_D3D_SURFACE_RTT);163static final SurfaceType D3DTexture =164SurfaceType.Any.deriveSubType(DESC_D3D_TEXTURE);165166private int type;167private int width, height;168private final double scaleX;169private final double scaleY;170// these fields are set from the native code when the surface is171// initialized172private int nativeWidth, nativeHeight;173protected WComponentPeer peer;174private Image offscreenImage;175protected D3DGraphicsDevice graphicsDevice;176177private int swapEffect;178private VSyncType syncType;179private int backBuffersNum;180181private WritableRasterNative wrn;182183protected static D3DRenderer d3dRenderPipe;184protected static PixelToParallelogramConverter d3dTxRenderPipe;185protected static ParallelogramPipe d3dAAPgramPipe;186protected static D3DTextRenderer d3dTextPipe;187protected static D3DDrawImage d3dImagePipe;188189private native boolean initTexture(long pData, boolean isRTT,190boolean isOpaque);191private native boolean initFlipBackbuffer(long pData, long pPeerData,192int numbuffers,193int swapEffect, int syncType);194private native boolean initRTSurface(long pData, boolean isOpaque);195private native void initOps(int screen, int width, int height);196197static {198D3DRenderQueue rq = D3DRenderQueue.getInstance();199d3dImagePipe = new D3DDrawImage();200d3dTextPipe = new D3DTextRenderer(rq);201d3dRenderPipe = new D3DRenderer(rq);202if (GraphicsPrimitive.tracingEnabled()) {203d3dTextPipe = d3dTextPipe.traceWrap();204d3dRenderPipe = d3dRenderPipe.traceWrap();205//The wrapped d3dRenderPipe will wrap the AA pipe as well...206//d3dAAPgramPipe = d3dRenderPipe.traceWrap();207}208d3dAAPgramPipe = d3dRenderPipe.getAAParallelogramPipe();209d3dTxRenderPipe =210new PixelToParallelogramConverter(d3dRenderPipe, d3dRenderPipe,2111.0, 0.25, true);212213D3DBlitLoops.register();214D3DMaskFill.register();215D3DMaskBlit.register();216}217218protected D3DSurfaceData(WComponentPeer peer, D3DGraphicsConfig gc,219int width, int height, Image image,220ColorModel cm, int numBackBuffers,221int swapEffect, VSyncType vSyncType,222int type)223{224super(getCustomSurfaceType(type), cm);225this.graphicsDevice = gc.getD3DDevice();226this.scaleX = type == TEXTURE ? 1 : graphicsDevice.getDefaultScaleX();227this.scaleY = type == TEXTURE ? 1 : graphicsDevice.getDefaultScaleY();228this.peer = peer;229this.type = type;230231if (scaleX == 1 && scaleY == 1) {232this.width = width;233this.height = height;234} else if (peer instanceof WWindowPeer) {235Dimension scaledSize = ((WWindowPeer) peer).getScaledWindowSize();236this.width = scaledSize.width;237this.height = scaledSize.height;238} else {239this.width = Region.clipRound(width * scaleX);240this.height = Region.clipRound(height * scaleY);241}242243this.offscreenImage = image;244this.backBuffersNum = numBackBuffers;245this.swapEffect = swapEffect;246this.syncType = vSyncType;247248initOps(graphicsDevice.getScreen(), this.width, this.height);249if (type == WINDOW) {250// we put the surface into the "lost"251// state; it will be restored by the D3DScreenUpdateManager252// prior to rendering to it for the first time. This is done253// so that vram is not wasted for surfaces never rendered to254setSurfaceLost(true);255} else {256initSurface();257}258setBlitProxyKey(gc.getProxyKey());259}260261@Override262public double getDefaultScaleX() {263return scaleX;264}265266@Override267public double getDefaultScaleY() {268return scaleY;269}270271@Override272public SurfaceDataProxy makeProxyFor(SurfaceData srcData) {273return D3DSurfaceDataProxy.274createProxy(srcData,275(D3DGraphicsConfig)graphicsDevice.getDefaultConfiguration());276}277278/**279* Creates a SurfaceData object representing the back buffer of a280* double-buffered on-screen Window.281*/282public static D3DSurfaceData createData(WComponentPeer peer, Image image) {283D3DGraphicsConfig gc = getGC(peer);284if (gc == null || !peer.isAccelCapable()) {285return null;286}287BufferCapabilities caps = peer.getBackBufferCaps();288VSyncType vSyncType = VSYNC_DEFAULT;289if (caps instanceof ExtendedBufferCapabilities) {290vSyncType = ((ExtendedBufferCapabilities)caps).getVSync();291}292Rectangle r = peer.getBounds();293BufferCapabilities.FlipContents flip = caps.getFlipContents();294int swapEffect;295if (flip == FlipContents.COPIED) {296swapEffect = SWAP_COPY;297} else if (flip == FlipContents.PRIOR) {298swapEffect = SWAP_FLIP;299} else { // flip == FlipContents.UNDEFINED || .BACKGROUND300swapEffect = SWAP_DISCARD;301}302return new D3DSurfaceData(peer, gc, r.width, r.height,303image, peer.getColorModel(),304peer.getBackBuffersNum(),305swapEffect, vSyncType, FLIP_BACKBUFFER);306}307308/**309* Returns a WINDOW type of surface - a310* swap chain which serves as an on-screen surface,311* handled by the D3DScreenUpdateManager.312*313* Note that the native surface is not initialized314* when the surface is created to avoid using excessive315* resources, and the surface is placed into the lost316* state. It will be restored prior to any rendering317* to it.318*319* @param peer peer for which the onscreen surface is to be created320* @return a D3DWindowSurfaceData (flip chain) surface321*/322public static D3DSurfaceData createData(WComponentPeer peer) {323D3DGraphicsConfig gc = getGC(peer);324if (gc == null || !peer.isAccelCapable()) {325return null;326}327return new D3DWindowSurfaceData(peer, gc);328}329330/**331* Creates a SurfaceData object representing an off-screen buffer (either332* a plain surface or Texture).333*/334public static D3DSurfaceData createData(D3DGraphicsConfig gc,335int width, int height,336ColorModel cm,337Image image, int type)338{339if (type == RT_TEXTURE) {340boolean isOpaque = cm.getTransparency() == Transparency.OPAQUE;341int cap = isOpaque ? CAPS_RT_TEXTURE_OPAQUE : CAPS_RT_TEXTURE_ALPHA;342if (!gc.getD3DDevice().isCapPresent(cap)) {343type = RT_PLAIN;344}345}346D3DSurfaceData ret = null;347try {348ret = new D3DSurfaceData(null, gc, width, height,349image, cm, 0, SWAP_DISCARD, VSYNC_DEFAULT,350type);351} catch (InvalidPipeException ipe) {352// try again - we might have ran out of vram, and rt textures353// could take up more than a plain surface, so it might succeed354if (type == RT_TEXTURE) {355// If a RT_TEXTURE was requested do not attempt to create a356// plain surface. (note that RT_TEXTURE can only be requested357// from a VI so the cast is safe)358if (((SunVolatileImage)image).getForcedAccelSurfaceType() !=359RT_TEXTURE)360{361type = RT_PLAIN;362ret = new D3DSurfaceData(null, gc, width, height,363image, cm, 0, SWAP_DISCARD,364VSYNC_DEFAULT, type);365}366}367}368return ret;369}370371/**372* Returns the appropriate SurfaceType corresponding to the given D3D373* surface type constant (e.g. TEXTURE -> D3DTexture).374*/375private static SurfaceType getCustomSurfaceType(int d3dType) {376switch (d3dType) {377case TEXTURE:378return D3DTexture;379case RT_TEXTURE:380return D3DSurfaceRTT;381default:382return D3DSurface;383}384}385386private boolean initSurfaceNow() {387boolean isOpaque = (getTransparency() == Transparency.OPAQUE);388switch (type) {389case RT_PLAIN:390return initRTSurface(getNativeOps(), isOpaque);391case TEXTURE:392return initTexture(getNativeOps(), false/*isRTT*/, isOpaque);393case RT_TEXTURE:394return initTexture(getNativeOps(), true/*isRTT*/, isOpaque);395// REMIND: we may want to pass the exact type to the native396// level here so that we could choose the right presentation397// interval for the frontbuffer (immediate vs v-synced)398case WINDOW:399case FLIP_BACKBUFFER:400return initFlipBackbuffer(getNativeOps(), peer.getData(),401backBuffersNum, swapEffect,402syncType.id());403default:404return false;405}406}407408/**409* Initializes the appropriate D3D offscreen surface based on the value410* of the type parameter. If the surface creation fails for any reason,411* an OutOfMemoryError will be thrown.412*/413protected void initSurface() {414// any time we create or restore the surface, recreate the raster415synchronized (this) {416wrn = null;417}418// REMIND: somewhere a puppy died419class Status {420boolean success = false;421};422final Status status = new Status();423D3DRenderQueue rq = D3DRenderQueue.getInstance();424rq.lock();425try {426rq.flushAndInvokeNow(new Runnable() {427public void run() {428status.success = initSurfaceNow();429}430});431if (!status.success) {432throw new InvalidPipeException("Error creating D3DSurface");433}434} finally {435rq.unlock();436}437}438439/**440* Returns the D3DContext for the GraphicsConfig associated with this441* surface.442*/443public final D3DContext getContext() {444return graphicsDevice.getContext();445}446447/**448* Returns one of the surface type constants defined above.449*/450public final int getType() {451return type;452}453454private static native int dbGetPixelNative(long pData, int x, int y);455private static native void dbSetPixelNative(long pData, int x, int y,456int pixel);457static class D3DDataBufferNative extends DataBufferNative {458int pixel;459protected D3DDataBufferNative(SurfaceData sData,460int type, int w, int h)461{462super(sData, type, w, h);463}464465protected int getElem(final int x, final int y,466final SurfaceData sData)467{468if (sData.isSurfaceLost()) {469return 0;470}471472int retPixel;473D3DRenderQueue rq = D3DRenderQueue.getInstance();474rq.lock();475try {476rq.flushAndInvokeNow(new Runnable() {477public void run() {478pixel = dbGetPixelNative(sData.getNativeOps(), x, y);479}480});481} finally {482retPixel = pixel;483rq.unlock();484}485return retPixel;486}487488protected void setElem(final int x, final int y, final int pixel,489final SurfaceData sData)490{491if (sData.isSurfaceLost()) {492return;493}494495D3DRenderQueue rq = D3DRenderQueue.getInstance();496rq.lock();497try {498rq.flushAndInvokeNow(new Runnable() {499public void run() {500dbSetPixelNative(sData.getNativeOps(), x, y, pixel);501}502});503sData.markDirty();504} finally {505rq.unlock();506}507}508}509510public synchronized Raster getRaster(int x, int y, int w, int h) {511if (wrn == null) {512DirectColorModel dcm = (DirectColorModel)getColorModel();513SampleModel smHw;514int dataType = 0;515int scanStride = width;516517if (dcm.getPixelSize() > 16) {518dataType = DataBuffer.TYPE_INT;519} else {520// 15, 16521dataType = DataBuffer.TYPE_USHORT;522}523524// note that we have to use the surface width and height here,525// not the passed w,h526smHw = new SinglePixelPackedSampleModel(dataType, width, height,527scanStride, dcm.getMasks());528DataBuffer dbn = new D3DDataBufferNative(this, dataType,529width, height);530wrn = WritableRasterNative.createNativeRaster(smHw, dbn);531}532533return wrn;534}535536/**537* For now, we can only render LCD text if:538* - the pixel shaders are available, and539* - blending is disabled, and540* - the source color is opaque541* - and the destination is opaque542*/543public boolean canRenderLCDText(SunGraphics2D sg2d) {544return545graphicsDevice.isCapPresent(CAPS_LCD_SHADER) &&546sg2d.compositeState <= SunGraphics2D.COMP_ISCOPY &&547sg2d.paintState <= SunGraphics2D.PAINT_OPAQUECOLOR &&548sg2d.surfaceData.getTransparency() == Transparency.OPAQUE;549}550551/**552* If acceleration should no longer be used for this surface.553* This implementation flags to the manager that it should no554* longer attempt to re-create a D3DSurface.555*/556void disableAccelerationForSurface() {557if (offscreenImage != null) {558SurfaceManager sm = SurfaceManager.getManager(offscreenImage);559if (sm instanceof D3DVolatileSurfaceManager) {560setSurfaceLost(true);561((D3DVolatileSurfaceManager)sm).setAccelerationEnabled(false);562}563}564}565566public void validatePipe(SunGraphics2D sg2d) {567TextPipe textpipe;568boolean validated = false;569570// REMIND: the D3D pipeline doesn't support XOR!, more571// fixes will be needed below. For now we disable D3D rendering572// for the surface which had any XOR rendering done to.573if (sg2d.compositeState >= SunGraphics2D.COMP_XOR) {574super.validatePipe(sg2d);575sg2d.imagepipe = d3dImagePipe;576disableAccelerationForSurface();577return;578}579580// D3DTextRenderer handles both AA and non-AA text, but581// only works with the following modes:582// (Note: For LCD text we only enter this code path if583// canRenderLCDText() has already validated that the mode is584// CompositeType.SrcNoEa (opaque color), which will be subsumed585// by the CompositeType.SrcNoEa (any color) test below.)586587if (/* CompositeType.SrcNoEa (any color) */588(sg2d.compositeState <= SunGraphics2D.COMP_ISCOPY &&589sg2d.paintState <= SunGraphics2D.PAINT_ALPHACOLOR) ||590591/* CompositeType.SrcOver (any color) */592(sg2d.compositeState == SunGraphics2D.COMP_ALPHA &&593sg2d.paintState <= SunGraphics2D.PAINT_ALPHACOLOR &&594(((AlphaComposite)sg2d.composite).getRule() ==595AlphaComposite.SRC_OVER)) ||596597/* CompositeType.Xor (any color) */598(sg2d.compositeState == SunGraphics2D.COMP_XOR &&599sg2d.paintState <= SunGraphics2D.PAINT_ALPHACOLOR))600{601textpipe = d3dTextPipe;602} else {603// do this to initialize textpipe correctly; we will attempt604// to override the non-text pipes below605super.validatePipe(sg2d);606textpipe = sg2d.textpipe;607validated = true;608}609610PixelToParallelogramConverter txPipe = null;611D3DRenderer nonTxPipe = null;612613if (sg2d.antialiasHint != SunHints.INTVAL_ANTIALIAS_ON) {614if (sg2d.paintState <= SunGraphics2D.PAINT_ALPHACOLOR) {615if (sg2d.compositeState <= SunGraphics2D.COMP_XOR) {616txPipe = d3dTxRenderPipe;617nonTxPipe = d3dRenderPipe;618}619} else if (sg2d.compositeState <= SunGraphics2D.COMP_ALPHA) {620if (D3DPaints.isValid(sg2d)) {621txPipe = d3dTxRenderPipe;622nonTxPipe = d3dRenderPipe;623}624// custom paints handled by super.validatePipe() below625}626} else {627if (sg2d.paintState <= SunGraphics2D.PAINT_ALPHACOLOR) {628if (graphicsDevice.isCapPresent(CAPS_AA_SHADER) &&629(sg2d.imageComp == CompositeType.SrcOverNoEa ||630sg2d.imageComp == CompositeType.SrcOver))631{632if (!validated) {633super.validatePipe(sg2d);634validated = true;635}636PixelToParallelogramConverter aaConverter =637new PixelToParallelogramConverter(sg2d.shapepipe,638d3dAAPgramPipe,6391.0/8.0, 0.499,640false);641sg2d.drawpipe = aaConverter;642sg2d.fillpipe = aaConverter;643sg2d.shapepipe = aaConverter;644} else if (sg2d.compositeState == SunGraphics2D.COMP_XOR) {645// install the solid pipes when AA and XOR are both enabled646txPipe = d3dTxRenderPipe;647nonTxPipe = d3dRenderPipe;648}649}650// other cases handled by super.validatePipe() below651}652653if (txPipe != null) {654if (sg2d.transformState >= SunGraphics2D.TRANSFORM_TRANSLATESCALE) {655sg2d.drawpipe = txPipe;656sg2d.fillpipe = txPipe;657} else if (sg2d.strokeState != SunGraphics2D.STROKE_THIN) {658sg2d.drawpipe = txPipe;659sg2d.fillpipe = nonTxPipe;660} else {661sg2d.drawpipe = nonTxPipe;662sg2d.fillpipe = nonTxPipe;663}664// Note that we use the transforming pipe here because it665// will examine the shape and possibly perform an optimized666// operation if it can be simplified. The simplifications667// will be valid for all STROKE and TRANSFORM types.668sg2d.shapepipe = txPipe;669} else {670if (!validated) {671super.validatePipe(sg2d);672}673}674675// install the text pipe based on our earlier decision676sg2d.textpipe = textpipe;677678// always override the image pipe with the specialized D3D pipe679sg2d.imagepipe = d3dImagePipe;680}681682@Override683protected MaskFill getMaskFill(SunGraphics2D sg2d) {684if (sg2d.paintState > SunGraphics2D.PAINT_ALPHACOLOR) {685/*686* We can only accelerate non-Color MaskFill operations if687* all of the following conditions hold true:688* - there is an implementation for the given paintState689* - the current Paint can be accelerated for this destination690* - multitexturing is available (since we need to modulate691* the alpha mask texture with the paint texture)692*693* In all other cases, we return null, in which case the694* validation code will choose a more general software-based loop.695*/696if (!D3DPaints.isValid(sg2d) ||697!graphicsDevice.isCapPresent(CAPS_MULTITEXTURE))698{699return null;700}701}702return super.getMaskFill(sg2d);703}704705@Override706public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h,707int dx, int dy) {708if (sg2d.compositeState >= SunGraphics2D.COMP_XOR) {709return false;710}711d3dRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy);712return true;713}714715@Override716public void flush() {717D3DRenderQueue rq = D3DRenderQueue.getInstance();718rq.lock();719try {720RenderBuffer buf = rq.getBuffer();721rq.ensureCapacityAndAlignment(12, 4);722buf.putInt(FLUSH_SURFACE);723buf.putLong(getNativeOps());724725// this call is expected to complete synchronously, so flush now726rq.flushNow();727} finally {728rq.unlock();729}730}731732/**733* Disposes the native resources associated with the given D3DSurfaceData734* (referenced by the pData parameter). This method is invoked from735* the native Dispose() method from the Disposer thread when the736* Java-level D3DSurfaceData object is about to go away.737*/738static void dispose(long pData) {739D3DRenderQueue rq = D3DRenderQueue.getInstance();740rq.lock();741try {742RenderBuffer buf = rq.getBuffer();743rq.ensureCapacityAndAlignment(12, 4);744buf.putInt(DISPOSE_SURFACE);745buf.putLong(pData);746747// this call is expected to complete synchronously, so flush now748rq.flushNow();749} finally {750rq.unlock();751}752}753754static void swapBuffers(D3DSurfaceData sd,755final int x1, final int y1,756final int x2, final int y2)757{758long pData = sd.getNativeOps();759D3DRenderQueue rq = D3DRenderQueue.getInstance();760// swapBuffers can be called from the toolkit thread by swing, we761// should detect this and prevent the deadlocks762if (D3DRenderQueue.isRenderQueueThread()) {763if (!rq.tryLock()) {764// if we could not obtain the lock, repaint the area765// that was supposed to be swapped, and no-op this swap766final Component target = (Component)sd.getPeer().getTarget();767SunToolkit.executeOnEventHandlerThread(target, new Runnable() {768public void run() {769double scaleX = sd.getDefaultScaleX();770double scaleY = sd.getDefaultScaleY();771if (scaleX > 1 || scaleY > 1) {772int sx1 = (int) Math.floor(x1 / scaleX);773int sy1 = (int) Math.floor(y1 / scaleY);774int sx2 = (int) Math.ceil(x2 / scaleX);775int sy2 = (int) Math.ceil(y2 / scaleY);776target.repaint(sx1, sy1, sx2 - sx1, sy2 - sy1);777} else {778target.repaint(x1, y1, x2 - x1, y2 - y1);779}780}781});782return;783}784} else {785rq.lock();786}787try {788RenderBuffer buf = rq.getBuffer();789rq.ensureCapacityAndAlignment(28, 4);790buf.putInt(SWAP_BUFFERS);791buf.putLong(pData);792buf.putInt(x1);793buf.putInt(y1);794buf.putInt(x2);795buf.putInt(y2);796rq.flushNow();797} finally {798rq.unlock();799}800}801802/**803* Returns destination Image associated with this SurfaceData.804*/805public Object getDestination() {806return offscreenImage;807}808809public Rectangle getBounds() {810if (type == FLIP_BACKBUFFER || type == WINDOW) {811double scaleX = getDefaultScaleX();812double scaleY = getDefaultScaleY();813Rectangle r = peer.getBounds();814r.x = r.y = 0;815r.width = Region.clipRound(r.width * scaleX);816r.height = Region.clipRound(r.height * scaleY);817return r;818} else {819return new Rectangle(width, height);820}821}822823public Rectangle getNativeBounds() {824D3DRenderQueue rq = D3DRenderQueue.getInstance();825// need to lock to make sure nativeWidth and Height are consistent826// since they are set from the render thread from the native827// level828rq.lock();829try {830// REMIND: use xyoffsets?831return new Rectangle(nativeWidth, nativeHeight);832} finally {833rq.unlock();834}835}836837838public GraphicsConfiguration getDeviceConfiguration() {839return graphicsDevice.getDefaultConfiguration();840}841842public SurfaceData getReplacement() {843return restoreContents(offscreenImage);844}845846private static D3DGraphicsConfig getGC(WComponentPeer peer) {847GraphicsConfiguration gc;848if (peer != null) {849gc = peer.getGraphicsConfiguration();850} else {851GraphicsEnvironment env =852GraphicsEnvironment.getLocalGraphicsEnvironment();853GraphicsDevice gd = env.getDefaultScreenDevice();854gc = gd.getDefaultConfiguration();855}856return (gc instanceof D3DGraphicsConfig) ? (D3DGraphicsConfig)gc : null;857}858859/**860* Attempts to restore the surface by initializing the native data861*/862void restoreSurface() {863initSurface();864}865866WComponentPeer getPeer() {867return peer;868}869870/**871* We need to let the surface manager know that the surface is lost so872* that for example BufferStrategy.contentsLost() returns correct result.873* Normally the status of contentsLost is set in validate(), but in some874* cases (like Swing's buffer per window) we intentionally don't call875* validate from the toolkit thread but only check for the BS status.876*/877@Override878public void setSurfaceLost(boolean lost) {879super.setSurfaceLost(lost);880if (lost && offscreenImage != null) {881SurfaceManager sm = SurfaceManager.getManager(offscreenImage);882sm.acceleratedSurfaceLost();883}884}885886private static native long getNativeResourceNative(long sdops, int resType);887/**888* Returns a pointer to the native resource of specified {@code resType}889* associated with this surface.890*891* Specifically, for {@code D3DSurfaceData} this method returns pointers of892* the following:893* <pre>894* TEXTURE - (IDirect3DTexture9*)895* RT_TEXTURE, RT_PLAIN - (IDirect3DSurface9*)896* FLIP_BACKBUFFER - (IDirect3DSwapChain9*)897* D3D_DEVICE_RESOURCE - (IDirect3DDevice9*)898* </pre>899*900* Multiple resources may be available for some types (i.e. for render to901* texture one could retrieve both a destination surface by specifying902* RT_TEXTURE, and a texture by using TEXTURE).903*904* Note: the pointer returned by this method is only valid on the rendering905* thread.906*907* @return pointer to the native resource of specified type or 0L if908* such resource doesn't exist or can not be retrieved.909* @see sun.java2d.pipe.hw.AccelSurface#getNativeResource910*/911public long getNativeResource(int resType) {912return getNativeResourceNative(getNativeOps(), resType);913}914915/**916* Class representing an on-screen d3d surface. Since d3d can't917* render to the screen directly, it is implemented as a swap chain,918* controlled by D3DScreenUpdateManager.919*920* @see D3DScreenUpdateManager921*/922public static class D3DWindowSurfaceData extends D3DSurfaceData {923StateTracker dirtyTracker;924925public D3DWindowSurfaceData(WComponentPeer peer,926D3DGraphicsConfig gc)927{928super(peer, gc,929peer.getBounds().width, peer.getBounds().height,930null, peer.getColorModel(), 1, SWAP_COPY, VSYNC_DEFAULT,931WINDOW);932dirtyTracker = getStateTracker();933}934935/**936* {@inheritDoc}937*938* Overridden to use ScreenUpdateManager to obtain the replacement939* surface.940*941* @see sun.java2d.ScreenUpdateManager#getReplacementScreenSurface942*/943@Override944public SurfaceData getReplacement() {945ScreenUpdateManager mgr = ScreenUpdateManager.getInstance();946return mgr.getReplacementScreenSurface(peer, this);947}948949/**950* Returns destination Component associated with this SurfaceData.951*/952@Override953public Object getDestination() {954return peer.getTarget();955}956957@Override958void disableAccelerationForSurface() {959// for on-screen surfaces we need to make sure a backup GDI surface is960// is used until a new one is set (which may happen during a resize). We961// don't want the screen update maanger to replace the surface right way962// because it causes repainting issues in Swing, so we invalidate it,963// this will prevent SUM from issuing a replaceSurfaceData call.964setSurfaceLost(true);965invalidate();966flush();967peer.disableAcceleration();968ScreenUpdateManager.getInstance().dropScreenSurface(this);969}970971@Override972void restoreSurface() {973if (!peer.isAccelCapable()) {974throw new InvalidPipeException("Onscreen acceleration " +975"disabled for this surface");976}977Window fsw = graphicsDevice.getFullScreenWindow();978if (fsw != null && fsw != peer.getTarget()) {979throw new InvalidPipeException("Can't restore onscreen surface"+980" when in full-screen mode");981}982super.restoreSurface();983// if initialization was unsuccessful, an IPE will be thrown984// and the surface will remain lost985setSurfaceLost(false);986987// This is to make sure the render target is reset after this988// surface is restored. The reason for this is that sometimes this989// surface can be restored from multiple threads (the screen update990// manager's thread and app's rendering thread) at the same time,991// and when that happens the second restoration will create the992// native resource which will not be set as render target because993// the BufferedContext's validate method will think that since the994// surface data object didn't change then the current render target995// is correct and no rendering will appear on the screen.996D3DRenderQueue rq = D3DRenderQueue.getInstance();997rq.lock();998try {999getContext().invalidateContext();1000} finally {1001rq.unlock();1002}1003}10041005public boolean isDirty() {1006return !dirtyTracker.isCurrent();1007}10081009public void markClean() {1010dirtyTracker = getStateTracker();1011}1012}10131014/**1015* Updates the layered window with the contents of the surface.1016*1017* @param pd3dsd pointer to the D3DSDOps structure1018* @param pData pointer to the AwtWindow peer data1019* @param w width of the window1020* @param h height of the window1021* @see sun.awt.windows.TranslucentWindowPainter1022*/1023public static native boolean updateWindowAccelImpl(long pd3dsd, long pData,1024int w, int h);1025}102610271028