コード例 #1
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            if (HighLogic.LoadedSceneIsFlight == false)
            {
                setupExperimentGUI();
                return;
            }

            //Get drill animation
            drillAnimation = this.part.FindModuleImplementing<ModuleAnimationGroup>();

            //Harvester
            harvester = this.part.FindModuleImplementing<ModuleResourceHarvester>();

            //Core sample state
            coreSampleState = CoreSampleStates.Ready;

            //If the biome has been unlocked yet then get the samples left
            if (situationIsValid() && Utils.IsBiomeUnlocked(this.part.vessel))
                coreSampleStatus = getSamplesLeft().ToString();
            else
                coreSampleStatus = kUnknown;

            //Setup the gui
            setupGUI();
        }
コード例 #2
0
 public override void OnStart(StartState state)
 {
     base.OnStart (state);
     initResource ();									//find ablator resource in part
     initMeshes ();										//load mesh from mesh names specified in config
     updateHeatShieldColor ();							//update heat-shield color to appropriate color from stored ablator amount
 }
コード例 #3
0
 public override void OnStart(StartState state)
 {
     if (state == StartState.Editor && !spawned) {
         currentState = initialState;
     } else {
         part.CrewCapacity = currentState ? capacityWhenTrue : capacityWhenFalse;
         if (vessel.situation == Vessel.Situations.PRELAUNCH) {
             int difference = part.protoModuleCrew.Count - part.CrewCapacity;
             if (difference > 0) {
                 JUtil.LogMessage (this, "Stowaways found in part {0}", part.partName);
             }
             var stowaways = new List<ProtoCrewMember> ();
             // We go through the list backwards, assuming that the 'more important' seats are first in the list of seats.
             for (int i = part.protoModuleCrew.Count - 1; i >= 0; i--) {
                 if (difference > 0) {
                     stowaways.Add (part.protoModuleCrew [i]);
                     difference--;
                 } else {
                     break;
                 }
             }
             foreach (ProtoCrewMember stowaway in stowaways) {
                 part.RemoveCrewmember (stowaway);
                 stowaway.seat = null;
                 stowaway.rosterStatus = ProtoCrewMember.RosterStatus.Available;
             }
             JUtil.LogMessage (this, "{0} stowaways evicted.", stowaways.Count);
         }
         // And then make sure the seat flags are correct.
         AlterCrewCapacity (part);
         if (vessel.isActiveVessel)
             GameEvents.onVesselChange.Fire (vessel);
     }
     spawned = true;
 }
コード例 #4
0
ファイル: GeoSurveyCamera.cs プロジェクト: Bear67/Pathfinder
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            //Grab the survey module
            orbitalSurveyer = this.part.FindModuleImplementing<ModuleOrbitalSurveyor>();
            orbitalScanner = this.part.FindModuleImplementing<ModuleOrbitalScanner>();

            //Verify that the planet is really unlocked
            verifyPlanetUnlock();

            //Hide stock survey GUI
            if (orbitalSurveyer != null)
            {
                orbitalSurveyer.Events["PerformSurvey"].guiActive = false;
                orbitalSurveyer.Events["PerformSurvey"].guiActiveUnfocused = false;
                orbitalSurveyer.Events["PerformSurvey"].guiActiveEditor = false;
            }

            //Create swizzler
            swizzler = new WBIResultsDialogSwizzler();
            swizzler.onTransmit = transmitData;

            //Setup the science container
            scienceContainer = this.part.FindModuleImplementing<ModuleScienceContainer>();
            scienceContainer.Events["ReviewDataEvent"].guiActiveUnfocused = false;
            scienceContainer.Events["ReviewDataEvent"].guiActive = false;

            //Now setup our own GUI
            botchedResultsMsg = kSafeMode;
            SetupGUI();
        }
コード例 #5
0
        //set the names of the actions
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            Events["changeRate"].guiName = changeRateString;
            Fields["guiProductionRate"].guiName = converterRateName;
        }
コード例 #6
0
ファイル: SCANsat.cs プロジェクト: BobPalmer/SCANsat
		/* SAT: KSP entry points */
		public override void OnStart ( StartState state )
        {
			if (state == StartState.Editor)
            {
				print ("[SCANsat] start: in editor");
				Events["editorExtend"].active = !string.IsNullOrEmpty(animationName);
            } else
            {
				print ("[SCANsat] start: live");
            }
			if (animationName != null)
            {
				Animation[] a = part.FindModelAnimators (animationName);
				if (a.Length == 0)
                {
					print ("[SCANsat] animation '" + animationName + "' not found");
                } else
                {
					print ("[SCANsat] using animation #1 out of " + a.Length.ToString () + " animations named '" + animationName + "'");
					anim = a [0];
					// maybe use this later for advanced animation...
					Transform modeltransform = part.transform.FindChild ("model");
					foreach (Transform t in modeltransform.GetComponentsInChildren<Transform>())
                    {
						//print("[SCANsat] transform " + t.name + ": " + t);
                    }
                }
            }
			print ("[SCANsat] sensorType: " + sensorType.ToString () + " fov: " + fov.ToString () + " min_alt: " + min_alt.ToString () + " max_alt: " + max_alt.ToString () + " best_alt: " + best_alt.ToString () + " power: " + power.ToString ());
        }
コード例 #7
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     _basePitchTorque = PitchTorque;
     _baseYawTorque = YawTorque;
     _baseRollTorque = RollTorque;
 }
コード例 #8
0
ファイル: usagePods.cs プロジェクト: MartynasStropa/KSP_rusty
        public override void OnStart(StartState state)
        {
            // parent OnStart
            base.OnStart(state);

            module = Utils.getModuleByType<ModuleCommand>(base.part);
        }
コード例 #9
0
 public override void OnStart(StartState state)
 {
     try
     {
         part.force_activate();
         if (isActive)
         {
             ToggleEvent("EngageDampen", false);
             ToggleEvent("DisengageDampen", true);
             Dampen();
         }
         else
         {
             ToggleEvent("EngageDampen", true);
             ToggleEvent("DisengageDampen", false);
         }
         if (autoActivate)
         {
             isActive = true;
             ToggleEvent("EngageDampen", false);
             ToggleEvent("DisengageDampen", false);
         }
     }
     catch (Exception ex)
     {
         print("ERROR in Inertial Dampener OnStart - " + ex.Message);
     }
 }
コード例 #10
0
ファイル: WBIOSEWorkshop.cs プロジェクト: PalverZ/Pathfinder
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            inflatableModule = this.part.FindModuleImplementing<WBIInflatablePartModule>();

            foreach (PartModule mod in this.part.Modules)
            {
                if (mod.moduleName == "OseModuleWorkshop")
                    oseWorkshop = mod;
                else if (mod.moduleName == "OseModuleRecycler")
                    oseRecycler = mod;
            }

            /* For some reason we can't seem to hide the fields and events anymore. :(
            //Now, hide the workshop and recycler GUI.
            if (oseWorkshop != null)
            {
                oseWorkshop.Fields["Status"].guiActive = false;
                oseWorkshop.Events["ContextMenuOnOpenWorkbench"].guiActive = false;
            }

            if (oseRecycler != null)
            {
                oseRecycler.Fields["Status"].guiActive = false;
                oseRecycler.Events["ContextMenuOnOpenWorkbench"].guiActive = false;
            }
             */ 

            //Use reflection to find the methods we need.
            findWorkshopMethods();
        }
コード例 #11
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     if (!HighLogic.LoadedSceneIsFlight)
         return;
     SetDescentMode(IsDescentMode);
 }
コード例 #12
0
 public override void OnStart(StartState state)
 {
     if (state != StartState.Editor) {
         part.force_activate ();
     }
     base.OnStart (state);
 }
