com.github.asus4.texture-source 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -57,7 +57,7 @@ Add the following setting to `Packages/manifest.json`
57
57
  }
58
58
  ],
59
59
  "dependencies": {
60
- "com.github.asus4.texture-source": "0.2.2",
60
+ "com.github.asus4.texture-source": "0.3.1",
61
61
  ...// other dependencies
62
62
  }
63
63
  }
@@ -87,6 +87,14 @@ Useful when using test videos only in the Editor.
87
87
 
88
88
  ![video-texture-source](https://github.com/asus4/TextureSource/assets/357497/8e38ed1a-d2d8-4e16-9fc4-e5d4c6d0a888)
89
89
 
90
+ ### Image Texture Source
91
+
92
+ Test with static images.
93
+
94
+ `OnTexture` event is invoked every frame if the `sendContinuousUpdate` is enabled.
95
+
96
+ ![image-texture-source](https://github.com/asus4/TextureSource/assets/357497/3d7eef4b-40c5-40b4-8403-b70f394ce938)
97
+
90
98
  ### AR Foundation Texture Source
91
99
 
92
100
  Provides AR camera texture access. It supports both ARCore/ARKit.
@@ -0,0 +1,101 @@
1
+ // Only available with AR Foundation
2
+ #if MODULE_ARFOUNDATION_ENABLED
3
+ namespace TextureSource
4
+ {
5
+ using System.Collections;
6
+ using System.Collections.Generic;
7
+ using UnityEngine;
8
+ using UnityEngine.XR.ARFoundation;
9
+
10
+ /// <summary>
11
+ /// The same with ARFoundationTextureSource but depth is encoded into alpha channel
12
+ /// (Experimental feature, only available with the latest AR Foundation)
13
+ /// </summary>
14
+ [CreateAssetMenu(menuName = "ScriptableObject/Texture Source/ARFoundation Depth", fileName = "ARFoundationDepthTextureSource")]
15
+ public sealed class ARFoundationDepthTextureSource : ARFoundationTextureSource
16
+ {
17
+ public enum DepthMode
18
+ {
19
+ Depth01,
20
+ RawDistance,
21
+ }
22
+
23
+ [SerializeField]
24
+ private DepthMode depthMode = DepthMode.Depth01;
25
+
26
+ // [HideInInspector]
27
+ [SerializeField]
28
+ private Shader shaderForARCore;
29
+ // [HideInInspector]
30
+ [SerializeField]
31
+ private Shader shaderForARKit;
32
+
33
+ private AROcclusionManager occlusionManager;
34
+
35
+ protected override RenderTextureFormat PreferredRenderTextureFormat => RenderTextureFormat.ARGBHalf;
36
+
37
+ protected override Shader ARCameraBackgroundShader
38
+ {
39
+ get
40
+ {
41
+ return Application.platform switch
42
+ {
43
+ RuntimePlatform.Android => shaderForARCore,
44
+ RuntimePlatform.IPhonePlayer => shaderForARKit,
45
+ #if UNITY_ANDROID
46
+ _ => shaderForARCore,
47
+ #elif UNITY_IOS
48
+ _ => shaderForARKit,
49
+ #else
50
+ _ => throw new NotSupportedException($"ARFoundationTextureSource is not supported on {Application.platform}"),
51
+ #endif
52
+ };
53
+ }
54
+ }
55
+
56
+ public override void Start()
57
+ {
58
+ occlusionManager = FindAnyObjectByType<AROcclusionManager>();
59
+ if (occlusionManager == null)
60
+ {
61
+ throw new System.InvalidOperationException("Requires AROcclusionManager to use ARFoundationDepthTextureSource");
62
+ }
63
+ occlusionManager.frameReceived += OnOcclusionFrameReceived;
64
+
65
+ base.Start();
66
+
67
+ if (depthMode == DepthMode.RawDistance)
68
+ {
69
+ material.EnableKeyword("TEXTURE_SOURCE_RAW_DISTANCE");
70
+ }
71
+ }
72
+
73
+ public override void Stop()
74
+ {
75
+ if (occlusionManager != null)
76
+ {
77
+ occlusionManager.frameReceived -= OnOcclusionFrameReceived;
78
+ }
79
+
80
+ base.Stop();
81
+ }
82
+
83
+ private void OnOcclusionFrameReceived(AROcclusionFrameEventArgs args)
84
+ {
85
+ if (args.textures.Count == 0)
86
+ {
87
+ return;
88
+ }
89
+
90
+ SetMaterialKeywords(material, args.enabledMaterialKeywords, args.disabledMaterialKeywords);
91
+
92
+ int count = args.textures.Count;
93
+ for (int i = 0; i < count; i++)
94
+ {
95
+ var tex = args.textures[i];
96
+ material.SetTexture(args.propertyNameIds[i], tex);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ #endif // MODULE_ARFOUNDATION_ENABLED
@@ -0,0 +1,13 @@
1
+ fileFormatVersion: 2
2
+ guid: e468045a73ccc46f1afb6f48292c11b1
3
+ MonoImporter:
4
+ externalObjects: {}
5
+ serializedVersion: 2
6
+ defaultReferences:
7
+ - shaderForARKit: {fileID: 4800000, guid: c8b0b30194e1b4026abc942f037e6f86, type: 3}
8
+ - shaderForARCore: {fileID: 4800000, guid: a68a981b98d2c47b881e7e696a7b0f1f, type: 3}
9
+ executionOrder: 0
10
+ icon: {instanceID: 0}
11
+ userData:
12
+ assetBundleName:
13
+ assetBundleVariant:
@@ -3,38 +3,48 @@
3
3
  namespace TextureSource
4
4
  {
5
5
  using System;
6
+ using System.Collections.Generic;
6
7
  using UnityEngine;
7
8
  using UnityEngine.XR.ARFoundation;
8
9
 
10
+ /// <summary>
11
+ /// Source from ARFoundation
12
+ /// </summary>
9
13
  [CreateAssetMenu(menuName = "ScriptableObject/Texture Source/ARFoundation", fileName = "ARFoundationTextureSource")]
10
- public sealed class ARFoundationTextureSource : BaseTextureSource
14
+ public class ARFoundationTextureSource : BaseTextureSource
11
15
  {
12
16
  private static readonly int _DisplayTransformID = Shader.PropertyToID("_UnityDisplayTransform");
13
17
 
14
18
  private ARCameraManager cameraManager;
15
19
  private RenderTexture texture;
16
- private Material material;
17
20
  private int lastUpdatedFrame = -1;
18
21
 
19
- private static readonly Lazy<Shader> ARCameraBackgroundShader = new(() =>
22
+ protected Material material;
23
+
24
+ public override bool DidUpdateThisFrame => lastUpdatedFrame == Time.frameCount;
25
+ public override Texture Texture => texture;
26
+
27
+ protected virtual RenderTextureFormat PreferredRenderTextureFormat => RenderTextureFormat.ARGB32;
28
+
29
+ protected virtual Shader ARCameraBackgroundShader
20
30
  {
21
- string shaderName = Application.platform switch
31
+ get
22
32
  {
23
- RuntimePlatform.Android => "Unlit/ARCoreBackground",
24
- RuntimePlatform.IPhonePlayer => "Unlit/ARKitBackground",
33
+ string shaderName = Application.platform switch
34
+ {
35
+ RuntimePlatform.Android => "Unlit/ARCoreBackground",
36
+ RuntimePlatform.IPhonePlayer => "Unlit/ARKitBackground",
25
37
  #if UNITY_ANDROID
26
- _ => "Unlit/ARCoreBackground",
38
+ _ => "Unlit/ARCoreBackground",
27
39
  #elif UNITY_IOS
28
- _ => "Unlit/ARKitBackground",
40
+ _ => "Unlit/ARKitBackground",
29
41
  #else
30
- _ => throw new NotSupportedException($"ARFoundationTextureSource is not supported on {Application.platform}"),
42
+ _ => throw new NotSupportedException($"ARFoundationTextureSource is not supported on {Application.platform}"),
31
43
  #endif
32
- };
33
- return Shader.Find(shaderName);
34
- });
35
-
36
- public override bool DidUpdateThisFrame => lastUpdatedFrame == Time.frameCount;
37
- public override Texture Texture => texture;
44
+ };
45
+ return Shader.Find(shaderName);
46
+ }
47
+ }
38
48
 
39
49
  public override void Start()
40
50
  {
@@ -43,9 +53,7 @@ namespace TextureSource
43
53
  {
44
54
  throw new InvalidOperationException("ARCameraManager is not found");
45
55
  }
46
-
47
- var shader = ARCameraBackgroundShader.Value;
48
- material = new Material(shader);
56
+ material = new Material(ARCameraBackgroundShader);
49
57
 
50
58
  cameraManager.frameReceived += OnFrameReceived;
51
59
  }
@@ -86,8 +94,12 @@ namespace TextureSource
86
94
  };
87
95
  }
88
96
 
97
+
89
98
  private void OnFrameReceived(ARCameraFrameEventArgs args)
90
99
  {
100
+ // The shader doesn't work for some reason when set ARKIT_BACKGROUND_URP
101
+ // SetMaterialKeywords(material, args.enabledMaterialKeywords, args.disabledMaterialKeywords);
102
+
91
103
  // Find best texture size
92
104
  int bestWidth = 0;
93
105
  int bestHeight = 0;
@@ -109,11 +121,11 @@ namespace TextureSource
109
121
 
110
122
  // Create render texture
111
123
  Utils.GetTargetSizeScale(
112
- new Vector2Int(bestWidth, bestHeight), screenAspect,
113
- out Vector2Int dstSize, out Vector2 scale);
114
- EnsureRenderTexture(dstSize.x, dstSize.y);
115
-
116
- // SetMaterialKeywords(material, args.enabledMaterialKeywords, args.disabledMaterialKeywords);
124
+ new Vector2Int(bestWidth, bestHeight),
125
+ screenAspect,
126
+ out Vector2Int dstSize,
127
+ out Vector2 scale);
128
+ EnsureRenderTexture(ref texture, dstSize.x, dstSize.y, 24, PreferredRenderTextureFormat);
117
129
 
118
130
  if (args.displayMatrix.HasValue)
119
131
  {
@@ -125,17 +137,35 @@ namespace TextureSource
125
137
  lastUpdatedFrame = Time.frameCount;
126
138
  }
127
139
 
128
- private void EnsureRenderTexture(int width, int height)
140
+ protected static void SetMaterialKeywords(Material material, List<string> enabledKeywords, List<string> disabledKeywords)
141
+ {
142
+ if (enabledKeywords != null)
143
+ {
144
+ foreach (var keyword in enabledKeywords)
145
+ {
146
+ material.EnableKeyword(keyword);
147
+ }
148
+ }
149
+ if (disabledKeywords != null)
150
+ {
151
+ foreach (var keyword in disabledKeywords)
152
+ {
153
+ material.DisableKeyword(keyword);
154
+ }
155
+ }
156
+ }
157
+
158
+ public static void EnsureRenderTexture(ref RenderTexture texture,
159
+ int width, int height,
160
+ int depth, RenderTextureFormat format)
129
161
  {
130
162
  if (texture == null || texture.width != width || texture.height != height)
131
163
  {
132
164
  if (texture != null)
133
165
  {
134
166
  texture.Release();
135
- texture = null;
136
167
  }
137
- int depth = 32;
138
- texture = new RenderTexture(width, height, depth, RenderTextureFormat.ARGB32);
168
+ texture = new RenderTexture(width, height, depth, format);
139
169
  texture.Create();
140
170
  }
141
171
  }
@@ -2,6 +2,9 @@ namespace TextureSource
2
2
  {
3
3
  using UnityEngine;
4
4
 
5
+ /// <summary>
6
+ /// Abstract class for the source.
7
+ /// </summary>
5
8
  public abstract class BaseTextureSource : ScriptableObject, ITextureSource
6
9
  {
7
10
  public abstract bool DidUpdateThisFrame { get; }
@@ -2,6 +2,9 @@ namespace TextureSource
2
2
  {
3
3
  using UnityEngine;
4
4
 
5
+ /// <summary>
6
+ /// Interface for the source
7
+ /// </summary>
5
8
  public interface ITextureSource
6
9
  {
7
10
  bool DidUpdateThisFrame { get; }
@@ -0,0 +1,58 @@
1
+ namespace TextureSource
2
+ {
3
+ using UnityEngine;
4
+
5
+ /// <summary>
6
+ /// Source from image texture
7
+ /// </summary>
8
+ [CreateAssetMenu(menuName = "ScriptableObject/Texture Source/Image", fileName = "ImageTextureSource")]
9
+ public class ImageTextureSource : BaseTextureSource
10
+ {
11
+ [SerializeField]
12
+ private Texture[] textures = default;
13
+
14
+ [SerializeField]
15
+ private bool sendContinuousUpdate = false;
16
+
17
+ public override bool DidUpdateThisFrame
18
+ {
19
+ get
20
+ {
21
+ if (sendContinuousUpdate)
22
+ {
23
+ return true;
24
+ }
25
+
26
+ bool updated = isUpdated;
27
+ isUpdated = false;
28
+ return updated;
29
+ }
30
+ }
31
+
32
+ public override Texture Texture => textures[currentIndex];
33
+
34
+ private int currentIndex = 0;
35
+ private bool isUpdated = false;
36
+
37
+ public override void Start()
38
+ {
39
+ if (textures.Length == 0)
40
+ {
41
+ Debug.LogError("No texture is set");
42
+ return;
43
+ }
44
+ isUpdated = true;
45
+ }
46
+
47
+ public override void Stop()
48
+ {
49
+ isUpdated = false;
50
+ }
51
+
52
+ public override void Next()
53
+ {
54
+ currentIndex = (currentIndex + 1) % textures.Length;
55
+ isUpdated = true;
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,11 @@
1
+ fileFormatVersion: 2
2
+ guid: b51cafa6a901147349bf2af15e41f6a5
3
+ MonoImporter:
4
+ externalObjects: {}
5
+ serializedVersion: 2
6
+ defaultReferences: []
7
+ executionOrder: 0
8
+ icon: {instanceID: 0}
9
+ userData:
10
+ assetBundleName:
11
+ assetBundleVariant:
@@ -3,6 +3,9 @@ namespace TextureSource
3
3
  using System;
4
4
  using UnityEngine;
5
5
 
6
+ /// <summary>
7
+ /// Transforms 2D texture with any arbitrary matrix
8
+ /// </summary>
6
9
  public class TextureTransformer : IDisposable
7
10
  {
8
11
  private static readonly int _InputTex = Shader.PropertyToID("_InputTex");
@@ -24,7 +27,7 @@ namespace TextureSource
24
27
 
25
28
  public RenderTexture Texture => texture;
26
29
 
27
- public TextureTransformer(int width, int height, ComputeShader shader = null)
30
+ public TextureTransformer(int width, int height, RenderTextureFormat format, ComputeShader shader = null)
28
31
  {
29
32
  compute = shader != null
30
33
  ? shader
@@ -34,7 +37,7 @@ namespace TextureSource
34
37
  this.width = width;
35
38
  this.height = height;
36
39
 
37
- var desc = new RenderTextureDescriptor(width, height, RenderTextureFormat.ARGB32)
40
+ var desc = new RenderTextureDescriptor(width, height, format)
38
41
  {
39
42
  enableRandomWrite = true,
40
43
  useMipMap = false,
package/Runtime/Utils.cs CHANGED
@@ -2,6 +2,9 @@ namespace TextureSource
2
2
  {
3
3
  using UnityEngine;
4
4
 
5
+ /// <summary>
6
+ /// Internal utility functions
7
+ /// </summary>
5
8
  internal static class Utils
6
9
  {
7
10
  public static void GetTargetSizeScale(
@@ -4,6 +4,9 @@ namespace TextureSource
4
4
  using UnityEngine;
5
5
  using UnityEngine.Video;
6
6
 
7
+ /// <summary>
8
+ /// Source from video player
9
+ /// </summary>
7
10
  [CreateAssetMenu(menuName = "ScriptableObject/Texture Source/Video", fileName = "VideoTextureSource")]
8
11
  public class VideoTextureSource : BaseTextureSource
9
12
  {
@@ -5,7 +5,7 @@ namespace TextureSource
5
5
  using UnityEngine.Scripting;
6
6
 
7
7
  /// <summary>
8
- /// Virtual Texture Source
8
+ /// Invokes texture update event from the provided texture source ScriptableObject asset.
9
9
  /// </summary>
10
10
  public class VirtualTextureSource : MonoBehaviour
11
11
  {
@@ -118,7 +118,11 @@ namespace TextureSource
118
118
  if (needInitialize)
119
119
  {
120
120
  transformer?.Dispose();
121
- transformer = new TextureTransformer(dstSize.x, dstSize.y);
121
+ // Copy the format if the source is a RenderTexture
122
+ RenderTextureFormat format = (texture is RenderTexture renderTex)
123
+ ? renderTex.format :
124
+ RenderTextureFormat.ARGB32;
125
+ transformer = new TextureTransformer(dstSize.x, dstSize.y, format);
122
126
  }
123
127
 
124
128
  return transformer.Transform(texture, Vector2.zero, 0, scale);
@@ -4,30 +4,32 @@ namespace TextureSource
4
4
  using System.Linq;
5
5
  using UnityEngine;
6
6
 
7
+ /// <summary>
8
+ /// Source from WebCamTexture
9
+ /// </summary>
7
10
  [CreateAssetMenu(menuName = "ScriptableObject/Texture Source/WebCam", fileName = "WebCamTextureSource")]
8
11
  public sealed class WebCamTextureSource : BaseTextureSource
9
12
  {
10
- [Flags]
11
- public enum WebCamKindFlag
13
+ /// <summary>
14
+ /// Facing direction of the camera
15
+ /// </summary>
16
+ public enum CameraFacing
12
17
  {
13
- WideAngle = 1 << 0,
14
- Telephoto = 1 << 1,
15
- ColorAndDepth = 1 << 2,
16
- UltraWideAngle = 1 << 3,
17
- }
18
-
19
- [Flags]
20
- public enum FacingFlag
21
- {
22
- Front = 1 << 0,
23
- Back = 1 << 1,
18
+ Front,
19
+ Back,
24
20
  }
25
21
 
26
22
  [SerializeField]
27
- private WebCamKindFlag kindFilter = WebCamKindFlag.WideAngle | WebCamKindFlag.Telephoto | WebCamKindFlag.UltraWideAngle;
23
+ [Tooltip("Priorities of Camera Facing Direction")]
24
+ private CameraFacing[] facingPriorities = new CameraFacing[] {
25
+ CameraFacing.Back, CameraFacing.Front
26
+ };
28
27
 
29
28
  [SerializeField]
30
- private FacingFlag facingFilter = FacingFlag.Front | FacingFlag.Back;
29
+ [Tooltip("Priorities of WebCamKind")]
30
+ private WebCamKind[] kindPriority = new WebCamKind[] {
31
+ WebCamKind.WideAngle, WebCamKind.Telephoto, WebCamKind.UltraWideAngle,
32
+ };
31
33
 
32
34
  [SerializeField]
33
35
  private Vector2Int resolution = new Vector2Int(1270, 720);
@@ -57,16 +59,16 @@ namespace TextureSource
57
59
  private int lastUpdatedFrame = -1;
58
60
  private bool isFrontFacing;
59
61
 
60
- public WebCamKindFlag KindFilter
62
+ public CameraFacing[] FacingPriorities
61
63
  {
62
- get => kindFilter;
63
- set => kindFilter = value;
64
+ get => facingPriorities;
65
+ set => facingPriorities = value;
64
66
  }
65
67
 
66
- public FacingFlag FacingFilter
68
+ public WebCamKind[] KindPriorities
67
69
  {
68
- get => facingFilter;
69
- set => facingFilter = value;
70
+ get => kindPriority;
71
+ set => kindPriority = value;
70
72
  }
71
73
 
72
74
  public Vector2Int Resolution
@@ -85,7 +87,24 @@ namespace TextureSource
85
87
 
86
88
  public override void Start()
87
89
  {
88
- devices = WebCamTexture.devices.Where(IsMatchFilter).ToArray();
90
+ static CameraFacing GetFacing(WebCamDevice device)
91
+ {
92
+ return device.isFrontFacing ? CameraFacing.Front : CameraFacing.Back;
93
+ }
94
+
95
+ // Sort with facing, then kind
96
+ devices = WebCamTexture.devices
97
+ .Where(d => facingPriorities.Contains(GetFacing(d)) && kindPriority.Contains(d.kind))
98
+ .OrderBy(d => Array.IndexOf(facingPriorities, GetFacing(d)))
99
+ .ThenBy(d => Array.IndexOf(kindPriority, d.kind))
100
+ .ToArray();
101
+
102
+ if (devices.Length == 0)
103
+ {
104
+ Debug.LogError("No available camera found for the given priorities. Falling back to the default.");
105
+ devices = WebCamTexture.devices;
106
+ }
107
+
89
108
  StartCamera(currentIndex);
90
109
  }
91
110
 
@@ -140,7 +159,7 @@ namespace TextureSource
140
159
  if (needInitialize)
141
160
  {
142
161
  transformer?.Dispose();
143
- transformer = new TextureTransformer(width, height);
162
+ transformer = new TextureTransformer(width, height, RenderTextureFormat.ARGB32);
144
163
  }
145
164
 
146
165
  Vector2 scale;
@@ -159,23 +178,5 @@ namespace TextureSource
159
178
  lastUpdatedFrame = Time.frameCount;
160
179
  return transformer.Texture;
161
180
  }
162
-
163
- private bool IsMatchFilter(WebCamDevice device)
164
- {
165
- WebCamKindFlag kind = device.kind switch
166
- {
167
- WebCamKind.WideAngle => WebCamKindFlag.WideAngle,
168
- WebCamKind.Telephoto => WebCamKindFlag.Telephoto,
169
- WebCamKind.ColorAndDepth => WebCamKindFlag.ColorAndDepth,
170
- WebCamKind.UltraWideAngle => WebCamKindFlag.UltraWideAngle,
171
- _ => throw new NotImplementedException($"Unknown WebCamKind: {device.kind}"),
172
- };
173
- FacingFlag facing = device.isFrontFacing
174
- ? FacingFlag.Front
175
- : FacingFlag.Back;
176
-
177
- return kindFilter.HasFlag(kind)
178
- && facingFilter.HasFlag(facing);
179
- }
180
181
  }
181
182
  }
@@ -0,0 +1,138 @@
1
+ Shader "Unlit/TextureSource/ARCoreBackgroundDepth"
2
+ {
3
+ Properties
4
+ {
5
+ _MainTex("Texture", 2D) = "white" {}
6
+ _EnvironmentDepth("Texture", 2D) = "black" {}
7
+ }
8
+
9
+ SubShader
10
+ {
11
+ Name "ARCore Background (Before Opaques)"
12
+ Tags
13
+ {
14
+ "Queue" = "Background"
15
+ "RenderType" = "Background"
16
+ "ForceNoShadowCasting" = "True"
17
+ }
18
+
19
+ Pass
20
+ {
21
+ Name "AR Camera Background (ARCore)"
22
+ Cull Off
23
+ ZTest Always
24
+ ZWrite On
25
+ Lighting Off
26
+ LOD 100
27
+ Tags
28
+ {
29
+ "LightMode" = "Always"
30
+ }
31
+
32
+ GLSLPROGRAM
33
+
34
+ #pragma multi_compile_local __ ARCORE_ENVIRONMENT_DEPTH_ENABLED
35
+ #pragma multi_compile_local __ TEXTURE_SOURCE_RAW_DISTANCE
36
+
37
+ #pragma only_renderers gles3
38
+
39
+ #include "UnityCG.glslinc"
40
+
41
+ #ifdef SHADER_API_GLES3
42
+ #extension GL_OES_EGL_image_external_essl3 : require
43
+ #endif // SHADER_API_GLES3
44
+
45
+ // Device display transform is provided by the AR Foundation camera background renderer.
46
+ uniform mat4 _UnityDisplayTransform;
47
+
48
+ #ifdef VERTEX
49
+ varying vec2 textureCoord;
50
+
51
+ void main()
52
+ {
53
+ #ifdef SHADER_API_GLES3
54
+ // Transform the position from object space to clip space.
55
+ gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
56
+
57
+ // Remap the texture coordinates based on the device rotation.
58
+ textureCoord = (_UnityDisplayTransform * vec4(gl_MultiTexCoord0.x, 1.0f - gl_MultiTexCoord0.y, 1.0f, 0.0f)).xy;
59
+ #endif // SHADER_API_GLES3
60
+ }
61
+ #endif // VERTEX
62
+
63
+ #ifdef FRAGMENT
64
+ varying vec2 textureCoord;
65
+ uniform samplerExternalOES _MainTex;
66
+ uniform float _UnityCameraForwardScale;
67
+
68
+ #ifdef ARCORE_ENVIRONMENT_DEPTH_ENABLED
69
+ uniform sampler2D _EnvironmentDepth;
70
+ #endif // ARCORE_ENVIRONMENT_DEPTH_ENABLED
71
+
72
+ #if defined(SHADER_API_GLES3) && !defined(UNITY_COLORSPACE_GAMMA)
73
+ float GammaToLinearSpaceExact (float value)
74
+ {
75
+ if (value <= 0.04045F)
76
+ return value / 12.92F;
77
+ else if (value < 1.0F)
78
+ return pow((value + 0.055F)/1.055F, 2.4F);
79
+ else
80
+ return pow(value, 2.2F);
81
+ }
82
+
83
+ vec3 GammaToLinearSpace (vec3 sRGB)
84
+ {
85
+ // Approximate version from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1
86
+ return sRGB * (sRGB * (sRGB * 0.305306011F + 0.682171111F) + 0.012522878F);
87
+
88
+ // Precise version, useful for debugging, but the pow() function is too slow.
89
+ // return vec3(GammaToLinearSpaceExact(sRGB.r), GammaToLinearSpaceExact(sRGB.g), GammaToLinearSpaceExact(sRGB.b));
90
+ }
91
+
92
+ #endif // SHADER_API_GLES3 && !UNITY_COLORSPACE_GAMMA
93
+
94
+ float ConvertDistanceToDepth(float d)
95
+ {
96
+ #if TEXTURE_SOURCE_RAW_DISTANCE
97
+ return d;
98
+ #else
99
+ d = _UnityCameraForwardScale > 0.0 ? _UnityCameraForwardScale * d : d;
100
+
101
+ float zBufferParamsW = 1.0 / _ProjectionParams.y;
102
+ float zBufferParamsY = _ProjectionParams.z * zBufferParamsW;
103
+ float zBufferParamsX = 1.0 - zBufferParamsY;
104
+ float zBufferParamsZ = zBufferParamsX * _ProjectionParams.w;
105
+
106
+ // Clip any distances smaller than the near clip plane, and compute the depth value from the distance.
107
+ return (d < _ProjectionParams.y) ? 1.0f : ((1.0 / zBufferParamsZ) * ((1.0 / d) - zBufferParamsW));
108
+ #endif // TEXTURE_SOURCE_RAW_DISTANCE
109
+ }
110
+
111
+ void main()
112
+ {
113
+ #ifdef SHADER_API_GLES3
114
+ vec3 result = texture(_MainTex, textureCoord).xyz;
115
+ float depth = 1.0;
116
+
117
+ #ifdef ARCORE_ENVIRONMENT_DEPTH_ENABLED
118
+ float distance = texture(_EnvironmentDepth, textureCoord).x;
119
+ depth = ConvertDistanceToDepth(distance);
120
+ #endif // ARCORE_ENVIRONMENT_DEPTH_ENABLED
121
+
122
+ #ifndef UNITY_COLORSPACE_GAMMA
123
+ result = GammaToLinearSpace(result);
124
+ #endif // !UNITY_COLORSPACE_GAMMA
125
+
126
+ // gl_FragColor = vec4(result, 1.0);
127
+ gl_FragColor = vec4(result, depth);
128
+ gl_FragDepth = depth;
129
+ #endif // SHADER_API_GLES3
130
+ }
131
+
132
+ #endif // FRAGMENT
133
+ ENDGLSL
134
+ }
135
+ }
136
+
137
+ FallBack Off
138
+ }
@@ -0,0 +1,9 @@
1
+ fileFormatVersion: 2
2
+ guid: a68a981b98d2c47b881e7e696a7b0f1f
3
+ ShaderImporter:
4
+ externalObjects: {}
5
+ defaultTextures: []
6
+ nonModifiableTextures: []
7
+ userData:
8
+ assetBundleName:
9
+ assetBundleVariant:
@@ -0,0 +1,199 @@
1
+ Shader "Unlit/TextureSource/ARKitBackgroundDepth"
2
+ {
3
+ Properties
4
+ {
5
+ _textureY ("TextureY", 2D) = "white" {}
6
+ _textureCbCr ("TextureCbCr", 2D) = "black" {}
7
+ _HumanStencil ("HumanStencil", 2D) = "black" {}
8
+ _HumanDepth ("HumanDepth", 2D) = "black" {}
9
+ _EnvironmentDepth ("EnvironmentDepth", 2D) = "black" {}
10
+ }
11
+
12
+ SubShader
13
+ {
14
+ Tags
15
+ {
16
+ "Queue" = "Background"
17
+ "RenderType" = "Background"
18
+ "ForceNoShadowCasting" = "True"
19
+ }
20
+
21
+ Pass
22
+ {
23
+ Cull Off
24
+ ZTest Always
25
+ ZWrite On
26
+ Lighting Off
27
+ LOD 100
28
+ Tags
29
+ {
30
+ "LightMode" = "Always"
31
+ }
32
+
33
+
34
+ HLSLPROGRAM
35
+
36
+ #pragma vertex vert
37
+ #pragma fragment frag
38
+
39
+ #pragma multi_compile_local __ ARKIT_BACKGROUND_URP
40
+ #pragma multi_compile_local __ ARKIT_HUMAN_SEGMENTATION_ENABLED ARKIT_ENVIRONMENT_DEPTH_ENABLED
41
+ #pragma multi_compile_local __ TEXTURE_SOURCE_RAW_DISTANCE
42
+
43
+
44
+ #if ARKIT_BACKGROUND_URP
45
+
46
+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
47
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
48
+
49
+ #define ARKIT_TEXTURE2D_HALF(texture) TEXTURE2D(texture)
50
+ #define ARKIT_SAMPLER_HALF(sampler) SAMPLER(sampler)
51
+ #define ARKIT_TEXTURE2D_FLOAT(texture) TEXTURE2D(texture)
52
+ #define ARKIT_SAMPLER_FLOAT(sampler) SAMPLER(sampler)
53
+ #define ARKIT_SAMPLE_TEXTURE2D(texture,sampler,texcoord) SAMPLE_TEXTURE2D(texture,sampler,texcoord)
54
+
55
+ #else // Legacy RP
56
+
57
+ #include "UnityCG.cginc"
58
+
59
+ #define real4 half4
60
+ #define real4x4 half4x4
61
+ #define TransformObjectToHClip UnityObjectToClipPos
62
+ #define FastSRGBToLinear GammaToLinearSpace
63
+
64
+ #define ARKIT_TEXTURE2D_HALF(texture) UNITY_DECLARE_TEX2D_HALF(texture)
65
+ #define ARKIT_SAMPLER_HALF(sampler)
66
+ #define ARKIT_TEXTURE2D_FLOAT(texture) UNITY_DECLARE_TEX2D_FLOAT(texture)
67
+ #define ARKIT_SAMPLER_FLOAT(sampler)
68
+ #define ARKIT_SAMPLE_TEXTURE2D(texture,sampler,texcoord) UNITY_SAMPLE_TEX2D(texture,texcoord)
69
+
70
+ #endif
71
+
72
+
73
+ struct appdata
74
+ {
75
+ float3 position : POSITION;
76
+ float2 texcoord : TEXCOORD0;
77
+ };
78
+
79
+ struct v2f
80
+ {
81
+ float4 position : SV_POSITION;
82
+ float2 texcoord : TEXCOORD0;
83
+ };
84
+
85
+ struct fragment_output
86
+ {
87
+ real4 color : SV_Target;
88
+ // float depth : SV_Depth;
89
+ };
90
+
91
+
92
+ CBUFFER_START(UnityARFoundationPerFrame)
93
+ // Device display transform is provided by the AR Foundation camera background renderer.
94
+ float4x4 _UnityDisplayTransform;
95
+ float _UnityCameraForwardScale;
96
+ CBUFFER_END
97
+
98
+
99
+ v2f vert (appdata v)
100
+ {
101
+ // Transform the position from object space to clip space.
102
+ float4 position = TransformObjectToHClip(v.position);
103
+
104
+ // Remap the texture coordinates based on the device rotation.
105
+ float2 texcoord = mul(float4(v.texcoord, 1.0f, 1.0f), _UnityDisplayTransform).xy;
106
+
107
+ v2f o;
108
+ o.position = position;
109
+ o.texcoord = texcoord;
110
+ return o;
111
+ }
112
+
113
+
114
+ CBUFFER_START(ARKitColorTransformations)
115
+ static const real4x4 s_YCbCrToSRGB = real4x4(
116
+ real4(1.0h, 0.0000h, 1.4020h, -0.7010h),
117
+ real4(1.0h, -0.3441h, -0.7141h, 0.5291h),
118
+ real4(1.0h, 1.7720h, 0.0000h, -0.8860h),
119
+ real4(0.0h, 0.0000h, 0.0000h, 1.0000h)
120
+ );
121
+ CBUFFER_END
122
+
123
+
124
+ inline float ConvertDistanceToDepth(float d)
125
+ {
126
+ #if TEXTURE_SOURCE_RAW_DISTANCE
127
+ return d;
128
+ #else
129
+ // Account for scale
130
+ d = _UnityCameraForwardScale > 0.0 ? _UnityCameraForwardScale * d : d;
131
+
132
+ // Clip any distances smaller than the near clip plane, and compute the depth value from the distance.
133
+ return (d < _ProjectionParams.y) ? 0.0f : ((1.0f / _ZBufferParams.z) * ((1.0f / d) - _ZBufferParams.w));
134
+ #endif // TEXTURE_SOURCE_RAW_DISTANCE
135
+ }
136
+
137
+
138
+ ARKIT_TEXTURE2D_HALF(_textureY);
139
+ ARKIT_SAMPLER_HALF(sampler_textureY);
140
+ ARKIT_TEXTURE2D_HALF(_textureCbCr);
141
+ ARKIT_SAMPLER_HALF(sampler_textureCbCr);
142
+ #if ARKIT_ENVIRONMENT_DEPTH_ENABLED
143
+ ARKIT_TEXTURE2D_FLOAT(_EnvironmentDepth);
144
+ ARKIT_SAMPLER_FLOAT(sampler_EnvironmentDepth);
145
+ #elif ARKIT_HUMAN_SEGMENTATION_ENABLED
146
+ ARKIT_TEXTURE2D_HALF(_HumanStencil);
147
+ ARKIT_SAMPLER_HALF(sampler_HumanStencil);
148
+ ARKIT_TEXTURE2D_FLOAT(_HumanDepth);
149
+ ARKIT_SAMPLER_FLOAT(sampler_HumanDepth);
150
+ #endif // ARKIT_HUMAN_SEGMENTATION_ENABLED
151
+
152
+
153
+ fragment_output frag (v2f i)
154
+ {
155
+ // Sample the video textures (in YCbCr).
156
+ real4 ycbcr = real4(ARKIT_SAMPLE_TEXTURE2D(_textureY, sampler_textureY, i.texcoord).r,
157
+ ARKIT_SAMPLE_TEXTURE2D(_textureCbCr, sampler_textureCbCr, i.texcoord).rg,
158
+ 1.0h);
159
+
160
+ // Convert from YCbCr to sRGB.
161
+ real4 videoColor = mul(s_YCbCrToSRGB, ycbcr);
162
+
163
+ #if !UNITY_COLORSPACE_GAMMA
164
+ // If rendering in linear color space, convert from sRGB to RGB.
165
+ videoColor.xyz = FastSRGBToLinear(videoColor.xyz);
166
+ #endif // !UNITY_COLORSPACE_GAMMA
167
+
168
+ // Assume the background depth is the back of the depth clipping volume.
169
+ float depthValue = 0.0f;
170
+
171
+ #if ARKIT_ENVIRONMENT_DEPTH_ENABLED
172
+ // Sample the environment depth (in meters).
173
+ float envDistance = ARKIT_SAMPLE_TEXTURE2D(_EnvironmentDepth, sampler_EnvironmentDepth, i.texcoord).r;
174
+
175
+ // Convert the distance to depth.
176
+ depthValue = ConvertDistanceToDepth(envDistance);
177
+ #elif ARKIT_HUMAN_SEGMENTATION_ENABLED
178
+ // Check the human stencil, and skip non-human pixels.
179
+ if (ARKIT_SAMPLE_TEXTURE2D(_HumanStencil, sampler_HumanStencil, i.texcoord).r > 0.5h)
180
+ {
181
+ // Sample the human depth (in meters).
182
+ float humanDistance = ARKIT_SAMPLE_TEXTURE2D(_HumanDepth, sampler_HumanDepth, i.texcoord).r;
183
+
184
+ // Convert the distance to depth.
185
+ depthValue = ConvertDistanceToDepth(humanDistance);
186
+ }
187
+ #endif // ARKIT_HUMAN_SEGMENTATION_ENABLED
188
+
189
+ fragment_output o;
190
+ o.color = real4(videoColor.x, videoColor.y, videoColor.z, depthValue);
191
+ // o.color = real4(depthValue, depthValue, depthValue, 0.5h);
192
+ // o.depth = depthValue;
193
+ return o;
194
+ }
195
+
196
+ ENDHLSL
197
+ }
198
+ }
199
+ }
@@ -0,0 +1,9 @@
1
+ fileFormatVersion: 2
2
+ guid: c8b0b30194e1b4026abc942f037e6f86
3
+ ShaderImporter:
4
+ externalObjects: {}
5
+ defaultTextures: []
6
+ nonModifiableTextures: []
7
+ userData:
8
+ assetBundleName:
9
+ assetBundleVariant:
package/Shaders.meta ADDED
@@ -0,0 +1,8 @@
1
+ fileFormatVersion: 2
2
+ guid: 72ce354a7d6da4f62bd4862f571441a8
3
+ folderAsset: yes
4
+ DefaultImporter:
5
+ externalObjects: {}
6
+ userData:
7
+ assetBundleName:
8
+ assetBundleVariant:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "com.github.asus4.texture-source",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "displayName": "TextureSource",
5
5
  "description": "Simplify WebCamera and test video handling for using Computer Vision in Unity",
6
6
  "unity": "2020.3",
@@ -11,6 +11,7 @@
11
11
  ],
12
12
  "documentationUrl": "https://github.com/asus4/TextureSource/tree/main",
13
13
  "changelogUrl": "https://github.com/asus4/TextureSource/releases",
14
+ "license": "MIT",
14
15
  "licensesUrl": "https://github.com/asus4/TextureSource/blob/main/Packages/com.github.asus4.texture-source/LICENSE",
15
16
  "author": {
16
17
  "name": "Koki Ibukuro",