public void EnsureBothDirections()
        {
            var dictionary = new TwoWayDictionary <int, int>();

            dictionary.Add(1, 2);

            Assert.True(dictionary.ContainsKey(1));
            Assert.True(dictionary.ContainsValue(2));
            Assert.False(dictionary.ContainsKey(2));
            Assert.False(dictionary.ContainsValue(1));
            Assert.Equal(2, dictionary[1]);
            Assert.Equal(1, dictionary.Reverse[2]);
        }
Beispiel #2
0
        public void AddLine(string line)
        {
            BufferData data = new BufferData(line);

            // The hub
            PreLine(ref data);
            if (app.InvokeRequired)
            {
                Line(ref data);
            }
            else
            {
                SelfLine(ref data);
            }
            PostLine(ref data);

            if (data.Ignore)
            {
                return;
            }
            if (data.BroadcastId != null)
            {
                broadcastHelper(data);
            }
            else
            {
                Room tab = new Room(this.connection, data.Channel, null);
                if (!proust.ContainsKey(tab))
                {
                    app.Invoke((M)(() => AddChannel(tab)));
                }

                // AddChannel now guarantees `tab` is inside
                // `proust`, ripe for picking. Forward & reverse
                // ensures that tab.LogBox is not null.
                tab = proust[proust[tab]];
                app.Invoke(new AddLineDel(tab.LogBox.AddLine),
                           data.Line, data.Color);
            }
        }
Beispiel #3
0
        private RoomTemplate GetRoomTemplate(GameObject roomTemplatePrefab)
        {
            if (prefabToRoomTemplateMapping.ContainsKey(roomTemplatePrefab))
            {
                return(prefabToRoomTemplateMapping[roomTemplatePrefab]);
            }

            var roomTemplate = RoomTemplatesLoader.GetRoomTemplate(roomTemplatePrefab);

            prefabToRoomTemplateMapping.Add(roomTemplatePrefab, roomTemplate);

            return(roomTemplate);
        }
Beispiel #4
0
        private void RemoveMarker(Marker marker)
        {
            marker.PropertyChanged -= Marker_PropertyChanged;
            if (marker.Label != null)
            {
                RemoveLabel(marker);
            }

            if (markers.ContainsKey(marker))
            {
                markers[marker].Remove();
                markers.Remove(marker);
            }
        }
Beispiel #5
0
        private bool RegisterType(TwoWayDictionary <Type, MessageDescriptor> registeredTypes, Type type)
        {
            lock (_lock)
            {
                if (!registeredTypes.ContainsKey(type) && TryGetDescriptorFromAttribute(type, out var descriptor))
                {
                    registeredTypes.Add(type, descriptor);

                    return(true);
                }

                return(false);
            }
        }
Beispiel #6
0
        private RoomTemplateGrid2D GetRoomTemplate(GameObject roomTemplatePrefab)
        {
            if (prefabToRoomTemplateMapping.ContainsKey(roomTemplatePrefab))
            {
                return(prefabToRoomTemplateMapping[roomTemplatePrefab]);
            }

            if (RoomTemplateLoaderGrid2D.TryGetRoomTemplate(roomTemplatePrefab, out var roomTemplate, out var result))
            {
                prefabToRoomTemplateMapping.Add(roomTemplatePrefab, roomTemplate);
                return(roomTemplate);
            }

            Debug.LogError($"There was a problem when loading the room template \"{roomTemplatePrefab.name}\":");
            foreach (var error in result.Errors)
            {
                Debug.LogError($"- {error}");
            }

            throw new ConfigurationException("Please fix all the errors above and try again");
        }
