forked from alto-io/xgr-arcadians
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.jsx
417 lines (333 loc) · 10.9 KB
/
index.jsx
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import { ScreenshotHandler } from "./screenshotHandler";
import { PartsLoader } from "./partsLoader";
import * as Config from "./config";
import * as BABYLON from "@babylonjs/core/Legacy/legacy";
// import * as jsora from "./jsora";
// global variables
var g_config = Config.g_config;
var g_canvas = null;
var g_scene = null;
var g_engine = null;
var g_camera = null;
var g_isLoaded = false;
var g_partsIdx = 0;
var g_screenshotHandler = new ScreenshotHandler();
var g_partsLoader = new PartsLoader();
var g_animPrev = null;
var g_jsoraProject = null;
var g_oraCanvas = null;
async function loadOraFile() {
g_jsoraProject = window.jsora.JSOra();
const loadedFile = await fetch(g_config.oraConfigPath).then(r => r.blob());
await g_jsoraProject.load(loadedFile);
// console.log("ora loaded");
}
export async function loadLocalOraFile(fileblob) {
try {
await g_jsoraProject.load(fileblob);
} catch (e) {
alert("invalid .ora file");
return false;
}
await initializeVariablesFromOra();
await renderAvatar();
return true;
}
/**
* List of files per avatar part. Contents are generated at runtime, based on g_config.partsConfigPath
* Initial value is sample format for reference.
* */
var g_fileList = [
{
Gender: "Female",
Parts: [
{
Name: "Bottom",
Files: [
{
Name: "Alien-Queen-Bottom",
Path: "v1/arcadian-parts/Female/Bottom/Alien-Queen-Bottom.png",
},
],
},
],
},
];
var g_OraPartsList = { PartsList: {} };
var g_OraPartsCategoryArray = [];
var g_ArrayOfAllParts = [];
var g_initialized = false;
var g_nftLoaded = false;
var g_oraLoaded = false;
/**
* Main initialize function.
*/
export async function initialize(canvas, scene) {
g_canvas = canvas;
g_scene = scene;
g_engine = scene.getEngine();
g_camera = new BABYLON.UniversalCamera("Camera", new BABYLON.Vector3(0, 1, 10), g_scene);
g_camera.setTarget(new BABYLON.Vector3(0, 1, 0));
g_camera.fov = 0.5;
var light1 = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 1, 0), g_scene);
await waitForLoading();
}
export function isInitialized() {
return g_initialized;
}
export function nftLoaded() {
return g_nftLoaded;
}
export function oraLoaded() {
return g_oraLoaded;
}
async function initializeVariablesFromOra() {
function recursivelyCreateNodes(partArray) {
if (partArray.length <= 1) {
return partArray[0];
} else {
var node = {};
var nodeName = partArray.pop();
node[nodeName] = recursivelyCreateNodes(partArray);
return node;
}
}
function addToPartsList(partString) {
const objectToAdd = recursivelyCreateNodes(partString.split("/").reverse());
const partStringArray = partString.split("/");
const name = partStringArray[partStringArray.length - 1];
const path = partString.split("PartsList/")[1];
const partToAdd = {
name,
path
};
var partCategory = partString.slice(0, partString.lastIndexOf("/"));
// check if object should be added to array
var currentPartSet = _.get(g_OraPartsList, partCategory);
if (currentPartSet == undefined) {
currentPartSet = [partToAdd];
} else {
if (Array.isArray(currentPartSet)) {
currentPartSet.push(partToAdd);
} else {
console.warn(`Incorrect partString: ${partString}, not an array`);
}
}
_.set(objectToAdd, partCategory, currentPartSet);
var newItem = partCategory.split("/").pop();
g_OraPartsCategoryArray.indexOf(newItem) === -1 ? g_OraPartsCategoryArray.push(newItem) : 0;
g_ArrayOfAllParts.push(path);
g_OraPartsList = _.merge(g_OraPartsList, objectToAdd);
}
function recurseOverParts(obj, parent) {
for (let child of obj.children) {
if (child.children != undefined) {
// unhide parent layers
child.hidden = false;
recurseOverParts(child, parent + "/" + child.name);
} else {
addToPartsList(parent + "/" + child.name);
}
}
}
g_OraPartsList = { PartsList: {} };
g_OraPartsCategoryArray = [];
g_ArrayOfAllParts = [];
recurseOverParts(g_jsoraProject, "PartsList");
g_ArrayOfAllParts.reverse(); // to display in proper order in frontend
}
export async function initializeOra(canvas) {
g_oraCanvas = canvas;
await loadOraFile();
await initializeVariablesFromOra();
g_oraLoaded = true;
// setTimeout(renderAvatar, 50);
}
export async function initializeOraWithoutCanvas() {
// console.log("loading ora file");
await loadOraFile();
await initializeVariablesFromOra();
g_oraLoaded = true;
}
export function getOraPartsCategories() {
return g_OraPartsCategoryArray;
}
export function getArrayOfAllParts() {
return g_ArrayOfAllParts;
}
export async function getItemImage(itemPath) {
var imageData = await g_jsoraProject.get_by_path(itemPath).get_base64();
return imageData;
}
export function displayPart(itemPath, rerender) {
var partLayer = g_jsoraProject.get_by_path(itemPath);
// hide same layer parts
partLayer.parent && partLayer.parent.children.map((child) =>
{
if (child != partLayer) {
child.hidden = true;
}
}
)
// toggle visibility
partLayer.hidden = !partLayer.hidden;
if (rerender) {
renderAvatar();
}
}
// TODO:
// Loading from jsora source does not currently work on production build due to
// next compile + gpu.js issues. We hack a fix for this by loading jsora via Script in _app.js
//
//
// see:
// https://github.com/gpujs/gpu.js/issues/776
// https://stackoverflow.com/questions/43017000/babel-ignores-es6-inside-react-dangerouslysetinnerhtml-script-tag
//
export async function renderAvatar() {
let rend;
try {
rend = new jsora.Renderer(g_jsoraProject);
} catch (e) {
console.log("canvas dimensions not ready, retrying in 1 second");
setTimeout(renderAvatar, 1000);
return;
}
var renderCanvas = await rend.make_merged_image();
var sourceImageData = renderCanvas.toDataURL("image/png");
var destCanvasContext = g_oraCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function () {
var scaleFactor = Math.min(g_oraCanvas.width / destinationImage.width,
g_oraCanvas.height / destinationImage.height);
var newWidth = destinationImage.width * scaleFactor;
var newHeight = destinationImage.height * scaleFactor;
var x = (g_oraCanvas.width / 2) - (newWidth / 2);
var y = (g_oraCanvas.height / 2) - (newHeight / 2);
destCanvasContext.clearRect(0, 0, g_oraCanvas.width, g_oraCanvas.height);
destCanvasContext.drawImage(destinationImage, x, y, newWidth, newHeight);
// destCanvasContext.drawImage(destinationImage, 0, 0);
};
destinationImage.src = sourceImageData;
}
async function waitForLoading() {
g_fileList.length = 0;
await fetch(g_config.partsConfigPath)
.then((response) => response.json())
.then((json) => (g_fileList = json));
// g_screenshotHandler.initialize(g_config);
g_partsLoader.initialize(g_scene, g_config, g_fileList);
afterLoading();
}
function afterLoading() {
// for debugging
//g_camera.attachControl(g_canvas, true);
//g_scene.debugLayer.show();
initEvents();
initGender();
loadAvatar("Male");
g_initialized = true;
}
/**
* Initialize event handling
*/
function initEvents() {}
/**
* Add gender buttons to the html
*/
function initGender() {
// var element = document.getElementById("gender");
// if (element == null) return;
//
// element.innerHTML = "";
//
// for (var g of g_config.list) {
// var button = document.createElement("button");
// button.innerText = g.id;
// button.setAttribute("onClick", `loadAvatar('${g.id}')`);
// element.appendChild(button);
// }
}
/**
* Plays the animation of an avatar
* @param {string} animName - Name of the animation this is defined in config.js
*/
export function playAnim(animName) {
var info = g_partsLoader.currAvatar.animations.find((x) => x.name == animName);
if (info == null) return;
var anim = g_scene.getAnimationGroupByName(info.id);
if (anim == null) return;
if (g_animPrev != null) g_animPrev.stop();
anim.start(true);
g_animPrev = anim;
}
/**
* Cycles through each texture and replace a specific part
* @param {string} key - The key for the material of the part to be replaced this is defined in the config.js
*/
function cycleParts(key) {
if (!g_isLoaded) return;
g_partsIdx++;
var arr = g_partsLoader.list[key];
if (arr == null) return;
if (g_partsIdx >= arr.length) {
g_partsIdx = 0;
}
var dir = arr[g_partsIdx];
this.replaceParts(key, dir);
}
/**
* Replaces the texture of a selected part material
* @param {string} key - The key for the material of the part to be replaced this is defined in the config.js
* @param {string} fileName - Name of the file with a file format suffix (FileName.png)
*/
export function replaceParts(key, fileName) {
g_partsLoader.replaceParts(key, fileName);
}
export async function updateBabylonParts(key, oraPath) {
var base64Image = await g_jsoraProject.get_by_path(oraPath).get_base64(false);
g_partsLoader.replaceParts(key, base64Image);
}
/**
* Loads the avatar and the list of materials and the collection of parts, additionally sets the animation to 'Idle' by default
* @param {string} id - ID of the avatar this is defined in config.js
*/
export function loadAvatar(id) {
g_partsLoader.loadAvatar(id, () => {
g_isLoaded = true;
// play idle by default
playAnim("Idle");
});
}
function findNodeInOra(part) {
let partPath;
let partSuffix = part.trait_type + "/" + part.value;
for (var i = 0; i < g_ArrayOfAllParts.length; i++) {
partPath = g_ArrayOfAllParts[i];
if (partPath.includes(partSuffix)) {
return partPath;
}
}
return null;
}
export function loadNFT(nft) {
nft.attributes.map( (part) => {
let partPath = findNodeInOra(part);
if (partPath) {
updateBabylonParts(part.trait_type, partPath);
}
});
g_nftLoaded = true;
}
export function renderOraCanvas(nft) {
nft.rawData.attributes.map( (part) => {
let partPath = findNodeInOra(part);
if (partPath) {
displayPart(partPath, false);
}
});
renderAvatar();
}
function createSpritesheet() {
g_scene.onBeforeRenderObservable.runCoroutineAsync(g_screenshotHandler.startScreenshotsCr(g_canvas, g_engine, g_scene, g_camera));
}