/// <summary>
    /// Sets the focus point to be the center of the screen on start.
    /// </summary>
    private void Start()
    {
        Vector2 screenCenter = new Vector2(0.5f, 0.5f);

        FocusPoint.position = DepthSource.GetVertexInWorldSpaceFromScreenUV(screenCenter);
        Update();
    }
Exemplo n.º 2
0
 private void Start()
 {
     if (DepthSource == null)
     {
         DepthSource = GetComponent <DepthSource>();
     }
 }
    private void Update()
    {
        // Waits until Depth API is initialized.
        if (!_initialized && DepthSource.Initialized)
        {
            _initialized = true;
        }

        if (_initialized)
        {
            if (_cachedUseRawDepth != UseRawDepth)
            {
                DepthSource.SwitchToRawDepth(UseRawDepth);
                _cachedUseRawDepth = UseRawDepth;
            }

            UpdateRawPointCloud();
        }

        transform.position = DepthSource.ARCamera.transform.forward * OffsetFromCamera;
        float normalizedDeltaTime = Mathf.Clamp01(
            (float)(Time.deltaTime - _minUpdateInvervalInSeconds));

        _updateInvervalInSeconds = Mathf.Lerp((float)_minUpdateInvervalInSeconds,
                                              (float)_maxUpdateInvervalInSeconds,
                                              normalizedDeltaTime);
    }
Exemplo n.º 4
0
    private void Start()
    {
        var config = (DepthDataSourceConfig)Resources.Load("DepthDataSourceConfig");

        if (config != null && config.DepthDataSource != null)
        {
            s_DepthDataSource = config.DepthDataSource;
        }

        s_Instance          = this;
        s_AlwaysUpdateDepth = true;

        // Default texture, will be updated each frame.
        s_DepthTexture = new Texture2D(2, 2);

        foreach (DepthTarget target in s_DepthTargets)
        {
            if (target.DepthTargetMaterial != null)
            {
                SetDepthTexture(target);
                UpdateScreenOrientationOnMaterial(target.DepthTargetMaterial);
                SetAlphaForBlendedOcclusionProperties(target.DepthTargetMaterial);
            }
        }
    }
        /// <summary>
        /// Tests if worldPosition is behind the physical environment.
        /// </summary>
        /// <param name="targetWorldPosition">The position of the virtual object in the world space.</param>
        /// <returns>True if collision occurs.</returns>
        private CollisionResults CollisionTestSingleVertex(Vector3 targetWorldPosition)
        {
            // Computes the environment's depth.
            var screenPosition = Camera.main.WorldToScreenPoint(targetWorldPosition);

            // Note that the screenspace is in portrait mode.
            var normalizedScreenPosition = new Vector3(
                Mathf.Clamp01(1f - (screenPosition.y / Screen.currentResolution.height)),
                Mathf.Clamp01(1f - (screenPosition.x / Screen.currentResolution.width)),
                screenPosition.z);

            // Fetches the environment depth.
            var normalizedScreenPoint = new Vector2(
                normalizedScreenPosition.x, normalizedScreenPosition.y);
            var depthArray       = DepthSource.DepthArray;
            var environmentDepth = DepthSource.GetDepthFromUV(normalizedScreenPoint,
                                                              depthArray);

            //// Use this when new API is ready.
            //// var environmentDepth = FetchEnvironmentDepth(normalizedScreenPosition);

            if (environmentDepth == DepthSource.InvalidDepthValue)
            {
                return(CollisionResults.InvalidDepth);
            }

            // Computes the virtual object's depth.
            var targetDepth = normalizedScreenPosition.z;

            return(targetDepth >
                   environmentDepth + ParentCollisionDetector.VertexCollisionThresholdInMeters
                   ? CollisionResults.Collided : CollisionResults.NoCollision);
        }
Exemplo n.º 6
0
    /// <summary>
    /// Initializes the sun position.
    /// </summary>
    private void Start()
    {
        Vector2 screenCenter = new Vector2(0.5f, 0.5f);

        m_SunPosition = DepthSource.GetVertexInWorldSpaceFromScreenUV(screenCenter);
        Camera.main.depthTextureMode = DepthTextureMode.Depth;
    }
