Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 55 additions & 48 deletions Assets/LDtkUnity/Editor/ScriptedImporter/LDtkProjectImporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,17 @@ internal sealed class LDtkProjectImporter : LDtkJsonImporter<LDtkProjectFile>
public const string CREATE_LEVEL_BOUNDS_TRIGGER = nameof(_createLevelBoundsTrigger);
public const string USE_PARALLAX = nameof(_useParallax);
public const string SCALE_ENTITIES = nameof(_scaleEntities);

public const string INTGRID = nameof(_intGridValues);
public const string ENTITIES = nameof(_entities);

public const string ENUM_GENERATE = nameof(_enumGenerate);
public const string ENUM_PATH = nameof(_enumPath);
public const string ENUM_NAMESPACE = nameof(_enumNamespace);
public const string USE_LAYER_SORTING_ORDERS = nameof(_useLayerCustomSortingOrders);
public const string LAYER_SORTING_ORDERS = nameof(_layerCustomSortingOrders);

public const string USE_LAYER_SORTING_ORDERS = nameof(_useLayerCustomSortingOrders);
public const string LAYER_SORTING_ORDERS = nameof(_layerCustomSortingOrders);

/// <summary>
/// This is cached into the meta file upon an import. Could be null if the import was a failure. Invisible to the inspector.
/// </summary>
Expand All @@ -56,19 +56,19 @@ internal sealed class LDtkProjectImporter : LDtkJsonImporter<LDtkProjectFile>
[SerializeField] private bool _createLevelBoundsTrigger = false;
[SerializeField] private bool _useParallax = true;
[SerializeField] private bool _scaleEntities = true;

[SerializeField] private LDtkAssetIntGridValue[] _intGridValues = Array.Empty<LDtkAssetIntGridValue>();

[SerializeField] private LDtkAssetEntity[] _entities = Array.Empty<LDtkAssetEntity>();

[SerializeField] private bool _enumGenerate = false;
[SerializeField] private string _enumPath = null;
[SerializeField] private string _enumNamespace = string.Empty;

[SerializeField] private bool _useLayerCustomSortingOrders = false;
[SerializeField] private LDtkLayerCustomSortingOrder[] _layerCustomSortingOrders = Array.Empty<LDtkLayerCustomSortingOrder>();
[SerializeField] private LDtkLayerCustomSortingOrder[] _layerCustomSortingOrders = Array.Empty<LDtkLayerCustomSortingOrder>();



public LDtkProjectFile JsonFile => _jsonFile;
public bool IntGridValueColorsVisible => _intGridValueColorsVisible;
public int PixelsPerUnit => _pixelsPerUnit;
Expand Down Expand Up @@ -123,38 +123,38 @@ protected override void Import()
FailImport();
return;
}

if (IsVersionOutdated())
{
BufferEditorCache();
FailImport();
return;
}

LDtkProfiler.BeginSample("CreateJsonAsset");
CreateJsonAsset();
LDtkProfiler.EndSample();

if (!TryGetJson(out LdtkJson json))
{
Logger.LogError("Json deserialization error. Not importing.");
BufferEditorCache();
FailImport();
return;
}

LDtkProfiler.BeginSample("CacheSchemaDefs");
CacheSchemaDefs(json);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("CreateArtifactAsset");
CreateArtifactAsset(json);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("MakeDefObjects");
MakeDefObjects(json);
LDtkProfiler.EndSample();

//if for whatever reason (or backwards compatibility), if the ppu is -1 in any capacity
LDtkProfiler.BeginSample("SetPixelsPerUnit");
LDtkPpuInitializer ppu = new LDtkPpuInitializer(_pixelsPerUnit, assetPath, assetPath);
Expand All @@ -164,27 +164,27 @@ protected override void Import()
EditorUtility.SetDirty(this);
}
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("CreateTableOfContents");
TryCreateTableOfContents(json);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("MainBuild");
MainBuild(json);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("TryGenerateEnums");
TryGenerateEnums(json);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("CreateConfigurationFile");
GenerateConfigurationFile(json);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("BufferEditorCache");
BufferEditorCache();
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("ReleaseDefs");
ReleaseDefs();
LDtkProfiler.EndSample();
Expand All @@ -197,11 +197,11 @@ private void MakeDefObjects(LdtkJson json)
LDtkProfiler.BeginSample("InitializeFromProject");
DefinitionObjects.InitializeFromProject(json.Defs, artifacts);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("Set _definitions");
_artifacts._definitions = DefinitionObjects.Defs;
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("AddAllObjectsToAsset");
foreach (var obj in DefinitionObjects.Defs)
{
Expand Down Expand Up @@ -242,18 +242,18 @@ private void TryCreateTableOfContents(LdtkJson json)
{
return;
}

Toc = ScriptableObject.CreateInstance<LDtkTableOfContents>();
Toc.name += AssetName + "_Toc";

LDtkTocFieldFactory factory = new LDtkTocFieldFactory(json, this, this);

LDtkProfiler.BeginSample("Toc_IndexEntitiesAndFieldsByIdentifiers");
factory.IndexEntitiesAndFieldsByIdentifiers();
LDtkProfiler.EndSample();

Toc.InitializeList(json);

LDtkFieldParser.CacheRecentBuilder(null);
LDtkProfiler.BeginSample("Toc_GenerateAndAddEntries");
foreach (LdtkTableOfContentEntry tocEntry in json.Toc)
Expand All @@ -262,8 +262,8 @@ private void TryCreateTableOfContents(LdtkJson json)
Toc.AddEntry(tocEntry, output.Definition, output.Fields);
}
LDtkProfiler.EndSample();


