private void LogicCard(HoverTextDrawer hoverTextDrawer, List <KSelectable> hoverObjects)
        {
            foreach (KSelectable kselectable2 in hoverObjects)
            {
                LogicPorts ports      = kselectable2.GetComponent <LogicPorts>();
                string     properName = kselectable2.GetProperName().ToUpper();

                if (ports != null)
                {
                    LogicPorts.Port port;
                    bool            portIsInput;
                    if (ports.TryGetPortAtCell(cellPos, out port, out portIsInput))
                    {
                        LogicCardPort(hoverTextDrawer, properName, ports, port, portIsInput);
                    }
                }

                LogicGate            gates = kselectable2.GetComponent <LogicGate>();
                LogicGateBase.PortId portId;
                if (gates != null && gates.TryGetPortAtCell(cellPos, out portId))
                {
                    LogicCardGate(hoverTextDrawer, properName, gates, portId);
                }
            }
        }
Beispiel #2
0
        public override object Evaluate(ParseTreeNode node)
        {
            if (node.ChildNodes[0].ChildNodes.Count == 1)
            {
                return(EvaluateGeneral(node.ChildNodes[0].ChildNodes[0]));
            }
            else
            {
                var inputSignals = new List <ISignal>();
                foreach (var factorNode in node.ChildNodes[0].ChildNodes)
                {
                    var factor = EvaluateGeneral(factorNode);
                    if (!(factor is ISignal))
                    {
                        throw new Exception("unsupported operation");
                    }

                    inputSignals.Add((ISignal)factor);
                }

                var gateType = (LogicGate.GateType)Enum.Parse(typeof(LogicGate.GateType),
                                                              node.ChildNodes[0].Term.Name.Split('_')[0], true);

                var newSignalName = this.declaredObjects.signalNameGenerator.getSignalName();
                var newSignal     = new StdLogic(newSignalName);
                this.declaredObjects.signalTable[newSignalName] = newSignal;

                var logicGate = new LogicGate(gateType, inputSignals, newSignal);
                this.declaredObjects.logicGates.Add(logicGate);

                return(newSignal);
            }
        }
Beispiel #3
0
    public static void ConnectComponents(LogicComponent input, LogicGate output, int outputPort, Layer puzzleLayer, List <GridPosition> positionsHorizontal, List <GridPosition> positionsVertical)
    {
        var line = new Line(output, outputPort);

        line.AddGridPositions(puzzleLayer, positionsHorizontal, positionsVertical);
        input.lines.Add(line);
    }
Beispiel #4
0
    public override void RefreshTile(Vector3Int location, ITilemap tilemap)
    {
        realTilemap = tilemap.GetComponent <Tilemap>();

        TileBase previousTile;

        Circuit.RemoveComponent(location);
        tilemap.RefreshTile(location);
        if (tilemap.GetTile <OrTile>(location))
        {
            TrueOrTile orGate = ScriptableObject.CreateInstance <TrueOrTile>();
            orGate.gateWireSprites = trueOrSprites;

            previousTile        = tilemap.GetTile(location + new Vector3Int(-1, 0, 0));
            orGate.replacedTile = previousTile;
            realTilemap.SetTile(location + new Vector3Int(-1, 0, 0), orGate);
        }
        else
        {
            CircuitComponent component = Circuit.circuitComponents[location + new Vector3Int(-1, 0, 0)];
            if (component is OrGate)
            {
                LogicGate gate = (LogicGate)component;
                realTilemap.SetTile(location + new Vector3Int(-1, 0, 0), gate.previousTile);
            }
        }
    }
Beispiel #5
0
    /// <summary>
    /// Returns the output of the logic gate with the given inputs
    /// </summary>
    /// <param name="Gate"></param>
    /// <returns></returns>
    public static bool GetOutput(LogicGate Gate, bool Input1, bool Input2)
    {
        // Quick if-statement
        // Supposedly a few 'if' statements are faster than switch statement? o.0
        if (!Input1 && !Input2)
        {
            return(Gate.Output00);
        }
        else if (Input1 && !Input2)
        {
            return(Gate.Output01);
        }
        else if (!Input1 && Input2)
        {
            return(Gate.Output10);
        }
        else if (Input1 && Input2)
        {
            return(Gate.Output11);
        }

        // If somehow the inputs aren't true or false (??????) then return an error
        Debug.LogError("Somehow the inputs aren't true or false?!");
        return(false);
    }
Beispiel #6
0
        public OnlyWhenAttribute(LogicGate gate, string flag, params string[] rest)
        {
            Gate = gate;

            Flags = rest.Prepend(flag);
            Type  = JudgeType.Flag;
        }
    public override void DoPostConfigureComplete(GameObject go)
    {
        LogicGate logicGate = go.AddComponent <LogicGate>();

        logicGate.op = GetLogicOp();
        go.GetComponent <KPrefabID>().prefabInitFn += delegate(GameObject game_object)
        {
            LogicGate component = game_object.GetComponent <LogicGate>();
            component.SetPortDescriptions(GetDescriptions());
        };
    }
