コード例 #1
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var settings = new SearchDatabase.Settings {
                type = "asset", options = GetOptions()
            };

            try
            {
                var indexer = SearchDatabase.CreateIndexer(settings);
                try
                {
                    ctx.DependsOnCustomDependency(GetType().GUID.ToString("N"));
                    ctx.DependsOnCustomDependency(nameof(CustomObjectIndexerAttribute));
                    indexer.IndexDocument(ctx.assetPath, false);
                    indexer.ApplyUnsorted();
                }
                catch (Exception ex)
                {
                    ctx.LogImportError($"Failed to build search index for {ctx.assetPath}\n{ex}");
                }

                #if USE_SEARCH_MODULE
                var indexArtifactPath = ctx.GetOutputArtifactFilePath($"{(int)options:X}.index".ToLowerInvariant());
                #else
                var indexArtifactPath = ctx.GetResultPath($"{(int)options:X}.index".ToLowerInvariant());
                #endif
                using (var fileStream = new FileStream(indexArtifactPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
                    indexer.Write(fileStream);
            }
            catch (Exception ex)
            {
                ctx.LogImportError(ex.Message);
            }
        }
コード例 #2
0
        public override void OnImportAsset(AssetImportContext context)
        {
            PointCloudData data;

            var ext = Path.GetExtension(context.assetPath);

            try
            {
                if (ext == ".pcd")
                {
                    data = ImportPcd(context);
                }
                else if (ext == ".ply")
                {
                    data = ImportPly(context);
                }
                else if (ext == ".las")
                {
                    data = ImportLas(context);
                }
                else if (ext == ".laz")
                {
                    data = ImportLaz(context);
                }
                else
                {
                    context.LogImportError("Unsupported Point Cloud format");
                    return;
                }
            }
            catch (Exception ex)
            {
                context.LogImportError(ex.Message);
                return;
            }

            Debug.Assert(data != null);
            data.name = Path.GetFileNameWithoutExtension(context.assetPath);

            var obj      = new GameObject();
            var renderer = obj.AddComponent <PointCloudRenderer>();

            renderer.Data = data;

            if (data.HasColor)
            {
                renderer.Colorize = PointCloudRenderer.ColorizeType.Colors;
            }

            if (data.Count > 16 * 1000 * 1000)
            {
                renderer.ConstantSize = true;
                renderer.PixelSize    = 1.0f;
            }

            context.AddObjectToAsset("prefab", obj);
            context.AddObjectToAsset("data", data);

            context.SetMainObject(obj);
        }
コード例 #3
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            isWhitelisted = IsWhiteListed(ctx);
            string contents = string.Empty;

            try
            {
                contents = File.ReadAllText(ctx.assetPath);
            }
            catch (IOException exc)
            {
                ctx.LogImportError($"IOException : {exc.Message}");
            }
            finally
            {
                StyleSheet asset = ScriptableObject.CreateInstance <StyleSheet>();
                asset.hideFlags = HideFlags.NotEditable;

                if (!string.IsNullOrEmpty(contents))
                {
                    var importer = new StyleSheetImporterImpl(ctx);
                    importer.disableValidation = disableValidation | isWhitelisted;
                    importer.Import(asset, contents);
                }

                // make sure to produce a style sheet object in all cases
                ctx.AddObjectToAsset("stylesheet", asset);
                ctx.SetMainObject(asset);
            }
        }
コード例 #4
0
ファイル: YarnImporter.cs プロジェクト: MaraSlavk/novel
        private void ImportCompiledYarn(AssetImportContext ctx)
        {
            var bytes = File.ReadAllBytes(ctx.assetPath);

            try
            {
                // Validate that this can be parsed as a Program protobuf
                var _ = Program.Parser.ParseFrom(bytes);
            }
            catch (Google.Protobuf.InvalidProtocolBufferException)
            {
                ctx.LogImportError("Invalid compiled yarn file. Please re-compile the source code.");
                return;
            }

            isSuccesfullyCompiled = true;

            // Create a container for storing the bytes
            var programContainer = ScriptableObject.CreateInstance <YarnProgram>();

            programContainer.compiledProgram = bytes;

            // Add this container to the imported asset; it will be
            // what the user interacts with in Unity
            ctx.AddObjectToAsset("Program", programContainer);
            ctx.SetMainObject(programContainer);
        }
コード例 #5
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var contents = string.Empty;

            try
            {
                contents = File.ReadAllText(ctx.assetPath);
            }
            catch (IOException exc)
            {
                ctx.LogImportError($"IOException : {exc.Message}");
            }
            finally
            {
                var theme = ScriptableObject.CreateInstance <ThemeStyleSheet>();
                theme.hideFlags = HideFlags.NotEditable;

                if (!string.IsNullOrEmpty(contents))
                {
                    var importer = new StyleSheetImporterImpl(ctx);
                    importer.disableValidation = disableValidation | isWhitelisted;
                    importer.Import(theme, contents);
                }

                var icon = EditorGUIUtility.FindTexture("GUISkin Icon");
                ctx.AddObjectToAsset("themeStyleSheet", theme, icon);
                ctx.SetMainObject(theme);
            }
        }
コード例 #6
0
        static unsafe ColorAccess GetColorAccess(AssetImportContext context, List <PointElement> elements, byte *data, int stride)
        {
            var result = new ColorAccess()
            {
                Stride = stride,
            };

            for (int i = 0; i < elements.Count; i++)
            {
                if (elements[i].Name == PointElementName.I && elements[i].Type == PointElementType.Byte)
                {
                    result.Intensity = data + elements[i].Offset;
                }
                else if (elements[i].Name == PointElementName.I && elements[i].Type == PointElementType.Float)
                {
                    result.IntensityF = data + elements[i].Offset;
                }
                else if (i < elements.Count - 2 &&
                         elements[i].Name == PointElementName.R && elements[i + 1].Name == PointElementName.G && elements[i + 2].Name == PointElementName.B &&
                         elements[i].Type == PointElementType.Byte && elements[i + 1].Type == PointElementType.Byte && elements[i + 2].Type == PointElementType.Byte)
                {
                    result.Color = data + elements[i].Offset;
                }
            }

            if (result.Intensity == null && result.IntensityF == null && result.Color == null)
            {
                context.LogImportError("Point Cloud has no color and intensity data. Everything will be black!");
            }

            return(result);
        }
コード例 #7
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            try
            {
                if (Utils.IsUsingADBV1())
                {
                    ctx.LogImportWarning("Search indexes are not supported with the Asset Database V1");
                    return;
                }

                var db = ScriptableObject.CreateInstance <SearchDatabase>();
                db.Import(ctx.assetPath);
                ctx.AddObjectToAsset("index", db);
                ctx.SetMainObject(db);

                #if UNITY_2020_1_OR_NEWER
                ctx.DependsOnCustomDependency(nameof(CustomObjectIndexerAttribute));
                #endif

                hideFlags |= HideFlags.HideInInspector;
            }
            catch (SearchDatabaseException ex)
            {
                ctx.LogImportError(ex.Message, AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(ex.guid)));
            }
        }
コード例 #8
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            FileInfo info = new FileInfo(ctx.assetPath);

            filesize = info.Length;

            if (cols <= 0 || rows <= 0)
            {
                return;
            }

            int colorSize = GetPixelSize(colorFormat);

            if ((long)originalWidth * originalHeight * depth * colorSize != info.Length * 8)
            {
                ctx.LogImportError("Cols * Rows * Depth * Pixel Size must be equal to file size * 8");
                return;
            }

            Stream         stream = File.OpenRead(ctx.assetPath);
            Texture2DArray array  = InitTexture2DArray(stream, ctx);

            ctx.AddObjectToAsset("_MainTex", array);
            ctx.SetMainObject(array);
        }
