-
Notifications
You must be signed in to change notification settings - Fork 364
/
HoudiniMaterialTranslator.cpp
executable file
·3786 lines (3208 loc) · 130 KB
/
HoudiniMaterialTranslator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) <2021> Side Effects Software Inc.
* 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. The name of Side Effects Software may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "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 SIDE EFFECTS SOFTWARE 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.
*/
#include "HoudiniMaterialTranslator.h"
#include "HoudiniApi.h"
#include "HoudiniEngine.h"
#include "HoudiniEngineUtils.h"
#include "HoudiniEngineString.h"
#include "HoudiniEnginePrivatePCH.h"
#include "HoudiniGenericAttribute.h"
#include "HoudiniPackageParams.h"
#include "HoudiniMeshTranslator.h"
#include "Materials/Material.h"
#include "Materials/MaterialInstance.h"
#include "Materials/MaterialInstanceConstant.h"
#include "PhysicalMaterials/PhysicalMaterial.h"
#include "Materials/MaterialExpressionTextureSample.h"
#include "Materials/MaterialExpressionTextureCoordinate.h"
#include "Materials/MaterialExpressionConstant4Vector.h"
#include "Materials/MaterialExpressionConstant.h"
#include "Materials/MaterialExpressionMultiply.h"
#include "Materials/MaterialExpressionVertexColor.h"
#include "Materials/MaterialExpressionTextureSampleParameter2D.h"
#include "Materials/MaterialExpressionVectorParameter.h"
#include "Materials/MaterialExpressionScalarParameter.h"
#include "ImageUtils.h"
#include "PackageTools.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "UObject/MetaData.h"
#if ENGINE_MINOR_VERSION > 1
#include "MaterialShared.h"
#endif
#include "Engine/Texture2D.h"
#if WITH_EDITOR
#include "Factories/MaterialFactoryNew.h"
#include "Factories/MaterialInstanceConstantFactoryNew.h"
#endif
const int32 FHoudiniMaterialTranslator::MaterialExpressionNodeX = -400;
const int32 FHoudiniMaterialTranslator::MaterialExpressionNodeY = -150;
const int32 FHoudiniMaterialTranslator::MaterialExpressionNodeStepX = 220;
const int32 FHoudiniMaterialTranslator::MaterialExpressionNodeStepY = 220;
bool
FHoudiniMaterialTranslator::CreateHoudiniMaterials(
const HAPI_NodeId& InAssetId,
const FHoudiniPackageParams& InPackageParams,
const TArray<int32>& InUniqueMaterialIds,
const TArray<HAPI_MaterialInfo>& InUniqueMaterialInfos,
const TMap<FString, UMaterialInterface *>& InMaterials,
const TMap<FString, UMaterialInterface *>& InAllOutputMaterials,
TMap<FString, UMaterialInterface *>& OutMaterials,
TArray<UPackage*>& OutPackages,
const bool& bForceRecookAll,
bool bInTreatExistingMaterialsAsUpToDate)
{
TRACE_CPUPROFILER_EVENT_SCOPE(TEXT("FHoudiniMaterialTranslator::CreateHoudiniMaterials"));
if (InUniqueMaterialIds.Num() <= 0)
return false;
if (InUniqueMaterialInfos.Num() != InUniqueMaterialIds.Num())
return false;
// Empty returned materials.
OutMaterials.Empty();
// Update context for generated materials (will trigger when object goes out of scope).
FMaterialUpdateContext MaterialUpdateContext;
// Default Houdini material.
UMaterial * DefaultMaterial = FHoudiniEngine::Get().GetHoudiniDefaultMaterial().Get();
OutMaterials.Add(HAPI_UNREAL_DEFAULT_MATERIAL_NAME, DefaultMaterial);
// Factory to create materials.
UMaterialFactoryNew * MaterialFactory = NewObject<UMaterialFactoryNew>();
MaterialFactory->AddToRoot();
for (int32 MaterialIdx = 0; MaterialIdx < InUniqueMaterialIds.Num(); MaterialIdx++)
{
HAPI_NodeId MaterialId = (HAPI_NodeId)InUniqueMaterialIds[MaterialIdx];
const HAPI_MaterialInfo& MaterialInfo = InUniqueMaterialInfos[MaterialIdx];
if (!MaterialInfo.exists)
{
// The material does not exist,
// we will use the default Houdini material in this case.
continue;
}
// Get the material node's node information.
HAPI_NodeInfo NodeInfo;
FHoudiniApi::NodeInfo_Init(&NodeInfo);
if (HAPI_RESULT_SUCCESS != FHoudiniApi::GetNodeInfo(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, &NodeInfo))
{
continue;
}
FString MaterialName = TEXT("");
if (!FHoudiniEngineString::ToFString(NodeInfo.nameSH, MaterialName))
{
// shouldnt happen, give a generic name
HOUDINI_LOG_WARNING(TEXT("Failed to retrieve material name!"));
MaterialName = TEXT("Material_") + FString::FromInt(MaterialInfo.nodeId);
}
FString MaterialPathName = TEXT("");
if (!FHoudiniMaterialTranslator::GetMaterialRelativePath(InAssetId, MaterialInfo, MaterialPathName))
continue;
// Check first in the existing material map
UMaterial * Material = nullptr;
UMaterialInterface* const * FoundMaterial = InMaterials.Find(MaterialPathName);
bool bCanReuseExistingMaterial = false;
if (FoundMaterial)
{
bCanReuseExistingMaterial = (bInTreatExistingMaterialsAsUpToDate || !MaterialInfo.hasChanged) && !bForceRecookAll;
Material = Cast<UMaterial>(*FoundMaterial);
}
if(!Material || !bCanReuseExistingMaterial)
{
// Try to see if another output/part of this HDA has already recreated this material
// Since those materials have just been recreated, they are considered up to date and can always be reused.
FoundMaterial = InAllOutputMaterials.Find(MaterialPathName);
if (FoundMaterial)
{
Material = Cast<UMaterial>(*FoundMaterial);
bCanReuseExistingMaterial = true;
}
}
// Check that the existing material is in the expected directory (temp folder could have been changed between
// cooks).
if (IsValid(Material) && !InPackageParams.HasMatchingPackageDirectories(Material))
{
bCanReuseExistingMaterial = false;
Material = nullptr;
}
bool bCreatedNewMaterial = false;
if (IsValid(Material))
{
// If the cached material exists and is up to date, we can reuse it.
if (bCanReuseExistingMaterial)
{
OutMaterials.Add(MaterialPathName, Material);
continue;
}
}
else
{
// Previous Material was not found, we need to create a new one.
EObjectFlags ObjFlags = RF_Public | RF_Standalone;
// Create material package and get material name.
FString MaterialPackageName;
UPackage * MaterialPackage = FHoudiniMaterialTranslator::CreatePackageForMaterial(
MaterialInfo.nodeId, MaterialName, InPackageParams, MaterialPackageName);
Material = (UMaterial *)MaterialFactory->FactoryCreateNew(
UMaterial::StaticClass(), MaterialPackage, *MaterialPackageName, ObjFlags, NULL, GWarn);
// Add meta information to this package.
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
MaterialPackage, Material, HAPI_UNREAL_PACKAGE_META_GENERATED_OBJECT, TEXT("true"));
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
MaterialPackage, Material, HAPI_UNREAL_PACKAGE_META_GENERATED_NAME, *MaterialName);
bCreatedNewMaterial = true;
}
if (!IsValid(Material))
continue;
// Get the asset name from the package params
FString AssetName = InPackageParams.HoudiniAssetName.IsEmpty() ? TEXT("HoudiniAsset") : InPackageParams.HoudiniAssetName;
// Get the package and add it to our list
UPackage* Package = Material->GetOutermost();
OutPackages.AddUnique(Package);
/*
// TODO: This should be handled in the mesh/instance translator
// If this is an instancer material, enable the instancing flag.
if (UniqueInstancerMaterialIds.Contains(MaterialId))
Material->bUsedWithInstancedStaticMeshes = true;
*/
// Reset material expressions.
#if ENGINE_MINOR_VERSION < 1
Material->Expressions.Empty();
#else
Material->GetExpressionCollection().Empty();
#endif
// Generate various components for this material.
bool bMaterialComponentCreated = false;
int32 MaterialNodeY = FHoudiniMaterialTranslator::MaterialExpressionNodeY;
// By default we mark material as opaque. Some of component creators can change this.
Material->BlendMode = BLEND_Opaque;
// Extract diffuse plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentDiffuse(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Extract metallic plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentMetallic(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Extract specular plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentSpecular(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Extract roughness plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentRoughness(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Extract emissive plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentEmissive(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Extract opacity plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentOpacity(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Extract opacity mask plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentOpacityMask(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Extract normal plane.
bMaterialComponentCreated |= FHoudiniMaterialTranslator::CreateMaterialComponentNormal(
InAssetId, AssetName, MaterialInfo, InPackageParams, Material, OutPackages, MaterialNodeY);
// Set other material properties.
Material->TwoSided = true;
Material->SetShadingModel(MSM_DefaultLit);
// Schedule this material for update.
MaterialUpdateContext.AddMaterial(Material);
// Cache material.
OutMaterials.Add(MaterialPathName, Material);
// Propagate and trigger material updates.
if (bCreatedNewMaterial)
FAssetRegistryModule::AssetCreated(Material);
Material->PreEditChange(nullptr);
Material->PostEditChange();
Material->MarkPackageDirty();
}
MaterialFactory->RemoveFromRoot();
return true;
}
//
bool
FHoudiniMaterialTranslator::CreateMaterialInstances(
const FHoudiniGeoPartObject& InHGPO,
const FHoudiniPackageParams& InPackageParams,
const TMap<FString, int32>& UniqueMaterialInstanceOverrides,
const TArray<UPackage*>& InPackages,
const TMap<FString, UMaterialInterface *>& InMaterials,
TMap<FString, UMaterialInterface *>& OutMaterials,
const bool& bForceRecookAll)
{
// Check the node ID is valid
if (InHGPO.AssetId < 0)
return false;
// No material instance attributes
if (UniqueMaterialInstanceOverrides.Num() <= 0)
return false;
// See if we need to override some of the material instance's parameters
TArray<FHoudiniGenericAttribute> DetailMatParams;
// Get the detail material parameters
int32 ParamCount = FHoudiniEngineUtils::GetGenericAttributeList(
InHGPO.GeoId, InHGPO.PartId, HAPI_UNREAL_ATTRIB_GENERIC_MAT_PARAM_PREFIX,
DetailMatParams, HAPI_ATTROWNER_DETAIL, -1);
// TODO: Improve!
// Get the material name from the material_instance attribute
// Since the material instance attribute can be set per primitive, it's going to be very difficult to know
// exactly where to look for the nth material instance. In order for the material slot to be created,
// we used the fact that the material instance attribute had to be different
// This is pretty hacky and we should probably require an extra material_instance_index attribute instead.
// as we can only create one instance of the same material, and cant get two slots for the same "source" material.
int32 MaterialIndex = 0;
for (TMap<FString, int32>::TConstIterator Iter(UniqueMaterialInstanceOverrides); Iter; ++Iter)
{
FString CurrentSourceMaterial = Iter->Key;
int32 SlotIndex = MaterialIndex;
FHoudiniMeshTranslator::ExtractMaterialIndex(CurrentSourceMaterial, SlotIndex);
if (CurrentSourceMaterial.IsEmpty())
continue;
// Try to find the material we want to create an instance of
UMaterialInterface* CurrentSourceMaterialInterface = Cast<UMaterialInterface>(
StaticLoadObject(UMaterialInterface::StaticClass(), nullptr, *CurrentSourceMaterial, nullptr, LOAD_NoWarn, nullptr));
if (!IsValid(CurrentSourceMaterialInterface))
{
// Couldn't find the source material
HOUDINI_LOG_WARNING(TEXT("Couldn't find the source material %s to create a material instance."), *CurrentSourceMaterial);
continue;
}
// Create/Retrieve the package for the MI
FString MaterialInstanceName;
FString MaterialInstanceNamePrefix = UPackageTools::SanitizePackageName(
CurrentSourceMaterialInterface->GetName() + TEXT("_instance_") + FString::FromInt(MaterialIndex));
// Increase the material index
MaterialIndex++;
// See if we can find an existing package for that instance
UPackage * MaterialInstancePackage = nullptr;
UMaterialInterface * const * FoundMatPtr = InMaterials.Find(MaterialInstanceNamePrefix);
if (FoundMatPtr && *FoundMatPtr)
{
// We found an already existing MI, get its package
MaterialInstancePackage = Cast<UPackage>((*FoundMatPtr)->GetOuter());
}
if (MaterialInstancePackage)
{
MaterialInstanceName = MaterialInstancePackage->GetName();
}
else
{
// We couldnt find the corresponding M_I package, so create a new one
MaterialInstancePackage = CreatePackageForMaterial(InHGPO.AssetId, MaterialInstanceNamePrefix, InPackageParams, MaterialInstanceName);
}
// Couldn't create a package for that Material Instance
if (!MaterialInstancePackage)
continue;
bool bNewMaterialCreated = false;
UMaterialInstanceConstant* NewMaterialInstance = LoadObject<UMaterialInstanceConstant>(MaterialInstancePackage, *MaterialInstanceName, nullptr, LOAD_None, nullptr);
if (!NewMaterialInstance)
{
// Factory to create materials.
UMaterialInstanceConstantFactoryNew* MaterialInstanceFactory = NewObject< UMaterialInstanceConstantFactoryNew >();
if (!MaterialInstanceFactory)
continue;
// Create the new material instance
MaterialInstanceFactory->AddToRoot();
MaterialInstanceFactory->InitialParent = CurrentSourceMaterialInterface;
NewMaterialInstance = (UMaterialInstanceConstant*)MaterialInstanceFactory->FactoryCreateNew(
UMaterialInstanceConstant::StaticClass(), MaterialInstancePackage, FName(*MaterialInstanceName),
RF_Public | RF_Standalone, NULL, GWarn);
if (NewMaterialInstance)
bNewMaterialCreated = true;
MaterialInstanceFactory->RemoveFromRoot();
}
if (!NewMaterialInstance)
{
HOUDINI_LOG_WARNING(TEXT("Couldn't access the material instance for %s"), *CurrentSourceMaterial);
continue;
}
// Update context for generated materials (will trigger when the object goes out of scope).
FMaterialUpdateContext MaterialUpdateContext;
bool bModifiedMaterialParameters = false;
TArray<FHoudiniGenericAttribute> AllMatParams = DetailMatParams;
// Then the primitive material parameters
int32 MaterialIndexToAttributeIndex = Iter->Value;
ParamCount += FHoudiniEngineUtils::GetGenericAttributeList(
InHGPO.GeoId, InHGPO.PartId, HAPI_UNREAL_ATTRIB_GENERIC_MAT_PARAM_PREFIX,
AllMatParams, HAPI_ATTROWNER_PRIM, MaterialIndexToAttributeIndex);
for (int32 ParamIdx = 0; ParamIdx < AllMatParams.Num(); ParamIdx++)
{
FHoudiniGenericAttribute& ParamOverride = AllMatParams[ParamIdx];
FString& AttribName = ParamOverride.AttributeName;
// If no index specified, assume it applies to all mats
int32 OverrideIndex = MaterialIndex - 1;
int32 TentativeIndex = 0;
char CurChar = AttribName[0];
int32 AttribNameIndex = 0;
while (CurChar >= '0' && CurChar <= '9')
{
TentativeIndex *= 10;
TentativeIndex += CurChar - '0';
CurChar = AttribName[++AttribNameIndex];
}
if (CurChar == '_')
{
AttribName = AttribName.Mid(AttribNameIndex + 1);
OverrideIndex = TentativeIndex;
}
if (OverrideIndex != MaterialIndex - 1)
{
continue;
}
// Try to update the material instance parameter corresponding to the attribute
if (UpdateMaterialInstanceParameter(ParamOverride, NewMaterialInstance, InPackages))
bModifiedMaterialParameters = true;
}
// Schedule this material for update if needed.
if (bNewMaterialCreated || bModifiedMaterialParameters)
MaterialUpdateContext.AddMaterialInstance(NewMaterialInstance);
if (bNewMaterialCreated)
{
// Add meta information to this package.
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
MaterialInstancePackage, NewMaterialInstance, HAPI_UNREAL_PACKAGE_META_GENERATED_OBJECT, TEXT("true"));
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
MaterialInstancePackage, NewMaterialInstance, HAPI_UNREAL_PACKAGE_META_GENERATED_NAME, *MaterialInstanceName);
// Notify registry that we have created a new material.
FAssetRegistryModule::AssetCreated(NewMaterialInstance);
}
if (bNewMaterialCreated || bModifiedMaterialParameters)
{
// Dirty the material
NewMaterialInstance->MarkPackageDirty();
// Update the material instance
NewMaterialInstance->InitStaticPermutation();
NewMaterialInstance->PreEditChange(nullptr);
NewMaterialInstance->PostEditChange();
/*
// Automatically save the package to avoid further issue
MaterialInstancePackage->SetDirtyFlag( true );
MaterialInstancePackage->FullyLoad();
UPackage::SavePackage(
MaterialInstancePackage, nullptr, EObjectFlags::RF_Public | EObjectFlags::RF_Standalone,
*FPackageName::LongPackageNameToFilename( MaterialInstancePackage->GetName(), FPackageName::GetAssetPackageExtension() ) );
*/
}
// Add the created material to the output assignement map
// Use the "source" material name as we want the instance to replace it
OutMaterials.Add(CurrentSourceMaterial, NewMaterialInstance);
}
return true;
}
bool FHoudiniMaterialTranslator::SortUniqueFaceMaterialOverridesAndCreateMaterialInstances(
const TArray<FString>& Materials,
const FHoudiniGeoPartObject& InHGPO,
const FHoudiniPackageParams& InPackageParams,
const TArray<UPackage*>& InPackages,
const TMap<FString, UMaterialInterface*>& InMaterials,
TMap<FString, UMaterialInterface*>& OutMaterials,
const bool& bForceRecookAll)
{
// Map containing unique face materials override attribute
// and their first valid prim index
// We create only one material instance per attribute
TMap<FString, int32> UniqueFaceMaterialOverrides;
for (int FaceIdx = 0; FaceIdx < Materials.Num(); FaceIdx++)
{
FString MatOverrideAttr = Materials[FaceIdx];
if (UniqueFaceMaterialOverrides.Contains(MatOverrideAttr))
continue;
// Add the material override and face index to the map
UniqueFaceMaterialOverrides.Add(MatOverrideAttr, FaceIdx);
}
return FHoudiniMaterialTranslator::CreateMaterialInstances(
InHGPO, InPackageParams,
UniqueFaceMaterialOverrides, InPackages,
InMaterials, OutMaterials,
bForceRecookAll);
}
bool
FHoudiniMaterialTranslator::GetMaterialRelativePath(const HAPI_NodeId& InAssetId, const HAPI_NodeId& InMaterialNodeId, FString& OutRelativePath)
{
HAPI_MaterialInfo MaterialInfo;
FHoudiniApi::MaterialInfo_Init(&MaterialInfo);
HOUDINI_CHECK_ERROR_RETURN(FHoudiniApi::GetMaterialInfo(
FHoudiniEngine::Get().GetSession(), InMaterialNodeId,
&MaterialInfo), false);
return GetMaterialRelativePath(InAssetId, MaterialInfo, OutRelativePath);
}
bool
FHoudiniMaterialTranslator::GetMaterialRelativePath(const HAPI_NodeId& InAssetId, const HAPI_MaterialInfo& InMaterialInfo, FString& OutRelativePath)
{
if (InAssetId < 0 || !InMaterialInfo.exists)
return false;
// We want to get the asset node path so we can remove it from the material name
FString AssetNodeName = TEXT("");
{
HAPI_AssetInfo AssetInfo;
FHoudiniApi::AssetInfo_Init(&AssetInfo);
HOUDINI_CHECK_ERROR_RETURN(FHoudiniApi::GetAssetInfo(
FHoudiniEngine::Get().GetSession(), InAssetId, &AssetInfo), false);
HAPI_NodeInfo AssetNodeInfo;
FHoudiniApi::NodeInfo_Init(&AssetNodeInfo);
HOUDINI_CHECK_ERROR_RETURN(FHoudiniApi::GetNodeInfo(
FHoudiniEngine::Get().GetSession(), AssetInfo.nodeId, &AssetNodeInfo), false);
FHoudiniEngineString::ToFString(AssetNodeInfo.internalNodePathSH, AssetNodeName);
}
// Get the material name from the info
FString MaterialNodeName = TEXT("");
{
HAPI_NodeInfo MaterialNodeInfo;
FHoudiniApi::NodeInfo_Init(&MaterialNodeInfo);
HOUDINI_CHECK_ERROR_RETURN(FHoudiniApi::GetNodeInfo(
FHoudiniEngine::Get().GetSession(), InMaterialInfo.nodeId, &MaterialNodeInfo), false);
FHoudiniEngineString::ToFString(MaterialNodeInfo.internalNodePathSH, MaterialNodeName);
}
if (AssetNodeName.Len() > 0 && MaterialNodeName.Len() > 0)
{
// Remove AssetNodeName part from MaterialNodeName. Extra position is for separator.
OutRelativePath = MaterialNodeName.Mid(AssetNodeName.Len() + 1);
return true;
}
return false;
}
UPackage*
FHoudiniMaterialTranslator::CreatePackageForMaterial(
const HAPI_NodeId& InMaterialNodeId,
const FString& InMaterialName,
const FHoudiniPackageParams& InPackageParams,
FString& OutMaterialName)
{
FString MaterialDescriptor = TEXT("_material_") + FString::FromInt(InMaterialNodeId) + TEXT("_") + InMaterialName;
FHoudiniPackageParams MyPackageParams = InPackageParams;
if (!MyPackageParams.ObjectName.IsEmpty())
{
MyPackageParams.ObjectName += MaterialDescriptor;
}
else if (!MyPackageParams.HoudiniAssetName.IsEmpty())
{
MyPackageParams.ObjectName = MyPackageParams.HoudiniAssetName + MaterialDescriptor;
}
else
{
MyPackageParams.ObjectName = MaterialDescriptor;
}
MyPackageParams.PackageMode = FHoudiniPackageParams::GetDefaultMaterialAndTextureCookMode();
return MyPackageParams.CreatePackageForObject(OutMaterialName);
}
UPackage*
FHoudiniMaterialTranslator::CreatePackageForTexture(
const HAPI_NodeId& InMaterialNodeId,
const FString& InTextureType,
const FHoudiniPackageParams& InPackageParams,
FString& OutTextureName)
{
FString TextureInfoDescriptor = TEXT("_texture_") + FString::FromInt(InMaterialNodeId) + TEXT("_") + InTextureType;
FHoudiniPackageParams MyPackageParams = InPackageParams;
if (!MyPackageParams.ObjectName.IsEmpty())
{
MyPackageParams.ObjectName += TextureInfoDescriptor;
}
else if (!MyPackageParams.HoudiniAssetName.IsEmpty())
{
MyPackageParams.ObjectName = MyPackageParams.HoudiniAssetName + TextureInfoDescriptor;
}
else
{
MyPackageParams.ObjectName = TextureInfoDescriptor;
}
MyPackageParams.PackageMode = FHoudiniPackageParams::GetDefaultMaterialAndTextureCookMode();
return MyPackageParams.CreatePackageForObject(OutTextureName);
}
UTexture2D *
FHoudiniMaterialTranslator::CreateUnrealTexture(
UTexture2D* ExistingTexture,
const HAPI_ImageInfo& ImageInfo,
UPackage* Package,
const FString& TextureName,
const TArray<char>& ImageBuffer,
const FCreateTexture2DParameters& TextureParameters,
const TextureGroup& LODGroup,
const FString& TextureType,
const FString& NodePath)
{
if (!IsValid(Package))
return nullptr;
UTexture2D * Texture = nullptr;
if (ExistingTexture)
{
Texture = ExistingTexture;
}
else
{
// Create new texture object.
Texture = NewObject< UTexture2D >(
Package, UTexture2D::StaticClass(), *TextureName,
RF_Transactional);
// Assign texture group.
Texture->LODGroup = LODGroup;
}
// Add/Update meta information to package.
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
Package, Texture, HAPI_UNREAL_PACKAGE_META_GENERATED_OBJECT, TEXT("true"));
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
Package, Texture, HAPI_UNREAL_PACKAGE_META_GENERATED_NAME, *TextureName);
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
Package, Texture, HAPI_UNREAL_PACKAGE_META_GENERATED_TEXTURE_TYPE, *TextureType);
FHoudiniEngineUtils::AddHoudiniMetaInformationToPackage(
Package, Texture, HAPI_UNREAL_PACKAGE_META_NODE_PATH, *NodePath);
// Initialize texture source.
Texture->Source.Init(ImageInfo.xRes, ImageInfo.yRes, 1, 1, TSF_BGRA8);
// Lock the texture.
uint8 * MipData = Texture->Source.LockMip(0);
// Create base map.
uint8* DestPtr = nullptr;
uint32 SrcWidth = ImageInfo.xRes;
uint32 SrcHeight = ImageInfo.yRes;
const char * SrcData = &ImageBuffer[0];
// Handle the different packing for the source Houdini texture
uint32 PackOffset = 4;
uint32 OffsetR = 0;
uint32 OffsetG = 1;
uint32 OffsetB = 2;
uint32 OffsetA = 3;
switch (ImageInfo.packing)
{
case HAPI_IMAGE_PACKING_SINGLE:
PackOffset = 1;
OffsetR = 0;
OffsetG = 0;
OffsetB = 0;
OffsetA = 0;
break;
case HAPI_IMAGE_PACKING_DUAL:
PackOffset = 2;
OffsetR = 0;
OffsetG = 1;
OffsetB = 1;
OffsetA = 0;
break;
case HAPI_IMAGE_PACKING_RGB:
PackOffset = 3;
OffsetR = 0;
OffsetG = 1;
OffsetB = 2;
OffsetA = 0;
break;
case HAPI_IMAGE_PACKING_BGR:
PackOffset = 3;
OffsetR = 2;
OffsetG = 1;
OffsetB = 0;
OffsetA = 0;
break;
case HAPI_IMAGE_PACKING_RGBA:
PackOffset = 4;
OffsetR = 0;
OffsetG = 1;
OffsetB = 2;
OffsetA = 3;
break;
case HAPI_IMAGE_PACKING_ABGR:
PackOffset = 4;
OffsetR = 3;
OffsetG = 2;
OffsetB = 1;
OffsetA = 0;
break;
case HAPI_IMAGE_PACKING_UNKNOWN:
case HAPI_IMAGE_PACKING_MAX:
// invalid packing
HOUDINI_CHECK_RETURN(false, nullptr);
break;
}
for (uint32 y = 0; y < SrcHeight; y++)
{
DestPtr = &MipData[(SrcHeight - 1 - y) * SrcWidth * sizeof(FColor)];
for (uint32 x = 0; x < SrcWidth; x++)
{
uint32 DataOffset = y * SrcWidth * PackOffset + x * PackOffset;
*DestPtr++ = *(uint8*)(SrcData + DataOffset + OffsetB); // B
*DestPtr++ = *(uint8*)(SrcData + DataOffset + OffsetG); // G
*DestPtr++ = *(uint8*)(SrcData + DataOffset + OffsetR); // R
if (TextureParameters.bUseAlpha && PackOffset == 4)
*DestPtr++ = *(uint8*)(SrcData + DataOffset + OffsetA); // A
else
*DestPtr++ = 0xFF;
}
}
bool bHasAlphaValue = false;
if (TextureParameters.bUseAlpha)
{
// See if there is an actual alpha value in the texture or if we can ignore the texture alpha
for (uint32 y = 0; y < SrcHeight; y++)
{
for (uint32 x = 0; x < SrcWidth; x++)
{
uint32 DataOffset = y * SrcWidth * 4 + x * 4;
if (*(uint8*)(SrcData + DataOffset + 3) != 0xFF)
{
bHasAlphaValue = true;
break;
}
}
if (bHasAlphaValue)
break;
}
}
// Unlock the texture.
Texture->Source.UnlockMip(0);
// Texture creation parameters.
Texture->SRGB = TextureParameters.bSRGB;
Texture->CompressionSettings = TextureParameters.CompressionSettings;
Texture->CompressionNoAlpha = !bHasAlphaValue;
Texture->DeferCompression = TextureParameters.bDeferCompression;
// Set the Source Guid/Hash if specified.
/*
if ( TextureParameters.SourceGuidHash.IsValid() )
{
Texture->Source.SetId( TextureParameters.SourceGuidHash, true );
}
*/
Texture->PostEditChange();
return Texture;
}
bool
FHoudiniMaterialTranslator::HapiExtractImage(
const HAPI_ParmId& NodeParmId,
const HAPI_MaterialInfo& MaterialInfo,
const char * PlaneType,
const HAPI_ImageDataFormat& ImageDataFormat,
HAPI_ImagePacking ImagePacking,
bool bRenderToImage,
TArray<char>& OutImageBuffer )
{
if (bRenderToImage)
{
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::RenderTextureToImage(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, NodeParmId), false);
}
HAPI_ImageInfo ImageInfo;
FHoudiniApi::ImageInfo_Init(&ImageInfo);
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::GetImageInfo(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, &ImageInfo), false);
ImageInfo.dataFormat = ImageDataFormat;
ImageInfo.interleaved = true;
ImageInfo.packing = ImagePacking;
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::SetImageInfo(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, &ImageInfo), false);
int32 ImageBufferSize = 0;
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::ExtractImageToMemory(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, HAPI_RAW_FORMAT_NAME,
PlaneType, &ImageBufferSize), false);
if (ImageBufferSize <= 0)
return false;
OutImageBuffer.SetNumUninitialized(ImageBufferSize);
HOUDINI_CHECK_ERROR_RETURN(FHoudiniApi::GetImageMemoryBuffer(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, &OutImageBuffer[0],
ImageBufferSize), false);
return true;
}
bool
FHoudiniMaterialTranslator::HapiGetImagePlanes(
const HAPI_ParmId& NodeParmId, const HAPI_MaterialInfo& MaterialInfo, TArray<FString>& OutImagePlanes)
{
OutImagePlanes.Empty();
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::RenderTextureToImage(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, NodeParmId), false);
int32 ImagePlaneCount = 0;
HOUDINI_CHECK_ERROR_RETURN(FHoudiniApi::GetImagePlaneCount(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, &ImagePlaneCount), false);
if (ImagePlaneCount <= 0)
return true;
TArray<HAPI_StringHandle> ImagePlaneStringHandles;
ImagePlaneStringHandles.SetNumZeroed(ImagePlaneCount);
HOUDINI_CHECK_ERROR_RETURN(FHoudiniApi::GetImagePlanes(
FHoudiniEngine::Get().GetSession(),
MaterialInfo.nodeId, &ImagePlaneStringHandles[0], ImagePlaneCount), false);
FHoudiniEngineString::SHArrayToFStringArray(ImagePlaneStringHandles, OutImagePlanes);
return true;
}
UMaterialExpression *
FHoudiniMaterialTranslator::MaterialLocateExpression(UMaterialExpression* Expression, UClass* ExpressionClass)
{
if (!Expression)
return nullptr;
#if WITH_EDITOR
if (ExpressionClass == Expression->GetClass())
return Expression;
// If this is a channel multiply expression, we can recurse.
UMaterialExpressionMultiply * MaterialExpressionMultiply = Cast< UMaterialExpressionMultiply >(Expression);
if (MaterialExpressionMultiply)
{
{
UMaterialExpression * MaterialExpression = MaterialExpressionMultiply->A.Expression;
if (MaterialExpression)
{
if (MaterialExpression->GetClass() == ExpressionClass)
return MaterialExpression;
MaterialExpression = FHoudiniMaterialTranslator::MaterialLocateExpression(
Cast<UMaterialExpressionMultiply>(MaterialExpression), ExpressionClass);
if (MaterialExpression)
return MaterialExpression;
}
}
{
UMaterialExpression * MaterialExpression = MaterialExpressionMultiply->B.Expression;
if (MaterialExpression)
{
if (MaterialExpression->GetClass() == ExpressionClass)
return MaterialExpression;
MaterialExpression = FHoudiniMaterialTranslator::MaterialLocateExpression(
Cast<UMaterialExpressionMultiply>(MaterialExpression), ExpressionClass);
if (MaterialExpression)
return MaterialExpression;
}
}
}
#endif
return nullptr;
}
void
FHoudiniMaterialTranslator::_AddMaterialExpression(UMaterial* InMaterial, UMaterialExpression* InMatExp)
{
if (!InMaterial || !InMatExp)
return;
// Access to material expressions has changed in UE5.1
#if ENGINE_MINOR_VERSION < 1
InMaterial->Expressions.Add(InMatExp);
#else
InMaterial->GetExpressionCollection().AddExpression(InMatExp);
#endif
}
bool
FHoudiniMaterialTranslator::CreateMaterialComponentDiffuse(
const HAPI_NodeId& InAssetId,
const FString& InHoudiniAssetName,
const HAPI_MaterialInfo& InMaterialInfo,
const FHoudiniPackageParams& InPackageParams,
UMaterial* Material,
TArray<UPackage*>& OutPackages,
int32& MaterialNodeY)
{
if (!IsValid(Material))
return false;
HAPI_Result Result = HAPI_RESULT_SUCCESS;
EObjectFlags ObjectFlag = (InPackageParams.PackageMode == EPackageMode::Bake) ? RF_Standalone : RF_NoFlags;
// Names of generating Houdini parameters.
FString GeneratingParameterNameDiffuseTexture = TEXT("");
FString GeneratingParameterNameUniformColor = TEXT("");
FString GeneratingParameterNameVertexColor = TEXT(HAPI_UNREAL_ATTRIB_COLOR);
// Diffuse texture creation parameters.
FCreateTexture2DParameters CreateTexture2DParameters;
CreateTexture2DParameters.SourceGuidHash = FGuid();
CreateTexture2DParameters.bUseAlpha = false;
CreateTexture2DParameters.CompressionSettings = TC_Default;
CreateTexture2DParameters.bDeferCompression = true;
CreateTexture2DParameters.bSRGB = true;
// Attempt to look up previously created expressions.
#if ENGINE_MINOR_VERSION < 1
FColorMaterialInput& MatDiffuse = Material->BaseColor;
#else
UMaterialEditorOnlyData* MaterialEditorOnly = Material->GetEditorOnlyData();
FColorMaterialInput& MatDiffuse = MaterialEditorOnly->BaseColor;
#endif
// Locate sampling expression.
UMaterialExpressionTextureSampleParameter2D * ExpressionTextureSample =
Cast< UMaterialExpressionTextureSampleParameter2D >(FHoudiniMaterialTranslator::MaterialLocateExpression(
MatDiffuse.Expression, UMaterialExpressionTextureSampleParameter2D::StaticClass()));
// If texture sampling expression does exist, attempt to look up corresponding texture.
UTexture2D * TextureDiffuse = nullptr;
if (IsValid(ExpressionTextureSample))
TextureDiffuse = Cast< UTexture2D >(ExpressionTextureSample->Texture);