Beispiel #8
0
        private static bool JudgeFlags(IEnumerable <string> actualFlags, LogicGate gate, IEnumerable <string> expectedFlags)
        {
            switch (gate)
            {
            case LogicGate.AND:
                foreach (string flag in actualFlags)
                {
                    if (!expectedFlags.Contains(flag))
                    {
                        return(false);
                    }
                }

                return(true);

            case LogicGate.OR:
                foreach (string flag in actualFlags)
                {
                    if (expectedFlags.Contains(flag))
                    {
                        return(true);
                    }
                }

                return(false);

            case LogicGate.NAND:
                foreach (string flag in actualFlags)
                {
                    if (!expectedFlags.Contains(flag))
                    {
                        return(true);
                    }
                }

                return(false);

            case LogicGate.NOR:
                foreach (string flag in actualFlags)
                {
                    if (expectedFlags.Contains(flag))
                    {
                        return(false);
                    }
                }

                return(true);

            default:
                return(true);
            }
        }
Beispiel #9
0
    public LogicGateEnum logicGateToEnum(LogicGate logicGate)
    {
        LogicGateEnum logicGateEnum = new LogicGateEnum();

        logicGateEnum.objectCondition       = logicGate.objectCondition.enumID();
        logicGateEnum.objectConditionOption = logicGate.objectConditionOption;
        logicGateEnum.condition             = logicGate.condition.enumID();
        logicGateEnum.conditionOption       = logicGate.conditionOption;
        logicGateEnum.action             = logicGate.action.enumID();
        logicGateEnum.actionOption       = logicGate.actionOption;
        logicGateEnum.objectAction       = logicGate.objectAction.enumID();
        logicGateEnum.objectActionOption = logicGate.objectActionOption;

        return(logicGateEnum);
    }
Beispiel #10
0
        public void LoadFrom(Logic modContext, LogicGate baseObject, GameObject go)
        {
            ModContext = modContext;
            // BasicInfo
            Prefab            = baseObject.Prefab;
            infoType          = baseObject.infoType;
            Rigidbody         = baseObject.Rigidbody;
            noRigidbody       = baseObject.noRigidbody;
            MeshRenderer      = baseObject.MeshRenderer;
            noRigidbody       = baseObject.noRigidbody;
            stripped          = baseObject.stripped;
            NetBlock          = baseObject.NetBlock;
            _hasParentMachine = baseObject._hasParentMachine;
            _parentMachine    = baseObject._parentMachine;
            SimPhysics        = baseObject.SimPhysics;
            isSimulating      = baseObject.isSimulating;
            IsMagnetic        = baseObject.IsMagnetic;
            isDestroyed       = baseObject.isDestroyed;
            ShelterAmount     = baseObject.ShelterAmount;
            offsetDir         = baseObject.offsetDir;

            // SaveableDataHolder

            // BlockBehavior
            VisualController       = baseObject.VisualController;
            VisualController.Block = this;
            BreakOnImpact          = baseObject.BreakOnImpact;
            BlockHealth            = baseObject.BlockHealth;
            myBounds              = baseObject.myBounds;
            fireTag               = baseObject.fireTag;
            iceTag                = baseObject.iceTag;
            blockJoint            = baseObject.blockJoint;
            DestroyOnClient       = baseObject.DestroyOnClient;
            DestroyOnSimulate     = baseObject.DestroyOnSimulate;
            CurrentWindController = baseObject.CurrentWindController;

            var componentsInChildren = baseObject.GetComponentsInChildren <TriggerSetJoint>();

            for (int i = 0; i < componentsInChildren.Length; i++)
            {
                componentsInChildren[i].block = this;
            }

            leaverA  = baseObject.leaverA;
            leaverB  = baseObject.leaverB;
            ledColor = baseObject.ledColor;
        }
Beispiel #11
0
    public Connection(Connector source, Connector dest)
    {
        GateTextureData sourceGate = source.GetComponentInParent <GateTextureData>(),
                        destGate   = dest.GetComponentInParent <GateTextureData>();

        int sourcePort = sourceGate.Conn_Out_Points.ToList().IndexOf(source),
            destPort   = destGate.Conn_In_Points.ToList().IndexOf(dest);

        this.source      = sourceGate.logicGate;
        this.destination = destGate.logicGate;

        this.sourcePort = sourcePort;
        this.destPort   = destPort;

        this.source.Output_Conns[sourcePort]   = this;
        this.destination.Input_Conns[destPort] = this;
    }