コード例 #9
0
ファイル: YarnImporter.cs プロジェクト: Greentwip/Leana-Fire
        private void ImportCompiledYarn(AssetImportContext ctx)
        {
            var bytes = File.ReadAllBytes(ctx.assetPath);

            try
            {
                // Validate that this can be parsed as a Program protobuf
                var _ = Program.Parser.ParseFrom(bytes);
            }
            catch (Google.Protobuf.InvalidProtocolBufferException)
            {
                ctx.LogImportError("Invalid compiled yarn file. Please re-compile the source code.");
                return;
            }

            isSuccessfullyParsed = true;

            // Create a container for storing the bytes
            var programContainer = new TextAsset("<pre-compiled Yarn script>");

            // Add this container to the imported asset; it will be what
            // the user interacts with in Unity
            ctx.AddObjectToAsset("Program", programContainer, YarnEditorUtility.GetYarnDocumentIconTexture());
            ctx.SetMainObject(programContainer);
        }
コード例 #10
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var contents = string.Empty;

            try
            {
                var bytes = File.ReadAllBytes(ctx.assetPath);
                contents = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

                // Purge BOM. Unity auto adding it when creating script assets: https://git.io/fjVgY
                if (contents.Length > 0 && contents[0] == '\uFEFF')
                {
                    contents = contents.Substring(1);
                    File.WriteAllText(ctx.assetPath, contents);
                }
            }
            catch (IOException exc)
            {
                ctx.LogImportError($"IOException: {exc.Message}");
            }
            finally
            {
                var assetName = Path.GetFileNameWithoutExtension(ctx.assetPath);
                var asset     = Script.FromScriptText(assetName, contents);
                asset.hideFlags = HideFlags.NotEditable;

                ctx.AddObjectToAsset("naniscript", asset);
                ctx.SetMainObject(asset);
            }
        }
コード例 #11
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var hdAsset = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;

            if (hdAsset == null)
            {
                ctx.LogImportError("No HD Render Pipeline set in Graphics Settings");
                return;
            }

            var lutSize = hdAsset.currentPlatformRenderPipelineSettings.postProcessSettings.lutSize;

            bool success = ParseCubeData(ctx, lutSize, out var pixels);

            if (!success)
            {
                return;
            }

            var tex = new Texture3D(lutSize, lutSize, lutSize, TextureFormat.RGBAHalf, false)
            {
                filterMode = FilterMode.Bilinear,
                wrapMode   = TextureWrapMode.Clamp,
                anisoLevel = 0
            };

            tex.SetPixels(pixels);

            ctx.AddObjectToAsset("3D Lookup Texture", tex);
            ctx.SetMainObject(tex);
        }
コード例 #12
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var settings = new SearchDatabase.Settings {
                type = "asset", options = GetOptions()
            };
            var indexer = SearchDatabase.CreateIndexer(settings);

            try
            {
                indexer.IndexDocument(ctx.assetPath, false);
                indexer.Finish(removedDocuments: null);

                var indexArtifactPath = ctx.GetOutputArtifactFilePath($"{(int)options:X}.index".ToLowerInvariant());
                using (var fileStream = new FileStream(indexArtifactPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                    indexer.Write(fileStream);

                ctx.DependsOnSourceAsset(ctx.assetPath);
                ctx.DependsOnCustomDependency(GetType().GUID.ToString("N"));
                ctx.DependsOnCustomDependency(nameof(CustomObjectIndexerAttribute));
            }
            catch (Exception ex)
            {
                ctx.LogImportError($"Failed to build search index for {ctx.assetPath}\n{ex}");
            }
        }
コード例 #13
0
        /// <summary>
        /// Checks if the asset is set up properly and all its dependencies are ok.
        /// </summary>
        /// <returns>
        /// Returns true if the asset can be imported, false otherwise.
        /// </returns>
        bool Verify(AssetImportContext ctx, bool logToConsole)
        {
            if (!SystemInfo.supportsCubemapArrayTextures)
            {
                if (logToConsole)
                {
                    ctx.LogImportError($"Import failed '{ctx.assetPath}'. Your system does not support cubemap arrays.", ctx.mainObject);
                }

                return(false);
            }

            if (m_Cubemaps.Count > 0)
            {
                if (m_Cubemaps[0] == null)
                {
                    if (logToConsole)
                    {
                        ctx.LogImportError($"Import failed '{ctx.assetPath}'. The first element in the 'Cubemaps' list must not be 'None'.", ctx.mainObject);
                    }

                    return(false);
                }
            }

            var result = m_Cubemaps.Count > 0;

            for (var n = 0; n < m_Cubemaps.Count; ++n)
            {
                var valid = Verify(n);
                if (valid != VerifyResult.Valid)
                {
                    result = false;
                    if (logToConsole)
                    {
                        var error = GetVerifyString(n);
                        if (!string.IsNullOrEmpty(error))
                        {
                            var msg = $"Import failed '{ctx.assetPath}'. {error}";
                            ctx.LogImportError(msg, ctx.mainObject);
                        }
                    }
                }
            }

            return(result);
        }
コード例 #14
0
        /// <summary>
        /// Checks if the asset is set up properly and all its dependencies are ok.
        /// </summary>
        /// <returns>
        /// Returns true if the asset can be imported, false otherwise.
        /// </returns>
        bool Verify(AssetImportContext ctx, bool logToConsole)
        {
            if (!SystemInfo.supports3DTextures)
            {
                if (logToConsole)
                {
                    ctx.LogImportError(string.Format("Import failed '{0}'. Your system does not support Texture3D.", ctx.assetPath), ctx.mainObject);
                }

                return(false);
            }

            if (m_Textures.Count > 0)
            {
                if (m_Textures[0] == null)
                {
                    if (logToConsole)
                    {
                        ctx.LogImportError(string.Format("Import failed '{0}'. The first element in the 'Textures' list must not be 'None'.", ctx.assetPath), ctx.mainObject);
                    }

                    return(false);
                }
            }

            var result = m_Textures.Count > 0;

            for (var n = 0; n < m_Textures.Count; ++n)
            {
                var valid = Verify(n);
                if (valid != VerifyResult.Valid)
                {
                    result = false;
                    if (logToConsole)
                    {
                        var error = GetVerifyString(n);
                        if (!string.IsNullOrEmpty(error))
                        {
                            var msg = string.Format("Import failed '{0}'. {1}", ctx.assetPath, error);
                            ctx.LogImportError(msg, ctx.mainObject);
                        }
                    }
                }
            }

            return(result);
        }
コード例 #15
0
        private void LogImportError(AssetImportContext ctx, string error)
        {
#if UNITY_2018_1_OR_NEWER
            ctx.LogImportError(error);
#else
            Debug.LogError(error);
#endif
        }
コード例 #16
0
ファイル: VoxdescImporter.cs プロジェクト: DigitalQR/LD47
    public override void OnImportAsset(AssetImportContext ctx)
    {
        // Attempt to generate models for each frame
        string    expectedImage = Path.Combine(Path.GetDirectoryName(ctx.assetPath), Path.GetFileNameWithoutExtension(ctx.assetPath));
        Texture2D sourceTexture = AssetDatabase.LoadAssetAtPath <Texture2D>(expectedImage);

        if (sourceTexture == null)
        {
            ctx.LogImportError($"Failed to load associated texture at '{expectedImage}'");
            return;
        }

        ctx.DependsOnSourceAsset(expectedImage);
        IVoxelVolume textureVolume = new Texture2DVoxelVolume(sourceTexture);

        // Layers will be stacked next to each other progressing
        int layerCount = m_ImportSettings.GetTotalChannelCountRounded(4) / 4;

        Vector3Int cellSize, frameStep, channelStep;

        if (m_ImportFrameOrientation == LayoutOrientation.Vertical)
        {
            cellSize   = new Vector3Int();
            cellSize.x = sourceTexture.width / layerCount;
            cellSize.y = sourceTexture.height / m_ImportSettings.FrameCount;

            frameStep   = new Vector3Int(0, cellSize.y, 0);
            channelStep = new Vector3Int(cellSize.x, 0, 0);
        }
        else
        {
            cellSize   = new Vector3Int();
            cellSize.x = sourceTexture.width / m_ImportSettings.FrameCount;
            cellSize.y = sourceTexture.height / layerCount;

            frameStep   = new Vector3Int(cellSize.x, 0, 0);
            channelStep = new Vector3Int(0, cellSize.y, 0);
        }

        CommonVoxelImporter importer  = new CommonVoxelImporter(textureVolume, m_ImportSettings, cellSize, frameStep, channelStep);
        MeshSheet           meshSheet = importer.GenerateMeshSheet();

        ctx.AddObjectToAsset("Meshes", meshSheet);
        for (int i = 0; i < meshSheet.FrameCount; ++i)
        {
            Mesh mesh = meshSheet.GetMeshAtFrame(i);
            mesh.name = Path.GetFileNameWithoutExtension(ctx.assetPath) + "_MeshFrame_" + i;
            ctx.AddObjectToAsset("MeshFrame_" + i, mesh);
        }

        ctx.SetMainObject(meshSheet);
    }
コード例 #17
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var settings = new SearchDatabase.Settings
            {
                guid      = null,
                root      = null,
                roots     = null,
                source    = null,
                name      = null,
                baseScore = 0,
                excludes  = null,
                includes  = null,

                type    = type,
                options = GetOptions(),
            };

            EditorApplication.LockReloadAssemblies();
            try
            {
                var indexer = SearchDatabase.CreateIndexer(settings);
                indexer.IndexDocument(ctx.assetPath, false);
                indexer.ApplyUnsorted();

                var indexArtifactPath = ctx.GetResultPath($"{type}.{(int)options:X}.index".ToLowerInvariant());
                using (var fileStream = new FileStream(indexArtifactPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
                    indexer.Write(fileStream);

                Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, $"\nGenerated {type} ({GetType().Name}) {indexArtifactPath} for {ctx.assetPath} with {options}");

                ctx.DependsOnSourceAsset(Path.GetDirectoryName(ctx.assetPath).Replace("\\", "/"));
                ctx.DependsOnCustomDependency(GetType().GUID.ToString("N"));

                #if UNITY_2020_1_OR_NEWER
                ctx.DependsOnCustomDependency(nameof(CustomObjectIndexerAttribute));
                #endif
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                ctx.LogImportError(ex.Message);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #18
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            try
            {
                var db = ScriptableObject.CreateInstance <SearchDatabase>();
                db.Import(ctx.assetPath);
                ctx.AddObjectToAsset("index", db);
                ctx.SetMainObject(db);

                ctx.DependsOnCustomDependency(nameof(CustomObjectIndexerAttribute));

                hideFlags |= HideFlags.HideInInspector;
            }
            catch (SearchDatabaseException ex)
            {
                ctx.LogImportError(ex.Message, AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(ex.guid)));
            }
        }
コード例 #19
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            try
            {
                var aseWorker = new AseImportContextWorkerPro(ctx);

                //Check if this is a ase file. If it's not, we have no business here
                if (!aseWorker.ContextFileIsAseFile())
                {
                    return;
                }

                var ase = new AsepriteCli(AsepriteAutoImporterSettings.GetSettings().pathToAsepriteExecutable,
                                          importOptions);

                var exportDir = GetTempFolder();

                var sheetFile     = $"{exportDir}/{aseWorker.AseFileNoExt}_sheet.png";
                var sheetDataFile = $"{exportDir}/{aseWorker.AseFileNoExt}_data.json";

                ase.ExportSpriteSheet(aseWorker.AseFile, sheetFile, sheetDataFile);

                aseWorker.TextureCreationOptions = textureCreationOptions;
                aseWorker.SpriteImportOptions    = spriteImportOptions;

                aseWorker.AddMainTextureToContext(sheetFile);

                sheetData = AseSheetData.Create(sheetDataFile, aseWorker.AseFile);

                RefreshAnimationOptions();

                aseWorker.AddIndividualSpritesToContext(sheetData);
                aseWorker.AddAnimationsToContext(sheetData,
                                                 animationOptions.ToDictionary(e => e.tagName, e => e.animationOptions));

                Directory.Delete(exportDir, true);
                AssetDatabase.SaveAssets();
            }
            catch (Exception e)
            {
                ctx.LogImportError($"AsepriteAutoImporter: Error while importing file '{ctx.assetPath}'. {e.Message}");
            }
        }
