public TileLightCullingPass(ComputeShader TileLightCullingCS)
        {
            renderPassEvent            = RenderPassEvent.BeforeRenderingPrepasses;
            m_targetTileLightCullingCS = TileLightCullingCS;
            m_tileLightCullingCSID     = m_targetTileLightCullingCS.FindKernel("CSMain");
            int stride = Marshal.SizeOf(typeof(LightData)) * 4;

            m_lightListBuffer = new ComputeBuffer((int)mc_maxLightCount,
                                                  stride, ComputeBufferType.Default);

            m_targetTileLightCullingCS.SetBuffer(
                m_tileLightCullingCSID,
                "_Lights",
                m_lightListBuffer);

            m_currentLightIndexBuffer = new ComputeBuffer(1, 4,
                                                          ComputeBufferType.Default);
            m_currentLightIndexBuffer.SetData(m_zeroLightIndexBuffer);
            m_targetTileLightCullingCS.SetBuffer(
                m_tileLightCullingCSID,
                "_CurrentIndex",
                m_currentLightIndexBuffer);

            //clear all lightData
            for (int i = 0; i < mc_maxLightCount; ++i)
            {
                m_lightsDatas[i] = new LightData(
                    Vector3.zero, 0, Vector3.zero, 0, Vector4.zero);
            }

            m_copyCameraDepthRTIdentifier =
                new RenderTargetIdentifier("_CopyCameraDepthRT");
        }
Пример #2
0
    public SpriteGeneratorBuilder ByLightData(LightData data)
    {
        this.lights    = data;
        this.hasLights = true;

        return(this);
    }
Пример #3
0
        private void SetupLight(RendererMetadata metadata, LightData data)
        {
            var light = data.Light;

            if (material != null)
            {
                Matrix  view      = metadata.Get <Matrix>("view").Value;
                Vector3 direction = light.Direction;
                Vector3.TransformNormal(ref direction, ref view, out direction);

                var shadowsEnabled = light.ShadowResolution > 0;

                material.Parameters["Direction"].SetValue(direction);
                material.Parameters["Colour"].SetValue(light.Colour);
                material.Parameters["EnableShadows"].SetValue(shadowsEnabled);

                if (shadowsEnabled)
                {
                    material.Parameters["ShadowProjection"].SetValue(metadata.Get <Matrix>("inverseview").Value *data.View *data.Projection);
                    material.Parameters["ShadowMapSize"].SetValue(new Vector2(light.ShadowResolution, light.ShadowResolution));
                    material.Parameters["ShadowMap"].SetValue(data.ShadowMap);
                    material.Parameters["LightFarClip"].SetValue(data.FarClip);
                    material.Parameters["LightNearPlane"].SetValue(data.NearClip);
                }
            }
        }
Пример #4
0
 private static void InitLightsMop()
 {
     LightData.Load(@"DBFilesClient\LightData.dbc");
     LightParams.Load(@"DBFilesClient\LightParams.dbc");
     ZoneLight.Load(@"DBFilesClient\ZoneLight.dbc");
     ZoneLightPoint.Load(@"DBFilesClient\ZoneLightPoint.dbc");
 }
Пример #5
0
 private static void ValidateLightData(LightData data)
 {
     data.BlinkInterval.Should().Be(126);
     data.BlinkPattern.Should().Be("10011");
     data.BulbHaloHeight.Should().Be(28.298f);
     data.BulbModulateVsAdd.Should().Be(0.9723f);
     data.Center.X.Should().Be(450.7777f);
     data.Center.Y.Should().Be(109.552f);
     data.Color.Red.Should().Be(151);
     data.Color.Green.Should().Be(221);
     data.Color.Blue.Should().Be(34);
     data.Color2.Red.Should().Be(235);
     data.Color2.Green.Should().Be(50);
     data.Color2.Blue.Should().Be(193);
     data.DepthBias.Should().Be(0.0012f);
     data.DragPoints.Length.Should().Be(8);
     data.FadeSpeedDown.Should().Be(0.223f);
     data.FadeSpeedUp.Should().Be(0.265f);
     data.FalloffPower.Should().Be(2.021f);
     data.Intensity.Should().Be(1.293f);
     data.IsBackglass.Should().Be(false);
     data.IsBulbLight.Should().Be(true);
     data.IsImageMode.Should().Be(false);
     data.IsRoundLight.Should().Be(false);
     data.MeshRadius.Should().Be(20.231f);
     data.OffImage.Should().Be("smiley");
     data.ShowBulbMesh.Should().Be(false);
     data.ShowReflectionOnBall.Should().Be(true);
     data.State.Should().Be(LightStatus.LightStateOff);
     data.Surface.Should().Be("");
     data.TransmissionScale.Should().Be(0.5916f);
 }
Пример #6
0
        /// <summary>
        ///     Devuelve la luz mas cercana a la posicion especificada
        /// </summary>
        private LightData getClosestLight(TGCVector3 pos, LightData ignore1, LightData ignore2)
        {
            var       minDist  = float.MaxValue;
            LightData minLight = null;

            foreach (var light in lights)
            {
                //Ignorar las luces indicadas
                if (ignore1 != null && light.Equals(ignore1))
                {
                    continue;
                }
                if (ignore2 != null && light.Equals(ignore2))
                {
                    continue;
                }

                var distSq = TGCVector3.LengthSq(pos - light.pos);
                if (distSq < minDist)
                {
                    minDist  = distSq;
                    minLight = light;
                }
            }

            return(minLight);
        }
