device9.c revision ea3f504f7caf9900f71a52f1711baf8a50fec490
1/*
2 * Copyright 2011 Joakim Sindholt <opensource@zhasha.com>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * on the rights to use, copy, modify, merge, publish, distribute, sub
8 * license, and/or sell copies of the Software, and to permit persons to whom
9 * the Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21 * USE OR OTHER DEALINGS IN THE SOFTWARE. */
22
23#include "device9.h"
24#include "stateblock9.h"
25#include "surface9.h"
26#include "swapchain9.h"
27#include "swapchain9ex.h"
28#include "indexbuffer9.h"
29#include "vertexbuffer9.h"
30#include "vertexdeclaration9.h"
31#include "vertexshader9.h"
32#include "pixelshader9.h"
33#include "query9.h"
34#include "texture9.h"
35#include "cubetexture9.h"
36#include "volumetexture9.h"
37#include "nine_helpers.h"
38#include "nine_pipe.h"
39#include "nine_ff.h"
40#include "nine_dump.h"
41
42#include "pipe/p_screen.h"
43#include "pipe/p_context.h"
44#include "pipe/p_config.h"
45#include "util/u_math.h"
46#include "util/u_inlines.h"
47#include "util/u_hash_table.h"
48#include "util/u_format.h"
49#include "util/u_surface.h"
50#include "util/u_upload_mgr.h"
51#include "hud/hud_context.h"
52
53#include "cso_cache/cso_context.h"
54
55#define DBG_CHANNEL DBG_DEVICE
56
57#if defined(PIPE_CC_GCC) && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64))
58
59#include <fpu_control.h>
60
61static void nine_setup_fpu()
62{
63    fpu_control_t c;
64
65    _FPU_GETCW(c);
66    /* clear the control word */
67    c &= _FPU_RESERVED;
68    /* d3d9 doc/wine tests: mask all exceptions, use single-precision
69     * and round to nearest */
70    c |= _FPU_MASK_IM | _FPU_MASK_DM | _FPU_MASK_ZM | _FPU_MASK_OM |
71         _FPU_MASK_UM | _FPU_MASK_PM | _FPU_SINGLE | _FPU_RC_NEAREST;
72    _FPU_SETCW(c);
73}
74
75#else
76
77static void nine_setup_fpu(void)
78{
79    WARN_ONCE("FPU setup not supported on non-x86 platforms\n");
80}
81
82#endif
83
84static void
85NineDevice9_SetDefaultState( struct NineDevice9 *This, boolean is_reset )
86{
87    struct NineSurface9 *refSurf = NULL;
88
89    DBG("This=%p is_reset=%d\n", This, (int) is_reset);
90
91    assert(!This->is_recording);
92
93    nine_state_set_defaults(This, &This->caps, is_reset);
94
95    This->state.viewport.X = 0;
96    This->state.viewport.Y = 0;
97    This->state.viewport.Width = 0;
98    This->state.viewport.Height = 0;
99
100    This->state.scissor.minx = 0;
101    This->state.scissor.miny = 0;
102    This->state.scissor.maxx = 0xffff;
103    This->state.scissor.maxy = 0xffff;
104
105    if (This->nswapchains && This->swapchains[0]->params.BackBufferCount)
106        refSurf = This->swapchains[0]->buffers[0];
107
108    if (refSurf) {
109        This->state.viewport.Width = refSurf->desc.Width;
110        This->state.viewport.Height = refSurf->desc.Height;
111        This->state.scissor.maxx = refSurf->desc.Width;
112        This->state.scissor.maxy = refSurf->desc.Height;
113    }
114
115    if (This->nswapchains && This->swapchains[0]->params.EnableAutoDepthStencil)
116        This->state.rs[D3DRS_ZENABLE] = TRUE;
117    if (This->state.rs[D3DRS_ZENABLE])
118        NineDevice9_SetDepthStencilSurface(
119            This, (IDirect3DSurface9 *)This->swapchains[0]->zsbuf);
120}
121
122#define GET_PCAP(n) pScreen->get_param(pScreen, PIPE_CAP_##n)
123HRESULT
124NineDevice9_ctor( struct NineDevice9 *This,
125                  struct NineUnknownParams *pParams,
126                  struct pipe_screen *pScreen,
127                  D3DDEVICE_CREATION_PARAMETERS *pCreationParameters,
128                  D3DCAPS9 *pCaps,
129                  D3DPRESENT_PARAMETERS *pPresentationParameters,
130                  IDirect3D9 *pD3D9,
131                  ID3DPresentGroup *pPresentationGroup,
132                  struct d3dadapter9_context *pCTX,
133                  boolean ex,
134                  D3DDISPLAYMODEEX *pFullscreenDisplayMode )
135{
136    unsigned i;
137    HRESULT hr = NineUnknown_ctor(&This->base, pParams);
138
139    DBG("This=%p pParams=%p pScreen=%p pCreationParameters=%p pCaps=%p pPresentationParameters=%p "
140        "pD3D9=%p pPresentationGroup=%p pCTX=%p ex=%d pFullscreenDisplayMode=%p\n",
141        This, pParams, pScreen, pCreationParameters, pCaps, pPresentationParameters, pD3D9,
142        pPresentationGroup, pCTX, (int) ex, pFullscreenDisplayMode);
143
144    if (FAILED(hr)) { return hr; }
145
146    list_inithead(&This->update_textures);
147    list_inithead(&This->managed_textures);
148
149    This->screen = pScreen;
150    This->caps = *pCaps;
151    This->d3d9 = pD3D9;
152    This->params = *pCreationParameters;
153    This->ex = ex;
154    This->present = pPresentationGroup;
155    IDirect3D9_AddRef(This->d3d9);
156    ID3DPresentGroup_AddRef(This->present);
157
158    if (!(This->params.BehaviorFlags & D3DCREATE_FPU_PRESERVE))
159        nine_setup_fpu();
160
161    if (This->params.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING)
162        DBG("Application asked full Software Vertex Processing. Ignoring.\n");
163    if (This->params.BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING)
164        DBG("Application asked mixed Software Vertex Processing. Ignoring.\n");
165
166    This->pipe = This->screen->context_create(This->screen, NULL, 0);
167    if (!This->pipe) { return E_OUTOFMEMORY; } /* guess */
168
169    This->cso = cso_create_context(This->pipe);
170    if (!This->cso) { return E_OUTOFMEMORY; } /* also a guess */
171
172    /* Create first, it messes up our state. */
173    This->hud = hud_create(This->pipe, This->cso); /* NULL result is fine */
174
175    /* create implicit swapchains */
176    This->nswapchains = ID3DPresentGroup_GetMultiheadCount(This->present);
177    This->swapchains = CALLOC(This->nswapchains,
178                              sizeof(struct NineSwapChain9 *));
179    if (!This->swapchains) { return E_OUTOFMEMORY; }
180
181    for (i = 0; i < This->nswapchains; ++i) {
182        ID3DPresent *present;
183
184        hr = ID3DPresentGroup_GetPresent(This->present, i, &present);
185        if (FAILED(hr))
186            return hr;
187
188        if (ex) {
189            D3DDISPLAYMODEEX *mode = NULL;
190            struct NineSwapChain9Ex **ret =
191                (struct NineSwapChain9Ex **)&This->swapchains[i];
192
193            if (pFullscreenDisplayMode) mode = &(pFullscreenDisplayMode[i]);
194            /* when this is a Device9Ex, it should create SwapChain9Exs */
195            hr = NineSwapChain9Ex_new(This, TRUE, present,
196                                      &pPresentationParameters[i], pCTX,
197                                      This->params.hFocusWindow, mode, ret);
198        } else {
199            hr = NineSwapChain9_new(This, TRUE, present,
200                                    &pPresentationParameters[i], pCTX,
201                                    This->params.hFocusWindow,
202                                    &This->swapchains[i]);
203        }
204
205        ID3DPresent_Release(present);
206        if (FAILED(hr))
207            return hr;
208        NineUnknown_ConvertRefToBind(NineUnknown(This->swapchains[i]));
209
210        hr = NineSwapChain9_GetBackBuffer(This->swapchains[i], 0,
211                                          D3DBACKBUFFER_TYPE_MONO,
212                                          (IDirect3DSurface9 **)
213                                          &This->state.rt[i]);
214        if (FAILED(hr))
215            return hr;
216        NineUnknown_ConvertRefToBind(NineUnknown(This->state.rt[i]));
217    }
218
219    /* Initialize a dummy VBO to be used when a a vertex declaration does not
220     * specify all the inputs needed by vertex shader, on win default behavior
221     * is to pass 0,0,0,0 to the shader */
222    {
223        struct pipe_transfer *transfer;
224        struct pipe_resource tmpl;
225        struct pipe_box box;
226        unsigned char *data;
227
228        tmpl.target = PIPE_BUFFER;
229        tmpl.format = PIPE_FORMAT_R8_UNORM;
230        tmpl.width0 = 16; /* 4 floats */
231        tmpl.height0 = 1;
232        tmpl.depth0 = 1;
233        tmpl.array_size = 1;
234        tmpl.last_level = 0;
235        tmpl.nr_samples = 0;
236        tmpl.usage = PIPE_USAGE_DEFAULT;
237        tmpl.bind = PIPE_BIND_VERTEX_BUFFER | PIPE_BIND_TRANSFER_WRITE;
238        tmpl.flags = 0;
239        This->dummy_vbo = pScreen->resource_create(pScreen, &tmpl);
240
241        if (!This->dummy_vbo)
242            return D3DERR_OUTOFVIDEOMEMORY;
243
244        u_box_1d(0, 16, &box);
245        data = This->pipe->transfer_map(This->pipe, This->dummy_vbo, 0,
246                                        PIPE_TRANSFER_WRITE |
247                                        PIPE_TRANSFER_DISCARD_WHOLE_RESOURCE,
248                                        &box, &transfer);
249        assert(data);
250        assert(transfer);
251        memset(data, 0, 16);
252        This->pipe->transfer_unmap(This->pipe, transfer);
253    }
254
255    This->cursor.software = FALSE;
256    This->cursor.hotspot.x = -1;
257    This->cursor.hotspot.y = -1;
258    {
259        struct pipe_resource tmpl;
260        tmpl.target = PIPE_TEXTURE_2D;
261        tmpl.format = PIPE_FORMAT_R8G8B8A8_UNORM;
262        tmpl.width0 = 64;
263        tmpl.height0 = 64;
264        tmpl.depth0 = 1;
265        tmpl.array_size = 1;
266        tmpl.last_level = 0;
267        tmpl.nr_samples = 0;
268        tmpl.usage = PIPE_USAGE_DEFAULT;
269        tmpl.bind = PIPE_BIND_CURSOR | PIPE_BIND_SAMPLER_VIEW;
270        tmpl.flags = 0;
271
272        This->cursor.image = pScreen->resource_create(pScreen, &tmpl);
273        if (!This->cursor.image)
274            return D3DERR_OUTOFVIDEOMEMORY;
275    }
276
277    /* Create constant buffers. */
278    {
279        struct pipe_resource tmpl;
280        unsigned max_const_vs, max_const_ps;
281
282        /* vs 3.0: >= 256 float constants, but for cards with exactly 256 slots,
283         * we have to take in some more slots for int and bool*/
284        max_const_vs = _min(pScreen->get_shader_param(pScreen, PIPE_SHADER_VERTEX,
285                                PIPE_SHADER_CAP_MAX_CONST_BUFFER_SIZE) /
286                                sizeof(float[4]),
287                            NINE_MAX_CONST_ALL);
288        /* ps 3.0: 224 float constants. All cards supported support at least
289         * 256 constants for ps */
290        max_const_ps = NINE_MAX_CONST_F_PS3 + (NINE_MAX_CONST_I + NINE_MAX_CONST_B / 4);
291
292        This->max_vs_const_f = max_const_vs -
293                               (NINE_MAX_CONST_I + NINE_MAX_CONST_B / 4);
294        This->max_ps_const_f = max_const_ps -
295                               (NINE_MAX_CONST_I + NINE_MAX_CONST_B / 4);
296
297        This->vs_const_size = max_const_vs * sizeof(float[4]);
298        This->ps_const_size = max_const_ps * sizeof(float[4]);
299        /* Include space for I,B constants for user constbuf. */
300        This->state.vs_const_f = CALLOC(This->vs_const_size, 1);
301        This->state.ps_const_f = CALLOC(This->ps_const_size, 1);
302        This->state.vs_lconstf_temp = CALLOC(This->vs_const_size,1);
303        This->state.ps_lconstf_temp = CALLOC(This->ps_const_size,1);
304        if (!This->state.vs_const_f || !This->state.ps_const_f ||
305            !This->state.vs_lconstf_temp || !This->state.ps_lconstf_temp)
306            return E_OUTOFMEMORY;
307
308        if (strstr(pScreen->get_name(pScreen), "AMD") ||
309            strstr(pScreen->get_name(pScreen), "ATI")) {
310            This->driver_bugs.buggy_barycentrics = TRUE;
311        }
312
313        /* Disable NV path for now, needs some fixes */
314        This->prefer_user_constbuf = TRUE;
315
316        tmpl.target = PIPE_BUFFER;
317        tmpl.format = PIPE_FORMAT_R8_UNORM;
318        tmpl.height0 = 1;
319        tmpl.depth0 = 1;
320        tmpl.array_size = 1;
321        tmpl.last_level = 0;
322        tmpl.nr_samples = 0;
323        tmpl.usage = PIPE_USAGE_DYNAMIC;
324        tmpl.bind = PIPE_BIND_CONSTANT_BUFFER;
325        tmpl.flags = 0;
326
327        tmpl.width0 = This->vs_const_size;
328        This->constbuf_vs = pScreen->resource_create(pScreen, &tmpl);
329
330        tmpl.width0 = This->ps_const_size;
331        This->constbuf_ps = pScreen->resource_create(pScreen, &tmpl);
332
333        if (!This->constbuf_vs || !This->constbuf_ps)
334            return E_OUTOFMEMORY;
335    }
336
337    /* allocate dummy texture/sampler for when there are missing ones bound */
338    {
339        struct pipe_resource tmplt;
340        struct pipe_sampler_view templ;
341        struct pipe_sampler_state samp;
342        memset(&samp, 0, sizeof(samp));
343
344        tmplt.target = PIPE_TEXTURE_2D;
345        tmplt.width0 = 1;
346        tmplt.height0 = 1;
347        tmplt.depth0 = 1;
348        tmplt.last_level = 0;
349        tmplt.array_size = 1;
350        tmplt.usage = PIPE_USAGE_DEFAULT;
351        tmplt.flags = 0;
352        tmplt.format = PIPE_FORMAT_B8G8R8A8_UNORM;
353        tmplt.bind = PIPE_BIND_SAMPLER_VIEW;
354        tmplt.nr_samples = 0;
355
356        This->dummy_texture = This->screen->resource_create(This->screen, &tmplt);
357        if (!This->dummy_texture)
358            return D3DERR_DRIVERINTERNALERROR;
359
360        templ.format = PIPE_FORMAT_B8G8R8A8_UNORM;
361        templ.u.tex.first_layer = 0;
362        templ.u.tex.last_layer = 0;
363        templ.u.tex.first_level = 0;
364        templ.u.tex.last_level = 0;
365        templ.swizzle_r = PIPE_SWIZZLE_ZERO;
366        templ.swizzle_g = PIPE_SWIZZLE_ZERO;
367        templ.swizzle_b = PIPE_SWIZZLE_ZERO;
368        templ.swizzle_a = PIPE_SWIZZLE_ONE;
369        templ.target = This->dummy_texture->target;
370
371        This->dummy_sampler_view = This->pipe->create_sampler_view(This->pipe, This->dummy_texture, &templ);
372        if (!This->dummy_sampler_view)
373            return D3DERR_DRIVERINTERNALERROR;
374
375        samp.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
376        samp.max_lod = 15.0f;
377        samp.wrap_s = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
378        samp.wrap_t = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
379        samp.wrap_r = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
380        samp.min_img_filter = PIPE_TEX_FILTER_NEAREST;
381        samp.mag_img_filter = PIPE_TEX_FILTER_NEAREST;
382        samp.compare_mode = PIPE_TEX_COMPARE_NONE;
383        samp.compare_func = PIPE_FUNC_LEQUAL;
384        samp.normalized_coords = 1;
385        samp.seamless_cube_map = 1;
386        This->dummy_sampler_state = samp;
387    }
388
389    /* Allocate upload helper for drivers that suck (from st pov ;). */
390
391    This->driver_caps.user_vbufs = GET_PCAP(USER_VERTEX_BUFFERS);
392    This->driver_caps.user_ibufs = GET_PCAP(USER_INDEX_BUFFERS);
393    This->driver_caps.user_cbufs = GET_PCAP(USER_CONSTANT_BUFFERS);
394
395    if (!This->driver_caps.user_vbufs)
396        This->vertex_uploader = u_upload_create(This->pipe, 65536,
397                                                PIPE_BIND_VERTEX_BUFFER, PIPE_USAGE_STREAM);
398    if (!This->driver_caps.user_ibufs)
399        This->index_uploader = u_upload_create(This->pipe, 128 * 1024,
400                                               PIPE_BIND_INDEX_BUFFER, PIPE_USAGE_STREAM);
401    if (!This->driver_caps.user_cbufs) {
402        This->constbuf_alignment = GET_PCAP(CONSTANT_BUFFER_OFFSET_ALIGNMENT);
403        This->constbuf_uploader = u_upload_create(This->pipe, This->vs_const_size,
404                                                  PIPE_BIND_CONSTANT_BUFFER, PIPE_USAGE_STREAM);
405    }
406
407    This->driver_caps.window_space_position_support = GET_PCAP(TGSI_VS_WINDOW_SPACE_POSITION);
408    This->driver_caps.vs_integer = pScreen->get_shader_param(pScreen, PIPE_SHADER_VERTEX, PIPE_SHADER_CAP_INTEGERS);
409    This->driver_caps.ps_integer = pScreen->get_shader_param(pScreen, PIPE_SHADER_FRAGMENT, PIPE_SHADER_CAP_INTEGERS);
410
411    nine_ff_init(This); /* initialize fixed function code */
412
413    NineDevice9_SetDefaultState(This, FALSE);
414
415    {
416        struct pipe_poly_stipple stipple;
417        memset(&stipple, ~0, sizeof(stipple));
418        This->pipe->set_polygon_stipple(This->pipe, &stipple);
419    }
420
421    This->update = &This->state;
422    nine_update_state(This);
423
424    ID3DPresentGroup_Release(This->present);
425
426    return D3D_OK;
427}
428#undef GET_PCAP
429
430void
431NineDevice9_dtor( struct NineDevice9 *This )
432{
433    unsigned i;
434
435    DBG("This=%p\n", This);
436
437    if (This->pipe && This->cso)
438        nine_pipe_context_clear(This);
439    nine_ff_fini(This);
440    nine_state_clear(&This->state, TRUE);
441
442    if (This->vertex_uploader)
443        u_upload_destroy(This->vertex_uploader);
444    if (This->index_uploader)
445        u_upload_destroy(This->index_uploader);
446    if (This->constbuf_uploader)
447        u_upload_destroy(This->constbuf_uploader);
448
449    nine_bind(&This->record, NULL);
450
451    pipe_sampler_view_reference(&This->dummy_sampler_view, NULL);
452    pipe_resource_reference(&This->dummy_texture, NULL);
453    pipe_resource_reference(&This->constbuf_vs, NULL);
454    pipe_resource_reference(&This->constbuf_ps, NULL);
455    pipe_resource_reference(&This->dummy_vbo, NULL);
456    FREE(This->state.vs_const_f);
457    FREE(This->state.ps_const_f);
458    FREE(This->state.vs_lconstf_temp);
459    FREE(This->state.ps_lconstf_temp);
460
461    if (This->swapchains) {
462        for (i = 0; i < This->nswapchains; ++i)
463            NineUnknown_Unbind(NineUnknown(This->swapchains[i]));
464        FREE(This->swapchains);
465    }
466
467    /* state stuff */
468    if (This->pipe) {
469        if (This->cso) {
470            cso_destroy_context(This->cso);
471        }
472        if (This->pipe->destroy) { This->pipe->destroy(This->pipe); }
473    }
474
475    if (This->present) { ID3DPresentGroup_Release(This->present); }
476    if (This->d3d9) { IDirect3D9_Release(This->d3d9); }
477
478    NineUnknown_dtor(&This->base);
479}
480
481struct pipe_screen *
482NineDevice9_GetScreen( struct NineDevice9 *This )
483{
484    return This->screen;
485}
486
487struct pipe_context *
488NineDevice9_GetPipe( struct NineDevice9 *This )
489{
490    return This->pipe;
491}
492
493struct cso_context *
494NineDevice9_GetCSO( struct NineDevice9 *This )
495{
496    return This->cso;
497}
498
499const D3DCAPS9 *
500NineDevice9_GetCaps( struct NineDevice9 *This )
501{
502    return &This->caps;
503}
504
505static inline void
506NineDevice9_PauseRecording( struct NineDevice9 *This )
507{
508    if (This->record) {
509        This->update = &This->state;
510        This->is_recording = FALSE;
511    }
512}
513
514static inline void
515NineDevice9_ResumeRecording( struct NineDevice9 *This )
516{
517    if (This->record) {
518        This->update = &This->record->state;
519        This->is_recording = TRUE;
520    }
521}
522
523HRESULT WINAPI
524NineDevice9_TestCooperativeLevel( struct NineDevice9 *This )
525{
526    return D3D_OK; /* TODO */
527}
528
529UINT WINAPI
530NineDevice9_GetAvailableTextureMem( struct NineDevice9 *This )
531{
532   const unsigned mem = This->screen->get_param(This->screen, PIPE_CAP_VIDEO_MEMORY);
533   if (mem < 4096)
534      return mem << 20;
535   else
536      return UINT_MAX;
537}
538
539HRESULT WINAPI
540NineDevice9_EvictManagedResources( struct NineDevice9 *This )
541{
542    struct NineBaseTexture9 *tex;
543
544    DBG("This=%p\n", This);
545    LIST_FOR_EACH_ENTRY(tex, &This->managed_textures, list2) {
546        NineBaseTexture9_UnLoad(tex);
547    }
548
549    return D3D_OK;
550}
551
552HRESULT WINAPI
553NineDevice9_GetDirect3D( struct NineDevice9 *This,
554                         IDirect3D9 **ppD3D9 )
555{
556    user_assert(ppD3D9 != NULL, E_POINTER);
557    IDirect3D9_AddRef(This->d3d9);
558    *ppD3D9 = This->d3d9;
559    return D3D_OK;
560}
561
562HRESULT WINAPI
563NineDevice9_GetDeviceCaps( struct NineDevice9 *This,
564                           D3DCAPS9 *pCaps )
565{
566    user_assert(pCaps != NULL, D3DERR_INVALIDCALL);
567    *pCaps = This->caps;
568    return D3D_OK;
569}
570
571HRESULT WINAPI
572NineDevice9_GetDisplayMode( struct NineDevice9 *This,
573                            UINT iSwapChain,
574                            D3DDISPLAYMODE *pMode )
575{
576    DBG("This=%p iSwapChain=%u pMode=%p\n", This, iSwapChain, pMode);
577
578    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
579
580    return NineSwapChain9_GetDisplayMode(This->swapchains[iSwapChain], pMode);
581}
582
583HRESULT WINAPI
584NineDevice9_GetCreationParameters( struct NineDevice9 *This,
585                                   D3DDEVICE_CREATION_PARAMETERS *pParameters )
586{
587    user_assert(pParameters != NULL, D3DERR_INVALIDCALL);
588    *pParameters = This->params;
589    return D3D_OK;
590}
591
592HRESULT WINAPI
593NineDevice9_SetCursorProperties( struct NineDevice9 *This,
594                                 UINT XHotSpot,
595                                 UINT YHotSpot,
596                                 IDirect3DSurface9 *pCursorBitmap )
597{
598    struct NineSurface9 *surf = NineSurface9(pCursorBitmap);
599    struct pipe_context *pipe = This->pipe;
600    struct pipe_box box;
601    struct pipe_transfer *transfer;
602    BOOL hw_cursor;
603    void *ptr;
604
605    DBG_FLAG(DBG_SWAPCHAIN, "This=%p XHotSpot=%u YHotSpot=%u "
606             "pCursorBitmap=%p\n", This, XHotSpot, YHotSpot, pCursorBitmap);
607
608    user_assert(pCursorBitmap, D3DERR_INVALIDCALL);
609
610    if (This->swapchains[0]->params.Windowed) {
611        This->cursor.w = MIN2(surf->desc.Width, 32);
612        This->cursor.h = MIN2(surf->desc.Height, 32);
613        hw_cursor = 1; /* always use hw cursor for windowed mode */
614    } else {
615        This->cursor.w = MIN2(surf->desc.Width, This->cursor.image->width0);
616        This->cursor.h = MIN2(surf->desc.Height, This->cursor.image->height0);
617        hw_cursor = This->cursor.w == 32 && This->cursor.h == 32;
618    }
619
620    u_box_origin_2d(This->cursor.w, This->cursor.h, &box);
621
622    ptr = pipe->transfer_map(pipe, This->cursor.image, 0,
623                             PIPE_TRANSFER_WRITE |
624                             PIPE_TRANSFER_DISCARD_WHOLE_RESOURCE,
625                             &box, &transfer);
626    if (!ptr)
627        ret_err("Failed to update cursor image.\n", D3DERR_DRIVERINTERNALERROR);
628
629    This->cursor.hotspot.x = XHotSpot;
630    This->cursor.hotspot.y = YHotSpot;
631
632    /* Copy cursor image to internal storage. */
633    {
634        D3DLOCKED_RECT lock;
635        HRESULT hr;
636        const struct util_format_description *sfmt =
637            util_format_description(surf->base.info.format);
638        assert(sfmt);
639
640        hr = NineSurface9_LockRect(surf, &lock, NULL, D3DLOCK_READONLY);
641        if (FAILED(hr))
642            ret_err("Failed to map cursor source image.\n",
643                    D3DERR_DRIVERINTERNALERROR);
644
645        sfmt->unpack_rgba_8unorm(ptr, transfer->stride,
646                                 lock.pBits, lock.Pitch,
647                                 This->cursor.w, This->cursor.h);
648
649        if (hw_cursor)
650            hw_cursor = ID3DPresent_SetCursor(This->swapchains[0]->present,
651                                              lock.pBits,
652                                              &This->cursor.hotspot,
653                                              This->cursor.visible) == D3D_OK;
654
655        NineSurface9_UnlockRect(surf);
656    }
657    pipe->transfer_unmap(pipe, transfer);
658
659    /* hide cursor if we emulate it */
660    if (!hw_cursor)
661        ID3DPresent_SetCursor(This->swapchains[0]->present, NULL, NULL, FALSE);
662    This->cursor.software = !hw_cursor;
663
664    return D3D_OK;
665}
666
667void WINAPI
668NineDevice9_SetCursorPosition( struct NineDevice9 *This,
669                               int X,
670                               int Y,
671                               DWORD Flags )
672{
673    struct NineSwapChain9 *swap = This->swapchains[0];
674
675    DBG("This=%p X=%d Y=%d Flags=%d\n", This, X, Y, Flags);
676
677    This->cursor.pos.x = X;
678    This->cursor.pos.y = Y;
679
680    if (!This->cursor.software)
681        This->cursor.software = ID3DPresent_SetCursorPos(swap->present, &This->cursor.pos) != D3D_OK;
682}
683
684BOOL WINAPI
685NineDevice9_ShowCursor( struct NineDevice9 *This,
686                        BOOL bShow )
687{
688    BOOL old = This->cursor.visible;
689
690    DBG("This=%p bShow=%d\n", This, (int) bShow);
691
692    This->cursor.visible = bShow && (This->cursor.hotspot.x != -1);
693    if (!This->cursor.software)
694        This->cursor.software = ID3DPresent_SetCursor(This->swapchains[0]->present, NULL, NULL, bShow) != D3D_OK;
695
696    return old;
697}
698
699HRESULT WINAPI
700NineDevice9_CreateAdditionalSwapChain( struct NineDevice9 *This,
701                                       D3DPRESENT_PARAMETERS *pPresentationParameters,
702                                       IDirect3DSwapChain9 **pSwapChain )
703{
704    struct NineSwapChain9 *swapchain, *tmplt = This->swapchains[0];
705    ID3DPresent *present;
706    HRESULT hr;
707
708    DBG("This=%p pPresentationParameters=%p pSwapChain=%p\n",
709        This, pPresentationParameters, pSwapChain);
710
711    user_assert(pPresentationParameters, D3DERR_INVALIDCALL);
712
713    hr = ID3DPresentGroup_CreateAdditionalPresent(This->present, pPresentationParameters, &present);
714
715    if (FAILED(hr))
716        return hr;
717
718    hr = NineSwapChain9_new(This, FALSE, present, pPresentationParameters,
719                            tmplt->actx,
720                            tmplt->params.hDeviceWindow,
721                            &swapchain);
722    if (FAILED(hr))
723        return hr;
724
725    *pSwapChain = (IDirect3DSwapChain9 *)swapchain;
726    return D3D_OK;
727}
728
729HRESULT WINAPI
730NineDevice9_GetSwapChain( struct NineDevice9 *This,
731                          UINT iSwapChain,
732                          IDirect3DSwapChain9 **pSwapChain )
733{
734    user_assert(pSwapChain != NULL, D3DERR_INVALIDCALL);
735
736    *pSwapChain = NULL;
737    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
738
739    NineUnknown_AddRef(NineUnknown(This->swapchains[iSwapChain]));
740    *pSwapChain = (IDirect3DSwapChain9 *)This->swapchains[iSwapChain];
741
742    return D3D_OK;
743}
744
745UINT WINAPI
746NineDevice9_GetNumberOfSwapChains( struct NineDevice9 *This )
747{
748    return This->nswapchains;
749}
750
751HRESULT WINAPI
752NineDevice9_Reset( struct NineDevice9 *This,
753                   D3DPRESENT_PARAMETERS *pPresentationParameters )
754{
755    HRESULT hr = D3D_OK;
756    unsigned i;
757
758    DBG("This=%p pPresentationParameters=%p\n", This, pPresentationParameters);
759
760    for (i = 0; i < This->nswapchains; ++i) {
761        D3DPRESENT_PARAMETERS *params = &pPresentationParameters[i];
762        hr = NineSwapChain9_Resize(This->swapchains[i], params, NULL);
763        if (hr != D3D_OK)
764            return hr;
765    }
766
767    nine_pipe_context_clear(This);
768    nine_state_clear(&This->state, TRUE);
769
770    NineDevice9_SetDefaultState(This, TRUE);
771    NineDevice9_SetRenderTarget(
772        This, 0, (IDirect3DSurface9 *)This->swapchains[0]->buffers[0]);
773    /* XXX: better use GetBackBuffer here ? */
774
775    return hr;
776}
777
778HRESULT WINAPI
779NineDevice9_Present( struct NineDevice9 *This,
780                     const RECT *pSourceRect,
781                     const RECT *pDestRect,
782                     HWND hDestWindowOverride,
783                     const RGNDATA *pDirtyRegion )
784{
785    unsigned i;
786    HRESULT hr;
787
788    DBG("This=%p pSourceRect=%p pDestRect=%p hDestWindowOverride=%p pDirtyRegion=%p\n",
789        This, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
790
791    /* XXX is this right? */
792    for (i = 0; i < This->nswapchains; ++i) {
793        hr = NineSwapChain9_Present(This->swapchains[i], pSourceRect, pDestRect,
794                                    hDestWindowOverride, pDirtyRegion, 0);
795        if (FAILED(hr)) { return hr; }
796    }
797
798    return D3D_OK;
799}
800
801HRESULT WINAPI
802NineDevice9_GetBackBuffer( struct NineDevice9 *This,
803                           UINT iSwapChain,
804                           UINT iBackBuffer,
805                           D3DBACKBUFFER_TYPE Type,
806                           IDirect3DSurface9 **ppBackBuffer )
807{
808    user_assert(ppBackBuffer != NULL, D3DERR_INVALIDCALL);
809    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
810
811    return NineSwapChain9_GetBackBuffer(This->swapchains[iSwapChain],
812                                        iBackBuffer, Type, ppBackBuffer);
813}
814
815HRESULT WINAPI
816NineDevice9_GetRasterStatus( struct NineDevice9 *This,
817                             UINT iSwapChain,
818                             D3DRASTER_STATUS *pRasterStatus )
819{
820    user_assert(pRasterStatus != NULL, D3DERR_INVALIDCALL);
821    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
822
823    return NineSwapChain9_GetRasterStatus(This->swapchains[iSwapChain],
824                                          pRasterStatus);
825}
826
827HRESULT WINAPI
828NineDevice9_SetDialogBoxMode( struct NineDevice9 *This,
829                              BOOL bEnableDialogs )
830{
831    STUB(D3DERR_INVALIDCALL);
832}
833
834void WINAPI
835NineDevice9_SetGammaRamp( struct NineDevice9 *This,
836                          UINT iSwapChain,
837                          DWORD Flags,
838                          const D3DGAMMARAMP *pRamp )
839{
840    DBG("This=%p iSwapChain=%u Flags=%x pRamp=%p\n", This,
841        iSwapChain, Flags, pRamp);
842
843    user_warn(iSwapChain >= This->nswapchains);
844    user_warn(!pRamp);
845
846    if (pRamp && (iSwapChain < This->nswapchains)) {
847        struct NineSwapChain9 *swap = This->swapchains[iSwapChain];
848        swap->gamma = *pRamp;
849        ID3DPresent_SetGammaRamp(swap->present, pRamp, swap->params.hDeviceWindow);
850    }
851}
852
853void WINAPI
854NineDevice9_GetGammaRamp( struct NineDevice9 *This,
855                          UINT iSwapChain,
856                          D3DGAMMARAMP *pRamp )
857{
858    DBG("This=%p iSwapChain=%u pRamp=%p\n", This, iSwapChain, pRamp);
859
860    user_warn(iSwapChain >= This->nswapchains);
861    user_warn(!pRamp);
862
863    if (pRamp && (iSwapChain < This->nswapchains))
864        *pRamp = This->swapchains[iSwapChain]->gamma;
865}
866
867HRESULT WINAPI
868NineDevice9_CreateTexture( struct NineDevice9 *This,
869                           UINT Width,
870                           UINT Height,
871                           UINT Levels,
872                           DWORD Usage,
873                           D3DFORMAT Format,
874                           D3DPOOL Pool,
875                           IDirect3DTexture9 **ppTexture,
876                           HANDLE *pSharedHandle )
877{
878    struct NineTexture9 *tex;
879    HRESULT hr;
880
881    DBG("This=%p Width=%u Height=%u Levels=%u Usage=%s Format=%s Pool=%s "
882        "ppOut=%p pSharedHandle=%p\n", This, Width, Height, Levels,
883        nine_D3DUSAGE_to_str(Usage), d3dformat_to_string(Format),
884        nine_D3DPOOL_to_str(Pool), ppTexture, pSharedHandle);
885
886    Usage &= D3DUSAGE_AUTOGENMIPMAP | D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_DMAP |
887             D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE | D3DUSAGE_RENDERTARGET |
888             D3DUSAGE_SOFTWAREPROCESSING | D3DUSAGE_TEXTAPI;
889
890    *ppTexture = NULL;
891    user_assert(Width && Height, D3DERR_INVALIDCALL);
892    user_assert(!pSharedHandle || This->ex, D3DERR_INVALIDCALL);
893    /* When is used shared handle, Pool must be
894     * SYSTEMMEM with Levels 1 or DEFAULT with any Levels */
895    user_assert(!pSharedHandle || Pool != D3DPOOL_SYSTEMMEM || Levels == 1,
896                D3DERR_INVALIDCALL);
897    user_assert(!pSharedHandle || Pool == D3DPOOL_SYSTEMMEM || Pool == D3DPOOL_DEFAULT,
898                D3DERR_INVALIDCALL);
899    user_assert((Usage != D3DUSAGE_AUTOGENMIPMAP || Levels <= 1), D3DERR_INVALIDCALL);
900
901    hr = NineTexture9_new(This, Width, Height, Levels, Usage, Format, Pool,
902                          &tex, pSharedHandle);
903    if (SUCCEEDED(hr))
904        *ppTexture = (IDirect3DTexture9 *)tex;
905
906    return hr;
907}
908
909HRESULT WINAPI
910NineDevice9_CreateVolumeTexture( struct NineDevice9 *This,
911                                 UINT Width,
912                                 UINT Height,
913                                 UINT Depth,
914                                 UINT Levels,
915                                 DWORD Usage,
916                                 D3DFORMAT Format,
917                                 D3DPOOL Pool,
918                                 IDirect3DVolumeTexture9 **ppVolumeTexture,
919                                 HANDLE *pSharedHandle )
920{
921    struct NineVolumeTexture9 *tex;
922    HRESULT hr;
923
924    DBG("This=%p Width=%u Height=%u Depth=%u Levels=%u Usage=%s Format=%s Pool=%s "
925        "ppOut=%p pSharedHandle=%p\n", This, Width, Height, Depth, Levels,
926        nine_D3DUSAGE_to_str(Usage), d3dformat_to_string(Format),
927        nine_D3DPOOL_to_str(Pool), ppVolumeTexture, pSharedHandle);
928
929    Usage &= D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE |
930             D3DUSAGE_SOFTWAREPROCESSING;
931
932    *ppVolumeTexture = NULL;
933    user_assert(Width && Height && Depth, D3DERR_INVALIDCALL);
934    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
935
936    hr = NineVolumeTexture9_new(This, Width, Height, Depth, Levels,
937                                Usage, Format, Pool, &tex, pSharedHandle);
938    if (SUCCEEDED(hr))
939        *ppVolumeTexture = (IDirect3DVolumeTexture9 *)tex;
940
941    return hr;
942}
943
944HRESULT WINAPI
945NineDevice9_CreateCubeTexture( struct NineDevice9 *This,
946                               UINT EdgeLength,
947                               UINT Levels,
948                               DWORD Usage,
949                               D3DFORMAT Format,
950                               D3DPOOL Pool,
951                               IDirect3DCubeTexture9 **ppCubeTexture,
952                               HANDLE *pSharedHandle )
953{
954    struct NineCubeTexture9 *tex;
955    HRESULT hr;
956
957    DBG("This=%p EdgeLength=%u Levels=%u Usage=%s Format=%s Pool=%s ppOut=%p "
958        "pSharedHandle=%p\n", This, EdgeLength, Levels,
959        nine_D3DUSAGE_to_str(Usage), d3dformat_to_string(Format),
960        nine_D3DPOOL_to_str(Pool), ppCubeTexture, pSharedHandle);
961
962    Usage &= D3DUSAGE_AUTOGENMIPMAP | D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_DYNAMIC |
963             D3DUSAGE_NONSECURE | D3DUSAGE_RENDERTARGET |
964             D3DUSAGE_SOFTWAREPROCESSING;
965
966    *ppCubeTexture = NULL;
967    user_assert(EdgeLength, D3DERR_INVALIDCALL);
968    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
969
970    hr = NineCubeTexture9_new(This, EdgeLength, Levels, Usage, Format, Pool,
971                              &tex, pSharedHandle);
972    if (SUCCEEDED(hr))
973        *ppCubeTexture = (IDirect3DCubeTexture9 *)tex;
974
975    return hr;
976}
977
978HRESULT WINAPI
979NineDevice9_CreateVertexBuffer( struct NineDevice9 *This,
980                                UINT Length,
981                                DWORD Usage,
982                                DWORD FVF,
983                                D3DPOOL Pool,
984                                IDirect3DVertexBuffer9 **ppVertexBuffer,
985                                HANDLE *pSharedHandle )
986{
987    struct NineVertexBuffer9 *buf;
988    HRESULT hr;
989    D3DVERTEXBUFFER_DESC desc;
990
991    DBG("This=%p Length=%u Usage=%x FVF=%x Pool=%u ppOut=%p pSharedHandle=%p\n",
992        This, Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle);
993
994    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_NOTAVAILABLE);
995
996    desc.Format = D3DFMT_VERTEXDATA;
997    desc.Type = D3DRTYPE_VERTEXBUFFER;
998    desc.Usage = Usage &
999        (D3DUSAGE_DONOTCLIP | D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE |
1000         D3DUSAGE_NPATCHES | D3DUSAGE_POINTS | D3DUSAGE_RTPATCHES |
1001         D3DUSAGE_SOFTWAREPROCESSING | D3DUSAGE_TEXTAPI |
1002         D3DUSAGE_WRITEONLY);
1003    desc.Pool = Pool;
1004    desc.Size = Length;
1005    desc.FVF = FVF;
1006
1007    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1008    user_assert(desc.Usage == Usage, D3DERR_INVALIDCALL);
1009
1010    hr = NineVertexBuffer9_new(This, &desc, &buf);
1011    if (SUCCEEDED(hr))
1012        *ppVertexBuffer = (IDirect3DVertexBuffer9 *)buf;
1013    return hr;
1014}
1015
1016HRESULT WINAPI
1017NineDevice9_CreateIndexBuffer( struct NineDevice9 *This,
1018                               UINT Length,
1019                               DWORD Usage,
1020                               D3DFORMAT Format,
1021                               D3DPOOL Pool,
1022                               IDirect3DIndexBuffer9 **ppIndexBuffer,
1023                               HANDLE *pSharedHandle )
1024{
1025    struct NineIndexBuffer9 *buf;
1026    HRESULT hr;
1027    D3DINDEXBUFFER_DESC desc;
1028
1029    DBG("This=%p Length=%u Usage=%x Format=%s Pool=%u ppOut=%p "
1030        "pSharedHandle=%p\n", This, Length, Usage,
1031        d3dformat_to_string(Format), Pool, ppIndexBuffer, pSharedHandle);
1032
1033    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_NOTAVAILABLE);
1034
1035    desc.Format = Format;
1036    desc.Type = D3DRTYPE_INDEXBUFFER;
1037    desc.Usage = Usage &
1038        (D3DUSAGE_DONOTCLIP | D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE |
1039         D3DUSAGE_NPATCHES | D3DUSAGE_POINTS | D3DUSAGE_RTPATCHES |
1040         D3DUSAGE_SOFTWAREPROCESSING | D3DUSAGE_WRITEONLY);
1041    desc.Pool = Pool;
1042    desc.Size = Length;
1043
1044    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1045    user_assert(desc.Usage == Usage, D3DERR_INVALIDCALL);
1046
1047    hr = NineIndexBuffer9_new(This, &desc, &buf);
1048    if (SUCCEEDED(hr))
1049        *ppIndexBuffer = (IDirect3DIndexBuffer9 *)buf;
1050    return hr;
1051}
1052
1053static HRESULT
1054create_zs_or_rt_surface(struct NineDevice9 *This,
1055                        unsigned type, /* 0 = RT, 1 = ZS, 2 = plain */
1056                        D3DPOOL Pool,
1057                        UINT Width, UINT Height,
1058                        D3DFORMAT Format,
1059                        D3DMULTISAMPLE_TYPE MultiSample,
1060                        DWORD MultisampleQuality,
1061                        BOOL Discard_or_Lockable,
1062                        IDirect3DSurface9 **ppSurface,
1063                        HANDLE *pSharedHandle)
1064{
1065    struct NineSurface9 *surface;
1066    struct pipe_screen *screen = This->screen;
1067    struct pipe_resource *resource = NULL;
1068    HRESULT hr;
1069    D3DSURFACE_DESC desc;
1070    struct pipe_resource templ;
1071
1072    DBG("This=%p type=%u Pool=%s Width=%u Height=%u Format=%s MS=%u Quality=%u "
1073        "Discard_or_Lockable=%i ppSurface=%p pSharedHandle=%p\n",
1074        This, type, nine_D3DPOOL_to_str(Pool), Width, Height,
1075        d3dformat_to_string(Format), MultiSample, MultisampleQuality,
1076        Discard_or_Lockable, ppSurface, pSharedHandle);
1077
1078    if (pSharedHandle)
1079      DBG("FIXME Used shared handle! This option isn't probably handled correctly!\n");
1080
1081    user_assert(Width && Height, D3DERR_INVALIDCALL);
1082    user_assert(Pool != D3DPOOL_MANAGED, D3DERR_INVALIDCALL);
1083
1084    templ.target = PIPE_TEXTURE_2D;
1085    templ.width0 = Width;
1086    templ.height0 = Height;
1087    templ.depth0 = 1;
1088    templ.array_size = 1;
1089    templ.last_level = 0;
1090    templ.nr_samples = (unsigned)MultiSample;
1091    templ.usage = PIPE_USAGE_DEFAULT;
1092    templ.flags = 0;
1093    templ.bind = PIPE_BIND_SAMPLER_VIEW; /* StretchRect */
1094    switch (type) {
1095    case 0: templ.bind |= PIPE_BIND_RENDER_TARGET; break;
1096    case 1: templ.bind = d3d9_get_pipe_depth_format_bindings(Format); break;
1097    default:
1098        assert(type == 2);
1099        break;
1100    }
1101    templ.format = d3d9_to_pipe_format_checked(screen, Format, templ.target,
1102                                               templ.nr_samples, templ.bind,
1103                                               FALSE);
1104
1105    desc.Format = Format;
1106    desc.Type = D3DRTYPE_SURFACE;
1107    desc.Usage = 0;
1108    desc.Pool = Pool;
1109    desc.MultiSampleType = MultiSample;
1110    desc.MultiSampleQuality = MultisampleQuality;
1111    desc.Width = Width;
1112    desc.Height = Height;
1113    switch (type) {
1114    case 0: desc.Usage = D3DUSAGE_RENDERTARGET; break;
1115    case 1: desc.Usage = D3DUSAGE_DEPTHSTENCIL; break;
1116    default: break;
1117    }
1118
1119    if (compressed_format(Format)) {
1120        const unsigned w = util_format_get_blockwidth(templ.format);
1121        const unsigned h = util_format_get_blockheight(templ.format);
1122
1123        user_assert(!(Width % w) && !(Height % h), D3DERR_INVALIDCALL);
1124    }
1125
1126    if (Pool == D3DPOOL_DEFAULT && Format != D3DFMT_NULL) {
1127        /* resource_create doesn't return an error code, so check format here */
1128        user_assert(templ.format != PIPE_FORMAT_NONE, D3DERR_INVALIDCALL);
1129        resource = screen->resource_create(screen, &templ);
1130        user_assert(resource, D3DERR_OUTOFVIDEOMEMORY);
1131        if (Discard_or_Lockable && (desc.Usage & D3DUSAGE_RENDERTARGET))
1132            resource->flags |= NINE_RESOURCE_FLAG_LOCKABLE;
1133    } else {
1134        resource = NULL;
1135    }
1136    hr = NineSurface9_new(This, NULL, resource, NULL, 0, 0, 0, &desc, &surface);
1137    pipe_resource_reference(&resource, NULL);
1138
1139    if (SUCCEEDED(hr))
1140        *ppSurface = (IDirect3DSurface9 *)surface;
1141    return hr;
1142}
1143
1144HRESULT WINAPI
1145NineDevice9_CreateRenderTarget( struct NineDevice9 *This,
1146                                UINT Width,
1147                                UINT Height,
1148                                D3DFORMAT Format,
1149                                D3DMULTISAMPLE_TYPE MultiSample,
1150                                DWORD MultisampleQuality,
1151                                BOOL Lockable,
1152                                IDirect3DSurface9 **ppSurface,
1153                                HANDLE *pSharedHandle )
1154{
1155    *ppSurface = NULL;
1156    return create_zs_or_rt_surface(This, 0, D3DPOOL_DEFAULT,
1157                                   Width, Height, Format,
1158                                   MultiSample, MultisampleQuality,
1159                                   Lockable, ppSurface, pSharedHandle);
1160}
1161
1162HRESULT WINAPI
1163NineDevice9_CreateDepthStencilSurface( struct NineDevice9 *This,
1164                                       UINT Width,
1165                                       UINT Height,
1166                                       D3DFORMAT Format,
1167                                       D3DMULTISAMPLE_TYPE MultiSample,
1168                                       DWORD MultisampleQuality,
1169                                       BOOL Discard,
1170                                       IDirect3DSurface9 **ppSurface,
1171                                       HANDLE *pSharedHandle )
1172{
1173    *ppSurface = NULL;
1174    if (!depth_stencil_format(Format))
1175        return D3DERR_NOTAVAILABLE;
1176    return create_zs_or_rt_surface(This, 1, D3DPOOL_DEFAULT,
1177                                   Width, Height, Format,
1178                                   MultiSample, MultisampleQuality,
1179                                   Discard, ppSurface, pSharedHandle);
1180}
1181
1182HRESULT WINAPI
1183NineDevice9_UpdateSurface( struct NineDevice9 *This,
1184                           IDirect3DSurface9 *pSourceSurface,
1185                           const RECT *pSourceRect,
1186                           IDirect3DSurface9 *pDestinationSurface,
1187                           const POINT *pDestPoint )
1188{
1189    struct NineSurface9 *dst = NineSurface9(pDestinationSurface);
1190    struct NineSurface9 *src = NineSurface9(pSourceSurface);
1191    int copy_width, copy_height;
1192    RECT destRect;
1193
1194    DBG("This=%p pSourceSurface=%p pDestinationSurface=%p "
1195        "pSourceRect=%p pDestPoint=%p\n", This,
1196        pSourceSurface, pDestinationSurface, pSourceRect, pDestPoint);
1197    if (pSourceRect)
1198        DBG("pSourceRect = (%u,%u)-(%u,%u)\n",
1199            pSourceRect->left, pSourceRect->top,
1200            pSourceRect->right, pSourceRect->bottom);
1201    if (pDestPoint)
1202        DBG("pDestPoint = (%u,%u)\n", pDestPoint->x, pDestPoint->y);
1203
1204    user_assert(dst && src, D3DERR_INVALIDCALL);
1205
1206    user_assert(dst->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1207    user_assert(src->base.pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1208
1209    user_assert(dst->desc.MultiSampleType == D3DMULTISAMPLE_NONE, D3DERR_INVALIDCALL);
1210    user_assert(src->desc.MultiSampleType == D3DMULTISAMPLE_NONE, D3DERR_INVALIDCALL);
1211
1212    user_assert(!src->lock_count, D3DERR_INVALIDCALL);
1213    user_assert(!dst->lock_count, D3DERR_INVALIDCALL);
1214
1215    user_assert(dst->desc.Format == src->desc.Format, D3DERR_INVALIDCALL);
1216    user_assert(!depth_stencil_format(dst->desc.Format), D3DERR_INVALIDCALL);
1217
1218    if (pSourceRect) {
1219        copy_width = pSourceRect->right - pSourceRect->left;
1220        copy_height = pSourceRect->bottom - pSourceRect->top;
1221
1222        user_assert(pSourceRect->left >= 0 &&
1223                    copy_width > 0 &&
1224                    pSourceRect->right <= src->desc.Width &&
1225                    pSourceRect->top >= 0 &&
1226                    copy_height > 0 &&
1227                    pSourceRect->bottom <= src->desc.Height,
1228                    D3DERR_INVALIDCALL);
1229    } else {
1230        copy_width = src->desc.Width;
1231        copy_height = src->desc.Height;
1232    }
1233
1234    destRect.right = copy_width;
1235    destRect.bottom = copy_height;
1236
1237    if (pDestPoint) {
1238        user_assert(pDestPoint->x >= 0 && pDestPoint->y >= 0,
1239                    D3DERR_INVALIDCALL);
1240        destRect.right += pDestPoint->x;
1241        destRect.bottom += pDestPoint->y;
1242    }
1243
1244    user_assert(destRect.right <= dst->desc.Width &&
1245                destRect.bottom <= dst->desc.Height,
1246                D3DERR_INVALIDCALL);
1247
1248    if (compressed_format(dst->desc.Format)) {
1249        const unsigned w = util_format_get_blockwidth(dst->base.info.format);
1250        const unsigned h = util_format_get_blockheight(dst->base.info.format);
1251
1252        if (pDestPoint) {
1253            user_assert(!(pDestPoint->x % w) && !(pDestPoint->y % h),
1254                        D3DERR_INVALIDCALL);
1255        }
1256
1257        if (pSourceRect) {
1258            user_assert(!(pSourceRect->left % w) && !(pSourceRect->top % h),
1259                        D3DERR_INVALIDCALL);
1260        }
1261        if (!(copy_width == src->desc.Width &&
1262              copy_width == dst->desc.Width &&
1263              copy_height == src->desc.Height &&
1264              copy_height == dst->desc.Height)) {
1265            user_assert(!(copy_width  % w) && !(copy_height % h),
1266                        D3DERR_INVALIDCALL);
1267        }
1268    }
1269
1270    NineSurface9_CopyMemToDefault(dst, src, pDestPoint, pSourceRect);
1271
1272    return D3D_OK;
1273}
1274
1275HRESULT WINAPI
1276NineDevice9_UpdateTexture( struct NineDevice9 *This,
1277                           IDirect3DBaseTexture9 *pSourceTexture,
1278                           IDirect3DBaseTexture9 *pDestinationTexture )
1279{
1280    struct NineBaseTexture9 *dstb = NineBaseTexture9(pDestinationTexture);
1281    struct NineBaseTexture9 *srcb = NineBaseTexture9(pSourceTexture);
1282    unsigned l, m;
1283    unsigned last_level = dstb->base.info.last_level;
1284    RECT rect;
1285
1286    DBG("This=%p pSourceTexture=%p pDestinationTexture=%p\n", This,
1287        pSourceTexture, pDestinationTexture);
1288
1289    user_assert(pSourceTexture != pDestinationTexture, D3DERR_INVALIDCALL);
1290
1291    user_assert(dstb->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1292    user_assert(srcb->base.pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1293
1294    if (dstb->base.usage & D3DUSAGE_AUTOGENMIPMAP) {
1295        /* Only the first level is updated, the others regenerated. */
1296        last_level = 0;
1297        /* if the source has D3DUSAGE_AUTOGENMIPMAP, we have to ignore
1298         * the sublevels, thus level 0 has to match */
1299        user_assert(!(srcb->base.usage & D3DUSAGE_AUTOGENMIPMAP) ||
1300                    (srcb->base.info.width0 == dstb->base.info.width0 &&
1301                     srcb->base.info.height0 == dstb->base.info.height0 &&
1302                     srcb->base.info.depth0 == dstb->base.info.depth0),
1303                    D3DERR_INVALIDCALL);
1304    } else {
1305        user_assert(!(srcb->base.usage & D3DUSAGE_AUTOGENMIPMAP), D3DERR_INVALIDCALL);
1306    }
1307
1308    user_assert(dstb->base.type == srcb->base.type, D3DERR_INVALIDCALL);
1309
1310    /* Find src level that matches dst level 0: */
1311    user_assert(srcb->base.info.width0 >= dstb->base.info.width0 &&
1312                srcb->base.info.height0 >= dstb->base.info.height0 &&
1313                srcb->base.info.depth0 >= dstb->base.info.depth0,
1314                D3DERR_INVALIDCALL);
1315    for (m = 0; m <= srcb->base.info.last_level; ++m) {
1316        unsigned w = u_minify(srcb->base.info.width0, m);
1317        unsigned h = u_minify(srcb->base.info.height0, m);
1318        unsigned d = u_minify(srcb->base.info.depth0, m);
1319
1320        if (w == dstb->base.info.width0 &&
1321            h == dstb->base.info.height0 &&
1322            d == dstb->base.info.depth0)
1323            break;
1324    }
1325    user_assert(m <= srcb->base.info.last_level, D3DERR_INVALIDCALL);
1326
1327    last_level = MIN2(last_level, srcb->base.info.last_level - m);
1328
1329    if (dstb->base.type == D3DRTYPE_TEXTURE) {
1330        struct NineTexture9 *dst = NineTexture9(dstb);
1331        struct NineTexture9 *src = NineTexture9(srcb);
1332
1333        if (src->dirty_rect.width == 0)
1334            return D3D_OK;
1335
1336        pipe_box_to_rect(&rect, &src->dirty_rect);
1337        for (l = 0; l < m; ++l)
1338            rect_minify_inclusive(&rect);
1339
1340        for (l = 0; l <= last_level; ++l, ++m) {
1341            fit_rect_format_inclusive(dst->base.base.info.format,
1342                                      &rect,
1343                                      dst->surfaces[l]->desc.Width,
1344                                      dst->surfaces[l]->desc.Height);
1345            NineSurface9_CopyMemToDefault(dst->surfaces[l],
1346                                          src->surfaces[m],
1347                                          (POINT *)&rect,
1348                                          &rect);
1349            rect_minify_inclusive(&rect);
1350        }
1351        u_box_origin_2d(0, 0, &src->dirty_rect);
1352    } else
1353    if (dstb->base.type == D3DRTYPE_CUBETEXTURE) {
1354        struct NineCubeTexture9 *dst = NineCubeTexture9(dstb);
1355        struct NineCubeTexture9 *src = NineCubeTexture9(srcb);
1356        unsigned z;
1357
1358        /* GPUs usually have them stored as arrays of mip-mapped 2D textures. */
1359        for (z = 0; z < 6; ++z) {
1360            if (src->dirty_rect[z].width == 0)
1361                continue;
1362
1363            pipe_box_to_rect(&rect, &src->dirty_rect[z]);
1364            for (l = 0; l < m; ++l)
1365                rect_minify_inclusive(&rect);
1366
1367            for (l = 0; l <= last_level; ++l, ++m) {
1368                fit_rect_format_inclusive(dst->base.base.info.format,
1369                                          &rect,
1370                                          dst->surfaces[l * 6 + z]->desc.Width,
1371                                          dst->surfaces[l * 6 + z]->desc.Height);
1372                NineSurface9_CopyMemToDefault(dst->surfaces[l * 6 + z],
1373                                              src->surfaces[m * 6 + z],
1374                                              (POINT *)&rect,
1375                                              &rect);
1376                rect_minify_inclusive(&rect);
1377            }
1378            u_box_origin_2d(0, 0, &src->dirty_rect[z]);
1379            m -= l;
1380        }
1381    } else
1382    if (dstb->base.type == D3DRTYPE_VOLUMETEXTURE) {
1383        struct NineVolumeTexture9 *dst = NineVolumeTexture9(dstb);
1384        struct NineVolumeTexture9 *src = NineVolumeTexture9(srcb);
1385
1386        if (src->dirty_box.width == 0)
1387            return D3D_OK;
1388        for (l = 0; l <= last_level; ++l, ++m)
1389            NineVolume9_CopyMemToDefault(dst->volumes[l],
1390                                         src->volumes[m], 0, 0, 0, NULL);
1391        u_box_3d(0, 0, 0, 0, 0, 0, &src->dirty_box);
1392    } else{
1393        assert(!"invalid texture type");
1394    }
1395
1396    if (dstb->base.usage & D3DUSAGE_AUTOGENMIPMAP) {
1397        dstb->dirty_mip = TRUE;
1398        NineBaseTexture9_GenerateMipSubLevels(dstb);
1399    }
1400
1401    return D3D_OK;
1402}
1403
1404HRESULT WINAPI
1405NineDevice9_GetRenderTargetData( struct NineDevice9 *This,
1406                                 IDirect3DSurface9 *pRenderTarget,
1407                                 IDirect3DSurface9 *pDestSurface )
1408{
1409    struct NineSurface9 *dst = NineSurface9(pDestSurface);
1410    struct NineSurface9 *src = NineSurface9(pRenderTarget);
1411
1412    DBG("This=%p pRenderTarget=%p pDestSurface=%p\n",
1413        This, pRenderTarget, pDestSurface);
1414
1415    user_assert(dst->desc.Pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1416    user_assert(src->desc.Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1417
1418    user_assert(dst->desc.MultiSampleType < 2, D3DERR_INVALIDCALL);
1419    user_assert(src->desc.MultiSampleType < 2, D3DERR_INVALIDCALL);
1420
1421    user_assert(src->desc.Width == dst->desc.Width, D3DERR_INVALIDCALL);
1422    user_assert(src->desc.Height == dst->desc.Height, D3DERR_INVALIDCALL);
1423
1424    NineSurface9_CopyDefaultToMem(dst, src);
1425
1426    return D3D_OK;
1427}
1428
1429HRESULT WINAPI
1430NineDevice9_GetFrontBufferData( struct NineDevice9 *This,
1431                                UINT iSwapChain,
1432                                IDirect3DSurface9 *pDestSurface )
1433{
1434    DBG("This=%p iSwapChain=%u pDestSurface=%p\n", This,
1435        iSwapChain, pDestSurface);
1436
1437    user_assert(pDestSurface != NULL, D3DERR_INVALIDCALL);
1438    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
1439
1440    return NineSwapChain9_GetFrontBufferData(This->swapchains[iSwapChain],
1441                                             pDestSurface);
1442}
1443
1444HRESULT WINAPI
1445NineDevice9_StretchRect( struct NineDevice9 *This,
1446                         IDirect3DSurface9 *pSourceSurface,
1447                         const RECT *pSourceRect,
1448                         IDirect3DSurface9 *pDestSurface,
1449                         const RECT *pDestRect,
1450                         D3DTEXTUREFILTERTYPE Filter )
1451{
1452    struct pipe_screen *screen = This->screen;
1453    struct pipe_context *pipe = This->pipe;
1454    struct NineSurface9 *dst = NineSurface9(pDestSurface);
1455    struct NineSurface9 *src = NineSurface9(pSourceSurface);
1456    struct pipe_resource *dst_res = NineSurface9_GetResource(dst);
1457    struct pipe_resource *src_res = NineSurface9_GetResource(src);
1458    boolean zs;
1459    struct pipe_blit_info blit;
1460    boolean scaled, clamped, ms, flip_x = FALSE, flip_y = FALSE;
1461
1462    DBG("This=%p pSourceSurface=%p pSourceRect=%p pDestSurface=%p "
1463        "pDestRect=%p Filter=%u\n",
1464        This, pSourceSurface, pSourceRect, pDestSurface, pDestRect, Filter);
1465    if (pSourceRect)
1466        DBG("pSourceRect=(%u,%u)-(%u,%u)\n",
1467            pSourceRect->left, pSourceRect->top,
1468            pSourceRect->right, pSourceRect->bottom);
1469    if (pDestRect)
1470        DBG("pDestRect=(%u,%u)-(%u,%u)\n", pDestRect->left, pDestRect->top,
1471            pDestRect->right, pDestRect->bottom);
1472
1473    user_assert(dst->base.pool == D3DPOOL_DEFAULT &&
1474                src->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1475    zs = util_format_is_depth_or_stencil(dst_res->format);
1476    user_assert(!zs || !This->in_scene, D3DERR_INVALIDCALL);
1477    user_assert(!zs || !pSourceRect ||
1478                (pSourceRect->left == 0 &&
1479                 pSourceRect->top == 0 &&
1480                 pSourceRect->right == src->desc.Width &&
1481                 pSourceRect->bottom == src->desc.Height), D3DERR_INVALIDCALL);
1482    user_assert(!zs || !pDestRect ||
1483                (pDestRect->left == 0 &&
1484                 pDestRect->top == 0 &&
1485                 pDestRect->right == dst->desc.Width &&
1486                 pDestRect->bottom == dst->desc.Height), D3DERR_INVALIDCALL);
1487    user_assert(!zs ||
1488                (dst->desc.Width == src->desc.Width &&
1489                 dst->desc.Height == src->desc.Height), D3DERR_INVALIDCALL);
1490    user_assert(zs || !util_format_is_depth_or_stencil(src_res->format),
1491                D3DERR_INVALIDCALL);
1492    user_assert(!zs || dst->desc.Format == src->desc.Format,
1493                D3DERR_INVALIDCALL);
1494    user_assert(screen->is_format_supported(screen, src_res->format,
1495                                            src_res->target,
1496                                            src_res->nr_samples,
1497                                            PIPE_BIND_SAMPLER_VIEW),
1498                D3DERR_INVALIDCALL);
1499
1500    /* We might want to permit these, but wine thinks we shouldn't. */
1501    user_assert(!pDestRect ||
1502                (pDestRect->left <= pDestRect->right &&
1503                 pDestRect->top <= pDestRect->bottom), D3DERR_INVALIDCALL);
1504    user_assert(!pSourceRect ||
1505                (pSourceRect->left <= pSourceRect->right &&
1506                 pSourceRect->top <= pSourceRect->bottom), D3DERR_INVALIDCALL);
1507
1508    memset(&blit, 0, sizeof(blit));
1509    blit.dst.resource = dst_res;
1510    blit.dst.level = dst->level;
1511    blit.dst.box.z = dst->layer;
1512    blit.dst.box.depth = 1;
1513    blit.dst.format = dst_res->format;
1514    if (pDestRect) {
1515        flip_x = pDestRect->left > pDestRect->right;
1516        if (flip_x) {
1517            blit.dst.box.x = pDestRect->right;
1518            blit.dst.box.width = pDestRect->left - pDestRect->right;
1519        } else {
1520            blit.dst.box.x = pDestRect->left;
1521            blit.dst.box.width = pDestRect->right - pDestRect->left;
1522        }
1523        flip_y = pDestRect->top > pDestRect->bottom;
1524        if (flip_y) {
1525            blit.dst.box.y = pDestRect->bottom;
1526            blit.dst.box.height = pDestRect->top - pDestRect->bottom;
1527        } else {
1528            blit.dst.box.y = pDestRect->top;
1529            blit.dst.box.height = pDestRect->bottom - pDestRect->top;
1530        }
1531    } else {
1532        blit.dst.box.x = 0;
1533        blit.dst.box.y = 0;
1534        blit.dst.box.width = dst->desc.Width;
1535        blit.dst.box.height = dst->desc.Height;
1536    }
1537    blit.src.resource = src_res;
1538    blit.src.level = src->level;
1539    blit.src.box.z = src->layer;
1540    blit.src.box.depth = 1;
1541    blit.src.format = src_res->format;
1542    if (pSourceRect) {
1543        if (flip_x ^ (pSourceRect->left > pSourceRect->right)) {
1544            blit.src.box.x = pSourceRect->right;
1545            blit.src.box.width = pSourceRect->left - pSourceRect->right;
1546        } else {
1547            blit.src.box.x = pSourceRect->left;
1548            blit.src.box.width = pSourceRect->right - pSourceRect->left;
1549        }
1550        if (flip_y ^ (pSourceRect->top > pSourceRect->bottom)) {
1551            blit.src.box.y = pSourceRect->bottom;
1552            blit.src.box.height = pSourceRect->top - pSourceRect->bottom;
1553        } else {
1554            blit.src.box.y = pSourceRect->top;
1555            blit.src.box.height = pSourceRect->bottom - pSourceRect->top;
1556        }
1557    } else {
1558        blit.src.box.x = flip_x ? src->desc.Width : 0;
1559        blit.src.box.y = flip_y ? src->desc.Height : 0;
1560        blit.src.box.width = flip_x ? -src->desc.Width : src->desc.Width;
1561        blit.src.box.height = flip_y ? -src->desc.Height : src->desc.Height;
1562    }
1563    blit.mask = zs ? PIPE_MASK_ZS : PIPE_MASK_RGBA;
1564    blit.filter = Filter == D3DTEXF_LINEAR ?
1565       PIPE_TEX_FILTER_LINEAR : PIPE_TEX_FILTER_NEAREST;
1566    blit.scissor_enable = FALSE;
1567    blit.alpha_blend = FALSE;
1568
1569    /* If both of a src and dst dimension are negative, flip them. */
1570    if (blit.dst.box.width < 0 && blit.src.box.width < 0) {
1571        blit.dst.box.width = -blit.dst.box.width;
1572        blit.src.box.width = -blit.src.box.width;
1573    }
1574    if (blit.dst.box.height < 0 && blit.src.box.height < 0) {
1575        blit.dst.box.height = -blit.dst.box.height;
1576        blit.src.box.height = -blit.src.box.height;
1577    }
1578    scaled =
1579        blit.dst.box.width != blit.src.box.width ||
1580        blit.dst.box.height != blit.src.box.height;
1581
1582    user_assert(!scaled || dst != src, D3DERR_INVALIDCALL);
1583    user_assert(!scaled ||
1584                !NineSurface9_IsOffscreenPlain(dst), D3DERR_INVALIDCALL);
1585    user_assert(!NineSurface9_IsOffscreenPlain(dst) ||
1586                NineSurface9_IsOffscreenPlain(src), D3DERR_INVALIDCALL);
1587    user_assert(NineSurface9_IsOffscreenPlain(dst) ||
1588                dst->desc.Usage & (D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL),
1589                D3DERR_INVALIDCALL);
1590    user_assert(!scaled ||
1591                (!util_format_is_compressed(dst->base.info.format) &&
1592                 !util_format_is_compressed(src->base.info.format)),
1593                D3DERR_INVALIDCALL);
1594
1595    user_warn(src == dst &&
1596              u_box_test_intersection_2d(&blit.src.box, &blit.dst.box));
1597
1598    /* Check for clipping/clamping: */
1599    {
1600        struct pipe_box box;
1601        int xy;
1602
1603        xy = u_box_clip_2d(&box, &blit.dst.box,
1604                           dst->desc.Width, dst->desc.Height);
1605        if (xy < 0)
1606            return D3D_OK;
1607        if (xy == 0)
1608            xy = u_box_clip_2d(&box, &blit.src.box,
1609                               src->desc.Width, src->desc.Height);
1610        clamped = !!xy;
1611    }
1612
1613    ms = (dst->desc.MultiSampleType | 1) != (src->desc.MultiSampleType | 1);
1614
1615    if (clamped || scaled || (blit.dst.format != blit.src.format) || ms) {
1616        DBG("using pipe->blit()\n");
1617        /* TODO: software scaling */
1618        user_assert(screen->is_format_supported(screen, dst_res->format,
1619                                                dst_res->target,
1620                                                dst_res->nr_samples,
1621                                                zs ? PIPE_BIND_DEPTH_STENCIL :
1622                                                PIPE_BIND_RENDER_TARGET),
1623                    D3DERR_INVALIDCALL);
1624
1625        pipe->blit(pipe, &blit);
1626    } else {
1627        assert(blit.dst.box.x >= 0 && blit.dst.box.y >= 0 &&
1628               blit.src.box.x >= 0 && blit.src.box.y >= 0 &&
1629               blit.dst.box.x + blit.dst.box.width <= dst->desc.Width &&
1630               blit.src.box.x + blit.src.box.width <= src->desc.Width &&
1631               blit.dst.box.y + blit.dst.box.height <= dst->desc.Height &&
1632               blit.src.box.y + blit.src.box.height <= src->desc.Height);
1633        /* Or drivers might crash ... */
1634        DBG("Using resource_copy_region.\n");
1635        pipe->resource_copy_region(pipe,
1636            blit.dst.resource, blit.dst.level,
1637            blit.dst.box.x, blit.dst.box.y, blit.dst.box.z,
1638            blit.src.resource, blit.src.level,
1639            &blit.src.box);
1640    }
1641
1642    /* Communicate the container it needs to update sublevels - if apply */
1643    NineSurface9_MarkContainerDirty(dst);
1644
1645    return D3D_OK;
1646}
1647
1648HRESULT WINAPI
1649NineDevice9_ColorFill( struct NineDevice9 *This,
1650                       IDirect3DSurface9 *pSurface,
1651                       const RECT *pRect,
1652                       D3DCOLOR color )
1653{
1654    struct pipe_context *pipe = This->pipe;
1655    struct NineSurface9 *surf = NineSurface9(pSurface);
1656    struct pipe_surface *psurf;
1657    unsigned x, y, w, h;
1658    union pipe_color_union rgba;
1659    boolean fallback;
1660
1661    DBG("This=%p pSurface=%p pRect=%p color=%08x\n", This,
1662        pSurface, pRect, color);
1663    if (pRect)
1664        DBG("pRect=(%u,%u)-(%u,%u)\n", pRect->left, pRect->top,
1665            pRect->right, pRect->bottom);
1666
1667    user_assert(surf->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1668
1669    user_assert((surf->base.usage & D3DUSAGE_RENDERTARGET) ||
1670                NineSurface9_IsOffscreenPlain(surf), D3DERR_INVALIDCALL);
1671
1672    if (pRect) {
1673        x = pRect->left;
1674        y = pRect->top;
1675        w = pRect->right - pRect->left;
1676        h = pRect->bottom - pRect->top;
1677    } else{
1678        x = 0;
1679        y = 0;
1680        w = surf->desc.Width;
1681        h = surf->desc.Height;
1682    }
1683    d3dcolor_to_pipe_color_union(&rgba, color);
1684
1685    fallback = !(surf->base.info.bind & PIPE_BIND_RENDER_TARGET);
1686
1687    if (!fallback) {
1688        psurf = NineSurface9_GetSurface(surf, 0);
1689        if (!psurf)
1690            fallback = TRUE;
1691    }
1692
1693    if (!fallback) {
1694        pipe->clear_render_target(pipe, psurf, &rgba, x, y, w, h);
1695    } else {
1696        D3DLOCKED_RECT lock;
1697        union util_color uc;
1698        HRESULT hr;
1699        /* XXX: lock pRect and fix util_fill_rect */
1700        hr = NineSurface9_LockRect(surf, &lock, NULL, 0);
1701        if (FAILED(hr))
1702            return hr;
1703        util_pack_color_ub(color >> 16, color >> 8, color >> 0, color >> 24,
1704                           surf->base.info.format, &uc);
1705        util_fill_rect(lock.pBits, surf->base.info.format,lock.Pitch,
1706                       x, y, w, h, &uc);
1707        NineSurface9_UnlockRect(surf);
1708    }
1709
1710    return D3D_OK;
1711}
1712
1713HRESULT WINAPI
1714NineDevice9_CreateOffscreenPlainSurface( struct NineDevice9 *This,
1715                                         UINT Width,
1716                                         UINT Height,
1717                                         D3DFORMAT Format,
1718                                         D3DPOOL Pool,
1719                                         IDirect3DSurface9 **ppSurface,
1720                                         HANDLE *pSharedHandle )
1721{
1722    HRESULT hr;
1723
1724    DBG("This=%p Width=%u Height=%u Format=%s(0x%x) Pool=%u "
1725        "ppSurface=%p pSharedHandle=%p\n", This,
1726        Width, Height, d3dformat_to_string(Format), Format, Pool,
1727        ppSurface, pSharedHandle);
1728
1729    *ppSurface = NULL;
1730    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT
1731                               || Pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1732    user_assert(Pool != D3DPOOL_MANAGED, D3DERR_INVALIDCALL);
1733
1734    /* Can be used with StretchRect and ColorFill. It's also always lockable.
1735     */
1736    hr = create_zs_or_rt_surface(This, 2, Pool, Width, Height,
1737                                 Format,
1738                                 D3DMULTISAMPLE_NONE, 0,
1739                                 TRUE,
1740                                 ppSurface, pSharedHandle);
1741    if (FAILED(hr))
1742        DBG("Failed to create surface.\n");
1743    return hr;
1744}
1745
1746HRESULT WINAPI
1747NineDevice9_SetRenderTarget( struct NineDevice9 *This,
1748                             DWORD RenderTargetIndex,
1749                             IDirect3DSurface9 *pRenderTarget )
1750{
1751    struct NineSurface9 *rt = NineSurface9(pRenderTarget);
1752    const unsigned i = RenderTargetIndex;
1753
1754    DBG("This=%p RenderTargetIndex=%u pRenderTarget=%p\n", This,
1755        RenderTargetIndex, pRenderTarget);
1756
1757    user_assert(i < This->caps.NumSimultaneousRTs, D3DERR_INVALIDCALL);
1758    user_assert(i != 0 || pRenderTarget, D3DERR_INVALIDCALL);
1759    user_assert(!pRenderTarget ||
1760                rt->desc.Usage & D3DUSAGE_RENDERTARGET, D3DERR_INVALIDCALL);
1761
1762    if (i == 0) {
1763        This->state.viewport.X = 0;
1764        This->state.viewport.Y = 0;
1765        This->state.viewport.Width = rt->desc.Width;
1766        This->state.viewport.Height = rt->desc.Height;
1767        This->state.viewport.MinZ = 0.0f;
1768        This->state.viewport.MaxZ = 1.0f;
1769
1770        This->state.scissor.minx = 0;
1771        This->state.scissor.miny = 0;
1772        This->state.scissor.maxx = rt->desc.Width;
1773        This->state.scissor.maxy = rt->desc.Height;
1774
1775        This->state.changed.group |= NINE_STATE_VIEWPORT | NINE_STATE_SCISSOR;
1776    }
1777
1778    if (This->state.rt[i] != NineSurface9(pRenderTarget)) {
1779       nine_bind(&This->state.rt[i], pRenderTarget);
1780       This->state.changed.group |= NINE_STATE_FB;
1781    }
1782    return D3D_OK;
1783}
1784
1785HRESULT WINAPI
1786NineDevice9_GetRenderTarget( struct NineDevice9 *This,
1787                             DWORD RenderTargetIndex,
1788                             IDirect3DSurface9 **ppRenderTarget )
1789{
1790    const unsigned i = RenderTargetIndex;
1791
1792    user_assert(i < This->caps.NumSimultaneousRTs, D3DERR_INVALIDCALL);
1793    user_assert(ppRenderTarget, D3DERR_INVALIDCALL);
1794
1795    *ppRenderTarget = (IDirect3DSurface9 *)This->state.rt[i];
1796    if (!This->state.rt[i])
1797        return D3DERR_NOTFOUND;
1798
1799    NineUnknown_AddRef(NineUnknown(This->state.rt[i]));
1800    return D3D_OK;
1801}
1802
1803HRESULT WINAPI
1804NineDevice9_SetDepthStencilSurface( struct NineDevice9 *This,
1805                                    IDirect3DSurface9 *pNewZStencil )
1806{
1807    DBG("This=%p pNewZStencil=%p\n", This, pNewZStencil);
1808
1809    if (This->state.ds != NineSurface9(pNewZStencil)) {
1810        nine_bind(&This->state.ds, pNewZStencil);
1811        This->state.changed.group |= NINE_STATE_FB;
1812    }
1813    return D3D_OK;
1814}
1815
1816HRESULT WINAPI
1817NineDevice9_GetDepthStencilSurface( struct NineDevice9 *This,
1818                                    IDirect3DSurface9 **ppZStencilSurface )
1819{
1820    user_assert(ppZStencilSurface, D3DERR_INVALIDCALL);
1821
1822    *ppZStencilSurface = (IDirect3DSurface9 *)This->state.ds;
1823    if (!This->state.ds)
1824        return D3DERR_NOTFOUND;
1825
1826    NineUnknown_AddRef(NineUnknown(This->state.ds));
1827    return D3D_OK;
1828}
1829
1830HRESULT WINAPI
1831NineDevice9_BeginScene( struct NineDevice9 *This )
1832{
1833    DBG("This=%p\n", This);
1834    user_assert(!This->in_scene, D3DERR_INVALIDCALL);
1835    This->in_scene = TRUE;
1836    /* Do we want to do anything else here ? */
1837    return D3D_OK;
1838}
1839
1840HRESULT WINAPI
1841NineDevice9_EndScene( struct NineDevice9 *This )
1842{
1843    DBG("This=%p\n", This);
1844    user_assert(This->in_scene, D3DERR_INVALIDCALL);
1845    This->in_scene = FALSE;
1846    return D3D_OK;
1847}
1848
1849HRESULT WINAPI
1850NineDevice9_Clear( struct NineDevice9 *This,
1851                   DWORD Count,
1852                   const D3DRECT *pRects,
1853                   DWORD Flags,
1854                   D3DCOLOR Color,
1855                   float Z,
1856                   DWORD Stencil )
1857{
1858    const int sRGB = This->state.rs[D3DRS_SRGBWRITEENABLE] ? 1 : 0;
1859    struct pipe_surface *cbuf, *zsbuf;
1860    struct pipe_context *pipe = This->pipe;
1861    struct NineSurface9 *zsbuf_surf = This->state.ds;
1862    struct NineSurface9 *rt;
1863    unsigned bufs = 0;
1864    unsigned r, i;
1865    union pipe_color_union rgba;
1866    unsigned rt_mask = 0;
1867    D3DRECT rect;
1868
1869    DBG("This=%p Count=%u pRects=%p Flags=%x Color=%08x Z=%f Stencil=%x\n",
1870        This, Count, pRects, Flags, Color, Z, Stencil);
1871
1872    user_assert(This->state.ds || !(Flags & NINED3DCLEAR_DEPTHSTENCIL),
1873                D3DERR_INVALIDCALL);
1874    user_assert(!(Flags & D3DCLEAR_STENCIL) ||
1875                (zsbuf_surf &&
1876                 util_format_is_depth_and_stencil(zsbuf_surf->base.info.format)),
1877                D3DERR_INVALIDCALL);
1878#ifdef NINE_STRICT
1879    user_assert((Count && pRects) || (!Count && !pRects), D3DERR_INVALIDCALL);
1880#else
1881    user_warn((pRects && !Count) || (!pRects && Count));
1882    if (pRects && !Count)
1883        return D3D_OK;
1884    if (!pRects)
1885        Count = 0;
1886#endif
1887
1888    if (Flags & D3DCLEAR_TARGET) bufs |= PIPE_CLEAR_COLOR;
1889    if (Flags & D3DCLEAR_ZBUFFER) bufs |= PIPE_CLEAR_DEPTH;
1890    if (Flags & D3DCLEAR_STENCIL) bufs |= PIPE_CLEAR_STENCIL;
1891    if (!bufs)
1892        return D3D_OK;
1893    d3dcolor_to_pipe_color_union(&rgba, Color);
1894
1895    nine_update_state_framebuffer(This);
1896
1897    rect.x1 = This->state.viewport.X;
1898    rect.y1 = This->state.viewport.Y;
1899    rect.x2 = This->state.viewport.Width + rect.x1;
1900    rect.y2 = This->state.viewport.Height + rect.y1;
1901
1902    /* Both rectangles apply, which is weird, but that's D3D9. */
1903    if (This->state.rs[D3DRS_SCISSORTESTENABLE]) {
1904        rect.x1 = MAX2(rect.x1, This->state.scissor.minx);
1905        rect.y1 = MAX2(rect.y1, This->state.scissor.miny);
1906        rect.x2 = MIN2(rect.x2, This->state.scissor.maxx);
1907        rect.y2 = MIN2(rect.y2, This->state.scissor.maxy);
1908    }
1909
1910    if (Count) {
1911        /* Maybe apps like to specify a large rect ? */
1912        if (pRects[0].x1 <= rect.x1 && pRects[0].x2 >= rect.x2 &&
1913            pRects[0].y1 <= rect.y1 && pRects[0].y2 >= rect.y2) {
1914            DBG("First rect covers viewport.\n");
1915            Count = 0;
1916            pRects = NULL;
1917        }
1918    }
1919
1920    if (rect.x1 >= This->state.fb.width || rect.y1 >= This->state.fb.height)
1921        return D3D_OK;
1922
1923    for (i = 0; i < This->caps.NumSimultaneousRTs; ++i) {
1924        if (This->state.rt[i] && This->state.rt[i]->desc.Format != D3DFMT_NULL)
1925            rt_mask |= 1 << i;
1926    }
1927
1928    /* fast path, clears everything at once */
1929    if (!Count &&
1930        (!(bufs & PIPE_CLEAR_COLOR) || (rt_mask == This->state.rt_mask)) &&
1931        rect.x1 == 0 && rect.y1 == 0 &&
1932        /* Case we clear only render target. Check clear region vs rt. */
1933        ((!(bufs & (PIPE_CLEAR_DEPTH | PIPE_CLEAR_STENCIL)) &&
1934         rect.x2 >= This->state.fb.width &&
1935         rect.y2 >= This->state.fb.height) ||
1936        /* Case we clear depth buffer (and eventually rt too).
1937         * depth buffer size is always >= rt size. Compare to clear region */
1938        ((bufs & (PIPE_CLEAR_DEPTH | PIPE_CLEAR_STENCIL)) &&
1939         This->state.fb.zsbuf != NULL &&
1940         rect.x2 >= zsbuf_surf->desc.Width &&
1941         rect.y2 >= zsbuf_surf->desc.Height))) {
1942        DBG("Clear fast path\n");
1943        pipe->clear(pipe, bufs, &rgba, Z, Stencil);
1944        return D3D_OK;
1945    }
1946
1947    if (!Count) {
1948        Count = 1;
1949        pRects = &rect;
1950    }
1951
1952    for (i = 0; i < This->caps.NumSimultaneousRTs; ++i) {
1953        rt = This->state.rt[i];
1954        if (!rt || rt->desc.Format == D3DFMT_NULL ||
1955            !(Flags & D3DCLEAR_TARGET))
1956            continue; /* save space, compiler should hoist this */
1957        cbuf = NineSurface9_GetSurface(rt, sRGB);
1958        for (r = 0; r < Count; ++r) {
1959            /* Don't trust users to pass these in the right order. */
1960            unsigned x1 = MIN2(pRects[r].x1, pRects[r].x2);
1961            unsigned y1 = MIN2(pRects[r].y1, pRects[r].y2);
1962            unsigned x2 = MAX2(pRects[r].x1, pRects[r].x2);
1963            unsigned y2 = MAX2(pRects[r].y1, pRects[r].y2);
1964#ifndef NINE_LAX
1965            /* Drop negative rectangles (like wine expects). */
1966            if (pRects[r].x1 > pRects[r].x2) continue;
1967            if (pRects[r].y1 > pRects[r].y2) continue;
1968#endif
1969
1970            x1 = MAX2(x1, rect.x1);
1971            y1 = MAX2(y1, rect.y1);
1972            x2 = MIN3(x2, rect.x2, rt->desc.Width);
1973            y2 = MIN3(y2, rect.y2, rt->desc.Height);
1974
1975            DBG("Clearing (%u..%u)x(%u..%u)\n", x1, x2, y1, y2);
1976            pipe->clear_render_target(pipe, cbuf, &rgba,
1977                                      x1, y1, x2 - x1, y2 - y1);
1978        }
1979    }
1980    if (!(Flags & NINED3DCLEAR_DEPTHSTENCIL))
1981        return D3D_OK;
1982
1983    bufs &= PIPE_CLEAR_DEPTHSTENCIL;
1984
1985    for (r = 0; r < Count; ++r) {
1986        unsigned x1 = MIN2(pRects[r].x1, pRects[r].x2);
1987        unsigned y1 = MIN2(pRects[r].y1, pRects[r].y2);
1988        unsigned x2 = MAX2(pRects[r].x1, pRects[r].x2);
1989        unsigned y2 = MAX2(pRects[r].y1, pRects[r].y2);
1990#ifndef NINE_LAX
1991        /* Drop negative rectangles. */
1992        if (pRects[r].x1 > pRects[r].x2) continue;
1993        if (pRects[r].y1 > pRects[r].y2) continue;
1994#endif
1995
1996        x1 = MIN2(x1, rect.x1);
1997        y1 = MIN2(y1, rect.y1);
1998        x2 = MIN3(x2, rect.x2, zsbuf_surf->desc.Width);
1999        y2 = MIN3(y2, rect.y2, zsbuf_surf->desc.Height);
2000
2001        zsbuf = NineSurface9_GetSurface(zsbuf_surf, 0);
2002        assert(zsbuf);
2003        pipe->clear_depth_stencil(pipe, zsbuf, bufs, Z, Stencil,
2004                                  x1, y1, x2 - x1, y2 - y1);
2005    }
2006    return D3D_OK;
2007}
2008
2009HRESULT WINAPI
2010NineDevice9_SetTransform( struct NineDevice9 *This,
2011                          D3DTRANSFORMSTATETYPE State,
2012                          const D3DMATRIX *pMatrix )
2013{
2014    struct nine_state *state = This->update;
2015    D3DMATRIX *M = nine_state_access_transform(state, State, TRUE);
2016
2017    DBG("This=%p State=%d pMatrix=%p\n", This, State, pMatrix);
2018
2019    user_assert(M, D3DERR_INVALIDCALL);
2020
2021    *M = *pMatrix;
2022    state->ff.changed.transform[State / 32] |= 1 << (State % 32);
2023    state->changed.group |= NINE_STATE_FF;
2024
2025    return D3D_OK;
2026}
2027
2028HRESULT WINAPI
2029NineDevice9_GetTransform( struct NineDevice9 *This,
2030                          D3DTRANSFORMSTATETYPE State,
2031                          D3DMATRIX *pMatrix )
2032{
2033    D3DMATRIX *M = nine_state_access_transform(&This->state, State, FALSE);
2034    user_assert(M, D3DERR_INVALIDCALL);
2035    *pMatrix = *M;
2036    return D3D_OK;
2037}
2038
2039HRESULT WINAPI
2040NineDevice9_MultiplyTransform( struct NineDevice9 *This,
2041                               D3DTRANSFORMSTATETYPE State,
2042                               const D3DMATRIX *pMatrix )
2043{
2044    struct nine_state *state = This->update;
2045    D3DMATRIX T;
2046    D3DMATRIX *M = nine_state_access_transform(state, State, TRUE);
2047
2048    DBG("This=%p State=%d pMatrix=%p\n", This, State, pMatrix);
2049
2050    user_assert(M, D3DERR_INVALIDCALL);
2051
2052    nine_d3d_matrix_matrix_mul(&T, pMatrix, M);
2053    return NineDevice9_SetTransform(This, State, &T);
2054}
2055
2056HRESULT WINAPI
2057NineDevice9_SetViewport( struct NineDevice9 *This,
2058                         const D3DVIEWPORT9 *pViewport )
2059{
2060    struct nine_state *state = This->update;
2061
2062    DBG("X=%u Y=%u W=%u H=%u MinZ=%f MaxZ=%f\n",
2063        pViewport->X, pViewport->Y, pViewport->Width, pViewport->Height,
2064        pViewport->MinZ, pViewport->MaxZ);
2065
2066    state->viewport = *pViewport;
2067    state->changed.group |= NINE_STATE_VIEWPORT;
2068
2069    return D3D_OK;
2070}
2071
2072HRESULT WINAPI
2073NineDevice9_GetViewport( struct NineDevice9 *This,
2074                         D3DVIEWPORT9 *pViewport )
2075{
2076    *pViewport = This->state.viewport;
2077    return D3D_OK;
2078}
2079
2080HRESULT WINAPI
2081NineDevice9_SetMaterial( struct NineDevice9 *This,
2082                         const D3DMATERIAL9 *pMaterial )
2083{
2084    struct nine_state *state = This->update;
2085
2086    DBG("This=%p pMaterial=%p\n", This, pMaterial);
2087    if (pMaterial)
2088        nine_dump_D3DMATERIAL9(DBG_FF, pMaterial);
2089
2090    user_assert(pMaterial, E_POINTER);
2091
2092    state->ff.material = *pMaterial;
2093    state->changed.group |= NINE_STATE_FF_MATERIAL;
2094
2095    return D3D_OK;
2096}
2097
2098HRESULT WINAPI
2099NineDevice9_GetMaterial( struct NineDevice9 *This,
2100                         D3DMATERIAL9 *pMaterial )
2101{
2102    user_assert(pMaterial, E_POINTER);
2103    *pMaterial = This->state.ff.material;
2104    return D3D_OK;
2105}
2106
2107HRESULT WINAPI
2108NineDevice9_SetLight( struct NineDevice9 *This,
2109                      DWORD Index,
2110                      const D3DLIGHT9 *pLight )
2111{
2112    struct nine_state *state = This->update;
2113
2114    DBG("This=%p Index=%u pLight=%p\n", This, Index, pLight);
2115    if (pLight)
2116        nine_dump_D3DLIGHT9(DBG_FF, pLight);
2117
2118    user_assert(pLight, D3DERR_INVALIDCALL);
2119    user_assert(pLight->Type < NINED3DLIGHT_INVALID, D3DERR_INVALIDCALL);
2120
2121    user_assert(Index < NINE_MAX_LIGHTS, D3DERR_INVALIDCALL); /* sanity */
2122
2123    if (Index >= state->ff.num_lights) {
2124        unsigned n = state->ff.num_lights;
2125        unsigned N = Index + 1;
2126
2127        state->ff.light = REALLOC(state->ff.light, n * sizeof(D3DLIGHT9),
2128                                                   N * sizeof(D3DLIGHT9));
2129        if (!state->ff.light)
2130            return E_OUTOFMEMORY;
2131        state->ff.num_lights = N;
2132
2133        for (; n < Index; ++n) {
2134            memset(&state->ff.light[n], 0, sizeof(D3DLIGHT9));
2135            state->ff.light[n].Type = (D3DLIGHTTYPE)NINED3DLIGHT_INVALID;
2136        }
2137    }
2138    state->ff.light[Index] = *pLight;
2139
2140    if (pLight->Type == D3DLIGHT_SPOT && pLight->Theta >= pLight->Phi) {
2141        DBG("Warning: clamping D3DLIGHT9.Theta\n");
2142        state->ff.light[Index].Theta = state->ff.light[Index].Phi;
2143    }
2144    if (pLight->Type != D3DLIGHT_DIRECTIONAL &&
2145        pLight->Attenuation0 == 0.0f &&
2146        pLight->Attenuation1 == 0.0f &&
2147        pLight->Attenuation2 == 0.0f) {
2148        DBG("Warning: all D3DLIGHT9.Attenuation[i] are 0\n");
2149    }
2150
2151    state->changed.group |= NINE_STATE_FF_LIGHTING;
2152
2153    return D3D_OK;
2154}
2155
2156HRESULT WINAPI
2157NineDevice9_GetLight( struct NineDevice9 *This,
2158                      DWORD Index,
2159                      D3DLIGHT9 *pLight )
2160{
2161    const struct nine_state *state = &This->state;
2162
2163    user_assert(pLight, D3DERR_INVALIDCALL);
2164    user_assert(Index < state->ff.num_lights, D3DERR_INVALIDCALL);
2165    user_assert(state->ff.light[Index].Type < NINED3DLIGHT_INVALID,
2166                D3DERR_INVALIDCALL);
2167
2168    *pLight = state->ff.light[Index];
2169
2170    return D3D_OK;
2171}
2172
2173HRESULT WINAPI
2174NineDevice9_LightEnable( struct NineDevice9 *This,
2175                         DWORD Index,
2176                         BOOL Enable )
2177{
2178    struct nine_state *state = This->update;
2179    unsigned i;
2180
2181    DBG("This=%p Index=%u Enable=%i\n", This, Index, Enable);
2182
2183    if (Index >= state->ff.num_lights ||
2184        state->ff.light[Index].Type == NINED3DLIGHT_INVALID) {
2185        /* This should create a default light. */
2186        D3DLIGHT9 light;
2187        memset(&light, 0, sizeof(light));
2188        light.Type = D3DLIGHT_DIRECTIONAL;
2189        light.Diffuse.r = 1.0f;
2190        light.Diffuse.g = 1.0f;
2191        light.Diffuse.b = 1.0f;
2192        light.Direction.z = 1.0f;
2193        NineDevice9_SetLight(This, Index, &light);
2194    }
2195    user_assert(Index < state->ff.num_lights, D3DERR_INVALIDCALL);
2196
2197    for (i = 0; i < state->ff.num_lights_active; ++i) {
2198        if (state->ff.active_light[i] == Index)
2199            break;
2200    }
2201
2202    if (Enable) {
2203        if (i < state->ff.num_lights_active)
2204            return D3D_OK;
2205        /* XXX wine thinks this should still succeed:
2206         */
2207        user_assert(i < NINE_MAX_LIGHTS_ACTIVE, D3DERR_INVALIDCALL);
2208
2209        state->ff.active_light[i] = Index;
2210        state->ff.num_lights_active++;
2211    } else {
2212        if (i == state->ff.num_lights_active)
2213            return D3D_OK;
2214        --state->ff.num_lights_active;
2215        for (; i < state->ff.num_lights_active; ++i)
2216            state->ff.active_light[i] = state->ff.active_light[i + 1];
2217    }
2218    state->changed.group |= NINE_STATE_FF_LIGHTING;
2219
2220    return D3D_OK;
2221}
2222
2223HRESULT WINAPI
2224NineDevice9_GetLightEnable( struct NineDevice9 *This,
2225                            DWORD Index,
2226                            BOOL *pEnable )
2227{
2228    const struct nine_state *state = &This->state;
2229    unsigned i;
2230
2231    user_assert(Index < state->ff.num_lights, D3DERR_INVALIDCALL);
2232    user_assert(state->ff.light[Index].Type < NINED3DLIGHT_INVALID,
2233                D3DERR_INVALIDCALL);
2234
2235    for (i = 0; i < state->ff.num_lights_active; ++i)
2236        if (state->ff.active_light[i] == Index)
2237            break;
2238
2239    *pEnable = i != state->ff.num_lights_active ? 128 : 0; // Taken from wine
2240
2241    return D3D_OK;
2242}
2243
2244HRESULT WINAPI
2245NineDevice9_SetClipPlane( struct NineDevice9 *This,
2246                          DWORD Index,
2247                          const float *pPlane )
2248{
2249    struct nine_state *state = This->update;
2250
2251    user_assert(pPlane, D3DERR_INVALIDCALL);
2252
2253    DBG("This=%p Index=%u pPlane=%f %f %f %f\n", This, Index,
2254        pPlane[0], pPlane[1],
2255        pPlane[2], pPlane[3]);
2256
2257    user_assert(Index < PIPE_MAX_CLIP_PLANES, D3DERR_INVALIDCALL);
2258
2259    memcpy(&state->clip.ucp[Index][0], pPlane, sizeof(state->clip.ucp[0]));
2260    state->changed.ucp |= 1 << Index;
2261
2262    return D3D_OK;
2263}
2264
2265HRESULT WINAPI
2266NineDevice9_GetClipPlane( struct NineDevice9 *This,
2267                          DWORD Index,
2268                          float *pPlane )
2269{
2270    const struct nine_state *state = &This->state;
2271
2272    user_assert(Index < PIPE_MAX_CLIP_PLANES, D3DERR_INVALIDCALL);
2273
2274    memcpy(pPlane, &state->clip.ucp[Index][0], sizeof(state->clip.ucp[0]));
2275    return D3D_OK;
2276}
2277
2278#define RESZ_CODE 0x7fa05000
2279
2280static HRESULT
2281NineDevice9_ResolveZ( struct NineDevice9 *This )
2282{
2283    struct nine_state *state = &This->state;
2284    const struct util_format_description *desc;
2285    struct NineSurface9 *source = state->ds;
2286    struct NineBaseTexture9 *destination = state->texture[0];
2287    struct pipe_resource *src, *dst;
2288    struct pipe_blit_info blit;
2289
2290    DBG("RESZ resolve\n");
2291
2292    user_assert(source && destination &&
2293                destination->base.type == D3DRTYPE_TEXTURE, D3DERR_INVALIDCALL);
2294
2295    src = source->base.resource;
2296    dst = destination->base.resource;
2297
2298    user_assert(src && dst, D3DERR_INVALIDCALL);
2299
2300    /* check dst is depth format. we know already for src */
2301    desc = util_format_description(dst->format);
2302    user_assert(desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS, D3DERR_INVALIDCALL);
2303
2304    memset(&blit, 0, sizeof(blit));
2305    blit.src.resource = src;
2306    blit.src.level = 0;
2307    blit.src.format = src->format;
2308    blit.src.box.z = 0;
2309    blit.src.box.depth = 1;
2310    blit.src.box.x = 0;
2311    blit.src.box.y = 0;
2312    blit.src.box.width = src->width0;
2313    blit.src.box.height = src->height0;
2314
2315    blit.dst.resource = dst;
2316    blit.dst.level = 0;
2317    blit.dst.format = dst->format;
2318    blit.dst.box.z = 0;
2319    blit.dst.box.depth = 1;
2320    blit.dst.box.x = 0;
2321    blit.dst.box.y = 0;
2322    blit.dst.box.width = dst->width0;
2323    blit.dst.box.height = dst->height0;
2324
2325    blit.mask = PIPE_MASK_ZS;
2326    blit.filter = PIPE_TEX_FILTER_NEAREST;
2327    blit.scissor_enable = FALSE;
2328
2329    This->pipe->blit(This->pipe, &blit);
2330    return D3D_OK;
2331}
2332
2333#define ALPHA_TO_COVERAGE_ENABLE   MAKEFOURCC('A', '2', 'M', '1')
2334#define ALPHA_TO_COVERAGE_DISABLE  MAKEFOURCC('A', '2', 'M', '0')
2335
2336HRESULT WINAPI
2337NineDevice9_SetRenderState( struct NineDevice9 *This,
2338                            D3DRENDERSTATETYPE State,
2339                            DWORD Value )
2340{
2341    struct nine_state *state = This->update;
2342
2343    DBG("This=%p State=%u(%s) Value=%08x\n", This,
2344        State, nine_d3drs_to_string(State), Value);
2345
2346    /* Amd hacks (equivalent to GL extensions) */
2347    if (State == D3DRS_POINTSIZE) {
2348        if (Value == RESZ_CODE)
2349            return NineDevice9_ResolveZ(This);
2350
2351        if (Value == ALPHA_TO_COVERAGE_ENABLE ||
2352            Value == ALPHA_TO_COVERAGE_DISABLE) {
2353            state->rs[NINED3DRS_ALPHACOVERAGE] = (Value == ALPHA_TO_COVERAGE_ENABLE);
2354            state->changed.group |= NINE_STATE_BLEND;
2355            return D3D_OK;
2356        }
2357    }
2358
2359    /* NV hack */
2360    if (State == D3DRS_ADAPTIVETESS_Y &&
2361        (Value == D3DFMT_ATOC || (Value == D3DFMT_UNKNOWN && state->rs[NINED3DRS_ALPHACOVERAGE]))) {
2362            state->rs[NINED3DRS_ALPHACOVERAGE] = (Value == D3DFMT_ATOC);
2363            state->changed.group |= NINE_STATE_BLEND;
2364            return D3D_OK;
2365    }
2366
2367    user_assert(State < Elements(state->rs), D3DERR_INVALIDCALL);
2368
2369    if (likely(state->rs[State] != Value) || unlikely(This->is_recording)) {
2370        state->rs[State] = Value;
2371        state->changed.rs[State / 32] |= 1 << (State % 32);
2372        state->changed.group |= nine_render_state_group[State];
2373    }
2374
2375    return D3D_OK;
2376}
2377
2378HRESULT WINAPI
2379NineDevice9_GetRenderState( struct NineDevice9 *This,
2380                            D3DRENDERSTATETYPE State,
2381                            DWORD *pValue )
2382{
2383    user_assert(State < Elements(This->state.rs), D3DERR_INVALIDCALL);
2384
2385    *pValue = This->state.rs[State];
2386    return D3D_OK;
2387}
2388
2389HRESULT WINAPI
2390NineDevice9_CreateStateBlock( struct NineDevice9 *This,
2391                              D3DSTATEBLOCKTYPE Type,
2392                              IDirect3DStateBlock9 **ppSB )
2393{
2394    struct NineStateBlock9 *nsb;
2395    struct nine_state *dst;
2396    HRESULT hr;
2397    enum nine_stateblock_type type;
2398    unsigned s;
2399
2400    DBG("This=%p Type=%u ppSB=%p\n", This, Type, ppSB);
2401
2402    user_assert(Type == D3DSBT_ALL ||
2403                Type == D3DSBT_VERTEXSTATE ||
2404                Type == D3DSBT_PIXELSTATE, D3DERR_INVALIDCALL);
2405
2406    switch (Type) {
2407    case D3DSBT_VERTEXSTATE: type = NINESBT_VERTEXSTATE; break;
2408    case D3DSBT_PIXELSTATE:  type = NINESBT_PIXELSTATE; break;
2409    default:
2410       type = NINESBT_ALL;
2411       break;
2412    }
2413
2414    hr = NineStateBlock9_new(This, &nsb, type);
2415    if (FAILED(hr))
2416       return hr;
2417    *ppSB = (IDirect3DStateBlock9 *)nsb;
2418    dst = &nsb->state;
2419
2420    dst->changed.group =
2421       NINE_STATE_TEXTURE |
2422       NINE_STATE_SAMPLER;
2423
2424    if (Type == D3DSBT_ALL || Type == D3DSBT_VERTEXSTATE) {
2425       dst->changed.group |=
2426           NINE_STATE_FF_LIGHTING |
2427           NINE_STATE_VS | NINE_STATE_VS_CONST |
2428           NINE_STATE_VDECL;
2429       /* TODO: texture/sampler state */
2430       memcpy(dst->changed.rs,
2431              nine_render_states_vertex, sizeof(dst->changed.rs));
2432       nine_ranges_insert(&dst->changed.vs_const_f, 0, This->max_vs_const_f,
2433                          &This->range_pool);
2434       dst->changed.vs_const_i = 0xffff;
2435       dst->changed.vs_const_b = 0xffff;
2436       for (s = 0; s < NINE_MAX_SAMPLERS; ++s)
2437           dst->changed.sampler[s] |= 1 << D3DSAMP_DMAPOFFSET;
2438       if (This->state.ff.num_lights) {
2439           dst->ff.num_lights = This->state.ff.num_lights;
2440           /* zero'd -> light type won't be NINED3DLIGHT_INVALID, so
2441            * all currently existing lights will be captured
2442            */
2443           dst->ff.light = CALLOC(This->state.ff.num_lights,
2444                                  sizeof(D3DLIGHT9));
2445           if (!dst->ff.light) {
2446               nine_bind(ppSB, NULL);
2447               return E_OUTOFMEMORY;
2448           }
2449       }
2450    }
2451    if (Type == D3DSBT_ALL || Type == D3DSBT_PIXELSTATE) {
2452       dst->changed.group |=
2453          NINE_STATE_PS | NINE_STATE_PS_CONST;
2454       /* TODO: texture/sampler state */
2455       memcpy(dst->changed.rs,
2456              nine_render_states_pixel, sizeof(dst->changed.rs));
2457       nine_ranges_insert(&dst->changed.ps_const_f, 0, This->max_ps_const_f,
2458                          &This->range_pool);
2459       dst->changed.ps_const_i = 0xffff;
2460       dst->changed.ps_const_b = 0xffff;
2461       for (s = 0; s < NINE_MAX_SAMPLERS; ++s)
2462           dst->changed.sampler[s] |= 0x1ffe;
2463    }
2464    if (Type == D3DSBT_ALL) {
2465       dst->changed.group |=
2466          NINE_STATE_VIEWPORT |
2467          NINE_STATE_SCISSOR |
2468          NINE_STATE_RASTERIZER |
2469          NINE_STATE_BLEND |
2470          NINE_STATE_DSA |
2471          NINE_STATE_IDXBUF |
2472          NINE_STATE_MATERIAL |
2473          NINE_STATE_BLEND_COLOR |
2474          NINE_STATE_SAMPLE_MASK;
2475       memset(dst->changed.rs, ~0, (D3DRS_COUNT / 32) * sizeof(uint32_t));
2476       dst->changed.rs[D3DRS_LAST / 32] |= (1 << (D3DRS_COUNT % 32)) - 1;
2477       dst->changed.vtxbuf = (1ULL << This->caps.MaxStreams) - 1;
2478       dst->changed.stream_freq = dst->changed.vtxbuf;
2479       dst->changed.ucp = (1 << PIPE_MAX_CLIP_PLANES) - 1;
2480       dst->changed.texture = (1 << NINE_MAX_SAMPLERS) - 1;
2481    }
2482    NineStateBlock9_Capture(NineStateBlock9(*ppSB));
2483
2484    /* TODO: fixed function state */
2485
2486    return D3D_OK;
2487}
2488
2489HRESULT WINAPI
2490NineDevice9_BeginStateBlock( struct NineDevice9 *This )
2491{
2492    HRESULT hr;
2493
2494    DBG("This=%p\n", This);
2495
2496    user_assert(!This->record, D3DERR_INVALIDCALL);
2497
2498    hr = NineStateBlock9_new(This, &This->record, NINESBT_CUSTOM);
2499    if (FAILED(hr))
2500        return hr;
2501    NineUnknown_ConvertRefToBind(NineUnknown(This->record));
2502
2503    This->update = &This->record->state;
2504    This->is_recording = TRUE;
2505
2506    return D3D_OK;
2507}
2508
2509HRESULT WINAPI
2510NineDevice9_EndStateBlock( struct NineDevice9 *This,
2511                           IDirect3DStateBlock9 **ppSB )
2512{
2513    DBG("This=%p ppSB=%p\n", This, ppSB);
2514
2515    user_assert(This->record, D3DERR_INVALIDCALL);
2516
2517    This->update = &This->state;
2518    This->is_recording = FALSE;
2519
2520    NineUnknown_AddRef(NineUnknown(This->record));
2521    *ppSB = (IDirect3DStateBlock9 *)This->record;
2522    NineUnknown_Unbind(NineUnknown(This->record));
2523    This->record = NULL;
2524
2525    return D3D_OK;
2526}
2527
2528HRESULT WINAPI
2529NineDevice9_SetClipStatus( struct NineDevice9 *This,
2530                           const D3DCLIPSTATUS9 *pClipStatus )
2531{
2532    STUB(D3DERR_INVALIDCALL);
2533}
2534
2535HRESULT WINAPI
2536NineDevice9_GetClipStatus( struct NineDevice9 *This,
2537                           D3DCLIPSTATUS9 *pClipStatus )
2538{
2539    STUB(D3DERR_INVALIDCALL);
2540}
2541
2542HRESULT WINAPI
2543NineDevice9_GetTexture( struct NineDevice9 *This,
2544                        DWORD Stage,
2545                        IDirect3DBaseTexture9 **ppTexture )
2546{
2547    user_assert(Stage < This->caps.MaxSimultaneousTextures ||
2548                Stage == D3DDMAPSAMPLER ||
2549                (Stage >= D3DVERTEXTEXTURESAMPLER0 &&
2550                 Stage <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2551    user_assert(ppTexture, D3DERR_INVALIDCALL);
2552
2553    if (Stage >= D3DDMAPSAMPLER)
2554        Stage = Stage - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2555
2556    *ppTexture = (IDirect3DBaseTexture9 *)This->state.texture[Stage];
2557
2558    if (This->state.texture[Stage])
2559        NineUnknown_AddRef(NineUnknown(This->state.texture[Stage]));
2560    return D3D_OK;
2561}
2562
2563HRESULT WINAPI
2564NineDevice9_SetTexture( struct NineDevice9 *This,
2565                        DWORD Stage,
2566                        IDirect3DBaseTexture9 *pTexture )
2567{
2568    struct nine_state *state = This->update;
2569    struct NineBaseTexture9 *tex = NineBaseTexture9(pTexture);
2570
2571    DBG("This=%p Stage=%u pTexture=%p\n", This, Stage, pTexture);
2572
2573    user_assert(Stage < This->caps.MaxSimultaneousTextures ||
2574                Stage == D3DDMAPSAMPLER ||
2575                (Stage >= D3DVERTEXTEXTURESAMPLER0 &&
2576                 Stage <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2577    user_assert(!tex || (tex->base.pool != D3DPOOL_SCRATCH &&
2578                tex->base.pool != D3DPOOL_SYSTEMMEM), D3DERR_INVALIDCALL);
2579
2580    if (Stage >= D3DDMAPSAMPLER)
2581        Stage = Stage - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2582
2583    if (!This->is_recording) {
2584        struct NineBaseTexture9 *old = state->texture[Stage];
2585        if (old == tex)
2586            return D3D_OK;
2587
2588        state->samplers_shadow &= ~(1 << Stage);
2589        if (tex) {
2590            state->samplers_shadow |= tex->shadow << Stage;
2591
2592            if ((tex->managed.dirty | tex->dirty_mip) && LIST_IS_EMPTY(&tex->list))
2593                list_add(&tex->list, &This->update_textures);
2594
2595            tex->bind_count++;
2596        }
2597        if (old)
2598            old->bind_count--;
2599    }
2600    nine_bind(&state->texture[Stage], pTexture);
2601
2602    state->changed.texture |= 1 << Stage;
2603    state->changed.group |= NINE_STATE_TEXTURE;
2604
2605    return D3D_OK;
2606}
2607
2608HRESULT WINAPI
2609NineDevice9_GetTextureStageState( struct NineDevice9 *This,
2610                                  DWORD Stage,
2611                                  D3DTEXTURESTAGESTATETYPE Type,
2612                                  DWORD *pValue )
2613{
2614    const struct nine_state *state = &This->state;
2615
2616    user_assert(Stage < Elements(state->ff.tex_stage), D3DERR_INVALIDCALL);
2617    user_assert(Type < Elements(state->ff.tex_stage[0]), D3DERR_INVALIDCALL);
2618
2619    *pValue = state->ff.tex_stage[Stage][Type];
2620
2621    return D3D_OK;
2622}
2623
2624HRESULT WINAPI
2625NineDevice9_SetTextureStageState( struct NineDevice9 *This,
2626                                  DWORD Stage,
2627                                  D3DTEXTURESTAGESTATETYPE Type,
2628                                  DWORD Value )
2629{
2630    struct nine_state *state = This->update;
2631    int bumpmap_index = -1;
2632
2633    DBG("Stage=%u Type=%u Value=%08x\n", Stage, Type, Value);
2634    nine_dump_D3DTSS_value(DBG_FF, Type, Value);
2635
2636    user_assert(Stage < Elements(state->ff.tex_stage), D3DERR_INVALIDCALL);
2637    user_assert(Type < Elements(state->ff.tex_stage[0]), D3DERR_INVALIDCALL);
2638
2639    state->ff.tex_stage[Stage][Type] = Value;
2640    switch (Type) {
2641    case D3DTSS_BUMPENVMAT00:
2642        bumpmap_index = 4 * Stage;
2643        break;
2644    case D3DTSS_BUMPENVMAT10:
2645        bumpmap_index = 4 * Stage + 1;
2646        break;
2647    case D3DTSS_BUMPENVMAT01:
2648        bumpmap_index = 4 * Stage + 2;
2649        break;
2650    case D3DTSS_BUMPENVMAT11:
2651        bumpmap_index = 4 * Stage + 3;
2652        break;
2653    case D3DTSS_BUMPENVLSCALE:
2654        bumpmap_index = 4 * 8 + 2 * Stage;
2655        break;
2656    case D3DTSS_BUMPENVLOFFSET:
2657        bumpmap_index = 4 * 8 + 2 * Stage + 1;
2658        break;
2659    case D3DTSS_TEXTURETRANSFORMFLAGS:
2660        state->changed.group |= NINE_STATE_PS1X_SHADER;
2661        break;
2662    default:
2663        break;
2664    }
2665
2666    if (bumpmap_index >= 0) {
2667        state->bumpmap_vars[bumpmap_index] = Value;
2668        state->changed.group |= NINE_STATE_PS_CONST;
2669    }
2670
2671    state->changed.group |= NINE_STATE_FF_PSSTAGES;
2672    state->ff.changed.tex_stage[Stage][Type / 32] |= 1 << (Type % 32);
2673
2674    return D3D_OK;
2675}
2676
2677HRESULT WINAPI
2678NineDevice9_GetSamplerState( struct NineDevice9 *This,
2679                             DWORD Sampler,
2680                             D3DSAMPLERSTATETYPE Type,
2681                             DWORD *pValue )
2682{
2683    user_assert(Sampler < This->caps.MaxSimultaneousTextures ||
2684                Sampler == D3DDMAPSAMPLER ||
2685                (Sampler >= D3DVERTEXTEXTURESAMPLER0 &&
2686                 Sampler <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2687
2688    if (Sampler >= D3DDMAPSAMPLER)
2689        Sampler = Sampler - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2690
2691    *pValue = This->state.samp[Sampler][Type];
2692    return D3D_OK;
2693}
2694
2695HRESULT WINAPI
2696NineDevice9_SetSamplerState( struct NineDevice9 *This,
2697                             DWORD Sampler,
2698                             D3DSAMPLERSTATETYPE Type,
2699                             DWORD Value )
2700{
2701    struct nine_state *state = This->update;
2702
2703    DBG("This=%p Sampler=%u Type=%s Value=%08x\n", This,
2704        Sampler, nine_D3DSAMP_to_str(Type), Value);
2705
2706    user_assert(Sampler < This->caps.MaxSimultaneousTextures ||
2707                Sampler == D3DDMAPSAMPLER ||
2708                (Sampler >= D3DVERTEXTEXTURESAMPLER0 &&
2709                 Sampler <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2710
2711    if (Sampler >= D3DDMAPSAMPLER)
2712        Sampler = Sampler - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2713
2714    if (state->samp[Sampler][Type] != Value || unlikely(This->is_recording)) {
2715        state->samp[Sampler][Type] = Value;
2716        state->changed.group |= NINE_STATE_SAMPLER;
2717        state->changed.sampler[Sampler] |= 1 << Type;
2718    }
2719
2720    return D3D_OK;
2721}
2722
2723HRESULT WINAPI
2724NineDevice9_ValidateDevice( struct NineDevice9 *This,
2725                            DWORD *pNumPasses )
2726{
2727    const struct nine_state *state = &This->state;
2728    unsigned i;
2729    unsigned w = 0, h = 0;
2730
2731    DBG("This=%p pNumPasses=%p\n", This, pNumPasses);
2732
2733    for (i = 0; i < Elements(state->samp); ++i) {
2734        if (state->samp[i][D3DSAMP_MINFILTER] == D3DTEXF_NONE ||
2735            state->samp[i][D3DSAMP_MAGFILTER] == D3DTEXF_NONE)
2736            return D3DERR_UNSUPPORTEDTEXTUREFILTER;
2737    }
2738
2739    for (i = 0; i < This->caps.NumSimultaneousRTs; ++i) {
2740        if (!state->rt[i])
2741            continue;
2742        if (w == 0) {
2743            w = state->rt[i]->desc.Width;
2744            h = state->rt[i]->desc.Height;
2745        } else
2746        if (state->rt[i]->desc.Width != w || state->rt[i]->desc.Height != h) {
2747            return D3DERR_CONFLICTINGRENDERSTATE;
2748        }
2749    }
2750    if (state->ds &&
2751        (state->rs[D3DRS_ZENABLE] || state->rs[D3DRS_STENCILENABLE])) {
2752        if (w != 0 &&
2753            (state->ds->desc.Width != w || state->ds->desc.Height != h))
2754            return D3DERR_CONFLICTINGRENDERSTATE;
2755    }
2756
2757    if (pNumPasses)
2758        *pNumPasses = 1;
2759
2760    return D3D_OK;
2761}
2762
2763HRESULT WINAPI
2764NineDevice9_SetPaletteEntries( struct NineDevice9 *This,
2765                               UINT PaletteNumber,
2766                               const PALETTEENTRY *pEntries )
2767{
2768    STUB(D3D_OK); /* like wine */
2769}
2770
2771HRESULT WINAPI
2772NineDevice9_GetPaletteEntries( struct NineDevice9 *This,
2773                               UINT PaletteNumber,
2774                               PALETTEENTRY *pEntries )
2775{
2776    STUB(D3DERR_INVALIDCALL);
2777}
2778
2779HRESULT WINAPI
2780NineDevice9_SetCurrentTexturePalette( struct NineDevice9 *This,
2781                                      UINT PaletteNumber )
2782{
2783    STUB(D3D_OK); /* like wine */
2784}
2785
2786HRESULT WINAPI
2787NineDevice9_GetCurrentTexturePalette( struct NineDevice9 *This,
2788                                      UINT *PaletteNumber )
2789{
2790    STUB(D3DERR_INVALIDCALL);
2791}
2792
2793HRESULT WINAPI
2794NineDevice9_SetScissorRect( struct NineDevice9 *This,
2795                            const RECT *pRect )
2796{
2797    struct nine_state *state = This->update;
2798
2799    DBG("x=(%u..%u) y=(%u..%u)\n",
2800        pRect->left, pRect->top, pRect->right, pRect->bottom);
2801
2802    state->scissor.minx = pRect->left;
2803    state->scissor.miny = pRect->top;
2804    state->scissor.maxx = pRect->right;
2805    state->scissor.maxy = pRect->bottom;
2806
2807    state->changed.group |= NINE_STATE_SCISSOR;
2808
2809    return D3D_OK;
2810}
2811
2812HRESULT WINAPI
2813NineDevice9_GetScissorRect( struct NineDevice9 *This,
2814                            RECT *pRect )
2815{
2816    pRect->left   = This->state.scissor.minx;
2817    pRect->top    = This->state.scissor.miny;
2818    pRect->right  = This->state.scissor.maxx;
2819    pRect->bottom = This->state.scissor.maxy;
2820
2821    return D3D_OK;
2822}
2823
2824HRESULT WINAPI
2825NineDevice9_SetSoftwareVertexProcessing( struct NineDevice9 *This,
2826                                         BOOL bSoftware )
2827{
2828    STUB(D3DERR_INVALIDCALL);
2829}
2830
2831BOOL WINAPI
2832NineDevice9_GetSoftwareVertexProcessing( struct NineDevice9 *This )
2833{
2834    return !!(This->params.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING);
2835}
2836
2837HRESULT WINAPI
2838NineDevice9_SetNPatchMode( struct NineDevice9 *This,
2839                           float nSegments )
2840{
2841    STUB(D3DERR_INVALIDCALL);
2842}
2843
2844float WINAPI
2845NineDevice9_GetNPatchMode( struct NineDevice9 *This )
2846{
2847    STUB(0);
2848}
2849
2850static inline void
2851init_draw_info(struct pipe_draw_info *info,
2852               struct NineDevice9 *dev, D3DPRIMITIVETYPE type, UINT count)
2853{
2854    info->mode = d3dprimitivetype_to_pipe_prim(type);
2855    info->count = prim_count_to_vertex_count(type, count);
2856    info->start_instance = 0;
2857    info->instance_count = 1;
2858    if (dev->state.stream_instancedata_mask & dev->state.stream_usage_mask)
2859        info->instance_count = MAX2(dev->state.stream_freq[0] & 0x7FFFFF, 1);
2860    info->primitive_restart = FALSE;
2861    info->restart_index = 0;
2862    info->count_from_stream_output = NULL;
2863    info->indirect = NULL;
2864}
2865
2866HRESULT WINAPI
2867NineDevice9_DrawPrimitive( struct NineDevice9 *This,
2868                           D3DPRIMITIVETYPE PrimitiveType,
2869                           UINT StartVertex,
2870                           UINT PrimitiveCount )
2871{
2872    struct pipe_draw_info info;
2873
2874    DBG("iface %p, PrimitiveType %u, StartVertex %u, PrimitiveCount %u\n",
2875        This, PrimitiveType, StartVertex, PrimitiveCount);
2876
2877    nine_update_state(This);
2878
2879    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
2880    info.indexed = FALSE;
2881    info.start = StartVertex;
2882    info.index_bias = 0;
2883    info.min_index = info.start;
2884    info.max_index = info.count - 1;
2885
2886    This->pipe->draw_vbo(This->pipe, &info);
2887
2888    return D3D_OK;
2889}
2890
2891HRESULT WINAPI
2892NineDevice9_DrawIndexedPrimitive( struct NineDevice9 *This,
2893                                  D3DPRIMITIVETYPE PrimitiveType,
2894                                  INT BaseVertexIndex,
2895                                  UINT MinVertexIndex,
2896                                  UINT NumVertices,
2897                                  UINT StartIndex,
2898                                  UINT PrimitiveCount )
2899{
2900    struct pipe_draw_info info;
2901
2902    DBG("iface %p, PrimitiveType %u, BaseVertexIndex %u, MinVertexIndex %u "
2903        "NumVertices %u, StartIndex %u, PrimitiveCount %u\n",
2904        This, PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices,
2905        StartIndex, PrimitiveCount);
2906
2907    user_assert(This->state.idxbuf, D3DERR_INVALIDCALL);
2908    user_assert(This->state.vdecl, D3DERR_INVALIDCALL);
2909
2910    nine_update_state(This);
2911
2912    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
2913    info.indexed = TRUE;
2914    info.start = StartIndex;
2915    info.index_bias = BaseVertexIndex;
2916    /* These don't include index bias: */
2917    info.min_index = MinVertexIndex;
2918    info.max_index = MinVertexIndex + NumVertices - 1;
2919
2920    This->pipe->draw_vbo(This->pipe, &info);
2921
2922    return D3D_OK;
2923}
2924
2925HRESULT WINAPI
2926NineDevice9_DrawPrimitiveUP( struct NineDevice9 *This,
2927                             D3DPRIMITIVETYPE PrimitiveType,
2928                             UINT PrimitiveCount,
2929                             const void *pVertexStreamZeroData,
2930                             UINT VertexStreamZeroStride )
2931{
2932    struct pipe_vertex_buffer vtxbuf;
2933    struct pipe_draw_info info;
2934
2935    DBG("iface %p, PrimitiveType %u, PrimitiveCount %u, data %p, stride %u\n",
2936        This, PrimitiveType, PrimitiveCount,
2937        pVertexStreamZeroData, VertexStreamZeroStride);
2938
2939    user_assert(pVertexStreamZeroData && VertexStreamZeroStride,
2940                D3DERR_INVALIDCALL);
2941
2942    nine_update_state(This);
2943
2944    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
2945    info.indexed = FALSE;
2946    info.start = 0;
2947    info.index_bias = 0;
2948    info.min_index = 0;
2949    info.max_index = info.count - 1;
2950
2951    vtxbuf.stride = VertexStreamZeroStride;
2952    vtxbuf.buffer_offset = 0;
2953    vtxbuf.buffer = NULL;
2954    vtxbuf.user_buffer = pVertexStreamZeroData;
2955
2956    if (!This->driver_caps.user_vbufs) {
2957        u_upload_data(This->vertex_uploader,
2958                      0,
2959                      (info.max_index + 1) * VertexStreamZeroStride, /* XXX */
2960                      4,
2961                      vtxbuf.user_buffer,
2962                      &vtxbuf.buffer_offset,
2963                      &vtxbuf.buffer);
2964        u_upload_unmap(This->vertex_uploader);
2965        vtxbuf.user_buffer = NULL;
2966    }
2967
2968    This->pipe->set_vertex_buffers(This->pipe, 0, 1, &vtxbuf);
2969
2970    This->pipe->draw_vbo(This->pipe, &info);
2971
2972    NineDevice9_PauseRecording(This);
2973    NineDevice9_SetStreamSource(This, 0, NULL, 0, 0);
2974    NineDevice9_ResumeRecording(This);
2975
2976    pipe_resource_reference(&vtxbuf.buffer, NULL);
2977
2978    return D3D_OK;
2979}
2980
2981HRESULT WINAPI
2982NineDevice9_DrawIndexedPrimitiveUP( struct NineDevice9 *This,
2983                                    D3DPRIMITIVETYPE PrimitiveType,
2984                                    UINT MinVertexIndex,
2985                                    UINT NumVertices,
2986                                    UINT PrimitiveCount,
2987                                    const void *pIndexData,
2988                                    D3DFORMAT IndexDataFormat,
2989                                    const void *pVertexStreamZeroData,
2990                                    UINT VertexStreamZeroStride )
2991{
2992    struct pipe_draw_info info;
2993    struct pipe_vertex_buffer vbuf;
2994    struct pipe_index_buffer ibuf;
2995
2996    DBG("iface %p, PrimitiveType %u, MinVertexIndex %u, NumVertices %u "
2997        "PrimitiveCount %u, pIndexData %p, IndexDataFormat %u "
2998        "pVertexStreamZeroData %p, VertexStreamZeroStride %u\n",
2999        This, PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount,
3000        pIndexData, IndexDataFormat,
3001        pVertexStreamZeroData, VertexStreamZeroStride);
3002
3003    user_assert(pIndexData && pVertexStreamZeroData, D3DERR_INVALIDCALL);
3004    user_assert(VertexStreamZeroStride, D3DERR_INVALIDCALL);
3005    user_assert(IndexDataFormat == D3DFMT_INDEX16 ||
3006                IndexDataFormat == D3DFMT_INDEX32, D3DERR_INVALIDCALL);
3007
3008    nine_update_state(This);
3009
3010    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
3011    info.indexed = TRUE;
3012    info.start = 0;
3013    info.index_bias = 0;
3014    info.min_index = MinVertexIndex;
3015    info.max_index = MinVertexIndex + NumVertices - 1;
3016
3017    vbuf.stride = VertexStreamZeroStride;
3018    vbuf.buffer_offset = 0;
3019    vbuf.buffer = NULL;
3020    vbuf.user_buffer = pVertexStreamZeroData;
3021
3022    ibuf.index_size = (IndexDataFormat == D3DFMT_INDEX16) ? 2 : 4;
3023    ibuf.offset = 0;
3024    ibuf.buffer = NULL;
3025    ibuf.user_buffer = pIndexData;
3026
3027    if (!This->driver_caps.user_vbufs) {
3028        const unsigned base = info.min_index * VertexStreamZeroStride;
3029        u_upload_data(This->vertex_uploader,
3030                      base,
3031                      (info.max_index -
3032                       info.min_index + 1) * VertexStreamZeroStride, /* XXX */
3033                      4,
3034                      (const uint8_t *)vbuf.user_buffer + base,
3035                      &vbuf.buffer_offset,
3036                      &vbuf.buffer);
3037        u_upload_unmap(This->vertex_uploader);
3038        /* Won't be used: */
3039        vbuf.buffer_offset -= base;
3040        vbuf.user_buffer = NULL;
3041    }
3042    if (!This->driver_caps.user_ibufs) {
3043        u_upload_data(This->index_uploader,
3044                      0,
3045                      info.count * ibuf.index_size,
3046                      4,
3047                      ibuf.user_buffer,
3048                      &ibuf.offset,
3049                      &ibuf.buffer);
3050        u_upload_unmap(This->index_uploader);
3051        ibuf.user_buffer = NULL;
3052    }
3053
3054    This->pipe->set_vertex_buffers(This->pipe, 0, 1, &vbuf);
3055    This->pipe->set_index_buffer(This->pipe, &ibuf);
3056
3057    This->pipe->draw_vbo(This->pipe, &info);
3058
3059    pipe_resource_reference(&vbuf.buffer, NULL);
3060    pipe_resource_reference(&ibuf.buffer, NULL);
3061
3062    NineDevice9_PauseRecording(This);
3063    NineDevice9_SetIndices(This, NULL);
3064    NineDevice9_SetStreamSource(This, 0, NULL, 0, 0);
3065    NineDevice9_ResumeRecording(This);
3066
3067    return D3D_OK;
3068}
3069
3070/* TODO: Write to pDestBuffer directly if vertex declaration contains
3071 * only f32 formats.
3072 */
3073HRESULT WINAPI
3074NineDevice9_ProcessVertices( struct NineDevice9 *This,
3075                             UINT SrcStartIndex,
3076                             UINT DestIndex,
3077                             UINT VertexCount,
3078                             IDirect3DVertexBuffer9 *pDestBuffer,
3079                             IDirect3DVertexDeclaration9 *pVertexDecl,
3080                             DWORD Flags )
3081{
3082    struct pipe_screen *screen = This->screen;
3083    struct NineVertexDeclaration9 *vdecl = NineVertexDeclaration9(pVertexDecl);
3084    struct NineVertexShader9 *vs;
3085    struct pipe_resource *resource;
3086    struct pipe_stream_output_target *target;
3087    struct pipe_draw_info draw;
3088    HRESULT hr;
3089    unsigned buffer_offset, buffer_size;
3090
3091    DBG("This=%p SrcStartIndex=%u DestIndex=%u VertexCount=%u "
3092        "pDestBuffer=%p pVertexDecl=%p Flags=%d\n",
3093        This, SrcStartIndex, DestIndex, VertexCount, pDestBuffer,
3094        pVertexDecl, Flags);
3095
3096    if (!screen->get_param(screen, PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS))
3097        STUB(D3DERR_INVALIDCALL);
3098
3099    nine_update_state(This);
3100
3101    /* TODO: Create shader with stream output. */
3102    STUB(D3DERR_INVALIDCALL);
3103    struct NineVertexBuffer9 *dst = NineVertexBuffer9(pDestBuffer);
3104
3105    vs = This->state.vs ? This->state.vs : This->ff.vs;
3106
3107    buffer_size = VertexCount * vs->so->stride[0];
3108    if (1) {
3109        struct pipe_resource templ;
3110
3111        templ.target = PIPE_BUFFER;
3112        templ.format = PIPE_FORMAT_R8_UNORM;
3113        templ.width0 = buffer_size;
3114        templ.flags = 0;
3115        templ.bind = PIPE_BIND_STREAM_OUTPUT;
3116        templ.usage = PIPE_USAGE_STREAM;
3117        templ.height0 = templ.depth0 = templ.array_size = 1;
3118        templ.last_level = templ.nr_samples = 0;
3119
3120        resource = This->screen->resource_create(This->screen, &templ);
3121        if (!resource)
3122            return E_OUTOFMEMORY;
3123        buffer_offset = 0;
3124    } else {
3125        /* SO matches vertex declaration */
3126        resource = NineVertexBuffer9_GetResource(dst);
3127        buffer_offset = DestIndex * vs->so->stride[0];
3128    }
3129    target = This->pipe->create_stream_output_target(This->pipe, resource,
3130                                                     buffer_offset,
3131                                                     buffer_size);
3132    if (!target) {
3133        pipe_resource_reference(&resource, NULL);
3134        return D3DERR_DRIVERINTERNALERROR;
3135    }
3136
3137    if (!vdecl) {
3138        hr = NineVertexDeclaration9_new_from_fvf(This, dst->desc.FVF, &vdecl);
3139        if (FAILED(hr))
3140            goto out;
3141    }
3142
3143    init_draw_info(&draw, This, D3DPT_POINTLIST, VertexCount);
3144    draw.instance_count = 1;
3145    draw.indexed = FALSE;
3146    draw.start = SrcStartIndex;
3147    draw.index_bias = 0;
3148    draw.min_index = SrcStartIndex;
3149    draw.max_index = SrcStartIndex + VertexCount - 1;
3150
3151    This->pipe->set_stream_output_targets(This->pipe, 1, &target, 0);
3152    This->pipe->draw_vbo(This->pipe, &draw);
3153    This->pipe->set_stream_output_targets(This->pipe, 0, NULL, 0);
3154    This->pipe->stream_output_target_destroy(This->pipe, target);
3155
3156    hr = NineVertexDeclaration9_ConvertStreamOutput(vdecl,
3157                                                    dst, DestIndex, VertexCount,
3158                                                    resource, vs->so);
3159out:
3160    pipe_resource_reference(&resource, NULL);
3161    if (!pVertexDecl)
3162        NineUnknown_Release(NineUnknown(vdecl));
3163    return hr;
3164}
3165
3166HRESULT WINAPI
3167NineDevice9_CreateVertexDeclaration( struct NineDevice9 *This,
3168                                     const D3DVERTEXELEMENT9 *pVertexElements,
3169                                     IDirect3DVertexDeclaration9 **ppDecl )
3170{
3171    struct NineVertexDeclaration9 *vdecl;
3172
3173    DBG("This=%p pVertexElements=%p ppDecl=%p\n",
3174        This, pVertexElements, ppDecl);
3175
3176    HRESULT hr = NineVertexDeclaration9_new(This, pVertexElements, &vdecl);
3177    if (SUCCEEDED(hr))
3178        *ppDecl = (IDirect3DVertexDeclaration9 *)vdecl;
3179
3180    return hr;
3181}
3182
3183HRESULT WINAPI
3184NineDevice9_SetVertexDeclaration( struct NineDevice9 *This,
3185                                  IDirect3DVertexDeclaration9 *pDecl )
3186{
3187    struct nine_state *state = This->update;
3188    BOOL was_programmable_vs = This->state.programmable_vs;
3189
3190    DBG("This=%p pDecl=%p\n", This, pDecl);
3191
3192    if (likely(!This->is_recording) && state->vdecl == NineVertexDeclaration9(pDecl))
3193        return D3D_OK;
3194
3195    nine_bind(&state->vdecl, pDecl);
3196
3197    This->state.programmable_vs = This->state.vs && !(This->state.vdecl && This->state.vdecl->position_t);
3198    if (likely(!This->is_recording) && was_programmable_vs != This->state.programmable_vs) {
3199        state->commit |= NINE_STATE_COMMIT_CONST_VS;
3200        state->changed.group |= NINE_STATE_VS;
3201    }
3202
3203    state->changed.group |= NINE_STATE_VDECL;
3204
3205    return D3D_OK;
3206}
3207
3208HRESULT WINAPI
3209NineDevice9_GetVertexDeclaration( struct NineDevice9 *This,
3210                                  IDirect3DVertexDeclaration9 **ppDecl )
3211{
3212    user_assert(ppDecl, D3DERR_INVALIDCALL);
3213
3214    *ppDecl = (IDirect3DVertexDeclaration9 *)This->state.vdecl;
3215    if (*ppDecl)
3216        NineUnknown_AddRef(NineUnknown(*ppDecl));
3217    return D3D_OK;
3218}
3219
3220HRESULT WINAPI
3221NineDevice9_SetFVF( struct NineDevice9 *This,
3222                    DWORD FVF )
3223{
3224    struct NineVertexDeclaration9 *vdecl;
3225    HRESULT hr;
3226
3227    DBG("FVF = %08x\n", FVF);
3228    if (!FVF)
3229        return D3D_OK; /* like wine */
3230
3231    vdecl = util_hash_table_get(This->ff.ht_fvf, &FVF);
3232    if (!vdecl) {
3233        hr = NineVertexDeclaration9_new_from_fvf(This, FVF, &vdecl);
3234        if (FAILED(hr))
3235            return hr;
3236        vdecl->fvf = FVF;
3237        util_hash_table_set(This->ff.ht_fvf, &vdecl->fvf, vdecl);
3238        NineUnknown_ConvertRefToBind(NineUnknown(vdecl));
3239    }
3240    return NineDevice9_SetVertexDeclaration(
3241        This, (IDirect3DVertexDeclaration9 *)vdecl);
3242}
3243
3244HRESULT WINAPI
3245NineDevice9_GetFVF( struct NineDevice9 *This,
3246                    DWORD *pFVF )
3247{
3248    *pFVF = This->state.vdecl ? This->state.vdecl->fvf : 0;
3249    return D3D_OK;
3250}
3251
3252HRESULT WINAPI
3253NineDevice9_CreateVertexShader( struct NineDevice9 *This,
3254                                const DWORD *pFunction,
3255                                IDirect3DVertexShader9 **ppShader )
3256{
3257    struct NineVertexShader9 *vs;
3258    HRESULT hr;
3259
3260    DBG("This=%p pFunction=%p ppShader=%p\n", This, pFunction, ppShader);
3261
3262    hr = NineVertexShader9_new(This, &vs, pFunction, NULL);
3263    if (FAILED(hr))
3264        return hr;
3265    *ppShader = (IDirect3DVertexShader9 *)vs;
3266    return D3D_OK;
3267}
3268
3269HRESULT WINAPI
3270NineDevice9_SetVertexShader( struct NineDevice9 *This,
3271                             IDirect3DVertexShader9 *pShader )
3272{
3273    struct nine_state *state = This->update;
3274    BOOL was_programmable_vs = This->state.programmable_vs;
3275
3276    DBG("This=%p pShader=%p\n", This, pShader);
3277
3278    if (!This->is_recording && state->vs == (struct NineVertexShader9*)pShader)
3279      return D3D_OK;
3280
3281    nine_bind(&state->vs, pShader);
3282
3283    This->state.programmable_vs = This->state.vs && !(This->state.vdecl && This->state.vdecl->position_t);
3284
3285    /* ff -> non-ff: commit back non-ff constants */
3286    if (!was_programmable_vs && This->state.programmable_vs)
3287        state->commit |= NINE_STATE_COMMIT_CONST_VS;
3288
3289    state->changed.group |= NINE_STATE_VS;
3290
3291    return D3D_OK;
3292}
3293
3294HRESULT WINAPI
3295NineDevice9_GetVertexShader( struct NineDevice9 *This,
3296                             IDirect3DVertexShader9 **ppShader )
3297{
3298    user_assert(ppShader, D3DERR_INVALIDCALL);
3299    nine_reference_set(ppShader, This->state.vs);
3300    return D3D_OK;
3301}
3302
3303HRESULT WINAPI
3304NineDevice9_SetVertexShaderConstantF( struct NineDevice9 *This,
3305                                      UINT StartRegister,
3306                                      const float *pConstantData,
3307                                      UINT Vector4fCount )
3308{
3309    struct nine_state *state = This->update;
3310
3311    DBG("This=%p StartRegister=%u pConstantData=%p Vector4fCount=%u\n",
3312        This, StartRegister, pConstantData, Vector4fCount);
3313
3314    user_assert(StartRegister                  < This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3315    user_assert(StartRegister + Vector4fCount <= This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3316
3317    if (!Vector4fCount)
3318       return D3D_OK;
3319    user_assert(pConstantData, D3DERR_INVALIDCALL);
3320
3321    if (!This->is_recording) {
3322        if (!memcmp(&state->vs_const_f[StartRegister * 4], pConstantData,
3323                    Vector4fCount * 4 * sizeof(state->vs_const_f[0])))
3324            return D3D_OK;
3325    }
3326
3327    memcpy(&state->vs_const_f[StartRegister * 4],
3328           pConstantData,
3329           Vector4fCount * 4 * sizeof(state->vs_const_f[0]));
3330
3331    nine_ranges_insert(&state->changed.vs_const_f,
3332                       StartRegister, StartRegister + Vector4fCount,
3333                       &This->range_pool);
3334
3335    state->changed.group |= NINE_STATE_VS_CONST;
3336
3337    return D3D_OK;
3338}
3339
3340HRESULT WINAPI
3341NineDevice9_GetVertexShaderConstantF( struct NineDevice9 *This,
3342                                      UINT StartRegister,
3343                                      float *pConstantData,
3344                                      UINT Vector4fCount )
3345{
3346    const struct nine_state *state = &This->state;
3347
3348    user_assert(StartRegister                  < This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3349    user_assert(StartRegister + Vector4fCount <= This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3350    user_assert(pConstantData, D3DERR_INVALIDCALL);
3351
3352    memcpy(pConstantData,
3353           &state->vs_const_f[StartRegister * 4],
3354           Vector4fCount * 4 * sizeof(state->vs_const_f[0]));
3355
3356    return D3D_OK;
3357}
3358
3359HRESULT WINAPI
3360NineDevice9_SetVertexShaderConstantI( struct NineDevice9 *This,
3361                                      UINT StartRegister,
3362                                      const int *pConstantData,
3363                                      UINT Vector4iCount )
3364{
3365    struct nine_state *state = This->update;
3366    int i;
3367
3368    DBG("This=%p StartRegister=%u pConstantData=%p Vector4iCount=%u\n",
3369        This, StartRegister, pConstantData, Vector4iCount);
3370
3371    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3372    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3373    user_assert(pConstantData, D3DERR_INVALIDCALL);
3374
3375    if (This->driver_caps.vs_integer) {
3376        if (!This->is_recording) {
3377            if (!memcmp(&state->vs_const_i[StartRegister][0], pConstantData,
3378                        Vector4iCount * sizeof(state->vs_const_i[0])))
3379                return D3D_OK;
3380        }
3381        memcpy(&state->vs_const_i[StartRegister][0],
3382               pConstantData,
3383               Vector4iCount * sizeof(state->vs_const_i[0]));
3384    } else {
3385        for (i = 0; i < Vector4iCount; i++) {
3386            state->vs_const_i[StartRegister+i][0] = fui((float)(pConstantData[4*i]));
3387            state->vs_const_i[StartRegister+i][1] = fui((float)(pConstantData[4*i+1]));
3388            state->vs_const_i[StartRegister+i][2] = fui((float)(pConstantData[4*i+2]));
3389            state->vs_const_i[StartRegister+i][3] = fui((float)(pConstantData[4*i+3]));
3390        }
3391    }
3392
3393    state->changed.vs_const_i |= ((1 << Vector4iCount) - 1) << StartRegister;
3394    state->changed.group |= NINE_STATE_VS_CONST;
3395
3396    return D3D_OK;
3397}
3398
3399HRESULT WINAPI
3400NineDevice9_GetVertexShaderConstantI( struct NineDevice9 *This,
3401                                      UINT StartRegister,
3402                                      int *pConstantData,
3403                                      UINT Vector4iCount )
3404{
3405    const struct nine_state *state = &This->state;
3406    int i;
3407
3408    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3409    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3410    user_assert(pConstantData, D3DERR_INVALIDCALL);
3411
3412    if (This->driver_caps.vs_integer) {
3413        memcpy(pConstantData,
3414               &state->vs_const_i[StartRegister][0],
3415               Vector4iCount * sizeof(state->vs_const_i[0]));
3416    } else {
3417        for (i = 0; i < Vector4iCount; i++) {
3418            pConstantData[4*i] = (int32_t) uif(state->vs_const_i[StartRegister+i][0]);
3419            pConstantData[4*i+1] = (int32_t) uif(state->vs_const_i[StartRegister+i][1]);
3420            pConstantData[4*i+2] = (int32_t) uif(state->vs_const_i[StartRegister+i][2]);
3421            pConstantData[4*i+3] = (int32_t) uif(state->vs_const_i[StartRegister+i][3]);
3422        }
3423    }
3424
3425    return D3D_OK;
3426}
3427
3428HRESULT WINAPI
3429NineDevice9_SetVertexShaderConstantB( struct NineDevice9 *This,
3430                                      UINT StartRegister,
3431                                      const BOOL *pConstantData,
3432                                      UINT BoolCount )
3433{
3434    struct nine_state *state = This->update;
3435    int i;
3436    uint32_t bool_true = This->driver_caps.vs_integer ? 0xFFFFFFFF : fui(1.0f);
3437
3438    DBG("This=%p StartRegister=%u pConstantData=%p BoolCount=%u\n",
3439        This, StartRegister, pConstantData, BoolCount);
3440
3441    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3442    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3443    user_assert(pConstantData, D3DERR_INVALIDCALL);
3444
3445    if (!This->is_recording) {
3446        bool noChange = true;
3447        for (i = 0; i < BoolCount; i++) {
3448            if (!!state->vs_const_b[StartRegister + i] != !!pConstantData[i])
3449              noChange = false;
3450        }
3451        if (noChange)
3452            return D3D_OK;
3453    }
3454
3455    for (i = 0; i < BoolCount; i++)
3456        state->vs_const_b[StartRegister + i] = pConstantData[i] ? bool_true : 0;
3457
3458    state->changed.vs_const_b |= ((1 << BoolCount) - 1) << StartRegister;
3459    state->changed.group |= NINE_STATE_VS_CONST;
3460
3461    return D3D_OK;
3462}
3463
3464HRESULT WINAPI
3465NineDevice9_GetVertexShaderConstantB( struct NineDevice9 *This,
3466                                      UINT StartRegister,
3467                                      BOOL *pConstantData,
3468                                      UINT BoolCount )
3469{
3470    const struct nine_state *state = &This->state;
3471    int i;
3472
3473    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3474    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3475    user_assert(pConstantData, D3DERR_INVALIDCALL);
3476
3477    for (i = 0; i < BoolCount; i++)
3478        pConstantData[i] = state->vs_const_b[StartRegister + i] != 0 ? TRUE : FALSE;
3479
3480    return D3D_OK;
3481}
3482
3483HRESULT WINAPI
3484NineDevice9_SetStreamSource( struct NineDevice9 *This,
3485                             UINT StreamNumber,
3486                             IDirect3DVertexBuffer9 *pStreamData,
3487                             UINT OffsetInBytes,
3488                             UINT Stride )
3489{
3490    struct nine_state *state = This->update;
3491    struct NineVertexBuffer9 *pVBuf9 = NineVertexBuffer9(pStreamData);
3492    const unsigned i = StreamNumber;
3493
3494    DBG("This=%p StreamNumber=%u pStreamData=%p OffsetInBytes=%u Stride=%u\n",
3495        This, StreamNumber, pStreamData, OffsetInBytes, Stride);
3496
3497    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3498    user_assert(Stride <= This->caps.MaxStreamStride, D3DERR_INVALIDCALL);
3499
3500    if (likely(!This->is_recording)) {
3501        if (state->stream[i] == NineVertexBuffer9(pStreamData) &&
3502            state->vtxbuf[i].stride == Stride &&
3503            state->vtxbuf[i].buffer_offset == OffsetInBytes)
3504            return D3D_OK;
3505    }
3506    nine_bind(&state->stream[i], pStreamData);
3507
3508    state->changed.vtxbuf |= 1 << StreamNumber;
3509
3510    if (pStreamData) {
3511        state->vtxbuf[i].stride = Stride;
3512        state->vtxbuf[i].buffer_offset = OffsetInBytes;
3513    }
3514    pipe_resource_reference(&state->vtxbuf[i].buffer,
3515                            pStreamData ? NineVertexBuffer9_GetResource(pVBuf9) : NULL);
3516
3517    return D3D_OK;
3518}
3519
3520HRESULT WINAPI
3521NineDevice9_GetStreamSource( struct NineDevice9 *This,
3522                             UINT StreamNumber,
3523                             IDirect3DVertexBuffer9 **ppStreamData,
3524                             UINT *pOffsetInBytes,
3525                             UINT *pStride )
3526{
3527    const struct nine_state *state = &This->state;
3528    const unsigned i = StreamNumber;
3529
3530    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3531    user_assert(ppStreamData, D3DERR_INVALIDCALL);
3532
3533    nine_reference_set(ppStreamData, state->stream[i]);
3534    *pStride = state->vtxbuf[i].stride;
3535    *pOffsetInBytes = state->vtxbuf[i].buffer_offset;
3536
3537    return D3D_OK;
3538}
3539
3540HRESULT WINAPI
3541NineDevice9_SetStreamSourceFreq( struct NineDevice9 *This,
3542                                 UINT StreamNumber,
3543                                 UINT Setting )
3544{
3545    struct nine_state *state = This->update;
3546    /* const UINT freq = Setting & 0x7FFFFF; */
3547
3548    DBG("This=%p StreamNumber=%u FrequencyParameter=0x%x\n", This,
3549        StreamNumber, Setting);
3550
3551    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3552    user_assert(StreamNumber != 0 || !(Setting & D3DSTREAMSOURCE_INSTANCEDATA),
3553                D3DERR_INVALIDCALL);
3554    user_assert(!((Setting & D3DSTREAMSOURCE_INSTANCEDATA) &&
3555                  (Setting & D3DSTREAMSOURCE_INDEXEDDATA)), D3DERR_INVALIDCALL);
3556    user_assert(Setting, D3DERR_INVALIDCALL);
3557
3558    state->stream_freq[StreamNumber] = Setting;
3559
3560    if (Setting & D3DSTREAMSOURCE_INSTANCEDATA)
3561        state->stream_instancedata_mask |= 1 << StreamNumber;
3562    else
3563        state->stream_instancedata_mask &= ~(1 << StreamNumber);
3564
3565    state->changed.stream_freq |= 1 << StreamNumber;
3566    return D3D_OK;
3567}
3568
3569HRESULT WINAPI
3570NineDevice9_GetStreamSourceFreq( struct NineDevice9 *This,
3571                                 UINT StreamNumber,
3572                                 UINT *pSetting )
3573{
3574    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3575    *pSetting = This->state.stream_freq[StreamNumber];
3576    return D3D_OK;
3577}
3578
3579HRESULT WINAPI
3580NineDevice9_SetIndices( struct NineDevice9 *This,
3581                        IDirect3DIndexBuffer9 *pIndexData )
3582{
3583    struct nine_state *state = This->update;
3584
3585    DBG("This=%p pIndexData=%p\n", This, pIndexData);
3586
3587    if (likely(!This->is_recording))
3588        if (state->idxbuf == NineIndexBuffer9(pIndexData))
3589            return D3D_OK;
3590    nine_bind(&state->idxbuf, pIndexData);
3591
3592    state->changed.group |= NINE_STATE_IDXBUF;
3593
3594    return D3D_OK;
3595}
3596
3597/* XXX: wine/d3d9 doesn't have pBaseVertexIndex, and it doesn't make sense
3598 * here because it's an argument passed to the Draw calls.
3599 */
3600HRESULT WINAPI
3601NineDevice9_GetIndices( struct NineDevice9 *This,
3602                        IDirect3DIndexBuffer9 **ppIndexData /*,
3603                        UINT *pBaseVertexIndex */ )
3604{
3605    user_assert(ppIndexData, D3DERR_INVALIDCALL);
3606    nine_reference_set(ppIndexData, This->state.idxbuf);
3607    return D3D_OK;
3608}
3609
3610HRESULT WINAPI
3611NineDevice9_CreatePixelShader( struct NineDevice9 *This,
3612                               const DWORD *pFunction,
3613                               IDirect3DPixelShader9 **ppShader )
3614{
3615    struct NinePixelShader9 *ps;
3616    HRESULT hr;
3617
3618    DBG("This=%p pFunction=%p ppShader=%p\n", This, pFunction, ppShader);
3619
3620    hr = NinePixelShader9_new(This, &ps, pFunction, NULL);
3621    if (FAILED(hr))
3622        return hr;
3623    *ppShader = (IDirect3DPixelShader9 *)ps;
3624    return D3D_OK;
3625}
3626
3627HRESULT WINAPI
3628NineDevice9_SetPixelShader( struct NineDevice9 *This,
3629                            IDirect3DPixelShader9 *pShader )
3630{
3631    struct nine_state *state = This->update;
3632    unsigned old_mask = state->ps ? state->ps->rt_mask : 1;
3633    unsigned mask;
3634
3635    DBG("This=%p pShader=%p\n", This, pShader);
3636
3637    if (!This->is_recording && state->ps == (struct NinePixelShader9*)pShader)
3638      return D3D_OK;
3639
3640    /* ff -> non-ff: commit back non-ff constants */
3641    if (!state->ps && pShader)
3642        state->commit |= NINE_STATE_COMMIT_CONST_PS;
3643
3644    nine_bind(&state->ps, pShader);
3645
3646    state->changed.group |= NINE_STATE_PS;
3647
3648    mask = state->ps ? state->ps->rt_mask : 1;
3649    /* We need to update cbufs if the pixel shader would
3650     * write to different render targets */
3651    if (mask != old_mask)
3652        state->changed.group |= NINE_STATE_FB;
3653
3654    return D3D_OK;
3655}
3656
3657HRESULT WINAPI
3658NineDevice9_GetPixelShader( struct NineDevice9 *This,
3659                            IDirect3DPixelShader9 **ppShader )
3660{
3661    user_assert(ppShader, D3DERR_INVALIDCALL);
3662    nine_reference_set(ppShader, This->state.ps);
3663    return D3D_OK;
3664}
3665
3666HRESULT WINAPI
3667NineDevice9_SetPixelShaderConstantF( struct NineDevice9 *This,
3668                                     UINT StartRegister,
3669                                     const float *pConstantData,
3670                                     UINT Vector4fCount )
3671{
3672    struct nine_state *state = This->update;
3673
3674    DBG("This=%p StartRegister=%u pConstantData=%p Vector4fCount=%u\n",
3675        This, StartRegister, pConstantData, Vector4fCount);
3676
3677    user_assert(StartRegister                  < NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3678    user_assert(StartRegister + Vector4fCount <= NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3679
3680    if (!Vector4fCount)
3681       return D3D_OK;
3682    user_assert(pConstantData, D3DERR_INVALIDCALL);
3683
3684    if (!This->is_recording) {
3685        if (!memcmp(&state->ps_const_f[StartRegister * 4], pConstantData,
3686                    Vector4fCount * 4 * sizeof(state->ps_const_f[0])))
3687            return D3D_OK;
3688    }
3689
3690    memcpy(&state->ps_const_f[StartRegister * 4],
3691           pConstantData,
3692           Vector4fCount * 4 * sizeof(state->ps_const_f[0]));
3693
3694    nine_ranges_insert(&state->changed.ps_const_f,
3695                       StartRegister, StartRegister + Vector4fCount,
3696                       &This->range_pool);
3697
3698    state->changed.group |= NINE_STATE_PS_CONST;
3699
3700    return D3D_OK;
3701}
3702
3703HRESULT WINAPI
3704NineDevice9_GetPixelShaderConstantF( struct NineDevice9 *This,
3705                                     UINT StartRegister,
3706                                     float *pConstantData,
3707                                     UINT Vector4fCount )
3708{
3709    const struct nine_state *state = &This->state;
3710
3711    user_assert(StartRegister                  < NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3712    user_assert(StartRegister + Vector4fCount <= NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3713    user_assert(pConstantData, D3DERR_INVALIDCALL);
3714
3715    memcpy(pConstantData,
3716           &state->ps_const_f[StartRegister * 4],
3717           Vector4fCount * 4 * sizeof(state->ps_const_f[0]));
3718
3719    return D3D_OK;
3720}
3721
3722HRESULT WINAPI
3723NineDevice9_SetPixelShaderConstantI( struct NineDevice9 *This,
3724                                     UINT StartRegister,
3725                                     const int *pConstantData,
3726                                     UINT Vector4iCount )
3727{
3728    struct nine_state *state = This->update;
3729    int i;
3730
3731    DBG("This=%p StartRegister=%u pConstantData=%p Vector4iCount=%u\n",
3732        This, StartRegister, pConstantData, Vector4iCount);
3733
3734    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3735    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3736    user_assert(pConstantData, D3DERR_INVALIDCALL);
3737
3738    if (This->driver_caps.ps_integer) {
3739        if (!This->is_recording) {
3740            if (!memcmp(&state->ps_const_i[StartRegister][0], pConstantData,
3741                        Vector4iCount * sizeof(state->ps_const_i[0])))
3742                return D3D_OK;
3743        }
3744        memcpy(&state->ps_const_i[StartRegister][0],
3745               pConstantData,
3746               Vector4iCount * sizeof(state->ps_const_i[0]));
3747    } else {
3748        for (i = 0; i < Vector4iCount; i++) {
3749            state->ps_const_i[StartRegister+i][0] = fui((float)(pConstantData[4*i]));
3750            state->ps_const_i[StartRegister+i][1] = fui((float)(pConstantData[4*i+1]));
3751            state->ps_const_i[StartRegister+i][2] = fui((float)(pConstantData[4*i+2]));
3752            state->ps_const_i[StartRegister+i][3] = fui((float)(pConstantData[4*i+3]));
3753        }
3754    }
3755    state->changed.ps_const_i |= ((1 << Vector4iCount) - 1) << StartRegister;
3756    state->changed.group |= NINE_STATE_PS_CONST;
3757
3758    return D3D_OK;
3759}
3760
3761HRESULT WINAPI
3762NineDevice9_GetPixelShaderConstantI( struct NineDevice9 *This,
3763                                     UINT StartRegister,
3764                                     int *pConstantData,
3765                                     UINT Vector4iCount )
3766{
3767    const struct nine_state *state = &This->state;
3768    int i;
3769
3770    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3771    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3772    user_assert(pConstantData, D3DERR_INVALIDCALL);
3773
3774    if (This->driver_caps.ps_integer) {
3775        memcpy(pConstantData,
3776               &state->ps_const_i[StartRegister][0],
3777               Vector4iCount * sizeof(state->ps_const_i[0]));
3778    } else {
3779        for (i = 0; i < Vector4iCount; i++) {
3780            pConstantData[4*i] = (int32_t) uif(state->ps_const_i[StartRegister+i][0]);
3781            pConstantData[4*i+1] = (int32_t) uif(state->ps_const_i[StartRegister+i][1]);
3782            pConstantData[4*i+2] = (int32_t) uif(state->ps_const_i[StartRegister+i][2]);
3783            pConstantData[4*i+3] = (int32_t) uif(state->ps_const_i[StartRegister+i][3]);
3784        }
3785    }
3786
3787    return D3D_OK;
3788}
3789
3790HRESULT WINAPI
3791NineDevice9_SetPixelShaderConstantB( struct NineDevice9 *This,
3792                                     UINT StartRegister,
3793                                     const BOOL *pConstantData,
3794                                     UINT BoolCount )
3795{
3796    struct nine_state *state = This->update;
3797    int i;
3798    uint32_t bool_true = This->driver_caps.ps_integer ? 0xFFFFFFFF : fui(1.0f);
3799
3800    DBG("This=%p StartRegister=%u pConstantData=%p BoolCount=%u\n",
3801        This, StartRegister, pConstantData, BoolCount);
3802
3803    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3804    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3805    user_assert(pConstantData, D3DERR_INVALIDCALL);
3806
3807    if (!This->is_recording) {
3808        bool noChange = true;
3809        for (i = 0; i < BoolCount; i++) {
3810            if (!!state->ps_const_b[StartRegister + i] != !!pConstantData[i])
3811              noChange = false;
3812        }
3813        if (noChange)
3814            return D3D_OK;
3815    }
3816
3817    for (i = 0; i < BoolCount; i++)
3818        state->ps_const_b[StartRegister + i] = pConstantData[i] ? bool_true : 0;
3819
3820    state->changed.ps_const_b |= ((1 << BoolCount) - 1) << StartRegister;
3821    state->changed.group |= NINE_STATE_PS_CONST;
3822
3823    return D3D_OK;
3824}
3825
3826HRESULT WINAPI
3827NineDevice9_GetPixelShaderConstantB( struct NineDevice9 *This,
3828                                     UINT StartRegister,
3829                                     BOOL *pConstantData,
3830                                     UINT BoolCount )
3831{
3832    const struct nine_state *state = &This->state;
3833    int i;
3834
3835    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3836    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3837    user_assert(pConstantData, D3DERR_INVALIDCALL);
3838
3839    for (i = 0; i < BoolCount; i++)
3840        pConstantData[i] = state->ps_const_b[StartRegister + i] ? TRUE : FALSE;
3841
3842    return D3D_OK;
3843}
3844
3845HRESULT WINAPI
3846NineDevice9_DrawRectPatch( struct NineDevice9 *This,
3847                           UINT Handle,
3848                           const float *pNumSegs,
3849                           const D3DRECTPATCH_INFO *pRectPatchInfo )
3850{
3851    STUB(D3DERR_INVALIDCALL);
3852}
3853
3854HRESULT WINAPI
3855NineDevice9_DrawTriPatch( struct NineDevice9 *This,
3856                          UINT Handle,
3857                          const float *pNumSegs,
3858                          const D3DTRIPATCH_INFO *pTriPatchInfo )
3859{
3860    STUB(D3DERR_INVALIDCALL);
3861}
3862
3863HRESULT WINAPI
3864NineDevice9_DeletePatch( struct NineDevice9 *This,
3865                         UINT Handle )
3866{
3867    STUB(D3DERR_INVALIDCALL);
3868}
3869
3870HRESULT WINAPI
3871NineDevice9_CreateQuery( struct NineDevice9 *This,
3872                         D3DQUERYTYPE Type,
3873                         IDirect3DQuery9 **ppQuery )
3874{
3875    struct NineQuery9 *query;
3876    HRESULT hr;
3877
3878    DBG("This=%p Type=%d ppQuery=%p\n", This, Type, ppQuery);
3879
3880    hr = nine_is_query_supported(This->screen, Type);
3881    if (!ppQuery || hr != D3D_OK)
3882        return hr;
3883
3884    hr = NineQuery9_new(This, &query, Type);
3885    if (FAILED(hr))
3886        return hr;
3887    *ppQuery = (IDirect3DQuery9 *)query;
3888    return D3D_OK;
3889}
3890
3891IDirect3DDevice9Vtbl NineDevice9_vtable = {
3892    (void *)NineUnknown_QueryInterface,
3893    (void *)NineUnknown_AddRef,
3894    (void *)NineUnknown_Release,
3895    (void *)NineDevice9_TestCooperativeLevel,
3896    (void *)NineDevice9_GetAvailableTextureMem,
3897    (void *)NineDevice9_EvictManagedResources,
3898    (void *)NineDevice9_GetDirect3D,
3899    (void *)NineDevice9_GetDeviceCaps,
3900    (void *)NineDevice9_GetDisplayMode,
3901    (void *)NineDevice9_GetCreationParameters,
3902    (void *)NineDevice9_SetCursorProperties,
3903    (void *)NineDevice9_SetCursorPosition,
3904    (void *)NineDevice9_ShowCursor,
3905    (void *)NineDevice9_CreateAdditionalSwapChain,
3906    (void *)NineDevice9_GetSwapChain,
3907    (void *)NineDevice9_GetNumberOfSwapChains,
3908    (void *)NineDevice9_Reset,
3909    (void *)NineDevice9_Present,
3910    (void *)NineDevice9_GetBackBuffer,
3911    (void *)NineDevice9_GetRasterStatus,
3912    (void *)NineDevice9_SetDialogBoxMode,
3913    (void *)NineDevice9_SetGammaRamp,
3914    (void *)NineDevice9_GetGammaRamp,
3915    (void *)NineDevice9_CreateTexture,
3916    (void *)NineDevice9_CreateVolumeTexture,
3917    (void *)NineDevice9_CreateCubeTexture,
3918    (void *)NineDevice9_CreateVertexBuffer,
3919    (void *)NineDevice9_CreateIndexBuffer,
3920    (void *)NineDevice9_CreateRenderTarget,
3921    (void *)NineDevice9_CreateDepthStencilSurface,
3922    (void *)NineDevice9_UpdateSurface,
3923    (void *)NineDevice9_UpdateTexture,
3924    (void *)NineDevice9_GetRenderTargetData,
3925    (void *)NineDevice9_GetFrontBufferData,
3926    (void *)NineDevice9_StretchRect,
3927    (void *)NineDevice9_ColorFill,
3928    (void *)NineDevice9_CreateOffscreenPlainSurface,
3929    (void *)NineDevice9_SetRenderTarget,
3930    (void *)NineDevice9_GetRenderTarget,
3931    (void *)NineDevice9_SetDepthStencilSurface,
3932    (void *)NineDevice9_GetDepthStencilSurface,
3933    (void *)NineDevice9_BeginScene,
3934    (void *)NineDevice9_EndScene,
3935    (void *)NineDevice9_Clear,
3936    (void *)NineDevice9_SetTransform,
3937    (void *)NineDevice9_GetTransform,
3938    (void *)NineDevice9_MultiplyTransform,
3939    (void *)NineDevice9_SetViewport,
3940    (void *)NineDevice9_GetViewport,
3941    (void *)NineDevice9_SetMaterial,
3942    (void *)NineDevice9_GetMaterial,
3943    (void *)NineDevice9_SetLight,
3944    (void *)NineDevice9_GetLight,
3945    (void *)NineDevice9_LightEnable,
3946    (void *)NineDevice9_GetLightEnable,
3947    (void *)NineDevice9_SetClipPlane,
3948    (void *)NineDevice9_GetClipPlane,
3949    (void *)NineDevice9_SetRenderState,
3950    (void *)NineDevice9_GetRenderState,
3951    (void *)NineDevice9_CreateStateBlock,
3952    (void *)NineDevice9_BeginStateBlock,
3953    (void *)NineDevice9_EndStateBlock,
3954    (void *)NineDevice9_SetClipStatus,
3955    (void *)NineDevice9_GetClipStatus,
3956    (void *)NineDevice9_GetTexture,
3957    (void *)NineDevice9_SetTexture,
3958    (void *)NineDevice9_GetTextureStageState,
3959    (void *)NineDevice9_SetTextureStageState,
3960    (void *)NineDevice9_GetSamplerState,
3961    (void *)NineDevice9_SetSamplerState,
3962    (void *)NineDevice9_ValidateDevice,
3963    (void *)NineDevice9_SetPaletteEntries,
3964    (void *)NineDevice9_GetPaletteEntries,
3965    (void *)NineDevice9_SetCurrentTexturePalette,
3966    (void *)NineDevice9_GetCurrentTexturePalette,
3967    (void *)NineDevice9_SetScissorRect,
3968    (void *)NineDevice9_GetScissorRect,
3969    (void *)NineDevice9_SetSoftwareVertexProcessing,
3970    (void *)NineDevice9_GetSoftwareVertexProcessing,
3971    (void *)NineDevice9_SetNPatchMode,
3972    (void *)NineDevice9_GetNPatchMode,
3973    (void *)NineDevice9_DrawPrimitive,
3974    (void *)NineDevice9_DrawIndexedPrimitive,
3975    (void *)NineDevice9_DrawPrimitiveUP,
3976    (void *)NineDevice9_DrawIndexedPrimitiveUP,
3977    (void *)NineDevice9_ProcessVertices,
3978    (void *)NineDevice9_CreateVertexDeclaration,
3979    (void *)NineDevice9_SetVertexDeclaration,
3980    (void *)NineDevice9_GetVertexDeclaration,
3981    (void *)NineDevice9_SetFVF,
3982    (void *)NineDevice9_GetFVF,
3983    (void *)NineDevice9_CreateVertexShader,
3984    (void *)NineDevice9_SetVertexShader,
3985    (void *)NineDevice9_GetVertexShader,
3986    (void *)NineDevice9_SetVertexShaderConstantF,
3987    (void *)NineDevice9_GetVertexShaderConstantF,
3988    (void *)NineDevice9_SetVertexShaderConstantI,
3989    (void *)NineDevice9_GetVertexShaderConstantI,
3990    (void *)NineDevice9_SetVertexShaderConstantB,
3991    (void *)NineDevice9_GetVertexShaderConstantB,
3992    (void *)NineDevice9_SetStreamSource,
3993    (void *)NineDevice9_GetStreamSource,
3994    (void *)NineDevice9_SetStreamSourceFreq,
3995    (void *)NineDevice9_GetStreamSourceFreq,
3996    (void *)NineDevice9_SetIndices,
3997    (void *)NineDevice9_GetIndices,
3998    (void *)NineDevice9_CreatePixelShader,
3999    (void *)NineDevice9_SetPixelShader,
4000    (void *)NineDevice9_GetPixelShader,
4001    (void *)NineDevice9_SetPixelShaderConstantF,
4002    (void *)NineDevice9_GetPixelShaderConstantF,
4003    (void *)NineDevice9_SetPixelShaderConstantI,
4004    (void *)NineDevice9_GetPixelShaderConstantI,
4005    (void *)NineDevice9_SetPixelShaderConstantB,
4006    (void *)NineDevice9_GetPixelShaderConstantB,
4007    (void *)NineDevice9_DrawRectPatch,
4008    (void *)NineDevice9_DrawTriPatch,
4009    (void *)NineDevice9_DeletePatch,
4010    (void *)NineDevice9_CreateQuery
4011};
4012
4013static const GUID *NineDevice9_IIDs[] = {
4014    &IID_IDirect3DDevice9,
4015    &IID_IUnknown,
4016    NULL
4017};
4018
4019HRESULT
4020NineDevice9_new( struct pipe_screen *pScreen,
4021                 D3DDEVICE_CREATION_PARAMETERS *pCreationParameters,
4022                 D3DCAPS9 *pCaps,
4023                 D3DPRESENT_PARAMETERS *pPresentationParameters,
4024                 IDirect3D9 *pD3D9,
4025                 ID3DPresentGroup *pPresentationGroup,
4026                 struct d3dadapter9_context *pCTX,
4027                 boolean ex,
4028                 D3DDISPLAYMODEEX *pFullscreenDisplayMode,
4029                 struct NineDevice9 **ppOut )
4030{
4031    BOOL lock;
4032    lock = !!(pCreationParameters->BehaviorFlags & D3DCREATE_MULTITHREADED);
4033
4034    NINE_NEW(Device9, ppOut, lock, /* args */
4035             pScreen, pCreationParameters, pCaps,
4036             pPresentationParameters, pD3D9, pPresentationGroup, pCTX,
4037             ex, pFullscreenDisplayMode);
4038}
4039