コード例 #20
0
ファイル: YarnImporter.cs プロジェクト: Greentwip/Leana-Fire
        private void ImportYarn(AssetImportContext ctx)
        {
            var    sourceText = File.ReadAllText(ctx.assetPath);
            string fileName   = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);

            var text = new TextAsset(File.ReadAllText(ctx.assetPath));

            // Add this container to the imported asset; it will be what
            // the user interacts with in Unity
            ctx.AddObjectToAsset("Program", text, YarnEditorUtility.GetYarnDocumentIconTexture());
            ctx.SetMainObject(text);

            Yarn.Program compiledProgram = null;
            IDictionary <string, Yarn.Compiler.StringInfo> stringTable = null;

            parseErrorMessage = null;

            try
            {
                // Compile the source code into a compiled Yarn program (or
                // generate a parse error)
                var compilationJob = CompilationJob.CreateFromString(fileName, sourceText, null);
                compilationJob.CompilationType = CompilationJob.Type.StringsOnly;

                var result = Yarn.Compiler.Compiler.Compile(compilationJob);

                LastImportHadImplicitStringIDs = result.ContainsImplicitStringTags;
                LastImportHadAnyStrings        = result.StringTable.Count > 0;

                stringTable          = result.StringTable;
                compiledProgram      = result.Program;
                isSuccessfullyParsed = true;
                parseErrorMessage    = string.Empty;
            }
            catch (Yarn.Compiler.ParseException e)
            {
                isSuccessfullyParsed = false;
                parseErrorMessage    = e.Message;
                ctx.LogImportError($"Error importing {ctx.assetPath}: {e.Message}");
                return;
            }
        }
コード例 #21
0
        public static UdsTexture FromNode(AssetImportContext ctx, XmlNode node)
        {
            UdsTexture tex = new UdsTexture();

            /*
             * <Texture name="concrete_cast-in-place_formwork_wood_boards_bump_0" texturemode="0" texturefilter="3" textureaddressx="0" textureaddressy="0" rgbcurve="-1.000000"
             *          srgb="0" file="rac_basic_sample_project_local_copy-3DView-UE4_Assets/concrete.cast-in-place.formwork.wood.boards.bump.jpg">
             *   <Hash value="c99e25a6f94199ce085a6e78e56639f2"/>
             * </Texture>
             */

            tex.name     = node.Attributes["name"].Value;
            tex.filePath = node.Attributes["file"].Value;

            if (Regex.Match(tex.filePath, @"\.ies$", RegexOptions.IgnoreCase).Success)
            {
                ctx.LogImportWarning(String.Format("Texture Reference \"{0}\" to IES light profile \"{1}\" cannot be resolved: IES light profile import is not implemented.", tex.name, tex.filePath));
                return(null);
            }


            tex.fullyQualifiedPath = Path.Combine(Path.GetDirectoryName(ctx.assetPath), tex.filePath);

            var texAssetObj = AssetDatabase.LoadAssetAtPath(tex.fullyQualifiedPath, typeof(Texture));

            if (texAssetObj != null)
            {
                tex.assetRef = (Texture)texAssetObj;
                var texImporterObj = AssetImporter.GetAtPath(tex.fullyQualifiedPath); // load import settings for possible later adjustment once we know what this will be used for
                if (texImporterObj != null)
                {
                    tex.importer = (TextureImporter)texImporterObj;
                }
            }

            if (tex.assetRef == null || tex.importer == null)
            {
                ctx.LogImportError(String.Format("UdsTexture::FromNode: Asset does not exist at path \"{0}\"", tex.fullyQualifiedPath));
            }

            return(tex);
        }
