Example #1
0
        public void TransformPointToNewPosition_RectanglePoints()
        {
            // Create a rectangular room shape
            // Move it away from (0, 0) so that we can properly test the functionality
            var rectangleShape = GridPolygon.GetRectangle(10, 4) + new IntVector2(10, 10);

            // Create points to be transformed
            // These could be for example traps, spawn points, etc.
            // We use points of the rectangle here because it is easy to check that the transformation is correct.
            var pointsToTransform = rectangleShape.GetPoints();

            var mapDescription = new MapDescription <int>();

            // Create simple graph with 2 vertices and 1 edge
            mapDescription.AddRoom(0);
            mapDescription.AddRoom(1);
            mapDescription.AddPassage(0, 1);

            // Add the rectangle shape
            mapDescription.AddRoomShapes(new RoomDescription(rectangleShape, new OverlapMode(1, 0)));

            var layoutGenerator = LayoutGeneratorFactory.GetDefaultChainBasedGenerator <int>();
            var layout          = layoutGenerator.GetLayouts(mapDescription, 1)[0];

            foreach (var room in layout.Rooms)
            {
                // The points were chosen to be the points of the polygon, so after transforming them, they should
                // be equal to the room.Shape + room.Position points
                var transformedPoints = pointsToTransform.Select(x => room.TransformPointToNewPosition(x));
                var expectedPoints    = (room.Shape + room.Position).GetPoints();

                Assert.That(transformedPoints, Is.EquivalentTo(expectedPoints));
            }
        }
        /// <summary>
        /// Runs one of the example presented in the Tutorial.
        /// </summary>
        public static void RunExample()
        {
            var configLoader    = new ConfigLoader();
            var layoutGenerator = LayoutGeneratorFactory.GetDefaultChainBasedGenerator <int>();

            // var layoutGenerator = LayoutGeneratorFactory.GetChainBasedGeneratorWithCorridors<int>(new List<int>() {1});
            layoutGenerator.InjectRandomGenerator(new Random(0));

            // var mapDescription = new BasicsExample().GetMapDescription();
            // var mapDescription = configLoader.LoadMapDescription("Resources/Maps/tutorial_basicDescription.yml");

            // var mapDescription = new DifferentShapesExample().GetMapDescription();
            // var mapDescription = configLoader.LoadMapDescription("Resources/Maps/tutorial_differentShapes.yml");

            // var mapDescription = new DIfferentProbabilitiesExample().GetMapDescription();
            var mapDescription = configLoader.LoadMapDescription("Resources/Maps/tutorial_differentProbabilities.yml");

            // var mapDescription = new CorridorsExample().GetMapDescription();
            // var mapDescription = configLoader.LoadMapDescription("Resources/Maps/tutorial_corridors.yml");

            var settings = new GeneratorSettings
            {
                MapDescription  = mapDescription,
                LayoutGenerator = layoutGenerator,

                NumberOfLayouts = 10,

                ShowPartialValidLayouts     = false,
                ShowPartialValidLayoutsTime = 500,
            };

            Application.Run(new GeneratorWindow(settings));
        }
        /// <summary>
        /// Runs a prepared benchmark.
        /// </summary>
        public static void RunBenchmark()
        {
            var scale   = new IntVector2(1, 1);
            var offsets = new List <int>()
            {
                2
            };
            const bool enableCorridors = false;

            //var mapDescriptions = GetMapDescriptionsSet(scale, enableCorridors, offsets);
            var mapDescriptions = GetMapDescriptionsForThesis(false);

            var layoutGenerator = LayoutGeneratorFactory.GetDefaultChainBasedGenerator <int>();
            // var layoutGenerator = LayoutGeneratorFactory.GetChainBasedGeneratorWithCorridors<int>(offsets);

            var benchmark = Benchmark.CreateFor(layoutGenerator);

            layoutGenerator.InjectRandomGenerator(new Random(0));
            layoutGenerator.SetLayoutValidityCheck(false);

            //layoutGenerator.SetChainDecompositionCreator(mapDescription => new OldChainDecomposition<int>(new GraphDecomposer<int>()));
            //// layoutGenerator.SetChainDecompositionCreator(mapDescription => new BreadthFirstChainDecomposition<int>(new GraphDecomposer<int>(), false));
            // layoutGenerator.SetGeneratorPlannerCreator(mapDescription => new SlowGeneratorPlanner<Layout<Configuration<EnergyData>, BasicEnergyData>>());
            //layoutGenerator.SetLayoutEvolverCreator((mapDescription, layoutOperations) =>
            //{
            //	var evolver =
            //		new SimulatedAnnealingEvolver<Layout<Configuration<EnergyData>, BasicEnergyData>, int,
            //			Configuration<EnergyData>>(layoutOperations);
            //	evolver.Configure(50, 500);
            //	evolver.SetRandomRestarts(true, SimulatedAnnealingEvolver<Layout<Configuration<EnergyData>, BasicEnergyData>, int, Configuration<EnergyData>>.RestartSuccessPlace.OnAccepted, false, 0.5f);

            //	return evolver;
            //});

            var scenario = BenchmarkScenario.CreateScenarioFor(layoutGenerator);

            scenario.SetRunsCount(2);

            var setups = scenario.MakeSetupsGroup();

            setups.AddSetup("Fixed generator", (generator) => generator.InjectRandomGenerator(new Random()));

            Benchmark.WithDefaultFiles((sw, dw) =>
            {
                benchmark.Execute(layoutGenerator, scenario, mapDescriptions, 100, 1, sw, dw);
            });
        }
