internal MASPagePolygon(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string colorString = string.Empty;

            if (!config.TryGetValue("color", ref colorString))
            {
                throw new ArgumentException("Unable to find 'color' in POLYGON " + name);
            }

            string[] vertexStrings = config.GetValues("vertex");
            if (vertexStrings.Length < 3)
            {
                throw new ArgumentException("Insufficient number of 'vertex' entries in POLYGON " + name + " (must have at least 3)");
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            polygonOrigin                    = new GameObject();
            polygonOrigin.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            polygonOrigin.layer              = pageRoot.gameObject.layer;
            polygonOrigin.transform.parent   = pageRoot;
            polygonOrigin.transform.position = pageRoot.position;
            polygonOrigin.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth);

            origin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                position = Vector2.zero;
                throw new ArgumentException("Unable to find 'position' in POLYGON " + name);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in POLYGON " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                {
                    position.x = (float)newValue;
                    polygonOrigin.transform.position = origin + new Vector3(position.x, -position.y, 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                {
                    position.y = (float)newValue;
                    polygonOrigin.transform.position = origin + new Vector3(position.x, -position.y, 0.0f);
                });
            }

            // add renderer stuff
            MeshFilter meshFilter = polygonOrigin.AddComponent <MeshFilter>();

            meshRenderer    = polygonOrigin.AddComponent <MeshRenderer>();
            mesh            = new Mesh();
            meshFilter.mesh = mesh;

            int numVertices = vertexStrings.Length;

            vertices = new Vector3[numVertices];

            polygonMaterial       = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            polygonMaterial.color = color;
            meshRenderer.material = polygonMaterial;

            for (int i = 0; i < numVertices; ++i)
            {
                // Need to make a copy of the value for the lambda capture,
                // otherwise we'll try using i = numVertices in the callbacks.
                int index = i;
                vertices[i] = Vector3.zero;

                string[] vtx = Utility.SplitVariableList(vertexStrings[i]);
                if (vtx.Length != 2)
                {
                    throw new ArgumentException("vertex " + (i + 1).ToString() + " does not contain two values in POLYGON " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(vtx[0], (double newValue) =>
                {
                    vertices[index].x = (float)newValue;
                    retriangulate     = true;
                });

                variableRegistrar.RegisterVariableChangeCallback(vtx[1], (double newValue) =>
                {
                    // Invert the value, since we stipulate +y is down on the monitor.
                    vertices[index].y = -(float)newValue;
                    retriangulate     = true;
                });
            }
            mesh.vertices = vertices;

            // For 3 or 4 vertices, the index array is invariant.  Load it now and be done with it.
            if (numVertices == 3)
            {
                mesh.triangles = new[]
                {
                    0, 2, 1
                };
            }
            else if (numVertices == 4)
            {
                mesh.triangles = new[]
                {
                    0, 2, 1,
                    0, 3, 2
                };
            }

            RenderPage(false);

            string rotationVariableName = string.Empty;

            if (config.TryGetValue("rotation", ref rotationVariableName))
            {
                variableRegistrar.RegisterVariableChangeCallback(rotationVariableName, RotationCallback);
            }

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                polygonOrigin.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                currentState = true;
                polygonOrigin.SetActive(true);
            }

            Color32 col;

            if (comp.TryGetNamedColor(colorString, out col))
            {
                color = col;
                polygonMaterial.color = color;
            }
            else
            {
                string[] colors = Utility.SplitVariableList(colorString);
                if (colors.Length < 3 || colors.Length > 4)
                {
                    throw new ArgumentException("color does not contain 3 or 4 values in POLYGON " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(colors[0], (double newValue) =>
                {
                    color.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    polygonMaterial.color = color;
                });

                variableRegistrar.RegisterVariableChangeCallback(colors[1], (double newValue) =>
                {
                    color.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    polygonMaterial.color = color;
                });

                variableRegistrar.RegisterVariableChangeCallback(colors[2], (double newValue) =>
                {
                    color.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    polygonMaterial.color = color;
                });

                if (colors.Length == 4)
                {
                    variableRegistrar.RegisterVariableChangeCallback(colors[3], (double newValue) =>
                    {
                        color.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        polygonMaterial.color = color;
                    });
                }
            }
        }
Exemple #2
0
        internal MASPageText(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            if (!config.TryGetValue("text", ref text))
            {
                string textfile = string.Empty;
                if (!config.TryGetValue("textfile", ref textfile))
                {
                    string rpmModText = string.Empty;
                    if (!config.TryGetValue("textmethod", ref rpmModText))
                    {
                        throw new ArgumentException("Unable to find 'text', 'textfile', or 'textmethod' in TEXT " + name);
                    }

                    string[] rpmMod = rpmModText.Split(':');
                    if (rpmMod.Length != 2)
                    {
                        throw new ArgumentException("Invalid 'textmethod' in TEXT " + name);
                    }
                    bool moduleFound = false;

                    int numModules = prop.internalModules.Count;
                    int moduleIndex;
                    for (moduleIndex = 0; moduleIndex < numModules; ++moduleIndex)
                    {
                        if (prop.internalModules[moduleIndex].ClassName == rpmMod[0])
                        {
                            moduleFound = true;
                            break;
                        }
                    }

                    if (moduleFound)
                    {
                        rpmModule = prop.internalModules[moduleIndex];
                        Type       moduleType = prop.internalModules[moduleIndex].GetType();
                        MethodInfo method     = moduleType.GetMethod(rpmMod[1]);
                        if (method != null && method.GetParameters().Length == 2 && method.GetParameters()[0].ParameterType == typeof(int) && method.GetParameters()[1].ParameterType == typeof(int))
                        {
                            rpmModuleTextMethod = DynamicMethodFactory.CreateFunc <object, int, int, string>(method);
                        }
                    }

                    if (rpmModuleTextMethod != null)
                    {
                        this.comp = comp;
                        this.prop = prop;
                    }
                    text = " ";
                }
                else
                {
                    // Load text
                    text = string.Join(Environment.NewLine, File.ReadAllLines(KSPUtil.ApplicationRootPath + "GameData/" + textfile.Trim(), Encoding.UTF8));
                }
            }

            string localFonts = string.Empty;

            if (!config.TryGetValue("font", ref localFonts))
            {
                localFonts = string.Empty;
            }

            string    styleStr = string.Empty;
            FontStyle style    = FontStyle.Normal;

            if (config.TryGetValue("style", ref styleStr))
            {
                style = MdVTextMesh.FontStyle(styleStr);
            }
            else
            {
                style = monitor.defaultStyle;
            }

            Vector2 fontSize = Vector2.zero;

            if (!config.TryGetValue("fontSize", ref fontSize) || fontSize.x < 0.0f || fontSize.y < 0.0f)
            {
                fontSize = monitor.fontSize;
            }

            Color32 textColor;
            string  textColorStr = string.Empty;

            if (!config.TryGetValue("textColor", ref textColorStr) || string.IsNullOrEmpty(textColorStr))
            {
                textColor = monitor.textColor_;
            }
            else
            {
                textColor = Utility.ParseColor32(textColorStr, comp);
            }

            // Position is based on default font size
            fontScale = monitor.fontSize;
            // Position is based on local font size.
            //fontScale = fontSize;

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            // Set up our text.
            imageOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            meshObject                    = new GameObject();
            meshObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            meshObject.layer              = pageRoot.gameObject.layer;
            meshObject.transform.parent   = pageRoot;
            meshObject.transform.position = imageOrigin;

            string positionString = string.Empty;

            if (config.TryGetValue("position", ref positionString))
            {
                string[] positions = Utility.SplitVariableList(positionString);
                if (positions.Length != 2)
                {
                    throw new ArgumentException("position does not contain 2 values in TEXT " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(positions[0], (double newValue) =>
                {
                    position.x = (float)newValue * fontScale.x;
                    meshObject.transform.position = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(positions[1], (double newValue) =>
                {
                    position.y = (float)newValue * fontScale.y;
                    meshObject.transform.position = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                });
            }

            textObj = meshObject.gameObject.AddComponent <MdVTextMesh>();

            Font font;

            if (string.IsNullOrEmpty(localFonts))
            {
                font = monitor.defaultFont;
            }
            else
            {
                font = MASLoader.GetFont(localFonts.Trim());
            }

            // We want to use a different shader for monitor displays.
            textObj.material = new Material(MASLoader.shaders["MOARdV/TextMonitor"]);
            textObj.SetFont(font, fontSize);
            textObj.SetColor(textColor);
            textObj.material.SetFloat(Shader.PropertyToID("_EmissiveFactor"), 1.0f);
            textObj.fontStyle = style;

            // text, immutable, preserveWhitespace, comp, prop
            textObj.SetText(text, false, true, comp, prop);
            RenderPage(false);

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                meshObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                currentState = true;
            }

            if (rpmModuleTextMethod != null)
            {
                comp.StartCoroutine(TextMethodUpdate());
            }
        }
        internal MASPageRpmModule(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            this.comp = comp;

            Vector2 size = Vector2.zero;

            if (!config.TryGetValue("size", ref size))
            {
                size = monitor.screenSize;
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            displayTexture = new RenderTexture(((int)size.x) >> MASConfig.CameraTextureScale, ((int)size.y) >> MASConfig.CameraTextureScale, 24, RenderTextureFormat.ARGB32);
            displayTexture.Create();

            string moduleNameString = string.Empty;

            if (!config.TryGetValue("moduleName", ref moduleNameString))
            {
                throw new ArgumentException("Unable to find 'moduleName' in RPM_MODULE " + name);
            }

            bool moduleFound = false;

            int numModules = prop.internalModules.Count;
            int moduleIndex;

            for (moduleIndex = 0; moduleIndex < numModules; ++moduleIndex)
            {
                if (prop.internalModules[moduleIndex].ClassName == moduleNameString)
                {
                    moduleFound = true;
                    break;
                }
            }

            if (moduleFound)
            {
                rpmModule = prop.internalModules[moduleIndex];
                Type moduleType = prop.internalModules[moduleIndex].GetType();

                string renderMethodName = string.Empty;
                if (config.TryGetValue("renderMethod", ref renderMethodName))
                {
                    MethodInfo method = moduleType.GetMethod(renderMethodName);
                    if (method != null && method.GetParameters().Length == 2 && method.GetParameters()[0].ParameterType == typeof(RenderTexture) && method.GetParameters()[1].ParameterType == typeof(float))
                    {
                        renderMethod = DynamicMethodFactory.CreateFunc <object, RenderTexture, float, object>(method);
                    }

                    if (renderMethod != null)
                    {
                        Vector2 renderSize = Vector2.zero;
                        if (!config.TryGetValue("renderSize", ref renderSize))
                        {
                            renderSize = size;
                        }

                        if (renderSize != size)
                        {
                            temporarySizeX      = (int)renderSize.x;
                            temporarySizeY      = (int)renderSize.y;
                            useTemporaryTexture = true;

                            float xScaling = size.x / renderSize.x;
                            float yScaling = size.y / renderSize.y;

                            float aspectRatio = xScaling / yScaling;
                            if (aspectRatio > 1.0f)
                            {
                                // wide aspect ratio
                                uvScale.y  = 1.0f / aspectRatio;
                                uvOffset.y = uvScale.y * 0.5f;
                            }
                            else if (aspectRatio < 1.0f)
                            {
                                uvScale.x  = aspectRatio;
                                uvOffset.x = uvScale.x * 0.5f;
                            }
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Unable to initialize 'renderMethod' " + renderMethodName + " in RPM_MODULE " + name);
                    }
                }

                string pageActiveMethodName = string.Empty;
                if (config.TryGetValue("pageActiveMethod", ref pageActiveMethodName))
                {
                    MethodInfo method = moduleType.GetMethod(pageActiveMethodName);
                    if (method != null && method.GetParameters().Length == 2 && method.GetParameters()[0].ParameterType == typeof(bool) && method.GetParameters()[1].ParameterType == typeof(int))
                    {
                        pageActiveMethod = DynamicMethodFactory.CreateFunc <object, bool, int, object>(method);
                    }
                    else
                    {
                        throw new ArgumentException("Unable to initialize 'pageActiveMethod' " + pageActiveMethodName + " in RPM_MODULE " + name);
                    }
                }

                string buttonClickMethodName = string.Empty;
                if (config.TryGetValue("buttonClickMethod", ref buttonClickMethodName))
                {
                    MethodInfo method = moduleType.GetMethod(buttonClickMethodName);
                    if (method != null && method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(int))
                    {
                        buttonClickMethod = DynamicMethodFactory.CreateDynFunc <object, int, object>(method);
                    }
                }
            }
            else
            {
                string textureName = string.Empty;
                if (config.TryGetValue("texture", ref textureName))
                {
                    Texture missingTexture = GameDatabase.Instance.GetTexture(textureName, false);
                    if (missingTexture != null)
                    {
                        Graphics.Blit(missingTexture, displayTexture);
                    }
                }
            }

            componentOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f + size.x * 0.5f, monitor.screenSize.y * 0.5f - size.y * 0.5f, depth);

            // Set up our surface.
            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = pageRoot.position;
            imageObject.transform.Translate(monitor.screenSize.x * -0.5f + position.x + size.x * 0.5f, monitor.screenSize.y * 0.5f - position.y - size.y * 0.5f, depth);
            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer = imageObject.AddComponent <MeshRenderer>();
            Mesh mesh = new Mesh();

            mesh.vertices = new[]
            {
                new Vector3(-0.5f * size.x, 0.5f * size.y, depth),
                new Vector3(0.5f * size.x, 0.5f * size.y, depth),
                new Vector3(-0.5f * size.x, -0.5f * size.y, depth),
                new Vector3(0.5f * size.x, -0.5f * size.y, depth),
            };
            mesh.uv = new[]
            {
                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(true);
            meshFilter.mesh = mesh;

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                positionString = "0,0";
            }

            string[] pos = Utility.SplitVariableList(positionString);
            if (pos.Length != 2)
            {
                throw new ArgumentException("Invalid number of values for 'position' in RPM_MODULE " + name);
            }

            variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
            {
                position.x = (float)newValue;
                imageObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
            });

            variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
            {
                position.y = (float)newValue;
                imageObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
            });

            imageMaterial             = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            imageMaterial.mainTexture = displayTexture;
            meshRenderer.material     = imageMaterial;
            RenderPage(false);

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                currentState = true;
                imageObject.SetActive(true);
            }

            if (renderMethod != null)
            {
                comp.StartCoroutine(QueryModule());
            }
        }
Exemple #4
0
        internal MASPageImage(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string textureName = string.Empty;

            if (!config.TryGetValue("texture", ref textureName))
            {
                throw new ArgumentException("Unable to find 'texture' in IMAGE " + name);
            }
            Texture2D mainTexture = null;

            if (textureName == "%MAP_ICON%")
            {
                mainTexture = MASLoader.OrbitIconsAtlas();
            }
            else if (textureName == "%NAVBALL_ICON%")
            {
                mainTexture = GameDatabase.Instance.GetTexture("Squad/Props/IVANavBall/ManeuverNode_vectors", false);
            }
            else
            {
                if (textureName == "%FLAG%")
                {
                    textureName = prop.part.flagURL;
                }
                mainTexture = GameDatabase.Instance.GetTexture(textureName, false);
            }
            if (mainTexture == null)
            {
                throw new ArgumentException("Unable to find 'texture' " + textureName + " for IMAGE " + name);
            }

            bool wrap = true;

            if (config.TryGetValue("wrap", ref wrap))
            {
                mainTexture.wrapMode = (wrap) ? TextureWrapMode.Repeat : TextureWrapMode.Clamp;
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            string rotationVariableName = string.Empty;

            if (config.TryGetValue("rotation", ref rotationVariableName))
            {
                config.TryGetValue("rotationOffset", ref rotationOffset);
            }

            // Need Mesh for UpdateVertices.
            mesh = new Mesh();
            string sizeString = string.Empty;

            if (!config.TryGetValue("size", ref sizeString))
            {
                size = new Vector2(mainTexture.width, mainTexture.height);
                UpdateVertices();
            }
            else
            {
                string[] sizes = Utility.SplitVariableList(sizeString);
                if (sizes.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'size' in IMAGE " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(sizes[0], (double newValue) =>
                {
                    size.x = (float)newValue;
                    UpdateVertices();
                });

                variableRegistrar.RegisterVariableChangeCallback(sizes[1], (double newValue) =>
                {
                    size.y = (float)newValue;
                    UpdateVertices();
                });
            }

            imageOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            // Need imageObject for UpdatePosition.
            imageObject = new GameObject();
            imageObject.transform.parent = pageRoot;
            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                position = Vector2.zero;
                imageObject.transform.position = imageOrigin + new Vector3(position.x + rotationOffset.x + size.x * 0.5f, -(position.y + rotationOffset.y + size.y * 0.5f), 0.0f);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in IMAGE " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                {
                    position.x = (float)newValue;
                    imageObject.transform.position = imageOrigin + new Vector3(position.x + rotationOffset.x + size.x * 0.5f, -(position.y + rotationOffset.y + size.y * 0.5f), 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                {
                    position.y = (float)newValue;
                    imageObject.transform.position = imageOrigin + new Vector3(position.x + rotationOffset.x + size.x * 0.5f, -(position.y + rotationOffset.y + size.y * 0.5f), 0.0f);
                });
            }

            // Set up our surface.
            imageObject.name  = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer = pageRoot.gameObject.layer;

            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer = imageObject.AddComponent <MeshRenderer>();

            mesh.uv = new[]
            {
                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(false);
            meshFilter.mesh = mesh;

            imageMaterial             = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            imageMaterial.mainTexture = mainTexture;
            meshRenderer.material     = imageMaterial;
            RenderPage(false);

            currentBlend = 0.0f;

            passiveColor = Color.white;
            activeColor  = Color.white;

            string passiveColorName = string.Empty;

            if (config.TryGetValue("passiveColor", ref passiveColorName))
            {
                Color32 color32;
                if (comp.TryGetNamedColor(passiveColorName, out color32))
                {
                    passiveColor = color32;
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(passiveColorName);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("'passiveColor' does not contain 3 or 4 values in IMAGE " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], (double newValue) =>
                    {
                        passiveColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        UpdateColor();
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], (double newValue) =>
                    {
                        passiveColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        UpdateColor();
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], (double newValue) =>
                    {
                        passiveColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        UpdateColor();
                    });

                    if (startColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], (double newValue) =>
                        {
                            passiveColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            UpdateColor();
                        });
                    }
                }
            }

            string colorVariableName = string.Empty;

            if (config.TryGetValue("colorVariable", ref colorVariableName))
            {
                if (string.IsNullOrEmpty(passiveColorName))
                {
                    throw new ArgumentException("'colorVariable' found, but no 'passiveColor' in IMAGE " + name);
                }

                string activeColorName = string.Empty;
                if (!config.TryGetValue("activeColor", ref activeColorName))
                {
                    throw new ArgumentException("'colorVariable' found, but no 'activeColor' in IMAGE " + name);
                }

                string colorRangeString = string.Empty;
                if (config.TryGetValue("colorRange", ref colorRangeString))
                {
                    string[] colorRanges = Utility.SplitVariableList(colorRangeString);
                    if (colorRanges.Length != 2)
                    {
                        throw new ArgumentException("Expected 2 values for 'colorRange' in IMAGE " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(colorRanges[0], (double newValue) => colorRange1 = (float)newValue);
                    variableRegistrar.RegisterVariableChangeCallback(colorRanges[1], (double newValue) => colorRange2 = (float)newValue);

                    bool colorBlend = false;
                    if (config.TryGetValue("colorBlend", ref colorBlend) && colorBlend == true)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(colorVariableName, (double newValue) =>
                        {
                            float newBlend = Mathf.InverseLerp(colorRange1, colorRange2, (float)newValue);

                            if (!Mathf.Approximately(newBlend, currentBlend))
                            {
                                currentBlend = newBlend;
                                UpdateColor();
                            }
                        });
                    }
                    else
                    {
                        variableRegistrar.RegisterVariableChangeCallback(colorVariableName, (double newValue) =>
                        {
                            float newBlend = (newValue.Between(colorRange1, colorRange2)) ? 1.0f : 0.0f;
                            if (newBlend != currentBlend)
                            {
                                currentBlend = newBlend;
                                UpdateColor();
                            }
                        });
                    }
                }
                else
                {
                    variableRegistrar.RegisterVariableChangeCallback(colorVariableName, (double newValue) =>
                    {
                        float newBlend = (newValue > 0.0) ? 1.0f : 0.0f;
                        if (newBlend != currentBlend)
                        {
                            currentBlend = newBlend;
                            UpdateColor();
                        }
                    });
                }

                Color32 color32;
                if (comp.TryGetNamedColor(activeColorName, out color32))
                {
                    activeColor = color32;
                }
                else
                {
                    string[] activeColors = Utility.SplitVariableList(activeColorName);
                    if (activeColors.Length < 3 || activeColors.Length > 4)
                    {
                        throw new ArgumentException("'activeColor' does not contain 3 or 4 values in IMAGE " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(activeColors[0], (double newValue) =>
                    {
                        activeColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        UpdateColor();
                    });

                    variableRegistrar.RegisterVariableChangeCallback(activeColors[1], (double newValue) =>
                    {
                        activeColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        UpdateColor();
                    });

                    variableRegistrar.RegisterVariableChangeCallback(activeColors[2], (double newValue) =>
                    {
                        activeColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        UpdateColor();
                    });

                    if (activeColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(activeColors[3], (double newValue) =>
                        {
                            activeColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            UpdateColor();
                        });
                    }
                }
            }

            // In case fixed colors are being used.
            UpdateColor();

            string uvTilingString = string.Empty;

            if (config.TryGetValue("tiling", ref uvTilingString))
            {
                string[] uvTile = Utility.SplitVariableList(uvTilingString);
                if (uvTile.Length != 2)
                {
                    throw new ArgumentException("'tiling' does not contain 2 values in IMAGE " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(uvTile[0], (double newValue) =>
                {
                    float rescale = Mathf.Max((float)newValue, 0.0f);
                    if (!Mathf.Approximately(rescale, uvScale.x))
                    {
                        uvScale.x = rescale;
                        imageMaterial.SetTextureScale("_MainTex", uvScale);
                    }
                });

                variableRegistrar.RegisterVariableChangeCallback(uvTile[1], (double newValue) =>
                {
                    float rescale = Mathf.Max((float)newValue, 0.0f);
                    if (!Mathf.Approximately(rescale, uvScale.y))
                    {
                        uvScale.y = rescale;
                        imageMaterial.SetTextureScale("_MainTex", uvScale);
                    }
                });
            }

            string uvShiftString = string.Empty;

            if (config.TryGetValue("uvShift", ref uvShiftString))
            {
                string[] uvShifting = Utility.SplitVariableList(uvShiftString);
                if (uvShifting.Length != 2)
                {
                    throw new ArgumentException("'uvShift' does not contain 2 values in IMAGE " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(uvShifting[0], (double newValue) =>
                {
                    float reshift = (float)newValue;

                    uvShift.x = reshift;
                    imageMaterial.SetTextureOffset("_MainTex", uvShift);
                });
                variableRegistrar.RegisterVariableChangeCallback(uvShifting[1], (double newValue) =>
                {
                    float reshift = (float)newValue;

                    uvShift.y = reshift;
                    imageMaterial.SetTextureOffset("_MainTex", uvShift);
                });
            }

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                imageObject.SetActive(true);
            }

            if (!string.IsNullOrEmpty(rotationVariableName))
            {
                variableRegistrar.RegisterVariableChangeCallback(rotationVariableName, RotationCallback);
            }
        }
Exemple #5
0
        internal MASPageCompoundText(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            this.comp = comp;

            if (!config.TryGetValue("maxLines", ref maxLines))
            {
                throw new ArgumentException("Missing 'maxLines' in COMPOUND_TEXT " + name);
            }
            if (maxLines < 1)
            {
                throw new ArgumentException("'maxLines' must be greater than zero in COMPOUND_TEXT " + name);
            }

            string localFonts = string.Empty;

            if (!config.TryGetValue("font", ref localFonts))
            {
                localFonts = string.Empty;
            }

            string    styleStr = string.Empty;
            FontStyle style    = FontStyle.Normal;

            if (config.TryGetValue("style", ref styleStr))
            {
                style = MdVTextMesh.FontStyle(styleStr);
            }
            else
            {
                style = monitor.defaultStyle;
            }

            Vector2 fontSize = Vector2.zero;

            if (!config.TryGetValue("fontSize", ref fontSize) || fontSize.x < 0.0f || fontSize.y < 0.0f)
            {
                fontSize = monitor.fontSize;
            }

            lineAdvance = fontSize.y;

            Color32 textColor;
            string  textColorStr = string.Empty;

            if (!config.TryGetValue("textColor", ref textColorStr) || string.IsNullOrEmpty(textColorStr))
            {
                textColor = monitor.textColor_;
            }
            else
            {
                textColor = Utility.ParseColor32(textColorStr, comp);
            }

            // Set up our text.
            textOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            rootObject                    = new GameObject();
            rootObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            rootObject.layer              = pageRoot.gameObject.layer;
            rootObject.transform.parent   = pageRoot;
            rootObject.transform.position = textOrigin;

            string positionString = string.Empty;

            if (config.TryGetValue("position", ref positionString))
            {
                string[] positions = Utility.SplitVariableList(positionString);
                if (positions.Length != 2)
                {
                    throw new ArgumentException("position does not contain 2 values in COMPOUND_TEXT " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(positions[0], (double newValue) =>
                {
                    position.x = (float)newValue * monitor.fontSize.x;
                    rootObject.transform.position = textOrigin + new Vector3(position.x, -position.y, 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(positions[1], (double newValue) =>
                {
                    position.y = (float)newValue * monitor.fontSize.y;
                    rootObject.transform.position = textOrigin + new Vector3(position.x, -position.y, 0.0f);
                });
            }

            Font font;

            if (string.IsNullOrEmpty(localFonts))
            {
                font = monitor.defaultFont;
            }
            else
            {
                font = MASLoader.GetFont(localFonts.Trim());
            }

            List <CompoundPageText> textNodes = new List <CompoundPageText>();

            ConfigNode[] textConfigNodes = config.GetNodes("TEXT");
            foreach (ConfigNode textNode in textConfigNodes)
            {
                CompoundPageText cpt = new CompoundPageText();

                if (!textNode.TryGetValue("name", ref cpt.name))
                {
                    cpt.name = "anonymous";
                }

                string variableName = string.Empty;
                if (!textNode.TryGetValue("variable", ref variableName))
                {
                    variableName.Trim();
                }

                string text = string.Empty;
                if (textNode.TryGetValue("text", ref text))
                {
                    cpt.textObject                    = new GameObject();
                    cpt.textObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name + textNodes.Count, cpt.name, (int)(-depth / MASMonitor.depthDelta));
                    cpt.textObject.layer              = rootObject.layer;
                    cpt.textObject.transform.parent   = rootObject.transform;
                    cpt.textObject.transform.position = rootObject.transform.position;

                    cpt.textMesh          = cpt.textObject.AddComponent <MdVTextMesh>();
                    cpt.textMesh.material = new Material(MASLoader.shaders["MOARdV/TextMonitor"]);
                    cpt.textMesh.SetFont(font, fontSize);
                    cpt.textMesh.SetColor(textColor);
                    cpt.textMesh.material.SetFloat(Shader.PropertyToID("_EmissiveFactor"), 1.0f);
                    cpt.textMesh.fontStyle = style;

                    // text, immutable, preserveWhitespace, comp, prop
                    cpt.textMesh.SetText(text, false, true, comp, prop);
                }

                // Process callbacks
                if (!string.IsNullOrEmpty(variableName))
                {
                    if (cpt.textObject != null)
                    {
                        cpt.textObject.SetActive(false);
                    }
                    variableRegistrar.RegisterVariableChangeCallback(variableName, (double newValue) => VariableCallback(newValue, cpt));
                }
                else
                {
                    cpt.currentState = true;
                    if (!coroutineActive)
                    {
                        coroutineActive = true;
                        comp.StartCoroutine(TextMethodUpdate());
                    }
                }

                textNodes.Add(cpt);
            }
            textElements = textNodes.ToArray();

            string masterVariableName = string.Empty;

            if (config.TryGetValue("variable", ref masterVariableName))
            {
                rootObject.SetActive(false);

                variableRegistrar.RegisterVariableChangeCallback(masterVariableName, VariableCallback);
            }
            else
            {
                rootObject.SetActive(true);
            }

            RenderPage(false);
        }
Exemple #6
0
        internal MASPageCamera(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            this.comp = comp;

            Vector2 position = Vector2.zero;

            if (!config.TryGetValue("position", ref position))
            {
                throw new ArgumentException("Unable to find 'position' in CAMERA " + name);
            }

            Vector2 size = Vector2.zero;

            if (!config.TryGetValue("size", ref size))
            {
                throw new ArgumentException("Unable to find 'size' in CAMERA " + name);
            }
            float aspectRatio = size.x / size.y;

            rentexWidth   = ((int)size.x) >> MASConfig.CameraTextureScale;
            rentexHeight  = ((int)size.y) >> MASConfig.CameraTextureScale;
            cameraTexture = new RenderTexture(rentexWidth, rentexHeight, 24, RenderTextureFormat.ARGB32);

            string cameraName = string.Empty;

            if (config.TryGetValue("camera", ref cameraName))
            {
                cameraName = cameraName.Trim();
            }
            else
            {
                throw new ArgumentException("Unable to find 'cameraName' in CAMERA " + name);
            }

            string missingTextureName = string.Empty;

            if (config.TryGetValue("missingTexture", ref missingTextureName))
            {
                missingCameraTexture = GameDatabase.Instance.GetTexture(missingTextureName, false);
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = pageRoot.position;
            imageObject.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth);
            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer = imageObject.AddComponent <MeshRenderer>();
            Mesh mesh = new Mesh();

            mesh.vertices = new[]
            {
                new Vector3(0.0f, 0.0f, 0.0f),
                new Vector3(size.x, 0.0f, 0.0f),
                new Vector3(0.0f, -size.y, 0.0f),
                new Vector3(size.x, -size.y, 0.0f),
            };
            mesh.uv = new[]
            {
                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(true);
            meshFilter.mesh = mesh;

            string shader = string.Empty;

            if (config.TryGetValue("shader", ref shader))
            {
                Shader ppShader;
                if (MASLoader.shaders.TryGetValue(shader, out ppShader))
                {
                    monitorMaterial = new Material(ppShader);
                }
            }
            if (monitorMaterial != null)
            {
                string textureName = string.Empty;
                if (config.TryGetValue("texture", ref textureName))
                {
                    Texture auxTexture = GameDatabase.Instance.GetTexture(textureName, false);
                    if (auxTexture == null)
                    {
                        throw new ArgumentException("Unable to find 'texture' " + textureName + " for CAMERA " + name);
                    }
                    monitorMaterial.SetTexture("_AuxTex", auxTexture);
                }

                string concatProperties = string.Empty;
                if (config.TryGetValue("properties", ref concatProperties))
                {
                    string[] propertiesList = concatProperties.Split(';');
                    int      listLength     = propertiesList.Length;
                    if (listLength > 0)
                    {
                        propertyId    = new int[listLength];
                        propertyValue = new string[listLength];

                        for (int i = 0; i < listLength; ++i)
                        {
                            string[] pair = propertiesList[i].Split(':');
                            if (pair.Length != 2)
                            {
                                throw new ArgumentOutOfRangeException("Incorrect number of parameters for property: requires 2, found " + pair.Length + " in property " + propertiesList[i] + " for CAMERA " + name);
                            }
                            propertyId[i]    = Shader.PropertyToID(pair[0].Trim());
                            propertyValue[i] = pair[1].Trim();
                        }
                        for (int i = 0; i < propertyValue.Length; ++i)
                        {
                            int id = propertyId[i];
                            variableRegistrar.RegisterVariableChangeCallback(propertyValue[i], (double newValue) => monitorMaterial.SetFloat(id, (float)newValue));
                        }
                    }
                }
            }

            imageMaterial             = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            imageMaterial.mainTexture = cameraTexture;
            meshRenderer.material     = imageMaterial;
            RenderPage(false);

            if (!string.IsNullOrEmpty(variableName))
            {
                currentState = false;
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                currentState = true;
                imageObject.SetActive(true);
            }

            if (!cameraTexture.IsCreated())
            {
                cameraTexture.Create();
            }
            cameraTexture.DiscardContents();
            ApplyMissingCamera();

            cameraSelector = variableRegistrar.RegisterVariableChangeCallback(cameraName, CameraSelectCallback, false);
            CameraSelectCallback(0.0);
        }
        internal MASPageVerticalBar(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string textureName = string.Empty;

            if (!config.TryGetValue("texture", ref textureName))
            {
                textureName = string.Empty;
            }
            Texture2D mainTexture = null;

            if (!string.IsNullOrEmpty(textureName))
            {
                mainTexture = GameDatabase.Instance.GetTexture(textureName, false);
                if (mainTexture == null)
                {
                    throw new ArgumentException("Unable to find 'texture' " + textureName + " for VERTICAL_BAR " + name);
                }
                mainTexture.wrapMode = TextureWrapMode.Clamp;
            }

            Vector2 size = Vector2.zero;

            if (!config.TryGetValue("size", ref size))
            {
                throw new ArgumentException("Unable to find 'size' in VERTICAL_BAR " + name);
            }
            barHeight = size.y;

            string sourceName = string.Empty;

            if (!config.TryGetValue("source", ref sourceName))
            {
                throw new ArgumentException("Unable to find 'input' in VERTICAL_BAR " + name);
            }

            string sourceRange = string.Empty;

            if (!config.TryGetValue("sourceRange", ref sourceRange))
            {
                throw new ArgumentException("Unable to find 'sourceRange' in VERTICAL_BAR " + name);
            }
            string[] ranges = Utility.SplitVariableList(sourceRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'sourceRange' in VERTICAL_BAR " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => sourceRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => sourceRange2 = (float)newValue);

            string anchorName = string.Empty;

            if (config.TryGetValue("anchor", ref anchorName))
            {
                anchorName = anchorName.Trim();
                if (anchorName == VBarAnchor.Top.ToString())
                {
                    anchor = VBarAnchor.Top;
                }
                else if (anchorName == VBarAnchor.Bottom.ToString())
                {
                    anchor = VBarAnchor.Bottom;
                }
                else if (anchorName == VBarAnchor.Middle.ToString())
                {
                    anchor = VBarAnchor.Middle;
                }
                else
                {
                    throw new ArgumentException("Uncrecognized 'anchor' " + anchorName + " in VERTICAL_BAR " + name);
                }
            }
            else
            {
                anchor = VBarAnchor.Bottom;
            }

            float borderWidth = 0.0f;

            if (!config.TryGetValue("borderWidth", ref borderWidth))
            {
                borderWidth = 0.0f;
            }
            else
            {
                borderWidth = Math.Max(1.0f, borderWidth);
            }
            string borderColorName = string.Empty;

            if (!config.TryGetValue("borderColor", ref borderColorName))
            {
                borderColorName = string.Empty;
            }
            if (string.IsNullOrEmpty(borderColorName) == (borderWidth > 0.0f))
            {
                throw new ArgumentException("Only one of 'borderColor' and 'borderWidth' are defined in VERTICAL_BAR " + name);
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            // Set up our display surface.
            imageOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);
            if (borderWidth > 0.0f)
            {
                borderObject                    = new GameObject();
                borderObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name + "-border", (int)(-depth / MASMonitor.depthDelta));
                borderObject.layer              = pageRoot.gameObject.layer;
                borderObject.transform.parent   = pageRoot;
                borderObject.transform.position = imageOrigin + new Vector3(position.x, -(position.y + size.y), 0.0f);

                borderMaterial             = new Material(MASLoader.shaders["MOARdV/Monitor"]);
                lineRenderer               = borderObject.AddComponent <LineRenderer>();
                lineRenderer.useWorldSpace = false;
                lineRenderer.material      = borderMaterial;
                lineRenderer.startColor    = borderColor;
                lineRenderer.endColor      = borderColor;
                lineRenderer.startWidth    = borderWidth;
                lineRenderer.endWidth      = borderWidth;

                Color32 namedColor;
                if (comp.TryGetNamedColor(borderColorName, out namedColor))
                {
                    borderColor             = namedColor;
                    lineRenderer.startColor = borderColor;
                    lineRenderer.endColor   = borderColor;
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(borderColorName);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("borderColor does not contain 3 or 4 values in VERTICAL_BAR " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], (double newValue) =>
                    {
                        borderColor.r           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = borderColor;
                        lineRenderer.endColor   = borderColor;
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], (double newValue) =>
                    {
                        borderColor.g           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = borderColor;
                        lineRenderer.endColor   = borderColor;
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], (double newValue) =>
                    {
                        borderColor.b           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = borderColor;
                        lineRenderer.endColor   = borderColor;
                    });

                    if (startColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], (double newValue) =>
                        {
                            borderColor.a           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.startColor = borderColor;
                            lineRenderer.endColor   = borderColor;
                        });
                    }
                }

                float     halfWidth    = borderWidth * 0.5f - 0.5f;
                Vector3[] borderPoints = new Vector3[]
                {
                    new Vector3(-halfWidth, -halfWidth, 0.0f),
                    new Vector3(size.x + halfWidth, -halfWidth, 0.0f),
                    new Vector3(size.x + halfWidth, size.y + halfWidth, 0.0f),
                    new Vector3(-halfWidth, size.y + halfWidth, 0.0f),
                    new Vector3(-halfWidth, -halfWidth, 0.0f)
                };
                lineRenderer.positionCount = 5;
                lineRenderer.SetPositions(borderPoints);
            }
            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = imageOrigin + new Vector3(position.x, -position.y, 0.0f);

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                throw new ArgumentException("Unable to find 'position' in VERTICAL_BAR " + name);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in VERTICAL_BAR " + name);
                }

                if (borderWidth > 0.0f)
                {
                    variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                    {
                        position.x = (float)newValue;
                        borderObject.transform.position = imageOrigin + new Vector3(position.x, -(position.y + size.y), 0.0f);
                        imageObject.transform.position  = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                    });

                    variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                    {
                        position.y = (float)newValue;
                        borderObject.transform.position = imageOrigin + new Vector3(position.x, -(position.y + size.y), 0.0f);
                        imageObject.transform.position  = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                    });
                }
                else
                {
                    variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                    {
                        position.x = (float)newValue;
                        imageObject.transform.position = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                    });

                    variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                    {
                        position.y = (float)newValue;
                        imageObject.transform.position = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                    });
                }
            }

            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer   = imageObject.AddComponent <MeshRenderer>();
            mesh           = new Mesh();
            vertices[0]    = new Vector3(0.0f, 0.0f, 0.0f);
            vertices[1]    = new Vector3(size.x, 0.0f, 0.0f);
            vertices[2]    = new Vector3(0.0f, -size.y, 0.0f);
            vertices[3]    = new Vector3(size.x, -size.y, 0.0f);
            mesh.vertices  = vertices;
            uv[0]          = new Vector2(0.0f, 1.0f);
            uv[1]          = Vector2.one;
            uv[2]          = Vector2.zero;
            uv[3]          = new Vector2(1.0f, 0.0f);
            mesh.uv        = uv;
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(false);
            meshFilter.mesh = mesh;
            imageMaterial   = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            if (mainTexture != null)
            {
                imageMaterial.mainTexture = mainTexture;
            }
            imageMaterial.SetColor(colorField, sourceColor);
            meshRenderer.material = imageMaterial;
            RenderPage(false);

            string sourceColorName = string.Empty;

            if (config.TryGetValue("sourceColor", ref sourceColorName))
            {
                Color32 namedColor;
                if (comp.TryGetNamedColor(sourceColorName, out namedColor))
                {
                    sourceColor = namedColor;
                    imageMaterial.SetColor(colorField, sourceColor);
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(sourceColorName);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("sourceColor does not contain 3 or 4 values in VERTICAL_BAR " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], (double newValue) =>
                    {
                        sourceColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        imageMaterial.SetColor(colorField, sourceColor);
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], (double newValue) =>
                    {
                        sourceColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        imageMaterial.SetColor(colorField, sourceColor);
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], (double newValue) =>
                    {
                        sourceColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        imageMaterial.SetColor(colorField, sourceColor);
                    });

                    if (startColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], (double newValue) =>
                        {
                            sourceColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            imageMaterial.SetColor(colorField, sourceColor);
                        });
                    }
                }
            }

            variableRegistrar.RegisterVariableChangeCallback(sourceName, SourceCallback);
            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                if (borderObject != null)
                {
                    borderObject.SetActive(false);
                }
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                if (borderObject != null)
                {
                    borderObject.SetActive(true);
                }
                imageObject.SetActive(true);
            }
        }
