コード例 #1
0
/** Loc is an anchor point in the world to guide which part of the infinite plane to draw. */
void DrawDebugSolidPlane(const UWorld* InWorld, FPlane const& P, FVector const& Loc, float Size, FColor const& Color, bool bPersistent, float LifeTime, uint8 DepthPriority)
{
	// no debug line drawing on dedicated server
	if (GEngine->GetNetMode(InWorld) != NM_DedicatedServer)
	{
		FVector const ClosestPtOnPlane = Loc - P.PlaneDot(Loc) * P;

		FVector U, V;
		P.FindBestAxisVectors(U, V);
		U *= Size;
		V *= Size;

		TArray<FVector> Verts;
		Verts.AddUninitialized(4);
		Verts[0] = ClosestPtOnPlane + U + V;
		Verts[1] = ClosestPtOnPlane - U + V;
		Verts[2] = ClosestPtOnPlane + U - V;
		Verts[3] = ClosestPtOnPlane - U - V;

		TArray<int32> Indices;
		Indices.AddUninitialized(6);
		Indices[0] = 0; Indices[1] = 2; Indices[2] = 1;
		Indices[3] = 1; Indices[4] = 2; Indices[5] = 3;

		// plane quad
		DrawDebugMesh(InWorld, Verts, Indices, Color, bPersistent, LifeTime, DepthPriority);

		// arrow indicating normal
		DrawDebugDirectionalArrow(InWorld, ClosestPtOnPlane, ClosestPtOnPlane + P * 16.f, 8.f, FColor::White, bPersistent, LifeTime, DepthPriority);
	}
}
コード例 #2
0
void FAnimationRuntime::BlendPosesTogetherPerBone(const TArray<FCompactPose>& SourcePoses, const TArray<FBlendedCurve>& SourceCurves, const UBlendSpaceBase* BlendSpace, const TArray<FBlendSampleData>& BlendSampleDataCache, /*out*/ FCompactPose& ResultPose, /*out*/ FBlendedCurve& ResultCurve)
{
	check(SourcePoses.Num() > 0);

	const TArray<FBoneIndexType> & RequiredBoneIndices = ResultPose.GetBoneContainer().GetBoneIndicesArray();

	TArray<int32> PerBoneIndices;
	PerBoneIndices.AddUninitialized(ResultPose.GetNumBones());
	for (int32 BoneIndex = 0; BoneIndex < PerBoneIndices.Num(); ++BoneIndex)
	{
		PerBoneIndices[BoneIndex] = BlendSpace->GetPerBoneInterpolationIndex(RequiredBoneIndices[BoneIndex], ResultPose.GetBoneContainer());
	}

	BlendPosePerBone<ETransformBlendMode::Overwrite>(PerBoneIndices, BlendSampleDataCache[0], ResultPose, SourcePoses[0]);

	for (int32 i = 1; i < SourcePoses.Num(); ++i)
	{
		BlendPosePerBone<ETransformBlendMode::Accumulate>(PerBoneIndices, BlendSampleDataCache[i], ResultPose, SourcePoses[i]);
	}

	// Ensure that all of the resulting rotations are normalized
	ResultPose.NormalizeRotations();

	if (SourceCurves.Num() > 0)
	{
		TArray<float> SourceWeights;
		SourceWeights.AddUninitialized(BlendSampleDataCache.Num());
		for (int32 CacheIndex=0; CacheIndex<BlendSampleDataCache.Num(); ++CacheIndex)
		{
			SourceWeights[CacheIndex] = BlendSampleDataCache[CacheIndex].TotalWeight;
		}

		BlendCurves(SourceCurves, SourceWeights, ResultCurve);
	}
}
コード例 #3
0
ファイル: BuildPatchUtil.cpp プロジェクト: xiangyuan/Unreal4
bool FBuildPatchUtils::UncompressFileDataFile(TArray< uint8 >& DataFileArray, FChunkHeader* OutHeader/* = nullptr*/)
{
	FChunkHeader Header;
	if (OutHeader == nullptr)
	{
		OutHeader = &Header;
	}
	FMemoryReader FileArrayReader(DataFileArray);
	// Read the header
	FileArrayReader << *OutHeader;
	// Check header
	const bool bValidHeader = OutHeader->IsValidMagic();
	const bool bSupportedFormat = !(OutHeader->StoredAs & FChunkHeader::STORED_ENCRYPTED);
	if (bValidHeader && bSupportedFormat)
	{
		bool bSuccess = true;
		// Uncompress if we need to
		if (OutHeader->StoredAs == FChunkHeader::STORED_COMPRESSED)
		{
			// Load the compressed data
			const int32 CompressedSize = DataFileArray.Num() - OutHeader->HeaderSize;
			TArray< uint8 > CompressedData;
			TArray< uint8 > UncompressedData;
			CompressedData.Empty(CompressedSize);
			CompressedData.AddUninitialized(CompressedSize);
			UncompressedData.Empty(OutHeader->DataSize);
			UncompressedData.AddUninitialized(OutHeader->DataSize);
			FileArrayReader.Serialize(CompressedData.GetData(), CompressedSize);
			FileArrayReader.Close();
			// Uncompress
			bSuccess = FCompression::UncompressMemory(
				static_cast<ECompressionFlags>(COMPRESS_ZLIB | COMPRESS_BiasMemory),
				UncompressedData.GetData(),
				UncompressedData.Num(),
				CompressedData.GetData(),
				CompressedData.Num());
			// If successful, write back over the original array
			if (bSuccess)
			{
				DataFileArray.Empty();
				FMemoryWriter FileArrayWriter(DataFileArray);
				OutHeader->StoredAs = FChunkHeader::STORED_RAW;
				FileArrayWriter << *OutHeader;
				FileArrayWriter.Serialize(UncompressedData.GetData(), UncompressedData.Num());
				FileArrayWriter.Close();
			}
		}
		return bSuccess;
	}
	return false;
}
コード例 #4
0
TArray<uint8> UGTCaptureComponent::CaptureNpyFloat16(FString Mode, int32 Channels)
{
	// Flush location and rotation
	check(CaptureComponents.Num() != 0);
	USceneCaptureComponent2D* CaptureComponent = CaptureComponents.FindRef(Mode);

	TArray<uint8> NpyData;
	if (CaptureComponent == nullptr) {
	  UE_LOG(LogUnrealCV, Error, TEXT("Component for mode %s not found. Returning empty array."), *Mode);
		return NpyData;
  }

	// Attach this to something, for example, a real camera
	const FRotator PawnViewRotation = Pawn->GetViewRotation();
	if (!PawnViewRotation.Equals(CaptureComponent->GetComponentRotation()))
	{
		CaptureComponent->SetWorldRotation(PawnViewRotation);
	}

	UTextureRenderTarget2D* RenderTarget = CaptureComponent->TextureTarget;
	int32 Width = RenderTarget->SizeX, Height = RenderTarget->SizeY;
	TArray<FFloat16Color> ImageData;
	FTextureRenderTargetResource* RenderTargetResource;
	ImageData.AddUninitialized(Width * Height);
	RenderTargetResource = RenderTarget->GameThread_GetRenderTargetResource();
	RenderTargetResource->ReadFloat16Pixels(ImageData);

	// Check the byte order of data
	// Compress image data to npy array
	// Generate a header for the numpy array
	NpyData = NpySerialization(ImageData, Width, Height, Channels);

	return NpyData;
}
コード例 #5
0
	bool FFileAttributesParserImpl::ParseFileAttributes(const FString& MetaFilename, TMap<FString, FFileAttributes>& FileAttributes)
	{
		TAutoPtr<IFileHandle> Handle(PlatformFile.OpenRead(*MetaFilename));
		if (Handle.IsValid())
		{
			TArray<uint8> FileData;
			FileData.AddUninitialized(Handle->Size());
			if (Handle->Read(FileData.GetData(), FileData.Num()))
			{
				FString FileDataString;
				FFileHelper::BufferToString(FileDataString, FileData.GetData(), FileData.Num());
				return FileAttributesMetaToMap(FileDataString, FileAttributes);
			}
			else
			{
				UE_LOG(LogFileAttributesParser, Error, TEXT("Could not read meta file %s"), *MetaFilename);
			}
		}
		else
		{
			UE_LOG(LogFileAttributesParser, Error, TEXT("Could not open meta file %s"), *MetaFilename);
		}

		return false;
	}