コード例 #13
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            loadValuesFromConfig();

            //Parse planet efficiencies
            string[] efficiencies = planetEfficiencies.Split(new char[] { ';' });
            string[] efficiencyID;

            foreach (string efficiency in efficiencies)
            {
                efficiencyID = efficiency.Split(new char[] { ',' });

                efficiencyModifiers.Add(int.Parse(efficiencyID[0]), float.Parse(efficiencyID[1]));
            }

            //Now set the efficiency based upon planet.
            int planetID = this.part.vessel.mainBody.flightGlobalsIndex;
            if (efficiencyModifiers.ContainsKey(planetID))
            {
                this.Efficiency = efficiencyModifiers[planetID];
            }

            efficiencyString = "Geothermal Efficiency";
        }
コード例 #14
0
ファイル: JetWing.cs プロジェクト: Kerbas-ad-astra/Buffalo
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            if (HighLogic.LoadedSceneIsEditor == false && HighLogic.LoadedSceneIsFlight == false)
                return;

            //Set landing gear action
            ModuleAnimateGeneric kickstandAnim = this.part.FindModuleImplementing<ModuleAnimateGeneric>();
            kickstandAnim.Actions[0].actionGroup = KSPActionGroup.Gear;

            //Setup the GUI
            setupGUI();

            //Get the primary and secondary engine
            List<ModuleEngines> engineList = this.part.FindModulesImplementing<ModuleEngines>();
            foreach (ModuleEngines engine in engineList)
            {
                if (engine.engineID == multiModeEngine.primaryEngineID)
                    primaryEngine = engine;
                else if (engine.engineID == multiModeEngine.secondaryEngineID)
                    secondaryEngine = engine;
            }

            //Setup the engine mode
            setupEngineMode();
        }
コード例 #15
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     base.Startup();
     if (Failed)
         DoFailure();
 }
コード例 #16
0
        public override void OnStart(StartState state)
        {
            if (HighLogic.LoadedSceneIsFlight)
            {

                if (escapeHatch == null)
                {
                    escapeHatch = new GameObject("EscapeHatch");
                    escapeHatch.tag = "Airlock";
                    escapeHatch.layer = 21;
                    escapeHatch.transform.parent = this.part.transform;
                    escapeHatch.transform.localEulerAngles = new Vector3(0, 0, 0);
                    escapeHatch.transform.localPosition = new Vector3(0, 0, 0);

                    escapeHatch.AddComponent<BoxCollider>();
                    escapeHatchCollider = escapeHatch.GetComponent<BoxCollider>();
                    escapeHatchCollider.size = new Vector3(0.25f, 0.25f, 0.25f);
                    escapeHatchCollider.isTrigger = true;

                    this.part.airlock = escapeHatch.transform;
                    print("[TakeCommand] added escape hatch to " + this.part.name + " (" + this.part.GetInstanceID() + ")");

                    // Disable it for now until we need it
                    escapeHatch.collider.enabled = true;
                }

            }
            base.OnStart(state);
        }
コード例 #17
0
        //the part that is enabled and disabled
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            string[] transformGroupNames = transormNames.Split(',');
            models = new List<ModelTransforms>();

            //----------------------------------------------------------
            //create the list of transforms to be made switchable
            //----------------------------------------------------------

            foreach (string transformName in transformGroupNames)
            {
                name = transformName.Trim();

                List<Transform> transforms = new List<Transform>();
                transforms.AddRange(part.FindModelTransforms(name));

                ModelTransforms mt = new ModelTransforms();
                mt.transforms = new List<Transform>();
                mt.transforms.AddRange(transforms);

                models.Add(mt);
            }

            if (!HighLogic.LoadedSceneIsEditor)
            {
                Events["toggleModel"].guiActive = false;
            }
            updateActiveModel();
        }
コード例 #18
0
ファイル: WBIMeshToggle.cs プロジェクト: Bear67/WildBlueTools
        public override void OnStart(StartState state)
        {
            showGui = false;
            base.OnStart(state);

            updateGui();
        }
コード例 #19
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     if (state == StartState.Editor || state == StartState.None) return;
     KAS_Shared.createFXSound(this.part, fxSndAttach, attachSndPath, false);
     KAS_Shared.createFXSound(this.part, fxSndDetach, detachSndPath, false);
 }
コード例 #20
0
ファイル: MechJebPod.cs プロジェクト: BryceSchroeder/MechJeb2
 public override void OnStart(StartState state)
 {
     core = part.Modules.OfType<MechJebCore>().FirstOrDefault();
     eye_base = part.FindModelTransform("r4m0n_Control_point_socket"); //    Rotation: 0, 0, Z Azimuth
     eye_ball = part.FindModelTransform("r4m0n_Control_point_Eye"); //       Rotation: X, 0, 0 Altitude
     lastFlaps = new float[] { 0, 0, 0, 0 };
 }
コード例 #21
0
 public override void OnStart(StartState state)
 {
     base.OnStart (state);
     if (state != StartState.Editor) {
         RenderingManager.AddToPostDrawQueue (0, OnGUI);
     }
 }
コード例 #22
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);
            anim = this.part.FindModelAnimators(animationName)[0];

            prevTemplateName = CurrentTemplateName;
        }
コード例 #23
0
        public override void OnStart(StartState state)
        {
            // parent OnStart
            base.OnStart(state);

            module = Utils.getModuleByType<ModuleReactionWheel>(base.part);
        }
コード例 #24
0
 public override void OnStart(StartState state)
 {
     base.OnStart (state);
     animatedTransform = part.FindModelTransform (meshName);
     if(animatedTransform==null){print ("ERROR: Could not locate transform for name: "+meshName);}
     locateEngineModule ();
 }
コード例 #25
0
ファイル: ModuleRCSReliability.cs プロジェクト: vzwick/DangIt
 protected override void DI_Start(StartState state)
 {
     if (HighLogic.LoadedSceneIsFlight)
     {
         rcsModule = this.part.Modules.OfType<ModuleRCS>().Single();
     }
 }
コード例 #26
0
ファイル: USI_CrewTank.cs プロジェクト: Kerbas-ad-astra/ART
 public override void OnStart(StartState state)
 {
     _state = state;
     FindPotato();
     LatchAnimation[latchAnimationName].layer = 2;
     base.OnStart(state);
 }
コード例 #27
0
 public override void OnStart(StartState state)
 {
     base.OnStart (state);
     parseTransformData();
     findTransforms();
     updateGuiData();
 }
コード例 #28
0
        public override void OnStart(StartState state)
        {
            if (!HighLogic.LoadedSceneIsEditor)
                return;

            if (pPart.lengthMin == pPart.lengthMax)
                Fields["length"].guiActiveEditor = false;
            else
            {
                UI_FloatEdit lengthEdit = (UI_FloatEdit)Fields["length"].uiControlEditor;
                lengthEdit.maxValue = pPart.lengthMax;
                lengthEdit.minValue = pPart.lengthMin;
                lengthEdit.incrementLarge = pPart.lengthLargeStep;
                lengthEdit.incrementSmall = pPart.lengthSmallStep;
            }

            if (pPart.diameterMin == pPart.diameterMax)
                Fields["diameter"].guiActiveEditor = false;
            else
            {
                UI_FloatEdit diameterEdit = (UI_FloatEdit)Fields["diameter"].uiControlEditor;
                diameterEdit.maxValue = pPart.diameterMax;
                diameterEdit.minValue = pPart.diameterMin;
                diameterEdit.incrementLarge = pPart.diameterLargeStep;
                diameterEdit.incrementSmall = pPart.diameterSmallStep;
            }
        }
コード例 #29
0
        public override void OnStart(StartState state)
        {
            if (!String.IsNullOrEmpty(Pivot1Name) && !String.IsNullOrEmpty(Pivot2Name)) {
                ForceTransform = part.FindModelTransform(Pivot2Name);
                BreakTransform = part.FindModelTransform(Pivot1Name);
            } else {
                RTUtil.Log("ModuleRTAntennaAnimated: Pivot error");
                enabled = false;
                return;
            }

            if (IsRTBroken) {
                TrackingMode = TrackingModes.Broken;
            }

            base.OnStart(state);

            if (RTCore.Instance != null) {
                mPivot1 = new Pivot(BreakTransform, Pivot1Speed, Pivot1Range);
                mPivot2 = new Pivot(ForceTransform, Pivot2Speed, Pivot2Range);

                if (IsRTActive) {
                    TrackingMode = TrackingModes.Tracking;
                    mPivot1.SnapToTarget(new DynamicTarget(RTAntennaTargetGuid));
                    mPivot2.SnapToTarget(new DynamicTarget(RTAntennaTargetGuid));
                }
            }
        }