Exemplo n.º 7
0
    private void Update()
    {
        if (_initialized)
        {
            if (_getDataCountdown > 0)
            {
                _getDataCountdown--;
            }
            else if (_getDataCountdown == 0)
            {
                UpdateDepthTexture();
                UpdateCollider();
            }
        }
        else
        {
            if (DepthSource.Initialized)
            {
                if (_cachedUseRawDepth != UseRawDepth)
                {
                    DepthSource.SwitchToRawDepth(UseRawDepth);
                    _cachedUseRawDepth = UseRawDepth;
                }

                _meshWidth   = DepthSource.DepthWidth / _depthPixelSkippingX;
                _meshHeight  = DepthSource.DepthHeight / _depthPixelSkippingY;
                _numElements = _meshWidth * _meshHeight;

                UpdateDepthTexture();
                InitializeComputeShader();
                InitializeMesh();
                _initialized = true;
            }
        }
    }
    /// <summary>
    /// Raycasts into the depth map from a start point to an end point.
    /// </summary>
    /// <param name="depthArray">CPU depth array to raycast into.</param>
    /// <param name="start">Start point of the raycast operation.</param>
    /// <param name="end">End point of the raycast operation.</param>
    /// <param name="step">The step size of the raycast operation.</param>
    /// <returns>Returns the hit point of raycast, negative inifinity for no hit.</returns>
    public static Vector3 RaycastDepth(short[] depthArray, Vector3 start, Vector3 end, float step)
    {
        Vector3 vector       = end - start;
        Vector3 direction    = vector.normalized;
        float   length       = vector.magnitude;
        float   squareLength = vector.sqrMagnitude;

        Vector3 intermediatePoint = start;
        Vector3 stepVector        = step * direction;

        Vector3 hitPoint = Vector3.negativeInfinity;

        int stepCount = 0;

        while ((intermediatePoint - start).sqrMagnitude <= squareLength)
        {
            intermediatePoint = start + (stepCount * stepVector);
            Vector3    screenPoint = Camera.main.WorldToScreenPoint(intermediatePoint);
            Vector2Int depthXY     = DepthSource.ScreenToDepthXY(
                (int)screenPoint.x, (int)screenPoint.y);

            float realDepth = DepthSource.GetDepthFromXY(depthXY.x, depthXY.y, depthArray);

            // Detects a hit if the ray lands farther than the depth from the depth map.
            if ((realDepth != 0) && (screenPoint.z >= realDepth))
            {
                hitPoint = intermediatePoint;
                break;
            }

            stepCount++;
        }

        return(hitPoint);
    }
    /// <summary>
    /// Takes a snapshot of the current depth array and sets a static depth texture.
    /// </summary>
    public void FreezeDepthFrame()
    {
        m_FreezeMesh         = true;
        m_StaticDepthTexture = DepthSource.GetDepthTextureSnapshot();

        Material material = GetComponent <Renderer>().material;

        material.SetTexture("_CurrentDepthTexture", m_StaticDepthTexture);
    }
