Search code examples
unreal-engine4assimp

How can i convert FBX embedded texture to TArray<uint8> Data?


I want to make a function that returns the textures built into FBX as 'TArray[uint8]' or UTexture2D using Assimp library. This is my code.

void UAIScene::GetTexture2D(bool& IsValid, UTexture2D*& ReturnedTexture)
{
    IsValid = false;
    UTexture2D* LoadedT2D = NULL;
    TArray<uint8> RawFileData;
    IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));

    aiString texture_file;
    scene->mMaterials[0]->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), texture_file);
    if (const aiTexture* texture = scene->GetEmbeddedTexture(texture_file.C_Str())) {
        
//Here Is Problem
        RawFileData = *(TArray<uint8>*) & (texture->pcData[0]);

        TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(ImageWrapperModule.DetectImageFormat(RawFileData.GetData(), RawFileData.Num()));



        if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))
        {
            TArray<uint8> UncompressedBRGA;


            if (ImageWrapper->GetRaw(ERGBFormat::BGRA, (int32)8, UncompressedBRGA))
            {
                LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);

                if (!LoadedT2D)
                {
                    IsValid = false;
                }


                void* TextureData = LoadedT2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
                FMemory::Memcpy(TextureData, UncompressedBRGA.GetData(), UncompressedBRGA.Num());
                LoadedT2D->PlatformData->Mips[0].BulkData.Unlock();

                LoadedT2D->UpdateResource();
            }
        }
        ReturnedTexture = LoadedT2D;
        IsValid = true;
    }
    else {
        
    }
}

But Assimp's raw image file doesn't cast to TArray. Where do I have to fix to change Assimp's aiTexel to TArray?

This comment is my attempt.

//TextureBinary = *Cast<TArray<uint8>>(texture->pcData);


Solution

  • If I get the documentation for TArray right you need to copy the data with memcpy. You need the starting address of the embedded texture, the start-pointer of the TArray instance by GetData() or something similar and the size for the embedded texture which shall get copyied:

    memcpy(RawFileData.GetData(), static_cast<void*>(&LoadedT2D), texSize);
    

    Just make sure that the buffer-size for the TArray instance is big enough. Hope that helps.