コード例 #6
0
/**
* This function parses the Json response after uploading the save file to obtain the 
* URL of the save file.
*
* @param JsonString              Json string to parse
* @param PlayerControllerId      Player controller ID of the player who is saving the file
*
*/
void CloudyWebConnectorImpl::ReadAndStoreSaveFileURL(FString JsonString, int32 PlayerControllerId)
{
    JsonString = JsonString.Replace(TEXT("["), TEXT(""));
    JsonString = JsonString.Replace(TEXT("]"), TEXT(""));
    
    TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
    TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(JsonString);
    FJsonSerializer::Deserialize(JsonReader, JsonObject);

    // More player controllers than the TArray size
    if (PlayerControllerId >= SaveFileUrls.Num())
    {
        SaveFileUrls.AddUninitialized(PlayerControllerId - SaveFileUrls.Num() + 1);
    }
    if (JsonObject->HasField("saved_file"))
    {
        UE_LOG(CloudyWebConnectorLog, Error, TEXT("Json saved_file field found."));
        SaveFileUrls.Insert(JsonObject->GetStringField("saved_file"), PlayerControllerId);
    }
    else
    {
        UE_LOG(CloudyWebConnectorLog, Error, TEXT("Json saved_file field NOT found."));
        SaveFileUrls.Insert("", PlayerControllerId);
    }
}
コード例 #7
0
void FReflectionCaptureFullHDRDerivedData::InitializeFromUncompressedData(const TArray<uint8>& UncompressedData)
{
	DEC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, CompressedCapturedData.GetAllocatedSize());

	int32 UncompressedSize = UncompressedData.Num() * UncompressedData.GetTypeSize();

	TArray<uint8> TempCompressedMemory;
	// Compressed can be slightly larger than uncompressed
	TempCompressedMemory.Empty(UncompressedSize * 4 / 3);
	TempCompressedMemory.AddUninitialized(UncompressedSize * 4 / 3);
	int32 CompressedSize = TempCompressedMemory.Num() * TempCompressedMemory.GetTypeSize();

	verify(FCompression::CompressMemory(
		(ECompressionFlags)(COMPRESS_ZLIB | COMPRESS_BiasMemory), 
		TempCompressedMemory.GetData(), 
		CompressedSize, 
		UncompressedData.GetData(), 
		UncompressedSize));

	// Note: change REFLECTIONCAPTURE_FULL_DERIVEDDATA_VER when modifying the serialization layout
	FMemoryWriter FinalArchive(CompressedCapturedData, true);
	FinalArchive << UncompressedSize;
	FinalArchive << CompressedSize;
	FinalArchive.Serialize(TempCompressedMemory.GetData(), CompressedSize);

	INC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, CompressedCapturedData.GetAllocatedSize());
}
コード例 #8
0
ファイル: EpicSurvey.cpp プロジェクト: PickUpSU/UnrealEngine4
TSharedPtr< FSlateDynamicImageBrush > FEpicSurvey::LoadRawDataAsBrush( FName ResourceName, const TArray< uint8 >& RawData ) const
{
	TSharedPtr< FSlateDynamicImageBrush > Brush;

	uint32 BytesPerPixel = 4;
	int32 Width = 0;
	int32 Height = 0;

	bool bSucceeded = false;
	TArray<uint8> DecodedImage;
	IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>( FName("ImageWrapper") );
	IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper( EImageFormat::PNG );
	if ( ImageWrapper.IsValid() && ImageWrapper->SetCompressed( RawData.GetData(), RawData.Num() ) )
	{
		Width = ImageWrapper->GetWidth();
		Height = ImageWrapper->GetHeight();

		const TArray<uint8>* RawImageData = NULL;
		if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, RawImageData))
		{
			DecodedImage.AddUninitialized( Width * Height * BytesPerPixel );
			DecodedImage = *RawImageData;
			bSucceeded = true;
		}
	}

	if ( bSucceeded )
	{
		Brush = FSlateDynamicImageBrush::CreateWithImageData( ResourceName, FVector2D(ImageWrapper->GetWidth(), ImageWrapper->GetHeight()), DecodedImage );
	}

	return Brush;
}
コード例 #9
0
void FAnimationRuntime::FillUpSpaceBasesRetargetBasePose(const USkeleton* Skeleton, TArray<FTransform> &SpaceBaseRefPose)
{
	check(Skeleton);

	// @Todo fixme: this has to get preview mesh instead of skeleton
	
	const USkeletalMesh* PreviewMesh = Skeleton->GetPreviewMesh();
	if (PreviewMesh)
	{
		const TArray<FTransform> & ReferencePose = PreviewMesh->RetargetBasePose;
		SpaceBaseRefPose.Empty(ReferencePose.Num());
		SpaceBaseRefPose.AddUninitialized(ReferencePose.Num());

		// initialize to identity since some of them don't have tracks
		for(int Index=0; Index <SpaceBaseRefPose.Num(); ++Index)
		{
			int32 ParentIndex = PreviewMesh->RefSkeleton.GetParentIndex(Index);
			if(ParentIndex != INDEX_NONE)
			{
				SpaceBaseRefPose[Index] = ReferencePose[Index] * SpaceBaseRefPose[ParentIndex];
			}
			else
			{
				SpaceBaseRefPose[Index] = ReferencePose[Index];
			}
		}
	}
	else
	{
		FAnimationRuntime::FillUpSpaceBasesRefPose(Skeleton, SpaceBaseRefPose);
	}
}
コード例 #10
0
void UDestructibleComponent::SetCollisionResponseForActor(const FCollisionResponse& ColResponse, PxRigidDynamic* Actor, int32 ChunkIdx)
{
	// Get collision channel and response
	PxFilterData PQueryFilterData, PSimFilterData;
	uint8 MoveChannel = GetCollisionObjectType();
	if(IsCollisionEnabled())
	{
		AActor* Owner = GetOwner();
		CreateShapeFilterData(MoveChannel, (Owner ? Owner->GetUniqueID() : 0), ColResponse.GetResponseContainer(), 0, ChunkIdxToBoneIdx(ChunkIdx), PQueryFilterData, PSimFilterData, BodyInstance.bUseCCD, BodyInstance.bNotifyRigidBodyCollision, false);		
		PQueryFilterData.word3 |= EPDF_SimpleCollision | EPDF_ComplexCollision;

		SCOPED_SCENE_WRITE_LOCK(Actor->getScene());

		TArray<PxShape*> Shapes;
		Shapes.AddUninitialized(Actor->getNbShapes());

		int ShapeCount = Actor->getShapes(Shapes.GetTypedData(), Shapes.Num());

		for (int32 i=0; i < ShapeCount; ++i)
		{
			PxShape* Shape = Shapes[i];

			Shape->setQueryFilterData(PQueryFilterData);
			Shape->setSimulationFilterData(PSimFilterData);
			Shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); 
			Shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true); 
			Shape->setFlag(PxShapeFlag::eVISUALIZATION, true);
		}
	}
}
コード例 #11
0
ファイル: BuildPatchManifest.cpp プロジェクト: johndpope/UE4
bool FBuildPatchAppManifest::DeserializeFromData(const TArray<uint8>& DataInput)
{
	if (DataInput.Num())
	{
		if (BufferIsJsonManifest(DataInput))
		{
			FString JsonManifest;
			FFileHelper::BufferToString(JsonManifest, DataInput.GetData(), DataInput.Num());
			return DeserializeFromJSON(JsonManifest);
		}
		else
		{
			FMemoryReader ManifestFile(DataInput);
			FManifestFileHeader Header;
			ManifestFile << Header;
			const int32 SignedHeaderSize = Header.HeaderSize;
			if (Header.CheckMagic() && DataInput.Num() > SignedHeaderSize)
			{
				FSHAHashData DataHash;
				FSHA1::HashBuffer(&DataInput[Header.HeaderSize], DataInput.Num() - Header.HeaderSize, DataHash.Hash);
				if (DataHash == Header.SHAHash)
				{
					TArray<uint8> UncompressedData;
					if (Header.StoredAs == FChunkHeader::STORED_COMPRESSED && (Header.CompressedSize + Header.HeaderSize) == DataInput.Num())
					{
						UncompressedData.AddUninitialized(Header.DataSize);
						if (!FCompression::UncompressMemory(
							static_cast<ECompressionFlags>(COMPRESS_ZLIB | COMPRESS_BiasMemory),
							UncompressedData.GetData(),
							Header.DataSize,
							&DataInput[Header.HeaderSize],
							DataInput.Num() - Header.HeaderSize))
						{
							return false;
						}
					}
					else if ((Header.DataSize + Header.HeaderSize) == DataInput.Num())
					{
						UncompressedData.Append(&DataInput[Header.HeaderSize], Header.DataSize);
					}
					else
					{
						return false;
					}
					FManifestReader ManifestData(UncompressedData);
					return Serialize(ManifestData);
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
	}
	return false;
}
コード例 #12
0
TSharedPtr<FSlateDynamicImageBrush> FNewsFeedCache::RawDataToBrush( FName ResourceName, const TArray< uint8 >& InRawData ) const
{
	TSharedPtr<FSlateDynamicImageBrush> Brush;

	uint32 BytesPerPixel = 4;
	int32 Width = 0;
	int32 Height = 0;

	bool bSucceeded = false;
	TArray<uint8> DecodedImage;
	IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
	IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper( EImageFormat::PNG );

	if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(InRawData.GetData(), InRawData.Num()))
	{
		Width = ImageWrapper->GetWidth();
		Height = ImageWrapper->GetHeight();

		const TArray<uint8>* RawData = NULL;

		if (ImageWrapper->GetRaw( ERGBFormat::BGRA, 8, RawData))
		{
			DecodedImage.AddUninitialized( Width * Height * BytesPerPixel );
			DecodedImage = *RawData;
			bSucceeded = true;
		}
	}

	if (bSucceeded && FSlateApplication::Get().GetRenderer()->GenerateDynamicImageResource(ResourceName, ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), DecodedImage))
	{
		Brush = MakeShareable(new FSlateDynamicImageBrush(ResourceName, FVector2D(ImageWrapper->GetWidth(), ImageWrapper->GetHeight())));
	}

	return Brush;
}
コード例 #13
0
void UPhyaCollisionHandler::ProceduralWaveUnderflow(USoundWaveProcedural* InProceduralWave, int32 SamplesRequired)
{
	check(ProceduralWave == InProceduralWave);

	const int32 QueuedSamples = ProceduralWave->GetAvailableAudioByteCount()/sizeof(uint16);
	const int32 SamplesNeeded = SamplesRequired - QueuedSamples;
	const int32 BlocksNeeded = FMath::CeilToInt(SamplesNeeded/BlockSize);

	UE_LOG(LogTemp, Log, TEXT("Creating %d blocks for %s"), BlocksNeeded, *GetWorld()->GetPathName());

	TArray<int16> SampleData;
	SampleData.AddUninitialized(BlocksNeeded * BlockSize);
	int32 CurrSample = 0;

	for(int32 BlockIdx=0; BlockIdx<BlocksNeeded; BlockIdx++)
	{
		paBlock* AudioBlock = paTick();
		float* AudioData = AudioBlock->getStart();

		for(int32 SampleIdx=0; SampleIdx<BlockSize; SampleIdx++)
		{
			SampleData[CurrSample] = (int16)AudioData[SampleIdx];
			CurrSample++;
			//UE_LOG(LogTemp, Log, TEXT("%d:%f"), CurrSample, SampleData[CurrSample]);
		}
	}

	ProceduralWave->QueueAudio((uint8*)SampleData.GetData(), SampleData.Num() * sizeof(int16));
}
コード例 #14
0
bool UPoseableMeshComponent::AllocateTransformData()
{
	// Allocate transforms if not present.
	if ( Super::AllocateTransformData() )
	{
		if( LocalAtoms.Num() != SkeletalMesh->RefSkeleton.GetNum() )
		{
			LocalAtoms = SkeletalMesh->RefSkeleton.GetRefBonePose();

			TArray<FBoneIndexType> RequiredBoneIndexArray;
			RequiredBoneIndexArray.AddUninitialized(LocalAtoms.Num());
			for(int32 BoneIndex = 0; BoneIndex < LocalAtoms.Num(); ++BoneIndex)
			{
				RequiredBoneIndexArray[BoneIndex] = BoneIndex;
			}

			RequiredBones.InitializeTo(RequiredBoneIndexArray, *SkeletalMesh);
		}

		FillSpaceBases();
		FlipEditableSpaceBases();

		return true;
	}

	LocalAtoms.Empty();

	return false;
}
コード例 #15
0
void UBlendSpace::GetRawSamplesFromBlendInput(const FVector &BlendInput, TArray<FGridBlendSample> & OutBlendSamples) const
{
	OutBlendSamples.Empty(4);
	OutBlendSamples.AddUninitialized(4);

	GetGridSamplesFromBlendInput(BlendInput, OutBlendSamples[0], OutBlendSamples[1], OutBlendSamples[2], OutBlendSamples[3]);
}
コード例 #16
0
/** Populate OutSlateVerts and OutIndexes with data from this static mesh such that Slate can render it. */
static void SlateMeshToSlateRenderData(const USlateVectorArtData& DataSource, TArray<FSlateVertex>& OutSlateVerts, TArray<SlateIndex>& OutIndexes)
{
	// Populate Index data
	{
		// Note that we do a slow copy because on some platforms the SlateIndex is
		// a 16-bit value, so we cannot do a memcopy.
		const TArray<uint32>& IndexDataSource = DataSource.GetIndexData();
		const int32 NumIndexes = IndexDataSource.Num();
		OutIndexes.Empty();
		OutIndexes.Reserve(NumIndexes);
		for (int32 i = 0; i < NumIndexes; ++i)
		{
			OutIndexes.Add(IndexDataSource[i]);
		}
	}

	// Populate Vertex Data
	{
		const TArray<FSlateMeshVertex> VertexDataSource = DataSource.GetVertexData();
		const uint32 NumVerts = VertexDataSource.Num();
		OutSlateVerts.Empty();
		OutSlateVerts.Reserve(NumVerts);

		for (uint32 i = 0; i < NumVerts; ++i)
		{
			const FSlateMeshVertex& SourceVertex = VertexDataSource[i];
			FSlateVertex& NewVert = OutSlateVerts[OutSlateVerts.AddUninitialized()];

			// Copy Position
			{
				NewVert.Position[0] = SourceVertex.Position.X;
				NewVert.Position[1] = SourceVertex.Position.Y;
			}

			// Copy Color
			{
				NewVert.Color = SourceVertex.Color;
			}


			// Copy all the UVs that we have, and as many as we can fit.
			{
				NewVert.TexCoords[0] = SourceVertex.UV0.X;
				NewVert.TexCoords[1] = SourceVertex.UV0.Y;

				NewVert.TexCoords[2] = SourceVertex.UV1.X;
				NewVert.TexCoords[3] = SourceVertex.UV1.Y;

				NewVert.MaterialTexCoords[0] = SourceVertex.UV2.X;
				NewVert.MaterialTexCoords[1] = SourceVertex.UV2.Y;

				NewVert.ClipRect.TopLeft = SourceVertex.UV3;

				NewVert.ClipRect.ExtentX = SourceVertex.UV4;

				NewVert.ClipRect.ExtentY = SourceVertex.UV5;
			}
		}
	}
}
コード例 #17
0
void FVulkanPipelineStateCache::Save(FString& CacheFilename)
{
	TArray<uint8> MemFile;
	FMemoryWriter Ar(MemFile);
	int32 Version = FDiskEntry::VERSION;
	Ar << Version;
	int32 SizeOfDiskEntry = (int32)sizeof(FDiskEntry);
	Ar << SizeOfDiskEntry;
	Ar << DiskEntries;
	TArray<uint8> DeviceCache;
	size_t Size = 0;
	VERIFYVULKANRESULT(VulkanRHI::vkGetPipelineCacheData(Device->GetInstanceHandle(), PipelineCache, &Size, nullptr));
	if (Size > 0)
	{
		DeviceCache.AddUninitialized(Size);
		VERIFYVULKANRESULT(VulkanRHI::vkGetPipelineCacheData(Device->GetInstanceHandle(), PipelineCache, &Size, DeviceCache.GetData()));
	}
	Ar << DeviceCache;

	MemFile.Num();

	if (FFileHelper::SaveArrayToFile(MemFile, *CacheFilename))
	{
		UE_LOG(LogVulkanRHI, Display, TEXT("Saved pipeline cache file '%s', %d Pipelines, %d bytes"), *CacheFilename, DiskEntries.Num(), MemFile.Num());
	}
}
コード例 #18
0
TSharedPtr<FSlateDynamicImageBrush> FContentSourceViewModel::CreateBrushFromRawData(FString ResourceNamePrefix, const TArray< uint8 >& RawData) const
{
	TSharedPtr< FSlateDynamicImageBrush > Brush;

	uint32 BytesPerPixel = 4;
	int32 Width = 0;
	int32 Height = 0;

	bool bSucceeded = false;
	TArray<uint8> DecodedImage;
	IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
	IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);
	if (ImageWrapper.IsValid() && (RawData.Num() > 0) && ImageWrapper->SetCompressed(RawData.GetData(), RawData.Num()))
	{
		Width = ImageWrapper->GetWidth();
		Height = ImageWrapper->GetHeight();

		const TArray<uint8>* RawImageData = NULL;
		if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, RawImageData))
		{
			DecodedImage.AddUninitialized(Width * Height * BytesPerPixel);
			DecodedImage = *RawImageData;
			bSucceeded = true;
		}
	}

	if (bSucceeded)
	{
		FString UniqueResourceName = ResourceNamePrefix + "_" + FString::FromInt(ImageID++);
		Brush = FSlateDynamicImageBrush::CreateWithImageData(FName(*UniqueResourceName), FVector2D(ImageWrapper->GetWidth(), ImageWrapper->GetHeight()), DecodedImage);
	}

	return Brush;
}
コード例 #19
0
ファイル: BuildPatchUtil.cpp プロジェクト: xiangyuan/Unreal4
bool FBuildPatchUtils::UncompressChunkFile( TArray< uint8 >& ChunkFileArray )
{
	FMemoryReader ChunkArrayReader( ChunkFileArray );
	// Read the header
	FChunkHeader Header;
	ChunkArrayReader << Header;
	// Check header
	const bool bValidHeader = Header.IsValidMagic();
	const bool bSupportedFormat = Header.HashType == FChunkHeader::HASH_ROLLING && !( Header.StoredAs & FChunkHeader::STORED_ENCRYPTED );
	if( bValidHeader && bSupportedFormat )
	{
		bool bSuccess = true;
		// Uncompress if we need to
		if( Header.StoredAs == FChunkHeader::STORED_COMPRESSED )
		{
			// Load the compressed chunk data
			TArray< uint8 > CompressedData;
			TArray< uint8 > UncompressedData;
			CompressedData.Empty( Header.DataSize );
			CompressedData.AddUninitialized( Header.DataSize );
			UncompressedData.Empty( FBuildPatchData::ChunkDataSize );
			UncompressedData.AddUninitialized( FBuildPatchData::ChunkDataSize );
			ChunkArrayReader.Serialize( CompressedData.GetData(), Header.DataSize );
			ChunkArrayReader.Close();
			// Uncompress
			bSuccess = FCompression::UncompressMemory(
				static_cast< ECompressionFlags >( COMPRESS_ZLIB | COMPRESS_BiasMemory ),
				UncompressedData.GetData(),
				UncompressedData.Num(),
				CompressedData.GetData(),
				CompressedData.Num() );
			// If successful, write back over the original array
			if( bSuccess )
			{
				ChunkFileArray.Empty();
				FMemoryWriter ChunkArrayWriter( ChunkFileArray );
				Header.StoredAs = FChunkHeader::STORED_RAW;
				Header.DataSize = FBuildPatchData::ChunkDataSize;
				ChunkArrayWriter << Header;
				ChunkArrayWriter.Serialize( UncompressedData.GetData(), UncompressedData.Num() );
				ChunkArrayWriter.Close();
			}
		}
		return bSuccess;
	}
	return false;
}
コード例 #20
0
bool FBuildPatchAppManifest::SaveToFile(const FString& Filename, bool bUseBinary)
{
	bool bSuccess = false;
	FArchive* FileOut = IFileManager::Get().CreateFileWriter(*Filename);
	if (FileOut)
	{
		if (bUseBinary)
		{
			Data->ManifestFileVersion = EBuildPatchAppManifestVersion::GetLatestVersion();
			FManifestWriter ManifestData;
			Serialize(ManifestData);
			ManifestData.Finalize();
			if (!ManifestData.IsError())
			{
				int32 DataSize = ManifestData.TotalSize();
				TArray<uint8> TempCompressed;
				TempCompressed.AddUninitialized(DataSize);
				int32 CompressedSize = DataSize;
				bool bDataIsCompressed = FCompression::CompressMemory(
					static_cast<ECompressionFlags>(COMPRESS_ZLIB | COMPRESS_BiasMemory),
					TempCompressed.GetData(),
					CompressedSize,
					ManifestData.GetBytes().GetData(),
					DataSize);
				TempCompressed.SetNum(CompressedSize);

				TArray<uint8>& FileData = bDataIsCompressed ? TempCompressed : ManifestData.GetBytes();

				FManifestFileHeader Header;
				*FileOut << Header;
				Header.HeaderSize = FileOut->Tell();
				Header.StoredAs = bDataIsCompressed ? EManifestFileHeader::STORED_COMPRESSED : EManifestFileHeader::STORED_RAW;
				Header.DataSize = DataSize;
				Header.CompressedSize = bDataIsCompressed ? CompressedSize : 0;
				FSHA1::HashBuffer(FileData.GetData(), FileData.Num(), Header.SHAHash.Hash);

				FileOut->Seek(0);
				*FileOut << Header;

				FileOut->Serialize(FileData.GetData(), FileData.Num());
				bSuccess = !FileOut->IsError();
			}
		}
		else
		{
			Data->ManifestFileVersion = EBuildPatchAppManifestVersion::GetLatestJsonVersion();
			FString JSONOutput;
			SerializeToJSON(JSONOutput);
			FTCHARToUTF8 JsonUTF8(*JSONOutput);
			FileOut->Serialize((UTF8CHAR*)JsonUTF8.Get(), JsonUTF8.Length() * sizeof(UTF8CHAR));
		}
		FileOut->Close();
		delete FileOut;
		FileOut = nullptr;
	}

	return bSuccess;
}
コード例 #21
0
void UDestructibleComponent::UpdateDestructibleChunkTM(const TArray<const PxRigidActor*>& ActiveActors)
{
	//We want to consolidate the transforms so that we update each destructible component once by passing it an array of chunks to update.
	//This helps avoid a lot of duplicated work like marking render dirty, computing inverse world component, etc...

	TMap<UDestructibleComponent*, TArray<FUpdateChunksInfo> > ComponentUpdateMapping;
	
	//prepare map to update destructible components
	TArray<PxShape*> Shapes;
	for (const PxRigidActor* RigidActor : ActiveActors)
	{
		if (const FDestructibleChunkInfo* DestructibleChunkInfo = FPhysxUserData::Get<FDestructibleChunkInfo>(RigidActor->userData))
		{
			if (GApexModuleDestructible->owns(RigidActor) && DestructibleChunkInfo->OwningComponent.IsValid())
			{
				Shapes.AddUninitialized(RigidActor->getNbShapes());
				int32 NumShapes = RigidActor->getShapes(Shapes.GetData(), Shapes.Num());
				for (int32 ShapeIdx = 0; ShapeIdx < Shapes.Num(); ++ShapeIdx)
				{
					PxShape* Shape = Shapes[ShapeIdx];
					int32 ChunkIndex;
					if (NxDestructibleActor* DestructibleActor = GApexModuleDestructible->getDestructibleAndChunk(Shape, &ChunkIndex))
					{
						const physx::PxMat44 ChunkPoseRT = DestructibleActor->getChunkPose(ChunkIndex);
						const physx::PxTransform Transform(ChunkPoseRT);
						if (UDestructibleComponent* DestructibleComponent = Cast<UDestructibleComponent>(FPhysxUserData::Get<UPrimitiveComponent>(DestructibleActor->userData)))
						{
							if (DestructibleComponent->IsRegistered())
							{
								TArray<FUpdateChunksInfo>& UpdateInfos = ComponentUpdateMapping.FindOrAdd(DestructibleComponent);
								FUpdateChunksInfo* UpdateInfo = new (UpdateInfos)FUpdateChunksInfo(ChunkIndex, P2UTransform(Transform));
							}
						}
					}
				}

				Shapes.Empty(Shapes.Num());	//we want to keep largest capacity array to avoid reallocs
			}
		}
	}
	
	//update each component
	for (auto It = ComponentUpdateMapping.CreateIterator(); It; ++It)
	{
		UDestructibleComponent* DestructibleComponent = It.Key();
		TArray<FUpdateChunksInfo>& UpdateInfos = It.Value();
		if (DestructibleComponent->IsFracturedOrInitiallyStatic())
		{
			DestructibleComponent->SetChunksWorldTM(UpdateInfos);
		}
		else
		{
			//if we haven't fractured it must mean that we're simulating a destructible and so we should update our ComponentToWorld based on the single rigid body
			DestructibleComponent->SyncComponentToRBPhysics();
		}
	}

}
コード例 #22
0
void FExrImageWrapper::WriteFrameBufferChannel(Imf::FrameBuffer& ImfFrameBuffer, const char* ChannelName, const sourcetype* SrcData, TArray<uint8>& ChannelBuffer)
{
	const int32 OutputPixelSize = ((OutputFormat == Imf::HALF) ? 2 : 4);
	ChannelBuffer.AddUninitialized(Width*Height*OutputPixelSize);
	uint32 SrcChannels = GetNumChannelsFromFormat(RawFormat);
	ExtractAndConvertChannel(SrcData, SrcChannels, Width, Height, (typename TExrImageOutputChannelType<OutputFormat>::Type*)&ChannelBuffer[0]);
	Imf::Slice FrameChannel = Imf::Slice(OutputFormat, (char*)&ChannelBuffer[0], OutputPixelSize, Width*OutputPixelSize);
	ImfFrameBuffer.insert(ChannelName, FrameChannel);
}
コード例 #23
0
void UDebugSkelMeshComponent::GenSpaceBases(TArray<FTransform>& OutSpaceBases)
{
	TArray<FTransform> TempLocalAtoms;
	TempLocalAtoms.AddUninitialized(OutSpaceBases.Num());
	TArray<FActiveVertexAnim> TempVertexAnims;
	FVector TempRootBoneTranslation;
	FBlendedCurve TempCurve;
	PerformAnimationEvaluation(SkeletalMesh, AnimScriptInstance, OutSpaceBases, TempLocalAtoms, TempVertexAnims, TempRootBoneTranslation, TempCurve);
}
コード例 #24
0
void FTestCloudInterface::WriteRandomFile(TArray<uint8>& Buffer, int32 Size)
{
	Buffer.Empty(Size);
	Buffer.AddUninitialized(Size);
	for (int32 i=0; i<Size; i++)
	{
		Buffer[i] = i % 255;
	}
}
コード例 #25
0
void CacheOptimizeSortStrip(uint32* Indices, int32 NumIndices)
{
	TArray<uint32> TempIndices;
	TempIndices.AddUninitialized(NumIndices);
	FMemory::Memcpy(TempIndices.GetData(), Indices, NumIndices * sizeof(uint32));
	IMeshUtilities& MeshUtilities = FModuleManager::LoadModuleChecked<IMeshUtilities>("MeshUtilities");
	MeshUtilities.CacheOptimizeIndexBuffer(TempIndices);
	check(TempIndices.Num() == NumIndices);
	FMemory::Memcpy(Indices, TempIndices.GetData(), NumIndices * sizeof(uint32));
}
コード例 #26
0
ファイル: PhysDerivedData.cpp プロジェクト: johndpope/UE4
bool FDerivedDataPhysXCooker::BuildTriMesh( TArray<uint8>& OutData, bool bInMirrored, bool InUseAllTriData )
{
	check(Cooker != NULL);

	bool bResult = false;
	FTriMeshCollisionData TriangleMeshDesc;
	IInterface_CollisionDataProvider* CDP = Cast<IInterface_CollisionDataProvider>(CollisionDataProvider);
	check(CDP != NULL); // It's all been checked before getting into this function
		
	bool bHaveTriMeshData = CDP->GetPhysicsTriMeshData(&TriangleMeshDesc, InUseAllTriData);
	if(bHaveTriMeshData)
	{
		// If any of the below checks gets hit this usually means 
		// IInterface_CollisionDataProvider::ContainsPhysicsTriMeshData did not work properly.
		const int32 NumIndices = TriangleMeshDesc.Indices.Num();
		const int32 NumVerts = TriangleMeshDesc.Vertices.Num();
		if(NumIndices == 0 || NumVerts == 0 || TriangleMeshDesc.MaterialIndices.Num() > NumIndices)
		{
			UE_LOG(LogPhysics, Warning, TEXT("FDerivedDataPhysXCooker::BuildTriMesh: Triangle data from '%s' invalid (%d verts, %d indices)."), *CollisionDataProvider->GetPathName(), NumVerts, NumIndices );
			return bResult;
		}

		TArray<FVector>* MeshVertices = NULL;
		TArray<FVector> MirroredVerts;

		if( bInMirrored )
		{
			MirroredVerts.AddUninitialized(NumVerts);
			for(int32 VertIdx=0; VertIdx<NumVerts; VertIdx++)
			{
				MirroredVerts[VertIdx] = TriangleMeshDesc.Vertices[VertIdx] * FVector(-1,1,1);
			}
			MeshVertices = &MirroredVerts;
		}
		else
		{
			MeshVertices = &TriangleMeshDesc.Vertices;
		}

		UE_LOG(LogPhysics, Log, TEXT("Cook TriMesh: %s (FlipX: %d)"), *CollisionDataProvider->GetPathName(), bInMirrored);
		bool bPerPolySkeletalMesh = false;
		if (USkeletalMesh* SkeletalMesh = Cast<USkeletalMesh>(CollisionDataProvider))
		{
			ensure(SkeletalMesh->bEnablePerPolyCollision);
			bPerPolySkeletalMesh = true;
		}
		bResult = Cooker->CookTriMesh( Format, *MeshVertices, TriangleMeshDesc.Indices, TriangleMeshDesc.MaterialIndices, bInMirrored ? !TriangleMeshDesc.bFlipNormals : TriangleMeshDesc.bFlipNormals, OutData, bPerPolySkeletalMesh );
		if( !bResult )
		{
			UE_LOG(LogPhysics, Warning, TEXT("Failed to cook TriMesh: %s (FlipX:%d)."), *CollisionDataProvider->GetPathName(), bInMirrored );
		}
	}

	return bResult;
}
コード例 #27
0
// NB: ElemTM is assumed to have no scaling in it!
void FKConvexElem::DrawElemWire(FPrimitiveDrawInterface* PDI, const FTransform& ElemTM, const FVector& Scale3D, const FColor Color)
{
#if WITH_PHYSX

	FTransform LocalToWorld = ElemTM;
	LocalToWorld.SetScale3D(Scale3D);

	PxConvexMesh* Mesh = ConvexMesh;

	if(Mesh)
	{
		// Draw each triangle that makes up the convex hull
		PxU32 NbVerts = Mesh->getNbVertices();
		const PxVec3* Vertices = Mesh->getVertices();
		
		TArray<FVector> TransformedVerts;
		TransformedVerts.AddUninitialized(NbVerts);
		for(PxU32 i=0; i<NbVerts; i++)
		{
			TransformedVerts[i] = LocalToWorld.TransformPosition( P2UVector(Vertices[i]) );
		}
						
		const PxU8* PIndexBuffer = Mesh->getIndexBuffer();
		PxU32 NbPolygons = Mesh->getNbPolygons();

		for(PxU32 i=0;i<NbPolygons;i++)
		{
			PxHullPolygon Data;
			bool bStatus = Mesh->getPolygonData(i, Data);
			check(bStatus);

			const PxU8* PIndices = PIndexBuffer + Data.mIndexBase;
		
			for(PxU16 j=0;j<Data.mNbVerts;j++)
			{
				// Get the verts that make up this line.
				int32 I0 = PIndices[j];
				int32 I1 = PIndices[j+1];

				// Loop back last and first vertices
				if(j==Data.mNbVerts - 1)
				{
					I1 = PIndices[0];
				}

				PDI->DrawLine( TransformedVerts[I0], TransformedVerts[I1], Color, SDPG_World );
			}
		}
	}
	else
	{
		UE_LOG(LogPhysics, Log, TEXT("FKConvexElem::DrawElemWire : No ConvexMesh, so unable to draw."));
	}
#endif // WITH_PHYSX
}
コード例 #28
0
	void FDataStructure::PushKnownChunk(const FGuid& PotentialMatch, uint32 NumDataInWindow)
	{
		if (DataStructure.Top().PartSize > 0)
		{
			// Add for matched
			DataStructure.AddUninitialized();
			// Add for next
			DataStructure.AddUninitialized();

			// Fill out info
			FChunkPart& PreviousChunkPart = DataStructure[DataStructure.Num() - 3];
			FChunkPart& MatchedChunkPart = DataStructure[DataStructure.Num() - 2];
			FChunkPart& NextChunkPart = DataStructure[DataStructure.Num() - 1];

			MatchedChunkPart.DataOffset = PreviousChunkPart.DataOffset + PreviousChunkPart.PartSize;
			MatchedChunkPart.PartSize = NumDataInWindow;
			MatchedChunkPart.ChunkOffset = 0;
			MatchedChunkPart.ChunkGuid = PotentialMatch;

			NextChunkPart.DataOffset = MatchedChunkPart.DataOffset + MatchedChunkPart.PartSize;
			NextChunkPart.ChunkGuid = PreviousChunkPart.ChunkGuid;
			NextChunkPart.ChunkOffset = PreviousChunkPart.ChunkOffset + PreviousChunkPart.PartSize;
			NextChunkPart.PartSize = 0;
		}
		else
		{
			// Add for next
			DataStructure.AddZeroed();

			// Fill out info
			FChunkPart& MatchedChunkPart = DataStructure[DataStructure.Num() - 2];
			FChunkPart& NextChunkPart = DataStructure[DataStructure.Num() - 1];

			NextChunkPart.ChunkOffset = MatchedChunkPart.ChunkOffset;
			NextChunkPart.ChunkGuid = NewChunkGuid;
			NextChunkPart.DataOffset = MatchedChunkPart.DataOffset + NumDataInWindow;

			MatchedChunkPart.PartSize = NumDataInWindow;
			MatchedChunkPart.ChunkOffset = 0;
			MatchedChunkPart.ChunkGuid = PotentialMatch;
		}
	}
コード例 #29
0
bool FFeaturePackContentSource::LoadPakFileToBuffer(FPakPlatformFile& PakPlatformFile, FString Path, TArray<uint8>& Buffer)
{
	bool bResult = false;
	TSharedPtr<IFileHandle> FileHandle(PakPlatformFile.OpenRead(*Path));
	if( FileHandle.IsValid())
	{
		Buffer.AddUninitialized(FileHandle->Size());
		bResult = FileHandle->Read(Buffer.GetData(), FileHandle->Size());
	}
	return bResult;
}
コード例 #30
0
std::string FOnlineSubsystemGooglePlay::ConvertFStringToStdString(const FString& InString)
{
	int32 SrcLen  = InString.Len() + 1;
	int32 DestLen = FPlatformString::ConvertedLength<ANSICHAR>(*InString, SrcLen);
	TArray<ANSICHAR> Converted;
	Converted.AddUninitialized(DestLen);
	
	FPlatformString::Convert(Converted.GetData(), DestLen, *InString, SrcLen);

	return std::string(Converted.GetData());
}