Exemplo n.º 10
0
    private void ProcessTouch()
    {
        Touch touch = Input.GetTouch(0);

        // Avoids touch event in the top bar and bottom slider.
        if (touch.position.y < 0.2 * Screen.height || touch.position.y > 0.8 * Screen.height)
        {
            return;
        }

        if (Input.touchCount == 1)
        {
            // Computes the view-space anchor based on rendering mode.
            switch (m_RenderMode)
            {
            case DepthOfFieldRenderMode.FocusOnWorldAnchor:
                m_ScreenAnchorPosition = Camera.main.WorldToScreenPoint(FocusPoint.position);
                float depthMin   = MipmapBlurMaterial.GetFloat(k_NormalizedDepthMinName);
                float depthMax   = MipmapBlurMaterial.GetFloat(k_NormalizedDepthMaxName);
                float depthRange = depthMax - depthMin;

                m_ScreenAnchorPosition.x /= Screen.width;
                m_ScreenAnchorPosition.y /= Screen.height;
                float zScreenAnchorPosition =
                    (m_ScreenAnchorPosition.z - depthMin) / depthRange;
                m_ScreenAnchorPosition.z = Mathf.Clamp01(zScreenAnchorPosition);
                break;

            case DepthOfFieldRenderMode.FocusOnProjectedPoint:
            case DepthOfFieldRenderMode.FocusOnScreenPoint:
                m_ScreenAnchorPosition.z = Input.touchCount >= 1 ? 1 : 0;
                break;
            }
        }

        if (Input.touchCount > 0)
        {
            // For the first touch, computes the view-space anchor based on rendering mode.
            switch (m_RenderMode)
            {
            case DepthOfFieldRenderMode.FocusOnProjectedPoint:
            case DepthOfFieldRenderMode.FocusOnWorldAnchor:
                FocusPoint.position = DepthSource.GetVertexInWorldSpaceFromScreenXY(
                    (int)touch.position.x, (int)touch.position.y,
                    DepthSource.DepthArray);
                break;

            case DepthOfFieldRenderMode.FocusOnScreenPoint:
                // Touch position corresponds to the image UV in the portrait mode.
                // Depth map UV is in landscape mode.
                m_ScreenAnchorPosition = new Vector3(touch.position.x / Screen.width,
                                                     touch.position.y / Screen.height,
                                                     1f);
                break;
            }
        }
    }
 /// <summary>
 /// Triggers when the script initializes.
 /// </summary>
 private void Start()
 {
     // Use smooth depth for depth effects.
     DepthSource.SwitchToRawDepth(false);
     if (ShadowReceiver != null)
     {
         ShadowReceiver.MaximumMeshDistance = 0;
         _shadowReceiverMaterial            = ShadowReceiver.GetComponent <MeshRenderer>().material;
     }
 }
Exemplo n.º 12
0
 /// <summary>
 /// Checks whether this component is part of the scene.
 /// </summary>
 private static void CheckAttachedToScene()
 {
     if (s_Instance == null)
     {
         if (Camera.main != null)
         {
             s_Instance = Camera.main.gameObject.AddComponent <DepthSource>();
         }
     }
 }
Exemplo n.º 13
0
    private void Start()
    {
        if (!TapToFocus)
        {
            FocusPoint = new GameObject().transform;
        }

        Vector2 screenCenter = new Vector2(0.5f, 0.5f);
        FocusPoint.position = DepthSource.GetVertexInWorldSpaceFromScreenUV(screenCenter);
        Update();
    }
Exemplo n.º 14
0
    private void Start()
    {
        if (!TapToFocus)
        {
            FocusPoint = new GameObject().transform;
        }

        Vector2 screenCenter = new Vector2(0.5f, 0.5f);

        FocusPoint.position = DepthSource.GetVertexInWorldSpaceFromScreenUV(screenCenter);

        Camera.main.gameObject.AddComponent <MipmapBlurPrePostRender>();
        Update();
    }
Exemplo n.º 15
0
    private void OnEnable()
    {
        // Takes the material of the object's renderer, if no DepthTargetMaterial is explicitly set.
        if (DepthTargetMaterial == null)
        {
            var renderer = GetComponent <Renderer>();

            if (renderer != null)
            {
                DepthTargetMaterial = renderer.sharedMaterial;
            }
        }

        DepthSource.AddDepthTarget(this);
    }
    /// <summary>
    /// Takes a snapshot of the current depth array and sets a static depth texture.
    /// </summary>
    public void GrabNewFrame()
    {
        if (m_StaticDepthTexture != null)
        {
            Destroy(m_StaticDepthTexture);
        }

        m_StaticDepthTexture = DepthSource.GetDepthTextureSnapshot();
        Material material = GetComponent <Renderer>().material;

        material.SetTexture("_CurrentDepthTexture", m_StaticDepthTexture);
        material.SetFloat("_ClipRadius", 0);
        material.SetFloat("_AspectRatio", (float)Screen.width / (float)Screen.height);
        material.SetMatrix(k_VertexModelTransformPropertyName, DepthSource.LocalToWorldMatrix);
        m_FrameGrabbed = true;
    }
    /// <summary>
    /// Sets the focus point's world position to be the world position of the touched vertex.
    /// </summary>
    private void ProcessTouch()
    {
        if (Input.touchCount < 1)
        {
            return;
        }

        Touch touch = Input.GetTouch(0);

        // Ignore the bottom of the screen where the slider is located.
        if (touch.position.y > 350)
        {
            FocusPoint.position = DepthSource.GetVertexInWorldSpaceFromScreenXY(
                (int)touch.position.x, (int)touch.position.y,
                DepthSource.DepthArray);
        }
    }
