Skip to content

Instantly share code, notes, and snippets.

@ThePhD
Created March 4, 2014 19:12
Show Gist options
  • Save ThePhD/8898c49179b9ad962905 to your computer and use it in GitHub Desktop.
Save ThePhD/8898c49179b9ad962905 to your computer and use it in GitHub Desktop.
void Texture2D::SetData( uint32 mipmap, const Rectangleu32& source, const void* pixels, ulword pixelbytesize, ulword count ) {
#ifdef FURROVINEDIRECTX
ID3D11DeviceContext& context = Dx::rnative_handle( *graphicsdevice, Dx::context );
ID3D11Texture2D* tex2 = Dx::native_handle( *this );
uint32 dest = D3D11CalcSubresource( mipmap, 0, tex2desc.miplevels );
uint32 texpixelsize = ToByteSize( tex2desc.surfaceformat );
bool isempty = source.IsEmpty( );
if ( tex2desc.usage == ResourceUsage::Default ) {
D3D11_BOX d3dbox;
d3dbox.front = 0;
d3dbox.back = 1;
if ( !isempty ) {
d3dbox.left = source.left;
d3dbox.top = source.top;
d3dbox.right = source.Right( );
d3dbox.bottom = source.Bottom( );
}
context.UpdateSubresource( tex2, dest, isempty ? null : &d3dbox,
pixels, tex2desc.width * texpixelsize, 0 );
return;
}
D3D11_MAPPED_SUBRESOURCE res = { };
ResourceMapping mapping = ResourceMapping::WriteAndDiscard;
dxresultcode r = context.Map( tex2, dest, Dx::ToPlatform<D3D11_MAP>( mapping ), 0, &res );
if ( FAILED( r ) )
throw Exception( "Unable to Map Texture2D to device" );
auto dx = make_destructor( [ &context, &tex2 ] { context.Unmap( tex2, 0 ); } );
if ( isempty ) {
uint32 bytesize = pixelbytesize * count;
std::memcpy( res.pData, pixels, bytesize );
return;
}
bool samewidth = Width( ) == source.Width( ) && ToByteSize( tex2desc.surfaceformat ) == pixelbytesize;
if ( samewidth ) {
uint32 bytesize = pixelbytesize * count;
std::memcpy( res.pData, pixels, bytesize );
return;
}
byte* mappeddata = static_cast<byte*>( res.pData );
const byte* pixeldata = static_cast<const byte*>( pixels );
uint32 pixelrowsize = source.Width( ) * pixelbytesize;
for ( ulword h = 0; h < source.Height( ); ++h ) {
byte* mappedrow = mappeddata + ( res.RowPitch * h );
const byte* pixelrow = pixeldata + ( pixelrowsize * h );
std::memcpy( mappedrow, pixelrow, pixelrowsize );
}
#else
#error Implement for this graphics platform
#endif // DIRECTX || OPENGL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment