コード例 #1
0
 public VirtualTemplate(
     string name,
     OptimizeLevel l,
     TemplateCache cache = null)
 {
     Name = name;
     Cache = cache ?? new TemplateCache();
     TrimMode = TrimMode.FollowingNewLine;
     OptimizeLevel = l;
 }
コード例 #2
0
 public Interpreter(
     string text,
     TemplateCache cache = null)
 {
     Cache = cache ?? new TemplateCache();
     var stream = new ANTLRStringStream(text);
     var lexer = TemplateLexer.Create(stream);
     var tokenStream = new CommonTokenStream(lexer);
     var parser = new TemplateParser(tokenStream)
     {
         TraceDestination = Console.Out,
         Errors = _parserErrors
     };
     var docResult = parser.document();
     _ast = docResult.Tree;
 }
コード例 #3
0
        private static void ProcessGeysers(WorldGen __instance, ref List <KeyValuePair <Vector2I, TemplateContainer> > templateList, SeededRandom myRandom)
        {
            WorldGenReloadedData.CalculateGeysers(myRandom, __instance);
            List <TemplateContainer> featuresList = TemplateCache.CollectBaseTemplateAssets("features/");

            foreach (SubWorld subWorld in WorldGen.Settings.GetSubWorldList())
            {
                Debug.Log("Processing zone: " + subWorld.name);
                if (!WorldGenReloadedData.CalculatedGeysers.ContainsKey(subWorld.name))
                {
                    continue;
                }
                Dictionary <string, int> subworldConfig = WorldGenReloadedData.CalculatedGeysers[subWorld.name];

                if (subWorld.pointsOfInterest != null)
                {
                    foreach (KeyValuePair <string, int> item6 in subworldConfig)
                    {
                        Debug.Log("Processing geyser: [" + item6.Key + "," + item6.Value + "]");
                        for (int numGeysers = 0; numGeysers < item6.Value; numGeysers++)
                        {
                            List <TerrainCell> terrainCellsForTag2 = WorldGen.GetTerrainCellsForTag(subWorld.name.ToTag());
                            for (int num = terrainCellsForTag2.Count - 1; num >= 0; num--)
                            {
                                if (!__instance.IsSafeToSpawnPOI(terrainCellsForTag2[num]))
                                {
                                    terrainCellsForTag2.Remove(terrainCellsForTag2[num]);
                                }
                            }

                            /*
                             * if (terrainCellsForTag2.Count <= 0 && WorldGenReloadedData.Config.ForceSpawnGeyserUnsafePlace)
                             * {
                             *  terrainCellsForTag2 = WorldGen.GetTerrainCellsForTag(subWorld.name.ToTag());
                             * }
                             */
                            Debug.Log("Available cells = " + terrainCellsForTag2.Count);

                            if (terrainCellsForTag2.Count > 0)
                            {
                                string            template          = null;
                                TemplateContainer templateContainer = null;
                                int num2 = 0;

                                /*
                                 * while (templateContainer == null && num2 < item6.Value.Length)
                                 * {
                                 *  template = item6.Value[myRandom.RandomRange(0, item6.Value.Length)];
                                 *  templateContainer = list3.Find((TemplateContainer value) => value.name == template);
                                 *  num2++;
                                 * }
                                 */

                                // Constructs a template using the already existing feature generic geyser. first() cause there is only one feature in the folder. TODO
                                templateContainer = GetGeyserTemplate(featuresList.First(), item6.Key);

                                Debug.Log("Adding geyser: " + templateContainer.name + " [" + item6.Key + "]");
                                if (templateContainer != null)
                                {
                                    //list3.Remove(templateContainer);
                                    bool geyserPlaced = false;
                                    for (int i = 0; i < terrainCellsForTag2.Count; i++)
                                    {
                                        TerrainCell terrainCell = terrainCellsForTag2[myRandom.RandomRange(0, terrainCellsForTag2.Count)];
                                        if (!terrainCell.node.tags.Contains(WorldGenTags.POI))
                                        {
                                            if (!(templateContainer.info.size.Y > terrainCell.poly.MaxY - terrainCell.poly.MinY))
                                            {
                                                List <KeyValuePair <Vector2I, TemplateContainer> > list4 = templateList;
                                                Vector2 vector3 = terrainCell.poly.Centroid();
                                                int     a2      = (int)vector3.x;
                                                Vector2 vector4 = terrainCell.poly.Centroid();
                                                list4.Add(new KeyValuePair <Vector2I, TemplateContainer>(new Vector2I(a2, (int)vector4.y), templateContainer));
                                                terrainCell.node.tags.Add(template.ToTag());
                                                terrainCell.node.tags.Add(WorldGenTags.POI);
                                                geyserPlaced = true;
                                                break;
                                            }
                                            float num3 = templateContainer.info.size.Y - (terrainCell.poly.MaxY - terrainCell.poly.MinY);
                                            float num4 = templateContainer.info.size.X - (terrainCell.poly.MaxX - terrainCell.poly.MinX);
                                            if (terrainCell.poly.MaxY + num3 < (float)Grid.HeightInCells && terrainCell.poly.MinY - num3 > 0f && terrainCell.poly.MaxX + num4 < (float)Grid.WidthInCells && terrainCell.poly.MinX - num4 > 0f)
                                            {
                                                List <KeyValuePair <Vector2I, TemplateContainer> > list5 = templateList;
                                                Vector2 vector5 = terrainCell.poly.Centroid();
                                                int     a3      = (int)vector5.x;
                                                Vector2 vector6 = terrainCell.poly.Centroid();
                                                list5.Add(new KeyValuePair <Vector2I, TemplateContainer>(new Vector2I(a3, (int)vector6.y), templateContainer));
                                                terrainCell.node.tags.Add(template.ToTag());
                                                terrainCell.node.tags.Add(WorldGenTags.POI);
                                                geyserPlaced = true;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            Debug.Log("Cannot find a place for geyser. POI in the way: " + item6.Key);
                                        }
                                    }
                                    if (!geyserPlaced)
                                    {
                                        Debug.Log("Cannot find a place for geyser. Not enought space: " + item6.Key);
                                    }
                                }
                                else
                                {
                                    Debug.Log("Cannot build geyser template: " + item6.Key);
                                }
                            }
                            else
                            {
                                Debug.Log("Cannot find a place for geyser. Empty space: " + item6.Key);
                            }
                        }
                    }
                }
            }
        }
コード例 #4
0
 /// <summary>
 /// The backing data for this entity
 /// </summary>
 public override T Template <T>()
 {
     return((T)TemplateCache.Get(new TemplateCacheKey(typeof(INonPlayerCharacterTemplate), TemplateId)));
 }
コード例 #5
0
        /// <summary>
        /// Restores live entity backup from Current
        /// </summary>
        /// <returns>Success state</returns>
        public bool RestoreLiveBackup()
        {
            LiveData liveDataAccessor = new LiveData();

            string currentBackupDirectory = liveDataAccessor.BaseDirectory + liveDataAccessor.CurrentDirectoryName;

            //No backup directory? No live data.
            if (!Directory.Exists(currentBackupDirectory))
            {
                return(false);
            }

            LoggingUtility.Log("World restored from current live INITIATED.", LogChannels.Backup, false);

            try
            {
                //dont load players here
                List <IEntity>     entitiesToLoad   = new List <IEntity>();
                IEnumerable <Type> implimentedTypes = typeof(EntityPartial).Assembly.GetTypes().Where(ty => ty.GetInterfaces().Contains(typeof(IEntity)) &&
                                                                                                      ty.IsClass &&
                                                                                                      !ty.IsAbstract &&
                                                                                                      !ty.GetCustomAttributes <IgnoreAutomatedBackupAttribute>().Any());

                foreach (Type type in implimentedTypes.OrderByDescending(type => type == typeof(Gaia) ? 6 :
                                                                         type == typeof(Zone) ? 5 :
                                                                         type == typeof(Locale) ? 4 :
                                                                         type == typeof(Room) ? 3 :
                                                                         type == typeof(Pathway) ? 2 : 0))
                {
                    if (!Directory.Exists(currentBackupDirectory + type.Name))
                    {
                        continue;
                    }

                    DirectoryInfo entityFilesDirectory = new DirectoryInfo(currentBackupDirectory + type.Name);

                    foreach (FileInfo file in entityFilesDirectory.EnumerateFiles())
                    {
                        entitiesToLoad.Add(liveDataAccessor.ReadEntity(file, type));
                    }
                }

                //Check we found actual data
                if (!entitiesToLoad.Any(ent => ent.GetType() == typeof(Gaia)))
                {
                    throw new Exception("No Worlds found, failover.");
                }

                if (!entitiesToLoad.Any(ent => ent.GetType() == typeof(Zone)))
                {
                    throw new Exception("No zones found, failover.");
                }

                //Shove them all into the live system first
                foreach (IEntity entity in entitiesToLoad.OrderBy(ent => ent.Birthdate))
                {
                    entity.UpsertToLiveWorldCache();
                    entity.KickoffProcesses();
                }

                //We need to pick up any places that aren't already live from the file system incase someone added them during the last session\
                foreach (IGaiaTemplate thing in TemplateCache.GetAll <IGaiaTemplate>())
                {
                    if (!entitiesToLoad.Any(ent => ent.TemplateId.Equals(thing.Id) && ent.Birthdate >= thing.LastRevised))
                    {
                        IGaia entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IGaia;

                        entityThing.SpawnNewInWorld();
                    }
                    else
                    {
                        thing.GetLiveInstance().GetFromWorldOrSpawn();
                    }
                }

                foreach (IZoneTemplate thing in TemplateCache.GetAll <IZoneTemplate>())
                {
                    if (!entitiesToLoad.Any(ent => ent.TemplateId.Equals(thing.Id) && ent.Birthdate >= thing.LastRevised))
                    {
                        IZone entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IZone;

                        entityThing.SpawnNewInWorld();
                    }
                    else
                    {
                        thing.GetLiveInstance().GetFromWorldOrSpawn();
                    }
                }

                foreach (ILocaleTemplate thing in TemplateCache.GetAll <ILocaleTemplate>())
                {
                    if (!entitiesToLoad.Any(ent => ent.TemplateId.Equals(thing.Id) && ent.Birthdate >= thing.LastRevised))
                    {
                        ILocale entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as ILocale;

                        entityThing.ParentLocation = entityThing.ParentLocation.GetLiveInstance();
                        entityThing.SpawnNewInWorld();
                    }
                    else
                    {
                        thing.GetLiveInstance().GetFromWorldOrSpawn();
                    }
                }

                foreach (IRoomTemplate thing in TemplateCache.GetAll <IRoomTemplate>())
                {
                    if (!entitiesToLoad.Any(ent => ent.TemplateId.Equals(thing.Id) && ent.Birthdate >= thing.LastRevised))
                    {
                        IRoom entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IRoom;

                        entityThing.ParentLocation = entityThing.Template <IRoomTemplate>().ParentLocation.GetLiveInstance();
                        entityThing.SpawnNewInWorld();
                    }
                    else
                    {
                        thing.GetLiveInstance().GetFromWorldOrSpawn();
                    }
                }

                foreach (IPathwayTemplate thing in TemplateCache.GetAll <IPathwayTemplate>())
                {
                    if (!entitiesToLoad.Any(ent => ent.TemplateId.Equals(thing.Id) && ent.Birthdate >= thing.LastRevised))
                    {
                        IPathway entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IPathway;

                        entityThing.SpawnNewInWorld();
                    }
                    else
                    {
                        thing.GetLiveInstance().GetFromWorldOrSpawn();
                    }
                }

                //We have the containers contents and the birthmarks from the deserial
                //I don't know how we can even begin to do this type agnostically since the collections are held on type specific objects without some super ugly reflection
                foreach (Room entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(Room)))
                {
                    foreach (IInanimate obj in entity.Contents.EntitiesContained())
                    {
                        IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj));
                        entity.MoveFrom(obj);
                        entity.MoveInto(fullObj);
                    }

                    foreach (INonPlayerCharacter obj in entity.MobilesInside.EntitiesContained())
                    {
                        INonPlayerCharacter fullObj = LiveCache.Get <INonPlayerCharacter>(new LiveCacheKey(obj));
                        entity.MoveFrom(obj);
                        entity.MoveInto(fullObj);
                    }
                }

                foreach (NonPlayerCharacter entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(NonPlayerCharacter)))
                {
                    foreach (IInanimate obj in entity.Inventory.EntitiesContained())
                    {
                        IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj));
                        entity.MoveFrom(obj);
                        entity.MoveInto(fullObj);
                    }
                }

                foreach (Inanimate entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(Inanimate)))
                {
                    foreach (Tuple <string, IInanimate> obj in entity.Contents.EntitiesContainedByName())
                    {
                        IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj.Item2));
                        entity.MoveFrom(obj.Item2);
                        entity.MoveInto(fullObj, obj.Item1);
                    }

                    foreach (Tuple <string, IInanimate> obj in entity.Contents.EntitiesContainedByName())
                    {
                        INonPlayerCharacter fullObj = LiveCache.Get <INonPlayerCharacter>(new LiveCacheKey(obj.Item2));
                        entity.MoveFrom((INonPlayerCharacter)obj.Item2);
                        entity.MoveInto(fullObj, obj.Item1);
                    }
                }

                //We need to poll the WorldMaps here and give all the rooms their coordinates as well as the zones their sub-maps
                ParseDimension();

                LoggingUtility.Log("World restored from current live.", LogChannels.Backup, false);
                return(true);
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex);
            }

            return(false);
        }