Exemplo n.º 18
0
    /// <summary>
    /// Computes 3D vertices from the depth map and creates a Mesh() object with the Point primitive
    /// type. Each point differently colored based on a depth color ramp.
    /// </summary>
    public void ComputePointCloud()
    {
        if (!m_Initialized)
        {
            return;
        }

        List <Vector3> vertices      = new List <Vector3>();
        List <int>     indices       = new List <int>();
        List <Color>   colors        = new List <Color>();
        int            vertexCounter = 0;

        for (int y = 0; y < DepthSource.DepthHeight; y++)
        {
            for (int x = 0; x < DepthSource.DepthWidth; x++)
            {
                int   depthIndex = (y * DepthSource.DepthWidth) + x;
                float depthInM   = DepthSource.DepthArray[depthIndex] * DepthSource.MillimeterToMeter;

                Vector3 vertex = DepthSource.ComputeVertex(x, y, depthInM);
                if (vertex == Vector3.negativeInfinity)
                {
                    continue;
                }

                vertex = DepthSource.TransformVertexToWorldSpace(vertex);

                float depthRange      = k_MaxVisualizationDistanceM - k_MinVisualizationDistanceM;
                float normalizedDepth = (depthInM - k_MinVisualizationDistanceM) / depthRange;
                Color color           = ColorRampGenerator.Turbo(normalizedDepth);
                vertices.Add(vertex);
                indices.Add(vertexCounter++);
                colors.Add(color);
            }
        }

        m_Mesh.SetVertices(vertices);
        m_Mesh.SetIndices(indices.ToArray(), MeshTopology.Points, 0);
        m_Mesh.SetColors(colors);
        m_Mesh.RecalculateBounds();

        MeshFilter meshFilter = GetComponent <MeshFilter>();

        meshFilter.mesh = m_Mesh;
    }
Exemplo n.º 19
0
    private void OnUpdateStateUpdate()
    {
        m_LaserPosition += m_LaserDirection * LaserVelocity * Time.deltaTime;
        m_LaserRenderer.SetPosition(m_LaserRenderer.positionCount++, m_LaserPosition);

        var screenPosition = Camera.main.WorldToScreenPoint(m_LaserPosition);

        if ((screenPosition.x < 0) || (screenPosition.x > Screen.width) ||
            (screenPosition.y < 0) || (screenPosition.y > Screen.height))
        {
            // Clamps to screen space.
            screenPosition.x = Mathf.Clamp(screenPosition.x, 0, Screen.width - 1);
            screenPosition.y = Mathf.Clamp(screenPosition.y, 0, Screen.height - 1);

            m_NextState = LaserState.OutOfScreen;
        }

        Vector2 hitUv   = ScreenPointToViewCoordinate(screenPosition);
        Vector2 depthUV = DepthSource.ScreenToDepthUV(hitUv);
        float   depth   = DepthSource.GetDepthFromUV(depthUV, DepthSource.DepthArray);

        if (screenPosition.z > depth)
        {
            Vector3 CurrentDirection = m_LaserDirection;
            Vector3 normal           = ComputeNormalMapFromDepthWeightedMeanGradient(hitUv);

            // Checks if the normal is valid.
            if (float.IsInfinity(normal.x) ||
                float.IsNegativeInfinity(normal.x) ||
                float.IsNaN(normal.x))
            {
                return;
            }

            // Transforms normal to the world space.
            normal           = Camera.main.transform.TransformDirection(normal);
            m_LaserDirection = Reflect(CurrentDirection, normal);

            // Adds collision quad.
            VisualizeNormalVector(m_LaserPosition, normal);

            m_LaserPosition = m_LaserPosition + (m_LaserDirection * LaserVelocity * Time.deltaTime);
            m_LaserRenderer.SetPosition(m_LaserRenderer.positionCount++, m_LaserPosition);
        }
    }
