Sujet : 'Graphics' of libwy
De : wyniijj5 (at) *nospam* gmail.com (wij)
Groupes : comp.lang.c++Date : 15. Dec 2024, 11:04:50
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <4ffeda4ce7116f70754bcfcaee87cb729081fac3.camel@gmail.com>
User-Agent : Evolution 3.50.2 (3.50.2-1.fc39)
I had headache whenevr I think about graphics in C++. Why C++ does not provide
a graphics library (lots complaint about this), not even a simplest one for
demonstrating its 'power' of C++ itself? Then, I suddenly realized that the
minimal answer is already there because the resolution of modern text screen
(emulator) is barely enough (width can be >320).
---------- t_txtwind.cpp
#include <Wy.stdio.h>
#include <Wy.math.h>
#include <Wy.signal.h>
#include <CSCall/Array2D.h>
#include <CSCall/ioctl.h>
using namespace Wy;
typedef float FuncValue;
constexpr FuncValue FMinX=-5;
constexpr FuncValue FMaxX= 5;
FuncValue func(FuncValue x) { // function to plot
return ::sin(x);
};
//---------------------------------------------
typedef char Pixel;
Array2D<Pixel> txtwin;
// [Syn] Plot func(FuncValue) in current terminal (text window)
// (window size can change)
//
void plot() {
constexpr Pixel BgChar=' ';
constexpr Pixel FgChar='x';
Errno r;
WinSize ws;
if((r=getwinsize(cout,ws))!=Ok) {
WY_THROW(r);
}
Array<FuncValue> varr;
FuncValue dx= (FMaxX-FMinX)/ws.col();
FuncValue ymin= Limits<FuncValue>::Max;
FuncValue ymax= Limits<FuncValue>::Min;
for(FuncValue x=FMinX; x<=FMaxX; x+=dx) {
FuncValue v= func(x);
if(v>ymax) {
ymax=v;
}
if(v<ymin) {
ymin=v;
}
varr << func(x);
}
if((r=txtwin.reset(ws.col(),ws.row()))!=Ok) {
WY_THROW(r);
}
::memset(txtwin.header()._data(),BgChar,txtwin.size());
for(size_t x=0; x<varr.size(); ++x) {
unsigned int y=((varr[x]-ymin)/(ymax-ymin))*(txtwin.height()-1);
txtwin.header().write_point(x,y,FgChar);
}
for(size_t y=0; y<txtwin.height(); ++y) {
cout << StrSeg(&txtwin.header().at(0,y), txtwin.header().width()) << WY_ENDL;
}
};
void winch_handler(int, ::siginfo_t*, void*) {
SignaledContext sigcontext;
plot();
};
int main(int argc, const char* argv[])
try {
Errno r;
if((r=sig_setact(SIGWINCH, SigAct(winch_handler) ))!=Ok) {
WY_THROW(r);
}
plot();
for(int wcnt=0; wcnt<100; ++wcnt) { // wait for 100 win changes or Cntl-C
::pause();
}
cout << "OK" WY_ENDL;
return 0;
}
catch(const Errno& e) {
cerr << wrd(e) << WY_ENDL;
return -1; // e.c_errno();
}
catch(...) {
cerr << "main() caught(...)" WY_ENDL;
throw;
};
-------------------------
[]$ g++ t_txtwind.cpp -lwy
[]$ ./a.out
xxxxxx xxxxx
x x x
x x x
x x x
x x x
x
x x
x x x
x
x x
x x
x
x x x
x x x
x x x
x
x x
x x
x
x x x
x x
x
x x x
x x x
x x x
x x x
xx xxx xxxxxx
x