コード例 #22
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var schemaFile = Path.GetFullPath(ctx.assetPath);

            if (generatedSourcePath == null)
            {
                generatedSourcePath = AssetDatabase.LoadAssetAtPath <DefaultAsset>(Path.GetDirectoryName(ctx.assetPath));
                ctx.AddObjectToAsset("generatedSourcePath", generatedSourcePath);
                ctx.SetMainObject(generatedSourcePath);
            }

            var sourceFolder = Path.GetFullPath(AssetDatabase.GetAssetPath(generatedSourcePath));

            var flatcPath = Path.GetFullPath(Path.Combine("Assets/FlatBuffers/Editor/Compiler", k_FlatCompiler));
            var procArgs  = "-n \"" + schemaFile + "\" --gen-onefile";

            var process = new Process();

            process.StartInfo = new ProcessStartInfo(flatcPath, procArgs);
            process.StartInfo.WorkingDirectory      = sourceFolder;
            process.StartInfo.UseShellExecute       = false;
            process.StartInfo.CreateNoWindow        = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            var stderr = process.StandardError.ReadToEnd();

            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                ctx.LogImportError(stderr);
            }

//            var generatedScriptPath = ctx.assetPath.Replace(".fbs", ".cs");
//            AssetDatabase.ImportAsset(generatedScriptPath, ImportAssetOptions.ForceSynchronousImport);
//            var generatedScript = AssetDatabase.LoadAssetAtPath<MonoScript>(generatedScriptPath);
        }
コード例 #23
0
    public override void OnImportAsset(AssetImportContext ctx)
    {
        if (!schema)
        {
            ctx.LogImportError("need a schema");
            return;
        }

        var fileName = Path.GetFileName(ctx.assetPath);
        var text     = File.ReadAllText(ctx.assetPath);
        var document = Parser.Parse(schema, text);

        if (!Generator.Generate(document, ctx.assetPath))
        {
            // TODO: trigger reimport to load the generated class and add as component
        }

        var root = Spawner.Spawn(document);

        ctx.AddObjectToAsset("UAML", root);
        ctx.SetMainObject(root);
        ctx.DependsOnSourceAsset(AssetDatabase.GetAssetPath(schema));
    }
コード例 #24
0
ファイル: TexImporter.cs プロジェクト: nemerle/Seccu
    public override void OnImportAsset(AssetImportContext ctx)
    {
        int          idx       = ctx.assetPath.LastIndexOf("texture_library");
        FileStream   fs        = File.Open(ctx.assetPath, FileMode.Open);
        BinaryReader fs_reader = new BinaryReader(fs, new ASCIIEncoding());
        TexFileHdr   hdr       = readHeader(fs_reader);

        if (hdr.magic[0] != 'T' || hdr.magic[1] != 'X' || hdr.magic[2] != '2')
        {
            ctx.LogImportError("Unknown texture format");
            return;
        }

        var    name_chars   = fs_reader.ReadChars(hdr.header_size - 8 * 4);
        string originalname = new string(name_chars);

        originalname = originalname.Substring(0, originalname.IndexOf('\0'));
        SEGSRuntime.Tools.EnsureDirectoryExists(Path.GetDirectoryName(PREFAB_DESTINATION_DIRECTORY + originalname));
        FileStream tgt = File.Open(PREFAB_DESTINATION_DIRECTORY + originalname, FileMode.Create);

        fs.CopyTo(tgt);
        tgt.Close();
        fs.Close();
    }
コード例 #25
0
ファイル: IESImporter.cs プロジェクト: 709106608/Graphics
        /// <summary>
        /// Common method performing the import of the asset
        /// </summary>
        /// <param name="ctx">Asset importer context.</param>
        public override void OnImportAsset(AssetImportContext ctx)
        {
            engine.TextureGenerationType = TextureImporterType.Default;

            Texture cookieTextureCube = null;
            Texture cookieTexture2D   = null;

            string iesFilePath  = Path.Combine(Path.GetDirectoryName(Application.dataPath), ctx.assetPath);
            string errorMessage = engine.ReadFile(iesFilePath);

            if (string.IsNullOrEmpty(errorMessage))
            {
                iesMetaData.FileFormatVersion      = engine.FileFormatVersion;
                iesMetaData.IESPhotometricType     = engine.GetPhotometricType();
                iesMetaData.Manufacturer           = engine.GetKeywordValue("MANUFAC");
                iesMetaData.LuminaireCatalogNumber = engine.GetKeywordValue("LUMCAT");
                iesMetaData.LuminaireDescription   = engine.GetKeywordValue("LUMINAIRE");
                iesMetaData.LampCatalogNumber      = engine.GetKeywordValue("LAMPCAT");
                iesMetaData.LampDescription        = engine.GetKeywordValue("LAMP");

                (iesMetaData.IESMaximumIntensity, iesMetaData.IESMaximumIntensityUnit) = engine.GetMaximumIntensity();

                string warningMessage;

                (warningMessage, cookieTextureCube) = engine.GenerateCubeCookie(iesMetaData.CookieCompression, (int)iesMetaData.iesSize);
                if (!string.IsNullOrEmpty(warningMessage))
                {
                    ctx.LogImportWarning($"Cannot properly generate IES Cube texture: {warningMessage}");
                }
                cookieTextureCube.IncrementUpdateCount();

                (warningMessage, cookieTexture2D) = engine.Generate2DCookie(iesMetaData.CookieCompression, iesMetaData.SpotAngle, (int)iesMetaData.iesSize, iesMetaData.ApplyLightAttenuation);
                if (!string.IsNullOrEmpty(warningMessage))
                {
                    ctx.LogImportWarning($"Cannot properly generate IES 2D texture: {warningMessage}");
                }
                cookieTexture2D.IncrementUpdateCount();
            }
            else
            {
                ctx.LogImportError($"Cannot read IES file '{iesFilePath}': {errorMessage}");
            }

            string iesFileName = Path.GetFileNameWithoutExtension(ctx.assetPath);

            var iesObject = ScriptableObject.CreateInstance <IESObject>();

            iesObject.iesMetaData = iesMetaData;
            GameObject lightObject = new GameObject(iesFileName);

            lightObject.transform.localEulerAngles = new Vector3(90f, 0f, iesMetaData.LightAimAxisRotation);

            Light light = lightObject.AddComponent <Light>();

            light.type      = (iesMetaData.PrefabLightType == IESLightType.Point) ? LightType.Point : LightType.Spot;
            light.intensity = 1f;  // would need a better intensity value formula
            light.range     = 10f; // would need a better range value formula
            light.spotAngle = iesMetaData.SpotAngle;

            ctx.AddObjectToAsset("IES", iesObject);
            ctx.SetMainObject(iesObject);

            IESImporter.createRenderPipelinePrefabLight?.Invoke(ctx, iesFileName, iesMetaData.UseIESMaximumIntensity, iesMetaData.IESMaximumIntensityUnit, iesMetaData.IESMaximumIntensity, light, (iesMetaData.PrefabLightType == IESLightType.Point) ? cookieTextureCube : cookieTexture2D);

            if (cookieTextureCube != null)
            {
                cookieTextureCube.name = iesFileName + "-Cube-IES";
                ctx.AddObjectToAsset(cookieTextureCube.name, cookieTextureCube);
            }
            if (cookieTexture2D != null)
            {
                cookieTexture2D.name = iesFileName + "-2D-IES";
                ctx.AddObjectToAsset(cookieTexture2D.name, cookieTexture2D);
            }
        }
