Skip to content

Commit

Permalink
[SDK-593] Add permission and orientation fix to photo capture element (
Browse files Browse the repository at this point in the history
…#192)

## [SDK-593](https://ready-player-me.atlassian.net/browse/SDK-593)

## Description

- Added fetching of camera permission for ios and android
- Also fixed orientation of captured image
  • Loading branch information
rYuuk authored Jan 2, 2024
1 parent 94aee60 commit bf39b05
Showing 1 changed file with 51 additions and 1 deletion.
52 changes: 51 additions & 1 deletion Runtime/AvatarCreator/Scripts/UI/PhotoCaptureElement.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
#if UNITY_ANDROID
using UnityEngine.Android;
#endif
using UnityEngine.Events;
using UnityEngine.UI;

Expand All @@ -18,6 +23,11 @@ public class PhotoCaptureElement : MonoBehaviour
private WebCamTexture cameraTexture;
private bool isInitialized;

private int videoRotationAngle;
private bool videoVerticallyMirrored;

private CancellationTokenSource ctxSource;

private void OnEnable()
{
if (initializeOnEnable)
Expand All @@ -28,11 +38,14 @@ private void OnEnable()

private void OnDisable()
{
ctxSource?.Cancel();
StopCamera();
}

public void StartCamera()
public async void StartCamera()
{
await GetPermission();

if (!isInitialized)
{
InitializeCamera();
Expand All @@ -41,6 +54,14 @@ public void StartCamera()
if (cameraTexture != null && !cameraTexture.isPlaying)
{
cameraTexture.Play();

var currentRotation = cameraTextureTarget.transform.rotation;
cameraTextureTarget.transform.rotation = Quaternion.Euler(currentRotation.eulerAngles.x, currentRotation.eulerAngles.y, cameraTexture.videoRotationAngle);

if (!cameraTexture.videoVerticallyMirrored)
{
cameraTextureTarget.transform.localScale = new Vector3(-1, 1, 1);
}
}
}

Expand All @@ -64,6 +85,35 @@ public void TakePhoto()
onPhotoCaptured?.Invoke(texture);
}

private async Task GetPermission()
{
ctxSource?.Cancel();
ctxSource = new CancellationTokenSource();

#if UNITY_ANDROID
if (!Permission.HasUserAuthorizedPermission(Permission.Camera))
{
Permission.RequestUserPermission(Permission.Camera);
}

while (!Permission.HasUserAuthorizedPermission(Permission.Camera) && !ctxSource.IsCancellationRequested)
{
await Task.Yield();
}

#elif UNITY_IOS
if (!Application.HasUserAuthorization(UserAuthorization.WebCam))
{
var async = Application.RequestUserAuthorization(UserAuthorization.Microphone);
while (!async.isDone && !ctxSource.IsCancellationRequested)
{
await Task.Yield();
}
}
#endif

}

private void InitializeCamera()
{
var webCamDevice = GetWebCamDevice();
Expand Down

0 comments on commit bf39b05

Please sign in to comment.