Example #4
0
 private static void SaveBitmap(MapDescription <int> mapDescription, int seed, string name = null)
 {
     try
     {
         Stopwatch dunWatch = new Stopwatch();
         dunWatch.Start();
         var layoutGenerator = LayoutGeneratorFactory.GetDefaultChainBasedGenerator <int>();
         layoutGenerator.InjectRandomGenerator(new Random(seed));
         Debug.WriteLine(mapDescription.GetGraph().ToString());
         List <IMapLayout <int> > generatedLayouts = (List <IMapLayout <int> >)layoutGenerator.GetLayouts(mapDescription, 10); //Magic number 3 is how many different layouts we want
         dunWatch.Stop();
         dunGenerationTime = dunWatch.Elapsed.TotalSeconds;
         exportAllJpgButton_Click(generatedLayouts, name);
     }
     catch (ArgumentException e)
     {
         Debug.WriteLine($"{e.Message} by {e.ParamName} with: {e.Data} {e.StackTrace}");
     }
 }
Example #5
0
 /// <summary>
 /// Gets a basic layout generator that should not be used to generated layouts with corridors.
 /// </summary>
 /// <typeparam name="TNode"></typeparam>
 /// <returns></returns>
 public static ChainBasedGenerator <MapDescription <TNode>, Layout <Configuration <EnergyData>, BasicEnergyData>, int, Configuration <EnergyData>, IMapLayout <TNode> > GetDefaultChainBasedGenerator <TNode>()
 {
     return(LayoutGeneratorFactory.GetDefaultChainBasedGenerator <TNode>());
 }