Beispiel #7
0
        /// <inheritdoc />
        /// <remarks>
        /// Adds number to a given prefix until all corridors have a name.
        /// </remarks>
        public void AddCorridorsToMapping(ICorridorMapDescription <int> mapDescription, TwoWayDictionary <string, int> mapping)
        {
            var graph     = mapDescription.GetGraph();
            var corridors = graph.Vertices.Where(mapDescription.IsCorridorRoom).ToList();

            var counter = 0;

            foreach (var corridor in corridors)
            {
                while (true)
                {
                    var name = prefix + counter;

                    if (!mapping.ContainsKey(name))
                    {
                        mapping.Add(name, corridor);
                        break;
                    }

                    counter++;
                }
            }
        }
        private void SetupGenerator()
        {
            var mapping       = levelDescriptionMapped.GetMapping();
            var chainsGeneric = configuration.Chains;

            // Create chain decomposition
            if (chainsGeneric == null)
            {
                var chainDecomposition = new Common.TwoStageChainDecomposition <TRoom>(levelDescription, new BreadthFirstChainDecomposition <TRoom>(configuration.ChainDecompositionConfiguration ?? new ChainDecompositionConfiguration()));
                chainsGeneric = chainDecomposition.GetChains(levelDescription.GetGraph());
            }

            var chains = chainsGeneric
                         .Select(x => new Chain <RoomNode <TRoom> >(x.Nodes.Select(y => mapping[y]).ToList(), x.Number)
            {
                IsFromFace = x.IsFromFace
            })
                         .ToList();

            // Create generator planner
            var generatorPlanner = new GeneratorPlanner <Layout <TRoom, ConfigurationGrid2D <TRoom, EnergyData> >, RoomNode <TRoom> >(configuration.SimulatedAnnealingMaxBranching);

            // Create configuration spaces
            var configurationSpacesGenerator = new ConfigurationSpacesGenerator(
                new PolygonOverlap(),
                DoorHandler.DefaultHandler,
                new OrthogonalLineIntersection(),
                new GridPolygonUtils());

            // var configurationSpaces = configurationSpacesGenerator.GetConfigurationSpaces<ConfigurationNew2<CorridorsDataNew>>(mapDescription);
            var simpleConfigurationSpaces = new ConfigurationSpacesGrid2D <ConfigurationGrid2D <TRoom, EnergyData>, RoomNode <TRoom> >(levelDescriptionMapped);

            // Needlessly complex for backwards compatibility

            #region IntAliasMapping

            var roomDescriptions             = levelDescriptionMapped.GetGraph().Vertices.ToDictionary(x => x, x => (RoomDescriptionGrid2D)levelDescriptionMapped.GetRoomDescription(x));
            var roomTemplates                = roomDescriptions.Values.SelectMany(x => x.RoomTemplates).Distinct().ToList();
            var roomTemplateInstances        = roomTemplates.ToDictionary(x => x, configurationSpacesGenerator.GetRoomTemplateInstances);
            var roomTemplateInstancesMapping = roomTemplateInstances.SelectMany(x => x.Value).CreateIntMapping();
            var intAliasMapping              = new TwoWayDictionary <RoomTemplateInstanceGrid2D, IntAlias <PolygonGrid2D> >();

            foreach (var shape1 in roomTemplateInstancesMapping.Keys)
            {
                foreach (var shape2 in roomTemplateInstancesMapping.Keys)
                {
                    if (!intAliasMapping.ContainsKey(shape1))
                    {
                        var newAlias = new IntAlias <PolygonGrid2D>(intAliasMapping.Count, shape1.RoomShape);
                        intAliasMapping.Add(shape1, newAlias);
                        shape1.RoomShapeAlias = newAlias;
                    }
                    if (!intAliasMapping.ContainsKey(shape2))
                    {
                        var newAlias = new IntAlias <PolygonGrid2D>(intAliasMapping.Count, shape2.RoomShape);
                        intAliasMapping.Add(shape2, newAlias);
                        shape2.RoomShapeAlias = newAlias;
                    }
                }
            }

            // TODO: remove when possible
            foreach (var pair in intAliasMapping)
            {
                pair.Key.RoomShapeAlias = pair.Value;
            }

            var shapesForNodes = new Dictionary <RoomNode <TRoom>, List <WeightedShape> >();
            foreach (var vertex in levelDescriptionMapped.GetGraph().Vertices)
            {
                shapesForNodes.Add(vertex, new List <WeightedShape>());
                // var roomDescription = levelDescriptionMapped.GetRoomDescription(vertex);
                var roomDescription = roomDescriptions[vertex];

                foreach (var roomTemplate in roomDescription.RoomTemplates)
                {
                    var instances = roomTemplateInstances[roomTemplate];

                    foreach (var roomTemplateInstance in instances)
                    {
                        shapesForNodes[vertex].Add(new WeightedShape(intAliasMapping[roomTemplateInstance], 1d / instances.Count));
                    }
                }
            }

            var usedShapes = new HashSet <int>();
            var allShapes  = new List <IntAlias <PolygonGrid2D> >();
            foreach (var vertex in levelDescriptionMapped.GetGraph().Vertices)
            {
                var shapes = shapesForNodes[vertex];

                foreach (var shape in shapes)
                {
                    if (!usedShapes.Contains(shape.Shape.Alias))
                    {
                        allShapes.Add(shape.Shape);
                        usedShapes.Add(shape.Shape.Alias);
                    }
                }
            }

            var averageSize = (int)allShapes.Select(x => x.Value.BoundingRectangle).Average(x => (x.Width + x.Height) / 2);

            #endregion



            // var averageSize = configurationSpaces.GetAverageSize();

            var energyUpdater     = new BasicEnergyUpdater <RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData> >(10 * averageSize);
            var roomShapeGeometry = new FastGridPolygonGeometry <ConfigurationGrid2D <TRoom, EnergyData>, RoomNode <TRoom> >();

            // Create generator constraints
            var stageOneConstraints =
                new List <INodeConstraint <ILayout <RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData> >, RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData>,
                                           EnergyData> >
            {
                new BasicConstraint <RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData>, EnergyData>(
                    roomShapeGeometry,
                    simpleConfigurationSpaces,
                    levelDescriptionMapped,
                    configuration.OptimizeCorridorConstraints
                    ),
                new CorridorConstraint <RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData>, EnergyData>(
                    levelDescriptionMapped,
                    simpleConfigurationSpaces,
                    roomShapeGeometry
                    ),
            };

            if (levelDescription.MinimumRoomDistance > 0)
            {
                stageOneConstraints.Add(new MinimumDistanceConstraint <RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData>, EnergyData>(
                                            levelDescriptionMapped,
                                            roomShapeGeometry,
                                            levelDescription.MinimumRoomDistance
                                            ));
            }

            var constraintsEvaluator = new ConstraintsEvaluator <RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData>, EnergyData>(stageOneConstraints, energyUpdater);

            var roomShapesHandler = new RoomShapesHandlerGrid2D <RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData> >(
                intAliasMapping,
                levelDescriptionMapped,
                shapesForNodes,
                levelDescription.RoomTemplateRepeatModeOverride,
                levelDescription.RoomTemplateRepeatModeDefault
                );

            // Create layout operations
            var layoutOperations = new LayoutController <Layout <TRoom, ConfigurationGrid2D <TRoom, EnergyData> >, RoomNode <TRoom>, ConfigurationGrid2D <TRoom, EnergyData>, RoomTemplateInstanceGrid2D, EnergyData>(averageSize, levelDescriptionMapped, constraintsEvaluator, roomShapesHandler, configuration.ThrowIfRepeatModeNotSatisfied, simpleConfigurationSpaces, roomShapeGeometry);

            var initialLayout   = new Layout <TRoom, ConfigurationGrid2D <TRoom, EnergyData> >(levelDescriptionMapped.GetGraph());
            var layoutConverter =
                new BasicLayoutConverterGrid2D <TRoom,
                                                ConfigurationGrid2D <TRoom, EnergyData> >(levelDescription, simpleConfigurationSpaces,
                                                                                          intAliasMapping);

            // Create simulated annealing evolver
            var layoutEvolver =
                new Common.SimulatedAnnealingEvolver <Layout <TRoom, ConfigurationGrid2D <TRoom, EnergyData> >, RoomNode <TRoom>,
                                                      ConfigurationGrid2D <TRoom, EnergyData> >(layoutOperations, configuration.SimulatedAnnealingConfiguration, true);

            // Create the generator itself
            generator = new ChainBasedGenerator <Layout <TRoom, ConfigurationGrid2D <TRoom, EnergyData> >, LayoutGrid2D <TRoom>, RoomNode <TRoom> >(initialLayout, generatorPlanner, chains, layoutEvolver, layoutConverter);

            // Register event handlers
            generator.OnRandomInjected += (random) =>
            {
                // ((IRandomInjectable)configurationSpaces).InjectRandomGenerator(random);
                ((IRandomInjectable)layoutOperations).InjectRandomGenerator(random);
                ((IRandomInjectable)layoutEvolver).InjectRandomGenerator(random);
                ((IRandomInjectable)layoutConverter).InjectRandomGenerator(random);
                ((IRandomInjectable)simpleConfigurationSpaces).InjectRandomGenerator(random);
                ((IRandomInjectable)roomShapesHandler).InjectRandomGenerator(random);
            };

            generator.OnCancellationTokenInjected += (token) =>
            {
                ((ICancellable)generatorPlanner).SetCancellationToken(token);
                ((ICancellable)layoutEvolver).SetCancellationToken(token);
            };

            layoutEvolver.OnEvent              += (sender, args) => OnSimulatedAnnealingEvent?.Invoke(sender, args);
            layoutEvolver.OnPerturbed          += (sender, layout) => OnPerturbed?.Invoke(layoutConverter.Convert(layout, false));
            layoutEvolver.OnPerturbed          += (sender, layout) => OnPerturbedInternal?.Invoke(layout);
            layoutEvolver.OnValid              += (sender, layout) => OnPartialValid?.Invoke(layoutConverter.Convert(layout, true));
            generatorPlanner.OnLayoutGenerated += layout => OnValid?.Invoke(layoutConverter.Convert(layout, true));
        }