wiki-plugin-rcnsd 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/client/rcnsd.js +1752 -0
- package/factory.json +1 -0
- package/index.js +2 -0
- package/package.json +28 -4
- package/pages/about-rcnsd-plugin +242 -0
package/client/rcnsd.js
ADDED
|
@@ -0,0 +1,1752 @@
|
|
|
1
|
+
// wiki-plugin-rcnsd — an RCN System Dynamics model on a Federated Wiki page.
|
|
2
|
+
//
|
|
3
|
+
// The item HOLDS the model, the way an rcngraph item holds its graph: the Vensim
|
|
4
|
+
// .mdl text in `mdl`, its walks in `walks`, and the knob, graph and run settings
|
|
5
|
+
// in `settings`. The page draws the model, runs it live (math.js, loaded from
|
|
6
|
+
// cdnjs on first use) and plays its walks. "Edit in RCN System Dynamics ↗"
|
|
7
|
+
// opens the full tool with this model; its "→ Save to wiki item" sends the
|
|
8
|
+
// model, walks and settings back into the item.
|
|
9
|
+
//
|
|
10
|
+
// The drawing, the engine and the Vensim reader are the SAME files the tool
|
|
11
|
+
// uses, pasted below by build.js. Edit them in the rcn repo (tools/), then run
|
|
12
|
+
// `node build.js` here. Never edit a pasted block.
|
|
13
|
+
//
|
|
14
|
+
// Marc Pierson with Claude Opus 5.5, November 2026. MIT licence.
|
|
15
|
+
(function () {
|
|
16
|
+
|
|
17
|
+
// BEGIN rcn-mdl.js — pasted from tools/rcn-mdl.js by build.js. Edit that file, never this block.
|
|
18
|
+
/*
|
|
19
|
+
* rcn-mdl.js — read a Vensim .mdl file and turn each view into a Graph Tool graph.
|
|
20
|
+
*
|
|
21
|
+
* Pasted into the Graph Tool by tools/paste-mdl.js. Edit this file, never a
|
|
22
|
+
* pasted block. Runs in a browser and in Node (plain JavaScript, no libraries).
|
|
23
|
+
* tools/check-mdl.js runs it over every .mdl it is given and reports what
|
|
24
|
+
* came across.
|
|
25
|
+
*
|
|
26
|
+
* A .mdl file is the model's equations, then the sketch: one or more views,
|
|
27
|
+
* each a list of comma-separated records (Vensim's own reference:
|
|
28
|
+
* vensim.com/documentation/24305.html):
|
|
29
|
+
* 10 variable 10,id,name,x,y,w,h,shape,bits,hid,hasf,tpos,bw,nav1,nav2,box,fill,font
|
|
30
|
+
* 11 valve same layout; the flow's name is the variable that follows it
|
|
31
|
+
* 12 comment same layout; name 48 = cloud; bits&4 = its text is on the next line
|
|
32
|
+
* 1 arrow 1,id,from,to,shape,hid,pol,thick,hasf,dtype,res,color,font,np|(x,y)|...
|
|
33
|
+
* pol is the ASCII code of the sign drawn on the arrow (+ - S O ?), 0 for none.
|
|
34
|
+
* Arrow shape 4 or 100 is a flow pipe (4 has the arrowhead, 100 runs back to
|
|
35
|
+
* the source). Sizes w,h are half-widths.
|
|
36
|
+
*
|
|
37
|
+
* Signs: only what the file says. An arrow with no sign stays unsigned ('none'),
|
|
38
|
+
* except in files written by RCN's own older exports, which marked negatives
|
|
39
|
+
* with a red colour instead of a sign: those are read the way they were written.
|
|
40
|
+
*
|
|
41
|
+
* RCNMdl.read(text, fileName) -> { views: [{title, variables, arrows, ...}],
|
|
42
|
+
* convert(i, opts) -> { graph, stats } }
|
|
43
|
+
* opts.thick2Negative read arrows of thickness 2 as negative (an old RCN habit)
|
|
44
|
+
*
|
|
45
|
+
* Marc Pierson with Claude Opus 5.5, November 2026. MIT licence.
|
|
46
|
+
*/
|
|
47
|
+
(function (root) {
|
|
48
|
+
'use strict';
|
|
49
|
+
|
|
50
|
+
var RCN_EXPORT_HEADER = '$192-192-192,0,Times New Roman|12||0-0-0|0-0-0|0-0-255|-1--1--1|-1--1--1|96,96,5,0';
|
|
51
|
+
var SIGNS = { 43: '+', 45: '-', 83: '+', 79: '-', 63: '?' }; // + - S(ame) O(pposite) ?
|
|
52
|
+
|
|
53
|
+
// ── small parsers ──────────────────────────────────────────────────────────
|
|
54
|
+
function splitRecord(line) { // commas, except inside "quoted names" (which escape \" )
|
|
55
|
+
var out = [], cur = '', q = false;
|
|
56
|
+
for (var i = 0; i < line.length; i++) {
|
|
57
|
+
var ch = line[i];
|
|
58
|
+
if (q) {
|
|
59
|
+
if (ch === '\\' && i + 1 < line.length) { cur += ch + line[++i]; continue; }
|
|
60
|
+
if (ch === '"') q = false;
|
|
61
|
+
cur += ch;
|
|
62
|
+
} else if (ch === '"') { q = true; cur += ch; }
|
|
63
|
+
else if (ch === ',') { out.push(cur); cur = ''; }
|
|
64
|
+
else cur += ch;
|
|
65
|
+
}
|
|
66
|
+
out.push(cur);
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
function isNum(s) { return /^\s*-?\d+(\.\d+)?\s*$/.test(s || ''); }
|
|
70
|
+
function int(s) { var n = parseInt(s, 10); return isFinite(n) ? n : 0; }
|
|
71
|
+
function vColor(s) { // "255-7-21" -> "#ff0715"; "-1--1--1" or blank -> null
|
|
72
|
+
var m = /^\s*(\d+)-(\d+)-(\d+)\s*$/.exec(s || '');
|
|
73
|
+
if (!m) return null;
|
|
74
|
+
return '#' + [m[1], m[2], m[3]].map(function (v) { return ('0' + Math.min(255, +v).toString(16)).slice(-2); }).join('');
|
|
75
|
+
}
|
|
76
|
+
function fontParts(s) { // "face|size|attributes|color" -> {face,size,attrs,color}
|
|
77
|
+
var p = String(s || '').split('|');
|
|
78
|
+
return { face: p[0] || '', size: parseFloat(p[1]) || null, attrs: p[2] || '', color: vColor(p[3]) };
|
|
79
|
+
}
|
|
80
|
+
function cleanName(s) { // what a person reads: no outer quotes, no \" escapes, no underscores
|
|
81
|
+
s = String(s || '').trim();
|
|
82
|
+
if (s.length > 1 && s[0] === '"' && s[s.length - 1] === '"') s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
83
|
+
return s.replace(/\\n/g, '\n').replace(/_/g, ' ').replace(/[ \t]+/g, ' ').trim();
|
|
84
|
+
}
|
|
85
|
+
function nameKey(s) { return cleanName(s).replace(/\s+/g, ' ').toLowerCase(); }
|
|
86
|
+
|
|
87
|
+
// ── equations ──────────────────────────────────────────────────────────────
|
|
88
|
+
// Each entry: "name = expression ~ units ~ comment |". Kept per variable as
|
|
89
|
+
// its note (the comment), units and equation.
|
|
90
|
+
function readEquations(text) {
|
|
91
|
+
var eqs = {};
|
|
92
|
+
text = text.replace(/^/, '').replace(/^\{UTF-8\}\s*/, '').replace(/\\\r?\n\s*/g, '');
|
|
93
|
+
text.split(/\|\s*(?:\r?\n|$)/).forEach(function (chunk) {
|
|
94
|
+
if (!/~/.test(chunk) || /^\s*\*{5,}/.test(chunk)) return; // group headers
|
|
95
|
+
var parts = chunk.split('~'), def = parts[0].trim();
|
|
96
|
+
var m = /^("(?:[^"\\]|\\.)*"|[^=(:\[]+?)\s*(\[[^\]]*\])?\s*(?:=|:=|==|\(|:)/.exec(def);
|
|
97
|
+
if (!m) return;
|
|
98
|
+
var key = nameKey(m[1]);
|
|
99
|
+
if (!key || eqs[key]) return;
|
|
100
|
+
var rhs = def.slice(m[0].length).trim();
|
|
101
|
+
eqs[key] = {
|
|
102
|
+
stock: /\bINTEG\s*\(/i.test(def),
|
|
103
|
+
placeholder: /A FUNCTION OF/i.test(def),
|
|
104
|
+
equation: def.replace(/\s+/g, ' ').trim(),
|
|
105
|
+
units: (parts[1] || '').replace(/\s+/g, ' ').trim(),
|
|
106
|
+
comment: (parts[2] || '').replace(/[ \t]+/g, ' ').replace(/\s*\n\s*/g, '\n').trim(),
|
|
107
|
+
rhs: rhs
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
return eqs;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ── sketch ─────────────────────────────────────────────────────────────────
|
|
114
|
+
function readViews(text) {
|
|
115
|
+
var lines = text.replace(/\r\n?/g, '\n').split('\n'), views = [], v = null, i = 0;
|
|
116
|
+
var start = -1;
|
|
117
|
+
for (; i < lines.length; i++) if (/^\\\\\\---\/\/\//.test(lines[i].trim())) { start = i; break; }
|
|
118
|
+
if (start < 0) return [];
|
|
119
|
+
var legacyLayout = false;
|
|
120
|
+
for (i = start; i < lines.length; i++) {
|
|
121
|
+
var l = lines[i].replace(/\s+$/, '');
|
|
122
|
+
var t = l.trim();
|
|
123
|
+
if (/^\/\/\/---/.test(t)) break; // end of the sketch
|
|
124
|
+
if (/^\\\\\\---\/\/\//.test(t) || /^V300/.test(t) || !t) continue;
|
|
125
|
+
if (t[0] === '*') { v = { title: t.slice(1).trim() || 'View ' + (views.length + 1), header: '', records: [] }; views.push(v); continue; }
|
|
126
|
+
if (t[0] !== '$' && !/^\d+,/.test(t)) continue;
|
|
127
|
+
if (!v) { v = { title: 'View 1', header: '', records: [] }; views.push(v); }
|
|
128
|
+
if (t[0] === '$') { if (!v.header) v.header = t; continue; }
|
|
129
|
+
var f = splitRecord(t), type = int(f[0]);
|
|
130
|
+
if (type === 10 && isNum(f[2]) && !isNum(f[f.length - 1])) legacyLayout = true;
|
|
131
|
+
var rec = { type: type, f: f, text: null };
|
|
132
|
+
if (type === 12 && (int(f[8]) & 4) && i + 1 < lines.length) rec.text = lines[++i].replace(/\s+$/, '');
|
|
133
|
+
v.records.push(rec);
|
|
134
|
+
}
|
|
135
|
+
views = views.filter(function (vw) { return vw.records.length; }); // a view with nothing drawn in it
|
|
136
|
+
views.forEach(function (vw) { vw.legacyLayout = legacyLayout; });
|
|
137
|
+
return views;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ── one view -> one graph ──────────────────────────────────────────────────
|
|
141
|
+
function convertView(doc, vi, opts) {
|
|
142
|
+
opts = opts || {};
|
|
143
|
+
var view = doc.views[vi], recs = view.records;
|
|
144
|
+
var stats = { variables: 0, stocks: 0, flows: 0, clouds: 0, comments: 0, arrows: 0, pipes: 0,
|
|
145
|
+
'signed +': 0, 'signed -': 0, 'signed ?': 0, unsigned: 0, delays: 0,
|
|
146
|
+
'arrows dropped': 0, 'read as old RCN export': 0 };
|
|
147
|
+
var rcnExport = view.header === RCN_EXPORT_HEADER || view.legacyLayout;
|
|
148
|
+
if (rcnExport) stats['read as old RCN export'] = 1;
|
|
149
|
+
|
|
150
|
+
// view defaults: "$iniarrow,n2,face|size|attributes|color|shape|arrow|fill|background|ppix,ppiy,zoom,tf"
|
|
151
|
+
var hp = view.header.replace(/^\$/, '').split(','), hf = (hp[2] || '').split('|');
|
|
152
|
+
var defSize = parseFloat(hf[1]) || 12, defText = vColor(hf[3]) || '#000000';
|
|
153
|
+
var defShape = vColor(hf[4]) || '#000000', defArrow = vColor(hf[5]) || '#334155';
|
|
154
|
+
var bg = vColor(hf[7]);
|
|
155
|
+
|
|
156
|
+
// Which variables are stocks, and which word names each valve's flow.
|
|
157
|
+
var byId = {}, flowOfValve = {}, pipeEnds = {};
|
|
158
|
+
recs.forEach(function (r, k) {
|
|
159
|
+
byId[r.f[1]] = r;
|
|
160
|
+
if (r.type === 11) { // the flow's name is the valve-attached variable right after it
|
|
161
|
+
for (var j = k + 1; j < Math.min(recs.length, k + 4); j++) {
|
|
162
|
+
var nx = recs[j];
|
|
163
|
+
if (nx.type === 10 && (int(nx.f[7]) & 32)) { flowOfValve[r.f[1]] = nx; break; }
|
|
164
|
+
if (nx.type === 11) break;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (r.type === 1 && (int(r.f[4]) === 4 || int(r.f[4]) === 100)) pipeEnds[r.f[3]] = true;
|
|
168
|
+
});
|
|
169
|
+
var flowWord = {};
|
|
170
|
+
Object.keys(flowOfValve).forEach(function (vid) { flowWord[flowOfValve[vid].f[1]] = vid; });
|
|
171
|
+
|
|
172
|
+
var nodes = [], nodeOf = {}, sfd = false;
|
|
173
|
+
function baseNode(r, label) {
|
|
174
|
+
var f = r.f, legacy = r.type === 10 && view.legacyLayout && isNum(f[2]);
|
|
175
|
+
var x = parseFloat(legacy ? f[2] : f[3]) || 0, y = parseFloat(legacy ? f[3] : f[4]) || 0;
|
|
176
|
+
var w = parseFloat(legacy ? f[4] : f[5]) || 30, h = parseFloat(legacy ? f[5] : f[6]) || 12;
|
|
177
|
+
var k = legacy ? 1 : 2; // Vensim stores half-sizes; the old RCN layout stored whole ones
|
|
178
|
+
return { id: 'v' + f[1], label: label, x: x, y: y, w: Math.max(40, Math.round(w * k)), h: Math.max(24, Math.round(h * k)),
|
|
179
|
+
shape: 'rounded', color: '#ffffff', icon: '', fontSize: defSize, fontColor: defText,
|
|
180
|
+
borderColor: '#cbd5e1', borderWidth: 1, borderDash: 'solid', note: '', extraLabels: [], props: {} };
|
|
181
|
+
}
|
|
182
|
+
function styleFrom(n, f) { // Vensim's own colours and font, when the variable has them
|
|
183
|
+
var hasf = int(f[10]), font = fontParts(f[17]);
|
|
184
|
+
if (hasf & 1) { var bc = vColor(f[15]); if (bc) n.borderColor = bc; }
|
|
185
|
+
if (hasf & 4) { var fc = vColor(f[16]); if (fc) n.color = fc; }
|
|
186
|
+
if ((hasf & 2) && font.color) n.fontColor = font.color;
|
|
187
|
+
if ((hasf & 8) && font.size) n.fontSize = font.size;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
recs.forEach(function (r) {
|
|
191
|
+
var f = r.f;
|
|
192
|
+
if (r.type === 10) {
|
|
193
|
+
if (flowWord[f[1]]) return; // drawn as its valve
|
|
194
|
+
var legacy = view.legacyLayout && isNum(f[2]);
|
|
195
|
+
var raw = legacy ? f[f.length - 1] : f[2], label = cleanName(raw), eq = doc.eqs[nameKey(raw)];
|
|
196
|
+
var shadow = /^<.*>$/.test(label);
|
|
197
|
+
var n = baseNode(r, label.replace(/^<(.*)>$/, '$1'));
|
|
198
|
+
var sh = int(legacy ? 8 : f[7]) & 31, stock = (eq && eq.stock) || (pipeEnds[f[1]] && !legacy);
|
|
199
|
+
if (stock) { n.shape = 'stock'; n.sfdType = 'stock'; n.color = '#dbeafe'; n.fontColor = '#1e3a8a'; n.borderColor = '#000000'; n.borderWidth = 3; stats.stocks++; sfd = true; }
|
|
200
|
+
else if (sh === 3) { n.shape = 'rect'; n.borderColor = defShape; n.borderWidth = 1.5; }
|
|
201
|
+
else if (sh === 2) { n.shape = 'ellipse'; n.borderColor = defShape; n.borderWidth = 1.5; }
|
|
202
|
+
if (!legacy) styleFrom(n, f);
|
|
203
|
+
if (shadow) { n.borderDash = 'dashed'; n.fontColor = '#64748b'; n.props.vensimShadow = 'yes'; }
|
|
204
|
+
if (eq) {
|
|
205
|
+
if (eq.comment) n.note = eq.comment;
|
|
206
|
+
if (eq.units) n.props.vensimUnits = eq.units;
|
|
207
|
+
if (!eq.placeholder && eq.rhs) n.props.vensimEquation = eq.equation;
|
|
208
|
+
}
|
|
209
|
+
if (int(f[9])) n.props.vensimHideLevel = String(int(f[9]));
|
|
210
|
+
nodes.push(n); nodeOf[f[1]] = n.id; stats.variables++;
|
|
211
|
+
} else if (r.type === 11) {
|
|
212
|
+
var word = flowOfValve[f[1]], wl = word ? cleanName(word.f[2]) : 'Flow';
|
|
213
|
+
var vn = baseNode(r, wl), weq = word && doc.eqs[nameKey(word.f[2])];
|
|
214
|
+
vn.shape = 'valve'; vn.sfdType = 'valve'; vn.w = 46; vn.h = 46; vn.borderColor = '#000000'; vn.borderWidth = 2;
|
|
215
|
+
if (weq) {
|
|
216
|
+
if (weq.comment) vn.note = weq.comment;
|
|
217
|
+
if (weq.units) vn.props.vensimUnits = weq.units;
|
|
218
|
+
if (!weq.placeholder && weq.rhs) vn.props.vensimEquation = weq.equation;
|
|
219
|
+
}
|
|
220
|
+
nodes.push(vn); nodeOf[f[1]] = vn.id; if (word) nodeOf[word.f[1]] = vn.id;
|
|
221
|
+
stats.flows++; sfd = true;
|
|
222
|
+
} else if (r.type === 12) {
|
|
223
|
+
if (cleanName(f[2]) === '48') {
|
|
224
|
+
var cn = baseNode(r, '');
|
|
225
|
+
cn.shape = 'cloud'; cn.sfdType = 'cloud'; cn.color = '#e2e8f0'; cn.fontColor = '#475569'; cn.w = 70; cn.h = 50; cn.borderColor = '#000000'; cn.borderWidth = 1.5;
|
|
226
|
+
nodes.push(cn); nodeOf[f[1]] = cn.id; stats.clouds++;
|
|
227
|
+
} else if (r.text !== null && r.text.trim()) {
|
|
228
|
+
var tn = baseNode(r, r.text.replace(/\\n/g, '\n').trim());
|
|
229
|
+
tn.color = '#ffffff00'; tn.borderColor = '#ffffff00'; tn.borderWidth = 0;
|
|
230
|
+
styleFrom(tn, f);
|
|
231
|
+
nodes.push(tn); nodeOf[f[1]] = tn.id; stats.comments++;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// ── arrows
|
|
237
|
+
var edges = [];
|
|
238
|
+
recs.forEach(function (r) {
|
|
239
|
+
if (r.type !== 1) return;
|
|
240
|
+
var f = r.f, shape = int(f[4]), pipe = shape === 4 || shape === 100;
|
|
241
|
+
var from = nodeOf[f[2]], to = nodeOf[f[3]];
|
|
242
|
+
if (!from || !to || from === to) { stats['arrows dropped']++; return; }
|
|
243
|
+
var pol = int(f[6]), thick = int(f[7]), hasf = int(f[8]), dtype = int(f[9]);
|
|
244
|
+
var color = ((hasf & 1) || rcnExport) && vColor(f[11]) || (rcnExport ? '#000000' : defArrow);
|
|
245
|
+
var sign = SIGNS[pol] || 'none';
|
|
246
|
+
if (pol === 0 && rcnExport) sign = vColor(f[11]) === '#ff0000' ? '-' : '+'; // old RCN exports: red = negative
|
|
247
|
+
else if (pol === 0 && opts.thick2Negative && thick === 2) sign = '-';
|
|
248
|
+
var pts = (f.slice(13).join(',').match(/\((-?[\d.]+),(-?[\d.]+)\)/g) || []).map(function (p) {
|
|
249
|
+
var m = /\((-?[\d.]+),(-?[\d.]+)\)/.exec(p); return [+m[1], +m[2]];
|
|
250
|
+
});
|
|
251
|
+
var e = { id: 'a' + f[1], src: from, tgt: to, label: '', color: color,
|
|
252
|
+
width: pipe ? 5 : thick > 0 && thick < 10 ? 1.5 + thick * 0.75 : 1.5,
|
|
253
|
+
dash: 'solid', fontSize: 11, fontColor: color, polarity: pipe ? 'none' : sign,
|
|
254
|
+
curved: false, labelHoriz: true, labelWrap: true, note: '', props: {} };
|
|
255
|
+
if (pipe) { // shape 100 runs from the valve back to where the flow comes from
|
|
256
|
+
e.sfdFlow = true; e.color = '#334155';
|
|
257
|
+
if (shape === 100) { e.src = to; e.tgt = from; }
|
|
258
|
+
stats.pipes++;
|
|
259
|
+
} else {
|
|
260
|
+
stats.arrows++;
|
|
261
|
+
stats[sign === 'none' ? 'unsigned' : 'signed ' + sign]++;
|
|
262
|
+
// A sign Vensim drew that isn't + - S O ? (a digit, say) is kept, so nothing is lost.
|
|
263
|
+
// S and O are Vensim's other spelling of + and -; thickness shows as the line's width.
|
|
264
|
+
if (pol && !SIGNS[pol]) e.props.vensimSign = String.fromCharCode(pol);
|
|
265
|
+
if (dtype & 1) { e.delay = true; stats.delays++; }
|
|
266
|
+
// An arc: Vensim stores a point ON the curve; the Graph Tool wants the bend's control point.
|
|
267
|
+
if (pts.length === 1 && !(pts[0][0] === 0 && pts[0][1] === 0) && !view.legacyLayout) {
|
|
268
|
+
var a = nodes.find(function (n) { return n.id === from; }), b = nodes.find(function (n) { return n.id === to; });
|
|
269
|
+
var mx = pts[0][0], my = pts[0][1];
|
|
270
|
+
var off = Math.abs((b.x - a.x) * (my - a.y) - (b.y - a.y) * (mx - a.x)) / (Math.hypot(b.x - a.x, b.y - a.y) || 1);
|
|
271
|
+
if (off > 4) { e.curved = true; e.cpxUser = Math.round(2 * mx - (a.x + b.x) / 2); e.cpyUser = Math.round(2 * my - (a.y + b.y) / 2); }
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (int(f[5])) e.props.vensimHideLevel = String(int(f[5]));
|
|
275
|
+
edges.push(e);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
var base = String(doc.fileName || 'model.mdl').split('/').pop(), stem = base.replace(/\.[^.]*$/, '');
|
|
279
|
+
var generic = /^view\s*\d*$/i.test(view.title);
|
|
280
|
+
var graph = {
|
|
281
|
+
rcn: { tool: 'graph', format: 1 },
|
|
282
|
+
// Loop mode only when the view has signs: its loop finder counts an unsigned arrow as +,
|
|
283
|
+
// so a sign-free drawing would show every loop as reinforcing.
|
|
284
|
+
version: '1.0', mode: sfd ? 'sfd' : (stats['signed +'] + stats['signed -'] + stats['signed ?'] ? 'cld' : 'select'),
|
|
285
|
+
modelName: doc.views.length === 1 || generic ? stem + (generic && doc.views.length > 1 ? ': ' + view.title : '') : stem + ': ' + view.title,
|
|
286
|
+
modelNote: 'Imported from the Vensim file "' + base + '", view "' + view.title + '".',
|
|
287
|
+
canvasBg: bg || '#ffffff',
|
|
288
|
+
graphAttrs: {}, cldLoopNames: {}, legendEntries: [], legendVisible: false,
|
|
289
|
+
nodes: nodes, edges: edges, lines: [], metaEdges: [], walks: []
|
|
290
|
+
};
|
|
291
|
+
return { graph: graph, stats: stats };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ── the document ───────────────────────────────────────────────────────────
|
|
295
|
+
function read(text, fileName) {
|
|
296
|
+
text = String(text || '');
|
|
297
|
+
var cut = text.search(/^\\\\\\---\/\/\//m);
|
|
298
|
+
var views = readViews(text);
|
|
299
|
+
if (!views.length) throw new Error('no sketch in this file (is it a Vensim .mdl?)');
|
|
300
|
+
var doc = { fileName: fileName || 'model.mdl', eqs: readEquations(cut > 0 ? text.slice(0, cut) : ''), views: views };
|
|
301
|
+
doc.views.forEach(function (v) {
|
|
302
|
+
v.variables = v.records.filter(function (r) { return r.type === 10; }).length;
|
|
303
|
+
v.arrows = v.records.filter(function (r) { return r.type === 1; }).length;
|
|
304
|
+
v.valves = v.records.filter(function (r) { return r.type === 11; }).length;
|
|
305
|
+
});
|
|
306
|
+
doc.convert = function (i, opts) { return convertView(doc, i, opts); };
|
|
307
|
+
return doc;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
var api = { read: read, splitRecord: splitRecord, RCN_EXPORT_HEADER: RCN_EXPORT_HEADER };
|
|
311
|
+
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
|
312
|
+
else root.RCNMdl = api;
|
|
313
|
+
})(typeof window !== 'undefined' ? window : this);
|
|
314
|
+
// END rcn-mdl.js
|
|
315
|
+
|
|
316
|
+
// BEGIN rcn-sd-engine.js — pasted from tools/rcn-sd-engine.js by build.js. Edit that file, never this block.
|
|
317
|
+
/*
|
|
318
|
+
* rcn-sd-engine.js — read the equations of a Vensim .mdl file and run them.
|
|
319
|
+
*
|
|
320
|
+
* Pasted into tools/rcn-sd.html by tools/paste-sd-engine.js. Edit this file,
|
|
321
|
+
* never a pasted block. Runs in a browser (needs math.js loaded as `math`) and
|
|
322
|
+
* in Node (needs `npm install mathjs`). tools/check-sd.js runs it over .mdl
|
|
323
|
+
* files and, given a CSV from PySD or Vensim, compares the numbers.
|
|
324
|
+
*
|
|
325
|
+
* What it does, in order:
|
|
326
|
+
* 1. Splits the equations into variables: constants and auxiliaries, stocks
|
|
327
|
+
* (INTEG), lookup tables, and the four control settings (INITIAL TIME,
|
|
328
|
+
* FINAL TIME, TIME STEP, SAVEPER).
|
|
329
|
+
* 2. Turns each Vensim expression into math.js syntax. Names with spaces
|
|
330
|
+
* become short ids (v0, v1 …); Vensim's functions become ours.
|
|
331
|
+
* Functions that remember (SMOOTH, DELAY1, DELAY3, TREND, INITIAL,
|
|
332
|
+
* DELAY FIXED) become hidden stocks, the way Vensim itself defines them.
|
|
333
|
+
* 3. math.js parses and compiles every expression. Its syntax tree tells us
|
|
334
|
+
* what each variable reads, so the variables can be put in an order
|
|
335
|
+
* where everything is worked out before it is needed.
|
|
336
|
+
* 4. Runs: Euler (Vensim's default) or Runge-Kutta 4.
|
|
337
|
+
*
|
|
338
|
+
* Not handled yet, and reported by name when a model uses them: subscripts,
|
|
339
|
+
* data variables, macros, and functions not in the FUNCTIONS list below.
|
|
340
|
+
*
|
|
341
|
+
* RCNSD.compile(text) -> model { vars, problems, control, constants, run(opts) }
|
|
342
|
+
* model.run({ method: 'euler'|'rk4', overrides: {name: value}, final: n, dt: n })
|
|
343
|
+
* -> { time: [...], series: {name: [...]}, problems: [...] }
|
|
344
|
+
*
|
|
345
|
+
* Marc Pierson with Claude Opus 5.5, November 2026. MIT licence.
|
|
346
|
+
*/
|
|
347
|
+
(function (root) {
|
|
348
|
+
'use strict';
|
|
349
|
+
|
|
350
|
+
function getMath() {
|
|
351
|
+
if (root && root.math) return root.math;
|
|
352
|
+
if (typeof require === 'function') return require('mathjs');
|
|
353
|
+
throw new Error('math.js is not loaded');
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ── names ──────────────────────────────────────────────────────────────────
|
|
357
|
+
function unquote(s) {
|
|
358
|
+
s = String(s || '').trim();
|
|
359
|
+
if (s.length > 1 && s[0] === '"' && s[s.length - 1] === '"') s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
360
|
+
return s;
|
|
361
|
+
}
|
|
362
|
+
function nameKey(s) { return unquote(s).replace(/\\n/g, ' ').replace(/_/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase(); }
|
|
363
|
+
function display(s) { return unquote(s).replace(/\\n/g, ' ').replace(/_/g, ' ').replace(/\s+/g, ' ').trim(); }
|
|
364
|
+
|
|
365
|
+
// ── text helpers ───────────────────────────────────────────────────────────
|
|
366
|
+
function matchParen(s, open) { // index of the ) that closes the ( at `open`
|
|
367
|
+
var depth = 0, q = false;
|
|
368
|
+
for (var i = open; i < s.length; i++) {
|
|
369
|
+
var c = s[i];
|
|
370
|
+
if (q) { if (c === '\\') i++; else if (c === '"') q = false; continue; }
|
|
371
|
+
if (c === '"') q = true;
|
|
372
|
+
else if (c === '(' || c === '[') depth++;
|
|
373
|
+
else if (c === ')' || c === ']') { depth--; if (depth === 0) return i; }
|
|
374
|
+
}
|
|
375
|
+
return -1;
|
|
376
|
+
}
|
|
377
|
+
function splitTop(s) { // split on commas that are not inside ( ) [ ] or quotes
|
|
378
|
+
var out = [], depth = 0, q = false, cur = '';
|
|
379
|
+
for (var i = 0; i < s.length; i++) {
|
|
380
|
+
var c = s[i];
|
|
381
|
+
if (q) { cur += c; if (c === '\\') { cur += s[++i] || ''; } else if (c === '"') q = false; continue; }
|
|
382
|
+
if (c === '"') q = true;
|
|
383
|
+
if (c === '(' || c === '[') depth++;
|
|
384
|
+
if (c === ')' || c === ']') depth--;
|
|
385
|
+
if (c === ',' && depth === 0) { out.push(cur); cur = ''; continue; }
|
|
386
|
+
cur += c;
|
|
387
|
+
}
|
|
388
|
+
out.push(cur);
|
|
389
|
+
return out.map(function (a) { return a.trim(); });
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// A lookup table: "[(0,0)-(10,1)],(0,0),(5,0.5),(10,1)" or the older
|
|
393
|
+
// "x1,x2,…,y1,y2,…". The [range] part only sets the graph's frame in Vensim.
|
|
394
|
+
function parseTable(s) {
|
|
395
|
+
s = String(s || '').trim();
|
|
396
|
+
if (s[0] === '(' && matchParen(s, 0) === s.length - 1 && /^\(\s*\[/.test(s)) s = s.slice(1, -1).trim();
|
|
397
|
+
s = s.replace(/^\s*\[[^\]]*\]\s*,?/, '');
|
|
398
|
+
var xs = [], ys = [], re = /\(\s*([-+]?[\d.]+(?:[eE][-+]?\d+)?)\s*,\s*([-+]?[\d.]+(?:[eE][-+]?\d+)?)\s*\)/g, m;
|
|
399
|
+
while ((m = re.exec(s))) { xs.push(+m[1]); ys.push(+m[2]); }
|
|
400
|
+
if (!xs.length) {
|
|
401
|
+
var nums = (s.match(/[-+]?[\d.]+(?:[eE][-+]?\d+)?/g) || []).map(Number);
|
|
402
|
+
var h = Math.floor(nums.length / 2);
|
|
403
|
+
xs = nums.slice(0, h); ys = nums.slice(h, 2 * h);
|
|
404
|
+
}
|
|
405
|
+
if (!xs.length) throw new Error('a lookup table with no points');
|
|
406
|
+
return { x: xs, y: ys };
|
|
407
|
+
}
|
|
408
|
+
function lookupFn(t, mode) { // mode: '' hold the ends, 'x' extrapolate, 'f' forward, 'b' backward
|
|
409
|
+
var X = t.x, Y = t.y, n = X.length;
|
|
410
|
+
return function (v) {
|
|
411
|
+
v = +v;
|
|
412
|
+
if (n === 1) return Y[0];
|
|
413
|
+
if (v <= X[0]) return mode === 'x' ? Y[0] + (v - X[0]) * (Y[1] - Y[0]) / (X[1] - X[0]) : Y[0];
|
|
414
|
+
if (v >= X[n - 1]) return mode === 'x' ? Y[n - 1] + (v - X[n - 1]) * (Y[n - 1] - Y[n - 2]) / (X[n - 1] - X[n - 2]) : Y[n - 1];
|
|
415
|
+
var i = 1; while (i < n - 1 && X[i] < v) i++;
|
|
416
|
+
if (mode === 'b') return v === X[i] ? Y[i] : Y[i - 1];
|
|
417
|
+
if (mode === 'f') return v === X[i - 1] ? Y[i - 1] : Y[i];
|
|
418
|
+
return Y[i - 1] + (v - X[i - 1]) * (Y[i] - Y[i - 1]) / (X[i] - X[i - 1]);
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ── 1. split the equations ─────────────────────────────────────────────────
|
|
423
|
+
var CONTROL = { 'initial time': 1, 'final time': 1, 'time step': 1, 'saveper': 1 };
|
|
424
|
+
|
|
425
|
+
function readEquations(text) {
|
|
426
|
+
var cut = text.search(/^\\\\\\---\/\/\//m);
|
|
427
|
+
if (cut >= 0) text = text.slice(0, cut);
|
|
428
|
+
text = text.replace(/^/, '').replace(/^\{UTF-8\}\s*/, '').replace(/\\\r?\n\s*/g, ' ');
|
|
429
|
+
var out = [], problems = [];
|
|
430
|
+
if (/:MACRO:/i.test(text)) problems.push({ kind: 'unsupported', what: 'macros (:MACRO:)' });
|
|
431
|
+
text = text.replace(/:MACRO:[\s\S]*?:END OF MACRO:/gi, '');
|
|
432
|
+
text.split(/\|\s*(?:\r?\n|$)/).forEach(function (chunk) {
|
|
433
|
+
if (!/~/.test(chunk)) return;
|
|
434
|
+
var parts = chunk.split('~');
|
|
435
|
+
// A group header ("*****" lines) and any notes written under it come before the
|
|
436
|
+
// definition in the same chunk: keep only what follows the last line of asterisks.
|
|
437
|
+
var def = parts[0].replace(/^[\s\S]*\*{5,}[^\n]*(\n|$)/, '').replace(/\{[^{}]*\}/g, ' ').trim(); // {inline comments}
|
|
438
|
+
if (!def) return;
|
|
439
|
+
// find where the name ends: the first = ( : [ outside quotes
|
|
440
|
+
var i = 0, q = false;
|
|
441
|
+
for (; i < def.length; i++) {
|
|
442
|
+
var c = def[i];
|
|
443
|
+
if (q) { if (c === '\\') i++; else if (c === '"') q = false; continue; }
|
|
444
|
+
if (c === '"') { q = true; continue; }
|
|
445
|
+
if (c === '=' || c === '(' || c === '[') break;
|
|
446
|
+
// a colon ends the name only for data (:=) or a subscript range (no = after it);
|
|
447
|
+
// otherwise it is part of the name, as in "Male:Female Ratio"
|
|
448
|
+
if (c === ':' && (def[i + 1] === '=' || def.indexOf('=', i) < 0)) break;
|
|
449
|
+
}
|
|
450
|
+
var name = def.slice(0, i).trim(), rest = def.slice(i);
|
|
451
|
+
if (!name) return;
|
|
452
|
+
var v = { name: display(name), key: nameKey(name), units: (parts[1] || '').replace(/\s+/g, ' ').trim(),
|
|
453
|
+
comment: (parts[2] || '').replace(/[ \t]+/g, ' ').trim(), equation: def.replace(/\s+/g, ' ') };
|
|
454
|
+
var range = /\[\s*([-\d.eE+]+|\?)\s*,\s*([-\d.eE+]+|\?)\s*(?:,\s*([-\d.eE+]+))?\s*\]/.exec(v.units);
|
|
455
|
+
if (range) v.range = [range[1] === '?' ? null : +range[1], range[2] === '?' ? null : +range[2], range[3] ? +range[3] : null];
|
|
456
|
+
if (rest[0] === '[') { v.kind = 'unsupported'; v.why = 'subscripts'; }
|
|
457
|
+
else if (rest[0] === '(') {
|
|
458
|
+
var close = matchParen(rest, 0);
|
|
459
|
+
try { v.kind = 'table'; v.table = parseTable(rest.slice(1, close < 0 ? rest.length : close)); }
|
|
460
|
+
catch (e) { v.kind = 'unsupported'; v.why = e.message; }
|
|
461
|
+
} else if (/^:=/.test(rest)) { v.kind = 'unsupported'; v.why = 'data variable (:=)'; }
|
|
462
|
+
else if (/^:/.test(rest) && !/^:=/.test(rest)) { v.kind = 'unsupported'; v.why = 'subscript range'; }
|
|
463
|
+
else if (rest[0] === '=') {
|
|
464
|
+
var rhs = rest.replace(/^==?/, '').trim();
|
|
465
|
+
if (!rhs) { v.kind = 'unsupported'; v.why = 'data variable (no equation)'; }
|
|
466
|
+
else if (/^A FUNCTION OF\b/i.test(rhs)) { v.kind = 'unsupported'; v.why = 'no equation yet (A FUNCTION OF)'; }
|
|
467
|
+
else if (/^INTEG\s*\(/i.test(rhs)) {
|
|
468
|
+
var op = rhs.indexOf('('), cl = matchParen(rhs, op), args = splitTop(rhs.slice(op + 1, cl));
|
|
469
|
+
if (args.length !== 2) { v.kind = 'unsupported'; v.why = 'INTEG needs two parts: the flows and the starting value'; }
|
|
470
|
+
else { v.kind = 'stock'; v.rate = args[0]; v.init = args[1]; }
|
|
471
|
+
} else { v.kind = 'aux'; v.expr = rhs; }
|
|
472
|
+
} else { v.kind = 'unsupported'; v.why = 'data variable (no equation)'; }
|
|
473
|
+
if (CONTROL[v.key]) v.control = true;
|
|
474
|
+
out.push(v);
|
|
475
|
+
});
|
|
476
|
+
return { vars: out, problems: problems };
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// ── 2. Vensim expression -> math.js expression ─────────────────────────────
|
|
480
|
+
// Plain functions: name -> the scope function that does it.
|
|
481
|
+
var FUNCTIONS = {
|
|
482
|
+
'MIN': 'F_MIN', 'MAX': 'F_MAX', 'ABS': 'F_ABS', 'EXP': 'F_EXP', 'LN': 'F_LN', 'LOG': 'F_LOG',
|
|
483
|
+
'SQRT': 'F_SQRT', 'SIN': 'F_SIN', 'COS': 'F_COS', 'TAN': 'F_TAN', 'ARCSIN': 'F_ASIN', 'ARCCOS': 'F_ACOS',
|
|
484
|
+
'ARCTAN': 'F_ATAN', 'TANH': 'F_TANH', 'SINH': 'F_SINH', 'COSH': 'F_COSH', 'INTEGER': 'F_INT', 'MODULO': 'F_MOD', 'POWER': 'F_POW', 'ZIDZ': 'F_ZIDZ',
|
|
485
|
+
'XIDZ': 'F_XIDZ', 'SIGN': 'F_SIGN', 'QUANTUM': 'F_QUANTUM', 'STEP': 'F_STEP', 'PULSE': 'F_PULSE',
|
|
486
|
+
'PULSE TRAIN': 'F_PULSE_TRAIN', 'RAMP': 'F_RAMP', 'RANDOM UNIFORM': 'F_RANDOM_UNIFORM',
|
|
487
|
+
'RANDOM NORMAL': 'F_RANDOM_NORMAL'
|
|
488
|
+
};
|
|
489
|
+
// Functions that remember: handled by making hidden stocks.
|
|
490
|
+
var STATEFUL = { 'SMOOTH': 1, 'SMOOTHI': 1, 'SMOOTH3': 1, 'SMOOTH3I': 1, 'DELAY1': 1, 'DELAY1I': 1,
|
|
491
|
+
'DELAY3': 1, 'DELAY3I': 1, 'DELAY FIXED': 1, 'INITIAL': 1, 'ACTIVE INITIAL': 1, 'TREND': 1 };
|
|
492
|
+
var NA = '(-6.49037e32)';
|
|
493
|
+
|
|
494
|
+
function Translator(model) { this.m = model; }
|
|
495
|
+
Translator.prototype.tr = function (src) {
|
|
496
|
+
var s = String(src), i = 0, out = '', m = this.m;
|
|
497
|
+
function isNameStart(c) { return /[A-Za-z_$'À-]/.test(c); }
|
|
498
|
+
function isNameChar(c) { return /[A-Za-z0-9_$'.&À-]/.test(c); }
|
|
499
|
+
while (i < s.length) {
|
|
500
|
+
var c = s[i];
|
|
501
|
+
if (/\s/.test(c)) { i++; continue; }
|
|
502
|
+
var name = null;
|
|
503
|
+
if (c === '"') { // quoted name
|
|
504
|
+
var j = i + 1;
|
|
505
|
+
while (j < s.length && s[j] !== '"') { if (s[j] === '\\') j++; j++; }
|
|
506
|
+
name = s.slice(i, j + 1); i = j + 1;
|
|
507
|
+
} else if (isNameStart(c)) { // a name, which may have spaces in it
|
|
508
|
+
var k = i;
|
|
509
|
+
while (k < s.length && isNameChar(s[k])) k++;
|
|
510
|
+
name = s.slice(i, k); i = k;
|
|
511
|
+
for (;;) {
|
|
512
|
+
var w = i; while (w < s.length && /[ \t]/.test(s[w])) w++;
|
|
513
|
+
if (w > i && w < s.length && (isNameStart(s[w]) || /[0-9]/.test(s[w]))) {
|
|
514
|
+
var e = w; while (e < s.length && isNameChar(s[e])) e++;
|
|
515
|
+
name += ' ' + s.slice(w, e); i = e;
|
|
516
|
+
} else break;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
if (name !== null) {
|
|
520
|
+
var p = i; while (p < s.length && /\s/.test(s[p])) p++;
|
|
521
|
+
if (s[p] === '(') { // a call: function or lookup table
|
|
522
|
+
var close = matchParen(s, p);
|
|
523
|
+
if (close < 0) throw new Error('a "(" with no ")" after ' + display(name));
|
|
524
|
+
out += ' ' + this.call(display(name), s.slice(p + 1, close)) + ' ';
|
|
525
|
+
i = close + 1;
|
|
526
|
+
} else out += ' ' + this.symbol(name) + ' ';
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
var num = /^(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?/.exec(s.slice(i));
|
|
530
|
+
if (num) { out += num[0]; i += num[0].length; continue; }
|
|
531
|
+
var two = s.substr(i, 2), kw = /^:(AND|OR|NOT|NA):/i.exec(s.slice(i));
|
|
532
|
+
if (kw) { var k2 = kw[1].toUpperCase(); out += k2 === 'NA' ? NA : ' ' + k2.toLowerCase() + ' '; i += kw[0].length; continue; }
|
|
533
|
+
if (two === '<>') { out += ' != '; i += 2; continue; }
|
|
534
|
+
if (two === '<=' || two === '>=') { out += ' ' + two + ' '; i += 2; continue; }
|
|
535
|
+
if (c === '=') { out += ' == '; i++; continue; }
|
|
536
|
+
if ('+-*/^(),<>'.indexOf(c) >= 0) { out += c; i++; continue; }
|
|
537
|
+
throw new Error('cannot read "' + c + '" in: ' + s.trim());
|
|
538
|
+
}
|
|
539
|
+
return out.replace(/\s+/g, ' ').trim();
|
|
540
|
+
};
|
|
541
|
+
Translator.prototype.symbol = function (raw) {
|
|
542
|
+
var key = nameKey(raw);
|
|
543
|
+
if (key === 'time') return 'T_';
|
|
544
|
+
var v = this.m.byKey[key];
|
|
545
|
+
if (!v) throw new Error('uses ' + display(raw) + ', which has no equation in this file');
|
|
546
|
+
if (v.kind === 'table') throw new Error(v.name + ' is a lookup table; it needs a value in brackets after it');
|
|
547
|
+
return v.id;
|
|
548
|
+
};
|
|
549
|
+
Translator.prototype.call = function (name, inner) {
|
|
550
|
+
var self = this, m = this.m, fname = name.toUpperCase().replace(/\s+/g, ' ');
|
|
551
|
+
var args = splitTop(inner);
|
|
552
|
+
function a(n) { if (args[n] == null || args[n] === '') throw new Error(fname + ' is missing a part'); return '(' + self.tr(args[n]) + ')'; }
|
|
553
|
+
if (fname === 'IF THEN ELSE') return '((' + a(0) + ') ? ' + a(1) + ' : ' + a(2) + ')';
|
|
554
|
+
if (fname === 'WITH LOOKUP') return m.addTable(parseTable(args[1]), '') + '(' + a(0) + ')';
|
|
555
|
+
var lk = /^LOOKUP (EXTRAPOLATE|FORWARD|BACKWARD)$/.exec(fname);
|
|
556
|
+
if (lk) {
|
|
557
|
+
var tv = m.byKey[nameKey(args[0])];
|
|
558
|
+
if (!tv || tv.kind !== 'table') throw new Error(fname + ' needs a lookup table first');
|
|
559
|
+
return m.tableFn(tv, lk[1][0].toLowerCase()) + '(' + a(1) + ')';
|
|
560
|
+
}
|
|
561
|
+
if (FUNCTIONS[fname]) return FUNCTIONS[fname] + '(' + args.map(function (x, n) { return a(n); }).join(', ') + ')';
|
|
562
|
+
if (STATEFUL[fname]) return m.addState(fname, args.map(function (x, n) { return a(n); }));
|
|
563
|
+
var v = m.byKey[nameKey(name)];
|
|
564
|
+
if (v && v.kind === 'table') return m.tableFn(v, '') + '(' + a(0) + ')';
|
|
565
|
+
if (v) throw new Error(v.name + ' is used like a function, but it is not a lookup table');
|
|
566
|
+
m.unsupportedFns[fname] = true;
|
|
567
|
+
throw new Error('function not handled yet: ' + fname);
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
// ── 3. compile ─────────────────────────────────────────────────────────────
|
|
571
|
+
function compile(text) {
|
|
572
|
+
var math = getMath();
|
|
573
|
+
var read = readEquations(String(text || ''));
|
|
574
|
+
var m = { vars: [], byKey: {}, hidden: [], problems: read.problems.slice(), unsupportedFns: {}, tables: {}, nTables: 0 };
|
|
575
|
+
read.vars.forEach(function (v, n) {
|
|
576
|
+
if (m.byKey[v.key]) return;
|
|
577
|
+
v.id = 'v' + n; m.byKey[v.key] = v; m.vars.push(v);
|
|
578
|
+
});
|
|
579
|
+
m.addTable = function (t, mode) { var id = 'L' + (m.nTables++); m.tables[id] = lookupFn(t, mode); return id; };
|
|
580
|
+
m.tableFn = function (v, mode) {
|
|
581
|
+
var id = v.id + '_L' + mode;
|
|
582
|
+
if (!m.tables[id]) m.tables[id] = lookupFn(v.table, mode);
|
|
583
|
+
return id;
|
|
584
|
+
};
|
|
585
|
+
var hn = 0;
|
|
586
|
+
function hid() { return 'h' + (hn++); }
|
|
587
|
+
function hStock(rate, init) { var id = hid(); m.hidden.push({ id: id, kind: 'stock', rateM: rate, initM: init }); return id; }
|
|
588
|
+
function hAux(expr) { var id = hid(); m.hidden.push({ id: id, kind: 'aux', exprM: expr }); return id; }
|
|
589
|
+
m.addState = function (f, A) {
|
|
590
|
+
var x = A[0], t = A[1], s1, s2, s3, L1, L2, L3, t3 = '(' + t + '/3)';
|
|
591
|
+
switch (f) {
|
|
592
|
+
case 'SMOOTH': case 'SMOOTHI': {
|
|
593
|
+
var id = hid(); m.hidden.push({ id: id, kind: 'stock', rateM: '(' + x + ' - ' + id + ') / ' + t, initM: f === 'SMOOTHI' ? A[2] : x });
|
|
594
|
+
return id;
|
|
595
|
+
}
|
|
596
|
+
case 'SMOOTH3': case 'SMOOTH3I': {
|
|
597
|
+
var i0 = f === 'SMOOTH3I' ? A[2] : x;
|
|
598
|
+
s1 = hid(); s2 = hid(); s3 = hid();
|
|
599
|
+
m.hidden.push({ id: s1, kind: 'stock', rateM: '(' + x + ' - ' + s1 + ') / ' + t3, initM: i0 });
|
|
600
|
+
m.hidden.push({ id: s2, kind: 'stock', rateM: '(' + s1 + ' - ' + s2 + ') / ' + t3, initM: i0 });
|
|
601
|
+
m.hidden.push({ id: s3, kind: 'stock', rateM: '(' + s2 + ' - ' + s3 + ') / ' + t3, initM: i0 });
|
|
602
|
+
return s3;
|
|
603
|
+
}
|
|
604
|
+
case 'DELAY1': case 'DELAY1I': {
|
|
605
|
+
L1 = hid();
|
|
606
|
+
m.hidden.push({ id: L1, kind: 'stock', rateM: x + ' - ' + L1 + ' / ' + t, initM: (f === 'DELAY1I' ? A[2] : x) + ' * ' + t });
|
|
607
|
+
return hAux(L1 + ' / ' + t);
|
|
608
|
+
}
|
|
609
|
+
case 'DELAY3': case 'DELAY3I': {
|
|
610
|
+
var d0 = (f === 'DELAY3I' ? A[2] : x) + ' * ' + t3;
|
|
611
|
+
L1 = hid(); L2 = hid(); L3 = hid();
|
|
612
|
+
m.hidden.push({ id: L1, kind: 'stock', rateM: x + ' - ' + L1 + ' / ' + t3, initM: d0 });
|
|
613
|
+
m.hidden.push({ id: L2, kind: 'stock', rateM: L1 + ' / ' + t3 + ' - ' + L2 + ' / ' + t3, initM: d0 });
|
|
614
|
+
m.hidden.push({ id: L3, kind: 'stock', rateM: L2 + ' / ' + t3 + ' - ' + L3 + ' / ' + t3, initM: d0 });
|
|
615
|
+
return hAux(L3 + ' / ' + t3);
|
|
616
|
+
}
|
|
617
|
+
case 'TREND': {
|
|
618
|
+
var avg = hid();
|
|
619
|
+
m.hidden.push({ id: avg, kind: 'stock', rateM: '(' + x + ' - ' + avg + ') / ' + t, initM: x + ' / (1 + ' + A[2] + ' * ' + t + ')' });
|
|
620
|
+
return hAux('F_ZIDZ(' + x + ' - ' + avg + ', ' + avg + ' * ' + t + ')');
|
|
621
|
+
}
|
|
622
|
+
case 'INITIAL': { var ii = hid(); m.hidden.push({ id: ii, kind: 'initial', exprM: x }); return ii; }
|
|
623
|
+
case 'ACTIVE INITIAL': { var ai = hid(); m.hidden.push({ id: ai, kind: 'aux', exprM: x, initM: A[1] }); return ai; }
|
|
624
|
+
case 'DELAY FIXED': { var df = hid(); m.hidden.push({ id: df, kind: 'fixed', inM: x, delayM: t, initM: A[2] }); return df; }
|
|
625
|
+
}
|
|
626
|
+
throw new Error('not handled: ' + f);
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
// translate every variable
|
|
630
|
+
var tr = new Translator(m), bad = {};
|
|
631
|
+
m.vars.forEach(function (v) {
|
|
632
|
+
try {
|
|
633
|
+
if (v.kind === 'unsupported') throw new Error(v.why);
|
|
634
|
+
if (v.kind === 'stock') { v.rateM = tr.tr(v.rate); v.initM = tr.tr(v.init); }
|
|
635
|
+
else if (v.kind === 'aux') v.exprM = tr.tr(v.expr);
|
|
636
|
+
} catch (e) { bad[v.id] = true; v.error = e.message; m.problems.push({ kind: 'variable', name: v.name, what: e.message }); }
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
// parse with math.js, find what each expression reads, compile it
|
|
640
|
+
var known = {};
|
|
641
|
+
m.vars.concat(m.hidden).forEach(function (v) { if (v.kind !== 'table') known[v.id] = v; });
|
|
642
|
+
function prep(src, owner) {
|
|
643
|
+
var node = math.parse(src), deps = {};
|
|
644
|
+
node.traverse(function (n, path, parent) {
|
|
645
|
+
if (n.isSymbolNode && !(parent && parent.isFunctionNode && path === 'fn') && known[n.name]) deps[n.name] = true;
|
|
646
|
+
});
|
|
647
|
+
return { code: node.compile(), deps: Object.keys(deps), text: src, owner: owner };
|
|
648
|
+
}
|
|
649
|
+
m.vars.concat(m.hidden).forEach(function (v) {
|
|
650
|
+
if (bad[v.id] || v.kind === 'table') return;
|
|
651
|
+
try {
|
|
652
|
+
if (v.exprM != null) v.expr_ = prep(v.exprM, v);
|
|
653
|
+
if (v.rateM != null) v.rate_ = prep(v.rateM, v);
|
|
654
|
+
if (v.initM != null) v.init_ = prep(v.initM, v);
|
|
655
|
+
if (v.inM != null) v.in_ = prep(v.inM, v);
|
|
656
|
+
if (v.delayM != null) v.delay_ = prep(v.delayM, v);
|
|
657
|
+
} catch (e) {
|
|
658
|
+
bad[v.id] = true; v.error = e.message;
|
|
659
|
+
m.problems.push({ kind: 'variable', name: v.name || 'a hidden part', what: e.message });
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
// anything that reads a broken variable cannot run either
|
|
663
|
+
var changed = true;
|
|
664
|
+
while (changed) {
|
|
665
|
+
changed = false;
|
|
666
|
+
m.vars.concat(m.hidden).forEach(function (v) {
|
|
667
|
+
if (bad[v.id] || v.kind === 'table') return;
|
|
668
|
+
var all = [].concat(v.expr_ ? v.expr_.deps : [], v.rate_ ? v.rate_.deps : [], v.init_ ? v.init_.deps : [], v.in_ ? v.in_.deps : [], v.delay_ ? v.delay_.deps : []);
|
|
669
|
+
var hit = all.filter(function (d) { return bad[d]; })[0];
|
|
670
|
+
if (hit) { bad[v.id] = true; v.error = 'reads ' + (known[hit].name || 'a broken part'); changed = true; }
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
m.bad = bad;
|
|
674
|
+
m.runnable = !Object.keys(bad).length && !read.problems.length;
|
|
675
|
+
var fnList = Object.keys(m.unsupportedFns);
|
|
676
|
+
if (fnList.length) m.problems.unshift({ kind: 'unsupported', what: 'functions not handled yet: ' + fnList.join(', ') });
|
|
677
|
+
|
|
678
|
+
// the orders things are worked out in
|
|
679
|
+
function order(nodes, depsOf, label) {
|
|
680
|
+
var seen = {}, temp = {}, out = [];
|
|
681
|
+
function visit(v, chain) {
|
|
682
|
+
if (seen[v.id]) return;
|
|
683
|
+
if (temp[v.id]) {
|
|
684
|
+
var cyc = chain.slice(chain.indexOf(v.id)).map(function (id) { return known[id].name || 'a hidden part'; });
|
|
685
|
+
throw new Error(label + ': these variables depend on each other with no stock between them: ' + cyc.join(' → '));
|
|
686
|
+
}
|
|
687
|
+
temp[v.id] = true;
|
|
688
|
+
depsOf(v).forEach(function (d) { if (nodesById[d]) visit(nodesById[d], chain.concat(v.id)); });
|
|
689
|
+
temp[v.id] = false; seen[v.id] = true; out.push(v);
|
|
690
|
+
}
|
|
691
|
+
var nodesById = {}; nodes.forEach(function (v) { nodesById[v.id] = v; });
|
|
692
|
+
nodes.forEach(function (v) { visit(v, []); });
|
|
693
|
+
return out;
|
|
694
|
+
}
|
|
695
|
+
var live = m.vars.concat(m.hidden).filter(function (v) { return !bad[v.id] && v.kind !== 'table' && v.kind !== 'unsupported'; });
|
|
696
|
+
if (m.runnable) {
|
|
697
|
+
try {
|
|
698
|
+
m.initOrder = order(live, function (v) {
|
|
699
|
+
if (v.kind === 'stock') return v.init_.deps;
|
|
700
|
+
if (v.kind === 'fixed') return v.init_.deps.concat(v.delay_.deps);
|
|
701
|
+
if (v.kind === 'aux' && v.init_) return v.init_.deps;
|
|
702
|
+
return v.expr_.deps;
|
|
703
|
+
}, 'At the start');
|
|
704
|
+
m.stepOrder = order(live.filter(function (v) { return v.kind === 'aux'; }), function (v) { return v.expr_.deps; }, 'While running');
|
|
705
|
+
} catch (e) { m.runnable = false; m.problems.push({ kind: 'loop', what: e.message }); }
|
|
706
|
+
}
|
|
707
|
+
m.stocks = live.filter(function (v) { return v.kind === 'stock'; });
|
|
708
|
+
m.fixed = live.filter(function (v) { return v.kind === 'fixed'; });
|
|
709
|
+
m.constants = m.vars.filter(function (v) {
|
|
710
|
+
return v.kind === 'aux' && !v.control && v.expr_ && !v.expr_.deps.length && /^-?[\d.]+(e[-+]?\d+)?$/i.test(v.expr.trim());
|
|
711
|
+
});
|
|
712
|
+
m.control = {};
|
|
713
|
+
m.run = function (opts) { return run(m, opts || {}); };
|
|
714
|
+
return m;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// ── 4. run ─────────────────────────────────────────────────────────────────
|
|
718
|
+
function run(m, opts) {
|
|
719
|
+
if (!m.runnable) throw new Error('This model cannot run yet: ' + m.problems.map(function (p) { return (p.name ? p.name + ': ' : '') + p.what; }).join('; '));
|
|
720
|
+
var S = {}, clock = { t: 0, dt: 1 }, seed = 1;
|
|
721
|
+
function rand() { seed = (seed * 16807) % 2147483647; return (seed - 1) / 2147483646; }
|
|
722
|
+
var F = {
|
|
723
|
+
F_MIN: Math.min, F_MAX: Math.max, F_ABS: Math.abs, F_EXP: Math.exp, F_LN: Math.log,
|
|
724
|
+
F_LOG: function (x, b) { return Math.log(x) / Math.log(b == null ? 10 : b); },
|
|
725
|
+
F_SQRT: Math.sqrt, F_SIN: Math.sin, F_COS: Math.cos, F_TAN: Math.tan, F_ASIN: Math.asin, F_ACOS: Math.acos, F_ATAN: Math.atan,
|
|
726
|
+
F_TANH: Math.tanh, F_SINH: Math.sinh, F_COSH: Math.cosh,
|
|
727
|
+
F_INT: function (x) { return Math.trunc(x); },
|
|
728
|
+
F_MOD: function (a, b) { return a - b * Math.floor(a / b); },
|
|
729
|
+
F_POW: Math.pow, F_SIGN: Math.sign,
|
|
730
|
+
F_ZIDZ: function (a, b) { return b === 0 ? 0 : a / b; },
|
|
731
|
+
F_XIDZ: function (a, b, x) { return b === 0 ? x : a / b; },
|
|
732
|
+
F_QUANTUM: function (a, q) { return q <= 0 ? a : q * Math.trunc(a / q); },
|
|
733
|
+
F_STEP: function (h, st) { return clock.t + clock.dt / 2 > st ? h : 0; },
|
|
734
|
+
F_PULSE: function (st, w) { var t = clock.t + clock.dt / 2; return t > st && t < st + Math.max(w, clock.dt) ? 1 : 0; },
|
|
735
|
+
F_PULSE_TRAIN: function (st, w, every, end) {
|
|
736
|
+
var t = clock.t + clock.dt / 2; if (t < st || t > end) return 0;
|
|
737
|
+
var into = (t - st) % every; return into < Math.max(w, clock.dt) ? 1 : 0;
|
|
738
|
+
},
|
|
739
|
+
F_RAMP: function (slope, st, end) {
|
|
740
|
+
var t = clock.t; if (t <= st) return 0;
|
|
741
|
+
return slope * (Math.min(t, end == null ? Infinity : end) - st);
|
|
742
|
+
},
|
|
743
|
+
F_RANDOM_UNIFORM: function (lo, hi, sd) { return lo + (hi - lo) * rand(); },
|
|
744
|
+
F_RANDOM_NORMAL: function (lo, hi, mean, sd) {
|
|
745
|
+
var u = rand() || 1e-12, v = rand(), z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
|
|
746
|
+
return Math.min(hi, Math.max(lo, mean + sd * z));
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
Object.keys(F).forEach(function (k) { S[k] = F[k]; });
|
|
750
|
+
Object.keys(m.tables).forEach(function (k) { S[k] = m.tables[k]; });
|
|
751
|
+
var over = {};
|
|
752
|
+
Object.keys(opts.overrides || {}).forEach(function (name) {
|
|
753
|
+
var v = m.byKey[nameKey(name)];
|
|
754
|
+
if (v && isFinite(+opts.overrides[name])) over[v.id] = +opts.overrides[name];
|
|
755
|
+
});
|
|
756
|
+
function ev(c) { return +c.code.evaluate(S); }
|
|
757
|
+
function valOf(v, phase) {
|
|
758
|
+
if (over[v.id] != null) return over[v.id];
|
|
759
|
+
if (phase === 'init' && v.init_ && v.kind === 'aux') return ev(v.init_);
|
|
760
|
+
return ev(v.expr_);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
// start: the control settings first, then everything at the initial time
|
|
764
|
+
var byKey = m.byKey;
|
|
765
|
+
function ctl(key, dflt) { var v = byKey[key]; return v && v.expr_ && !v.expr_.deps.length ? ev(v.expr_) : dflt; }
|
|
766
|
+
var t0 = ctl('initial time', 0);
|
|
767
|
+
S.T_ = t0; clock.t = t0;
|
|
768
|
+
var dt0 = ctl('time step', 1);
|
|
769
|
+
clock.dt = dt0;
|
|
770
|
+
m.initOrder.forEach(function (v) {
|
|
771
|
+
if (v.kind === 'stock') S[v.id] = ev(v.init_);
|
|
772
|
+
else if (v.kind === 'initial') S[v.id] = ev(v.expr_);
|
|
773
|
+
else if (v.kind === 'fixed') {
|
|
774
|
+
var n = Math.max(1, Math.round(ev(v.delay_) / dt0)), i0 = ev(v.init_);
|
|
775
|
+
v.queue = []; for (var q = 0; q < n; q++) v.queue.push(i0);
|
|
776
|
+
S[v.id] = v.queue[0];
|
|
777
|
+
} else S[v.id] = valOf(v, 'init');
|
|
778
|
+
});
|
|
779
|
+
var idOf = function (k) { return byKey[k] && byKey[k].id; };
|
|
780
|
+
var tf = opts.final != null ? +opts.final : (idOf('final time') ? S[idOf('final time')] : 100);
|
|
781
|
+
var dt = opts.dt != null ? +opts.dt : (idOf('time step') ? S[idOf('time step')] : 1);
|
|
782
|
+
var saveper = idOf('saveper') ? S[idOf('saveper')] : dt;
|
|
783
|
+
if (opts.dt != null) saveper = Math.max(saveper, dt);
|
|
784
|
+
if (!(dt > 0)) throw new Error('TIME STEP must be more than 0');
|
|
785
|
+
clock.dt = dt;
|
|
786
|
+
m.control = { initial: t0, final: tf, dt: dt, saveper: saveper };
|
|
787
|
+
|
|
788
|
+
var shown = m.vars.filter(function (v) { return !m.bad[v.id] && (v.kind === 'aux' || v.kind === 'stock'); });
|
|
789
|
+
var res = { time: [], series: {}, names: shown.map(function (v) { return v.name; }), control: m.control };
|
|
790
|
+
shown.forEach(function (v) { res.series[v.name] = []; });
|
|
791
|
+
function record() { res.time.push(+S.T_.toFixed(10)); shown.forEach(function (v) { res.series[v.name].push(S[v.id]); }); }
|
|
792
|
+
|
|
793
|
+
var stocks = m.stocks, aux = m.stepOrder, fixed = m.fixed;
|
|
794
|
+
function auxAt(t) { S.T_ = t; clock.t = t; aux.forEach(function (v) { S[v.id] = valOf(v, 'step'); }); }
|
|
795
|
+
function rates() { return stocks.map(function (v) { return ev(v.rate_); }); }
|
|
796
|
+
|
|
797
|
+
var steps = Math.round((tf - t0) / dt), every = Math.max(1, Math.round(saveper / dt));
|
|
798
|
+
var rk4 = opts.method === 'rk4';
|
|
799
|
+
if (steps > 2e6) throw new Error('too many steps (' + steps + '): make TIME STEP bigger');
|
|
800
|
+
for (var k = 0; k <= steps; k++) {
|
|
801
|
+
var t = t0 + k * dt;
|
|
802
|
+
auxAt(t);
|
|
803
|
+
if (k % every === 0 || k === steps) record();
|
|
804
|
+
if (k === steps) break;
|
|
805
|
+
var x0 = stocks.map(function (v) { return S[v.id]; }), r1 = rates(), fin = fixed.map(function (v) { return ev(v.in_); });
|
|
806
|
+
if (!rk4) {
|
|
807
|
+
stocks.forEach(function (v, j) { S[v.id] = x0[j] + dt * r1[j]; });
|
|
808
|
+
} else {
|
|
809
|
+
var set = function (r, h) { stocks.forEach(function (v, j) { S[v.id] = x0[j] + h * r[j]; }); };
|
|
810
|
+
set(r1, dt / 2); auxAt(t + dt / 2); var r2 = rates();
|
|
811
|
+
set(r2, dt / 2); auxAt(t + dt / 2); var r3 = rates();
|
|
812
|
+
set(r3, dt); auxAt(t + dt); var r4 = rates();
|
|
813
|
+
stocks.forEach(function (v, j) { S[v.id] = x0[j] + dt / 6 * (r1[j] + 2 * r2[j] + 2 * r3[j] + r4[j]); });
|
|
814
|
+
}
|
|
815
|
+
fixed.forEach(function (v, j) { v.queue.push(fin[j]); v.queue.shift(); S[v.id] = v.queue[0]; });
|
|
816
|
+
}
|
|
817
|
+
return res;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
var api = { compile: compile, readEquations: readEquations, parseTable: parseTable, nameKey: nameKey, version: '0.1.0' };
|
|
821
|
+
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
|
822
|
+
else root.RCNSD = api;
|
|
823
|
+
})(typeof window !== 'undefined' ? window : this);
|
|
824
|
+
// END rcn-sd-engine.js
|
|
825
|
+
|
|
826
|
+
// BEGIN rcn-sd-sketch.js — pasted from tools/rcn-sd-sketch.js by build.js. Edit that file, never this block.
|
|
827
|
+
/*
|
|
828
|
+
* rcn-sd-sketch.js — draw a Vensim model's sketch as SVG, put the run's values
|
|
829
|
+
* on it, and light it for a walk.
|
|
830
|
+
*
|
|
831
|
+
* Shared by tools/rcn-sd.html (pasted in by tools/paste-sd-engine.js) and the
|
|
832
|
+
* FedWiki plugin wiki-plugin-rcnsd (copied in by its build.js), so a model
|
|
833
|
+
* looks and walks the same in both. Edit this file, never a pasted copy.
|
|
834
|
+
* Needs tools/rcn-mdl.js (RCNMdl, reads the sketch) and tools/rcn-sd-engine.js
|
|
835
|
+
* (RCNSD, the model) loaded first.
|
|
836
|
+
*
|
|
837
|
+
* var sk = RCNSDSketch.draw(svg, doc, viewIndex, model, { onThing: fn(g, name, node) })
|
|
838
|
+
* sk.bounds {x, y, w, h} of everything drawn, padded
|
|
839
|
+
* sk.values(result, k, look) numbers, stock sparklines and dots at saved time k;
|
|
840
|
+
* look = { color: fn(name) -> css colour, selected: fn(name) -> bool }
|
|
841
|
+
* sk.paint(z, edit) z = RCNSDSketch.litSets(walk, k): lit / half lit / faint; null clears
|
|
842
|
+
* sk.nodes, sk.els what was drawn
|
|
843
|
+
* RCNSDSketch.css the styles; RCNSDSketch.injectCss(document) adds them once
|
|
844
|
+
*
|
|
845
|
+
* Colours come from CSS variables (--fg, --surface, --muted, --accent, --pipe,
|
|
846
|
+
* --arrow, --cloud, --stock-fill, --stock-line, --accent-soft) when a page
|
|
847
|
+
* sets them, and from light defaults when it doesn't (a wiki page).
|
|
848
|
+
*
|
|
849
|
+
* Marc Pierson with Claude Opus 5.5, November 2026. MIT licence.
|
|
850
|
+
*/
|
|
851
|
+
(function (root) {
|
|
852
|
+
'use strict';
|
|
853
|
+
var NS = 'http://www.w3.org/2000/svg';
|
|
854
|
+
|
|
855
|
+
var CSS = [
|
|
856
|
+
'.rcnsd-sketch text{font-family:system-ui,-apple-system,"Segoe UI",sans-serif;fill:var(--fg,#1d2420);stroke:var(--surface,#fff);stroke-width:3.5px;stroke-linejoin:round;paint-order:stroke}',
|
|
857
|
+
'.rcnsd-sketch .v-name{font-size:12px}',
|
|
858
|
+
'.rcnsd-sketch .v-val{font-size:11px;fill:var(--muted,#5d6862);font-variant-numeric:tabular-nums}',
|
|
859
|
+
'.rcnsd-sketch .v{cursor:pointer}',
|
|
860
|
+
'.rcnsd-sketch .v .hit{fill:transparent;stroke:none}',
|
|
861
|
+
'.rcnsd-sketch .v:hover .hit{fill:var(--accent-soft,#e2efe9)}',
|
|
862
|
+
'.rcnsd-sketch .v.sel .v-name{font-weight:700}',
|
|
863
|
+
'.rcnsd-sketch .stock rect.box{fill:var(--stock-fill,#eef4fb);stroke:var(--stock-line,#1f3b5c);stroke-width:1.5}',
|
|
864
|
+
'.rcnsd-sketch .v.sel rect.box{stroke-width:3}',
|
|
865
|
+
'.rcnsd-sketch .spark{fill:none;stroke-width:1.5}',
|
|
866
|
+
'.rcnsd-sketch .spark-dot{stroke:var(--surface,#fff);stroke-width:1.5}',
|
|
867
|
+
'.rcnsd-sketch .pipe-out{fill:none;stroke:var(--pipe,#33414f);stroke-width:6;stroke-linejoin:round}',
|
|
868
|
+
'.rcnsd-sketch .pipe-in{fill:none;stroke:var(--surface,#fff);stroke-width:2.5;stroke-linejoin:round}',
|
|
869
|
+
'.rcnsd-sketch .pipe-head{fill:var(--pipe,#33414f)}',
|
|
870
|
+
'.rcnsd-sketch .valve{fill:var(--surface,#fff);stroke:var(--pipe,#33414f);stroke-width:1.5}',
|
|
871
|
+
'.rcnsd-sketch .conn{fill:none;stroke:var(--arrow,#6b7f95);stroke-width:1.1}',
|
|
872
|
+
'.rcnsd-sketch .conn-head{fill:var(--arrow,#6b7f95)}',
|
|
873
|
+
'.rcnsd-sketch .cloud{fill:var(--surface,#fff);stroke:var(--cloud,#8a97a5);stroke-width:1.3}',
|
|
874
|
+
'.rcnsd-sketch .sign{font-size:12px;font-weight:700;fill:var(--arrow,#6b7f95)}',
|
|
875
|
+
'.rcnsd-sketch .comment{font-size:12px;fill:var(--muted,#5d6862)}',
|
|
876
|
+
'.rcnsd-sketch .shadow .v-name{fill:var(--muted,#5d6862)}',
|
|
877
|
+
'.rcnsd-sketch .w-el,.rcnsd-sketch .v{transition:opacity .35s}',
|
|
878
|
+
'.rcnsd-sketch .v.w-new .v-name{fill:var(--accent,#2f6f5e)}',
|
|
879
|
+
'.rcnsd-sketch .v.w-new rect.box{stroke:var(--accent,#2f6f5e);stroke-width:3}'
|
|
880
|
+
].join('\n');
|
|
881
|
+
function injectCss(doc) {
|
|
882
|
+
doc = doc || document;
|
|
883
|
+
if (doc.getElementById('rcnsd-sketch-css')) return;
|
|
884
|
+
var s = doc.createElement('style'); s.id = 'rcnsd-sketch-css'; s.textContent = CSS;
|
|
885
|
+
(doc.head || doc.documentElement).appendChild(s);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// ── small helpers ──
|
|
889
|
+
function el(tag, attrs, parent) {
|
|
890
|
+
var e = document.createElementNS(NS, tag);
|
|
891
|
+
for (var k in attrs) if (attrs[k] != null) e.setAttribute(k, attrs[k]);
|
|
892
|
+
if (parent) parent.appendChild(e);
|
|
893
|
+
return e;
|
|
894
|
+
}
|
|
895
|
+
function int(s) { var n = parseInt(s, 10); return isFinite(n) ? n : 0; }
|
|
896
|
+
function cleanName(s) {
|
|
897
|
+
s = String(s || '').trim();
|
|
898
|
+
if (s.length > 1 && s[0] === '"' && s[s.length - 1] === '"') s = s.slice(1, -1).replace(/\\"/g, '"');
|
|
899
|
+
return s.replace(/\\n/g, ' ').replace(/_/g, ' ').replace(/\s+/g, ' ').trim();
|
|
900
|
+
}
|
|
901
|
+
function wrap(text, maxW, size) {
|
|
902
|
+
var per = Math.max(4, Math.floor(maxW / (size * 0.55))), words = text.split(' '), lines = [], cur = '';
|
|
903
|
+
words.forEach(function (w) {
|
|
904
|
+
if (!cur) cur = w;
|
|
905
|
+
else if ((cur + ' ' + w).length <= per) cur += ' ' + w;
|
|
906
|
+
else { lines.push(cur); cur = w; }
|
|
907
|
+
});
|
|
908
|
+
if (cur) lines.push(cur);
|
|
909
|
+
return lines;
|
|
910
|
+
}
|
|
911
|
+
function textBlock(parent, lines, x, y, cls, lh) {
|
|
912
|
+
lh = lh || 14;
|
|
913
|
+
var t = el('text', { x: x, y: y - (lines.length - 1) * lh / 2, 'text-anchor': 'middle', 'dominant-baseline': 'middle', class: cls }, parent);
|
|
914
|
+
lines.forEach(function (l, i) { var s = el('tspan', { x: x, dy: i ? lh : 0 }, t); s.textContent = l; });
|
|
915
|
+
return t;
|
|
916
|
+
}
|
|
917
|
+
function pointsOf(f) {
|
|
918
|
+
return (f.slice(13).join(',').match(/\((-?[\d.]+),(-?[\d.]+)\)/g) || []).map(function (p) {
|
|
919
|
+
var m = /\((-?[\d.]+),(-?[\d.]+)\)/.exec(p); return [+m[1], +m[2]];
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
function boxOf(n) {
|
|
923
|
+
if (n.shape === 'stock') return { x: n.x, y: n.y, w: Math.max(n.w, 40), h: Math.max(n.h, 22) };
|
|
924
|
+
if (n.shape === 'valve') return { x: n.x, y: n.y, w: 9, h: 9 };
|
|
925
|
+
if (n.shape === 'cloud') return { x: n.x, y: n.y, w: 17, h: 11 };
|
|
926
|
+
return { x: n.x, y: n.y, w: n.w + 2, h: n.h + 2 };
|
|
927
|
+
}
|
|
928
|
+
function insideBox(p, n) { var b = boxOf(n); return Math.abs(p[0] - b.x) < b.w && Math.abs(p[1] - b.y) < b.h; }
|
|
929
|
+
// where a pipe coming from p meets the edge of n: straight across if p lines up with the box
|
|
930
|
+
function edgePoint(p, n) {
|
|
931
|
+
var b = boxOf(n);
|
|
932
|
+
if (Math.abs(p[0] - b.x) <= b.w) return [p[0], p[1] < b.y ? b.y - b.h : b.y + b.h];
|
|
933
|
+
if (Math.abs(p[1] - b.y) <= b.h) return [p[0] < b.x ? b.x - b.w : b.x + b.w, p[1]];
|
|
934
|
+
var dx = p[0] - b.x, dy = p[1] - b.y, s = Math.min(b.w / Math.abs(dx || 1e-9), b.h / Math.abs(dy || 1e-9));
|
|
935
|
+
return [b.x + dx * s, b.y + dy * s];
|
|
936
|
+
}
|
|
937
|
+
// Vensim keeps one point ON a connector's arc: draw the circle through the three points
|
|
938
|
+
function arcPoints(A, P, B) {
|
|
939
|
+
var ax = A[0], ay = A[1], bx = P[0], by = P[1], cx = B[0], cy = B[1];
|
|
940
|
+
var d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
|
|
941
|
+
if (Math.abs(d) < 1e-6) return [A, B];
|
|
942
|
+
var ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d;
|
|
943
|
+
var uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d;
|
|
944
|
+
var r = Math.hypot(ax - ux, ay - uy);
|
|
945
|
+
if (r > 1e5) return [A, B];
|
|
946
|
+
var t1 = Math.atan2(ay - uy, ax - ux), t2 = Math.atan2(by - uy, bx - ux), t3 = Math.atan2(cy - uy, cx - ux);
|
|
947
|
+
function norm(t) { while (t < 0) t += 2 * Math.PI; while (t >= 2 * Math.PI) t -= 2 * Math.PI; return t; }
|
|
948
|
+
var ccw = norm(t2 - t1) < norm(t3 - t1); // going counter-clockwise from A meets P before B
|
|
949
|
+
var span = ccw ? norm(t3 - t1) : -norm(t1 - t3);
|
|
950
|
+
var out = [], n = 40;
|
|
951
|
+
for (var i = 0; i <= n; i++) { var t = t1 + span * i / n; out.push([ux + r * Math.cos(t), uy + r * Math.sin(t)]); }
|
|
952
|
+
return out;
|
|
953
|
+
}
|
|
954
|
+
function clipTo(line, a, b) {
|
|
955
|
+
var i = 0, j = line.length - 1;
|
|
956
|
+
while (i < j && insideBox(line[i], a)) i++;
|
|
957
|
+
while (j > i && insideBox(line[j], b)) j--;
|
|
958
|
+
return line.slice(i, j + 1);
|
|
959
|
+
}
|
|
960
|
+
function arrowHead(parent, from, to, kind, size) {
|
|
961
|
+
var dx = to[0] - from[0], dy = to[1] - from[1], L = Math.hypot(dx, dy) || 1, ux = dx / L, uy = dy / L;
|
|
962
|
+
var bx = to[0] - ux * size, by = to[1] - uy * size, w = size * 0.5;
|
|
963
|
+
el('path', { d: 'M' + to[0] + ',' + to[1] + ' L' + (bx - uy * w) + ',' + (by + ux * w) + ' L' + (bx + uy * w) + ',' + (by - ux * w) + ' Z',
|
|
964
|
+
class: kind === 'pipe' ? 'pipe-head' : 'conn-head' }, parent);
|
|
965
|
+
}
|
|
966
|
+
function cloud(parent, x, y) {
|
|
967
|
+
var d = 'M' + (x - 14) + ',' + (y + 6) +
|
|
968
|
+
' a6,6 0 0,1 2,-11 a7,7 0 0,1 12,-3 a6,6 0 0,1 10,2 a5,5 0 0,1 3,9 a5,5 0 0,1 -5,6 h-18 a5,5 0 0,1 -4,-3 z';
|
|
969
|
+
return el('path', { d: d, class: 'cloud w-el' }, parent);
|
|
970
|
+
}
|
|
971
|
+
var fmt4 = (typeof Intl !== 'undefined') ? new Intl.NumberFormat(undefined, { maximumSignificantDigits: 4 }) : null;
|
|
972
|
+
function num(v) {
|
|
973
|
+
if (v == null || !isFinite(v)) return v == null ? '' : String(v);
|
|
974
|
+
if (Math.abs(v) >= 1e9 || (Math.abs(v) < 1e-4 && v !== 0)) return v.toExponential(2);
|
|
975
|
+
return fmt4 ? fmt4.format(v) : String(+v.toPrecision(4));
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
// ── draw one view ──
|
|
979
|
+
function draw(svg, doc, vi, model, opts) {
|
|
980
|
+
opts = opts || {};
|
|
981
|
+
var nameKey = root.RCNSD.nameKey;
|
|
982
|
+
svg.innerHTML = '';
|
|
983
|
+
svg.classList.add('rcnsd-sketch');
|
|
984
|
+
var NODES = {}, ELS = [], THINGS = [];
|
|
985
|
+
var gPipes = el('g', {}, svg), gConn = el('g', {}, svg), gNodes = el('g', {}, svg);
|
|
986
|
+
var view = doc && doc.views[vi || 0];
|
|
987
|
+
if (!view) return { nodes: NODES, els: ELS, things: THINGS, bounds: { x: 0, y: 0, w: 400, h: 200 }, values: function () {}, paint: function () {} };
|
|
988
|
+
var recs = view.records;
|
|
989
|
+
// which variable record names each valve, and which records are pipe ends
|
|
990
|
+
var flowOfValve = {}, isFlowWord = {}, pipeEnd = {};
|
|
991
|
+
recs.forEach(function (r, k) {
|
|
992
|
+
if (r.type === 11) {
|
|
993
|
+
for (var j = k + 1; j < Math.min(recs.length, k + 4); j++) {
|
|
994
|
+
var nx = recs[j];
|
|
995
|
+
if (nx.type === 10 && (int(nx.f[7]) & 32)) { flowOfValve[r.f[1]] = nx; isFlowWord[nx.f[1]] = r.f[1]; break; }
|
|
996
|
+
if (nx.type === 11) break;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
if (r.type === 1 && (int(r.f[4]) === 4 || int(r.f[4]) === 100)) pipeEnd[r.f[3]] = true;
|
|
1000
|
+
});
|
|
1001
|
+
var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
1002
|
+
function grow(x, y, w, h) { minX = Math.min(minX, x - w); maxX = Math.max(maxX, x + w); minY = Math.min(minY, y - h); maxY = Math.max(maxY, y + h); }
|
|
1003
|
+
recs.forEach(function (r) {
|
|
1004
|
+
if (r.type !== 10 && r.type !== 11 && r.type !== 12) return;
|
|
1005
|
+
var f = r.f, x = +f[3] || 0, y = +f[4] || 0, w = +f[5] || 20, h = +f[6] || 10;
|
|
1006
|
+
var n = { id: f[1], x: x, y: y, w: w, h: h, type: r.type };
|
|
1007
|
+
if (r.type === 10) {
|
|
1008
|
+
n.name = cleanName(f[2]); n.key = nameKey(f[2]);
|
|
1009
|
+
var v = model && model.byKey[n.key];
|
|
1010
|
+
n.shape = (v && v.kind === 'stock') || pipeEnd[f[1]] ? 'stock' : isFlowWord[f[1]] ? 'flowword' : 'aux';
|
|
1011
|
+
n.shadow = !(int(f[8]) & 1) && n.shape !== 'flowword';
|
|
1012
|
+
} else if (r.type === 11) { n.shape = 'valve'; n.w = 9; n.h = 9; var fw = flowOfValve[f[1]]; if (fw) { n.key = nameKey(fw.f[2]); n.name = cleanName(fw.f[2]); } }
|
|
1013
|
+
else if (cleanName(f[2]) === '48') { n.shape = 'cloud'; n.w = 16; n.h = 10; }
|
|
1014
|
+
else if (r.text && r.text.trim()) { n.shape = 'comment'; n.text = r.text.replace(/\\n/g, ' ').trim(); }
|
|
1015
|
+
else return;
|
|
1016
|
+
NODES[f[1]] = n; grow(n.x, n.y, Math.max(n.w, 20), Math.max(n.h, 12) + 14);
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
// pipes first, so stocks and valves sit on top of them
|
|
1020
|
+
recs.forEach(function (r) {
|
|
1021
|
+
if (r.type !== 1) return;
|
|
1022
|
+
var f = r.f, shape = int(f[4]);
|
|
1023
|
+
if (shape !== 4 && shape !== 100) return;
|
|
1024
|
+
var a = NODES[f[2]], b = NODES[f[3]];
|
|
1025
|
+
if (!a || !b) return;
|
|
1026
|
+
var pts = pointsOf(f).filter(function (p) { return !(p[0] === 0 && p[1] === 0); });
|
|
1027
|
+
var path = [[a.x, a.y]].concat(pts);
|
|
1028
|
+
var last = path[path.length - 1], end = edgePoint(last, b);
|
|
1029
|
+
// if the last stored point sits inside the box, aim from the one before it
|
|
1030
|
+
if (insideBox(last, b) && path.length > 1) { path.pop(); end = edgePoint(path[path.length - 1], b); }
|
|
1031
|
+
path.push(end);
|
|
1032
|
+
var d = 'M' + path.map(function (p) { return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' L');
|
|
1033
|
+
var gp = el('g', { class: 'w-el' }, gPipes);
|
|
1034
|
+
el('path', { d: d, class: 'pipe-out' }, gp);
|
|
1035
|
+
el('path', { d: d, class: 'pipe-in' }, gp);
|
|
1036
|
+
if (shape === 4) arrowHead(gp, path[path.length - 2], end, 'pipe', 11);
|
|
1037
|
+
ELS.push({ el: gp, kind: 'pipe', a: a, b: b });
|
|
1038
|
+
});
|
|
1039
|
+
|
|
1040
|
+
// connectors
|
|
1041
|
+
recs.forEach(function (r) {
|
|
1042
|
+
if (r.type !== 1) return;
|
|
1043
|
+
var f = r.f, shape = int(f[4]);
|
|
1044
|
+
if (shape === 4 || shape === 100) return;
|
|
1045
|
+
var a = NODES[f[2]], b = NODES[f[3]];
|
|
1046
|
+
if (!a || !b || a === b) return;
|
|
1047
|
+
var A = [a.x, a.y], B = [b.x, b.y];
|
|
1048
|
+
var p = pointsOf(f)[0];
|
|
1049
|
+
var line = (p && !(p[0] === 0 && p[1] === 0)) ? arcPoints(A, p, B) : [A, B];
|
|
1050
|
+
if (line.length === 2) line = [A, [(A[0] + B[0]) / 2, (A[1] + B[1]) / 2], B];
|
|
1051
|
+
line = clipTo(line, a, b);
|
|
1052
|
+
if (line.length < 2) return;
|
|
1053
|
+
var gc = el('g', { class: 'w-el' }, gConn);
|
|
1054
|
+
ELS.push({ el: gc, kind: 'conn', a: a, b: b });
|
|
1055
|
+
el('path', { d: 'M' + line.map(function (q) { return q[0].toFixed(1) + ',' + q[1].toFixed(1); }).join(' L'), class: 'conn' }, gc);
|
|
1056
|
+
arrowHead(gc, line[line.length - 2], line[line.length - 1], 'conn', 7);
|
|
1057
|
+
var pol = int(f[6]), sign = { 43: '+', 45: '−', 83: '+', 79: '−', 63: '?' }[pol];
|
|
1058
|
+
if (sign) {
|
|
1059
|
+
var e = line[line.length - 1], pr = line[Math.max(0, line.length - 4)];
|
|
1060
|
+
var dx = e[0] - pr[0], dy = e[1] - pr[1], L = Math.hypot(dx, dy) || 1;
|
|
1061
|
+
var t = el('text', { x: e[0] - dx / L * 12 - dy / L * 9, y: e[1] - dy / L * 12 + dx / L * 9, 'text-anchor': 'middle', 'dominant-baseline': 'middle', class: 'sign' }, gc);
|
|
1062
|
+
t.textContent = sign;
|
|
1063
|
+
}
|
|
1064
|
+
});
|
|
1065
|
+
|
|
1066
|
+
// the things themselves
|
|
1067
|
+
function thing(parent, n) {
|
|
1068
|
+
var v = model && model.byKey[n.key];
|
|
1069
|
+
var name = v ? v.name : n.name;
|
|
1070
|
+
var g = el('g', { class: 'v ' + n.shape + (n.shadow ? ' shadow' : ''), 'data-name': name, tabindex: 0 }, parent);
|
|
1071
|
+
g.__name = name; g.__node = n;
|
|
1072
|
+
if (n.shape === 'stock') {
|
|
1073
|
+
var w = Math.max(n.w, 40), h = Math.max(n.h, 22);
|
|
1074
|
+
el('rect', { x: n.x - w, y: n.y - h, width: 2 * w, height: 2 * h, rx: 2, class: 'box' }, g);
|
|
1075
|
+
var lines = wrap(name, 2 * w - 8, 12);
|
|
1076
|
+
textBlock(g, lines, n.x, n.y - h + 6 + lines.length * 7, 'v-name');
|
|
1077
|
+
g.__spark = el('polyline', { class: 'spark', points: '' }, g);
|
|
1078
|
+
g.__spark.__box = { x: n.x - w + 6, y: n.y + h - 22, w: 2 * w - 12, h: 15 };
|
|
1079
|
+
g.__dot = el('circle', { class: 'spark-dot', r: 0 }, g);
|
|
1080
|
+
g.__val = el('text', { x: n.x + w - 4, y: n.y + h + 12, 'text-anchor': 'end', class: 'v-val' }, g);
|
|
1081
|
+
} else {
|
|
1082
|
+
var label = n.shadow ? '<' + name + '>' : name;
|
|
1083
|
+
var ls = wrap(label, Math.max(2 * n.w, 70), 12);
|
|
1084
|
+
el('rect', { class: 'hit', x: n.x - n.w - 4, y: n.y - n.h - 3, width: 2 * n.w + 8, height: 2 * n.h + 18, rx: 4 }, g);
|
|
1085
|
+
textBlock(g, ls, n.x, n.y, 'v-name');
|
|
1086
|
+
g.__val = el('text', { x: n.x, y: n.y + ls.length * 7 + 7, 'text-anchor': 'middle', class: 'v-val' }, g);
|
|
1087
|
+
}
|
|
1088
|
+
THINGS.push(g);
|
|
1089
|
+
if (opts.onThing) opts.onThing(g, name, n);
|
|
1090
|
+
return g;
|
|
1091
|
+
}
|
|
1092
|
+
Object.keys(NODES).forEach(function (id) {
|
|
1093
|
+
var n = NODES[id];
|
|
1094
|
+
if (n.shape === 'cloud') { ELS.push({ el: cloud(gNodes, n.x, n.y), kind: 'cloud', n: n }); return; }
|
|
1095
|
+
if (n.shape === 'comment') { ELS.push({ el: textBlock(gNodes, wrap(n.text, n.w * 2, 12), n.x, n.y, 'comment'), kind: 'comment', n: n }); return; }
|
|
1096
|
+
if (n.shape === 'valve') {
|
|
1097
|
+
var gv = el('g', { class: 'w-el' }, gNodes);
|
|
1098
|
+
el('path', { d: 'M' + (n.x - 7) + ',' + (n.y - 8) + ' L' + (n.x + 7) + ',' + (n.y + 8) + ' L' + (n.x + 7) + ',' + (n.y - 8) + ' L' + (n.x - 7) + ',' + (n.y + 8) + ' Z', class: 'valve' }, gv);
|
|
1099
|
+
ELS.push({ el: gv, kind: 'valve', n: n });
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
if (n.shape === 'flowword' || n.shape === 'aux' || n.shape === 'stock') ELS.push({ el: thing(gNodes, n), kind: 'thing', n: n });
|
|
1103
|
+
});
|
|
1104
|
+
|
|
1105
|
+
if (!isFinite(minX)) { minX = 0; minY = 0; maxX = 400; maxY = 300; }
|
|
1106
|
+
var pad = 30;
|
|
1107
|
+
var bounds = { x: minX - pad, y: minY - pad, w: maxX - minX + 2 * pad, h: maxY - minY + 2 * pad };
|
|
1108
|
+
|
|
1109
|
+
// numbers, sparklines and dots at saved time k
|
|
1110
|
+
function values(result, k, look) {
|
|
1111
|
+
look = look || {};
|
|
1112
|
+
THINGS.forEach(function (g) {
|
|
1113
|
+
var name = g.__name, s = result && result.series[name];
|
|
1114
|
+
var sel = look.selected ? look.selected(name) : false;
|
|
1115
|
+
g.classList.toggle('sel', !!sel);
|
|
1116
|
+
if (g.__val) g.__val.textContent = s ? num(s[k]) : '';
|
|
1117
|
+
if (!g.__spark) return;
|
|
1118
|
+
var b = g.__spark.__box, color = look.color ? look.color(name, sel) : '#5d6862';
|
|
1119
|
+
if (!s || !s.length) { g.__spark.setAttribute('points', ''); g.__dot.setAttribute('r', 0); return; }
|
|
1120
|
+
var lo = Infinity, hi = -Infinity;
|
|
1121
|
+
for (var i = 0; i < s.length; i++) { if (s[i] < lo) lo = s[i]; if (s[i] > hi) hi = s[i]; }
|
|
1122
|
+
var span = hi - lo || 1;
|
|
1123
|
+
var X = function (j) { return b.x + b.w * j / Math.max(1, s.length - 1); };
|
|
1124
|
+
var Y = function (v) { return b.y + b.h - b.h * (v - lo) / span; };
|
|
1125
|
+
g.__spark.setAttribute('points', s.map(function (v, j) { return X(j).toFixed(1) + ',' + Y(v).toFixed(1); }).join(' '));
|
|
1126
|
+
g.__spark.setAttribute('stroke', color);
|
|
1127
|
+
g.__dot.setAttribute('cx', X(k)); g.__dot.setAttribute('cy', Y(s[k])); g.__dot.setAttribute('r', 3); g.__dot.setAttribute('fill', color);
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// a walk's lighting: 2 lit, 1 half lit (seen at an earlier step), 0 faint
|
|
1132
|
+
function paint(z, edit) {
|
|
1133
|
+
ELS.forEach(function (e) { e.el.style.opacity = ''; if (e.el.classList) e.el.classList.remove('w-new'); });
|
|
1134
|
+
if (!z) return;
|
|
1135
|
+
var op = edit ? { 2: 1, 1: 0.45, 0: 0.22 } : { 2: 1, 1: 0.38, 0: 0.09 };
|
|
1136
|
+
function ks(k) { return z.all ? 2 : !k ? 0 : z.lit[k] ? 2 : z.seen[k] ? 1 : 0; }
|
|
1137
|
+
var cloudState = {};
|
|
1138
|
+
function ns(n) { return n.shape === 'cloud' ? (cloudState[n.id] || 0) : n.shape === 'comment' ? (z.all ? 2 : 0) : ks(n.key); }
|
|
1139
|
+
ELS.forEach(function (e) {
|
|
1140
|
+
if (e.kind !== 'pipe') return;
|
|
1141
|
+
var va = ks(e.a.key);
|
|
1142
|
+
e.state = e.b.shape === 'cloud' ? va : Math.min(va, ns(e.b));
|
|
1143
|
+
if (e.b.shape === 'cloud') cloudState[e.b.id] = Math.max(cloudState[e.b.id] || 0, va);
|
|
1144
|
+
if (e.a.shape === 'cloud') cloudState[e.a.id] = Math.max(cloudState[e.a.id] || 0, ks(e.b.key));
|
|
1145
|
+
});
|
|
1146
|
+
ELS.forEach(function (e) {
|
|
1147
|
+
var st = e.kind === 'pipe' ? e.state : e.kind === 'conn' ? Math.min(ns(e.a), ns(e.b)) : ns(e.n);
|
|
1148
|
+
e.el.style.opacity = op[st];
|
|
1149
|
+
if (e.kind === 'thing' && !z.all && z.fresh[e.n.key]) e.el.classList.add('w-new');
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
function isFlow(name) {
|
|
1154
|
+
var key = nameKey(name);
|
|
1155
|
+
return Object.keys(NODES).some(function (id) { return NODES[id].shape === 'valve' && NODES[id].key === key; });
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
return { nodes: NODES, els: ELS, things: THINGS, bounds: bounds, values: values, paint: paint, isFlow: isFlow };
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
// which names a walk lights at step k: this step's names lit, earlier steps' names
|
|
1162
|
+
// half lit ("seen"), names lit for the first time "fresh"; an all-step lights everything
|
|
1163
|
+
// and never counts as seen
|
|
1164
|
+
function litSets(walk, k) {
|
|
1165
|
+
if (!walk) return null;
|
|
1166
|
+
var nameKey = root.RCNSD.nameKey, lit = {}, seen = {}, fresh = {};
|
|
1167
|
+
walk.steps.forEach(function (st, i) {
|
|
1168
|
+
if (i > k || st.all) return;
|
|
1169
|
+
(st.names || []).forEach(function (n) { (i === k ? lit : seen)[nameKey(n)] = true; });
|
|
1170
|
+
});
|
|
1171
|
+
Object.keys(lit).forEach(function (key) { if (!seen[key]) fresh[key] = true; });
|
|
1172
|
+
var cur = walk.steps[k];
|
|
1173
|
+
return { lit: lit, seen: seen, fresh: fresh, all: !!(cur && cur.all) };
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
var api = { draw: draw, litSets: litSets, css: CSS, injectCss: injectCss, num: num, version: '0.1.0' };
|
|
1177
|
+
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
|
1178
|
+
else root.RCNSDSketch = api;
|
|
1179
|
+
})(typeof window !== 'undefined' ? window : this);
|
|
1180
|
+
// END rcn-sd-sketch.js
|
|
1181
|
+
|
|
1182
|
+
const RCNSD = window.RCNSD, RCNMdl = window.RCNMdl, Sketch = window.RCNSDSketch
|
|
1183
|
+
|
|
1184
|
+
// Local wikis (localhost and *.localhost farm sites) get the working copy off the
|
|
1185
|
+
// sofi-proxy static server; everything else the shared copy beside the Graph Tool.
|
|
1186
|
+
const LOCAL = /(^|\.)localhost$/.test(window.location.hostname)
|
|
1187
|
+
const TOOL_URL = LOCAL
|
|
1188
|
+
? 'http://localhost:8765/tools/rcn-sd.html'
|
|
1189
|
+
: 'https://marc.relocalizecreativity.net/assets/Drag/rcn-sd.html'
|
|
1190
|
+
const MATH_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjs/12.4.2/math.min.js'
|
|
1191
|
+
const COLORS = ['#2a78d6', '#eb6834', '#1baf7a', '#eda100', '#e87ba4', '#008300', '#6250d6', '#e34948']
|
|
1192
|
+
|
|
1193
|
+
// ── the words a reader sees ──
|
|
1194
|
+
const W = {
|
|
1195
|
+
title: 'RCN System Dynamics',
|
|
1196
|
+
empty: 'A stock-and-flow model that runs on the page.',
|
|
1197
|
+
emptyHow: 'Drop a Vensim <b>.mdl</b> file here, or open the tool and save a model back with <b>→ Save to wiki item</b>.',
|
|
1198
|
+
open: 'Open RCN System Dynamics ↗',
|
|
1199
|
+
edit: 'Edit in RCN System Dynamics ↗',
|
|
1200
|
+
loading: 'Loading the model…',
|
|
1201
|
+
noMath: 'The model could not run: math.js did not load (it comes from cdnjs.cloudflare.com).',
|
|
1202
|
+
cannotRun: 'This model cannot run yet: ',
|
|
1203
|
+
at: 'Show the numbers at',
|
|
1204
|
+
hint: 'Click a name to graph it. Hover for its equation. Drag to move the drawing; + and − zoom.',
|
|
1205
|
+
zoomIn: 'Zoom in', zoomOut: 'Zoom out', zoomFit: 'Show the whole drawing', fit: 'Fit',
|
|
1206
|
+
walk: '▶ Walk',
|
|
1207
|
+
play: '▶', pause: '❚❚', prev: '◀', next: '▶|', close: '✕',
|
|
1208
|
+
voiceOn: '🔈', voiceOff: '🔇',
|
|
1209
|
+
count: (k, n) => 'Step ' + (k + 1) + ' of ' + n,
|
|
1210
|
+
ask: 'A question for the group',
|
|
1211
|
+
keys: 'Space plays · ← → step · Esc stops',
|
|
1212
|
+
end: 'End of the walk. ← to go back, Esc to stop.',
|
|
1213
|
+
over: 'Over to you. Press Space or ▶ to go on.',
|
|
1214
|
+
dropped: name => 'Opened ' + name + ' into this item.',
|
|
1215
|
+
walksAdded: n => n + ' walk' + (n === 1 ? '' : 's') + ' added to this item.',
|
|
1216
|
+
notMdl: 'That isn\'t a Vensim .mdl file or a walks file.',
|
|
1217
|
+
savedBack: 'Saved from RCN System Dynamics.',
|
|
1218
|
+
// writing walks on the page (the page's owner only)
|
|
1219
|
+
newWalk: '+ New walk',
|
|
1220
|
+
newWalkName: c => 'A walk through ' + c,
|
|
1221
|
+
editWalk: '✎ Edit walk',
|
|
1222
|
+
doneEdit: '✓ Done (save to page)',
|
|
1223
|
+
weSay: 'What to say at this step',
|
|
1224
|
+
weHow: 'Click names in the drawing to put them on the graph, then press "Light the names on the graph". Move the slider before "Show this time" or "Play the run up to this time".',
|
|
1225
|
+
weLight: 'Light the names on the graph',
|
|
1226
|
+
weAll: 'Light everything',
|
|
1227
|
+
weGraphs: 'Keep these graphs',
|
|
1228
|
+
weTime: 'Show this time',
|
|
1229
|
+
weRun: 'Play the run up to this time',
|
|
1230
|
+
weAsk: 'A question for the group',
|
|
1231
|
+
weAdd: '+ Step after this',
|
|
1232
|
+
weDel: 'Delete this step',
|
|
1233
|
+
weUp: '↑', weDown: '↓',
|
|
1234
|
+
weName: 'Walk name',
|
|
1235
|
+
weDelWalk: 'Delete this walk',
|
|
1236
|
+
weDelSure: 'Click "Delete this walk" again within 4 seconds to delete the whole walk.',
|
|
1237
|
+
weSaved: 'Saved to the page.',
|
|
1238
|
+
weSum: (lit, extra) => 'This step lights ' + lit + '.' + extra,
|
|
1239
|
+
weAllLit: 'everything',
|
|
1240
|
+
weNone: 'nothing yet',
|
|
1241
|
+
weTimeSum: t => ' Shows ' + t + '.',
|
|
1242
|
+
weRunSum: t => ' Plays the run to ' + t + '.',
|
|
1243
|
+
weGraphSum: g => ' Graphs ' + g + '.'
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
// ── math.js, once per page ──
|
|
1247
|
+
let mathP = null
|
|
1248
|
+
function needMath () {
|
|
1249
|
+
if (window.math) return Promise.resolve()
|
|
1250
|
+
if (!mathP) mathP = new Promise((resolve, reject) => {
|
|
1251
|
+
const s = document.createElement('script')
|
|
1252
|
+
s.src = MATH_URL; s.onload = resolve
|
|
1253
|
+
s.onerror = () => { mathP = null; reject(new Error('math.js did not load')) }
|
|
1254
|
+
document.head.appendChild(s)
|
|
1255
|
+
})
|
|
1256
|
+
return mathP
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
function esc (s) { return String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])) }
|
|
1260
|
+
const num = v => Sketch.num(v)
|
|
1261
|
+
const unitsOf = (model, name) => { const v = model.byKey[RCNSD.nameKey(name)]; return v && v.units ? v.units.replace(/\s*\[.*$/, '').trim() : '' }
|
|
1262
|
+
|
|
1263
|
+
// ── the item's text: a caption, then the model in words (for search, and for a
|
|
1264
|
+
// wiki without this plugin) ──
|
|
1265
|
+
function describe (item) {
|
|
1266
|
+
const caption = String(item.text || '').split('\n')[0].trim() || (item.fileName || 'Model').replace(/\.mdl$/i, '')
|
|
1267
|
+
if (!item.mdl) return caption
|
|
1268
|
+
let vars = []
|
|
1269
|
+
try { vars = RCNSD.readEquations(item.mdl).vars } catch (e) {}
|
|
1270
|
+
const stocks = vars.filter(v => v.kind === 'stock')
|
|
1271
|
+
const flows = new Set()
|
|
1272
|
+
stocks.forEach(s => String(s.rate || '').split(/[+\-]/).forEach(p => {
|
|
1273
|
+
const k = RCNSD.nameKey(p.trim()); const v = vars.find(x => x.key === k); if (v && v.kind === 'aux') flows.add(v.name)
|
|
1274
|
+
}))
|
|
1275
|
+
const lines = [caption]
|
|
1276
|
+
if (stocks.length) lines.push('Stocks: ' + stocks.map(v => v.name).join(', ') + '.')
|
|
1277
|
+
if (flows.size) lines.push('Flows: ' + [...flows].join(', ') + '.')
|
|
1278
|
+
if (item.walks && item.walks.length) lines.push('Walks: ' + item.walks.map(w => w.name).join('; ') + '.')
|
|
1279
|
+
return lines.join('\n')
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
// ── drawing ──
|
|
1283
|
+
function emit ($item, item) {
|
|
1284
|
+
$item.empty()
|
|
1285
|
+
if (!item.mdl) {
|
|
1286
|
+
$item.append(`
|
|
1287
|
+
<div class="rcnsd-empty" style="background:#eee;padding:15px;text-align:center;border:2px dashed transparent">
|
|
1288
|
+
<p style="font-weight:bold;margin:0 0 6px">${W.title}</p>
|
|
1289
|
+
<p style="color:#666;font-size:.85em;margin:0 0 4px">${W.empty}</p>
|
|
1290
|
+
<p style="color:#666;font-size:.85em;margin:0 0 12px">${W.emptyHow}</p>
|
|
1291
|
+
<button class="rcnsd-open" style="cursor:pointer">${W.open}</button>
|
|
1292
|
+
<div class="rcnsd-msg" style="font-size:12px;color:#92400e;padding-top:6px"></div>
|
|
1293
|
+
</div>`)
|
|
1294
|
+
return
|
|
1295
|
+
}
|
|
1296
|
+
const caption = String(item.text || '').split('\n')[0].trim()
|
|
1297
|
+
$item.append(`
|
|
1298
|
+
<div class="rcnsd" style="background:#f5f5f5;padding:8px">
|
|
1299
|
+
${caption ? `<div style="font-weight:600;font-size:14px;margin:0 0 4px">${esc(caption)}</div>` : ''}
|
|
1300
|
+
<div class="rcnsd-box" style="border:1px solid #ddd;background:#fff;position:relative">
|
|
1301
|
+
<svg class="rcnsd-svg" style="width:100%;height:300px;display:block" role="img" aria-label="Stock and flow drawing"></svg>
|
|
1302
|
+
<div class="rcnsd-status" style="position:absolute;left:8px;top:6px;font-size:12px;color:#64748b">${W.loading}</div>
|
|
1303
|
+
<div style="position:absolute;right:6px;top:6px;display:flex;gap:3px">
|
|
1304
|
+
<button class="rcnsd-zin" title="${W.zoomIn}" style="cursor:pointer;width:26px">+</button>
|
|
1305
|
+
<button class="rcnsd-zout" title="${W.zoomOut}" style="cursor:pointer;width:26px">−</button>
|
|
1306
|
+
<button class="rcnsd-zfit" title="${W.zoomFit}" style="cursor:pointer">${W.fit}</button>
|
|
1307
|
+
</div>
|
|
1308
|
+
</div>
|
|
1309
|
+
<div class="rcnsd-scrub" style="display:flex;gap:8px;align-items:center;font-size:12px;color:#475569;padding:6px 2px 0">
|
|
1310
|
+
<span>${W.at}</span><input type="range" class="rcnsd-range" min="0" max="0" value="0" style="flex:1"><b class="rcnsd-time" style="min-width:64px;text-align:right"></b>
|
|
1311
|
+
</div>
|
|
1312
|
+
<div class="rcnsd-info" style="font-size:12px;color:#475569;min-height:1.4em;padding:2px 2px 0">${W.hint}</div>
|
|
1313
|
+
<div class="rcnsd-charts"></div>
|
|
1314
|
+
<div class="rcnsd-walkbar" tabindex="0" style="outline:none"></div>
|
|
1315
|
+
<div style="padding:6px 0 0;display:flex;gap:6px;justify-content:center">
|
|
1316
|
+
<button class="rcnsd-edit" style="cursor:pointer">${W.edit}</button>
|
|
1317
|
+
</div>
|
|
1318
|
+
<div class="rcnsd-msg" style="font-size:12px;color:#92400e;padding-top:4px"></div>
|
|
1319
|
+
</div>`)
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// ── a little line graph, one per kind of unit (never two scales on one graph) ──
|
|
1323
|
+
function charts ($item, st) {
|
|
1324
|
+
const box = $item.find('.rcnsd-charts')[0]
|
|
1325
|
+
if (!box) return
|
|
1326
|
+
const r = st.result, names = st.selected.filter(n => r && r.series[n])
|
|
1327
|
+
if (!names.length) { box.innerHTML = ''; return }
|
|
1328
|
+
const groups = []
|
|
1329
|
+
names.forEach(n => { const u = unitsOf(st.model, n); let g = groups.find(x => x.u === u); if (!g) groups.push(g = { u, names: [] }); g.names.push(n) })
|
|
1330
|
+
const Wd = 560, H = 120, L = 46, R = 120, T = 8, B = 20
|
|
1331
|
+
box.innerHTML = groups.map(g => {
|
|
1332
|
+
let lo = Infinity, hi = -Infinity
|
|
1333
|
+
g.names.forEach(n => r.series[n].forEach(v => { if (isFinite(v)) { lo = Math.min(lo, v); hi = Math.max(hi, v) } }))
|
|
1334
|
+
if (lo > 0 && lo < hi * 0.5) lo = 0
|
|
1335
|
+
if (hi === lo) { hi = lo + 1 }
|
|
1336
|
+
const t0 = r.time[0], t1 = r.time[r.time.length - 1] || 1
|
|
1337
|
+
const X = t => L + (Wd - L - R) * (t - t0) / ((t1 - t0) || 1), Y = v => T + (H - T - B) * (1 - (v - lo) / (hi - lo))
|
|
1338
|
+
// name each line at its right-hand end, nudged apart so the names don't overlap
|
|
1339
|
+
const ends = g.names.map(n => ({ n, y: Y(r.series[n][r.series[n].length - 1]) + 4 })).sort((a, b) => a.y - b.y)
|
|
1340
|
+
for (let i = 1; i < ends.length; i++) if (ends[i].y - ends[i - 1].y < 11) ends[i].y = ends[i - 1].y + 11
|
|
1341
|
+
const lines = g.names.map(n => {
|
|
1342
|
+
const c = COLORS[st.colorOf[n] || 0]
|
|
1343
|
+
const pts = r.series[n].map((v, k) => X(r.time[k]).toFixed(1) + ',' + Y(v).toFixed(1)).join(' ')
|
|
1344
|
+
const y = ends.find(e => e.n === n).y
|
|
1345
|
+
return `<polyline points="${pts}" fill="none" stroke="${c}" stroke-width="2"/>` +
|
|
1346
|
+
`<text x="${X(t1) + 5}" y="${y}" font-size="10" fill="#1d2420">${esc(n.length > 18 ? n.slice(0, 17) + '…' : n)}</text>`
|
|
1347
|
+
}).join('')
|
|
1348
|
+
const xt = X(r.time[st.k])
|
|
1349
|
+
return `<div style="font-size:11px;color:#64748b;margin:6px 0 0">${esc(g.u || '')}</div>
|
|
1350
|
+
<svg viewBox="0 0 ${Wd} ${H}" style="width:100%;height:auto;display:block;background:#fff;border:1px solid #e5e7eb">
|
|
1351
|
+
<line x1="${L}" y1="${H - B}" x2="${Wd - R}" y2="${H - B}" stroke="#d8ded9"/>
|
|
1352
|
+
<text x="${L - 4}" y="${T + 8}" font-size="10" fill="#64748b" text-anchor="end">${esc(num(hi))}</text>
|
|
1353
|
+
<text x="${L - 4}" y="${H - B}" font-size="10" fill="#64748b" text-anchor="end">${esc(num(lo))}</text>
|
|
1354
|
+
<text x="${L}" y="${H - 6}" font-size="10" fill="#64748b">${esc(num(t0))}</text>
|
|
1355
|
+
<text x="${Wd - R}" y="${H - 6}" font-size="10" fill="#64748b" text-anchor="end">${esc(num(t1))} ${esc(st.timeUnit)}</text>
|
|
1356
|
+
<line x1="${xt}" y1="${T}" x2="${xt}" y2="${H - B}" stroke="#94a3b8" stroke-dasharray="3 3"/>
|
|
1357
|
+
${lines}
|
|
1358
|
+
</svg>`
|
|
1359
|
+
}).join('')
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
// ── bind: run the model, wire the drawing, the walk and the editor ──
|
|
1363
|
+
let popup = null, pendingItem = null, pending$item = null
|
|
1364
|
+
|
|
1365
|
+
function openTool ($item, item) {
|
|
1366
|
+
pendingItem = item; pending$item = $item
|
|
1367
|
+
popup = window.open(item.tool || TOOL_URL, 'rcnsd', 'popup,height=860,width=1440')
|
|
1368
|
+
if (popup) try { popup.focus() } catch (e) {}
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
function save ($item, item) {
|
|
1372
|
+
item.text = describe(item)
|
|
1373
|
+
wiki.pageHandler.put($item.parents('.page:first'), { type: 'edit', id: item.id, item })
|
|
1374
|
+
emit($item, item); bind($item, item)
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
function canEdit ($item) {
|
|
1378
|
+
if (!window.isOwner) return false
|
|
1379
|
+
const $p = $item.parents('.page:first')
|
|
1380
|
+
return !$p.hasClass('remote') && !$p.hasClass('ghost')
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
function bind ($item, item) {
|
|
1384
|
+
$item.off('.rcnsd')
|
|
1385
|
+
$item.on('click.rcnsd', '.rcnsd-open, .rcnsd-edit', e => { e.stopPropagation(); openTool($item, item) })
|
|
1386
|
+
$item.on('dblclick.rcnsd', e => {
|
|
1387
|
+
if ($(e.target).closest('.rcnsd-box, .rcnsd-walkbar, .rcnsd-scrub, .rcnsd-charts').length) return
|
|
1388
|
+
wiki.textEditor($item, item)
|
|
1389
|
+
})
|
|
1390
|
+
// Drop a .mdl into an empty item, or a walks file onto a full one.
|
|
1391
|
+
$item.on('dragover.rcnsd', e => { e.preventDefault(); e.stopPropagation(); $item.find('.rcnsd-empty').css('border-color', '#2f6f5e') })
|
|
1392
|
+
$item.on('dragleave.rcnsd', () => $item.find('.rcnsd-empty').css('border-color', 'transparent'))
|
|
1393
|
+
$item.on('drop.rcnsd', e => {
|
|
1394
|
+
const dt = e.originalEvent && e.originalEvent.dataTransfer, f = dt && dt.files && dt.files[0]
|
|
1395
|
+
if (!f) return
|
|
1396
|
+
e.preventDefault(); e.stopPropagation()
|
|
1397
|
+
$item.find('.rcnsd-empty').css('border-color', 'transparent')
|
|
1398
|
+
if (!canEdit($item)) return
|
|
1399
|
+
const rd = new FileReader()
|
|
1400
|
+
rd.onload = () => {
|
|
1401
|
+
const text = String(rd.result)
|
|
1402
|
+
const msg = m => $item.find('.rcnsd-msg').text(m)
|
|
1403
|
+
if (/\.mdl$/i.test(f.name) || /\\\\\\---\/\/\//.test(text)) {
|
|
1404
|
+
if (item.mdl) { msg('This item already holds a model. Open it in the tool to replace it.'); return }
|
|
1405
|
+
item.mdl = text; item.fileName = f.name; item.walks = item.walks || []
|
|
1406
|
+
save($item, item); $item.find('.rcnsd-msg').text(W.dropped(f.name))
|
|
1407
|
+
} else {
|
|
1408
|
+
try {
|
|
1409
|
+
const d = JSON.parse(text), ws = d.walks || (Array.isArray(d) ? d : null)
|
|
1410
|
+
if (!ws || !item.mdl) throw new Error()
|
|
1411
|
+
item.walks = (item.walks || []).concat(ws)
|
|
1412
|
+
save($item, item); $item.find('.rcnsd-msg').text(W.walksAdded(ws.length))
|
|
1413
|
+
} catch (err) { msg(W.notMdl) }
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
rd.readAsText(f)
|
|
1417
|
+
})
|
|
1418
|
+
if (!item.mdl) return
|
|
1419
|
+
|
|
1420
|
+
const svg = $item.find('.rcnsd-svg')[0]
|
|
1421
|
+
const st = { model: null, doc: null, sk: null, result: null, k: 0, selected: [], colorOf: {}, timeUnit: 'Time', base: item.settings || {}, over: {}, final: null }
|
|
1422
|
+
const status = t => $item.find('.rcnsd-status').text(t || '')
|
|
1423
|
+
|
|
1424
|
+
needMath().then(() => {
|
|
1425
|
+
st.model = RCNSD.compile(item.mdl)
|
|
1426
|
+
try { st.doc = RCNMdl.read(item.mdl, item.fileName) } catch (e) { st.doc = null }
|
|
1427
|
+
const ts = st.model.byKey['time step']
|
|
1428
|
+
st.timeUnit = ts && ts.units ? ts.units.replace(/\[.*$/, '').trim() : 'Time'
|
|
1429
|
+
st.over = Object.assign({}, st.base.overrides || {})
|
|
1430
|
+
st.final = st.base.final
|
|
1431
|
+
run()
|
|
1432
|
+
st.k = st.result ? st.result.time.length - 1 : 0
|
|
1433
|
+
const want = Array.isArray(st.base.graph) ? st.base.graph : st.model.vars.filter(v => v.kind === 'stock' && !st.model.bad[v.id]).slice(0, 4).map(v => v.name)
|
|
1434
|
+
want.forEach(n => pick(n, true))
|
|
1435
|
+
draw()
|
|
1436
|
+
status(st.model.runnable ? '' : W.cannotRun + st.model.problems.map(p => (p.name ? p.name + ': ' : '') + p.what).join('; '))
|
|
1437
|
+
if (!st.model.runnable) $item.find('.rcnsd-status').css({ position: 'static', padding: '6px 8px', color: '#92400e' })
|
|
1438
|
+
}).catch(err => { status(W.noMath); if (wiki.debug) console.log('rcnsd', err) })
|
|
1439
|
+
|
|
1440
|
+
function run () {
|
|
1441
|
+
if (!st.model || !st.model.runnable) { st.result = null; return }
|
|
1442
|
+
const opts = { method: st.base.method || 'euler', overrides: st.over }
|
|
1443
|
+
if (st.final != null) opts.final = st.final
|
|
1444
|
+
if (st.base.dt != null) opts.dt = st.base.dt
|
|
1445
|
+
try { st.result = st.model.run(opts) } catch (e) { st.result = null; status(e.message) }
|
|
1446
|
+
const range = $item.find('.rcnsd-range')[0]
|
|
1447
|
+
if (range && st.result) { range.max = st.result.time.length - 1; st.k = Math.min(st.k, st.result.time.length - 1); range.value = st.k }
|
|
1448
|
+
}
|
|
1449
|
+
function pick (name, on) {
|
|
1450
|
+
const i = st.selected.indexOf(name)
|
|
1451
|
+
if (on && i < 0 && st.selected.length < 8 && (!st.result || st.result.series[name])) {
|
|
1452
|
+
const used = new Set(st.selected.map(n => st.colorOf[n]))
|
|
1453
|
+
let c = 0; while (used.has(c)) c++
|
|
1454
|
+
st.selected.push(name); st.colorOf[name] = c
|
|
1455
|
+
}
|
|
1456
|
+
if (!on && i >= 0) { st.selected.splice(i, 1); delete st.colorOf[name] }
|
|
1457
|
+
}
|
|
1458
|
+
function values () {
|
|
1459
|
+
if (!st.sk) return
|
|
1460
|
+
st.sk.values(st.result, st.k, { selected: n => st.selected.includes(n), color: (n, sel) => sel ? COLORS[st.colorOf[n] || 0] : '#5d6862' })
|
|
1461
|
+
$item.find('.rcnsd-time').text(st.result ? st.timeUnit + ' ' + num(st.result.time[st.k]) : '')
|
|
1462
|
+
$item.find('.rcnsd-range').val(st.k)
|
|
1463
|
+
charts($item, st)
|
|
1464
|
+
}
|
|
1465
|
+
function draw () {
|
|
1466
|
+
st.sk = Sketch.draw(svg, st.doc, st.base.view || 0, st.model, {
|
|
1467
|
+
onThing: (g, name) => {
|
|
1468
|
+
g.addEventListener('click', ev => { ev.stopPropagation(); if (dragged) return; pick(name, !st.selected.includes(name)); values() })
|
|
1469
|
+
g.addEventListener('mouseenter', () => {
|
|
1470
|
+
const v = st.model.byKey[RCNSD.nameKey(name)]
|
|
1471
|
+
if (!v) return
|
|
1472
|
+
const val = st.result && st.result.series[v.name] ? ' = ' + num(st.result.series[v.name][st.k]) : ''
|
|
1473
|
+
$item.find('.rcnsd-info').html('<b>' + esc(v.name) + '</b>' + esc(val) + (v.units ? ' <span style="color:#94a3b8">' + esc(v.units.replace(/\s*\[.*$/, '')) + '</span>' : '') +
|
|
1474
|
+
' · <code style="font-size:11px">' + esc(v.equation.replace(/^[^=]*=\s*/, '')) + '</code>')
|
|
1475
|
+
})
|
|
1476
|
+
g.addEventListener('mouseleave', () => $item.find('.rcnsd-info').text(W.hint))
|
|
1477
|
+
}
|
|
1478
|
+
})
|
|
1479
|
+
fit()
|
|
1480
|
+
values()
|
|
1481
|
+
walkBar()
|
|
1482
|
+
}
|
|
1483
|
+
$item.on('input.rcnsd', '.rcnsd-range', e => { st.k = +e.target.value; values() })
|
|
1484
|
+
|
|
1485
|
+
// ── zoom and drag ──
|
|
1486
|
+
let vb = null, dragged = false
|
|
1487
|
+
const setVB = () => svg.setAttribute('viewBox', vb.x + ' ' + vb.y + ' ' + vb.w + ' ' + vb.h)
|
|
1488
|
+
function fit () {
|
|
1489
|
+
const b = st.sk.bounds
|
|
1490
|
+
vb = { x: b.x, y: b.y, w: b.w, h: b.h }
|
|
1491
|
+
// the box takes the drawing's own shape, within reason
|
|
1492
|
+
const wpx = svg.getBoundingClientRect().width || 420
|
|
1493
|
+
svg.style.height = Math.round(Math.max(220, Math.min(460, wpx * b.h / b.w))) + 'px'
|
|
1494
|
+
setVB()
|
|
1495
|
+
}
|
|
1496
|
+
function zoom (f) {
|
|
1497
|
+
if (!vb) return
|
|
1498
|
+
const cx = vb.x + vb.w / 2, cy = vb.y + vb.h / 2
|
|
1499
|
+
vb.w *= f; vb.h *= f; vb.x = cx - vb.w / 2; vb.y = cy - vb.h / 2; setVB()
|
|
1500
|
+
}
|
|
1501
|
+
$item.on('click.rcnsd', '.rcnsd-zin', e => { e.stopPropagation(); zoom(1 / 1.4) })
|
|
1502
|
+
$item.on('click.rcnsd', '.rcnsd-zout', e => { e.stopPropagation(); zoom(1.4) })
|
|
1503
|
+
$item.on('click.rcnsd', '.rcnsd-zfit', e => { e.stopPropagation(); if (st.sk) fit() })
|
|
1504
|
+
svg.addEventListener('pointerdown', ev => {
|
|
1505
|
+
if (!vb || ev.button !== 0) return
|
|
1506
|
+
const r = svg.getBoundingClientRect(), k = Math.max(vb.w / r.width, vb.h / r.height)
|
|
1507
|
+
const s0 = { x: ev.clientX, y: ev.clientY, vx: vb.x, vy: vb.y }
|
|
1508
|
+
dragged = false
|
|
1509
|
+
const move = e => {
|
|
1510
|
+
const dx = e.clientX - s0.x, dy = e.clientY - s0.y
|
|
1511
|
+
if (!dragged && Math.hypot(dx, dy) < 4) return
|
|
1512
|
+
dragged = true; svg.style.cursor = 'grabbing'
|
|
1513
|
+
vb.x = s0.vx - dx * k; vb.y = s0.vy - dy * k; setVB()
|
|
1514
|
+
}
|
|
1515
|
+
const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); svg.style.cursor = ''; setTimeout(() => { dragged = false }, 0) }
|
|
1516
|
+
window.addEventListener('pointermove', move); window.addEventListener('pointerup', up)
|
|
1517
|
+
})
|
|
1518
|
+
|
|
1519
|
+
// ── walks ──
|
|
1520
|
+
const wk = { w: null, i: 0, playing: false, token: 0, anim: 0, timer: 0, heard: null }
|
|
1521
|
+
const curWalk = () => (wk.w !== null && item.walks) ? item.walks[wk.w] : null
|
|
1522
|
+
const voiceOn = () => { try { return localStorage.getItem('rcnSdWalkVoice') !== 'off' } catch (e) { return true } }
|
|
1523
|
+
function stopAll () { wk.token++; clearTimeout(wk.timer); cancelAnimationFrame(wk.anim); try { speechSynthesis.cancel() } catch (e) {} }
|
|
1524
|
+
function walkBar () {
|
|
1525
|
+
const $b = $item.find('.rcnsd-walkbar'), ws = item.walks || [], owner = canEdit($item)
|
|
1526
|
+
const walk = curWalk(), btn = 'cursor:pointer;color:#2f6f5e'
|
|
1527
|
+
if (!ws.length && !owner) { $b.empty(); return }
|
|
1528
|
+
if (!walk) {
|
|
1529
|
+
$b.html(`<div style="padding:6px 0 0;display:flex;gap:6px;justify-content:center;flex-wrap:wrap">` +
|
|
1530
|
+
ws.map((w, i) => `<button class="rcnsd-wstart" data-w="${i}" style="${btn}">${W.walk}: ${esc(w.name || 'Walk ' + (i + 1))}</button>`).join('') +
|
|
1531
|
+
(owner ? `<button class="rcnsd-wnew" style="cursor:pointer;color:#64748b">${W.newWalk}</button>` : '') + `</div>` +
|
|
1532
|
+
(wk.note ? `<div class="rcnsd-wnote" style="font-size:11px;color:#64748b;text-align:center;padding-top:2px">${esc(wk.note)}</div>` : ''))
|
|
1533
|
+
return
|
|
1534
|
+
}
|
|
1535
|
+
const s = walk.steps[wk.i] || {}
|
|
1536
|
+
$b.html(`<div style="padding:6px 0 0;display:flex;gap:6px;justify-content:center;align-items:center;flex-wrap:wrap">
|
|
1537
|
+
<button class="rcnsd-wprev" style="${btn}" title="Back (←)">${W.prev}</button>
|
|
1538
|
+
<button class="rcnsd-wplay" style="${btn};font-weight:700" title="Play or pause (Space)">${wk.playing ? W.pause : W.play}</button>
|
|
1539
|
+
<button class="rcnsd-wnext" style="${btn}" title="Next (→)">${W.next}</button>
|
|
1540
|
+
<span style="font-size:12px;color:#64748b;min-width:80px;text-align:center">${W.count(wk.i, walk.steps.length)}</span>
|
|
1541
|
+
<button class="rcnsd-wvoice" style="${btn}" title="Read aloud">${voiceOn() ? W.voiceOn : W.voiceOff}</button>
|
|
1542
|
+
${owner ? `<button class="rcnsd-wedit" style="${btn}">${wk.edit ? W.doneEdit : W.editWalk}</button>` : ''}
|
|
1543
|
+
<button class="rcnsd-wclose" style="${btn}" title="Stop (Esc)">${W.close}</button>
|
|
1544
|
+
</div>
|
|
1545
|
+
${wk.edit ? editPanel(walk, s) : `<div style="font-size:14px;line-height:1.5;padding:6px 4px 0;color:${s.ask ? '#7c2d12' : '#1e1b4b'};${s.ask ? 'font-style:italic' : ''}">
|
|
1546
|
+
${s.ask ? `<span style="font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;border:1px solid currentColor;border-radius:3px;padding:0 4px;margin-right:6px;font-style:normal">${W.ask}</span>` : ''}${esc(s.say || '')}
|
|
1547
|
+
</div>`}
|
|
1548
|
+
<div class="rcnsd-wnote" style="font-size:11px;color:#64748b;text-align:center;padding-top:2px">${esc(wk.note || (wk.playing || wk.edit ? '' : W.keys))}</div>`)
|
|
1549
|
+
}
|
|
1550
|
+
function editPanel (walk, s) {
|
|
1551
|
+
const b = 'cursor:pointer;font-size:12px'
|
|
1552
|
+
const lit = s.all ? W.weAllLit : (s.names && s.names.length ? s.names.join(', ') : W.weNone)
|
|
1553
|
+
const extra = (s.run ? W.weRunSum(st.timeUnit + ' ' + num(s.run[1])) : s.time != null ? W.weTimeSum(st.timeUnit + ' ' + num(s.time)) : '') +
|
|
1554
|
+
(s.graph && s.graph.length ? W.weGraphSum(s.graph.join(', ')) : '')
|
|
1555
|
+
return `<div class="rcnsd-editor" style="display:grid;gap:5px;padding:6px 2px 0">
|
|
1556
|
+
<label style="font-size:12px;color:#475569;display:grid;gap:2px">${W.weSay}
|
|
1557
|
+
<textarea class="rcnsd-we-say" rows="3" style="width:100%;height:5.2em;min-height:0;font:inherit;font-size:14px;padding:4px 6px;box-sizing:border-box;resize:vertical">${esc(s.say || '')}</textarea></label>
|
|
1558
|
+
<div style="font-size:12px;color:#475569">${esc(W.weSum(lit, extra))}</div>
|
|
1559
|
+
<div style="display:flex;gap:4px;flex-wrap:wrap">
|
|
1560
|
+
<button class="rcnsd-we-light" style="${b}">${W.weLight}</button>
|
|
1561
|
+
<button class="rcnsd-we-all" style="${b}">${W.weAll}</button>
|
|
1562
|
+
<button class="rcnsd-we-graphs" style="${b}">${W.weGraphs}</button>
|
|
1563
|
+
<button class="rcnsd-we-time" style="${b}">${W.weTime}</button>
|
|
1564
|
+
<button class="rcnsd-we-run" style="${b}">${W.weRun}</button>
|
|
1565
|
+
<label style="font-size:12px;display:inline-flex;gap:3px;align-items:center"><input type="checkbox" class="rcnsd-we-ask" ${s.ask ? 'checked' : ''}> ${W.weAsk}</label>
|
|
1566
|
+
</div>
|
|
1567
|
+
<div style="display:flex;gap:4px;flex-wrap:wrap;align-items:center">
|
|
1568
|
+
<button class="rcnsd-we-add" style="${b}">${W.weAdd}</button>
|
|
1569
|
+
<button class="rcnsd-we-up" style="${b}" ${wk.i === 0 ? 'disabled' : ''}>${W.weUp}</button>
|
|
1570
|
+
<button class="rcnsd-we-down" style="${b}" ${wk.i >= walk.steps.length - 1 ? 'disabled' : ''}>${W.weDown}</button>
|
|
1571
|
+
<button class="rcnsd-we-del" style="${b}">${W.weDel}</button>
|
|
1572
|
+
<span style="flex:1"></span>
|
|
1573
|
+
<label style="font-size:12px;color:#475569">${W.weName} <input class="rcnsd-we-name" value="${esc(walk.name || '')}" style="width:12em;font-size:12px"></label>
|
|
1574
|
+
<button class="rcnsd-we-delwalk" style="${b};color:#9a3412">${W.weDelWalk}</button>
|
|
1575
|
+
</div>
|
|
1576
|
+
<div style="font-size:11px;color:#64748b">${W.weHow}</div>
|
|
1577
|
+
</div>`
|
|
1578
|
+
}
|
|
1579
|
+
// save the walks into the item, and the page; the walk stays open where it was
|
|
1580
|
+
function saveWalks (note) {
|
|
1581
|
+
item.text = describe(item)
|
|
1582
|
+
wiki.pageHandler.put($item.parents('.page:first'), { type: 'edit', id: item.id, item })
|
|
1583
|
+
wk.dirty = false
|
|
1584
|
+
if (note !== false) wk.note = W.weSaved
|
|
1585
|
+
}
|
|
1586
|
+
function edited (redraw) {
|
|
1587
|
+
wk.dirty = true
|
|
1588
|
+
const walk = curWalk()
|
|
1589
|
+
if (redraw && walk && st.sk) st.sk.paint(Sketch.litSets(walk, wk.i), wk.edit)
|
|
1590
|
+
walkBar()
|
|
1591
|
+
}
|
|
1592
|
+
function walkShow (i) {
|
|
1593
|
+
const walk = curWalk(); if (!walk) return
|
|
1594
|
+
stopAll(); wk.note = ''
|
|
1595
|
+
wk.i = Math.max(0, Math.min(walk.steps.length - 1, i))
|
|
1596
|
+
const s = walk.steps[wk.i], tok = wk.token
|
|
1597
|
+
// the model as this step wants it
|
|
1598
|
+
st.over = Object.assign({}, st.base.overrides || {}, s.set || {})
|
|
1599
|
+
st.final = s.final != null ? s.final : st.base.final
|
|
1600
|
+
run()
|
|
1601
|
+
if (s.graph) { st.selected = []; st.colorOf = {}; s.graph.forEach(n => pick(n, true)) }
|
|
1602
|
+
if (st.sk) st.sk.paint(Sketch.litSets(walk, wk.i), !!wk.edit)
|
|
1603
|
+
const idx = t => { const r = st.result; if (!r) return 0; let b = 0; r.time.forEach((x, k) => { if (Math.abs(x - t) < Math.abs(r.time[b] - t)) b = k }); return b }
|
|
1604
|
+
let animDone = true, spoken = !wk.playing || !voiceOn() || !s.say
|
|
1605
|
+
if (s.run && st.result) {
|
|
1606
|
+
animDone = false
|
|
1607
|
+
const a = idx(s.run[0]), b = idx(s.run[1]), t0 = performance.now(), dur = (s.seconds || 5) * 1000
|
|
1608
|
+
const frame = () => {
|
|
1609
|
+
if (tok !== wk.token) return
|
|
1610
|
+
const f = Math.min(1, (performance.now() - t0) / dur)
|
|
1611
|
+
st.k = Math.round(a + (b - a) * f); $item.find('.rcnsd-range').val(st.k); values()
|
|
1612
|
+
if (f < 1) wk.anim = requestAnimationFrame(frame); else { animDone = true; onward() }
|
|
1613
|
+
}
|
|
1614
|
+
frame()
|
|
1615
|
+
} else { if (s.time != null) st.k = idx(s.time); $item.find('.rcnsd-range').val(st.k); values() }
|
|
1616
|
+
walkBar()
|
|
1617
|
+
if (wk.playing && voiceOn() && s.say) speak(s.say, tok, () => { spoken = true; onward() })
|
|
1618
|
+
else if (wk.playing) wk.timer = setTimeout(() => { if (tok === wk.token) { spoken = true; onward() } }, 2500 + (s.say || '').length * 55)
|
|
1619
|
+
function onward () {
|
|
1620
|
+
if (tok !== wk.token || !wk.playing || !spoken || !animDone) return
|
|
1621
|
+
const last = wk.i >= walk.steps.length - 1
|
|
1622
|
+
if (s.ask || last) { wk.playing = false; wk.heard = wk.i; wk.note = last && !s.ask ? W.end : W.over; walkBar(); return }
|
|
1623
|
+
wk.timer = setTimeout(() => { if (tok === wk.token && wk.playing) walkShow(wk.i + 1) }, 900)
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
function speak (text, tok, done) {
|
|
1627
|
+
if (!window.speechSynthesis) { done(); return }
|
|
1628
|
+
const parts = text.match(/[^.!?]+[.!?]*\s*/g) || [text]; let i = 0
|
|
1629
|
+
const safety = setTimeout(() => { if (tok === wk.token) done() }, 4000 + text.length * 90)
|
|
1630
|
+
const next = () => {
|
|
1631
|
+
if (tok !== wk.token) return
|
|
1632
|
+
if (i >= parts.length) { clearTimeout(safety); done(); return }
|
|
1633
|
+
const u = new SpeechSynthesisUtterance(parts[i++].trim())
|
|
1634
|
+
u.onend = u.onerror = () => { if (tok === wk.token) next() }
|
|
1635
|
+
speechSynthesis.speak(u)
|
|
1636
|
+
}
|
|
1637
|
+
next()
|
|
1638
|
+
}
|
|
1639
|
+
function walkEnd () {
|
|
1640
|
+
const was = wk.dirty
|
|
1641
|
+
stopAll(); wk.w = null; wk.playing = false; wk.note = ''; wk.edit = false
|
|
1642
|
+
if (was) saveWalks()
|
|
1643
|
+
st.over = Object.assign({}, st.base.overrides || {}); st.final = st.base.final
|
|
1644
|
+
run()
|
|
1645
|
+
st.selected = []; st.colorOf = {}
|
|
1646
|
+
const want = Array.isArray(st.base.graph) ? st.base.graph : st.model.vars.filter(v => v.kind === 'stock' && !st.model.bad[v.id]).slice(0, 4).map(v => v.name)
|
|
1647
|
+
want.forEach(n => pick(n, true))
|
|
1648
|
+
st.k = st.result ? st.result.time.length - 1 : 0
|
|
1649
|
+
$item.find('.rcnsd-range').val(st.k)
|
|
1650
|
+
if (st.sk) st.sk.paint(null)
|
|
1651
|
+
values(); walkBar()
|
|
1652
|
+
}
|
|
1653
|
+
function walkToggle () {
|
|
1654
|
+
const walk = curWalk(); if (!walk) return
|
|
1655
|
+
if (wk.playing) { wk.playing = false; stopAll(); walkBar(); return }
|
|
1656
|
+
wk.playing = true
|
|
1657
|
+
if (wk.heard === wk.i && wk.i < walk.steps.length - 1) walkShow(wk.i + 1); else walkShow(wk.i)
|
|
1658
|
+
}
|
|
1659
|
+
$item.on('click.rcnsd', '.rcnsd-wstart', e => { e.stopPropagation(); wk.w = +e.currentTarget.dataset.w; wk.i = 0; wk.playing = false; wk.heard = null; walkShow(0); $item.find('.rcnsd-walkbar').trigger('focus') })
|
|
1660
|
+
$item.on('click.rcnsd', '.rcnsd-wplay', e => { e.stopPropagation(); walkToggle() })
|
|
1661
|
+
$item.on('click.rcnsd', '.rcnsd-wprev', e => { e.stopPropagation(); walkShow(wk.i - 1) })
|
|
1662
|
+
$item.on('click.rcnsd', '.rcnsd-wnext', e => { e.stopPropagation(); walkShow(wk.i + 1) })
|
|
1663
|
+
$item.on('click.rcnsd', '.rcnsd-wclose', e => { e.stopPropagation(); walkEnd() })
|
|
1664
|
+
$item.on('click.rcnsd', '.rcnsd-wvoice', e => {
|
|
1665
|
+
e.stopPropagation()
|
|
1666
|
+
try { localStorage.setItem('rcnSdWalkVoice', voiceOn() ? 'off' : 'on') } catch (err) {}
|
|
1667
|
+
if (!voiceOn()) try { speechSynthesis.cancel() } catch (err) {}
|
|
1668
|
+
walkBar()
|
|
1669
|
+
})
|
|
1670
|
+
// ── writing walks ──
|
|
1671
|
+
const cur = () => { const w = curWalk(); return w && w.steps[wk.i] }
|
|
1672
|
+
const timeAt = k => st.result ? st.result.time[k] : 0
|
|
1673
|
+
$item.on('click.rcnsd', '.rcnsd-wnew', e => {
|
|
1674
|
+
e.stopPropagation()
|
|
1675
|
+
if (!canEdit($item)) return
|
|
1676
|
+
item.walks = item.walks || []
|
|
1677
|
+
const caption = String(item.text || '').split('\n')[0].trim() || (item.fileName || 'this model').replace(/\.mdl$/i, '')
|
|
1678
|
+
item.walks.push({ name: W.newWalkName(caption), steps: [{ say: '', all: true }] })
|
|
1679
|
+
wk.w = item.walks.length - 1; wk.i = 0; wk.playing = false; wk.edit = true; wk.dirty = true
|
|
1680
|
+
walkShow(0)
|
|
1681
|
+
})
|
|
1682
|
+
$item.on('click.rcnsd', '.rcnsd-wedit', e => {
|
|
1683
|
+
e.stopPropagation()
|
|
1684
|
+
stopAll(); wk.playing = false
|
|
1685
|
+
if (wk.edit) { wk.edit = false; if (wk.dirty) saveWalks() } else { wk.edit = true; wk.note = '' }
|
|
1686
|
+
const walk = curWalk(); if (walk && st.sk) st.sk.paint(Sketch.litSets(walk, wk.i), wk.edit)
|
|
1687
|
+
walkBar()
|
|
1688
|
+
})
|
|
1689
|
+
$item.on('input.rcnsd', '.rcnsd-we-say', e => { const s = cur(); if (s) { s.say = e.target.value; wk.dirty = true } })
|
|
1690
|
+
$item.on('input.rcnsd', '.rcnsd-we-name', e => { const w = curWalk(); if (w) { w.name = e.target.value; wk.dirty = true } })
|
|
1691
|
+
$item.on('click.rcnsd', '.rcnsd-we-light', e => { e.stopPropagation(); const s = cur(); delete s.all; s.names = st.selected.slice(); edited(true) })
|
|
1692
|
+
$item.on('click.rcnsd', '.rcnsd-we-all', e => { e.stopPropagation(); const s = cur(); s.all = true; s.names = []; edited(true) })
|
|
1693
|
+
$item.on('click.rcnsd', '.rcnsd-we-graphs', e => { e.stopPropagation(); cur().graph = st.selected.slice(); edited() })
|
|
1694
|
+
$item.on('click.rcnsd', '.rcnsd-we-time', e => { e.stopPropagation(); const s = cur(); delete s.run; s.time = timeAt(st.k); edited() })
|
|
1695
|
+
$item.on('click.rcnsd', '.rcnsd-we-run', e => { e.stopPropagation(); const s = cur(); delete s.time; s.run = [timeAt(0), timeAt(st.k)]; edited() })
|
|
1696
|
+
$item.on('change.rcnsd', '.rcnsd-we-ask', e => { const s = cur(); if (e.target.checked) s.ask = true; else delete s.ask; edited() })
|
|
1697
|
+
$item.on('click.rcnsd', '.rcnsd-we-add', e => { e.stopPropagation(); const w = curWalk(); w.steps.splice(wk.i + 1, 0, { say: '', names: [] }); wk.dirty = true; walkShow(wk.i + 1) })
|
|
1698
|
+
$item.on('click.rcnsd', '.rcnsd-we-del', e => {
|
|
1699
|
+
e.stopPropagation(); const w = curWalk()
|
|
1700
|
+
if (w.steps.length <= 1) w.steps[0] = { say: '', names: [] }; else w.steps.splice(wk.i, 1)
|
|
1701
|
+
wk.dirty = true; walkShow(Math.min(wk.i, w.steps.length - 1))
|
|
1702
|
+
})
|
|
1703
|
+
$item.on('click.rcnsd', '.rcnsd-we-up', e => { e.stopPropagation(); const s2 = curWalk().steps; if (wk.i < 1) return; s2.splice(wk.i - 1, 0, s2.splice(wk.i, 1)[0]); wk.dirty = true; walkShow(wk.i - 1) })
|
|
1704
|
+
$item.on('click.rcnsd', '.rcnsd-we-down', e => { e.stopPropagation(); const s2 = curWalk().steps; if (wk.i >= s2.length - 1) return; s2.splice(wk.i + 1, 0, s2.splice(wk.i, 1)[0]); wk.dirty = true; walkShow(wk.i + 1) })
|
|
1705
|
+
$item.on('click.rcnsd', '.rcnsd-we-delwalk', e => {
|
|
1706
|
+
e.stopPropagation()
|
|
1707
|
+
if (!wk.delArmed || Date.now() - wk.delArmed > 4000) { wk.delArmed = Date.now(); wk.note = W.weDelSure; walkBar(); return }
|
|
1708
|
+
wk.delArmed = 0
|
|
1709
|
+
item.walks.splice(wk.w, 1)
|
|
1710
|
+
wk.dirty = false; walkEnd(); saveWalks(false); walkBar()
|
|
1711
|
+
})
|
|
1712
|
+
|
|
1713
|
+
$item.on('keydown.rcnsd', '.rcnsd-walkbar', e => {
|
|
1714
|
+
if (wk.w === null) return
|
|
1715
|
+
if (/^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) { if (e.key === 'Escape') e.target.blur(); e.stopPropagation(); return }
|
|
1716
|
+
if (e.key === ' ') { e.preventDefault(); e.stopPropagation(); walkToggle() }
|
|
1717
|
+
else if (e.key === 'ArrowRight') { e.preventDefault(); e.stopPropagation(); walkShow(wk.i + 1) }
|
|
1718
|
+
else if (e.key === 'ArrowLeft') { e.preventDefault(); e.stopPropagation(); walkShow(wk.i - 1) }
|
|
1719
|
+
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); walkEnd() }
|
|
1720
|
+
})
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
// ── the tool talks back ──
|
|
1724
|
+
// Only the popup this page opened is listened to.
|
|
1725
|
+
function listener (event) {
|
|
1726
|
+
const d = event.data
|
|
1727
|
+
if (!d || d.toolType !== 'rcn-sd' || !popup || event.source !== popup) return
|
|
1728
|
+
if (d.action === 'ready' && pendingItem) {
|
|
1729
|
+
const pageTitle = pending$item ? pending$item.parents('.page').data('title') : undefined
|
|
1730
|
+
popup.postMessage({ toolType: 'rcn-sd', action: 'loadModel', mdl: pendingItem.mdl || null, fileName: pendingItem.fileName || null,
|
|
1731
|
+
walks: pendingItem.walks || [], settings: pendingItem.settings || null, pageTitle }, '*')
|
|
1732
|
+
} else if (d.action === 'saveModel' && pendingItem && pending$item) {
|
|
1733
|
+
if (typeof d.mdl !== 'string' || !d.mdl) return
|
|
1734
|
+
const item = pendingItem, $item = pending$item
|
|
1735
|
+
item.mdl = d.mdl
|
|
1736
|
+
item.fileName = d.fileName || item.fileName
|
|
1737
|
+
item.walks = Array.isArray(d.walks) ? d.walks : (item.walks || [])
|
|
1738
|
+
if (d.settings) item.settings = d.settings
|
|
1739
|
+
save($item, item)
|
|
1740
|
+
$item.find('.rcnsd-msg').text(W.savedBack)
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
if (typeof window !== 'undefined') {
|
|
1745
|
+
window.plugins.rcnsd = { emit, bind }
|
|
1746
|
+
if (!window.rcnsdListener) {
|
|
1747
|
+
window.rcnsdListener = listener
|
|
1748
|
+
window.addEventListener('message', listener)
|
|
1749
|
+
}
|
|
1750
|
+
Sketch.injectCss(document)
|
|
1751
|
+
}
|
|
1752
|
+
})()
|