コード例 #26
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            {
                var ext = Path.GetExtension(ctx.assetPath).ToLower();
                if (ext == ".vox")
                {
                    fileType = VoxelBase.FileType.vox;
                }
                else if (ext == ".qb")
                {
                    fileType = VoxelBase.FileType.qb;
                }
                else
                {
                    return;
                }
            }

            #region DefaultScale
            if (dataVersion == 0 &&
                importScale == Vector3.one &&
                AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(ctx.assetPath) == null)
            {
                var x = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleX", 1f);
                var y = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleY", 1f);
                var z = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleZ", 1f);
                importScale = new Vector3(x, y, z);
            }
            #endregion

            #region LegacyAssetNaming
            if (dataVersion > 0 && dataVersion < 6)
            {
                legacyAssetNaming = true;
            }
            #endregion

            Action <string> LogImportError = (log) =>
            {
#if UNITY_2018_1_OR_NEWER
                ctx.LogImportError(log);
#else
                Debug.LogError(log);
#endif
            };
            Action <VoxelBase> SetBasicOptions = (voxelObject) =>
            {
                voxelObject.importMode                    = importMode;
                voxelObject.importScale                   = importScale;
                voxelObject.importOffset                  = importOffset;
                voxelObject.combineFaces                  = combineFaces;
                voxelObject.ignoreCavity                  = ignoreCavity;
                voxelObject.shareSameFace                 = shareSameFace;
                voxelObject.removeUnusedPalettes          = removeUnusedPalettes;
                voxelObject.voxelStructure                = outputStructure ? ScriptableObject.CreateInstance <VoxelStructure>() : null;
                voxelObject.generateLightmapUVs           = generateLightmapUVs;
                voxelObject.generateLightmapUVsAngleError = generateLightmapUVsAngleError;
                voxelObject.generateLightmapUVsAreaError  = generateLightmapUVsAreaError;
                voxelObject.generateLightmapUVsHardAngle  = generateLightmapUVsHardAngle;
                voxelObject.generateLightmapUVsPackMargin = generateLightmapUVsPackMargin;
                voxelObject.generateTangents              = generateTangents;
                voxelObject.meshFaceVertexOffset          = meshFaceVertexOffset;
                voxelObject.loadFromVoxelFile             = loadFromVoxelFile;
                voxelObject.generateMipMaps               = generateMipMaps;
                voxelObject.legacyVoxImport               = legacyVoxImport;
                voxelObject.legacyAssetNaming             = legacyAssetNaming;
            };

            Action <VoxelBaseCore> Export = (core) =>
            {
                if (export)
                {
                    var fullPath = Application.dataPath + ctx.assetPath.Remove(0, "Assets".Length);
                    fullPath = fullPath.Remove(fullPath.LastIndexOf('.')) + ".dae";
                    core.ExportDaeFile(fullPath, false);
                }
            };

            var gameObject = new GameObject(Path.GetFileNameWithoutExtension(ctx.assetPath));
            if (string.IsNullOrEmpty(gameObjectName))
            {
                gameObjectName = gameObject.name;
            }
            if (meshMode == MeshMode.Combine)
            {
                #region Combine
                var voxelObject = gameObject.AddComponent <VoxelObject>();
                SetBasicOptions(voxelObject);
                var objectCore = new VoxelObjectCore(voxelObject);
                try
                {
                    if (!objectCore.Create(ctx.assetPath, null))
                    {
                        LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                        DestroyImmediate(gameObject);
                        return;
                    }
                }
                catch
                {
                    LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                    DestroyImmediate(gameObject);
                    return;
                }

                #region Correspondence in Issue ID 947055 Correction in case before correction is applied
                foreach (var material in voxelObject.materials)
                {
                    if (material != null)
                    {
                        material.hideFlags |= HideFlags.NotEditable;
                    }
                }
                if (voxelObject.atlasTexture != null)
                {
                    voxelObject.atlasTexture.hideFlags |= HideFlags.NotEditable;
                }
                if (voxelObject.mesh != null)
                {
                    voxelObject.mesh.hideFlags |= HideFlags.NotEditable;
                }
                #endregion

                #region Material
                {
                    materials     = new Material[voxelObject.materialIndexes.Count];
                    materialNames = new string[voxelObject.materialIndexes.Count];
                    for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                    {
                        var index    = voxelObject.materialIndexes[i];
                        var material = voxelObject.materials[index];
                        materials[i]     = material;
                        materialNames[i] = material.name;
                    }
                    if (remappedMaterials != null)
                    {
                        remappedMaterials = remappedMaterials.Where(item => item.material != null && materialNames.Contains(item.name)).ToArray();
                    }
                }
                #endregion

                #region Structure
                if (voxelObject.voxelStructure != null)
                {
                    if (legacyAssetNaming)
                    {
                        voxelObject.voxelStructure.name = "structure";
                    }
                    else
                    {
                        voxelObject.voxelStructure.name = Path.GetFileNameWithoutExtension(ctx.assetPath);
                    }
                }
                #endregion

                #region Collider
                switch (colliderType)
                {
                case ColliderType.Box:
                    gameObject.AddComponent <BoxCollider>();
                    break;

                case ColliderType.Sphere:
                    gameObject.AddComponent <SphereCollider>();
                    break;

                case ColliderType.Capsule:
                    gameObject.AddComponent <CapsuleCollider>();
                    break;

                case ColliderType.Mesh:
                    gameObject.AddComponent <MeshCollider>();
                    break;
                }
                #endregion

                Export(objectCore);

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(gameObjectName, gameObject);
                ctx.AddObjectToAsset("mesh", voxelObject.mesh);
                {
                    var list = new List <Material>();
                    for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                    {
                        var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                        list.Add(material);
                        if (remappedMaterials != null)
                        {
                            var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                            if (index >= 0)
                            {
                                list[i] = remappedMaterials[index].material;
                                continue;
                            }
                        }
                        ctx.AddObjectToAsset(string.Format("mat{0}", i), material);
                    }
                    gameObject.GetComponent <MeshRenderer>().sharedMaterials = list.ToArray();
                }
                ctx.AddObjectToAsset("tex", voxelObject.atlasTexture);
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddObjectToAsset("structure", voxelObject.voxelStructure);
                }

                VoxelObject.DestroyImmediate(voxelObject);

                ctx.SetMainObject(gameObject);
#else
                ctx.SetMainAsset(gameObjectName, gameObject);
                ctx.AddSubAsset("mesh", voxelObject.mesh);
                for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                {
                    var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                    ctx.AddSubAsset(string.Format("mat{0}", i), material);
                }
                ctx.AddSubAsset("tex", voxelObject.atlasTexture);
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddSubAsset("structure", voxelObject.voxelStructure);
                }

                VoxelObject.DestroyImmediate(voxelObject);
