Beispiel #1
0
        public void CustomModel1LoadSave()
        {
            SpaceEngineersCore.LoadDefinitions();
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var cockpitModelPath = Path.Combine(contentPath, @"Models\Characters\Animations\cockpit1_large.mwm");

            Assert.IsTrue(File.Exists(cockpitModelPath), "Filepath should exist on developer machine");

            var modelData = MyModel.LoadCustomModelData(cockpitModelPath);

            var testFilePath = @".\TestOutput\cockpit_animation.mwm";

            MyModel.SaveModelData(testFilePath, modelData);

            var originalBytes = File.ReadAllBytes(cockpitModelPath);
            var newBytes      = File.ReadAllBytes(testFilePath);

            Assert.AreEqual(originalBytes.Length, newBytes.Length, "Bytestream content must equal");
            Assert.IsTrue(originalBytes.SequenceEqual(newBytes), "Bytestream content must equal");
        }
Beispiel #2
0
        public void ReadBackgroundTextures()
        {
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var backgroundPath = Path.Combine(contentPath, @"Textures\BackgroundCube\Final\BackgroundCube.dds");

            Assert.IsTrue(File.Exists(backgroundPath), "Filepath should exist on developer machine");

            var backgroundBmp = TexUtil.CreateBitmap(backgroundPath, 0, -1, -1);

            ImageTextureUtil.WriteImage(backgroundBmp, @".\TestOutput\BackgroundCube0_Full.png");

            backgroundBmp = TexUtil.CreateBitmap(backgroundPath, 1, 1024, 1024);
            ImageTextureUtil.WriteImage(backgroundBmp, @".\TestOutput\BackgroundCube1_1024.png");

            backgroundBmp = TexUtil.CreateBitmap(backgroundPath, 2, 512, 512);
            ImageTextureUtil.WriteImage(backgroundBmp, @".\TestOutput\BackgroundCube2_512.png");

            backgroundBmp = TexUtil.CreateBitmap(backgroundPath, 3, 128, 128);
            ImageTextureUtil.WriteImage(backgroundBmp, @".\TestOutput\BackgroundCube3_128.png");

            backgroundBmp = TexUtil.CreateBitmap(backgroundPath, 4, 64, 64);
            ImageTextureUtil.WriteImage(backgroundBmp, @".\TestOutput\BackgroundCube4_64.png");

            backgroundBmp = TexUtil.CreateBitmap(backgroundPath, 5, 32, 32);
            ImageTextureUtil.WriteImage(backgroundBmp, @".\TestOutput\BackgroundCube5_32.png");
        }
Beispiel #3
0
        public void CreateMenuTextures()
        {
            SpaceEngineersCore.LoadDefinitions();

            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var smallBlockLandingGear     = SpaceEngineersApi.GetDefinition(new MyObjectBuilderType(typeof(MyObjectBuilder_LandingGear)), "SmallBlockLandingGear");
            var smallBlockLandingGearPath = Path.Combine(contentPath, smallBlockLandingGear.Icons.First());

            Assert.IsTrue(File.Exists(smallBlockLandingGearPath), "Filepath should exist on developer machine");
            Assert.IsTrue(smallBlockLandingGear is MyObjectBuilder_CubeBlockDefinition, "Type should match");
            var smallBlockLandingGearBmp = TexUtil.CreateBitmap(smallBlockLandingGearPath);

            var gridItemPath = Path.Combine(contentPath, @"Textures\GUI\Controls\grid_item.dds");

            Assert.IsTrue(File.Exists(gridItemPath), "Filepath should exist on developer machine");
            var gridBmp = TexUtil.CreateBitmap(gridItemPath);

            var bmp = ImageTextureUtil.MergeImages(gridBmp, smallBlockLandingGearBmp, Brushes.Black);

            ImageTextureUtil.WriteImage(bmp, @".\TestOutput\Menu_SmallBlockLandingGear.png");
        }
        public void Load(MyCubeSize cubeSize, MyObjectBuilderType typeId, string subTypeId)
        {
            CubeList.Clear();
            var list            = new SortedList <string, ComponentItemModel>();
            var contentPath     = ToolboxUpdater.GetApplicationContentPath();
            var cubeDefinitions = SpaceEngineersCore.Resources.CubeBlockDefinitions.Where(c => c.CubeSize == cubeSize);

            foreach (var cubeDefinition in cubeDefinitions)
            {
                var c = new ComponentItemModel
                {
                    Name         = cubeDefinition.DisplayNameText,
                    TypeId       = cubeDefinition.Id.TypeId,
                    TypeIdString = cubeDefinition.Id.TypeId.ToString(),
                    SubtypeId    = cubeDefinition.Id.SubtypeName,
                    TextureFile  = (cubeDefinition.Icons == null || cubeDefinition.Icons.First() == null) ? null : SpaceEngineersCore.GetDataPathOrDefault(cubeDefinition.Icons.First(), Path.Combine(contentPath, cubeDefinition.Icons.First())),
                    Time         = TimeSpan.FromSeconds(cubeDefinition.MaxIntegrity / cubeDefinition.IntegrityPointsPerSec),
                    Accessible   = cubeDefinition.Public,
                    Mass         = SpaceEngineersApi.FetchCubeBlockMass(cubeDefinition.Id.TypeId, cubeDefinition.CubeSize, cubeDefinition.Id.SubtypeName),
                    CubeSize     = cubeDefinition.CubeSize,
                    Size         = new BindableSize3DIModel(cubeDefinition.Size),
                };

                list.Add(c.FriendlyName + c.TypeIdString + c.SubtypeId, c);
            }

            foreach (var kvp in list)
            {
                CubeList.Add(kvp.Value);
            }

            CubeItem = CubeList.FirstOrDefault(c => c.TypeId == typeId && c.SubtypeId == subTypeId);
        }
Beispiel #5
0
        public void BaseModel1LoadSave()
        {
            SpaceEngineersCore.LoadDefinitions();
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var largeThruster     = (MyObjectBuilder_CubeBlockDefinition)SpaceEngineersApi.GetDefinition(SpaceEngineersTypes.Thrust, "LargeBlockLargeThrust");
            var thrusterModelPath = Path.Combine(contentPath, largeThruster.Model);

            Assert.IsTrue(File.Exists(thrusterModelPath), "Filepath should exist on developer machine");

            var modelData = MyModel.LoadModelData(thrusterModelPath);
            //var modelData = MyModel.LoadCustomModelData(thrusterModelPath);

            var testFilePath = @".\TestOutput\Thruster.mwm";

            MyModel.SaveModelData(testFilePath, modelData);

            var originalBytes = File.ReadAllBytes(thrusterModelPath);
            var newBytes      = File.ReadAllBytes(testFilePath);

            Assert.AreEqual(originalBytes.Length, newBytes.Length, "Bytestream content must equal");
            Assert.IsTrue(originalBytes.SequenceEqual(newBytes), "Bytestream content must equal");
        }
Beispiel #6
0
        public void VoxelLoadStock()
        {
            SpaceEngineersCore.LoadDefinitions();
            var materials = SpaceEngineersCore.Resources.GetMaterialList();

            Assert.IsTrue(materials.Count > 0, "Materials should exist. Has the developer got Space Engineers installed?");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();
            var redShipCrashedAsteroidPath = Path.Combine(contentPath, "VoxelMaps", "RedShipCrashedAsteroid.vx2");

            var voxelMap = new MyVoxelMap();

            voxelMap.Load(redShipCrashedAsteroidPath, materials[0].Id.SubtypeId);

            Assert.AreEqual(1, voxelMap.FileVersion, "FileVersion should be equal.");

            IList <byte>            materialAssets;
            Dictionary <byte, long> materialVoxelCells;

            voxelMap.CalculateMaterialCellAssets(out materialAssets, out materialVoxelCells);
            Assert.AreEqual(563742, materialAssets.Count, "Asset count should be equal.");

            var asset0 = materialAssets.Where(c => c == 0).ToList();

            Assert.AreEqual(563742, asset0.Count, "asset0 count should be equal.");

            var assetNameCount = voxelMap.CountAssets(materialAssets);

            Assert.IsTrue(assetNameCount.Count > 0, "Contains assets.");

            var lengthOriginal = new FileInfo(redShipCrashedAsteroidPath).Length;

            Assert.AreEqual(51819, lengthOriginal, "File size must match.");
        }