コード例 #30
0
 void Awake()
 {
     startState = new StartState(this);
     inLapState = new InLapState(this);
     finishState = new FinishState(this);
     ;
 }
コード例 #31
0
 protected override void hideEditorGUI(StartState state)
 {
     hideEditorButtons();
 }
コード例 #32
0
ファイル: TrueSyncManager.cs プロジェクト: laijingquan/TS2.0
        void Start()
        {
            instance = this;
            Application.runInBackground = true;

            //离线状态 就AbstractLockstep的OnEventDataReceived接收网络数据不会执行
            //更换网络接口 可以从ICommunicator接口 入手
            ICommunicator communicator = null;

            if (!PhotonNetwork.connected || !PhotonNetwork.inRoom)
            {
                Debug.LogWarning("You are not connected to Photon. TrueSync will start in offline mode.");
            }
            else
            {
                communicator = new PhotonTrueSyncCommunicator(PhotonNetwork.networkingPeer);
            }

            TrueSyncConfig activeConfig = ActiveConfig;

            lockstep = AbstractLockstep.NewInstance(
                lockedTimeStep.AsFloat(),
                communicator,
                PhysicsManager.instance,
                activeConfig.syncWindow,
                activeConfig.panicWindow,
                activeConfig.rollbackWindow,
                OnGameStarted,
                OnGamePaused,
                OnGameUnPaused,
                OnGameEnded,
                OnPlayerDisconnection,
                OnStepUpdate,
                GetLocalData,
                ProvideInputData
                );

            if (ReplayRecord.replayMode == ReplayMode.LOAD_REPLAY)
            {
                ReplayPicker.replayToLoad.Load();

                ReplayRecord replayRecord = ReplayRecord.replayToLoad;
                if (replayRecord == null)
                {
                    Debug.LogError("Replay Record can't be loaded");
                    gameObject.SetActive(false);
                    return;
                }
                else
                {
                    lockstep.ReplayRecord = replayRecord;
                }
            }

            if (activeConfig.showStats)
            {
                this.gameObject.AddComponent <TrueSyncStats>().Lockstep = lockstep;
            }

            scheduler = new CoroutineScheduler(lockstep);

            if (ReplayRecord.replayMode != ReplayMode.LOAD_REPLAY)
            {
                if (communicator == null)
                {
                    lockstep.AddPlayer(0, "Local_Player", true);
                }
                else
                {
                    List <PhotonPlayer> players = new List <PhotonPlayer>(PhotonNetwork.playerList);
                    players.Sort(UnityUtils.playerComparer);

                    for (int index = 0, length = players.Count; index < length; index++)
                    {
                        PhotonPlayer p = players[index];
                        lockstep.AddPlayer((byte)p.ID, p.NickName, p.IsLocal); //更新players activePlayers
                    }
                }
            }

            //搜寻场景预先挂载的TrueSyncBehaviour脚本,为它生成TrueSyncManagedBehaviour脚本
            //可能这部分脚本有些属于玩家 有些属于公共部分,都根据OwnerIndex来区分
            TrueSyncBehaviour[] behavioursArray = FindObjectsOfType <TrueSyncBehaviour>();
            for (int index = 0, length = behavioursArray.Length; index < length; index++)
            {
                generalBehaviours.Add(NewManagedBehavior(behavioursArray[index]));//一个TrueSyncBehaviour对应TrueSyncManagedBehaviour
            }

            initBehaviors();                                //初始化玩家prefab和挂在prefab上的TrueSyncBehaviour
            initGeneralBehaviors(generalBehaviours, false); //公用和玩家的区分,公用分给generalBehaviours,玩家分给behaviorsByPlayer

            PhysicsManager.instance.OnRemoveBody(OnRemovedRigidBody);

            startState = StartState.BEHAVIOR_INITIALIZED;//初始化完毕状态
        }
コード例 #33
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            if (!string.IsNullOrEmpty(macTriggerName))
            {
                macTriggerTransform = this.part.FindModelTransform(macTriggerName);
            }

            //Generate an identifier if needed. This is used for payload transactions.
            if (uniqueIdentifier == kNoIdentifier)
            {
                uniqueIdentifier = Guid.NewGuid().ToString();
            }

            //Setup pipeline window
            pipelineWidow      = new PipelineWindow();
            pipelineWidow.part = this.part;
            pipelineWidow.blackListedResources    = this.blackListedResources;
            pipelineWidow.maxKineticEnergy        = this.maxKineticEnergy;
            pipelineWidow.fuelMassFraction        = this.fuelMassFraction;
            pipelineWidow.dryMassFraction         = this.dryMassFraction;
            pipelineWidow.dataCostPerKm           = this.dataCostPerKm;
            pipelineWidow.orbitalCostMultiplier   = this.orbitalCostMultiplier;
            pipelineWidow.electricityCostPerTonne = this.electricityCostPerTonne;
            pipelineWidow.allowOrbitToGround      = this.allowOrbitToGround;
            pipelineWidow.totalGuidanceData       = this.totalGuidanceData;
            pipelineWidow.setGuidanceDataAmount   = setGuidanceDataAmount;
            pipelineWidow.maxLaunchAzimuth        = this.maxLaunchAzimuth;

            //Get resource definition for electric charge
            if (activationCostEC > 0f)
            {
                PartResourceDefinitionList definitions = PartResourceLibrary.Instance.resourceDefinitions;
                if (definitions.Contains("ElectricCharge"))
                {
                    resourceDef = definitions["ElectricCharge"];
                }
                else
                {
                    return;
                }
            }

            //Setup events
            packingBox = this.part.FindModuleImplementing <WBIPackingBox>();
            if (packingBox != null)
            {
                packingBox.onPackingStateChanged += onPackingStateChanged;
                onPackingStateChanged(packingBox.isDeployed);
            }
            else
            {
                this.Events["ToggleSendGUI"].active = true;
            }

            //Setup GUI
            if (IsActivated)
            {
                Events["ToggleActivation"].guiName = kPowerOff;
            }
            else
            {
                Events["ToggleActivation"].guiName = kPowerOn;
            }

            //If we have any deliveries then grab them and distribute the resources.
            processDeliveries();
        }
コード例 #34
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     initialize();
 }
コード例 #35
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     this.Log("ThrusterTransforms:\n{}",
              thrusterTransforms.Aggregate("", (s, t) => s + t.name + ": " + t.position + "\n"));
 }
コード例 #36
0
 partial void OnStartRF(StartState state);
        //==========================================
        // Methods
        //==========================================

        /// <summary>
        /// Initialize the module
        /// </summary>
        /// <param name="state">The start state of the part</param>
        public override void OnStart(StartState state)
        {
            initReferences();
        }
コード例 #38
0
 public override void OnStart(StartState state)
 {
     Events["DisableTransfer"].active = transferEnabled;
     Events["EnableTransfer"].active  = !transferEnabled;
 }
コード例 #39
0
 public override void OnStart(StartState state)
 {
     part.force_activate();
     base.OnStart(state);
 }