#endif
                #endregion
            }
            else if (meshMode == MeshMode.Individual)
            {
                #region Individual
                var voxelObject = gameObject.AddComponent <VoxelChunksObject>();
                SetBasicOptions(voxelObject);
                {
                    voxelObject.createContactChunkFaces = createContactChunkFaces;
                    voxelObject.materialMode            = materialMode;
                }
                var objectCore = new VoxelChunksObjectCore(voxelObject);
                try
                {
                    if (!objectCore.Create(ctx.assetPath, null))
                    {
                        LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                        DestroyImmediate(gameObject);
                        return;
                    }
                }
                catch
                {
                    LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                    DestroyImmediate(gameObject);
                    return;
                }

                #region Correspondence in Issue ID 947055 Correction in case before correction is applied
                if (voxelObject.materials != null)
                {
                    foreach (var material in voxelObject.materials)
                    {
                        if (material != null)
                        {
                            material.hideFlags |= HideFlags.NotEditable;
                        }
                    }
                }
                if (voxelObject.atlasTexture != null)
                {
                    voxelObject.atlasTexture.hideFlags |= HideFlags.NotEditable;
                }
                foreach (var chunk in voxelObject.chunks)
                {
                    if (chunk.materials != null)
                    {
                        foreach (var material in chunk.materials)
                        {
                            if (material != null)
                            {
                                material.hideFlags |= HideFlags.NotEditable;
                            }
                        }
                    }
                    if (chunk.atlasTexture != null)
                    {
                        chunk.atlasTexture.hideFlags |= HideFlags.NotEditable;
                    }
                    if (chunk.mesh != null)
                    {
                        chunk.mesh.hideFlags |= HideFlags.NotEditable;
                    }
                }
                #endregion

                #region Legacy
                if (legacyAssetNaming)
                {
                    foreach (var chunk in voxelObject.chunks)
                    {
                        var oldName = chunk.chunkName;
                        chunk.chunkName       = chunk.chunkName.Replace("Chunk(", "");
                        chunk.chunkName       = chunk.chunkName.Remove(chunk.chunkName.Length - 1, 1);
                        chunk.gameObject.name = chunk.chunkName;
                        chunk.mesh.name       = chunk.mesh.name.Replace(oldName, chunk.chunkName);
                        if (chunk.materials != null)
                        {
                            foreach (var mat in chunk.materials)
                            {
                                if (mat == null)
                                {
                                    continue;
                                }
                                mat.name = mat.name.Replace(oldName, chunk.chunkName);
                            }
                        }
                        if (chunk.atlasTexture != null)
                        {
                            chunk.atlasTexture.name = chunk.atlasTexture.name.Replace(oldName, chunk.chunkName);
                        }
                    }
                }
                #endregion

                #region Material
                {
                    if (materialMode == VoxelChunksObject.MaterialMode.Combine)
                    {
                        materials     = new Material[voxelObject.materialIndexes.Count];
                        materialNames = new string[voxelObject.materialIndexes.Count];
                        for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                        {
                            var index    = voxelObject.materialIndexes[i];
                            var material = voxelObject.materials[index];
                            materials[i]     = material;
                            materialNames[i] = material.name;
                        }
                    }
                    else if (materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        List <Material> list = new List <Material>();
                        foreach (var chunk in voxelObject.chunks)
                        {
                            for (int i = 0; i < chunk.materialIndexes.Count; i++)
                            {
                                var index    = chunk.materialIndexes[i];
                                var material = chunk.materials[index];
                                if (!list.Contains(material))
                                {
                                    list.Add(material);
                                }
                            }
                        }
                        materials     = list.ToArray();
                        materialNames = new string[list.Count];
                        for (int i = 0; i < list.Count; i++)
                        {
                            materialNames[i] = list[i].name;
                        }
                    }
                    if (remappedMaterials != null)
                    {
                        remappedMaterials = remappedMaterials.Where(item => item.material != null && materialNames.Contains(item.name)).ToArray();
                    }
                }
                #endregion

                #region Structure
                if (voxelObject.voxelStructure != null)
                {
                    if (legacyAssetNaming)
                    {
                        voxelObject.voxelStructure.name = "structure";
                    }
                    else
                    {
                        voxelObject.voxelStructure.name = Path.GetFileNameWithoutExtension(ctx.assetPath);
                    }
                }
                #endregion

                #region Collider
                foreach (var chunk in voxelObject.chunks)
                {
                    switch (colliderType)
                    {
                    case ColliderType.Box:
                        chunk.gameObject.AddComponent <BoxCollider>();
                        break;

                    case ColliderType.Sphere:
                        chunk.gameObject.AddComponent <SphereCollider>();
                        break;

                    case ColliderType.Capsule:
                        chunk.gameObject.AddComponent <CapsuleCollider>();
                        break;

                    case ColliderType.Mesh:
                        chunk.gameObject.AddComponent <MeshCollider>();
                        break;
                    }
                }
                #endregion

                Export(objectCore);

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(gameObjectName, gameObject);
                foreach (var chunk in voxelObject.chunks)
                {
                    ctx.AddObjectToAsset(chunk.chunkName + "_mesh", chunk.mesh);
                }
                {
                    if (materialMode == VoxelChunksObject.MaterialMode.Combine)
                    {
                        var materials = new List <Material>();
                        for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                        {
                            var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                            materials.Add(material);
                            if (remappedMaterials != null)
                            {
                                var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                if (index >= 0)
                                {
                                    materials[i] = remappedMaterials[index].material;
                                    continue;
                                }
                            }
                            ctx.AddObjectToAsset(string.Format("mat{0}", i), material);
                        }
                        foreach (var chunk in voxelObject.chunks)
                        {
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                        }
                        ctx.AddObjectToAsset("tex", voxelObject.atlasTexture);
                    }
                    else if (materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        foreach (var chunk in voxelObject.chunks)
                        {
                            var materials = new List <Material>();
                            for (int i = 0; i < chunk.materialIndexes.Count; i++)
                            {
                                var material = chunk.materials[chunk.materialIndexes[i]];
                                materials.Add(material);
                                if (remappedMaterials != null)
                                {
                                    var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                    if (index >= 0)
                                    {
                                        materials[i] = remappedMaterials[index].material;
                                        continue;
                                    }
                                }
                                ctx.AddObjectToAsset(chunk.gameObject.name + string.Format("_mat{0}", i), material);
                            }
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                            ctx.AddObjectToAsset(chunk.gameObject.name + "_tex", chunk.atlasTexture);
                        }
                    }
                }
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddObjectToAsset("structure", voxelObject.voxelStructure);
                }

                foreach (var chunk in voxelObject.chunks)
                {
                    VoxelChunksObjectChunk.DestroyImmediate(chunk.GetComponent <VoxelChunksObjectChunk>());
                }
                VoxelObject.DestroyImmediate(voxelObject);

                ctx.SetMainObject(gameObject);
#else
                ctx.SetMainAsset(gameObjectName, gameObject);
                foreach (var chunk in voxelObject.chunks)
                {
                    ctx.AddSubAsset(chunk.gameObject.name + "_mesh", chunk.mesh);
                }
                {
                    if (materialMode == VoxelChunksObject.MaterialMode.Combine)
                    {
                        var materials = new List <Material>();
                        for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                        {
                            var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                            materials.Add(material);
                            if (remappedMaterials != null)
                            {
                                var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                if (index >= 0)
                                {
                                    materials[i] = remappedMaterials[index].material;
                                    continue;
                                }
                            }
                            ctx.AddSubAsset(string.Format("mat{0}", i), material, material);
                        }
                        foreach (var chunk in voxelObject.chunks)
                        {
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                        }
                        ctx.AddSubAsset("tex", voxelObject.atlasTexture);
                    }
                    else if (materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        foreach (var chunk in voxelObject.chunks)
                        {
                            var materials = new List <Material>();
                            for (int i = 0; i < chunk.materialIndexes.Count; i++)
                            {
                                var material = chunk.materials[chunk.materialIndexes[i]];
                                materials.Add(material);
                                if (remappedMaterials != null)
                                {
                                    var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                    if (index >= 0)
                                    {
                                        materials[i] = remappedMaterials[index].material;
                                        continue;
                                    }
                                }
                                ctx.AddSubAsset(chunk.gameObject.name + string.Format("_mat{0}", i), material);
                            }
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                            ctx.AddSubAsset(chunk.gameObject.name + "_tex", chunk.atlasTexture);
                        }
                    }
                }
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddSubAsset("structure", voxelObject.voxelStructure);
                }

                foreach (var chunk in voxelObject.chunks)
                {
                    VoxelChunksObjectChunk.DestroyImmediate(chunk.GetComponent <VoxelChunksObjectChunk>());
                }
                VoxelObject.DestroyImmediate(voxelObject);