Пример #7
0
 private static void ValidateLightData(LightData data)
 {
     Assert.Equal(126, data.BlinkInterval);
     Assert.Equal("10011", data.BlinkPattern);
     Assert.Equal(28.298f, data.BulbHaloHeight);
     Assert.Equal(0.9723f, data.BulbModulateVsAdd);
     Assert.Equal(450.7777f, data.Center.X);
     Assert.Equal(109.552f, data.Center.Y);
     Assert.Equal(151, data.Color.Red);
     Assert.Equal(221, data.Color.Green);
     Assert.Equal(34, data.Color.Blue);
     Assert.Equal(235, data.Color2.Red);
     Assert.Equal(50, data.Color2.Green);
     Assert.Equal(193, data.Color2.Blue);
     Assert.Equal(0.0012f, data.DepthBias);
     Assert.Equal(8, data.DragPoints.Length);
     Assert.Equal(0.223f, data.FadeSpeedDown);
     Assert.Equal(0.265f, data.FadeSpeedUp);
     Assert.Equal(2.021f, data.FalloffPower);
     Assert.Equal(1.293f, data.Intensity);
     Assert.Equal(false, data.IsBackglass);
     Assert.Equal(true, data.IsBulbLight);
     Assert.Equal(false, data.IsImageMode);
     Assert.Equal(false, data.IsRoundLight);
     Assert.Equal(20.231f, data.MeshRadius);
     Assert.Equal("smiley", data.OffImage);
     Assert.Equal(false, data.ShowBulbMesh);
     Assert.Equal(true, data.ShowReflectionOnBall);
     Assert.Equal(LightStatus.LightStateOff, data.State);
     Assert.Equal("", data.Surface);
     Assert.Equal(0.5916f, data.TransmissionScale);
 }
    //=============================================================================================

    /**
     *  @brief Updates the axis aligned bounding boxes of all registered lights.
     *
     *********************************************************************************************/
    private void _UpdateBounds()
    {
        int count = m_lights.Count;

        for (int i = 0; i < count; i++)
        {
            LightData data = m_lights[i];

            if (data.LightType == EFogVolumeLightType.None)
            {
                continue;
            }


            switch (data.LightType)
            {
            case EFogVolumeLightType.None:
            {
                break;
            }

            case EFogVolumeLightType.PointLight:
            {
                data.Bounds = new Bounds(data.Transform.position,
                                         Vector3.one * data.Light.range *
                                         m_pointLightCullSizeMultiplier);
                break;
            }

            case EFogVolumeLightType.SpotLight:
            {
                Vector3 center = data.Transform.position +
                                 data.Transform.forward * data.Light.range * 0.5f;
                data.Bounds = new Bounds(center,
                                         Vector3.one * data.Light.range *
                                         m_pointLightCullSizeMultiplier * 1.25f);
                break;
            }

            case EFogVolumeLightType.FogVolumePointLight:
            {
                data.Bounds = new Bounds(data.Transform.position,
                                         Vector3.one * data.FogVolumeLight.Range *
                                         m_pointLightCullSizeMultiplier);
                break;
            }

            case EFogVolumeLightType.FogVolumeSpotLight:
            {
                Vector3 center = data.Transform.position +
                                 data.Transform.forward * data.FogVolumeLight.Range * 0.5f;
                data.Bounds = new Bounds(center,
                                         Vector3.one * data.FogVolumeLight.Range *
                                         m_pointLightCullSizeMultiplier * 1.25f);
                break;
            }
            }
        }
    }
Пример #9
0
    public override void ProcessFrame(Playable playable, FrameData info, object playerData)
    {
        m_trackBinding = playerData as Light;
        if (m_trackBinding == null)
        {
            return;
        }

        if (!m_isFirstFrameProcess)
        {
            m_isFirstFrameProcess = true;
            m_defaultRange        = m_trackBinding.range;
            m_defaultColor        = m_trackBinding.color;
            m_defaultIntensity    = m_trackBinding.intensity;
            m_defaultRotation     = m_trackBinding.transform.rotation;
        }

        int        inputCount     = playable.GetInputCount();
        float      blendRange     = 0;
        Color      blendColor     = Color.clear;
        float      blendIntensity = 0;
        Quaternion blendRotation  = Quaternion.identity;

        float totalWeight    = 0;
        float greatestWeight = 0;
        int   currentInputs  = 0;

        for (int i = 0; i < inputCount; i++)
        {
            ScriptPlayable <LightData> playableInput = (ScriptPlayable <LightData>)playable.GetInput(i);
            LightData input = playableInput.GetBehaviour();

            float inputWeight = playable.GetInputWeight(i);
            blendRange     += input.range * inputWeight;
            blendColor     += input.color * inputWeight;
            blendIntensity += input.intensity * inputWeight;
            if (input.lookTarget != null && inputWeight > 0)
            {
                blendRotation *= Quaternion.LookRotation((input.lookTarget.position - m_trackBinding.transform.position) * inputWeight);
            }

            totalWeight += inputWeight;

            if (inputWeight > greatestWeight)
            {
                greatestWeight = inputWeight;
            }

            if (!Mathf.Approximately(inputWeight, 0f))
            {
                currentInputs++;
            }
        }

        m_trackBinding.range              = blendRange + m_defaultRange * (1 - totalWeight);
        m_trackBinding.color              = blendColor + m_defaultColor * (1 - totalWeight);
        m_trackBinding.intensity          = blendIntensity + m_defaultIntensity * (1 - totalWeight);
        m_trackBinding.transform.rotation = blendRotation;
    }
Пример #10
0
    static void MapColorGradient(OscMessage message, Light light, LightData lightdata)
    {
        float val = message.GetFloat(0);

        val = Unicom.Utility.MapValue(val, lightdata.inputRange.x, lightdata.inputRange.y, lightdata.outputRange.x, lightdata.outputRange.y);
        // Mathf.Clamp(val, 0.0f, 1.0f);
        light.color = lightdata.colorGradient.Evaluate(val);
    }
Пример #11
0
    static void MapColorVec3(OscMessage message, Light light, LightData lightdata)
    {
        float r = message.GetFloat(0);
        float g = message.GetFloat(1);
        float b = message.GetFloat(2);

        light.color = new Color(r, g, b);
    }
Пример #12
0
    static void MapIntensity(OscMessage message, Light light, LightData lightdata)
    {
        float val = message.GetFloat(0);

        val = Unicom.Utility.MapValue(val, lightdata.inputRange.x, lightdata.inputRange.y, lightdata.outputRange.x, lightdata.outputRange.y);
        // Mathf.Clamp(val, 0.0f, 1.0f);
        light.intensity = val;
    }
Пример #13
0
        private void NumericByte_ValueChanged(object sender, EventArgs e)
        {
            NumericUpDown n = sender as NumericUpDown;

            LightData.Get(mCurrentLight).Set(Convert.ToString(n.Tag), Convert.ToByte(n.Value));

            UpdateEditor();
        }
Пример #14
0
        public override void Init()
        {
            //Cargar escenario, pero inicialmente solo hacemos el parser, para separar los objetos que son solo luces y no meshes
            var scenePath = MediaDir + "Escenario\\EscenarioLuces-TgcScene.xml";
            var mediaPath = MediaDir + "Escenario\\";
            var parser    = new TgcSceneParser();
            var sceneData = parser.parseSceneFromString(File.ReadAllText(scenePath));

            //Separar modelos reales de las luces, segun layer "Lights"
            lights = new List <LightData>();
            var realMeshData = new List <TgcMeshData>();

            for (var i = 0; i < sceneData.meshesData.Length; i++)
            {
                var meshData = sceneData.meshesData[i];

                //Es una luz, no cargar mesh, solo importan sus datos
                if (meshData.layerName == "Lights")
                {
                    //Guardar datos de luz
                    var light = new LightData();
                    light.color = Color.FromArgb((int)meshData.color[0], (int)meshData.color[1],
                                                 (int)meshData.color[2]);
                    light.aabb = new TgcBoundingAxisAlignBox(TgcParserUtils.float3ArrayToVector3(meshData.pMin),
                                                             TgcParserUtils.float3ArrayToVector3(meshData.pMax));
                    light.pos = light.aabb.calculateBoxCenter();
                    lights.Add(light);
                }
                //Es un mesh real, agregar a array definitivo
                else
                {
                    realMeshData.Add(meshData);
                }
            }

            //Reemplazar array original de meshData de sceneData por el definitivo
            sceneData.meshesData = realMeshData.ToArray();

            //Ahora si cargar meshes reales
            var loader = new TgcSceneLoader();

            scene = loader.loadScene(sceneData, mediaPath);

            //Camara en 1ra persona
            Camara = new TgcFpsCamera(new Vector3(-20, 80, 450), 400f, 300f, Input);

            //Modifiers para variables de luz
            Modifiers.addBoolean("lightEnable", "lightEnable", true);
            Modifiers.addFloat("lightIntensity", 0, 150, 20);
            Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.3f);
            Modifiers.addFloat("specularEx", 0, 20, 9f);

            //Modifiers para material
            Modifiers.addColor("mEmissive", Color.Black);
            Modifiers.addColor("mAmbient", Color.White);
            Modifiers.addColor("mDiffuse", Color.White);
            Modifiers.addColor("mSpecular", Color.White);
        }