Beispiel #12
0
    public void ConnectGates(LogicGate source, int sourcePort, LogicGate dest, int destPort)
    {
        if (sourcePort != -1 && destPort != -1)
        {
            Connection conn = GameObject.Instantiate(default_Connection);
            conn.source      = source;
            conn.destination = dest;

            conn.sourcePort = sourcePort;
            conn.destPort   = destPort;

            source.Output_Conns[sourcePort] = conn;
            dest.Input_Conns[destPort]      = conn;

            conn.Draw();
        }
    }
    public override bool Create(Editor.Editor editor, [NotNullWhen(true)] out Component?component)
    {
        ImGui.SetNextItemWidth(80);
        if (ImGui.InputInt("Bits", ref this.bits, 1, 1))
        {
            this.bits = Math.Max(2, this.bits);
        }

        ImGui.Button("Create");
        if (ImGui.IsItemClicked())
        {
            ImGui.CloseCurrentPopup();
            component = new LogicGate(editor.GetWorldMousePos(), this.bits, this.logic);
            return(true);
        }

        component = null;
        return(false);
    }
Beispiel #14
0
        public void TrainWithData(LogicGate data, int trainingIterations = 10)
        {
            if (this.Layers.Count == 0)
            {
                throw new Exception("Neural net not initialized");
            }
            if (trainingIterations < 1 || data == null || data.learningData == null || data.learningData.Count == 0)
            {
                throw new Exception("Wrong learning data");
            }
            foreach (var trainingSet in data.learningData)
            {
                if (trainingSet.Count < 2)
                {
                    throw new Exception("Wrong learning data");
                }
                var inputData  = trainingSet[0].ToArray();
                var outputData = trainingSet[1].ToArray();
                this.Propagate(inputData);
                Console.WriteLine($"Input data: ({string.Join(",", inputData)})   Output data: ({this.OutputLayer.Neurons[0].Value})  Ideal ({string.Join(",", outputData)})");
            }
            Console.WriteLine("Training...");
            int i = 0;

            while (i < trainingIterations)
            {
                foreach (var trainingSet in data.learningData)
                {
                    var inputData  = trainingSet[0].ToArray();
                    var outputData = trainingSet[1].ToArray();
                    this.Train(inputData, outputData);
                }
                i++;
            }
            foreach (var trainingSet in data.learningData)
            {
                var inputData  = trainingSet[0].ToArray();
                var outputData = trainingSet[1].ToArray();
                this.Propagate(inputData);
                Console.WriteLine($"Input data: ({string.Join(",", inputData)})   Output data: ({this.OutputLayer.Neurons[0].Value})  Ideal ({string.Join(",", outputData)})");
            }
        }
Beispiel #15
0
    public LogicGate EnumToLogicGate(LogicGateEnum logicGateEnum)
    {
        LogicGate logicGate = new LogicGate();

        var objects    = GetComponents <MonoBehaviour>().OfType <IObject>();
        var conditions = GetComponents <MonoBehaviour>().OfType <ICondition>();
        var actions    = GetComponents <MonoBehaviour>().OfType <IAction>();

        foreach (IObject obj in objects)
        {
            if (logicGateEnum.objectCondition == obj.enumID())
            {
                logicGate.objectCondition = obj;
            }

            if (logicGateEnum.objectAction == obj.enumID())
            {
                logicGate.objectAction = obj;
            }
        }
        foreach (ICondition cond in conditions)
        {
            if (logicGateEnum.condition == cond.enumID())
            {
                logicGate.condition = cond;
            }
        }
        foreach (IAction act in actions)
        {
            if (logicGateEnum.action == act.enumID())
            {
                logicGate.action = act;
            }
        }

        logicGate.objectConditionOption = logicGateEnum.objectConditionOption;
        logicGate.conditionOption       = logicGateEnum.conditionOption;
        logicGate.actionOption          = logicGateEnum.actionOption;
        logicGate.objectActionOption    = logicGateEnum.objectActionOption;

        return(logicGate);
    }
Beispiel #16
0
    /// <summary>
    /// Spawns a logic gate in the world
    /// </summary>
    /// <param name="Gate">The gate type to spawn</param>
    /// <param name="Location">The world position to spawn it</param>
    public static GateBehaviour SpawnGate(LogicGate Gate, Vector2 Position)
    {
        // Check that there are no other gates nearby
        for (int i = 0; i < CurrentGates.Count; i++)
        {
            // If the distance is below a certain threshold, do not allow a gate to be placed
            if (Mathf.Pow(Vector2.Distance(Position, CurrentGates[i].transform.position), 2f) < 0.001f)
            {
                return(null);
            }
        }

        // Setup the object
        GameObject GateObject = new GameObject();

        GateObject.transform.position   = Position;
        GateObject.transform.localScale = Vector3.one * 0.2f;
        GateObject.name             = "Gate (" + Gate.GateName + ")"; // name is just "Gate (Type)", using gate list count is gonna be odd :)
        GateObject.transform.parent = GateParent.transform;

        // Setup gate behaviour
        GateBehaviour GateScript = GateObject.AddComponent <GateBehaviour>();

        GateScript.LogicGate = Gate;
        GateScript.Working   = true;

        // Setup sprite renderer
        SpriteRenderer GateSR = GateObject.AddComponent <SpriteRenderer>();

        GateSR.sprite       = Gate.GateSprite;
        GateSR.sortingOrder = 3;

        // Add the gate to the list, bearing in mind we need the GateBehaviour
        CurrentGates.Add(GateScript);

        // Return the gate behaviour
        return(GateScript);
    }
