Commit 6cdeb206 by wester

testing fpr exposing API

parent 110727d8
// Fill out your copyright notice in the Description page of Project Settings.
#include "GLTFLoaderPrivatePCH.h"
#include "GLTFFactory.h"
#include "Engine.h"
#include "Editor/UnrealEd/Public/Editor.h"
#include "GLTFMeshBuilder.h"
#include "UnrealEd.h"
#include "Factories.h"
#include "BusyCursor.h"
#include "SSkeletonWidget.h"
#include "AssetRegistryModule.h"
#include "Engine/StaticMesh.h"
#include "FbxErrors.h"
#define LOCTEXT_NAMESPACE "GLTFFactory"
UGLTFFactory::UGLTFFactory(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
SupportedClass = UStaticMeshComponent::StaticClass();
Formats.Add(TEXT("gltf;GLTF meshes"));
bCreateNew = false;
bText = false;
bEditorImport = true;
bOperationCanceled = false;
bDetectImportTypeOnImport = false;
}
//This function is adapted from ::CreateBinary()
UObject* UGLTFFactory::FactoryCreateBinary
(
UClass* Class,
UObject* InParent,
FName Name,
EObjectFlags Flags,
UObject* Context,
const TCHAR* Type,
const uint8*& Buffer,
const uint8* BufferEnd,
FFeedbackContext* Warn,
bool& bOutOperationCanceled
)
{
if (bOperationCanceled)
{
bOutOperationCanceled = true;
FEditorDelegates::OnAssetPostImport.Broadcast(this, NULL);
return NULL;
}
FEditorDelegates::OnAssetPreImport.Broadcast(this, Class, InParent, Name, Type);
UObject* NewObject = NULL;
GLTFMeshBuilder Builder(*UFactory::CurrentFilename);
bool bShowImportDialog = bShowOption && !GIsAutomationTesting;
bool bImportAll = false;
auto ImportOptions = FGLTFLoaderModule::ImportOptions;
bOutOperationCanceled = bOperationCanceled;
if (bImportAll)
{
// If the user chose to import all, we don't show the dialog again and use the same settings for each object until importing another set of files
bShowOption = false;
}
// For multiple files, use the same settings
bDetectImportTypeOnImport = false;
Warn->BeginSlowTask(NSLOCTEXT("GLTFFactory", "BeginImportingGLTFMeshTask", "Importing GLTF mesh"), true);
if (!Builder.LoadedSuccessfully())
{
// Log the error message and fail the import.
Warn->Log(ELogVerbosity::Error, Builder.GetError());
}
else
{
// Log the import message and import the mesh.
const FString errorMessage = Builder.GetError();
if (errorMessage.Len() > 0)
{
Warn->Log(errorMessage);
}
FString RootNodeToImport = "";
RootNodeToImport = Builder.GetRootNode();
// For animation and static mesh we assume there is at lease one interesting node by default
int32 InterestingNodeCount = 1;
bool bImportStaticMeshLODs = /*ImportUI->StaticMeshImportData->bImportMeshLODs*/ false;
bool bCombineMeshes = /*ImportUI->bCombineMeshes*/ true;
if (bCombineMeshes && !bImportStaticMeshLODs)
{
// If Combine meshes and dont import mesh LODs, the interesting node count should be 1 so all the meshes are grouped together into one static mesh
InterestingNodeCount = 1;
}
else
{
// count meshes in lod groups if we dont care about importing LODs
bool bCountLODGroupMeshes = !bImportStaticMeshLODs;
int32 NumLODGroups = 0;
InterestingNodeCount = Builder.GetMeshCount(RootNodeToImport/*, bCountLODGroupMeshes, NumLODGroups*/);
// if there were LODs in the file, do not combine meshes even if requested
if (bImportStaticMeshLODs && bCombineMeshes)
{
bCombineMeshes = NumLODGroups == 0;
}
}
const FString Filename(UFactory::CurrentFilename);
if (RootNodeToImport.Len() != 0 && InterestingNodeCount > 0)
{
int32 NodeIndex = 0;
int32 ImportedMeshCount = 0;
UStaticMeshComponent* NewStaticMesh = NULL;
if (bCombineMeshes)
{
auto MeshNames = Builder.GetMeshNames(RootNodeToImport);
if (MeshNames.Num() > 0)
{
NewStaticMesh = Builder.ImportStaticMeshAsSingle(InParent, MeshNames, Name, Flags/*, ImportUI->StaticMeshImportData*/, NULL/*, 0*/);
for (auto Mesh : MeshNames)
{
Warn->Log(FString("Found mesh: ") + Mesh);
}
}
ImportedMeshCount = NewStaticMesh ? 1 : 0;
}
NewObject = NewStaticMesh;
}
else
{
if (RootNodeToImport == "")
{
Builder.AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, LOCTEXT("FailedToImport_InvalidRoot", "Could not find root node.")), FFbxErrors::SkeletalMesh_InvalidRoot);
}
else
{
Builder.AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, LOCTEXT("FailedToImport_InvalidNode", "Could not find any node.")), FFbxErrors::SkeletalMesh_InvalidNode);
}
}
}
if (NewObject == NULL)
{
// Import fail error message
Builder.AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, LOCTEXT("FailedToImport_NoObject", "Import failed.")), FFbxErrors::Generic_ImportingNewObjectFailed);
Warn->Log(ELogVerbosity::Warning, "Failed to import GLTF mesh");
}
Warn->EndSlowTask();
FEditorDelegates::OnAssetPostImport.Broadcast(this, NewObject);
return NewObject;
}
bool UGLTFFactory::DoesSupportClass(UClass * Class)
{
return (Class == UStaticMesh::StaticClass());
}
bool UGLTFFactory::FactoryCanImport(const FString& Filename)
{
const FString Extension = FPaths::GetExtension(Filename);
if (Extension == TEXT("gltf"))
{
return true;
}
return false;
}
// Fill out your copyright notice in the Description page of Project Settings.
#include "GLTFLoaderPrivatePCH.h"
#include "GLTFFactory.h"
#include "Engine.h"
#include "Editor/UnrealEd/Public/Editor.h"
#include "GLTFMeshBuilder.h"
#include "UnrealEd.h"
#include "Factories.h"
#include "BusyCursor.h"
#include "SSkeletonWidget.h"
#include "AssetRegistryModule.h"
#include "Engine/StaticMesh.h"
#include "FbxErrors.h"
#define LOCTEXT_NAMESPACE "GLTFFactory"
UGLTFFactory::UGLTFFactory(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
SupportedClass = UStaticMeshComponent::StaticClass();
Formats.Add(TEXT("gltf;GLTF meshes"));
bCreateNew = false;
bText = false;
bEditorImport = true;
bOperationCanceled = false;
bDetectImportTypeOnImport = false;
}
//This function is adapted from ::CreateBinary()
UObject* UGLTFFactory::FactoryCreateBinary
(
UClass* Class,
UObject* InParent,
FName Name,
EObjectFlags Flags,
UObject* Context,
const TCHAR* Type,
const uint8*& Buffer,
const uint8* BufferEnd,
FFeedbackContext* Warn,
bool& bOutOperationCanceled
)
{
if (bOperationCanceled)
{
bOutOperationCanceled = true;
FEditorDelegates::OnAssetPostImport.Broadcast(this, NULL);
return NULL;
}
FEditorDelegates::OnAssetPreImport.Broadcast(this, Class, InParent, Name, Type);
UObject* NewObject = NULL;
GLTFMeshBuilder Builder(*UFactory::CurrentFilename);
bool bShowImportDialog = bShowOption && !GIsAutomationTesting;
bool bImportAll = false;
auto ImportOptions = FGLTFLoaderModule::ImportOptions;
bOutOperationCanceled = bOperationCanceled;
if (bImportAll)
{
// If the user chose to import all, we don't show the dialog again and use the same settings for each object until importing another set of files
bShowOption = false;
}
// For multiple files, use the same settings
bDetectImportTypeOnImport = false;
Warn->BeginSlowTask(NSLOCTEXT("GLTFFactory", "BeginImportingGLTFMeshTask", "Importing GLTF mesh"), true);
if (!Builder.LoadedSuccessfully())
{
// Log the error message and fail the import.
Warn->Log(ELogVerbosity::Error, Builder.GetError());
}
else
{
// Log the import message and import the mesh.
const FString errorMessage = Builder.GetError();
if (errorMessage.Len() > 0)
{
Warn->Log(errorMessage);
}
FString RootNodeToImport = "";
RootNodeToImport = Builder.GetRootNode();
// For animation and static mesh we assume there is at lease one interesting node by default
int32 InterestingNodeCount = 1;
bool bImportStaticMeshLODs = /*ImportUI->StaticMeshImportData->bImportMeshLODs*/ false;
bool bCombineMeshes = /*ImportUI->bCombineMeshes*/ true;
if (bCombineMeshes && !bImportStaticMeshLODs)
{
// If Combine meshes and dont import mesh LODs, the interesting node count should be 1 so all the meshes are grouped together into one static mesh
InterestingNodeCount = 1;
}
else
{
// count meshes in lod groups if we dont care about importing LODs
bool bCountLODGroupMeshes = !bImportStaticMeshLODs;
int32 NumLODGroups = 0;
InterestingNodeCount = Builder.GetMeshCount(RootNodeToImport/*, bCountLODGroupMeshes, NumLODGroups*/);
// if there were LODs in the file, do not combine meshes even if requested
if (bImportStaticMeshLODs && bCombineMeshes)
{
bCombineMeshes = NumLODGroups == 0;
}
}
const FString Filename(UFactory::CurrentFilename);
if (RootNodeToImport.Len() != 0 && InterestingNodeCount > 0)
{
int32 NodeIndex = 0;
int32 ImportedMeshCount = 0;
UStaticMeshComponent* NewStaticMesh = NULL;
if (bCombineMeshes)
{
auto MeshNames = Builder.GetMeshNames(RootNodeToImport);
if (MeshNames.Num() > 0)
{
NewStaticMesh = Builder.ImportStaticMeshAsSingle(InParent, MeshNames, Name, Flags/*, ImportUI->StaticMeshImportData*/, NULL/*, 0*/);
for (auto Mesh : MeshNames)
{
Warn->Log(FString("Found mesh: ") + Mesh);
}
}
ImportedMeshCount = NewStaticMesh ? 1 : 0;
}
NewObject = NewStaticMesh;
}
else
{
if (RootNodeToImport == "")
{
Builder.AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, LOCTEXT("FailedToImport_InvalidRoot", "Could not find root node.")), FFbxErrors::SkeletalMesh_InvalidRoot);
}
else
{
Builder.AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, LOCTEXT("FailedToImport_InvalidNode", "Could not find any node.")), FFbxErrors::SkeletalMesh_InvalidNode);
}
}
}
if (NewObject == NULL)
{
// Import fail error message
Builder.AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, LOCTEXT("FailedToImport_NoObject", "Import failed.")), FFbxErrors::Generic_ImportingNewObjectFailed);
Warn->Log(ELogVerbosity::Warning, "Failed to import GLTF mesh");
}
Warn->EndSlowTask();
FEditorDelegates::OnAssetPostImport.Broadcast(this, NewObject);
return NewObject;
}
bool UGLTFFactory::DoesSupportClass(UClass * Class)
{
return (Class == UStaticMesh::StaticClass());
}
bool UGLTFFactory::FactoryCanImport(const FString& Filename)
{
const FString Extension = FPaths::GetExtension(Filename);
if (Extension == TEXT("gltf"))
{
return true;
}
return false;
}
#undef LOCTEXT_NAMESPACE
\ No newline at end of file
/// @file GLTFFactory.h by Robert Poncelet
#pragma once
#include "Factories/Factory.h"
#include "GLTFFactory.generated.h"
UCLASS()
/// The class instantiated by the AssetToolsModule for importing the chosen UAsset into the content browser. Adapted from UFbxFactory.
class UGLTFFactory : public UFactory
{
GENERATED_BODY()
UGLTFFactory(const FObjectInitializer& ObjectInitializer);
/// @name UFactory Implementation
///@{
virtual bool DoesSupportClass(UClass * Class) override;
virtual UObject* FactoryCreateBinary(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, const TCHAR* Type, const uint8*& Buffer, const uint8* BufferEnd, FFeedbackContext* Warn, bool& bOutOperationCanceled) override;
virtual bool FactoryCanImport(const FString& Filename) override;
///@}
bool bShowOption;
bool bDetectImportTypeOnImport;
/** true if the import operation was canceled. */
bool bOperationCanceled;
};
/// @file GLTFFactory.h by Robert Poncelet
#pragma once
#include "Factories/Factory.h"
#include "GLTFFactory.generated.h"
UCLASS()
/// The class instantiated by the AssetToolsModule for importing the chosen UAsset into the content browser. Adapted from UFbxFactory.
class UGLTFFactory : public UFactory
{
GENERATED_BODY()
UGLTFFactory(const FObjectInitializer& ObjectInitializer);
/// @name UFactory Implementation
///@{
virtual bool DoesSupportClass(UClass * Class) override;
virtual UObject* FactoryCreateBinary(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, const TCHAR* Type, const uint8*& Buffer, const uint8* BufferEnd, FFeedbackContext* Warn, bool& bOutOperationCanceled) override;
virtual bool FactoryCanImport(const FString& Filename) override;
///@}
bool bShowOption;
bool bDetectImportTypeOnImport;
/** true if the import operation was canceled. */
bool bOperationCanceled;
};
// Some copyright should be here...
#include "GLTFLoaderPrivatePCH.h"
#include "SlateBasics.h"
#include "SlateExtras.h"
#include "Developer/DesktopPlatform/Public/DesktopPlatformModule.h"
#include "Developer/AssetTools/Public/AssetToolsModule.h"
#include "GLTFLoaderStyle.h"
#include "GLTFLoaderCommands.h"
#include "GLTFFactory.h"
#include "LevelEditor.h"
static const FName GLTFLoaderTabName("GLTFLoader");
GLTFImportOptions FGLTFLoaderModule::ImportOptions = GLTFImportOptions::Default();
#define LOCTEXT_NAMESPACE "FGLTFLoaderModule"
void FGLTFLoaderModule::StartupModule()
{
FGLTFLoaderStyle::Initialize();
FGLTFLoaderStyle::ReloadTextures();
FGLTFLoaderCommands::Register();
PluginCommands = MakeShareable(new FUICommandList);
PluginCommands->MapAction(
FGLTFLoaderCommands::Get().OpenPluginWindow,
FExecuteAction::CreateRaw(this, &FGLTFLoaderModule::PluginButtonClicked),
FCanExecuteAction());
PluginCommands->MapAction(
FGLTFLoaderCommands::Get().OpenImportWindow,
FExecuteAction::CreateRaw(this, &FGLTFLoaderModule::OpenImportWindow),
FCanExecuteAction());
FLevelEditorModule& LevelEditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");
{
TSharedPtr<FExtender> MenuExtender = MakeShareable(new FExtender());
MenuExtender->AddMenuExtension("WindowLayout", EExtensionHook::After, PluginCommands, FMenuExtensionDelegate::CreateRaw(this, &FGLTFLoaderModule::AddMenuExtension));
LevelEditorModule.GetMenuExtensibilityManager()->AddExtender(MenuExtender);
}
{
TSharedPtr<FExtender> ToolbarExtender = MakeShareable(new FExtender);
ToolbarExtender->AddToolBarExtension("Settings", EExtensionHook::After, PluginCommands, FToolBarExtensionDelegate::CreateRaw(this, &FGLTFLoaderModule::AddToolbarExtension));
LevelEditorModule.GetToolBarExtensibilityManager()->AddExtender(ToolbarExtender);
}
FGlobalTabmanager::Get()->RegisterNomadTabSpawner(GLTFLoaderTabName, FOnSpawnTab::CreateRaw(this, &FGLTFLoaderModule::OnSpawnPluginTab))
.SetDisplayName(LOCTEXT("FGLTFLoaderTabTitle", "GLTFLoader"))
.SetMenuType(ETabSpawnerMenuType::Hidden);
UE_LOG(LogInit, Warning, TEXT("GLTFLoader module started successfully."));
}
void FGLTFLoaderModule::ShutdownModule()
{
FGLTFLoaderStyle::Shutdown();
FGLTFLoaderCommands::Unregister();
FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(GLTFLoaderTabName);
}
TSharedRef<SDockTab> FGLTFLoaderModule::OnSpawnPluginTab(const FSpawnTabArgs& SpawnTabArgs)
{
return SNew(SDockTab)
.TabRole(ETabRole::NomadTab)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Top)
[
SNew(STextBlock)
.Text(LOCTEXT("TopText", "Import a glTF file"))
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("ImportTranslation", "Import Translation"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SVectorInputBox)
.X_Raw(this, &FGLTFLoaderModule::GetImportTX)
.Y_Raw(this, &FGLTFLoaderModule::GetImportTY)
.Z_Raw(this, &FGLTFLoaderModule::GetImportTZ)
.bColorAxisLabels(true)
.AllowResponsiveLayout(true)
.OnXChanged_Raw(this, &FGLTFLoaderModule::SetImportTX)
.OnYChanged_Raw(this, &FGLTFLoaderModule::SetImportTY)
.OnZChanged_Raw(this, &FGLTFLoaderModule::SetImportTZ)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("ImportRotation", "Import Rotation"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SRotatorInputBox)
.Pitch_Raw(this, &FGLTFLoaderModule::GetImportRPitch)
.Yaw_Raw(this, &FGLTFLoaderModule::GetImportRYaw)
.Roll_Raw(this, &FGLTFLoaderModule::GetImportRRoll)
.bColorAxisLabels(true)
.AllowResponsiveLayout(true)
.OnPitchChanged_Raw(this, &FGLTFLoaderModule::SetImportRPitch)
.OnYawChanged_Raw(this, &FGLTFLoaderModule::SetImportRYaw)
.OnRollChanged_Raw(this, &FGLTFLoaderModule::SetImportRRoll)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("ImportScale", "Import Scale"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SNumericEntryBox<float>)
.Value_Raw(this, &FGLTFLoaderModule::GetImportScale)
.OnValueChanged_Raw(this, &FGLTFLoaderModule::SetImportScale)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("CorrectUp", "Correct Y up to Z up"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SCheckBox)
.IsChecked_Raw(this, &FGLTFLoaderModule::GetCorrectUp)
.OnCheckStateChanged_Raw(this, &FGLTFLoaderModule::SetCorrectUp)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
[
SNew(SBox)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SButton)
.OnClicked_Raw(this, &FGLTFLoaderModule::OpenImportWindowDelegateFunc)
.Content()
[
SNew(STextBlock)
.Text(LOCTEXT("ImportWindow", "Import File"))
]
]
]
];
}
void FGLTFLoaderModule::OpenImportWindow()
{
TArray<FString> Filenames;
if (FDesktopPlatformModule::Get()->OpenFileDialog(nullptr,
TEXT("Choose a GLTF file to import"),
TEXT(""),
TEXT(""),
TEXT("GL Transmission Format files (*.gltf)|*.gltf"),
EFileDialogFlags::None,
Filenames))
{
for (FString File : Filenames)
{
UE_LOG(LogTemp, Log, TEXT("File: %s"), *File);
}
FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked<FAssetToolsModule>("AssetTools");
//TArray<FString> Filenames;
//Filenames.Add("D:/Dropbox/Studium/MasterArbeit/glTF-Sample-Models/1.0/Box/glTF/Box.gltf");
AssetToolsModule.Get().ImportAssets(Filenames, FString("/Game/Content"));
}
}
void FGLTFLoaderModule::PluginButtonClicked()
{
FGlobalTabmanager::Get()->InvokeTab(GLTFLoaderTabName);
}
void FGLTFLoaderModule::AddMenuExtension(FMenuBuilder& Builder)
{
Builder.AddMenuEntry(FGLTFLoaderCommands::Get().OpenPluginWindow);
}
void FGLTFLoaderModule::AddToolbarExtension(FToolBarBuilder& Builder)
{
Builder.AddToolBarButton(FGLTFLoaderCommands::Get().OpenPluginWindow);
}
// Delegate setters
void FGLTFLoaderModule::SetImportTX(float Value) { ImportOptions.ImportTranslation.X = Value; }
void FGLTFLoaderModule::SetImportTY(float Value) { ImportOptions.ImportTranslation.Y = Value; }
void FGLTFLoaderModule::SetImportTZ(float Value) { ImportOptions.ImportTranslation.Z = Value; }
void FGLTFLoaderModule::SetImportRPitch(float Value) { ImportOptions.ImportRotation.Pitch = Value; }
void FGLTFLoaderModule::SetImportRYaw(float Value) { ImportOptions.ImportRotation.Yaw = Value; }
void FGLTFLoaderModule::SetImportRRoll(float Value) { ImportOptions.ImportRotation.Roll = Value; }
void FGLTFLoaderModule::SetImportScale(float Value) { ImportOptions.ImportUniformScale = Value; }
void FGLTFLoaderModule::SetCorrectUp(ECheckBoxState Value) { ImportOptions.bCorrectUpDirection = (Value == ECheckBoxState::Checked); }
// Delegate getters
TOptional<float> FGLTFLoaderModule::GetImportTX() const { return ImportOptions.ImportTranslation.X; }
TOptional<float> FGLTFLoaderModule::GetImportTY() const { return ImportOptions.ImportTranslation.Y; }
TOptional<float> FGLTFLoaderModule::GetImportTZ() const { return ImportOptions.ImportTranslation.Z; }
TOptional<float> FGLTFLoaderModule::GetImportRPitch() const { return ImportOptions.ImportRotation.Pitch; }
TOptional<float> FGLTFLoaderModule::GetImportRYaw() const { return ImportOptions.ImportRotation.Yaw; }
TOptional<float> FGLTFLoaderModule::GetImportRRoll() const { return ImportOptions.ImportRotation.Roll; }
TOptional<float> FGLTFLoaderModule::GetImportScale() const { return ImportOptions.ImportUniformScale; }
ECheckBoxState FGLTFLoaderModule::GetCorrectUp() const { return ImportOptions.bCorrectUpDirection ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }
#undef LOCTEXT_NAMESPACE
// Some copyright should be here...
#include "GLTFLoaderPrivatePCH.h"
#include "SlateBasics.h"
#include "SlateExtras.h"
#include "Developer/DesktopPlatform/Public/DesktopPlatformModule.h"
#include "Developer/AssetTools/Public/AssetToolsModule.h"
#include "GLTFLoaderStyle.h"
#include "GLTFLoaderCommands.h"
#include "GLTFFactory.h"
#include "LevelEditor.h"
static const FName GLTFLoaderTabName("GLTFLoader");
GLTFImportOptions FGLTFLoaderModule::ImportOptions = GLTFImportOptions::Default();
#define LOCTEXT_NAMESPACE "FGLTFLoaderModule"
void FGLTFLoaderModule::StartupModule()
{
FGLTFLoaderStyle::Initialize();
FGLTFLoaderStyle::ReloadTextures();
FGLTFLoaderCommands::Register();
PluginCommands = MakeShareable(new FUICommandList);
PluginCommands->MapAction(
FGLTFLoaderCommands::Get().OpenPluginWindow,
FExecuteAction::CreateRaw(this, &FGLTFLoaderModule::PluginButtonClicked),
FCanExecuteAction());
PluginCommands->MapAction(
FGLTFLoaderCommands::Get().OpenImportWindow,
FExecuteAction::CreateRaw(this, &FGLTFLoaderModule::OpenImportWindow),
FCanExecuteAction());
FLevelEditorModule& LevelEditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");
{
TSharedPtr<FExtender> MenuExtender = MakeShareable(new FExtender());
MenuExtender->AddMenuExtension("WindowLayout", EExtensionHook::After, PluginCommands, FMenuExtensionDelegate::CreateRaw(this, &FGLTFLoaderModule::AddMenuExtension));
LevelEditorModule.GetMenuExtensibilityManager()->AddExtender(MenuExtender);
}
{
TSharedPtr<FExtender> ToolbarExtender = MakeShareable(new FExtender);
ToolbarExtender->AddToolBarExtension("Settings", EExtensionHook::After, PluginCommands, FToolBarExtensionDelegate::CreateRaw(this, &FGLTFLoaderModule::AddToolbarExtension));
LevelEditorModule.GetToolBarExtensibilityManager()->AddExtender(ToolbarExtender);
}
FGlobalTabmanager::Get()->RegisterNomadTabSpawner(GLTFLoaderTabName, FOnSpawnTab::CreateRaw(this, &FGLTFLoaderModule::OnSpawnPluginTab))
.SetDisplayName(LOCTEXT("FGLTFLoaderTabTitle", "GLTFLoader"))
.SetMenuType(ETabSpawnerMenuType::Hidden);
UE_LOG(LogInit, Warning, TEXT("GLTFLoader module started successfully."));
}
void FGLTFLoaderModule::ShutdownModule()
{
FGLTFLoaderStyle::Shutdown();
FGLTFLoaderCommands::Unregister();
FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(GLTFLoaderTabName);
}
TSharedRef<SDockTab> FGLTFLoaderModule::OnSpawnPluginTab(const FSpawnTabArgs& SpawnTabArgs)
{
return SNew(SDockTab)
.TabRole(ETabRole::NomadTab)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Top)
[
SNew(STextBlock)
.Text(LOCTEXT("TopText", "Import a glTF file"))
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("ImportTranslation", "Import Translation"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SVectorInputBox)
.X_Raw(this, &FGLTFLoaderModule::GetImportTX)
.Y_Raw(this, &FGLTFLoaderModule::GetImportTY)
.Z_Raw(this, &FGLTFLoaderModule::GetImportTZ)
.bColorAxisLabels(true)
.AllowResponsiveLayout(true)
.OnXChanged_Raw(this, &FGLTFLoaderModule::SetImportTX)
.OnYChanged_Raw(this, &FGLTFLoaderModule::SetImportTY)
.OnZChanged_Raw(this, &FGLTFLoaderModule::SetImportTZ)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("ImportRotation", "Import Rotation"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SRotatorInputBox)
.Pitch_Raw(this, &FGLTFLoaderModule::GetImportRPitch)
.Yaw_Raw(this, &FGLTFLoaderModule::GetImportRYaw)
.Roll_Raw(this, &FGLTFLoaderModule::GetImportRRoll)
.bColorAxisLabels(true)
.AllowResponsiveLayout(true)
.OnPitchChanged_Raw(this, &FGLTFLoaderModule::SetImportRPitch)
.OnYawChanged_Raw(this, &FGLTFLoaderModule::SetImportRYaw)
.OnRollChanged_Raw(this, &FGLTFLoaderModule::SetImportRRoll)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("ImportScale", "Import Scale"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SNumericEntryBox<float>)
.Value_Raw(this, &FGLTFLoaderModule::GetImportScale)
.OnValueChanged_Raw(this, &FGLTFLoaderModule::SetImportScale)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("CorrectUp", "Correct Y up to Z up"))
]
+ SHorizontalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SCheckBox)
.IsChecked_Raw(this, &FGLTFLoaderModule::GetCorrectUp)
.OnCheckStateChanged_Raw(this, &FGLTFLoaderModule::SetCorrectUp)
]
]
+ SVerticalBox::Slot()
.Padding(1.0f)
.HAlign(HAlign_Center)
[
SNew(SBox)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SButton)
.OnClicked_Raw(this, &FGLTFLoaderModule::OpenImportWindowDelegateFunc)
.Content()
[
SNew(STextBlock)
.Text(LOCTEXT("ImportWindow", "Import File"))
]
]
]
];
}
void FGLTFLoaderModule::OpenImportWindow()
{
TArray<FString> Filenames;
if (FDesktopPlatformModule::Get()->OpenFileDialog(nullptr,
TEXT("Choose a GLTF file to import"),
TEXT(""),
TEXT(""),
TEXT("GL Transmission Format files (*.gltf)|*.gltf"),
EFileDialogFlags::None,
Filenames))
{
for (FString File : Filenames)
{
UE_LOG(LogTemp, Log, TEXT("File: %s"), *File);
}
FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked<FAssetToolsModule>("AssetTools");
//TArray<FString> Filenames;
//Filenames.Add("D:/Dropbox/Studium/MasterArbeit/glTF-Sample-Models/1.0/Box/glTF/Box.gltf");
AssetToolsModule.Get().ImportAssets(Filenames, FString("/Game/Content"));
}
}
void FGLTFLoaderModule::PluginButtonClicked()
{
FGlobalTabmanager::Get()->InvokeTab(GLTFLoaderTabName);
}
void FGLTFLoaderModule::AddMenuExtension(FMenuBuilder& Builder)
{
Builder.AddMenuEntry(FGLTFLoaderCommands::Get().OpenPluginWindow);
}
void FGLTFLoaderModule::AddToolbarExtension(FToolBarBuilder& Builder)
{
Builder.AddToolBarButton(FGLTFLoaderCommands::Get().OpenPluginWindow);
}
// Delegate setters
void FGLTFLoaderModule::SetImportTX(float Value) { ImportOptions.ImportTranslation.X = Value; }
void FGLTFLoaderModule::SetImportTY(float Value) { ImportOptions.ImportTranslation.Y = Value; }
void FGLTFLoaderModule::SetImportTZ(float Value) { ImportOptions.ImportTranslation.Z = Value; }
void FGLTFLoaderModule::SetImportRPitch(float Value) { ImportOptions.ImportRotation.Pitch = Value; }
void FGLTFLoaderModule::SetImportRYaw(float Value) { ImportOptions.ImportRotation.Yaw = Value; }
void FGLTFLoaderModule::SetImportRRoll(float Value) { ImportOptions.ImportRotation.Roll = Value; }
void FGLTFLoaderModule::SetImportScale(float Value) { ImportOptions.ImportUniformScale = Value; }
void FGLTFLoaderModule::SetCorrectUp(ECheckBoxState Value) { ImportOptions.bCorrectUpDirection = (Value == ECheckBoxState::Checked); }
// Delegate getters
TOptional<float> FGLTFLoaderModule::GetImportTX() const { return ImportOptions.ImportTranslation.X; }
TOptional<float> FGLTFLoaderModule::GetImportTY() const { return ImportOptions.ImportTranslation.Y; }
TOptional<float> FGLTFLoaderModule::GetImportTZ() const { return ImportOptions.ImportTranslation.Z; }
TOptional<float> FGLTFLoaderModule::GetImportRPitch() const { return ImportOptions.ImportRotation.Pitch; }
TOptional<float> FGLTFLoaderModule::GetImportRYaw() const { return ImportOptions.ImportRotation.Yaw; }
TOptional<float> FGLTFLoaderModule::GetImportRRoll() const { return ImportOptions.ImportRotation.Roll; }
TOptional<float> FGLTFLoaderModule::GetImportScale() const { return ImportOptions.ImportUniformScale; }
ECheckBoxState FGLTFLoaderModule::GetCorrectUp() const { return ImportOptions.bCorrectUpDirection ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FGLTFLoaderModule, GLTFLoader)
\ No newline at end of file
// Some copyright should be here...
#include "SlateBasics.h"
#include "GLTFLoader.h"
// You should place include statements to your module's private header files here. You only need to
// Some copyright should be here...
#include "SlateBasics.h"
#include "GLTFLoader.h"
// You should place include statements to your module's private header files here. You only need to
// add includes for headers that are used in most of your module's source files though.
\ No newline at end of file
// Some copyright should be here...
#include "GLTFLoaderPrivatePCH.h"
#include "GLTFLoaderStyle.h"
#include "SlateGameResources.h"
#include "IPluginManager.h"
TSharedPtr< FSlateStyleSet > FGLTFLoaderStyle::StyleInstance = NULL;
void FGLTFLoaderStyle::Initialize()
{
if (!StyleInstance.IsValid())
{
StyleInstance = Create();
FSlateStyleRegistry::RegisterSlateStyle(*StyleInstance);
}
}
void FGLTFLoaderStyle::Shutdown()
{
FSlateStyleRegistry::UnRegisterSlateStyle(*StyleInstance);
ensure(StyleInstance.IsUnique());
StyleInstance.Reset();
}
FName FGLTFLoaderStyle::GetStyleSetName()
{
static FName StyleSetName(TEXT("GLTFLoaderStyle"));
return StyleSetName;
}
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define TTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define OTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
TSharedRef< FSlateStyleSet > FGLTFLoaderStyle::Create()
{
TSharedRef< FSlateStyleSet > Style = MakeShareable(new FSlateStyleSet("GLTFLoaderStyle"));
Style->SetContentRoot(IPluginManager::Get().FindPlugin("GLTFLoader")->GetBaseDir() / TEXT("Resources"));
Style->Set("GLTFLoader.OpenPluginWindow", new IMAGE_BRUSH(TEXT("ButtonIcon_40x"), Icon40x40));
return Style;
}
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef OTF_FONT
void FGLTFLoaderStyle::ReloadTextures()
{
FSlateApplication::Get().GetRenderer()->ReloadTextureResources();
}
const ISlateStyle& FGLTFLoaderStyle::Get()
{
return *StyleInstance;
}
// Some copyright should be here...
#include "GLTFLoaderPrivatePCH.h"
#include "GLTFLoaderStyle.h"
#include "SlateGameResources.h"
#include "IPluginManager.h"
TSharedPtr< FSlateStyleSet > FGLTFLoaderStyle::StyleInstance = NULL;
void FGLTFLoaderStyle::Initialize()
{
if (!StyleInstance.IsValid())
{
StyleInstance = Create();
FSlateStyleRegistry::RegisterSlateStyle(*StyleInstance);
}
}
void FGLTFLoaderStyle::Shutdown()
{
FSlateStyleRegistry::UnRegisterSlateStyle(*StyleInstance);
ensure(StyleInstance.IsUnique());
StyleInstance.Reset();
}
FName FGLTFLoaderStyle::GetStyleSetName()
{
static FName StyleSetName(TEXT("GLTFLoaderStyle"));
return StyleSetName;
}
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define TTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define OTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
TSharedRef< FSlateStyleSet > FGLTFLoaderStyle::Create()
{
TSharedRef< FSlateStyleSet > Style = MakeShareable(new FSlateStyleSet("GLTFLoaderStyle"));
Style->SetContentRoot(IPluginManager::Get().FindPlugin("GLTFLoader")->GetBaseDir() / TEXT("Resources"));
Style->Set("GLTFLoader.OpenPluginWindow", new IMAGE_BRUSH(TEXT("ButtonIcon_40x"), Icon40x40));
return Style;
}
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef OTF_FONT
void FGLTFLoaderStyle::ReloadTextures()
{
FSlateApplication::Get().GetRenderer()->ReloadTextureResources();
}
const ISlateStyle& FGLTFLoaderStyle::Get()
{
return *StyleInstance;
}
#include "GLTFLoaderPrivatePCH.h"
#include <locale>
#include <codecvt>
#define TINYGLTF_LOADER_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "tiny_gltf_loader.h"
#include "GLTFMeshBuilder.h"
#include "GLTFLoaderCommands.h"
//#include "Editor/UnrealEd/Classes/Factories/Factory.h"
// These replace TargetPlatform.h since it can't seem to find the right paths from here
#include "ModuleManager.h"
#include "Developer/TargetPlatform/Public/Interfaces/TargetDeviceId.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetDevice.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetPlatform.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetPlatformModule.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetPlatformManagerModule.h"
#include "UnrealEd.h"
#include "Developer/RawMesh/Public/RawMesh.h"
#include "Developer/MeshUtilities/Public/MeshUtilities.h"
#include "Engine.h"
#include "StaticMeshResources.h"
#include "TextureLayout.h"
#include "ObjectTools.h"
#include "PackageTools.h"
#include "Editor/UnrealEd/Classes/Factories/FbxStaticMeshImportData.h"
#include "../Private/GeomFitUtils.h"
#include "FbxErrors.h"
#include "Engine/StaticMeshSocket.h"
#include "Engine/Polys.h"
#include "PhysicsEngine/BodySetup.h"
/// @cond
// Syntactic sugar to neatly map the TinyGLTF enum to the corresponding data type
// Adapted from http://stackoverflow.com/questions/1735796/is-it-possible-to-choose-a-c-generic-type-parameter-at-runtime
template<int Type> struct GLTFType;
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_BYTE> { typedef int8 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> { typedef uint8 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_SHORT> { typedef int16 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> { typedef uint16 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_INT> { typedef int32 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> { typedef uint32 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_FLOAT> { typedef float Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_DOUBLE> { typedef double Type; };
template<> struct GLTFType <TINYGLTF_TYPE_VEC2> { typedef FVector2D Type; };
template<> struct GLTFType <TINYGLTF_TYPE_VEC3> { typedef FVector Type; };
template<> struct GLTFType <TINYGLTF_TYPE_VEC4> { typedef FVector4 Type; };
/// @endcond
template <typename T>
bool GLTFMeshBuilder::ConvertAttrib(TArray<T> &OutArray, tinygltf::Mesh* Mesh, std::string AttribName, bool UseWedgeIndices, bool AutoSetArraySize)
{
if (AttribName != "__WedgeIndices" && !HasAttribute(Mesh, AttribName))
{
return false;
}
UE_LOG(LogTemp, Log, TEXT("%s"), *(FText::Format(FText::FromString("Importing data for attribute \"{0}\""), FText::FromString(ToFString(AttribName)))).ToString());
if (AutoSetArraySize)// This should always be false since for now we are just extending the array each time we want to add an element
{
int32 Size = 0;
if (UseWedgeIndices)
{
for (auto Prim : Mesh->primitives)
{
Size += GetNumWedges(&Prim); // Number of wedges
}
}
else
{
for (auto Prim : Mesh->primitives)
{
Size += Scene->accessors[Prim.attributes.begin()->second].count; // Number of vertices
}
}
OutArray.SetNumUninitialized(Size);
}
// Getting an attribute for individual triangle corners ("wedges")
else if (UseWedgeIndices && AttribName != "__WedgeIndices")// Make sure we don't try to access indices for the index array itself!
{
for (auto Prim : Mesh->primitives)
{
std::string IndexAccessorName = Prim.indices;
std::string AttribAccessorName = Prim.attributes[AttribName];
tinygltf::Accessor* IndexAccessor = &Scene->accessors[IndexAccessorName];
tinygltf::Accessor* AttribAccessor = &Scene->accessors[AttribAccessorName];
if (!IndexAccessor || !AttribAccessor)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::FromString(FString("Invalid accessor"))),
FFbxErrors::Generic_Mesh_NoGeometry);
return false;
}
TArray<int32> IndexArray;
TArray<T> VertArray;
if (!GetBufferData(IndexArray, IndexAccessor) || !GetBufferData(VertArray, AttribAccessor))
{
return false;
}
switch (Prim.mode)
{
case TINYGLTF_MODE_TRIANGLES:
for (auto Index : IndexArray)
{
OutArray.Add(VertArray[Index]);
}
break;
case TINYGLTF_MODE_TRIANGLE_STRIP:
OutArray.Add(VertArray[IndexArray[0]]);
OutArray.Add(VertArray[IndexArray[1]]);
OutArray.Add(VertArray[IndexArray[2]]);
for (int i = 2; i < IndexAccessor->count - 2; i += 2)
{
// First triangle
OutArray.Add(VertArray[IndexArray[ i ]]);
OutArray.Add(VertArray[IndexArray[i-1]]);
OutArray.Add(VertArray[IndexArray[i+1]]);
// Second triangle
OutArray.Add(VertArray[IndexArray[ i ]]);
OutArray.Add(VertArray[IndexArray[i+1]]);
OutArray.Add(VertArray[IndexArray[i+2]]);
}
break;
case TINYGLTF_MODE_TRIANGLE_FAN:
for (int i = 1; i < IndexAccessor->count - 1; ++i)
{
// Triangle
OutArray.Add(VertArray[IndexArray[ 0 ]]);
OutArray.Add(VertArray[IndexArray[ i ]]);
OutArray.Add(VertArray[IndexArray[i+1]]);
}
break;
default:
return false;
}
}
}
// Getting a vertex attribute
else
{
for (auto Prim : Mesh->primitives)
{
std::string AccessorName;
if (AttribName == "__WedgeIndices")
{
AccessorName = Prim.indices;
}
else
{
AccessorName = Prim.attributes[AttribName];
}
if (!GetBufferData(OutArray, &Scene->accessors[AccessorName], true))
{
return false;
}
}
}
return true;
}
// Retrieve a value from the buffer, implicitly accounting for endianness
// Adapted from http://stackoverflow.com/questions/13001183/how-to-read-little-endian-integers-from-file-in-c
template <typename T> T GLTFMeshBuilder::BufferValue(void* Data/*, uint8 Size*/)
{
T Ret = T(0);
auto NewData = reinterpret_cast<unsigned char*>(Data);
for (int i = 0; i < sizeof(T); ++i)
{
Ret |= (T)(NewData[i]) << (8 * i);
}
return Ret;
}
// Use unions for floats and doubles since they don't have a bitwise OR operator
template <> float GLTFMeshBuilder::BufferValue(void* Data)
{
assert(sizeof(float) == sizeof(int32));
union
{
float Ret;
int32 IntRet;
};
Ret = 0.0f;
auto NewData = reinterpret_cast<unsigned char*>(Data);
for (int i = 0; i < sizeof(int32); ++i)
{
IntRet |= (int32)(NewData[i]) << (8 * i);
}
return Ret;
}
template <> double GLTFMeshBuilder::BufferValue(void* Data)
{
assert(sizeof(float) == sizeof(int64));
union
{
double Ret;
int64 IntRet;
};
Ret = 0.0;
auto NewData = reinterpret_cast<unsigned char*>(Data);
for (int i = 0; i < sizeof(int64); ++i)
{
IntRet |= (int64)(NewData[i]) << (8 * i);
}
return Ret;
}
/// @cond
struct MaterialPair
{
tinygltf::Material* GLTFMaterial;
UMaterialInterface* Material;
};
/// @endcond
GLTFMeshBuilder::GLTFMeshBuilder(FString FilePath)
{
Loader = new tinygltf::TinyGLTFLoader;
Scene = new tinygltf::Scene;
std::string TempError;
LoadSuccess = Loader->LoadFromFile((*Scene), TempError, ToStdString(FilePath));
Error = ToFString(TempError);
}
GLTFMeshBuilder::~GLTFMeshBuilder()
{
delete Loader;
delete Scene;
}
int32 GLTFMeshBuilder::GetMeshCount(FString NodeName)
{
return (int32)Scene->nodes[ToStdString(NodeName)].meshes.size();
}
FString GLTFMeshBuilder::GetRootNode()
{
for (auto ThisNode : Scene->nodes)
{
bool ShouldReturn = false;
for (auto ThatNode : Scene->nodes)
{
if (FindInStdVector<std::string>(ThatNode.second.children, ThisNode.first) == -1) // If this node's name doesn't appear in any node's list of children
{
ShouldReturn = true;
}
}
if (ShouldReturn)
{
return ToFString(ThisNode.first);
}
}
return FString("");
}
tinygltf::Node* GLTFMeshBuilder::GetMeshParentNode(tinygltf::Mesh* InMesh)
{
for (auto &Node : Scene->nodes)
{
for (auto &MeshName : Node.second.meshes)
{
if (&Scene->meshes[MeshName] == InMesh)
{
return &Node.second;
}
}
}
return NULL;
}
TArray<FString> GLTFMeshBuilder::GetMeshNames(FString NodeName, bool GetChildren)
{
TArray<FString> MeshNameArray;
for (auto Mesh : Scene->nodes[ToStdString(NodeName)].meshes)
{
MeshNameArray.Add(ToFString(Mesh));
}
if (GetChildren)
{
for (auto ChildName : Scene->nodes[ToStdString(NodeName)].children)
{
MeshNameArray.Append(GetMeshNames(ToFString(ChildName)));
}
}
return MeshNameArray;
}
UStaticMeshComponent* GLTFMeshBuilder::ImportStaticMeshAsSingle(UObject* InParent, TArray<FString>& MeshNameArray, const FName InName, EObjectFlags Flags, UStaticMeshComponent* InStaticMesh)
{
auto ImportOptions = FGLTFLoaderModule::ImportOptions;
int LODIndex = 0;
bool bBuildStatus = true;
// Make sure rendering is done - so we are not changing data being used by collision drawing.
FlushRenderingCommands();
if (MeshNameArray.Num() == 0)
{
return NULL;
}
Parent = InParent;
FString MeshName = ObjectTools::SanitizeObjectName(InName.ToString());
// Parent package to place new meshes
UPackage* Package = NULL;
// create empty mesh
UStaticMeshComponent* StaticMeshComponent = NULL;
UStaticMeshComponent* ExistingMesh = NULL;
UObject* ExistingObject = NULL;
// A mapping of vertex positions to their color in the existing static mesh
TMap<FVector, FColor> ExistingVertexColorData;
FString NewPackageName;
if( InStaticMesh == NULL || LODIndex == 0 )
{
// Create a package for each mesh
NewPackageName = FPackageName::GetLongPackagePath(Parent->GetOutermost()->GetName()) + TEXT("/") + MeshName;
NewPackageName = PackageTools::SanitizePackageName(NewPackageName);
Package = CreatePackage(NULL, *NewPackageName);
ExistingMesh = FindObject<UStaticMeshComponent>( Package, *MeshName );
ExistingObject = FindObject<UObject>( Package, *MeshName );
}
if (ExistingMesh)
{
// Free any RHI resources for existing mesh before we re-create in place.
ExistingMesh->PreEditChange(NULL);
}
else if (ExistingObject)
{
// Replacing an object. Here we go!
// Delete the existing object
bool bDeleteSucceeded = ObjectTools::DeleteSingleObject( ExistingObject );
if (bDeleteSucceeded)
{
// Force GC so we can cleanly create a new asset (and not do an 'in place' replacement)
CollectGarbage( GARBAGE_COLLECTION_KEEPFLAGS );
// Create a package for each mesh
Package = CreatePackage(NULL, *NewPackageName);
// Require the parent because it will have been invalidated from the garbage collection
Parent = Package;
}
else
{
// failed to delete
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, FText::Format(FText::FromString(FString("{0} wasn't created.\n\nThe asset is referenced by other content.")), FText::FromString(MeshName))), FFbxErrors::Generic_CannotDeleteReferenced);
return NULL;
}
}
if( InStaticMesh != NULL && LODIndex > 0 )
{
StaticMeshComponent = InStaticMesh;
}
else
{
StaticMeshComponent = NewObject<UStaticMeshComponent>(Package, FName(*MeshName), Flags | RF_Public);
}
verify(StaticMeshComponent != NULL);
if (StaticMeshComponent->GetStaticMesh() == NULL ) {
UStaticMesh *mesh = NewObject<UStaticMesh>(Package);
StaticMeshComponent->SetStaticMesh(mesh);
}
verify(StaticMeshComponent->GetStaticMesh() != NULL);
if (StaticMeshComponent->GetStaticMesh()->SourceModels.Num() < LODIndex+1)
{
// Add one LOD
//StaticMeshComponent->GetStaticMesh()->SourceModels.AddUninitialized();
//StaticMeshComponent->GetStaticMesh()->SourceModels = new FStaticMeshSourceModel();
new(StaticMeshComponent->GetStaticMesh()->SourceModels) FStaticMeshSourceModel();
if (StaticMeshComponent->GetStaticMesh()->SourceModels.Num() < LODIndex+1)
{
LODIndex = StaticMeshComponent->GetStaticMesh()->SourceModels.Num() - 1;
}
}
FStaticMeshSourceModel& SrcModel = StaticMeshComponent->GetStaticMesh()->SourceModels[LODIndex];
if( InStaticMesh != NULL && LODIndex > 0 && !SrcModel.RawMeshBulkData->IsEmpty() )
{
// clear out the old mesh data
FRawMesh EmptyRawMesh;
SrcModel.RawMeshBulkData->SaveRawMesh( EmptyRawMesh );
}
// make sure it has a new lighting guid
StaticMeshComponent->GetStaticMesh()->LightingGuid = FGuid::NewGuid();
// Set it to use textured lightmaps. Note that Build Lighting will do the error-checking (texcoordindex exists for all LODs, etc).
StaticMeshComponent->GetStaticMesh()->LightMapResolution = 64;
StaticMeshComponent->GetStaticMesh()->LightMapCoordinateIndex = 1;
FRawMesh NewRawMesh;
SrcModel.RawMeshBulkData->LoadRawMesh(NewRawMesh);
//for (FString Name : MeshNameArray)
for(int i = 0; i < MeshNameArray.Num(); i++)
{
FString Name = MeshNameArray[i];
tinygltf::Mesh* Mesh = &Scene->meshes[ToStdString(Name)];
if (Mesh)
{
for (auto Prim : Mesh->primitives)
{
MeshMaterials.AddUnique(ToFString(Prim.material));
}
}
}
for (FString Name : MeshNameArray)
{
tinygltf::Mesh* Mesh = &Scene->meshes[ToStdString(Name)];
if (Mesh)
{
if (!BuildStaticMeshFromGeometry(Mesh, StaticMeshComponent, LODIndex, NewRawMesh))
{
bBuildStatus = false;
break;
}
}
}
// Store the new raw mesh.
SrcModel.RawMeshBulkData->SaveRawMesh(NewRawMesh);
if (bBuildStatus)
{
// Compress the materials array by removing any duplicates.
bool bDoRemap = false;
TArray<int32> MaterialMap;
TArray<tinygltf::Material*> UniqueMaterials;
for (int32 MaterialIndex = 0; MaterialIndex < MeshMaterials.Num(); ++MaterialIndex)
{
bool bUnique = true;
for (int32 OtherMaterialIndex = MaterialIndex - 1; OtherMaterialIndex >= 0; --OtherMaterialIndex)
{
if (MeshMaterials[MaterialIndex] == MeshMaterials[OtherMaterialIndex])
{
int32 UniqueIndex = MaterialMap[OtherMaterialIndex];
MaterialMap.Add(UniqueIndex);
bDoRemap = true;
bUnique = false;
break;
}
}
if (bUnique)
{
int32 UniqueIndex = UniqueMaterials.Add(&Scene->materials[ToStdString(MeshMaterials[MaterialIndex])]);
MaterialMap.Add( UniqueIndex );
}
}
if (UniqueMaterials.Num() > 8)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::Format(FText::FromString(FString("StaticMesh has a large number({1}) of materials and may render inefficently. Consider breaking up the mesh into multiple Static Mesh Assets.")),
FText::AsNumber(UniqueMaterials.Num())
)),
FFbxErrors::StaticMesh_TooManyMaterials);
}
// Sort materials based on _SkinXX in the name.
TArray<uint32> SortedMaterialIndex;
for (int32 MaterialIndex = 0; MaterialIndex < MeshMaterials.Num(); ++MaterialIndex)
{
int32 SkinIndex = 0xffff;
int32 RemappedIndex = MaterialMap[MaterialIndex];
if (!SortedMaterialIndex.IsValidIndex(RemappedIndex))
{
FString GLTFMatName = MeshMaterials[RemappedIndex];
int32 Offset = GLTFMatName.Find(TEXT("_SKIN"), ESearchCase::IgnoreCase, ESearchDir::FromEnd);
if (Offset != INDEX_NONE)
{
// Chop off the material name so we are left with the number in _SKINXX
FString SkinXXNumber = GLTFMatName.Right(GLTFMatName.Len() - (Offset + 1)).RightChop(4);
if (SkinXXNumber.IsNumeric())
{
SkinIndex = FPlatformString::Atoi( *SkinXXNumber );
bDoRemap = true;
}
}
SortedMaterialIndex.Add(((uint32)SkinIndex << 16) | ((uint32)RemappedIndex & 0xffff));
}
}
SortedMaterialIndex.Sort();
TArray<tinygltf::Material*> SortedMaterials;
for (int32 SortedIndex = 0; SortedIndex < SortedMaterialIndex.Num(); ++SortedIndex)
{
int32 RemappedIndex = SortedMaterialIndex[SortedIndex] & 0xffff;
SortedMaterials.Add(UniqueMaterials[RemappedIndex]);
}
for (int32 MaterialIndex = 0; MaterialIndex < MaterialMap.Num(); ++MaterialIndex)
{
for (int32 SortedIndex = 0; SortedIndex < SortedMaterialIndex.Num(); ++SortedIndex)
{
int32 RemappedIndex = SortedMaterialIndex[SortedIndex] & 0xffff;
if (MaterialMap[MaterialIndex] == RemappedIndex)
{
MaterialMap[MaterialIndex] = SortedIndex;
break;
}
}
}
// Remap material indices.
int32 MaxMaterialIndex = 0;
int32 FirstOpenUVChannel = 1;
{
FRawMesh LocalRawMesh;
SrcModel.RawMeshBulkData->LoadRawMesh(LocalRawMesh);
if (bDoRemap)
{
for (int32 TriIndex = 0; TriIndex < LocalRawMesh.FaceMaterialIndices.Num(); ++TriIndex)
{
LocalRawMesh.FaceMaterialIndices[TriIndex] = MaterialMap[LocalRawMesh.FaceMaterialIndices[TriIndex]];
}
}
// Compact material indices so that we won't have any sections with zero triangles.
LocalRawMesh.CompactMaterialIndices();
// Also compact the sorted materials array.
if (LocalRawMesh.MaterialIndexToImportIndex.Num() > 0)
{
TArray<tinygltf::Material*> OldSortedMaterials;
Exchange(OldSortedMaterials,SortedMaterials);
SortedMaterials.Empty(LocalRawMesh.MaterialIndexToImportIndex.Num());
for (int32 MaterialIndex = 0; MaterialIndex < LocalRawMesh.MaterialIndexToImportIndex.Num(); ++MaterialIndex)
{
tinygltf::Material* Material;
int32 ImportIndex = LocalRawMesh.MaterialIndexToImportIndex[MaterialIndex];
if (OldSortedMaterials.IsValidIndex(ImportIndex))
{
Material = OldSortedMaterials[ImportIndex];
}
SortedMaterials.Add(Material);
}
}
for (int32 TriIndex = 0; TriIndex < LocalRawMesh.FaceMaterialIndices.Num(); ++TriIndex)
{
MaxMaterialIndex = FMath::Max<int32>(MaxMaterialIndex,LocalRawMesh.FaceMaterialIndices[TriIndex]);
}
for( int32 i = 0; i < MAX_MESH_TEXTURE_COORDS; i++ )
{
if( LocalRawMesh.WedgeTexCoords[i].Num() == 0 )
{
FirstOpenUVChannel = i;
break;
}
}
SrcModel.RawMeshBulkData->SaveRawMesh(LocalRawMesh);
}
// Setup per-section info and the materials array.
if (LODIndex == 0)
{
StaticMeshComponent->GetMaterial(0);
//TODO check if right
//StaticMeshComponent->Materials.Empty();
StaticMeshComponent->GetNumMaterials();
}
// Build a new map of sections with the unique material set
FMeshSectionInfoMap NewMap;
int32 NumMaterials = FMath::Min(SortedMaterials.Num(),MaxMaterialIndex+1);
for (int32 MaterialIndex = 0; MaterialIndex < NumMaterials; ++MaterialIndex)
{
FMeshSectionInfo Info = StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Get(LODIndex, MaterialIndex);
//FIXME
//int32 Index = StaticMeshComponent->Materials.Add(ToUMaterial(SortedMaterials[MaterialIndex]));
//Info.MaterialIndex = Index;
//NewMap.Set( LODIndex, MaterialIndex, Info);
}
// Copy the final section map into the static mesh
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Clear();
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.CopyFrom(NewMap);
FRawMesh LocalRawMesh;
SrcModel.RawMeshBulkData->LoadRawMesh(LocalRawMesh);
// Setup default LOD settings based on the selected LOD group.
if (ExistingMesh == NULL && LODIndex == 0)
{
ITargetPlatform* CurrentPlatform = GetTargetPlatformManagerRef().GetRunningTargetPlatform();
check(CurrentPlatform);
const FStaticMeshLODGroup& LODGroup = CurrentPlatform->GetStaticMeshLODSettings().GetLODGroup(ImportOptions.StaticMeshLODGroup);
int32 NumLODs = LODGroup.GetDefaultNumLODs();
while (StaticMeshComponent->GetStaticMesh()->SourceModels.Num() < NumLODs)
{
new (StaticMeshComponent->GetStaticMesh()->SourceModels) FStaticMeshSourceModel();
}
for (int32 ModelLODIndex = 0; ModelLODIndex < NumLODs; ++ModelLODIndex)
{
StaticMeshComponent->GetStaticMesh()->SourceModels[ModelLODIndex].ReductionSettings = LODGroup.GetDefaultSettings(ModelLODIndex);
}
StaticMeshComponent->GetStaticMesh()->LightMapResolution = LODGroup.GetDefaultLightMapResolution();
}
// @todo This overrides restored values currently but we need to be able to import over the existing settings if the user chose to do so.
SrcModel.BuildSettings.bRemoveDegenerates = ImportOptions.bRemoveDegenerates;
SrcModel.BuildSettings.bBuildAdjacencyBuffer = ImportOptions.bBuildAdjacencyBuffer;
SrcModel.BuildSettings.bRecomputeNormals = LocalRawMesh.WedgeTangentZ.Num() == 0;
SrcModel.BuildSettings.bRecomputeTangents = LocalRawMesh.WedgeTangentX.Num() == 0 || LocalRawMesh.WedgeTangentY.Num() == 0;
SrcModel.BuildSettings.bUseMikkTSpace = false;
if( ImportOptions.bGenerateLightmapUVs )
{
SrcModel.BuildSettings.bGenerateLightmapUVs = true;
SrcModel.BuildSettings.DstLightmapIndex = FirstOpenUVChannel;
StaticMeshComponent->GetStaticMesh()->LightMapCoordinateIndex = FirstOpenUVChannel;
}
else
{
SrcModel.BuildSettings.bGenerateLightmapUVs = false;
}
TArray<FText> BuildErrors;
StaticMeshComponent->GetStaticMesh()->LODGroup = ImportOptions.StaticMeshLODGroup;
StaticMeshComponent->GetStaticMesh()->Build(false, &BuildErrors);
for( FText& Error : BuildErrors )
{
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Warning, Error), FFbxErrors::StaticMesh_BuildError );
}
// this is damage control. After build, we'd like to absolutely sure that
// all index is pointing correctly and they're all used. Otherwise we remove them
FMeshSectionInfoMap OldSectionInfoMap = StaticMeshComponent->GetStaticMesh()->SectionInfoMap;
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Clear();
// fix up section data
for (int32 LODResourceIndex = 0; LODResourceIndex < StaticMeshComponent->GetStaticMesh()->RenderData->LODResources.Num(); ++LODResourceIndex)
{
FStaticMeshLODResources& LOD = StaticMeshComponent->GetStaticMesh()->RenderData->LODResources[LODResourceIndex];
int32 NumSections = LOD.Sections.Num();
for(int32 SectionIndex = 0; SectionIndex < NumSections; ++SectionIndex)
{
FMeshSectionInfo Info = OldSectionInfoMap.Get(LODResourceIndex, SectionIndex);
if (StaticMeshComponent->GetMaterials().IsValidIndex(Info.MaterialIndex))
{
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Set(LODResourceIndex, SectionIndex, Info);
}
}
}
}
else
{
StaticMeshComponent = NULL;
}
return StaticMeshComponent;
}
// Reverse the winding order for triangle indices
template <typename T>
void GLTFMeshBuilder::ReverseTriDirection(TArray<T>& OutArray)
{
for (int i = 0; i < OutArray.Num() - 2; i += 3)
{
T Temp = OutArray[i];
OutArray[i] = OutArray[i + 2];
OutArray[i + 2] = Temp;
}
}
bool GLTFMeshBuilder::BuildStaticMeshFromGeometry(tinygltf::Mesh* Mesh, UStaticMeshComponent* StaticMeshComponent, int LODIndex, FRawMesh& RawMesh)
{
check(StaticMeshComponent->GetStaticMesh()->SourceModels.IsValidIndex(LODIndex));
auto ImportOptions = FGLTFLoaderModule::ImportOptions;
tinygltf::Node* Node = GetMeshParentNode(Mesh);
FStaticMeshSourceModel& SrcModel = StaticMeshComponent->GetStaticMesh()->SourceModels[LODIndex];
tinygltf::Primitive* BaseLayer = &Mesh->primitives[0];
if (BaseLayer == NULL)
{
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, FText::Format(FText::FromString(FString("Error_NoGeometryInMesh", "There is no geometry information in mesh '{0}'")), FText::FromString(ToFString(Mesh->name)))), FFbxErrors::Generic_Mesh_NoGeometry);
return false;
}
//
// create materials
//
TArray<tinygltf::Material*> FoundMaterials;
for (auto Prim : Mesh->primitives)
{
tinygltf::Material* CurrentMaterial = &Scene->materials[Prim.material];
FoundMaterials.AddUnique(CurrentMaterial);
}
TArray<UMaterialInterface*> Materials;
if (ImportOptions.bImportMaterials)
{
Materials.Add(UMaterial::GetDefaultMaterial(EMaterialDomain::MD_Surface));
}
else if (ImportOptions.bImportTextures)
{
ImportTexturesFromNode(Node);
}
// Used later to offset the material indices on the raw triangle data
int32 MaterialIndexOffset = MeshMaterials.Num();
for (int32 MaterialIndex = 0; MaterialIndex < FoundMaterials.Num(); MaterialIndex++)
{
MaterialPair NewMaterialPair;// = new(MeshMaterials)FFbxMaterial;
tinygltf::Material* GLTFMaterial = FoundMaterials[MaterialIndex];
NewMaterialPair.GLTFMaterial = GLTFMaterial;
if (ImportOptions.bImportMaterials)
{
NewMaterialPair.Material = Materials[MaterialIndex];
}
else
{
FString MaterialFullName = ObjectTools::SanitizeObjectName(ToFString(GLTFMaterial->name));
FString BasePackageName = PackageTools::SanitizePackageName(FPackageName::GetLongPackagePath(StaticMeshComponent->GetOutermost()->GetName()) / MaterialFullName);
UMaterialInterface* UnrealMaterialInterface = FindObject<UMaterialInterface>(NULL, *(BasePackageName + TEXT(".") + MaterialFullName));
if (UnrealMaterialInterface == NULL)
{
UnrealMaterialInterface = UMaterial::GetDefaultMaterial(MD_Surface);
}
NewMaterialPair.Material = UnrealMaterialInterface;
}
}
if (FoundMaterials.Num() == 0)
{
UMaterial* DefaultMaterial = UMaterial::GetDefaultMaterial(MD_Surface);
check(DefaultMaterial);
MaterialPair NewMaterial;
NewMaterial.Material = DefaultMaterial;
NewMaterial.GLTFMaterial = NULL;
FoundMaterials.AddDefaulted(1);
}
// Smoothing is already included in the format
bool bSmoothingAvailable = true;
// TODO: Collisions
//
// build collision
//
bool bImportedCollision = false;
bool bEnableCollision = bImportedCollision || (/*GBuildStaticMeshCollision*/true && LODIndex == 0 && ImportOptions.bRemoveDegenerates);
for (int32 SectionIndex = MaterialIndexOffset; SectionIndex<MaterialIndexOffset + FoundMaterials.Num(); SectionIndex++)
{
FMeshSectionInfo Info = StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Get(LODIndex, SectionIndex);
Info.bEnableCollision = bEnableCollision;
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Set(LODIndex, SectionIndex, Info);
}
//
// build un-mesh triangles
//
// Construct the matrices for the conversion from right handed to left handed system
FMatrix TotalMatrix;
FMatrix TotalMatrixForNormal;
TotalMatrix = GetNodeTransform(GetMeshParentNode(Mesh));
FTransform ImportTransform(ImportOptions.ImportRotation.Quaternion(), ImportOptions.ImportTranslation, FVector(ImportOptions.ImportUniformScale));
FMatrix ImportMatrix = ImportTransform.ToMatrixWithScale();
TotalMatrix = TotalMatrix * ImportMatrix;
if (ImportOptions.bCorrectUpDirection)
{
FTransform Temp(FRotator(0.0f, 0.0f, -90.0f));
TotalMatrix = TotalMatrix * Temp.ToMatrixWithScale();
}
TotalMatrixForNormal = TotalMatrix.Inverse();
TotalMatrixForNormal = TotalMatrixForNormal.GetTransposed();
// Whether an odd number of axes have negative scale
bool OddNegativeScale = (TotalMatrix.M[0][0] * TotalMatrix.M[1][1] * TotalMatrix.M[2][2]) < 0;
// Copy the actual data!
// Vertex Positions
TArray<FVector> NewVertexPositions;
if (!ConvertAttrib(NewVertexPositions, Mesh, std::string("POSITION"), false))
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Error,
FText::FromString(FString("Could not obtain position data."))),
FFbxErrors::Generic_Mesh_LOD_InvalidIndex);
return false;
}
for (auto& Vertex : NewVertexPositions)
{
FVector4 Vert4(Vertex);
Vertex = TotalMatrix.TransformFVector4(Vert4);
}
int32 VertexCount = NewVertexPositions.Num();
// Triangle indices
TArray<int32> NewWedgeIndices;
ConvertAttrib(NewWedgeIndices, Mesh, std::string("__WedgeIndices"));
int32 WedgeCount = NewWedgeIndices.Num();
int32 TriangleCount = WedgeCount / 3;
if (TriangleCount == 0)
{
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, FText::Format(FText::FromString(FString("Error_NoTrianglesFoundInMesh", "No triangles were found on mesh '{0}'")), FText::FromString(ToFString(Mesh->name)))), FFbxErrors::StaticMesh_NoTriangles);
return false;
}
// Normals
TArray<FVector> NewWedgeTangentX, NewWedgeTangentY, NewWedgeTangentZ;
bool HasNormals = ConvertAttrib(NewWedgeTangentZ, Mesh, "NORMAL");
ConvertAttrib(NewWedgeTangentY, Mesh, "TANGENT");
ConvertAttrib(NewWedgeTangentX, Mesh, "BINORMAL");
if (!HasNormals)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::FromString(FString("Could not obtain data for normals; they will be recalculated but the model will lack smoothing data."))),
FFbxErrors::Generic_Mesh_LOD_InvalidIndex);
}
for (auto& Normal : NewWedgeTangentZ)
{
Normal = TotalMatrixForNormal.TransformVector(Normal);
}
// UVs
TArray<FVector2D> NewWedgeTexCoords[MAX_MESH_TEXTURE_COORDS];
bool bHasUVs = false;
for (int i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
bHasUVs |= ConvertAttrib(NewWedgeTexCoords[i], Mesh, std::string("TEXCOORD_") + std::to_string(i));
}
if (!bHasUVs)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::FromString(FString("Could not obtain UV data."))),
FFbxErrors::Generic_Mesh_LOD_InvalidIndex);
}
TArray<FColor> NewWedgeColors;
ConvertAttrib(NewWedgeColors, Mesh, std::string("COLOR")); // No need to check for errors
// Reverse the triangle winding order since glTF uses the opposite to Unreal
// Except if the model has negative scale on an odd number of axes, which will effectively do it for us
if (!OddNegativeScale)
{
ReverseTriDirection(NewWedgeIndices);
ReverseTriDirection(NewWedgeColors);
ReverseTriDirection(NewWedgeTangentX);
ReverseTriDirection(NewWedgeTangentY);
ReverseTriDirection(NewWedgeTangentZ);
for (int i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
ReverseTriDirection(NewWedgeTexCoords[i]);
}
}
TArray<int32> NewFaceMaterialIndices;
GetMaterialIndices(NewFaceMaterialIndices, (*Mesh));
TArray<int32> NewFaceSmoothingMasks; // Don't need to do anything with this since smoothing information is included implicitly in glTF
// Force attribute arrays to the correct size, otherwise it complains
NewFaceMaterialIndices.SetNumZeroed(TriangleCount);
NewFaceSmoothingMasks.SetNumZeroed(TriangleCount);
NewWedgeColors.SetNumZeroed(WedgeCount);
NewWedgeTangentX.SetNumZeroed(WedgeCount);
NewWedgeTangentY.SetNumZeroed(WedgeCount);
NewWedgeTangentZ.SetNumZeroed(WedgeCount);
for (int32 i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
NewWedgeTexCoords[i].SetNumZeroed(WedgeCount);
}
// Add the new data to the raw mesh
RawMesh.VertexPositions.Append(NewVertexPositions);
RawMesh.WedgeIndices.Append(NewWedgeIndices);
RawMesh.FaceMaterialIndices.Append(NewFaceMaterialIndices);
RawMesh.FaceSmoothingMasks.Append(NewFaceSmoothingMasks);
RawMesh.WedgeColors.Append(NewWedgeColors);
RawMesh.WedgeTangentX.Append(NewWedgeTangentX);
RawMesh.WedgeTangentY.Append(NewWedgeTangentY);
RawMesh.WedgeTangentZ.Append(NewWedgeTangentZ);
for (int32 i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
RawMesh.WedgeTexCoords[i].Append(NewWedgeTexCoords[i]);
}
return true;
}
UMaterialInterface* GLTFMeshBuilder::ToUMaterial(tinygltf::Material* Material)
{
return UMaterial::GetDefaultMaterial(MD_Surface);
}
FString GLTFMeshBuilder::GetError()
{
return Error;
}
FString GLTFMeshBuilder::ToFString(std::string InString)
{
return FString(InString.c_str());
}
std::string GLTFMeshBuilder::ToStdString(FString InString)
{
auto CharArray = InString.GetCharArray();
std::wstring WideString(&CharArray[0]);
std::wstring_convert< std::codecvt_utf8<wchar_t> > Convert;
return Convert.to_bytes(WideString);
}
template <typename T>
bool GLTFMeshBuilder::GetBufferData(TArray<T> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_SCALAR)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
default: BufferCopy<T, T>(OutArray, Start, Accessor->count, Stride); break;
}
return true;
}
// This specialization is almost the same, but checks for the VEC2 GLTF type and uses the overloaded BufferCopy function for FVector2D
template <>
bool GLTFMeshBuilder::GetBufferData(TArray<FVector2D> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC2)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
// This specialization is almost the same, but checks for the VEC3 GLTF type and uses the overloaded BufferCopy function for FVector
template <>
bool GLTFMeshBuilder::GetBufferData(TArray<FVector> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC3)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
// This specialization is almost the same, but checks for the VEC4 GLTF type and uses the overloaded BufferCopy function for FVector4
template <>
bool GLTFMeshBuilder::GetBufferData(TArray<FVector4> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC4)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
// This specialization is almost the same, but checks for a VEC3 or VEC4 GLTF type and uses the overloaded BufferCopy function for FColor
template <>
bool GLTFMeshBuilder::GetBufferData(TArray<FColor> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC3 && Accessor->type != TINYGLTF_TYPE_VEC4)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
bool GLTFMeshBuilder::HasAttribute(tinygltf::Mesh* Mesh, std::string AttribName) const
{
for (auto Prim : Mesh->primitives)
{
for (auto Entry : Prim.attributes)
{
if (Entry.first == AttribName)
{
return true;
}
}
}
return false;
}
template <typename T> int32 GLTFMeshBuilder::FindInStdVector(const std::vector<T> &InVector, const T &InElement) const
{
for (int32 i = 0; i < InVector.size(); ++i)
{
if (InVector[i] == InElement)
{
return i;
}
}
return -1;
}
FMatrix GLTFMeshBuilder::GetNodeTransform(tinygltf::Node* Node)
{
if (Node->matrix.size() == 16)
{
FMatrix Ret;
for (int32 i = 0; i < 4; ++i)
{
for (int32 j = 0; j < 4; ++j)
{
// Reverse order since glTF is column major and FMatrix is row major
Ret.M[j][i] = Node->matrix[(4 * i) + j];
}
}
return Ret;
}
else if (Node->rotation.size() == 4 && Node->scale.size() == 3 && Node->translation.size() == 3)
{
FQuat Rotation((float)Node->rotation[0], (float)Node->rotation[1], (float)Node->rotation[2], (float)Node->rotation[3]);
FVector Scale((float)Node->scale[0], (float)Node->scale[1], (float)Node->scale[2]);
FVector Translation((float)Node->translation[0], (float)Node->translation[1], (float)Node->translation[2]);
return FTransform(Rotation, Translation, Scale).ToMatrixWithScale();
}
else
{
return FMatrix::Identity;
}
}
size_t GLTFMeshBuilder::TypeSize(int Type) const
{
switch (Type)
{
case TINYGLTF_COMPONENT_TYPE_BYTE:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE>::Type);
case TINYGLTF_COMPONENT_TYPE_SHORT:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT>::Type);
case TINYGLTF_COMPONENT_TYPE_INT:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_INT>::Type);
case TINYGLTF_COMPONENT_TYPE_FLOAT:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT>::Type);
case TINYGLTF_COMPONENT_TYPE_DOUBLE:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE>::Type);
default:
return -1;
}
}
int32 GLTFMeshBuilder::GetNumWedges(tinygltf::Primitive* Prim) const
{
switch (Prim->mode)
{
case TINYGLTF_MODE_TRIANGLES:
return Prim->indices.size();
case TINYGLTF_MODE_TRIANGLE_STRIP:
case TINYGLTF_MODE_TRIANGLE_FAN:
return (Prim->indices.size() - 2) * 3;
default:
return 0;
}
}
void GLTFMeshBuilder::GetMaterialIndices(TArray<int32>& OutArray, tinygltf::Mesh& Mesh)
{
for (auto Prim : Mesh.primitives)
{
int32 Index = MeshMaterials.Find(ToFString(Prim.material));
for (int i = 0; i < GetNumWedges(&Prim) / 3; ++i)
{
OutArray.Add(Index);
}
}
}
template <typename SrcType, typename DstType> void GLTFMeshBuilder::BufferCopy(TArray<DstType>& OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add((DstType)BufferValue<SrcType>(Data));
Data += Stride;
}
}
template <typename SrcType> void GLTFMeshBuilder::BufferCopy(TArray<FVector2D> &OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FVector2D(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType))));
Data += Stride;
}
}
template <typename SrcType> void GLTFMeshBuilder::BufferCopy(TArray<FVector> &OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FVector(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType))));
Data += Stride;
}
}
template <typename SrcType> void GLTFMeshBuilder::BufferCopy(TArray<FVector4> &OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FVector4(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType)), BufferValue<SrcType>(Data + 3 * sizeof(SrcType))));
Data += Stride;
}
}
template <typename SrcType> void GLTFMeshBuilder::BufferCopy(TArray<FColor> &OutArray, int InType, unsigned char* Data, int32 Count, size_t Stride)
{
switch (InType)
{
case TINYGLTF_TYPE_VEC3:
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FColor(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType))));
Data += Stride;
}
break;
case TINYGLTF_TYPE_VEC4:
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FColor(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType)), BufferValue<SrcType>(Data + 3 * sizeof(SrcType))));
Data += Stride;
}
break;
default: return;
}
}
void GLTFMeshBuilder::AddTokenizedErrorMessage(TSharedRef<FTokenizedMessage> Error, FName ErrorName)
{
UE_LOG(LogTemp, Warning, TEXT("%s"), *(Error->ToText().ToString()));
#include "GLTFLoaderPrivatePCH.h"
#include <locale>
#include <codecvt>
#define TINYGLTF_LOADER_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "tiny_gltf_loader.h"
#include "GLTFMeshBuilder.h"
#include "GLTFLoaderCommands.h"
//#include "Editor/UnrealEd/Classes/Factories/Factory.h"
// These replace TargetPlatform.h since it can't seem to find the right paths from here
#include "ModuleManager.h"
#include "Developer/TargetPlatform/Public/Interfaces/TargetDeviceId.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetDevice.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetPlatform.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetPlatformModule.h"
#include "Developer/TargetPlatform/Public/Interfaces/ITargetPlatformManagerModule.h"
#include "UnrealEd.h"
#include "Developer/RawMesh/Public/RawMesh.h"
#include "Developer/MeshUtilities/Public/MeshUtilities.h"
#include "Engine.h"
#include "StaticMeshResources.h"
#include "TextureLayout.h"
#include "ObjectTools.h"
#include "PackageTools.h"
#include "Editor/UnrealEd/Classes/Factories/FbxStaticMeshImportData.h"
#include "../Private/GeomFitUtils.h"
#include "FbxErrors.h"
#include "Engine/StaticMeshSocket.h"
#include "Engine/Polys.h"
#include "PhysicsEngine/BodySetup.h"
/// @cond
// Syntactic sugar to neatly map the TinyGLTF enum to the corresponding data type
// Adapted from http://stackoverflow.com/questions/1735796/is-it-possible-to-choose-a-c-generic-type-parameter-at-runtime
template<int Type> struct GLTFType;
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_BYTE> { typedef int8 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> { typedef uint8 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_SHORT> { typedef int16 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> { typedef uint16 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_INT> { typedef int32 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> { typedef uint32 Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_FLOAT> { typedef float Type; };
template<> struct GLTFType <TINYGLTF_COMPONENT_TYPE_DOUBLE> { typedef double Type; };
template<> struct GLTFType <TINYGLTF_TYPE_VEC2> { typedef FVector2D Type; };
template<> struct GLTFType <TINYGLTF_TYPE_VEC3> { typedef FVector Type; };
template<> struct GLTFType <TINYGLTF_TYPE_VEC4> { typedef FVector4 Type; };
/// @endcond
template <typename T>
bool UUGLTFMeshBuilder::ConvertAttrib(TArray<T> &OutArray, tinygltf::Mesh* Mesh, std::string AttribName, bool UseWedgeIndices, bool AutoSetArraySize)
{
if (AttribName != "__WedgeIndices" && !HasAttribute(Mesh, AttribName))
{
return false;
}
UE_LOG(LogTemp, Log, TEXT("%s"), *(FText::Format(FText::FromString("Importing data for attribute \"{0}\""), FText::FromString(ToFString(AttribName)))).ToString());
if (AutoSetArraySize)// This should always be false since for now we are just extending the array each time we want to add an element
{
int32 Size = 0;
if (UseWedgeIndices)
{
for (auto Prim : Mesh->primitives)
{
Size += GetNumWedges(&Prim); // Number of wedges
}
}
else
{
for (auto Prim : Mesh->primitives)
{
Size += Scene->accessors[Prim.attributes.begin()->second].count; // Number of vertices
}
}
OutArray.SetNumUninitialized(Size);
}
// Getting an attribute for individual triangle corners ("wedges")
else if (UseWedgeIndices && AttribName != "__WedgeIndices")// Make sure we don't try to access indices for the index array itself!
{
for (auto Prim : Mesh->primitives)
{
std::string IndexAccessorName = Prim.indices;
std::string AttribAccessorName = Prim.attributes[AttribName];
tinygltf::Accessor* IndexAccessor = &Scene->accessors[IndexAccessorName];
tinygltf::Accessor* AttribAccessor = &Scene->accessors[AttribAccessorName];
if (!IndexAccessor || !AttribAccessor)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::FromString(FString("Invalid accessor"))),
FFbxErrors::Generic_Mesh_NoGeometry);
return false;
}
TArray<int32> IndexArray;
TArray<T> VertArray;
if (!GetBufferData(IndexArray, IndexAccessor) || !GetBufferData(VertArray, AttribAccessor))
{
return false;
}
switch (Prim.mode)
{
case TINYGLTF_MODE_TRIANGLES:
for (auto Index : IndexArray)
{
OutArray.Add(VertArray[Index]);
}
break;
case TINYGLTF_MODE_TRIANGLE_STRIP:
OutArray.Add(VertArray[IndexArray[0]]);
OutArray.Add(VertArray[IndexArray[1]]);
OutArray.Add(VertArray[IndexArray[2]]);
for (int i = 2; i < IndexAccessor->count - 2; i += 2)
{
// First triangle
OutArray.Add(VertArray[IndexArray[ i ]]);
OutArray.Add(VertArray[IndexArray[i-1]]);
OutArray.Add(VertArray[IndexArray[i+1]]);
// Second triangle
OutArray.Add(VertArray[IndexArray[ i ]]);
OutArray.Add(VertArray[IndexArray[i+1]]);
OutArray.Add(VertArray[IndexArray[i+2]]);
}
break;
case TINYGLTF_MODE_TRIANGLE_FAN:
for (int i = 1; i < IndexAccessor->count - 1; ++i)
{
// Triangle
OutArray.Add(VertArray[IndexArray[ 0 ]]);
OutArray.Add(VertArray[IndexArray[ i ]]);
OutArray.Add(VertArray[IndexArray[i+1]]);
}
break;
default:
return false;
}
}
}
// Getting a vertex attribute
else
{
for (auto Prim : Mesh->primitives)
{
std::string AccessorName;
if (AttribName == "__WedgeIndices")
{
AccessorName = Prim.indices;
}
else
{
AccessorName = Prim.attributes[AttribName];
}
if (!GetBufferData(OutArray, &Scene->accessors[AccessorName], true))
{
return false;
}
}
}
return true;
}
// Retrieve a value from the buffer, implicitly accounting for endianness
// Adapted from http://stackoverflow.com/questions/13001183/how-to-read-little-endian-integers-from-file-in-c
template <typename T> T UGLTFMeshBuilder::BufferValue(void* Data/*, uint8 Size*/)
{
T Ret = T(0);
auto NewData = reinterpret_cast<unsigned char*>(Data);
for (int i = 0; i < sizeof(T); ++i)
{
Ret |= (T)(NewData[i]) << (8 * i);
}
return Ret;
}
// Use unions for floats and doubles since they don't have a bitwise OR operator
template <> float UGLTFMeshBuilder::BufferValue(void* Data)
{
assert(sizeof(float) == sizeof(int32));
union
{
float Ret;
int32 IntRet;
};
Ret = 0.0f;
auto NewData = reinterpret_cast<unsigned char*>(Data);
for (int i = 0; i < sizeof(int32); ++i)
{
IntRet |= (int32)(NewData[i]) << (8 * i);
}
return Ret;
}
template <> double UGLTFMeshBuilder::BufferValue(void* Data)
{
assert(sizeof(float) == sizeof(int64));
union
{
double Ret;
int64 IntRet;
};
Ret = 0.0;
auto NewData = reinterpret_cast<unsigned char*>(Data);
for (int i = 0; i < sizeof(int64); ++i)
{
IntRet |= (int64)(NewData[i]) << (8 * i);
}
return Ret;
}
/// @cond
struct MaterialPair
{
tinygltf::Material* GLTFMaterial;
UMaterialInterface* Material;
};
/// @endcond
UGLTFMeshBuilder::UGLTFMeshBuilder()
: UGLTFMeshBuilder(TEXT("H:/Repositories/MasterArbeit/glTF-Sample-Models/1.0/Duck/glTF/Duck.gltf"))
{
} //DO NOT USE
UGLTFMeshBuilder::UGLTFMeshBuilder(FString FilePath)
{
Loader = new tinygltf::TinyGLTFLoader;
Scene = new tinygltf::Scene;
std::string TempError;
LoadSuccess = Loader->LoadFromFile((*Scene), TempError, ToStdString(FilePath));
Error = ToFString(TempError);
}
UGLTFMeshBuilder::~UGLTFMeshBuilder()
{
delete Loader;
delete Scene;
}
int32 UGLTFMeshBuilder::GetMeshCount(FString NodeName)
{
return (int32)Scene->nodes[ToStdString(NodeName)].meshes.size();
}
FString UGLTFMeshBuilder::GetRootNode()
{
for (auto ThisNode : Scene->nodes)
{
bool ShouldReturn = false;
for (auto ThatNode : Scene->nodes)
{
if (FindInStdVector<std::string>(ThatNode.second.children, ThisNode.first) == -1) // If this node's name doesn't appear in any node's list of children
{
ShouldReturn = true;
}
}
if (ShouldReturn)
{
return ToFString(ThisNode.first);
}
}
return FString("");
}
tinygltf::Node* UGLTFMeshBuilder::GetMeshParentNode(tinygltf::Mesh* InMesh)
{
for (auto &Node : Scene->nodes)
{
for (auto &MeshName : Node.second.meshes)
{
if (&Scene->meshes[MeshName] == InMesh)
{
return &Node.second;
}
}
}
return NULL;
}
TArray<FString> UGLTFMeshBuilder::GetMeshNames(FString NodeName, bool GetChildren)
{
TArray<FString> MeshNameArray;
for (auto Mesh : Scene->nodes[ToStdString(NodeName)].meshes)
{
MeshNameArray.Add(ToFString(Mesh));
}
if (GetChildren)
{
for (auto ChildName : Scene->nodes[ToStdString(NodeName)].children)
{
MeshNameArray.Append(GetMeshNames(ToFString(ChildName)));
}
}
return MeshNameArray;
}
UStaticMeshComponent* UGLTFMeshBuilder::ImportStaticMeshAsSingle(UObject* InParent, TArray<FString>& MeshNameArray, const FName InName, EObjectFlags Flags, UStaticMeshComponent* InStaticMesh)
{
auto ImportOptions = FGLTFLoaderModule::ImportOptions;
int LODIndex = 0;
bool bBuildStatus = true;
// Make sure rendering is done - so we are not changing data being used by collision drawing.
FlushRenderingCommands();
if (MeshNameArray.Num() == 0)
{
return NULL;
}
Parent = InParent;
FString MeshName = ObjectTools::SanitizeObjectName(InName.ToString());
// Parent package to place new meshes
UPackage* Package = NULL;
// create empty mesh
UStaticMeshComponent* StaticMeshComponent = NULL;
UStaticMeshComponent* ExistingMesh = NULL;
UObject* ExistingObject = NULL;
// A mapping of vertex positions to their color in the existing static mesh
TMap<FVector, FColor> ExistingVertexColorData;
FString NewPackageName;
if( InStaticMesh == NULL || LODIndex == 0 )
{
// Create a package for each mesh
NewPackageName = FPackageName::GetLongPackagePath(Parent->GetOutermost()->GetName()) + TEXT("/") + MeshName;
NewPackageName = PackageTools::SanitizePackageName(NewPackageName);
Package = CreatePackage(NULL, *NewPackageName);
ExistingMesh = FindObject<UStaticMeshComponent>( Package, *MeshName );
ExistingObject = FindObject<UObject>( Package, *MeshName );
}
if (ExistingMesh)
{
// Free any RHI resources for existing mesh before we re-create in place.
ExistingMesh->PreEditChange(NULL);
}
else if (ExistingObject)
{
// Replacing an object. Here we go!
// Delete the existing object
bool bDeleteSucceeded = ObjectTools::DeleteSingleObject( ExistingObject );
if (bDeleteSucceeded)
{
// Force GC so we can cleanly create a new asset (and not do an 'in place' replacement)
CollectGarbage( GARBAGE_COLLECTION_KEEPFLAGS );
// Create a package for each mesh
Package = CreatePackage(NULL, *NewPackageName);
// Require the parent because it will have been invalidated from the garbage collection
Parent = Package;
}
else
{
// failed to delete
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, FText::Format(FText::FromString(FString("{0} wasn't created.\n\nThe asset is referenced by other content.")), FText::FromString(MeshName))), FFbxErrors::Generic_CannotDeleteReferenced);
return NULL;
}
}
if( InStaticMesh != NULL && LODIndex > 0 )
{
StaticMeshComponent = InStaticMesh;
}
else
{
StaticMeshComponent = NewObject<UStaticMeshComponent>(Package, FName(*MeshName), Flags | RF_Public);
}
verify(StaticMeshComponent != NULL);
if (StaticMeshComponent->GetStaticMesh() == NULL ) {
UStaticMesh *mesh = NewObject<UStaticMesh>(Package);
StaticMeshComponent->SetStaticMesh(mesh);
}
verify(StaticMeshComponent->GetStaticMesh() != NULL);
if (StaticMeshComponent->GetStaticMesh()->SourceModels.Num() < LODIndex+1)
{
// Add one LOD
//StaticMeshComponent->GetStaticMesh()->SourceModels.AddUninitialized();
//StaticMeshComponent->GetStaticMesh()->SourceModels = new FStaticMeshSourceModel();
new(StaticMeshComponent->GetStaticMesh()->SourceModels) FStaticMeshSourceModel();
if (StaticMeshComponent->GetStaticMesh()->SourceModels.Num() < LODIndex+1)
{
LODIndex = StaticMeshComponent->GetStaticMesh()->SourceModels.Num() - 1;
}
}
FStaticMeshSourceModel& SrcModel = StaticMeshComponent->GetStaticMesh()->SourceModels[LODIndex];
if( InStaticMesh != NULL && LODIndex > 0 && !SrcModel.RawMeshBulkData->IsEmpty() )
{
// clear out the old mesh data
FRawMesh EmptyRawMesh;
SrcModel.RawMeshBulkData->SaveRawMesh( EmptyRawMesh );
}
// make sure it has a new lighting guid
StaticMeshComponent->GetStaticMesh()->LightingGuid = FGuid::NewGuid();
// Set it to use textured lightmaps. Note that Build Lighting will do the error-checking (texcoordindex exists for all LODs, etc).
StaticMeshComponent->GetStaticMesh()->LightMapResolution = 64;
StaticMeshComponent->GetStaticMesh()->LightMapCoordinateIndex = 1;
FRawMesh NewRawMesh;
SrcModel.RawMeshBulkData->LoadRawMesh(NewRawMesh);
//for (FString Name : MeshNameArray)
for(int i = 0; i < MeshNameArray.Num(); i++)
{
FString Name = MeshNameArray[i];
tinygltf::Mesh* Mesh = &Scene->meshes[ToStdString(Name)];
if (Mesh)
{
for (auto Prim : Mesh->primitives)
{
MeshMaterials.AddUnique(ToFString(Prim.material));
}
}
}
for (FString Name : MeshNameArray)
{
tinygltf::Mesh* Mesh = &Scene->meshes[ToStdString(Name)];
if (Mesh)
{
if (!BuildStaticMeshFromGeometry(Mesh, StaticMeshComponent, LODIndex, NewRawMesh))
{
bBuildStatus = false;
break;
}
}
}
// Store the new raw mesh.
SrcModel.RawMeshBulkData->SaveRawMesh(NewRawMesh);
if (bBuildStatus)
{
// Compress the materials array by removing any duplicates.
bool bDoRemap = false;
TArray<int32> MaterialMap;
TArray<tinygltf::Material*> UniqueMaterials;
for (int32 MaterialIndex = 0; MaterialIndex < MeshMaterials.Num(); ++MaterialIndex)
{
bool bUnique = true;
for (int32 OtherMaterialIndex = MaterialIndex - 1; OtherMaterialIndex >= 0; --OtherMaterialIndex)
{
if (MeshMaterials[MaterialIndex] == MeshMaterials[OtherMaterialIndex])
{
int32 UniqueIndex = MaterialMap[OtherMaterialIndex];
MaterialMap.Add(UniqueIndex);
bDoRemap = true;
bUnique = false;
break;
}
}
if (bUnique)
{
int32 UniqueIndex = UniqueMaterials.Add(&Scene->materials[ToStdString(MeshMaterials[MaterialIndex])]);
MaterialMap.Add( UniqueIndex );
}
}
if (UniqueMaterials.Num() > 8)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::Format(FText::FromString(FString("StaticMesh has a large number({1}) of materials and may render inefficently. Consider breaking up the mesh into multiple Static Mesh Assets.")),
FText::AsNumber(UniqueMaterials.Num())
)),
FFbxErrors::StaticMesh_TooManyMaterials);
}
// Sort materials based on _SkinXX in the name.
TArray<uint32> SortedMaterialIndex;
for (int32 MaterialIndex = 0; MaterialIndex < MeshMaterials.Num(); ++MaterialIndex)
{
int32 SkinIndex = 0xffff;
int32 RemappedIndex = MaterialMap[MaterialIndex];
if (!SortedMaterialIndex.IsValidIndex(RemappedIndex))
{
FString GLTFMatName = MeshMaterials[RemappedIndex];
int32 Offset = GLTFMatName.Find(TEXT("_SKIN"), ESearchCase::IgnoreCase, ESearchDir::FromEnd);
if (Offset != INDEX_NONE)
{
// Chop off the material name so we are left with the number in _SKINXX
FString SkinXXNumber = GLTFMatName.Right(GLTFMatName.Len() - (Offset + 1)).RightChop(4);
if (SkinXXNumber.IsNumeric())
{
SkinIndex = FPlatformString::Atoi( *SkinXXNumber );
bDoRemap = true;
}
}
SortedMaterialIndex.Add(((uint32)SkinIndex << 16) | ((uint32)RemappedIndex & 0xffff));
}
}
SortedMaterialIndex.Sort();
TArray<tinygltf::Material*> SortedMaterials;
for (int32 SortedIndex = 0; SortedIndex < SortedMaterialIndex.Num(); ++SortedIndex)
{
int32 RemappedIndex = SortedMaterialIndex[SortedIndex] & 0xffff;
SortedMaterials.Add(UniqueMaterials[RemappedIndex]);
}
for (int32 MaterialIndex = 0; MaterialIndex < MaterialMap.Num(); ++MaterialIndex)
{
for (int32 SortedIndex = 0; SortedIndex < SortedMaterialIndex.Num(); ++SortedIndex)
{
int32 RemappedIndex = SortedMaterialIndex[SortedIndex] & 0xffff;
if (MaterialMap[MaterialIndex] == RemappedIndex)
{
MaterialMap[MaterialIndex] = SortedIndex;
break;
}
}
}
// Remap material indices.
int32 MaxMaterialIndex = 0;
int32 FirstOpenUVChannel = 1;
{
FRawMesh LocalRawMesh;
SrcModel.RawMeshBulkData->LoadRawMesh(LocalRawMesh);
if (bDoRemap)
{
for (int32 TriIndex = 0; TriIndex < LocalRawMesh.FaceMaterialIndices.Num(); ++TriIndex)
{
LocalRawMesh.FaceMaterialIndices[TriIndex] = MaterialMap[LocalRawMesh.FaceMaterialIndices[TriIndex]];
}
}
// Compact material indices so that we won't have any sections with zero triangles.
LocalRawMesh.CompactMaterialIndices();
// Also compact the sorted materials array.
if (LocalRawMesh.MaterialIndexToImportIndex.Num() > 0)
{
TArray<tinygltf::Material*> OldSortedMaterials;
Exchange(OldSortedMaterials,SortedMaterials);
SortedMaterials.Empty(LocalRawMesh.MaterialIndexToImportIndex.Num());
for (int32 MaterialIndex = 0; MaterialIndex < LocalRawMesh.MaterialIndexToImportIndex.Num(); ++MaterialIndex)
{
tinygltf::Material* Material;
int32 ImportIndex = LocalRawMesh.MaterialIndexToImportIndex[MaterialIndex];
if (OldSortedMaterials.IsValidIndex(ImportIndex))
{
Material = OldSortedMaterials[ImportIndex];
}
SortedMaterials.Add(Material);
}
}
for (int32 TriIndex = 0; TriIndex < LocalRawMesh.FaceMaterialIndices.Num(); ++TriIndex)
{
MaxMaterialIndex = FMath::Max<int32>(MaxMaterialIndex,LocalRawMesh.FaceMaterialIndices[TriIndex]);
}
for( int32 i = 0; i < MAX_MESH_TEXTURE_COORDS; i++ )
{
if( LocalRawMesh.WedgeTexCoords[i].Num() == 0 )
{
FirstOpenUVChannel = i;
break;
}
}
SrcModel.RawMeshBulkData->SaveRawMesh(LocalRawMesh);
}
// Setup per-section info and the materials array.
if (LODIndex == 0)
{
StaticMeshComponent->GetMaterial(0);
//TODO check if right
//StaticMeshComponent->Materials.Empty();
StaticMeshComponent->GetNumMaterials();
}
// Build a new map of sections with the unique material set
FMeshSectionInfoMap NewMap;
int32 NumMaterials = FMath::Min(SortedMaterials.Num(),MaxMaterialIndex+1);
for (int32 MaterialIndex = 0; MaterialIndex < NumMaterials; ++MaterialIndex)
{
FMeshSectionInfo Info = StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Get(LODIndex, MaterialIndex);
//FIXME
//int32 Index = StaticMeshComponent->Materials.Add(ToUMaterial(SortedMaterials[MaterialIndex]));
//Info.MaterialIndex = Index;
//NewMap.Set( LODIndex, MaterialIndex, Info);
}
// Copy the final section map into the static mesh
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Clear();
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.CopyFrom(NewMap);
FRawMesh LocalRawMesh;
SrcModel.RawMeshBulkData->LoadRawMesh(LocalRawMesh);
// Setup default LOD settings based on the selected LOD group.
if (ExistingMesh == NULL && LODIndex == 0)
{
ITargetPlatform* CurrentPlatform = GetTargetPlatformManagerRef().GetRunningTargetPlatform();
check(CurrentPlatform);
const FStaticMeshLODGroup& LODGroup = CurrentPlatform->GetStaticMeshLODSettings().GetLODGroup(ImportOptions.StaticMeshLODGroup);
int32 NumLODs = LODGroup.GetDefaultNumLODs();
while (StaticMeshComponent->GetStaticMesh()->SourceModels.Num() < NumLODs)
{
new (StaticMeshComponent->GetStaticMesh()->SourceModels) FStaticMeshSourceModel();
}
for (int32 ModelLODIndex = 0; ModelLODIndex < NumLODs; ++ModelLODIndex)
{
StaticMeshComponent->GetStaticMesh()->SourceModels[ModelLODIndex].ReductionSettings = LODGroup.GetDefaultSettings(ModelLODIndex);
}
StaticMeshComponent->GetStaticMesh()->LightMapResolution = LODGroup.GetDefaultLightMapResolution();
}
// @todo This overrides restored values currently but we need to be able to import over the existing settings if the user chose to do so.
SrcModel.BuildSettings.bRemoveDegenerates = ImportOptions.bRemoveDegenerates;
SrcModel.BuildSettings.bBuildAdjacencyBuffer = ImportOptions.bBuildAdjacencyBuffer;
SrcModel.BuildSettings.bRecomputeNormals = LocalRawMesh.WedgeTangentZ.Num() == 0;
SrcModel.BuildSettings.bRecomputeTangents = LocalRawMesh.WedgeTangentX.Num() == 0 || LocalRawMesh.WedgeTangentY.Num() == 0;
SrcModel.BuildSettings.bUseMikkTSpace = false;
if( ImportOptions.bGenerateLightmapUVs )
{
SrcModel.BuildSettings.bGenerateLightmapUVs = true;
SrcModel.BuildSettings.DstLightmapIndex = FirstOpenUVChannel;
StaticMeshComponent->GetStaticMesh()->LightMapCoordinateIndex = FirstOpenUVChannel;
}
else
{
SrcModel.BuildSettings.bGenerateLightmapUVs = false;
}
TArray<FText> BuildErrors;
StaticMeshComponent->GetStaticMesh()->LODGroup = ImportOptions.StaticMeshLODGroup;
StaticMeshComponent->GetStaticMesh()->Build(false, &BuildErrors);
for( FText& Error : BuildErrors )
{
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Warning, Error), FFbxErrors::StaticMesh_BuildError );
}
// this is damage control. After build, we'd like to absolutely sure that
// all index is pointing correctly and they're all used. Otherwise we remove them
FMeshSectionInfoMap OldSectionInfoMap = StaticMeshComponent->GetStaticMesh()->SectionInfoMap;
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Clear();
// fix up section data
for (int32 LODResourceIndex = 0; LODResourceIndex < StaticMeshComponent->GetStaticMesh()->RenderData->LODResources.Num(); ++LODResourceIndex)
{
FStaticMeshLODResources& LOD = StaticMeshComponent->GetStaticMesh()->RenderData->LODResources[LODResourceIndex];
int32 NumSections = LOD.Sections.Num();
for(int32 SectionIndex = 0; SectionIndex < NumSections; ++SectionIndex)
{
FMeshSectionInfo Info = OldSectionInfoMap.Get(LODResourceIndex, SectionIndex);
if (StaticMeshComponent->GetMaterials().IsValidIndex(Info.MaterialIndex))
{
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Set(LODResourceIndex, SectionIndex, Info);
}
}
}
}
else
{
StaticMeshComponent = NULL;
}
return StaticMeshComponent;
}
// Reverse the winding order for triangle indices
template <typename T>
void UGLTFMeshBuilder::ReverseTriDirection(TArray<T>& OutArray)
{
for (int i = 0; i < OutArray.Num() - 2; i += 3)
{
T Temp = OutArray[i];
OutArray[i] = OutArray[i + 2];
OutArray[i + 2] = Temp;
}
}
bool UGLTFMeshBuilder::BuildStaticMeshFromGeometry(tinygltf::Mesh* Mesh, UStaticMeshComponent* StaticMeshComponent, int LODIndex, FRawMesh& RawMesh)
{
check(StaticMeshComponent->GetStaticMesh()->SourceModels.IsValidIndex(LODIndex));
auto ImportOptions = FGLTFLoaderModule::ImportOptions;
tinygltf::Node* Node = GetMeshParentNode(Mesh);
FStaticMeshSourceModel& SrcModel = StaticMeshComponent->GetStaticMesh()->SourceModels[LODIndex];
tinygltf::Primitive* BaseLayer = &Mesh->primitives[0];
if (BaseLayer == NULL)
{
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, FText::Format(FText::FromString(FString("Error_NoGeometryInMesh", "There is no geometry information in mesh '{0}'")), FText::FromString(ToFString(Mesh->name)))), FFbxErrors::Generic_Mesh_NoGeometry);
return false;
}
//
// create materials
//
TArray<tinygltf::Material*> FoundMaterials;
for (auto Prim : Mesh->primitives)
{
tinygltf::Material* CurrentMaterial = &Scene->materials[Prim.material];
FoundMaterials.AddUnique(CurrentMaterial);
}
TArray<UMaterialInterface*> Materials;
if (ImportOptions.bImportMaterials)
{
Materials.Add(UMaterial::GetDefaultMaterial(EMaterialDomain::MD_Surface));
}
else if (ImportOptions.bImportTextures)
{
ImportTexturesFromNode(Node);
}
// Used later to offset the material indices on the raw triangle data
int32 MaterialIndexOffset = MeshMaterials.Num();
for (int32 MaterialIndex = 0; MaterialIndex < FoundMaterials.Num(); MaterialIndex++)
{
MaterialPair NewMaterialPair;// = new(MeshMaterials)FFbxMaterial;
tinygltf::Material* GLTFMaterial = FoundMaterials[MaterialIndex];
NewMaterialPair.GLTFMaterial = GLTFMaterial;
if (ImportOptions.bImportMaterials)
{
NewMaterialPair.Material = Materials[MaterialIndex];
}
else
{
FString MaterialFullName = ObjectTools::SanitizeObjectName(ToFString(GLTFMaterial->name));
FString BasePackageName = PackageTools::SanitizePackageName(FPackageName::GetLongPackagePath(StaticMeshComponent->GetOutermost()->GetName()) / MaterialFullName);
UMaterialInterface* UnrealMaterialInterface = FindObject<UMaterialInterface>(NULL, *(BasePackageName + TEXT(".") + MaterialFullName));
if (UnrealMaterialInterface == NULL)
{
UnrealMaterialInterface = UMaterial::GetDefaultMaterial(MD_Surface);
}
NewMaterialPair.Material = UnrealMaterialInterface;
}
}
if (FoundMaterials.Num() == 0)
{
UMaterial* DefaultMaterial = UMaterial::GetDefaultMaterial(MD_Surface);
check(DefaultMaterial);
MaterialPair NewMaterial;
NewMaterial.Material = DefaultMaterial;
NewMaterial.GLTFMaterial = NULL;
FoundMaterials.AddDefaulted(1);
}
// Smoothing is already included in the format
bool bSmoothingAvailable = true;
// TODO: Collisions
//
// build collision
//
bool bImportedCollision = false;
bool bEnableCollision = bImportedCollision || (/*GBuildStaticMeshCollision*/true && LODIndex == 0 && ImportOptions.bRemoveDegenerates);
for (int32 SectionIndex = MaterialIndexOffset; SectionIndex<MaterialIndexOffset + FoundMaterials.Num(); SectionIndex++)
{
FMeshSectionInfo Info = StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Get(LODIndex, SectionIndex);
Info.bEnableCollision = bEnableCollision;
StaticMeshComponent->GetStaticMesh()->SectionInfoMap.Set(LODIndex, SectionIndex, Info);
}
//
// build un-mesh triangles
//
// Construct the matrices for the conversion from right handed to left handed system
FMatrix TotalMatrix;
FMatrix TotalMatrixForNormal;
TotalMatrix = GetNodeTransform(GetMeshParentNode(Mesh));
FTransform ImportTransform(ImportOptions.ImportRotation.Quaternion(), ImportOptions.ImportTranslation, FVector(ImportOptions.ImportUniformScale));
FMatrix ImportMatrix = ImportTransform.ToMatrixWithScale();
TotalMatrix = TotalMatrix * ImportMatrix;
if (ImportOptions.bCorrectUpDirection)
{
FTransform Temp(FRotator(0.0f, 0.0f, -90.0f));
TotalMatrix = TotalMatrix * Temp.ToMatrixWithScale();
}
TotalMatrixForNormal = TotalMatrix.Inverse();
TotalMatrixForNormal = TotalMatrixForNormal.GetTransposed();
// Whether an odd number of axes have negative scale
bool OddNegativeScale = (TotalMatrix.M[0][0] * TotalMatrix.M[1][1] * TotalMatrix.M[2][2]) < 0;
// Copy the actual data!
// Vertex Positions
TArray<FVector> NewVertexPositions;
if (!ConvertAttrib(NewVertexPositions, Mesh, std::string("POSITION"), false))
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Error,
FText::FromString(FString("Could not obtain position data."))),
FFbxErrors::Generic_Mesh_LOD_InvalidIndex);
return false;
}
for (auto& Vertex : NewVertexPositions)
{
FVector4 Vert4(Vertex);
Vertex = TotalMatrix.TransformFVector4(Vert4);
}
int32 VertexCount = NewVertexPositions.Num();
// Triangle indices
TArray<int32> NewWedgeIndices;
ConvertAttrib(NewWedgeIndices, Mesh, std::string("__WedgeIndices"));
int32 WedgeCount = NewWedgeIndices.Num();
int32 TriangleCount = WedgeCount / 3;
if (TriangleCount == 0)
{
AddTokenizedErrorMessage(FTokenizedMessage::Create(EMessageSeverity::Error, FText::Format(FText::FromString(FString("Error_NoTrianglesFoundInMesh", "No triangles were found on mesh '{0}'")), FText::FromString(ToFString(Mesh->name)))), FFbxErrors::StaticMesh_NoTriangles);
return false;
}
// Normals
TArray<FVector> NewWedgeTangentX, NewWedgeTangentY, NewWedgeTangentZ;
bool HasNormals = ConvertAttrib(NewWedgeTangentZ, Mesh, "NORMAL");
ConvertAttrib(NewWedgeTangentY, Mesh, "TANGENT");
ConvertAttrib(NewWedgeTangentX, Mesh, "BINORMAL");
if (!HasNormals)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::FromString(FString("Could not obtain data for normals; they will be recalculated but the model will lack smoothing data."))),
FFbxErrors::Generic_Mesh_LOD_InvalidIndex);
}
for (auto& Normal : NewWedgeTangentZ)
{
Normal = TotalMatrixForNormal.TransformVector(Normal);
}
// UVs
TArray<FVector2D> NewWedgeTexCoords[MAX_MESH_TEXTURE_COORDS];
bool bHasUVs = false;
for (int i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
bHasUVs |= ConvertAttrib(NewWedgeTexCoords[i], Mesh, std::string("TEXCOORD_") + std::to_string(i));
}
if (!bHasUVs)
{
AddTokenizedErrorMessage(
FTokenizedMessage::Create(
EMessageSeverity::Warning,
FText::FromString(FString("Could not obtain UV data."))),
FFbxErrors::Generic_Mesh_LOD_InvalidIndex);
}
TArray<FColor> NewWedgeColors;
ConvertAttrib(NewWedgeColors, Mesh, std::string("COLOR")); // No need to check for errors
// Reverse the triangle winding order since glTF uses the opposite to Unreal
// Except if the model has negative scale on an odd number of axes, which will effectively do it for us
if (!OddNegativeScale)
{
ReverseTriDirection(NewWedgeIndices);
ReverseTriDirection(NewWedgeColors);
ReverseTriDirection(NewWedgeTangentX);
ReverseTriDirection(NewWedgeTangentY);
ReverseTriDirection(NewWedgeTangentZ);
for (int i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
ReverseTriDirection(NewWedgeTexCoords[i]);
}
}
TArray<int32> NewFaceMaterialIndices;
GetMaterialIndices(NewFaceMaterialIndices, (*Mesh));
TArray<int32> NewFaceSmoothingMasks; // Don't need to do anything with this since smoothing information is included implicitly in glTF
// Force attribute arrays to the correct size, otherwise it complains
NewFaceMaterialIndices.SetNumZeroed(TriangleCount);
NewFaceSmoothingMasks.SetNumZeroed(TriangleCount);
NewWedgeColors.SetNumZeroed(WedgeCount);
NewWedgeTangentX.SetNumZeroed(WedgeCount);
NewWedgeTangentY.SetNumZeroed(WedgeCount);
NewWedgeTangentZ.SetNumZeroed(WedgeCount);
for (int32 i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
NewWedgeTexCoords[i].SetNumZeroed(WedgeCount);
}
// Add the new data to the raw mesh
RawMesh.VertexPositions.Append(NewVertexPositions);
RawMesh.WedgeIndices.Append(NewWedgeIndices);
RawMesh.FaceMaterialIndices.Append(NewFaceMaterialIndices);
RawMesh.FaceSmoothingMasks.Append(NewFaceSmoothingMasks);
RawMesh.WedgeColors.Append(NewWedgeColors);
RawMesh.WedgeTangentX.Append(NewWedgeTangentX);
RawMesh.WedgeTangentY.Append(NewWedgeTangentY);
RawMesh.WedgeTangentZ.Append(NewWedgeTangentZ);
for (int32 i = 0; i < MAX_MESH_TEXTURE_COORDS; ++i)
{
RawMesh.WedgeTexCoords[i].Append(NewWedgeTexCoords[i]);
}
return true;
}
UMaterialInterface* UGLTFMeshBuilder::ToUMaterial(tinygltf::Material* Material)
{
return UMaterial::GetDefaultMaterial(MD_Surface);
}
FString UGLTFMeshBuilder::GetError()
{
return Error;
}
FString UGLTFMeshBuilder::ToFString(std::string InString)
{
return FString(InString.c_str());
}
std::string UGLTFMeshBuilder::ToStdString(FString InString)
{
auto CharArray = InString.GetCharArray();
std::wstring WideString(&CharArray[0]);
std::wstring_convert< std::codecvt_utf8<wchar_t> > Convert;
return Convert.to_bytes(WideString);
}
template <typename T>
bool UGLTFMeshBuilder::GetBufferData(TArray<T> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_SCALAR)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type, T>(OutArray, Start, Accessor->count, Stride); break;
default: BufferCopy<T, T>(OutArray, Start, Accessor->count, Stride); break;
}
return true;
}
// This specialization is almost the same, but checks for the VEC2 GLTF type and uses the overloaded BufferCopy function for FVector2D
template <>
bool UGLTFMeshBuilder::GetBufferData(TArray<FVector2D> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC2)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
// This specialization is almost the same, but checks for the VEC3 GLTF type and uses the overloaded BufferCopy function for FVector
template <>
bool UGLTFMeshBuilder::GetBufferData(TArray<FVector> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC3)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
// This specialization is almost the same, but checks for the VEC4 GLTF type and uses the overloaded BufferCopy function for FVector4
template <>
bool UGLTFMeshBuilder::GetBufferData(TArray<FVector4> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC4)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
// This specialization is almost the same, but checks for a VEC3 or VEC4 GLTF type and uses the overloaded BufferCopy function for FColor
template <>
bool UGLTFMeshBuilder::GetBufferData(TArray<FColor> &OutArray, tinygltf::Accessor* Accessor, bool Append)
{
if (Accessor->type != TINYGLTF_TYPE_VEC3 && Accessor->type != TINYGLTF_TYPE_VEC4)
{
return false;
}
if (!Accessor)
{
return false;
}
tinygltf::BufferView* BufferView = &Scene->bufferViews[Accessor->bufferView];
if (!BufferView)
{
return false;
}
tinygltf::Buffer* Buffer = &Scene->buffers[BufferView->buffer];
if (!Buffer)
{
return false;
}
if (!Append)
{
OutArray.Empty();
}
size_t Stride;
if (Accessor->byteStride != 0)
{
Stride = Accessor->byteStride;
}
else
{
Stride = TypeSize(Accessor->componentType);
}
unsigned char* Start = &Buffer->data[Accessor->byteOffset + BufferView->byteOffset];
switch (Accessor->componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_INT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_FLOAT: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
case TINYGLTF_COMPONENT_TYPE_DOUBLE: BufferCopy<GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE> ::Type>(OutArray, Accessor->type, Start, Accessor->count, Stride); break;
default: return false;
}
return true;
}
bool UGLTFMeshBuilder::HasAttribute(tinygltf::Mesh* Mesh, std::string AttribName) const
{
for (auto Prim : Mesh->primitives)
{
for (auto Entry : Prim.attributes)
{
if (Entry.first == AttribName)
{
return true;
}
}
}
return false;
}
template <typename T> int32 UGLTFMeshBuilder::FindInStdVector(const std::vector<T> &InVector, const T &InElement) const
{
for (int32 i = 0; i < InVector.size(); ++i)
{
if (InVector[i] == InElement)
{
return i;
}
}
return -1;
}
FMatrix UGLTFMeshBuilder::GetNodeTransform(tinygltf::Node* Node)
{
if (Node->matrix.size() == 16)
{
FMatrix Ret;
for (int32 i = 0; i < 4; ++i)
{
for (int32 j = 0; j < 4; ++j)
{
// Reverse order since glTF is column major and FMatrix is row major
Ret.M[j][i] = Node->matrix[(4 * i) + j];
}
}
return Ret;
}
else if (Node->rotation.size() == 4 && Node->scale.size() == 3 && Node->translation.size() == 3)
{
FQuat Rotation((float)Node->rotation[0], (float)Node->rotation[1], (float)Node->rotation[2], (float)Node->rotation[3]);
FVector Scale((float)Node->scale[0], (float)Node->scale[1], (float)Node->scale[2]);
FVector Translation((float)Node->translation[0], (float)Node->translation[1], (float)Node->translation[2]);
return FTransform(Rotation, Translation, Scale).ToMatrixWithScale();
}
else
{
return FMatrix::Identity;
}
}
size_t UGLTFMeshBuilder::TypeSize(int Type) const
{
switch (Type)
{
case TINYGLTF_COMPONENT_TYPE_BYTE:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_BYTE>::Type);
case TINYGLTF_COMPONENT_TYPE_SHORT:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_SHORT>::Type);
case TINYGLTF_COMPONENT_TYPE_INT:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_INT>::Type);
case TINYGLTF_COMPONENT_TYPE_FLOAT:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_FLOAT>::Type);
case TINYGLTF_COMPONENT_TYPE_DOUBLE:
return sizeof(GLTFType<TINYGLTF_COMPONENT_TYPE_DOUBLE>::Type);
default:
return -1;
}
}
int32 UGLTFMeshBuilder::GetNumWedges(tinygltf::Primitive* Prim) const
{
switch (Prim->mode)
{
case TINYGLTF_MODE_TRIANGLES:
return Prim->indices.size();
case TINYGLTF_MODE_TRIANGLE_STRIP:
case TINYGLTF_MODE_TRIANGLE_FAN:
return (Prim->indices.size() - 2) * 3;
default:
return 0;
}
}
void UGLTFMeshBuilder::GetMaterialIndices(TArray<int32>& OutArray, tinygltf::Mesh& Mesh)
{
for (auto Prim : Mesh.primitives)
{
int32 Index = MeshMaterials.Find(ToFString(Prim.material));
for (int i = 0; i < GetNumWedges(&Prim) / 3; ++i)
{
OutArray.Add(Index);
}
}
}
template <typename SrcType, typename DstType> void UGLTFMeshBuilder::BufferCopy(TArray<DstType>& OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add((DstType)BufferValue<SrcType>(Data));
Data += Stride;
}
}
template <typename SrcType> void UGLTFMeshBuilder::BufferCopy(TArray<FVector2D> &OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FVector2D(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType))));
Data += Stride;
}
}
template <typename SrcType> void UGLTFMeshBuilder::BufferCopy(TArray<FVector> &OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FVector(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType))));
Data += Stride;
}
}
template <typename SrcType> void UGLTFMeshBuilder::BufferCopy(TArray<FVector4> &OutArray, unsigned char* Data, int32 Count, size_t Stride)
{
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FVector4(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType)), BufferValue<SrcType>(Data + 3 * sizeof(SrcType))));
Data += Stride;
}
}
template <typename SrcType> void UGLTFMeshBuilder::BufferCopy(TArray<FColor> &OutArray, int InType, unsigned char* Data, int32 Count, size_t Stride)
{
switch (InType)
{
case TINYGLTF_TYPE_VEC3:
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FColor(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType))));
Data += Stride;
}
break;
case TINYGLTF_TYPE_VEC4:
for (int32 i = 0; i < Count; ++i)
{
// At this point, assume we can cast directly to the destination type
OutArray.Add(FColor(BufferValue<SrcType>(Data), BufferValue<SrcType>(Data + sizeof(SrcType)), BufferValue<SrcType>(Data + 2 * sizeof(SrcType)), BufferValue<SrcType>(Data + 3 * sizeof(SrcType))));
Data += Stride;
}
break;
default: return;
}
}
void UGLTFMeshBuilder::AddTokenizedErrorMessage(TSharedRef<FTokenizedMessage> Error, FName ErrorName)
{
UE_LOG(LogTemp, Warning, TEXT("%s"), *(Error->ToText().ToString()));
}
\ No newline at end of file
/// @file GLTFMeshBuilder.h by Robert Poncelet
#pragma once
#include "UnrealString.h"
#include "TokenizedMessage.h"
#include "GLTFImportOptions.h"
#include <string>
#include <vector>
class UStaticMesh;
class UMaterialInterface;
struct FRawMesh;
/// Forward-declared TinyGLTF types since its header can only be #included in one source file.
/// This also means that we must use pointers to these types outside of GLTFMeshBuilder.cpp.
namespace tinygltf
{
class TinyGLTFLoader;
class Scene;
class Node;
struct ACCESSOR;
typedef struct ACCESSOR Accessor;
struct PRIMITIVE;
typedef struct PRIMITIVE Primitive;
struct MESH;
typedef struct MESH Mesh;
struct MATERIAL;
typedef struct MATERIAL Material;
}
/// Works in conjunction with TinyGLTF and Unreal's Static Mesh build system to return a UStaticMesh to the factory. This class is adapted from FbxImporter.
class GLTFMeshBuilder
{
public:
GLTFMeshBuilder(FString FilePath);
~GLTFMeshBuilder();
/// Returns whether we have a valid glTF scene loaded up. For a new MeshBuilder, this should always be queried before calling other functions.
bool LoadedSuccessfully() { return LoadSuccess; }
/// Returns the number of meshes owned by a given node.
int32 GetMeshCount(FString NodeName);
/// Returns the name of the scene's root node.
FString GetRootNode();
/// Obtains the mesh names of a node (and optionally its children); useful as an argument to <B>ImportStaticMeshAsSingle()</B>.
TArray<FString> GetMeshNames(FString NodeName, bool GetChildren = true);
/// Organises materials and builds the StaticMesh using a RawMesh filled with data using <B>BuildStaticMeshFromGeometry()</B>.
/// This function mirrors that in FFbxImporter of the same name.
/// @param InParent A pointer provided by the system importing the file (i.e. probably AssetImportModule) so we know where the saved package goes.
/// @param MeshNameArray An array of strings used as keys to obtain the actual meshes from the glTF scene.
/// @param InName The name of the package to be saved.
/// @param Flags Metadata used for the creation of the new package.
/// @param InStaticMesh A pointer to the StaticMesh to be built and have this new geometry added to it.
UStaticMeshComponent* ImportStaticMeshAsSingle(UObject* InParent, TArray<FString>& MeshNameArray, const FName InName, EObjectFlags Flags, UStaticMeshComponent* InStaticMesh);
/// Obtains the geometry data from the file and adds it to the RawMesh ready to be built for the StaticMesh.
/// This function mirrors that in FFbxImporter of the same name.
/// @param Mesh The glTF mesh to grab the data from.
/// @param StaticMesh The asset the mesh will be built for. This will eventually be the object serialised and saved in the import process.
/// @param MeshMaterials An array of materials to convert to those used by the engine and send to the build process.
/// @param LODIndex Level of detail for this mesh - currently unused i.e. always 0.
/// @param RawMesh The intermediate container for the data between the external format (glTF in our case) and the built StaticMesh.
bool BuildStaticMeshFromGeometry(tinygltf::Mesh* Mesh, UStaticMeshComponent* StaticMesh, int LODIndex, FRawMesh& RawMesh);
/// Material/texture system does nothing currently.
UMaterialInterface* ToUMaterial(tinygltf::Material* Material);
void CreateUnrealMaterial(tinygltf::Material* Material, TArray<UMaterialInterface*>& OutMaterials) { return; };
int32 CreateNodeMaterials(tinygltf::Node* Node, TArray<UMaterialInterface*>& OutMaterials) { return 0; };
void ImportTexturesFromNode(tinygltf::Node* Node) { return; }
/// Logs an error message.
void AddTokenizedErrorMessage(TSharedRef<FTokenizedMessage> Error, FName ErrorName);
/// Returns the error message left by TinyGLTFLoader, if any.
FString GetError();
private:
// Templated data copy functions, from highest to lowest level:
/// @name Level 4: ConvertAttrib
///@{
/// Fills a TArray with a particular vertex attribute. Set InAttribName to "__WedgeIndex" to use the "indices" accessor for each primitive, or "__MaterialIndices" to obtain the material index.
/// @param OutArray The array to fill with data from the imported file.
/// @param Mesh The glTF from which to convert the specified attribute.
/// @param AttribName The name of the attribute to convert.
/// @param UseWedgeIndices Whether to copy data for each triangle corner ("wedge") or each vertex.
/// @param AutoSetArraySize Whether to resize the array to the number of elements in this attribute (usually false since we may be adding to data from another mesh).
template <typename T> bool ConvertAttrib(TArray<T> &OutArray, tinygltf::Mesh* Mesh, std::string AttribName, bool UseWedgeIndices = true, bool AutoSetArraySize = false);
///@}
/// @name Level 3: GetBufferData
///@{
/// Fills a TArray with typed data; works at the glTF Accessor level and figures out which arguments to send to <B>BufferCopy()</B>.
/// @param OutArray The array to fill with data from the imported file.
/// @param Accessor A pointer to a glTF Accessor containing the type data for the geometry attribute.
/// @param Append Whether to add to the array or overwrite the elements currently in it.
template <typename T> bool GetBufferData (TArray<T> &OutArray, tinygltf::Accessor* Accessor, bool Append = true);
template <> bool GetBufferData<FVector2D> (TArray<FVector2D> &OutArray, tinygltf::Accessor* Accessor, bool Append );
template <> bool GetBufferData<FVector> (TArray<FVector> &OutArray, tinygltf::Accessor* Accessor, bool Append );
template <> bool GetBufferData<FVector4> (TArray<FVector4> &OutArray, tinygltf::Accessor* Accessor, bool Append );
///@}
/// @name Level 2: BufferCopy
///@{
/// Handles filling the TArray at the data type level.
/// @param OutArray The array to fill with data from the imported file.
/// @param Data A pointer to the raw data to use as the argument to <B>BufferValue()</B>.
/// @param Count The number of elements to add to the array i.e. the number of calls to <B>BufferValue()</B>.
/// @param Stride The number of bytes between the first byte of each element - usually the size of one element.
template <typename SrcType, typename DstType> void BufferCopy(TArray<DstType> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FVector2D> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FVector> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FVector4> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FColor> &OutArray, int Type, unsigned char* Data, int32 Count, size_t Stride);
///@}
/// @name Level 1: BufferValue
///@{
/// Obtains a single value from the geometry data buffer, accounting for endianness.
/// Adapted from http://stackoverflow.com/questions/13001183/how-to-read-little-endian-integers-from-file-in-c
/// @param Data A pointer to the raw data to cast to the desired type.
/// @return The typed data value.
template <typename T> T BufferValue(void* Data);
///@}
/// Separate function to obtain material indices since it is not stored as a buffer. Should be called after MeshMaterials has been filled in.
void GetMaterialIndices(TArray<int32>& OutArray, tinygltf::Mesh& Mesh);
// Miscellaneous helper functions
/// Reverses the order of every group of 3 elements.
template<typename T> void ReverseTriDirection(TArray<T>& OutArray);
/// Whether a mesh's geometry has a specified attribute.
bool HasAttribute(tinygltf::Mesh* Mesh, std::string AttribName) const;
/// Similar to TArray's Find() function; returns the array index if the specified object was found, -1 otherwise.
template <typename T> int32 FindInStdVector(const std::vector<T> &InVector, const T &InElement) const;
/// Returns the transform of a node relative to its parent.
FMatrix GetNodeTransform(tinygltf::Node* Node);
/// Returns the size of the C++ data type given the corresponding glTF type.
size_t TypeSize(int Type) const;
/// Returns the number of triangle corners given a glTF primitive, taking into account its draw mode.
int32 GetNumWedges(tinygltf::Primitive* Prim) const;
/// Returns the owning node of a given mesh.
tinygltf::Node* GetMeshParentNode(tinygltf::Mesh* InMesh);
/// @name String Conversion
///@{
/// Helper functions for converting between Unreal's and STL's strings.
static FString ToFString(std::string InString);
static std::string ToStdString(FString InString);
///@}
///
TWeakObjectPtr<UObject> Parent;
tinygltf::TinyGLTFLoader* Loader;
tinygltf::Scene* Scene;
TArray<FString> MeshMaterials;
bool LoadSuccess;
FString Error;
};
/// @file GLTFMeshBuilder.h by Robert Poncelet
#pragma once
#include "UnrealString.h"
#include "TokenizedMessage.h"
#include "GLTFImportOptions.h"
#include <string>
#include <vector>
#include "GLTFMeshBuilder.generated.h"
class UStaticMesh;
class UMaterialInterface;
struct FRawMesh;
/// Forward-declared TinyGLTF types since its header can only be #included in one source file.
/// This also means that we must use pointers to these types outside of GLTFMeshBuilder.cpp.
namespace tinygltf
{
class TinyGLTFLoader;
class Scene;
class Node;
struct ACCESSOR;
typedef struct ACCESSOR Accessor;
struct PRIMITIVE;
typedef struct PRIMITIVE Primitive;
struct MESH;
typedef struct MESH Mesh;
struct MATERIAL;
typedef struct MATERIAL Material;
}
/// Works in conjunction with TinyGLTF and Unreal's Static Mesh build system to return a UStaticMesh to the factory. This class is adapted from FbxImporter.
UCLASS()
class GLTFLOADER_API UGLTFMeshBuilder : public UObject
{
GENERATED_BODY()
public:
UGLTFMeshBuilder();
UGLTFMeshBuilder(FString FilePath);
~UGLTFMeshBuilder();
/// Returns whether we have a valid glTF scene loaded up. For a new MeshBuilder, this should always be queried before calling other functions.
bool LoadedSuccessfully() { return LoadSuccess; }
/// Returns the number of meshes owned by a given node.
int32 GetMeshCount(FString NodeName);
/// Returns the name of the scene's root node.
FString GetRootNode();
/// Obtains the mesh names of a node (and optionally its children); useful as an argument to <B>ImportStaticMeshAsSingle()</B>.
TArray<FString> GetMeshNames(FString NodeName, bool GetChildren = true);
/// Organises materials and builds the StaticMesh using a RawMesh filled with data using <B>BuildStaticMeshFromGeometry()</B>.
/// This function mirrors that in FFbxImporter of the same name.
/// @param InParent A pointer provided by the system importing the file (i.e. probably AssetImportModule) so we know where the saved package goes.
/// @param MeshNameArray An array of strings used as keys to obtain the actual meshes from the glTF scene.
/// @param InName The name of the package to be saved.
/// @param Flags Metadata used for the creation of the new package.
/// @param InStaticMesh A pointer to the StaticMesh to be built and have this new geometry added to it.
UStaticMeshComponent* ImportStaticMeshAsSingle(UObject* InParent, TArray<FString>& MeshNameArray, const FName InName, EObjectFlags Flags, UStaticMeshComponent* InStaticMesh);
/// Obtains the geometry data from the file and adds it to the RawMesh ready to be built for the StaticMesh.
/// This function mirrors that in FFbxImporter of the same name.
/// @param Mesh The glTF mesh to grab the data from.
/// @param StaticMesh The asset the mesh will be built for. This will eventually be the object serialised and saved in the import process.
/// @param MeshMaterials An array of materials to convert to those used by the engine and send to the build process.
/// @param LODIndex Level of detail for this mesh - currently unused i.e. always 0.
/// @param RawMesh The intermediate container for the data between the external format (glTF in our case) and the built StaticMesh.
bool BuildStaticMeshFromGeometry(tinygltf::Mesh* Mesh, UStaticMeshComponent* StaticMesh, int LODIndex, FRawMesh& RawMesh);
/// Material/texture system does nothing currently.
UMaterialInterface* ToUMaterial(tinygltf::Material* Material);
void CreateUnrealMaterial(tinygltf::Material* Material, TArray<UMaterialInterface*>& OutMaterials) { return; };
int32 CreateNodeMaterials(tinygltf::Node* Node, TArray<UMaterialInterface*>& OutMaterials) { return 0; };
void ImportTexturesFromNode(tinygltf::Node* Node) { return; }
/// Logs an error message.
void AddTokenizedErrorMessage(TSharedRef<FTokenizedMessage> Error, FName ErrorName);
/// Returns the error message left by TinyGLTFLoader, if any.
FString GetError();
private:
// Templated data copy functions, from highest to lowest level:
/// @name Level 4: ConvertAttrib
///@{
/// Fills a TArray with a particular vertex attribute. Set InAttribName to "__WedgeIndex" to use the "indices" accessor for each primitive, or "__MaterialIndices" to obtain the material index.
/// @param OutArray The array to fill with data from the imported file.
/// @param Mesh The glTF from which to convert the specified attribute.
/// @param AttribName The name of the attribute to convert.
/// @param UseWedgeIndices Whether to copy data for each triangle corner ("wedge") or each vertex.
/// @param AutoSetArraySize Whether to resize the array to the number of elements in this attribute (usually false since we may be adding to data from another mesh).
template <typename T> bool ConvertAttrib(TArray<T> &OutArray, tinygltf::Mesh* Mesh, std::string AttribName, bool UseWedgeIndices = true, bool AutoSetArraySize = false);
///@}
/// @name Level 3: GetBufferData
///@{
/// Fills a TArray with typed data; works at the glTF Accessor level and figures out which arguments to send to <B>BufferCopy()</B>.
/// @param OutArray The array to fill with data from the imported file.
/// @param Accessor A pointer to a glTF Accessor containing the type data for the geometry attribute.
/// @param Append Whether to add to the array or overwrite the elements currently in it.
template <typename T> bool GetBufferData (TArray<T> &OutArray, tinygltf::Accessor* Accessor, bool Append = true);
template <> bool GetBufferData<FVector2D> (TArray<FVector2D> &OutArray, tinygltf::Accessor* Accessor, bool Append );
template <> bool GetBufferData<FVector> (TArray<FVector> &OutArray, tinygltf::Accessor* Accessor, bool Append );
template <> bool GetBufferData<FVector4> (TArray<FVector4> &OutArray, tinygltf::Accessor* Accessor, bool Append );
///@}
/// @name Level 2: BufferCopy
///@{
/// Handles filling the TArray at the data type level.
/// @param OutArray The array to fill with data from the imported file.
/// @param Data A pointer to the raw data to use as the argument to <B>BufferValue()</B>.
/// @param Count The number of elements to add to the array i.e. the number of calls to <B>BufferValue()</B>.
/// @param Stride The number of bytes between the first byte of each element - usually the size of one element.
template <typename SrcType, typename DstType> void BufferCopy(TArray<DstType> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FVector2D> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FVector> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FVector4> &OutArray, unsigned char* Data, int32 Count, size_t Stride);
template <typename SrcType> void BufferCopy(TArray<FColor> &OutArray, int Type, unsigned char* Data, int32 Count, size_t Stride);
///@}
/// @name Level 1: BufferValue
///@{
/// Obtains a single value from the geometry data buffer, accounting for endianness.
/// Adapted from http://stackoverflow.com/questions/13001183/how-to-read-little-endian-integers-from-file-in-c
/// @param Data A pointer to the raw data to cast to the desired type.
/// @return The typed data value.
template <typename T> T BufferValue(void* Data);
///@}
/// Separate function to obtain material indices since it is not stored as a buffer. Should be called after MeshMaterials has been filled in.
void GetMaterialIndices(TArray<int32>& OutArray, tinygltf::Mesh& Mesh);
// Miscellaneous helper functions
/// Reverses the order of every group of 3 elements.
template<typename T> void ReverseTriDirection(TArray<T>& OutArray);
/// Whether a mesh's geometry has a specified attribute.
bool HasAttribute(tinygltf::Mesh* Mesh, std::string AttribName) const;
/// Similar to TArray's Find() function; returns the array index if the specified object was found, -1 otherwise.
template <typename T> int32 FindInStdVector(const std::vector<T> &InVector, const T &InElement) const;
/// Returns the transform of a node relative to its parent.
FMatrix GetNodeTransform(tinygltf::Node* Node);
/// Returns the size of the C++ data type given the corresponding glTF type.
size_t TypeSize(int Type) const;
/// Returns the number of triangle corners given a glTF primitive, taking into account its draw mode.
int32 GetNumWedges(tinygltf::Primitive* Prim) const;
/// Returns the owning node of a given mesh.
tinygltf::Node* GetMeshParentNode(tinygltf::Mesh* InMesh);
/// @name String Conversion
///@{
/// Helper functions for converting between Unreal's and STL's strings.
static FString ToFString(std::string InString);
static std::string ToStdString(FString InString);
///@}
///
TWeakObjectPtr<UObject> Parent;
tinygltf::TinyGLTFLoader* Loader;
tinygltf::Scene* Scene;
TArray<FString> MeshMaterials;
bool LoadSuccess;
FString Error;
};
/*
* Copyright 2009-2010 Cybozu Labs, Inc.
* Copyright 2011-2014 Kazuho Oku
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef picojson_h
#define picojson_h
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
// for isnan/isinf
#if __cplusplus>=201103L
# include <cmath>
#else
extern "C" {
# ifdef _MSC_VER
# include <float.h>
# elif defined(__INTEL_COMPILER)
# include <mathimf.h>
# else
# include <math.h>
# endif
}
#endif
#ifndef PICOJSON_USE_RVALUE_REFERENCE
# if (defined(__cpp_rvalue_references) && __cpp_rvalue_references >= 200610) || (defined(_MSC_VER) && _MSC_VER >= 1600)
# define PICOJSON_USE_RVALUE_REFERENCE 1
# else
# define PICOJSON_USE_RVALUE_REFERENCE 0
# endif
#endif//PICOJSON_USE_RVALUE_REFERENCE
// experimental support for int64_t (see README.mkdn for detail)
#ifdef PICOJSON_USE_INT64
# define __STDC_FORMAT_MACROS
# include <errno.h>
# include <inttypes.h>
#endif
// to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0
#ifndef PICOJSON_USE_LOCALE
# define PICOJSON_USE_LOCALE 1
#endif
#if PICOJSON_USE_LOCALE
extern "C" {
# include <locale.h>
}
#endif
#ifndef PICOJSON_ASSERT
# define PICOJSON_ASSERT(e) do { if (! (e)) throw std::runtime_error(#e); } while (0)
#endif
#ifdef _MSC_VER
#define SNPRINTF _snprintf_s
#pragma warning(push)
#pragma warning(disable : 4244) // conversion from int to char
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4702) // unreachable code
#else
#define SNPRINTF snprintf
#endif
namespace picojson {
enum {
null_type,
boolean_type,
number_type,
string_type,
array_type,
object_type
#ifdef PICOJSON_USE_INT64
, int64_type
#endif
};
enum {
INDENT_WIDTH = 2
};
struct null {};
class value {
public:
typedef std::vector<value> array;
typedef std::map<std::string, value> object;
union _storage {
bool boolean_;
double number_;
#ifdef PICOJSON_USE_INT64
int64_t int64_;
#endif
std::string* string_;
array* array_;
object* object_;
};
protected:
int type_;
_storage u_;
public:
value();
value(int type, bool);
explicit value(bool b);
#ifdef PICOJSON_USE_INT64
explicit value(int64_t i);
#endif
explicit value(double n);
explicit value(const std::string& s);
explicit value(const array& a);
explicit value(const object& o);
explicit value(const char* s);
value(const char* s, size_t len);
~value();
value(const value& x);
value& operator=(const value& x);
#if PICOJSON_USE_RVALUE_REFERENCE
value(value&& x)throw();
value& operator=(value&& x)throw();
#endif
void swap(value& x)throw();
template <typename T> bool is() const;
template <typename T> const T& get() const;
template <typename T> T& get();
bool evaluate_as_boolean() const;
const value& get(size_t idx) const;
const value& get(const std::string& key) const;
value& get(size_t idx);
value& get(const std::string& key);
bool contains(size_t idx) const;
bool contains(const std::string& key) const;
std::string to_str() const;
template <typename Iter> void serialize(Iter os, bool prettify = false) const;
std::string serialize(bool prettify = false) const;
private:
template <typename T> value(const T*); // intentionally defined to block implicit conversion of pointer to bool
template <typename Iter> static void _indent(Iter os, int indent);
template <typename Iter> void _serialize(Iter os, int indent) const;
std::string _serialize(int indent) const;
};
typedef value::array array;
typedef value::object object;
inline value::value() : type_(null_type) {}
inline value::value(int type, bool) : type_(type) {
switch (type) {
#define INIT(p, v) case p##type: u_.p = v; break
INIT(boolean_, false);
INIT(number_, 0.0);
#ifdef PICOJSON_USE_INT64
INIT(int64_, 0);
#endif
INIT(string_, new std::string());
INIT(array_, new array());
INIT(object_, new object());
#undef INIT
default: break;
}
}
inline value::value(bool b) : type_(boolean_type) {
u_.boolean_ = b;
}
#ifdef PICOJSON_USE_INT64
inline value::value(int64_t i) : type_(int64_type) {
u_.int64_ = i;
}
#endif
inline value::value(double n) : type_(number_type) {
if (
#ifdef _MSC_VER
! _finite(n)
#elif __cplusplus>=201103L || !(defined(isnan) && defined(isinf))
std::isnan(n) || std::isinf(n)
#else
isnan(n) || isinf(n)
#endif
) {
throw std::overflow_error("");
}
u_.number_ = n;
}
inline value::value(const std::string& s) : type_(string_type) {
u_.string_ = new std::string(s);
}
inline value::value(const array& a) : type_(array_type) {
u_.array_ = new array(a);
}
inline value::value(const object& o) : type_(object_type) {
u_.object_ = new object(o);
}
inline value::value(const char* s) : type_(string_type) {
u_.string_ = new std::string(s);
}
inline value::value(const char* s, size_t len) : type_(string_type) {
u_.string_ = new std::string(s, len);
}
inline value::~value() {
switch (type_) {
#define DEINIT(p) case p##type: delete u_.p; break
DEINIT(string_);
DEINIT(array_);
DEINIT(object_);
#undef DEINIT
default: break;
}
}
inline value::value(const value& x) : type_(x.type_) {
switch (type_) {
#define INIT(p, v) case p##type: u_.p = v; break
INIT(string_, new std::string(*x.u_.string_));
INIT(array_, new array(*x.u_.array_));
INIT(object_, new object(*x.u_.object_));
#undef INIT
default:
u_ = x.u_;
break;
}
}
inline value& value::operator=(const value& x) {
if (this != &x) {
value t(x);
swap(t);
}
return *this;
}
#if PICOJSON_USE_RVALUE_REFERENCE
inline value::value(value&& x)throw() : type_(null_type) {
swap(x);
}
inline value& value::operator=(value&& x)throw() {
swap(x);
return *this;
}
#endif
inline void value::swap(value& x)throw() {
std::swap(type_, x.type_);
std::swap(u_, x.u_);
}
#define IS(ctype, jtype) \
template <> inline bool value::is<ctype>() const { \
return type_ == jtype##_type; \
}
IS(null, null)
IS(bool, boolean)
#ifdef PICOJSON_USE_INT64
IS(int64_t, int64)
#endif
IS(std::string, string)
IS(array, array)
IS(object, object)
#undef IS
template <> inline bool value::is<double>() const {
return type_ == number_type
#ifdef PICOJSON_USE_INT64
|| type_ == int64_type
#endif
;
}
#define GET(ctype, var) \
template <> inline const ctype& value::get<ctype>() const { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" \
&& is<ctype>()); \
return var; \
} \
template <> inline ctype& value::get<ctype>() { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" \
&& is<ctype>()); \
return var; \
}
GET(bool, u_.boolean_)
GET(std::string, *u_.string_)
GET(array, *u_.array_)
GET(object, *u_.object_)
#ifdef PICOJSON_USE_INT64
GET(double, (type_ == int64_type && (const_cast<value*>(this)->type_ = number_type, const_cast<value*>(this)->u_.number_ = u_.int64_), u_.number_))
GET(int64_t, u_.int64_)
#else
GET(double, u_.number_)
#endif
#undef GET
inline bool value::evaluate_as_boolean() const {
switch (type_) {
case null_type:
return false;
case boolean_type:
return u_.boolean_;
case number_type:
return u_.number_ != 0;
#ifdef PICOJSON_USE_INT64
case int64_type:
return u_.int64_ != 0;
#endif
case string_type:
return ! u_.string_->empty();
default:
return true;
}
}
inline const value& value::get(size_t idx) const {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline value& value::get(size_t idx) {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline const value& value::get(const std::string& key) const {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline value& value::get(const std::string& key) {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline bool value::contains(size_t idx) const {
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size();
}
inline bool value::contains(const std::string& key) const {
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end();
}
inline std::string value::to_str() const {
switch (type_) {
case null_type: return "null";
case boolean_type: return u_.boolean_ ? "true" : "false";
#ifdef PICOJSON_USE_INT64
case int64_type: {
char buf[sizeof("-9223372036854775808")];
SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_);
return buf;
}
#endif
case number_type: {
char buf[256];
double tmp;
SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_);
#if PICOJSON_USE_LOCALE
char *decimal_point = localeconv()->decimal_point;
if (strcmp(decimal_point, ".") != 0) {
size_t decimal_point_len = strlen(decimal_point);
for (char *p = buf; *p != '\0'; ++p) {
if (strncmp(p, decimal_point, decimal_point_len) == 0) {
return std::string(buf, p) + "." + (p + decimal_point_len);
}
}
}
#endif
return buf;
}
case string_type: return *u_.string_;
case array_type: return "array";
case object_type: return "object";
default: PICOJSON_ASSERT(0);
#ifdef _MSC_VER
__assume(0);
#endif
}
return std::string();
}
template <typename Iter> void copy(const std::string& s, Iter oi) {
std::copy(s.begin(), s.end(), oi);
}
template <typename Iter> void serialize_str(const std::string& s, Iter oi) {
*oi++ = '"';
for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
switch (*i) {
#define MAP(val, sym) case val: copy(sym, oi); break
MAP('"', "\\\"");
MAP('\\', "\\\\");
MAP('/', "\\/");
MAP('\b', "\\b");
MAP('\f', "\\f");
MAP('\n', "\\n");
MAP('\r', "\\r");
MAP('\t', "\\t");
#undef MAP
default:
if (static_cast<unsigned char>(*i) < 0x20 || *i == 0x7f) {
char buf[7];
SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff);
copy(buf, buf + 6, oi);
} else {
*oi++ = *i;
}
break;
}
}
*oi++ = '"';
}
template <typename Iter> void value::serialize(Iter oi, bool prettify) const {
return _serialize(oi, prettify ? 0 : -1);
}
inline std::string value::serialize(bool prettify) const {
return _serialize(prettify ? 0 : -1);
}
template <typename Iter> void value::_indent(Iter oi, int indent) {
*oi++ = '\n';
for (int i = 0; i < indent * INDENT_WIDTH; ++i) {
*oi++ = ' ';
}
}
template <typename Iter> void value::_serialize(Iter oi, int indent) const {
switch (type_) {
case string_type:
serialize_str(*u_.string_, oi);
break;
case array_type: {
*oi++ = '[';
if (indent != -1) {
++indent;
}
for (array::const_iterator i = u_.array_->begin();
i != u_.array_->end();
++i) {
if (i != u_.array_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
i->_serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (! u_.array_->empty()) {
_indent(oi, indent);
}
}
*oi++ = ']';
break;
}
case object_type: {
*oi++ = '{';
if (indent != -1) {
++indent;
}
for (object::const_iterator i = u_.object_->begin();
i != u_.object_->end();
++i) {
if (i != u_.object_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
serialize_str(i->first, oi);
*oi++ = ':';
if (indent != -1) {
*oi++ = ' ';
}
i->second._serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (! u_.object_->empty()) {
_indent(oi, indent);
}
}
*oi++ = '}';
break;
}
default:
copy(to_str(), oi);
break;
}
if (indent == 0) {
*oi++ = '\n';
}
}
inline std::string value::_serialize(int indent) const {
std::string s;
_serialize(std::back_inserter(s), indent);
return s;
}
template <typename Iter> class input {
protected:
Iter cur_, end_;
int last_ch_;
bool ungot_;
int line_;
public:
input(const Iter& first, const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) {}
int getc() {
if (ungot_) {
ungot_ = false;
return last_ch_;
}
if (cur_ == end_) {
last_ch_ = -1;
return -1;
}
if (last_ch_ == '\n') {
line_++;
}
last_ch_ = *cur_ & 0xff;
++cur_;
return last_ch_;
}
void ungetc() {
if (last_ch_ != -1) {
PICOJSON_ASSERT(! ungot_);
ungot_ = true;
}
}
Iter cur() const { return cur_; }
int line() const { return line_; }
void skip_ws() {
while (1) {
int ch = getc();
if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) {
ungetc();
break;
}
}
}
bool expect(int expect) {
skip_ws();
if (getc() != expect) {
ungetc();
return false;
}
return true;
}
bool match(const std::string& pattern) {
for (std::string::const_iterator pi(pattern.begin());
pi != pattern.end();
++pi) {
if (getc() != *pi) {
ungetc();
return false;
}
}
return true;
}
};
template<typename Iter> inline int _parse_quadhex(input<Iter> &in) {
int uni_ch = 0, hex;
for (int i = 0; i < 4; i++) {
if ((hex = in.getc()) == -1) {
return -1;
}
if ('0' <= hex && hex <= '9') {
hex -= '0';
} else if ('A' <= hex && hex <= 'F') {
hex -= 'A' - 0xa;
} else if ('a' <= hex && hex <= 'f') {
hex -= 'a' - 0xa;
} else {
in.ungetc();
return -1;
}
uni_ch = uni_ch * 16 + hex;
}
return uni_ch;
}
template<typename String, typename Iter> inline bool _parse_codepoint(String& out, input<Iter>& in) {
int uni_ch;
if ((uni_ch = _parse_quadhex(in)) == -1) {
return false;
}
if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
if (0xdc00 <= uni_ch) {
// a second 16-bit of a surrogate pair appeared
return false;
}
// first 16-bit of surrogate pair, get the next one
if (in.getc() != '\\' || in.getc() != 'u') {
in.ungetc();
return false;
}
int second = _parse_quadhex(in);
if (! (0xdc00 <= second && second <= 0xdfff)) {
return false;
}
uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
uni_ch += 0x10000;
}
if (uni_ch < 0x80) {
out.push_back(uni_ch);
} else {
if (uni_ch < 0x800) {
out.push_back(0xc0 | (uni_ch >> 6));
} else {
if (uni_ch < 0x10000) {
out.push_back(0xe0 | (uni_ch >> 12));
} else {
out.push_back(0xf0 | (uni_ch >> 18));
out.push_back(0x80 | ((uni_ch >> 12) & 0x3f));
}
out.push_back(0x80 | ((uni_ch >> 6) & 0x3f));
}
out.push_back(0x80 | (uni_ch & 0x3f));
}
return true;
}
template<typename String, typename Iter> inline bool _parse_string(String& out, input<Iter>& in) {
while (1) {
int ch = in.getc();
if (ch < ' ') {
in.ungetc();
return false;
} else if (ch == '"') {
return true;
} else if (ch == '\\') {
if ((ch = in.getc()) == -1) {
return false;
}
switch (ch) {
#define MAP(sym, val) case sym: out.push_back(val); break
MAP('"', '\"');
MAP('\\', '\\');
MAP('/', '/');
MAP('b', '\b');
MAP('f', '\f');
MAP('n', '\n');
MAP('r', '\r');
MAP('t', '\t');
#undef MAP
case 'u':
if (! _parse_codepoint(out, in)) {
return false;
}
break;
default:
return false;
}
} else {
out.push_back(ch);
}
}
return false;
}
template <typename Context, typename Iter> inline bool _parse_array(Context& ctx, input<Iter>& in) {
if (! ctx.parse_array_start()) {
return false;
}
size_t idx = 0;
if (in.expect(']')) {
return ctx.parse_array_stop(idx);
}
do {
if (! ctx.parse_array_item(in, idx)) {
return false;
}
idx++;
} while (in.expect(','));
return in.expect(']') && ctx.parse_array_stop(idx);
}
template <typename Context, typename Iter> inline bool _parse_object(Context& ctx, input<Iter>& in) {
if (! ctx.parse_object_start()) {
return false;
}
if (in.expect('}')) {
return true;
}
do {
std::string key;
if (! in.expect('"')
|| ! _parse_string(key, in)
|| ! in.expect(':')) {
return false;
}
if (! ctx.parse_object_item(in, key)) {
return false;
}
} while (in.expect(','));
return in.expect('}');
}
template <typename Iter> inline std::string _parse_number(input<Iter>& in) {
std::string num_str;
while (1) {
int ch = in.getc();
if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-'
|| ch == 'e' || ch == 'E') {
num_str.push_back(ch);
} else if (ch == '.') {
#if PICOJSON_USE_LOCALE
num_str += localeconv()->decimal_point;
#else
num_str.push_back('.');
#endif
} else {
in.ungetc();
break;
}
}
return num_str;
}
template <typename Context, typename Iter> inline bool _parse(Context& ctx, input<Iter>& in) {
in.skip_ws();
int ch = in.getc();
switch (ch) {
#define IS(ch, text, op) case ch: \
if (in.match(text) && op) { \
return true; \
} else { \
return false; \
}
IS('n', "ull", ctx.set_null());
IS('f', "alse", ctx.set_bool(false));
IS('t', "rue", ctx.set_bool(true));
#undef IS
case '"':
return ctx.parse_string(in);
case '[':
return _parse_array(ctx, in);
case '{':
return _parse_object(ctx, in);
default:
if (('0' <= ch && ch <= '9') || ch == '-') {
double f;
char *endp;
in.ungetc();
std::string num_str = _parse_number(in);
if (num_str.empty()) {
return false;
}
#ifdef PICOJSON_USE_INT64
{
errno = 0;
intmax_t ival = strtoimax(num_str.c_str(), &endp, 10);
if (errno == 0
&& std::numeric_limits<int64_t>::min() <= ival
&& ival <= std::numeric_limits<int64_t>::max()
&& endp == num_str.c_str() + num_str.size()) {
ctx.set_int64(ival);
return true;
}
}
#endif
f = strtod(num_str.c_str(), &endp);
if (endp == num_str.c_str() + num_str.size()) {
ctx.set_number(f);
return true;
}
return false;
}
break;
}
in.ungetc();
return false;
}
class deny_parse_context {
public:
bool set_null() { return false; }
bool set_bool(bool) { return false; }
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t) { return false; }
#endif
bool set_number(double) { return false; }
template <typename Iter> bool parse_string(input<Iter>&) { return false; }
bool parse_array_start() { return false; }
template <typename Iter> bool parse_array_item(input<Iter>&, size_t) {
return false;
}
bool parse_array_stop(size_t) { return false; }
bool parse_object_start() { return false; }
template <typename Iter> bool parse_object_item(input<Iter>&, const std::string&) {
return false;
}
};
class default_parse_context {
protected:
value* out_;
public:
default_parse_context(value* out) : out_(out) {}
bool set_null() {
*out_ = value();
return true;
}
bool set_bool(bool b) {
*out_ = value(b);
return true;
}
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t i) {
*out_ = value(i);
return true;
}
#endif
bool set_number(double f) {
*out_ = value(f);
return true;
}
template<typename Iter> bool parse_string(input<Iter>& in) {
*out_ = value(string_type, false);
return _parse_string(out_->get<std::string>(), in);
}
bool parse_array_start() {
*out_ = value(array_type, false);
return true;
}
template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) {
array& a = out_->get<array>();
a.push_back(value());
default_parse_context ctx(&a.back());
return _parse(ctx, in);
}
bool parse_array_stop(size_t) { return true; }
bool parse_object_start() {
*out_ = value(object_type, false);
return true;
}
template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string& key) {
object& o = out_->get<object>();
default_parse_context ctx(&o[key]);
return _parse(ctx, in);
}
private:
default_parse_context(const default_parse_context&);
default_parse_context& operator=(const default_parse_context&);
};
class null_parse_context {
public:
struct dummy_str {
void push_back(int) {}
};
public:
null_parse_context() {}
bool set_null() { return true; }
bool set_bool(bool) { return true; }
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t) { return true; }
#endif
bool set_number(double) { return true; }
template <typename Iter> bool parse_string(input<Iter>& in) {
dummy_str s;
return _parse_string(s, in);
}
bool parse_array_start() { return true; }
template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) {
return _parse(*this, in);
}
bool parse_array_stop(size_t) { return true; }
bool parse_object_start() { return true; }
template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string&) {
return _parse(*this, in);
}
private:
null_parse_context(const null_parse_context&);
null_parse_context& operator=(const null_parse_context&);
};
// obsolete, use the version below
template <typename Iter> inline std::string parse(value& out, Iter& pos, const Iter& last) {
std::string err;
pos = parse(out, pos, last, &err);
return err;
}
template <typename Context, typename Iter> inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) {
input<Iter> in(first, last);
if (! _parse(ctx, in) && err != NULL) {
char buf[64];
SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line());
*err = buf;
while (1) {
int ch = in.getc();
if (ch == -1 || ch == '\n') {
break;
} else if (ch >= ' ') {
err->push_back(ch);
}
}
}
return in.cur();
}
template <typename Iter> inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) {
default_parse_context ctx(&out);
return _parse(ctx, first, last, err);
}
inline std::string parse(value& out, const std::string& s) {
std::string err;
parse(out, s.begin(), s.end(), &err);
return err;
}
inline std::string parse(value& out, std::istream& is) {
std::string err;
parse(out, std::istreambuf_iterator<char>(is.rdbuf()),
std::istreambuf_iterator<char>(), &err);
return err;
}
template <typename T> struct last_error_t {
static std::string s;
};
template <typename T> std::string last_error_t<T>::s;
inline void set_last_error(const std::string& s) {
last_error_t<bool>::s = s;
}
inline const std::string& get_last_error() {
return last_error_t<bool>::s;
}
inline bool operator==(const value& x, const value& y) {
if (x.is<null>())
return y.is<null>();
#define PICOJSON_CMP(type) \
if (x.is<type>()) \
return y.is<type>() && x.get<type>() == y.get<type>()
PICOJSON_CMP(bool);
PICOJSON_CMP(double);
PICOJSON_CMP(std::string);
PICOJSON_CMP(array);
PICOJSON_CMP(object);
#undef PICOJSON_CMP
PICOJSON_ASSERT(0);
#ifdef _MSC_VER
__assume(0);
#endif
return false;
}
inline bool operator!=(const value& x, const value& y) {
return ! (x == y);
}
}
#if !PICOJSON_USE_RVALUE_REFERENCE
namespace std {
template<> inline void swap(picojson::value& x, picojson::value& y)
{
x.swap(y);
}
}
#endif
inline std::istream& operator>>(std::istream& is, picojson::value& x)
{
picojson::set_last_error(std::string());
std::string err = picojson::parse(x, is);
if (! err.empty()) {
picojson::set_last_error(err);
is.setstate(std::ios::failbit);
}
return is;
}
inline std::ostream& operator<<(std::ostream& os, const picojson::value& x)
{
x.serialize(std::ostream_iterator<char>(os));
return os;
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
/*
* Copyright 2009-2010 Cybozu Labs, Inc.
* Copyright 2011-2014 Kazuho Oku
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef picojson_h
#define picojson_h
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
// for isnan/isinf
#if __cplusplus>=201103L
# include <cmath>
#else
extern "C" {
# ifdef _MSC_VER
# include <float.h>
# elif defined(__INTEL_COMPILER)
# include <mathimf.h>
# else
# include <math.h>
# endif
}
#endif
#ifndef PICOJSON_USE_RVALUE_REFERENCE
# if (defined(__cpp_rvalue_references) && __cpp_rvalue_references >= 200610) || (defined(_MSC_VER) && _MSC_VER >= 1600)
# define PICOJSON_USE_RVALUE_REFERENCE 1
# else
# define PICOJSON_USE_RVALUE_REFERENCE 0
# endif
#endif//PICOJSON_USE_RVALUE_REFERENCE
// experimental support for int64_t (see README.mkdn for detail)
#ifdef PICOJSON_USE_INT64
# define __STDC_FORMAT_MACROS
# include <errno.h>
# include <inttypes.h>
#endif
// to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0
#ifndef PICOJSON_USE_LOCALE
# define PICOJSON_USE_LOCALE 1
#endif
#if PICOJSON_USE_LOCALE
extern "C" {
# include <locale.h>
}
#endif
#ifndef PICOJSON_ASSERT
# define PICOJSON_ASSERT(e) do { if (! (e)) throw std::runtime_error(#e); } while (0)
#endif
#ifdef _MSC_VER
#define SNPRINTF _snprintf_s
#pragma warning(push)
#pragma warning(disable : 4244) // conversion from int to char
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4702) // unreachable code
#else
#define SNPRINTF snprintf
#endif
namespace picojson {
enum {
null_type,
boolean_type,
number_type,
string_type,
array_type,
object_type
#ifdef PICOJSON_USE_INT64
, int64_type
#endif
};
enum {
INDENT_WIDTH = 2
};
struct null {};
class value {
public:
typedef std::vector<value> array;
typedef std::map<std::string, value> object;
union _storage {
bool boolean_;
double number_;
#ifdef PICOJSON_USE_INT64
int64_t int64_;
#endif
std::string* string_;
array* array_;
object* object_;
};
protected:
int type_;
_storage u_;
public:
value();
value(int type, bool);
explicit value(bool b);
#ifdef PICOJSON_USE_INT64
explicit value(int64_t i);
#endif
explicit value(double n);
explicit value(const std::string& s);
explicit value(const array& a);
explicit value(const object& o);
explicit value(const char* s);
value(const char* s, size_t len);
~value();
value(const value& x);
value& operator=(const value& x);
#if PICOJSON_USE_RVALUE_REFERENCE
value(value&& x)throw();
value& operator=(value&& x)throw();
#endif
void swap(value& x)throw();
template <typename T> bool is() const;
template <typename T> const T& get() const;
template <typename T> T& get();
bool evaluate_as_boolean() const;
const value& get(size_t idx) const;
const value& get(const std::string& key) const;
value& get(size_t idx);
value& get(const std::string& key);
bool contains(size_t idx) const;
bool contains(const std::string& key) const;
std::string to_str() const;
template <typename Iter> void serialize(Iter os, bool prettify = false) const;
std::string serialize(bool prettify = false) const;
private:
template <typename T> value(const T*); // intentionally defined to block implicit conversion of pointer to bool
template <typename Iter> static void _indent(Iter os, int indent);
template <typename Iter> void _serialize(Iter os, int indent) const;
std::string _serialize(int indent) const;
};
typedef value::array array;
typedef value::object object;
inline value::value() : type_(null_type) {}
inline value::value(int type, bool) : type_(type) {
switch (type) {
#define INIT(p, v) case p##type: u_.p = v; break
INIT(boolean_, false);
INIT(number_, 0.0);
#ifdef PICOJSON_USE_INT64
INIT(int64_, 0);
#endif
INIT(string_, new std::string());
INIT(array_, new array());
INIT(object_, new object());
#undef INIT
default: break;
}
}
inline value::value(bool b) : type_(boolean_type) {
u_.boolean_ = b;
}
#ifdef PICOJSON_USE_INT64
inline value::value(int64_t i) : type_(int64_type) {
u_.int64_ = i;
}
#endif
inline value::value(double n) : type_(number_type) {
if (
#ifdef _MSC_VER
! _finite(n)
#elif __cplusplus>=201103L || !(defined(isnan) && defined(isinf))
std::isnan(n) || std::isinf(n)
#else
isnan(n) || isinf(n)
#endif
) {
throw std::overflow_error("");
}
u_.number_ = n;
}
inline value::value(const std::string& s) : type_(string_type) {
u_.string_ = new std::string(s);
}
inline value::value(const array& a) : type_(array_type) {
u_.array_ = new array(a);
}
inline value::value(const object& o) : type_(object_type) {
u_.object_ = new object(o);
}
inline value::value(const char* s) : type_(string_type) {
u_.string_ = new std::string(s);
}
inline value::value(const char* s, size_t len) : type_(string_type) {
u_.string_ = new std::string(s, len);
}
inline value::~value() {
switch (type_) {
#define DEINIT(p) case p##type: delete u_.p; break
DEINIT(string_);
DEINIT(array_);
DEINIT(object_);
#undef DEINIT
default: break;
}
}
inline value::value(const value& x) : type_(x.type_) {
switch (type_) {
#define INIT(p, v) case p##type: u_.p = v; break
INIT(string_, new std::string(*x.u_.string_));
INIT(array_, new array(*x.u_.array_));
INIT(object_, new object(*x.u_.object_));
#undef INIT
default:
u_ = x.u_;
break;
}
}
inline value& value::operator=(const value& x) {
if (this != &x) {
value t(x);
swap(t);
}
return *this;
}
#if PICOJSON_USE_RVALUE_REFERENCE
inline value::value(value&& x)throw() : type_(null_type) {
swap(x);
}
inline value& value::operator=(value&& x)throw() {
swap(x);
return *this;
}
#endif
inline void value::swap(value& x)throw() {
std::swap(type_, x.type_);
std::swap(u_, x.u_);
}
#define IS(ctype, jtype) \
template <> inline bool value::is<ctype>() const { \
return type_ == jtype##_type; \
}
IS(null, null)
IS(bool, boolean)
#ifdef PICOJSON_USE_INT64
IS(int64_t, int64)
#endif
IS(std::string, string)
IS(array, array)
IS(object, object)
#undef IS
template <> inline bool value::is<double>() const {
return type_ == number_type
#ifdef PICOJSON_USE_INT64
|| type_ == int64_type
#endif
;
}
#define GET(ctype, var) \
template <> inline const ctype& value::get<ctype>() const { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" \
&& is<ctype>()); \
return var; \
} \
template <> inline ctype& value::get<ctype>() { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" \
&& is<ctype>()); \
return var; \
}
GET(bool, u_.boolean_)
GET(std::string, *u_.string_)
GET(array, *u_.array_)
GET(object, *u_.object_)
#ifdef PICOJSON_USE_INT64
GET(double, (type_ == int64_type && (const_cast<value*>(this)->type_ = number_type, const_cast<value*>(this)->u_.number_ = u_.int64_), u_.number_))
GET(int64_t, u_.int64_)
#else
GET(double, u_.number_)
#endif
#undef GET
inline bool value::evaluate_as_boolean() const {
switch (type_) {
case null_type:
return false;
case boolean_type:
return u_.boolean_;
case number_type:
return u_.number_ != 0;
#ifdef PICOJSON_USE_INT64
case int64_type:
return u_.int64_ != 0;
#endif
case string_type:
return ! u_.string_->empty();
default:
return true;
}
}
inline const value& value::get(size_t idx) const {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline value& value::get(size_t idx) {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline const value& value::get(const std::string& key) const {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline value& value::get(const std::string& key) {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline bool value::contains(size_t idx) const {
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size();
}
inline bool value::contains(const std::string& key) const {
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end();
}
inline std::string value::to_str() const {
switch (type_) {
case null_type: return "null";
case boolean_type: return u_.boolean_ ? "true" : "false";
#ifdef PICOJSON_USE_INT64
case int64_type: {
char buf[sizeof("-9223372036854775808")];
SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_);
return buf;
}
#endif
case number_type: {
char buf[256];
double tmp;
SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_);
#if PICOJSON_USE_LOCALE
char *decimal_point = localeconv()->decimal_point;
if (strcmp(decimal_point, ".") != 0) {
size_t decimal_point_len = strlen(decimal_point);
for (char *p = buf; *p != '\0'; ++p) {
if (strncmp(p, decimal_point, decimal_point_len) == 0) {
return std::string(buf, p) + "." + (p + decimal_point_len);
}
}
}
#endif
return buf;
}
case string_type: return *u_.string_;
case array_type: return "array";
case object_type: return "object";
default: PICOJSON_ASSERT(0);
#ifdef _MSC_VER
__assume(0);
#endif
}
return std::string();
}
template <typename Iter> void copy(const std::string& s, Iter oi) {
std::copy(s.begin(), s.end(), oi);
}
template <typename Iter> void serialize_str(const std::string& s, Iter oi) {
*oi++ = '"';
for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {
switch (*i) {
#define MAP(val, sym) case val: copy(sym, oi); break
MAP('"', "\\\"");
MAP('\\', "\\\\");
MAP('/', "\\/");
MAP('\b', "\\b");
MAP('\f', "\\f");
MAP('\n', "\\n");
MAP('\r', "\\r");
MAP('\t', "\\t");
#undef MAP
default:
if (static_cast<unsigned char>(*i) < 0x20 || *i == 0x7f) {
char buf[7];
SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff);
copy(buf, buf + 6, oi);
} else {
*oi++ = *i;
}
break;
}
}
*oi++ = '"';
}
template <typename Iter> void value::serialize(Iter oi, bool prettify) const {
return _serialize(oi, prettify ? 0 : -1);
}
inline std::string value::serialize(bool prettify) const {
return _serialize(prettify ? 0 : -1);
}
template <typename Iter> void value::_indent(Iter oi, int indent) {
*oi++ = '\n';
for (int i = 0; i < indent * INDENT_WIDTH; ++i) {
*oi++ = ' ';
}
}
template <typename Iter> void value::_serialize(Iter oi, int indent) const {
switch (type_) {
case string_type:
serialize_str(*u_.string_, oi);
break;
case array_type: {
*oi++ = '[';
if (indent != -1) {
++indent;
}
for (array::const_iterator i = u_.array_->begin();
i != u_.array_->end();
++i) {
if (i != u_.array_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
i->_serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (! u_.array_->empty()) {
_indent(oi, indent);
}
}
*oi++ = ']';
break;
}
case object_type: {
*oi++ = '{';
if (indent != -1) {
++indent;
}
for (object::const_iterator i = u_.object_->begin();
i != u_.object_->end();
++i) {
if (i != u_.object_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
serialize_str(i->first, oi);
*oi++ = ':';
if (indent != -1) {
*oi++ = ' ';
}
i->second._serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (! u_.object_->empty()) {
_indent(oi, indent);
}
}
*oi++ = '}';
break;
}
default:
copy(to_str(), oi);
break;
}
if (indent == 0) {
*oi++ = '\n';
}
}
inline std::string value::_serialize(int indent) const {
std::string s;
_serialize(std::back_inserter(s), indent);
return s;
}
template <typename Iter> class input {
protected:
Iter cur_, end_;
int last_ch_;
bool ungot_;
int line_;
public:
input(const Iter& first, const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) {}
int getc() {
if (ungot_) {
ungot_ = false;
return last_ch_;
}
if (cur_ == end_) {
last_ch_ = -1;
return -1;
}
if (last_ch_ == '\n') {
line_++;
}
last_ch_ = *cur_ & 0xff;
++cur_;
return last_ch_;
}
void ungetc() {
if (last_ch_ != -1) {
PICOJSON_ASSERT(! ungot_);
ungot_ = true;
}
}
Iter cur() const { return cur_; }
int line() const { return line_; }
void skip_ws() {
while (1) {
int ch = getc();
if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) {
ungetc();
break;
}
}
}
bool expect(int expect) {
skip_ws();
if (getc() != expect) {
ungetc();
return false;
}
return true;
}
bool match(const std::string& pattern) {
for (std::string::const_iterator pi(pattern.begin());
pi != pattern.end();
++pi) {
if (getc() != *pi) {
ungetc();
return false;
}
}
return true;
}
};
template<typename Iter> inline int _parse_quadhex(input<Iter> &in) {
int uni_ch = 0, hex;
for (int i = 0; i < 4; i++) {
if ((hex = in.getc()) == -1) {
return -1;
}
if ('0' <= hex && hex <= '9') {
hex -= '0';
} else if ('A' <= hex && hex <= 'F') {
hex -= 'A' - 0xa;
} else if ('a' <= hex && hex <= 'f') {
hex -= 'a' - 0xa;
} else {
in.ungetc();
return -1;
}
uni_ch = uni_ch * 16 + hex;
}
return uni_ch;
}
template<typename String, typename Iter> inline bool _parse_codepoint(String& out, input<Iter>& in) {
int uni_ch;
if ((uni_ch = _parse_quadhex(in)) == -1) {
return false;
}
if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
if (0xdc00 <= uni_ch) {
// a second 16-bit of a surrogate pair appeared
return false;
}
// first 16-bit of surrogate pair, get the next one
if (in.getc() != '\\' || in.getc() != 'u') {
in.ungetc();
return false;
}
int second = _parse_quadhex(in);
if (! (0xdc00 <= second && second <= 0xdfff)) {
return false;
}
uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
uni_ch += 0x10000;
}
if (uni_ch < 0x80) {
out.push_back(uni_ch);
} else {
if (uni_ch < 0x800) {
out.push_back(0xc0 | (uni_ch >> 6));
} else {
if (uni_ch < 0x10000) {
out.push_back(0xe0 | (uni_ch >> 12));
} else {
out.push_back(0xf0 | (uni_ch >> 18));
out.push_back(0x80 | ((uni_ch >> 12) & 0x3f));
}
out.push_back(0x80 | ((uni_ch >> 6) & 0x3f));
}
out.push_back(0x80 | (uni_ch & 0x3f));
}
return true;
}
template<typename String, typename Iter> inline bool _parse_string(String& out, input<Iter>& in) {
while (1) {
int ch = in.getc();
if (ch < ' ') {
in.ungetc();
return false;
} else if (ch == '"') {
return true;
} else if (ch == '\\') {
if ((ch = in.getc()) == -1) {
return false;
}
switch (ch) {
#define MAP(sym, val) case sym: out.push_back(val); break
MAP('"', '\"');
MAP('\\', '\\');
MAP('/', '/');
MAP('b', '\b');
MAP('f', '\f');
MAP('n', '\n');
MAP('r', '\r');
MAP('t', '\t');
#undef MAP
case 'u':
if (! _parse_codepoint(out, in)) {
return false;
}
break;
default:
return false;
}
} else {
out.push_back(ch);
}
}
return false;
}
template <typename Context, typename Iter> inline bool _parse_array(Context& ctx, input<Iter>& in) {
if (! ctx.parse_array_start()) {
return false;
}
size_t idx = 0;
if (in.expect(']')) {
return ctx.parse_array_stop(idx);
}
do {
if (! ctx.parse_array_item(in, idx)) {
return false;
}
idx++;
} while (in.expect(','));
return in.expect(']') && ctx.parse_array_stop(idx);
}
template <typename Context, typename Iter> inline bool _parse_object(Context& ctx, input<Iter>& in) {
if (! ctx.parse_object_start()) {
return false;
}
if (in.expect('}')) {
return true;
}
do {
std::string key;
if (! in.expect('"')
|| ! _parse_string(key, in)
|| ! in.expect(':')) {
return false;
}
if (! ctx.parse_object_item(in, key)) {
return false;
}
} while (in.expect(','));
return in.expect('}');
}
template <typename Iter> inline std::string _parse_number(input<Iter>& in) {
std::string num_str;
while (1) {
int ch = in.getc();
if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-'
|| ch == 'e' || ch == 'E') {
num_str.push_back(ch);
} else if (ch == '.') {
#if PICOJSON_USE_LOCALE
num_str += localeconv()->decimal_point;
#else
num_str.push_back('.');
#endif
} else {
in.ungetc();
break;
}
}
return num_str;
}
template <typename Context, typename Iter> inline bool _parse(Context& ctx, input<Iter>& in) {
in.skip_ws();
int ch = in.getc();
switch (ch) {
#define IS(ch, text, op) case ch: \
if (in.match(text) && op) { \
return true; \
} else { \
return false; \
}
IS('n', "ull", ctx.set_null());
IS('f', "alse", ctx.set_bool(false));
IS('t', "rue", ctx.set_bool(true));
#undef IS
case '"':
return ctx.parse_string(in);
case '[':
return _parse_array(ctx, in);
case '{':
return _parse_object(ctx, in);
default:
if (('0' <= ch && ch <= '9') || ch == '-') {
double f;
char *endp;
in.ungetc();
std::string num_str = _parse_number(in);
if (num_str.empty()) {
return false;
}
#ifdef PICOJSON_USE_INT64
{
errno = 0;
intmax_t ival = strtoimax(num_str.c_str(), &endp, 10);
if (errno == 0
&& std::numeric_limits<int64_t>::min() <= ival
&& ival <= std::numeric_limits<int64_t>::max()
&& endp == num_str.c_str() + num_str.size()) {
ctx.set_int64(ival);
return true;
}
}
#endif
f = strtod(num_str.c_str(), &endp);
if (endp == num_str.c_str() + num_str.size()) {
ctx.set_number(f);
return true;
}
return false;
}
break;
}
in.ungetc();
return false;
}
class deny_parse_context {
public:
bool set_null() { return false; }
bool set_bool(bool) { return false; }
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t) { return false; }
#endif
bool set_number(double) { return false; }
template <typename Iter> bool parse_string(input<Iter>&) { return false; }
bool parse_array_start() { return false; }
template <typename Iter> bool parse_array_item(input<Iter>&, size_t) {
return false;
}
bool parse_array_stop(size_t) { return false; }
bool parse_object_start() { return false; }
template <typename Iter> bool parse_object_item(input<Iter>&, const std::string&) {
return false;
}
};
class default_parse_context {
protected:
value* out_;
public:
default_parse_context(value* out) : out_(out) {}
bool set_null() {
*out_ = value();
return true;
}
bool set_bool(bool b) {
*out_ = value(b);
return true;
}
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t i) {
*out_ = value(i);
return true;
}
#endif
bool set_number(double f) {
*out_ = value(f);
return true;
}
template<typename Iter> bool parse_string(input<Iter>& in) {
*out_ = value(string_type, false);
return _parse_string(out_->get<std::string>(), in);
}
bool parse_array_start() {
*out_ = value(array_type, false);
return true;
}
template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) {
array& a = out_->get<array>();
a.push_back(value());
default_parse_context ctx(&a.back());
return _parse(ctx, in);
}
bool parse_array_stop(size_t) { return true; }
bool parse_object_start() {
*out_ = value(object_type, false);
return true;
}
template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string& key) {
object& o = out_->get<object>();
default_parse_context ctx(&o[key]);
return _parse(ctx, in);
}
private:
default_parse_context(const default_parse_context&);
default_parse_context& operator=(const default_parse_context&);
};
class null_parse_context {
public:
struct dummy_str {
void push_back(int) {}
};
public:
null_parse_context() {}
bool set_null() { return true; }
bool set_bool(bool) { return true; }
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t) { return true; }
#endif
bool set_number(double) { return true; }
template <typename Iter> bool parse_string(input<Iter>& in) {
dummy_str s;
return _parse_string(s, in);
}
bool parse_array_start() { return true; }
template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) {
return _parse(*this, in);
}
bool parse_array_stop(size_t) { return true; }
bool parse_object_start() { return true; }
template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string&) {
return _parse(*this, in);
}
private:
null_parse_context(const null_parse_context&);
null_parse_context& operator=(const null_parse_context&);
};
// obsolete, use the version below
template <typename Iter> inline std::string parse(value& out, Iter& pos, const Iter& last) {
std::string err;
pos = parse(out, pos, last, &err);
return err;
}
template <typename Context, typename Iter> inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) {
input<Iter> in(first, last);
if (! _parse(ctx, in) && err != NULL) {
char buf[64];
SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line());
*err = buf;
while (1) {
int ch = in.getc();
if (ch == -1 || ch == '\n') {
break;
} else if (ch >= ' ') {
err->push_back(ch);
}
}
}
return in.cur();
}
template <typename Iter> inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) {
default_parse_context ctx(&out);
return _parse(ctx, first, last, err);
}
inline std::string parse(value& out, const std::string& s) {
std::string err;
parse(out, s.begin(), s.end(), &err);
return err;
}
inline std::string parse(value& out, std::istream& is) {
std::string err;
parse(out, std::istreambuf_iterator<char>(is.rdbuf()),
std::istreambuf_iterator<char>(), &err);
return err;
}
template <typename T> struct last_error_t {
static std::string s;
};
template <typename T> std::string last_error_t<T>::s;
inline void set_last_error(const std::string& s) {
last_error_t<bool>::s = s;
}
inline const std::string& get_last_error() {
return last_error_t<bool>::s;
}
inline bool operator==(const value& x, const value& y) {
if (x.is<null>())
return y.is<null>();
#define PICOJSON_CMP(type) \
if (x.is<type>()) \
return y.is<type>() && x.get<type>() == y.get<type>()
PICOJSON_CMP(bool);
PICOJSON_CMP(double);
PICOJSON_CMP(std::string);
PICOJSON_CMP(array);
PICOJSON_CMP(object);
#undef PICOJSON_CMP
PICOJSON_ASSERT(0);
#ifdef _MSC_VER
__assume(0);
#endif
return false;
}
inline bool operator!=(const value& x, const value& y) {
return ! (x == y);
}
}
#if !PICOJSON_USE_RVALUE_REFERENCE
namespace std {
template<> inline void swap(picojson::value& x, picojson::value& y)
{
x.swap(y);
}
}
#endif
inline std::istream& operator>>(std::istream& is, picojson::value& x)
{
picojson::set_last_error(std::string());
std::string err = picojson::parse(x, is);
if (! err.empty()) {
picojson::set_last_error(err);
is.setstate(std::ios::failbit);
}
return is;
}
inline std::ostream& operator<<(std::ostream& os, const picojson::value& x)
{
x.serialize(std::ostream_iterator<char>(os));
return os;
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
This source diff could not be displayed because it is too large. You can view the blob instead.
//
// Tiny glTF loader.
//
// Copyright (c) 2015, Syoyo Fujita.
// All rights reserved.
// (Licensed under 2-clause BSD liecense)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Version:
// - v0.9.2 Support parsing `texture`
// - v0.9.1 Support loading glTF asset from memory
// - v0.9.0 Initial
//
// Tiny glTF loader is using following libraries:
//
// - picojson: C++ JSON library.
// - base64: base64 decode/encode library.
// - stb_image: Image loading library.
//
#ifndef TINY_GLTF_LOADER_H
#define TINY_GLTF_LOADER_H
#include <string>
#include <vector>
#include <map>
namespace tinygltf {
#define TINYGLTF_MODE_POINTS (0)
#define TINYGLTF_MODE_LINE (1)
#define TINYGLTF_MODE_LINE_LOOP (2)
#define TINYGLTF_MODE_TRIANGLES (4)
#define TINYGLTF_MODE_TRIANGLE_STRIP (5)
#define TINYGLTF_MODE_TRIANGLE_FAN (6)
#define TINYGLTF_COMPONENT_TYPE_BYTE (5120)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121)
#define TINYGLTF_COMPONENT_TYPE_SHORT (5122)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123)
#define TINYGLTF_COMPONENT_TYPE_INT (5124)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125)
#define TINYGLTF_COMPONENT_TYPE_FLOAT (5126)
#define TINYGLTF_COMPONENT_TYPE_DOUBLE (5127)
#define TINYGLTF_TYPE_VEC2 (2)
#define TINYGLTF_TYPE_VEC3 (3)
#define TINYGLTF_TYPE_VEC4 (4)
#define TINYGLTF_TYPE_MAT2 (32 + 2)
#define TINYGLTF_TYPE_MAT3 (32 + 3)
#define TINYGLTF_TYPE_MAT4 (32 + 4)
#define TINYGLTF_TYPE_SCALAR (64 + 1)
#define TINYGLTF_TYPE_VECTOR (64 + 4)
#define TINYGLTF_TYPE_MATRIX (64 + 16)
#define TINYGLTF_IMAGE_FORMAT_JPEG (0)
#define TINYGLTF_IMAGE_FORMAT_PNG (1)
#define TINYGLTF_IMAGE_FORMAT_BMP (2)
#define TINYGLTF_IMAGE_FORMAT_GIF (3)
#define TINYGLTF_TEXTURE_FORMAT_RGBA (6408)
#define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553)
#define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121)
#define TINYGLTF_TARGET_ARRAY_BUFFER (34962)
#define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963)
typedef struct PARAMETER {
std::string stringValue;
std::vector<double> numberArray;
} Parameter;
typedef std::map<std::string, Parameter> ParameterMap;
typedef struct IMAGE {
std::string name;
int width;
int height;
int component;
std::vector<unsigned char> image;
} Image;
typedef struct TEXTURE {
int format;
int internalFormat;
std::string sampler; // Required
std::string source; // Required
int target;
int type;
std::string name;
} Texture;
typedef struct MATERIAL {
std::string name;
std::string technique;
ParameterMap values;
} Material;
typedef struct BUFFERVIEW {
std::string name;
std::string buffer; // Required
size_t byteOffset; // Required
size_t byteLength; // default: 0
int target;
} BufferView;
typedef struct ACCESSOR {
std::string bufferView;
std::string name;
size_t byteOffset;
size_t byteStride;
int componentType; // One of TINYGLTF_COMPONENT_TYPE_***
size_t count;
int type; // One of TINYGLTF_TYPE_***
std::vector<double> minValues; // Optional
std::vector<double> maxValues; // Optional
} Accessor;
class Camera {
public:
Camera() {}
~Camera() {}
std::string name;
bool isOrthographic; // false = perspective.
// Some common properties.
float aspectRatio;
float yFov;
float zFar;
float zNear;
};
typedef struct PRIMITIVE {
std::map<std::string, std::string> attributes; // A dictionary object of
// strings, where each string
// is the ID of the accessor
// containing an attribute.
std::string material; // The ID of the material to apply to this primitive
// when rendering.
std::string indices; // The ID of the accessor that contains the indices.
int mode; // one of TINYGLTF_MODE_***
} Primitive;
typedef struct MESH {
std::string name;
std::vector<Primitive> primitives;
} Mesh;
class Node {
public:
Node() {}
~Node() {}
std::string camera; // camera object referenced by this node.
std::string name;
std::vector<std::string> children;
std::vector<double> rotation; // length must be 0 or 4
std::vector<double> scale; // length must be 0 or 3
std::vector<double> translation; // length must be 0 or 3
std::vector<double> matrix; // length must be 0 or 16
std::vector<std::string> meshes;
};
typedef struct BUFFER {
std::string name;
std::vector<unsigned char> data;
} Buffer;
typedef struct ASSET {
std::string generator;
std::string version;
std::string profile_api;
std::string profile_version;
bool premultipliedAlpha;
} Asset;
class Scene {
public:
Scene() {}
~Scene() {}
std::map<std::string, Accessor> accessors;
std::map<std::string, Buffer> buffers;
std::map<std::string, BufferView> bufferViews;
std::map<std::string, Material> materials;
std::map<std::string, Mesh> meshes;
std::map<std::string, Node> nodes;
std::map<std::string, Texture> textures;
std::map<std::string, Image> images;
std::map<std::string, std::vector<std::string> > scenes; // list of nodes
std::string defaultScene;
Asset asset;
};
class TinyGLTFLoader {
public:
TinyGLTFLoader(){};
~TinyGLTFLoader(){};
/// Loads glTF asset from a file.
/// Returns false and set error string to `err` if there's an error.
bool LoadFromFile(Scene &scene, std::string &err,
const std::string &filename);
/// Loads glTF asset from string(memory).
/// `length` = strlen(str);
/// Returns false and set error string to `err` if there's an error.
bool LoadFromString(Scene &scene, std::string &err, const char *str,
const unsigned int length, const std::string &baseDir);
};
} // namespace tinygltf
#ifdef TINYGLTF_LOADER_IMPLEMENTATION
#include <sstream>
#include <fstream>
#include <cassert>
#include "picojson.h"
#include "stb_image.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <wordexp.h>
#endif
using namespace tinygltf;
namespace {
bool FileExists(const std::string &abs_filename) {
bool ret;
FILE *fp = fopen(abs_filename.c_str(), "rb");
if (fp) {
ret = true;
fclose(fp);
} else {
ret = false;
}
return ret;
}
std::string ExpandFilePath(const std::string &filepath) {
#ifdef _WIN32
uint32 len = ExpandEnvironmentStringsA(filepath.c_str(), NULL, 0);
char *str = new char[len];
ExpandEnvironmentStringsA(filepath.c_str(), str, len);
std::string s(str);
delete[] str;
return s;
#else
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
// no expansion
std::string s = filepath;
#else
std::string s;
wordexp_t p;
if (filepath.empty()) {
return "";
}
// char** w;
int ret = wordexp(filepath.c_str(), &p, 0);
if (ret) {
// err
s = filepath;
return s;
}
// Use first element only.
if (p.we_wordv) {
s = std::string(p.we_wordv[0]);
wordfree(&p);
} else {
s = filepath;
}
#endif
return s;
#endif
}
std::string JoinPath(const std::string &path0, const std::string &path1) {
if (path0.empty()) {
return path1;
} else {
// check '/'
char lastChar = *path0.rbegin();
if (lastChar != '/') {
return path0 + std::string("/") + path1;
} else {
return path0 + path1;
}
}
}
std::string FindFile(const std::vector<std::string> &paths,
const std::string &filepath) {
for (size_t i = 0; i < paths.size(); i++) {
std::string absPath = ExpandFilePath(JoinPath(paths[i], filepath));
if (FileExists(absPath)) {
return absPath;
}
}
return std::string();
}
// std::string GetFilePathExtension(const std::string& FileName)
//{
// if(FileName.find_last_of(".") != std::string::npos)
// return FileName.substr(FileName.find_last_of(".")+1);
// return "";
//}
std::string GetBaseDir(const std::string &filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\"));
return "";
}
// std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const &s);
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
//#include "base64.h"
//#include <iostream>
static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
#if 0
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
#endif
std::string base64_decode(std::string const &encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && (encoded_string[in_] != '=') &&
is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_];
in_++;
if (i == 4) {
for (i = 0; i < 4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] =
(char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++)
char_array_4[j] = 0;
for (j = 0; j < 4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++)
ret += char_array_3[j];
}
return ret;
}
bool LoadExternalFile(std::vector<unsigned char> &out, std::string &err,
const std::string &filename, const std::string &basedir,
size_t reqBytes, bool checkSize) {
out.clear();
std::vector<std::string> paths;
paths.push_back(basedir);
paths.push_back(".");
std::string filepath = FindFile(paths, filename);
if (filepath.empty()) {
err += "File not found : " + filename;
return false;
}
std::ifstream f(filepath.c_str(), std::ifstream::binary);
if (!f) {
err += "File open error : " + filepath;
return false;
}
f.seekg(0, f.end);
size_t sz = f.tellg();
std::vector<unsigned char> buf(sz);
f.seekg(0, f.beg);
f.read(reinterpret_cast<char *>(&buf.at(0)), sz);
f.close();
if (checkSize) {
if (reqBytes == sz) {
out.swap(buf);
return true;
} else {
std::stringstream ss;
ss << "File size mismatch : " << filepath << ", requestedBytes "
<< reqBytes << ", but got " << sz << std::endl;
err += ss.str();
return false;
}
}
out.swap(buf);
return true;
}
bool IsDataURI(const std::string &in) {
std::string header = "data:application/octet-stream;base64,";
if (in.find(header) == 0) {
return true;
}
header = "data:image/png;base64,";
if (in.find(header) == 0) {
return true;
}
header = "data:image/jpeg;base64,";
if (in.find(header) == 0) {
return true;
}
return false;
}
bool DecodeDataURI(std::vector<unsigned char> &out, const std::string &in,
size_t reqBytes, bool checkSize) {
std::string header = "data:application/octet-stream;base64,";
std::string data;
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
if (data.empty()) {
header = "data:image/jpeg;base64,";
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
}
if (data.empty()) {
header = "data:image/png;base64,";
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
}
if (data.empty()) {
return false;
}
if (checkSize) {
if (data.size() != reqBytes) {
return false;
}
out.resize(reqBytes);
} else {
out.resize(data.size());
}
std::copy(data.begin(), data.end(), out.begin());
return true;
return false;
}
bool ParseBooleanProperty(bool &ret, std::string &err,
const picojson::object &o,
const std::string &property, bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<bool>()) {
if (required) {
err += "'" + property + "' property is not a bool type.\n";
}
return false;
}
ret = it->second.get<bool>();
return true;
}
bool ParseNumberProperty(double &ret, std::string &err,
const picojson::object &o, const std::string &property,
bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<double>()) {
if (required) {
err += "'" + property + "' property is not a number type.\n";
}
return false;
}
ret = it->second.get<double>();
return true;
}
bool ParseNumberArrayProperty(std::vector<double> &ret, std::string &err,
const picojson::object &o,
const std::string &property, bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<picojson::array>()) {
if (required) {
err += "'" + property + "' property is not an array.\n";
}
return false;
}
ret.clear();
const picojson::array &arr = it->second.get<picojson::array>();
for (size_t i = 0; i < arr.size(); i++) {
if (!arr[i].is<double>()) {
if (required) {
err += "'" + property + "' property is not a number.\n";
}
return false;
}
ret.push_back(arr[i].get<double>());
}
return true;
}
bool ParseStringProperty(std::string &ret, std::string &err,
const picojson::object &o, const std::string &property,
bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<std::string>()) {
if (required) {
err += "'" + property + "' property is not a string type.\n";
}
return false;
}
ret = it->second.get<std::string>();
return true;
}
bool ParseStringArrayProperty(std::vector<std::string> &ret, std::string &err,
const picojson::object &o,
const std::string &property, bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<picojson::array>()) {
if (required) {
err += "'" + property + "' property is not an array.\n";
}
return false;
}
ret.clear();
const picojson::array &arr = it->second.get<picojson::array>();
for (size_t i = 0; i < arr.size(); i++) {
if (!arr[i].is<std::string>()) {
if (required) {
err += "'" + property + "' property is not a string.\n";
}
return false;
}
ret.push_back(arr[i].get<std::string>());
}
return true;
}
bool ParseAsset(Asset &asset, std::string &err, const picojson::object &o) {
ParseStringProperty(asset.generator, err, o, "generator", false);
ParseBooleanProperty(asset.premultipliedAlpha, err, o, "premultipliedAlpha",
false);
ParseStringProperty(asset.version, err, o, "version", false);
picojson::object::const_iterator profile = o.find("profile");
if (profile != o.end()) {
const picojson::value &v = profile->second;
if (v.contains("api") & v.get("api").is<std::string>()) {
asset.profile_api = v.get("api").get<std::string>();
}
if (v.contains("version") & v.get("version").is<std::string>()) {
asset.profile_version = v.get("version").get<std::string>();
}
}
return true;
}
bool ParseImage(Image &image, std::string &err, const picojson::object &o,
const std::string &basedir) {
std::string uri;
if (!ParseStringProperty(uri, err, o, "uri", true)) {
return false;
}
ParseStringProperty(image.name, err, o, "name", false);
std::vector<unsigned char> img;
if (IsDataURI(uri)) {
if (!DecodeDataURI(img, uri, 0, false)) {
err += "Failed to decode 'uri'.\n";
return false;
}
} else {
// Assume external file
if (!LoadExternalFile(img, err, uri, basedir, 0, false)) {
err += "Failed to load external 'uri'.\n";
return false;
}
if (img.empty()) {
err += "File is empty.\n";
return false;
}
}
int w, h, comp;
unsigned char *data =
stbi_load_from_memory(&img.at(0), img.size(), &w, &h, &comp, 0);
if (!data) {
err += "Unknown image format.\n";
return false;
}
if (w < 1 || h < 1) {
err += "Unknown image format.\n";
return false;
}
image.width = w;
image.height = h;
image.component = comp;
image.image.resize(w * h * comp);
std::copy(data, data + w * h * comp, image.image.begin());
return true;
}
bool ParseTexture(Texture &texture, std::string &err, const picojson::object &o,
const std::string &basedir) {
if (!ParseStringProperty(texture.sampler, err, o, "sampler", true)) {
return false;
}
if (!ParseStringProperty(texture.source, err, o, "source", true)) {
return false;
}
ParseStringProperty(texture.name, err, o, "name", false);
double format = TINYGLTF_TEXTURE_FORMAT_RGBA;
ParseNumberProperty(format, err, o, "format", false);
double internalFormat = TINYGLTF_TEXTURE_FORMAT_RGBA;
ParseNumberProperty(internalFormat, err, o, "internalFormat", false);
double target = TINYGLTF_TEXTURE_TARGET_TEXTURE2D;
ParseNumberProperty(target, err, o, "target", false);
double type = TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE;
ParseNumberProperty(type, err, o, "type", false);
texture.format = static_cast<int>(format);
texture.internalFormat = static_cast<int>(internalFormat);
texture.target = static_cast<int>(target);
texture.type = static_cast<int>(type);
return true;
}
bool ParseBuffer(Buffer &buffer, std::string &err, const picojson::object &o,
const std::string &basedir) {
double byteLength;
if (!ParseNumberProperty(byteLength, err, o, "byteLength", true)) {
return false;
}
std::string uri;
if (!ParseStringProperty(uri, err, o, "uri", true)) {
return false;
}
picojson::object::const_iterator type = o.find("type");
if (type != o.end()) {
if (type->second.is<std::string>()) {
const std::string &ty = (type->second).get<std::string>();
if (ty.compare("arraybuffer") == 0) {
// buffer.type = "arraybuffer";
}
}
}
size_t bytes = static_cast<size_t>(byteLength);
if (IsDataURI(uri)) {
if (!DecodeDataURI(buffer.data, uri, bytes, true)) {
err += "Failed to decode 'uri'.\n";
return false;
}
} else {
// Assume external .bin file.
if (!LoadExternalFile(buffer.data, err, uri, basedir, bytes, true)) {
return false;
}
}
ParseStringProperty(buffer.name, err, o, "name", false);
return true;
}
bool ParseBufferView(BufferView &bufferView, std::string &err,
const picojson::object &o) {
std::string buffer;
if (!ParseStringProperty(buffer, err, o, "buffer", true)) {
return false;
}
double byteOffset;
if (!ParseNumberProperty(byteOffset, err, o, "byteOffset", true)) {
return false;
}
double byteLength = 0.0;
ParseNumberProperty(byteLength, err, o, "byteLength", false);
double target = 0.0;
ParseNumberProperty(target, err, o, "target", false);
int targetValue = static_cast<int>(target);
if ((targetValue == TINYGLTF_TARGET_ARRAY_BUFFER) ||
(targetValue == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER)) {
// OK
} else {
targetValue = 0;
}
bufferView.target = targetValue;
ParseStringProperty(bufferView.name, err, o, "name", false);
bufferView.buffer = buffer;
bufferView.byteOffset = static_cast<size_t>(byteOffset);
bufferView.byteLength = static_cast<size_t>(byteLength);
return true;
}
bool ParseAccessor(Accessor &accessor, std::string &err,
const picojson::object &o) {
std::string bufferView;
if (!ParseStringProperty(bufferView, err, o, "bufferView", true)) {
return false;
}
double byteOffset;
if (!ParseNumberProperty(byteOffset, err, o, "byteOffset", true)) {
return false;
}
double componentType;
if (!ParseNumberProperty(componentType, err, o, "componentType", true)) {
return false;
}
double count = 0.0;
if (!ParseNumberProperty(count, err, o, "count", true)) {
return false;
}
std::string type;
if (!ParseStringProperty(type, err, o, "type", true)) {
return false;
}
if (type.compare("SCALAR") == 0) {
accessor.type = TINYGLTF_TYPE_SCALAR;
} else if (type.compare("VEC2") == 0) {
accessor.type = TINYGLTF_TYPE_VEC2;
} else if (type.compare("VEC3") == 0) {
accessor.type = TINYGLTF_TYPE_VEC3;
} else if (type.compare("VEC4") == 0) {
accessor.type = TINYGLTF_TYPE_VEC4;
} else if (type.compare("MAT2") == 0) {
accessor.type = TINYGLTF_TYPE_MAT2;
} else if (type.compare("MAT3") == 0) {
accessor.type = TINYGLTF_TYPE_MAT3;
} else if (type.compare("MAT4") == 0) {
accessor.type = TINYGLTF_TYPE_MAT4;
} else {
std::stringstream ss;
ss << "Unsupported `type` for accessor object. Got \"" << type << "\"\n";
err += ss.str();
return false;
}
double byteStride = 0.0;
ParseNumberProperty(byteStride, err, o, "byteStride", false);
ParseStringProperty(accessor.name, err, o, "name", false);
accessor.minValues.clear();
accessor.maxValues.clear();
ParseNumberArrayProperty(accessor.minValues, err, o, "min", false);
ParseNumberArrayProperty(accessor.maxValues, err, o, "max", false);
accessor.count = static_cast<size_t>(count);
accessor.bufferView = bufferView;
accessor.byteOffset = static_cast<size_t>(byteOffset);
accessor.byteStride = static_cast<size_t>(byteStride);
{
int comp = static_cast<size_t>(componentType);
if (comp >= TINYGLTF_COMPONENT_TYPE_BYTE &&
comp <= TINYGLTF_COMPONENT_TYPE_DOUBLE) {
// OK
accessor.componentType = comp;
} else {
std::stringstream ss;
ss << "Invalid `componentType` in accessor. Got " << comp << "\n";
err += ss.str();
return false;
}
}
return true;
}
bool ParsePrimitive(Primitive &primitive, std::string &err,
const picojson::object &o) {
if (!ParseStringProperty(primitive.material, err, o, "material", true)) {
return false;
}
double mode = static_cast<double>(TINYGLTF_MODE_TRIANGLES);
ParseNumberProperty(mode, err, o, "mode", false);
int primMode = static_cast<int>(mode);
if (primMode != TINYGLTF_MODE_TRIANGLES) {
err += "Currently TinyGLTFLoader doesn not support primitive mode other \n"
"than TRIANGLES.\n";
return false;
}
primitive.mode = primMode;
primitive.indices = "";
ParseStringProperty(primitive.indices, err, o, "indices", false);
primitive.attributes.clear();
picojson::object::const_iterator attribsObject = o.find("attributes");
if ((attribsObject != o.end()) &&
(attribsObject->second).is<picojson::object>()) {
const picojson::object &attribs =
(attribsObject->second).get<picojson::object>();
picojson::object::const_iterator it(attribs.begin());
picojson::object::const_iterator itEnd(attribs.end());
for (; it != itEnd; it++) {
const std::string &name = it->first;
if (!(it->second).is<std::string>()) {
err += "attribute expects string value.\n";
return false;
}
const std::string &value = (it->second).get<std::string>();
primitive.attributes[name] = value;
}
}
return true;
}
bool ParseMesh(Mesh &mesh, std::string &err, const picojson::object &o) {
ParseStringProperty(mesh.name, err, o, "name", false);
mesh.primitives.clear();
picojson::object::const_iterator primObject = o.find("primitives");
if ((primObject != o.end()) && (primObject->second).is<picojson::array>()) {
const picojson::array &primArray =
(primObject->second).get<picojson::array>();
for (size_t i = 0; i < primArray.size(); i++) {
Primitive primitive;
ParsePrimitive(primitive, err, primArray[i].get<picojson::object>());
mesh.primitives.push_back(primitive);
}
}
return true;
}
bool ParseNode(Node &node, std::string &err, const picojson::object &o) {
ParseStringProperty(node.name, err, o, "name", false);
ParseNumberArrayProperty(node.rotation, err, o, "rotation", false);
ParseNumberArrayProperty(node.scale, err, o, "scale", false);
ParseNumberArrayProperty(node.translation, err, o, "translation", false);
ParseNumberArrayProperty(node.matrix, err, o, "matrix", false);
ParseStringArrayProperty(node.meshes, err, o, "meshes", false);
node.children.clear();
picojson::object::const_iterator childrenObject = o.find("children");
if ((childrenObject != o.end()) &&
(childrenObject->second).is<picojson::array>()) {
const picojson::array &childrenArray =
(childrenObject->second).get<picojson::array>();
for (size_t i = 0; i < childrenArray.size(); i++) {
Node node;
if (!childrenArray[i].is<std::string>()) {
err += "Invalid `children` array.\n";
return false;
}
const std::string &childrenNode = childrenArray[i].get<std::string>();
node.children.push_back(childrenNode);
}
}
return true;
}
bool ParseMaterial(Material &material, std::string &err,
const picojson::object &o) {
ParseStringProperty(material.name, err, o, "name", false);
ParseStringProperty(material.technique, err, o, "technique", false);
material.values.clear();
picojson::object::const_iterator valuesIt = o.find("values");
if ((valuesIt != o.end()) && (valuesIt->second).is<picojson::object>()) {
const picojson::object &valuesObject =
(valuesIt->second).get<picojson::object>();
picojson::object::const_iterator it(valuesObject.begin());
picojson::object::const_iterator itEnd(valuesObject.end());
for (; it != itEnd; it++) {
// Assume number values.
Parameter param;
if (ParseStringProperty(param.stringValue, err, valuesObject, it->first,
false)) {
// Found string property.
} else if (!ParseNumberArrayProperty(param.numberArray, err, valuesObject,
it->first, false)) {
// Fallback to numer property.
double value;
if (ParseNumberProperty(value, err, valuesObject, it->first, false)) {
param.numberArray.push_back(value);
}
}
material.values[it->first] = param;
}
}
return true;
}
}
bool TinyGLTFLoader::LoadFromString(Scene &scene, std::string &err,
const char *str, unsigned int length,
const std::string &baseDir) {
picojson::value v;
std::string perr = picojson::parse(v, str, str + length);
if (!perr.empty()) {
err = perr;
return false;
}
if (v.contains("scene") && v.get("scene").is<std::string>()) {
// OK
} else {
err += "\"scene\" object not found in .gltf\n";
return false;
}
if (v.contains("scenes") && v.get("scenes").is<picojson::object>()) {
// OK
} else {
err += "\"scenes\" object not found in .gltf\n";
return false;
}
if (v.contains("nodes") && v.get("nodes").is<picojson::object>()) {
// OK
} else {
err += "\"nodes\" object not found in .gltf\n";
return false;
}
if (v.contains("accessors") && v.get("accessors").is<picojson::object>()) {
// OK
} else {
err += "\"accessors\" object not found in .gltf\n";
return false;
}
if (v.contains("buffers") && v.get("buffers").is<picojson::object>()) {
// OK
} else {
err += "\"buffers\" object not found in .gltf\n";
return false;
}
if (v.contains("bufferViews") &&
v.get("bufferViews").is<picojson::object>()) {
// OK
} else {
err += "\"bufferViews\" object not found in .gltf\n";
return false;
}
scene.buffers.clear();
scene.bufferViews.clear();
scene.accessors.clear();
scene.meshes.clear();
scene.nodes.clear();
scene.defaultScene = "";
// 0. Parse Asset
if (v.contains("asset") && v.get("asset").is<picojson::object>()) {
const picojson::object &root = v.get("asset").get<picojson::object>();
ParseAsset(scene.asset, err, root);
}
// 1. Parse Buffer
if (v.contains("buffers") && v.get("buffers").is<picojson::object>()) {
const picojson::object &root = v.get("buffers").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Buffer buffer;
if (!ParseBuffer(buffer, err, (it->second).get<picojson::object>(),
baseDir)) {
return false;
}
scene.buffers[it->first] = buffer;
}
}
// 2. Parse BufferView
if (v.contains("bufferViews") &&
v.get("bufferViews").is<picojson::object>()) {
const picojson::object &root = v.get("bufferViews").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
BufferView bufferView;
if (!ParseBufferView(bufferView, err,
(it->second).get<picojson::object>())) {
return false;
}
scene.bufferViews[it->first] = bufferView;
}
}
// 3. Parse Accessor
if (v.contains("accessors") && v.get("accessors").is<picojson::object>()) {
const picojson::object &root = v.get("accessors").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Accessor accessor;
if (!ParseAccessor(accessor, err, (it->second).get<picojson::object>())) {
return false;
}
scene.accessors[it->first] = accessor;
}
}
// 4. Parse Mesh
if (v.contains("meshes") && v.get("meshes").is<picojson::object>()) {
const picojson::object &root = v.get("meshes").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Mesh mesh;
if (!ParseMesh(mesh, err, (it->second).get<picojson::object>())) {
return false;
}
scene.meshes[it->first] = mesh;
}
}
// 5. Parse Node
if (v.contains("nodes") && v.get("nodes").is<picojson::object>()) {
const picojson::object &root = v.get("nodes").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Node node;
if (!ParseNode(node, err, (it->second).get<picojson::object>())) {
return false;
}
scene.nodes[it->first] = node;
}
}
// 6. Parse scenes.
if (v.contains("scenes") && v.get("scenes").is<picojson::object>()) {
const picojson::object &root = v.get("scenes").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
const picojson::object &o = (it->second).get<picojson::object>();
std::vector<std::string> nodes;
if (!ParseStringArrayProperty(nodes, err, o, "nodes", false)) {
return false;
}
scene.scenes[it->first] = nodes;
}
}
// 7. Parse default scenes.
if (v.contains("scene") && v.get("scene").is<std::string>()) {
const std::string defaultScene = v.get("scene").get<std::string>();
scene.defaultScene = defaultScene;
}
// 8. Parse Material
if (v.contains("materials") && v.get("materials").is<picojson::object>()) {
const picojson::object &root = v.get("materials").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Material material;
if (!ParseMaterial(material, err, (it->second).get<picojson::object>())) {
return false;
}
scene.materials[it->first] = material;
}
}
// 9. Parse Image
if (v.contains("images") && v.get("images").is<picojson::object>()) {
const picojson::object &root = v.get("images").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Image image;
if (!ParseImage(image, err, (it->second).get<picojson::object>(),
baseDir)) {
return false;
}
scene.images[it->first] = image;
}
}
// 9. Parse Texture
if (v.contains("textures") && v.get("textures").is<picojson::object>()) {
const picojson::object &root = v.get("textures").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Texture texture;
if (!ParseTexture(texture, err, (it->second).get<picojson::object>(),
baseDir)) {
return false;
}
scene.textures[it->first] = texture;
}
}
return true;
}
bool TinyGLTFLoader::LoadFromFile(Scene &scene, std::string &err,
const std::string &filename) {
std::stringstream ss;
std::ifstream f(filename.c_str());
if (!f) {
ss << "Failed to open file: " << filename << std::endl;
err = ss.str();
return false;
}
f.seekg(0, f.end);
size_t sz = f.tellg();
std::vector<char> buf(sz);
f.seekg(0, f.beg);
f.read(&buf.at(0), sz);
f.close();
std::string basedir = GetBaseDir(filename);
bool ret = LoadFromString(scene, err, &buf.at(0), buf.size(), basedir);
return ret;
}
#endif // TINYGLTF_LOADER_IMPLEMENTATION
#endif // TINY_GLTF_LOADER_H
//
// Tiny glTF loader.
//
// Copyright (c) 2015, Syoyo Fujita.
// All rights reserved.
// (Licensed under 2-clause BSD liecense)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Version:
// - v0.9.2 Support parsing `texture`
// - v0.9.1 Support loading glTF asset from memory
// - v0.9.0 Initial
//
// Tiny glTF loader is using following libraries:
//
// - picojson: C++ JSON library.
// - base64: base64 decode/encode library.
// - stb_image: Image loading library.
//
#ifndef TINY_GLTF_LOADER_H
#define TINY_GLTF_LOADER_H
#include <string>
#include <vector>
#include <map>
namespace tinygltf {
#define TINYGLTF_MODE_POINTS (0)
#define TINYGLTF_MODE_LINE (1)
#define TINYGLTF_MODE_LINE_LOOP (2)
#define TINYGLTF_MODE_TRIANGLES (4)
#define TINYGLTF_MODE_TRIANGLE_STRIP (5)
#define TINYGLTF_MODE_TRIANGLE_FAN (6)
#define TINYGLTF_COMPONENT_TYPE_BYTE (5120)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121)
#define TINYGLTF_COMPONENT_TYPE_SHORT (5122)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123)
#define TINYGLTF_COMPONENT_TYPE_INT (5124)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125)
#define TINYGLTF_COMPONENT_TYPE_FLOAT (5126)
#define TINYGLTF_COMPONENT_TYPE_DOUBLE (5127)
#define TINYGLTF_TYPE_VEC2 (2)
#define TINYGLTF_TYPE_VEC3 (3)
#define TINYGLTF_TYPE_VEC4 (4)
#define TINYGLTF_TYPE_MAT2 (32 + 2)
#define TINYGLTF_TYPE_MAT3 (32 + 3)
#define TINYGLTF_TYPE_MAT4 (32 + 4)
#define TINYGLTF_TYPE_SCALAR (64 + 1)
#define TINYGLTF_TYPE_VECTOR (64 + 4)
#define TINYGLTF_TYPE_MATRIX (64 + 16)
#define TINYGLTF_IMAGE_FORMAT_JPEG (0)
#define TINYGLTF_IMAGE_FORMAT_PNG (1)
#define TINYGLTF_IMAGE_FORMAT_BMP (2)
#define TINYGLTF_IMAGE_FORMAT_GIF (3)
#define TINYGLTF_TEXTURE_FORMAT_RGBA (6408)
#define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553)
#define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121)
#define TINYGLTF_TARGET_ARRAY_BUFFER (34962)
#define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963)
typedef struct PARAMETER {
std::string stringValue;
std::vector<double> numberArray;
} Parameter;
typedef std::map<std::string, Parameter> ParameterMap;
typedef struct IMAGE {
std::string name;
int width;
int height;
int component;
std::vector<unsigned char> image;
} Image;
typedef struct TEXTURE {
int format;
int internalFormat;
std::string sampler; // Required
std::string source; // Required
int target;
int type;
std::string name;
} Texture;
typedef struct MATERIAL {
std::string name;
std::string technique;
ParameterMap values;
} Material;
typedef struct BUFFERVIEW {
std::string name;
std::string buffer; // Required
size_t byteOffset; // Required
size_t byteLength; // default: 0
int target;
} BufferView;
typedef struct ACCESSOR {
std::string bufferView;
std::string name;
size_t byteOffset;
size_t byteStride;
int componentType; // One of TINYGLTF_COMPONENT_TYPE_***
size_t count;
int type; // One of TINYGLTF_TYPE_***
std::vector<double> minValues; // Optional
std::vector<double> maxValues; // Optional
} Accessor;
class Camera {
public:
Camera() {}
~Camera() {}
std::string name;
bool isOrthographic; // false = perspective.
// Some common properties.
float aspectRatio;
float yFov;
float zFar;
float zNear;
};
typedef struct PRIMITIVE {
std::map<std::string, std::string> attributes; // A dictionary object of
// strings, where each string
// is the ID of the accessor
// containing an attribute.
std::string material; // The ID of the material to apply to this primitive
// when rendering.
std::string indices; // The ID of the accessor that contains the indices.
int mode; // one of TINYGLTF_MODE_***
} Primitive;
typedef struct MESH {
std::string name;
std::vector<Primitive> primitives;
} Mesh;
class Node {
public:
Node() {}
~Node() {}
std::string camera; // camera object referenced by this node.
std::string name;
std::vector<std::string> children;
std::vector<double> rotation; // length must be 0 or 4
std::vector<double> scale; // length must be 0 or 3
std::vector<double> translation; // length must be 0 or 3
std::vector<double> matrix; // length must be 0 or 16
std::vector<std::string> meshes;
};
typedef struct BUFFER {
std::string name;
std::vector<unsigned char> data;
} Buffer;
typedef struct ASSET {
std::string generator;
std::string version;
std::string profile_api;
std::string profile_version;
bool premultipliedAlpha;
} Asset;
class Scene {
public:
Scene() {}
~Scene() {}
std::map<std::string, Accessor> accessors;
std::map<std::string, Buffer> buffers;
std::map<std::string, BufferView> bufferViews;
std::map<std::string, Material> materials;
std::map<std::string, Mesh> meshes;
std::map<std::string, Node> nodes;
std::map<std::string, Texture> textures;
std::map<std::string, Image> images;
std::map<std::string, std::vector<std::string> > scenes; // list of nodes
std::string defaultScene;
Asset asset;
};
class TinyGLTFLoader {
public:
TinyGLTFLoader(){};
~TinyGLTFLoader(){};
/// Loads glTF asset from a file.
/// Returns false and set error string to `err` if there's an error.
bool LoadFromFile(Scene &scene, std::string &err,
const std::string &filename);
/// Loads glTF asset from string(memory).
/// `length` = strlen(str);
/// Returns false and set error string to `err` if there's an error.
bool LoadFromString(Scene &scene, std::string &err, const char *str,
const unsigned int length, const std::string &baseDir);
};
} // namespace tinygltf
#ifdef TINYGLTF_LOADER_IMPLEMENTATION
#include <sstream>
#include <fstream>
#include <cassert>
#include "picojson.h"
#include "stb_image.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <wordexp.h>
#endif
using namespace tinygltf;
namespace {
bool FileExists(const std::string &abs_filename) {
bool ret;
FILE *fp = fopen(abs_filename.c_str(), "rb");
if (fp) {
ret = true;
fclose(fp);
} else {
ret = false;
}
return ret;
}
std::string ExpandFilePath(const std::string &filepath) {
#ifdef _WIN32
uint32 len = ExpandEnvironmentStringsA(filepath.c_str(), NULL, 0);
char *str = new char[len];
ExpandEnvironmentStringsA(filepath.c_str(), str, len);
std::string s(str);
delete[] str;
return s;
#else
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
// no expansion
std::string s = filepath;
#else
std::string s;
wordexp_t p;
if (filepath.empty()) {
return "";
}
// char** w;
int ret = wordexp(filepath.c_str(), &p, 0);
if (ret) {
// err
s = filepath;
return s;
}
// Use first element only.
if (p.we_wordv) {
s = std::string(p.we_wordv[0]);
wordfree(&p);
} else {
s = filepath;
}
#endif
return s;
#endif
}
std::string JoinPath(const std::string &path0, const std::string &path1) {
if (path0.empty()) {
return path1;
} else {
// check '/'
char lastChar = *path0.rbegin();
if (lastChar != '/') {
return path0 + std::string("/") + path1;
} else {
return path0 + path1;
}
}
}
std::string FindFile(const std::vector<std::string> &paths,
const std::string &filepath) {
for (size_t i = 0; i < paths.size(); i++) {
std::string absPath = ExpandFilePath(JoinPath(paths[i], filepath));
if (FileExists(absPath)) {
return absPath;
}
}
return std::string();
}
// std::string GetFilePathExtension(const std::string& FileName)
//{
// if(FileName.find_last_of(".") != std::string::npos)
// return FileName.substr(FileName.find_last_of(".")+1);
// return "";
//}
std::string GetBaseDir(const std::string &filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\"));
return "";
}
// std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const &s);
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
//#include "base64.h"
//#include <iostream>
static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
#if 0
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
#endif
std::string base64_decode(std::string const &encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && (encoded_string[in_] != '=') &&
is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_];
in_++;
if (i == 4) {
for (i = 0; i < 4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] =
(char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++)
char_array_4[j] = 0;
for (j = 0; j < 4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++)
ret += char_array_3[j];
}
return ret;
}
bool LoadExternalFile(std::vector<unsigned char> &out, std::string &err,
const std::string &filename, const std::string &basedir,
size_t reqBytes, bool checkSize) {
out.clear();
std::vector<std::string> paths;
paths.push_back(basedir);
paths.push_back(".");
std::string filepath = FindFile(paths, filename);
if (filepath.empty()) {
err += "File not found : " + filename;
return false;
}
std::ifstream f(filepath.c_str(), std::ifstream::binary);
if (!f) {
err += "File open error : " + filepath;
return false;
}
f.seekg(0, f.end);
size_t sz = f.tellg();
std::vector<unsigned char> buf(sz);
f.seekg(0, f.beg);
f.read(reinterpret_cast<char *>(&buf.at(0)), sz);
f.close();
if (checkSize) {
if (reqBytes == sz) {
out.swap(buf);
return true;
} else {
std::stringstream ss;
ss << "File size mismatch : " << filepath << ", requestedBytes "
<< reqBytes << ", but got " << sz << std::endl;
err += ss.str();
return false;
}
}
out.swap(buf);
return true;
}
bool IsDataURI(const std::string &in) {
std::string header = "data:application/octet-stream;base64,";
if (in.find(header) == 0) {
return true;
}
header = "data:image/png;base64,";
if (in.find(header) == 0) {
return true;
}
header = "data:image/jpeg;base64,";
if (in.find(header) == 0) {
return true;
}
return false;
}
bool DecodeDataURI(std::vector<unsigned char> &out, const std::string &in,
size_t reqBytes, bool checkSize) {
std::string header = "data:application/octet-stream;base64,";
std::string data;
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
if (data.empty()) {
header = "data:image/jpeg;base64,";
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
}
if (data.empty()) {
header = "data:image/png;base64,";
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
}
if (data.empty()) {
return false;
}
if (checkSize) {
if (data.size() != reqBytes) {
return false;
}
out.resize(reqBytes);
} else {
out.resize(data.size());
}
std::copy(data.begin(), data.end(), out.begin());
return true;
return false;
}
bool ParseBooleanProperty(bool &ret, std::string &err,
const picojson::object &o,
const std::string &property, bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<bool>()) {
if (required) {
err += "'" + property + "' property is not a bool type.\n";
}
return false;
}
ret = it->second.get<bool>();
return true;
}
bool ParseNumberProperty(double &ret, std::string &err,
const picojson::object &o, const std::string &property,
bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<double>()) {
if (required) {
err += "'" + property + "' property is not a number type.\n";
}
return false;
}
ret = it->second.get<double>();
return true;
}
bool ParseNumberArrayProperty(std::vector<double> &ret, std::string &err,
const picojson::object &o,
const std::string &property, bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<picojson::array>()) {
if (required) {
err += "'" + property + "' property is not an array.\n";
}
return false;
}
ret.clear();
const picojson::array &arr = it->second.get<picojson::array>();
for (size_t i = 0; i < arr.size(); i++) {
if (!arr[i].is<double>()) {
if (required) {
err += "'" + property + "' property is not a number.\n";
}
return false;
}
ret.push_back(arr[i].get<double>());
}
return true;
}
bool ParseStringProperty(std::string &ret, std::string &err,
const picojson::object &o, const std::string &property,
bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<std::string>()) {
if (required) {
err += "'" + property + "' property is not a string type.\n";
}
return false;
}
ret = it->second.get<std::string>();
return true;
}
bool ParseStringArrayProperty(std::vector<std::string> &ret, std::string &err,
const picojson::object &o,
const std::string &property, bool required) {
picojson::object::const_iterator it = o.find(property);
if (it == o.end()) {
if (required) {
err += "'" + property + "' property is missing.\n";
}
return false;
}
if (!it->second.is<picojson::array>()) {
if (required) {
err += "'" + property + "' property is not an array.\n";
}
return false;
}
ret.clear();
const picojson::array &arr = it->second.get<picojson::array>();
for (size_t i = 0; i < arr.size(); i++) {
if (!arr[i].is<std::string>()) {
if (required) {
err += "'" + property + "' property is not a string.\n";
}
return false;
}
ret.push_back(arr[i].get<std::string>());
}
return true;
}
bool ParseAsset(Asset &asset, std::string &err, const picojson::object &o) {
ParseStringProperty(asset.generator, err, o, "generator", false);
ParseBooleanProperty(asset.premultipliedAlpha, err, o, "premultipliedAlpha",
false);
ParseStringProperty(asset.version, err, o, "version", false);
picojson::object::const_iterator profile = o.find("profile");
if (profile != o.end()) {
const picojson::value &v = profile->second;
if (v.contains("api") & v.get("api").is<std::string>()) {
asset.profile_api = v.get("api").get<std::string>();
}
if (v.contains("version") & v.get("version").is<std::string>()) {
asset.profile_version = v.get("version").get<std::string>();
}
}
return true;
}
bool ParseImage(Image &image, std::string &err, const picojson::object &o,
const std::string &basedir) {
std::string uri;
if (!ParseStringProperty(uri, err, o, "uri", true)) {
return false;
}
ParseStringProperty(image.name, err, o, "name", false);
std::vector<unsigned char> img;
if (IsDataURI(uri)) {
if (!DecodeDataURI(img, uri, 0, false)) {
err += "Failed to decode 'uri'.\n";
return false;
}
} else {
// Assume external file
if (!LoadExternalFile(img, err, uri, basedir, 0, false)) {
err += "Failed to load external 'uri'.\n";
return false;
}
if (img.empty()) {
err += "File is empty.\n";
return false;
}
}
int w, h, comp;
unsigned char *data =
stbi_load_from_memory(&img.at(0), img.size(), &w, &h, &comp, 0);
if (!data) {
err += "Unknown image format.\n";
return false;
}
if (w < 1 || h < 1) {
err += "Unknown image format.\n";
return false;
}
image.width = w;
image.height = h;
image.component = comp;
image.image.resize(w * h * comp);
std::copy(data, data + w * h * comp, image.image.begin());
return true;
}
bool ParseTexture(Texture &texture, std::string &err, const picojson::object &o,
const std::string &basedir) {
if (!ParseStringProperty(texture.sampler, err, o, "sampler", true)) {
return false;
}
if (!ParseStringProperty(texture.source, err, o, "source", true)) {
return false;
}
ParseStringProperty(texture.name, err, o, "name", false);
double format = TINYGLTF_TEXTURE_FORMAT_RGBA;
ParseNumberProperty(format, err, o, "format", false);
double internalFormat = TINYGLTF_TEXTURE_FORMAT_RGBA;
ParseNumberProperty(internalFormat, err, o, "internalFormat", false);
double target = TINYGLTF_TEXTURE_TARGET_TEXTURE2D;
ParseNumberProperty(target, err, o, "target", false);
double type = TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE;
ParseNumberProperty(type, err, o, "type", false);
texture.format = static_cast<int>(format);
texture.internalFormat = static_cast<int>(internalFormat);
texture.target = static_cast<int>(target);
texture.type = static_cast<int>(type);
return true;
}
bool ParseBuffer(Buffer &buffer, std::string &err, const picojson::object &o,
const std::string &basedir) {
double byteLength;
if (!ParseNumberProperty(byteLength, err, o, "byteLength", true)) {
return false;
}
std::string uri;
if (!ParseStringProperty(uri, err, o, "uri", true)) {
return false;
}
picojson::object::const_iterator type = o.find("type");
if (type != o.end()) {
if (type->second.is<std::string>()) {
const std::string &ty = (type->second).get<std::string>();
if (ty.compare("arraybuffer") == 0) {
// buffer.type = "arraybuffer";
}
}
}
size_t bytes = static_cast<size_t>(byteLength);
if (IsDataURI(uri)) {
if (!DecodeDataURI(buffer.data, uri, bytes, true)) {
err += "Failed to decode 'uri'.\n";
return false;
}
} else {
// Assume external .bin file.
if (!LoadExternalFile(buffer.data, err, uri, basedir, bytes, true)) {
return false;
}
}
ParseStringProperty(buffer.name, err, o, "name", false);
return true;
}
bool ParseBufferView(BufferView &bufferView, std::string &err,
const picojson::object &o) {
std::string buffer;
if (!ParseStringProperty(buffer, err, o, "buffer", true)) {
return false;
}
double byteOffset;
if (!ParseNumberProperty(byteOffset, err, o, "byteOffset", true)) {
return false;
}
double byteLength = 0.0;
ParseNumberProperty(byteLength, err, o, "byteLength", false);
double target = 0.0;
ParseNumberProperty(target, err, o, "target", false);
int targetValue = static_cast<int>(target);
if ((targetValue == TINYGLTF_TARGET_ARRAY_BUFFER) ||
(targetValue == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER)) {
// OK
} else {
targetValue = 0;
}
bufferView.target = targetValue;
ParseStringProperty(bufferView.name, err, o, "name", false);
bufferView.buffer = buffer;
bufferView.byteOffset = static_cast<size_t>(byteOffset);
bufferView.byteLength = static_cast<size_t>(byteLength);
return true;
}
bool ParseAccessor(Accessor &accessor, std::string &err,
const picojson::object &o) {
std::string bufferView;
if (!ParseStringProperty(bufferView, err, o, "bufferView", true)) {
return false;
}
double byteOffset;
if (!ParseNumberProperty(byteOffset, err, o, "byteOffset", true)) {
return false;
}
double componentType;
if (!ParseNumberProperty(componentType, err, o, "componentType", true)) {
return false;
}
double count = 0.0;
if (!ParseNumberProperty(count, err, o, "count", true)) {
return false;
}
std::string type;
if (!ParseStringProperty(type, err, o, "type", true)) {
return false;
}
if (type.compare("SCALAR") == 0) {
accessor.type = TINYGLTF_TYPE_SCALAR;
} else if (type.compare("VEC2") == 0) {
accessor.type = TINYGLTF_TYPE_VEC2;
} else if (type.compare("VEC3") == 0) {
accessor.type = TINYGLTF_TYPE_VEC3;
} else if (type.compare("VEC4") == 0) {
accessor.type = TINYGLTF_TYPE_VEC4;
} else if (type.compare("MAT2") == 0) {
accessor.type = TINYGLTF_TYPE_MAT2;
} else if (type.compare("MAT3") == 0) {
accessor.type = TINYGLTF_TYPE_MAT3;
} else if (type.compare("MAT4") == 0) {
accessor.type = TINYGLTF_TYPE_MAT4;
} else {
std::stringstream ss;
ss << "Unsupported `type` for accessor object. Got \"" << type << "\"\n";
err += ss.str();
return false;
}
double byteStride = 0.0;
ParseNumberProperty(byteStride, err, o, "byteStride", false);
ParseStringProperty(accessor.name, err, o, "name", false);
accessor.minValues.clear();
accessor.maxValues.clear();
ParseNumberArrayProperty(accessor.minValues, err, o, "min", false);
ParseNumberArrayProperty(accessor.maxValues, err, o, "max", false);
accessor.count = static_cast<size_t>(count);
accessor.bufferView = bufferView;
accessor.byteOffset = static_cast<size_t>(byteOffset);
accessor.byteStride = static_cast<size_t>(byteStride);
{
int comp = static_cast<size_t>(componentType);
if (comp >= TINYGLTF_COMPONENT_TYPE_BYTE &&
comp <= TINYGLTF_COMPONENT_TYPE_DOUBLE) {
// OK
accessor.componentType = comp;
} else {
std::stringstream ss;
ss << "Invalid `componentType` in accessor. Got " << comp << "\n";
err += ss.str();
return false;
}
}
return true;
}
bool ParsePrimitive(Primitive &primitive, std::string &err,
const picojson::object &o) {
if (!ParseStringProperty(primitive.material, err, o, "material", true)) {
return false;
}
double mode = static_cast<double>(TINYGLTF_MODE_TRIANGLES);
ParseNumberProperty(mode, err, o, "mode", false);
int primMode = static_cast<int>(mode);
if (primMode != TINYGLTF_MODE_TRIANGLES) {
err += "Currently TinyGLTFLoader doesn not support primitive mode other \n"
"than TRIANGLES.\n";
return false;
}
primitive.mode = primMode;
primitive.indices = "";
ParseStringProperty(primitive.indices, err, o, "indices", false);
primitive.attributes.clear();
picojson::object::const_iterator attribsObject = o.find("attributes");
if ((attribsObject != o.end()) &&
(attribsObject->second).is<picojson::object>()) {
const picojson::object &attribs =
(attribsObject->second).get<picojson::object>();
picojson::object::const_iterator it(attribs.begin());
picojson::object::const_iterator itEnd(attribs.end());
for (; it != itEnd; it++) {
const std::string &name = it->first;
if (!(it->second).is<std::string>()) {
err += "attribute expects string value.\n";
return false;
}
const std::string &value = (it->second).get<std::string>();
primitive.attributes[name] = value;
}
}
return true;
}
bool ParseMesh(Mesh &mesh, std::string &err, const picojson::object &o) {
ParseStringProperty(mesh.name, err, o, "name", false);
mesh.primitives.clear();
picojson::object::const_iterator primObject = o.find("primitives");
if ((primObject != o.end()) && (primObject->second).is<picojson::array>()) {
const picojson::array &primArray =
(primObject->second).get<picojson::array>();
for (size_t i = 0; i < primArray.size(); i++) {
Primitive primitive;
ParsePrimitive(primitive, err, primArray[i].get<picojson::object>());
mesh.primitives.push_back(primitive);
}
}
return true;
}
bool ParseNode(Node &node, std::string &err, const picojson::object &o) {
ParseStringProperty(node.name, err, o, "name", false);
ParseNumberArrayProperty(node.rotation, err, o, "rotation", false);
ParseNumberArrayProperty(node.scale, err, o, "scale", false);
ParseNumberArrayProperty(node.translation, err, o, "translation", false);
ParseNumberArrayProperty(node.matrix, err, o, "matrix", false);
ParseStringArrayProperty(node.meshes, err, o, "meshes", false);
node.children.clear();
picojson::object::const_iterator childrenObject = o.find("children");
if ((childrenObject != o.end()) &&
(childrenObject->second).is<picojson::array>()) {
const picojson::array &childrenArray =
(childrenObject->second).get<picojson::array>();
for (size_t i = 0; i < childrenArray.size(); i++) {
Node node;
if (!childrenArray[i].is<std::string>()) {
err += "Invalid `children` array.\n";
return false;
}
const std::string &childrenNode = childrenArray[i].get<std::string>();
node.children.push_back(childrenNode);
}
}
return true;
}
bool ParseMaterial(Material &material, std::string &err,
const picojson::object &o) {
ParseStringProperty(material.name, err, o, "name", false);
ParseStringProperty(material.technique, err, o, "technique", false);
material.values.clear();
picojson::object::const_iterator valuesIt = o.find("values");
if ((valuesIt != o.end()) && (valuesIt->second).is<picojson::object>()) {
const picojson::object &valuesObject =
(valuesIt->second).get<picojson::object>();
picojson::object::const_iterator it(valuesObject.begin());
picojson::object::const_iterator itEnd(valuesObject.end());
for (; it != itEnd; it++) {
// Assume number values.
Parameter param;
if (ParseStringProperty(param.stringValue, err, valuesObject, it->first,
false)) {
// Found string property.
} else if (!ParseNumberArrayProperty(param.numberArray, err, valuesObject,
it->first, false)) {
// Fallback to numer property.
double value;
if (ParseNumberProperty(value, err, valuesObject, it->first, false)) {
param.numberArray.push_back(value);
}
}
material.values[it->first] = param;
}
}
return true;
}
}
bool TinyGLTFLoader::LoadFromString(Scene &scene, std::string &err,
const char *str, unsigned int length,
const std::string &baseDir) {
picojson::value v;
std::string perr = picojson::parse(v, str, str + length);
if (!perr.empty()) {
err = perr;
return false;
}
if (v.contains("scene") && v.get("scene").is<std::string>()) {
// OK
} else {
err += "\"scene\" object not found in .gltf\n";
return false;
}
if (v.contains("scenes") && v.get("scenes").is<picojson::object>()) {
// OK
} else {
err += "\"scenes\" object not found in .gltf\n";
return false;
}
if (v.contains("nodes") && v.get("nodes").is<picojson::object>()) {
// OK
} else {
err += "\"nodes\" object not found in .gltf\n";
return false;
}
if (v.contains("accessors") && v.get("accessors").is<picojson::object>()) {
// OK
} else {
err += "\"accessors\" object not found in .gltf\n";
return false;
}
if (v.contains("buffers") && v.get("buffers").is<picojson::object>()) {
// OK
} else {
err += "\"buffers\" object not found in .gltf\n";
return false;
}
if (v.contains("bufferViews") &&
v.get("bufferViews").is<picojson::object>()) {
// OK
} else {
err += "\"bufferViews\" object not found in .gltf\n";
return false;
}
scene.buffers.clear();
scene.bufferViews.clear();
scene.accessors.clear();
scene.meshes.clear();
scene.nodes.clear();
scene.defaultScene = "";
// 0. Parse Asset
if (v.contains("asset") && v.get("asset").is<picojson::object>()) {
const picojson::object &root = v.get("asset").get<picojson::object>();
ParseAsset(scene.asset, err, root);
}
// 1. Parse Buffer
if (v.contains("buffers") && v.get("buffers").is<picojson::object>()) {
const picojson::object &root = v.get("buffers").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Buffer buffer;
if (!ParseBuffer(buffer, err, (it->second).get<picojson::object>(),
baseDir)) {
return false;
}
scene.buffers[it->first] = buffer;
}
}
// 2. Parse BufferView
if (v.contains("bufferViews") &&
v.get("bufferViews").is<picojson::object>()) {
const picojson::object &root = v.get("bufferViews").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
BufferView bufferView;
if (!ParseBufferView(bufferView, err,
(it->second).get<picojson::object>())) {
return false;
}
scene.bufferViews[it->first] = bufferView;
}
}
// 3. Parse Accessor
if (v.contains("accessors") && v.get("accessors").is<picojson::object>()) {
const picojson::object &root = v.get("accessors").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Accessor accessor;
if (!ParseAccessor(accessor, err, (it->second).get<picojson::object>())) {
return false;
}
scene.accessors[it->first] = accessor;
}
}
// 4. Parse Mesh
if (v.contains("meshes") && v.get("meshes").is<picojson::object>()) {
const picojson::object &root = v.get("meshes").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Mesh mesh;
if (!ParseMesh(mesh, err, (it->second).get<picojson::object>())) {
return false;
}
scene.meshes[it->first] = mesh;
}
}
// 5. Parse Node
if (v.contains("nodes") && v.get("nodes").is<picojson::object>()) {
const picojson::object &root = v.get("nodes").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Node node;
if (!ParseNode(node, err, (it->second).get<picojson::object>())) {
return false;
}
scene.nodes[it->first] = node;
}
}
// 6. Parse scenes.
if (v.contains("scenes") && v.get("scenes").is<picojson::object>()) {
const picojson::object &root = v.get("scenes").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
const picojson::object &o = (it->second).get<picojson::object>();
std::vector<std::string> nodes;
if (!ParseStringArrayProperty(nodes, err, o, "nodes", false)) {
return false;
}
scene.scenes[it->first] = nodes;
}
}
// 7. Parse default scenes.
if (v.contains("scene") && v.get("scene").is<std::string>()) {
const std::string defaultScene = v.get("scene").get<std::string>();
scene.defaultScene = defaultScene;
}
// 8. Parse Material
if (v.contains("materials") && v.get("materials").is<picojson::object>()) {
const picojson::object &root = v.get("materials").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Material material;
if (!ParseMaterial(material, err, (it->second).get<picojson::object>())) {
return false;
}
scene.materials[it->first] = material;
}
}
// 9. Parse Image
if (v.contains("images") && v.get("images").is<picojson::object>()) {
const picojson::object &root = v.get("images").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Image image;
if (!ParseImage(image, err, (it->second).get<picojson::object>(),
baseDir)) {
return false;
}
scene.images[it->first] = image;
}
}
// 9. Parse Texture
if (v.contains("textures") && v.get("textures").is<picojson::object>()) {
const picojson::object &root = v.get("textures").get<picojson::object>();
picojson::object::const_iterator it(root.begin());
picojson::object::const_iterator itEnd(root.end());
for (; it != itEnd; it++) {
Texture texture;
if (!ParseTexture(texture, err, (it->second).get<picojson::object>(),
baseDir)) {
return false;
}
scene.textures[it->first] = texture;
}
}
return true;
}
bool TinyGLTFLoader::LoadFromFile(Scene &scene, std::string &err,
const std::string &filename) {
std::stringstream ss;
std::ifstream f(filename.c_str());
if (!f) {
ss << "Failed to open file: " << filename << std::endl;
err = ss.str();
return false;
}
f.seekg(0, f.end);
size_t sz = f.tellg();
std::vector<char> buf(sz);
f.seekg(0, f.beg);
f.read(&buf.at(0), sz);
f.close();
std::string basedir = GetBaseDir(filename);
bool ret = LoadFromString(scene, err, &buf.at(0), buf.size(), basedir);
return ret;
}
#endif // TINYGLTF_LOADER_IMPLEMENTATION
#endif // TINY_GLTF_LOADER_H
Copyright (c) 2016, Syoyo Fujita
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Copyright (c) 2016, Syoyo Fujita
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment