我正在尝试使用C ++和DirectX绘制一个使用以下代码的三角形:
Renderer.h
#pragma once
#include "DirectX.h"
#include "Camera.h"
#include "OBJMesh.h"
class Renderer : public DirectX
{
public:
Renderer(std::string windowTitle, int x, int y, unsigned int windowWidth, unsigned int windowHeight, bool fullscreen);
~Renderer();
void Update();
void Render();
protected:
OBJMesh* modelMesh;
Camera* camera;
VERTEX vertices[3];
};
Renderer.cpp
#include "Renderer.h"
Renderer::Renderer(std::string windowTitle, int x, int y, unsigned int windowWidth, unsigned int windowHeight, bool fullscreen) : DirectX(windowTitle, x, y, windowWidth, windowHeight, fullscreen)
{
//camera = new Camera(Vector3(0.0f, -100.0f, 5000.0f), 0.0f, 0.0f);
camera = new Camera(0.0f, 0.0f, D3DXVECTOR3(0.0f, 0.0f, 10.0f));
OBJMesh* modelMesh = new OBJMesh("../Models/Tank/destroyedTank.obj");
VERTEX v1, v2, v3;
v1.x = 0.0f;
v1.y = -1.0f;
v1.z = 0.5f;
v1.color = D3DCOLOR_XRGB(0, 0, 255);
v2.x = 1.0f;
v2.y = 1.0f;
v2.z = 0.5f;
v2.color = D3DCOLOR_XRGB(0, 255, 0);
v3.x = -1.0f;
v3.y = 1.0f;
v3.z = 0.5f;
v3.color = D3DCOLOR_XRGB(255, 0, 0);
vertices[0] = v1;
vertices[1] = v2;
vertices[2] = v3;
device->CreateVertexBuffer(3 * sizeof(VERTEX), 0, VERTEXFORMAT, D3DPOOL_MANAGED, &vertexBuffer, NULL);
VOID* lockingAd;
vertexBuffer->Lock(0, 0, (void**)&lockingAd, 0);
memcpy(lockingAd, vertices, sizeof(vertices));
vertexBuffer->Unlock();
device->SetRenderState(D3DRS_LIGHTING, FALSE); //turn off lighting - DirectX needs to know this :(
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); //turns off face culling (for now)
}
Renderer::~Renderer()
{
delete camera;
}
void Renderer::Update()
{
window->Update();
float msec = Window::GetGameTimer()->GetFrameTime();
camera->Update(msec);
}
void Renderer::Render()
{
device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(40, 40, 40), 1.0f, 0);
device->BeginScene(); //Must be used as it tells DirectX we're starting to draw stuff.
D3DXMATRIX worldMat;
D3DXMatrixTranslation(&worldMat, 0.0f, 0.0f, 0.0f);
device->SetTransform(D3DTS_WORLD, &worldMat);
device->SetTransform(D3DTS_VIEW, &camera->BuildViewMatrix());
D3DXMATRIX projMatrix;
D3DXMatrixPerspectiveFovLH( &projMatrix,
D3DXToRadian(45),
(float)width/(float)height,
1.0f,
10000.0f);
device->SetTransform(D3DTS_PROJECTION, &projMatrix);
device->SetFVF(VERTEXFORMAT);
device->SetStreamSource(0, vertexBuffer, 0, sizeof(VERTEX));
device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
device->EndScene(); //Thank you for waiting, I have finished drawing stuff on the screen, please handle the rest Mr DirectX.
device->Present(NULL, NULL, NULL, NULL);
}
但是,当我将顶点数组更改为头文件中的VERTEX* vertices
和我的cpp文件中的vertices = new VERTEX[3]
时,它不会绘制任何内容......为什么?我该如何解决这个问题?
答案 0 :(得分:1)
我不确定这是不是你的问题,但看起来这可能是违法行:
memcpy( lockingAd, vertices, sizeof(vertices) );
如果vertices
类型为VERTEX[3]
和VERTEX*
,则会执行不同的操作。在第一种情况下,sizeof
将返回数组的大小,而在第二种情况下,它将简单地返回机器上指针的大小,以解决此问题(如果您有固定数量的元素{{ 1}})您应该将其更改为以下内容:
3