Exemplo n.º 20
0
    /// <summary>
    /// Updates the sun position to an offset above the surface where the user touches.
    /// </summary>
    private void UpdateTouch()
    {
        // If the player has not touched the screen, we are done with this update.
        Touch touch;

        if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
        {
            return;
        }

        var worldPosition = DepthSource.GetVertexInWorldSpaceFromScreenXY(
            (int)touch.position.x, (int)touch.position.y,
            DepthSource.DepthArray);

        m_SunPosition       = worldPosition + k_LightRelativePosition;
        m_LastTouchPosition = touch.position;
        m_Initialized       = true;
    }
Exemplo n.º 21
0
    private void OnFireStateEnter()
    {
        ResetBeam();

        if (!m_AllowTouch)
        {
            m_LastTouchPosition.x = Screen.width / 2.0f;
            m_LastTouchPosition.y = Screen.height / 2.0f;
        }

        // Shoots the laser from the camera.
        m_StartPosition = Camera.main.transform.position + m_LaserOffset;

        // Computes the first hit position in the world space.
        Vector3 hitPosition = DepthSource.GetVertexInWorldSpaceFromScreenXY(
            (int)m_LastTouchPosition.x, (int)m_LastTouchPosition.y);

        m_LaserDirection = (hitPosition - m_StartPosition).normalized;
        m_LaserPosition  = m_StartPosition + (m_LaserDirection * 0.1f);
    }
Exemplo n.º 22
0
    private static CollisionResults TestCollisionOnVertex(Vector3 targetWorldPosition)
    {
        // Computes the environment's depth.
        var screenPosition = Camera.main.WorldToScreenPoint(targetWorldPosition);
        var screenUv       = new Vector2(screenPosition.x / Screen.width,
                                         screenPosition.y / Screen.height);
        var depthUv          = DepthSource.ScreenToDepthUV(screenUv);
        var environmentDepth = DepthSource.GetDepthFromUV(depthUv, DepthSource.DepthArray);

        if (environmentDepth == DepthSource.InvalidDepthValue)
        {
            return(CollisionResults.InvalidDepth);
        }

        // Computes the virtual object's depth.
        var targetDepth = screenPosition.z;

        return(targetDepth >
               environmentDepth + k_VertexCollisionThresholdInMeters
               ? CollisionResults.Collided : CollisionResults.NoCollision);
    }
Exemplo n.º 23
0
    /// <summary>
    /// Updates touch events and passes uniform values to the GPU shader.
    /// </summary>
    private void Update()
    {
        if (m_FollowScreenCenter)
        {
            var worldPosition = DepthSource.GetVertexInWorldSpaceFromScreenXY(
                Screen.width / 2, Screen.height / 2,
                DepthSource.DepthArray);
            m_SunPosition = worldPosition + k_LightRelativePosition;
        }

        UpdateTouch();
        m_LightAnchorPosition = Camera.main.WorldToScreenPoint(m_SunPosition);
        float depthMin             = RelightingMaterial.GetFloat(k_NormalizedDepthMinName);
        float depthMax             = RelightingMaterial.GetFloat(k_NormalizedDepthMaxName);
        float depthRange           = depthMax - depthMin;
        float zLightAnchorPosition = (m_LightAnchorPosition.z - depthMin) / depthRange;

        m_LightAnchorPosition.z = Mathf.Clamp01(zLightAnchorPosition);

        RelightingMaterial.SetVector(k_LightAnchorPositionName, m_LightAnchorPosition);
        RelightingMaterial.SetFloat(k_GlobalAlphaValueName, m_GlobalAlphaValue);
    }