Example #6
0
        /// <summary>
        /// Run the generator.
        /// </summary>
        private void Run()
        {
            cancellationTokenSource = new CancellationTokenSource();
            var ct = cancellationTokenSource.Token;

            task = Task.Run(() =>
            {
                try
                {
                    dumpFolder          = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();
                    dumpCount           = 0;
                    var layoutGenerator = settings.LayoutGenerator;

                    if (layoutGenerator == null)
                    {
                        if (settings.MapDescription.IsWithCorridors)
                        {
                            var defaultGenerator =
                                LayoutGeneratorFactory.GetChainBasedGeneratorWithCorridors <int>(settings.MapDescription.CorridorsOffsets);
                            defaultGenerator.InjectRandomGenerator(new Random(settings.RandomGeneratorSeed));

                            layoutGenerator = defaultGenerator;
                        }
                        else
                        {
                            var defaultGenerator = LayoutGeneratorFactory.GetDefaultChainBasedGenerator <int>();
                            defaultGenerator.InjectRandomGenerator(new Random(settings.RandomGeneratorSeed));

                            layoutGenerator = defaultGenerator;
                        }
                    }

                    // Set cancellation token
                    if (layoutGenerator is ICancellable cancellable)
                    {
                        cancellable.SetCancellationToken(ct);
                    }

                    infoStopwatch.Start();

                    // Register handler that shows generated layouts OnValid
                    layoutGenerator.OnValid += layout =>
                    {
                        if (!showFinalLayouts.Checked)
                        {
                            return;
                        }

                        lastEvent    = GeneratorEvent.OnValid;
                        layoutToDraw = layout;
                        mainPictureBox.BeginInvoke((Action)(() => mainPictureBox.Refresh()));
                        SleepWithFastCancellation((int)showFinalLayoutsTime.Value, ct);
                    };

                    // Register handler that shows generated layouts OnPartialValid
                    layoutGenerator.OnPartialValid += layout =>
                    {
                        if (!showPartialValidLayouts.Checked)
                        {
                            return;
                        }

                        lastEvent    = GeneratorEvent.OnPartialValid;
                        layoutToDraw = layout;
                        mainPictureBox.BeginInvoke((Action)(() => mainPictureBox.Refresh()));
                        SleepWithFastCancellation((int)showAcceptedLayoutsTime.Value, ct);
                    };

                    // Register handler that shows generated layouts OnPerturbed
                    layoutGenerator.OnPerturbed += layout =>
                    {
                        if (!showPerturbedLayouts.Checked)
                        {
                            return;
                        }

                        lastEvent    = GeneratorEvent.OnPerturbed;
                        layoutToDraw = layout;
                        mainPictureBox.BeginInvoke((Action)(() => mainPictureBox.Refresh()));
                        SleepWithFastCancellation((int)showPerturbedLayoutsTime.Value, ct);
                    };

                    // Register handler that counts iteration count
                    layoutGenerator.OnPerturbed += layout =>
                    {
                        lastEvent = GeneratorEvent.OnPerturbed;
                        iterationsCount++;
                        if (infoStopwatch.ElapsedMilliseconds >= 200)
                        {
                            BeginInvoke((Action)(UpdateInfoPanel));
                            infoStopwatch.Restart();
                        }
                    };

                    // Register handler that resets iteration count
                    layoutGenerator.OnValid += layout =>
                    {
                        lastEvent       = GeneratorEvent.OnValid;
                        iterationsCount = 0;
                        layoutsCount++;
                        BeginInvoke((Action)(UpdateInfoPanel));
                        infoStopwatch.Restart();
                    };

                    generatedLayouts =
                        (List <IMapLayout <int> >)layoutGenerator.GetLayouts(settings.MapDescription, settings.NumberOfLayouts);

                    isRunning = false;
                    BeginInvoke((Action)(UpdateInfoPanel));
                    BeginInvoke((Action)(OnFinished));
                }
                catch (Exception e)
                {
                    ShowExceptionAndClose(e);
                }
            }, ct);
        }
        /// <summary>
        /// Benchmark our speed improvements.
        /// </summary>
        public static void CompareOldAndNew()
        {
            //var mapDescriptions = GetMapDescriptionsSet(new IntVector2(1, 1), false);
            var mapDescriptions = GetMapDescriptionsForThesis(false);

            var layoutGenerator = LayoutGeneratorFactory.GetDefaultChainBasedGenerator <int>();
            var benchmark       = Benchmark.CreateFor(layoutGenerator);

            layoutGenerator.InjectRandomGenerator(new Random(0));
            layoutGenerator.SetLayoutValidityCheck(false);

            var scenario = BenchmarkScenario.CreateScenarioFor(layoutGenerator);

            scenario.SetRunsCount(1);

            // Measure the difference between old and new approaches
            {
                var setups = scenario.MakeSetupsGroup();

                setups.AddSetup("Old", (generator) =>
                {
                    //generator.SetChainDecompositionCreator(mapDescription => new OriginalChainDecomposition());
                    generator.SetChainDecompositionCreator(mapDescription => new OldChainDecomposition <int>(new GraphDecomposer <int>()));
                    //generator.SetGeneratorPlannerCreator(mapDescription => new SlowGeneratorPlanner<Layout<Configuration<EnergyData>, BasicEnergyData>>());
                    //generator.SetLayoutEvolverCreator((mapDescription, layoutOperations) =>
                    //{
                    //	var evolver =
                    //		new SimulatedAnnealingEvolver<Layout<Configuration<EnergyData>, BasicEnergyData>, int,
                    //			Configuration<EnergyData>>(layoutOperations);
                    //	evolver.Configure(50, 500);
                    //	evolver.SetRandomRestarts(true, SimulatedAnnealingEvolver<Layout<Configuration<EnergyData>, BasicEnergyData>, int, Configuration<EnergyData>>.RestartSuccessPlace.OnAccepted, false, 0.5f);

                    //	return evolver;
                    //});

                    generator.SetGeneratorPlannerCreator(mapDescription => new BasicGeneratorPlanner <Layout <Configuration <EnergyData>, BasicEnergyData> >());
                    generator.SetLayoutEvolverCreator((mapDescription, layoutOperations) =>
                    {
                        var evolver =
                            new SimulatedAnnealingEvolver <Layout <Configuration <EnergyData>, BasicEnergyData>, int,
                                                           Configuration <EnergyData> >(layoutOperations);

                        return(evolver);
                    });

                    generator.InjectRandomGenerator(new Random(0));
                });
                setups.AddSetup("New", (generator) =>
                {
                    generator.SetChainDecompositionCreator(mapDescription =>
                                                           new BreadthFirstChainDecomposition <int>(new GraphDecomposer <int>()));
                    generator.SetGeneratorPlannerCreator(mapDescription => new BasicGeneratorPlanner <Layout <Configuration <EnergyData>, BasicEnergyData> >());
                    generator.SetLayoutEvolverCreator((mapDescription, layoutOperations) =>
                    {
                        var evolver =
                            new SimulatedAnnealingEvolver <Layout <Configuration <EnergyData>, BasicEnergyData>, int,
                                                           Configuration <EnergyData> >(layoutOperations);

                        return(evolver);
                    });

                    generator.InjectRandomGenerator(new Random(0));
                });
            }

            Benchmark.WithDefaultFiles((sw, dw) =>
            {
                benchmark.Execute(layoutGenerator, scenario, mapDescriptions, 80, 1, sw, dw);
            });
        }