/*
 * Direct3D8 textures
 * Copyright (c) 2002, TransGaming Technologies Inc.
 */

#include "config.h"

#include "winbase.h"
#include "winuser.h"
#include "d3d8.h"
#include "wine/debug.h"

#include "d3d8_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(ddraw);

HRESULT WINAPI Direct3DTexture8_QueryInterface(LPDIRECT3DTEXTURE8 iface,
					       REFIID riid,
					       LPVOID* obj)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), obj);
  if (IsEqualGUID(&IID_IUnknown, riid) ||
      IsEqualGUID(&IID_IDirect3DResource8, riid) ||
      IsEqualGUID(&IID_IDirect3DBaseTexture8, riid) ||
      IsEqualGUID(&IID_IDirect3DTexture8, riid)) {
    This->ref++;
    *obj = This;
    return S_OK;
  }
  else {
    FIXME("(%p)->(%s): no interface", iface, debugstr_guid(riid));
    return E_NOINTERFACE;
  }
}

ULONG WINAPI Direct3DTexture8_AddRef(LPDIRECT3DTEXTURE8 iface)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  TRACE("(%p)->()\n", iface);
  return ++This->ref - This->intref;
}

ULONG WINAPI Direct3DTexture8_Release(LPDIRECT3DTEXTURE8 iface)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  unsigned u;

  TRACE("(%p)->()\n", iface);
  if (--This->ref) return This->ref - This->intref;

  for (u=0; u<This->Levels; u++) {
    IDirect3DSurface8Impl* surf = (IDirect3DSurface8Impl*)This->surf[u];
    if (This->parent->demolish_texture)
      This->parent->demolish_texture(This->parent->ip_ctx,
				     (DWORD)&surf->t);
    IDirect3DSurface8_Release(This->surf[u]);
  }

  /* take the texture out of the linked list */
  if (This->prev_device)
    This->prev_device->next_device = This->next_device;
  else /* if there is no previous, this must be head */
    This->parent->textures = This->next_device;

  if (This->next_device)
    This->next_device->prev_device = This->prev_device;

  HeapFree(GetProcessHeap(), 0, This);
  return 0;
}

HRESULT WINAPI Direct3DTexture8_GetDevice(LPDIRECT3DTEXTURE8 iface,
					  IDirect3DDevice8** ppDevice)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  IDirect3DDevice8* pDevice;

  TRACE("(%p)->(%p)\n", iface, ppDevice);
  pDevice = (IDirect3DDevice8*)This->parent;
  IDirect3DDevice8_AddRef(pDevice);
  *ppDevice = pDevice;

  TRACE("=> %p\n", *ppDevice);
  return D3D_OK;
}

static
DWORD WINAPI Direct3DTexture8_SetPriority( LPDIRECT3DTEXTURE8 iface, DWORD dwNewPriority )
{
  FIXME( "(%p)->(%lu): stub\n", iface, dwNewPriority );
  return 0;
}

static
DWORD WINAPI Direct3DTexture8_GetPriority( LPDIRECT3DTEXTURE8 iface )
{
  FIXME( "(%p): stub\n", iface );
  return 0;
}


VOID WINAPI Direct3DTexture8_PreLoad(LPDIRECT3DTEXTURE8 iface)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  D3DHAL_DP2COMMAND cmd = { D3DDP2OP_TEXBLT, 0, {1} };
  D3DHAL_DP2TEXBLT data;

  TRACE("(%p)->()\n", iface);
  This->UpdateTexture(This, NULL);
  data.dwDDDestSurface = 0;
  data.dwDDSrcSurface = TEXTURE_HANDLE(This);
  data.pDest.x = 0;
  data.pDest.y = 0;
  data.rSrc.left   = 0;
  data.rSrc.top    = 0;
  data.rSrc.right  = This->Width;
  data.rSrc.bottom = This->Height;
  data.dwFlags = 0;
  This->parent->emit_dp2(This->parent->ip_ctx, &cmd, &data, sizeof(data), NULL, 0);
}

D3DRESOURCETYPE WINAPI Direct3DTexture8_GetType(LPDIRECT3DTEXTURE8 iface)
{
  TRACE("(%p)->()\n", iface);
  return D3DRTYPE_TEXTURE;
}