Beispiel #17
0
    public override Component ToComponent()
    {
        LogicGate s = new LogicGate(this.Position, this.Bits, Util.GetGateLogicFromName(this.Logic), this.UniqueID);

        return(s);
    }
Beispiel #18
0
        public void PostProcess(string name, ref Block[] blocks)
        {
            // playback IO
            LogicGate startConnector = blocks[blocks.Length - 3].Specialise <LogicGate>();
            LogicGate stopConnector  = blocks[blocks.Length - 2].Specialise <LogicGate>();
            LogicGate resetConnector = blocks[blocks.Length - 1].Specialise <LogicGate>();
            uint      count          = 0;

            // generate channel data
            byte[] channelPrograms = new byte[16];
            for (byte i = 0; i < channelPrograms.Length; i++) // init array
            {
                channelPrograms[i] = 5;                       // Piano
            }

            foreach (TimedEvent e in openFiles[name].GetTimedEvents())
            {
                if (e.Event.EventType == MidiEventType.ProgramChange)
                {
                    ProgramChangeEvent pce = (ProgramChangeEvent)e.Event;
                    channelPrograms[pce.Channel] = AudioTools.TrackType(pce.ProgramNumber);
#if DEBUG
                    Logging.MetaLog($"Detected channel {pce.Channel} as program {pce.ProgramNumber} (index {channelPrograms[pce.Channel]})");
#endif
                }
            }

            Timer t = null;
            //count = 0;
            foreach (Note n in openFiles[name].GetNotes())
            {
                while (blocks[count].Type == BlockIDs.Timer)
                {
                    // set timing info
#if DEBUG
                    Logging.Log($"Handling Timer for notes at {n.TimeAs<MetricTimeSpan>(openFiles[name].GetTempoMap()).TotalMicroseconds * 0.000001f}s");
#endif
                    t       = blocks[count].Specialise <Timer>();
                    t.Start = 0;
                    t.End   = 0.01f + n.TimeAs <MetricTimeSpan>(openFiles[name].GetTempoMap()).TotalMicroseconds * 0.000001f;
                    count++;
                }
                // set notes info
                SfxBlock sfx = blocks[count].Specialise <SfxBlock>();
                sfx.Pitch      = n.NoteNumber - 60 + Key; // In MIDI, 60 is middle C, but GC uses 0 for middle C
                sfx.TrackIndex = channelPrograms[n.Channel];
                sfx.Is3D       = ThreeDee;
                sfx.Volume     = AudioTools.VelocityToVolume(n.Velocity) * VolumeMultiplier;
                count++;
                // connect wires
                if (t == null)
                {
                    continue;            // this should never happen
                }
                t.Connect(0, sfx, 0);
                startConnector.Connect(0, t, 0);
                stopConnector.Connect(0, t, 1);
                resetConnector.Connect(0, t, 2);
            }
            openFiles.Remove(name);
        }
