source: cpp/frams/canvas/neurodiagram.cpp @ 151

Last change on this file since 151 was 151, checked in by sz, 10 years ago

(c) header added

  • Property svn:eol-style set to native
File size: 16.2 KB
Line 
1// This file is a part of the Framsticks GDK.
2// Copyright (C) 2002-2014  Maciej Komosinski and Szymon Ulatowski.  See LICENSE.txt for details.
3// Refer to http://www.framsticks.com/ for further information.
4
5#include "neurodiagram.h"
6#include "nn_layout.h"
7#include <frams/neuro/neurolibrary.h>
8#include <frams/mech/mechworld.h>
9#include <frams/util/multirange.h>
10#include "canvasutil.h"
11#include <frams/neuro/neuroimpl.h>
12#include <frams/model/modelobj.h>
13#include <frams/simul/simul.h>
14#include "common/nonstd_time.h"
15
16#define FIELDSTRUCT NeuroDiagram
17ParamEntry neurodiagram_paramtab[] =
18{
19        { "NeuroDiagram", 1, 4, "NeuroDiagram", "Can be used as the client object in the Window.", },
20        { "new", 0, PARAM_USERHIDDEN, "create new NeuroDiagram", "p oNeuroDiagram", PROCEDURE(p_new), },
21        { "showCreature", 0, PARAM_USERHIDDEN + PARAM_NOSTATIC, "show dynamic NN", "p(oCreature)", PROCEDURE(p_showcr), },
22        { "showModel", 0, PARAM_USERHIDDEN + PARAM_NOSTATIC, "show static NN", "p(oModel)", PROCEDURE(p_showmod), },
23        { "hide", 0, PARAM_USERHIDDEN + PARAM_NOSTATIC, "hide NN", "p()", PROCEDURE(p_hide), },
24        { 0, 0, 0, },
25};
26#undef FIELDSTRUCT
27
28Param neurodiagram_param(neurodiagram_paramtab, 0);
29
30static struct ColorDefs colordefs;
31
32void NeuroDiagram::p_new(ExtValue*args, ExtValue*ret)
33{
34        NeuroDiagram *d = new NeuroDiagram(&colordefs);
35        d->drawbackground = false;
36        ret->setObject(ExtObject(&neurodiagram_param, d));
37}
38
39void NeuroDiagram::p_showcr(ExtValue*args, ExtValue*ret)
40{
41        Creature *cr = 0;
42        if (args->type == TObj)
43        {
44                const ExtObject& o = args->getObject();
45                cr = (Creature*)o.getTarget();
46        }
47        showLive(cr);
48}
49
50void NeuroDiagram::p_showmod(ExtValue*args, ExtValue*ret)
51{
52        Model *mod = ModelObj::fromObject(args[0]);
53        show(mod);
54}
55
56static void addNeuroDescription(SString &t, Neuro *n)
57{
58        static Param par;
59        SString c(n->getClassName());
60        NeuroClass* cl = n->getClass();
61        t += c;
62        t += " (";
63        if (cl)
64                t += cl->getLongName();
65        else
66                t += "Unknown";
67        t += ")";
68}
69
70NeuroDiagram::NeuroDiagram(ColorDefs *cd)
71:FramDrawToolkit(cd), livewire(false), indestructor(false), showing_not_alive_label(false), o(0),
72warn_if_not_alive(true), selection(*this), drawbackground(true), linetype(true), layouttype(2)
73{
74        scroll.setMargin(10, 10); // appropriate size should be adjusted
75        dontPaintOutside(0);
76        add(&scroll);
77        pluginactive = false;
78        FramDrawToolkit::setBackColor(ColorDefs::neurobackground);
79}
80
81NeuroDiagram::~NeuroDiagram()
82{
83        indestructor = 1;
84        hide();
85        remove(&scroll);
86        updatePlugin();
87}
88
89void NeuroDiagram::hide()
90{
91        showing_not_alive_label = 0;
92        if (o) o->delmodel_list.remove(killnode);
93        FOREACH(NeuroProbe*,pr,probes)
94                delete pr;
95        probes.clear();
96        selection.clear(0);
97        cr = 0;
98        livewire = false;
99}
100
101class NNLayoutState_Neurodiagram : public NNLayoutState
102{
103public:
104        NeuroDiagram *nd;
105        NNLayoutState_Neurodiagram(NeuroDiagram *_nd) :nd(_nd) {}
106
107        int GetElements()
108        {
109                return nd->scroll.count();
110        }
111
112        int *GetXYWH(int el)
113        {
114                return &nd->scroll.getInfo(el)->pos.x;
115        }
116
117        void SetXYWH(int el, int x, int y, int w, int h)
118        {
119                ScrollInfo *si = nd->scroll.getInfo(el);
120                si->pos.set(x, y); si->size.set(w, h);
121        }
122
123        int GetInputs(int el)
124        {
125                return nd->getNS(el)->n->getInputCount();
126        }
127
128        int GetLink(int el, int i)
129        {
130                return nd->getNS(el)->n->getInput(i)->refno;
131        }
132
133        int *GetLinkXY(int el, int i)
134        {
135                static int XY[2];
136                int *xywh = GetXYWH(el);
137                XY[0] = 0;
138                XY[1] = ((1 + i)*xywh[3]) / (GetInputs(el) + 1);
139                return XY;
140        }
141};
142
143
144void NeuroDiagram::show(Model *o_)
145{
146        hide();
147        o = o_;
148        scroll.removeAll();
149        if (o)
150        {
151                Neuro *n;
152                int i;
153                killnode = o->delmodel_list.add(STATRICKCALLBACK(this, &NeuroDiagram::onKill, 0));
154
155                // create symbol objects
156                for (i = 0; n = o->getNeuro(i); i++)
157                {
158                        NeuroSymbol *ns = new NeuroSymbol(*this, n);
159                        scroll.add(ns, 1); // autodel   
160                }
161                if (i)
162                {
163                        struct NNLayoutFunction *nnfun = &nn_layout_functions[layouttype];
164                        NNLayoutState_Neurodiagram nn(this);
165                        nnfun->doLayout(&nn);
166                }
167                scroll.invalidate();
168                scroll.autoZoom();
169        }
170
171        updatePlugin();
172        requestPaint();
173}
174
175void NeuroDiagram::showLive(Creature *_cr)
176{
177        showing_not_alive_label = 0;
178        if (!_cr) { show(0); return; }
179        show(&_cr->getModel());
180        cr = _cr;
181        livewire = true;
182        updatePlugin();
183}
184
185void NeuroDiagram::paint()
186{
187        if (drawbackground)
188        {
189                setColor(ColorDefs::neurobackground);
190                clear();
191        }
192
193        if (countNeurons() > 0)
194        {
195                CanvasWindowContainer::paint();
196        }
197        else
198        {
199                setColor(ColorDefs::neuroneuron);
200                drawAlignedText(size.x / 2, (size.y - textHeight()) / 2, 0, "[No neural network]");
201        }
202
203        if (showing_not_alive_label)
204        {
205                if (time(0) > showing_not_alive_label)
206                        showing_not_alive_label = 0;
207                else
208                {
209                        setColor(0, 0, 0);
210                        drawAlignedText(not_alive_location.x, not_alive_location.y, 0, "select a creature");
211                        drawAlignedText(not_alive_location.x, not_alive_location.y + textHeight(), 0, "to probe neurons");
212                }
213        }
214}
215
216void NeuroDiagram::resize(int w, int h)
217{
218        CanvasWindowContainer::resize(w, h);
219        scroll.autoZoom();
220}
221
222int NeuroDiagram::countNeurons()
223{
224        return scroll.count();
225}
226
227void NeuroDiagram::addProbe(int i)
228{
229        if (i >= countNeurons()) return;
230        NeuroProbe *probe = new NeuroProbe(getNS(i));
231        probes += (void*)probe;
232        add(probe);
233        updatePlugin();
234        requestPaint();
235}
236
237void NeuroDiagram::onKill(void*obj, long dummy)
238{
239        show(0);
240}
241
242///////////////////////////
243
244NeuroSymbol::NeuroSymbol(NeuroDiagram &nd, Neuro * _n)
245:selected(0), n(_n), diagram(nd)
246{
247        tooltip = "#";
248        tooltip += SString::valueOf((int)n->refno);
249        tooltip += " - ";
250        label = tooltip;
251        addNeuroDescription(tooltip, n);
252        label += n->getClassName();
253        if (n->getClassParams().len())
254        {
255                tooltip += "\n"; tooltip += n->getClassParams();
256        }
257}
258
259void NeuroSymbol::paint()
260{
261        if (selected)
262        {
263                setColor(255, 255, 255);
264                fillRect(0, 0, size.x, size.y);
265        }
266        diagram.setClip();
267        diagram.setColor(ColorDefs::neuroneuron);
268        drawNeuroSymbol(this, n->getClass(), 0, 0, size.x, size.y);
269
270        if (size.y > 4 * textHeight())
271        {
272                const char* t = label;
273                drawAlignedText(size.x / 2, size.y - textHeight(), 0, t);
274
275                NeuroImpl *ni = NeuroNetImpl::getImpl(n);
276                if (ni && (ni->getChannelCount() > 1))
277                {
278                        drawLine(size.x - size.x / 16, size.y / 2 - size.y / 16,
279                                size.x - size.x / 8, size.y / 2 + size.y / 16);
280                        char t[20];
281                        sprintf(t, "%d", ni->getChannelCount());
282                        moveTo(size.x, size.y / 2 - textHeight());
283                        drawText(t);
284                }
285        }
286
287        // NeuroSymbol is also responsible for drawing connection lines from its inputs to other NeuroSymbols' outputs
288        NeuroSymbol *ns2;
289        if (!diagram.isLive())
290                diagram.setColor(ColorDefs::neurolink);
291        for (int iw = 0; iw < n->getInputCount(); iw++)
292        {
293                ns2 = diagram.getNS(n->getInput(iw)->refno); // the other NeuroSymbol (our input will connect to its output)
294
295                int yw = inputY(iw);
296                int xw = yw / 4; // x coordinate of the first corner point, depends on yw to avoid overlapping between inputs
297                drawLine(size.x / 4, yw, xw, yw); // first horizontal segment (to the left)
298                diagram.setWireColor(ns2->n->state, 0);
299                if ((diagram.linetype != 1) || (ns2->pos.x + ns2->size.x / 2 < pos.x))
300                { // straight line to the other neuron's output (the signal goes forwards)
301                        ns2->lineTo(ns2->size.x, ns2->size.y / 2);
302                }
303                else
304                { // make an U-shaped loop from 3 segments - vert/horiz/vert (the signal goes backwards)
305                        int y2;
306                        int down;
307                        if (ns2 == this) down = (iw >= ((n->getInputCount()) / 2)); else down = (ns2->pos.y > (pos.y + size.y));
308                        if (down)
309                        {
310                                y2 = (pos.y + size.y + (size.y - yw) / 3);
311                        }
312                        else
313                        {
314                                y2 = pos.y - yw / 3;
315                                if ((ns2->pos.y<pos.y) && (ns2->pos.y>(pos.y - ns2->size.y))) y2 -= pos.y - ns2->pos.y;
316                        }
317                        // note: "diagram" uses global coordinate system, so we add "pos" or "ns2->pos" to get NeuroSymbol's global positions
318                        diagram.lineTo(pos.x + xw, y2);
319                        diagram.lineTo(ns2->pos.x + ns2->size.x, y2);
320                        diagram.lineTo(ns2->pos.x + ns2->size.x, ns2->pos.y + ns2->size.y / 2);
321                }
322
323        }
324}
325
326void NeuroSymbol::mouse(int x, int y, int t)
327{
328        if ((t & (LeftButton | ShiftButton)) == (LeftButton | ShiftButton))
329        {
330                ScrollManager& sc = diagram.scroll;
331                sc.setPos2(n->refno, pos.x + x - diagram.symboldragpos.x, pos.y + y - diagram.symboldragpos.y);
332                sc.validate();
333                requestPaint();
334        }
335}
336
337int NeuroSymbol::mouseclick(int x, int y, int t)
338{
339        if ((t & (LeftButton | DblClick)) == (LeftButton | DblClick))
340        {
341                if (diagram.isLive())
342                        diagram.addProbe(n->refno);
343                else
344                {
345                        if (diagram.warn_if_not_alive)
346                        {
347                                diagram.showing_not_alive_label = time(0) + 10;
348                                diagram.not_alive_location.x = pos.x + x;
349                                diagram.not_alive_location.y = pos.y + y;
350                                diagram.requestPaint();
351                        }
352                }
353                return LeftButton | DblClick;
354        }
355
356        if ((t & (LeftButton | ShiftButton)) == (LeftButton | ShiftButton))
357        {
358                if (selected)
359                        diagram.selection.remove(Model::neuroToMap(n->refno));
360                else
361                        diagram.selection.add(Model::neuroToMap(n->refno));
362                diagram.symboldragpos.set(x, y);
363                return LeftButton | ShiftButton;
364        }
365
366        if (t & LeftButton)
367        {
368                diagram.selection.set(Model::neuroToMap(n->refno));
369                return LeftButton;
370        }
371
372        return 0;
373}
374
375// coordinate y of i-th input
376int NeuroSymbol::inputY(int i)
377{
378        return (1 + i)*size.y / ((n->getInputCount()) + 1);
379}
380
381SString NeuroSymbol::hint(int x, int y)
382{
383        if ((y >= 0) && (y < size.y))
384                if (x<size.x / 4)
385                { // inputs?
386                        if (n->getInputCount()>0)
387                        {
388                                int i = (y*n->getInputCount()) / size.y;
389                                double w;
390                                Neuro* target = n->getInput(i, w);
391                                if (target)
392                                {
393                                        SString t = "connected to #";
394                                        t += SString::valueOf((int)target->refno);
395                                        t += " - ";
396                                        addNeuroDescription(t, target);
397                                        //              if (w!=1.0)
398                                        {
399                                                t += ", weight=";
400                                                t += SString::valueOf(w);
401                                        }
402                                        return t;
403                                }
404                        }
405                }
406        return CanvasWindow::hint(x, y);
407}
408
409/////////////////////////
410
411NeuroProbe::NeuroProbe(NeuroSymbol* ns)
412:DCanvasWindow(DCanvasWindow::Title + DCanvasWindow::Border + DCanvasWindow::Close + DCanvasWindow::Size,
413(const char*)ns->getLabel(), &neurochart, &neurochart)
414{
415        holdismine = 0;
416        drawing = 0; whichdrawing = -1;
417        clientbordersset = 0;
418        adjustingvalue = 0;
419        link = ns;
420        tooltip = SString("Probe for ") + ns->tooltip;
421        setPos(ns->getPos().x, ns->getPos().y);
422        neurochart.printMinMax(0);
423        neurochart.data.setMinMax(-1, 1);
424        chnum = 1; chnum2 = 0; chsel = 0;
425        chselwidth = 0;
426        chselecting = 0;
427        updateChannelCount(NeuroNetImpl::getImpl(link->n));
428}
429
430void NeuroProbe::onClose()
431{
432        link->diagram.probes -= this;
433        delete this;
434}
435
436NeuroProbe::~NeuroProbe()
437{
438        if (holdismine)
439                link->n->flags &= ~Neuro::HoldState;
440}
441
442void NeuroProbe::paint()
443{
444        static char t[40];
445        if (!clientbordersset)
446        {
447                clientbordersset = 1;
448                setClientBorder(0, 1, 16, textHeight() + 2); // don't use textheight outside paint/mouse events
449        }
450        int hold = link->n->flags & Neuro::HoldState;
451        float state = (float)link->n->state;
452        NeuroImpl *ni = 0;
453        if (chsel != 0)
454        {
455                ni = NeuroNetImpl::getImpl(link->n);
456                if (chsel < 0)
457                {
458                        int dr = -chsel - 1;
459                        if (whichdrawing != dr)
460                        {
461                                drawing = ni->getDrawing(dr);
462                                whichdrawing = dr;
463                        }
464                        if (drawing)
465                        {
466                                int *dr = drawing;
467                                int w = size.x - 2, h = size.y - clienttop - clientbottom;
468                                int scale = min(w, h);
469                                int x0 = clienttop + leftborder + ((w > h) ? (w - h) / 2 : 0);
470                                int y0 = clientleft + topborder + ((h > w) ? (h - w) / 2 : 0);
471
472                                while (*dr != NeuroImpl::ENDDRAWING)
473                                {
474                                        int first = 1;
475                                        unsigned char r, g, b;
476                                        FramDrawToolkit::splitRGB(*(dr++), r, g, b);
477                                        setColor(r, g, b);
478                                        while (*dr != NeuroImpl::ENDDRAWING)
479                                        {
480                                                int x = ((*(dr++))*scale) / (NeuroImpl::MAXDRAWINGXY + 1) + x0;
481                                                int y = ((*(dr++))*scale) / (NeuroImpl::MAXDRAWINGXY + 1) + y0;
482                                                if (first) { moveTo(x, y); first = 0; }
483                                                else lineTo(x, y);
484                                        }
485                                        dr++;
486                                }
487                        }
488                }
489        }
490        DCanvasWindow::paintWithClient((chsel < 0) ? 0 : client);
491        setColor(0, 0, 0);
492        int yline = size.y - 2;
493        if (chsel >= 0)
494        {
495                if (ni) state = (float)ni->getState(chsel);
496                yline -= textHeight();
497                int y = mapClientY(neurochart.mapData(state));
498                int x = size.x - 15 - 1;
499                drawLine(1, yline, size.x - 2, yline);
500                if (hold)
501                {
502                        sprintf(t, "hold: %1.3g", state);
503                        fillRect(x, y - 1 - 5, 15, 3 + 5 + 5);
504                        setColor(255, 0, 0);
505                        fillRect(x + 2, y - 1, 15 - 2 - 2, 3);
506                }
507                else
508                {
509                        sprintf(t, "signal: %1.3g", state);
510                        fillRect(x, y - 1, 15, 3);
511                }
512                drawAlignedText(size.x - textHeight(), yline, 1, t);
513        }
514
515        if ((chnum > 1) || (chnum2 > 0))
516        {
517                if (chselecting) setColor(255, 255, 255); else setColor(0, 70, 0);
518                if (chsel < 0)
519                        sprintf(t, "%c/%c", 'A' - chsel - 1, 'A' + chnum2 - 1);
520                else
521                        sprintf(t, "%d/%d", chsel, chnum);
522                moveTo(0, yline - textHeight());
523                chselwidth = textWidth(t);
524                drawText(t, -1, getSize().x);
525        }
526        else
527                chselwidth = 0;
528}
529
530void NeuroProbe::mouse(int x, int y, int b)
531{
532        if (chselecting)
533        {
534                int ch = chsel0 + (x - chselx0) / 10;
535                if (selectChannel(ch)) requestPaint();
536                b &= ~LeftButton;
537        }
538        DCanvasWindow::mouse(x, y, b);
539        if (adjustingvalue)
540        {
541                double st = neurochart.unmapData(unmapClientY(y));
542                if (st<-1.0) st = -1.0; else if (st>1.0) st = 1.0;
543                if (chsel == 0)
544                        link->n->state = st;
545                else if (chsel >= 0)
546                {
547                        NeuroImpl *ni = NeuroNetImpl::getImpl(link->n);
548                        if (ni) ni->setCurrentState(st, chsel);
549                }
550                requestPaint();
551        }
552}
553
554void NeuroProbe::mouseunclick(int x, int y, int b)
555{
556        adjustingvalue = 0;
557        chselecting = 0;
558        DCanvasWindow::mouseunclick(x, y, b);
559}
560
561bool NeuroProbe::insideChSelector(int x, int y)
562{
563        if ((x > 0) && (x < chselwidth))
564        {
565                int sy = size.y;
566                if (chsel >= 0) sy -= textHeight();
567                return ((y<sy) && (y>(sy - textHeight())));
568        }
569        return 0;
570}
571
572int NeuroProbe::mouseclick(int x, int y, int b)
573{
574        if ((b & LeftButton) && insideChSelector(x, y))
575        {
576                chselx0 = x; chsel0 = chsel;
577                chselecting = 1;
578                requestPaint();
579                return LeftButton;
580        }
581        int ret = DCanvasWindow::mouseclick(x, y, b);
582        if (ret)
583        {
584                link->diagram.selection.set(Model::neuroToMap(link->n->refno));
585                return ret;
586        }
587        if (b & LeftButton)
588        {
589                if (x > size.x - 16)
590                {
591                        link->n->flags |= Neuro::HoldState;
592                        holdismine = 1;
593                        adjustingvalue = 1;
594                        mouse(x, y, b);
595                        return LeftButton;
596                }
597                else if (y > size.y - 16)
598                {
599                        link->n->flags ^= Neuro::HoldState;
600                        holdismine = ((link->n->flags&Neuro::HoldState) != 0);
601                        requestPaint();
602                        return LeftButton;
603                }
604        }
605        return 0;
606}
607
608SString NeuroProbe::hint(int x, int y)
609{
610        if ((chsel >= 0) && (x<size.x - 16) && (y>size.y - 16))
611                return SString((link->n->flags&Neuro::HoldState) ? "Click to release" : "Click to hold");
612        else if (insideChSelector(x, y))
613                return SString::sprintf("channel %d of %d (click and drag to switch channels)", chsel, chnum);
614        return DCanvasWindow::hint(x, y);
615}
616
617/** @return true == channel changed */
618bool NeuroProbe::selectChannel(int ch)
619{
620        if (ch < -chnum2) ch = -chnum2; else if (ch >= chnum) ch = chnum - 1;
621        if (ch == chsel) return false;
622        chsel = ch;
623        neurochart.data.clear();
624        return true;
625}
626
627void NeuroProbe::updateChannelCount(NeuroImpl *ni)
628{
629        if (!ni) return;
630        chnum = ni->getChannelCount();
631        chnum2 = ni->getDrawingCount();
632        if (chsel >= chnum) selectChannel(chnum - 1);
633        if (chsel < -chnum2) selectChannel(-chnum2);
634}
635
636void NeuroProbe::sampling()
637{
638        NeuroImpl *ni = NeuroNetImpl::getImpl(link->n);
639        updateChannelCount(ni);
640        if (!chsel)
641                neurochart.data += (float)(link->n->state);
642        else
643                neurochart.data += (float)(ni->getState(chsel));
644        whichdrawing = -1;
645}
646
647////
648
649void NeuroDiagram::probeSampling(void*obj, long dummy)
650{
651        FOREACH(NeuroProbe*,pr,probes) pr->sampling();
652        requestPaint();
653}
654
655void NeuroDiagram::updatePlugin()
656{
657        //int needplugin=(!probes)>0;
658        bool needplugin = livewire;
659        if (needplugin == pluginactive) return;
660        if (needplugin)
661        {
662                if (!cr) return;
663                sim = cr->group->getLibrary().sim;
664                pluginnode = sim->l_plugin.add(STATRICKCALLBACK(this, &NeuroDiagram::probeSampling, 0));
665        }
666        else
667                sim->l_plugin.remove(pluginnode);
668        pluginactive = needplugin;
669}
670
671/////////////
672
673void NeuroDiagramSelection::updateSelection(MultiRange& newsel)
674{
675        MultiRange added = getAdded(newsel);
676        if (!added.isEmpty())
677        {
678                added.shift(Model::mapToNeuro(0));
679                added.intersect(0, diagram.countNeurons() - 1);
680                for (int i = 0; i < added.rangeCount(); i++)
681                {
682                        const IRange &r = added.getRange(i);
683                        for (int j = r.begin; j <= r.end; j++)
684                                diagram.getNS(j)->selected = 1;
685                }
686        }
687        MultiRange removed = getRemoved(newsel);
688        if (!removed.isEmpty())
689        {
690                removed.shift(Model::mapToNeuro(0));
691                removed.intersect(0, diagram.countNeurons() - 1);
692                for (int i = 0; i < removed.rangeCount(); i++)
693                {
694                        const IRange &r = removed.getRange(i);
695                        for (int j = r.begin; j <= r.end; j++)
696                                diagram.getNS(j)->selected = 0;
697                }
698        }
699        if (!diagram.indestructor) diagram.requestPaint();
700}
Note: See TracBrowser for help on using the repository browser.