#endif
                #endregion
            }

            dataVersion = EditorDataVersion;
        }
コード例 #27
0
    private void ImportYarn(AssetImportContext ctx)
    {
        var    sourceText = File.ReadAllText(ctx.assetPath);
        string fileName   = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);

        try
        {
            // Compile the source code into a compiled Yarn program (or
            // generate a parse error)
            compilationStatus = Compiler.CompileString(sourceText, fileName, out var compiledProgram, out var stringTable);

            // Create a container for storing the bytes
            var programContainer = ScriptableObject.CreateInstance <YarnProgram>();

            using (var memoryStream = new MemoryStream())
                using (var outputStream = new Google.Protobuf.CodedOutputStream(memoryStream))
                {
                    // Serialize the compiled program to memory
                    compiledProgram.WriteTo(outputStream);
                    outputStream.Flush();

                    byte[] compiledBytes = memoryStream.ToArray();

                    programContainer.compiledProgram = compiledBytes;

                    // Add this container to the imported asset; it will be
                    // what the user interacts with in Unity
                    ctx.AddObjectToAsset("Program", programContainer);
                    ctx.SetMainObject(programContainer);

                    isSuccesfullyCompiled = true;
                }

            if (stringTable.Count > 0)
            {
                using (var memoryStream = new MemoryStream())
                    using (var textWriter = new StreamWriter(memoryStream)) {
                        // Generate the localised .csv file
                        var csv = new CsvHelper.CsvWriter(textWriter);

                        var lines = stringTable.Select(x => new {
                            id         = x.Key,
                            text       = x.Value.text,
                            file       = x.Value.fileName,
                            node       = x.Value.nodeName,
                            lineNumber = x.Value.lineNumber
                        });

                        csv.WriteRecords(lines);

                        textWriter.Flush();

                        memoryStream.Position = 0;

                        using (var reader = new StreamReader(memoryStream)) {
                            var textAsset = new TextAsset(reader.ReadToEnd());
                            textAsset.name = $"{fileName} ({baseLanguageID})";

                            ctx.AddObjectToAsset("Strings", textAsset);

                            programContainer.baseLocalisationStringTable = textAsset;
                            baseLanguage = textAsset;
                            programContainer.localizations = localizations;
                        }

                        stringIDs = lines.Select(l => l.id).ToArray();
                    }
            }
        }
        catch (Yarn.Compiler.ParseException e)
        {
            isSuccesfullyCompiled   = false;
            compilationErrorMessage = e.Message;
            ctx.LogImportError(e.Message);
            return;
        }
    }
コード例 #28
0
        bool ParseCubeData(AssetImportContext ctx, out int lutSize, out Color[] pixels)
        {
            // Quick & dirty error utility
            bool Error(string msg)
            {
                ctx.LogImportError(msg);
                return(false);
            }

            var lines = File.ReadAllLines(ctx.assetPath);

            pixels  = null;
            lutSize = -1;

            // Start parsing
            int sizeCube = -1;
            var table    = new List <Color>();

            for (int i = 0; true; i++)
            {
                // EOF
                if (i >= lines.Length)
                {
                    if (table.Count != sizeCube)
                    {
                        return(Error("Premature end of file"));
                    }

                    break;
                }

                // Cleanup & comment removal
                var line = FilterLine(lines[i]);

                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                // Header data
                if (line.StartsWith("TITLE"))
                {
                    continue; // Skip the title tag, we don't need it
                }
                if (line.StartsWith("LUT_3D_SIZE"))
                {
                    var sizeStr = line.Substring(11).TrimStart();

                    if (!int.TryParse(sizeStr, out var size))
                    {
                        return(Error($"Invalid data on line {i}"));
                    }

                    if (size < GlobalPostProcessSettings.k_MinLutSize || size > GlobalPostProcessSettings.k_MaxLutSize)
                    {
                        return(Error("LUT size out of range"));
                    }

                    lutSize  = size;
                    sizeCube = size * size * size;

                    continue;
                }

                if (line.StartsWith("DOMAIN_"))
                {
                    continue; // Skip domain boundaries, haven't run into a single cube file that used them
                }
                // Table
                var row = line.Split();

                if (row.Length != 3)
                {
                    return(Error($"Invalid data on line {i}"));
                }

                var color = Color.black;

                for (int j = 0; j < 3; j++)
                {
                    if (!float.TryParse(row[j], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out var d))
                    {
                        return(Error($"Invalid data on line {i}"));
                    }

                    color[j] = d;
                }

                table.Add(color);
            }

            if (sizeCube != table.Count)
            {
                return(Error($"Wrong table size - Expected {sizeCube} elements, got {table.Count}"));
            }

            pixels = table.ToArray();
            return(true);
        }
コード例 #29
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var width         = 64;
            var mipmapEnabled = true;
            var textureFormat = TextureFormat.RGBA32;
            var srgbTexture   = true;

            // Mark all input textures as dependency to the CubemapArray.
            // This causes the CubemapArray to get re-generated when any input texture changes or when the build target changed.
            for (var n = 0; n < m_Cubemaps.Count; ++n)
            {
                var source = m_Cubemaps[n];
                if (source != null)
                {
                    var path = AssetDatabase.GetAssetPath(source);
#if UNITY_2020_1_OR_NEWER
                    ctx.DependsOnArtifact(path);
#else
                    ctx.DependsOnSourceAsset(path);
#endif
                }
            }

#if !UNITY_2020_1_OR_NEWER
            // This value is not really used in this importer,
            // but getting the build target here will add a dependency to the current active buildtarget.
            // Because DependsOnArtifact does not exist in 2019.4, adding this dependency on top of the DependsOnSourceAsset
            // will force a re-import when the target platform changes in case it would have impacted any texture this importer depends on.
            var buildTarget = ctx.selectedBuildTarget;