Beispiel #19
0
    // Activates a specific object connect to this conduit
    protected void UpdateObject(GameObject obj)
    {
        ObjectEffect.EffectType effect = obj.GetComponent <ObjectEffect>().effect; // Get the effect that the conduit should have on the objectd

        switch (effect)                                                            // Do a switch on that effect to quickly find the effect
        {
        // Doors
        //--------------------
        case ObjectEffect.EffectType.DOOR_CLOSE:        // Door opens when signal is revieved
            obj.SetActive(conduitEnabled);
            break;

        case ObjectEffect.EffectType.DOOR_OPEN:         // Door closes when signal is recieved
            obj.SetActive(!conduitEnabled);
            break;

        // Wires
        //--------------------
        case ObjectEffect.EffectType.WIRE_ON:
            if (conduitEnabled)      // If conduit is on, turn on wire
            {
                obj.GetComponent <Renderer>().material = wireOnMaterial;
            }
            else                    // If conduit is off, turn off wire
            {
                obj.GetComponent <Renderer>().material = wireOffMaterial;
            }
            break;

        case ObjectEffect.EffectType.WIRE_OFF:
            if (conduitEnabled)      // If conduit is on, turn off wire
            {
                obj.GetComponent <Renderer>().material = wireOffMaterial;
            }
            else                    // If conduit is off, turn on wire
            {
                obj.GetComponent <Renderer>().material = wireOnMaterial;
            }
            break;

        // Pistons
        //--------------------
        case ObjectEffect.EffectType.PISTON_EXTEND:
            if (conduitEnabled)      // If conduit is on, extend the piston
            {
                obj.GetComponent <Piston>().Extend();
            }
            else                    // If conduit os off, retract the piston
            {
                obj.GetComponent <Piston>().Retract();
            }
            break;

        case ObjectEffect.EffectType.PISTON_RETRACT:
            if (conduitEnabled)      // If conduit is on, retract the piston
            {
                obj.GetComponent <Piston>().Retract();
            }
            else                    // If conduit is off, extend the piston
            {
                obj.GetComponent <Piston>().Extend();
            }
            break;

        // Gates
        //--------------------
        case ObjectEffect.EffectType.LOGIC_GATE: // AND
            LogicGate gate = obj.GetComponent <LogicGate>();
            if (gate.conduitA == gameObject)     // Check if this conduit is conduit A
            {
                gate.InA = conduitEnabled;
            }
            else                                // This conduit is conduit B
            {
                gate.InB = conduitEnabled;
            }
            break;

        // Bouncers
        //--------------------
        case ObjectEffect.EffectType.BOUNCER:
            obj.GetComponent <Bouncer>().Enabled = conduitEnabled;
            break;

        case ObjectEffect.EffectType.BOUNCER_INV:
            obj.GetComponent <Bouncer>().Enabled = !conduitEnabled;
            break;

        // TOrrets
        //--------------------
        case ObjectEffect.EffectType.TURRET:
            obj.GetComponent <TurretController>().TurretState = conduitEnabled;
            break;

        case ObjectEffect.EffectType.TURRET_INV:
            obj.GetComponent <TurretController>().TurretState = !conduitEnabled;
            break;

        // Water Level Change
        //--------------------
        case ObjectEffect.EffectType.WATER_LEVEL:
            WaterLevel level = obj.GetComponent <WaterLevel>();
            level.waterBody.StopAllCoroutines();
            level.waterBody.StartCoroutine(level.waterBody.ChangeWaterLevel(level.waterHeight));
            break;
        }
    }
        public override object Evaluate(ParseTreeNode node)
        {
            if (node.ChildNodes[0].Term.Name == "not")
            {
                var primary = EvaluateGeneral(node.ChildNodes[1]);
                if (!(primary is ISignal))
                {
                    throw new Exception("unsupported operation");
                }

                var inputSignal = (ISignal)primary;

                if (!inputSignal.name.isTemp)
                {
                    // notゲートを生成
                    var newSignalName = this.declaredObjects.signalNameGenerator.getSignalName();
                    var newSignal     = new StdLogic(newSignalName);
                    this.declaredObjects.signalTable[newSignalName] = newSignal;

                    var notGate = new LogicGate(LogicGate.GateType.NOT, new List <ISignal> {
                        inputSignal
                    }, newSignal);
                    this.declaredObjects.logicGates.Add(notGate);

                    return(newSignal);
                }
                else
                {
                    // and, or, xorをnand, nor, xnorに変換
                    foreach (var gate in this.declaredObjects.logicGates)
                    {
                        if (gate.outputSignal.Equals(inputSignal))
                        {
                            switch (gate.gateType)
                            {
                            case LogicGate.GateType.AND:
                                gate.gateType = LogicGate.GateType.NAND;
                                break;

                            case LogicGate.GateType.OR:
                                gate.gateType = LogicGate.GateType.NOR;
                                break;

                            case LogicGate.GateType.XOR:
                                gate.gateType = LogicGate.GateType.XNOR;
                                break;

                            default:
                                throw new Exception("");
                            }
                            return(inputSignal);
                        }
                    }

                    throw new Exception("");
                }
            }
            else
            {
                return(EvaluateGeneral(node.ChildNodes[0]));
            }
        }
