0

I want to program 3D transformations in QT. I already wrote code to draw a cube. I don't know what I should to do to program translation, rotate and scaling. I only found matrixes: https://www.tutorialspoint.com/computer_graphics/3d_transformation.htm, but I don't know how to use it.

#include "widget.h"
#include "ui_widget.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    img = new QImage(600,600,QImage::Format_RGB32);
    ui->setupUi(this);
    drawCube(200, 300);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::paintEvent(QPaintEvent*)
{
    QPainter p(this);
    p.drawImage(0,0,*img);
}

void Widget::drawCube(int x, int y)
{
    drawLine(x,y,x+100,y);
    drawLine(x,y-100,x+100,y-100);
    drawLine(x+100,y,x+100,y-100);
    drawLine(x,y,x,y-100);
    drawLine(x+50,y-50,x+150,y-50);
    drawLine(x+50,y-150,x+150,y-150);
    drawLine(x+150,y-50,x+150,y-150);
    drawLine(x+50,y-50,x+50,y-150);
    drawLine(x,y,x+50,y-50);
    drawLine(x+100,y,x+150,y-50);
    drawLine(x+100,y-100,x+150,y-150);
    drawLine(x,y-100,x+50,y-150);
}

void Widget::drawLine(int x1, int y1, int x2, int y2)
{
    uchar * bits = img->bits();
    float a,b;
    int x;
    a=(float)(y2-y1)/(x2-x1);
    b=y1-a*x1;
    if(x1>x2)
    {
        swap(x1,x2);
        swap(y1,y2);
    }
    if(y1<=y2)
    {
        for (int y=y1; y<y2; y++)
        {
            if(x1!=x2) x=(y-b)/a;
            else x=x1;
            colorPixel(x,y,bits);
        }
    }
    if(y1>y2)
    {
        for (int y=y2; y<y1; y++)
        {
            if(x1!=x2) x=(y-b)/a;
            else x=x1;
            colorPixel(x,y,bits);
         }
    }
    for (int x=x1; x<x2; x++)
    {
        int y=a*x+b;
        colorPixel(x,y,bits);
    }
}

void Widget::colorPixel(int x, int y, unsigned char * bits)
{
    if (x < 0 || y < 0 || x >= 600 || y >= 600) return;
    int p = x * 4 + y * 600 * 4;
    bits[p] = 255;
    bits[p+1] = 255;
    bits[p+2] = 255;
}
halfer
  • 18,701
  • 13
  • 79
  • 158
  • 1
    The 'glm' lib could be handy for you. – Hannes Hauptmann Aug 02 '17 at 16:46
  • I can't use glm :( My teacher prohibit that. – StachuOddawajPieniadzeZaLas Aug 02 '17 at 16:53
  • Please, have a look at my answer to [SO: How to compose a matrix to perform isometric (dimetric) projection of a world coordinate?](https://stackoverflow.com/a/44503376/7478597). It contains some basic "3d math" and a simple 3d renderer based on `QPainter` functions only. – Scheff's Cat Aug 03 '17 at 07:53
  • I'd expect any Qt 3D graphics code to be at least using things like QMatrix4x4 / QTransform, and maybe even the newfangled Qt3DCore::QTransform (although probably not the latter for this sort of SW rendering!) – timday Aug 03 '17 at 09:50

0 Answers0