コード例 #40
0
        public override void OnStart(StartState state)
        {
            if (!HighLogic.LoadedSceneIsEditor && !HighLogic.LoadedSceneIsFlight || !CompatibilityChecker.IsAllCompatible)
            {
                return;
            }
            //Identification of the RealChuteModule
            if (this.part.Modules.Contains("RealChuteModule"))
            {
                this.rcModule = (RealChuteModule)this.part.Modules["RealChuteModule"];
            }
            else
            {
                return;
            }
            this.secondaryChute = this.rcModule.SecondaryChute;
            if (!string.IsNullOrEmpty(this.textureLibrary))
            {
                TextureLibrary.Instance.TryGetConfig(this.textureLibrary, ref this.textures);
            }
            this.body = AtmoPlanets.Instance.GetBody(this.planets);

            //Initializes ChuteTemplates
            if (this.chutes.Count <= 0)
            {
                if (this.node == null && !PersistentManager.Instance.TryGetNode <ProceduralChute>(this.part.name, ref this.node))
                {
                    return;
                }
                LoadChutes();
            }
            this.chutes.ForEach(c => c.Initialize());
            if (this.sizes.Count <= 0)
            {
                this.sizes = PersistentManager.Instance.GetSizes(this.part.partInfo.name);
            }

            //Creates an instance of the texture library
            this.editorGUI = new EditorGUI(this);
            if (HighLogic.LoadedSceneIsEditor)
            {
                //Windows initiation
                this.editorGUI.window = new Rect(5, 390, 420, Screen.height - 395);
                this.chutes.ForEach(c =>
                {
                    c.templateGUI.materialsWindow = new Rect(this.editorGUI.matX, this.editorGUI.matY, 375, 275);
                    c.templateGUI.drag            = new Rect(0, 0, 375, 25);
                });
                this.editorGUI.failedWindow         = new Rect((Screen.width / 2) - 150, (Screen.height / 2) - 150, 300, 300);
                this.editorGUI.successfulWindow     = new Rect((Screen.width / 2) - 150, (Screen.height / 2) - 25, 300, 50);
                this.editorGUI.presetsWindow        = new Rect((Screen.width / 2) - 200, (Screen.height / 2) - 250, 400, 500);
                this.editorGUI.presetsSaveWindow    = new Rect((Screen.width / 2) - 175, (Screen.height / 2) - 110, 350, 220);
                this.editorGUI.presetsWarningWindow = new Rect((Screen.width / 2) - 100, (Screen.height / 2) - 50, 200, 100);

                if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
                {
                    float level = 0;
                    bool  isVab = true;
                    switch (EditorDriver.editorFacility)
                    {
                    case EditorFacility.VAB:
                        level = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding); break;

                    case EditorFacility.SPH:
                        level = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar); isVab = false; break;
                    }
                    if (GameVariables.Instance.UnlockedActionGroupsStock(level, isVab))
                    {
                        this.Events.ForEach(e => e.guiActiveEditor = false);
                    }
                }
                else
                {
                    this.Events.ForEach(e => e.guiActiveEditor = false);
                }

                //Gets the original part state
                if (this.textures != null && this.caseId == -1)
                {
                    if (this.caseId == -1)
                    {
                        if (this.textures.TryGetCase(this.currentCase, ref this.parachuteCase))
                        {
                            this.caseId = this.textures.GetCaseIndex(this.parachuteCase.Name);
                        }
                    }
                    else
                    {
                        this.textures.TryGetCase(this.caseId, this.type, ref this.parachuteCase);
                    }
                    this.lastCaseId = this.caseId;
                }

                if (!this.initiated)
                {
                    if (!AtmoPlanets.Instance.TryGetBodyIndex("Kerbin", ref this.planets))
                    {
                        this.planets = 0;
                    }
                    this.body = AtmoPlanets.Instance.GetBody(this.planets);

                    //Identification of the values from the RealChuteModule
                    this.mustGoDown     = this.rcModule.mustGoDown;
                    this.deployOnGround = this.rcModule.deployOnGround;
                    this.timer          = this.rcModule.timer + "s";
                    this.cutSpeed       = this.rcModule.cutSpeed.ToString();
                    this.delayBeforeCut = this.rcModule.delayBeforeCut.ToString();
                    if (this.rcModule.spareChutes != -1)
                    {
                        this.spares = this.rcModule.spareChutes.ToString();
                    }
                    this.originalSize = this.part.transform.GetChild(0).localScale;
                    this.initiated    = true;
                }
            }
            else if (this.textures != null)
            {
                this.textures.TryGetCase(this.caseId, this.type, ref this.parachuteCase);
                this.lastCaseId = this.caseId;
            }

            if (this.parent == null)
            {
                this.parent = this.part.FindModelTransform(this.rcModule.parachutes[0].parachuteName).parent;
            }

            //Updates the part
            if (this.textures != null)
            {
                UpdateCaseTexture(this.rcModule);
                this.editorGUI.cases    = this.textures.CaseNames;
                this.editorGUI.canopies = this.textures.CanopyNames;
                this.editorGUI.models   = this.textures.ModelNames;
            }
            UpdateScale(this.part, this.rcModule);
        }
コード例 #41
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            ShowParticleEffect(isActivated);
        }
コード例 #42
0
        public override void OnStart(StartState state)
        {
            powerSupply = part.FindModuleImplementing <IPowerSupply>();

            if (powerSupply != null)
            {
                powerSupply.DisplayName = Localizer.Format("#LOC_KSPIE_Refinery_started"); //"started"
            }
            if (state == StartState.Editor)
            {
                return;
            }

            // load stored overflow setting
            _overflowAllowed = lastOverflowSettings;

            _windowId = new System.Random(part.GetInstanceID()).Next(int.MinValue, int.MaxValue);

            var refineriesList = part.FindModulesImplementing <IRefineryActivity>().ToList();

            if (refineryType > 0)
            {
                AddIfMissing(refineriesList, new AluminiumElectrolyzer());
                AddIfMissing(refineriesList, new AmmoniaElectrolyzer());
                AddIfMissing(refineriesList, new AnthraquinoneProcessor());
                AddIfMissing(refineriesList, new AtmosphereProcessor());
                AddIfMissing(refineriesList, new CarbonDioxideElectrolyzer());
                AddIfMissing(refineriesList, new HaberProcess());
                AddIfMissing(refineriesList, new HeavyWaterElectrolyzer());
                AddIfMissing(refineriesList, new PartialMethaneOxidation());
                AddIfMissing(refineriesList, new PeroxideProcess());
                AddIfMissing(refineriesList, new UF4Ammonolysiser());
                AddIfMissing(refineriesList, new RegolithProcessor());
                AddIfMissing(refineriesList, new ReverseWaterGasShift());
                AddIfMissing(refineriesList, new NuclearFuelReprocessor());
                AddIfMissing(refineriesList, new SabatierReactor());
                AddIfMissing(refineriesList, new OceanProcessor());
                AddIfMissing(refineriesList, new SolarWindProcessor());
                AddIfMissing(refineriesList, new WaterElectrolyzer());
                AddIfMissing(refineriesList, new WaterGasShift());

                availableRefineries = refineriesList
                                      .Where(m => ((int)m.RefineryType & refineryType) == (int)m.RefineryType)
                                      .OrderBy(a => a.ActivityName).ToList();
            }
            else
            {
                availableRefineries = refineriesList.OrderBy(a => a.ActivityName).ToList();
            }

            // initialize refineries
            availableRefineries.ForEach(m => m.Initialize(part, this));

            foreach (var availableRefinery in availableRefineries)
            {
                try
                {
                    availableRefinery.Initialize(part, this);
                }
                catch (Exception e)
                {
                    Debug.LogError("[KSPI]: Failed to initialized " + availableRefinery.ActivityName + " with exception: " + e.Message);
                }
            }

            // load same
            if (refinery_is_enabled && !string.IsNullOrEmpty(lastActivityName))
            {
                Debug.Log("[KSPI]: ISRU Refinery looking to restart " + lastActivityName);
                currentActivity = availableRefineries.FirstOrDefault(a => a.ActivityName == lastActivityName);

                if (currentActivity == null)
                {
                    Debug.Log("[KSPI]: ISRU Refinery looking to restart " + lastClassName);
                    currentActivity = availableRefineries.FirstOrDefault(a => a.GetType().Name == lastClassName);
                }
            }

            if (currentActivity != null)
            {
                bool hasRequirement = currentActivity.HasActivityRequirements();
                lastActivityName = currentActivity.ActivityName;

                Debug.Log("[KSPI]: ISRU Refinery initializing " + lastActivityName + " for which hasRequirement: " + hasRequirement);

                var timeDifference = (Planetarium.GetUniversalTime() - lastActiveTime);

                if (timeDifference > 0.01)
                {
                    string message = Localizer.Format("#LOC_KSPIE_Refinery_Postmsg1", lastActivityName, timeDifference.ToString("0")); //"IRSU performed " +  + " for " +  + " seconds"
                    Debug.Log("[KSPI]: " + message);
                    ScreenMessages.PostScreenMessage(message, 20, ScreenMessageStyle.LOWER_CENTER);
                }

                var productionModifier = productionMult * baseProduction;
                if (lastActivityName == "Atmospheric Extraction")
                {
                    ((AtmosphereProcessor)currentActivity).ExtractAir(lastPowerRatio * productionModifier,
                                                                      lastPowerRatio, productionModifier, lastOverflowSettings, timeDifference, true);
                }
                else if (lastActivityName == "Seawater Extraction")
                {
                    ((OceanProcessor)currentActivity).ExtractSeawater(lastPowerRatio * productionModifier,
                                                                      lastPowerRatio, productionModifier, lastOverflowSettings, timeDifference, true);
                }
                else
                {
                    currentActivity.UpdateFrame(lastPowerRatio * productionModifier, lastPowerRatio,
                                                productionModifier, lastOverflowSettings, timeDifference, true);
                }
            }
        }