Пример #15
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public Primitive()
 {
     Flexible     = new FlexibleData();
     Light        = new LightData();
     LightMap     = new LightImage();
     Sculpt       = new SculptData();
     PrimData     = new ConstructionData();
     PhysicsProps = new PhysicsProperties();
 }
Пример #16
0
        void SetupMainLightConstants(CommandBuffer cmd, ref LightData lightData)
        {
            Vector4 lightPos, lightColor, lightAttenuation, lightSpotDir, lightOcclusionChannel;

            InitializeLightConstants(lightData.visibleLights, lightData.mainLightIndex, out lightPos, out lightColor, out lightAttenuation, out lightSpotDir, out lightOcclusionChannel);

            cmd.SetGlobalVector(LightConstantBuffer._MainLightPosition, lightPos);
            cmd.SetGlobalVector(LightConstantBuffer._MainLightColor, lightColor);
        }
Пример #17
0
    // Factory method that generates a playable based on this asset
    public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
    {
        var playable = ScriptPlayable <LightData> .Create(graph, templete);

        LightData clone = playable.GetBehaviour();

        clone.lookTarget = lookTarget.Resolve(graph.GetResolver());
        return(playable);
    }
Пример #18
0
        private void DrawLightData(LightData lightData)
        {
            EditorGUILayout.Separator();

            lightData.Pitch     = EditorGUILayout.FloatField("Pitch", lightData.Pitch);
            lightData.Yaw       = EditorGUILayout.FloatField("Yaw", lightData.Yaw);
            lightData.Intensity = EditorGUILayout.FloatField("Intensity", lightData.Intensity);
            lightData.Color     = EditorGUILayout.ColorField("Color", lightData.Color);
        }
 // Start is called before the first frame update
 void Start()
 {
     m_lightDatas = new LightData[m_lightList.Length];
     for (var i = 0; i < m_lightList.Length; i++)
     {
         LightData _d = new LightData();
         m_lightDatas[i] = _d;
     }
 }
Пример #20
0
        void SetupMainLightConstants(CommandBuffer cmd, ref LightData lightData)
        {
            Vector4 lightPos, lightColor;

            InitializeLightConstants(lightData.visibleLights, lightData.mainLightIndex, out lightPos, out lightColor);

            cmd.SetGlobalVector(LightConstantBuffer._MainLightPosition, lightPos);
            cmd.SetGlobalVector(LightConstantBuffer._MainLightColor, lightColor);
        }
Пример #21
0
 public LightList(BinaryReader bin)
 {
     light_count = bin.ReadUInt32();
     light       = new LightData[light_count];
     for (int i = 0; i < light_count; i++)
     {
         light[i] = new LightData(bin);
     }
     Array.Sort(light);
 }
Пример #22
0
        public LightAttribEditor(string areaLightName)
        {
            InitializeComponent();

            List <string> areaNames = LightData.GetNames();

            areaNames.ForEach(n => lightsList.Items.Add(n));

            lightsList.SelectedIndex = areaNames.IndexOf(areaLightName);
        }
Пример #23
0
        public void Setup(ScriptableRenderContext context, ref LightData lightData)
        {
            CommandBuffer cmd = CommandBufferPool.Get(k_SetupLightConstants);

            SetupMainLightConstants(cmd, ref lightData);
            SetupAdditionalLightConstants(cmd);

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
        RendererConfiguration GetRendererSettings(ref LightData lightData)
        {
            RendererConfiguration settings = RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe;

            if (lightData.totalAdditionalLightsCount > 0)
            {
                settings |= RendererConfiguration.PerObjectLightIndices8;
            }
            return(settings);
        }
Пример #25
0
        public override void Add(SpotLight behaviour)
        {
            var data = new LightData()
            {
                Light = behaviour
            };

            lights.Add(data);

            base.Add(behaviour);
        }
Пример #26
0
 public VoxelLight GetVoxelLightIncludingNeighbors(Coords c)
 {
     if (AreLocalCoordsInBounds(c))
     {
         return(LightData.GetVoxelLight(c));
     }
     else
     {
         return(Volume?.GetVoxelLight(LocalToVolumeCoords(c)) ?? VoxelLight.NULL);
     }
 }
Пример #27
0
    public void SetLightStrobeSpeed(float value)
    {
        LightData data = (LightData)GetSelectedExtension(PStrings.light);

        if (data == null)
        {
            return;
        }

        data.strobeSpeed = value;
    }
Пример #28
0
        public void DrawLMap(GraphicsDevice gd, LightData light, Matrix projection, Matrix lightTransform)
        {
            if (ShapeDirty)
            {
                RegenRoof(gd);
                ShapeDirty = false;
                StyleDirty = false;
            }
            else if (StyleDirty)
            {
                RemeshRoof(gd);
                StyleDirty = false;
            }

            var s = Matrix.Identity;

            s.M22 = 0;
            s.M33 = 0;
            s.M23 = 1;
            s.M32 = 1;

            for (int i = light.Level; i < Drawgroups.Length; i++)
            {
                Effect.Parameters["Level"].SetValue((float)i + 1);
                if (Drawgroups[i] != null)
                {
                    var dg = Drawgroups[i];
                    if (dg.NumPrimitives == 0)
                    {
                        continue;
                    }

                    Effect.Parameters["UseTexture"].SetValue(false);
                    Effect.Parameters["Projection"].SetValue(projection);
                    var view = Matrix.Identity;
                    Effect.Parameters["View"].SetValue(view);

                    var worldmat = Matrix.CreateScale(1 / 3f, 0, 1 / 3f) * Matrix.CreateTranslation(0, 1f * (i - (light.Level - 1)), 0) * s * lightTransform;

                    Effect.Parameters["World"].SetValue(worldmat);
                    Effect.Parameters["DiffuseColor"].SetValue(new Vector4(1, 1, 1, 1) * (float)(4 - (i - (light.Level))) / 5f);

                    gd.SetVertexBuffer(dg.VertexBuffer);
                    gd.Indices = dg.IndexBuffer;

                    Effect.CurrentTechnique = Effect.Techniques["DrawLMap"];
                    foreach (var pass in Effect.CurrentTechnique.Passes)
                    {
                        pass.Apply();
                        gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, dg.NumPrimitives);
                    }
                }
            }
        }