DWORD WINAPI Direct3DTexture8_SetLOD(LPDIRECT3DTEXTURE8 iface, DWORD LODNew)
{
  FIXME("(%p)->(%ld): stub\n", iface, LODNew);
  return 0;
}

DWORD WINAPI Direct3DTexture8_GetLOD(LPDIRECT3DTEXTURE8 iface)
{
  FIXME("(%p)->(): stub\n", iface);
  return 0;
}

DWORD WINAPI Direct3DTexture8_GetLevelCount(LPDIRECT3DTEXTURE8 iface)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  TRACE("(%p)->()\n", iface);
  return This->Levels;
}

HRESULT WINAPI Direct3DTexture8_GetLevelDesc(LPDIRECT3DTEXTURE8 iface,
					     UINT Level,
					     D3DSURFACE_DESC* pDesc)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  TRACE("(%p)->(%d,%p)\n", iface, Level, pDesc);
  return IDirect3DSurface8_GetDesc(This->surf[Level], pDesc);
}

HRESULT WINAPI Direct3DTexture8_GetSurfaceLevel(LPDIRECT3DTEXTURE8 iface,
						UINT Level,
						IDirect3DSurface8** ppSurfaceLevel)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  TRACE("(%p)->(%d,%p)\n", iface, Level, ppSurfaceLevel);
  *ppSurfaceLevel = This->surf[Level];
  IDirect3DSurface8_AddRef(*ppSurfaceLevel);
  return D3D_OK;
}

HRESULT WINAPI Direct3DTexture8_LockRect(LPDIRECT3DTEXTURE8 iface,
					 UINT Level,
					 D3DLOCKED_RECT* pLockedRect,
					 CONST RECT* pRect,
					 DWORD Flags)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  HRESULT hr;
  TRACE("(%p)->(%d,%p,%p,%lx)\n", iface, Level,
	pLockedRect, pRect, Flags);
  hr = IDirect3DSurface8_LockRect(This->surf[Level],
				  pLockedRect,
				  pRect,
				  Flags);
  return hr;
}

HRESULT WINAPI Direct3DTexture8_UnlockRect(LPDIRECT3DTEXTURE8 iface,
					   UINT Level)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  TRACE("(%p)->(%d)\n", iface, Level);
  return IDirect3DSurface8_UnlockRect(This->surf[Level]);
}

HRESULT WINAPI Direct3DTexture8_AddDirtyRect(LPDIRECT3DTEXTURE8 iface,
					     CONST RECT* pDirtyRect)
{
  ICOM_THIS(IDirect3DTexture8Impl, iface);
  TRACE("(%p)->(%p)\n", iface, pDirtyRect);
  return This->AddDirtyRect(This, This->main, pDirtyRect);
}

static ICOM_VTABLE(IDirect3DTexture8) D3DT8_Vtbl =
{
  ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
  Direct3DTexture8_QueryInterface,
  Direct3DTexture8_AddRef,
  Direct3DTexture8_Release,
  Direct3DTexture8_GetDevice,
  (void*)0xdead4005, /* SetPrivateData */
  (void*)0xdead4006, /* GetPrivateData */
  (void*)0xdead4007, /* FreePrivateData */
  Direct3DTexture8_SetPriority,
  Direct3DTexture8_GetPriority,
  Direct3DTexture8_PreLoad,
  Direct3DTexture8_GetType,
  Direct3DTexture8_SetLOD,
  Direct3DTexture8_GetLOD,
  Direct3DTexture8_GetLevelCount,
  Direct3DTexture8_GetLevelDesc,
  Direct3DTexture8_GetSurfaceLevel,
  Direct3DTexture8_LockRect,
  Direct3DTexture8_UnlockRect,
  Direct3DTexture8_AddDirtyRect
};

HRESULT Direct3DTexture8Impl_AddDirtyRect(IDirect3DTexture8Impl* This,
					  LPDIRECT3DSURFACE8 surf,
					  CONST RECT* pDirtyRect)
{
  TRACE("(%p)->(%p,%p)\n", This, surf, pDirtyRect);
  if (surf != This->main) return D3D_OK;
  if (pDirtyRect)
    UnionRect(&This->DirtyRect, &This->DirtyRect, pDirtyRect);
  else
    SetRect(&This->DirtyRect, 0, 0, This->Width, This->Height);
  This->IsDirty = TRUE;
  This->parent->dirty_textures = TRUE;
  return D3D_OK;
}