コード例 #43
0
 public override void OnStart(StartState state)
 {
     liftEngineActive          = false;
     FSHoverDoLift.totalThrust = 0;
 }
コード例 #44
0
        //the part that is enabled and disabled
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            string[] nodenames           = nodeNames.Split(',');
            string[] transformGroupNames = transormNames.Split(',');

            List <string[]> transformnames = new List <string[]>();

            //when the lengths are not equal
            if (transformGroupNames.Length != nodenames.Length)
            {
                return;
            }

            //----------------------------------------------------------
            //create the list of transforms to be made visible on attach
            //----------------------------------------------------------

            //remove the whitespaces
            for (int i = 0; i < nodenames.Length; i++)
            {
                nodenames[i] = nodenames[i].Trim();

                //split up the names for the nodes
                string[] transformGroup = transformGroupNames[i].Split('|');

                for (int j = 0; j < transformGroup.Length; j++)
                {
                    transformGroup[j] = transformGroup[j].Trim();
                }
                transformnames.Add(transformGroup);
            }

            int num = 0;

            foreach (string nodeName in nodenames)
            {
                AttachNode node = part.findAttachNode(nodeName);

                List <Transform> transforms = new List <Transform>();
                for (int k = 0; k < transformnames[num].Length; k++)
                {
                    transforms.AddRange(part.FindModelTransforms(transformnames[num][k]));
                }

                //when nodes and transforms are valid and found
                if ((node != null) && (transforms.Count > 0))
                {
                    //create the new corridor data
                    CorridorPart corridor = new CorridorPart();
                    corridor.node       = node;
                    corridor.transforms = transforms;

                    if ((allowSurfaceAttach) && (surfaceAttachNode == nodeName) && (part.srfAttachNode != null))
                    {
                        corridor.isSurfaceAttachPoint = true;
                    }
                    else
                    {
                        corridor.isSurfaceAttachPoint = false;
                    }

                    corridor.lastAttached = true;
                    corridors.Add(corridor);
                }
                num++;
            }

            //------------------------------------------------------------
            //create the list of transforms to be made invisible on attach
            //------------------------------------------------------------
            string[]        replaceTransformGroupNames = null;
            string[]        replaceNodeGroupNames      = null;
            List <string[]> replacetransformnames      = new List <string[]>();
            List <string[]> replacenodenames           = new List <string[]>();

            if ((replaceTransformNames != string.Empty) && (replaceNodeNames != string.Empty))
            {
                replaceTransformGroupNames = replaceTransformNames.Split(',');
                replaceNodeGroupNames      = replaceNodeNames.Split(',');


                if (replaceNodeGroupNames.Length == replaceTransformGroupNames.Length)
                {
                    //split up all the name for the groups
                    for (int i = 0; i < replaceNodeGroupNames.Length; i++)
                    {
                        //split up the names for the nodes
                        string[] transformGroup = replaceTransformGroupNames[i].Split('|');
                        for (int j = 0; j < transformGroup.Length; j++)
                        {
                            transformGroup[j] = transformGroup[j].Trim();
                        }
                        replacetransformnames.Add(transformGroup);

                        string[] nodeGroup = replaceNodeGroupNames[i].Split('|');
                        for (int j = 0; j < nodeGroup.Length; j++)
                        {
                            nodeGroup[j] = nodeGroup[j].Trim();
                        }
                        replacenodenames.Add(nodeGroup);
                    }


                    //for all transform groups
                    num = 0;
                    foreach (string[] tNames in replacetransformnames)
                    {
                        List <Transform>  rTransforms  = new List <Transform>();
                        List <AttachNode> rAttachnodes = new List <AttachNode>();

                        foreach (string tName in tNames)
                        {
                            Debug.Log("[KPBS] Replace Tranform Name: " + tName);
                            rTransforms.AddRange(part.FindModelTransforms(tName));
                        }
                        foreach (string nName in replacenodenames[num])
                        {
                            Debug.Log("[KPBS] Replace Node Name: " + nName);
                            rAttachnodes.Add(part.findAttachNode(nName));
                        }

                        if ((rTransforms.Count > 0) && (rAttachnodes.Count > 0))
                        {
                            ReplacedPart rp = new ReplacedPart();
                            rp.nodes      = rAttachnodes;
                            rp.transforms = rTransforms;
                            replaceParts.Add(rp);
                        }
                        num++;
                    }
                }
            }
            //check the visibility of all the parts
            updateAllCorridors();
        }
コード例 #45
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            Fields["dailyOutput"].guiName = "Max Recycling";
        }
コード例 #46
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state); thrustDisplay = all_thrusts();
 }
コード例 #47
0
 public override void OnStart(StartState state)
 {
     Events["ScrapPart"].unfocusedRange = EVARange;
     Events["ScrapPart"].guiName        = Menu;
     base.OnStart(state);
 }
コード例 #48
0
        // Runs on PartModule startup.
        public override void OnStart(StartState state)
        {
            // Startup the PartModule stuff first.
            base.OnStart(state);

            // Fetch the solar panel module from the part.
            if (this.part.tryGetFirstModuleByName(this.moduleType, out this.panelModule))
            {
                // Set our state trackers to the opposite of our states, to force first-run updates.
                this.sunTrackingState = !this.sunTrackingEnabled;

                // Fetch the UnityEngine.Animation object from the solar panel module.
                Animation anim = this.panelModule.GetComponentInChildren <Animation>();

                // If the animation is null, bailout.
                if (anim != null)
                {
                    this.LogDebug("Animation is not null; wrapping.");
                    if (animationNameField == null)
                    {
                        animationNameField = this.panelModule.GetType().GetField("animationName");
                    }

                    // Build an ToadicusTools.
                    this.panelAnimation = new ToadicusTools.AnimationWrapper(
                        anim,
                        (string)animationNameField.GetValue(this.panelModule),
                        ToadicusTools.PlayDirection.Forward
                        );
                }

                // Yay debugging!
                this.LogDebug("panelAnimation: " + this.panelAnimation);

                // If we are in the editor and have an animation...
                if (HighLogic.LoadedSceneIsEditor && this.panelAnimation != null)
                {
                    // ...pre-set the panel's currentRotation...

                    if (originalRotationField == null)
                    {
                        originalRotationField = this.panelModule.GetType().GetField("originalRotation");
                    }

                    if (currentRotationField == null)
                    {
                        currentRotationField = this.panelModule.GetType().GetField("currentRotation");
                    }

                    currentRotationField.SetValue(this.panelModule, originalRotationField.GetValue(this.panelModule));
                }

                /*
                 * Checks whether this panel is a sun tracking panel or not.  Despite its name, ModuleDeployableSolarPanel
                 * is used for all (most?) solar panels, even those that don't deploy or rotate.
                 * */
                // If the panel is sun tracking panel...
                if (sunTrackingField == null)
                {
                    sunTrackingField = this.panelModule.GetType().GetField("sunTracking");
                }

                bool moduleIsSunTracking = (bool)sunTrackingField.GetValue(this.panelModule);

                if (moduleIsSunTracking)
                {
                    if (trackingSpeedField == null)
                    {
                        trackingSpeedField = this.panelModule.GetType().GetField("trackingSpeed");
                    }

                    // ...go fetch the tracking speed and make sure our tracking tweakable is active.
                    this.baseTrackingSpeed = (float)trackingSpeedField.GetValue(this.panelModule);
                    this.Fields["sunTrackingEnabled"].guiActive       = true;
                    this.Fields["sunTrackingEnabled"].guiActiveEditor = true;
                }
                else
                {
                    // ...otherwise, make sure our tracking code and tweakable are inactive.
                    this.sunTrackingEnabled = false;
                    this.sunTrackingState   = false;
                    this.Fields["sunTrackingEnabled"].guiActive       = false;
                    this.Fields["sunTrackingEnabled"].guiActiveEditor = false;
                }
            }
        }