#endif

            // Check if the input textures are valid to be used to build the texture array.
            var isValid = Verify(ctx, false);
            if (isValid)
            {
                // Use the texture assigned to the first slice as "master".
                // This means all other textures have to use same settings as the master texture.
                var sourceTexture = m_Cubemaps[0];
                width         = sourceTexture.width;
                textureFormat = sourceTexture.format;

                var sourceTexturePath = AssetDatabase.GetAssetPath(sourceTexture);
                var textureImporter   = (TextureImporter)AssetImporter.GetAtPath(sourceTexturePath);
                mipmapEnabled = textureImporter.mipmapEnabled;
                srgbTexture   = textureImporter.sRGBTexture;
            }

            CubemapArray cubemapArray;
            try
            {
                // Create the texture array.
                // When the texture array asset is being created, there are no input textures added yet,
                // thus we do Max(1, Count) to make sure to add at least 1 slice.
                cubemapArray = new CubemapArray(width, Mathf.Max(1, m_Cubemaps.Count), textureFormat, mipmapEnabled, !srgbTexture);
            }
            catch (System.Exception e)
            {
                Debug.LogException(e);
                ctx.LogImportError($"Import failed '{ctx.assetPath}'.", ctx.mainObject);

                isValid       = false;
                textureFormat = TextureFormat.RGBA32;
                cubemapArray  = new CubemapArray(width, Mathf.Max(1, m_Cubemaps.Count), textureFormat, mipmapEnabled, !srgbTexture);
            }

            cubemapArray.wrapMode   = m_WrapMode;
            cubemapArray.filterMode = m_FilterMode;
            cubemapArray.anisoLevel = m_AnisoLevel;

            if (isValid)
            {
                // If everything is valid, copy source textures over to the texture array.
                for (int face = 0; face < 6; face++)
                {
                    for (var n = 0; n < m_Cubemaps.Count; ++n)
                    {
                        var source = m_Cubemaps[n];
                        Graphics.CopyTexture(source, face, cubemapArray, face + (n * 6));
                    }
                }
            }
            else
            {
                // If there is any error, copy a magenta colored texture into every slice.
                // I was thinking to only make the invalid slice magenta, but then it's way less obvious that
                // something isn't right with the texture array. Thus I mark the entire texture array as broken.
                var errorTexture = new Cubemap(width, textureFormat, mipmapEnabled);
                try
                {
                    for (var face = 0; face < 6; ++face)
                    {
                        var errorPixels = errorTexture.GetPixels((CubemapFace)face);
                        for (var n = 0; n < errorPixels.Length; ++n)
                        {
                            errorPixels[n] = Color.magenta;
                        }
                        errorTexture.SetPixels(errorPixels, (CubemapFace)face);
                    }
                    errorTexture.Apply();

                    for (int face = 0; face < 6; face++)
                    {
                        for (var n = 0; n < cubemapArray.cubemapCount; ++n)
                        {
                            Graphics.CopyTexture(errorTexture, face, cubemapArray, face + (n * 6));
                        }
                    }
                }
                finally
                {
                    DestroyImmediate(errorTexture);
                }
            }

            // this should have been named "MainAsset" to be conform with Unity, but changing it now
            // would break all existing CubemapArray assets, so we don't touch it.
            cubemapArray.Apply(false, !m_IsReadable);
            ctx.AddObjectToAsset("CubemapArray", cubemapArray);
            ctx.SetMainObject(cubemapArray);

            if (!isValid)
            {
                // Run the verify step again, but this time we have the main object asset.
                // Console logs should ping the asset, but they don't in 2019.3 beta, bug?
                Verify(ctx, true);
            }
        }
コード例 #30
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            {
                var ext = Path.GetExtension(ctx.assetPath).ToLower();
                if (ext == ".vox")
                {
                    fileType = VoxelBase.FileType.vox;
                }
                else if (ext == ".qb")
                {
                    fileType = VoxelBase.FileType.qb;
                }
                else
                {
                    return;
                }
            }

            #region DefaultScale
            if (dataVersion == 0 &&
                importScale == Vector3.one &&
                AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(ctx.assetPath) == null)
            {
                var x = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleX", 1f);
                var y = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleY", 1f);
                var z = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleZ", 1f);
                importScale = new Vector3(x, y, z);
            }
            #endregion

            Action <string> LogImportError = (log) =>
            {
#if UNITY_2018_1_OR_NEWER
                ctx.LogImportError(log);
#else
                Debug.LogError(log);
#endif
            };

            var gameObject  = new GameObject(Path.GetFileNameWithoutExtension(ctx.assetPath));
            var voxelObject = gameObject.AddComponent <VoxelObject>();
            {
                voxelObject.legacyVoxImport               = legacyVoxImport;
                voxelObject.importMode                    = importMode;
                voxelObject.importScale                   = importScale;
                voxelObject.importOffset                  = importOffset;
                voxelObject.combineFaces                  = combineFaces;
                voxelObject.ignoreCavity                  = ignoreCavity;
                voxelObject.voxelStructure                = outputStructure ? ScriptableObject.CreateInstance <VoxelStructure>() : null;
                voxelObject.generateLightmapUVs           = generateLightmapUVs;
                voxelObject.generateLightmapUVsAngleError = generateLightmapUVsAngleError;
                voxelObject.generateLightmapUVsAreaError  = generateLightmapUVsAreaError;
                voxelObject.generateLightmapUVsHardAngle  = generateLightmapUVsHardAngle;
                voxelObject.generateLightmapUVsPackMargin = generateLightmapUVsPackMargin;
                voxelObject.generateTangents              = generateTangents;
                voxelObject.meshFaceVertexOffset          = meshFaceVertexOffset;
                voxelObject.loadFromVoxelFile             = loadFromVoxelFile;
                voxelObject.generateMipMaps               = generateMipMaps;
            }
            var objectCore = new VoxelObjectCore(voxelObject);
            try
            {
                if (!objectCore.Create(ctx.assetPath, null))
                {
                    LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                    DestroyImmediate(gameObject);
                    return;
                }
            }
            catch
            {
                LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                DestroyImmediate(gameObject);
                return;
            }

            #region Correspondence in Issue ID 947055 Correction in case before correction is applied
            for (int i = 0; i < voxelObject.materials.Count; i++)
            {
                if (voxelObject.materials[i] != null)
                {
                    voxelObject.materials[i].hideFlags |= HideFlags.NotEditable;
                }
            }
            if (voxelObject.atlasTexture != null)
            {
                voxelObject.atlasTexture.hideFlags |= HideFlags.NotEditable;
            }
            if (voxelObject.mesh != null)
            {
                voxelObject.mesh.hideFlags |= HideFlags.NotEditable;
            }
            #endregion

            #region Material
            {
                materials     = new Material[voxelObject.materialIndexes.Count];
                materialNames = new string[voxelObject.materialIndexes.Count];
                for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                {
                    var index    = voxelObject.materialIndexes[i];
                    var material = voxelObject.materials[index];
                    material.name    = string.Format("mat{0}", index);
                    materials[i]     = material;
                    materialNames[i] = material.name;
                }
                if (remappedMaterials != null)
                {
                    remappedMaterials = remappedMaterials.Where(item => item.material != null).ToArray();
                }
            }
            #endregion

            #region Collider
            switch (colliderType)
            {
            case ColliderType.Box:
                gameObject.AddComponent <BoxCollider>();
                break;

            case ColliderType.Sphere:
                gameObject.AddComponent <SphereCollider>();
                break;

            case ColliderType.Capsule:
                gameObject.AddComponent <CapsuleCollider>();
                break;

            case ColliderType.Mesh:
                gameObject.AddComponent <MeshCollider>();
                break;
            }
            #endregion

#if UNITY_2017_3_OR_NEWER
            ctx.AddObjectToAsset(gameObject.name, gameObject);
            ctx.AddObjectToAsset(voxelObject.mesh.name = "mesh", voxelObject.mesh);
            {
                var materials = new List <Material>();
                for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                {
                    var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                    materials.Add(material);
                    if (remappedMaterials != null)
                    {
                        var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                        if (index >= 0)
                        {
                            materials[i] = remappedMaterials[index].material;
                            continue;
                        }
                    }
                    ctx.AddObjectToAsset(material.name, material);
                }
                gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
            }
            ctx.AddObjectToAsset(voxelObject.atlasTexture.name = "tex", voxelObject.atlasTexture);
            if (voxelObject.voxelStructure != null)
            {
                ctx.AddObjectToAsset(voxelObject.voxelStructure.name = "structure", voxelObject.voxelStructure);
            }

            VoxelObject.DestroyImmediate(voxelObject);

            ctx.SetMainObject(gameObject);
#else
            ctx.SetMainAsset(gameObject.name, gameObject);
            ctx.AddSubAsset(voxelObject.mesh.name = "mesh", voxelObject.mesh);
            for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
            {
                var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                ctx.AddSubAsset(material.name, material);
            }
            ctx.AddSubAsset(voxelObject.atlasTexture.name = "tex", voxelObject.atlasTexture);
            if (voxelObject.voxelStructure != null)
            {
                ctx.AddSubAsset(voxelObject.voxelStructure.name = "structure", voxelObject.voxelStructure);
            }

            VoxelObject.DestroyImmediate(voxelObject);
#endif
            dataVersion = EditorDataVersion;
        }