Exemplo n.º 24
0
    private float ComputeCenterScreenDistance()
    {
        Vector2 depthMapPoint = ScreenPosition;

        if (!DepthSource.Initialized)
        {
            Debug.LogError("Depth source is not initialized");
            throw new InvalidOperationException("Depth source is not initialized");
        }

        short[] depthMap = DepthSource.DepthArray;
        float   depthM   = DepthSource.GetDepthFromUV(depthMapPoint, depthMap);

        if (depthM <= DepthSource.InvalidDepthValue)
        {
            Debug.LogError("Invalid depth value");
            throw new InvalidOperationException("Invalid depth value");
        }

        Vector3 viewspacePoint = DepthSource.ComputeVertex(depthMapPoint, depthM);

        return(viewspacePoint.magnitude);
    }
Exemplo n.º 25
0
    /// <summary>
    /// Estimates the normal vector for each point based on weighted mean gradients
    /// on neighborhood depth data.
    /// </summary>
    /// <param name="screenUV">The normalized screen uv coordinates.</param>
    /// <returns>The computed normal.</returns>
    private Vector3 ComputeNormalMapFromDepthWeightedMeanGradient(Vector2 screenUV)
    {
        short[]    depthMap = DepthSource.DepthArray;
        Vector2    depthUV  = DepthSource.ScreenToDepthUV(screenUV);
        Vector2Int depthXY  = DepthSource.DepthUVtoXY(depthUV);
        float      depth_m  = DepthSource.GetDepthFromUV(depthUV, depthMap);

        if (depth_m == DepthSource.InvalidDepthValue)
        {
            return(Vector3.negativeInfinity);
        }

        // Iterates over neighbors to compute normal vector.
        float neighbor_corr_x            = 0.0f;
        float neighbor_corr_y            = 0.0f;
        float outlier_distance_m         = k_OutlierDepthRatio * depth_m;
        int   radius                     = k_WindowRadiusPixels;
        float neighbor_sum_confidences_x = 0.0f;
        float neighbor_sum_confidences_y = 0.0f;

        for (int dy = -radius; dy <= radius; ++dy)
        {
            for (int dx = -radius; dx <= radius; ++dx)
            {
                // Self isn't a neighbor.
                if (dx == 0 && dy == 0)
                {
                    continue;
                }

                Vector2Int offset   = DepthSource.ReorientDepthXY(dx, dy);
                int        currentX = depthXY.x + offset.x;
                int        currentY = depthXY.y + offset.y;

                // Retrieves neighbor value.
                float neighbor_depth_m = DepthSource.GetDepthFromXY(currentX, currentY, depthMap);

                // Confidence is not currently being packed yet, so for now this hardcoded.
                float neighbor_confidence = 1.0f;
                if (neighbor_depth_m == 0.0)
                {
                    continue;  // Neighbor does not exist.
                }

                float neighbor_distance_m = neighbor_depth_m - depth_m;

                // Checks for outliers.
                if (neighbor_confidence == 0.0f ||
                    Mathf.Abs(neighbor_distance_m) > outlier_distance_m)
                {
                    continue;
                }

                // Updates correlations in each dimension.
                if (dx != 0)
                {
                    neighbor_sum_confidences_x += neighbor_confidence;
                    neighbor_corr_x            += neighbor_confidence * neighbor_distance_m / dx;
                }

                if (dy != 0)
                {
                    neighbor_sum_confidences_y += neighbor_confidence;
                    neighbor_corr_y            += neighbor_confidence * neighbor_distance_m / dy;
                }
            }
        }

        if (neighbor_sum_confidences_x == 0 && neighbor_sum_confidences_y == 0)
        {
            return(Vector3.negativeInfinity);
        }

        // Estimates the normal vector by finding the weighted averages of
        // the surface gradients in x and y.
        float pixel_width_m = depth_m / DepthSource.FocalLength.x;
        float slope_x       = neighbor_corr_x / (pixel_width_m * neighbor_sum_confidences_x);
        float slope_y       = neighbor_corr_y / (pixel_width_m * neighbor_sum_confidences_y);

        // The normal points towards the camera, so its z-component is negative.
        Vector3 normal = new Vector3(slope_x, -slope_y, -1.0f);

        normal.Normalize();

        return(normal);
    }