Beispiel #7
0
        public void ConvertCubeToLightArmorExecuted()
        {
            MainViewModel.IsBusy = true;
            MainViewModel.ResetProgress(0, Selections.Count);

            var  contentPath = ToolboxUpdater.GetApplicationContentPath();
            bool changes     = false;

            foreach (var cubeVm in Selections)
            {
                MainViewModel.Progress++;
                if (cubeVm.ConvertFromHeavyToLightArmor())
                {
                    changes = true;

                    var idx            = DataModel.CubeGrid.CubeBlocks.IndexOf(cubeVm.Cube);
                    var cubeDefinition = SpaceEngineersApi.GetCubeDefinition(cubeVm.Cube.TypeId, GridSize, cubeVm.Cube.SubtypeName);
                    var newCube        = cubeVm.CreateCube(cubeVm.Cube.TypeId, cubeVm.Cube.SubtypeName, cubeDefinition);
                    cubeVm.TextureFile = (cubeDefinition.Icons == null || cubeDefinition.Icons.First() == null) ? null : SpaceEngineersCore.GetDataPathOrDefault(cubeDefinition.Icons.First(), Path.Combine(contentPath, cubeDefinition.Icons.First()));

                    DataModel.CubeGrid.CubeBlocks.RemoveAt(idx);
                    DataModel.CubeGrid.CubeBlocks.Insert(idx, newCube);
                }
            }

            MainViewModel.ClearProgress();
            if (changes)
            {
                MainViewModel.IsModified = true;
            }
            MainViewModel.IsBusy = false;
        }
        public SpaceEngineersCore()
        {
            var    contentPath  = ToolboxUpdater.GetApplicationContentPath();
            string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath;

            MyFileSystem.Reset();
            MyFileSystem.Init(contentPath, userDataPath);

            MyLog.Default        = MySandboxGame.Log;
            MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME.
            MySandboxGame.Config.Load();

            MyFileSystem.InitUserSpecific(null);

            SpaceEngineersGame.SetupPerGameSettings();

            VRageRender.MyRenderProxy.Initialize(new MyNullRender());
            // We create a whole instance of MySandboxGame!
            MySandboxGame gameTemp = new MySandboxGame(null);

            // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it.
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode);
            SpaceEngineersApi.LoadLocalization();

            _stockDefinitions = new SpaceEngineersResources();
            _stockDefinitions.LoadDefinitions();
            _manageDeleteVoxelList = new List <string>();
        }
Beispiel #9
0
        internal void Additem(MyObjectBuilder_InventoryItem item)
        {
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            item.ItemId = _inventory.nextItemId++;
            _inventory.Items.Add(item);
            Items.Add(CreateItem(item, contentPath));
        }
Beispiel #10
0
        public SpaceEngineersCore()
        {
            var    contentPath  = ToolboxUpdater.GetApplicationContentPath();
            string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath;

            MyFileSystem.Reset();
            MyFileSystem.Init(contentPath, userDataPath);

            MyLog.Default        = MySandboxGame.Log;
            MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME.
            MySandboxGame.Config.Load();

            MyFileSystem.InitUserSpecific(null);

            SpaceEngineersGame.SetupPerGameSettings();

            VRageRender.MyRenderProxy.Initialize(new MyNullRender());
            // We create a whole instance of MySandboxGame!
            // If this is causing an exception, then there is a missing dependency.
            MySandboxGame gameTemp = new MySandboxGame(new string[] { "-skipintro" });

            // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it.
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode);
            SpaceEngineersApi.LoadLocalization();
            MyStorageBase.UseStorageCache = false;

            #region MySession creation

            // Replace the private constructor on MySession, so we can create it without getting involed with Havok and other depdancies.
            var keenStart = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null);
            var ourStart  = typeof(SEToolbox.Interop.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null);
            ReflectionUtil.ReplaceMethod(ourStart, keenStart);

            // Create an empty instance of MySession for use by low level code.
            Sandbox.Game.World.MySession mySession = ReflectionUtil.ConstructPrivateClass <Sandbox.Game.World.MySession>(new Type[0], new object[0]);
            ReflectionUtil.ConstructField(mySession, "m_sessionComponents"); // Required as the above code doesn't populate it during ctor of MySession.
            mySession.Settings = new MyObjectBuilder_SessionSettings {
                EnableVoxelDestruction = true
            };

            VRage.MyVRage.Init(new ToolboxPlatform());

            // change for the Clone() method to use XML cloning instead of Protobuf because of issues with MyObjectBuilder_CubeGrid.Clone()
            ReflectionUtil.SetFieldValue(typeof(VRage.ObjectBuilders.MyObjectBuilderSerializer), "ENABLE_PROTOBUFFERS_CLONING", false);

            // Assign the instance back to the static.
            Sandbox.Game.World.MySession.Static = mySession;

            Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static = new MyHeightMapLoadingSystem();
            Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static.LoadData();

            #endregion

            _stockDefinitions = new SpaceEngineersResources();
            _stockDefinitions.LoadDefinitions();
            _manageDeleteVoxelList = new List <string>();
        }
Beispiel #11
0
        public void LoadAllCubeTextures()
        {
            var files = Directory.GetFiles(Path.Combine(ToolboxUpdater.GetApplicationContentPath(), @"Textures\Models\Cubes"), "*.dds");

            foreach (var filename in files)
            {
                var outputFilename = Path.Combine(@".\TestOutput", Path.GetFileNameWithoutExtension(filename) + ".png");
                var imageBitmap    = TestLoadTexture(filename);
                ImageTextureUtil.WriteImage(imageBitmap, outputFilename);
            }
        }
Beispiel #12
0
        public static void LoadLocalization()
        {
            var languageTag = System.Threading.Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;

            var contentPath      = ToolboxUpdater.GetApplicationContentPath();
            var localizationPath = Path.Combine(contentPath, @"Data\Localization");

            var codes    = languageTag.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            var maincode = codes.Length > 0 ? codes[0] : null;
            var subcode  = codes.Length > 1 ? codes[1] : null;

            MyTexts.Clear();
            MyTexts.LoadTexts(localizationPath, maincode, subcode);
        }
Beispiel #13
0
        public void LoadComponentTexturesDx10PremultipliedAlpha()
        {
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();


            TestLoadTextureAndExport(Path.Combine(contentPath, @"Textures\GUI\Icons\Cubes\AdvancedMotor.dds"));

            TestLoadTextureAndExport(Path.Combine(contentPath, @"Textures\GUI\Icons\component\ExplosivesComponent.dds"));
        }
Beispiel #14
0
        //[TestMethod]
        public void LoadModelFailures()
        {
            SpaceEngineersCore.LoadDefinitions();
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var files          = Directory.GetFiles(Path.Combine(contentPath, "Models"), "*.mwm", SearchOption.AllDirectories);
            var badList        = new List <string>();
            var convertDiffers = new List <string>();

            foreach (var file in files)
            {
                Dictionary <string, object> data = null;
                try
                {
                    data = MyModel.LoadModelData(file);
                    //data = MyModel.LoadCustomModelData(file);
                }
                catch (Exception)
                {
                    badList.Add(file);
                    continue;
                }

                if (data != null)
                {
                    var testFilePath = @".\TestOutput\TempModelTest.mwm";

                    MyModel.SaveModelData(testFilePath, data);

                    var originalBytes = File.ReadAllBytes(file);
                    var newBytes      = File.ReadAllBytes(testFilePath);

                    if (!originalBytes.SequenceEqual(newBytes))
                    {
                        convertDiffers.Add(file);
                    }

                    //Assert.AreEqual(originalBytes.Length, newBytes.Length, "File {0} Bytestream content must equal", file);
                    //Assert.IsTrue(originalBytes.SequenceEqual(newBytes), "File {0} Bytestream content must equal", file);
                }
            }

            Assert.IsTrue(convertDiffers.Count > 0, "");
            Assert.IsTrue(badList.Count > 0, "");
        }
