]> git.plutz.net Git - flarejs/blob - engine.js
3b363311d188b05fbc23499f431a9b31aa97c23d
[flarejs] / engine.js
1 var gamedata = {
2   // associative array for gamedata files
3   load: function(def) { return this[def] ? this[def] : this[def] = new Textfile(def); }
4 }
5 var gfx = {
6   // associative array for game graphics
7   load: function(def) {
8     if (!this[def]) {
9       this[def] = document.createElement("img");
10       this[def].setAttribute("src", def);
11     }
12     return this[def];
13   }
14 };
15 var map;
16
17 function Textfile(txtfile) {
18   // fetch and parse gamedata file into structured object
19   var lines, fetch = new XMLHttpRequest();
20   fetch.open("GET", txtfile, false);
21   fetch.send();
22
23   var line, key, value, ref = this, section;
24   for (line of fetch.responseText.split('\n')) switch(true) {
25     // section headers that always become array elements
26     case /^\[(npc|event|layer|dialog)\]$/.test(line):
27       section = line.split(/[\]\[]/)[1]; ref = {};
28       if                     (!this[section]) this[section] = [ref];
29       else if ( Array.isArray(this[section])) this[section].push(ref);
30       break;
31     // general section headers (may or may not be unique)
32     case /^\[.*\]$/.test(line):
33       section = line.split(/[\]\[]/)[1]; ref = {};
34       if                     (!this[section]) this[section] = ref;
35       else if (!Array.isArray(this[section])) this[section] = [this[section],ref];
36       else if ( Array.isArray(this[section])) this[section].push(ref);
37       break;
38     // frame definition from animation files
39     // frame=#frame,direction,srcX,srcY,width,height,dstX,dstY
40     case /^frame=[0-9]+,[0-7](,[0-9-]+){6}$/.test(line):
41       key = line.split(/[=,]/).slice(1,3);  value = line.split(/,/).slice(-6);
42       if (!ref.frame) ref.frame = [];
43       if (!ref.frame[key[0]]) ref.frame[key[0]] = [];
44       ref.frame[key[0]][key[1]] = value.map(x => parseInt(x));
45       break;
46     // order of gfx draw from engine/hero_layers.txt
47     // layer=direction,list,of,limbs,...
48     case /^layer=[0-9]+,/.test(line):
49       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
50       if (!ref.layer) ref.layer = []; ref.layer[key] = value;
51       break;
52     // empty data= line starting map data in map files
53     case /^data=$/.test(line):
54       ref.data = [];
55       break;
56     // map data array
57     case /^[0-9,]+,$/.test(line):
58       value = line.split(/,/).slice(0,-1);
59       ref.data = ref.data.concat(value);
60       break;
61     // map data array (last line)
62     case /^[0-9,]+$/.test(line):
63       value = line.split(/,/);
64       ref.data = ref.data.concat(value);
65       ref.data = ref.data.map(x => parseInt(x));
66       break;
67     // tile description from tiledef file
68     // tile=#tile,srcX,srcY,width,height,dstX,dstY
69     case /^tile=[0-9]+,/.test(line):
70       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
71       if (!ref.tile) ref.tile = []; ref.tile[key] = value.map(x => parseInt(x));
72       break;
73     // animated tile from tiledef file
74     // animation=#tile;(srcX,srcY,duration;)...
75     case /^animation=[0-9]+;.*;$/.test(line):
76       key = line.split(/[=;]/)[1];  value = line.split(/;/).slice(1,-1);
77       value = value.map(x => x.split(/,/));
78       value.forEach(x => x[2] = parseInt(x[2]));
79       if (!ref.animation) ref.animation = []; ref.animation[key] = value;
80       break;
81     // frame duration from animation file (im millisec)
82     case /^duration=[0-9]+ms$/.test(line):
83       ref.duration = line.split(/=|ms$/)[1];
84       break;
85     // frame duration from animation file (in whole seconds)
86     case /^duration=[0-9]+s$/.test(line):
87       ref.duration = line.split(/=|s$/)[1] * 1000;
88       break;
89     // mapmod events
90     case /^mapmod=.*$/.test(line):
91       ref.mapmod = line.split(/[=]/)[1].split(/[;]/).map( m => m.split(/[,]/).map( n => n * 1 ? n * 1 : n) );
92       break;
93     // general array type, will not be aggregated
94     case /^[^#].*=.*,.*$/.test(line):
95       key = line.split(/[=]/)[0]; value = line.split(/[=]/)[1].split(/,/);
96       ref[key] = value.map(m => m * 1 ? m * 1 : m);  // parse numerics
97       break;
98     // general key=value
99     case /^[^#].*=.+$/.test(line):
100       key = line.split(/[=]/)[0];
101       value = line.split(/=/).slice(1).join("=");
102       value = value * 1 ? value * 1 : value;  // try to parse as numeric
103       if                     (!ref[key]) ref[key] = value;
104       else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value];
105       else if ( Array.isArray(ref[key])) ref[key].push(value);
106       break;
107   }
108 }
109
110 function Map(textdef) {
111   // object for map operations (drawing coorinate transformation, etc.)
112   this.info = gamedata.load(textdef);
113   const tileset = gamedata.load(this.info.header.tileset);
114   const frametime = performance.now();
115   gfx.load(tileset.img);
116
117   const  h = this.info.header.height,      w = this.info.header.width;
118   const th = this.info.header.tileheight, tw = this.info.header.tilewidth;
119   var posx = canvas.canvas.width / 2, posy = canvas.canvas.height / 2 - h * th/2;
120
121   canvas.fillStyle = "rgba("+this.info.header.background_color+")";
122
123   // precalculated tile positions
124   // assign x/y coordinates to each tile index
125   // looks dumb but is faster than on the fly isometric calculations
126   const dx = [], dy = [];
127   for ( let y = 0; y < h; y++ ) for ( let x = 0; x < w; x++ ) {
128     dx[y * w + x] = (w + x - y) * tw / 2;
129     dy[y * w + x] = (x + y) * th / 2;
130   }
131
132   const npcs = [];
133   if (this.info.npc) for (let def of this.info.npc) {
134     let loc = def.location[1] * w + def.location[0];
135     npcs[loc] = new Npc(def.filename)
136     npcs[loc].place(dx[loc], dy[loc]);
137     this.info.layer.find(l => l.type == "collision").data[loc] = 1;
138   }
139
140   this.events = [];
141   for (let ev of this.info.event) {
142     for (let x = ev.location[0]; x < ev.location[0] + ev.location[2]; x++)
143       for (let y = ev.location[1]; y < ev.location[1] + ev.location[3]; y++) {
144         let loc = y * w + x;
145         if (!this.events[loc]) this.events[loc] = [];
146         this.events[loc].push(ev);
147       }
148   }
149
150   // tile index for pixel position on map
151   this.tileAt = function(x, y) {
152     var r = (y + th / 2) / th; var c = (x - w * tw /2) / tw;
153     var nx = r + c |0; var ny = r - c |0;
154     return ny * w + nx;
155   }
156   this.tileX = (x,y) => this.tileAt(x,y) % w;
157   this.tileY = (x,y) => this.tileAt(x,y) / w |0;
158
159   // vice versa the pixel coordinates of a given map tile
160   this.positionOf = (tl, ty = -1) => (~ty) ? [dx[ty * w + tl], dy[ty * w + tl]] : [ dx[tl], dy[tl] ];
161   this.xOf = (tl, ty = -1) => (~ty) ? dx[ty * w + tl] : dx[tl];
162   this.yOf = (tl, ty = -1) => (~ty) ? dy[ty * w + tl] : dy[tl]; 
163
164   // map pixel for given screen pixel
165   this.mapX = x => x - posx;
166   this.mapY = y => y - posy;
167
168   // center map to pixel position (by setting drawing offsets)
169   this.center = function(x, y) {
170     posx = canvas.canvas.width  / 2 - x;
171     posy = canvas.canvas.height / 2 - y;
172     return this;
173   }
174
175   // draw the entire map, including all mobs
176   // mobs in an array of all heros, enemies, loot, npcs, etc.
177   this.draw = function(mobs) {
178     const bg = this.info.layer.find(l => l.type == "background").data;
179     const ob = this.info.layer.find(l => l.type == "object").data;
180     var i, mm = [];
181
182     // mobs only have x/y pixel positions,
183     // to draw them in order with map tiles we set up
184     // an array with current tile positions of mobs
185     mobs.forEach(m => {
186       let i = this.tileAt(m.position[0], m.position[1]);
187       mm[i] = mobs.filter(m => i == this.tileAt(m.position[0], m.position[1]));
188     });
189     canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height);
190
191     // draw background layer first
192     for ( i = 0; i < h * w; i++ ) draw_tile(bg[i], posx + dx[i], posy + dy[i]);
193
194     // draw object layer and mobs
195     for ( i = 0; i < h * w; i++ ) {
196       draw_tile(ob[i], posx + dx[i], posy + dy[i]);
197       if (mm[i]) mm[i].forEach(m => m.draw(posx + m.position[0], posy + m.position[1]));
198       if (npcs[i]) npcs[i].draw(posx + dx[i], posy + dy[i]);
199     }
200   }
201
202   // draw a single map tile at screen position x/y
203   // tile may be animated, if so defined in tiledef
204   function draw_tile(tile, x, y) {
205     const t = tileset.tile[tile];
206     const f = tileset.animation[tile];
207     x = x |0; y = y |0;
208
209     if (t && f) {
210       frame = ((performance.now() - frametime) / f[0][2] |0) % f.length;
211       if ( x + t[2] - t[4] > 0 && y + t[3] - t[5] > 0 && x - t[4] < canvas.canvas.width && y - t[5] < canvas.canvas.height)
212       canvas.drawImage(gfx[tileset.img], f[frame][0], f[frame][1], t[2], t[3],
213                                                x - t[4], y - t[5], t[2], t[3]);
214     } else if (t) {
215       if ( x + t[2] - t[4] > 0 && y + t[3] - t[5] > 0 && x - t[4] < canvas.canvas.width && y - t[5] < canvas.canvas.height)
216       canvas.drawImage(gfx[tileset.img], t[0], t[1], t[2], t[3],
217                                  x - t[4], y - t[5], t[2], t[3]);
218     }
219   }
220 }
221
222 function Mob(textdef) {
223   // any mobile object, mostly for gfx representation
224   // may be hero, enemy, loot, npc, etc.
225   this.position = [0, 0];
226   const info = gamedata.load(textdef);
227   var direction = 0;
228   var animation = "stance";
229   var previous_animation = "";
230   var frametime = performance.now();
231   gfx.load(info.image)
232
233   // some simplified npc files do not define animation frames
234   // render size and offset are given instead, and we
235   // assume, that we can just loop horizontally over the image
236   if (!info[animation].frame){
237     info[animation].frame = [];
238     let rs = info.render_size, ro = info.render_offset;
239
240     for (let i = 0; i < info[animation].frames; i++ )
241       info[animation].frame[i] = [[ i * rs[0], 0, rs[0], rs[1], ro[0], ro[1]]];
242   }
243
244   // place mob on x/y pixel coordinates
245   // e.g. when spawning, walking, etc.
246   this.place = function(x, y) {
247     this.position[0] = x, this.position[1] = y;
248     return this;
249   }
250
251   // change facing direction of mob
252   this.direct = function(d) { direction = d % 8; return this; }
253
254   // set animation cycle for drawing
255   // play_once animations will automatically fall back
256   // to previous loop after completion
257   this.animate = function(a) {
258     if ( a != animation ) {
259       previous_animation = animation;
260       animation = a;
261       frametime = performance.now();
262     }
263     return this;
264   }
265
266   // draw this mob to screen position x/y
267   this.draw = function(x, y){
268     var f, a = info[animation];
269     var f, frame = ( performance.now() - frametime ) * a.frames / a.duration | 0;
270
271     // determine current animation frame
272     switch(a.type){
273       case "looped":
274         frame = frame % a.frames;
275         break;
276       case "play_once":
277         if ( frame >= a.frames ){
278           animation = previous_animation;
279           previous_animation = "";
280           frametime = performance.now();
281           a = info[animation];
282           frame = 0;
283         }
284         break;
285       case "back_forth":
286         frame = frame % (a.frames * 2 - 2);
287         if ( frame >= a.frames ){
288          frame = a.frames - frame % a.frames - 1;
289         }
290         break;
291       default: break;
292     }
293     f = a.frame[frame][direction];
294
295     canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3],
296                      x - f[4], y - f[5],
297                      f[2], f[3]);
298   }
299
300   // shortcut functions for specific animations
301   this.block  = () => this.animate("block" );
302   this.cast   = () => this.animate("cast"  );
303   this.die    = () => this.animate("die"   );
304   this.hit    = () => this.animate("hit"   );
305   this.run    = () => this.animate("run"   );
306   this.shoot  = () => this.animate("shoot" );
307   this.stance = () => this.animate("stance");
308   this.swing  = () => this.animate("swing" );
309 }
310
311 function Npc(textdef){
312   this.info = gamedata.load(textdef);
313   const avatar = new Mob(this.info.gfx);
314
315   this.place = function(x, y) {
316     avatar.place(x,y);
317     return this;
318   }
319
320   this.draw = function(x, y) {
321     avatar.draw(x, y);
322     return this;
323   }
324 }
325
326 function Hero(gender = "female", hair = "short"){
327   // Object for player character
328   // unique in single player
329   this.position = [0,0];
330   this.stats = gamedata.load("/engine/stats.txt");
331   const layers = gamedata.load("/engine/hero_layers.txt");
332   var direction = 0, animation = "stance";
333   hair = (gender == "female")?"long":hair;
334
335   // hero consists of multiple mobs, one for each clothing/item overlay
336   var limbs = {
337     head : new Mob("/animations/avatar/"+gender+"/head_"+hair+".txt"),
338     chest: new Mob("/animations/avatar/"+gender+"/cloth_shirt.txt"),
339     hands: new Mob("/animations/avatar/"+gender+"/default_hands.txt"),
340     legs : new Mob("/animations/avatar/"+gender+"/cloth_pants.txt"),
341     feet : new Mob("/animations/avatar/"+gender+"/default_feet.txt"),
342     main : null, // main hand, e.g. melee weapon, magic weapon
343     off  : null  // off hand, e.g. shield, ranged weapon
344   }
345
346   // "dress" the player, i.e. assign clothing/item to limb
347   this.dress = function(limb, item) {
348     limbs[limb] = new Mob("/animations/avatar/"+gender+"/"+item+".txt")
349     limbs[limb].place(this.position[0], this.position[1]).direct(direction);
350     this.animate(animation);
351     return this;
352   }
353
354   // // Wrapper functions for Mob class // //
355
356   // place all mobs beloning to hero (when spawning, walking, teleporting, etc.)
357   this.place   = function(x,y) {
358     this.position[0] = x, this.position[1] = y;
359     for (var limb in limbs) limbs[limb] && limbs[limb].place(x,y);
360     return this;
361   }
362   // change facing direction of hero (i.e. of all mobs)
363   this.direct  = function(d)   {
364     direction = d;
365     for (var limb in limbs) limbs[limb] && limbs[limb].direct(d);
366     return this;
367   }
368   // start animation cycle
369   this.animate = function(anim){
370     animation = anim;
371     for (var limb in limbs) limbs[limb] && limbs[limb].animate(anim);
372     return this;
373   }
374   this.draw    = function(x, y){
375     layers.layer[direction].forEach(limb => limbs[limb] && limbs[limb].draw(x, y));
376     return this;
377   }
378
379   // shortcuts for animation
380   this.block  = () => this.animate("block" );
381   this.cast   = () => this.animate("cast"  );
382   this.die    = () => this.animate("die"   );
383   this.hit    = () => this.animate("hit"   );
384   this.run    = () => this.animate("run"   );
385   this.shoot  = () => this.animate("shoot" );
386   this.stance = () => this.animate("stance");
387   this.swing  = () => this.animate("swing" );
388 }
389
390 function Controls(hero){
391   // processes keyboard / touch / mouse
392   // causes according player actions
393   // single player only, conrol will be assigned to server in multi player
394   var kbdmap = {
395        up: 87,    altup: 38,
396      down: 83,  altdown: 40,
397      left: 65,  altleft: 37,
398     right: 68, altright: 39,
399   }
400   var keys = [], click = [];
401
402   window.addEventListener("keydown", e => keys[e.keyCode] = true );
403   window.addEventListener("keyup"  , e => keys[e.keyCode] = false);
404   window.addEventListener("click", m => click = [ map.mapX(m.clientX), map.mapY(m.clientY) ] );
405   setInterval(() => input(), 33.33)
406
407   // cause player to walk, processes blocked terrain and player speed
408   // x/y are factors of speed and direction
409   //     i.e. +/-1 for diagonal movement
410   //     and  +/-1.4 for horizontal/vertical movement
411   function translate(x, y){
412     var sx = map.info.header.tilewidth  * hero.stats.speed / 33.33;
413     var sy = map.info.header.tileheight * hero.stats.speed / 33.33;
414     var dx = x * sx, hx = hero.position[0];
415     var dy = y * sy, hy = hero.position[1];
416     var f = 2.1;
417     const col = map.info.layer.find(l => l.type == "collision").data;
418
419     if (col[map.tileAt(hx + dx, hy + dy)] == 0 )
420             hero.place(hx + dx, hy + dy);
421     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy + sy / 1.5)] == 0 )
422                              hero.place(hx + dx / f, hy + sy / 1.5);
423     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy - sy / 1.5)] == 0 )
424                              hero.place(hx + dx / f, hy - sy / 1.5);
425     else if ( dx == 0 && col[map.tileAt(hx + sx / 1.5, hy + dy / f)] == 0 )
426                              hero.place(hx + sx / 1.5, hy + dy / f);
427     else if ( dx == 0 && col[map.tileAt(hx - sx / 1.5, hy + dy / f)] == 0 )
428                              hero.place(hx - sx / 1.5, hy + dy / f);
429     else player.stance();
430
431     map.center(hero.position[0], hero.position[1]);
432     events(hero.position[0], hero.position[1]);
433   }
434
435   // Process on_trigger events at pixel position x/y
436   function events(x, y) {
437     const i = map.tileAt(x,y); let ev, e, n;
438     if (map.events[i]) {
439       // intramap (teleporters)
440       if ( ev = map.events[i].find(e => (e.activate == "on_trigger" && e.intramap)) ){
441         ev = ev.intramap;
442         hero.place( map.xOf(ev[0], ev[1]), map.yOf(ev[0], ev[1]) );
443         map.center( map.xOf(ev[0], ev[1]), map.yOf(ev[0], ev[1]) );
444       }
445       // mapmod (e.g. opening doors, activating platforms, changing terrain, ...)
446       for (ev of map.events[i].filter(e => (e.activate == "on_trigger" && e.mapmod)) ){
447         for (ev of ev.mapmod)
448           map.info.layer.find(l => l.type == ev[0]).data[ev[2] * map.info.header.width + ev[1]] = ev[3];
449       }
450       // intermap (must be last because loading new map breaks further event search)
451       if ( ev = map.events[i].find(e => (e.activate == "on_trigger" && e.intermap)) ){
452         ev = ev.intermap;
453         map = new Map(ev[0]);
454         hero.place( map.xOf(ev[1], ev[2]), map.yOf(ev[1], ev[2]) );
455         map.center( map.xOf(ev[1], ev[2]), map.yOf(ev[1], ev[2]) );
456       }
457     }
458   }
459
460   // process input and decide on according action
461   function input(){
462     // facing directions, indexed by OR of key press combinations
463     const dir   = [ -1, 0, 4, -1, 2, 1, 3, 2, 6, 7, 5, 6, -1, 0, 4, -1 ];
464     // translation speed and direction, indexed by facing direction of movement
465     const trans = [ [-1.4,0], [-1,-1], [0,-1.4], [1,-1], [1.4,0], [1,1], [0,1.4], [-1,1] ];
466     var k = 0;
467
468     // OR of direction key presses
469     k += (keys[kbdmap.left]  || keys[kbdmap.altleft])  ? 1 : 0;
470     k += (keys[kbdmap.right] || keys[kbdmap.altright]) ? 2 : 0;
471     k += (keys[kbdmap.up]    || keys[kbdmap.altup])    ? 4 : 0;
472     k += (keys[kbdmap.down]  || keys[kbdmap.altdown])  ? 8 : 0;
473
474     if (~dir[k]) {
475       hero.direct(dir[k]).run();
476       translate(trans[dir[k]][0], trans[dir[k]][1]);
477     } else hero.stance();
478
479     if (click[0]) {
480         let hx = map.tileX(hero.position[0], hero.position[1]);
481         let hy = map.tileY(hero.position[0], hero.position[1]);
482         let cx = map.tileX(click[0], click[1]);
483         let cy = map.tileY(click[0], click[1]);
484         if (   (cx == hx - 1 || cx == hx + 1 || cx == hx)
485             && (cy == hy - 1 || cy == hy + 1 || cy == hy))
486         events(click[0], click[1]);
487       click = [];
488     }
489   }
490 }
491
492 document.querySelector("body").setAttribute("style", "margin: 0; padding: 0;");
493 canvas = document.createElement("canvas").getContext("2d");
494 canvas.canvas.setAttribute("style", "display: block; border: 0; margin: 0; padding: 0;");
495 document.querySelector("body").appendChild(canvas.canvas);
496
497 canvas.canvas.width  = window.innerWidth;
498 canvas.canvas.height = window.innerHeight;
499 window.addEventListener("resize", function(){
500   canvas.canvas.width  = window.innerWidth;
501   canvas.canvas.height = window.innerHeight;
502 });
503
504 // player = new Mob("animations/enemies/zombie.txt"); player.stats = { speed: 3 };
505 player = new Hero();
506 map = new Map("/maps/perdition_harbor.txt");
507 player.place(map.xOf(map.info.header.hero_pos[0], map.info.header.hero_pos[1]),
508              map.yOf(map.info.header.hero_pos[0], map.info.header.hero_pos[1]));
509 player.direct(6).stance();
510
511 map.center(player.position[0], player.position[1]);
512 c = new Controls(player);
513
514 setInterval (() => map.draw([player]), 33.33 );