Init undefined variables in function definitions

This commit is contained in:
John Alanbrook 2024-04-07 13:16:54 -05:00
parent 33d450189c
commit 53f2addeec
18 changed files with 106 additions and 212 deletions

View file

@ -41,8 +41,7 @@ var ai = {
]);
},
wait(secs) {
secs ??= 1;
wait(secs = 1) {
var accum = 0;
return function(dt) {
accum += dt;

View file

@ -135,11 +135,10 @@ time.timecode = function(t, fps = 24)
time.monthdays = [31,28,31,30,31,30,31,31,30,31,30,31];
time.zones = {};
time.zones['-12'] = 'IDLW';
time.record = function(num, zone)
time.record = function(num, zone = this.computer_zone())
{
if (typeof num === 'object') return num;
else if (typeof num === 'number') {
zone ??= this.computer_zone();
var monthdays = this.monthdays.slice();
var rec = {
second: 0,
@ -261,9 +260,8 @@ time.number = function(rec)
time.fmt = "vB mB d h:nn:ss TZz a y c";
/* If num is a number, converts to a rec first. */
time.text = function(num, fmt, zone)
time.text = function(num, fmt = this.fmt, zone)
{
fmt ??= this.fmt;
var rec = num;
if (typeof rec === 'number')
@ -325,9 +323,8 @@ Object.methods = function(o)
}
Object.methods.doc = "Retun an array of all functions an object has access to.";
Object.dig = function(obj, path, def)
Object.dig = function(obj, path, def = {})
{
def ??= {};
var pp = path.split('.');
for (var i = 0; i < pp.length-1; i++) {
obj = obj[pp[i]] = obj[pp[i]] || {};
@ -336,17 +333,6 @@ Object.dig = function(obj, path, def)
return def;
}
Object.samenewkeys = function(a,b)
{
b ??= a.__proto__;
var ret = {};
ret.same = [];
ret.unique = [];
Object.keys(a).forEach(key => (key in b) ? ret.same.push(key) : ret.unique.push(key));
return ret;
}
Object.samenewkeys.doc = "Return an object listing which keys are the same and unique on a compared to b.";
Object.rkeys = function(o)
{
var keys = [];
@ -821,10 +807,7 @@ Object.defineProperty(String.prototype, 'splice', {
});
Object.defineProperty(String.prototype, 'rm', {
value: function(index, endidx) {
endidx ??= index+1;
return this.slice(0,index) + this.slice(endidx);
}
value: function(index, endidx = index+1) { return this.slice(0,index) + this.slice(endidx); }
});
Object.defineProperty(String.prototype, 'updir', {

View file

@ -32,4 +32,13 @@ this.world2view = function(pos) {
this.screenright = function() { return this.view2world(window.size).x; }
this.screenleft = function() { return this.view2world([0,0]).x; }
this.zoom = 1;
var zoom = 1;
Object.mixin(self, {
set zoom(x) {
zoom = x;
if (zoom <= 0.1) zoom = 0.1;
},
get zoom() { return zoom; }
}
);

View file

@ -173,9 +173,8 @@ ColorMap.Viridis = ColorMap.makemap({
Color.normalize(ColorMap);
ColorMap.sample = function(t, map)
ColorMap.sample = function(t, map = this)
{
map ??= this;
if (t < 0) return map[0];
if (t > 1) return map[1];

View file

@ -90,7 +90,7 @@ Object.mixin(os.sprite(true), {
]),
anim:{},
playing: 0,
play(str) {
play(str = 0) {
this.del_anim?.();
var self = this;
var stop;
@ -100,7 +100,6 @@ Object.mixin(os.sprite(true), {
advance = undefined;
stop?.();
}
str ??= 0;
var playing = self.anim[str];
if (!playing) return;
var f = 0;

View file

@ -1,6 +1,5 @@
debug.fn_break = function(fn,obj) {
debug.fn_break = function(fn,obj = globalThis) {
if (typeof fn !== 'function') return;
obj ??= globalThis;
var newfn = function() {
console.log("broke");
@ -47,11 +46,10 @@ debug.draw = function() {
"EDIT", [0, 0], 1);
}
function assert(op, str)
function assert(op, str = `assertion failed [value '${op}']`)
{
str ??= `assertion failed [value '${op}']`;
if (!op) {
console.error(`Assertion failed: ${str}`);
console.error(str);
os.quit();
}
}
@ -64,9 +62,7 @@ var Gizmos = {
},
};
profile.cpu = function(fn, times, q) {
times ??= 1;
q ??= "unnamed";
profile.cpu = function(fn, times = 1, q = "unnamed") {
var start = profile.now();
for (var i = 0; i < times; i++)
fn();

View file

@ -338,10 +338,9 @@ var editor = {
}
},
draw_objects_names(obj,root,depth){
draw_objects_names(obj,root,depth = 0){
if (!obj) return;
if (!obj.objects) return;
depth ??= 0;
root = root ? root + "." : root;
Object.entries(obj.objects).forEach(function(x) {
var p = root + x[0];
@ -450,7 +449,7 @@ var editor = {
render.text("$$$$$$", [0,ypos],1,editor.color_depths[depth]);
this.selectlist.forEach(function(x) {
render.text(x.urstr(), x.screenpos().add([0, 32]), 1, Color.editor.ur);
render.text(x.worldpos().map(function(x) { return Math.round(x); }), x.screenpos(), 1, Color.white);
render.text(x.pos.map(function(x) { return Math.round(x); }), x.screenpos(), 1, Color.white);
render.cross(x.screenpos(), 10, Color.blue);
});
@ -531,7 +530,7 @@ var editor = {
var mur = ur[urstr];
if (!mur) return;
var obj = editor.edit_level.spawn(mur);
obj.set_worldpos(input.mouse.worldpos());
obj.set_pos(input.mouse.worldpos());
this.selectlist = [obj];
},
@ -612,7 +611,7 @@ var editor = {
editor.new_object = function()
{
var obj = editor.edit_level.spawn();
obj.set_worldpos(input.mouse.worldpos());
obj.set_pos(input.mouse.worldpos());
this.selectlist = [obj];
return obj;
}
@ -804,7 +803,7 @@ editor.inputs['C-r'].doc = "Negate the selected's angle.";
editor.inputs.r = function() {
if (editor.sel_comp && 'angle' in editor.sel_comp) {
var relpos = input.mouse.worldpos().sub(editor.sel_comp.gameobject.worldpos());
var relpos = input.mouse.worldpos().sub(editor.sel_comp.gameobject.pos);
editor.startoffset = Math.atan2(relpos.y, relpos.x);
editor.startrot = editor.sel_comp.angle;

View file

@ -54,9 +54,8 @@ Resources.replstrs = function(path)
}
globalThis.json = {};
json.encode = function(value, replacer, space, whitelist)
json.encode = function(value, replacer, space = 1)
{
space ??= 1;
return JSON.stringify(value, replacer, space);
}
@ -182,11 +181,10 @@ console.doc = {
globalThis.global = globalThis;
function use(file, env, script)
function use(file, env = {}, script)
{
file = Resources.find_script(file);
var st = profile.now();
env ??= {};
if (use.cache[file]) {
var ret = use.cache[file].call(env);
@ -313,10 +311,7 @@ var eachobj = function(obj,fn)
eachobj(obj.objects[o],fn);
}
game.all_objects = function(fn, startobj) {
startobj ??= world;
eachobj(startobj,fn);
};
game.all_objects = function(fn, startobj = world) { eachobj(startobj,fn); };
game.tags = {};
game.tag_add = function(tag, obj) {

View file

@ -10,54 +10,6 @@ function obj_unique_name(name, obj) {
return n;
}
var gameobject_impl = {
get pos() {
assert(this.master, `Entity ${this.toString()} has no master.`);
return this.master.world2this(this.worldpos());
},
set pos(x) {
assert(this.master, `Entity ${this.toString()} has no master.`);
this.set_worldpos(this.master.this2world(x));
},
get angle() {
assert(this.master, `No master set on ${this.toString()}`);
return this.worldangle() - this.master.worldangle();
},
set angle(x) {
var diff = x - this.angle;
this.objects.forEach(function(x) {
x.rotate(diff);
x.pos = Vector.rotate(x.pos, diff);
});
this.sworldangle(x - this.master.worldangle());
},
get scale() {
assert(this.master, `No master set on ${this.toString()}`);
var pscale = [1, 1, 1];
return this.gscale().map((x, i) => x / (this.master.gscale()[i] * pscale[i]));
},
set scale(x) {
if (typeof x === 'number')
x = [x, x];
var pct = this.scale.map((s, i) => x[i] / s);
this.grow(pct);
/* TRANSLATE ALL SUB OBJECTS */
this.objects.forEach(obj => {
obj.grow(pct);
obj.pos = obj.pos.map((x, i) => x * pct[i]);
});
},
};
var gameobject = {
get_comp_by_name(name) {
var comps = [];
@ -103,35 +55,23 @@ var gameobject = {
pin(to) {
var p = joint.pin(this,to);
},
slide(to, a, b, min, max) {
a ??= [0, 0];
b ??= [0, 0];
min ??= 0;
max ??= 50;
slide(to, a = [0,0], b = [0,0], min = 0, max = 50) {
var p = joint.slide(this, to, a, b, min, max);
p.max_force = 500;
p.break();
},
pivot(to, piv) {
piv ??= this.worldpos();
pivot(to, piv = this.pos) {
var p = joint.pivot(this, to, piv);
},
/* groove is on to, from local points a and b, anchored to this at local anchor */
groove(to, a, b, anchor) {
anchor ??= [0, 0];
groove(to, a, b, anchor = [0,0]) {
var p = joint.groove(to, this, a, b, anchor);
},
damped_spring(to, length, stiffness, damping) {
length ??= Vector.length(this.worldpos(), to.worldpos());
stiffness ??= 1;
damping ??= 1;
damped_spring(to, length = Vector.length(this.pos,to.pos), stiffness = 1, damping = 1) {
var dc = 2 * Math.sqrt(stiffness * this.mass);
var p = joint.damped_spring(this, to, [0, 0], [0, 0], stiffness, damping * dc);
},
damped_rotary_spring(to, angle, stiffness, damping) {
angle ??= 0;
stiffness ??= 1;
damping ??= 1;
damped_rotary_spring(to, angle = 0, stiffness = 1, damping = 1) {
/* calculate actual damping value from the damping ratio */
/* damping = 1 is critical */
var dc = 2 * Math.sqrt(stiffness * this.get_moi()); /* critical damping number */
@ -145,9 +85,7 @@ var gameobject = {
var phase = this.angle - to.angle;
var p = joint.ratchet(this, to, phase, Math.turn2rad(ratch));
},
gear(to, ratio) {
phase ??= 1;
ratio ??= 1;
gear(to, ratio = 1, phase = 0) {
var phase = this.angle - to.angle;
var p = joint.gear(this, to, phase, ratio);
},
@ -202,37 +140,57 @@ var gameobject = {
return stop;
},
tween(prop, values, def) {
var t = Tween.make(this, prop, values, def);
t.play();
var k = function() { t.pause(); }
this.timers.push(k);
return k;
},
cry(file) {
return audio.cry(file);
},
gscale() { return this.scale; },
sgscale(x) {
if (typeof x === 'number')
x = [x, x];
physics.sgscale(this, x)
},
worldpos() { return this.pos; },
set_worldpos(x) {
var poses = this.objects.map(x => x.pos);
set_pos(x, relative = world) {
var move = x.sub(this.pos);
this.pos = x;
this.objects.forEach((o, i) => o.set_worldpos(this.this2world(poses[i])));
this.objects.forEach(x => x.move(move));
},
screenpos() { return game.camera.world2view(this.worldpos()); },
worldangle() { return this.angle; },
sworldangle(x) { this.angle = x; },
set_angle(x, relative = world) {
var diff = x - this.angle;
this.angle = x;
this.objects.forEach(obj => {
obj.rotate(diff);
obj.set_pos(Vector.rotate(obj.pos, diff));
});
},
set_scale(x, relative = world) {
if (typeof x === 'number') x = [x,x,x];
var pct = this.scale.map((s,i) => x[i]/s);
this.scale = x;
this.objects.forEach(obj => {
obj.grow(pct);
obj.set_pos(obj.pos.map((x,i) => x*pct[i]));
});
},
get_pos(relative = world) {
if (relative === world) return this.pos;
return this.pos.sub(relative.pos);
},
get_angle(relative = world) {
if (relative === world) return this.angle;
return this.master.angle - this.angle;
},
get_scale(relative = world) {
if (relative === world) return this.scale;
var masterscale = this.master.scale;
return this.scale.map((x,i) => x/masterscale[i]);
},
/* Moving, rotating, scaling functions, world relative */
move(vec) { this.set_pos(this.pos.add(vec)); },
rotate(x) { this.set_angle(this.angle + x); },
grow(vec) { this.set_scale(this.scale.map((x, i) => x * vec[i])); },
screenpos() { return game.camera.world2view(this.pos); },
get_ur() { return this.ur; },
@ -290,8 +248,8 @@ var gameobject = {
if (sim.playing())
if (typeof ent.start === 'function') ent.start();
Object.hide(ent, 'ur', 'components', 'objects', 'timers', 'guid', 'master');
Object.hide(ent, 'ur', 'components', 'objects', 'timers', 'guid', 'master');
ent._ed = {
selectable: true,
dirty: false,
@ -336,8 +294,7 @@ var gameobject = {
this.master = parent;
function unique_name(list, name) {
name ??= "new_object";
function unique_name(list, name = "new_object") {
var str = name.replaceAll('.', '_');
var n = 1;
var t = str;
@ -388,11 +345,6 @@ var gameobject = {
return bb.t - bb.b;
},
/* Moving, rotating, scaling functions, world relative */
move(vec) { this.set_worldpos(this.worldpos().add(vec)); },
rotate(x) { this.sworldangle(this.worldangle() + x); },
grow(vec) { this.sgscale(this.gscale().map((x, i) => x * vec[i])); },
/* Make a unique object the same as its prototype */
revert() {
var jobj = this.json_obj();
@ -574,9 +526,8 @@ var gameobject = {
return this.objects[newname];
},
add_component(comp, data, name) {
add_component(comp, data, name = comp.toString()) {
if (typeof comp.make !== 'function') return;
name ??= comp.toString();
name = obj_unique_name(name, this);
this[name] = comp.make(this);
this[name].comp = comp.toString();
@ -613,7 +564,7 @@ gameobject.doc = {
mass: `The higher the mass of the object, the less forces will affect it.`,
phys: `Set to 0, 1, or 2, representing dynamic, kinematic, and static.`,
worldpos: `Function returns the world position of the object.`,
set_worldpos: `Function to set the position of the object in world coordinates.`,
set_pos: `Function to set the position of the object in world coordinates.`,
worldangle: `Function to get the angle of the entity in the world.`,
rotate: `Function to rotate this object by x degrees.`,
move: 'Move an object by x,y,z. If the first parameter is an array, uses up to the first three array values.',

View file

@ -2,11 +2,9 @@ var shape = {};
shape.sphere = {};
shape.circle = {};
shape.sphere.volume = function(r) { return Math.pi*r*r*r*4/3; };
shape.sphere.random = function(r,theta,phi)
shape.sphere.random = function(r,theta = [0,1], phi = [-0.5,0.5])
{
if (typeof r === 'number') r = [r,r];
theta ??= [0,1];
phi ??= [-0.5,0.5];
if (typeof theta === 'number') theta = [theta,theta];
if (typeof phi === 'number') phi = [phi,phi];
@ -44,8 +42,7 @@ shape.ngon = function(radius, n) {
return shape.arc(radius,360,n);
};
shape.arc = function(radius, angle, n, start) {
start ??= 0;
shape.arc = function(radius, angle, n, start = 0) {
start = Math.deg2rad(start);
if (angle >= 360)
angle = 360;

View file

@ -118,9 +118,7 @@ var Mum = {
}
Mum.text = Mum.extend({
draw(cursor, cnt) {
cursor ??= [0,0];
cnt ??= Mum;
draw(cursor = [0,0], cnt = Mum) {
if (this.hide) return;
if (this.selectable) gui.controls.check_bb(this);
this.caret ??= -1;
@ -171,9 +169,7 @@ Mum.window = Mum.extend({
this.wh = [this.width, this.height];
this.bb = bbox.fromcwh([0,0], this.wh);
},
draw(cursor, cnt) {
cursor ??= [0,0];
cnt ??= Mum;
draw(cursor = [0,0], cnt = Mum) {
var p = cursor.sub(this.wh.scale(this.anchor)).add(this.padding);
render.window(p,this.wh, this.color);
this.bb = bbox.blwh(p, this.wh);
@ -220,9 +216,7 @@ Mum.image = Mum.extend({
});
Mum.column = Mum.extend({
draw(cursor, cnt) {
cursor ??= [0,0];
cnt ??= Mum;
draw(cursor = [0,0], cnt = Mum) {
if (this.hide) return;
cursor = cursor.add(this.offset);
this.max_width = cnt.width;

View file

@ -141,8 +141,7 @@ input.mouse.mode = function(m) {
input.mouse_cursor(m);
};
input.mouse.set_custom_cursor = function(img, mode) {
mode ??= input.mouse.cursor.default;
input.mouse.set_custom_cursor = function(img, mode = input.mouse.cursor.default) {
if (!img)
delete input.mouse.custom[mode];
else {

View file

@ -10,10 +10,7 @@ var HIT = {
*/
var pq = physics.pos_query;
physics.pos_query = function(pos,give) {
give ??= 25;
return pq(pos,give);
}
physics.pos_query = function(pos,give = 25) { return pq(pos,give); }
physics.box_point_query = function(box,points) {
if (!box || !points) return [];

View file

@ -41,20 +41,16 @@ render.device = {
render.device.doc = `Device resolutions given as [x,y,inches diagonal].`;
/* All draw in screen space */
render.point = function(pos,size,color) {
color ??= Color.blue;
render.point = function(pos,size,color = Color.blue) {
render.circle(pos,size,size,color);
};
var tmpline = render.line;
render.line = function(points, color, thickness) {
thickness ??= 1;
color ??= Color.white;
render.line = function(points, color = Color.white, thickness = 1) {
tmpline(points,color,thickness);
};
render.cross = function(pos, size, color) {
color ??= Color.red;
render.cross = function(pos, size, color = Color.red) {
var a = [
pos.add([0,size]),
pos.add([0,-size])
@ -68,11 +64,7 @@ render.cross = function(pos, size, color) {
render.line(b,color);
};
render.arrow = function(start, end, color, wingspan, wingangle) {
color ??= Color.red;
wingspan ??= 4;
wingangle ??=10;
render.arrow = function(start, end, color = Color.red, wingspan = 4, wingangle = 10) {
var dir = end.sub(start).normalized();
var wing1 = [
Vector.rotate(dir, wingangle).scale(wingspan).add(end),
@ -92,8 +84,7 @@ render.coordinate = function(pos, size, color) {
render.point(pos, 2, color);
}
render.boundingbox = function(bb, color) {
color ??= Color.white;
render.boundingbox = function(bb, color = Color.white) {
render.poly(bbox.topoints(bb), color);
}
@ -102,8 +93,7 @@ render.rectangle = function(lowerleft, upperright, color) {
render.poly(points, color);
};
render.box = function(pos, wh, color) {
color ??= Color.white;
render.box = function(pos, wh, color = Color.white) {
var lower = pos.sub(wh.scale(0.5));
var upper = pos.add(wh.scale(0.5));
render.rectangle(lower,upper,color);
@ -115,14 +105,7 @@ render.window = function(pos, wh, color) {
render.box(p,wh,color);
};
render.text = function(str, pos, size, color, wrap, anchor, cursor) {
size ??= 1;
color ??= Color.white;
wrap ??= -1;
anchor ??= [0,1];
cursor ??= -1;
render.text = function(str, pos, size = 1, color = Color.white, wrap = -1, anchor = [0,1], cursor = -1) {
var bb = render.text_size(str, size, wrap);
var w = bb.r*2;
var h = bb.t*2;
@ -140,10 +123,7 @@ render.text = function(str, pos, size, color, wrap, anchor, cursor) {
return bb;
};
render.image = function(tex, pos, rotation, color, dimensions) {
color ??= Color.white;
rotation ??= 0;
dimensions ??= [tex.width, tex.height];
render.image = function(tex, pos, rotation = 0, color = Color.white, dimensions = [tex.width, tex.height]) {
var scale = [dimensions.x/tex.width, dimensions.y/tex.height];
gui.img(tex,pos, scale, 0.0, false, [0.0,0.0], color);
return bbox.fromcwh([0,0], [tex.width,tex.height]);

View file

@ -2,8 +2,7 @@ var audio = {};
var cries = {};
audio.samplerate = dspsound.samplerate();
audio.play = function(file,bus) {
bus ??= audio.bus.master;
audio.play = function(file,bus = audio.bus.master) {
file = Resources.find_sound(file);
if (!file) {
console.error(`Cannot play sound ${file}: does not exist.`);
@ -40,8 +39,7 @@ var killer = Register.appupdate.register(function() {
var song;
audio.music = function(file, fade) {
fade ??= 0;
audio.music = function(file, fade = 0) {
if (!fade) {
song = audio.play(file);
return;

View file

@ -178,10 +178,9 @@ Cmdline.register_cmd = function(flag, fn, doc) {
});
};
Cmdline.register_order = function(order, fn, doc, usage) {
Cmdline.register_order = function(order, fn, doc, usage = "") {
Cmdline.orders[order] = fn;
fn.doc = doc;
usage ??= "";
fn.usage = `${order} ${usage}`;
}

View file

@ -428,10 +428,10 @@ HMM_Vec2 *inflatepoints(HMM_Vec2 *p, float d, int n)
}
/* Given a strip of points, draws them as segments. So 5 points is 4 segments, and ultimately 8 vertices */
void draw_edge(HMM_Vec2 *points, int n, struct rgba color, int thickness, int flags, struct rgba line_color, float line_seg)
void draw_edge(HMM_Vec2 *points, int n, struct rgba color, float thickness, int flags, struct rgba line_color, float line_seg)
{
int closed = 0;
if (thickness <= 1) {
if (thickness <= 0) {
draw_line(points,n,line_color,0,0);
return;
}

View file

@ -9,7 +9,7 @@ void draw_cppoint(HMM_Vec2 point, float r, struct rgba color);
void draw_points(HMM_Vec2 *points, int n, float size, struct rgba color);
void draw_line(HMM_Vec2 *points, int n, struct rgba color, float seg_len, float seg_speed);
void draw_edge(HMM_Vec2 *points, int n, struct rgba color, int thickness, int flags, struct rgba line_color, float line_seg);
void draw_edge(HMM_Vec2 *points, int n, struct rgba color, float thickness, int flags, struct rgba line_color, float line_seg);
/* pixels - how many pixels thick, segsize - dashed line seg len */
void draw_circle(HMM_Vec2 c, float radius, float pixels, struct rgba color, float seg);