コード例 #49
0
        public override void OnStart(StartState state)
        {
            _deploymentAnimation = part.FindModuleImplementing <ModuleAnimateGeneric>();

            part.OnJustAboutToBeDestroyed += OnJustAboutToBeDestroyed;
            part.OnJustAboutToDie         += OnJustAboutToDie;

            _antimatterDefinition = PartResourceLibrary.Instance.GetDefinition(resourceName);

            _antimatterDensityModifier = 1e-17 / _antimatterDefinition.density;

            antimatterDensity = _antimatterDefinition.density;

            var antimatterResource = part.Resources[resourceName];

            if (antimatterResource == null)
            {
                var alternativeResource = part.Resources.OrderBy(m => m.maxAmount).FirstOrDefault();
                if (alternativeResource != null)
                {
                    antimatterResource = alternativeResource;
                }
                else
                {
                    return;
                }
            }

            // determine TechLevel maximum storage amount only in editor
            if (state == StartState.Editor && maxStorage != 0)
            {
                DetermineTechLevel();
                var currentStorageRatio = antimatterResource.amount / antimatterResource.maxAmount;
                antimatterResource.maxAmount = maxStorage * storedResourceCostMultiplier * StorageCapacityModifier;
                antimatterResource.amount    = antimatterResource.maxAmount * currentStorageRatio;
            }

            // charge if there is any significant antimatter
            _shouldCharge = antimatterResource.amount > _minimumAntimatterAmount;

            partMass    = part.mass;
            initialMass = part.prefabMass * storedMassMultiplier;

            Fields[nameof(techLevel)].guiActiveEditor = maxStorage != 0;
            _capacityStrField    = Fields[nameof(capacityStr)];
            _maxAmountStrField   = Fields[nameof(maxAmountStr)];
            _temperatureStrField = Fields[nameof(TemperatureStr)];
            _geeforceStrField    = Fields[nameof(GeeforceStr)];

            _geeforceQueue.Enqueue(0);
            if (state == StartState.Editor)
            {
                part.OnEditorAttach += OnEditorAttach;
                part.OnEditorDetach += OnEditorDetach;

                UpdateTargetMass();
                return;
            }
            else
            {
                UpdateTargetMass();
            }

            this.enabled = true;

            UpdateTolerances();

            UpdateAttachedTanks();
        }
コード例 #50
0
        public override void OnStart(StartState state)
        {
            if (!HighLogic.LoadedSceneIsEditor && !HighLogic.LoadedSceneIsFlight)
            {
                return;
            }
            if (!CompatibilityChecker.IsAllCompatible)
            {
                foreach (BaseAction a in this.Actions)
                {
                    a.active = false;
                }
                foreach (BaseEvent e in this.Events)
                {
                    e.active          = false;
                    e.guiActive       = false;
                    e.guiActiveEditor = false;
                }
                this.Fields["chuteCount"].guiActive = false;
                return;
            }
            //Staging icon
            this.part.stagingIcon = "PARACHUTES";

            //Part GUI
            if (this.spareChutes < 0)
            {
                this.Fields["chuteCount"].guiActive = false;
            }
            if (!this.SecondaryChute)
            {
                this.Actions["ActionCut"].guiName = "Cut chute";
                this.Cut.guiName = "Cut chute";
            }
            this.Actions["ActionArm"].active = !RealChuteSettings.Instance.AutoArm;

            //Initiates the Parachutes
            if (this.parachutes.Count <= 0)
            {
                if (this.node == null && !PersistentManager.Instance.TryGetNode <RealChuteModule>(this.part.name, ref this.node))
                {
                    return;
                }
                LoadParachutes();
            }
            this.parachutes.ForEach(p => p.Initialize());

            //First initiation of the part
            if (!this.initiated)
            {
                this.initiated = true;
                this.armed     = false;
                if (this.spareChutes >= 0)
                {
                    this.chuteCount = (int)this.spareChutes;
                }
            }

            //Flight loading
            if (HighLogic.LoadedSceneIsFlight)
            {
                Random random = new Random();
                this.parachutes.ForEach(p => p.randomTime = (float)random.NextDouble());

                //Hide/show UI event addition
                GameEvents.onHideUI.Add(HideUI);
                GameEvents.onShowUI.Add(ShowUI);

                if (this.CanRepack)
                {
                    SetRepack();
                }
            }

            //GUI
            this.window = new Rect(200, 100, 350, 400);
            this.drag   = new Rect(0, 0, 350, 30);
        }