Beispiel #15
0
        public static void LoadLocalization()
        {
            var culture     = System.Threading.Thread.CurrentThread.CurrentUICulture;
            var languageTag = culture.IetfLanguageTag;

            var contentPath      = ToolboxUpdater.GetApplicationContentPath();
            var localizationPath = Path.Combine(contentPath, @"Data\Localization");

            var codes    = languageTag.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            var maincode = codes.Length > 0 ? codes[0] : null;
            var subcode  = codes.Length > 1 ? codes[1] : null;

            MyTexts.Clear();

            if (GlobalSettings.Default.UseCustomResource.HasValue && GlobalSettings.Default.UseCustomResource.Value)
            {
                // no longer required, as Chinese is now officially in game.
                // left as an example for later additional custom languages.
                //AddLanguage(MyLanguagesEnum.ChineseChina, "zh-CN", null, "Chinese", 1f, true);
            }

            MyTexts.LoadTexts(localizationPath, maincode, subcode);

            if (GlobalSettings.Default.UseCustomResource.HasValue && GlobalSettings.Default.UseCustomResource.Value)
            {
                // Load alternate localization in instead using game refined resources, as they may not yet exist.
                ResourceManager customGameResourceManager = new ResourceManager("SEToolbox.Properties.MyTexts", Assembly.GetExecutingAssembly());
                ResourceSet     customResourceSet         = customGameResourceManager.GetResourceSet(culture, true, false);
                if (customResourceSet != null)
                {
                    // Reflection copy of MyTexts.PatchTexts(string resourceFile)
                    var m_strings        = typeof(MyTexts).GetStaticField <Dictionary <MyStringId, string> >("m_strings");
                    var m_stringBuilders = typeof(MyTexts).GetStaticField <Dictionary <MyStringId, StringBuilder> >("m_stringBuilders");

                    foreach (DictionaryEntry dictionaryEntry in customResourceSet)
                    {
                        string text  = dictionaryEntry.Key as string;
                        string text2 = dictionaryEntry.Value as string;
                        if (text != null && text2 != null)
                        {
                            MyStringId orCompute = MyStringId.GetOrCompute(text);

                            m_strings[orCompute]        = text2;
                            m_stringBuilders[orCompute] = new StringBuilder(text2);
                        }
                    }
                }
            }
        }
Beispiel #16
0
        public void LoadComponentTexturesDx11()
        {
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();


            TestLoadTextureAndExport(Path.Combine(contentPath, @"Textures\Models\Cubes\large_medical_room_cm.dds"));


            TestLoadTextureAndExport(Path.Combine(contentPath, @"Textures\Models\Cubes\large_medical_room_cm.dds"), true);
        }
Beispiel #17
0
        public void CreateBackgroundPreview()
        {
            const int  size        = 128;
            const bool ignoreAlpha = true;

            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var backgroundPath = Path.Combine(contentPath, @"Textures\BackgroundCube\Final\BackgroundCube.dds");

            Assert.IsTrue(File.Exists(backgroundPath), "Filepath should exist on developer machine");

            var result = new Bitmap(size * 4, size * 3);

            using (var graphics = Graphics.FromImage(result))
            {
                //set the resize quality modes to high quality
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                if (ignoreAlpha)
                {
                    graphics.FillRectangle(Brushes.Black, size * 2, size * 1, size, size);
                    graphics.FillRectangle(Brushes.Black, size * 0, size * 1, size, size);
                    graphics.FillRectangle(Brushes.Black, size * 1, size * 0, size, size);
                    graphics.FillRectangle(Brushes.Black, size * 1, size * 2, size, size);
                    graphics.FillRectangle(Brushes.Black, size * 1, size * 1, size, size);
                    graphics.FillRectangle(Brushes.Black, size * 3, size * 1, size, size);
                }

                graphics.DrawImage(TexUtil.CreateBitmap(backgroundPath, 0, size, size, ignoreAlpha), size * 2, size * 1, size, size);
                graphics.DrawImage(TexUtil.CreateBitmap(backgroundPath, 1, size, size, ignoreAlpha), size * 0, size * 1, size, size);
                graphics.DrawImage(TexUtil.CreateBitmap(backgroundPath, 2, size, size, ignoreAlpha), size * 1, size * 0, size, size);
                graphics.DrawImage(TexUtil.CreateBitmap(backgroundPath, 3, size, size, ignoreAlpha), size * 1, size * 2, size, size);
                graphics.DrawImage(TexUtil.CreateBitmap(backgroundPath, 4, size, size, ignoreAlpha), size * 1, size * 1, size, size);
                graphics.DrawImage(TexUtil.CreateBitmap(backgroundPath, 5, size, size, ignoreAlpha), size * 3, size * 1, size, size);

                // Approximate position of local Sun and light source.
                graphics.FillEllipse(Brushes.White, size * 1 + (int)(size * 0.7), size * 2 + (int)(size * 0.93), (int)(size * 0.06), (int)(size * 0.06));
            }

            ImageTextureUtil.WriteImage(result, string.Format(@".\TestOutput\BackgroundCube_{0}.png", size));
        }
Beispiel #18
0
        public void Load(MyPositionAndOrientation characterPosition)
        {
            CharacterPosition = characterPosition;

            var vms         = SpaceEngineersCore.Resources.Definitions.VoxelMapStorages;
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            foreach (var voxelMap in vms)
            {
                var fileName = SpaceEngineersCore.GetDataPathOrDefault(voxelMap.StorageFile, Path.Combine(contentPath, voxelMap.StorageFile));

                if (!File.Exists(fileName))
                {
                    continue;
                }

                var voxel = new GenerateVoxelDetailModel
                {
                    Name           = Path.GetFileNameWithoutExtension(voxelMap.StorageFile),
                    SourceFilename = fileName,
                    FileSize       = new FileInfo(fileName).Length,
                    Size           = MyVoxelMap.LoadVoxelSize(fileName)
                };
                VoxelFileList.Add(voxel);
            }

            // Custom voxel files directory.
            List <string> files = new List <string>();

            if (!string.IsNullOrEmpty(GlobalSettings.Default.CustomVoxelPath) && Directory.Exists(GlobalSettings.Default.CustomVoxelPath))
            {
                files.AddRange(Directory.GetFiles(GlobalSettings.Default.CustomVoxelPath, "*" + MyVoxelMap.V1FileExtension));
                files.AddRange(Directory.GetFiles(GlobalSettings.Default.CustomVoxelPath, "*" + MyVoxelMap.V2FileExtension));
            }

            VoxelFileList.AddRange(files.Select(file => new GenerateVoxelDetailModel
            {
                Name           = Path.GetFileNameWithoutExtension(file),
                SourceFilename = file,
                FileSize       = new FileInfo(file).Length,
                Size           = MyVoxelMap.LoadVoxelSize(file)
            }));


            VoxelFileList = VoxelFileList.OrderBy(s => s.Name).ToList();
        }
Beispiel #19
0
        public void LoadSandbox_Compressed_BaseEasyStart()
        {
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var baseEasyStart1Path = Path.Combine(contentPath, @"Data\Prefabs\LargeShipRed.sbc");

            Assert.IsTrue(File.Exists(baseEasyStart1Path), "Sandbox content file should exist");

            MyObjectBuilder_Definitions prefabDefinitions;
            bool isCompressed;
            var  ret = SpaceEngineersApi.TryReadSpaceEngineersFile(baseEasyStart1Path, out prefabDefinitions, out isCompressed);

            Assert.IsNotNull(prefabDefinitions, "Sandbox content should not be null");
            Assert.IsTrue(ret, "Sandbox content should have been detected");
            Assert.IsTrue(isCompressed, "Sandbox content should be compressed");
            Assert.IsTrue(prefabDefinitions.Prefabs[0].CubeGrid.CubeBlocks.Count > 10, "Sandbox content should have cube blocks");
        }