HRESULT Direct3DTexture8Impl_UpdateTexture(IDirect3DTexture8Impl* This,
					   IDirect3DTexture8Impl* pDest)
{
  LPDIRECT3DSURFACE8* ssurf = This->surf;
  LPDIRECT3DSURFACE8* dsurf = pDest ? pDest->surf : NULL;
  UINT Levels = This->Levels, Skip = 0;
  HRESULT hr;
  if (pDest && pDest->Levels < Levels)
    Skip = Levels - pDest->Levels;
  /* FIXME: some validation */
  hr = Direct3DBaseTexture8_UpdateTexture(This->parent,
					  This->Width, This->Height,
					  Levels, Skip, &This->DirtyRect, FALSE,
					  ssurf, dsurf);
  if (FAILED(hr)) return hr;
  This->IsDirty = FALSE;
  return D3D_OK;
}

HRESULT Direct3DTexture8Impl_UnloadTexture(IDirect3DTexture8Impl* This)
{
  UINT Level;
  D3DLOCKED_RECT rect;
  /* this makes d3dgl load all mipmap levels into system memory. */
  for (Level=0; Level<This->Levels; Level++) {
    IDirect3DSurface8_LockRect(This->surf[Level], &rect, NULL, D3DLOCK_READONLY);
    IDirect3DSurface8_UnlockRect(This->surf[Level]);
  }
  return D3D_OK;
}

HRESULT WINAPI Direct3DDevice8_CreateTexture(LPDIRECT3DDEVICE8 iface,
					     UINT Width,
					     UINT Height,
					     UINT Levels,
					     DWORD Usage,
					     D3DFORMAT Format,
					     D3DPOOL Pool,
					     IDirect3DTexture8** ppTexture)
{
  ICOM_THIS(IDirect3DDevice8Impl, iface);
  IDirect3DTexture8Impl *pTexture;
  UINT levels = Levels;
  DDSCAPS2 caps;
  unsigned u;
  HRESULT hr;

  TRACE("(%p}->(%d,%d,%d,%ld,0x%x,%d,%p)\n", iface, Width, Height,
	Levels, Usage, Format, Pool, ppTexture);

  if (!levels) {
    /* calculate levels */
    UINT Dim = (Width > Height) ? Width : Height;
    levels = 1;
    while (Dim > 1) {
      Dim = Dim / 2;
      levels++;
    }
  }

  pTexture = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DTexture8Impl) +
		       (levels-1) * sizeof(LPDIRECT3DSURFACE8));
  pTexture->lpVtbl = &D3DT8_Vtbl;
  pTexture->ref = 1;
  pTexture->intref = 0;
  pTexture->parent = This;
  pTexture->Width  = Width;
  pTexture->Height = Height;
  pTexture->Levels = levels;
  pTexture->Usage  = Usage;
  pTexture->Format = Format;
  pTexture->AddDirtyRect = Direct3DTexture8Impl_AddDirtyRect;
  pTexture->UpdateTexture = Direct3DTexture8Impl_UpdateTexture;
  pTexture->UnloadTexture = Direct3DTexture8Impl_UnloadTexture;

  memset(&caps, 0, sizeof(caps));
  /* FIXME: handle caps bits */
  caps.dwCaps = DDSCAPS_TEXTURE;
  caps.dwCaps2 = 0;
  caps.dwCaps3 = 0;
  caps.dwCaps4 = 0;
  if (Usage & D3DUSAGE_RENDERTARGET) caps.dwCaps |= DDSCAPS_3DDEVICE;
  if (Usage & D3DUSAGE_DEPTHSTENCIL) caps.dwCaps |= DDSCAPS_ZBUFFER;
  if (Usage & D3DUSAGE_WRITEONLY)    caps.dwCaps |= DDSCAPS_WRITEONLY;

  switch (Pool) {
  case D3DPOOL_DEFAULT:
    /* textures in D3DPOOL_DEFAULT are not lockable, they must be
     * accessed via CopyRects or UpdateTexture. Perhaps we could use
     * DDSCAPS2_OPAQUE to let the driver know about this. */
    caps.dwCaps |= DDSCAPS_VIDEOMEMORY;
    break;
  case D3DPOOL_MANAGED:
    caps.dwCaps2 |= DDSCAPS2_TEXTUREMANAGE;
    break;
  case D3DPOOL_SYSTEMMEM:
    caps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
    break;
  default:
    break;
  }

  if (levels > 1) caps.dwCaps |= DDSCAPS_MIPMAP;

  for (u=0; u<levels; u++) {
    hr = Direct3DDevice8_CreateSurface(iface, (LPUNKNOWN)pTexture,
				       Width, Height, Format,
				       &caps, &pTexture->surf[u],
				       FALSE);
    if (hr != D3D_OK)
        goto bail_out;
    if (u) {
      Direct3DDevice8_AttachSurface(pTexture->surf[u-1],
				    pTexture->surf[u]);
    } else {
      caps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
    }
    if (Width  > 1) Width  = Width / 2;
    if (Height > 1) Height = Height / 2;
  }

  pTexture->main = pTexture->surf[0];

  TRACE("created %p\n", pTexture);
  *ppTexture = (LPDIRECT3DTEXTURE8)pTexture;

  /* add texture to linked list */
  if (!This->textures)
  {
    This->textures = (IDirect3DBaseTexture8Impl*)pTexture;
  }
  else
  {
    This->textures->prev_device = (IDirect3DBaseTexture8Impl*)pTexture;
    pTexture->next_device = This->textures;
    This->textures = (IDirect3DBaseTexture8Impl*)pTexture;
  }

  return D3D_OK;