コード例 #51
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);
            initialize();
            this.updateUIFloatEditControl(nameof(currentTopDiameter), minDiameter, maxDiameter, diameterIncrement * 2, diameterIncrement, diameterIncrement * 0.05f, true, currentTopDiameter);
            this.updateUIFloatEditControl(nameof(currentBottomDiameter), minDiameter, maxDiameter, diameterIncrement * 2, diameterIncrement, diameterIncrement * 0.05f, true, currentBottomDiameter);
            this.updateUIFloatEditControl(nameof(currentHeight), minHeight, maxHeight, heightIncrement * 2, heightIncrement, heightIncrement * 0.05f, true, currentHeight);
            this.updateUIFloatEditControl(nameof(currentTaperHeight), minHeight, maxHeight, heightIncrement * 2, heightIncrement, heightIncrement * 0.05f, true, currentTaperHeight);

            Action <SSTUInterstageDecoupler> rebuild = delegate(SSTUInterstageDecoupler m)
            {
                m.updateEditorFields();
                m.buildFairing();
                m.updateEnginePositionAndScale();
                m.updateNodePositions(true);
                m.updatePartMass();
                m.updateShielding();
                m.updateDragCubes();
                m.updateFairingTextureSet(false);
            };

            Fields[nameof(currentTopDiameter)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    if (m != this)
                    {
                        m.currentTopDiameter = this.currentTopDiameter;
                    }
                    rebuild(m);
                });
            };
            Fields[nameof(currentBottomDiameter)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    if (m != this)
                    {
                        m.currentBottomDiameter = this.currentBottomDiameter;
                    }
                    rebuild(m);
                });
            };
            Fields[nameof(currentHeight)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    if (m != this)
                    {
                        m.currentHeight = this.currentHeight;
                    }
                    rebuild(m);
                });
            };
            Fields[nameof(currentTaperHeight)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    if (m != this)
                    {
                        m.currentTaperHeight = this.currentTaperHeight;
                    }
                    rebuild(m);
                });
            };
            Fields[nameof(editorTransparency)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    if (m != this)
                    {
                        m.editorTransparency = this.editorTransparency;
                    }
                    m.fairingBase.setOpacity(m.editorTransparency ? 0.25f : 1);
                });
            };
            Fields[nameof(generateColliders)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    if (m != this)
                    {
                        m.generateColliders = this.generateColliders;
                    }
                    if (m.fairingBase.generateColliders != m.generateColliders)
                    {
                        m.fairingBase.generateColliders = m.generateColliders;
                        m.buildFairing();
                        m.updateFairingTextureSet(false);
                    }
                });
            };

            Fields[nameof(currentTextureSet)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    m.currentTextureSet = currentTextureSet;
                    m.updateFairingTextureSet(!SSTUGameSettings.persistRecolor());
                });
            };

            Fields[nameof(currentEngineModel)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                engineModels.modelSelected(a, b);
                this.actionWithSymmetry(m =>
                {
                    //model selected action sets vars on symmetry parts
                    rebuild(m);
                    m.reInitEngineModule();
                    SSTUModInterop.updateResourceVolume(m.part);
                });
            };
            Fields[nameof(currentEngineScale)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                this.actionWithSymmetry(m =>
                {
                    if (m != this)
                    {
                        m.currentEngineScale = this.currentEngineScale;
                    }
                    rebuild(m);
                    SSTUModInterop.updateResourceVolume(m.part);
                });
            };
            Fields[nameof(currentEngineLayout)].uiControlEditor.onFieldChanged = delegate(BaseField a, System.Object b)
            {
                engineModels.layoutSelected(a, b);
                this.actionWithSymmetry(m =>
                {
                    m.reInitEngineModule();
                    m.updatePartMass();
                    m.updateDragCubes();
                    SSTUModInterop.updateResourceVolume(m.part);
                });
            };
            Fields[nameof(currentEngineTextureSet)].uiControlEditor.onFieldChanged = engineModels.textureSetSelected;
            Fields[nameof(currentEngineTextureSet)].guiActiveEditor = engineModels.definition.textureSets.Length > 1;

            GameEvents.onEditorShipModified.Add(new EventData <ShipConstruct> .OnEvent(onEditorShipModified));
            SSTUModInterop.onPartGeometryUpdate(part, true);
            SSTUModInterop.updateResourceVolume(part);
        }
        //private AvailablePart availablePart;
        //private Part prefab_available_part;
        //private FNGeneratorAdapterVariable prefab_generator_module;

        public override void OnStart(StartState state)
        {
            try
            {
                if (state == StartState.Editor)
                {
                    return;
                }

                //InitializePartModule();

                var modules = part.FindModulesImplementing <ModuleGenerator>();

                moduleGenerator = modules.Count > index ? modules[index] : null;

                if (moduleGenerator == null)
                {
                    return;
                }

                String[] resources_to_supply = { ResourceManager.FNRESOURCE_MEGAJOULES };
                this.resources_to_supply = resources_to_supply;
                base.OnStart(state);

                if (maintainsBuffer)
                {
                    resourceBuffers = new ResourceBuffers();
                }

                outputType = ResourceType.other;
                inputType  = ResourceType.other;

                foreach (ModuleResource moduleResource in moduleGenerator.resHandler.inputResources)
                {
                    if (moduleResource.name == ResourceManager.FNRESOURCE_MEGAJOULES)
                    {
                        inputType = ResourceType.megajoule;
                    }
                    else if (moduleResource.name == ResourceManager.STOCK_RESOURCE_ELECTRICCHARGE)
                    {
                        inputType = ResourceType.electricCharge;
                    }

                    if (inputType != ResourceType.other)
                    {
                        moduleInputResource = moduleResource;

                        if (inputRate != 0)
                        {
                            moduleInputResource.rate = inputRate;
                        }

                        initialInputAmount = moduleInputResource.rate;

                        break;
                    }
                }

                if (offlineProcessing && moduleInputResource != null && last_active_time > 0 && powerGeneratorPowerInput > 0)
                {
                    var timePassedSinceLastProcessing = Planetarium.GetUniversalTime() - last_active_time;

                    var consumption = timePassedSinceLastProcessing * powerGeneratorPowerInput;

                    part.RequestResource(moduleInputResource.name, consumption);

                    var message = timePassedSinceLastProcessing + " seconds passed durring which " + consumption + " " + moduleInputResource.name + " was consumed ";

                    Debug.Log("[KSPI]: " + message);
                }

                foreach (ModuleResource moduleResource in moduleGenerator.resHandler.outputResources)
                {
                    // assuming only one of those two is present
                    if (moduleResource.name == ResourceManager.FNRESOURCE_MEGAJOULES)
                    {
                        outputType = ResourceType.megajoule;
                    }
                    else if (moduleResource.name == ResourceManager.STOCK_RESOURCE_ELECTRICCHARGE)
                    {
                        outputType = ResourceType.electricCharge;
                    }

                    if (outputType != ResourceType.other)
                    {
                        if (maintainsBuffer)
                        {
                            var bufferResource = part.Resources[moduleResource.name];
                            if (bufferResource != null)
                            {
                                if (initialMaxBufferSize == 0)
                                {
                                    initialMaxBufferSize = bufferResource.maxAmount;
                                }
                                else
                                {
                                    bufferResource.maxAmount = initialMaxBufferSize;
                                }
                            }

                            resourceBuffers.AddConfiguration(new ResourceBuffers.MaxAmountConfig(moduleResource.name, 50));
                        }

                        mockInputResource      = new ModuleResource();
                        mockInputResource.name = moduleResource.name;
                        mockInputResource.id   = moduleResource.name.GetHashCode();
                        moduleGenerator.resHandler.inputResources.Add(mockInputResource);

                        moduleOutputResource = moduleResource;

                        if (outputRate != 0)
                        {
                            moduleOutputResource.rate = outputRate;
                        }

                        initialOutputAmount = moduleOutputResource.rate;

                        moduleGeneratorEfficienctBaseField = moduleGenerator.Fields["efficiency"];
                        if (moduleGeneratorEfficienctBaseField != null)
                        {
                            moduleGeneratorEfficienctBaseField.guiActive       = false;
                            moduleGeneratorEfficienctBaseField.guiActiveEditor = false;
                        }

                        break;
                    }
                }

                if (maintainsBuffer)
                {
                    resourceBuffers.Init(this.part);
                }

                efficiencyField    = moduleGenerator.Fields["efficiency"];
                displayStatusField = moduleGenerator.Fields["displayStatus"];

                powerGeneratorPowerInputField  = Fields["powerGeneratorPowerInput"];
                powerGeneratorPowerOutputField = Fields["powerGeneratorPowerOutput"];

                if (index > 0)
                {
                    powerGeneratorPowerInputField.guiName  = powerGeneratorPowerInputField.guiName + " " + (index + 1);
                    powerGeneratorPowerOutputField.guiName = powerGeneratorPowerOutputField.guiName + " " + (index + 1);
                }
            }
            catch (Exception e)
            {
                Debug.LogError("[KSPI]: Exception in FNGeneratorAdapter.OnStart " + e.Message);
                throw;
            }
        }
コード例 #53
0
ファイル: Class2.cs プロジェクト: Fengist/MPUtils
 public override void OnStart(StartState state)
 {
     MPLog.Writelog("[Maritime Pack] MPEngine Found on " + vessel.name);
 }