Exemplo n.º 26
0
 private void OnDisable()
 {
     DepthSource.RemoveDepthTarget(this);
 }
Exemplo n.º 27
0
    private void CreateMesh(Rect ScreenSpaceWindow)
    {
        List <Vector3> vertices = new List <Vector3>();
        List <Vector2> uvs      = new List <Vector2>();
        int            step_x   = (int)(ScreenSpaceWindow.width / Width);
        int            step_y   = (int)(ScreenSpaceWindow.height / Height);

        int start_point_x = (int)ScreenSpaceWindow.x;
        int start_point_y = (int)ScreenSpaceWindow.y;

        float inverseWidth  = 1.0f / (Width - 1);
        float inverseHeight = 1.0f / (Height - 1);

        for (int y = Height - 1; y >= 0; --y)
        {
            for (int x = 0; x < Width; ++x)
            {
                Vector3    vertex      = Vector3.zero;
                Vector2Int screenPoint = new Vector2Int(start_point_x + (x * step_x),
                                                        start_point_y + (y * step_y));
#if UNITY_EDITOR
                Ray ray = Camera.main.ScreenPointToRay(
                    new Vector3(screenPoint.x, screenPoint.y, 1.0f));
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                    float depthM = hit.distance;
                    vertex = Camera.main.ScreenToWorldPoint(
                        new Vector3(screenPoint.x, screenPoint.y, depthM));
                }
#else
                short[]    depthMap   = DepthSource.DepthArray;
                Vector2Int depthPoint = DepthSource.ScreenToDepthXY(screenPoint.x, screenPoint.y);
                float      depth_m    = DepthSource.GetDepthFromXY(depthPoint.x, depthPoint.y, depthMap);
                vertex = DepthSource.ComputeVertex(depthPoint.x, depthPoint.y, depth_m);
                vertex = DepthSource.TransformVertexToWorldSpace(vertex);
#endif
                Vector2 uv = new Vector2(x * inverseWidth, y * inverseHeight);
                uvs.Add(uv);
                vertices.Add(vertex - transform.position);
            }
        }

        if (vertices.Count > 0)
        {
            int[] triangles = GenerateTriangles(Width, Height);

            Mesh mesh = new Mesh();
            mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
            mesh.SetVertices(vertices);
            mesh.SetUVs(0, uvs);
            mesh.SetTriangles(triangles, 0);
            mesh.RecalculateBounds();
            mesh.RecalculateNormals();
            mesh.UploadMeshData(false);

            MeshFilter   meshFilter   = GetComponent <MeshFilter>();
            MeshCollider meshCollider = GetComponent <MeshCollider>();
            meshFilter.mesh         = mesh;
            meshCollider.sharedMesh = mesh;

            transform.rotation = Quaternion.identity;
        }
    }