Beispiel #20
0
        public StructureVoxelModel(MyObjectBuilder_EntityBase entityBase, string voxelPath)
            : base(entityBase)
        {
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            if (voxelPath != null)
            {
                VoxelFilepath = Path.Combine(voxelPath, Name + MyVoxelMap.V2FileExtension);
                var previewFile = VoxelFilepath;

                if (!File.Exists(VoxelFilepath))
                {
                    var oldFilepath = Path.Combine(voxelPath, Name + MyVoxelMap.V1FileExtension);
                    if (File.Exists(oldFilepath))
                    {
                        SourceVoxelFilepath = oldFilepath;
                        previewFile         = oldFilepath;
                        SpaceEngineersCore.ManageDeleteVoxelList.Add(oldFilepath);
                    }
                }

                // Has a huge upfront loading cost
                //ReadVoxelDetails(previewFile);
            }

            var materialList = new Dictionary <string, string>();

            foreach (MyVoxelMaterialDefinition item in SpaceEngineersCore.Resources.VoxelMaterialDefinitions.OrderBy(m => m.Id.SubtypeName))
            {
                string texture = item.GetVoxelDisplayTexture();
                materialList.Add(item.Id.SubtypeName, texture == null ? null : SpaceEngineersCore.GetDataPathOrDefault(texture, Path.Combine(contentPath, texture)));
            }

            GameMaterialList = new List <VoxelMaterialAssetModel>(materialList.Select(m => new VoxelMaterialAssetModel {
                MaterialName = m.Key, DisplayName = m.Key, TextureFile = m.Value
            }));
            EditMaterialList = new List <VoxelMaterialAssetModel> {
                new VoxelMaterialAssetModel {
                    MaterialName = null, DisplayName = Res.CtlVoxelMnuRemoveMaterial
                }
            };
            EditMaterialList.AddRange(materialList.Select(m => new VoxelMaterialAssetModel {
                MaterialName = m.Key, DisplayName = m.Key, TextureFile = m.Value
            }));
        }
        public void LoadSandbox_Fighter()
        {
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var fighterPath = Path.Combine(contentPath, @"Data\Prefabs\Fighter.sbc");

            Assert.IsTrue(File.Exists(fighterPath), "Sandbox content file should exist");

            MyObjectBuilder_Definitions prefabDefinitions;
            bool   isCompressed;
            string errorInformation;
            var    ret = SpaceEngineersApi.TryReadSpaceEngineersFile(fighterPath, out prefabDefinitions, out isCompressed, out errorInformation);

            Assert.IsNotNull(prefabDefinitions, "Sandbox content should not be null");
            Assert.IsTrue(ret, "Sandbox content should have been detected");
            Assert.IsFalse(isCompressed, "Sandbox content should not be compressed");
            Assert.IsTrue(prefabDefinitions.Prefabs[0].CubeGrids[0].CubeBlocks.Count > 10, "Sandbox content should have cube blocks");
        }
Beispiel #22
0
        public static void LoadLocalization()
        {
            var culture     = System.Threading.Thread.CurrentThread.CurrentUICulture;
            var languageTag = culture.IetfLanguageTag;

            var contentPath      = ToolboxUpdater.GetApplicationContentPath();
            var localizationPath = Path.Combine(contentPath, @"Data\Localization");

            var codes    = languageTag.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            var maincode = codes.Length > 0 ? codes[0] : null;
            var subcode  = codes.Length > 1 ? codes[1] : null;

            MyTexts.Clear();
            MyTexts.LoadTexts(localizationPath, maincode, subcode);

            GlobalSettings.Default.UseCustomResource = !MyTexts.Languages.Any(m => m.Value.FullCultureName.Equals(culture.IetfLanguageTag, StringComparison.InvariantCultureIgnoreCase) ||
                                                                              m.Value.CultureName.Equals(culture.Parent.IetfLanguageTag, StringComparison.InvariantCultureIgnoreCase));
        }
Beispiel #23
0
        private void UpdateGeneralFromEntityBase()
        {
            var list        = new ObservableCollection <InventoryModel>();
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            TotalVolume = 0;
            TotalMass   = 0;

            if (_inventory != null)
            {
                foreach (MyObjectBuilder_InventoryItem item in _inventory.Items)
                {
                    list.Add(CreateItem(item, contentPath));
                }
            }

            Items = list;
        }
        public void ReplaceCubesExecuted()
        {
            var model  = new SelectCubeModel();
            var loadVm = new SelectCubeViewModel(this, model);

            model.Load(GridSize, SelectedCubeItem.Cube.TypeId, SelectedCubeItem.SubtypeId);
            var result = _dialogService.ShowDialog <WindowSelectCube>(this, loadVm);

            if (result == true)
            {
                MainViewModel.IsBusy = true;
                var contentPath = ToolboxUpdater.GetApplicationContentPath();
                var change      = false;
                MainViewModel.ResetProgress(0, Selections.Count);

                foreach (var cube in Selections)
                {
                    MainViewModel.Progress++;
                    if (cube.TypeId != model.CubeItem.TypeId || cube.SubtypeId != model.CubeItem.SubtypeId)
                    {
                        var idx = DataModel.CubeGrid.CubeBlocks.IndexOf(cube.Cube);
                        DataModel.CubeGrid.CubeBlocks.RemoveAt(idx);

                        var cubeDefinition = SpaceEngineersApi.GetCubeDefinition(model.CubeItem.TypeId, GridSize, model.CubeItem.SubtypeId);
                        var newCube        = cube.CreateCube(model.CubeItem.TypeId, model.CubeItem.SubtypeId, cubeDefinition);
                        cube.TextureFile = SpaceEngineersCore.GetDataPathOrDefault(cubeDefinition.Icon, Path.Combine(contentPath, cubeDefinition.Icon));
                        DataModel.CubeGrid.CubeBlocks.Insert(idx, newCube);

                        change = true;
                    }
                }

                MainViewModel.ClearProgress();
                if (change)
                {
                    MainViewModel.IsModified = true;
                }
                MainViewModel.IsBusy = false;
            }
        }
