void PolynomialFitting::Init(const std::string& file) { std::vector<double> x; std::vector<double> y; Load(file, x, y); MatrixData X(x.size(), std::vector<double>(mPower + 1, 0)); for(size_t i = 0;i < x.size(); ++i) { X[i][0] = 1; for(size_t j = 1; j <= mPower; ++j) X[i][j] = X[i][j - 1] * x[i]; } MatrixData Y(1, std::vector<double>(y)); Matrix xm(X), ym(Y); ym = ym.Transpose(); Matrix res = xm.Transpose() * xm; res = res.Inverse() * xm.Transpose() * ym; X = res.Transpose().GetData(); std::cout << "Value: " << std::endl; for(int i = 0;i < X[0].size(); ++i) std::cout << X[0][i] << " "; std::cout << std::endl; mCofficient = Polynomial(X[0]); }
Eigen::MatrixXd kalmanFilter::kalmanFunc(Eigen::MatrixXd phi, Eigen::MatrixXd upsilon, Eigen::MatrixXd basis, Eigen::MatrixXd initial, Eigen::MatrixXd initial_cov, int measurements, Eigen::MatrixXd noise){ Eigen::MatrixXd x(measurements,2), xe(measurements,2), ym(measurements,1), covariance(measurements,2); Eigen::MatrixXd gain; x.setZero(measurements,2); x.row(0) = initial; xe.setZero(measurements,2); ym.setZero(measurements,1); ym.row(0) = (basis*x.row(0).transpose()).transpose()+(noise.cwiseSqrt().row(0))*Eigen::MatrixXd::Random(1,1); covariance.setZero(measurements,2); covariance.row(0) = initial_cov.diagonal().transpose(); // Main loop for(int i=0; i<(measurements-1); i++){ // Truth and Measurements x.row(i+1) = (phi*x.row(i).transpose()+upsilon*(noise.cwiseSqrt().row(1))*Eigen::MatrixXd::Random(1,1)).transpose(); ym.row(i+1) = (basis*x.row(i+1).transpose()).transpose()+(noise.cwiseSqrt().row(0))*Eigen::MatrixXd::Random(1,1); // Update Equations gain = initial_cov*basis.transpose()*((basis*initial_cov*basis.transpose())+noise.row(0)).cwiseInverse(); initial_cov = (Eigen::MatrixXd::Identity(2,2)-gain*basis)*initial_cov; xe.row(i) = xe.row(i)+(gain*(ym.row(i)-basis*xe.row(i).transpose())).transpose(); // Propagation Equations xe.row(i+1) = (phi*xe.row(i).transpose()).transpose(); initial_cov = phi*initial_cov*phi.transpose()+upsilon*noise.row(1)*upsilon.transpose(); covariance.row(i+1) = initial_cov.diagonal().transpose(); } Eigen::MatrixXd result(measurements,6); result << xe, x, (covariance.cwiseSqrt())*3; return result; }
/* Fit line y = ax+b (lineType ==1) or y = a log(x) + b (lineType == 2) on interval [qmin,qmax] * method == 1 : Least squares fit * method == 2 : Theil's partial robust fit */ void PowerCepstrum_fitTiltLine (PowerCepstrum me, double qmin, double qmax, double *p_a, double *p_intercept, int lineType, int method) { try { double a, intercept; if (qmax <= qmin) { qmin = my xmin; qmax = my xmax; } long imin, imax; if (! Matrix_getWindowSamplesX (me, qmin, qmax, & imin, & imax)) { return; } imin = (lineType == 2 && imin == 1) ? 2 : imin; // log(0) is undefined! long numberOfPoints = imax - imin + 1; if (numberOfPoints < 2) { Melder_throw (U"Not enough points for fit."); } autoNUMvector<double> y (1, numberOfPoints); autoNUMvector<double> x (1, numberOfPoints); for (long i = 1; i <= numberOfPoints; i++) { long isamp = imin + i - 1; x[i] = my x1 + (isamp - 1) * my dx; if (lineType == 2) { x[i] = log (x[i]); } y[i] = my v_getValueAtSample (isamp, 1, 0); } if (method == 3) { // try local maxima first autoNUMvector<double> ym (1, numberOfPoints / 2 + 1); autoNUMvector<double> xm (1, numberOfPoints / 2 + 1); long numberOfLocalPeaks = 0; // forget y[1] if y[2]<y[1] and y[n] if y[n-1]<y[n] ! for (long i = 2; i <= numberOfPoints; i++) { if (y[i - 1] <= y[i] && y[i] > y[i + 1]) { ym[++numberOfLocalPeaks] = y[i]; xm[numberOfLocalPeaks] = x[i]; } } if (numberOfLocalPeaks > numberOfPoints / 10) { for (long i = 1; i <= numberOfLocalPeaks; i++) { x[i] = xm[i]; y[i] = ym[i]; } numberOfPoints = numberOfLocalPeaks; } method = 2; // robust fit of peaks } // fit a straight line through (x,y)'s NUMlineFit (x.peek(), y.peek(), numberOfPoints, & a, & intercept, method); if (p_intercept) { *p_intercept = intercept; } if (p_a) { *p_a = a; } } catch (MelderError) { Melder_throw (me, U": couldn't fit a line."); } }
void BezierWidget::computeMatrices() { QMatrix4x4 xm(cp[0].x(), cp[1].x(), cp[2].x(), cp[3].x(), cp[4].x(), cp[5].x(), cp[6].x(), cp[7].x(), cp[8].x(), cp[9].x(), cp[10].x(), cp[11].x(), cp[12].x(), cp[13].x(), cp[14].x(), cp[15].x()); QMatrix4x4 ym(cp[0].y(), cp[1].y(), cp[2].y(), cp[3].y(), cp[4].y(), cp[5].y(), cp[6].y(), cp[7].y(), cp[8].y(), cp[9].y(), cp[10].y(), cp[11].y(), cp[12].y(), cp[13].y(), cp[14].y(), cp[15].y()); QMatrix4x4 zm(cp[0].z(), cp[1].z(), cp[2].z(), cp[3].z(), cp[4].z(), cp[5].z(), cp[6].z(), cp[7].z(), cp[8].z(), cp[9].z(), cp[10].z(), cp[11].z(), cp[12].z(), cp[13].z(), cp[14].z(), cp[15].z()); matrixX = matrixM * xm * matrixM; matrixY = matrixM * ym * matrixM; matrixZ = matrixM * zm * matrixM; }
int main(int, char**) { using year = std::chrono::year; using month = std::chrono::month; using year_month = std::chrono::year_month; ASSERT_NOEXCEPT( std::declval<const year_month>().year()); ASSERT_SAME_TYPE(year, decltype(std::declval<const year_month>().year())); static_assert( year_month{}.year() == year{}, ""); for (int i = 1; i <= 50; ++i) { year_month ym(year{i}, month{}); assert( static_cast<int>(ym.year()) == i); } return 0; }
void OrganizedData::process(RawData* raw, int nBlock, double pTest, int nSupport) { int nData = raw->nData, nDim = raw->nDim - 1; this->nSupport = nSupport; this->nBlock = nBlock; this->nDim = nDim; train = field<mat>(nBlock,2); test = field<mat>(nBlock,2); support = field<mat>(1,2); mat xm(nSupport,nDim), ym(nSupport,1); vec mark(nData); mark.fill(0); printf("Randomly selecting %d supporting point ...\n", nSupport); for (int i = 0; i < nSupport; i++) { int pos = IRAND(0, nData - 1); while (mark[pos] > 0) pos = IRAND(0, nData - 1); mark[pos] = 1; for (int j = 0; j < nDim; j++) xm(i, j) = raw->X(pos,j); ym(i,0) = raw->X(pos,nDim); } support(0,0) = xm; xm.clear(); support(0,1) = ym; ym.clear(); cout << "Partitioning the remaining data into " << nBlock << " cluster using K-Mean ..." << endl; vvd _remain; for (int i = 0; i < nData; i++) if (!mark(i)) { rowvec R = raw->X.row(i); _remain.push_back(r2v(R)); } mat remaining = v2m(_remain); mark.clear(); RawData* remain = new RawData(remaining); KMean* partitioner = new KMean(remain); Partition* clusters = partitioner->cluster(nBlock); cout << "Packaging training/testing data points into their respective cluster" << endl; for (int i = 0; i < nBlock; i++) { cout << "Processing block " << i + 1 << endl; int bSize = (int) clusters->member[i].size(), tSize = (int) floor(bSize * pTest), pos = 0, counter = 0; mark = vec(bSize); mark.fill(0); if (bSize > tSize) // if we can afford to draw tSize test points from this block without depleting it ... { mat xt(tSize,nDim), yt(tSize,1); for (int j = 0; j < tSize; j++) { pos = IRAND(0, bSize - 1); while (mark[pos] > 0) pos = IRAND(0, bSize - 1); mark[pos] = 1; pos = clusters->member[i][pos]; for (int t = 0; t < nDim; t++) xt(j, t) = remain->X(pos,t); yt(j,0) = remain->X(pos,nDim); } bSize -= tSize; nTest += tSize; test(i,0) = xt; xt.clear(); test(i,1) = yt; yt.clear(); } nTrain += bSize; mat xb(bSize,nDim), yb(bSize,1); //cout << remain->X.n_rows << endl; for (int j = 0; j < (int)mark.n_elem; j++) if (mark[j] < 1) { for (int t = 0; t < nDim; t++) { xb(counter,t) = remain->X(clusters->member[i][j],t); } yb(counter++,0) = remain->X(clusters->member[i][j],nDim); } train(i,0) = xb; xb.clear(); train(i,1) = yb; yb.clear(); mark.clear(); printf("Done ! nData[%d] = %d, nTrain[%d] = %d, nTest[%d] = %d .\n", i, (int) clusters->member[i].size(), i, train(i,0).n_rows, i, (int) test(i,0).n_rows); } }
void MG_poseReader::draw( M3dView & view, const MDagPath & path, M3dView::DisplayStyle dispStyle, M3dView::DisplayStatus status ) { MPlug sizeP (thisMObject(),size); double sizeV; sizeP.getValue(sizeV); MPlug poseMatrixP (thisMObject(),poseMatrix); MObject poseMatrixData; poseMatrixP.getValue(poseMatrixData); MFnMatrixData matrixFn(poseMatrixData); MMatrix poseMatrixV =matrixFn.matrix(); MPlug readerMatrixP (thisMObject(),readerMatrix); MObject readerMatrixData; readerMatrixP.getValue(readerMatrixData); matrixFn.setObject(readerMatrixData); MMatrix readerMatrixV =matrixFn.matrix(); MMatrix poseMatrixFix =poseMatrixV*readerMatrixV.inverse(); MPlug aimAxisP (thisMObject(),aimAxis); int aimAxisV; aimAxisP.getValue(aimAxisV); MVector aimBall; MPlug readerOnOffP(thisMObject(),readerOnOff); MPlug axisOnOffP(thisMObject(),axisOnOff); MPlug poseOnOffP(thisMObject(),poseOnOff); double readerOnOffV; double axisOnOffV; double poseOnOffV; readerOnOffP.getValue(readerOnOffV); axisOnOffP.getValue(axisOnOffV); poseOnOffP.getValue(poseOnOffV); MPlug xPositiveP (thisMObject(),xPositive); MPlug xNegativeP (thisMObject(),xNegative); double xPositiveV; double xNegativeV; xPositiveP.getValue(xPositiveV); xNegativeP.getValue(xNegativeV); double xColor = xPositiveV; if (xPositiveV==0) { xColor=xNegativeV; } MPlug yPositiveP (thisMObject(),yPositive); MPlug yNegativeP (thisMObject(),yNegative); double yPositiveV; double yNegativeV; yPositiveP.getValue(yPositiveV); yNegativeP.getValue(yNegativeV); double yColor = yPositiveV; if (yPositiveV==0) { yColor=yNegativeV; } MPlug zPositiveP (thisMObject(),zPositive); MPlug zNegativeP (thisMObject(),zNegative); double zPositiveV; double zNegativeV; zPositiveP.getValue(zPositiveV); zNegativeP.getValue(zNegativeV); double zColor = zPositiveV; if (zPositiveV==0) { zColor=zNegativeV; } if (aimAxisV==0) { aimBall.x=poseMatrixFix[0][0]; aimBall.y=poseMatrixFix[0][1]; aimBall.z=poseMatrixFix[0][2]; } else if (aimAxisV==1) { aimBall.x=poseMatrixFix[1][0]; aimBall.y=poseMatrixFix[1][1]; aimBall.z=poseMatrixFix[1][2]; }else { aimBall.x=poseMatrixFix[2][0]; aimBall.y=poseMatrixFix[2][1]; aimBall.z=poseMatrixFix[2][2]; } //***************************************************************** // Initialize opengl and draw //***************************************************************** view.beginGL(); glPushAttrib( GL_ALL_ATTRIB_BITS ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glLineWidth(2); if(status == M3dView::kLead) glColor4f(0.0,1.0,0.0,0.3f); else glColor4f(1.0,1.0,0.0,0.3f); MVector baseV(0,0,0); MVector xp(1*sizeV,0,0); MVector xm(-1*sizeV,0,0); MVector yp(0,1*sizeV,0); MVector ym(0,-1*sizeV,0); MVector zp(0,0,1*sizeV); MVector zm(0,0,-1*sizeV); double * red; red = new double[4]; red[0]=1; red[1]=0; red[2]=0; red[3]=1; double * green; green = new double[4]; green[0]=0; green[1]=1; green[2]=0; green[3]=1; double * blue; blue = new double[4]; blue[0]=0; blue[1]=0; blue[2]=1; blue[3]=1; double * yellow; yellow = new double[4]; yellow[0]=1; yellow[1]=1; yellow[2]=0.2; yellow[3]=0.3; if (readerOnOffV==1) { drawSphere(sizeV,20,20,baseV,yellow); } if (axisOnOffV==1) { drawSphere(sizeV/7,15,15,xp,red); drawSphere(sizeV/7,15,15,xm,red); drawSphere(sizeV/7,15,15,yp,green); drawSphere(sizeV/7,15,15,ym,green); drawSphere(sizeV/7,15,15,zp,blue); drawSphere(sizeV/7,15,15,zm,blue); } if (poseOnOffV==1) { double* color = blendColor(xColor,yColor,zColor,1); drawSphere(sizeV/7,15,15,aimBall*sizeV,color); } glDisable(GL_BLEND); glPopAttrib(); }
//рисуем куб, связанный с подвижной системой координат void DrawBox(HWND hwnd, HDC hdc, ANGLS an) { sf=sin(M_PI*an.fi/180); cf=cos(M_PI*an.fi/180); st=sin(M_PI*an.teta/180); ct=cos(M_PI*an.teta/180); double xe, ye; int x1,y1,x2,y2; double xt1,yt1,zt1,xt2,yt2,zt2; int j; for(int i=0; i<4; i++) { j = i + 1; if(j==4) j = 0; xt1 = Point[i].x; yt1 = Point[i].y; zt1 = Point[i].z; xt2 = Point[j].x; yt2 = Point[j].y; zt2 = Point[j].z; xe = Xe(xt1, yt1, zt1); ye=Ye(xt1,yt1,zt1); x1=xn(xe); y1=ym(ye); xe = Xe(xt2, yt2, zt2); ye=Ye(xt2,yt2,zt2); x2=xn(xe); y2=ym(ye); MoveToEx(hdc,x1,y1,NULL); LineTo(hdc,x2,y2); } for(int i=4; i<8; i++) { j = i + 1; if(j==8) j = 4; xt1 = Point[i].x; yt1 = Point[i].y; zt1 = Point[i].z; xt2 = Point[j].x; yt2 = Point[j].y; zt2 = Point[j].z; xe = Xe(xt1, yt1, zt1); ye=Ye(xt1,yt1,zt1); x1=xn(xe); y1=ym(ye); xe = Xe(xt2, yt2, zt2); ye=Ye(xt2,yt2,zt2); x2=xn(xe); y2=ym(ye); MoveToEx(hdc,x1,y1,NULL); LineTo(hdc,x2,y2); } for(int i=0; i<4; i++) { xt1 = Point[i].x; yt1 = Point[i].y; zt1 = Point[i].z; xt2 = Point[i+4].x; yt2 = Point[i+4].y; zt2 = Point[i+4].z; xe = Xe(xt1, yt1, zt1); ye=Ye(xt1,yt1,zt1); x1=xn(xe); y1=ym(ye); xe = Xe(xt2, yt2, zt2); ye=Ye(xt2,yt2,zt2); x2=xn(xe); y2=ym(ye); MoveToEx(hdc,x1,y1,NULL); LineTo(hdc,x2,y2); } for(int i=0; i<2; i++) { xt1 = Point[i].x; yt1 = Point[i].y; zt1 = Point[i].z; xt2 = Point[i+2].x; yt2 = Point[i+2].y; zt2 = Point[i+2].z; xe = Xe(xt1, yt1, zt1); ye=Ye(xt1,yt1,zt1); x1=xn(xe); y1=ym(ye); xe = Xe(xt2, yt2, zt2); ye=Ye(xt2,yt2,zt2); x2=xn(xe); y2=ym(ye); MoveToEx(hdc,x1,y1,NULL); LineTo(hdc,x2,y2); } }
//рисуем картину приложения void LinePicture(HWND hwnd, int Context) { //выбираем нужный контектс устройства для экрана //--------------------------------------------- HDC hdcWin; PAINTSTRUCT ps; //получаем контест устройства для экрана if(Context == 1) hdcWin = BeginPaint(hwnd, &ps); else hdcWin = GetDC(hwnd); //----------------------------------------------- //связываем размеры поля вывода с размерами клиентской области окна //-------------------------------------------------------------------- RECT rct; GetClientRect(hwnd,&rct); ne1 = rct.left+50; ne2 = rct.right -50; me1 = rct.bottom -50; me2 = rct.top + 50; //------------------------------------------------------------------ //создаем контекст экрана //------------------------------------------------------------ HDC hdc = CreateCompatibleDC(hdcWin); //создаем контекст //памяти связаный с контекстом экрана //памяти надо придать вид экрана - подходт битовая карта с форматом // как у экрана. В памяти будем рисовать на битовой карте HBITMAP hBitmap, hBitmapOld; hBitmap = CreateCompatibleBitmap(hdcWin, ne2, me1); //создаем //битовую карту совместмую с контекстом экрана hBitmapOld = (HBITMAP)SelectObject(hdc, hBitmap); //помещаем // битовую карту в контекст памяти //-------------------------------------------------------------- //выводи значения углов в верхней части поля вывода //-------------------------------------------------------- //создание прямоугольной области для вывода углов поворота HRGN hrgn2 = CreateRectRgn(ne1,me2-30,ne2,me1); //заливаем выделенную область серым цветом HBRUSH hBrush2 = CreateSolidBrush(RGB(0x80,0x80,0x80)); HBRUSH hBrushOld = (HBRUSH)SelectObject(hdc,hBrush2); FillRgn(hdc,hrgn2,hBrush2); SelectObject(hdc,hBrushOld); DeleteObject(hBrush2); DeleteObject(hrgn2); //вычисление угловых коэффициентов поворота системы координат sf=sin(M_PI*angl.fi/180); cf=cos(M_PI*angl.fi/180); st=sin(M_PI*angl.teta/180); ct=cos(M_PI*angl.teta/180); //информация об углах поворота системы координат TCHAR ss[20]; SetBkColor(hdc,RGB(0xC0,0xC0,0xC0)); SetTextColor(hdc,RGB(0,0,0x80)); swprintf_s(ss,20,L"fi = %4.0lf",angl.fi); TextOut(hdc,(ne1+ne2)/2-80,me2-25,ss,9); swprintf_s(ss,20,L"teta = %4.0lf",angl.teta); TextOut(hdc,(ne1+ne2)/2+20,me2-25,ss,11); //------------------------------------------------ //выделение памяти под Z-буфер и начальное его заполнение //------------------------------------------------------------- //вычисляем число пикселей в поле вывода Np = ne2-ne1 + 1, Mp = me1-me2 +1, NM = Np*Mp; //выделяем память под Z-буфер для каждого пикселя zb = new ZbuffS [NM]; //начальное заполнение z-буфера для каждого пикселя for ( long unsigned p=0; p<NM; p++) { zb[p].z = -1000; zb[p].c.R = 0xC0; zb[p].c.G = 0xC0; zb[p].c.B = 0xC0; } //----------------------------------------------------------- //"рисуем" магнитную пластинку заданным цветом заполняя Z-буфер //----------------------------------------------------------------------- //мировые координаты проецируемой точки double xt1,yt1,zt1; //видовые координаты проецируемой точки double xe,ye,ze1; //пиксельные координаты проецируемой точки int x1,y1; //пиксельные координаты 4-х углов пластинки int xp[4], yp[4]; //видовые z-координаты 4-х углов пластинки double ze[4]; for(int n=0; n<4; n++) { xt1 = Px[n]; yt1 = Py[n]; zt1 = Pz[n]; xe = Xe(xt1, yt1, zt1); ye=Ye(xt1,yt1,zt1); ze1=Ze(xt1,yt1,zt1); x1=xn(xe); y1=ym(ye); xp[n] = x1; yp[n] = y1; ze[n] = ze1; } //ZbufParallelogram(hdc,xp[0],yp[0],ze[0],xp[1],yp[1],ze[1], //xp[2],yp[2],ze[2],xp[3],yp[3],ze[3],RGB(255,255,0)); //------------------------------------------------------------------ //"рисуем" линии поля заполняя Z-буфер //---------------------------------------------------------------- for (int i = 0; i < 20; i++) { LineField(hdc,PointB[i],RGB(255,0,0),1); } for(int i=20; i<40; i++) { LineField(hdc,PointB[i],RGB(0,0,255), 1); } for (int i = 40; i<60; i++) { LineField(hdc, PointB[i], RGB(0, 255,0), 1); } //----------------------------------------------------------------------- //выводим содержимое Z-буфера в контекст памяти //-------------------------------------------------------------------- //двигаемся по всем пикселям окна вывода for (unsigned long ij=0; ij<NM; ij++) { x1 = ne1 + ij%Np; y1 = me2 + ij/Np; SetPixel(hdc,x1,y1,RGB(zb[ij].c.R,zb[ij].c.G,zb[ij].c.B)); } delete [] zb; //очищаем память под Z-буфером //------------------------------------------------------------- //рисуем координтные оси //------------------------------------------------------------------------ HPEN hPen = CreatePen(PS_SOLID,1,RGB(0,255,255)); HPEN hPenOld = (HPEN)SelectObject(hdc,hPen); int x2,y2; //ось Ox xe=Xe(-xmax/3,0,0); ye=Ye(-xmax/3,0,0); x1=xn(xe); y1=ym(ye); xe=Xe(xmax,0,0); ye=Ye(xmax,0,0); x2=xn(xe); y2=ym(ye); MoveToEx(hdc,x1,y1,NULL); LineTo(hdc,x2,y2); SetBkColor(hdc,RGB(0xC0,0xC0,0xC0)); SetTextColor(hdc,RGB(120,120,120)); TextOut(hdc,x2, y2, _T("X"),1); //Ось Oy xe=Xe(0,-ymax/3, 0); ye=Ye(0,-ymax/3,0); x1=xn(xe); y1=ym(ye); xe=Xe(0,ymax, 0); ye=Ye(0,ymax,0); x2=xn(xe); y2=ym(ye); MoveToEx(hdc,x1,y1,NULL); LineTo(hdc,x2,y2); SetBkColor(hdc,RGB(0xC0,0xC0,0xC0)); SetTextColor(hdc,RGB(120,120,120)); TextOut(hdc,x2, y2, _T("Y"),1); //Ось Oz xe=Xe(0,0, 0); ye=Ye(0,0,-zmax/3); x1=xn(xe); y1=ym(ye); xe=Xe(0,0, 0); ye=Ye(0,0,zmax); x2=xn(xe); y2=ym(ye); MoveToEx(hdc,x1,y1,NULL); LineTo(hdc,x2,y2); SetBkColor(hdc,RGB(0xC0,0xC0,0xC0)); SetTextColor(hdc,RGB(120,120,120)); TextOut(hdc,x2, y2, _T("Z"),1); SelectObject(hdc,hPenOld); DeleteObject(hPen); //----------------------------------------------------------------------------- //рисуем куб //---------------------------------------------------------------------- hPen = CreatePen(PS_SOLID,1,RGB(160,160,160)); hPenOld = (HPEN)SelectObject(hdc,hPen); DrawBox(hwnd, hdc, angl); SelectObject(hdc,hPenOld); DeleteObject(hPen); //------------------------------------------------------------------------ //копируем контекст памяти в контекст экрана //----------------------------------------------------------------------- BitBlt(hdcWin,ne1,me2-30,ne2,me1,hdc,ne1,me2-30,SRCCOPY); //---------------------------------------------------------------------- //завершаем работу с контекстами и памятью //------------------------------------------------------------------- SelectObject(hdc, hBitmapOld); //востанавливаем контекст памяти DeleteObject(hBitmap); //убираем битовую карту DeleteDC(hdc); // освобождаем контекст памяти //освобождаем контекст экрана if(Context == 1) EndPaint(hwnd, &ps); else ReleaseDC(hwnd, hdcWin); }
//"рисует" одну линию поля из начальной точки PointB //с помощью функций работающих с Z-буфером void LineField(HDC hdc,POINT3 PointB,COLORREF rgb, double force) { VECTORS vect; vect.x = PointB.x; vect.y = PointB.y; vect.z = PointB.z; //видовые координаты проецируемой точки double xe, ye, ze1, ze2; //координаты пикселов int x1,y1,x2,y2; double dt = force > 0 ? 0.1 : -0.1; //длина шага на линии поля double x, y, z, Hx, Hy, Hz, Ha; int k = 0; VECMAG mag; int step = 0; double xt1,yt1,zt1,xt2,yt2,zt2; do { step++; x = vect.x; y = vect.y; z = vect.z; mag = magn(x,y,z); Hx = mag.hx; Hy = mag.hy; Hz = mag.hz; Ha = sqrt(Hx*Hx + Hy*Hy + Hz*Hz); vect.dx = Hx/Ha; vect.dy = Hy/Ha; vect.dz = Hz/Ha; xt1 = vect.x; yt1 = vect.y; zt1 = vect.z; xt2 = xt1 + vect.dx*dt; yt2 = yt1 + vect.dy*dt; zt2 = zt1 + vect.dz*dt; xe = Xe(xt1, yt1, zt1); ye=Ye(xt1,yt1,zt1); ze1=Ze(xt1,yt1,zt1); x1=xn(xe); y1=ym(ye); xe = Xe(xt2, yt2, zt1); ye=Ye(xt2,yt2,zt2); ze2=Ze(xt2,yt2,zt2); x2=xn(xe); y2=ym(ye); //"рисуем" отрезок линии поля ZbufLineWidth(hdc,x1,y1,x2,y2,ze1,ze2,3,rgb); vect.x = xt2; vect.y = yt2; vect.z = zt2; //после 10-и шагов на лини поля "рисуем" стрелку k++; if(k == 10) { arrowVector(hdc,x1,y1,x2,y2,ze2,RGB(0,0,255)); k = 0; } //прекращаем рисовать линию поля на границе куба } while (step < 1000 && (x>-xmax) && (x<xmax) && (y>-ymax) && (y<ymax) && (z>-zmax) && (z<zmax)); }