Exemple #8
0
        internal MASPageHorizon(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string textureName = string.Empty;

            if (!config.TryGetValue("texture", ref textureName))
            {
                throw new ArgumentException("Unable to find 'texture' in HORIZON " + name);
            }
            Texture2D mainTexture = GameDatabase.Instance.GetTexture(textureName, false);

            if (mainTexture == null)
            {
                throw new ArgumentException("Unable to find 'texture' " + textureName + " for HORIZON " + name);
            }
            mainTexture.wrapMode = TextureWrapMode.Clamp;

            Vector2 position = Vector2.zero;

            if (!config.TryGetValue("position", ref position))
            {
                throw new ArgumentException("Unable to find 'position' in HORIZON " + name);
            }

            Vector2 size = Vector2.zero;

            if (!config.TryGetValue("size", ref size))
            {
                throw new ArgumentException("Unable to find 'size' in HORIZON " + name);
            }

            string variableName = string.Empty;
            string pitchName    = string.Empty;
            string rollName     = string.Empty;

            if (!config.TryGetValue("pitch", ref pitchName))
            {
                throw new ArgumentException("Unable to find 'pitch' in HORIZON " + name);
            }

            string pitchRange = string.Empty;

            if (!config.TryGetValue("pitchRange", ref pitchRange))
            {
                throw new ArgumentException("Unable to find 'pitchRange' in HORIZON " + name);
            }
            string[] ranges = Utility.SplitVariableList(pitchRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'pitchRange' in HORIZON " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => pitchRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => pitchRange2 = (float)newValue);

            string displayPitchRange = string.Empty;

            if (!config.TryGetValue("displayPitchRange", ref displayPitchRange))
            {
                throw new ArgumentException("Unable to find 'displayPitchRange' in HORIZON " + name);
            }
            ranges = Utility.SplitVariableList(displayPitchRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'displayPitchRange' in HORIZON " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => displayPitchRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => displayPitchRange2 = (float)newValue);

            if (!config.TryGetValue("roll", ref rollName))
            {
                throw new ArgumentException("Unable to find 'roll' in HORIZON " + name);
            }

            string rollRange = string.Empty;

            if (!config.TryGetValue("rollRange", ref rollRange))
            {
                throw new ArgumentException("Unable to find 'rollRange' in HORIZON " + name);
            }
            ranges = Utility.SplitVariableList(rollRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'rollRange' in HORIZON " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => rollRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => rollRange2 = (float)newValue);

            string displayRollRange = string.Empty;

            if (!config.TryGetValue("displayRollRange", ref displayRollRange))
            {
                throw new ArgumentException("Unable to find 'displayRollRange' in HORIZON " + name);
            }
            ranges = Utility.SplitVariableList(displayRollRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'displayRollRange' in HORIZON " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => displayRollRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => displayRollRange2 = (float)newValue);

            texelSize = mainTexture.texelSize;

            // Infer the scaling of the source image to the display size, fixing
            // the width as 100% of the texel width of the source.
            float texelsPerPixel = (float)mainTexture.width / size.x;
            // Get the inverse aspect ratio of the display
            float   aspectRatio  = size.y / size.x;
            float   texelsHeight = aspectRatio * size.y * texelsPerPixel;
            Vector2 textureScale = new Vector2(1.0f, texelsHeight * texelSize.y);

            textureOffset = 0.5f * texelsHeight * texelSize.y;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            // Set up our display surface.
            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = pageRoot.position;
            imageObject.transform.Translate(position.x, -position.y, depth);

            // Determine the extents of the horizon in clip coordinates for
            // feeding the shader.
            Vector4 clipCoords = new Vector4(
                position.x - size.x * 0.5f, position.y - size.y * 0.5f,
                position.x + size.x * 0.5f, position.y + size.y * 0.5f
                );

            clipCoords.x /= monitor.screenSize.x * 0.5f;
            clipCoords.y /= monitor.screenSize.y * 0.5f;
            clipCoords.z /= monitor.screenSize.x * 0.5f;
            clipCoords.w /= monitor.screenSize.y * 0.5f;

            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer = imageObject.AddComponent <MeshRenderer>();
            Mesh mesh = new Mesh();

            mesh.vertices = new[]
            {
                new Vector3(-size.x * 0.75f, size.y * 0.75f, depth),
                new Vector3(size.x * 0.75f, size.y * 0.75f, depth),
                new Vector3(-size.x * 0.75f, -size.y * 0.75f, depth),
                new Vector3(size.x * 0.75f, -size.y * 0.75f, depth),
            };
            mesh.uv = new[]
            {
                new Vector2(-0.5f, 1.5f),
                new Vector2(1.5f, 1.5f),
                new Vector2(-0.5f, -0.5f),
                new Vector2(1.5f, -0.5f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(true);
            meshFilter.mesh = mesh;
            Shader imageShader = MASLoader.shaders["MOARdV/Monitor"];

            imageMaterial                  = new Material(imageShader);
            imageMaterial.mainTexture      = mainTexture;
            imageMaterial.mainTextureScale = textureScale;
            meshRenderer.material          = imageMaterial;
            imageMaterial.SetVector("_ClipCoords", clipCoords);
            RenderPage(false);

            variableRegistrar.RegisterVariableChangeCallback(pitchName, PitchCallback);
            variableRegistrar.RegisterVariableChangeCallback(rollName, RollCallback);
            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                imageObject.SetActive(true);
            }
        }
Exemple #9
0
        internal MASPage(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform rootTransform)
        {
            if (!config.TryGetValue("name", ref name))
            {
                throw new ArgumentException("Invalid or missing 'name' in MASPage");
            }
            variableRegistrar = new VariableRegistrar(comp, prop);

            string[] softkeys    = config.GetValues("softkey");
            int      numSoftkeys = softkeys.Length;

            for (int i = 0; i < numSoftkeys; ++i)
            {
                string[] pair = Utility.SplitVariableList(softkeys[i]);
                if (pair.Length == 2)
                {
                    int id;
                    if (int.TryParse(pair[0], out id))
                    {
                        Action action = comp.GetAction(pair[1], prop);
                        if (action != null)
                        {
                            softkeyAction[id] = action;
                        }
                    }
                }
            }

            ConfigNode[] hitboxes    = config.GetNodes("hitbox");
            int          numHitboxes = hitboxes.Length;

            for (int i = 0; i < numHitboxes; ++i)
            {
                HitBox hb = InitHitBox(i, hitboxes[i], prop, comp);
                if (hb != null)
                {
                    hitboxActions.Add(hb);
                }
            }

            string entryMethod = string.Empty;

            if (config.TryGetValue("onEntry", ref entryMethod))
            {
                onEntry = comp.GetAction(entryMethod, prop);
            }
            string exitMethod = string.Empty;

            if (config.TryGetValue("onExit", ref exitMethod))
            {
                onExit = comp.GetAction(exitMethod, prop);
            }

            pageRoot                  = new GameObject();
            pageRoot.name             = Utility.ComposeObjectName(this.GetType().Name, name, prop.propID);
            pageRoot.layer            = rootTransform.gameObject.layer;
            pageRoot.transform.parent = rootTransform;
            pageRoot.transform.Translate(0.0f, 0.0f, 1.0f);

            float depth = 0.0f;

            ConfigNode[] components    = config.GetNodes();
            int          numComponents = components.Length;

            if (Array.Exists(components, x => x.name == "SUB_PAGE"))
            {
                // Need to collate
                List <ConfigNode> newComponents = new List <ConfigNode>();

                for (int i = 0; i < numComponents; ++i)
                {
                    ConfigNode node = components[i];
                    if (node.name == "SUB_PAGE")
                    {
                        newComponents.AddRange(ResolveSubPage(node, monitor.fontSize));
                    }
                    else
                    {
                        newComponents.Add(node);
                    }
                }

                components    = newComponents.ToArray();
                numComponents = components.Length;
            }

            for (int i = 0; i < numComponents; ++i)
            {
                try
                {
                    var pageComponent = CreatePageComponent(components[i], prop, comp, monitor, pageRoot.transform, depth);
                    if (pageComponent != null)
                    {
                        component.Add(pageComponent);
                        depth -= MASMonitor.depthDelta;
                    }
                }
                catch (Exception e)
                {
                    string componentName = string.Empty;
                    if (!components[i].TryGetValue("name", ref componentName))
                    {
                        componentName = "anonymous";
                    }

                    string error = string.Format("Error configuring MASPage " + name + " " + config.name + " " + componentName + ":");
                    Utility.LogError(this, error);
                    Utility.LogError(this, "{0}", e.ToString());
                    Utility.ComplainLoudly(error);
                }
            }

            if (numComponents > 256)
            {
                Utility.LogWarning(this, "{0} elements were used in MASPage {1}. This may exceed the number of supported elements.", numComponents, name);
            }
        }
        internal MASPageGroundTrack(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            this.comp = comp;

            if (!config.TryGetValue("vertexCount", ref vertexCount))
            {
                throw new ArgumentException("Unable to find 'vertexCount' in GROUND_TRACK " + name);
            }
            if (vertexCount < 2)
            {
                throw new ArgumentException("'vertexCount' needs to be at least 2 in GROUND_TRACK " + name);
            }
            vesselVertex1   = new Vector3[vertexCount];
            vesselVertex2   = new Vector3[vertexCount];
            targetVertex1   = new Vector3[vertexCount];
            targetVertex2   = new Vector3[vertexCount];
            maneuverVertex1 = new Vector3[vertexCount];
            maneuverVertex2 = new Vector3[vertexCount];
            positions       = new Vector3d[vertexCount];

            float width = 0.0f;

            if (!config.TryGetValue("size", ref width))
            {
                throw new ArgumentException("Unable to find 'size' in GROUND_TRACK " + name);
            }
            size.x = width; size.y = width * 0.5f;

            float lineWidth = 1.0f;

            if (!config.TryGetValue("lineWidth", ref lineWidth))
            {
                throw new ArgumentException("Unable to find 'lineWidth' in GROUND_TRACK " + name);
            }

            componentOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            for (int i = 0; i < numObjects; ++i)
            {
                lineOrigin[i] = new GameObject();
                lineOrigin[i].transform.parent   = pageRoot;
                lineOrigin[i].transform.position = pageRoot.position;
                lineOrigin[i].transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth);
                lineOrigin[i].name  = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name + "-" + i.ToString(), (int)(-depth / MASMonitor.depthDelta));
                lineOrigin[i].layer = pageRoot.gameObject.layer;

                lineMaterial[i] = new Material(MASLoader.shaders["MOARdV/Monitor"]);
                lineRenderer[i] = lineOrigin[i].AddComponent <LineRenderer>();
                lineRenderer[i].useWorldSpace = false;
                lineRenderer[i].material      = lineMaterial[i];
                lineRenderer[i].startWidth    = lineWidth;
                lineRenderer[i].endWidth      = lineWidth;
                lineRenderer[i].positionCount = vertexCount;
                lineRenderer[i].enabled       = false;
            }
            lineRenderer[0].SetPositions(vesselVertex1);
            lineRenderer[1].SetPositions(vesselVertex2);
            lineRenderer[2].SetPositions(targetVertex1);
            lineRenderer[3].SetPositions(targetVertex2);
            lineRenderer[4].SetPositions(maneuverVertex1);
            lineRenderer[5].SetPositions(maneuverVertex2);

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                position = Vector2.zero;
                throw new ArgumentException("Unable to find 'position' in GROUND_TRACK " + name);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in GROUND_TRACK " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                {
                    position.x = (float)newValue;
                    UpdateComponentPositions();
                });

                variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                {
                    position.y = (float)newValue;
                    UpdateComponentPositions();
                });
            }

            string vesselColorString = string.Empty;

            if (config.TryGetValue("vesselColor", ref vesselColorString))
            {
                Color32 color;
                if (comp.TryGetNamedColor(vesselColorString, out color))
                {
                    vesselColor = color;
                    lineRenderer[0].startColor = vesselColor;
                    lineRenderer[0].endColor   = vesselColor;
                    lineRenderer[1].startColor = vesselColor;
                    lineRenderer[1].endColor   = vesselColor;
                }
                else
                {
                    string[] vesselColors = Utility.SplitVariableList(vesselColorString);
                    if (vesselColors.Length < 3 || vesselColors.Length > 4)
                    {
                        throw new ArgumentException("vesselColor does not contain 3 or 4 values in GROUND_TRACK " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(vesselColors[0], (double newValue) =>
                    {
                        vesselColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[0].startColor = vesselColor;
                        lineRenderer[0].endColor   = vesselColor;
                        lineRenderer[1].startColor = vesselColor;
                        lineRenderer[1].endColor   = vesselColor;
                    });
                    variableRegistrar.RegisterVariableChangeCallback(vesselColors[1], (double newValue) =>
                    {
                        vesselColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[0].startColor = vesselColor;
                        lineRenderer[0].endColor   = vesselColor;
                        lineRenderer[1].startColor = vesselColor;
                        lineRenderer[1].endColor   = vesselColor;
                    });
                    variableRegistrar.RegisterVariableChangeCallback(vesselColors[2], (double newValue) =>
                    {
                        vesselColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[0].startColor = vesselColor;
                        lineRenderer[0].endColor   = vesselColor;
                        lineRenderer[1].startColor = vesselColor;
                        lineRenderer[1].endColor   = vesselColor;
                    });

                    if (vesselColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(vesselColors[3], (double newValue) =>
                        {
                            vesselColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer[0].startColor = vesselColor;
                            lineRenderer[0].endColor   = vesselColor;
                            lineRenderer[1].startColor = vesselColor;
                            lineRenderer[1].endColor   = vesselColor;
                        });
                    }
                }

                updateVessel = true;
            }
            else
            {
                lineOrigin[0].SetActive(false);
                lineOrigin[1].SetActive(false);
                updateVessel = false;
            }

            string maneuverColorString = string.Empty;

            if (config.TryGetValue("maneuverColor", ref maneuverColorString))
            {
                Color32 color;
                if (comp.TryGetNamedColor(maneuverColorString, out color))
                {
                    maneuverColor = color;
                    lineRenderer[4].startColor = maneuverColor;
                    lineRenderer[4].endColor   = maneuverColor;
                    lineRenderer[5].startColor = maneuverColor;
                    lineRenderer[5].endColor   = maneuverColor;
                }
                else
                {
                    string[] maneuverColors = Utility.SplitVariableList(maneuverColorString);
                    if (maneuverColors.Length < 3 || maneuverColors.Length > 4)
                    {
                        throw new ArgumentException("maneuverColor does not contain 3 or 4 values in GROUND_TRACK " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(maneuverColors[0], (double newValue) =>
                    {
                        maneuverColor.r            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[4].startColor = maneuverColor;
                        lineRenderer[4].endColor   = maneuverColor;
                        lineRenderer[5].startColor = maneuverColor;
                        lineRenderer[5].endColor   = maneuverColor;
                    });
                    variableRegistrar.RegisterVariableChangeCallback(maneuverColors[1], (double newValue) =>
                    {
                        maneuverColor.g            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[4].startColor = maneuverColor;
                        lineRenderer[4].endColor   = maneuverColor;
                        lineRenderer[5].startColor = maneuverColor;
                        lineRenderer[5].endColor   = maneuverColor;
                    });
                    variableRegistrar.RegisterVariableChangeCallback(maneuverColors[2], (double newValue) =>
                    {
                        maneuverColor.b            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[4].startColor = maneuverColor;
                        lineRenderer[4].endColor   = maneuverColor;
                        lineRenderer[5].startColor = maneuverColor;
                        lineRenderer[5].endColor   = maneuverColor;
                    });

                    if (maneuverColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(maneuverColors[3], (double newValue) =>
                        {
                            maneuverColor.a            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer[4].startColor = maneuverColor;
                            lineRenderer[4].endColor   = maneuverColor;
                            lineRenderer[5].startColor = maneuverColor;
                            lineRenderer[5].endColor   = maneuverColor;
                        });
                    }
                }

                updateManeuver = true;
            }
            else
            {
                lineOrigin[4].SetActive(false);
                lineOrigin[5].SetActive(false);
                updateManeuver = false;
            }

            string targetColorString = string.Empty;

            if (config.TryGetValue("targetColor", ref targetColorString))
            {
                Color32 color;
                if (comp.TryGetNamedColor(targetColorString, out color))
                {
                    targetColor = color;
                    lineRenderer[2].startColor = targetColor;
                    lineRenderer[2].endColor   = targetColor;
                    lineRenderer[3].startColor = targetColor;
                    lineRenderer[3].endColor   = targetColor;
                }
                else
                {
                    string[] targetColors = Utility.SplitVariableList(targetColorString);
                    if (targetColors.Length < 3 || targetColors.Length > 4)
                    {
                        throw new ArgumentException("targetColor does not contain 3 or 4 values in GROUND_TRACK " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(targetColors[0], (double newValue) =>
                    {
                        targetColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[2].startColor = targetColor;
                        lineRenderer[2].endColor   = targetColor;
                        lineRenderer[3].startColor = targetColor;
                        lineRenderer[3].endColor   = targetColor;
                    });
                    variableRegistrar.RegisterVariableChangeCallback(targetColors[1], (double newValue) =>
                    {
                        targetColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[2].startColor = targetColor;
                        lineRenderer[2].endColor   = targetColor;
                        lineRenderer[3].startColor = targetColor;
                        lineRenderer[3].endColor   = targetColor;
                    });
                    variableRegistrar.RegisterVariableChangeCallback(targetColors[2], (double newValue) =>
                    {
                        targetColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer[2].startColor = targetColor;
                        lineRenderer[2].endColor   = targetColor;
                        lineRenderer[3].startColor = targetColor;
                        lineRenderer[3].endColor   = targetColor;
                    });

                    if (targetColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(targetColors[3], (double newValue) =>
                        {
                            targetColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer[2].startColor = targetColor;
                            lineRenderer[2].endColor   = targetColor;
                            lineRenderer[3].startColor = targetColor;
                            lineRenderer[3].endColor   = targetColor;
                        });
                    }
                }

                updateTarget = true;
            }
            else
            {
                lineOrigin[2].SetActive(false);
                lineOrigin[3].SetActive(false);
                updateTarget = false;
            }

            string startLongitudeString = string.Empty;

            if (!config.TryGetValue("startLongitude", ref startLongitudeString))
            {
                startLongitude           = -180.0f;
                startLongitudeNormalized = startLongitude / 360.0f;
            }
            else
            {
                variableRegistrar.RegisterVariableChangeCallback(startLongitudeString, (double newValue) =>
                {
                    float longitude = (float)Utility.NormalizeLongitude(newValue);
                    if (!Mathf.Approximately(longitude, startLongitude))
                    {
                        startLongitude           = longitude;
                        startLongitudeNormalized = startLongitude / 360.0f;
                    }
                });
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                // Disable the mesh if we're in variable mode
                SetAllActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, (double newValue) =>
                {
                    if (EvaluateVariable(newValue))
                    {
                        SetAllActive(currentState);
                    }
                });
            }
            else
            {
                currentState = true;
                SetAllActive(true);
            }

            comp.StartCoroutine(LineUpdateCoroutine());
        }
Exemple #11
0
        internal MASPageHorizontalStrip(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string textureName = string.Empty;

            if (!config.TryGetValue("texture", ref textureName))
            {
                throw new ArgumentException("Unable to find 'texture' in HORIZONTAL_STRIP " + name);
            }
            Texture2D mainTexture = GameDatabase.Instance.GetTexture(textureName, false);

            if (mainTexture == null)
            {
                throw new ArgumentException("Unable to find 'texture' " + textureName + " for HORIZONTAL_STRIP " + name);
            }
            bool wrapMode = false;

            if (!config.TryGetValue("wrap", ref wrapMode))
            {
                wrapMode = false;
            }
            mainTexture.wrapMode = (wrapMode) ? TextureWrapMode.Repeat : TextureWrapMode.Clamp;

            Vector2 size = Vector2.zero;

            if (!config.TryGetValue("size", ref size))
            {
                throw new ArgumentException("Unable to find 'size' in HORIZONTAL_STRIP " + name);
            }

            string variableName = string.Empty;
            string inputName    = string.Empty;

            if (!config.TryGetValue("input", ref inputName))
            {
                throw new ArgumentException("Unable to find 'input' in HORIZONTAL_STRIP " + name);
            }

            string inputRange = string.Empty;

            if (!config.TryGetValue("inputRange", ref inputRange))
            {
                throw new ArgumentException("Unable to find 'inputRange' in HORIZONTAL_STRIP " + name);
            }
            string[] ranges = Utility.SplitVariableList(inputRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'inputRange' in HORIZONTAL_STRIP " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => inputRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => inputRange2 = (float)newValue);

            string displayRange = string.Empty;

            if (!config.TryGetValue("displayRange", ref displayRange))
            {
                throw new ArgumentException("Unable to find 'displayRange' in HORIZONTAL_STRIP " + name);
            }
            ranges = Utility.SplitVariableList(displayRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'displayRange' in HORIZONTAL_STRIP " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => displayRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => displayRange2 = (float)newValue);

            float displayWidth = 0.0f;

            if (!config.TryGetValue("displayWidth", ref displayWidth))
            {
                throw new ArgumentException("Unable to find 'displayWidth' in HORIZONTAL_STRIP " + name);
            }
            texelWidth = mainTexture.texelSize.x;
            float textureSpan = displayWidth * texelWidth;

            textureOffset = textureSpan * -0.5f;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            componentOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            // Set up our display surface.
            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = pageRoot.position;
            imageObject.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth);
            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer = imageObject.AddComponent <MeshRenderer>();
            Mesh mesh = new Mesh();

            mesh.vertices = new[]
            {
                new Vector3(0.0f, 0.0f, 0.0f),
                new Vector3(size.x, 0.0f, 0.0f),
                new Vector3(0.0f, -size.y, 0.0f),
                new Vector3(size.x, -size.y, 0.0f),
            };
            mesh.uv = new[]
            {
                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(true);
            meshFilter.mesh                = mesh;
            imageMaterial                  = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            imageMaterial.mainTexture      = mainTexture;
            imageMaterial.mainTextureScale = new Vector2(textureSpan, 1.0f);
            meshRenderer.material          = imageMaterial;
            RenderPage(false);

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                throw new ArgumentException("Unable to find 'position' in HORIZONTAL_STRIP " + name);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in HORIZONTAL_STRIP " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                {
                    position.x = (float)newValue;
                    imageObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                {
                    position.y = (float)newValue;
                    imageObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                });
            }

            variableRegistrar.RegisterVariableChangeCallback(inputName, InputCallback);
            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                imageObject.SetActive(true);
            }
        }
Exemple #12
0
        internal MASPageRollingDigit(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string localFonts = string.Empty;

            if (!config.TryGetValue("font", ref localFonts))
            {
                localFonts = string.Empty;
            }

            string styleStr = string.Empty;

            style = FontStyle.Normal;
            if (config.TryGetValue("style", ref styleStr))
            {
                style = MdVTextMesh.FontStyle(styleStr);
            }
            else
            {
                style = monitor.defaultStyle;
            }

            Vector2 fontDimensions = Vector2.zero;

            if (!config.TryGetValue("fontSize", ref fontDimensions) || fontDimensions.x < 0.0f || fontDimensions.y < 0.0f)
            {
                fontDimensions = monitor.fontSize;
            }

            Color32 textColor;
            string  textColorStr = string.Empty;

            if (!config.TryGetValue("textColor", ref textColorStr) || string.IsNullOrEmpty(textColorStr))
            {
                textColor = monitor.textColor_;
            }
            else
            {
                textColor = Utility.ParseColor32(textColorStr, comp);
            }

            // Position is based on default font size
            Vector2 fontScale = monitor.fontSize;

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            if (string.IsNullOrEmpty(localFonts))
            {
                font = monitor.defaultFont;
            }
            else
            {
                font = MASLoader.GetFont(localFonts.Trim());
            }

            // Set up our text.
            imageOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            meshObject                    = new GameObject();
            meshObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            meshObject.layer              = pageRoot.gameObject.layer;
            meshObject.transform.parent   = pageRoot;
            meshObject.transform.position = imageOrigin;

            meshFilter                        = meshObject.AddComponent <MeshFilter>();
            meshRenderer                      = meshObject.AddComponent <MeshRenderer>();
            meshRenderer.material             = new Material(MASLoader.shaders["MOARdV/TextMonitor"]);
            meshRenderer.material.mainTexture = font.material.mainTexture;

            string positionString = string.Empty;

            if (config.TryGetValue("position", ref positionString))
            {
                string[] positions = Utility.SplitVariableList(positionString);
                if (positions.Length != 2)
                {
                    throw new ArgumentException("position does not contain 2 values in ROLLING_DIGIT " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(positions[0], (double newValue) =>
                {
                    position.x = (float)newValue * fontScale.x;
                    meshObject.transform.position = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(positions[1], (double newValue) =>
                {
                    position.y = (float)newValue * fontScale.y;
                    meshObject.transform.position = imageOrigin + new Vector3(position.x, -position.y, 0.0f);
                });
            }

            int maxDigits = 0;

            if (!config.TryGetValue("maxDigits", ref maxDigits))
            {
                throw new ArgumentException("'maxDigits' missing in ROLLING_DIGIT " + name);
            }

            if (!config.TryGetValue("numRolling", ref numRolling))
            {
                throw new ArgumentException("'numRolling' missing in ROLLING_DIGIT " + name);
            }
            if (numRolling < 1)
            {
                throw new ArgumentException("numRolling must be greater than zero in ROLLING_DIGIT " + name);
            }
            valueScalar = Mathf.Pow(10.0f, numRolling);
            numDigits   = maxDigits - numRolling;
            if (numDigits < 0)
            {
                throw new ArgumentException("'numRolling' must be less than 'maxDigits' in ROLLING_DIGIT " + name);
            }
            scrollingVerticesOffset = 4 * numDigits;

            upperLimit = Mathf.Pow(10.0f, maxDigits) - 1.0f;
            lowerLimit = -Mathf.Pow(10.0f, maxDigits - 1) + 1.0f;

            bool padZero = false;

            if (!config.TryGetValue("padZero", ref padZero))
            {
                padZero = false;
            }

            int numVertices = 4 * numDigits + 12 * numRolling;
            int numIndices  = 6 * numDigits + 18 * numRolling;

            vertices  = new Vector3[numVertices];
            colors32  = new Color32[numVertices];
            tangents  = new Vector4[numVertices];
            uv        = new Vector2[numVertices];
            triangles = new int[numIndices];
            // These values are invariant:
            Vector4 tangent = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);

            for (int i = 0; i < numVertices; ++i)
            {
                colors32[i] = textColor;
                tangents[i] = tangent;
            }
            for (int i = 0; i < numIndices / 6; ++i)
            {
                triangles[i * 6 + 0] = i * 4 + 0;
                triangles[i * 6 + 1] = i * 4 + 3;
                triangles[i * 6 + 2] = i * 4 + 2;
                triangles[i * 6 + 3] = i * 4 + 0;
                triangles[i * 6 + 4] = i * 4 + 1;
                triangles[i * 6 + 5] = i * 4 + 3;
            }

            if (numDigits > 0)
            {
                StringBuilder sb = StringBuilderCache.Acquire();
                sb.AppendFormat("{{0,{0}:0", numDigits);
                if (padZero)
                {
                    sb.Append('0', numDigits - 1);
                }
                sb.Append("}");
                digitsFormat = sb.ToStringAndRelease();
            }

            string valueString = string.Empty;

            if (!config.TryGetValue("value", ref valueString))
            {
                throw new ArgumentException("'value' missing in ROLLING_DIGIT " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(valueString, ValueCallback);

            RenderPage(false);

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                meshObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                currentState = true;
            }

            dynamic = font.dynamic;

            float characterScalar;

            if (dynamic)
            {
                characterScalar = fontDimensions.y / (float)font.lineHeight;
                this.fontSize   = font.fontSize;
            }
            else
            {
                // Unfortunately, there doesn't seem to be a way to set the font metrics when
                // creating a bitmap font, so I have to play games here by fetching the values
                // I stored in the character info.
                CharacterInfo ci = font.characterInfo[0];
                characterScalar = fontDimensions.y / (float)ci.glyphHeight;
                this.fontSize   = ci.glyphHeight;
            }

            this.fixedAdvance     = (int)fontDimensions.x;
            this.fixedLineSpacing = Mathf.Floor(fontDimensions.y);
            this.characterScalar  = characterScalar;
            ascent    = (dynamic) ? font.ascent : (int)(0.8125f * fixedLineSpacing);
            yMaxLimit = 0.5f * fixedLineSpacing;
            yMinLimit = -1.5f * fixedLineSpacing;

            Font.textureRebuilt += FontRebuiltCallback;
            font.RequestCharactersInTexture(charactersUsed, fontSize, style);

            digitsChanged   = true;
            fractionChanged = true;
        }
        internal MASPageMenu(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            this.prop = prop;
            this.comp = comp;

            if (!config.TryGetValue("maxLines", ref maxLines))
            {
                maxLines = int.MaxValue;
            }
            if (maxLines < 1)
            {
                throw new ArgumentException("'maxLines' must be greater than zero in MENU " + name);
            }

            int itemPositionShift = 0;

            if (!config.TryGetValue("itemPositionShift", ref itemPositionShift))
            {
                itemPositionShift = 0;
            }

            if (!config.TryGetValue("cursorPersistentName", ref cursorPersistentName))
            {
                throw new ArgumentException("Missing 'cursorPersistentName' in MENU " + name);
            }

            config.TryGetValue("upSoftkey", ref upSoftkey);
            config.TryGetValue("downSoftkey", ref downSoftkey);
            config.TryGetValue("enterSoftkey", ref enterSoftkey);
            config.TryGetValue("homeSoftkey", ref homeSoftkey);
            config.TryGetValue("endSoftkey", ref endSoftkey);

            string localFonts = string.Empty;

            if (!config.TryGetValue("font", ref localFonts))
            {
                localFonts = string.Empty;
            }

            string styleStr = string.Empty;

            style = FontStyle.Normal;
            if (config.TryGetValue("style", ref styleStr))
            {
                style = MdVTextMesh.FontStyle(styleStr);
            }
            else
            {
                style = monitor.defaultStyle;
            }

            fontSize = Vector2.zero;
            if (!config.TryGetValue("fontSize", ref fontSize) || fontSize.x < 0.0f || fontSize.y < 0.0f)
            {
                fontSize = monitor.fontSize;
            }

            charAdvance = fontSize.x * itemPositionShift;
            lineAdvance = fontSize.y;

            defaultColor = monitor.textColor_;

            Color32 cursorColor;
            string  cursorColorStr = string.Empty;

            if (!config.TryGetValue("cursorColor", ref cursorColorStr) || string.IsNullOrEmpty(cursorColorStr))
            {
                cursorColor = monitor.textColor_;
            }
            else
            {
                cursorColor = Utility.ParseColor32(cursorColorStr, comp);
            }

            // Set up our text.
            textOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            rootObject                    = new GameObject();
            rootObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            rootObject.layer              = pageRoot.gameObject.layer;
            rootObject.transform.parent   = pageRoot;
            rootObject.transform.position = textOrigin;

            string positionString = string.Empty;

            if (config.TryGetValue("position", ref positionString))
            {
                string[] positions = Utility.SplitVariableList(positionString);
                if (positions.Length != 2)
                {
                    throw new ArgumentException("position does not contain 2 values in MENU " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(positions[0], (double newValue) =>
                {
                    position.x = (float)newValue * monitor.fontSize.x;
                    rootObject.transform.position = textOrigin + new Vector3(position.x, -position.y, 0.0f);
                    updateMenu = true;
                });

                variableRegistrar.RegisterVariableChangeCallback(positions[1], (double newValue) =>
                {
                    position.y = (float)newValue * monitor.fontSize.y;
                    rootObject.transform.position = textOrigin + new Vector3(position.x, -position.y, 0.0f);
                    updateMenu = true;
                });
            }

            if (string.IsNullOrEmpty(localFonts))
            {
                font = monitor.defaultFont;
            }
            else
            {
                font = MASLoader.GetFont(localFonts.Trim());
            }

            cursorObject                    = new GameObject();
            cursorObject.name               = rootObject.name + "_cursor";
            cursorObject.layer              = rootObject.layer;
            cursorObject.transform.parent   = rootObject.transform;
            cursorObject.transform.position = textOrigin;

            cursorText          = cursorObject.AddComponent <MdVTextMesh>();
            cursorText.material = new Material(MASLoader.shaders["MOARdV/TextMonitor"]);
            cursorText.SetFont(font, fontSize);
            cursorText.SetColor(cursorColor);
            cursorText.material.SetFloat(Shader.PropertyToID("_EmissiveFactor"), 1.0f);
            cursorText.fontStyle = style;

            string cursorPrompt = string.Empty;

            config.TryGetValue("cursor", ref cursorPrompt);
            // text, immutable, preserveWhitespace, comp, prop
            cursorText.SetText(cursorPrompt, false, true, comp, prop);

            string itemCountStr = string.Empty;

            config.TryGetValue("itemCount", ref itemCountStr);

            List <MenuItem> itemNodes = new List <MenuItem>();

            ConfigNode[] menuItemConfigNodes = config.GetNodes("ITEM");
            foreach (ConfigNode itemNode in menuItemConfigNodes)
            {
                try
                {
                    MenuItem cpt = new MenuItem(itemNode, rootObject, font, fontSize, style, defaultColor, comp, prop, variableRegistrar, itemNodes.Count);
                    itemNodes.Add(cpt);
                }
                catch (Exception e)
                {
                    Utility.LogError(this, "Exception creating ITEM in MENU " + name);
                    Utility.LogError(this, e.ToString());
                }
            }
            if (itemNodes.Count == 0)
            {
                throw new ArgumentException("No valid ITEM nodes in MENU " + name);
            }
            menuItems = itemNodes.ToArray();
            if (string.IsNullOrEmpty(itemCountStr))
            {
                numMenuItems = menuItems.Length;

                softkeyUpAction   = comp.GetAction(string.Format("fc.AddPersistentWrapped(\"{0}\", -1, 0, {1})", cursorPersistentName, numMenuItems), prop);
                softkeyDownAction = comp.GetAction(string.Format("fc.AddPersistentWrapped(\"{0}\", 1, 0, {1})", cursorPersistentName, numMenuItems), prop);
                softkeyEndAction  = comp.GetAction(string.Format("fc.SetPersistent(\"{0}\", {1})", cursorPersistentName, numMenuItems - 1), prop);
            }
            else if (itemNodes.Count > 1)
            {
                throw new ArgumentException("Only one valid ITEM node may be used in dynamic MENU " + name);
            }
            else
            {
                dynamicMenuTemplate = menuItemConfigNodes[0].CreateCopy();
            }

            variableRegistrar.RegisterVariableChangeCallback(string.Format("fc.GetPersistentAsNumber(\"{0}\")", cursorPersistentName), CursorMovedCallback);
            softkeyHomeAction = comp.GetAction(string.Format("fc.SetPersistent(\"{0}\", 0)", cursorPersistentName), prop);

            if (!string.IsNullOrEmpty(itemCountStr))
            {
                variableRegistrar.RegisterVariableChangeCallback(itemCountStr, MenuCountCallback);
            }

            string masterVariableName = string.Empty;

            if (config.TryGetValue("variable", ref masterVariableName))
            {
                rootObject.SetActive(false);

                variableRegistrar.RegisterVariableChangeCallback(masterVariableName, VariableCallback);
            }
            else
            {
                currentState = true;
                rootObject.SetActive(true);
            }

            RenderPage(false);
        }
Exemple #14
0
        internal MASPageViewport(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            screenSize = monitor.screenSize;

            // Set up our surface.
            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = pageRoot.position;
            imageObject.transform.Translate(monitor.screenSize.x * -0.5f, monitor.screenSize.y * -0.5f, depth);

            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer  = imageObject.AddComponent <MeshRenderer>();
            mesh          = new Mesh();
            mesh.vertices = new[]
            {
                // LEFT
                new Vector3(-1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(64.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(-1.0f, -1.0f, 0.0f),
                new Vector3(64.0f, -1.0f, 0.0f),

                // RIGHT
                new Vector3(394.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(394.0f, -1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, -1.0f, 0.0f),

                // BOTTOM - note that Y increases from the bottom
                new Vector3(-1.0f, screenSize.y - 32.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y - 32.0f, 0.0f),
                new Vector3(-1.0f, -1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, -1.0f, 0.0f),

                // TOP - note that Y increases from the bottom
                new Vector3(-1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(-1.0f, screenSize.y - 256.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y - 256.0f, 0.0f),
            };
            mesh.uv = new[]
            {
                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),

                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),

                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),

                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2,

                4, 5, 6,
                5, 7, 6,

                8, 9, 10,
                9, 11, 10,

                12, 13, 14,
                13, 15, 14
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(false);
            meshFilter.mesh = mesh;

            imageMaterial         = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            imageMaterial.color   = materialColor;
            meshRenderer.material = imageMaterial;
            RenderPage(false);

            string upperLeftCornerName = string.Empty;

            if (!config.TryGetValue("upperLeftCorner", ref upperLeftCornerName))
            {
                throw new ArgumentException("Unable to find 'upperLeftCorner' in VIEWPORT " + name);
            }

            string[] cornerVars = Utility.SplitVariableList(upperLeftCornerName);
            if (cornerVars.Length != 2)
            {
                throw new ArgumentException("Incorrect number of entries in 'upperLeftCorner' in VIEWPORT " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[0], UpdateLeft);
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[1], UpdateTop);

            string lowerRightCornerName = string.Empty;

            if (!config.TryGetValue("lowerRightCorner", ref lowerRightCornerName))
            {
                throw new ArgumentException("Unable to find 'lowerRightCorner' in VIEWPORT " + name);
            }
            cornerVars = Utility.SplitVariableList(lowerRightCornerName);
            if (cornerVars.Length != 2)
            {
                throw new ArgumentException("Incorrect number of entries in 'lowerRightCorner' in VIEWPORT " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[0], UpdateRight);
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[1], UpdateBottom);

            string colorString = string.Empty;

            if (config.TryGetValue("color", ref colorString))
            {
                string[] startColors = Utility.SplitVariableList(colorString);
                if (startColors.Length < 3 || startColors.Length > 4)
                {
                    throw new ArgumentException("color does not contain 3 or 4 values in VIEWPORT " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(startColors[0], (double newValue) =>
                {
                    materialColor.r     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    imageMaterial.color = materialColor;
                });

                variableRegistrar.RegisterVariableChangeCallback(startColors[1], (double newValue) =>
                {
                    materialColor.g     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    imageMaterial.color = materialColor;
                });

                variableRegistrar.RegisterVariableChangeCallback(startColors[2], (double newValue) =>
                {
                    materialColor.b     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    imageMaterial.color = materialColor;
                });

                if (startColors.Length == 4)
                {
                    variableRegistrar.RegisterVariableChangeCallback(startColors[3], (double newValue) =>
                    {
                        materialColor.a     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        imageMaterial.color = materialColor;
                    });
                }
            }


            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                imageObject.SetActive(true);
            }
        }
        internal MASPageLineString(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string startColorString = string.Empty;

            if (!config.TryGetValue("startColor", ref startColorString))
            {
                throw new ArgumentException("Unable to find 'startColor' in LINE_STRING " + name);
            }
            string endColorString = string.Empty;

            if (!config.TryGetValue("endColor", ref endColorString))
            {
                endColorString = string.Empty;
            }

            string startWidthString = string.Empty;

            if (!config.TryGetValue("startWidth", ref startWidthString))
            {
                throw new ArgumentException("Unable to find 'startWidth' in LINE_STRING " + name);
            }
            string endWidthString = string.Empty;

            if (!config.TryGetValue("endWidth", ref endWidthString))
            {
                endWidthString = string.Empty;
            }

            string[] vertexStrings = config.GetValues("vertex");

            if (vertexStrings.Length < 2)
            {
                throw new ArgumentException("Insufficient number of 'vertex' entries in LINE_STRING " + name + " (must have at least 2)");
            }


            Vector2 position = Vector2.zero;

            if (!config.TryGetValue("position", ref position))
            {
                throw new ArgumentException("Unable to find 'position' in LINE_STRING " + name);
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            string rotationVariableName = string.Empty;

            config.TryGetValue("rotation", ref rotationVariableName);

            bool loop = false;

            config.TryGetValue("loop", ref loop);

            lineOrigin                    = new GameObject();
            lineOrigin.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            lineOrigin.layer              = pageRoot.gameObject.layer;
            lineOrigin.transform.parent   = pageRoot;
            lineOrigin.transform.position = pageRoot.position;
            lineOrigin.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth);
            // add renderer stuff
            lineMaterial = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            lineRenderer = lineOrigin.AddComponent <LineRenderer>();
            lineRenderer.useWorldSpace = false;
            lineRenderer.material      = lineMaterial;
            lineRenderer.startColor    = startColor;
            lineRenderer.endColor      = endColor;
            lineRenderer.startWidth    = startWidth;
            lineRenderer.endWidth      = endWidth;
            lineRenderer.loop          = loop;

            int numVertices = vertexStrings.Length;

            lineRenderer.positionCount = numVertices;
            vertices = new Vector3[numVertices];

            string textureName = string.Empty;

            if (config.TryGetValue("texture", ref textureName))
            {
                Texture tex = GameDatabase.Instance.GetTexture(textureName, false);
                if (tex != null)
                {
                    lineMaterial.mainTexture = tex;
                    inverseTextureWidth      = 1.0f / (float)tex.width;
                    usesTexture = true;
                }
            }

            for (int i = 0; i < numVertices; ++i)
            {
                // Need to make a copy of the value for the lambda capture,
                // otherwise we'll try using i = numVertices in the callbacks.
                int index = i;
                vertices[i] = Vector3.zero;

                string[] vtx = Utility.SplitVariableList(vertexStrings[i]);
                if (vtx.Length != 2)
                {
                    throw new ArgumentException("vertex " + (i + 1).ToString() + " does not contain two value in LINE_STRING " + name);
                }

                Action <double> vertexX = (double newValue) =>
                {
                    vertices[index].x = (float)newValue;
                    lineRenderer.SetPosition(index, vertices[index]);
                    if (usesTexture)
                    {
                        RecalculateTextureScale();
                    }
                };
                variableRegistrar.RegisterVariableChangeCallback(vtx[0], vertexX);

                Action <double> vertexY = (double newValue) =>
                {
                    // Invert the value, since we stipulate +y is down on the monitor.
                    vertices[index].y = -(float)newValue;
                    lineRenderer.SetPosition(index, vertices[index]);
                    if (usesTexture)
                    {
                        RecalculateTextureScale();
                    }
                };
                variableRegistrar.RegisterVariableChangeCallback(vtx[1], vertexY);
            }
            lineRenderer.SetPositions(vertices);
            RenderPage(false);

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the lines if we're in variable mode
                lineOrigin.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                lineOrigin.SetActive(true);
            }

            if (!string.IsNullOrEmpty(rotationVariableName))
            {
                variableRegistrar.RegisterVariableChangeCallback(rotationVariableName, RotationCallback);
            }

            if (string.IsNullOrEmpty(endColorString))
            {
                Color32 col;
                if (comp.TryGetNamedColor(startColorString, out col))
                {
                    startColor = col;
                    endColor   = col;
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(startColorString);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("startColor does not contain 3 or 4 values in LINE_STRING " + name);
                    }

                    Action <double> startColorR = (double newValue) =>
                    {
                        startColor.r            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                        lineRenderer.endColor   = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], startColorR);

                    Action <double> startColorG = (double newValue) =>
                    {
                        startColor.g            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                        lineRenderer.endColor   = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], startColorG);

                    Action <double> startColorB = (double newValue) =>
                    {
                        startColor.b            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                        lineRenderer.endColor   = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], startColorB);

                    if (startColors.Length == 4)
                    {
                        Action <double> startColorA = (double newValue) =>
                        {
                            startColor.a            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.startColor = startColor;
                            lineRenderer.endColor   = startColor;
                        };
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], startColorA);
                    }
                }

                lineRenderer.startColor = startColor;
                lineRenderer.endColor   = startColor;
            }
            else
            {
                Color32 col;
                if (comp.TryGetNamedColor(startColorString, out col))
                {
                    startColor = col;
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(startColorString);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("startColor does not contain 3 or 4 values in LINE_STRING " + name);
                    }

                    Action <double> startColorR = (double newValue) =>
                    {
                        startColor.r            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], startColorR);

                    Action <double> startColorG = (double newValue) =>
                    {
                        startColor.g            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], startColorG);

                    Action <double> startColorB = (double newValue) =>
                    {
                        startColor.b            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], startColorB);

                    if (startColors.Length == 4)
                    {
                        Action <double> startColorA = (double newValue) =>
                        {
                            startColor.a            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.startColor = startColor;
                        };
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], startColorA);
                    }
                }

                if (comp.TryGetNamedColor(endColorString, out col))
                {
                    endColor = col;
                }
                else
                {
                    string[] endColors = Utility.SplitVariableList(endColorString);
                    if (endColors.Length < 3 || endColors.Length > 4)
                    {
                        throw new ArgumentException("endColor does not contain 3 or 4 values in LINE_STRING " + name);
                    }

                    Action <double> endColorR = (double newValue) =>
                    {
                        endColor.r            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.endColor = endColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(endColors[0], endColorR);

                    Action <double> endColorG = (double newValue) =>
                    {
                        endColor.g            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.endColor = endColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(endColors[1], endColorG);

                    Action <double> endColorB = (double newValue) =>
                    {
                        endColor.b            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.endColor = endColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(endColors[2], endColorB);

                    if (endColors.Length == 4)
                    {
                        Action <double> endColorA = (double newValue) =>
                        {
                            endColor.a            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.endColor = endColor;
                        };
                        variableRegistrar.RegisterVariableChangeCallback(endColors[3], endColorA);
                    }
                }

                lineRenderer.startColor = startColor;
                lineRenderer.endColor   = endColor;
            }

            if (string.IsNullOrEmpty(endWidthString))
            {
                // Monowidth line
                Action <double> startWidthAction = (double newValue) =>
                {
                    startWidth = (float)newValue;
                    lineRenderer.startWidth = startWidth;
                    lineRenderer.endWidth   = startWidth;
                };
                variableRegistrar.RegisterVariableChangeCallback(startWidthString, startWidthAction);
            }
            else
            {
                Action <double> startWidthAction = (double newValue) =>
                {
                    startWidth = (float)newValue;
                    lineRenderer.startWidth = startWidth;
                };
                variableRegistrar.RegisterVariableChangeCallback(startWidthString, startWidthAction);

                Action <double> endWidthAction = (double newValue) =>
                {
                    endWidth = (float)newValue;
                    lineRenderer.endWidth = endWidth;
                };
                variableRegistrar.RegisterVariableChangeCallback(endWidthString, endWidthAction);
            }
        }
Exemple #16
0
        private static IMASMonitorComponent CreatePageComponent(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
        {
            switch (config.name)
            {
            case "CAMERA":
                return(new MASPageCamera(config, prop, comp, monitor, pageRoot, depth));

            case "COMPOUND_TEXT":
                return(new MASPageCompoundText(config, prop, comp, monitor, pageRoot, depth));

            case "ELLIPSE":
                return(new MASPageEllipse(config, prop, comp, monitor, pageRoot, depth));

            case "GROUND_TRACK":
                return(new MASPageGroundTrack(config, prop, comp, monitor, pageRoot, depth));

            case "HORIZON":
                return(new MASPageHorizon(config, prop, comp, monitor, pageRoot, depth));

            case "HORIZONTAL_BAR":
                return(new MASPageHorizontalBar(config, prop, comp, monitor, pageRoot, depth));

            case "HORIZONTAL_STRIP":
                return(new MASPageHorizontalStrip(config, prop, comp, monitor, pageRoot, depth));

            case "IMAGE":
                return(new MASPageImage(config, prop, comp, monitor, pageRoot, depth));

            case "LINE_GRAPH":
                return(new MASPageLineGraph(config, prop, comp, monitor, pageRoot, depth));

            case "LINE_STRING":
                return(new MASPageLineString(config, prop, comp, monitor, pageRoot, depth));

            case "MENU":
                return(new MASPageMenu(config, prop, comp, monitor, pageRoot, depth));

            case "NAVBALL":
                return(new MASPageNavBall(config, prop, comp, monitor, pageRoot, depth));

            case "ORBIT_DISPLAY":
                return(new MASPageOrbitDisplay(config, prop, comp, monitor, pageRoot, depth));

            case "POLYGON":
                return(new MASPagePolygon(config, prop, comp, monitor, pageRoot, depth));

            case "ROLLING_DIGIT":
                return(new MASPageRollingDigit(config, prop, comp, monitor, pageRoot, depth));

            case "RPM_MODULE":
                return(new MASPageRpmModule(config, prop, comp, monitor, pageRoot, depth));

            case "TEXT":
                return(new MASPageText(config, prop, comp, monitor, pageRoot, depth));

            case "VERTICAL_BAR":
                return(new MASPageVerticalBar(config, prop, comp, monitor, pageRoot, depth));

            case "VERTICAL_STRIP":
                return(new MASPageVerticalStrip(config, prop, comp, monitor, pageRoot, depth));

            case "VIEWPORT":
                return(new MASPageViewport(config, prop, comp, monitor, pageRoot, depth));

            case "hitbox":
                return(null);    // Not an error - these nodes are handled separately.

            default:
                Utility.LogError(config, "Unrecognized MASPage child node {0} found", config.name);
                return(null);
            }
        }
        internal MASPageNavBall(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            this.comp = comp;

            string modelName = string.Empty;

            if (!config.TryGetValue("model", ref modelName))
            {
                throw new ArgumentException("Unable to find 'model' in NAVBALL " + name);
            }
            navballModel = GameDatabase.Instance.GetModel(modelName);
            if (navballModel == null)
            {
                throw new ArgumentException("Unable to find 'model' " + modelName + " for NAVBALL " + name);
            }
            try
            {
                Vector3 extents = navballModel.GetComponent <MeshFilter>().mesh.bounds.extents;
                navballExtents = Mathf.Max(extents.x, extents.y) * 1.01f;
            }
            catch
            {
                navballExtents = 1.0f;
            }
            iconDepth       = 1.4f - navballExtents - 0.01f;
            iconAlphaScalar = 0.6f / navballExtents;

            string textureName = string.Empty;

            if (!config.TryGetValue("texture", ref textureName))
            {
                throw new ArgumentException("Unable to find 'texture' in NAVBALL " + name);
            }
            Texture2D navballTexture = GameDatabase.Instance.GetTexture(textureName, false);

            if (navballTexture == null)
            {
                throw new ArgumentException("Unable to find 'texture' " + textureName + " for NAVBALL " + name);
            }

            Vector2 size = Vector2.zero;

            if (!config.TryGetValue("size", ref size))
            {
                throw new ArgumentException("Unable to find 'size' in NAVBALL " + name);
            }
            size = size * 0.5f;

            float opacity = 1.0f;

            if (!config.TryGetValue("opacity", ref opacity))
            {
                opacity = 1.0f;
            }
            else
            {
                opacity = Mathf.Clamp01(opacity);
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            // Set up our navball renderer
            Shader displayShader = MASLoader.shaders["MOARdV/Monitor"];

            navballRenTex = new RenderTexture(512, 512, 24, RenderTextureFormat.ARGB32);
            navballRenTex.Create();
            navballRenTex.DiscardContents();

            componentOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            // Set up our display surface.
            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = pageRoot.position;
            imageObject.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth);
            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            rentexRenderer = imageObject.AddComponent <MeshRenderer>();
            Mesh mesh = new Mesh();

            mesh.vertices = new[]
            {
                new Vector3(-size.x, size.y, 0.0f),
                new Vector3(size.x, size.y, 0.0f),
                new Vector3(-size.x, -size.y, 0.0f),
                new Vector3(size.x, -size.y, 0.0f),
            };
            mesh.uv = new[]
            {
                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(true);
            meshFilter.mesh           = mesh;
            imageMaterial             = new Material(displayShader);
            imageMaterial.mainTexture = navballRenTex;
            rentexRenderer.material   = imageMaterial;

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                throw new ArgumentException("Unable to find 'position' in NAVBALL " + name);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in NAVBALL " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                {
                    position.x = (float)newValue;
                    imageObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                {
                    position.y = (float)newValue;
                    imageObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                });
            }

            //cameraObject
            cameraObject                    = new GameObject();
            cameraObject.name               = pageRoot.gameObject.name + "-MASPageNavBallCamera-" + name + "-" + depth.ToString();
            cameraObject.layer              = pageRoot.gameObject.layer;
            cameraObject.transform.parent   = pageRoot;
            cameraObject.transform.position = pageRoot.position;
            navballCamera                   = cameraObject.AddComponent <Camera>();
            navballCamera.enabled           = true;
            navballCamera.orthographic      = true;
            navballCamera.aspect            = 1.0f;
            navballCamera.eventMask         = 0;
            navballCamera.farClipPlane      = 13.0f;
            navballCamera.orthographicSize  = navballExtents;
            navballCamera.cullingMask       = 1 << navballLayer;
            // TODO: Different shader... clearing to a=0 hides the navball
            navballCamera.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);
            //navballCamera.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 0.0f);
            navballCamera.clearFlags           = CameraClearFlags.SolidColor;
            navballCamera.transparencySortMode = TransparencySortMode.Orthographic;
            navballCamera.targetTexture        = navballRenTex;
            Camera.onPreCull    += CameraPrerender;
            Camera.onPostRender += CameraPostrender;

            navballModel.layer            = navballLayer;
            navballModel.transform.parent = cameraObject.transform;
            // TODO: this isn't working when the camera is shifted.  Camera needs
            // to be on a separate GO than the display.
            navballModel.transform.Translate(new Vector3(0.0f, 0.0f, 2.4f));
            navballRenderer = null;
            navballModel.GetComponentCached <Renderer>(ref navballRenderer);
            navballMaterial             = new Material(displayShader);
            navballMaterial.shader      = displayShader;
            navballMaterial.mainTexture = navballTexture;
            navballMaterial.SetFloat("_Opacity", opacity);
            navballRenderer.material          = navballMaterial;
            navballRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            navballRenderer.enabled           = false;
            navballModel.SetActive(true);
            navballCamera.transform.LookAt(navballModel.transform, Vector3.up);

            float iconScale = 1.0f;

            if (!config.TryGetValue("iconScale", ref iconScale))
            {
                iconScale = 1.0f;
            }
            InitMarkers(cameraObject.transform, iconScale);
            RenderPage(false);

            // Following icons are not currently supported:
            markers[9].SetActive(false); // Waypoint

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                cameraObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                imageObject.SetActive(true);
                cameraObject.SetActive(true);
            }
        }
        internal MASPageEllipse(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string startColorString = string.Empty;

            if (!config.TryGetValue("startColor", ref startColorString))
            {
                throw new ArgumentException("Unable to find 'startColor' in ELLIPSE " + name);
            }
            string endColorString = string.Empty;

            if (!config.TryGetValue("endColor", ref endColorString))
            {
                endColorString = string.Empty;
            }

            string startWidthString = string.Empty;

            if (!config.TryGetValue("startWidth", ref startWidthString))
            {
                throw new ArgumentException("Unable to find 'startWidth' in ELLIPSE " + name);
            }
            string endWidthString = string.Empty;

            if (!config.TryGetValue("endWidth", ref endWidthString))
            {
                endWidthString = string.Empty;
            }

            numVertices = 0;
            if (!config.TryGetValue("vertexCount", ref numVertices))
            {
                throw new ArgumentException("Unable to find 'vertexCount' in ELLIPSE " + name);
            }
            else if (numVertices < 3)
            {
                throw new ArgumentException("'vertexCount' must be at least 3 in ELLIPSE " + name);
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            string rotationVariableName = string.Empty;

            config.TryGetValue("rotation", ref rotationVariableName);

            lineOrigin                    = new GameObject();
            lineOrigin.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            lineOrigin.layer              = pageRoot.gameObject.layer;
            lineOrigin.transform.parent   = pageRoot;
            lineOrigin.transform.position = pageRoot.position;
            lineOrigin.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth);

            ellipseOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                position = Vector2.zero;
                throw new ArgumentException("Unable to find 'position' in ELLIPSE " + name);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in ELLIPSE " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                {
                    position.x = (float)newValue;
                    lineOrigin.transform.position = ellipseOrigin + new Vector3(position.x, -position.y, 0.0f);
                });

                variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                {
                    position.y = (float)newValue;
                    lineOrigin.transform.position = ellipseOrigin + new Vector3(position.x, -position.y, 0.0f);
                });
            }

            // add renderer stuff
            lineMaterial = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            lineRenderer = lineOrigin.AddComponent <LineRenderer>();
            lineRenderer.useWorldSpace = false;
            lineRenderer.material      = lineMaterial;
            lineRenderer.startColor    = startColor;
            lineRenderer.endColor      = endColor;
            lineRenderer.startWidth    = startWidth;
            lineRenderer.endWidth      = endWidth;

            ++numVertices;
            lineRenderer.positionCount = numVertices;
            vertices = new Vector3[numVertices];

            string textureName = string.Empty;

            if (config.TryGetValue("texture", ref textureName))
            {
                Texture tex = GameDatabase.Instance.GetTexture(textureName, false);
                if (tex != null)
                {
                    lineMaterial.mainTexture = tex;
                    inverseTextureWidth      = 1.0f / (float)tex.width;
                    usesTexture = true;
                }
            }

            string startAngleName = string.Empty;

            if (config.TryGetValue("startAngle", ref startAngleName))
            {
                variableRegistrar.RegisterVariableChangeCallback(startAngleName, (double newValue) =>
                {
                    startAngle = (float)newValue;
                    RecalculateVertices();
                });
            }
            else
            {
                startAngle = 0.0f;
            }

            string endAngleName = string.Empty;

            if (config.TryGetValue("endAngle", ref endAngleName))
            {
                if (string.IsNullOrEmpty(startAngleName))
                {
                    throw new ArgumentException("Missing 'startAngle', but found 'endAngle' in ELLIPSE " + name);
                }
                else
                {
                    variableRegistrar.RegisterVariableChangeCallback(endAngleName, (double newValue) =>
                    {
                        endAngle = (float)newValue;
                        RecalculateVertices();
                    });
                }
            }
            else if (!string.IsNullOrEmpty(startAngleName))
            {
                throw new ArgumentException("Found 'startAngle', but missing 'endAngle' in ELLIPSE " + name);
            }
            else
            {
                endAngle = 360.0f;
            }

            string radiusXName = string.Empty;

            if (!config.TryGetValue("radiusX", ref radiusXName))
            {
                throw new ArgumentException("Unable to find 'radiusX' in ELLIPSE " + name);
            }
            string radiusYName = string.Empty;

            if (!config.TryGetValue("radiusY", ref radiusYName))
            {
                Action <double> newRadius = (double newValue) =>
                {
                    radiusX = (float)newValue;
                    radiusY = radiusX;
                    RecalculateVertices();
                };
                variableRegistrar.RegisterVariableChangeCallback(radiusXName, newRadius);
            }
            else
            {
                Action <double> newRadiusX = (double newValue) =>
                {
                    radiusX = (float)newValue;
                    RecalculateVertices();
                };
                variableRegistrar.RegisterVariableChangeCallback(radiusXName, newRadiusX);
                Action <double> newRadiusY = (double newValue) =>
                {
                    radiusY = (float)newValue;
                    RecalculateVertices();
                };
                variableRegistrar.RegisterVariableChangeCallback(radiusYName, newRadiusY);
            }

            RenderPage(false);

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the lines if we're in variable mode
                lineOrigin.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                lineOrigin.SetActive(true);
            }

            if (!string.IsNullOrEmpty(rotationVariableName))
            {
                variableRegistrar.RegisterVariableChangeCallback(rotationVariableName, RotationCallback);
            }

            if (string.IsNullOrEmpty(endColorString))
            {
                Color32 namedColor;
                if (comp.TryGetNamedColor(startColorString, out namedColor))
                {
                    startColor = namedColor;
                    lineRenderer.startColor = startColor;
                    lineRenderer.endColor   = startColor;
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(startColorString);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("startColor does not contain 3 or 4 values in ELLIPSE " + name);
                    }

                    Action <double> startColorR = (double newValue) =>
                    {
                        startColor.r            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                        lineRenderer.endColor   = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], startColorR);

                    Action <double> startColorG = (double newValue) =>
                    {
                        startColor.g            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                        lineRenderer.endColor   = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], startColorG);

                    Action <double> startColorB = (double newValue) =>
                    {
                        startColor.b            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                        lineRenderer.endColor   = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], startColorB);

                    if (startColors.Length == 4)
                    {
                        Action <double> startColorA = (double newValue) =>
                        {
                            startColor.a            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.startColor = startColor;
                            lineRenderer.endColor   = startColor;
                        };
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], startColorA);
                    }
                }
            }
            else
            {
                Color32 namedColor;
                if (comp.TryGetNamedColor(startColorString, out namedColor))
                {
                    startColor = namedColor;
                    lineRenderer.startColor = startColor;
                    lineRenderer.endColor   = endColor;
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(startColorString);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("startColor does not contain 3 or 4 values in ELLIPSE " + name);
                    }

                    Action <double> startColorR = (double newValue) =>
                    {
                        startColor.r            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], startColorR);

                    Action <double> startColorG = (double newValue) =>
                    {
                        startColor.g            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], startColorG);

                    Action <double> startColorB = (double newValue) =>
                    {
                        startColor.b            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = startColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], startColorB);

                    if (startColors.Length == 4)
                    {
                        Action <double> startColorA = (double newValue) =>
                        {
                            startColor.a            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.startColor = startColor;
                        };
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], startColorA);
                    }
                }

                if (comp.TryGetNamedColor(endColorString, out namedColor))
                {
                    endColor = namedColor;
                    lineRenderer.startColor = startColor;
                    lineRenderer.endColor   = endColor;
                }
                else
                {
                    string[] endColors = Utility.SplitVariableList(endColorString);
                    if (endColors.Length < 3 || endColors.Length > 4)
                    {
                        throw new ArgumentException("endColor does not contain 3 or 4 values in ELLIPSE " + name);
                    }

                    Action <double> endColorR = (double newValue) =>
                    {
                        endColor.r            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.endColor = endColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(endColors[0], endColorR);

                    Action <double> endColorG = (double newValue) =>
                    {
                        endColor.g            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.endColor = endColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(endColors[1], endColorG);

                    Action <double> endColorB = (double newValue) =>
                    {
                        endColor.b            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.endColor = endColor;
                    };
                    variableRegistrar.RegisterVariableChangeCallback(endColors[2], endColorB);

                    if (endColors.Length == 4)
                    {
                        Action <double> endColorA = (double newValue) =>
                        {
                            endColor.a            = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.endColor = endColor;
                        };
                        variableRegistrar.RegisterVariableChangeCallback(endColors[3], endColorA);
                    }
                }
            }

            if (string.IsNullOrEmpty(endWidthString))
            {
                // Monowidth line
                Action <double> startWidthAction = (double newValue) =>
                {
                    startWidth = (float)newValue;
                    lineRenderer.startWidth = startWidth;
                    lineRenderer.endWidth   = startWidth;
                };
                variableRegistrar.RegisterVariableChangeCallback(startWidthString, startWidthAction);
            }
            else
            {
                Action <double> startWidthAction = (double newValue) =>
                {
                    startWidth = (float)newValue;
                    lineRenderer.startWidth = startWidth;
                };
                variableRegistrar.RegisterVariableChangeCallback(startWidthString, startWidthAction);

                Action <double> endWidthAction = (double newValue) =>
                {
                    endWidth = (float)newValue;
                    lineRenderer.endWidth = endWidth;
                };
                variableRegistrar.RegisterVariableChangeCallback(endWidthString, endWidthAction);
            }
        }
