-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathcodec.ts
More file actions
398 lines (347 loc) · 11.1 KB
/
codec.ts
File metadata and controls
398 lines (347 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import { sanitizeStorageKey } from 'src/util/minecraftUtil'
import { registerCodec } from 'src/util/moddingTools'
import { translate } from 'src/util/translation'
import { Variant } from 'src/variants'
import {
BLUEPRINT_FORMAT,
BLUEPRINT_FORMAT_ID,
getDefaultProjectSettings,
IBlueprintFormatJSON,
ICollectionJSON,
} from '.'
import { PACKAGE } from '../../constants'
import * as modelDatFixerUpper from './dfu'
import * as blueprintSettings from './settings'
// region Codec
export const BLUEPRINT_CODEC = registerCodec(
{ id: 'animated-java:codec/blueprint' },
{
name: 'Blueprint',
extension: 'ajblueprint',
remember: true,
load_filter: {
extensions: ['ajblueprint'],
type: 'json',
},
// region > load
load(model, file) {
const format = BLUEPRINT_FORMAT.get()
if (!format) throw new Error('Animated Java Blueprint format is not registered!')
console.log(`Loading Animated Java Blueprint from '${file.name}'...`)
model = modelDatFixerUpper.process(model)
setupProject(format, model.meta?.uuid)
if (!Project) throw new Error('Failed to load Animated Java Blueprint')
this.parse!(model, file.path)
const name = pathToName(file.path, true)
if (file.path && isApp && !file.no_file) {
Project.name = pathToName(file.path, false)
Project.save_path = file.path
addRecentProject({
name,
path: file.path,
icon: BLUEPRINT_FORMAT.get()?.icon,
})
const project = Project
setTimeout(() => {
if (Project === project) void updateRecentProjectThumbnail()
}, 500)
}
Settings.updateSettingsInProfiles()
console.log(
`Successfully loaded Animated Java Blueprint` +
`\n - Project: ${Project.name}` +
`\n - UUID: ${Project.uuid}`
)
},
// region > parse
// Takes the model file and injects it's data into the global Project
parse(model: IBlueprintFormatJSON, path) {
console.log(`Parsing Animated Java Blueprint from '${path}'...`)
if (!Project) throw new Error('No project to parse into')
Project.save_path = path
if (model.meta?.box_uv !== undefined) {
Project.box_uv = model.meta.box_uv
}
if (model.resolution !== undefined) {
Project.texture_width = model.resolution.width ?? 16
Project.texture_height = model.resolution.height ?? 16
}
// Misc Project Properties
for (const key in ModelProject.properties) {
ModelProject.properties[key].merge(Project, model)
}
if (model.blueprint_settings) {
Project.animated_java = {
...blueprintSettings.defaultValues,
...model.blueprint_settings,
}
}
Project.last_used_export_namespace =
model.meta?.last_used_export_namespace ?? Project.animated_java.export_namespace
if (model.textures) {
for (const texture of model.textures) {
const newTexture = new Texture(texture, texture.uuid).add(false)
if (texture.relative_path && Project.save_path) {
const resolvedPath = PathModule.resolve(
Project.save_path,
texture.relative_path
)
if (fs.existsSync(resolvedPath)) {
newTexture.fromPath(resolvedPath)
continue
}
}
if (texture.path && fs.existsSync(texture.path) && !model.meta?.backup) {
newTexture.fromPath(texture.path)
} else if (texture.source?.startsWith('data:')) {
newTexture.fromDataURL(texture.source)
}
}
}
if (model.elements) {
const defaultTexture = Texture.getDefault()
for (const element of model.elements) {
const newElement = OutlinerElement.fromSave(element, true)
switch (true) {
case newElement instanceof Cube: {
for (const face in newElement.faces) {
if (element.faces) {
const texture =
element.faces[face].texture !== undefined &&
Texture.all[element.faces[face].texture]
if (texture) {
newElement.faces[face].texture = texture.uuid
}
} else if (
defaultTexture &&
newElement.faces &&
newElement.faces[face].texture !== undefined
) {
newElement.faces[face].texture = defaultTexture.uuid
}
}
break
}
}
}
}
if (model.outliner) {
parseGroups(model.outliner)
for (const group of Group.all) {
group.name = sanitizeStorageKey(group.name)
}
}
if (model.variants) {
Variant.all = []
if (model.variants.default) {
Variant.fromJSON(model.variants?.default, true)
} else {
console.warn('No default Variant found, creating one named "Default"')
new Variant('Default', true)
}
if (Array.isArray(model.variants.list)) {
for (const variantJSON of model.variants.list) {
Variant.fromJSON(variantJSON)
}
Project.variants = Variant.all
}
}
if (model.animations) {
for (const animation of model.animations) {
const newAnimation = new Blockbench.Animation()
newAnimation.uuid = animation.uuid ?? guid()
newAnimation.extend(animation).add()
}
}
if (model.animation_controllers) {
for (const controller of model.animation_controllers) {
const newController = new Blockbench.AnimationController()
newController.uuid = controller.uuid ?? guid()
newController.extend(controller).add()
}
}
if (model.animation_variable_placeholders) {
Interface.Panels.variable_placeholders.inside_vue.$data.text =
model.animation_variable_placeholders
}
if (model.backgrounds) {
for (const key in model.backgrounds) {
if (Object.hasOwn(Project.backgrounds, key)) {
const store = model.backgrounds[key]
const real = Project.backgrounds[key]
if (store.image !== undefined) {
real.image = store.image
}
if (store.size !== undefined) {
real.size = store.size
}
if (store.x !== undefined) {
real.x = store.x
}
if (store.y !== undefined) {
real.y = store.y
}
if (store.lock !== undefined) {
real.lock = store.lock
}
}
}
Preview.all.forEach(p => {
if (p.canvas.isConnected) {
p.loadBackground()
}
})
}
if (Array.isArray(model.collections)) {
for (const collectionJSON of model.collections) {
new Collection(collectionJSON, collectionJSON.uuid).add()
}
}
Canvas.updateAll()
Validator.validate()
this.dispatchEvent!('parsed', { model })
},
// region > compile
compile(options = {}) {
console.log(`Compiling Animated Java Blueprint from ${Project!.name}...`)
if (!Project) throw new Error('No project to compile.')
// Disable variants while compiling
const previouslySelectedVariant = Variant.selected
Variant.selectDefault()
const model: IBlueprintFormatJSON = {
meta: {
format: BLUEPRINT_FORMAT_ID,
format_version: PACKAGE.version,
uuid: Project.uuid,
save_location: Project.save_path,
last_used_export_namespace: Project.last_used_export_namespace,
},
resolution: {
width: Project.texture_width ?? 16,
height: Project.texture_height ?? 16,
},
}
const defaultSettings = getDefaultProjectSettings()
for (const key of Object.keys(Project.animated_java) as Array<
keyof typeof Project.animated_java
>) {
const value = Project.animated_java[key]
if (value == undefined || value === defaultSettings[key]) continue
model.blueprint_settings ??= {}
// @ts-expect-error - Cannot index blueprint_settings with key
model.blueprint_settings[key] = value
}
for (const key in ModelProject.properties) {
if (ModelProject.properties[key].export)
ModelProject.properties[key].copy(Project, model)
}
model.elements = []
for (const element of elements) {
model.elements.push(element.getSaveCopy?.(!!model.meta))
}
model.outliner = compileGroups(true)
model.textures = []
for (const texture of Texture.all) {
const save = texture.getSaveCopy() as Texture
delete save.selected
if (
isApp &&
Project.save_path &&
texture.path &&
PathModule.isAbsolute(texture.path)
) {
const relative = PathModule.relative(
PathModule.dirname(Project.save_path),
texture.path
)
save.relative_path = relative.replace(/\\/g, '/')
}
if (
options.bitmaps != false &&
(Settings.get('embed_textures') || options.backup || options.bitmaps == true)
) {
save.source = texture.getDataURL()
save.internal = true
}
if (options.absolute_paths == false) delete save.path
model.textures.push(save)
}
model.variants = {
default: Variant.getDefault().toJSON(),
list: Variant.allExcludingDefault().map(v => v.toJSON()),
}
const animationOptions = { bone_names: true, absolute_paths: options.absolute_paths }
if (Blockbench.Animation.all.length > 0) {
model.animations = []
for (const animation of Blockbench.Animation.all) {
if (!animation.getUndoCopy) continue
model.animations.push(animation.getUndoCopy(animationOptions, true))
}
}
if (Blockbench.AnimationController.all.length > 0) {
model.animation_controllers = []
for (const controller of Blockbench.AnimationController.all) {
if (!controller.getUndoCopy) continue
model.animation_controllers.push(controller.getUndoCopy(animationOptions, true))
}
}
if (Interface.Panels.variable_placeholders.inside_vue.$data.text) {
model.animation_variable_placeholders =
Interface.Panels.variable_placeholders.inside_vue.$data.text
}
if (!options.backup) {
const backgrounds: Record<string, any> = {}
for (const key in Project.backgrounds) {
const scene = Project.backgrounds[key]
if (scene.image) {
backgrounds[key] = scene.getSaveCopy()
}
}
if (Object.keys(backgrounds).length) {
model.backgrounds = backgrounds
}
}
if (Collection.all.length > 0) {
model.collections = Collection.all.map(
collection => collection.getSaveCopy() as ICollectionJSON
)
}
previouslySelectedVariant?.select()
console.log('Successfully compiled Animated Java Blueprint', model)
return options.raw ? model : compileJSON(model)
},
// region > export
export() {
console.log(`Exporting Animated Java Blueprint for ${Project!.name}...`)
if (!Project) throw new Error('No project to export.')
Blockbench.export({
resource_id: 'animated_java_blueprint.export',
name: (Project.name || 'unnamed') + '.ajblueprint',
startpath: Project.save_path,
type: 'json',
extensions: [this.extension],
content: this.compile!(),
// eslint-disable-next-line @typescript-eslint/naming-convention
custom_writer: (content, path) => {
if (fs.existsSync(PathModule.dirname(path))) {
Project!.save_path = path
this.write!(content, path)
} else {
console.error(
`Failed to export Animated Java Blueprint, file location '${path}' does not exist!`
)
Blockbench.showMessageBox({
title: translate('error.blueprint_export_path_doesnt_exist.title'),
message: translate('error.blueprint_export_path_doesnt_exist', path),
})
}
},
})
},
// region > fileName
fileName() {
if (!Project?.name) return 'unnamed_project.ajblueprint'
return `${Project.name}.ajblueprint`
},
}
)