Files
UnrealEngineUWP/Engine/Source/Runtime/ClothingSystemRuntime/Private/Assets/ClothingAsset.cpp
Thomas Sarkanen 1102c5e12c Copying //UE4/Dev-AnimPhys to //UE4/Dev-Main (Source: //UE4/Dev-AnimPhys @ 3384744)
#lockdown Nick.Penwarden

==========================
MAJOR FEATURES + CHANGES
==========================

Change 3294073 on 2017/02/09 by Thomas.Sarkanen

	Delete old location of FriendViewModel.h that did not get picked up correctly in the merge

Change 3354003 on 2017/03/20 by Thomas.Sarkanen

	Back out changelist 3353914

Change 3355932 on 2017/03/21 by Thomas.Sarkanen

	Back out changelist 3354003

	Reinstating merge from Main:

	Merging //UE4/Dev-Main to Dev-AnimPhys (//UE4/Dev-AnimPhys) @ CL 3353839

Change 3358776 on 2017/03/22 by Ori.Cohen

	Recreate physics when changing mobility of components - fixes debug rendering issue

	#JIRA UE-39328

Change 3360075 on 2017/03/23 by James.Golding

	Back out changelist 3358776, as it was made after smoke testing. Will re-submit after copy to main.

Change 3362695 on 2017/03/24 by Thomas.Sarkanen

	Use correct extender when building menus for AnimationEditor, SkeletalMeshEditor & SkeletonEditor

	#jira UE-41100 - Persona code calling incorrect extenders when building menus.

Change 3362696 on 2017/03/24 by Thomas.Sarkanen

	Facial animation experimental feature now pops up restart editor toast

	#jira UE-40989 - User is not prompted to restart the editor when enabling the Facial Animation Importer

Change 3362699 on 2017/03/24 by Thomas.Sarkanen

	Enable snapping for translation in animation viewports

	#jira UE-39747 - Translating sockets in Persona is not affected by Snap Options
	#jira UE-39748 - Translating bones in Persona is not affected by Snap Options

Change 3362700 on 2017/03/24 by Thomas.Sarkanen

	Curve source nodes now dont update their source title if the source is a pin

	The title of the node is not recached when the pin default changes, so we cant display it in the title

	#jira UE-40108 - When changing a Curve Source Node doesn't update source binding name when typed in

Change 3362721 on 2017/03/24 by Thomas.Sarkanen

	CVar r.SkeletalMeshLODBias no longer affects meshes in animation viewports

	#jira UE-35733 - GSkeletalMeshLODBias affects render LOD in Persona

Change 3362724 on 2017/03/24 by Thomas.Sarkanen

	Fix animation preview scene keyboard bindings

	Also moved advanced preview scene into its own module

	#jira UE-41505 - Pressing the hotkey I and O do not hide the floor and environment if the Preview Scene Settings tab isn't opened.

Change 3362783 on 2017/03/24 by Ori.Cohen

	Fix incorrect locking and check when an editor static shape is changed. Originally this code assumed it would only get called at runtime, where there is only 1 shape. In the case of the async scene and static shapes - there are two shapes and if you update the body setup in the editor this will crash.

Change 3362796 on 2017/03/24 by Ori.Cohen

	Fix welded capsules not using the right rotation

	#JIRA UE-41546

Change 3362803 on 2017/03/24 by Ori.Cohen

	Recreate physics when changing mobility of components - fixes debug rendering issue

	#JIRA UE-39328

Change 3363013 on 2017/03/24 by Thomas.Sarkanen

	Fix CIS issue

Change 3363202 on 2017/03/24 by Ori.Cohen

	Fix bad #endif

Change 3363295 on 2017/03/24 by Ori.Cohen

	Remove bWelded and use WeldParent everywhere. This fixes a bad case where a kinematic is returned as the root welded of simulated children.

	#JIRA UE-40783

Change 3363435 on 2017/03/24 by Jon.Nabozny

	Fix infinite jump on client when Jump Max Hold Time is not 0.

	#jira UE-41004