ImportContext.AddObjectToAsset("toc", Toc, LDtkIconUtility.LoadListIcon());
}

Expand All @@ -288,13 +288,20 @@ private void GenerateConfigurationFile(LdtkJson json)
Entities = _entities,
ScaleEntities = _scaleEntities,
};
config.WriteJson(assetPath);

//importing the asset if it doesn't exist due to the asset database not refreshing this automatically
//NOTE: This is not allowed during the import of another asset because of determinism
//AssetDatabase.ImportAsset(writePath);
string writePath = config.WriteJson(assetPath, out bool isChanged);

if (isChanged)
{
EditorApplication.delayCall += () =>
{
if (File.Exists(writePath))
{
AssetDatabase.ImportAsset(writePath, ImportAssetOptions.ForceUpdate);
}
};
}
}

private void BufferEditorCache()
{
EditorApplication.delayCall += () =>
Expand All @@ -309,11 +316,11 @@ private void MainBuild(LdtkJson json)
var preAction = new LDtkAssetProcessorActionCache();
LDtkAssetProcessorInvoker.AddPreProcessProject(preAction, json, AssetName);
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("RunPreprocessors");
preAction.Process();
LDtkProfiler.EndSample();

LDtkProfiler.BeginSample("ImportProject");
LDtkBuilderProjectFactory factory = new LDtkBuilderProjectFactory(this);
factory.Import(json);
Expand All @@ -327,7 +334,7 @@ private void TryGenerateEnums(LdtkJson json)
{
return;
}

LDtkProjectImporterEnumGenerator enumGenerator = new LDtkProjectImporterEnumGenerator(json.Defs.Enums, ImportContext, _enumPath, _enumNamespace);
enumGenerator.Generate();
}
Expand All @@ -336,12 +343,12 @@ private void CreateArtifactAsset(LdtkJson json)
{
_artifacts = ScriptableObject.CreateInstance<LDtkArtifactAssets>();
_artifacts.name = AssetName + "_Artifacts";

LDtkProfiler.BeginSample("CreateAllBackgrounds");
LDtkBackgroundSliceCreator bgMaker = new LDtkBackgroundSliceCreator(this);
List<Sprite> allBackgrounds = bgMaker.CreateAllBackgrounds(json);
LDtkProfiler.EndSample();

_artifacts._backgrounds = new List<Sprite>(allBackgrounds);
foreach (Sprite bg in allBackgrounds)
{
Expand All @@ -354,7 +361,7 @@ private void CreateArtifactAsset(LdtkJson json)
}
ImportContext.AddObjectToAsset("artifacts", _artifacts, (Texture2D)LDtkIconUtility.GetUnityIcon("Image"));
}

public TileBase GetIntGridValueTile(string key) => GetSerializedImporterAsset(_intGridValues, key);
public GameObject GetEntity(string key) => GetSerializedImporterAsset(_entities, key);
private T GetSerializedImporterAsset<T>(IEnumerable<LDtkAsset<T>> input, string key) where T : Object //todo these should be indexed too for performance.
Expand Down Expand Up @@ -382,20 +389,20 @@ private void CreateArtifactAsset(LdtkJson json)
{
continue;
}

return (T)asset.Asset;
}

return default;
}

public void TryCacheArtifactsAsset(LDtkDebugInstance logger)
{
if (_artifacts != null)
{
return;
}

_artifacts = AssetDatabase.LoadAssetAtPath<LDtkArtifactAssets>(assetPath);
if (_artifacts == null)
{
Expand All @@ -420,11 +427,11 @@ public Sprite GetBackgroundArtifact(Level level)
}

LDtkArtifactAssets ldtkArtifactAssets = GetArtifactAssets();
string assetName = level.Identifier;
string assetName = level.Identifier;

Sprite asset = ldtkArtifactAssets.GetBackgroundSlow(assetName);
if (asset != null)
{
{
return asset;
}
Logger.LogError($"Tried retrieving a background from the importer's artifacts, but was null: \"{assetName}\"");
Expand Down
16 changes: 9 additions & 7 deletions Assets/LDtkUnity/Editor/Utility/Artifacts/LDtkConfigData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,16 @@ internal struct LDtkConfigData
public bool ScaleEntities;
public LDtkAssetIntGridValue[] IntGridValues;
public LDtkAssetEntity[] Entities;
internal string WriteJson(string projectAssetPath)

internal string WriteJson(string projectAssetPath, out bool isChanged)
{
string writePath = GetPath(projectAssetPath);
string json = EditorJsonUtility.ToJson(this, true);
byte[] byteArray = Encoding.UTF8.GetBytes(json);

isChanged = false;

LDtkPathUtility.TryCreateDirectoryForFile(writePath);

//Only write if the contents are actually changed! Otherwise, it's been observed to pollute source control
//It's not good practice to write files to disk during a scripted importer, but it works for now.
if (File.Exists(writePath))
Expand All @@ -41,11 +42,12 @@ internal string WriteJson(string projectAssetPath)
return writePath;
}
}


isChanged = true;
File.WriteAllBytes(writePath, byteArray);
return writePath;
}

internal static LDtkConfigData ReadJson(string assetPath)
{
if (!File.Exists(assetPath))
Expand All @@ -60,7 +62,7 @@ internal static LDtkConfigData ReadJson(string assetPath)
EditorJsonUtility.FromJsonOverwrite(json, data);
return data;
}

internal static string GetPath(string projectAssetPath)
{
string dir = Path.GetDirectoryName(projectAssetPath);
Expand Down