Пример #29
0
    public void SetLightFlickerBias(float value)
    {
        LightData data = (LightData)GetSelectedExtension(PStrings.light);

        if (data == null)
        {
            return;
        }

        data.flickerBias = value;
    }
Пример #30
0
 void Awake()
 {
     if (instance != null && instance != this)
     {
         Destroy(gameObject);
     }
     else
     {
         instance = this;
     }
 }
        public override void RenderEffect(InstanceID id, EffectInfo.SpawnArea area, Vector3 velocity, float acceleration, float magnitude, float timeDelta, RenderManager.CameraInfo cameraInfo)
        {
            var pos = area.m_matrix.MultiplyPoint(Vector3.zero);
            if ((pos - Camera.main.transform.position).sqrMagnitude > 1000.0f)
            {
                return;
            }

            var dir = area.m_matrix.MultiplyVector(Vector3.forward);

              //  Log.Warning(dir.ToString());

            pos += Vector3.up * 8.0f;
            pos += dir*5.0f;

            id.Index = (uint)UnityEngine.Random.Range(0, 256);
            LightData data = new LightData(id, pos, new Color(1.0f, 0.827f, 0.471f), 0.6f, 32.0f, 10.0f);

            data.m_type = LightType.Spot;
            data.m_spotAngle = 60.0f;
            data.m_rotation = Quaternion.Euler(90, 0, 0);

            Singleton<RenderManager>.instance.DrawLight(data);
        }
Пример #32
0
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;


            //Cargar textura de CubeMap para Environment Map, fijo para todos los meshes
            cubeMap = TextureLoader.FromCubeFile(d3dDevice, GuiController.Instance.ExamplesMediaDir + "Shaders\\CubeMap.dds");

            //Cargar Shader personalizado de EnvironmentMap
            effect = TgcShaders.loadEffect(GuiController.Instance.ExamplesMediaDir + "Shaders\\EnvironmentMap.fx");


            //Cargar escenario, pero inicialmente solo hacemos el parser, para separar los objetos que son solo luces y no meshes
            string scenePath = GuiController.Instance.ExamplesDir + "Lights\\NormalMapRoom\\NormalMapRoom-TgcScene.xml";
            string mediaPath = GuiController.Instance.ExamplesDir + "Lights\\NormalMapRoom\\";
            TgcSceneParser parser = new TgcSceneParser();
            TgcSceneData sceneData = parser.parseSceneFromString(File.ReadAllText(scenePath));

            //Separar modelos reales de las luces, segun layer "Lights"
            lights = new List<LightData>();
            List<TgcMeshData> realMeshData = new List<TgcMeshData>();
            for (int i = 0; i < sceneData.meshesData.Length; i++)
            {
                TgcMeshData meshData = sceneData.meshesData[i];

                //Es una luz, no cargar mesh, solo importan sus datos
                if (meshData.layerName == "Lights")
                {
                    //Guardar datos de luz
                    LightData light = new LightData();
                    light.color = Color.FromArgb((int)meshData.color[0], (int)meshData.color[1], (int)meshData.color[2]);
                    light.aabb = new TgcBoundingBox(TgcParserUtils.float3ArrayToVector3(meshData.pMin), TgcParserUtils.float3ArrayToVector3(meshData.pMax));
                    light.pos = light.aabb.calculateBoxCenter();
                    lights.Add(light);
                }
                //Es un mesh real, agregar a array definitivo
                else
                {
                    realMeshData.Add(meshData);
                }
            }

            //Reemplazar array original de meshData de sceneData por el definitivo
            sceneData.meshesData = realMeshData.ToArray();

            //Ahora si cargar meshes reales
            TgcSceneLoader loader = new TgcSceneLoader();
            TgcScene scene = loader.loadScene(sceneData, mediaPath);

            //Separar meshes con bumpMapping de los comunes
            bumpMeshes = new List<TgcMeshBumpMapping>();
            commonMeshes = new List<TgcMesh>();
            foreach (TgcMesh mesh in scene.Meshes)
            {
                //Mesh con BumpMapping
                if (mesh.Layer == "BumpMap")
                {
                    //Por convencion de este ejemplo el NormalMap se llama igual que el DiffuseMap (y cada mesh tiene una sola)
                    string path = mesh.DiffuseMaps[0].FilePath;
                    string[] split = path.Split('.');
                    path = split[0] + "_NormalMap.png";

                    //Convertir TgcMesh a TgcMeshBumpMapping
                    TgcTexture normalMap = TgcTexture.createTexture(path);
                    TgcTexture[] normalMapArray = new TgcTexture[] { normalMap };
                    TgcMeshBumpMapping bumpMesh = TgcMeshBumpMapping.fromTgcMesh(mesh, normalMapArray);
                    bumpMesh.Effect = effect;
                    bumpMesh.Technique = "EnvironmentMapTechnique";
                    bumpMeshes.Add(bumpMesh);

                    //Liberar original
                    mesh.dispose();
                }
                //Mesh normal
                else
                {
                    commonMeshes.Add(mesh);
                }
            }



            
            //Camara en 1ra persona
            GuiController.Instance.FpsCamera.Enable = true;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(0, 50, 100), new Vector3(0, 50, -1));

            
            
            //Modifiers
            GuiController.Instance.Modifiers.addBoolean("lightEnable", "lightEnable", true);
            GuiController.Instance.Modifiers.addFloat("reflection", 0, 1, 0.2f);
            GuiController.Instance.Modifiers.addFloat("bumpiness", 0, 2, 1f);
            GuiController.Instance.Modifiers.addFloat("lightIntensity", 0, 150, 20);
            GuiController.Instance.Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.3f);
            GuiController.Instance.Modifiers.addFloat("specularEx", 0, 20, 9f);

            GuiController.Instance.Modifiers.addColor("mEmissive", Color.Black);
            GuiController.Instance.Modifiers.addColor("mAmbient", Color.White);
            GuiController.Instance.Modifiers.addColor("mDiffuse", Color.White);
            GuiController.Instance.Modifiers.addColor("mSpecular", Color.White);
        }