コード例 #6
0
        private void btnNew_Click(object sender, EventArgs e)
        {
            FileSelector fs = (FileSelector)lstSolutions.SelectedItem;

            if (fs == null)
            {
                return;
            }

            string file = fs.CompletePath;

            TemplateCache.Instance().Clear(true);
            try
            {
                TemplateCache.Instance().LoadSolutionFile(file, false);
            }
            catch (ApplicationException aex)
            {
                OptionsSettings.Instance().UnRegisterLastUsedSolution(file);
                lstSolutions.Items.Remove(fs);
                MessageBox.Show(aex.Message, "Load solution error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            openFileDialog.Multiselect      = false;
            openFileDialog.CheckFileExists  = false;
            openFileDialog.Title            = "Create projectfile";
            openFileDialog.DefaultExt       = ".xmp";
            openFileDialog.Filter           = "NextGen projects (*.xmp)|*.xmp";
            openFileDialog.RestoreDirectory = false;
            openFileDialog.FileName         = "";
            if (openFileDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            // Treat all files to be opened. We'll have to do the same
            // as when initial loading with a list of filenames.
            file = openFileDialog.FileName;
            XmlDocument d = new XmlDocument();

            d.AppendChild(d.CreateElement("project"));
            XmlElement elm = d.CreateElement("solution");

            elm.AppendChild(d.CreateTextNode(TemplateCache.Instance().Solution));
            d.DocumentElement.AppendChild(elm);
            elm = d.CreateElement("solutionfilename");
            elm.AppendChild(d.CreateTextNode(TemplateCache.Instance().SolutionFilename));
            d.DocumentElement.AppendChild(elm);
            d.Save(file);

            string[] args = new string[] { file };

            try
            {
                TemplateMain.Instance().InitializeApplication(args);
                Close();
            }
            catch (ApplicationException aex)
            {
                OptionsSettings.Instance().UnRegisterLastUsedProject(file);
                MessageBox.Show(aex.Message, "New project error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #7
0
 public ViewRoomViewModel(string birthMark)
 {
     DataObject     = LiveCache.Get <IRoom>(new LiveCacheKey(typeof(IRoom), birthMark));
     ValidMaterials = TemplateCache.GetAll <IMaterial>(true);
     ValidModels    = TemplateCache.GetAll <IDimensionalModelData>();
 }
コード例 #8
0
 public ViewGaiaViewModel(string birthMark)
 {
     DataObject              = LiveCache.Get <IGaia>(new LiveCacheKey(typeof(IGaia), birthMark));
     ValidCelestials         = TemplateCache.GetAll <ICelestial>(true);
     ValidInanimateTemplates = TemplateCache.GetAll <IInanimateTemplate>(true);
 }
コード例 #9
0
 /// <summary>
 /// What pathways are affiliated with this room data (what it spawns with)
 /// </summary>
 /// <param name="withReturn">includes paths into this room as well</param>
 /// <returns>the valid pathways</returns>
 public virtual IEnumerable <IPathwayTemplate> GetPathways(bool withReturn = false)
 {
     return(TemplateCache.GetAll <IPathwayTemplate>().Where(path => path.Origin.Equals(this) || (withReturn && path.Destination.Equals(this))));
 }
コード例 #10
0
        private Assignment ProcessTypeMap(TypeMap rootMap)
        {
            var recorder = new Recorder();

            using (var bfm = new BeforeMapPrinter(new TypeNameContext(rootMap), recorder)) { }

            foreach (PropertyMap propertyMap in rootMap.PropertyMaps)
            {
                if (propertyMap.Ignored)
                {
                    continue;
                }

                RememberTypeLocations(propertyMap);

                var ctx = new PropertyNameContext(propertyMap);

                //using (var condition = new ConditionPrinter(context, Recorder))
                using (var condition = new ConditionPrinterV2(ctx, recorder))
                {
                    //assign without explicit cast
                    var st = propertyMap.SrcType;
                    var dt = propertyMap.DestType;

                    if (dt.IsAssignableFrom(st) || dt.IsImplicitCastableFrom(st))
                    {
                        recorder.AppendAssignment(Assign.AsNoCast, ctx);
                        continue;
                    }
                    //assign with explicit cast
                    if (dt.IsExplicitCastableFrom(st))
                    {
                        recorder.AppendAssignment(Assign.AsExplicitCast, ctx);
                        continue;
                    }
                    //assign with src.ToString() call
                    if (dt == typeof(string) && st != typeof(string))
                    {
                        recorder.AppendAssignment(Assign.AsToStringCall, ctx);
                        continue;
                    }
                    //assign with Convert call
                    if (st == typeof(string) && dt.IsValueType)
                    {
                        recorder.AppendAssignment(Assign.AsStringToValueTypeConvert, ctx);
                        continue;
                    }

                    if (!st.IsValueType && !dt.IsValueType)
                    {
                        using (var block = new Block(recorder, "if", $"{{0}}.{ctx.SrcMemberName} == null"))
                        {
                            recorder.AppendLine($"{{1}}.{ctx.DestMemberName} = null;");
                        }

                        using (var block = new Block(recorder, "else"))
                        {
                            if (st.IsCollectionType() && dt.IsCollectionType())
                            {
                                string template = AssignCollections(ctx)
                                                  .AddPropertyNamesToTemplate(ctx.SrcMemberName, ctx.DestMemberName);

                                recorder.AppendLine(template);
                            }

                            else
                            {
                                string template = AssignReferenceTypes(ctx)
                                                  .AddPropertyNamesToTemplate(ctx.SrcMemberName, ctx.DestMemberName);

                                recorder.AppendLine(template);
                            }
                        }
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
                }
            }

            var assignment = recorder.ToAssignment();

            TemplateCache.AddIfNotExist(rootMap.TypePair, assignment.RelativeTemplate);

            return(assignment);
        }
コード例 #11
0
        private string AssignCollections(IPropertyNameContext ctx)
        {
            var recorder = new Recorder();

            var itemSrcType  = ctx.SrcType.GenericTypeArguments[0];
            var itemDestType = ctx.DestType.GenericTypeArguments[0];

            using (var block = new Block(recorder, "if", "{1} == null"))
            {
                string newCollection = CreationTemplates.NewCollection(ctx.DestType, "{0}.Count");
                recorder.AppendLine($"{{1}} = {newCollection};");
            }
            using (var block = new Block(recorder, "else"))
            {
                recorder.AppendLine("{1}.Clear();");
            }

            //fill new (or cleared) collection with the new set of items
            recorder.AppendLine(CreationTemplates.Add("{1}", "{0}.Count", itemDestType));

            //inner cycle variables (on each iteration itemSrcName is mapped to itemDestName).
            string itemSrcName  = "src_" + NamingTools.NewGuid(4);
            string itemDestName = "dest_" + NamingTools.NewGuid(4);

            var typePair = new TypePair(itemSrcType, itemDestType);

            Assignment itemAssignment = new Assignment();

            string cachedTemplate;

            if (TemplateCache.TryGetValue(typePair, out cachedTemplate))
            {
                itemAssignment.RelativeTemplate = cachedTemplate;
            }
            else if (itemSrcType.IsCollectionType() && itemDestType.IsCollectionType())
            {
                var innerContext = PropertyNameContextFactory.CreateWithoutPropertyMap(
                    itemSrcType, itemDestType, itemSrcName, itemDestName);

                string innerTemplate = AssignCollections(innerContext);

                itemAssignment.RelativeTemplate = innerTemplate;
            }
            else
            {
                var nodeMap = GetTypeMap(typePair);

                itemAssignment = ProcessTypeMap(nodeMap);
            }

            string iterationCode = itemAssignment.GetCode(itemSrcName, itemDestName);

            string forCode = StatementTemplates.For(iterationCode,
                                                    new ForDeclarationContext("{0}", "{1}", itemSrcName, itemDestName));

            recorder.AppendLine(forCode);

            string template = recorder.ToAssignment().RelativeTemplate;

            return(template);
        }
コード例 #12
0
 public AddEditCelestialViewModel(string archivePath, ICelestial item) : base(archivePath, item)
 {
     ValidMaterials = TemplateCache.GetAll <IMaterial>(true);
     ValidModels    = TemplateCache.GetAll <IDimensionalModelData>(true);
     DataObject     = item;
 }
コード例 #13
0
 public AddEditCelestialViewModel() : base(-1)
 {
     ValidMaterials = TemplateCache.GetAll <IMaterial>(true);
     ValidModels    = TemplateCache.GetAll <IDimensionalModelData>(true);
 }
コード例 #14
0
        public string Quickbuild(long originId, long destinationId, int direction, int incline)
        {
            ApplicationUser authedUser = UserManager.FindById(User.Identity.GetUserId());

            IRoomTemplate origin      = TemplateCache.Get <IRoomTemplate>(originId);
            IRoomTemplate destination = TemplateCache.Get <IRoomTemplate>(destinationId);

            string message = string.Empty;

            if (destination == null)
            {
                destination = new RoomTemplate
                {
                    Name           = "Room",
                    Medium         = origin.Medium,
                    ParentLocation = origin.ParentLocation,
                    Model          = new DimensionalModel()
                    {
                        ModelTemplate     = origin.Model.ModelTemplate,
                        Composition       = origin.Model.Composition,
                        Height            = origin.Model.Height,
                        Length            = origin.Model.Length,
                        Width             = origin.Model.Width,
                        SurfaceCavitation = origin.Model.SurfaceCavitation,
                        Vacuity           = origin.Model.Vacuity
                    }
                };

                destination = (IRoomTemplate)destination.Create(authedUser.GameAccount, authedUser.GetStaffRank(User));
            }


            if (destination != null)
            {
                IPathwayTemplate newObj = new PathwayTemplate
                {
                    Name             = "Pathway",
                    Destination      = destination,
                    Origin           = origin,
                    InclineGrade     = incline,
                    DegreesFromNorth = direction,
                    Model            = new DimensionalModel()
                    {
                        ModelTemplate     = origin.Model.ModelTemplate,
                        Composition       = origin.Model.Composition,
                        Height            = origin.Model.Height,
                        Length            = origin.Model.Length,
                        Width             = origin.Model.Width,
                        SurfaceCavitation = origin.Model.SurfaceCavitation,
                        Vacuity           = origin.Model.Vacuity
                    }
                };

                if (newObj.Create(authedUser.GameAccount, authedUser.GetStaffRank(User)) == null)
                {
                    message = "Error; Creation failed.";
                }
                else
                {
                    PathwayTemplate reversePath = new PathwayTemplate
                    {
                        Name             = newObj.Name,
                        DegreesFromNorth = Utilities.ReverseDirection(newObj.DegreesFromNorth),
                        Origin           = newObj.Destination,
                        Destination      = newObj.Origin,
                        Model            = newObj.Model,
                        InclineGrade     = newObj.InclineGrade * -1
                    };

                    if (reversePath.Create(authedUser.GameAccount, authedUser.GetStaffRank(User)) == null)
                    {
                        message = "Reverse Path creation FAILED. Origin path creation SUCCESS.";
                    }

                    LoggingUtility.LogAdminCommandUsage("*WEB* - Quickbuild[" + newObj.Id.ToString() + "]", authedUser.GameAccount.GlobalIdentityHandle);
                }
            }
            else
            {
                message = "Error; Creation failed.";
            }

            return(message);
        }
コード例 #15
0
 public static void ClearCache()
 {
     TemplateCache.ClearCache();
     RendererCache.ClearCache();
 }
コード例 #16
0
 public static void ClearCache()
 {
     Current = new TemplateCache();
 }
コード例 #17
0
 public Installer(IEngineEnvironmentSettings environmentSettings)
 {
     _environmentSettings = environmentSettings;
     _paths         = new Paths(environmentSettings);
     _templateCache = new TemplateCache(_environmentSettings);
 }
コード例 #18
0
        /// <summary>
        /// Create a panel with the contents filled from the given Value XmlNode
        /// The name of the panel is the sequence-number of the panel
        /// (derived from the number of panels current in this form).
        /// The name will be fixed and will never change.
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        private Panel FillOne(XmlNode Value)
        {
            // Keep 2 pixels on the left free, and keep track of the maximum
            // height of all controls on the panel, to be able to size the panel
            // right.
            int left      = 2;
            int maxheight = 0;

            // Create the panel and give it its name.
            Panel pnlAttr = new Panel();

            pnlAttr.Name     = m_panelrowcount.ToString();
            pnlAttr.TabIndex = m_panelrowcount;

            // Top will be calculated on basis of ordering and current position
            // of the scroll bar. Initially is it the currenttop
            pnlAttr.Top  = m_currenttop;
            pnlAttr.Left = 0;
            // Width can increase when more space is needed, depending on the
            // number of elements defined per item.
            pnlAttr.Width = 100;

            // On entering, eventually attributesets initialisation,
            // and on leaving storing the results in the value.
            pnlAttr.Enter     += new System.EventHandler(this.pnlAttr_Enter);
            pnlAttr.Leave     += new System.EventHandler(this.pnlAttr_Leave);
            pnlAttr.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlAttr_MouseDown);
            pnlAttr.DragEnter += new System.Windows.Forms.DragEventHandler(this.pnlAttr_DragEnter);
            pnlAttr.DragLeave += new System.EventHandler(this.pnlAttr_DragLeave);
            pnlAttr.DragDrop  += new System.Windows.Forms.DragEventHandler(this.pnlAttr_DragDrop);
            pnlAttr.AllowDrop  = true;

            //pnlAttr.BorderStyle = BorderStyle.FixedSingle;

            // Store the value we're displaying on this panel on the x-th element
            // in the m_Value list.
            m_Value.Add(Value);
            int defindex = 0;

            foreach (XmlNode element in m_definitions.SelectNodes("element"))
            {
                XmlAttribute name    = element.Attributes["name"];
                XmlAttribute lines   = element.Attributes["lines"];
                XmlAttribute size    = element.Attributes["size"];
                XmlAttribute length  = element.Attributes["length"];
                XmlAttribute type    = element.Attributes["type"];
                XmlAttribute def_val = element.Attributes["default"];

                if (name == null)                 // || name.InnerText == "name")
                {
                    continue;
                }

                Control c = null;

                // Get the current string value, if available.
                string  stringValue = "";
                XmlNode valueNode   = Value.SelectSingleNode(name.Value);
                if (valueNode != null)
                {
                    stringValue = valueNode.InnerText;
                }
                else if (def_val != null)
                {
                    stringValue = def_val.InnerText;
                }

                if ((type == null) ||
                    (type.Value == "Name") ||
                    (type.Value == "Number") ||
                    (type.Value == "LoopField") ||
                    (type.Value == "Text"))
                {
                    TextBox t = new TextBox();
                    c = t;
                    int nLines = 0;
                    if (lines != null)
                    {
                        nLines = Int32.Parse(lines.Value);
                    }
                    else
                    {
                        nLines = 1;
                    }

                    t.Multiline     = (nLines != 1);
                    t.AcceptsReturn = t.Multiline;
                    t.Height        = nLines * 13 + 8;
                    if (length != null)
                    {
                        t.MaxLength = Int32.Parse(length.Value);
                    }
                    t.Text = stringValue;
                    if (type != null && type.Value == "Name")
                    {
                        m_NameControls.Add(t);
                        t.TextChanged += new System.EventHandler(this.txtName_TextLeave);
                    }
                    if (type != null && type.Value == "LoopField")
                    {
                        ArrayList ttparts = new ArrayList();
                        foreach (XmlNode e in element.SelectNodes("element"))
                        {
                            ttparts.Add(e.Attributes["name"].Value);
                        }
                        string ttt;
                        if (ttparts.Count > 1)
                        {
                            char partsep = TemplateGenerator.DEFAULT_PART_SEPERATOR;
                            if (element.Attributes["partsep"] != null)
                            {
                                partsep = element.Attributes["partsep"].Value[0];
                            }
                            String[] ttstrings = (ttparts.ToArray(typeof(String)) as String[]);
                            ttt = String.Join(partsep.ToString(), ttstrings);
                        }
                        else if (ttparts.Count > 0)
                        {
                            ttt = ttparts[0].ToString();
                        }
                        else
                        {
                            ttt = "";
                        }
                        char fieldsep = TemplateGenerator.DEFAULT_FIELD_SEPERATOR;
                        if (element.Attributes["fieldsep"] != null)
                        {
                            fieldsep = element.Attributes["fieldsep"].Value[0];
                        }
                        ttt = ttt + fieldsep.ToString() + ttt;
                        m_tt.SetToolTip(t, ttt);
                    }
                    t.TextChanged += new EventHandler(m_owner.Mark_Dirty);
                }
                else if (type.Value == "Order")
                {
                    NumericUpDown t = new NumericUpDown();
                    t.Maximum   = 999;
                    c           = t;
                    t.TextAlign = HorizontalAlignment.Right;
                    if (Value.ChildNodes.Count == 0)
                    {
                        // Find largest order value in all ordering controls
                        Decimal maxOrder = 0;
                        foreach (NumericUpDown n in m_OrderControls)
                        {
                            if (n.Value > maxOrder)
                            {
                                maxOrder = n.Value;
                            }
                        }
                        t.Text = (maxOrder + 1).ToString();
                    }
                    else
                    {
                        t.Text = stringValue;
                    }
                    t.Leave        += new System.EventHandler(this.txtOrder_Leave);
                    t.ValueChanged += new EventHandler(m_owner.Mark_Dirty);
                    m_OrderControls.Add(c);
                }
                else if (type.Value == "Checkbox")
                {
                    CheckBox t = new CheckBox();
                    t.ThreeState      = false;
                    t.Checked         = (stringValue == "1");
                    t.Height         -= 4;
                    c                 = t;
                    t.CheckedChanged += new EventHandler(m_owner.Mark_Dirty);
                }
                else if (type.Value == "Combobox")
                {
                    // Get the values in the list from the child element
                    // and put these in the combo
                    ComboBox t = new ComboBox();
                    t.DropDownStyle = ComboBoxStyle.DropDownList;
                    t.Items.Add("");
                    foreach (XmlNode x in element.SelectNodes("element"))
                    {
                        t.Items.Add(x.Attributes["name"].InnerText);
                    }
                    t.Text = stringValue;
                    c      = t;
                    t.SelectedValueChanged += new EventHandler(m_owner.Mark_Dirty);
                }
                else if (type.Value == "Table")
                {
                    // Get the values in the list from the cache with all tablenames
                    // and put these in the combo
                    ComboBox t = new ComboBox();
                    t.DropDownStyle = ComboBoxStyle.DropDownList;
                    t.Sorted        = true;
                    t.Items.Add("");
                    t.Items.AddRange(TemplateCache.Instance().GetTypenamesList("TableDefinition"));
                    t.Text = stringValue;
                    c      = t;
                    t.SelectedValueChanged += new EventHandler(m_owner.Mark_Dirty);
                }
                else if (type.Value == "AttributeCombobox")
                {
                    // Get the values in the list from all attribute panels
                    // and put these in the combo. Select the right one
                    // according to the id of the attribute.
                    ComboBox t = new ComboBox();
                    t.Sorted        = true;
                    t.DropDownStyle = ComboBoxStyle.DropDownList;
                    t.Items.Add("");

                    XmlAttribute id = Value.Attributes["refid"];
                    if (id == null)
                    {
                        id = Value.OwnerDocument.CreateAttribute("refid");
                        Value.Attributes.Append(id);
                    }
                    //t.Items.Add("");
                    foreach (Control tb in m_attributespanel.NameControls)
                    {
                        if (tb.Text.Trim() == "")
                        {
                            continue;
                        }

                        t.Items.Add(tb.Text);
                        // If no id connected yet, set it when value conforms
                        if (id.Value == tb.Parent.Name)
                        {
                            stringValue = tb.Text;
                        }
                        else if (id.Value == "" && stringValue == tb.Text)
                        {
                            id.Value = tb.Parent.Name;
                        }
                    }

                    t.Text = stringValue;
                    c      = t;
                    if (m_attributespanel != this)
                    {
                        m_NameControls.Add(t);
                        t.SelectedIndexChanged += new System.EventHandler(this.txtName_TextLeave);
                        t.Leave += new System.EventHandler(this.txtName_UpdateTextId);
                    }
                    t.SelectedValueChanged += new EventHandler(m_owner.Mark_Dirty);
                }
                else if (type.Value == "AttributeSet")
                {
                    // Keep in attributesets[i] an element
                    // where the attributes in the specific set
                    // are kept. Keep in that element not the names of the
                    // attributes but the number of the panel (the immutable id for
                    // this session) to avoid renaming over and over again.
                    XmlNode x = null;
                    if (Value != null)
                    {
                        x = Value.SelectSingleNode(name.Value);
                    }
                    if (x == null)
                    {
                        x = Value.OwnerDocument.CreateElement(name.Value);
                        Value.AppendChild(x);
                    }
                    c = null;
                }
                else
                {
                    // It must almost be a combobox with references to other types.
                    // Find the right directory
                    ComboBox t = new ComboBox();
                    t.DropDownStyle = ComboBoxStyle.DropDownList;
                    t.Sorted        = true;
                    t.Items.Add("");
                    t.Items.AddRange(TemplateCache.Instance().GetTypenamesList(type.Value));
                    t.Text = stringValue;

                    TemplateMain.Instance().CreateLinkContextMenu(t, type.Value);
                    c = t;
                    t.SelectedValueChanged += new EventHandler(m_owner.Mark_Dirty);
                }

                if (defindex >= m_AttributeControls.Count)
                {
                    m_AttributeControls.Add(new ArrayList());
                }

                if (c != null)
                {
                    if (m_LabelControls.Count > defindex)
                    {
                        Label label = m_LabelControls[defindex]     as Label;
                        if (label != null)
                        {
                            left = label.Left;
                        }
                    }

                    c.Name = name.Value;
                    c.Top  = 2;
                    c.Left = left;
                    int sizeval = 10;
                    if (size != null)
                    {
                        sizeval = int.Parse(size.Value);
                    }
                    else if (length != null)
                    {
                        sizeval = int.Parse(length.Value);
                    }

                    c.Width = sizeval * 8 + 4;
                    pnlAttr.Controls.Add(c);
                    ArrayList al = m_AttributeControls[defindex] as ArrayList;
                    al.Add(c);
                    if (al.Count > m_definitions_fixed &&
                        m_HScroll != null &&
                        al.Count - m_definitions_fixed <= m_HScroll.Value)
                    {
                        c.Visible = false;
                    }
                    else
                    {
                        left += 4 + c.Width;
                    }

                    if (c.Top + c.Height > maxheight)
                    {
                        maxheight = c.Top + c.Height;
                    }
                }

                // Make sure it is wide enough
                if (pnlAttr.Width < left)
                {
                    pnlAttr.Width = left + 2;
                }
                // increase index of processed attribute definition
                defindex++;
            }

            pnlAttr.Height = maxheight + 2;
            pnlAttr.Top    = m_currenttop;                                                                     // -	(maxheight + 2)	* (m_VScroll.Value);

            // Empty <attributes/> element does not count too, so test for > 1
            SetPanelVisible(pnlAttr, (Value.ChildNodes.Count > 1));
            m_panel.Controls.Add(pnlAttr);

            m_currenttop += pnlAttr.Height;

            return(pnlAttr);
        }
コード例 #19
0
 public ViewGaiaViewModel()
 {
     ValidCelestials         = TemplateCache.GetAll <ICelestial>(true);
     ValidInanimateTemplates = TemplateCache.GetAll <IInanimateTemplate>(true);
 }
コード例 #20
0
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public JsonResult getCache(string key)
        {
            ///缓存文件夹
            var cachePath = this.config.SitePath + "cache/";

            if (!string.IsNullOrEmpty(key))
            {
                cachePath += Utils.replace(key, "__", "/") + "/";
            }
            string template = Fetch.getMapPath(cachePath);

            var cacheList = new List <Entity.CacheFileInfo>();

            if (Directory.Exists(template))
            {
                //目录
                var directionList = new DirectoryInfo(template).GetDirectories();
                if (directionList != null && directionList.Count() > 0)
                {
                    foreach (var dir in directionList)
                    {
                        cacheList.Add(new Entity.CacheFileInfo()
                        {
                            Cachekey  = dir.Name,
                            CacheType = 0,
                            Size      = ""
                        });
                    }
                }

                //缓存文件
                var fileList = new DirectoryInfo(template).GetFiles("*.cshtml");
                if (fileList != null && fileList.Count() > 0)
                {
                    foreach (var file in fileList)
                    {
                        cacheList.Add(new Entity.CacheFileInfo()
                        {
                            Cachekey  = file.Name,
                            CacheType = 1,
                            Size      = (file.Length / 1024).ToString("0.00K")
                        });
                    }
                }
            }

            if (string.IsNullOrEmpty(key))
            {
                //字典缓存
                var cachelist = TemplateCache.getCache();

                if (cachelist != null && cachelist.Count() > 0)
                {
                    foreach (var cache in cachelist)
                    {
                        cacheList.Add(new Entity.CacheFileInfo()
                        {
                            Cachekey  = cache.Key,
                            CacheType = 2,
                            Size      = (Encoding.Default.GetByteCount(cache.Value.CacheContent) / 1024).ToString("0.00K")
                        });
                    }
                }
            }
            return(this.getResult(Entity.Error.请求成功, "请求成功", cacheList));
        }
コード例 #21
0
 public ViewRoomViewModel()
 {
     ValidMaterials = TemplateCache.GetAll <IMaterial>(true);
     ValidModels    = TemplateCache.GetAll <IDimensionalModelData>();
 }
コード例 #22
0
ファイル: UICacheManager.cs プロジェクト: wuhuolong/MaxBooks
 private void FreeTemplateCache(TemplateCache cache)
 {
     cache.Clear();
     cachePool.Add(cache);
 }
コード例 #23
0
        public static int Main(string[] args)
        {
            CommandLineApplication app = new CommandLineApplication(false)
            {
                Name     = "dotnet new3",
                FullName = "Template Instantiation Commands for .NET Core CLI."
            };

            CommandArgument template        = app.Argument("template", "The template to instantiate.");
            CommandOption   listOnly        = app.Option("-l|--list", "Lists templates with containing the specified name.", CommandOptionType.NoValue);
            CommandOption   name            = app.Option("-n|--name", "The name for the output. If no name is specified, the name of the current directory is used.", CommandOptionType.SingleValue);
            CommandOption   dir             = app.Option("-d|--dir", "Indicates whether to display create a directory for the generated content.", CommandOptionType.NoValue);
            CommandOption   alias           = app.Option("-a|--alias", "Creates an alias for the specified template", CommandOptionType.SingleValue);
            CommandOption   parametersFiles = app.Option("-x|--extra-args", "Adds a parameters file.", CommandOptionType.MultipleValue);
            CommandOption   install         = app.Option("-i|--install", "Installs a source or a template pack.", CommandOptionType.MultipleValue);
            CommandOption   help            = app.Option("-h|--help", "Indicates whether to display the help for the template's parameters instead of creating it.", CommandOptionType.NoValue);

            CommandOption quiet           = app.Option("--quiet", "Doesn't output any status information.", CommandOptionType.NoValue);
            CommandOption skipUpdateCheck = app.Option("--skip-update-check", "Don't check for updates.", CommandOptionType.NoValue);
            CommandOption update          = app.Option("--update", "Update matching templates.", CommandOptionType.NoValue);

            CommandOption localeOption = app.Option("--locale", "The locale to use", CommandOptionType.SingleValue);

            app.OnExecute(async() =>
            {
                //TODO: properly determine the locale, pass it to the host constructor
                // specifying on the command line is probaby not the ultimate answer.
                // Regardless, the locale should get set before anything else happens.
                string locale = localeOption.HasValue() ? localeOption.Value() : "en_US";
                EngineEnvironmentSettings.Host = new DefaultTemplateEngineHost(locale);

                bool reinitFlag = app.RemainingArguments.Any(x => x == "--debug:reinit");

                if (reinitFlag)
                {
                    Paths.User.FirstRunCookie.Delete();
                }

                // Note: this leaves things in a weird state. Might be related to the localized caches.
                // not sure, need to look into it.
                if (reinitFlag || app.RemainingArguments.Any(x => x == "--debug:reset-config"))
                {
                    Paths.User.AliasesFile.Delete();
                    Paths.User.SettingsFile.Delete();
                    TemplateCache.DeleteAllLocaleCacheFiles();
                    return(0);
                }

                if (!Paths.User.BaseDir.Exists() || !Paths.User.FirstRunCookie.Exists())
                {
                    if (!quiet.HasValue())
                    {
                        Reporter.Output.WriteLine("Getting things ready for first use...");
                    }

                    ConfigureEnvironment();
                    Paths.User.FirstRunCookie.WriteAllText("");
                }

                if (app.RemainingArguments.Any(x => x == "--debug:showconfig"))
                {
                    ShowConfig();
                    return(0);
                }

                if (install.HasValue())
                {
                    InstallPackage(install.Values, quiet.HasValue());
                    return(0);
                }

                if (update.HasValue())
                {
                    //return PerformUpdateAsync(template.Value, quiet.HasValue(), source);
                }

                if (listOnly.HasValue())
                {
                    ListTemplates(template);
                    return(0);
                }

                IReadOnlyDictionary <string, string> parameters;

                try
                {
                    parameters = app.ParseExtraArgs(parametersFiles);
                }
                catch (Exception ex)
                {
                    Reporter.Error.WriteLine(ex.Message.Red().Bold());
                    app.ShowHelp();
                    return(-1);
                }

                if (string.IsNullOrWhiteSpace(template.Value) && help.HasValue())
                {
                    app.ShowHelp();
                    return(0);
                }

                if (help.HasValue())
                {
                    return(DisplayHelp(template));
                }

                string aliasName    = alias.HasValue() ? alias.Value() : null;
                string fallbackName = new DirectoryInfo(Directory.GetCurrentDirectory()).Name;

                if (await TemplateCreator.Instantiate(template.Value ?? "", name.Value(), fallbackName, dir.HasValue(), aliasName, parameters, skipUpdateCheck.HasValue()) == -1)
                {
                    ListTemplates(template);
                    return(-1);
                }

                return(0);
            });

            int result;

            try
            {
                using (Timing.Over("Execute"))
                {
                    result = app.Execute(args);
                }
            }
            catch (Exception ex)
            {
                AggregateException ax = ex as AggregateException;

                while (ax != null && ax.InnerExceptions.Count == 1)
                {
                    ex = ax.InnerException;
                    ax = ex as AggregateException;
                }

                Reporter.Error.WriteLine(ex.Message.Bold().Red());

                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    ax = ex as AggregateException;

                    while (ax != null && ax.InnerExceptions.Count == 1)
                    {
                        ex = ax.InnerException;
                        ax = ex as AggregateException;
                    }

                    Reporter.Error.WriteLine(ex.Message.Bold().Red());
                }

                Reporter.Error.WriteLine(ex.StackTrace.Bold().Red());
                result = 1;
            }

            return(result);
        }
コード例 #24
0
 public AddEditGaiaViewModel() : base(-1)
 {
     ValidCelestials = TemplateCache.GetAll <ICelestial>(true);
     DataObject      = new GaiaTemplate();
 }
コード例 #25
0
 /// <summary>
 /// Get the zones associated with this world
 /// </summary>
 /// <returns>list of zones</returns>
 public IEnumerable <IZoneTemplate> GetZones()
 {
     return(TemplateCache.GetAll <IZoneTemplate>().Where(zone => zone.World.Equals(this)));
 }
コード例 #26
0
 public AddEditGaiaViewModel(string archivePath, IGaiaTemplate item) : base(archivePath, item)
 {
     ValidCelestials = TemplateCache.GetAll <ICelestial>(true);
     DataObject      = item;
 }
コード例 #27
0
        /// <summary>
        /// Something went wrong with restoring the live backup, this loads all persistence singeltons from the database (rooms, paths, spawns)
        /// </summary>
        /// <returns>success state</returns>
        public bool NewWorldFallback()
        {
            LiveData liveDataAccessor = new LiveData();

            //This means we delete the entire Current livedata dir since we're falling back.
            string currentLiveDirectory = liveDataAccessor.BaseDirectory + liveDataAccessor.CurrentDirectoryName;

            //No backup directory? No live data.
            if (Directory.Exists(currentLiveDirectory))
            {
                DirectoryInfo currentDir = new DirectoryInfo(currentLiveDirectory);

                LoggingUtility.Log("Current Live directory deleted during New World Fallback Procedures.", LogChannels.Backup, true);

                try
                {
                    currentDir.Delete(true);
                }
                catch
                {
                    //occasionally will be pissy in an async situation
                }
            }

            //Only load in stuff that is static and spawns as singleton
            //We need to pick up any places that aren't already live from the file system incase someone added them during the last session\
            foreach (IGaiaTemplate thing in TemplateCache.GetAll <IGaiaTemplate>())
            {
                IGaia entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IGaia;
            }

            foreach (IZoneTemplate thing in TemplateCache.GetAll <IZoneTemplate>())
            {
                IZone entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IZone;
            }

            foreach (ILocaleTemplate thing in TemplateCache.GetAll <ILocaleTemplate>())
            {
                ILocale entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as ILocale;

                entityThing.ParentLocation = entityThing.Template <ILocaleTemplate>().ParentLocation.GetLiveInstance();
                entityThing.GetFromWorldOrSpawn();
            }

            foreach (IRoomTemplate thing in TemplateCache.GetAll <IRoomTemplate>())
            {
                IRoom entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IRoom;

                entityThing.ParentLocation = entityThing.Template <IRoomTemplate>().ParentLocation.GetLiveInstance();
                entityThing.GetFromWorldOrSpawn();
            }

            foreach (IPathwayTemplate thing in TemplateCache.GetAll <IPathwayTemplate>())
            {
                IPathway entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IPathway;
            }

            ParseDimension();

            LoggingUtility.Log("World restored from data fallback.", LogChannels.Backup, true);

            return(true);
        }
コード例 #28
0
 public AddEditTemplateModel(long templateId)
 {
     DataTemplate       = TemplateCache.Get <T>(templateId);
     ValidTemplateBases = TemplateCache.GetAll <T>(true);
     Archives           = new string[0];
 }
コード例 #29
0
        private static bool Prefix(WorldGen __instance, ref Sim.Cell[] __result, bool doSettle, ref Sim.DiseaseCell[] dc)
        {
            Debug.Log(" === WorldGenReloadedMod_WorldGen_RenderOffline ===");
            WorldGen.OfflineCallbackFunction successCallbackFn = ((WorldGen.OfflineCallbackFunction)successCallbackFnF.GetValue(__instance));
            SeededRandom myRandom = ((SeededRandom)myRandomF.GetValue(__instance));
            Data         data     = ((Data)dataF.GetValue(null));
            Action <OfflineWorldGen.ErrorInfo> errorCallback = ((Action <OfflineWorldGen.ErrorInfo>)errorCallbackF.GetValue(__instance));


            Sim.Cell[] cells  = null;
            float[]    bgTemp = null;
            dc = null;
            HashSet <int> borderCells = new HashSet <int>();

            //CompleteLayout(successCallbackFn);
            __instance.CompleteLayout(successCallbackFn);
            //WriteOverWorldNoise(successCallbackFn);
            WorldGen.WriteOverWorldNoise(successCallbackFn);
            if (!WorldGen.RenderToMap(successCallbackFn, ref cells, ref bgTemp, ref dc, ref borderCells))
            {
                successCallbackFn(UI.WORLDGEN.FAILED.key, -100f, WorldGenProgressStages.Stages.Failure);
                __result = null;
                return(false);
            }
            WorldGen.EnsureEnoughAlgaeInStartingBiome(cells);
            List <KeyValuePair <Vector2I, TemplateContainer> > list = new List <KeyValuePair <Vector2I, TemplateContainer> >();
            TemplateContainer  baseStartingTemplate = TemplateCache.GetBaseStartingTemplate();
            List <TerrainCell> terrainCellsForTag   = WorldGen.GetTerrainCellsForTag(WorldGenTags.StartLocation);

            foreach (TerrainCell item5 in terrainCellsForTag)
            {
                List <KeyValuePair <Vector2I, TemplateContainer> > list2 = list;
                Vector2 vector  = item5.poly.Centroid();
                int     a       = (int)vector.x;
                Vector2 vector2 = item5.poly.Centroid();
                list2.Add(new KeyValuePair <Vector2I, TemplateContainer>(new Vector2I(a, (int)vector2.y), baseStartingTemplate));
            }

            List <TemplateContainer> list3 = TemplateCache.CollectBaseTemplateAssets("poi/");

            foreach (SubWorld subWorld in WorldGen.Settings.GetSubWorldList())
            {
                if (subWorld.pointsOfInterest != null)
                {
                    //// Disable default POI geysers
                    if (WorldGenReloadedData.Config.DisableDefaultPoiGeysers)
                    {
                        SubWorld _subWorld = subWorld;
                        DisableDefaultPoiGeysers(ref _subWorld);
                    }
                    ////
                    foreach (KeyValuePair <string, string[]> item6 in subWorld.pointsOfInterest)
                    {
                        List <TerrainCell> terrainCellsForTag2 = WorldGen.GetTerrainCellsForTag(subWorld.name.ToTag());
                        for (int num = terrainCellsForTag2.Count - 1; num >= 0; num--)
                        {
                            if (!__instance.IsSafeToSpawnPOI(terrainCellsForTag2[num]))
                            {
                                terrainCellsForTag2.Remove(terrainCellsForTag2[num]);
                            }
                        }
                        if (terrainCellsForTag2.Count > 0)
                        {
                            string            template          = null;
                            TemplateContainer templateContainer = null;
                            int num2 = 0;
                            while (templateContainer == null && num2 < item6.Value.Length)
                            {
                                template          = item6.Value[myRandom.RandomRange(0, item6.Value.Length)];
                                templateContainer = list3.Find((TemplateContainer value) => value.name == template);
                                num2++;
                            }
                            if (templateContainer != null)
                            {
                                list3.Remove(templateContainer);
                                for (int i = 0; i < terrainCellsForTag2.Count; i++)
                                {
                                    TerrainCell terrainCell = terrainCellsForTag2[myRandom.RandomRange(0, terrainCellsForTag2.Count)];
                                    if (!terrainCell.node.tags.Contains(WorldGenTags.POI))
                                    {
                                        if (!(templateContainer.info.size.Y > terrainCell.poly.MaxY - terrainCell.poly.MinY))
                                        {
                                            List <KeyValuePair <Vector2I, TemplateContainer> > list4 = list;
                                            Vector2 vector3 = terrainCell.poly.Centroid();
                                            int     a2      = (int)vector3.x;
                                            Vector2 vector4 = terrainCell.poly.Centroid();
                                            list4.Add(new KeyValuePair <Vector2I, TemplateContainer>(new Vector2I(a2, (int)vector4.y), templateContainer));
                                            terrainCell.node.tags.Add(template.ToTag());
                                            terrainCell.node.tags.Add(WorldGenTags.POI);
                                            break;
                                        }
                                        float num3 = templateContainer.info.size.Y - (terrainCell.poly.MaxY - terrainCell.poly.MinY);
                                        float num4 = templateContainer.info.size.X - (terrainCell.poly.MaxX - terrainCell.poly.MinX);
                                        if (terrainCell.poly.MaxY + num3 < (float)Grid.HeightInCells && terrainCell.poly.MinY - num3 > 0f && terrainCell.poly.MaxX + num4 < (float)Grid.WidthInCells && terrainCell.poly.MinX - num4 > 0f)
                                        {
                                            List <KeyValuePair <Vector2I, TemplateContainer> > list5 = list;
                                            Vector2 vector5 = terrainCell.poly.Centroid();
                                            int     a3      = (int)vector5.x;
                                            Vector2 vector6 = terrainCell.poly.Centroid();
                                            list5.Add(new KeyValuePair <Vector2I, TemplateContainer>(new Vector2I(a3, (int)vector6.y), templateContainer));
                                            terrainCell.node.tags.Add(template.ToTag());
                                            terrainCell.node.tags.Add(WorldGenTags.POI);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            ////
            ProcessGeysers(__instance, ref list, myRandom);
            ////

            // Generation of geyser Overwrited in the previous line

            /*
             * List<TemplateContainer> list6 = TemplateCache.CollectBaseTemplateAssets("features/");
             * foreach (SubWorld subWorld2 in WorldGen.Settings.GetSubWorldList())
             * {
             *  if (subWorld2.featureTemplates != null && subWorld2.featureTemplates.Count > 0)
             *  {
             *      List<string> list7 = new List<string>();
             *      foreach (KeyValuePair<string, int> featureTemplate in subWorld2.featureTemplates)
             *      {
             *          for (int j = 0; j < featureTemplate.Value; j++)
             *          {
             *              list7.Add(featureTemplate.Key);
             *          }
             *      }
             *      list7.ShuffleSeeded(myRandom.RandomSource());
             *      List<TerrainCell> terrainCellsForTag3 = WorldGen.GetTerrainCellsForTag(subWorld2.name.ToTag());
             *      terrainCellsForTag3.ShuffleSeeded(myRandom.RandomSource());
             *      foreach (TerrainCell item7 in terrainCellsForTag3)
             *      {
             *          if (list7.Count == 0)
             *          {
             *              break;
             *          }
             *          if (__instance.IsSafeToSpawnFeatureTemplate(item7))
             *          {
             *              string template2 = list7[list7.Count - 1];
             *              list7.RemoveAt(list7.Count - 1);
             *              TemplateContainer templateContainer2 = list6.Find((TemplateContainer value) => value.name == template2);
             *              if (templateContainer2 != null)
             *              {
             *                  List<KeyValuePair<Vector2I, TemplateContainer>> list8 = list;
             *                  Vector2 vector7 = item7.poly.Centroid();
             *                  int a4 = (int)vector7.x;
             *                  Vector2 vector8 = item7.poly.Centroid();
             *                  list8.Add(new KeyValuePair<Vector2I, TemplateContainer>(new Vector2I(a4, (int)vector8.y), templateContainer2));
             *                  item7.node.tags.Add(template2.ToTag());
             *                  item7.node.tags.Add(WorldGenTags.POI);
             *              }
             *          }
             *      }
             *  }
             * }
             */
            foreach (int item8 in borderCells)
            {
                cells[item8].SetValues(WorldGen.unobtaniumElement, ElementLoader.elements);
            }
            if (doSettle)
            {
                //running = WorldGenSimUtil.DoSettleSim(cells, bgTemp, dc, successCallbackFn, data, list, errorCallback, delegate (Sim.Cell[] updatedCells, float[] updatedBGTemp, Sim.DiseaseCell[] updatedDisease)
                runningF.SetValue(null, WorldGenSimUtil.DoSettleSim(cells, bgTemp, dc, successCallbackFn, data, list, errorCallback, delegate(Sim.Cell[] updatedCells, float[] updatedBGTemp, Sim.DiseaseCell[] updatedDisease)
                {
                    //SpawnMobsAndTemplates(updatedCells, updatedBGTemp, updatedDisease, borderCells);
                    SpawnMobsAndTemplatesM.Invoke(__instance, new object[] { updatedCells, updatedBGTemp, updatedDisease, borderCells });
                }));
            }
            foreach (KeyValuePair <Vector2I, TemplateContainer> item9 in list)
            {
                //PlaceTemplateSpawners(item9.Key, item9.Value);
                PlaceTemplateSpawnersM.Invoke(__instance, new object[] { item9.Key, item9.Value });
            }
            for (int num5 = data.gameSpawnData.buildings.Count - 1; num5 >= 0; num5--)
            {
                int item = Grid.XYToCell(data.gameSpawnData.buildings[num5].location_x, data.gameSpawnData.buildings[num5].location_y);
                if (borderCells.Contains(item))
                {
                    data.gameSpawnData.buildings.RemoveAt(num5);
                }
            }
            for (int num6 = data.gameSpawnData.elementalOres.Count - 1; num6 >= 0; num6--)
            {
                int item2 = Grid.XYToCell(data.gameSpawnData.elementalOres[num6].location_x, data.gameSpawnData.elementalOres[num6].location_y);
                if (borderCells.Contains(item2))
                {
                    data.gameSpawnData.elementalOres.RemoveAt(num6);
                }
            }
            for (int num7 = data.gameSpawnData.otherEntities.Count - 1; num7 >= 0; num7--)
            {
                int item3 = Grid.XYToCell(data.gameSpawnData.otherEntities[num7].location_x, data.gameSpawnData.otherEntities[num7].location_y);
                if (borderCells.Contains(item3))
                {
                    data.gameSpawnData.otherEntities.RemoveAt(num7);
                }
            }
            for (int num8 = data.gameSpawnData.pickupables.Count - 1; num8 >= 0; num8--)
            {
                int item4 = Grid.XYToCell(data.gameSpawnData.pickupables[num8].location_x, data.gameSpawnData.pickupables[num8].location_y);
                if (borderCells.Contains(item4))
                {
                    data.gameSpawnData.pickupables.RemoveAt(num8);
                }
            }
            WorldGen.SaveWorldGen();
            successCallbackFn(UI.WORLDGEN.COMPLETE.key, 101f, WorldGenProgressStages.Stages.Complete);
            //running = false;
            runningF.SetValue(null, false);
            __result = cells;
            return(false);
        }
コード例 #30
0
        //Also called Dashboard in most of the html
        public ActionResult Index()
        {
            IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));
            IGossipConfig gossipConfig = ConfigDataCache.Get <IGossipConfig>(new ConfigDataCacheKey(typeof(IGossipConfig), "GossipSettings", ConfigDataType.GameWorld));

            DashboardViewModel dashboardModel = new DashboardViewModel
            {
                AuthedUser = UserManager.FindById(User.Identity.GetUserId()),

                Inanimates = TemplateCache.GetAll <IInanimateTemplate>(),
                NPCs       = TemplateCache.GetAll <INonPlayerCharacterTemplate>(),
                Zones      = TemplateCache.GetAll <IZoneTemplate>(),
                Worlds     = TemplateCache.GetAll <IGaiaTemplate>(),
                Locales    = TemplateCache.GetAll <ILocaleTemplate>(),
                Rooms      = TemplateCache.GetAll <IRoomTemplate>(),

                HelpFiles         = TemplateCache.GetAll <IHelp>(),
                Races             = TemplateCache.GetAll <IRace>(),
                Celestials        = TemplateCache.GetAll <ICelestial>(),
                Journals          = TemplateCache.GetAll <IJournalEntry>(),
                DimensionalModels = TemplateCache.GetAll <IDimensionalModelData>(),
                Flora             = TemplateCache.GetAll <IFlora>(),
                Fauna             = TemplateCache.GetAll <IFauna>(),
                Minerals          = TemplateCache.GetAll <IMineral>(),
                Materials         = TemplateCache.GetAll <IMaterial>(),
                DictionaryWords   = ConfigDataCache.GetAll <ILexeme>(),
                DictionaryPhrases = ConfigDataCache.GetAll <IDictataPhrase>(),
                Languages         = ConfigDataCache.GetAll <ILanguage>(),
                Genders           = TemplateCache.GetAll <IGender>(),
                UIModules         = ConfigDataCache.GetAll <IUIModule>(),

                LiveTaskTokens = Processor.GetAllLiveTaskStatusTokens(),
                LivePlayers    = LiveCache.GetAll <IPlayer>().Count(),
                LiveInanimates = LiveCache.GetAll <IInanimate>().Count(),
                LiveNPCs       = LiveCache.GetAll <INonPlayerCharacter>().Count(),
                LiveZones      = LiveCache.GetAll <IZone>().Count(),
                LiveWorlds     = LiveCache.GetAll <IGaia>().Count(),
                LiveLocales    = LiveCache.GetAll <ILocale>().Count(),
                LiveRooms      = LiveCache.GetAll <IRoom>().Count(),

                ConfigDataObject      = globalConfig,
                WebsocketPortalActive = globalConfig.WebsocketPortalActive,
                AdminsOnly            = globalConfig.AdminsOnly,
                UserCreationActive    = globalConfig.UserCreationActive,
                BaseLanguage          = globalConfig.BaseLanguage,
                AzureTranslationKey   = globalConfig.AzureTranslationKey,
                TranslationActive     = globalConfig.TranslationActive,

                QualityChange      = new string[0],
                QualityChangeValue = new int[0],

                ValidZones     = TemplateCache.GetAll <IZoneTemplate>(true),
                ValidLanguages = ConfigDataCache.GetAll <ILanguage>(),

                GossipConfigDataObject = gossipConfig,
                GossipActive           = gossipConfig.GossipActive,
                ClientId                 = gossipConfig.ClientId,
                ClientSecret             = gossipConfig.ClientSecret,
                ClientName               = gossipConfig.ClientName,
                SuspendMultiplier        = gossipConfig.SuspendMultiplier,
                SuspendMultiplierMaximum = gossipConfig.SuspendMultiplierMaximum,
                SupportedChannels        = gossipConfig.SupportedChannels,
                SupportedFeatures        = gossipConfig.SupportedFeatures
            };

            return(View(dashboardModel));
        }
コード例 #31
0
        public ActionResult Index(string SearchTerms = "", int CurrentPageNumber = 1, int ItemsPerPage = 20)
        {
            ManageDimensionalModelDataViewModel vModel = new ManageDimensionalModelDataViewModel(TemplateCache.GetAll <DimensionalModelData>())
            {
                AuthedUser = UserManager.FindById(User.Identity.GetUserId()),

                CurrentPageNumber = CurrentPageNumber,
                ItemsPerPage      = ItemsPerPage,
                SearchTerms       = SearchTerms
            };

            return(View("~/Views/GameAdmin/DimensionalModel/Index.cshtml", vModel));
        }
コード例 #32
0
        public override object Convert(object input)
        {
            if (input == null)
            {
                return(null);
            }

            IEnumerable <string> valueCollection = input as IEnumerable <string>;

            HashSet <ICelestial> collective = new HashSet <ICelestial>(valueCollection.Select(stringInput => TemplateCache.Get <ICelestial>(long.Parse(stringInput))));

            return(collective);
        }