Beispiel #21
0
 public Line(LogicGate output, int outputPort)
 {
     this.output     = output;
     this.outputPort = outputPort;
 }
        private void LogicCardGate(HoverTextDrawer hoverTextDrawer, string properName, LogicGate gates, LogicGateBase.PortId portId)
        {
            int  portValue     = gates.GetPortValue(portId);
            bool portConnected = gates.GetPortConnected(portId);

            LogicGate.LogicGateDescriptions.Description portDescription = gates.GetPortDescription(portId);
            hoverTextDrawer.BeginShadowBar(false);

            LocString fmt =
                portId == LogicGateBase.PortId.Output ?
                UI.TOOLS.GENERIC.LOGIC_MULTI_OUTPUT_HOVER_FMT :
                UI.TOOLS.GENERIC.LOGIC_MULTI_INPUT_HOVER_FMT;

            hoverTextDrawer.DrawText(fmt.Replace("{Port}", portDescription.name.ToUpper()).Replace("{Name}", properName), __this.Styles_BodyText.Standard);


            hoverTextDrawer.NewLine(26);
            TextStyleSetting textStyleSetting3;

            if (portConnected)
            {
                textStyleSetting3 = ((portValue == 1) ? __this.Styles_LogicActive.Selected : __this.Styles_LogicSignalInactive);
            }
            else
            {
                textStyleSetting3 = __this.Styles_LogicActive.Standard;
            }
            hoverTextDrawer.DrawIcon((portValue == 1 && portConnected) ? __this.iconActiveAutomationPort : __this.iconDash, textStyleSetting3.textColor, 18, 2);
            hoverTextDrawer.DrawText(portDescription.active, textStyleSetting3);
            hoverTextDrawer.NewLine(26);
            TextStyleSetting textStyleSetting4;

            if (portConnected)
            {
                textStyleSetting4 = ((portValue == 0) ? __this.Styles_LogicStandby.Selected : __this.Styles_LogicSignalInactive);
            }
            else
            {
                textStyleSetting4 = __this.Styles_LogicStandby.Standard;
            }
            hoverTextDrawer.DrawIcon((portValue == 0 && portConnected) ? __this.iconActiveAutomationPort : __this.iconDash, textStyleSetting4.textColor, 18, 2);
            hoverTextDrawer.DrawText(portDescription.inactive, textStyleSetting4);
            hoverTextDrawer.EndShadowBar();
        }
    public override void UpdateHoverElements(List <KSelectable> hoverObjects)
    {
        HoverTextScreen instance        = HoverTextScreen.Instance;
        HoverTextDrawer hoverTextDrawer = instance.BeginDrawing();

        hoverTextDrawer.BeginShadowBar(false);
        ActionName = ((!((UnityEngine.Object)currentDef != (UnityEngine.Object)null) || !currentDef.DragBuild) ? UI.TOOLS.BUILD.TOOLACTION : UI.TOOLS.BUILD.TOOLACTION_DRAG);
        if ((UnityEngine.Object)currentDef != (UnityEngine.Object)null && currentDef.Name != null)
        {
            ToolName = string.Format(UI.TOOLS.BUILD.NAME, currentDef.Name);
        }
        DrawTitle(instance, hoverTextDrawer);
        DrawInstructions(instance, hoverTextDrawer);
        int cell       = Grid.PosToCell(Camera.main.ScreenToWorldPoint(KInputManager.GetMousePos()));
        int min_height = 26;
        int width      = 8;

        if ((UnityEngine.Object)currentDef != (UnityEngine.Object)null)
        {
            Orientation orientation = Orientation.Neutral;
            if ((UnityEngine.Object)PlayerController.Instance.ActiveTool != (UnityEngine.Object)null)
            {
                Type type = PlayerController.Instance.ActiveTool.GetType();
                if (typeof(BuildTool).IsAssignableFrom(type) || typeof(BaseUtilityBuildTool).IsAssignableFrom(type))
                {
                    if ((UnityEngine.Object)currentDef.BuildingComplete.GetComponent <Rotatable>() != (UnityEngine.Object)null)
                    {
                        hoverTextDrawer.NewLine(min_height);
                        hoverTextDrawer.AddIndent(width);
                        string text = UI.TOOLTIPS.HELP_ROTATE_KEY.ToString();
                        text = text.Replace("{Key}", GameUtil.GetActionString(Action.RotateBuilding));
                        hoverTextDrawer.DrawText(text, Styles_Instruction.Standard);
                    }
                    orientation = BuildTool.Instance.GetBuildingOrientation;
                    string  fail_reason = "Unknown reason";
                    Vector3 pos         = Grid.CellToPosCCC(cell, Grid.SceneLayer.Building);
                    if (!currentDef.IsValidPlaceLocation(BuildTool.Instance.visualizer, pos, orientation, out fail_reason))
                    {
                        hoverTextDrawer.NewLine(min_height);
                        hoverTextDrawer.AddIndent(width);
                        hoverTextDrawer.DrawText(fail_reason, HoverTextStyleSettings[1]);
                    }
                    RoomTracker component = currentDef.BuildingComplete.GetComponent <RoomTracker>();
                    if ((UnityEngine.Object)component != (UnityEngine.Object)null && !component.SufficientBuildLocation(cell))
                    {
                        hoverTextDrawer.NewLine(min_height);
                        hoverTextDrawer.AddIndent(width);
                        hoverTextDrawer.DrawText(UI.TOOLTIPS.HELP_REQUIRES_ROOM, HoverTextStyleSettings[1]);
                    }
                }
            }
            hoverTextDrawer.NewLine(min_height);
            hoverTextDrawer.AddIndent(width);
            hoverTextDrawer.DrawText(ResourceRemainingDisplayScreen.instance.GetString(), Styles_BodyText.Standard);
            hoverTextDrawer.EndShadowBar();
            HashedString mode = SimDebugView.Instance.GetMode();
            if (mode == OverlayModes.Logic.ID && hoverObjects != null)
            {
                SelectToolHoverTextCard component2 = SelectTool.Instance.GetComponent <SelectToolHoverTextCard>();
                foreach (KSelectable hoverObject in hoverObjects)
                {
                    LogicPorts component3 = hoverObject.GetComponent <LogicPorts>();
                    if ((UnityEngine.Object)component3 != (UnityEngine.Object)null && component3.TryGetPortAtCell(cell, out LogicPorts.Port port, out bool isInput))
                    {
                        bool flag = component3.IsPortConnected(port.id);
                        hoverTextDrawer.BeginShadowBar(false);
                        int num;
                        if (isInput)
                        {
                            string replacement = (!port.displayCustomName) ? UI.LOGIC_PORTS.PORT_INPUT_DEFAULT_NAME.text : port.description;
                            num = component3.GetInputValue(port.id);
                            hoverTextDrawer.DrawText(UI.TOOLS.GENERIC.LOGIC_INPUT_HOVER_FMT.Replace("{Port}", replacement).Replace("{Name}", hoverObject.GetProperName().ToUpper()), component2.Styles_Title.Standard);
                        }
                        else
                        {
                            string replacement2 = (!port.displayCustomName) ? UI.LOGIC_PORTS.PORT_OUTPUT_DEFAULT_NAME.text : port.description;
                            num = component3.GetOutputValue(port.id);
                            hoverTextDrawer.DrawText(UI.TOOLS.GENERIC.LOGIC_OUTPUT_HOVER_FMT.Replace("{Port}", replacement2).Replace("{Name}", hoverObject.GetProperName().ToUpper()), component2.Styles_Title.Standard);
                        }
                        hoverTextDrawer.NewLine(26);
                        TextStyleSetting textStyleSetting = (!flag) ? component2.Styles_LogicActive.Standard : ((num != 1) ? component2.Styles_LogicSignalInactive : component2.Styles_LogicActive.Selected);
                        hoverTextDrawer.DrawIcon((num != 1 || !flag) ? component2.iconDash : component2.iconActiveAutomationPort, textStyleSetting.textColor, 18, 2);
                        hoverTextDrawer.DrawText(port.activeDescription, textStyleSetting);
                        hoverTextDrawer.NewLine(26);
                        TextStyleSetting textStyleSetting2 = (!flag) ? component2.Styles_LogicStandby.Standard : ((num != 0) ? component2.Styles_LogicSignalInactive : component2.Styles_LogicStandby.Selected);
                        hoverTextDrawer.DrawIcon((num != 0 || !flag) ? component2.iconDash : component2.iconActiveAutomationPort, textStyleSetting2.textColor, 18, 2);
                        hoverTextDrawer.DrawText(port.inactiveDescription, textStyleSetting2);
                        hoverTextDrawer.EndShadowBar();
                    }
                    LogicGate component4 = hoverObject.GetComponent <LogicGate>();
                    if ((UnityEngine.Object)component4 != (UnityEngine.Object)null && component4.TryGetPortAtCell(cell, out LogicGateBase.PortId port2))
                    {
                        int  portValue     = component4.GetPortValue(port2);
                        bool portConnected = component4.GetPortConnected(port2);
                        LogicGate.LogicGateDescriptions.Description portDescription = component4.GetPortDescription(port2);
                        hoverTextDrawer.BeginShadowBar(false);
                        if (port2 == LogicGateBase.PortId.Output)
                        {
                            hoverTextDrawer.DrawText(UI.TOOLS.GENERIC.LOGIC_MULTI_OUTPUT_HOVER_FMT.Replace("{Port}", portDescription.name).Replace("{Name}", hoverObject.GetProperName().ToUpper()), component2.Styles_Title.Standard);
                        }
                        else
                        {
                            hoverTextDrawer.DrawText(UI.TOOLS.GENERIC.LOGIC_MULTI_INPUT_HOVER_FMT.Replace("{Port}", portDescription.name).Replace("{Name}", hoverObject.GetProperName().ToUpper()), component2.Styles_Title.Standard);
                        }
                        hoverTextDrawer.NewLine(26);
                        TextStyleSetting textStyleSetting3 = (!portConnected) ? component2.Styles_LogicActive.Standard : ((portValue != 1) ? component2.Styles_LogicSignalInactive : component2.Styles_LogicActive.Selected);
                        hoverTextDrawer.DrawIcon((portValue != 1 || !portConnected) ? component2.iconDash : component2.iconActiveAutomationPort, textStyleSetting3.textColor, 18, 2);
                        hoverTextDrawer.DrawText(portDescription.active, textStyleSetting3);
                        hoverTextDrawer.NewLine(26);
                        TextStyleSetting textStyleSetting4 = (!portConnected) ? component2.Styles_LogicStandby.Standard : ((portValue != 0) ? component2.Styles_LogicSignalInactive : component2.Styles_LogicStandby.Selected);
                        hoverTextDrawer.DrawIcon((portValue != 0 || !portConnected) ? component2.iconDash : component2.iconActiveAutomationPort, textStyleSetting4.textColor, 18, 2);
                        hoverTextDrawer.DrawText(portDescription.inactive, textStyleSetting4);
                        hoverTextDrawer.EndShadowBar();
                    }
                }
            }
            else if (mode == OverlayModes.Power.ID)
            {
                CircuitManager circuitManager = Game.Instance.circuitManager;
                ushort         circuitID      = circuitManager.GetCircuitID(cell);
                if (circuitID != 65535)
                {
                    hoverTextDrawer.BeginShadowBar(false);
                    float wattsNeededWhenActive = circuitManager.GetWattsNeededWhenActive(circuitID);
                    wattsNeededWhenActive += currentDef.EnergyConsumptionWhenActive;
                    float maxSafeWattageForCircuit = circuitManager.GetMaxSafeWattageForCircuit(circuitID);
                    Color color = (!(wattsNeededWhenActive >= maxSafeWattageForCircuit)) ? Color.white : Color.red;
                    hoverTextDrawer.AddIndent(width);
                    hoverTextDrawer.DrawText(string.Format(UI.DETAILTABS.ENERGYGENERATOR.POTENTIAL_WATTAGE_CONSUMED, GameUtil.GetFormattedWattage(wattsNeededWhenActive, GameUtil.WattageFormatterUnit.Automatic)), Styles_BodyText.Standard, color, true);
                    hoverTextDrawer.EndShadowBar();
                }
            }
        }
        hoverTextDrawer.EndDrawing();
    }
        //private void Ex1_FormClosed(object sender, FormClosedEventArgs e)
        //{
        //    myMenu.Show();

        //}

        private void Ex1_Load(object sender, EventArgs e)
        {
            ligicNetwork = new LogicGate();
        }