Change 3363451 on 2017/03/24 by Jon.Nabozny

	Fix USkeletalMeshComponent::PoseTickedThisFrame to use a frame counter instead of world time (which isn't changed while paused).

	#jira UE-39567

Change 3363504 on 2017/03/24 by Jon.Nabozny

	Fix SCE_NP_MATCHING2_REQUEST_EVENT_SEARCH_ROOM_A to treat result data as linked list instead of array.
	(Code originally came from SCE via UDN)

	#jira UE-41049

Change 3363532 on 2017/03/24 by Ori.Cohen

	Change default to SkipSimulatedBones.

	#JIRA UE-41404

Change 3363537 on 2017/03/24 by Ori.Cohen

	Remove the unsupported option of HideBone with DisableCollision. If we want this in the future we can add it.

	#JIRA UE-30826

Change 3363681 on 2017/03/24 by Jon.Nabozny

	Reapply 3292286 after it was clobbered by 3360002
	(Only clobbered in Ocean).

	#jira UE-37512

Change 3363722 on 2017/03/24 by mason.seay

	Updated map to improve testing

Change 3365351 on 2017/03/27 by Thomas.Sarkanen

	Fix non-PCH CIS errors

	#jira UE-43335 - CIS fail: 'FAdvancedPreviewSceneCommands is not a class name

Change 3365422 on 2017/03/27 by Thomas.Sarkanen

	Fixed skinned mesh LOD not updating in editor under various physics-related circumstances

	#jira UE-42013 - Skeletal meshes with recently generated LODs will not change LODs in viewport

Change 3365423 on 2017/03/27 by Thomas.Sarkanen

	Fix ensure when setting Spline IK Bone Axis  to 'None'

	Node is currently not in use, so I've avoided deprecating this for now. Values should be preserved.

	#jira UE-39723 - Ensure when setting Bone Axis to None in Spline IK

Change 3365424 on 2017/03/27 by Thomas.Sarkanen

	Fix control rigs being convertable to possessables

	Also prevent 'export to anim sequence' button from appearing on standard level sequences

	#jira UE-42070 - Crash converting a control rig to Possessable

Change 3365425 on 2017/03/27 by Thomas.Sarkanen

	When selecting bones that are non-required, we dont render gizmos or text labels

	#jira UE-35737 - Bone labels flicker between two locations when removing from LOD levels in Persona

Change 3365426 on 2017/03/27 by Thomas.Sarkanen

	Fixed foot placement IK doing line traces on worker threads

	Also exposed const access to required bones array (the proxy already does this, so I figure the instance should get it too).
	Note: Node is not actually used

	#jira UE-43179 - Fix FAnimNode_FootPlacementIK doing line trace on worker thread

Change 3365428 on 2017/03/27 by Thomas.Sarkanen

	Skeleton selection no does not lag behind choice made in viewport

	#jira UE-42236 - Mesh Overlay always lags behind actual selection

Change 3365429 on 2017/03/27 by Thomas.Sarkanen

	Fix anim BPs that contain state machines having blank palettes

	#jira UE-42172 - AnimBP Palette is blank on existing AnimBPs

Change 3365435 on 2017/03/27 by Jurre.deBaare

	Undoing Channel selection in Paint mode does not work
	#fix use duplicated CDO object instead of CDO directly
	#jira UE-42621

Change 3365436 on 2017/03/27 by Jurre.deBaare

	Functionless undo/redo transactions created when importing Alembic file and changing conversion settings
	#fix use duplicated CDO object instead of CDO directly
	#jira UE-40347

Change 3365437 on 2017/03/27 by Jurre.deBaare

	Ensure that HLOD cannot be set up in sub-levels
	#fix added functionality to check whether or not a level is used as a sub/streaming level in any other content, and if so show a widget similar to the checkout notice to inform the user why the hlod outliner is disabled
	#jira UE-40301

Change 3365438 on 2017/03/27 by Jurre.deBaare

	2D Blendspace breaks when aligning samples in a straight line
	#fix for some reason the number of samples to considerate was limit to 3 (old code) so removed it since it doesn't make sense
	#jira UE-42744

Change 3365439 on 2017/03/27 by Jurre.deBaare

	Color View Mode doesn't reset when closing/reopening editor
	#fix added a delegate to OnEditorClose to ensure we can reset the viewport modes while they still exist, this issue would happen if the user closes the editor with mesh paint mode open, exiting the mode would only happen after destructing most of the editor
	#jira UE-42466

Change 3365440 on 2017/03/27 by Jurre.deBaare

	LOD Model field scrubbing is very sensitive
	#fix made sure that max slider value is also driven by data
	#jira UE-42980

Change 3365441 on 2017/03/27 by Jurre.deBaare

	Replacing an asset in a sequence player node does not register in undo history
	#fix added transaction for dropping anim assets on player nodes
	#jira UE-39152

Change 3365442 on 2017/03/27 by Jurre.deBaare

	Crash on Mac importing some alembic files
	#fix disable multithread abc file reading with HDF5 backend
	#jira UE-39783

Change 3365443 on 2017/03/27 by Jurre.deBaare

	Moving over Alembic feature: "Add support for 'finding' materials according to the face-set names in abc files"

Change 3365444 on 2017/03/27 by Jurre.deBaare

	Moving over Alembic fixes:
	- Time offset issues > changed how we determine frame indices and frame steps
	- Incorrect tangent issues > enforce tangent calculation during skeletal mesh import
	- Automatically set recompute tangent flag on skeletal mesh sections

Change 3365451 on 2017/03/27 by Jurre.deBaare

	CIS: include needed for GetTransientPackage

Change 3365460 on 2017/03/27 by Jurre.deBaare

	CIS: apparently CIS wants explicit cast to UObject

Change 3365463 on 2017/03/27 by Jurre.deBaare

	CIS: final fix, was actually UPackage include missing ugh

Change 3365486 on 2017/03/27 by Thomas.Sarkanen

	Fix case error in include for Linux builds

Change 3365499 on 2017/03/27 by James.Golding

	Fix editing collision settings sometimes not 'sticking' - wait until after LoadProfileConfig (which modified Profiles array) to copy to 'SavedData'
	Fix FCollsiionProfileData typo
	#jira UE-42490

Change 3365500 on 2017/03/27 by Jurre.deBaare

	Turning on LOD Model Painting does not copy paint to other LODs on Skeletal Mesh
	#fix neede to pre edit / post edit the skeletal mesh to ensure the color buffers were re-initialised
	#jira UE-42637

Change 3365501 on 2017/03/27 by James.Golding

	Disable rather than hide anim picker when no mesh assigned
	#jira UE-35537

Change 3365505 on 2017/03/27 by James.Golding

	Fix USkinnedMeshComponent::FindClosestBone ignoring bRequirePhysicsAsset, because BodySetupIndexMap.FindRef would return 0 if bone not present
	https://udn.unrealengine.com/questions/353125/uskinnedmeshcomponentfindclosestbone-does-not-resp.html
	#jira UE-43061

Change 3365515 on 2017/03/27 by Jurre.deBaare

	Using Alt+Click to break Transition node connections cannot be undone using the Undo command
	#fix added transactions to breaking node links
	#jira UE-39068

Change 3365528 on 2017/03/27 by Jurre.deBaare

	Blendspaces don't update to reflect sync marker changes that have occurred on animations in the blend
	#fix added validation on blendspaces when removing or adding sync markers in animation editor
	#jira UE-39814

Change 3365535 on 2017/03/27 by Jurre.deBaare

	Camera moves at the same time as erasing paint when clicking Paint settings and back into Viewport
	#fix lock camera if erasing as well
	#jira UE-42474

Change 3365539 on 2017/03/27 by Jurre.deBaare

	Painting on animation sequence paints on invisible T-pose skeleton
	#fix during painting enforce bUseRefPoseOnInitAnim so you're always painting on a ref-pose skeletal mesh
	#jira UE-42484

Change 3365545 on 2017/03/27 by Jurre.deBaare

	Fill Tool does not fill the mesh with the selected Texture Weight Index when used in Weight Vertex Painting
	#fix added function to generate color according to texture weight settings and index, and fill using that color when the editor is in texture weight mode
	#jira UE-43091

Change 3365549 on 2017/03/27 by Jurre.deBaare

	CIS: include fix

Change 3365555 on 2017/03/27 by Jurre.deBaare

	Missing change from 3365545

Change 3365561 on 2017/03/27 by Jurre.deBaare

	Missing change from 3365545

Change 3365918 on 2017/03/27 by Ori.Cohen

	PR #3424: fix compile error when PHYSX_MEMORY_STATS=1 (Contributed by kayama-shift)

	#JIRA UE-43337

Change 3366234 on 2017/03/27 by Ori.Cohen

	Moved call to UpdateHasValidBodies into OnRegister. Original suggested fix came from github, but I think the bounds need to update even if OnCreatePhysics isn't called.

	#JIRA UE-43339

	#pr 3427

Change 3367252 on 2017/03/28 by Jurre.deBaare

	Vertex Weight Painting options are no longer present in MeshPaint mode
	#fix implemented singleton pattern for paint mode settings to ensure customization works correctly
	#jira UE-43357

Change 3367340 on 2017/03/28 by Jurre.deBaare

	GC fix for recent changes to painting / alembic settings

Change 3367445 on 2017/03/28 by Thomas.Sarkanen

	Fix fallout from Main merge

	OrionEditor needs to depend on the new AdvancedPreviewScene module.

Change 3367741 on 2017/03/28 by Ori.Cohen

	Remove unused physics warning when moving simulated object during physics

	#jira UE-41465

Change 3368072 on 2017/03/28 by Ori.Cohen

	Removed collision aggregates from ISMC collision. This is not a good candidate for aggregates as the bounding boxes generated could be huge (for example several trees that are very far away). This fixes perf regression from the PhysX 3.4 upgrade

	#JIRA UE-42956

Change 3368479 on 2017/03/28 by Ori.Cohen

	Fix GetClosestPoint incorrectly considering welded bodies.

	#JIRA UE-39329

Change 3368620 on 2017/03/28 by Lina.Halper

	Added code comment

	#rb:none
	#jira: UE-38836

Change 3368752 on 2017/03/28 by mason.seay

	Updated test map since UE-338836 came back as by design

Change 3369370 on 2017/03/29 by James.Golding

	Fix StaticMesh Editor drawing complex collision if 'use simple as complex' is enabled
	Add separate options for showing simple and complex collision in StaticMesh Editor
	#jira UE-42844

Change 3369438 on 2017/03/29 by Lina.Halper

	Fix issue where it updates more often when you give too high update rate - i.e. 60

	#jira: UE-38844
	#code review: Laurent.Delayen

Change 3369462 on 2017/03/29 by Thomas.Sarkanen

	Add preview mesh to animation blueprints

	Auto set preview mesh for animation assets and animation blueprints based off meshes.

	#jira UE-40032 - Creating animation assets from right-clicking skel mesh results in showing incorrect mesh in Persona

Change 3369463 on 2017/03/29 by Thomas.Sarkanen

	We now select current preview mesh in the preview mesh dropdown

Change 3369464 on 2017/03/29 by Thomas.Sarkanen

	Ticks now appear properly on anim sequence scrub bar

	#jira UE-41197 - No additional ticks appear on the timeline when you zoom in

Change 3369465 on 2017/03/29 by Thomas.Sarkanen

	Persona now depends publicly on SkeletonEditor

	GitHub PR #3431 from kayama-shift

	#jira UE-43344 - GitHub 3431 : Persona module must depend on SkeletonEditor publically

Change 3369466 on 2017/03/29 by Thomas.Sarkanen

	Blueprints are now only dirtied if edited properties are from objects in the Blueprint's package

	#jira UE-38956 - Changing Bone Transform between World and Local Location dirties Anim Blueprints

Change 3369467 on 2017/03/29 by Thomas.Sarkanen

	Tweaked combo box alignment for world/local transform

	Appearance is now closer to that of the level editor

Change 3369469 on 2017/03/29 by Thomas.Sarkanen

	Prevent switching to unsupported widget modes when editing control rigs

	#jira UE-42557 - When in Animation Mode, if you select a controller with the translation gizmo active, when you select a non animation controller the gizmo renders incorrectly

Change 3369588 on 2017/03/29 by Thomas.Sarkanen

	Make import data and thumbnail data transactional

	#jira UE-41579 - Undo not working for several Asset Details options in Skeletal Mesh editor (Persona)

Change 3369609 on 2017/03/29 by Thomas.Sarkanen

	Montages are now correctly initialized when created

	They can be used straight away without first opening them in the montage edtior.
	Moved initialization of composite sections from SMontageEditor to AnimMontageFactory.

	#jira UE-41219 - Animation montages created via Right click Create montage, that aren't opened in persona will not animate when used in an AnimBP

Change 3369610 on 2017/03/29 by Thomas.Sarkanen

	Fixed anim class being set by name, causing duplicate-named anim BPs to be incorrectly resolved

	#jira UE-39833 - SkelMesh Component > Anim Class does not handle identical AnimBP names

Change 3369647 on 2017/03/29 by Ori.Cohen

	Fix mass debug not working when moving components in the editor.

	#JIRA UE-43437

Change 3369875 on 2017/03/29 by Ori.Cohen

	Added the call into overlap instead of computePenetration when possible. There are edge cases that exist when computePenetration returns false but overlap returns true. Originally we were using computePenetration for all overlaps to make it consistent. However, computePenetration doesn't handle trimeshes correctly in certain cases. The reason for this is so that we can at least resolve a known issue with overlap events with complex collision. Nvidia may give us a flag for computePenetration to not do back-face culling which would give us a more consistent result.

	#JIRA UE-25923

Change 3370144 on 2017/03/29 by Lina.Halper

	Fix on the retargeting child anim BP

	#rb: Martin.Wilson
	#jira: UE-39928

Change 3371480 on 2017/03/30 by James.Golding

	Changes by BryanG at Nvidia required to get them up and running with plugins that override some skeletal mesh stuff.

	#jira UE-42132

Change 3371484 on 2017/03/30 by Thomas.Sarkanen

	We now propagate thread safety flags to child Animation Blueprints

Change 3371486 on 2017/03/30 by Thomas.Sarkanen

	Fixed crash and effector selection issues for two bone IK

	Crash occured when selecting the root bone as the end of the chain.
	Viewport selection was not working at all as we werent creating any selection proxy actors any more.

Change 3371497 on 2017/03/30 by Thomas.Sarkanen

	Added warning when Sequencer tries to write to properties that have changed type

	#jira UE-42098 - Sequencer writes rotation data to transform properties, causes assert

Change 3371614 on 2017/03/30 by Martin.Wilson

	Clean up deprecated property value after load so we dont get extra anim blueprint references

	#jira UE-42501

Change 3371619 on 2017/03/30 by James.Golding

	Fix CIS by removing unneeded UNREALED_API from FImportSkeletalMeshArgs

Change 3372452 on 2017/03/30 by Jon.Nabozny

	Add flag to CharacterMovementComponent to determine whether or not character should Sweep while using NavWalking, instead of relying on GenerateOverlaps flag.

	#jira UE-36546

Change 3373043 on 2017/03/30 by Lina.Halper

	- Consolidating to FastLerp to simply code
	- Added comment on FastLerp as the result is not normalized

	#rb: Michael.Noland, David.Hill

Change 3373292 on 2017/03/30 by Jeff.Farris

	Made Actor.DispatchPhysicsCollisionHit virtual.

	(Copied CL 3261103 from Robo Recall to Dev-AnimPhys)

Change 3373293 on 2017/03/30 by Jeff.Farris

	Added PhysicalAnimationComponent.GetBodyTargetTransform

	(Copied 3256175 from RoboRecall to Dev-AnimPhys)

Change 3373318 on 2017/03/30 by Jeff.Farris

	Added option for components to opt out of physics impulses on damage.

	(Copied CL 3282585 from RoboRecall to Dev-AnimPhys)

Change 3374064 on 2017/03/31 by Thomas.Sarkanen

	Renaming curves in animations is now saved properly

	Guids were not being set, so loading code obliterated the rename after an editor restart

	#jira UE-40582 - Curve name is not updated when user changes it in persona editor.

Change 3374175 on 2017/03/31 by Thomas.Sarkanen

	Two bone IK UI consistency fixes

	Completely removed all bone select actors. They have a terrible UX anyway.
	We now rely only on our custom hit proxy and use a unified path to generate effector locations to draw and manipulate.

	#jira UE-42359 - Two Bone IK modifying effector location from viewport when bone is not set

Change 3374216 on 2017/03/31 by Martin.Wilson

	Clear raw curve data during cooking + change Paragon game code so that it reads from the compressed curve data on Anim Sequences, not the raw data

	#jira UE-37897

Change 3374253 on 2017/03/31 by Thomas.Sarkanen

	Supplementary fix to CL 3371497

	Adding name exposure for property types that we support

Change 3374298 on 2017/03/31 by Jeff.Farris

	Code change from nVidia that improves physX perf (afterIntegration time).

	(Copied CL 3302239 from Robo Recall to Dev-AnimPhys)

Change 3374432 on 2017/03/31 by Lina.Halper

	Make sure AcitveBoneIndices contains parent

	#jira: UE-14597
	#rb: Martin.Wilson
	#code review: Benn.Gallagher, Alexis.Matte, James.Golding

Change 3374836 on 2017/03/31 by Jon.Nabozny

	Fixup hits returned before start of trace in raycast_capsule.

	This change is copied from CL-3297212

	#jira UE-42532

Change 3375195 on 2017/03/31 by Lina.Halper

	resave animation sequence for increasing info to warning

	#code review: Thomas.Sarkanen
	#jira: UE-40643

Change 3375282 on 2017/03/31 by Lina.Halper

	Fix odin content for animation : resave animation sequence for increasing info to warning

	#code review: Thomas.Sarkanen
	#jira: UE-40643

Change 3375288 on 2017/03/31 by Lina.Halper

	reverting code of degrading warning to info to avoid warning

	#jira: UE-40643

Change 3375865 on 2017/04/01 by Lina.Halper

	fix build error

Change 3375868 on 2017/04/01 by Lina.Halper

	fix build warning on shadow var

	#code review: Thomas.Sarkanen

Change 3376283 on 2017/04/03 by Thomas.Sarkanen

	Reworked, more generic property path handling in object change listener

	This allows all paths (auto vs manual key) to use the same code path, as well as regularizing the special-case handling of structs and arrays (and combinations thereof).
	The gist of the new implementation is to traverse the property path until we come across any property that satisfies our crirtera (exposed function, Interp flag etc.)
	Tweaked PropertyHandleToPropertyPath to correctly handle the slightly different way FPropertyNodes are arranged inside IPropertyHandle chains.
	IPropertyHandle chains contain arrays in a manner designed for display in the property editor, e.g. Container.Array.Array[ArrayIndex].StructInner. We need to collapse adjacent array properties as we are looking for Container.Array[ArrayIndex].StructInner to form a well-formed 'property path'.
	Small tweak to FPropertyChangedParams::GetPropertyValue. This is to handle property paths that end in an array (e.g. Struct.Array[0]).

	#jira UE-42271 - Pressing enter while the spine is in IK doesn't set any keys

Change 3376320 on 2017/04/03 by Benn.Gallagher

	Merging from OR39 - Fix for clothing perf regressions due to LOD switching leaving simulation enties in the clothing solver
	#jira OR-36926

Change 3376413 on 2017/04/03 by Benn.Gallagher

	Merge from OR - Fixes to stability due to component space being the simulation space, games like Paragon treat the mesh and component transforms differently and cause issues with added energy in the system.
	#jira OR-36927

Change 3376421 on 2017/04/03 by Benn.Gallagher

	Missed file from OR cloth fixes merge

Change 3376456 on 2017/04/03 by Lina.Halper

	Resave fortnite animation to remove warning

	#rb: none

Change 3376479 on 2017/04/03 by Jon.Nabozny

	Touch PhysXLibs to ensure physx links properly.
	(Needed for CL-3374836)

Change 3376610 on 2017/04/03 by Martin.Wilson

	Fix for crash when reimporting lodded mesh with virtual bones

	#jira UE-43557

Change 3376618 on 2017/04/03 by Jurre.deBaare

	Mesh Paint decrement rate is too slow when used with hotkeys
	#fix change way we increase/decrease brush value
	#jira UE-43402

Change 3376650 on 2017/04/03 by Benn.Gallagher

	Converted clothing asset editor warnings into toasts + logs so they are more discoverable by the user.
	#jira UE-41739

Change 3376771 on 2017/04/03 by Benn.Gallagher

	Fixed clothing selection dropdowns to no longer get out of sync with actual state (if the binding fails it falls back to the "None" selection correctly internally)
	#jira UE-41737

Change 3378117 on 2017/04/04 by Thomas.Sarkanen

	Prevented ensure by reverting to default unit vectors if zero-sized lookat/lookup vectors are specified

	Also added a warning to inform users of the issue.

	#jira UE-43360 - Enabling Use LookUp Axis causes handled ensure to occur

Change 3378118 on 2017/04/04 by Thomas.Sarkanen

	Fix 2-bone IK flickering

	First changed non-triangular range check to be >= instead  of >. Also removed fallback to doubled-back as this singularity also occurs at min stretch + float epsilon (which caused the flicker). We are OK to call ACos with out-of-range values as it clamps internally and the subsequent calculations work in these degenerate cases.

	#jira UE-43525 - Mesh Flicker when Two Bone IK is stretched

Change 3378192 on 2017/04/04 by Benn.Gallagher

	Trivial fix to clothing dropdowns to unbind clothing assets when switching

Change 3378206 on 2017/04/04 by Thomas.Sarkanen

	Fix IncludeTool static analysis errors

	Traced this back to the checkin that moved advanced preview scene into its own module. Further refined this to be the dependency on SharedSettingsWidgets. Simplest solution was to move the details customization back into the DetailsCustomizations module.

	#jira UE-43563 - //UE4/Dev-AnimPhys: Compile IncludeTool Static analysis Win64 completed with 1 error

Change 3378207 on 2017/04/04 by Thomas.Sarkanen

	Fix static analysis warning

Change 3378267 on 2017/04/04 by Benn.Gallagher

	Disabled "Accurate" wind mode selection for 4.16 by hiding enum option for windmode. Looks like there are some simulation issues that need resolved. Wind will act as it always has for 4.16.

Change 3378268 on 2017/04/04 by Benn.Gallagher

	Fixed bounds calculation on clothing to stop dissapearances or flickering at the edge of the screen.
	#jira UE-40407

Change 3378342 on 2017/04/04 by Jurre.deBaare

	Bone LOD preview doesn't get update if change removed bones array directly in Skeletalmesh editor
	#fix ensure that we update the skeleton tree when changes to the bones are made
	#misc made sure the reapply button its visibility is dynamic
	#misc made sure we always re-add previously removed bones when necessary
	#jira UE-40500

Change 3378374 on 2017/04/04 by Thomas.Sarkanen

	Fixed animation not working for dynamically-bound wheeled-vehicle anim instances

	Vehicle anim instance now looks for a wheeled vehicle component when it initializes.

	#jira UE-41048 - Set Anim Instance Class no longer works with Wheeled Vehicle Pawns

Change 3378518 on 2017/04/04 by Jon.Nabozny

	Fix jump height becoming frame dependent when JumpMaxHoldTime > 0.

	#jira UE-23695

Change 3378538 on 2017/04/04 by Martin.Wilson

	Speculative fix for unreproducable crash on loading animations

	#jira OR-37157

Change 3378592 on 2017/04/04 by Jurre.deBaare

	Mesh painting tools not working outside of QAGame
	#fix required a direct loadmodule call

Change 3378622 on 2017/04/04 by Jurre.deBaare

	CIS shadow variable fix

Change 3378742 on 2017/04/04 by Thomas.Sarkanen

	Fixed crash entering PIE in Orion

Change 3378907 on 2017/04/04 by Benn.Gallagher

	Re-added wind adaptiive effects to legacy wind path.
	Fixed math error in damping calculations (log2/loge).
	#jira UE-42044

Change 3379240 on 2017/04/04 by Jon.Nabozny

	Fix SkeletalMeshComponent GetWeldedBodies not returning actual Skeletal Bodies

Change 3379415 on 2017/04/04 by Jon.Nabozny

	Fix Skeletal Meshes imported with non-identity transform from reapplying transform when simulation is enabled / disabled.

	#JIRA UE-32598

Change 3379502 on 2017/04/04 by Lina.Halper

	Mirroring issue with flipping rotation due to not counting scale

	#jira: UE-33646, UE-34489
	#rb: Ori.Cohen
	#code review: Zak.Middleton

Change 3380544 on 2017/04/05 by Thomas.Sarkanen

	Fix warning spam when playing back UMG sequences animating visibility

	Reduced runtime overhead to a simple size check. This catches 90% of problem issues with much less runtime overhead. It would be well worth getting an FName-based type check working at some point, although we would need speciall case enum handling.
	Also removed message log usage in shipping/test builds.

	#jira UE-43621 - Large number of Sequencer warnings occur after opening Paragon in Pie - Property type mismatch for property 'Visibility'. Expected 'uint8', found 'ESlateVisibility'.

Change 3380605 on 2017/04/05 by Benn.Gallagher

	Fix clothing simulation to correctly index a master pose component for clothing pose data. Fixes integration blocking crash in UT when picking up the flag which sets a master pose mid-game.
	#jira UE-43624

Change 3381025 on 2017/04/05 by Jon.Nabozny

	Change ensure in UpdateKinematicBonesToAnim to ensureMsgf so we can track down potential content issues.

Change 3381475 on 2017/04/05 by Lina.Halper

	Fix crash on creating montage and setting slot node

	#jira: UE-43698
	#rb: Ori.Cohen

Change 3381558 on 2017/04/05 by Lina.Halper

	Better clean up of flipping issue of quaternion issue

	#jira: UE-33646, UE-34489
	#rb: Zak.Middleton

Change 3381789 on 2017/04/05 by Jon.Nabozny

	Revert InitAnim changes from CL-3379415 to fix cook warnings.
	(Will have proper fix for 4.17 instead).

Change 3381978 on 2017/04/05 by Aaron.McLeran

	#jira UE-43654 Fixing oculus audio SDK sample rate issue

Change 3383181 on 2017/04/06 by Lina.Halper

	Remove copy right of Dual quaternion since we no longer uses

	#code review:Leslie.Nivison

Change 3383283 on 2017/04/06 by Ori.Cohen

	Fixed missing invalidation for body setup when modifying materials

	#JIRA UE-43680

Change 3383602 on 2017/04/06 by Lina.Halper

	Fixed scroller in retargeting window

	#jira: UE-43736

Change 3384369 on 2017/04/07 by Jurre.deBaare

	Wrong bone is sometimes highlighted in skeleton editor
	#fix new behaviour caused the user to try and select a bone if we didn't find on through hit proxies
	#jira UE-43735

Change 3384744 on 2017/04/07 by Jon.Nabozny

	Fix body rotation being killed on load.

	#JIRA UE-43771

[CL 3385232 by Thomas Sarkanen in Main branch]
2017-04-07 16:51:51 -04:00

1162 lines
34 KiB
C++

// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Assets/ClothingAsset.h"
#include "PhysXPublic.h"
#if WITH_EDITOR
#include "Engine/SkeletalMesh.h"
#include "MeshUtilities.h"
#endif
#include "Components/SkeletalMeshComponent.h"
#include "PhysicsPublic.h"
#include "UObjectIterator.h"
#include "ModuleManager.h"
#include "SNotificationList.h"
#include "NotificationManager.h"
#include "ComponentReregisterContext.h"
DEFINE_LOG_CATEGORY(LogClothingAsset)
#define LOCTEXT_NAMESPACE "ClothingAsset"
UClothingAsset::UClothingAsset(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, ReferenceBoneIndex(0)
, CustomData(nullptr)
{
}
#if WITH_EDITOR
void LogAndToastClothingInfo(const FText& Error)
{
FNotificationInfo Info(Error);
Info.ExpireDuration = 5.0f;
FSlateNotificationManager::Get().AddNotification(Info);
UE_LOG(LogClothingAsset, Warning, TEXT("%s"), *Error.ToString());
}
bool UClothingAsset::BindToSkeletalMesh(USkeletalMesh* InSkelMesh, int32 InMeshLodIndex, int32 InSectionIndex, int32 InAssetLodIndex)
{
// If we've been added to the wrong mesh
if(InSkelMesh != GetOuter())
{
FText Error = FText::Format(LOCTEXT("Error_WrongMesh", "Failed to bind clothing asset {0} as the provided mesh is not the owner of this asset."), FText::FromString(GetName()));
LogAndToastClothingInfo(Error);
return false;
}
// If we don't have clothing data
if(!LodData.IsValidIndex(InAssetLodIndex))
{
FText Error = FText::Format(LOCTEXT("Error_NoClothingLod", "Failed to bind clothing asset {0} LOD{1} as LOD{2} does not exist."), FText::FromString(GetName()), FText::AsNumber(InAssetLodIndex), FText::AsNumber(InAssetLodIndex));
LogAndToastClothingInfo(Error);
return false;
}
// If we don't have a mesh
if(!InSkelMesh)
{
FText Error = FText::Format(LOCTEXT("Error_NoMesh", "Failed to bind clothing asset {0} as provided skel mesh does not exist."), FText::FromString(GetName()));
LogAndToastClothingInfo(Error);
return false;
}
// If the mesh LOD index is invalid
if(!InSkelMesh->GetImportedResource()->LODModels.IsValidIndex(InMeshLodIndex))
{
FText Error = FText::Format(LOCTEXT("Error_InvalidMeshLOD", "Failed to bind clothing asset {0} as mesh LOD{1} does not exist."), FText::FromString(GetName()), FText::AsNumber(InMeshLodIndex));
LogAndToastClothingInfo(Error);
return false;
}
const int32 NumMapEntries = LodMap.Num();
for(int MapIndex = 0; MapIndex < NumMapEntries; ++MapIndex)
{
const int32& MappedLod = LodMap[MapIndex];
if(MappedLod == InAssetLodIndex)
{
FText Error = FText::Format(LOCTEXT("Error_LodMapped", "Failed to bind clothing asset {0} LOD{1} as LOD{2} is already mapped to mesh LOD{3}."), FText::FromString(GetName()), FText::AsNumber(InAssetLodIndex), FText::AsNumber(InAssetLodIndex), FText::AsNumber(MapIndex));
LogAndToastClothingInfo(Error);
return false;
}
}
if(LodMap.IsValidIndex(InMeshLodIndex) && LodMap[InMeshLodIndex] != INDEX_NONE)
{
// Already mapped
return false;
}
BuildSelfCollisionData();
CalculateReferenceBoneIndex();
// Grab the clothing and skel lod data
FClothLODData& ClothLodData = LodData[InAssetLodIndex];
FStaticLODModel& SkelLod = InSkelMesh->GetImportedResource()->LODModels[InMeshLodIndex];
FSkelMeshSection* OriginalSection = &SkelLod.Sections[InSectionIndex];
FSkelMeshSection NewClothSection;
// Data for mesh to mesh binding
TArray<FMeshToMeshVertData> MeshToMeshData;
TArray<FVector> RenderPositions;
TArray<FVector> RenderNormals;
TArray<FVector> RenderTangents;
RenderPositions.Reserve(OriginalSection->SoftVertices.Num());
RenderNormals.Reserve(OriginalSection->SoftVertices.Num());
RenderTangents.Reserve(OriginalSection->SoftVertices.Num());
// Original data to weight to the clothing simulation mesh
for(FSoftSkinVertex& UnrealVert : OriginalSection->SoftVertices)
{
RenderPositions.Add(UnrealVert.Position);
RenderNormals.Add(UnrealVert.TangentZ);
RenderTangents.Add(UnrealVert.TangentX);
}
ClothingAssetUtils::GenerateMeshToMeshSkinningData(MeshToMeshData,
RenderPositions,
RenderNormals,
RenderTangents,
ClothLodData.PhysicalMeshData.Vertices,
ClothLodData.PhysicalMeshData.Normals,
ClothLodData.PhysicalMeshData.Indices);
if(MeshToMeshData.Num() == 0)
{
// Failed to generate skinning data, the function above will have notified
// with the cause of the failure, so just exit
return false;
}
// Calculate fixed verts
for(FMeshToMeshVertData& VertData : MeshToMeshData)
{
float TriangleDistanceMax = 0.0f;
TriangleDistanceMax += ClothLodData.PhysicalMeshData.MaxDistances[VertData.SourceMeshVertIndices[0]];
TriangleDistanceMax += ClothLodData.PhysicalMeshData.MaxDistances[VertData.SourceMeshVertIndices[1]];
TriangleDistanceMax += ClothLodData.PhysicalMeshData.MaxDistances[VertData.SourceMeshVertIndices[2]];
if(TriangleDistanceMax == 0.0f)
{
VertData.SourceMeshVertIndices[3] = 0xFFFF;
}
}
NewClothSection.SoftVertices = OriginalSection->SoftVertices;
NewClothSection.NumVertices = NewClothSection.SoftVertices.Num();
NewClothSection.BoneMap = OriginalSection->BoneMap;
NewClothSection.MaxBoneInfluences = OriginalSection->MaxBoneInfluences;
for(FName& BoneName : UsedBoneNames)
{
const int32 BoneIndex = InSkelMesh->RefSkeleton.FindBoneIndex(BoneName);
if(BoneIndex != INDEX_NONE)
{
NewClothSection.BoneMap.AddUnique(BoneIndex);
}
}
// Array of re-import contexts for components using this mesh
TIndirectArray<FComponentReregisterContext> ComponentContexts;
for (TObjectIterator<USkeletalMeshComponent> It; It; ++It)
{
USkeletalMeshComponent* Component = *It;
if (Component && !Component->IsTemplate() && Component->SkeletalMesh == InSkelMesh)
{
new(ComponentContexts) FComponentReregisterContext(Component);
}
}
// Ready to apply the changes
InSkelMesh->PreEditChange(nullptr);
// calculate LOD verts before adding our new section
uint32 NumLodVertices = 0;
for(const FSkelMeshSection& CurSection : SkelLod.Sections)
{
NumLodVertices += CurSection.GetNumVertices();
}
int32 NewSectionIdx = SkelLod.Sections.AddDefaulted();
SkelLod.Sections[NewSectionIdx] = SkelLod.Sections[InSectionIndex];
// Re set original here, may have just realloced
OriginalSection = &SkelLod.Sections[InSectionIndex];
FSkelMeshSection& ClothSection = SkelLod.Sections[NewSectionIdx];
ClothSection.bDisabled = false;
ClothSection.CorrespondClothSectionIndex = InSectionIndex;
OriginalSection->bDisabled = true;
OriginalSection->CorrespondClothSectionIndex = NewSectionIdx;
// Geo properties
ClothSection.SoftVertices = NewClothSection.SoftVertices;
ClothSection.NumVertices = NewClothSection.NumVertices;
ClothSection.BoneMap = NewClothSection.BoneMap;
ClothSection.MaxBoneInfluences = NewClothSection.MaxBoneInfluences;
// Set the asset index, used during rendering to pick the correct sim mesh buffer
int32 AssetIndex = INDEX_NONE;
check(InSkelMesh->MeshClothingAssets.Find(this, AssetIndex));
ClothSection.CorrespondClothAssetIndex = AssetIndex;
ClothSection.BaseVertexIndex = NumLodVertices;
// Material properties
ClothSection.MaterialIndex = OriginalSection->MaterialIndex;
ClothSection.TriangleSorting = OriginalSection->TriangleSorting;
ClothSection.bSelected = OriginalSection->bSelected;
ClothSection.bCastShadow = OriginalSection->bCastShadow;
ClothSection.bRecomputeTangent = OriginalSection->bRecomputeTangent;
ClothSection.bEnableClothLOD_DEPRECATED = OriginalSection->bEnableClothLOD_DEPRECATED;
// sim properties
ClothSection.ClothMappingData = MeshToMeshData;
ClothSection.PhysicalMeshVertices = ClothLodData.PhysicalMeshData.Vertices;
ClothSection.PhysicalMeshNormals = ClothLodData.PhysicalMeshData.Normals;
// Set asset links on both sections
ClothSection.ClothingData.AssetLodIndex = InAssetLodIndex;
ClothSection.ClothingData.AssetGuid = AssetGuid;
OriginalSection->ClothingData.AssetGuid = AssetGuid;
OriginalSection->ClothingData.AssetLodIndex = InAssetLodIndex;
// Copy original indices over
const int32 BaseIndexToCopy = OriginalSection->BaseIndex;
const int32 NumIndicesToCopy = OriginalSection->NumTriangles * 3;
const int32 BaseVertexOffset = ClothSection.BaseVertexIndex - OriginalSection->BaseVertexIndex;
FMultiSizeIndexContainerData NewIndexData;
SkelLod.MultiSizeIndexContainer.GetIndexBuffer(NewIndexData.Indices);
ClothSection.BaseIndex = NewIndexData.Indices.Num();
ClothSection.NumTriangles = OriginalSection->NumTriangles;
for(int32 CurrIdx = 0; CurrIdx < NumIndicesToCopy; ++CurrIdx)
{
int32 SourceIndex = NewIndexData.Indices[BaseIndexToCopy + CurrIdx];
NewIndexData.Indices.Add(SourceIndex + BaseVertexOffset);
}
SkelLod.NumVertices += ClothSection.GetNumVertices();
if(SkelLod.NumVertices > MAX_uint16)
{
NewIndexData.DataTypeSize = sizeof(uint32);
}
else
{
NewIndexData.DataTypeSize = sizeof(uint16);
}
SkelLod.MultiSizeIndexContainer.RebuildIndexBuffer(NewIndexData);
// Build adjacency info (Only need soft verts for cloth)
TArray<FSoftSkinVertex> TempVerts;
FMultiSizeIndexContainerData AdjacencyData;
SkelLod.GetVertices(TempVerts);
IMeshUtilities& MeshUtils = FModuleManager::Get().LoadModuleChecked<IMeshUtilities>("MeshUtilities");
MeshUtils.BuildSkeletalAdjacencyIndexBuffer(TempVerts, SkelLod.NumTexCoords, NewIndexData.Indices, AdjacencyData.Indices);
SkelLod.AdjacencyMultiSizeIndexContainer.RebuildIndexBuffer(AdjacencyData);
bool bRequireBoneChange = false;
for(FBoneIndexType& BoneIndex : ClothSection.BoneMap)
{
if(!SkelLod.RequiredBones.Contains(BoneIndex))
{
bRequireBoneChange = true;
if(InSkelMesh->RefSkeleton.IsValidIndex(BoneIndex))
{
SkelLod.RequiredBones.Add(BoneIndex);
SkelLod.ActiveBoneIndices.AddUnique(BoneIndex);
}
}
}
if(bRequireBoneChange)
{
SkelLod.RequiredBones.Sort();
InSkelMesh->RefSkeleton.EnsureParentExists(SkelLod.ActiveBoneIndices);
}
if(CustomData)
{
CustomData->BindToSkeletalMesh(InSkelMesh, InMeshLodIndex, InSectionIndex, InAssetLodIndex);
}
// Make sure the LOD map is always big enough for the asset to use.
// This shouldn't grow to an unwieldy size but maybe consider compacting later.
while(LodMap.Num() - 1 < InMeshLodIndex)
{
LodMap.Add(INDEX_NONE);
}
LodMap[InMeshLodIndex] = InAssetLodIndex;
InSkelMesh->PostEditChange();
return true;
// ComponentContexts goes out of scope, causing components to be re-registered
}
void UClothingAsset::UnbindFromSkeletalMesh(USkeletalMesh* InSkelMesh)
{
if(FSkeletalMeshResource* Mesh = InSkelMesh->GetImportedResource())
{
const int32 NumLods = Mesh->LODModels.Num();
for(int32 LodIndex = 0; LodIndex < NumLods; ++LodIndex)
{
UnbindFromSkeletalMesh(InSkelMesh, LodIndex);
}
}
}
void UClothingAsset::UnbindFromSkeletalMesh(USkeletalMesh* InSkelMesh, int32 InMeshLodIndex)
{
bool bChangedMesh = false;
// Find the chunk(s) we created
if(FSkeletalMeshResource* Mesh = InSkelMesh->GetImportedResource())
{
if(!Mesh->LODModels.IsValidIndex(InMeshLodIndex))
{
FText Error = FText::Format(LOCTEXT("Error_UnbindNoMeshLod", "Failed to remove clothing asset {0} from mesh LOD{1} as that LOD doesn't exist."), FText::FromString(GetName()), FText::AsNumber(InMeshLodIndex));
LogAndToastClothingInfo(Error);
return;
}
FStaticLODModel& LodModel = Mesh->LODModels[InMeshLodIndex];
{
for(int32 SectionIdx = LodModel.Sections.Num() - 1; SectionIdx >= 0; --SectionIdx)
{
FSkelMeshSection& ClothSection = LodModel.Sections[SectionIdx];
if(ClothSection.ClothingData.IsValid() && ClothSection.ClothingData.AssetGuid == AssetGuid)
{
// We made this one.
int32 OriginalSectionIdx = INDEX_NONE;
// Find the original section
for(int32 SearchIdx = 0; SearchIdx < LodModel.Sections.Num(); ++SearchIdx)
{
FSkelMeshSection& PossibleOriginalSection = LodModel.Sections[SearchIdx];
if(PossibleOriginalSection.CorrespondClothSectionIndex == SectionIdx)
{
OriginalSectionIdx = SearchIdx;
break;
}
}
check(OriginalSectionIdx != INDEX_NONE);
InSkelMesh->PreEditChange(nullptr);
FSkelMeshSection& OriginalSection = LodModel.Sections[OriginalSectionIdx];
FMultiSizeIndexContainerData NewIndexData;
LodModel.MultiSizeIndexContainer.GetIndexBuffer(NewIndexData.Indices);
uint32 NumIndicesToRemove = ClothSection.NumTriangles * 3;
uint32 BaseIndexToRemove = ClothSection.BaseIndex;
uint32 NumVertsToRemove = ClothSection.GetNumVertices();
uint32 BaseVertToRemove = ClothSection.BaseVertexIndex;
// Remove from index buffer
NewIndexData.Indices.RemoveAt(BaseIndexToRemove, NumIndicesToRemove);
// Fix up remaining indices (can this start at baseindextoremove?)
for(uint32& Index : NewIndexData.Indices)
{
if(Index >= BaseVertToRemove)
{
Index -= NumVertsToRemove;
}
}
// Count resulting vertices
int32 NumVertsAfter = 0;
for(int32 ResultSectionsIndex = 0; ResultSectionsIndex < SectionIdx; ++ResultSectionsIndex)
{
NumVertsAfter += LodModel.Sections[ResultSectionsIndex].NumVertices;
}
if(NumVertsAfter > MAX_uint16)
{
NewIndexData.DataTypeSize = sizeof(uint16);
}
else
{
NewIndexData.DataTypeSize = sizeof(uint32);
}
// Push back to buffer
LodModel.MultiSizeIndexContainer.RebuildIndexBuffer(NewIndexData);
LodModel.Sections.RemoveAt(SectionIdx);
LodModel.NumVertices -= NumVertsToRemove;
// Fix up other data
for(FSkelMeshSection& Section : LodModel.Sections)
{
if(Section.CorrespondClothSectionIndex > OriginalSection.CorrespondClothSectionIndex)
{
// We removed one here, so knock back
Section.CorrespondClothSectionIndex -= 1;
}
if(Section.BaseIndex > BaseIndexToRemove)
{
Section.BaseIndex -= NumIndicesToRemove;
}
if(Section.BaseVertexIndex > BaseVertToRemove)
{
Section.BaseVertexIndex -= NumVertsToRemove;
}
}
// Enable rendering for section
OriginalSection.bDisabled = false;
// Clear cloth link data
OriginalSection.CorrespondClothSectionIndex = INDEX_NONE;
OriginalSection.ClothingData.AssetLodIndex = INDEX_NONE;
OriginalSection.ClothingData.AssetGuid = FGuid();
// Track the mesh change so we can re-register later
bChangedMesh = true;
// Set the LOD map so nothing is mapped for this asset
LodMap[InMeshLodIndex] = INDEX_NONE;
InSkelMesh->PostEditChange();
}
}
}
}
// If the mesh changed we need to re-register any components that use it to reflect the changes
if(bChangedMesh)
{
for(TObjectIterator<USkeletalMeshComponent> It; It; ++It)
{
USkeletalMeshComponent* MeshComponent = *It;
if(MeshComponent &&
!MeshComponent->IsTemplate() &&
MeshComponent->SkeletalMesh == InSkelMesh)
{
MeshComponent->ReregisterComponent();
}
}
}
}
void UClothingAsset::RefreshBoneMapping(USkeletalMesh* InSkelMesh)
{
// No mesh, can't remap
if(!InSkelMesh)
{
return;
}
if(UsedBoneNames.Num() != UsedBoneIndices.Num())
{
UsedBoneIndices.Reset();
UsedBoneIndices.AddDefaulted(UsedBoneNames.Num());
}
// Repopulate the used indices.
for(int32 BoneNameIndex = 0; BoneNameIndex < UsedBoneNames.Num(); ++BoneNameIndex)
{
UsedBoneIndices[BoneNameIndex] = InSkelMesh->RefSkeleton.FindBoneIndex(UsedBoneNames[BoneNameIndex]);
}
}
void UClothingAsset::InvalidateCachedData()
{
for(FClothLODData& CurrentLodData : LodData)
{
// Recalculate inverse masses for the physical mesh particles
FClothPhysicalMeshData& PhysMesh = CurrentLodData.PhysicalMeshData;
check(PhysMesh.Indices.Num() % 3 == 0);
TArray<float>& InvMasses = PhysMesh.InverseMasses;
const int32 NumVerts = PhysMesh.Vertices.Num();
InvMasses.Empty(NumVerts);
InvMasses.AddZeroed(NumVerts);
for(int32 TriBaseIndex = 0; TriBaseIndex < PhysMesh.Indices.Num(); TriBaseIndex += 3)
{
const int32 Index0 = PhysMesh.Indices[TriBaseIndex];
const int32 Index1 = PhysMesh.Indices[TriBaseIndex + 1];
const int32 Index2 = PhysMesh.Indices[TriBaseIndex + 2];
const FVector AB = PhysMesh.Vertices[Index1] - PhysMesh.Vertices[Index0];
const FVector AC = PhysMesh.Vertices[Index2] - PhysMesh.Vertices[Index0];
const float TriArea = FVector::CrossProduct(AB, AC).Size();
InvMasses[Index0] += TriArea;
InvMasses[Index1] += TriArea;
InvMasses[Index2] += TriArea;
}
PhysMesh.NumFixedVerts = 0;
float MassSum = 0.0f;
for(int32 CurrVertIndex = 0; CurrVertIndex < NumVerts; ++CurrVertIndex)
{
float& InvMass = InvMasses[CurrVertIndex];
const float& MaxDistance = PhysMesh.MaxDistances[CurrVertIndex];
if(MaxDistance < SMALL_NUMBER)
{
InvMass = 0.0f;
++PhysMesh.NumFixedVerts;
}
else
{
MassSum += InvMass;
}
}
const float MassScale = (float)(NumVerts - PhysMesh.NumFixedVerts) / MassSum;
for(float& InvMass : InvMasses)
{
InvMass *= MassScale;
InvMass = 1.0f / InvMass;
}
}
}
void UClothingAsset::BuildLodTransitionData()
{
// Temporary until mesh to mesh is refactored to allow not having all inputs available
TArray<FVector> DummyTangentArray;
const int32 NumLods = LodData.Num();
for(int32 LodIndex = 0; LodIndex < NumLods; ++LodIndex)
{
const bool bHasPrevLod = LodIndex > 0;
const bool bHasNextLod = LodIndex < NumLods - 1;
FClothLODData& CurrentLod = LodData[LodIndex];
FClothPhysicalMeshData& CurrentPhysMesh = CurrentLod.PhysicalMeshData;
FClothLODData* PrevLod = bHasPrevLod ? &LodData[LodIndex - 1] : nullptr;
FClothLODData* NextLod = bHasNextLod ? &LodData[LodIndex + 1] : nullptr;
const int32 CurrentLodNumVerts = CurrentPhysMesh.Vertices.Num();
DummyTangentArray.Empty(CurrentLodNumVerts);
DummyTangentArray.AddDefaulted(CurrentLodNumVerts);
if(PrevLod)
{
FClothPhysicalMeshData& PrevPhysMesh = PrevLod->PhysicalMeshData;
CurrentLod.TransitionUpSkinData.Empty(CurrentLodNumVerts);
ClothingAssetUtils::GenerateMeshToMeshSkinningData(CurrentLod.TransitionUpSkinData, CurrentPhysMesh.Vertices, CurrentPhysMesh.Normals, DummyTangentArray, PrevPhysMesh.Vertices, PrevPhysMesh.Normals, PrevPhysMesh.Indices);
}
if(NextLod)
{
FClothPhysicalMeshData& NextPhysMesh = NextLod->PhysicalMeshData;
CurrentLod.TransitionDownSkinData.Empty(CurrentLodNumVerts);
ClothingAssetUtils::GenerateMeshToMeshSkinningData(CurrentLod.TransitionDownSkinData, CurrentPhysMesh.Vertices, CurrentPhysMesh.Normals, DummyTangentArray, NextPhysMesh.Vertices, NextPhysMesh.Normals, NextPhysMesh.Indices);
}
}
}
bool UClothingAsset::IsValidLod(int32 InLodIndex)
{
return LodData.IsValidIndex(InLodIndex);
}
int32 UClothingAsset::GetNumLods()
{
return LodData.Num();
}
#endif
void UClothingAsset::BuildSelfCollisionData()
{
if(!ClothConfig.HasSelfCollision())
{
// No self collision, can't generate data
return;
}
// We can inflate here by close to half, because we're only trying to make it so the spheres
// can't pass through the network of other spheres.
const float SCRadius = ClothConfig.SelfCollisionRadius * 1.4f;
const float SCRadiusSq = SCRadius * SCRadius;
for(FClothLODData& Lod : LodData)
{
FClothPhysicalMeshData& PhysMesh = Lod.PhysicalMeshData;
// Start with the full set
const int32 NumVerts = PhysMesh.Vertices.Num();
PhysMesh.SelfCollisionIndices.Reset();
for(int32 Index = 0; Index < NumVerts; ++Index)
{
PhysMesh.SelfCollisionIndices.Add(Index);
}
// Strip any verts that are fixed from the beginning of the array so we always
// start with a valid movable vertex
int32 PrepassIndex = PhysMesh.SelfCollisionIndices[0];
while(PhysMesh.MaxDistances[PrepassIndex] < SMALL_NUMBER)
{
PhysMesh.SelfCollisionIndices.RemoveAt(0);
if(PhysMesh.SelfCollisionIndices.Num() > 0)
{
// Take index again
PrepassIndex = PhysMesh.SelfCollisionIndices[0];
}
else
{
// We've cleared out the array, bail as we have no movable verts
break;
}
}
// Now start aggresively culling verts that are near others that we have accepted
for(int32 Vert0Itr = 0; Vert0Itr < PhysMesh.SelfCollisionIndices.Num(); ++Vert0Itr)
{
uint32 V0Index = PhysMesh.SelfCollisionIndices[Vert0Itr];
const FVector& V0Pos = PhysMesh.Vertices[V0Index];
float MaxDist0 = PhysMesh.MaxDistances[V0Index];
// Start one after our current V0, we've done the other checks
for(int32 Vert1Itr = Vert0Itr + 1; Vert1Itr < PhysMesh.SelfCollisionIndices.Num(); )
{
uint32 V1Index = PhysMesh.SelfCollisionIndices[Vert1Itr];
const FVector& V1Pos = PhysMesh.Vertices[V1Index];
float V0ToV1DistSq = (V1Pos - V0Pos).SizeSquared();
float MaxDist1 = PhysMesh.MaxDistances[V1Index];
if(V0ToV1DistSq < SCRadiusSq || MaxDist1 < SMALL_NUMBER)
{
// Too close, remove it
PhysMesh.SelfCollisionIndices.RemoveAt(Vert1Itr);
continue;
}
else
{
// Move to next if we didn't remove
++Vert1Itr;
}
}
}
}
}
void UClothingAsset::PostLoad()
{
Super::PostLoad();
BuildSelfCollisionData();
#if WITH_EDITORONLY_DATA
CalculateReferenceBoneIndex();
#endif
}
void UClothingAsset::CalculateReferenceBoneIndex()
{
// Starts at root
ReferenceBoneIndex = 0;
// Find the root bone for this clothing asset (common bone for all used bones)
typedef TArray<int32> BoneIndexArray;
// List of valid paths to the root bone from each weighted bone
TArray<BoneIndexArray> PathsToRoot;
USkeletalMesh* OwnerMesh = Cast<USkeletalMesh>(GetOuter());
if(OwnerMesh)
{
FReferenceSkeleton& RefSkel = OwnerMesh->RefSkeleton;
// First build a list per used bone for it's path to root
const int32 NumUsedBones = UsedBoneIndices.Num();
// List of actually weighted (not just used) bones
TArray<int32> WeightedBones;
for(FClothLODData& CurLod : LodData)
{
FClothPhysicalMeshData& MeshData = CurLod.PhysicalMeshData;
for(FClothVertBoneData& VertBoneData : MeshData.BoneData)
{
for(int32 InfluenceIndex = 0; InfluenceIndex < MAX_TOTAL_INFLUENCES; ++InfluenceIndex)
{
if(VertBoneData.BoneWeights[InfluenceIndex] > SMALL_NUMBER)
{
WeightedBones.AddUnique(VertBoneData.BoneIndices[InfluenceIndex]);
}
else
{
// Hit the last weight (they're sorted)
break;
}
}
}
}
const int32 NumWeightedBones = WeightedBones.Num();
PathsToRoot.Reserve(NumWeightedBones);
// Compute paths to the root bone
for(int32 WeightedBoneIndex = 0; WeightedBoneIndex < NumWeightedBones; ++WeightedBoneIndex)
{
PathsToRoot.AddDefaulted();
BoneIndexArray& Path = PathsToRoot.Last();
int32 CurrentBone = WeightedBones[WeightedBoneIndex];
Path.Add(CurrentBone);
while(CurrentBone != 0 && CurrentBone != INDEX_NONE)
{
CurrentBone = RefSkel.GetParentIndex(CurrentBone);
Path.Add(CurrentBone);
}
}
// Paths are from leaf->root, we want the other way
for(BoneIndexArray& Path : PathsToRoot)
{
Algo::Reverse(Path);
}
// Verify the last common bone in all paths as the root of the sim space
const int32 NumPaths = PathsToRoot.Num();
if(NumPaths > 0)
{
BoneIndexArray& FirstPath = PathsToRoot[0];
const int32 FirstPathSize = FirstPath.Num();
for(int32 PathEntryIndex = 0; PathEntryIndex < FirstPathSize; ++PathEntryIndex)
{
const int32 CurrentQueryIndex = FirstPath[PathEntryIndex];
bool bValidRoot = true;
for(int32 PathIndex = 1; PathIndex < NumPaths; ++PathIndex)
{
if(!PathsToRoot[PathIndex].Contains(CurrentQueryIndex))
{
bValidRoot = false;
break;
}
}
if(bValidRoot)
{
ReferenceBoneIndex = CurrentQueryIndex;
}
else
{
// Once we fail to find a valid root we're done.
break;
}
}
}
else
{
// Just use root
ReferenceBoneIndex = 0;
}
}
}
void ClothingAssetUtils::GetMeshClothingAssetBindings(USkeletalMesh* InSkelMesh, TArray<FClothingAssetMeshBinding>& OutBindings)
{
OutBindings.Empty();
if(!InSkelMesh)
{
return;
}
if(FSkeletalMeshResource* Resource = InSkelMesh->GetImportedResource())
{
const int32 NumLods = Resource->LODModels.Num();
for(int32 LodIndex = 0; LodIndex < NumLods; ++LodIndex)
{
TArray<FClothingAssetMeshBinding> LodBindings;
GetMeshClothingAssetBindings(InSkelMesh, LodBindings, LodIndex);
OutBindings.Append(LodBindings);
}
}
}
void ClothingAssetUtils::GetMeshClothingAssetBindings(USkeletalMesh* InSkelMesh, TArray<FClothingAssetMeshBinding>& OutBindings, int32 InLodIndex)
{
OutBindings.Empty();
if(!InSkelMesh)
{
return;
}
if(FSkeletalMeshResource* Resource = InSkelMesh->GetImportedResource())
{
if(Resource->LODModels.IsValidIndex(InLodIndex))
{
FStaticLODModel& LodModel = Resource->LODModels[InLodIndex];
const int32 NumSections = LodModel.Sections.Num();
for(int32 SectionIndex = 0; SectionIndex < NumSections; ++SectionIndex)
{
FSkelMeshSection& Section = LodModel.Sections[SectionIndex];
if(Section.bDisabled && Section.CorrespondClothSectionIndex != INDEX_NONE)
{
UClothingAsset* SectionAsset = Cast<UClothingAsset>(InSkelMesh->GetSectionClothingAsset(InLodIndex, SectionIndex));
if(SectionAsset)
{
// This is the original section of a clothing section pair
OutBindings.AddDefaulted();
FClothingAssetMeshBinding& Binding = OutBindings.Last();
Binding.Asset = SectionAsset;
Binding.LODIndex = InLodIndex;
Binding.SectionIndex = SectionIndex;
Binding.AssetInternalLodIndex = Section.ClothingData.AssetLodIndex;
}
}
}
}
}
}
void ClothingAssetUtils::GenerateMeshToMeshSkinningData(TArray<FMeshToMeshVertData>& OutSkinningData, const TArray<FVector>& Mesh0Verts, const TArray<FVector>& Mesh0Normals, const TArray<FVector>& Mesh0Tangents, const TArray<FVector>& Mesh1Verts, const TArray<FVector>& Mesh1Normals, const TArray<uint32>& Mesh1Indices)
{
const int32 NumMesh0Verts = Mesh0Verts.Num();
const int32 NumMesh0Normals = Mesh0Normals.Num();
const int32 NumMesh0Tangents = Mesh0Tangents.Num();
const int32 NumMesh1Verts = Mesh1Verts.Num();
const int32 NumMesh1Normals = Mesh1Normals.Num();
const int32 NumMesh1Indices = Mesh1Indices.Num();
// Check we have properly formed triangles
check(NumMesh1Indices % 3 == 0);
const int32 NumMesh1Triangles = NumMesh1Indices / 3;
// Check mesh data to make sure we have the same number of each element
if((NumMesh0Verts + NumMesh0Normals) / NumMesh0Tangents != 2)
{
UE_LOG(LogClothingAsset, Warning, TEXT("Can't generate mesh to mesh skinning data, Mesh0 data is missing verts."));
return;
}
if(NumMesh1Verts != NumMesh1Normals)
{
UE_LOG(LogClothingAsset, Warning, TEXT("Can't generate mesh to mesh skinning data, Mesh1 data is missing verts."));
return;
}
OutSkinningData.Reserve(NumMesh0Verts);
// For all mesh0 verts
for(int32 VertIdx0 = 0; VertIdx0 < NumMesh0Verts; ++VertIdx0)
{
OutSkinningData.AddZeroed();
FMeshToMeshVertData& SkinningData = OutSkinningData.Last();
const FVector& VertPosition = Mesh0Verts[VertIdx0];
const FVector& VertNormal = Mesh0Normals[VertIdx0];
const FVector& VertTangent = Mesh0Tangents[VertIdx0];
float MinimumDistanceSq = MAX_flt;
int32 ClosestTriangleBaseIdx = INDEX_NONE;
// For all mesh1 triangles
for(int32 Mesh1TriangleIdx = 0; Mesh1TriangleIdx < NumMesh1Triangles; ++Mesh1TriangleIdx)
{
int32 TriangleBaseIdx = Mesh1TriangleIdx * 3;
const FVector& A = Mesh1Verts[Mesh1Indices[TriangleBaseIdx]];
const FVector& B = Mesh1Verts[Mesh1Indices[TriangleBaseIdx + 1]];
const FVector& C = Mesh1Verts[Mesh1Indices[TriangleBaseIdx + 2]];
FVector PointOnTri = FMath::ClosestPointOnTriangleToPoint(VertPosition, A, B, C);
float DistSq = (PointOnTri - VertPosition).SizeSquared();
if(DistSq < MinimumDistanceSq)
{
MinimumDistanceSq = DistSq;
ClosestTriangleBaseIdx = TriangleBaseIdx;
}
}
// Should have found at least one triangle
check(ClosestTriangleBaseIdx != INDEX_NONE);
const FVector& A = Mesh1Verts[Mesh1Indices[ClosestTriangleBaseIdx]];
const FVector& B = Mesh1Verts[Mesh1Indices[ClosestTriangleBaseIdx + 1]];
const FVector& C = Mesh1Verts[Mesh1Indices[ClosestTriangleBaseIdx + 2]];
const FVector& NA = Mesh1Normals[Mesh1Indices[ClosestTriangleBaseIdx]];
const FVector& NB = Mesh1Normals[Mesh1Indices[ClosestTriangleBaseIdx + 1]];
const FVector& NC = Mesh1Normals[Mesh1Indices[ClosestTriangleBaseIdx + 2]];
// Before generating the skinning data we need to check for a degenerate triangle.
// If we find _any_ degenerate triangles we will notify and fail to generate the skinning data
const FVector TriNormal = FVector::CrossProduct(B - A, C - A);
if(TriNormal.SizeSquared() < SMALL_NUMBER)
{
// Failed, we have 2 identical vertices
OutSkinningData.Reset();
// Log and toast
FText Error = FText::Format(LOCTEXT("DegenerateTriangleError", "Failed to generate skinning data, found conincident vertices in triangle A={0} B={1} C={2}"), FText::FromString(A.ToString()), FText::FromString(B.ToString()), FText::FromString(C.ToString()));
UE_LOG(LogClothingAsset, Warning, TEXT("%s"), *Error.ToString());
#if WITH_EDITOR
FNotificationInfo Info(Error);
Info.ExpireDuration = 5.0f;
FSlateNotificationManager::Get().AddNotification(Info);
#endif
return;
}
SkinningData.PositionBaryCoordsAndDist = GetPointBaryAndDist(A, B, C, NA, NB, NC, VertPosition);
SkinningData.NormalBaryCoordsAndDist = GetPointBaryAndDist(A, B, C, NA, NB, NC, VertPosition + VertNormal);
SkinningData.TangentBaryCoordsAndDist = GetPointBaryAndDist(A, B, C, NA, NB, NC, VertPosition + VertTangent);
SkinningData.SourceMeshVertIndices[0] = Mesh1Indices[ClosestTriangleBaseIdx];
SkinningData.SourceMeshVertIndices[1] = Mesh1Indices[ClosestTriangleBaseIdx + 1];
SkinningData.SourceMeshVertIndices[2] = Mesh1Indices[ClosestTriangleBaseIdx + 2];
SkinningData.SourceMeshVertIndices[3] = 0;
}
}
FVector4 ClothingAssetUtils::GetPointBaryAndDist(const FVector& A, const FVector& B, const FVector& C, const FVector& NA, const FVector& NB, const FVector& NC, const FVector& Point)
{
FPlane TrianglePlane(A, B, C);
const FVector PointOnTriPlane = FVector::PointPlaneProject(Point, TrianglePlane);
const FVector BaryCoords = FMath::ComputeBaryCentric2D(PointOnTriPlane, A, B, C);
const FVector NormalAtPoint = TrianglePlane;
FVector TriPointToVert = Point - PointOnTriPlane;
TriPointToVert = TriPointToVert.ProjectOnTo(NormalAtPoint);
float Dist = TriPointToVert.Size();
float Sign = TrianglePlane.PlaneDot(Point) < 0.0f ? -1.0f : 1.0f;
return FVector4(BaryCoords, TrianglePlane.PlaneDot(Point));
}
bool FClothConfig::HasSelfCollision() const
{
return SelfCollisionRadius > 0.0f && SelfCollisionStiffness > 0.0f;
}
void FClothCollisionData::Reset()
{
Spheres.Reset();
SphereConnections.Reset();
Convexes.Reset();
}
void FClothCollisionData::Append(const FClothCollisionData& InOther)
{
const int32 NumSpheresBefore = Spheres.Num();
const int32 NumSphereConnectionsBefore = SphereConnections.Num();
Spheres.Append(InOther.Spheres);
SphereConnections.Append(InOther.SphereConnections);
const int32 NumSphereConnectionsAfter = SphereConnections.Num();
if(NumSpheresBefore > 0)
{
// Each connection that was added needs to have its sphere indices increased to match the new spheres that were added
for(int32 NewConnectionIndex = NumSphereConnectionsBefore; NewConnectionIndex < NumSphereConnectionsAfter; ++NewConnectionIndex)
{
FClothCollisionPrim_SphereConnection& Connection = SphereConnections[NewConnectionIndex];
Connection.SphereIndices[0] += NumSpheresBefore;
Connection.SphereIndices[1] += NumSpheresBefore;
}
}
Convexes.Append(InOther.Convexes);
}
void FClothPhysicalMeshData::Reset(const int32 InNumVerts)
{
Vertices.Reset();
Normals.Reset();
MaxDistances.Reset();
BackstopDistances.Reset();
BackstopRadiuses.Reset();
InverseMasses.Reset();
BoneData.Reset();
Vertices.AddDefaulted(InNumVerts);
Normals.AddDefaulted(InNumVerts);
MaxDistances.AddDefaulted(InNumVerts);
BackstopDistances.AddDefaulted(InNumVerts);
BackstopRadiuses.AddDefaulted(InNumVerts);
InverseMasses.AddDefaulted(InNumVerts);
BoneData.AddDefaulted(InNumVerts);
MaxBoneWeights = 0;
NumFixedVerts = 0;
}
void FClothParameterMask_PhysMesh::Initialize(const FClothPhysicalMeshData& InMeshData)
{
const int32 NumVerts = InMeshData.Vertices.Num();
// Set up value array
Values.Reset(NumVerts);
Values.AddZeroed(NumVerts);
}
void FClothParameterMask_PhysMesh::SetValue(int32 InVertexIndex, float InValue)
{
if(InVertexIndex < Values.Num())
{
Values[InVertexIndex] = InValue;
float TempMax = 0.0f;
for(const float& Value : Values)
{
TempMax = FMath::Max(TempMax, Value);
}
MaxValue = TempMax;
}
}
float FClothParameterMask_PhysMesh::GetValue(int32 InVertexIndex) const
{
return InVertexIndex < Values.Num() ? Values[InVertexIndex] : 0.0f;
}
#if WITH_EDITOR
void FClothParameterMask_PhysMesh::CalcRanges()
{
MinValue = MAX_flt;
MaxValue = -MinValue;
for(const float& Value : Values)
{
MaxValue = FMath::Max(Value, MaxValue);
if(Value > 0.0f)
{
MinValue = FMath::Min(Value, MinValue);
}
}
}
FColor FClothParameterMask_PhysMesh::GetValueAsColor(int32 InVertexIndex) const
{
if(InVertexIndex < Values.Num())
{
const float& Value = Values[InVertexIndex];
if(Value == 0.0f)
{
return FColor::Magenta;
}
uint8 ScaledValue = uint8(((Value - MinValue) / (MaxValue - MinValue)) * 255.0f);
return FColor(ScaledValue, ScaledValue, ScaledValue);
}
return FColor::Red;
}
#endif
void FClothParameterMask_PhysMesh::Apply(FClothPhysicalMeshData& InTargetMesh)
{
if(CurrentTarget == MaskTarget_PhysMesh::None)
{
// Nothing to do here, just return
return;
}
const int32 NumValues = Values.Num();
const int32 NumTargetMeshVerts = InTargetMesh.Vertices.Num();
if(NumTargetMeshVerts == NumValues)
{
TArray<float>* TargetArray = nullptr;
switch(CurrentTarget)
{
case MaskTarget_PhysMesh::MaxDistance:
TargetArray = &InTargetMesh.MaxDistances;
break;
case MaskTarget_PhysMesh::BackstopDistance:
TargetArray = &InTargetMesh.BackstopDistances;
break;
case MaskTarget_PhysMesh::BackstopRadius:
TargetArray = &InTargetMesh.BackstopRadiuses;
break;
default:
break;
}
if(!TargetArray)
{
return;
}
check((*TargetArray).Num() == NumValues);
for(int32 Index = 0; Index < NumTargetMeshVerts; ++Index)
{
(*TargetArray)[Index] = Values[Index];
}
}
else
{
UE_LOG(LogClothingAsset, Warning, TEXT("Aborted applying mask to physical mesh at %p, value mismatch (NumValues: %d, NumVerts: %d)."), &InTargetMesh, NumValues, NumTargetMeshVerts);
}
}
#undef LOCTEXT_NAMESPACE