Пример #33
0
        private void CaptureLoop()
        {
            try
            {
                //Get Light Setup Plugin
                ILightSetupPlugin lightSetupPlugin = CurrentProfile.LightSetupPlugin;

                Stopwatch timer = Stopwatch.StartNew();
                long lastTicks = 0;
                double waitTicks = 1.0 / CurrentProfile.CaptureFrequency;
                double freq = 1.0 / Stopwatch.Frequency;

                LightData newLightData = new LightData(_nextLightData);

                while (Active)
                {
                    lastTicks = timer.ElapsedTicks;

                    //Get screen segments
                    IDictionary<Light, PixelReader> ledSources = CurrentProfile.CapturePlugin.Capture(lightSetupPlugin);
                    newLightData.Time = timer.ElapsedTicks;
                    try
                    {
                        //Extract Colours from segments
                        int i = 0;
                        foreach (var keyValue in ledSources)
                        {
                            newLightData[i] = CurrentProfile.ColourExtractionPlugin.Extract(keyValue.Key, keyValue.Value);
                            i++;
                        }
                    }
                    finally
                    {
                        //Dispose of screen segments
                        foreach (var keyValue in ledSources)
                            keyValue.Value.Dispose();

                        //Dispose of whole screen
                        CurrentProfile.CapturePlugin.ReleaseCapture();
                    }

                    //Run any Post Process Plugins
                    foreach (var postProcessPlugin in CurrentProfile.PostProcessPlugins)
                    {
                        (postProcessPlugin as IPostProcessPlugin).Process(lightSetupPlugin.Lights, newLightData);
                    }

                    // Thread safe swap of new light data into _nextLightData
                    lock (sync)
                    {
                        var t = _nextLightData;
                        _nextLightData = newLightData;
                        newLightData = t;
                    }

                    // Throttle Capture Frequency
                    while ((timer.ElapsedTicks - lastTicks) * freq < waitTicks)
                    {
                        Task.Delay(5);
                    }

                    // Update capture FPS counter
                    _captureLoopFPS.Tick();
                }
            }
            catch (Exception e)
            {
                lock (sync)
                {
                    Active = false;
                    AfterglowRuntime.Logger.Error(e, "Afterglow Runtime - Capture Loop");
                }
            }
            finally
            {
                // Allow plugins to clean up
                CurrentProfile.CapturePlugins.ForEach(cp => cp.Stop());
                CurrentProfile.PostProcessPlugins.ForEach(pp => pp.Stop());
            }
        }
Пример #34
0
 public void Output(List<Core.Light> leds, LightData data)
 {
     //Debug.WriteLine("DebugOutput LEDs:");
     //Debug.WriteLine("LED count: {0}", leds.Count);
 }
