// Copyright (c) Microsoft Corporation. 
// Licensed under the MIT license.

#include "ScopedFPExceptionMaskState.h"

DEFINE_LOG_CATEGORY_STATIC(LogSimplygonFPExceptionMask, VeryVerbose, All);

FScopedFPExceptionMaskState::FScopedFPExceptionMaskState()
{
#ifdef _WIN32
	RequiresRestore = false;
	int32 Error = _controlfp_s(&CurrentControlWord, 0, 0);
	if (Error)
	{
		UE_LOG(LogSimplygonFPExceptionMask, Warning, TEXT("Could not get floating point control word."));
	}
	else
	{
		RequiresRestore = true;
		UE_LOG(LogSimplygonFPExceptionMask, Log, TEXT("Control Word (before) : 0x%.4x"));
	}

#endif
}

FScopedFPExceptionMaskState::~FScopedFPExceptionMaskState()
{
#ifdef _WIN32
	if (RequiresRestore)
	{
		int32 Error = _controlfp_s(&CurrentControlWord, _CW_DEFAULT, _MCW_EM);
		if (Error)
		{
			UE_LOG(LogSimplygonFPExceptionMask, Warning, TEXT("Could not restore  floating point control word."));
		}
	}
#endif
	UE_LOG(LogSimplygonFPExceptionMask, Log, TEXT("Control Word (after) : 0x%.4x"));
}