Beispiel #25
0
        public void LoadAllVoxelFiles()
        {
            SpaceEngineersCore.LoadDefinitions();

            var files = Directory.GetFiles(Path.Combine(ToolboxUpdater.GetApplicationContentPath(), "VoxelMaps"), "*.vx2");

            foreach (var filename in files)
            {
                var voxelMap = new MyVoxelMap();
                voxelMap.Load(filename, SpaceEngineersCore.Resources.GetDefaultMaterialName(), true);

                Assert.IsTrue(voxelMap.Size.X > 0, "Voxel Size must be greater than zero.");
                Assert.IsTrue(voxelMap.Size.Y > 0, "Voxel Size must be greater than zero.");
                Assert.IsTrue(voxelMap.Size.Z > 0, "Voxel Size must be greater than zero.");

                Debug.WriteLine(string.Format("Filename:\t{0}.vx2", Path.GetFileName(filename)));
                Debug.WriteLine(string.Format("Bounding Size:\t{0} × {1} × {2} blocks", voxelMap.Size.X, voxelMap.Size.Y, voxelMap.Size.Z));
                Debug.WriteLine(string.Format("Size:\t{0} m × {1} m × {2} m", voxelMap.BoundingContent.SizeInt().X + 1, voxelMap.BoundingContent.SizeInt().Y + 1, voxelMap.BoundingContent.SizeInt().Z + 1));
                Debug.WriteLine(string.Format("Volume:\t{0:##,###.00} m³", (double)voxelMap.SumVoxelCells() / 255));
                Debug.WriteLine("");
            }
        }
        public void Load()
        {
            CubeAssets      = new ObservableCollection <ComponentItemModel>();
            ComponentAssets = new ObservableCollection <ComponentItemModel>();
            ItemAssets      = new ObservableCollection <ComponentItemModel>();
            MaterialAssets  = new ObservableCollection <ComponentItemModel>();

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            foreach (var cubeDefinition in SpaceEngineersCore.Resources.CubeBlockDefinitions)
            {
                var props  = new Dictionary <string, string>();
                var fields = cubeDefinition.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);

                foreach (var field in fields)
                {
                    props.Add(field.Name, GetValue(field, cubeDefinition));
                }

                CubeAssets.Add(new ComponentItemModel
                {
                    Name             = cubeDefinition.DisplayNameText,
                    TypeId           = cubeDefinition.Id.TypeId,
                    TypeIdString     = cubeDefinition.Id.TypeId.ToString(),
                    SubtypeId        = cubeDefinition.Id.SubtypeName,
                    TextureFile      = (cubeDefinition.Icons == null || cubeDefinition.Icons.First() == null) ? null : SpaceEngineersCore.GetDataPathOrDefault(cubeDefinition.Icons.First(), Path.Combine(contentPath, cubeDefinition.Icons.First())),
                    Time             = TimeSpan.FromSeconds(cubeDefinition.MaxIntegrity / cubeDefinition.IntegrityPointsPerSec),
                    Accessible       = cubeDefinition.Public,
                    Mass             = SpaceEngineersApi.FetchCubeBlockMass(cubeDefinition.Id.TypeId, cubeDefinition.CubeSize, cubeDefinition.Id.SubtypeName),
                    CubeSize         = cubeDefinition.CubeSize,
                    Size             = new BindableSize3DIModel(cubeDefinition.Size),
                    CustomProperties = props,
                });
            }

            foreach (var componentDefinition in SpaceEngineersCore.Resources.ComponentDefinitions)
            {
                var   bp     = SpaceEngineersApi.GetBlueprint(componentDefinition.Id.TypeId, componentDefinition.Id.SubtypeName);
                float amount = 0;
                if (bp != null && bp.Results.Length > 0)
                {
                    amount = (float)bp.Results[0].Amount;
                }

                ComponentAssets.Add(new ComponentItemModel
                {
                    Name         = componentDefinition.DisplayNameText,
                    TypeId       = componentDefinition.Id.TypeId,
                    TypeIdString = componentDefinition.Id.TypeId.ToString(),
                    SubtypeId    = componentDefinition.Id.SubtypeName,
                    Mass         = componentDefinition.Mass,
                    TextureFile  = (componentDefinition.Icons == null || componentDefinition.Icons.First() == null) ? null : SpaceEngineersCore.GetDataPathOrDefault(componentDefinition.Icons.First(), Path.Combine(contentPath, componentDefinition.Icons.First())),
                    Volume       = componentDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    Accessible   = componentDefinition.Public,
                    Time         = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds / amount) : (TimeSpan?)null,
                });
            }

            foreach (var physicalItemDefinition in SpaceEngineersCore.Resources.PhysicalItemDefinitions)
            {
                var   bp     = SpaceEngineersApi.GetBlueprint(physicalItemDefinition.Id.TypeId, physicalItemDefinition.Id.SubtypeName);
                float amount = 0;
                if (bp != null)
                {
                    if (bp.Results != null && bp.Results.Length > 0)
                    {
                        amount = (float)bp.Results[0].Amount;
                    }
                }

                float timeMassMultiplyer = 1f;
                if (physicalItemDefinition.Id.TypeId == typeof(MyObjectBuilder_Ore) ||
                    physicalItemDefinition.Id.TypeId == typeof(MyObjectBuilder_Ingot))
                {
                    timeMassMultiplyer = physicalItemDefinition.Mass;
                }

                ItemAssets.Add(new ComponentItemModel
                {
                    Name         = physicalItemDefinition.DisplayNameText,
                    TypeId       = physicalItemDefinition.Id.TypeId,
                    TypeIdString = physicalItemDefinition.Id.TypeId.ToString(),
                    SubtypeId    = physicalItemDefinition.Id.SubtypeName,
                    Mass         = physicalItemDefinition.Mass,
                    Volume       = physicalItemDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    TextureFile  = physicalItemDefinition.Icons == null ? null : SpaceEngineersCore.GetDataPathOrDefault(physicalItemDefinition.Icons.First(), Path.Combine(contentPath, physicalItemDefinition.Icons.First())),
                    Accessible   = physicalItemDefinition.Public,
                    Time         = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds / amount / timeMassMultiplyer) : (TimeSpan?)null,
                });
            }

            foreach (MyVoxelMaterialDefinition voxelMaterialDefinition in SpaceEngineersCore.Resources.VoxelMaterialDefinitions)
            {
                string texture = voxelMaterialDefinition.GetVoxelDisplayTexture();

                MaterialAssets.Add(new ComponentItemModel
                {
                    Name         = voxelMaterialDefinition.Id.SubtypeName,
                    TextureFile  = texture == null ? null : SpaceEngineersCore.GetDataPathOrDefault(texture, Path.Combine(contentPath, texture)),
                    IsRare       = voxelMaterialDefinition.IsRare,
                    OreName      = voxelMaterialDefinition.MinedOre,
                    MineOreRatio = voxelMaterialDefinition.MinedOreRatio,
                });
            }
        }
        public void Load(MyPositionAndOrientation characterPosition, float maxFloatingObjects)
        {
            MaxFloatingObjects = maxFloatingObjects;
            CharacterPosition  = characterPosition;
            StockItemList.Clear();
            var list        = new List <ComponentItemModel>();
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            foreach (var componentDefinition in SpaceEngineersCore.Resources.ComponentDefinitions)
            {
                var bp = SpaceEngineersApi.GetBlueprint(componentDefinition.Id.TypeId, componentDefinition.Id.SubtypeName);
                list.Add(new ComponentItemModel
                {
                    Name        = componentDefinition.DisplayNameText,
                    TypeId      = componentDefinition.Id.TypeId,
                    SubtypeId   = componentDefinition.Id.SubtypeName,
                    Mass        = componentDefinition.Mass,
                    TextureFile = componentDefinition.Icons == null ? null : SpaceEngineersCore.GetDataPathOrDefault(componentDefinition.Icons.First(), Path.Combine(contentPath, componentDefinition.Icons.First())),
                    Volume      = componentDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    Accessible  = componentDefinition.Public,
                    Time        = bp != null ? TimeSpan.FromSeconds(TimeSpan.TicksPerSecond * bp.BaseProductionTimeInSeconds) : (TimeSpan?)null,
                });
            }

            foreach (var physicalItemDefinition in SpaceEngineersCore.Resources.PhysicalItemDefinitions)
            {
                if (physicalItemDefinition.Id.SubtypeName == "CubePlacerItem" || physicalItemDefinition.Id.SubtypeName == "WallPlacerItem")
                {
                    continue;
                }

                var bp = SpaceEngineersApi.GetBlueprint(physicalItemDefinition.Id.TypeId, physicalItemDefinition.Id.SubtypeName);
                list.Add(new ComponentItemModel
                {
                    Name        = physicalItemDefinition.DisplayNameText,
                    TypeId      = physicalItemDefinition.Id.TypeId,
                    SubtypeId   = physicalItemDefinition.Id.SubtypeName,
                    Mass        = physicalItemDefinition.Mass,
                    Volume      = physicalItemDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    TextureFile = physicalItemDefinition.Icons == null ? null : SpaceEngineersCore.GetDataPathOrDefault(physicalItemDefinition.Icons.First(), Path.Combine(contentPath, physicalItemDefinition.Icons.First())),
                    Accessible  = physicalItemDefinition.Public,
                    Time        = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds) : (TimeSpan?)null,
                });
            }

            foreach (var physicalItemDefinition in SpaceEngineersCore.Resources.AmmoMagazineDefinitions)
            {
                var bp = SpaceEngineersApi.GetBlueprint(physicalItemDefinition.Id.TypeId, physicalItemDefinition.Id.SubtypeName);
                list.Add(new ComponentItemModel
                {
                    Name        = physicalItemDefinition.DisplayNameText,
                    TypeId      = physicalItemDefinition.Id.TypeId,
                    SubtypeId   = physicalItemDefinition.Id.SubtypeName,
                    Mass        = physicalItemDefinition.Mass,
                    Volume      = physicalItemDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    TextureFile = physicalItemDefinition.Icons == null ? null : SpaceEngineersCore.GetDataPathOrDefault(physicalItemDefinition.Icons.First(), Path.Combine(contentPath, physicalItemDefinition.Icons.First())),
                    Accessible  = !string.IsNullOrEmpty(physicalItemDefinition.Model),
                    Time        = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds) : (TimeSpan?)null,
                });
            }

            foreach (var item in list.OrderBy(i => i.FriendlyName))
            {
                StockItemList.Add(item);
            }

            //list.Clear();

            //foreach (var cubeDefinition in SpaceEngineersAPI.CubeBlockDefinitions)
            //{
            //    list.Add(new ComponentItemModel
            //    {
            //        Name = cubeDefinition.DisplayName,
            //        TypeId = cubeDefinition.Id.TypeId,
            //        SubtypeId = cubeDefinition.Id.SubtypeName,
            //        CubeSize = cubeDefinition.CubeSize,
            //        TextureFile = cubeDefinition.Icon == null ? null : Path.Combine(contentPath, cubeDefinition.Icon),
            //        Accessible = !string.IsNullOrEmpty(cubeDefinition.Model),
            //    });
            //}

            //foreach (var item in list.OrderBy(i => i.FriendlyName))
            //{
            //    StockItemList.Add(item);
            //}
        }