Exemple #19
0
        internal MASPageLineGraph(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            Vector2 size = Vector2.zero;

            if (!config.TryGetValue("size", ref size))
            {
                throw new ArgumentException("Unable to find 'size' in LINE_GRAPH " + name);
            }
            verticalSpan = size.y;

            if (!config.TryGetValue("sampleRate", ref sampleRate))
            {
                throw new ArgumentException("Unable to find 'sampleRate' in LINE_GRAPH " + name);
            }
            maxSamples  = (int)(size.x / sampleRate);
            graphPoints = new Vector3[maxSamples];

            string sourceName = string.Empty;

            if (!config.TryGetValue("source", ref sourceName))
            {
                throw new ArgumentException("Unable to find 'source' in LINE_GRAPH " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(sourceName, (double newValue) => sourceValue = (float)newValue);

            string sourceRange = string.Empty;

            if (!config.TryGetValue("sourceRange", ref sourceRange))
            {
                throw new ArgumentException("Unable to find 'sourceRange' in LINE_GRAPH " + name);
            }
            string[] ranges = Utility.SplitVariableList(sourceRange);
            if (ranges.Length != 2)
            {
                throw new ArgumentException("Incorrect number of values in 'sourceRange' in LINE_GRAPH " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(ranges[0], (double newValue) => sourceRange1 = (float)newValue);
            variableRegistrar.RegisterVariableChangeCallback(ranges[1], (double newValue) => sourceRange2 = (float)newValue);

            float borderWidth = 0.0f;

            if (!config.TryGetValue("borderWidth", ref borderWidth))
            {
                borderWidth = 0.0f;
            }
            else
            {
                borderWidth = Math.Max(1.0f, borderWidth);
            }
            string borderColorName = string.Empty;

            if (!config.TryGetValue("borderColor", ref borderColorName))
            {
                borderColorName = string.Empty;
            }
            if (string.IsNullOrEmpty(borderColorName) == (borderWidth > 0.0f))
            {
                throw new ArgumentException("Only one of 'borderColor' and 'borderWidth' are defined in LINE_GRAPH " + name);
            }

            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            componentOrigin = pageRoot.position + new Vector3(monitor.screenSize.x * -0.5f, monitor.screenSize.y * 0.5f, depth);

            // Set up our display surface.
            if (borderWidth > 0.0f)
            {
                borderObject                    = new GameObject();
                borderObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name + "-border", (int)(-depth / MASMonitor.depthDelta));
                borderObject.layer              = pageRoot.gameObject.layer;
                borderObject.transform.parent   = pageRoot;
                borderObject.transform.position = pageRoot.position;
                borderObject.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y - size.y, depth);

                borderMaterial = new Material(MASLoader.shaders["MOARdV/Monitor"]);
                borderRenderer = borderObject.AddComponent <LineRenderer>();
                borderRenderer.useWorldSpace = false;
                borderRenderer.material      = borderMaterial;
                borderRenderer.startColor    = borderColor;
                borderRenderer.endColor      = borderColor;
                borderRenderer.startWidth    = borderWidth;
                borderRenderer.endWidth      = borderWidth;
                borderRenderer.positionCount = 4;
                borderRenderer.loop          = true;

                Color32 namedColor;
                if (comp.TryGetNamedColor(borderColorName, out namedColor))
                {
                    borderColor             = namedColor;
                    lineRenderer.startColor = borderColor;
                    lineRenderer.endColor   = borderColor;
                }
                else
                {
                    string[] startColors = Utility.SplitVariableList(borderColorName);
                    if (startColors.Length < 3 || startColors.Length > 4)
                    {
                        throw new ArgumentException("borderColor does not contain 3 or 4 values in LINE_GRAPH " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(startColors[0], (double newValue) =>
                    {
                        borderColor.r             = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        borderRenderer.startColor = borderColor;
                        borderRenderer.endColor   = borderColor;
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[1], (double newValue) =>
                    {
                        borderColor.g             = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        borderRenderer.startColor = borderColor;
                        borderRenderer.endColor   = borderColor;
                    });

                    variableRegistrar.RegisterVariableChangeCallback(startColors[2], (double newValue) =>
                    {
                        borderColor.b             = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        borderRenderer.startColor = borderColor;
                        borderRenderer.endColor   = borderColor;
                    });

                    if (startColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(startColors[3], (double newValue) =>
                        {
                            borderColor.a             = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            borderRenderer.startColor = borderColor;
                            borderRenderer.endColor   = borderColor;
                        });
                    }
                }

                float     halfWidth    = borderWidth * 0.5f;
                Vector3[] borderPoints = new Vector3[]
                {
                    new Vector3(-halfWidth, -halfWidth, 0.0f),
                    new Vector3(size.x + halfWidth, -halfWidth, 0.0f),
                    new Vector3(size.x + halfWidth, size.y + halfWidth, 0.0f),
                    new Vector3(-halfWidth, size.y + halfWidth, 0.0f)
                };
                borderRenderer.SetPositions(borderPoints);
            }

            graphObject                    = new GameObject();
            graphObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            graphObject.layer              = pageRoot.gameObject.layer;
            graphObject.transform.parent   = pageRoot;
            graphObject.transform.position = pageRoot.position;
            graphObject.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y - size.y, depth);
            // add renderer stuff
            graphMaterial = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            lineRenderer  = graphObject.AddComponent <LineRenderer>();
            lineRenderer.useWorldSpace = false;
            lineRenderer.material      = graphMaterial;
            lineRenderer.startColor    = sourceColor;
            lineRenderer.endColor      = sourceColor;
            lineRenderer.startWidth    = 2.5f;
            lineRenderer.endWidth      = 2.5f;
            lineRenderer.positionCount = maxSamples;
            lineRenderer.loop          = false;
            RenderPage(false);

            string positionString = string.Empty;

            if (!config.TryGetValue("position", ref positionString))
            {
                throw new ArgumentException("Unable to find 'position' in LINE_GRAPH " + name);
            }
            else
            {
                string[] pos = Utility.SplitVariableList(positionString);
                if (pos.Length != 2)
                {
                    throw new ArgumentException("Invalid number of values for 'position' in LINE_GRAPH " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(pos[0], (double newValue) =>
                {
                    position.x = (float)newValue;
                    graphObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                    if (borderWidth > 0.0f)
                    {
                        borderObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                    }
                });

                variableRegistrar.RegisterVariableChangeCallback(pos[1], (double newValue) =>
                {
                    position.y = (float)newValue;
                    graphObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                    if (borderWidth > 0.0f)
                    {
                        borderObject.transform.position = componentOrigin + new Vector3(position.x, -position.y, 0.0f);
                    }
                });
            }

            for (int i = 0; i < maxSamples; ++i)
            {
                graphPoints[i] = Vector3.zero;
            }

            string sourceColorName = string.Empty;

            if (config.TryGetValue("sourceColor", ref sourceColorName))
            {
                Color32 namedColor;
                if (comp.TryGetNamedColor(sourceColorName, out namedColor))
                {
                    sourceColor             = namedColor;
                    lineRenderer.startColor = sourceColor;
                    lineRenderer.endColor   = sourceColor;
                }
                else
                {
                    string[] sourceColors = Utility.SplitVariableList(sourceColorName);
                    if (sourceColors.Length < 3 || sourceColors.Length > 4)
                    {
                        throw new ArgumentException("sourceColor does not contain 3 or 4 values in LINE_GRAPH " + name);
                    }

                    variableRegistrar.RegisterVariableChangeCallback(sourceColors[0], (double newValue) =>
                    {
                        sourceColor.r           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = sourceColor;
                        lineRenderer.endColor   = sourceColor;
                    });

                    variableRegistrar.RegisterVariableChangeCallback(sourceColors[1], (double newValue) =>
                    {
                        sourceColor.g           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = sourceColor;
                        lineRenderer.endColor   = sourceColor;
                    });

                    variableRegistrar.RegisterVariableChangeCallback(sourceColors[2], (double newValue) =>
                    {
                        sourceColor.b           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        lineRenderer.startColor = sourceColor;
                        lineRenderer.endColor   = sourceColor;
                    });

                    if (sourceColors.Length == 4)
                    {
                        variableRegistrar.RegisterVariableChangeCallback(sourceColors[3], (double newValue) =>
                        {
                            sourceColor.a           = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                            lineRenderer.startColor = sourceColor;
                            lineRenderer.endColor   = sourceColor;
                        });
                    }
                }
            }

            currentSample = 0;

            comp.StartCoroutine(SampleData());

            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                if (borderObject != null)
                {
                    borderObject.SetActive(false);
                }
                graphObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                currentState = true;
                if (borderObject != null)
                {
                    borderObject.SetActive(true);
                }
                graphObject.SetActive(true);
            }
        }
Exemple #20
0
        internal MASPage(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform rootTransform)
        {
            if (!config.TryGetValue("name", ref name))
            {
                throw new ArgumentException("Invalid or missing 'name' in MASPage");
            }

            string[] softkeys    = config.GetValues("softkey");
            int      numSoftkeys = softkeys.Length;

            for (int i = 0; i < numSoftkeys; ++i)
            {
                string[] pair = Utility.SplitVariableList(softkeys[i]);
                if (pair.Length == 2)
                {
                    int id;
                    if (int.TryParse(pair[0], out id))
                    {
                        Action action = comp.GetAction(pair[1], prop);
                        if (action != null)
                        {
                            softkeyAction[id] = action;
                        }
                    }
                }
            }

            string entryMethod = string.Empty;

            if (config.TryGetValue("onEntry", ref entryMethod))
            {
                onEntry = comp.GetAction(entryMethod, prop);
            }
            string exitMethod = string.Empty;

            if (config.TryGetValue("onExit", ref exitMethod))
            {
                onExit = comp.GetAction(exitMethod, prop);
            }

            pageRoot                  = new GameObject();
            pageRoot.name             = Utility.ComposeObjectName(this.GetType().Name, name, prop.propID);
            pageRoot.layer            = rootTransform.gameObject.layer;
            pageRoot.transform.parent = rootTransform;
            pageRoot.transform.Translate(0.0f, 0.0f, 1.0f);

            float depth = 0.0f;

            ConfigNode[] components    = config.GetNodes();
            int          numComponents = components.Length;

            if (Array.Exists(components, x => x.name == "SUB_PAGE"))
            {
                // Need to collate
                List <ConfigNode> newComponents = new List <ConfigNode>();

                for (int i = 0; i < numComponents; ++i)
                {
                    ConfigNode node = components[i];
                    if (node.name == "SUB_PAGE")
                    {
                        string subPageName = string.Empty;
                        // Test for 'name'
                        if (!node.TryGetValue("name", ref subPageName))
                        {
                            throw new ArgumentException("No 'name' field in SUB_PAGE found in MASPage " + name);
                        }

                        // Test for 'variable'
                        string variableString = string.Empty;

                        bool editVariable = (node.TryGetValue("variable", ref variableString));

                        // Test for 'position'
                        bool     editPosition   = false;
                        string[] position       = new string[0];
                        string   positionString = string.Empty;
                        if (node.TryGetValue("position", ref positionString))
                        {
                            position = Utility.SplitVariableList(positionString);
                            if (position.Length != 2)
                            {
                                throw new ArgumentException("Invalid number of entries in 'position' for SUB_PAGE '" + subPageName + "' in MASPage " + name);
                            }
                            editPosition = true;
                        }

                        // Find the sub page.
                        List <ConfigNode> subPageNodes;
                        if (!MASLoader.subPages.TryGetValue(subPageName, out subPageNodes))
                        {
                            throw new ArgumentException("Unable to find MAS_SUB_PAGE '" + subPageName + "' for SUB_PAGE found in MASPage " + name);
                        }

                        if (editVariable || editPosition)
                        {
                            for (int subPageNodeIdx = 0; subPageNodeIdx < subPageNodes.Count; ++subPageNodeIdx)
                            {
                                ConfigNode subNode     = subPageNodes[subPageNodeIdx].CreateCopy();
                                string     subNodeName = string.Empty;
                                if (!subNode.TryGetValue("name", ref subNodeName))
                                {
                                    subNodeName = "anonymous";
                                }

                                if (editVariable)
                                {
                                    string currentVariable = string.Empty;
                                    if (subNode.TryGetValue("variable", ref currentVariable))
                                    {
                                        subNode.SetValue("variable", string.Format("({0}) and ({1})", variableString, currentVariable));
                                    }
                                    else
                                    {
                                        subNode.SetValue("variable", variableString, true);
                                    }
                                }

                                if (editPosition)
                                {
                                    string currentPositionString = string.Empty;
                                    if (subNode.TryGetValue("position", ref currentPositionString))
                                    {
                                        string[] currentPosition = Utility.SplitVariableList(currentPositionString);
                                        if (currentPosition.Length != 2)
                                        {
                                            throw new ArgumentException("Invalid number of values in 'position' for node '" + subNodeName + "' in MAS_SUB_PAGE " + subPageName);
                                        }

                                        if (IsTextNode(subNode))
                                        {
                                            subNode.SetValue("position", string.Format("{4} * ({0}) + ({1}), {5} * ({2}) + ({3})",
                                                                                       position[0], currentPosition[0], position[1], currentPosition[1],
                                                                                       1.0f / monitor.fontSize.x, 1.0f / monitor.fontSize.y));
                                        }
                                        else
                                        {
                                            subNode.SetValue("position", string.Format("({0}) + ({1}), ({2}) + ({3})",
                                                                                       position[0], currentPosition[0], position[1], currentPosition[1]));
                                        }
                                    }
                                    else
                                    {
                                        if (IsTextNode(subNode))
                                        {
                                            subNode.SetValue("position", string.Format("{2} * {0}, {3} * {1}",
                                                                                       position[0], position[1],
                                                                                       1.0f / monitor.fontSize.x, 1.0f / monitor.fontSize.y), true);
                                        }
                                        else
                                        {
                                            subNode.SetValue("position", string.Format("{0}, {1}", position[0], position[1]), true);
                                        }
                                    }
                                }

                                newComponents.Add(subNode);
                            }
                        }
                        else
                        {
                            // Simple and fast case: no edits required.
                            newComponents.AddRange(subPageNodes);
                        }
                    }
                    else
                    {
                        newComponents.Add(node);
                    }
                }

                components    = newComponents.ToArray();
                numComponents = components.Length;
            }

            for (int i = 0; i < numComponents; ++i)
            {
                try
                {
                    var pageComponent = CreatePageComponent(components[i], prop, comp, monitor, pageRoot.transform, depth);
                    if (pageComponent != null)
                    {
                        component.Add(pageComponent);
                        depth -= MASMonitor.depthDelta;
                    }
                }
                catch (Exception e)
                {
                    string componentName = string.Empty;
                    if (!components[i].TryGetValue("name", ref componentName))
                    {
                        componentName = "anonymous";
                    }

                    string error = string.Format("Error configuring MASPage " + name + " " + config.name + " " + componentName + ":");
                    Utility.LogError(this, error);
                    Utility.LogError(this, "{0}", e.ToString());
                    Utility.ComplainLoudly(error);
                }
            }

            if (numComponents > 256)
            {
                Utility.LogWarning(this, "{0} elements were used in MASPage {1}. This may exceed the number of supported elements.", numComponents, name);
            }
        }