RuntimeMeshComponent.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134
  1. // Copyright 2016 Chris Conway (Koderz). All Rights Reserved.
  2. #include "RuntimeMeshComponentPluginPrivatePCH.h"
  3. #include "RuntimeMeshComponent.h"
  4. #include "RuntimeMeshCore.h"
  5. #include "RuntimeMeshGenericVertex.h"
  6. #include "RuntimeMeshVersion.h"
  7. #include "PhysicsEngine/PhysicsSettings.h"
  8. /** Runtime mesh scene proxy */
  9. class FRuntimeMeshSceneProxy : public FPrimitiveSceneProxy
  10. {
  11. private:
  12. // Temporarily holds all section creation data until this proxy is passsed to the RT.
  13. // After this data is applied this array is cleared.
  14. TArray<FRuntimeMeshSectionCreateDataInterface*> SectionCreationData;
  15. public:
  16. FRuntimeMeshSceneProxy(URuntimeMeshComponent* Component)
  17. : FPrimitiveSceneProxy(Component)
  18. , BodySetup(Component->GetBodySetup())
  19. {
  20. bStaticElementsAlwaysUseProxyPrimitiveUniformBuffer = true;
  21. // Get the proxy for all mesh sections
  22. const int32 NumSections = Component->MeshSections.Num();
  23. Sections.AddDefaulted(NumSections);
  24. for (int32 SectionIdx = 0; SectionIdx < NumSections; SectionIdx++)
  25. {
  26. RuntimeMeshSectionPtr& SourceSection = Component->MeshSections[SectionIdx];
  27. if (SourceSection.IsValid())
  28. {
  29. UMaterialInterface* Material = Component->GetMaterial(SectionIdx);
  30. if (Material == nullptr)
  31. {
  32. Material = UMaterial::GetDefaultMaterial(MD_Surface);
  33. }
  34. // Get the section creation data
  35. auto* SectionData = SourceSection->GetSectionCreationData(&GetScene(), Material);
  36. SectionData->SetTargetSection(SectionIdx);
  37. SectionCreationData.Add(SectionData);
  38. }
  39. }
  40. // Update material relevancy information needed to control the rendering.
  41. UpdateMaterialRelevance();
  42. }
  43. virtual ~FRuntimeMeshSceneProxy()
  44. {
  45. for (FRuntimeMeshSectionProxyInterface* Section : Sections)
  46. {
  47. if (Section)
  48. {
  49. delete Section;
  50. }
  51. }
  52. }
  53. void CreateRenderThreadResources() override
  54. {
  55. FPrimitiveSceneProxy::CreateRenderThreadResources();
  56. for (auto Section : SectionCreationData)
  57. {
  58. CreateSection_RenderThread(Section);
  59. }
  60. // The individual items are deleted by CreateSection_RenderThread so just clear the array.
  61. SectionCreationData.Empty();
  62. }
  63. /** Called on render thread to create a new dynamic section. (Static sections are handled differently) */
  64. void CreateSection_RenderThread(FRuntimeMeshSectionCreateDataInterface* SectionData)
  65. {
  66. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_CreateSection_RenderThread);
  67. check(IsInRenderingThread());
  68. check(SectionData);
  69. int32 SectionIndex = SectionData->GetTargetSection();
  70. // Make sure the array is big enough
  71. if (SectionIndex >= Sections.Num())
  72. {
  73. Sections.SetNum(SectionIndex + 1, false);
  74. }
  75. // If a section already exists... destroy it!
  76. if (FRuntimeMeshSectionProxyInterface* Section = Sections[SectionIndex])
  77. {
  78. delete Section;
  79. }
  80. // Get the proxy and finish the creation here on the render thread.
  81. FRuntimeMeshSectionProxyInterface* Section = SectionData->NewProxy;
  82. Section->FinishCreate_RenderThread(SectionData);
  83. // Save ref to new section
  84. Sections[SectionIndex] = Section;
  85. delete SectionData;
  86. // Update material relevancy information needed to control the rendering.
  87. UpdateMaterialRelevance();
  88. }
  89. /** Called on render thread to assign new dynamic data */
  90. void UpdateSection_RenderThread(FRuntimeMeshRenderThreadCommandInterface* SectionData)
  91. {
  92. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateSection_RenderThread);
  93. check(IsInRenderingThread());
  94. check(SectionData);
  95. if (SectionData->GetTargetSection() < Sections.Num() && Sections[SectionData->GetTargetSection()] != nullptr)
  96. {
  97. Sections[SectionData->GetTargetSection()]->FinishUpdate_RenderThread(SectionData);
  98. }
  99. delete SectionData;
  100. }
  101. void UpdateSectionPositionOnly_RenderThread(FRuntimeMeshRenderThreadCommandInterface* SectionData)
  102. {
  103. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateSectionPositionOnly_RenderThread);
  104. check(IsInRenderingThread());
  105. check(SectionData);
  106. if (SectionData->GetTargetSection() < Sections.Num() && Sections[SectionData->GetTargetSection()] != nullptr)
  107. {
  108. Sections[SectionData->GetTargetSection()]->FinishPositionUpdate_RenderThread(SectionData);
  109. }
  110. delete SectionData;
  111. }
  112. void UpdateSectionProperties_RenderThread(FRuntimeMeshRenderThreadCommandInterface* SectionData)
  113. {
  114. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateSectionProperties_RenderThread);
  115. check(IsInRenderingThread());
  116. check(SectionData);
  117. int32 SectionIndex = SectionData->GetTargetSection();
  118. if (SectionIndex < Sections.Num() && Sections[SectionIndex] != nullptr)
  119. {
  120. Sections[SectionIndex]->FinishPropertyUpdate_RenderThread(SectionData);
  121. }
  122. }
  123. void DestroySection_RenderThread(int32 SectionIndex)
  124. {
  125. check(IsInRenderingThread());
  126. if (SectionIndex < Sections.Num() && Sections[SectionIndex] != nullptr)
  127. {
  128. delete Sections[SectionIndex];
  129. Sections[SectionIndex] = nullptr;
  130. }
  131. // Update material relevancy information needed to control the rendering.
  132. UpdateMaterialRelevance();
  133. }
  134. void ApplyBatchUpdate_RenderThread(FRuntimeMeshBatchUpdateData* BatchUpdateData)
  135. {
  136. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_ApplyBatchUpdate_RenderThread);
  137. check(IsInRenderingThread());
  138. check(BatchUpdateData);
  139. // Destroy flagged sections
  140. for (auto& SectionIndex : BatchUpdateData->DestroySections)
  141. {
  142. DestroySection_RenderThread(SectionIndex);
  143. }
  144. // Create new sections
  145. for (auto& SectionToCreate : BatchUpdateData->CreateSections)
  146. {
  147. CreateSection_RenderThread(static_cast<FRuntimeMeshSectionCreateDataInterface*>(SectionToCreate));
  148. }
  149. // Update sections
  150. for (auto& SectionToUpdate : BatchUpdateData->UpdateSections)
  151. {
  152. UpdateSection_RenderThread(SectionToUpdate);
  153. }
  154. // Apply section property updates
  155. for (auto& SectionToUpdate : BatchUpdateData->PropertyUpdateSections)
  156. {
  157. UpdateSectionProperties_RenderThread(SectionToUpdate);
  158. }
  159. delete BatchUpdateData;
  160. }
  161. bool HasDynamicSections() const
  162. {
  163. for (FRuntimeMeshSectionProxyInterface* Section : Sections)
  164. {
  165. if (Section && !Section->WantsToRenderInStaticPath())
  166. {
  167. return true;
  168. }
  169. }
  170. return false;
  171. }
  172. bool HasStaticSections() const
  173. {
  174. for (FRuntimeMeshSectionProxyInterface* Section : Sections)
  175. {
  176. if (Section && Section->WantsToRenderInStaticPath())
  177. {
  178. return true;
  179. }
  180. }
  181. return false;
  182. }
  183. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 11
  184. virtual FPrimitiveViewRelevance GetViewRelevance(const FSceneView* View) const override
  185. #else
  186. virtual FPrimitiveViewRelevance GetViewRelevance(const FSceneView* View) override
  187. #endif
  188. {
  189. FPrimitiveViewRelevance Result;
  190. Result.bDrawRelevance = IsShown(View);
  191. Result.bShadowRelevance = IsShadowCast(View);
  192. bool bForceDynamicPath = IsRichView(*View->Family) || View->Family->EngineShowFlags.Wireframe || IsSelected() || !IsStaticPathAvailable();
  193. Result.bStaticRelevance = !bForceDynamicPath && HasStaticSections();
  194. Result.bDynamicRelevance = bForceDynamicPath || HasDynamicSections();
  195. Result.bRenderInMainPass = ShouldRenderInMainPass();
  196. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 11
  197. Result.bUsesLightingChannels = GetLightingChannelMask() != GetDefaultLightingChannelMask();
  198. #endif
  199. Result.bRenderCustomDepth = ShouldRenderCustomDepth();
  200. MaterialRelevance.SetPrimitiveViewRelevance(Result);
  201. return Result;
  202. }
  203. void CreateMeshBatch(FMeshBatch& MeshBatch, FRuntimeMeshSectionProxyInterface* Section, FMaterialRenderProxy* WireframeMaterial) const
  204. {
  205. Section->CreateMeshBatch(MeshBatch, WireframeMaterial, IsSelected());
  206. MeshBatch.ReverseCulling = IsLocalToWorldDeterminantNegative();
  207. MeshBatch.bCanApplyViewModeOverrides = true;
  208. FMeshBatchElement& BatchElement = MeshBatch.Elements[0];
  209. BatchElement.PrimitiveUniformBufferResource = &GetUniformBuffer();
  210. }
  211. virtual void DrawStaticElements(FStaticPrimitiveDrawInterface* PDI) override
  212. {
  213. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_DrawStaticElements);
  214. for (FRuntimeMeshSectionProxyInterface* Section : Sections)
  215. {
  216. if (Section && Section->ShouldRender() && Section->WantsToRenderInStaticPath())
  217. {
  218. FMeshBatch MeshBatch;
  219. CreateMeshBatch(MeshBatch, Section, nullptr);
  220. PDI->DrawMesh(MeshBatch, FLT_MAX);
  221. }
  222. }
  223. }
  224. virtual void GetDynamicMeshElements(const TArray<const FSceneView*>& Views, const FSceneViewFamily& ViewFamily, uint32 VisibilityMap, FMeshElementCollector& Collector) const override
  225. {
  226. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_GetDynamicMeshElements);
  227. // Set up wireframe material (if needed)
  228. const bool bWireframe = AllowDebugViewmodes() && ViewFamily.EngineShowFlags.Wireframe;
  229. FColoredMaterialRenderProxy* WireframeMaterialInstance = nullptr;
  230. if (bWireframe)
  231. {
  232. WireframeMaterialInstance = new FColoredMaterialRenderProxy(
  233. GEngine->WireframeMaterial ? GEngine->WireframeMaterial->GetRenderProxy(IsSelected()) : nullptr,
  234. FLinearColor(0, 0.5f, 1.f)
  235. );
  236. Collector.RegisterOneFrameMaterialProxy(WireframeMaterialInstance);
  237. }
  238. // Iterate over sections
  239. for (FRuntimeMeshSectionProxyInterface* Section : Sections)
  240. {
  241. if (Section && Section->ShouldRender())
  242. {
  243. // Add the mesh batch to every view it's visible in
  244. for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
  245. {
  246. if (VisibilityMap & (1 << ViewIndex))
  247. {
  248. bool bForceDynamicPath = IsRichView(*Views[ViewIndex]->Family) || Views[ViewIndex]->Family->EngineShowFlags.Wireframe || IsSelected() || !IsStaticPathAvailable();
  249. if (bForceDynamicPath || !Section->WantsToRenderInStaticPath())
  250. {
  251. FMeshBatch& MeshBatch = Collector.AllocateMesh();
  252. CreateMeshBatch(MeshBatch, Section, WireframeMaterialInstance);
  253. Collector.AddMesh(ViewIndex, MeshBatch);
  254. }
  255. }
  256. }
  257. }
  258. }
  259. // Draw bounds
  260. #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
  261. for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
  262. {
  263. if (VisibilityMap & (1 << ViewIndex))
  264. {
  265. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 13
  266. // Draw simple collision as wireframe if 'show collision', and collision is enabled, and we are not using the complex as the simple
  267. if (ViewFamily.EngineShowFlags.Collision && IsCollisionEnabled() && BodySetup->GetCollisionTraceFlag() != ECollisionTraceFlag::CTF_UseComplexAsSimple)
  268. {
  269. FTransform GeomTransform(GetLocalToWorld());
  270. BodySetup->AggGeom.GetAggGeom(GeomTransform, GetSelectionColor(FColor(157, 149, 223, 255), IsSelected(), IsHovered()).ToFColor(true), NULL, false, false, UseEditorDepthTest(), ViewIndex, Collector);
  271. }
  272. #endif
  273. // Render bounds
  274. RenderBounds(Collector.GetPDI(ViewIndex), ViewFamily.EngineShowFlags, GetBounds(), IsSelected());
  275. }
  276. }
  277. #endif
  278. }
  279. virtual bool CanBeOccluded() const override
  280. {
  281. return !MaterialRelevance.bDisableDepthTest;
  282. }
  283. virtual uint32 GetMemoryFootprint(void) const
  284. {
  285. return(sizeof(*this) + GetAllocatedSize());
  286. }
  287. uint32 GetAllocatedSize(void) const
  288. {
  289. return(FPrimitiveSceneProxy::GetAllocatedSize());
  290. }
  291. void UpdateMaterialRelevance()
  292. {
  293. FMaterialRelevance NewMaterialRelevance;
  294. for (FRuntimeMeshSectionProxyInterface* Section : Sections)
  295. {
  296. if (Section)
  297. {
  298. NewMaterialRelevance |= Section->GetMaterialRelevance();
  299. }
  300. }
  301. MaterialRelevance = NewMaterialRelevance;
  302. }
  303. private:
  304. /** Array of sections */
  305. TArray<FRuntimeMeshSectionProxyInterface*> Sections;
  306. UBodySetup* BodySetup;
  307. FMaterialRelevance MaterialRelevance;
  308. };
  309. void FRuntimeMeshComponentPrePhysicsTickFunction::ExecuteTick( float DeltaTime, ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent)
  310. {
  311. /* Ensure target still exists */
  312. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 11
  313. bool bIsValid = Target && !Target->IsPendingKillOrUnreachable();
  314. #else
  315. bool bIsValid = Target && !Target->HasAnyFlags(RF_PendingKill | RF_Unreachable);
  316. #endif
  317. if (bIsValid)
  318. {
  319. FScopeCycleCounterUObject ActorScope(Target);
  320. Target->BakeCollision();
  321. }
  322. }
  323. FString FRuntimeMeshComponentPrePhysicsTickFunction::DiagnosticMessage()
  324. {
  325. return Target->GetFullName() + TEXT("[PrePhysicsTick]");
  326. }
  327. /* Helper for converting an array of FLinearColor to an array of FColors*/
  328. void ConvertLinearColorToFColor(const TArray<FLinearColor>& LinearColors, TArray<FColor>& Colors)
  329. {
  330. Colors.SetNumUninitialized(LinearColors.Num());
  331. for (int32 Index = 0; Index < LinearColors.Num(); Index++)
  332. {
  333. Colors[Index] = LinearColors[Index].ToFColor(false);
  334. }
  335. }
  336. URuntimeMeshComponent::URuntimeMeshComponent(const FObjectInitializer& ObjectInitializer)
  337. : Super(ObjectInitializer)
  338. , bUseComplexAsSimpleCollision(true)
  339. , bShouldSerializeMeshData(true)
  340. , bCollisionDirty(true)
  341. , CollisionMode(ERuntimeMeshCollisionCookingMode::CookingPerformance)
  342. {
  343. // Setup the collision update ticker
  344. PrePhysicsTick.TickGroup = TG_PrePhysics;
  345. PrePhysicsTick.bCanEverTick = true;
  346. PrePhysicsTick.bStartWithTickEnabled = true;
  347. // Reset the batch state
  348. BatchState.ResetBatch();
  349. SetNetAddressable();
  350. }
  351. TSharedPtr<FRuntimeMeshSectionInterface> URuntimeMeshComponent::CreateOrResetSectionLegacyType(int32 SectionIndex, int32 NumUVChannels)
  352. {
  353. if (NumUVChannels == 1)
  354. {
  355. return CreateOrResetSection<FRuntimeMeshSection<FRuntimeMeshVertexSimple>>(SectionIndex, false, true);
  356. }
  357. else if (NumUVChannels == 2)
  358. {
  359. return CreateOrResetSection<FRuntimeMeshSection<FRuntimeMeshVertexDualUV>>(SectionIndex, false, true);
  360. }
  361. else
  362. {
  363. check(false && "Legacy sections only support standard vertex formats wit 1 or 2 uv channels");
  364. return nullptr;
  365. }
  366. }
  367. void URuntimeMeshComponent::CreateSectionInternal(int32 SectionIndex, ESectionUpdateFlags UpdateFlags)
  368. {
  369. RuntimeMeshSectionPtr Section = MeshSections[SectionIndex];
  370. check(Section.IsValid());
  371. // Update normal/tangents if requested...
  372. if (!!(UpdateFlags & ESectionUpdateFlags::CalculateNormalTangent))
  373. {
  374. Section->GenerateNormalTangent();
  375. }
  376. // calculate tessellation if requested...
  377. if (!!(UpdateFlags & ESectionUpdateFlags::CalculateTessellationIndices))
  378. {
  379. Section->GenerateTessellationIndices();
  380. }
  381. // Use the batch update if one is running
  382. if (BatchState.IsBatchPending())
  383. {
  384. // Mark section created
  385. BatchState.MarkSectionCreated(SectionIndex, Section->UpdateFrequency == EUpdateFrequency::Infrequent);
  386. // Flag collision if this section affects it
  387. if (Section->CollisionEnabled)
  388. {
  389. BatchState.MarkCollisionDirty();
  390. }
  391. // Flag bounds update
  392. BatchState.MarkBoundsDirty();
  393. // bail since we don't update directly in this case.
  394. return;
  395. }
  396. // Enqueue the RT command if we already have a SceneProxy
  397. if (SceneProxy && Section->UpdateFrequency != EUpdateFrequency::Infrequent)
  398. {
  399. // Gather all needed update info
  400. auto* SectionData = Section->GetSectionCreationData(GetScene(), GetSectionMaterial(SectionIndex));
  401. SectionData->SetTargetSection(SectionIndex);
  402. // Enqueue update on RT
  403. ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
  404. FRuntimeMeshSectionCreate,
  405. FRuntimeMeshSceneProxy*, RuntimeMeshSceneProxy, (FRuntimeMeshSceneProxy*)SceneProxy,
  406. FRuntimeMeshSectionCreateDataInterface*, SectionData, SectionData,
  407. {
  408. RuntimeMeshSceneProxy->CreateSection_RenderThread(SectionData);
  409. }
  410. );
  411. }
  412. else
  413. {
  414. // Mark the render state dirty so it's recreated when necessary.
  415. MarkRenderStateDirty();
  416. }
  417. // Mark collision dirty so it's re-baked at the end of this frame
  418. if (Section->CollisionEnabled)
  419. {
  420. MarkCollisionDirty();
  421. }
  422. // Update overall bounds
  423. UpdateLocalBounds();
  424. }
  425. void URuntimeMeshComponent::UpdateSectionInternal(int32 SectionIndex, bool bHadVertexPositionsUpdate, bool bHadVertexUpdates, bool bHadIndexUpdates, bool bNeedsBoundsUpdate, ESectionUpdateFlags UpdateFlags)
  426. {
  427. // Ensure that something was updated
  428. check(bHadVertexPositionsUpdate || bHadVertexUpdates || bHadIndexUpdates || bNeedsBoundsUpdate);
  429. check(SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid());
  430. RuntimeMeshSectionPtr Section = MeshSections[SectionIndex];
  431. // Update normal/tangents if requested...
  432. if (!!(UpdateFlags & ESectionUpdateFlags::CalculateNormalTangent))
  433. {
  434. Section->GenerateNormalTangent();
  435. }
  436. // calculate tessellation if requested...
  437. if (!!(UpdateFlags & ESectionUpdateFlags::CalculateTessellationIndices))
  438. {
  439. Section->GenerateTessellationIndices();
  440. }
  441. /* Make sure this is only flagged if the section is dual buffer */
  442. bHadVertexPositionsUpdate = Section->IsDualBufferSection() && bHadVertexPositionsUpdate;
  443. bool bNeedsCollisionUpdate = Section->CollisionEnabled && (bHadVertexPositionsUpdate || (!Section->IsDualBufferSection() && bHadVertexUpdates));
  444. // Use the batch update if one is running
  445. if (BatchState.IsBatchPending())
  446. {
  447. // Mark update for section or promote to proxy recreate if static section
  448. if (Section->UpdateFrequency == EUpdateFrequency::Infrequent)
  449. {
  450. BatchState.MarkRenderStateDirty();
  451. }
  452. else
  453. {
  454. ERuntimeMeshSectionBatchUpdateType UpdateType = ERuntimeMeshSectionBatchUpdateType::None;
  455. UpdateType |= bHadVertexPositionsUpdate ? ERuntimeMeshSectionBatchUpdateType::PositionsUpdate : ERuntimeMeshSectionBatchUpdateType::None;
  456. UpdateType |= bHadVertexUpdates ? ERuntimeMeshSectionBatchUpdateType::VerticesUpdate : ERuntimeMeshSectionBatchUpdateType::None;
  457. UpdateType |= bHadIndexUpdates ? ERuntimeMeshSectionBatchUpdateType::IndicesUpdate : ERuntimeMeshSectionBatchUpdateType::None;
  458. BatchState.MarkUpdateForSection(SectionIndex, UpdateType);
  459. }
  460. // Flag collision if this section affects it
  461. if (bNeedsCollisionUpdate)
  462. {
  463. BatchState.MarkCollisionDirty();
  464. }
  465. // Flag bounds update if needed.
  466. if (bNeedsBoundsUpdate)
  467. {
  468. BatchState.MarkBoundsDirty();
  469. }
  470. // bail since we don't update directly in this case.
  471. return;
  472. }
  473. // Send the update to the render thread if the scene proxy exists
  474. if (SceneProxy && Section->UpdateFrequency != EUpdateFrequency::Infrequent)
  475. {
  476. auto* SectionData = Section->GetSectionUpdateData(bHadVertexPositionsUpdate, bHadVertexUpdates, bHadIndexUpdates);
  477. SectionData->SetTargetSection(SectionIndex);
  478. // Enqueue update on RT
  479. ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
  480. FRuntimeMeshSectionUpdate,
  481. FRuntimeMeshSceneProxy*, RuntimeMeshSceneProxy, (FRuntimeMeshSceneProxy*)SceneProxy,
  482. FRuntimeMeshRenderThreadCommandInterface*, SectionData, SectionData,
  483. {
  484. RuntimeMeshSceneProxy->UpdateSection_RenderThread(SectionData);
  485. }
  486. );
  487. }
  488. else
  489. {
  490. // Mark the renderstate dirty so it's recreated when necessary.
  491. MarkRenderStateDirty();
  492. }
  493. // Mark collision dirty so it's re-baked at the end of this frame
  494. if (bNeedsCollisionUpdate)
  495. {
  496. MarkCollisionDirty();
  497. }
  498. // Update overall bounds if needed
  499. if (bNeedsBoundsUpdate)
  500. {
  501. UpdateLocalBounds();
  502. }
  503. }
  504. void URuntimeMeshComponent::UpdateSectionVertexPositionsInternal(int32 SectionIndex, bool bNeedsBoundsUpdate)
  505. {
  506. check(SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid());
  507. RuntimeMeshSectionPtr Section = MeshSections[SectionIndex];
  508. if (SceneProxy)
  509. {
  510. auto SectionData = Section->GetSectionPositionUpdateData();
  511. SectionData->SetTargetSection(SectionIndex);
  512. // Enqueue command to modify render thread info
  513. ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
  514. FRuntimeMeshSectionPositionUpdate,
  515. FRuntimeMeshSceneProxy*, RuntimeMeshSceneProxy, (FRuntimeMeshSceneProxy*)SceneProxy,
  516. FRuntimeMeshRenderThreadCommandInterface*, SectionData, SectionData,
  517. {
  518. RuntimeMeshSceneProxy->UpdateSectionPositionOnly_RenderThread(SectionData);
  519. }
  520. );
  521. }
  522. else
  523. {
  524. MarkRenderStateDirty();
  525. }
  526. if (bNeedsBoundsUpdate)
  527. {
  528. UpdateLocalBounds();
  529. }
  530. }
  531. void URuntimeMeshComponent::UpdateSectionPropertiesInternal(int32 SectionIndex, bool bUpdateRequiresProxyRecreateIfStatic)
  532. {
  533. check(SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid());
  534. RuntimeMeshSectionPtr Section = MeshSections[SectionIndex];
  535. bool bRequiresRecreate = bUpdateRequiresProxyRecreateIfStatic && Section->UpdateFrequency == EUpdateFrequency::Infrequent;
  536. // Use the batch update if one is running
  537. if (BatchState.IsBatchPending())
  538. {
  539. if (bRequiresRecreate)
  540. {
  541. BatchState.MarkRenderStateDirty();
  542. }
  543. else
  544. {
  545. BatchState.MarkUpdateForSection(SectionIndex, ERuntimeMeshSectionBatchUpdateType::PropertyUpdate);
  546. }
  547. // bail since we don't update directly in this case.
  548. return;
  549. }
  550. if (SceneProxy && !bRequiresRecreate)
  551. {
  552. auto SectionData = new FRuntimeMeshSectionPropertyUpdateData();
  553. SectionData->SetTargetSection(SectionIndex);
  554. SectionData->bIsVisible = Section->bIsVisible;
  555. SectionData->bCastsShadow = Section->bCastsShadow;
  556. // Enqueue command to modify render thread info
  557. ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
  558. FRuntimeMeshSectionPropertyUpdate,
  559. FRuntimeMeshSceneProxy*, RuntimeMeshSceneProxy, (FRuntimeMeshSceneProxy*)SceneProxy,
  560. FRuntimeMeshRenderThreadCommandInterface*, SectionData, SectionData,
  561. {
  562. RuntimeMeshSceneProxy->UpdateSectionProperties_RenderThread(SectionData);
  563. }
  564. );
  565. }
  566. else
  567. {
  568. MarkRenderStateDirty();
  569. }
  570. }
  571. void URuntimeMeshComponent::UpdateMeshSectionPositionsImmediate(int32 SectionIndex, TArray<FVector>& VertexPositions, ESectionUpdateFlags UpdateFlags)
  572. {
  573. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateMeshSectionPositionsImmediate);
  574. // Validate all update parameters
  575. RMC_VALIDATE_UPDATEPARAMETERS_DUALBUFFER(SectionIndex, /*VoidReturn*/);
  576. // Get section
  577. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  578. // Check dual buffer section status
  579. if (VertexPositions.Num() != Section->PositionVertexBuffer.Num())
  580. {
  581. Log(TEXT("UpdateMeshSection() - Positions cannot change length unless the vertexdata is updated as well."), true);
  582. return;
  583. }
  584. bool bShouldUseMove = (UpdateFlags & ESectionUpdateFlags::MoveArrays) != ESectionUpdateFlags::None;
  585. bool bNeedsBoundsUpdate = false;
  586. // Update vertex positions if supplied
  587. bool bUpdatedVertexPositions = false;
  588. if (VertexPositions.Num() > 0)
  589. {
  590. bNeedsBoundsUpdate = Section->UpdateVertexPositionBuffer(VertexPositions, nullptr, bShouldUseMove);
  591. bUpdatedVertexPositions = true;
  592. }
  593. else
  594. {
  595. Log(TEXT("UpdatemeshSection() - Vertex positions empty. They will not be updated."));
  596. }
  597. // Finalize section update if we have anything to apply
  598. if (bUpdatedVertexPositions)
  599. {
  600. UpdateSectionVertexPositionsInternal(SectionIndex, bNeedsBoundsUpdate);
  601. }
  602. }
  603. void URuntimeMeshComponent::UpdateMeshSectionPositionsImmediate(int32 SectionIndex, TArray<FVector>& VertexPositions, const FBox& BoundingBox, ESectionUpdateFlags UpdateFlags)
  604. {
  605. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateMeshSectionPositionsImmediate_WithBoundinBox);
  606. // Validate all update parameters
  607. RMC_VALIDATE_UPDATEPARAMETERS_DUALBUFFER(SectionIndex, /*VoidReturn*/);
  608. // Get section
  609. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  610. // Check dual buffer section status
  611. if (VertexPositions.Num() != Section->PositionVertexBuffer.Num())
  612. {
  613. Log(TEXT("UpdateMeshSection() - Positions cannot change length unless the vertexdata is updated as well."), true);
  614. return;
  615. }
  616. bool bShouldUseMove = (UpdateFlags & ESectionUpdateFlags::MoveArrays) != ESectionUpdateFlags::None;
  617. bool bNeedsBoundsUpdate = false;
  618. // Update vertex positions if supplied
  619. bool bUpdatedVertexPositions = false;
  620. if (VertexPositions.Num() > 0)
  621. {
  622. bNeedsBoundsUpdate = Section->UpdateVertexPositionBuffer(VertexPositions, &BoundingBox, bShouldUseMove);
  623. bUpdatedVertexPositions = true;
  624. }
  625. else
  626. {
  627. Log(TEXT("UpdatemeshSection() - Vertex positions empty. They will not be updated."));
  628. }
  629. // Finalize section update if we have anything to apply
  630. if (bUpdatedVertexPositions)
  631. {
  632. UpdateSectionVertexPositionsInternal(SectionIndex, bNeedsBoundsUpdate);
  633. }
  634. }
  635. TArray<FVector>* URuntimeMeshComponent::BeginMeshSectionPositionUpdate(int32 SectionIndex)
  636. {
  637. // Validate all update parameters
  638. RMC_VALIDATE_UPDATEPARAMETERS_DUALBUFFER(SectionIndex, nullptr);
  639. // Get section
  640. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  641. return &Section->PositionVertexBuffer;
  642. }
  643. void URuntimeMeshComponent::EndMeshSectionPositionUpdate(int32 SectionIndex)
  644. {
  645. // Validate all update parameters
  646. RMC_VALIDATE_UPDATEPARAMETERS_DUALBUFFER(SectionIndex, /*VoidReturn*/);
  647. // TODO: Validate that the position buffer is still the same length
  648. UpdateSectionVertexPositionsInternal(SectionIndex, true);
  649. }
  650. void URuntimeMeshComponent::EndMeshSectionPositionUpdate(int32 SectionIndex, const FBox& BoundingBox)
  651. {
  652. // Validate all update parameters
  653. RMC_VALIDATE_UPDATEPARAMETERS_DUALBUFFER(SectionIndex, /*VoidReturn*/);
  654. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  655. bool bNeedsBoundingBoxUpdate = !(Section->LocalBoundingBox == BoundingBox);
  656. if (bNeedsBoundingBoxUpdate)
  657. {
  658. Section->LocalBoundingBox = BoundingBox;
  659. }
  660. // TODO: Validate that the position buffer is still the same length
  661. UpdateSectionVertexPositionsInternal(SectionIndex, bNeedsBoundingBoxUpdate);
  662. }
  663. void URuntimeMeshComponent::EndMeshSectionUpdate(int32 SectionIndex, ERuntimeMeshBuffer UpdatedBuffers, ESectionUpdateFlags UpdateFlags)
  664. {
  665. // Bail if we have no buffers to update.
  666. if (UpdatedBuffers == ERuntimeMeshBuffer::None)
  667. {
  668. return;
  669. }
  670. // Validate all update parameters
  671. RMC_VALIDATE_UPDATEPARAMETERS(SectionIndex, /*VoidReturn*/);
  672. // Get section and update bounding box
  673. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  674. Section->RecalculateBoundingBox();
  675. // Finalize section update
  676. UpdateSectionInternal(SectionIndex,
  677. !!(UpdatedBuffers & ERuntimeMeshBuffer::Positions),
  678. !!(UpdatedBuffers & ERuntimeMeshBuffer::Vertices),
  679. !!(UpdatedBuffers & ERuntimeMeshBuffer::Triangles), true, UpdateFlags);
  680. }
  681. void URuntimeMeshComponent::EndMeshSectionUpdate(int32 SectionIndex, ERuntimeMeshBuffer UpdatedBuffers, const FBox& BoundingBox, ESectionUpdateFlags UpdateFlags)
  682. {
  683. // Bail if we have no buffers to update.
  684. if (UpdatedBuffers == ERuntimeMeshBuffer::None)
  685. {
  686. return;
  687. }
  688. // Validate all update parameters
  689. RMC_VALIDATE_UPDATEPARAMETERS(SectionIndex, /*VoidReturn*/);
  690. // Get section and update bounding box
  691. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  692. Section->LocalBoundingBox = BoundingBox;
  693. // Finalize section update
  694. UpdateSectionInternal(SectionIndex,
  695. !!(UpdatedBuffers & ERuntimeMeshBuffer::Positions),
  696. !!(UpdatedBuffers & ERuntimeMeshBuffer::Vertices),
  697. !!(UpdatedBuffers & ERuntimeMeshBuffer::Triangles), true, UpdateFlags);
  698. }
  699. void URuntimeMeshComponent::CreateMeshSection(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<int32>& Triangles, const TArray<FVector>& Normals,
  700. const TArray<FVector2D>& UV0, const TArray<FColor>& Colors, const TArray<FRuntimeMeshTangent>& Tangents, bool bCreateCollision, EUpdateFrequency UpdateFrequency,
  701. ESectionUpdateFlags UpdateFlags)
  702. {
  703. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_CreateMeshSection);
  704. // Validate all creation parameters
  705. RMC_VALIDATE_CREATIONPARAMETERS(SectionIndex, Vertices, Triangles, /*VoidReturn*/);
  706. // Create the section
  707. auto NewSection = CreateOrResetSectionLegacyType(SectionIndex, 1);
  708. // Update the mesh data in the section
  709. NewSection->UpdateVertexBufferInternal(Vertices, Normals, Tangents, UV0, TArray<FVector2D>(), Colors);
  710. TArray<int32>& TrianglesRef = const_cast<TArray<int32>&>(Triangles);
  711. NewSection->UpdateIndexBuffer(TrianglesRef, false);
  712. // Track collision status and update collision information if necessary
  713. NewSection->CollisionEnabled = bCreateCollision;
  714. NewSection->UpdateFrequency = UpdateFrequency;
  715. // Finalize section.
  716. CreateSectionInternal(SectionIndex, UpdateFlags);
  717. }
  718. void URuntimeMeshComponent::CreateMeshSection(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<int32>& Triangles, const TArray<FVector>& Normals,
  719. const TArray<FVector2D>& UV0, const TArray<FVector2D>& UV1, const TArray<FColor>& Colors, const TArray<FRuntimeMeshTangent>& Tangents,
  720. bool bCreateCollision, EUpdateFrequency UpdateFrequency, ESectionUpdateFlags UpdateFlags)
  721. {
  722. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_CreateMeshSection_DualUV);
  723. // Validate all creation parameters
  724. RMC_VALIDATE_CREATIONPARAMETERS(SectionIndex, Vertices, Triangles, /*VoidReturn*/);
  725. // Create the section
  726. auto NewSection = CreateOrResetSectionLegacyType(SectionIndex, 2);
  727. // Update the mesh data in the section
  728. NewSection->UpdateVertexBufferInternal(Vertices, Normals, Tangents, UV0, UV1, Colors);
  729. TArray<int32>& TrianglesRef = const_cast<TArray<int32>&>(Triangles);
  730. NewSection->UpdateIndexBuffer(TrianglesRef, false);
  731. // Track collision status and update collision information if necessary
  732. NewSection->CollisionEnabled = bCreateCollision;
  733. NewSection->UpdateFrequency = UpdateFrequency;
  734. // Finalize section.
  735. CreateSectionInternal(SectionIndex, UpdateFlags);
  736. }
  737. void URuntimeMeshComponent::UpdateMeshSection(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<FVector>& Normals, const TArray<FVector2D>& UV0,
  738. const TArray<FColor>& Colors, const TArray<FRuntimeMeshTangent>& Tangents, ESectionUpdateFlags UpdateFlags)
  739. {
  740. UpdateMeshSection(SectionIndex, Vertices, TArray<int32>(), Normals, UV0, Colors, Tangents, UpdateFlags);
  741. }
  742. void URuntimeMeshComponent::UpdateMeshSection(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<FVector>& Normals, const TArray<FVector2D>& UV0,
  743. const TArray<FVector2D>& UV1, const TArray<FColor>& Colors, const TArray<FRuntimeMeshTangent>& Tangents, ESectionUpdateFlags UpdateFlags)
  744. {
  745. UpdateMeshSection(SectionIndex, Vertices, TArray<int32>(), Normals, UV0, UV1, Colors, Tangents, UpdateFlags);
  746. }
  747. void URuntimeMeshComponent::UpdateMeshSection(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<int32>& Triangles, const TArray<FVector>& Normals,
  748. const TArray<FVector2D>& UV0, const TArray<FColor>& Colors, const TArray<FRuntimeMeshTangent>& Tangents, ESectionUpdateFlags UpdateFlags)
  749. {
  750. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateMeshSection);
  751. // Validate all update parameters
  752. RMC_VALIDATE_UPDATEPARAMETERS_INTERNALSECTION(SectionIndex, /*VoidReturn*/);
  753. // Validate section type
  754. MeshSections[SectionIndex]->GetVertexType()->EnsureEquals<FRuntimeMeshVertexSimple>();
  755. // Get section
  756. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  757. // Tell the section to update the vertex buffer
  758. bool bHadVertexUpdates = Section->UpdateVertexBufferInternal(Vertices, Normals, Tangents, UV0, TArray<FVector2D>(), Colors);
  759. bool bHadTriangleUpdates = Triangles.Num() > 0;
  760. if (bHadTriangleUpdates)
  761. {
  762. TArray<int32>& TrianglesRef = const_cast<TArray<int32>&>(Triangles);
  763. Section->UpdateIndexBuffer(TrianglesRef, false);
  764. }
  765. UpdateSectionInternal(SectionIndex, false, bHadVertexUpdates, bHadTriangleUpdates, true, UpdateFlags);
  766. }
  767. void URuntimeMeshComponent::UpdateMeshSection(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<int32>& Triangles, const TArray<FVector>& Normals,
  768. const TArray<FVector2D>& UV0, const TArray<FVector2D>& UV1, const TArray<FColor>& Colors, const TArray<FRuntimeMeshTangent>& Tangents, ESectionUpdateFlags UpdateFlags)
  769. {
  770. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateMeshSection_DualUV);
  771. // Validate all update parameters
  772. RMC_VALIDATE_UPDATEPARAMETERS_INTERNALSECTION(SectionIndex, /*VoidReturn*/);
  773. // Validate section type
  774. MeshSections[SectionIndex]->GetVertexType()->EnsureEquals<FRuntimeMeshVertexDualUV>();
  775. // Get section
  776. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  777. // Tell the section to update the vertex buffer
  778. bool bHadVertexUpdates = Section->UpdateVertexBufferInternal(Vertices, Normals, Tangents, UV0, UV1, Colors);
  779. bool bHadTriangleUpdates = Triangles.Num() > 0;
  780. if (bHadTriangleUpdates)
  781. {
  782. TArray<int32>& TrianglesRef = const_cast<TArray<int32>&>(Triangles);
  783. Section->UpdateIndexBuffer(TrianglesRef, false);
  784. }
  785. UpdateSectionInternal(SectionIndex, false, bHadVertexUpdates, bHadTriangleUpdates, true, UpdateFlags);
  786. }
  787. void URuntimeMeshComponent::CreateMeshSection_Blueprint(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<int32>& Triangles, const TArray<FVector>& Normals, const TArray<FRuntimeMeshTangent>& Tangents,
  788. const TArray<FVector2D>& UV0, const TArray<FVector2D>& UV1, const TArray<FLinearColor>& VertexColors, bool bCreateCollision, bool bCalculateNormalTangent, bool bGenerateTessellationTriangles, EUpdateFrequency UpdateFrequency)
  789. {
  790. // Convert vertex colors to FColor
  791. TArray<FColor> Colors;
  792. ConvertLinearColorToFColor(VertexColors, Colors);
  793. ESectionUpdateFlags UpdateFlags = ESectionUpdateFlags::None;
  794. UpdateFlags |= bCalculateNormalTangent ? ESectionUpdateFlags::CalculateNormalTangent : ESectionUpdateFlags::None;
  795. UpdateFlags |= bGenerateTessellationTriangles ? ESectionUpdateFlags::CalculateTessellationIndices : ESectionUpdateFlags::None;
  796. // Create section
  797. CreateMeshSection(SectionIndex, Vertices, Triangles, Normals, UV0, UV1, Colors, Tangents, bCreateCollision, UpdateFrequency, UpdateFlags);
  798. }
  799. void URuntimeMeshComponent::UpdateMeshSection_Blueprint(int32 SectionIndex, const TArray<FVector>& Vertices, const TArray<int32>& Triangles, const TArray<FVector>& Normals, const TArray<FRuntimeMeshTangent>& Tangents,
  800. const TArray<FVector2D>& UV0, const TArray<FVector2D>& UV1, const TArray<FLinearColor>& VertexColors, bool bCalculateNormalTangent, bool bGenerateTessellationTriangles)
  801. {
  802. // Convert vertex colors to FColor
  803. TArray<FColor> Colors;
  804. ConvertLinearColorToFColor(VertexColors, Colors);
  805. ESectionUpdateFlags UpdateFlags = ESectionUpdateFlags::None;
  806. UpdateFlags |= bCalculateNormalTangent ? ESectionUpdateFlags::CalculateNormalTangent : ESectionUpdateFlags::None;
  807. UpdateFlags |= bGenerateTessellationTriangles ? ESectionUpdateFlags::CalculateTessellationIndices : ESectionUpdateFlags::None;
  808. // Update section
  809. UpdateMeshSection(SectionIndex, Vertices, Triangles, Normals, UV0, UV1, Colors, Tangents, UpdateFlags);
  810. }
  811. void URuntimeMeshComponent::CreateMeshSection(int32 SectionIndex, IRuntimeMeshVerticesBuilder& Vertices, FRuntimeMeshIndicesBuilder& Triangles, bool bCreateCollision,
  812. EUpdateFrequency UpdateFrequency, ESectionUpdateFlags UpdateFlags)
  813. {
  814. RMC_CHECKINGAME_LOGINEDITOR((SectionIndex >= 0), "SectionIndex cannot be negative.", /**/);
  815. RMC_CHECKINGAME_LOGINEDITOR((Vertices.Length() > 0), "Vertices length must not be 0.", /**/);
  816. RMC_CHECKINGAME_LOGINEDITOR((Triangles.Length() > 0), "Triangles length must not be 0", /**/);
  817. // First we need to create the new section
  818. TSharedPtr<FRuntimeMeshSectionInterface> Section = MakeShareable(Vertices.GetVertexType()->CreateSection(Vertices.WantsSeparatePositionBuffer()));
  819. // Ensure sections array is long enough
  820. if (SectionIndex >= MeshSections.Num())
  821. {
  822. MeshSections.SetNum(SectionIndex + 1, false);
  823. }
  824. // Set the new section
  825. MeshSections[SectionIndex] = Section;
  826. // Set vertex/index buffers
  827. Section->UpdateVertexBuffer(Vertices, nullptr, !!(UpdateFlags & ESectionUpdateFlags::MoveArrays));
  828. Section->UpdateIndexBuffer(Triangles, !!(UpdateFlags & ESectionUpdateFlags::MoveArrays));
  829. // Track collision status and update collision information if necessary
  830. Section->CollisionEnabled = bCreateCollision;
  831. Section->UpdateFrequency = UpdateFrequency;
  832. // Finalize section.
  833. CreateSectionInternal(SectionIndex, UpdateFlags);
  834. }
  835. void URuntimeMeshComponent::UpdateMeshSection(int32 SectionIndex, IRuntimeMeshVerticesBuilder& Vertices, FRuntimeMeshIndicesBuilder& Triangles, ESectionUpdateFlags UpdateFlags)
  836. {
  837. // Validate all update parameters
  838. RMC_VALIDATE_UPDATEPARAMETERS_INTERNALSECTION(SectionIndex, /*VoidReturn*/);
  839. // Get section
  840. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  841. // Set vertex/index buffers
  842. Section->UpdateVertexBuffer(Vertices, nullptr, !!(UpdateFlags & ESectionUpdateFlags::MoveArrays));
  843. Section->UpdateIndexBuffer(Triangles, !!(UpdateFlags & ESectionUpdateFlags::MoveArrays));
  844. UpdateSectionInternal(SectionIndex, Vertices.WantsSeparatePositionBuffer(), true, true, true, UpdateFlags);
  845. }
  846. void URuntimeMeshComponent::ClearMeshSection(int32 SectionIndex)
  847. {
  848. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_ClearMeshSection);
  849. if (SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid())
  850. {
  851. // Did this section have collision
  852. bool HadCollision = MeshSections[SectionIndex]->CollisionEnabled;
  853. bool bWasStaticSection = MeshSections[SectionIndex]->UpdateFrequency == EUpdateFrequency::Infrequent;
  854. // Clear the section
  855. MeshSections[SectionIndex].Reset();
  856. // Use the batch update if one is running
  857. if (BatchState.IsBatchPending())
  858. {
  859. // Mark section created
  860. BatchState.MarkSectionDestroyed(SectionIndex, bWasStaticSection);
  861. // Flag collision if this section affects it
  862. if (HadCollision)
  863. {
  864. BatchState.MarkCollisionDirty();
  865. }
  866. // Flag bounds update
  867. BatchState.MarkBoundsDirty();
  868. // bail since we don't update directly in this case.
  869. return;
  870. }
  871. if (SceneProxy && !bWasStaticSection)
  872. {
  873. // Enqueue update on RT
  874. ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
  875. FRuntimeMeshSectionUpdate,
  876. FRuntimeMeshSceneProxy*, RuntimeMeshSceneProxy, (FRuntimeMeshSceneProxy*)SceneProxy,
  877. int32, SectionIndex, SectionIndex,
  878. {
  879. RuntimeMeshSceneProxy->DestroySection_RenderThread(SectionIndex);
  880. }
  881. );
  882. }
  883. else
  884. {
  885. MarkRenderStateDirty();
  886. }
  887. // Update our collision info only if this section had any influence on it
  888. if (HadCollision)
  889. {
  890. MarkCollisionDirty();
  891. }
  892. UpdateLocalBounds();
  893. }
  894. }
  895. void URuntimeMeshComponent::ClearAllMeshSections()
  896. {
  897. MeshSections.Empty();
  898. // Use the batch update if one is running
  899. if (BatchState.IsBatchPending())
  900. {
  901. // Mark render state dirty
  902. BatchState.MarkRenderStateDirty();
  903. // Flag collision
  904. BatchState.MarkCollisionDirty();
  905. // Flag bounds update
  906. BatchState.MarkBoundsDirty();
  907. // bail since we don't update directly in this case.
  908. return;
  909. }
  910. MarkRenderStateDirty();
  911. MarkCollisionDirty();
  912. UpdateLocalBounds();
  913. }
  914. void URuntimeMeshComponent::SetSectionTessellationTriangles(int32 SectionIndex, const TArray<int32>& TessellationTriangles, bool bShouldMoveArray)
  915. {
  916. // Validate all update parameters
  917. RMC_VALIDATE_UPDATEPARAMETERS_INTERNALSECTION(SectionIndex, /*VoidReturn*/);
  918. // Get section
  919. RuntimeMeshSectionPtr& Section = MeshSections[SectionIndex];
  920. // Tell the section to update the tessellation index buffer
  921. Section->UpdateTessellationIndexBuffer(const_cast<TArray<int32>&>(TessellationTriangles), bShouldMoveArray);
  922. UpdateSectionInternal(SectionIndex, false, false, true, false, ESectionUpdateFlags::None);
  923. }
  924. bool URuntimeMeshComponent::GetSectionBoundingBox(int32 SectionIndex, FBox& OutBoundingBox)
  925. {
  926. if (SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid())
  927. {
  928. OutBoundingBox = MeshSections[SectionIndex]->LocalBoundingBox;
  929. return true;
  930. }
  931. return false;
  932. }
  933. void URuntimeMeshComponent::SetMeshSectionVisible(int32 SectionIndex, bool bNewVisibility)
  934. {
  935. if (SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid())
  936. {
  937. // Set game thread state
  938. MeshSections[SectionIndex]->bIsVisible = bNewVisibility;
  939. // Finish the update
  940. UpdateSectionPropertiesInternal(SectionIndex, false);
  941. }
  942. }
  943. bool URuntimeMeshComponent::IsMeshSectionVisible(int32 SectionIndex) const
  944. {
  945. return SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid() && MeshSections[SectionIndex]->bIsVisible;
  946. }
  947. void URuntimeMeshComponent::SetMeshSectionCastsShadow(int32 SectionIndex, bool bNewCastsShadow)
  948. {
  949. if (SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid())
  950. {
  951. // Set game thread state
  952. MeshSections[SectionIndex]->bCastsShadow = bNewCastsShadow;
  953. // Finish the update
  954. UpdateSectionPropertiesInternal(SectionIndex, true);
  955. }
  956. }
  957. bool URuntimeMeshComponent::IsMeshSectionCastingShadows(int32 SectionIndex) const
  958. {
  959. return SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid() && MeshSections[SectionIndex]->bCastsShadow;
  960. }
  961. void URuntimeMeshComponent::SetMeshSectionCollisionEnabled(int32 SectionIndex, bool bNewCollisionEnabled)
  962. {
  963. if (SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid())
  964. {
  965. auto& Section = MeshSections[SectionIndex];
  966. if (Section->CollisionEnabled != bNewCollisionEnabled)
  967. {
  968. Section->CollisionEnabled = bNewCollisionEnabled;
  969. // Use the batch update if one is running
  970. if (BatchState.IsBatchPending())
  971. {
  972. // Mark render state dirty
  973. BatchState.MarkCollisionDirty();
  974. }
  975. else
  976. {
  977. MarkCollisionDirty();
  978. }
  979. }
  980. }
  981. }
  982. bool URuntimeMeshComponent::IsMeshSectionCollisionEnabled(int32 SectionIndex)
  983. {
  984. return SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid() && MeshSections[SectionIndex]->CollisionEnabled;
  985. }
  986. int32 URuntimeMeshComponent::GetNumSections() const
  987. {
  988. int32 SectionCount = 0;
  989. for (int32 Index = 0; Index < MeshSections.Num(); Index++)
  990. {
  991. if (MeshSections[Index].IsValid())
  992. {
  993. SectionCount++;
  994. }
  995. }
  996. return SectionCount;
  997. }
  998. bool URuntimeMeshComponent::DoesSectionExist(int32 SectionIndex) const
  999. {
  1000. return SectionIndex < MeshSections.Num() && MeshSections[SectionIndex].IsValid();
  1001. }
  1002. int32 URuntimeMeshComponent::FirstAvailableMeshSectionIndex() const
  1003. {
  1004. for (int32 Index = 0; Index < MeshSections.Num(); Index++)
  1005. {
  1006. if (!MeshSections[Index].IsValid())
  1007. {
  1008. return Index;
  1009. }
  1010. }
  1011. return MeshSections.Num();
  1012. }
  1013. int32 URuntimeMeshComponent::GetLastSectionIndex() const
  1014. {
  1015. for (int32 Index = MeshSections.Num() - 1; Index >= 0; Index--)
  1016. {
  1017. if (MeshSections[Index].IsValid())
  1018. {
  1019. return Index;
  1020. }
  1021. }
  1022. return -1;
  1023. }
  1024. void URuntimeMeshComponent::SetMeshCollisionSection(int32 CollisionSectionIndex, const TArray<FVector>& Vertices, const TArray<int32>& Triangles)
  1025. {
  1026. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_SetMeshCollisionSection);
  1027. if (MeshCollisionSections.Num() <= CollisionSectionIndex)
  1028. {
  1029. MeshCollisionSections.SetNum(CollisionSectionIndex + 1, false);
  1030. }
  1031. auto& Section = MeshCollisionSections[CollisionSectionIndex];
  1032. Section.VertexBuffer = Vertices;
  1033. Section.IndexBuffer = Triangles;
  1034. // Use the batch update if one is running
  1035. if (BatchState.IsBatchPending())
  1036. {
  1037. // Mark render state dirty
  1038. BatchState.MarkCollisionDirty();
  1039. }
  1040. else
  1041. {
  1042. MarkCollisionDirty();
  1043. }
  1044. }
  1045. void URuntimeMeshComponent::ClearMeshCollisionSection(int32 CollisionSectionIndex)
  1046. {
  1047. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_ClearMeshCollisionSection);
  1048. if (MeshCollisionSections.Num() <= CollisionSectionIndex)
  1049. return;
  1050. MeshCollisionSections[CollisionSectionIndex].Reset();
  1051. // Use the batch update if one is running
  1052. if (BatchState.IsBatchPending())
  1053. {
  1054. // Mark render state dirty
  1055. BatchState.MarkCollisionDirty();
  1056. }
  1057. else
  1058. {
  1059. MarkCollisionDirty();
  1060. }
  1061. }
  1062. void URuntimeMeshComponent::ClearAllMeshCollisionSections()
  1063. {
  1064. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_ClearAllMeshCollisionSections);
  1065. MeshCollisionSections.Empty();
  1066. // Use the batch update if one is running
  1067. if (BatchState.IsBatchPending())
  1068. {
  1069. // Mark render state dirty
  1070. BatchState.MarkCollisionDirty();
  1071. }
  1072. else
  1073. {
  1074. MarkCollisionDirty();
  1075. }
  1076. }
  1077. void URuntimeMeshComponent::AddCollisionConvexMesh(TArray<FVector> ConvexVerts)
  1078. {
  1079. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_AddCollisionConvexMesh);
  1080. if (ConvexVerts.Num() >= 4)
  1081. {
  1082. FRuntimeConvexCollisionSection ConvexSection;
  1083. ConvexSection.VertexBuffer = ConvexVerts;
  1084. ConvexSection.BoundingBox = FBox(ConvexVerts);
  1085. ConvexCollisionSections.Add(ConvexSection);
  1086. // Use the batch update if one is running
  1087. if (BatchState.IsBatchPending())
  1088. {
  1089. // Mark render state dirty
  1090. BatchState.MarkCollisionDirty();
  1091. }
  1092. else
  1093. {
  1094. MarkCollisionDirty();
  1095. }
  1096. }
  1097. }
  1098. void URuntimeMeshComponent::ClearCollisionConvexMeshes()
  1099. {
  1100. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_ClearCollisionConvexMeshes);
  1101. // Empty simple collision info
  1102. ConvexCollisionSections.Empty();
  1103. // Use the batch update if one is running
  1104. if (BatchState.IsBatchPending())
  1105. {
  1106. // Mark render state dirty
  1107. BatchState.MarkCollisionDirty();
  1108. }
  1109. else
  1110. {
  1111. MarkCollisionDirty();
  1112. }
  1113. }
  1114. void URuntimeMeshComponent::SetCollisionConvexMeshes(const TArray< TArray<FVector> >& ConvexMeshes)
  1115. {
  1116. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_SetCollisionConvexMeshes);
  1117. ConvexCollisionSections.Empty(ConvexMeshes.Num());
  1118. // Create element for each convex mesh
  1119. for (int32 ConvexIndex = 0; ConvexIndex < ConvexMeshes.Num(); ConvexIndex++)
  1120. {
  1121. FRuntimeConvexCollisionSection ConvexSection;
  1122. ConvexSection.VertexBuffer = ConvexMeshes[ConvexIndex];
  1123. ConvexSection.BoundingBox = FBox(ConvexSection.VertexBuffer);
  1124. ConvexCollisionSections.Add(ConvexSection);
  1125. }
  1126. // Use the batch update if one is running
  1127. if (BatchState.IsBatchPending())
  1128. {
  1129. // Mark render state dirty
  1130. BatchState.MarkCollisionDirty();
  1131. }
  1132. else
  1133. {
  1134. MarkCollisionDirty();
  1135. }
  1136. }
  1137. void URuntimeMeshComponent::UpdateLocalBounds(bool bMarkRenderTransform)
  1138. {
  1139. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateLocalBounds);
  1140. FBox LocalBox(EForceInit::ForceInitToZero);
  1141. for (const RuntimeMeshSectionPtr& Section : MeshSections)
  1142. {
  1143. if (Section.IsValid() && Section->bIsVisible)
  1144. {
  1145. LocalBox += Section->LocalBoundingBox;
  1146. }
  1147. }
  1148. LocalBounds = LocalBox.IsValid ? FBoxSphereBounds(LocalBox) : FBoxSphereBounds(FVector(0, 0, 0), FVector(0, 0, 0), 0); // fallback to reset box sphere bounds
  1149. // Update global bounds
  1150. UpdateBounds();
  1151. if (bMarkRenderTransform)
  1152. {
  1153. // Need to send to render thread
  1154. MarkRenderTransformDirty();
  1155. }
  1156. }
  1157. FPrimitiveSceneProxy* URuntimeMeshComponent::CreateSceneProxy()
  1158. {
  1159. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_CreateSceneProxy);
  1160. return new FRuntimeMeshSceneProxy(this);
  1161. }
  1162. int32 URuntimeMeshComponent::GetNumMaterials() const
  1163. {
  1164. return MeshSections.Num();
  1165. }
  1166. FBoxSphereBounds URuntimeMeshComponent::CalcBounds(const FTransform& LocalToWorld) const
  1167. {
  1168. return LocalBounds.TransformBy(LocalToWorld);
  1169. }
  1170. void URuntimeMeshComponent::EndBatchUpdates()
  1171. {
  1172. // Bail if we have no pending updates
  1173. if (!BatchState.IsBatchPending())
  1174. return;
  1175. // Handle all pending rendering updates..
  1176. if (BatchState.RequiresSceneProxyRecreate())
  1177. {
  1178. MarkRenderStateDirty();
  1179. }
  1180. else
  1181. {
  1182. auto* BatchUpdateData = new FRuntimeMeshBatchUpdateData;
  1183. for (int32 Index = 0; Index <= BatchState.GetMaxSection(); Index++)
  1184. {
  1185. // Skip this section if it has no updates.
  1186. if (!BatchState.HasAnyFlagSet(Index))
  1187. {
  1188. continue;
  1189. }
  1190. // Check that we don't have both create and destroy flagged
  1191. check(!(BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::Create) && BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::Destroy)));
  1192. // Handle section created
  1193. if (BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::Create))
  1194. {
  1195. // Validate section exists
  1196. check(MeshSections.Num() >= Index && MeshSections[Index].IsValid());
  1197. UMaterialInterface* Material = GetMaterial(Index);
  1198. if (Material == nullptr)
  1199. {
  1200. Material = UMaterial::GetDefaultMaterial(MD_Surface);
  1201. }
  1202. // Get the section create data and add it to the list
  1203. auto SectionCreateData = MeshSections[Index]->GetSectionCreationData(GetScene(), Material);
  1204. SectionCreateData->SetTargetSection(Index);
  1205. BatchUpdateData->CreateSections.Add(SectionCreateData);
  1206. }
  1207. // Handle destroy
  1208. else if (BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::Destroy))
  1209. {
  1210. BatchUpdateData->DestroySections.Add(Index);
  1211. }
  1212. // Handle vertex/index updates
  1213. else if (BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::VerticesUpdate) || BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::IndicesUpdate))
  1214. {
  1215. // Validate section exists
  1216. check(MeshSections.Num() >= Index && MeshSections[Index].IsValid());
  1217. // Get the section update data and add it to the list.
  1218. bool bHadPositionUpdates = BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::PositionsUpdate);
  1219. bool bHadVertexUpdates = BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::VerticesUpdate);
  1220. bool bHadIndexUpdates = BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::IndicesUpdate);
  1221. auto SectionUpdateData = MeshSections[Index]->GetSectionUpdateData(bHadPositionUpdates, bHadVertexUpdates, bHadIndexUpdates);
  1222. SectionUpdateData->SetTargetSection(Index);
  1223. BatchUpdateData->UpdateSections.Add(SectionUpdateData);
  1224. }
  1225. // Handle property updates
  1226. else if (BatchState.HasFlagSet(Index, ERuntimeMeshSectionBatchUpdateType::PropertyUpdate))
  1227. {
  1228. // Validate section exists
  1229. check(MeshSections.Num() >= Index && MeshSections[Index].IsValid());
  1230. auto SectionProperties = new(BatchUpdateData->PropertyUpdateSections) FRuntimeMeshSectionPropertyUpdateData;
  1231. auto& Section = MeshSections[Index];
  1232. SectionProperties->SetTargetSection(Index);
  1233. SectionProperties->bIsVisible = Section->bIsVisible;
  1234. SectionProperties->bCastsShadow = Section->bCastsShadow;
  1235. }
  1236. else
  1237. {
  1238. // Unknown update type.
  1239. checkNoEntry();
  1240. }
  1241. }
  1242. // Enqueue update on RT
  1243. ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
  1244. FRuntimeMeshBatchUpdateCommand,
  1245. FRuntimeMeshSceneProxy*, RuntimeMeshSceneProxy, (FRuntimeMeshSceneProxy*)SceneProxy,
  1246. FRuntimeMeshBatchUpdateData*, BatchUpdateData, BatchUpdateData,
  1247. {
  1248. RuntimeMeshSceneProxy->ApplyBatchUpdate_RenderThread(BatchUpdateData);
  1249. }
  1250. );
  1251. }
  1252. // Update collision if necessary
  1253. if (BatchState.RequiresCollisionUpdate())
  1254. {
  1255. MarkCollisionDirty();
  1256. }
  1257. // Update local bounds if necessary
  1258. if (BatchState.RequiresBoundsUpdate())
  1259. {
  1260. UpdateLocalBounds(!BatchState.RequiresSceneProxyRecreate());
  1261. }
  1262. // Clear batch info
  1263. BatchState.ResetBatch();
  1264. }
  1265. void URuntimeMeshComponent::GetSectionMesh(int32 SectionIndex, const IRuntimeMeshVerticesBuilder*& Vertices, const FRuntimeMeshIndicesBuilder*& Indices)
  1266. {
  1267. RMC_VALIDATE_UPDATEPARAMETERS(SectionIndex, /*VoidReturn*/);
  1268. IRuntimeMeshVerticesBuilder* TempVertices;
  1269. FRuntimeMeshIndicesBuilder* TempIndices;
  1270. MeshSections[SectionIndex]->GetSectionMesh(TempVertices, TempIndices);
  1271. Vertices = TempVertices;
  1272. Indices = TempIndices;
  1273. }
  1274. void URuntimeMeshComponent::BeginMeshSectionUpdate(int32 SectionIndex, IRuntimeMeshVerticesBuilder*& Vertices, FRuntimeMeshIndicesBuilder*& Indices)
  1275. {
  1276. RMC_VALIDATE_UPDATEPARAMETERS(SectionIndex, /*VoidReturn*/);
  1277. // Get mesh
  1278. MeshSections[SectionIndex]->GetSectionMesh(Vertices, Indices);
  1279. }
  1280. bool URuntimeMeshComponent::GetPhysicsTriMeshData(struct FTriMeshCollisionData* CollisionData, bool InUseAllTriData)
  1281. {
  1282. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_GetPhysicsTriMeshData);
  1283. int32 VertexBase = 0; // Base vertex index for current section
  1284. bool HadCollision = false;
  1285. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 13
  1286. // See if we should copy UVs
  1287. bool bCopyUVs = UPhysicsSettings::Get()->bSupportUVFromHitResults;
  1288. if (bCopyUVs)
  1289. {
  1290. CollisionData->UVs.AddZeroed(1); // only one UV channel
  1291. }
  1292. #endif
  1293. // For each section..
  1294. for (int32 SectionIdx = 0; SectionIdx < MeshSections.Num(); SectionIdx++)
  1295. {
  1296. const RuntimeMeshSectionPtr& Section = MeshSections[SectionIdx];
  1297. if (Section.IsValid() && Section->CollisionEnabled)
  1298. {
  1299. // Copy vertex data
  1300. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 13
  1301. Section->GetCollisionInformation(CollisionData->Vertices, CollisionData->UVs, bCopyUVs);
  1302. #else
  1303. Section->GetCollisionInformation(CollisionData->Vertices);
  1304. #endif
  1305. // Copy indices
  1306. const int32 NumTriangles = Section->IndexBuffer.Num() / 3;
  1307. for (int32 TriIdx = 0; TriIdx < NumTriangles; TriIdx++)
  1308. {
  1309. // Add the triangle
  1310. FTriIndices& Triangle = *new (CollisionData->Indices) FTriIndices;
  1311. Triangle.v0 = Section->IndexBuffer[(TriIdx * 3) + 0] + VertexBase;
  1312. Triangle.v1 = Section->IndexBuffer[(TriIdx * 3) + 1] + VertexBase;
  1313. Triangle.v2 = Section->IndexBuffer[(TriIdx * 3) + 2] + VertexBase;
  1314. // Add material info
  1315. CollisionData->MaterialIndices.Add(SectionIdx);
  1316. }
  1317. // Update the vertex base index
  1318. VertexBase = CollisionData->Vertices.Num();
  1319. HadCollision = true;
  1320. }
  1321. }
  1322. for (int32 SectionIdx = 0; SectionIdx < MeshCollisionSections.Num(); SectionIdx++)
  1323. {
  1324. auto& Section = MeshCollisionSections[SectionIdx];
  1325. if (Section.VertexBuffer.Num() > 0 && Section.IndexBuffer.Num() > 0)
  1326. {
  1327. CollisionData->Vertices.Append(Section.VertexBuffer);
  1328. const int32 NumTriangles = Section.IndexBuffer.Num() / 3;
  1329. for (int32 TriIdx = 0; TriIdx < NumTriangles; TriIdx++)
  1330. {
  1331. // Add the triangle
  1332. FTriIndices& Triangle = *new (CollisionData->Indices) FTriIndices;
  1333. Triangle.v0 = Section.IndexBuffer[(TriIdx * 3) + 0] + VertexBase;
  1334. Triangle.v1 = Section.IndexBuffer[(TriIdx * 3) + 1] + VertexBase;
  1335. Triangle.v2 = Section.IndexBuffer[(TriIdx * 3) + 2] + VertexBase;
  1336. // Add material info
  1337. CollisionData->MaterialIndices.Add(SectionIdx);
  1338. }
  1339. VertexBase = CollisionData->Vertices.Num();
  1340. HadCollision = true;
  1341. }
  1342. }
  1343. CollisionData->bFlipNormals = true;
  1344. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14
  1345. if (CollisionMode == ERuntimeMeshCollisionCookingMode::CookingPerformance)
  1346. {
  1347. CollisionData->bFlipNormals = true;
  1348. }
  1349. #endif
  1350. return HadCollision;
  1351. }
  1352. bool URuntimeMeshComponent::ContainsPhysicsTriMeshData(bool InUseAllTriData) const
  1353. {
  1354. for (const RuntimeMeshSectionPtr& Section : MeshSections)
  1355. {
  1356. if (Section.IsValid() && Section->IndexBuffer.Num() >= 3 && Section->CollisionEnabled)
  1357. {
  1358. return true;
  1359. }
  1360. }
  1361. for (const auto& Section : MeshCollisionSections)
  1362. {
  1363. if (Section.VertexBuffer.Num() > 0 && Section.IndexBuffer.Num() > 0)
  1364. {
  1365. return true;
  1366. }
  1367. }
  1368. return false;
  1369. }
  1370. void URuntimeMeshComponent::EnsureBodySetupCreated()
  1371. {
  1372. if (BodySetup == nullptr)
  1373. {
  1374. BodySetup = NewObject<UBodySetup>(this, NAME_None, (IsTemplate() ? RF_Public : RF_NoFlags));
  1375. BodySetup->BodySetupGuid = FGuid::NewGuid();
  1376. BodySetup->bGenerateMirroredCollision = false;
  1377. BodySetup->bDoubleSidedGeometry = true;
  1378. }
  1379. }
  1380. void URuntimeMeshComponent::UpdateCollision()
  1381. {
  1382. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_UpdateCollision);
  1383. bool NeedsNewPhysicsState = false;
  1384. // Destroy physics state if it exists
  1385. if (bPhysicsStateCreated)
  1386. {
  1387. DestroyPhysicsState();
  1388. NeedsNewPhysicsState = true;
  1389. }
  1390. // Ensure we have a BodySetup
  1391. EnsureBodySetupCreated();
  1392. // Fill in simple collision convex elements
  1393. BodySetup->AggGeom.ConvexElems.SetNum(ConvexCollisionSections.Num());
  1394. for (int32 Index = 0; Index < ConvexCollisionSections.Num(); Index++)
  1395. {
  1396. FKConvexElem& NewConvexElem = BodySetup->AggGeom.ConvexElems[Index];
  1397. NewConvexElem.VertexData = ConvexCollisionSections[Index].VertexBuffer;
  1398. NewConvexElem.ElemBox = FBox(NewConvexElem.VertexData);
  1399. }
  1400. // Set trace flag
  1401. BodySetup->CollisionTraceFlag = bUseComplexAsSimpleCollision ? CTF_UseComplexAsSimple : CTF_UseDefault;
  1402. // New GUID as collision has changed
  1403. BodySetup->BodySetupGuid = FGuid::NewGuid();
  1404. #if WITH_RUNTIME_PHYSICS_COOKING || WITH_EDITOR
  1405. // Clear current mesh data
  1406. BodySetup->InvalidatePhysicsData();
  1407. // Create new mesh data
  1408. BodySetup->CreatePhysicsMeshes();
  1409. #endif // WITH_RUNTIME_PHYSICS_COOKING || WITH_EDITOR
  1410. // Recreate physics state if necessary
  1411. if (NeedsNewPhysicsState)
  1412. {
  1413. CreatePhysicsState();
  1414. }
  1415. UpdateNavigation();
  1416. }
  1417. UBodySetup* URuntimeMeshComponent::GetBodySetup()
  1418. {
  1419. EnsureBodySetupCreated();
  1420. return BodySetup;
  1421. }
  1422. void URuntimeMeshComponent::MarkCollisionDirty()
  1423. {
  1424. if (!bCollisionDirty)
  1425. {
  1426. bCollisionDirty = true;
  1427. PrePhysicsTick.SetTickFunctionEnable(true);
  1428. }
  1429. }
  1430. void URuntimeMeshComponent::CookCollisionNow()
  1431. {
  1432. if (bCollisionDirty)
  1433. {
  1434. BakeCollision();
  1435. }
  1436. }
  1437. void URuntimeMeshComponent::BakeCollision()
  1438. {
  1439. // Bake the collision
  1440. UpdateCollision();
  1441. bCollisionDirty = false;
  1442. PrePhysicsTick.SetTickFunctionEnable(false);
  1443. }
  1444. void URuntimeMeshComponent::UpdateNavigation()
  1445. {
  1446. if (UNavigationSystem::ShouldUpdateNavOctreeOnComponentChange() && IsRegistered())
  1447. {
  1448. UWorld* MyWorld = GetWorld();
  1449. #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 13
  1450. if (MyWorld != nullptr && MyWorld->GetNavigationSystem() != nullptr &&
  1451. (MyWorld->GetNavigationSystem()->ShouldAllowClientSideNavigation() || !MyWorld->IsNetMode(ENetMode::NM_Client)))
  1452. #else
  1453. if (MyWorld != nullptr && MyWorld->IsGameWorld() && MyWorld->GetNetMode() < ENetMode::NM_Client)
  1454. #endif
  1455. {
  1456. UNavigationSystem::UpdateComponentInNavOctree(*this);
  1457. }
  1458. }
  1459. }
  1460. void URuntimeMeshComponent::RegisterComponentTickFunctions(bool bRegister)
  1461. {
  1462. Super::RegisterComponentTickFunctions(bRegister);
  1463. if (bRegister)
  1464. {
  1465. if (SetupActorComponentTickFunction(&PrePhysicsTick))
  1466. {
  1467. PrePhysicsTick.Target = this;
  1468. PrePhysicsTick.SetTickFunctionEnable(bCollisionDirty);
  1469. }
  1470. }
  1471. else
  1472. {
  1473. if (PrePhysicsTick.IsTickFunctionRegistered())
  1474. {
  1475. PrePhysicsTick.UnRegisterTickFunction();
  1476. }
  1477. }
  1478. }
  1479. void URuntimeMeshComponent::SerializeLegacy(FArchive& Ar)
  1480. {
  1481. if (Ar.CustomVer(FRuntimeMeshVersion::GUID) >= FRuntimeMeshVersion::Initial)
  1482. {
  1483. int32 SectionsCount = bShouldSerializeMeshData ? MeshSections.Num() : 0;
  1484. Ar << SectionsCount;
  1485. if (Ar.IsLoading() && MeshSections.Num() < SectionsCount)
  1486. {
  1487. MeshSections.SetNum(SectionsCount);
  1488. }
  1489. for (int32 Index = 0; Index < SectionsCount; Index++)
  1490. {
  1491. bool IsSectionValid = MeshSections[Index].IsValid();
  1492. // WE can only load/save internal types (we don't know how to serialize arbitrary vertex types.
  1493. if (Ar.IsSaving() && (IsSectionValid && !MeshSections[Index]->bIsLegacySectionType))
  1494. {
  1495. IsSectionValid = false;
  1496. }
  1497. Ar << IsSectionValid;
  1498. if (IsSectionValid)
  1499. {
  1500. if (Ar.CustomVer(FRuntimeMeshVersion::GUID) >= FRuntimeMeshVersion::TemplatedVertexFix)
  1501. {
  1502. int32 NumUVChannels;
  1503. bool WantsHalfPrecisionUVs;
  1504. if (Ar.IsSaving())
  1505. {
  1506. MeshSections[Index]->GetInternalVertexComponents(NumUVChannels, WantsHalfPrecisionUVs);
  1507. }
  1508. Ar << NumUVChannels;
  1509. Ar << WantsHalfPrecisionUVs;
  1510. if (Ar.IsLoading())
  1511. {
  1512. CreateOrResetSectionLegacyType(Index, NumUVChannels);
  1513. }
  1514. }
  1515. else
  1516. {
  1517. bool bWantsNormal;
  1518. bool bWantsTangent;
  1519. bool bWantsColor;
  1520. int32 TextureChannels;
  1521. Ar << bWantsNormal;
  1522. Ar << bWantsTangent;
  1523. Ar << bWantsColor;
  1524. Ar << TextureChannels;
  1525. if (Ar.IsLoading())
  1526. {
  1527. CreateOrResetSectionLegacyType(Index, TextureChannels);
  1528. }
  1529. }
  1530. FRuntimeMeshSectionInterface& SectionPtr = *MeshSections[Index].Get();
  1531. SectionPtr.Serialize(Ar);
  1532. }
  1533. }
  1534. }
  1535. if (Ar.CustomVer(FRuntimeMeshVersion::GUID) >= FRuntimeMeshVersion::SerializationOptional)
  1536. {
  1537. if (bShouldSerializeMeshData || Ar.IsLoading())
  1538. {
  1539. // Serialize the real data if we want it, also use this path for loading to get anything that was in the last save
  1540. // Serialize the collision data
  1541. Ar << MeshCollisionSections;
  1542. Ar << ConvexCollisionSections;
  1543. }
  1544. else
  1545. {
  1546. // serialize empty arrays if we don't want serialization
  1547. TArray<FRuntimeMeshCollisionSection> NullCollisionSections;
  1548. Ar << NullCollisionSections;
  1549. TArray<FRuntimeConvexCollisionSection> NullConvexBodies;
  1550. Ar << NullConvexBodies;
  1551. }
  1552. }
  1553. }
  1554. void URuntimeMeshComponent::Serialize(FArchive& Ar)
  1555. {
  1556. Super::Serialize(Ar);
  1557. SerializeInternal(Ar);
  1558. }
  1559. void URuntimeMeshComponent::SerializeInternal(FArchive& Ar, bool bForceSaveAll)
  1560. {
  1561. SCOPE_CYCLE_COUNTER(STAT_RuntimeMesh_Serialize);
  1562. Ar.UsingCustomVersion(FRuntimeMeshVersion::GUID);
  1563. // Handle old serialization
  1564. if (Ar.CustomVer(FRuntimeMeshVersion::GUID) < FRuntimeMeshVersion::SerializationV2)
  1565. {
  1566. SerializeLegacy(Ar);
  1567. return;
  1568. }
  1569. bool bSerializeMeshData = bShouldSerializeMeshData || bForceSaveAll;
  1570. // Serialize basic settings
  1571. Ar << bSerializeMeshData;
  1572. Ar << bUseComplexAsSimpleCollision;
  1573. // Serialize the number of sections...
  1574. int32 NumSections = bSerializeMeshData ? MeshSections.Num() : 0;
  1575. Ar << NumSections;
  1576. // Resize the section array if we're loading.
  1577. if (Ar.IsLoading())
  1578. {
  1579. MeshSections.Reset(NumSections);
  1580. MeshSections.SetNum(NumSections);
  1581. }
  1582. // Next serialize all the sections...
  1583. for (int32 Index = 0; Index < NumSections; Index++)
  1584. {
  1585. SerializeRMCSection(Ar, Index);
  1586. }
  1587. if (bSerializeMeshData || Ar.IsLoading())
  1588. {
  1589. // Serialize the real data if we want it, also use this path for loading to get anything that was in the last save
  1590. // Serialize the collision data
  1591. Ar << MeshCollisionSections;
  1592. Ar << ConvexCollisionSections;
  1593. }
  1594. else
  1595. {
  1596. // serialize empty arrays if we don't want serialization
  1597. TArray<FRuntimeMeshCollisionSection> NullCollisionSections;
  1598. Ar << NullCollisionSections;
  1599. TArray<FRuntimeConvexCollisionSection> NullConvexBodies;
  1600. Ar << NullConvexBodies;
  1601. }
  1602. }
  1603. void URuntimeMeshComponent::SerializeRMC(FArchive& Ar)
  1604. {
  1605. SerializeInternal(Ar, true);
  1606. }
  1607. void URuntimeMeshComponent::SerializeRMCSection(FArchive& Ar, int32 SectionIndex)
  1608. {
  1609. if (Ar.IsLoading() && MeshSections.Num() <= SectionIndex)
  1610. {
  1611. MeshSections.SetNum(SectionIndex + 1);
  1612. }
  1613. // Serialize the section validity (default it to section valid + type known for saving reasons)
  1614. bool bSectionIsValid = MeshSections[SectionIndex].IsValid();
  1615. bool bSectionTypeFound = bSectionIsValid ? FRuntimeMeshVertexTypeRegistrationContainer::GetInstance().GetVertexType(MeshSections[SectionIndex]->GetVertexType()->TypeGuid) != nullptr : true;
  1616. bSectionIsValid = bSectionIsValid && bSectionTypeFound;
  1617. Ar << bSectionIsValid;
  1618. // If section is invalid, skip
  1619. if (!bSectionIsValid)
  1620. {
  1621. if (!bSectionTypeFound)
  1622. {
  1623. UE_LOG(RuntimeMeshLog, Error, TEXT("Attempted to serialize a vertex of unknown type %s"), *MeshSections[SectionIndex]->GetVertexType()->TypeGuid.ToString());
  1624. }
  1625. return;
  1626. }
  1627. // Serialize section type info
  1628. FGuid TypeGuid;
  1629. bool bHasSeparatePositionBuffer;
  1630. if (Ar.IsSaving())
  1631. {
  1632. TypeGuid = MeshSections[SectionIndex]->GetVertexType()->TypeGuid;
  1633. bHasSeparatePositionBuffer = MeshSections[SectionIndex]->IsDualBufferSection();
  1634. }
  1635. Ar << TypeGuid;
  1636. Ar << bHasSeparatePositionBuffer;
  1637. if (Ar.IsLoading())
  1638. {
  1639. auto VertexTypeRegistration = FRuntimeMeshVertexTypeRegistrationContainer::GetInstance().GetVertexType(TypeGuid);
  1640. if (VertexTypeRegistration == nullptr)
  1641. {
  1642. UE_LOG(RuntimeMeshLog, Error, TEXT("Attempted to serialize a vertex of unknown type %s"), *MeshSections[SectionIndex]->GetVertexType()->TypeGuid.ToString());
  1643. bSectionIsValid = false;
  1644. }
  1645. else
  1646. {
  1647. auto NewSection = VertexTypeRegistration->CreateSection(bHasSeparatePositionBuffer);
  1648. MeshSections[SectionIndex] = MakeShareable(NewSection);
  1649. }
  1650. }
  1651. // Now we save the section data to a separate archive and then write in into the main.
  1652. // This way we can recover from unknown types or mismatch sizes
  1653. TArray<uint8> SectionData;
  1654. if (Ar.IsSaving())
  1655. {
  1656. FMemoryWriter SectionAr(SectionData, true);
  1657. SectionAr.UsingCustomVersion(FRuntimeMeshVersion::GUID);
  1658. MeshSections[SectionIndex]->Serialize(SectionAr);
  1659. }
  1660. Ar << SectionData;
  1661. if (Ar.IsLoading() && bSectionIsValid)
  1662. {
  1663. FMemoryReader SectionAr(SectionData, true);
  1664. SectionAr.Seek(0);
  1665. SectionAr.UsingCustomVersion(FRuntimeMeshVersion::GUID);
  1666. MeshSections[SectionIndex]->Serialize(SectionAr);
  1667. // Was this section loaded correctly?
  1668. if (SectionAr.IsError())
  1669. {
  1670. MeshSections[SectionIndex].Reset();
  1671. UE_LOG(RuntimeMeshLog, Log, TEXT("Unable to load section %d of type %s. This is most likely caused by a reconfigured vertex type."),
  1672. SectionIndex, *MeshSections[SectionIndex]->GetVertexType()->TypeName);
  1673. }
  1674. }
  1675. }
  1676. void URuntimeMeshComponent::PostLoad()
  1677. {
  1678. Super::PostLoad();
  1679. // Rebuild collision and local bounds.
  1680. MarkCollisionDirty();
  1681. UpdateLocalBounds();
  1682. if (BodySetup && IsTemplate())
  1683. {
  1684. BodySetup->SetFlags(RF_Public);
  1685. }
  1686. }