Beispiel #28
0
        private static void LoadModel3d(Model3DGroup myModel, string filename)
        {
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var tagData = MyModel.LoadCustomModelData(filename);
            //var model = new MyModelImporter();
            //model.ImportData(filename);

            Dictionary <string, VRage.Import.MyModelDummy> dummies = null;

            VRageMath.PackedVector.Byte4[]       normals    = null;
            VRageMath.PackedVector.HalfVector2[] texCoords0 = null;
            //VRageMath.PackedVector.Byte4[] binormals = null;
            //VRageMath.PackedVector.Byte4[] tangents = null;
            //VRageMath.PackedVector.HalfVector2[] texCoords1 = null;
            VRageMath.PackedVector.HalfVector4[] vertices  = null;
            List <VRage.Import.MyMeshPartInfo>   meshParts = null;
            //float specularShininess = 0;
            float specularPower = 0;

            //VRage.Import.MyModelInfo modelInfo = null;

            foreach (var kvp in tagData)
            {
                if (kvp.Key == MyImporterConstants.TAG_DUMMIES)
                {
                    dummies = (Dictionary <string, VRage.Import.MyModelDummy>)kvp.Value;
                }
                if (kvp.Key == MyImporterConstants.TAG_VERTICES)
                {
                    vertices = (VRageMath.PackedVector.HalfVector4[])kvp.Value;
                }
                if (kvp.Key == MyImporterConstants.TAG_MESH_PARTS)
                {
                    meshParts = (List <VRage.Import.MyMeshPartInfo>)kvp.Value;
                }
                //if (kvp.Key == MyImporterConstants.TAG_MODEL_INFO) modelInfo = (VRage.Import.MyModelInfo)kvp.Value;
                //if (kvp.Key == MyImporterConstants.TAG_SPECULAR_SHININESS) specularShininess = (float)kvp.Value;
                if (kvp.Key == MyImporterConstants.TAG_SPECULAR_POWER)
                {
                    specularPower = (float)kvp.Value;
                }
                if (kvp.Key == MyImporterConstants.TAG_NORMALS)
                {
                    normals = (VRageMath.PackedVector.Byte4[])kvp.Value;
                }
                if (kvp.Key == MyImporterConstants.TAG_TEXCOORDS0)
                {
                    texCoords0 = (VRageMath.PackedVector.HalfVector2[])kvp.Value;
                }
                //if (kvp.Key == MyImporterConstants.TAG_BINORMALS) binormals = (VRageMath.PackedVector.Byte4[])kvp.Value;
                //if (kvp.Key == MyImporterConstants.TAG_TANGENTS) tangents = (VRageMath.PackedVector.Byte4[])kvp.Value;
                //if (kvp.Key == MyImporterConstants.TAG_TEXCOORDS1) texCoords1 = (VRageMath.PackedVector.HalfVector2[])kvp.Value;
            }

            foreach (var meshPart in meshParts)
            {
                GeometryModel3D geomentryModel = new GeometryModel3D();
                myModel.Children.Add(geomentryModel);

                MeshGeometry3D meshGeometery = new MeshGeometry3D();
                geomentryModel.Geometry = meshGeometery;

                #region mesh parts

                meshGeometery.Normals            = new Vector3DCollection();
                meshGeometery.Positions          = new Point3DCollection();
                meshGeometery.TextureCoordinates = new PointCollection();
                meshGeometery.TriangleIndices    = new Int32Collection();

                for (var i = 0; i < normals.Length; i++)
                {
                    meshGeometery.Normals.Add(VRage.Import.VF_Packer.UnpackNormal(ref normals[i]).ToVector3D());
                }

                foreach (var vertex in vertices)
                {
                    var vector = vertex.ToVector4();
                    meshGeometery.Positions.Add(new Point3D(vector.W * vector.X, vector.W * vector.Y, vector.W * vector.Z));
                }

                // http://blogs.msdn.com/b/danlehen/archive/2005/11/06/489627.aspx
                //var texTransform = MeshHelper.TransformVector(new Vector3D(0, 0, 0), -90, 90, 0);
                //Transform="scale(1,-1) translate(0,1)"
                foreach (var vertex in texCoords0)
                {
                    meshGeometery.TextureCoordinates.Add(vertex.ToVector2().ToPoint());
                    //var point = vertex.ToVector2().ToPoint();
                    //meshGeometery.TextureCoordinates.Add(new Point(point.X, ((point.Y + 0) * +1) + 0));
                }

                //foreach (var index in meshPart.m_indices)
                //{
                //    meshGeometery.TriangleIndices.Add(index);
                //}

                // Flip the indicides so the textures are on the Outside, not the inside.
                for (var i = 0; i < meshPart.m_indices.Count; i += 3)
                {
                    try
                    {
                        meshGeometery.TriangleIndices.Add(meshPart.m_indices[i + 2]);
                        meshGeometery.TriangleIndices.Add(meshPart.m_indices[i + 1]);
                        meshGeometery.TriangleIndices.Add(meshPart.m_indices[i + 0]);
                    }
                    catch
                    {
                        break;
                    }
                }

                #endregion


                if (meshPart.m_MaterialDesc != null)
                {
                    #region filenames

                    var diffuseTextureName = meshPart.m_MaterialDesc.Textures.FirstOrDefault().Value;

                    var directoryName = Path.GetDirectoryName(diffuseTextureName);
                    var textureName   = Path.GetFileNameWithoutExtension(diffuseTextureName);
                    var textureExt    = Path.GetExtension(diffuseTextureName);

                    if (textureName.LastIndexOf(C_POSTFIX_DIFFUSE) == (textureName.Length - 2))
                    {
                        textureName = textureName.Substring(0, textureName.Length - 2);
                    }

                    if (textureName.LastIndexOf(C_POSTFIX_DIFFUSE_EMISSIVE) == (textureName.Length - 3))
                    {
                        textureName = textureName.Substring(0, textureName.Length - 3);
                    }

                    if (textureName.LastIndexOf(C_POSTFIX_MASK_EMISSIVE) == (textureName.Length - 3))
                    {
                        textureName = textureName.Substring(0, textureName.Length - 3);
                    }
                    var maskTextureFile     = Path.Combine(Path.Combine(contentPath, directoryName), textureName + C_POSTFIX_MASK_EMISSIVE + textureExt);
                    var diffuseTextureFile  = Path.Combine(Path.Combine(contentPath, directoryName), textureName + C_POSTFIX_DIFFUSE_EMISSIVE + textureExt);
                    var specularTextureFile = Path.Combine(Path.Combine(contentPath, directoryName), textureName + C_POSTFIX_NORMAL_SPECULAR + textureExt);

                    #endregion

                    // Jan.Nekvapil:
                    // HSV in color mask isnt absolute value, as you can see ingame in Color Picker, Hue is absolute and Saturation with Value are just offsets to texture values.

                    var ambient      = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
                    var diffuseColor = meshPart.m_MaterialDesc.DiffuseColor.ToSandboxMediaColor();
                    //var specular = meshPart.m_MaterialDesc.SpecularColor.ToSandboxMediaColor();
                    var diffuseBrush = new SolidColorBrush(diffuseColor);
                    var colorBrush   = new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0xFF, 0x00));

                    // method in memory source
                    //var defaultImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(Path.Combine(contentPath, meshPart.m_MaterialDesc.DiffuseTextureName));
                    //var defaultImageBrush = defaultImage == null ? null : new ImageBrush(defaultImage) { ViewportUnits = BrushMappingMode.Absolute };

                    // method file
                    //var imageBitmap = SEToolbox.ImageLibrary.ImageTextureUtil.CreateBitmap(textureFile);
                    //var tempFile = Path.Combine(@"C:\temp", Path.GetFileNameWithoutExtension(textureFile) + ".png");
                    //ImageTextureUtil.WriteImage(imageBitmap, tempFile);
                    //var imageBrush = new ImageBrush(new BitmapImage(new Uri(tempFile, UriKind.Absolute)));

                    //MaterialGroup myBackMatGroup = new MaterialGroup();
                    //myBackMatGroup.Children.Add(new DiffuseMaterial() { AmbientColor = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF), Brush = diffuseImageBrush, Color = diffuseColor });
                    //myBackMatGroup.Children.Add(new SpecularMaterial() { Brush = maskImageBrush, Color = specular, SpecularPower = specularPower });
                    //geomentryModel.BackMaterial = myBackMatGroup;

                    MaterialGroup myMatGroup = new MaterialGroup();
                    if (File.Exists(maskTextureFile))
                    {
                        var cubeColor = Color.FromArgb(255, 159, 68, 68);

                        //var diffuseTextureImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(maskTextureFile, false);
                        //var diffuseImageBrush = diffuseTextureImage == null ? null : new ImageBrush(diffuseTextureImage) { ViewportUnits = BrushMappingMode.Absolute };
                        //myMatGroup.Children.Add(new DiffuseMaterial() { Brush = diffuseImageBrush, Color = diffuseColor, AmbientColor = ambient });

                        myMatGroup.Children.Add(new DiffuseMaterial()
                        {
                            Brush = new SolidColorBrush(cubeColor), Color = cubeColor, AmbientColor = ambient
                        });

                        var maskTextureImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(maskTextureFile, false, new MaskPixelEffect());
                        var maskImageBrush   = maskTextureImage == null ? null : new ImageBrush(maskTextureImage)
                        {
                            ViewportUnits = BrushMappingMode.Absolute
                        };

                        myMatGroup.Children.Add(new DiffuseMaterial()
                        {
                            Brush = maskImageBrush, Color = diffuseColor, AmbientColor = ambient
                        });
                        //myMatGroup.Children.Add(new EmissiveMaterial() { Brush = maskImageBrush, Color = diffuseColor });
                        //myMatGroup.Children.Add(new SpecularMaterial() { Brush = specularImageBrush, Color = specular, SpecularPower = specularPower });


                        var emissiveTextureImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(maskTextureFile, false, new EmissivePixelEffect(0));
                        var emissiveImageBrush   = emissiveTextureImage == null ? null : new ImageBrush(emissiveTextureImage)
                        {
                            ViewportUnits = BrushMappingMode.Absolute
                        };
                        myMatGroup.Children.Add(new EmissiveMaterial()
                        {
                            Brush = emissiveImageBrush, Color = diffuseColor
                        });
                    }
                    else
                    {
                        var diffuseTextureImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(diffuseTextureFile, true);
                        var diffuseImageBrush   = diffuseTextureImage == null ? null : new ImageBrush(diffuseTextureImage)
                        {
                            ViewportUnits = BrushMappingMode.Absolute
                        };
                        myMatGroup.Children.Add(new DiffuseMaterial()
                        {
                            Brush = diffuseImageBrush, Color = diffuseColor, AmbientColor = ambient
                        });

                        var emissiveTextureImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(diffuseTextureFile, false, new EmissivePixelEffect(0));
                        var emissiveImageBrush   = emissiveTextureImage == null ? null : new ImageBrush(emissiveTextureImage)
                        {
                            ViewportUnits = BrushMappingMode.Absolute
                        };
                        //myMatGroup.Children.Add(new EmissiveMaterial() { Brush = emissiveImageBrush, Color = diffuseColor });
                        myMatGroup.Children.Add(new EmissiveMaterial()
                        {
                            Brush = emissiveImageBrush, Color = Color.FromArgb(0x00, 0xFF, 0xFF, 0xFF)
                        });
                    }

                    if (File.Exists(specularTextureFile))
                    {
                        //new NormalMaterial() Normal maps?

                        var specularTextureImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(specularTextureFile);
                        var specularImageBrush   = specularTextureImage == null ? null : new ImageBrush(specularTextureImage)
                        {
                            ViewportUnits = BrushMappingMode.Absolute
                        };
                        myMatGroup.Children.Add(new SpecularMaterial()
                        {
                            Brush = specularImageBrush, SpecularPower = specularPower
                        });
                    }

                    geomentryModel.Material = myMatGroup;
                }
                else
                {
                    // No material assigned.
                    MaterialGroup myMatGroup   = new MaterialGroup();
                    var           cubeColor    = Color.FromArgb(255, 159, 68, 68);
                    var           ambient      = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
                    var           diffuseColor = Color.FromArgb(255, 159, 68, 68);
                    var           colorBrush   = new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0xFF, 0x00));

                    myMatGroup.Children.Add(new DiffuseMaterial()
                    {
                        Brush = new SolidColorBrush(cubeColor), Color = cubeColor, AmbientColor = ambient
                    });
                    myMatGroup.Children.Add(new DiffuseMaterial()
                    {
                        Brush = colorBrush, Color = diffuseColor, AmbientColor = ambient
                    });
                    geomentryModel.Material = myMatGroup;
                }


                foreach (var dummy in dummies)
                {
                    foreach (var data in dummy.Value.CustomData)
                    {
                        if (data.Key == "file")
                        {
                            var newfilename = Path.Combine(Path.GetDirectoryName(filename), data.Value + ".mwm");
                            LoadModel3d(myModel, newfilename);
                        }
                    }
                }
            }
        }