Пример #35
0
        internal int SetExtraParamsFromBytes(byte[] data, int pos)
        {
            int i = pos;
            int totalLength = 1;

            if (data.Length == 0 || pos >= data.Length)
                return 0;

            try
            {
                byte extraParamCount = data[i++];

                for (int k = 0; k < extraParamCount; k++)
                {
                    ExtraParamType type = (ExtraParamType)Helpers.BytesToUInt16(data, i);
                    i += 2;

                    uint paramLength = Helpers.BytesToUIntBig(data, i);
                    i += 4;

                    if (type == ExtraParamType.Flexible)
                        Flexible = new FlexibleData(data, i);
                    else if (type == ExtraParamType.Light)
                        Light = new LightData(data, i);
                    else if (type == ExtraParamType.Sculpt)
                        Sculpt = new SculptData(data, i);

                    i += (int)paramLength;
                    totalLength += (int)paramLength + 6;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return totalLength;
        }
Пример #36
0
        private void OutputLoop()
        {
            try
            {
                //Get Light Setup Plugin
                ILightSetupPlugin lightSetupPlugin = CurrentProfile.LightSetupPlugin;

                Stopwatch timer = new Stopwatch();
                double waitTicks = 1.0 / CurrentProfile.OutputFrequency;
                double freq = 1.0 / Stopwatch.Frequency;

                long lastUpdate = 0;

                // Initialise temporary lightData
                LightData lightData = new LightData(lightSetupPlugin.Lights.Count);

                while (Active)
                {
                    timer.Restart();

                    // If available, replace _currentLightData with _nextLightData
                    lock (sync)
                    {
                        if (lastUpdate < _nextLightData.Time)
                        {
                            var t = lightData;
                            lightData = _nextLightData;
                            _nextLightData = t;
                            lastUpdate = lightData.Time;
                        }
                    }

                    if (lightData != null)
                    {
                        // Run pre-output plugins
                        CurrentProfile.PreOutputPlugins.ToList().ForEach(po => po.PreOutput(lightSetupPlugin.Lights, lightData));

                        //Run Output Plugin(s)
                        CurrentProfile.OutputPlugins.ToList().ForEach(o => o.Output(lightSetupPlugin.Lights, lightData));
                    }

                    // Copy the last frame to _prevLightData
                    lock(previousSync)
                    {
                        Buffer.BlockCopy(lightData.ColourData, 0, _prevLightData.ColourData, 0, lightData.ColourData.Length);
                    }

                    // Throttle Output Frequency
                    while (timer.ElapsedTicks * freq < waitTicks)
                    {
                        Task.Delay(5);
                    }

                    _outputLoopFPS.Tick();
                }
            }
            catch (Exception e)
            {
                lock (sync)
                {
                    Active = false;
                    AfterglowRuntime.Logger.Error(e, "Afterglow Runtime - Output Loop");
                }
            }
            finally
            {
                // Allow plugins to clean up
                CurrentProfile.PreOutputPlugins.ForEach(po => po.Stop());
                CurrentProfile.OutputPlugins.ForEach(o => o.Stop());
            }
        }
Пример #37
0
        public BlendHueData(GroupID gID, LightID lID, LightData fromData, LightData toData, float transitionTime)
        {
            _gID = gID;
             _lID = lID;
             _fromData = fromData;
             _toData = toData;
             _transitionTime = transitionTime;

             _timeStamp = Time.time;
        }
    //Create a light mesh object. Cram as much lights as you can into the LightData array. If there are too many lights for one GameObject, it will
    //automatically be split into multiple objects.
    public static GameObject[] CreateLights(string name, LightData[] lightData, Material material)
    {
        int transformAmount = lightData.Length;
        int lightsInThisBatch;

        //The triangle limit is 21844 (65534 vertices) per mesh, so split the objects up if needed.
        int meshAmount = (int)Mathf.Ceil(transformAmount / (float)maxTriangleAmount);

        GameObject[] lightObjects = new GameObject[meshAmount];

        //Get the remainder.
        int remainder = (int)(transformAmount % (float)maxTriangleAmount);

        //Loop through the mesh batches.
        for(int l = 0; l < meshAmount; l++){

            //Get the amount of lights in this mesh batch.
            if(meshAmount == 1){

                lightsInThisBatch = transformAmount;
            }

            else{

                //Last mesh batch.
                if(l == (meshAmount - 1)){

                    if(remainder == 0){

                        lightsInThisBatch = maxTriangleAmount;
                    }

                    else{

                        lightsInThisBatch = remainder;
                    }
                }

                else{

                    lightsInThisBatch = maxTriangleAmount;
                }
            }

            int vertexCount = lightsInThisBatch * 3;

            Vector4[] corners = new Vector4[vertexCount];
            Vector2[] uvs = new Vector2[vertexCount];
            Vector4[] triangleCorners = new Vector4[3];
            Vector2[] triangleUvs = new Vector2[3];
            bool directional = false;
            bool omnidirectional = false;
            bool strobe = false;
            bool papi = false;
            Vector3 normal = Vector3.one;
            Vector3 right = Vector3.one;
            Vector3 up = Vector3.one;

            //Create temporary arrays.
            Vector3[] centers = new Vector3[vertexCount];
            Vector3[] normals = new Vector3[vertexCount];
            int[] triangles = new int[vertexCount];
            int[] indices = new int[vertexCount];

            //What is stored in here, depends on the shader.
            Vector2[] uv3Channel = new Vector2[vertexCount];
            Vector2[] uv2Channel = new Vector2[vertexCount];
            Vector2[] uv4Channel = new Vector2[vertexCount];
            Color[] colorChannel = new Color[vertexCount];

            if(material.shader.name.Contains("Directional")){

                directional = true;
            }

            if(material.shader.name.Contains("Omnidirectional")){

                omnidirectional = true;
            }

            if(material.shader.name.Contains("Strobe")){

                strobe = true;
            }

            if(material.shader.name.Contains("PAPI")){

                papi = true;
            }

            //Loop through all the lights and set them up.
            for(int i = 0; i < lightsInThisBatch; i++){

                int e = i * 3;
                int e1 = e + 1;
                int e2 = e + 2;
                int index = (l * maxTriangleAmount) + i;

                //Generate a triangle which fits over a quad.
                GenerateTriangle(out triangleCorners, out triangleUvs, lightData[index].size, Quaternion.identity);

                centers[e] = lightData[index].position;
                centers[e1] = lightData[index].position;
                centers[e2] = lightData[index].position;

                //Get the rotation vectors.
                normal = -Math3d.GetForwardVector(lightData[index].rotation);
                right = Math3d.GetRightVector(lightData[index].rotation);
                up = Math3d.GetUpVector(lightData[index].rotation);

                //Store the scale offset in the w component of the triangle corner.
                triangleCorners[0] = new Vector4(triangleCorners[0].x, triangleCorners[0].y, triangleCorners[0].z, lightData[index].size);
                triangleCorners[1] = new Vector4(triangleCorners[1].x, triangleCorners[1].y, triangleCorners[1].z, lightData[index].size);
                triangleCorners[2] = new Vector4(triangleCorners[2].x, triangleCorners[2].y, triangleCorners[2].z, lightData[index].size);

                corners[e] = triangleCorners[0];
                corners[e1] = triangleCorners[1];
                corners[e2] = triangleCorners[2];

                uvs[e] = triangleUvs[0];
                uvs[e1] = triangleUvs[1];
                uvs[e2] = triangleUvs[2];

                normals[e] = normal;
                normals[e1] = normal;
                normals[e2] = normal;

                if(papi){

                    uv2Channel[e] = right;
                    uv2Channel[e1] = right;
                    uv2Channel[e2] = right;

                    uv3Channel[e] = up;
                    uv3Channel[e1] = up;
                    uv3Channel[e2] = up;

                    //Compose the z vector.
                    Vector2 zVector = new Vector2(right.z, up.z);
                    uv4Channel[e] = zVector;
                    uv4Channel[e1] = zVector;
                    uv4Channel[e2] = zVector;
                }

                if(directional){

                    //Create the back color.
                    Vector2 RG = new Vector2(lightData[index].backColor.r, lightData[index].backColor.g);
                    Vector2 BA = new Vector2(lightData[index].backColor.b, lightData[index].backColor.a);

                    uv2Channel[e] = RG;
                    uv2Channel[e1] = RG;
                    uv2Channel[e2] = RG;

                    uv3Channel[e] = BA;
                    uv3Channel[e1] = BA;
                    uv3Channel[e2] = BA;
                }

                if(omnidirectional){

                    //Create the back color.
                    Vector2 RG = new Vector2(lightData[index].backColor.r, lightData[index].backColor.g);

                    uv2Channel[e] = RG;
                    uv2Channel[e1] = RG;
                    uv2Channel[e2] = RG;

                    uv3Channel[e] = up;
                    uv3Channel[e1] = up;
                    uv3Channel[e2] = up;

                    //Compose the z vector. The x component is used for the blue component of the back color.
                    Vector2 zVector = new Vector2(lightData[index].backColor.b, up.z);
                    uv4Channel[e] = zVector;
                    uv4Channel[e1] = zVector;
                    uv4Channel[e2] = zVector;
                }

                if(strobe){

                    //Store the light and group id in the color channel.
                    Color id = new Color(lightData[index].strobeID, lightData[index].strobeGroupID, 0, 0);

                    colorChannel[e] = id;
                    colorChannel[e1] = id;
                    colorChannel[e2] = id;
                }

                if(directional || omnidirectional){

                    //Create the front color. Note that the light brightness value is stored in the alpha channel.
                    Color frontColor = new Color(lightData[index].frontColor.r, lightData[index].frontColor.g, lightData[index].frontColor.b, lightData[index].brightness);

                    colorChannel[e] = frontColor;
                    colorChannel[e1] = frontColor;
                    colorChannel[e2] = frontColor;
                }

                triangles[e] = e;
                triangles[e1] = e1;
                triangles[e2] = e2;

                indices[e] = e;
                indices[e1] = e1;
                indices[e2] = e2;
            }

            //Create a new gameObject.
            GameObject lightObject = new GameObject(name + " " + l);
            lightObjects[l] = lightObject;

            //Add the required components to the game object.
            MeshFilter meshFilter = lightObject.AddComponent<MeshFilter>();
            MeshRenderer meshRenderer = lightObject.AddComponent<MeshRenderer>();

            //Create a new mesh.
            meshFilter.sharedMesh = new Mesh();

            //Apply the mesh properties
            meshFilter.sharedMesh.vertices = centers;
            meshFilter.sharedMesh.tangents = corners; //The mesh corner is stored in the tangent channel. The scale is stored in the w component.
            meshFilter.sharedMesh.normals = normals;
            meshFilter.sharedMesh.uv = uvs;
            meshFilter.sharedMesh.triangles = triangles;
            meshFilter.sharedMesh.colors = colorChannel; //Front color for directional lights. Alpha is the brightness reduction. //ID for strobe lights.
            meshFilter.sharedMesh.uv2 = uv2Channel; //RG(BA) back color for directional lights. //Rotation vector for omnidirectional lights and PAPIs.
            meshFilter.sharedMesh.uv3 = uv3Channel; //(RG)BA back color for directional lights. Alpha is for invisibility. //Rotation vector for omnidirectional lights and PAPIS.
            meshFilter.sharedMesh.uv4 = uv4Channel; //The UV channels only hold two floats, so use a third UV channel to store the Z components of the vectors.

            //Set the indices.
            meshFilter.sharedMesh.SetIndices(indices, MeshTopology.Triangles, 0);

            //Set the gameObject properties;
            meshRenderer.sharedMaterial = material;
            meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            meshRenderer.receiveShadows = false;
            meshRenderer.useLightProbes = false;
            meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
        }

        return lightObjects;
    }
Пример #39
0
            public static LightData FromLLSD(LLSD llsd)
            {
                LightData light = new LightData();

                if (llsd.Type == LLSDType.Map)
                {
                    LLSDMap map = (LLSDMap)llsd;

                    light.Color.FromLLSD(map["color"]);
                    light.Intensity = (float)map["intensity"].AsReal();
                    light.Radius = (float)map["radius"].AsReal();
                    light.Cutoff = (float)map["cutoff"].AsReal();
                    light.Falloff = (float)map["falloff"].AsReal();
                }

                return light;
            }
Пример #40
0
        /// <summary>
        /// Devuelve la luz mas cercana a la posicion especificada
        /// </summary>
        private LightData getClosestLight(Vector3 pos, LightData ignore1, LightData ignore2)
        {
            float minDist = float.MaxValue;
            LightData minLight = null;

            foreach (LightData light in lights)
            {
                //Ignorar las luces indicadas
                if (ignore1 != null && light.Equals(ignore1))
                    continue;
                if (ignore2 != null && light.Equals(ignore2))
                    continue;

                float distSq = Vector3.LengthSq(pos - light.pos);
                if (distSq < minDist)
                {
                    minDist = distSq;
                    minLight = light;
                }
            }

            return minLight;
        }
Пример #41
0
        /// <summary>
        /// Send the light information to the arduino
        /// </summary>
        /// <param name="lights"></param>
        public void Output(List<Core.Light> lights, LightData data)
        {
            if (_port != null && _port.IsOpen)
            {
                if (_serialData == null || _serialData.Length != lights.Count)
                {
                    _serialData = new byte[6 + lights.Count * 3];

                    _serialData[0] = Convert.ToByte(this.MagicWord.ToCharArray(0, 1)[0]); // Magic word
                    _serialData[1] = Convert.ToByte(this.MagicWord.ToCharArray(1, 1)[0]);
                    _serialData[2] = Convert.ToByte(this.MagicWord.ToCharArray(2, 1)[0]);
                    _serialData[3] = (byte)((lights.Count) >> 8); // LED count high byte
                    _serialData[4] = (byte)((lights.Count) & 0xff); // LED count low byte
                    _serialData[5] = (byte)(_serialData[3] ^ _serialData[4] ^ 0x55); // Checksum
                }

                int serialDataPos = 6;
                // Fast copy of data to serial buffer
                Buffer.BlockCopy(data.ColourData, 0, _serialData, serialDataPos, data.ColourData.Length);

                // Issue data to Arduino
                try
                {
                    if (_port != null)
                    {
                        _port.Write(_serialData, 0, _serialData.Length);
                    }
                }
                catch (Exception ex)
                {
                    AfterglowRuntime.Logger.Error(ex, "Arduino Output - Output - Write to port error");
                }
            }
            else
            {
                Start();
            }
        }
Пример #42
0
        /// <summary>
        /// Start running the current profile
        /// </summary>
        public void Start()
        {
            Stop();
            Logger.Info("Starting...");

            bool profileJustSet = false;
            if (this.CurrentProfile == null)
            {
                this.CurrentProfile = (from p in this.Setup.Profiles
                                       where p.Id == this.Setup.CurrentProfileId
                                       select p).FirstOrDefault();
                profileJustSet = true;
            }

            if (this.CurrentProfile == null)
            {
                CurrentProfile = this.Setup.Profiles.FirstOrDefault();
                profileJustSet = true;
            }

            if (CurrentProfile == null)
            {
                Logger.Error("No profile has been selected");
                return;
            }
            else
            {
                //Reset current profile incase there has been any setting changes
                if (!profileJustSet)
                {
                    this.CurrentProfile = (from p in this.Setup.Profiles
                                           where p.Id == this.CurrentProfile.Id
                                           select p).First();
                }

                CurrentProfile.Validate();

                if (!Active)
                {
                    Active = true;
                    
                    // Prepare light data buffer
                    _nextLightData = new LightData(CurrentProfile.LightSetupPlugin.Lights.Count);
                    _prevLightData = new LightData(CurrentProfile.LightSetupPlugin.Lights.Count); ;

                    // Start all plugins
                    CurrentProfile.CapturePlugin.Start();
                    CurrentProfile.ColourExtractionPlugin.Start();
                    CurrentProfile.PostProcessPlugins.ToList().ForEach(p => p.Start());
                    CurrentProfile.PreOutputPlugins.ToList().ForEach(p => p.Start());

                    string errorMessage = String.Empty;
                    int outputFailures = 0;
                    List<IOutputPlugin> outputPluginsInError = new List<IOutputPlugin>();
                    foreach (IOutputPlugin outputPlugin in CurrentProfile.OutputPlugins)
                    {
                        if (!outputPlugin.TryStart())
                        {
                            outputFailures++;
                            outputPluginsInError.Add(outputPlugin);
                        }
                    }

                    //If all output plugins are in error then stop
                    if (outputFailures == CurrentProfile.OutputPlugins.Count())
                    {
                        Stop();
                    }
                    else
                    {
                        //Remove plugins in error and allow other plugins to continue to run
                        outputPluginsInError.ForEach(o => this.CurrentProfile.OutputPlugins.Remove(o));
                        
                        // Commence capture and output threads
                        _captureLoopTask = Task.Factory.StartNew(CaptureLoop);
                        _outputLoopTask = Task.Factory.StartNew(OutputLoop);
                    }
                }
            }
        }
Пример #43
0
 /// <summary>
 /// Thread safe retrieval of the previous frame's final adjusted light data
 /// </summary>
 /// <returns>A copy of the current light data (can be null if no light data)</returns>
 /// <remarks>Frequent calling of this method may have a performance impact due to thread synchronisation.</remarks>
 public LightData GetPreviousLightData()
 {
     lock (previousSync)
     {
         if (_prevLightData == null)
             return null;
         LightData data = new LightData(_prevLightData);
         return data;
     }
 }
Пример #44
0
        public void Update()
        {
            if (_timeStamp > 0.0f)
             {
            float u = Mathf.Clamp01((Time.time - _timeStamp) / _transitionTime);
            LightData blendedData = new LightData(Color.Lerp(_fromData.LightColor, _toData.LightColor, u), Mathf.Lerp(_fromData.LightIntensity, _toData.LightIntensity, u));

            EightNightsMgr.Instance.SendHueEvent(_gID, _lID, blendedData);

            if (Mathf.Approximately(u, 1.0f))
               _timeStamp = -1.0f;
             }
        }
        public void Process(List<Core.Light> lights, LightData data)
        {
            if (this.Brightness == 100 && this.RedSaturation == 100 && this.GreenSaturation == 100 && this.BlueSaturation == 100)
                return;

            for (var i = 0; i < data.Length; i++)
            {
                var lightColour = data[i];
                double red = lightColour.R;
                double green = lightColour.G;
                double blue = lightColour.B;

                bool coloursChanged = false;
                 
                 // Apply Gamma first...
                 // Ref: http://www.cambridgeincolour.com/tutorials/gamma-correction.htm
                 if (this.Gamma != 100)
                 {
                     red = this._gammaArray[(int) red];
                     green = this._gammaArray[(int) green];
                     blue = this._gammaArray[(int) blue];
 
                     coloursChanged = true;
                 }

                //Change brightness second
                if (this.Brightness != 100)
                {
                    double percent = Brightness / 100.00;
                    red = red * percent;
                    green = green * percent;
                    blue = blue * percent;

                    coloursChanged = true;
                }

                if (this.RedSaturation != 100)
                {
                    double percent = RedSaturation / 100.00;
                    red = red * percent;

                    coloursChanged = true;
                }

                if (this.GreenSaturation != 100)
                {
                    double percent = GreenSaturation / 100.00;
                    green = green * percent;

                    coloursChanged = true;
                }

                if (this.BlueSaturation != 100)
                {
                    double percent = BlueSaturation / 100.00;
                    blue = blue * percent;

                    coloursChanged = true;
                }

                if (coloursChanged)
                {
                    data[i] = Color.FromArgb((int)red, (int)green, (int)blue);
                }
            }
        }
Пример #46
0
 public LightEventArgs(GroupID g, LightID l, LightTypes lt, LightData d)
 {
     Group = g; Light = l; LightType = lt;  Data = d;
 }
Пример #47
0
 public void SendHueEvent(GroupID gID, LightID lID, LightData newData)
 {
     if(OnLightChanged != null)
      OnLightChanged(this, new LightEventArgs(gID, lID, LightTypes.Hue, newData));
 }
Пример #48
0
 public LightEventArgs(EightNightsMgr.GroupID g, EightNightsMgr.LightID l, LightTypes lt, LightData d)
 {
     Group = g; Light = l; LightType = lt; Data = d;
 }
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Cargar escenario, pero inicialmente solo hacemos el parser, para separar los objetos que son solo luces y no meshes
            string scenePath = GuiController.Instance.ExamplesDir + "Lights\\Escenario\\EscenarioLuces-TgcScene.xml";
            string mediaPath = GuiController.Instance.ExamplesDir + "Lights\\Escenario\\";
            TgcSceneParser parser = new TgcSceneParser();
            TgcSceneData sceneData = parser.parseSceneFromString(File.ReadAllText(scenePath));

            //Separar modelos reales de las luces, segun layer "Lights"
            lights = new List<LightData>();
            List<TgcMeshData> realMeshData = new List<TgcMeshData>();
            for (int i = 0; i < sceneData.meshesData.Length; i++)
            {
                TgcMeshData meshData = sceneData.meshesData[i];

                //Es una luz, no cargar mesh, solo importan sus datos
                if (meshData.layerName == "Lights")
                {
                    //Guardar datos de luz
                    LightData light = new LightData();
                    light.color = Color.FromArgb((int)meshData.color[0], (int)meshData.color[1], (int)meshData.color[2]);
                    light.aabb = new TgcBoundingBox(TgcParserUtils.float3ArrayToVector3(meshData.pMin), TgcParserUtils.float3ArrayToVector3(meshData.pMax));
                    light.pos = light.aabb.calculateBoxCenter();
                    lights.Add(light);
                }
                //Es un mesh real, agregar a array definitivo
                else
                {
                    realMeshData.Add(meshData);
                }
            }

            //Reemplazar array original de meshData de sceneData por el definitivo
            sceneData.meshesData = realMeshData.ToArray();

            //Ahora si cargar meshes reales
            TgcSceneLoader loader = new TgcSceneLoader();
            scene = loader.loadScene(sceneData, mediaPath);

            //Camara en 1ra persona
            GuiController.Instance.FpsCamera.Enable = true;
            GuiController.Instance.FpsCamera.MovementSpeed = 400f;
            GuiController.Instance.FpsCamera.JumpSpeed = 300f;
            GuiController.Instance.FpsCamera.setCamera(new Vector3(-20, 80, 450), new Vector3(0, 80, 1));

            //Modifiers para variables de luz
            GuiController.Instance.Modifiers.addBoolean("lightEnable", "lightEnable", true);
            GuiController.Instance.Modifiers.addFloat("lightIntensity", 0, 150, 20);
            GuiController.Instance.Modifiers.addFloat("lightAttenuation", 0.1f, 2, 0.3f);
            GuiController.Instance.Modifiers.addFloat("specularEx", 0, 20, 9f);

            //Modifiers para material
            GuiController.Instance.Modifiers.addColor("mEmissive", Color.Black);
            GuiController.Instance.Modifiers.addColor("mAmbient", Color.White);
            GuiController.Instance.Modifiers.addColor("mDiffuse", Color.White);
            GuiController.Instance.Modifiers.addColor("mSpecular", Color.White);
        }
Пример #50
0
    void OnHueLightChanged(object sender, HueMessenger.HueEventArgs e)
    {
        if (OnLightChanged != null)
          {
         GroupID gID = GroupID.RiftGroup1;
         LightID lID = LightID.Light1;
         if (FindLight(e.LightID, LightTypes.Hue, ref gID, ref lID))
         {
            LightData newData = new LightData(e.LightColor, e.LightFade);

            //simulate fades
            if (e.TransitionTime > 0.0)
            {
               LightData fromData = new LightData(e.PrevColor, e.PrevFade);
               BlendHueData newBlendData = new BlendHueData(gID, lID, fromData, newData, e.TransitionTime);

               foreach (BlendHueData h in _eventBlends)
               {
                  if ((h.GetGroupID() == gID) && (h.GetLightID() == lID))
                  {
                     _eventBlends.Remove(h);
                     break;
                  }
               }

               _eventBlends.Add(newBlendData);
            }
            else
            {
               SendHueEvent(gID, lID, newData);
            }
         }
          }
    }