﻿using UnityEngine;

namespace SkyboxPlus {

    [ExecuteInEditMode]
    public class SkyboxPlus : MonoBehaviour {

        static readonly int LightWorldToLocal = Shader.PropertyToID("_LightWL");
        static readonly int LightDir = Shader.PropertyToID("_WorldSpaceSunDir");
        static readonly int MoonLightWorldToLocal = Shader.PropertyToID("_MoonLightWL");
        static readonly int MoonLightDir = Shader.PropertyToID("_WorldSpaceMoonDir");
        const string SKW_CUSTOM_POSITIONS = "SBP_CUSTOM_POSITIONS";

        public Transform sun;
        public Transform moon;

        private void OnEnable() {
            if (sun == null) sun = transform;
            Shader.EnableKeyword(SKW_CUSTOM_POSITIONS);
        }

        private void OnDisable() {
            Shader.DisableKeyword(SKW_CUSTOM_POSITIONS);
        }

        void LateUpdate() {
            Shader.SetGlobalMatrix(LightWorldToLocal, sun.worldToLocalMatrix);
            Shader.SetGlobalVector(LightDir, -sun.forward);
            if (moon == null) {
                Shader.SetGlobalMatrix(MoonLightWorldToLocal, sun.worldToLocalMatrix);
                Vector4 moonDir = sun.forward;
                moonDir.w = -1;
                Shader.SetGlobalVector(MoonLightDir, moonDir);
            } else {
                Shader.SetGlobalMatrix(MoonLightWorldToLocal, moon.worldToLocalMatrix);
                Vector4 moonDir = moon.forward;
                moonDir.w = 1;
                Shader.SetGlobalVector(MoonLightDir, moonDir);
            }
        }
    }

}