コード例 #54
0
		public override void OnStart (StartState state)
		{
			base.OnStart (state);

			ParseWeaponType();
            ParseBulletDragType();

            bulletBallisticCoefficient = bulletMass / bulletDragArea * 1000;        //1000 to convert from tonnes to kilograms

			if(shortName == string.Empty)
			{
				shortName = part.partInfo.title;
			}

			foreach(var emitter in part.FindModelComponents<KSPParticleEmitter>())
			{
				emitter.emit = false;
			}

			if(airDetonation)
			{
				var detRange = (UI_FloatRange)Fields["defaultDetonationRange"].uiControlEditor;
				detRange.maxValue = maxAirDetonationRange;
			}
			else
			{
				Fields["defaultDetonationRange"].guiActive = false;
				Fields["defaultDetonationRange"].guiActiveEditor = false;
			}

			if(HighLogic.LoadedSceneIsFlight)
			{
				if(eWeaponType != WeaponTypes.Laser)
				{
					if(bulletPool == null)
					{
						SetupBulletPool();
					}
					if(shellPool == null)
					{
						SetupShellPool();
					}
				}

				//setup transforms
				fireTransforms = part.FindModelTransforms(fireTransformName);
				shellEjectTransforms = part.FindModelTransforms(shellEjectTransformName);

				//setup emitters
				foreach(var pe in part.FindModelComponents<KSPParticleEmitter>())
				{
					pe.maxSize *= part.rescaleFactor;
					pe.minSize *= part.rescaleFactor;
					pe.shape3D *= part.rescaleFactor;
					pe.shape2D *= part.rescaleFactor;
					pe.shape1D *= part.rescaleFactor;

					if(pe.useWorldSpace && !oneShotWorldParticles)
					{
						BDAGaplessParticleEmitter gpe = pe.gameObject.AddComponent<BDAGaplessParticleEmitter>();	
						gpe.part = part;
						gaplessEmitters.Add(gpe);
					}
				}

				
				//setup projectile colors
				projectileColorC = Misc.ParseColor255(projectileColor);
				startColorC = Misc.ParseColor255(startColor);
				
				//init and zero points
				targetPosition = Vector3.zero;
				pointingAtPosition = Vector3.zero;
				bulletPrediction = Vector3.zero;

				//setup audio
				SetupAudio();

				//laser setup
				if(eWeaponType == WeaponTypes.Laser)
				{
					SetupLaserSpecifics();
				}
			}
			else if(HighLogic.LoadedSceneIsEditor)
			{
				fireTransforms = part.FindModelTransforms(fireTransformName);
			}

			//turret setup
			foreach(var turr in part.FindModulesImplementing<ModuleTurret>())
			{
				if(turr.turretID == turretID)
				{
					turret = turr;
					break;
				}
			}

			if(!turret)
			{
				Fields["onlyFireInRange"].guiActive = false;
				Fields["onlyFireInRange"].guiActiveEditor = false;
			}


			//setup animations
			if(hasDeployAnim)
			{
				deployState = Misc.SetUpSingleAnimation(deployAnimName, this.part);
				deployState.normalizedTime = 0;
				deployState.speed = 0;
				deployState.enabled = true;
			}
			if(hasFireAnimation)
			{
				fireState = Misc.SetUpSingleAnimation (fireAnimName, this.part);
				fireState.enabled = false;	
			}

			BDArmorySettings.OnVolumeChange += UpdateVolume;
		}
コード例 #55
0
        public override void OnStart(StartState state)
        {
            // extension for feature_engagementenvelope
            InitializeEngagementRange(0, maxTargetingRange);

            if (HighLogic.LoadedSceneIsFlight)
            {
                part.force_activate();

                aimerTexture = BDArmorySetup.Instance.greenPointCircleTexture;
                // GameDatabase.Instance.GetTexture("BDArmory/Textures/grayCircle", false);


                MakeRocketArray();
                UpdateRocketScales();

                if (shortName == string.Empty)
                {
                    shortName = part.partInfo.title;
                }

                UpdateAudio();
                BDArmorySetup.OnVolumeChange += UpdateAudio;
            }

            if (HighLogic.LoadedSceneIsFlight || HighLogic.LoadedSceneIsEditor)
            {
                List <ModuleTurret> .Enumerator turr = part.FindModulesImplementing <ModuleTurret>().GetEnumerator();
                while (turr.MoveNext())
                {
                    if (turr.Current == null)
                    {
                        continue;
                    }
                    if (turr.Current.turretID != turretID)
                    {
                        continue;
                    }
                    turret             = turr.Current;
                    targetInTurretView = false;
                    break;
                }
                turr.Dispose();

                if (turret)
                {
                    Events["GuiFire"].guiActive  = false;
                    Events["Jettison"].guiActive = false;
                    Actions["AGFire"].active     = false;

                    if (HighLogic.LoadedSceneIsFlight)
                    {
                        Events["ToggleTurret"].guiActive = true;
                    }
                }

                if (!string.IsNullOrEmpty(deployAnimationName))
                {
                    deployAnimState    = Misc.Misc.SetUpSingleAnimation(deployAnimationName, part);
                    hasDeployAnimation = true;

                    readyToFire = false;
                }
            }
            SetupAudio();

            blastForce = BlastPhysicsUtils.CalculateExplosiveMass(blastRadius);
        }
コード例 #56
0
 public override void OnStart(StartState state)
 {
     setActive();
 }
コード例 #57
0
 public override void OnStartFinished(StartState state)
 {
     base.OnStartFinished(state);
     StartCoroutine(LateStart());
 }
コード例 #58
0
        public override void OnStart(StartState state)
        {
            _decaySourceDefinition  = PartResourceLibrary.Instance.GetDefinition(resourceName);
            _decayProductDefinition = PartResourceLibrary.Instance.GetDefinition(decayProduct);

            if (_decaySourceDefinition == null)
            {
                return;
            }

            var decayResource = part.Resources[resourceName];

            if (decayResource == null)
            {
                return;
            }

            if (part.vessel != null)
            {
                var compatibleTanks =
                    part.vessel.FindPartModulesImplementing <FNResourceTransfer>()
                    .Where(m => m.resourceName == _decayProductDefinition.displayName);

                _managedTransferableResources.AddRange(compatibleTanks);
            }

            if (halfLifeInYears > 0)
            {
                decayConstant = Math.Log(2) / (halfLifeInYears * LengthYear * SecondsInDay);
            }

            if (halfLifeInDays > 0)
            {
                decayConstant = Math.Log(2) / (halfLifeInDays * SecondsInDay);
            }

            if (_decayProductDefinition != null)
            {
                if (_decayProductDefinition.density > 0 && _decaySourceDefinition.density > 0)
                {
                    _densityRat = (double)(decimal)_decaySourceDefinition.density / (double)(decimal)_decayProductDefinition.density;
                }
            }

            if (state == StartState.Editor || CheatOptions.UnbreakableJoints)
            {
                return;
            }

            if (lastActiveTime < 0)
            {
                lastActiveTime = Planetarium.GetUniversalTime();
            }

            double timeDiffInSeconds = Planetarium.GetUniversalTime() - lastActiveTime;

            if (!(timeDiffInSeconds > 0))
            {
                return;
            }

            double resourceAmount = decayResource.amount;

            decayResource.amount = resourceAmount * Math.Exp(-decayConstant * timeDiffInSeconds);

            if (_decayProductDefinition == null)
            {
                return;
            }

            double resourceChange = resourceAmount - decayResource.amount;

            if (resourceChange <= 0)
            {
                return;
            }

            var decayProductAmount = resourceChange * _densityRat;

            var decayProductResource = part.Resources[decayProduct];

            if (canConvertVolume && decayProductResource != null)
            {
                decayProductResource.amount += decayProductAmount;

                var productOverflow = Math.Max(0, decayProductResource.amount - decayProductResource.maxAmount);
                if (productOverflow > 0)
                {
                    decayProductResource.maxAmount = decayProductResource.amount;
                }

                var previousAmount     = decayResource.maxAmount;
                var appliedDecayAmount = productOverflow / _densityRat;
                decayResource.maxAmount -= appliedDecayAmount;
                var effectiveDecayAmount = previousAmount - decayResource.maxAmount;
                var decayDifference      = appliedDecayAmount - effectiveDecayAmount;

                decayResource.amount = Math.Min(decayResource.amount, decayResource.maxAmount);

                return;
            }

            StoreDecayProduct(decayProductAmount, decayProductResource);
        }
コード例 #59
0
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     engine = new EngineModuleWrapper();
     engine.InitWithEngine(this.part, engineID);
 }
コード例 #60
0
ファイル: KKLModuleVent.cs プロジェクト: craidler/KKL
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     Setup();
 }