bail_out:
  levels = u;
  for (u = 0; u < levels; u++)
  {
    IDirect3DSurface8_Release(pTexture->surf[u]);
  }
  HeapFree(GetProcessHeap(), 0, pTexture);
  return hr;
}

HRESULT WINAPI Direct3DBaseTexture8_UpdateTexture(IDirect3DDevice8Impl* dev,
						  UINT Width, UINT Height, UINT Levels,
						  UINT Skip, RECT* pDirtyRect, BOOL force,
						  LPDIRECT3DSURFACE8* src, LPDIRECT3DSURFACE8* dst)
{
  D3DHAL_DP2COMMAND cmd = { D3DDP2OP_TEXBLT, 0, {1} };
  D3DHAL_DP2TEXBLT data;
  unsigned u;

  TRACE("(%p)->(%d,%d,%d,%d,%p,%d,%p,%p)\n", dev, Width, Height, Levels, Skip, pDirtyRect, force, src, dst);
  if (IsRectEmpty(pDirtyRect)) {
    if (!force) return D3D_OK;
    data.rSrc.left = 0;
    data.rSrc.top = 0;
    data.rSrc.right = Width;
    data.rSrc.bottom = Height;
  }
  else memcpy(&data.rSrc, pDirtyRect, sizeof(RECT));
  SetRectEmpty(pDirtyRect);

  data.dwDDSrcSurface = 0;
  data.pDest.x = 0;
  data.pDest.y = 0;
  data.dwFlags = 0;

  for (u=0; u<Levels; u++) {
    IDirect3DSurface8Impl* surf = (IDirect3DSurface8Impl*)src[u];
    if (u >= Skip) {
      if (dst) {
        IDirect3DDevice8_CopyRects((LPDIRECT3DDEVICE8)dev, src[u], (RECT*)&data.rSrc, 1, dst[u-Skip], &data.pDest);
      } else {
        data.dwDDDestSurface = (DWORD)&surf->t;
        dev->emit_dp2(dev->ip_ctx, &cmd, &data, sizeof(data), NULL, 0);
      }
    }
    if (surf->t.gbl.wWidth > 1) {
      data.rSrc.left = data.rSrc.left / 2;
      data.rSrc.right = (data.rSrc.right+1) / 2;
    }
    if (surf->t.gbl.wHeight > 1) {
      data.rSrc.top = data.rSrc.top / 2;
      data.rSrc.bottom = (data.rSrc.bottom+1) / 2;
    }
  }
  return D3D_OK;
}