Beispiel #25
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            entity.CannotSuspend = true;
            Transform transform = entity.GetOrCreate <Transform>("Transform");
            LogicGate gate      = entity.GetOrCreate <LogicGate>("LogicGate");

            base.Bind(entity, main, creating);

            entity.Add("Input1", gate.Input1, new PropertyEntry.EditorData {
                Readonly = true
            });
            entity.Add("Input1On", gate.Input1On);
            entity.Add("Input1Off", gate.Input1Off);

            entity.Add("Input2", gate.Input2, new PropertyEntry.EditorData {
                Readonly = true
            });
            entity.Add("Input2On", gate.Input2On);
            entity.Add("Input2Off", gate.Input2Off);

            entity.Add("Output", gate.Output, new PropertyEntry.EditorData {
                Readonly = true
            });
            entity.Add("OutputOn", gate.OutputOn);
            entity.Add("OutputOff", gate.OutputOff);

            if (main.EditorEnabled)
            {
                Action <ListProperty <string>, Entity.Handle> populateOptions = delegate(ListProperty <string> options, Entity.Handle target)
                {
                    options.Clear();
                    Entity e = target.Target;
                    if (e != null && e.Active)
                    {
                        foreach (KeyValuePair <string, PropertyEntry> p in e.Properties)
                        {
                            if (p.Value.Property.GetType().GetGenericArguments().First() == typeof(bool))
                            {
                                options.Add(p.Key);
                            }
                        }
                    }
                };

                ListProperty <string> input1Options = new ListProperty <string>();
                entity.Add("Input1TargetProperty", gate.Input1TargetProperty, new PropertyEntry.EditorData
                {
                    Options = input1Options,
                });

                entity.Add(new NotifyBinding(delegate()
                {
                    populateOptions(input1Options, gate.Input1Target);
                }, gate.Input1Target));

                ListProperty <string> input2Options = new ListProperty <string>();
                entity.Add("Input2TargetProperty", gate.Input2TargetProperty, new PropertyEntry.EditorData
                {
                    Options = input2Options,
                });

                entity.Add(new NotifyBinding(delegate()
                {
                    populateOptions(input2Options, gate.Input2Target);
                }, gate.Input2Target));


                entity.Add(new PostInitialization(delegate()
                {
                    populateOptions(input1Options, gate.Input1Target);
                    populateOptions(input2Options, gate.Input2Target);
                }));
            }
            else
            {
                entity.Add("Input1TargetProperty", gate.Input1TargetProperty);
                entity.Add("Input2TargetProperty", gate.Input2TargetProperty);
            }
        }