Exemplo n.º 28
0
        public static void ParseRDPSetOtherMode(F3DEX2Command cmd,
                                                out PipelineMode pm, out CycleType cyc, out TexturePersp tp, out TextureDetail td, out TextureLOD tl,
                                                out TextureLUT tt, out TextureFilter tf, out TextureConvert tc, out CombineKey ck, out ColorDither cd,
                                                out AlphaDither ad, out AlphaCompare ac, out DepthSource zs, out RenderMode rm)
        {
            rm = new RenderMode(cmd.Words & (0xFFFFFFFF & ~((ulong)AlphaCompare.Mask | (ulong)DepthSource.Mask)));

            if (!rm.Known) // Handle TCL modes by checking again with alpha compare and dither included
            {
                rm = new RenderMode(cmd.Words & (0xFFFFFFFF & ~(ulong)DepthSource.Mask));
            }

            ulong wordH = cmd.Words >> 32;

            ad  = (AlphaDither)(wordH & (ulong)AlphaDither.Mask);
            cd  = (ColorDither)(wordH & (ulong)ColorDither.Mask);
            ck  = (CombineKey)(wordH & (ulong)CombineKey.Mask);
            pm  = (PipelineMode)(wordH & (ulong)PipelineMode.Mask);
            cyc = (CycleType)(wordH & (ulong)CycleType.Mask);
            tp  = (TexturePersp)(wordH & (ulong)TexturePersp.Mask);
            td  = (TextureDetail)(wordH & (ulong)TextureDetail.Mask);
            tl  = (TextureLOD)(wordH & (ulong)TextureLOD.Mask);
            tt  = (TextureLUT)(wordH & (ulong)TextureLUT.Mask);
            tf  = (TextureFilter)(wordH & (ulong)TextureFilter.Mask);
            tc  = (TextureConvert)(wordH & (ulong)TextureConvert.Mask);

            ac = (AlphaCompare)(cmd.Words & (ulong)AlphaCompare.Mask);
            zs = (DepthSource)(cmd.Words & (ulong)DepthSource.Mask);
        }
    private void UpdateShaderVariables()
    {
        if (m_RenderMode == RelightingMode.LightsFollowScreenCenter)
        {
            FocusPoint.position = DepthSource.GetVertexInWorldSpaceFromScreenXY(
                Screen.width / 2, Screen.height / 2,
                DepthSource.DepthArray);
        }

        m_ScreenAnchorPosition    = Camera.main.WorldToScreenPoint(FocusPoint.position);
        m_ScreenAnchorPosition.x /= Screen.width;
        m_ScreenAnchorPosition.y /= Screen.height;

        RelitMaterial.SetVector(k_TouchPositionPropertyName, m_ScreenAnchorPosition);
        Vector2 aspectRatio = new Vector2(1f, Screen.height / Screen.width);

        RelitMaterial.SetVector(k_AspectRatioPropertyName, aspectRatio);

        string DebugMessage = string.Empty;

        for (int i = 0; i < PointLights.Length; ++i)
        {
            PointLights[i].transform.position = FocusPoint.position + k_LightOffset;

            var     light = PointLights[i];
            Vector3 offset;

            // Assigns random movement to individual point lights.
            if (i == 0)
            {
                offset = new Vector3(
                    Mathf.Cos((Time.time * 1.2f) + 1.2f),
                    Mathf.Sin((Time.time * 1.6f) + 0.7f),
                    Mathf.Cos((Time.time * 1.5f) + 0.2f));
            }
            else
            if (i == 1)
            {
                offset = new Vector3(
                    Mathf.Cos((Time.time * 1.7f) + 1.0f),
                    Mathf.Sin(Time.time * 1.4f),
                    Mathf.Sin(Time.time * 1.2f));
            }
            else
            {
                offset = new Vector3(
                    Mathf.Cos((Time.time * 1.8f) + 0.5f),
                    Mathf.Sin((Time.time * 1.8f) + 0.2f),
                    Mathf.Cos(Time.time * 1.4f));
            }

            // Rescales the movement of the dynamic point lights to be smaller.
            offset *= 0.3f;

            var world = PointLights[i].transform.position + offset;
            var local = Camera.main.WorldToScreenPoint(world);
            local.x /= Screen.width;
            local.y /= Screen.height;

            m_PointlightPositions[i] = new Vector4(local.x, local.y, local.z, 1);

            var color = light.GetComponent <Light>().color;
            m_PointlightColors[i] = color;

            var intensity = light.GetComponent <Light>().intensity;
            m_PointlightIntensities[i] = intensity;
        }

        RelitMaterial.SetVectorArray("_PointLightPositions", m_PointlightPositions);
        RelitMaterial.SetFloatArray("_PointLightIntensities", m_PointlightIntensities);
        RelitMaterial.SetVectorArray("_PointLightColors", m_PointlightColors);
        RelitMaterial.SetFloat("_GlobalDarkness", m_GlobalDarkness);
        RelitMaterial.SetFloat("_RenderMode", (int)m_RenderMode);

        // Updates the values related to DepthSource.
        if (!DepthSource.Initialized)
        {
            return;
        }
    }
Exemplo n.º 30
0
 private void Start()
 {
     // Use smooth depth for oriented reticles.
     DepthSource.SwitchToRawDepth(false);
 }