Beispiel #29
0
        public void PixelEffectTextures()
        {
            SpaceEngineersCore.LoadDefinitions();
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            // ----

            var medicalDiffuseEmissivePath = Path.Combine(contentPath, @"Textures\Models\Cubes\large_medical_room_de.dds");

            Assert.IsTrue(File.Exists(medicalDiffuseEmissivePath), "Filepath should exist on developer machine");
            var medicalDiffuseEmissiveBmp = TexUtil.CreateBitmap(medicalDiffuseEmissivePath);

            ImageTextureUtil.WriteImage(medicalDiffuseEmissiveBmp, @".\TestOutput\large_medical_room_de.png");

            var medicalDiffuseEmissiveBmp2 = TexUtil.CreateBitmap(medicalDiffuseEmissivePath, true);

            ImageTextureUtil.WriteImage(medicalDiffuseEmissiveBmp2, @".\TestOutput\large_medical_room_de_full.png");

            IPixelEffect effect = new AlphaPixelEffect();
            var          medicalDiffuseEmissiveAlphaBmp = effect.Quantize(medicalDiffuseEmissiveBmp);

            ImageTextureUtil.WriteImage(medicalDiffuseEmissiveAlphaBmp, @".\TestOutput\large_medical_room_de_alpha.png");

            effect = new EmissivePixelEffect(0);
            var medicalNormalSpecularEmissiveBmp = effect.Quantize(medicalDiffuseEmissiveBmp);

            ImageTextureUtil.WriteImage(medicalNormalSpecularEmissiveBmp, @".\TestOutput\large_medical_room_emissive.png");

            var defaultImage = SEToolbox.ImageLibrary.ImageTextureUtil.CreateImage(medicalDiffuseEmissivePath, false, new EmissivePixelEffect(0));

            // ----

            var largeThrustDiffuseEmissivePath = Path.Combine(contentPath, @"Textures\Models\Cubes\large_thrust_large_me.dds");

            Assert.IsTrue(File.Exists(largeThrustDiffuseEmissivePath), "Filepath should exist on developer machine");
            var largeThrustDiffuseEmissiveBmp = TexUtil.CreateBitmap(largeThrustDiffuseEmissivePath);

            ImageTextureUtil.WriteImage(largeThrustDiffuseEmissiveBmp, @".\TestOutput\large_thrust_large_me.png");

            var largeThrustDiffuseEmissiveBmp2 = TexUtil.CreateBitmap(largeThrustDiffuseEmissivePath, true);

            ImageTextureUtil.WriteImage(largeThrustDiffuseEmissiveBmp2, @".\TestOutput\large_thrust_large_me_full.png");

            effect = new AlphaPixelEffect();
            var largeThrustDiffuseEmissiveAlphaBmp = effect.Quantize(largeThrustDiffuseEmissiveBmp);

            ImageTextureUtil.WriteImage(largeThrustDiffuseEmissiveAlphaBmp, @".\TestOutput\large_thrust_large_me_alpha.png");

            effect = new EmissivePixelEffect(0);
            var largeThrustNormalSpecularEmissiveBmp = effect.Quantize(largeThrustDiffuseEmissiveBmp);

            ImageTextureUtil.WriteImage(largeThrustNormalSpecularEmissiveBmp, @".\TestOutput\large_thrust_large_me_emissive.png");

            // ----

            var astronautMaskEmissivePath = Path.Combine(contentPath, @"Textures\Models\Characters\Astronaut\Astronaut_me.dds");

            Assert.IsTrue(File.Exists(astronautMaskEmissivePath), "Filepath should exist on developer machine");
            var astronautMaskEmissiveBmp = TexUtil.CreateBitmap(astronautMaskEmissivePath);

            ImageTextureUtil.WriteImage(astronautMaskEmissiveBmp, @".\TestOutput\Astronaut_me.png");

            effect = new AlphaPixelEffect();
            var astronautMaskEmissiveAlphaBmp = effect.Quantize(astronautMaskEmissiveBmp);

            ImageTextureUtil.WriteImage(astronautMaskEmissiveAlphaBmp, @".\TestOutput\Astronaut_me_alpha.png");

            var astronautMaskEmissiveBmp2 = TexUtil.CreateBitmap(astronautMaskEmissivePath, true);

            ImageTextureUtil.WriteImage(astronautMaskEmissiveBmp2, @".\TestOutput\Astronaut_me_full.png");

            effect = new EmissivePixelEffect(255);
            var astronautNormalSpecularEmissiveBmp = effect.Quantize(astronautMaskEmissiveBmp);

            ImageTextureUtil.WriteImage(astronautNormalSpecularEmissiveBmp, @".\TestOutput\Astronaut_me_emissive.png");

            // ----

            var astronautNormalSpecularPath = Path.Combine(contentPath, @"Textures\Models\Characters\Astronaut\Astronaut_ns.dds");

            Assert.IsTrue(File.Exists(astronautNormalSpecularPath), "Filepath should exist on developer machine");
            var astronautNormalSpecularBmp = TexUtil.CreateBitmap(astronautNormalSpecularPath);

            ImageTextureUtil.WriteImage(astronautNormalSpecularBmp, @".\TestOutput\Astronaut_ns.png");
        }
Beispiel #30
0
        public void LoadComponentTextures()
        {
            SpaceEngineersCore.LoadDefinitions();
            var location = ToolboxUpdater.GetApplicationFilePath();

            Assert.IsNotNull(location, "Space Engineers should be installed on developer machine");
            Assert.IsTrue(Directory.Exists(location), "Filepath should exist on developer machine");

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            var magnesiumOre     = SpaceEngineersApi.GetDefinition(SpaceEngineersTypes.Ore, "Magnesium");
            var magnesiumOrePath = Path.Combine(contentPath, magnesiumOre.Icons.First());

            Assert.IsTrue(File.Exists(magnesiumOrePath), "Filepath should exist on developer machine");
            Assert.IsTrue(magnesiumOre is MyObjectBuilder_PhysicalItemDefinition, "Type should match");
            var magnesiumOreBmp = TexUtil.CreateBitmap(magnesiumOrePath);

            ImageTextureUtil.WriteImage(magnesiumOreBmp, @".\TestOutput\Magnesium_Ore.png");

            var goldIngot     = SpaceEngineersApi.GetDefinition(SpaceEngineersTypes.Ingot, "Gold");
            var goldIngotPath = Path.Combine(contentPath, goldIngot.Icons.First());

            Assert.IsTrue(File.Exists(goldIngotPath), "Filepath should exist on developer machine");
            Assert.IsTrue(goldIngot is MyObjectBuilder_PhysicalItemDefinition, "Type should match");
            var goldIngotBmp = TexUtil.CreateBitmap(goldIngotPath);

            ImageTextureUtil.WriteImage(goldIngotBmp, @".\TestOutput\Gold_Ingot.png");

            var ammoMagazine     = SpaceEngineersApi.GetDefinition(SpaceEngineersTypes.AmmoMagazine, "NATO_5p56x45mm");
            var ammoMagazinePath = Path.Combine(contentPath, ammoMagazine.Icons.First());

            Assert.IsTrue(File.Exists(ammoMagazinePath), "Filepath should exist on developer machine");
            Assert.IsTrue(ammoMagazine is MyObjectBuilder_AmmoMagazineDefinition, "Type should match");
            var ammoMagazineBmp = TexUtil.CreateBitmap(ammoMagazinePath);

            ImageTextureUtil.WriteImage(ammoMagazineBmp, @".\TestOutput\NATO_5p56x45mm.png");

            var steelPlate     = SpaceEngineersApi.GetDefinition(SpaceEngineersTypes.Component, "SteelPlate");
            var steelPlatePath = Path.Combine(contentPath, steelPlate.Icons.First());

            Assert.IsTrue(File.Exists(steelPlatePath), "Filepath should exist on developer machine");
            Assert.IsTrue(steelPlate is MyObjectBuilder_ComponentDefinition, "Type should match");
            var steelPlateBmp = TexUtil.CreateBitmap(steelPlatePath);

            ImageTextureUtil.WriteImage(steelPlateBmp, @".\TestOutput\SteelPlate.png");

            var smallBlockLandingGear     = SpaceEngineersApi.GetDefinition(new MyObjectBuilderType(typeof(MyObjectBuilder_LandingGear)), "SmallBlockLandingGear");
            var smallBlockLandingGearPath = Path.Combine(contentPath, smallBlockLandingGear.Icons.First());

            Assert.IsTrue(File.Exists(smallBlockLandingGearPath), "Filepath should exist on developer machine");
            Assert.IsTrue(smallBlockLandingGear is MyObjectBuilder_CubeBlockDefinition, "Type should match");
            var smallBlockLandingGearBmp = TexUtil.CreateBitmap(smallBlockLandingGearPath);

            ImageTextureUtil.WriteImage(smallBlockLandingGearBmp, @".\TestOutput\SmallBlockLandingGear.png");

            var gridItemPath = Path.Combine(contentPath, @"Textures\GUI\Controls\grid_item.dds");

            Assert.IsTrue(File.Exists(gridItemPath), "Filepath should exist on developer machine");
            var gridBmp = TexUtil.CreateBitmap(gridItemPath);

            ImageTextureUtil.WriteImage(gridBmp, @".\TestOutput\grid_item.png");

            var sunPath = Path.Combine(contentPath, @"Textures\BackgroundCube\Prerender\Sun.dds");

            Assert.IsTrue(File.Exists(sunPath), "Filepath should exist on developer machine");
            var sunBmp = TexUtil.CreateBitmap(sunPath);

            ImageTextureUtil.WriteImage(sunBmp, @".\TestOutput\sun.png");

            var goldPath = Path.Combine(contentPath, @"Textures\Voxels\Gold_01_ForAxisXZ_de.dds");

            Assert.IsTrue(File.Exists(goldPath), "Filepath should exist on developer machine");
            var goldBmp = TexUtil.CreateBitmap(goldPath);

            ImageTextureUtil.WriteImage(goldBmp, @".\TestOutput\gold.png");

            var siliconPath = Path.Combine(contentPath, @"Textures\Voxels\Silicon_01_ForAxisXZ_de.dds");

            Assert.IsTrue(File.Exists(siliconPath), "Filepath should exist on developer machine");
            var siliconBmp = TexUtil.CreateBitmap(siliconPath);

            ImageTextureUtil.WriteImage(siliconBmp, @".\TestOutput\silicon.png");

            var platinumPath = Path.Combine(contentPath, @"Textures\Voxels\Platinum_01_ForAxisXZ_de.dds");

            Assert.IsTrue(File.Exists(platinumPath), "Filepath should exist on developer machine");
            var platinumBmp = TexUtil.CreateBitmap(platinumPath);

            ImageTextureUtil.WriteImage(platinumBmp, @".\TestOutput\platinum.png");

            var medicalDiffuseEmissivePath = Path.Combine(contentPath, @"Textures\Models\Cubes\large_medical_room_de.dds");

            Assert.IsTrue(File.Exists(medicalDiffuseEmissivePath), "Filepath should exist on developer machine");
            var medicalDiffuseEmissiveBmp = TexUtil.CreateBitmap(medicalDiffuseEmissivePath);

            ImageTextureUtil.WriteImage(medicalDiffuseEmissiveBmp, @".\TestOutput\large_medical_room_de.png");

            medicalDiffuseEmissiveBmp = TexUtil.CreateBitmap(medicalDiffuseEmissivePath, true);
            ImageTextureUtil.WriteImage(medicalDiffuseEmissiveBmp, @".\TestOutput\large_medical_room.png");

            var astronautMaskEmissivePath = Path.Combine(contentPath, @"Textures\Models\Characters\Astronaut\Astronaut_me.dds");

            Assert.IsTrue(File.Exists(astronautMaskEmissivePath), "Filepath should exist on developer machine");
            var astronautMaskEmissiveBmp = TexUtil.CreateBitmap(astronautMaskEmissivePath);

            ImageTextureUtil.WriteImage(astronautMaskEmissiveBmp, @".\TestOutput\Astronaut_me.png");

            astronautMaskEmissiveBmp = TexUtil.CreateBitmap(astronautMaskEmissivePath, true);
            ImageTextureUtil.WriteImage(astronautMaskEmissiveBmp, @".\TestOutput\Astronaut_me2.png");

            var astronautNormalSpecularPath = Path.Combine(contentPath, @"Textures\Models\Characters\Astronaut\Astronaut_ns.dds");

            Assert.IsTrue(File.Exists(astronautNormalSpecularPath), "Filepath should exist on developer machine");
            var astronautNormalSpecularBmp = TexUtil.CreateBitmap(astronautNormalSpecularPath);

            ImageTextureUtil.WriteImage(astronautNormalSpecularBmp, @".\TestOutput\Astronaut_ns.png");

            astronautNormalSpecularBmp = TexUtil.CreateBitmap(astronautNormalSpecularPath, true);
            ImageTextureUtil.WriteImage(astronautNormalSpecularBmp, @".\TestOutput\Astronaut_ns2.png");
        }