Beispiel #1
1
int main()
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	// =======================================================
	//                   INITIALIZE
	// =======================================================
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGl Program", nullptr, nullptr);
	if (window == nullptr)
	{
		printf("Failed to create GLFW window\n");
		glfwTerminate();
		return false;
	}
	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE;
	if (glewInit() != GLEW_OK)
	{
		printf("Failed to initialize GLEW\n");
		return false;
	}

	glViewport(0, 0, WIDTH, HEIGHT);
	glEnable(GL_DEPTH_TEST);

	glfwSetKeyCallback(window, Key_callback);
	glfwSetCursorPosCallback(window, mouse_callback);
	glfwSetScrollCallback(window, scroll_callback);


	// Build and compile our shader program
	Shader lightingShader("../Data/Shaders/vertexShaderLighting_nano.vs",
		"../Data/Shaders/fragmentShaderLighting_nano.frag", 2);

	Shader lampShader("../Data/Shaders/vertexShaderLighting_Lamp.vs",
		"../Data/Shaders/fragmentShaderLighting_Lamp.frag", 0);

	// set the application to capture the cursor
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	glm::vec3 pointLightPositions[] =
	{
		glm::vec3(2.0f, 0.0f, 2.0f),
		glm::vec3(-2.0f, 0.0f, -2.0f),
	};



	DirLight dirlight(lightingShader, vect3(-0.2f, -1.0f, -0.3f), vect3(255, 255, 255), 0.5f);
	PointLight pointLight1(lightingShader, pointLightPositions[0], vect3(255, 255, 255), 0.5f);
	PointLight pointLight2(lightingShader, pointLightPositions[1], vect3(255, 255, 255), 0.5f);
	//PointLight pointLight3(lightingShader, pointLightPositions[2], vect3(255, 255, 255), 1.0f);
	//PointLight pointLight4(lightingShader, pointLightPositions[3], vect3(255, 255, 255), 1.0f);
	SpotLight spotLight(lightingShader, MainCamera.Position, MainCamera.Front, vect3(255, 255, 255), 1.0f);

	GLfloat time = glfwGetTime();
	Model nanosuit("../Data/Models/Box/OutPutModel.txt");
	time = glfwGetTime() - time;
	printf("Time to load: %f", time);

	nanosuit.SetPosition(glm::vec3(0.0f, 0.0f, 0.0f));
	
	// =======================================================
	//                  MAIN UPDATE LOOP
	// =======================================================
	//float count = 0;
	//GLfloat time = 0;

	while (!glfwWindowShouldClose(window))
	{

		// Update deltaTime
		GLfloat currentFrame = glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;

		// FPS check
		//if (time >= 1.0f)
		//{
		//	printf("FPS: %f", count);
		//	time = 0;
		//	count = 0;
		//}

		// check and call events
		glfwPollEvents();
		UpdateCamera();

		// Rendering commands here
		//glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
		glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// draw triangle
		lightingShader.Use();

		GLint viewPosLoc = lightingShader.GetUniformLocation("viewPos");
		glUniform3f(viewPosLoc, MainCamera.Position.x, MainCamera.Position.y, MainCamera.Position.z);

		// Directional light
		dirlight.Update();

		// Point lights		
		pointLight1.Update(0);
		pointLight2.Update(1);

		// SpotLight
		spotLight.SetPosDir(MainCamera.Position, MainCamera.Front);
		spotLight.Update();

		// Camera/View transformation
		glm::mat4 view;
		view = MainCamera.GetViewMatrix();

		// set the projection matrix (perspective)
		glm::mat4 projectionMatrix;

		// FOV, aspect ratio, near plane, far plane
		projectionMatrix = glm::perspective(glm::radians(MainCamera.Zoom), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, farPlane);

		// specify matrices
		GLint modelLoc = lightingShader.GetUniformLocation("modelMat");

		GLint viewLoc = lightingShader.GetUniformLocation("viewMat");
		glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));

		GLint projLoc = lightingShader.GetUniformLocation("projectionMat");
		glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projectionMatrix));		

		//glm::mat4 model;
		//model = glm::translate(model, glm::vec3(0, -1.75f, 0.0f)); // Translate it down a bit so it's at the center of the scene
		//model += glm::translate(model, glm::vec3(0.2f, 0.0f, 0.0f));
		//model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f));	// It's a bit too big for our scene, so scale it down
		//glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "modelMat"), 1, GL_FALSE, glm::value_ptr(model));

		nanosuit.Draw(lightingShader);

		
		// Swap the buffers
		glfwSwapBuffers(window);
	}

	// =======================================================
	//                     CLEANUP
	// =======================================================
	
	glfwTerminate();
	return 0;
}
Beispiel #2
0
void CameraFollow::Update(float dt)
{
	UpdateCamera(dt);
}
Beispiel #3
0
void Pipeline::SetCameraPosition(Vector3f vPosition)
{
	this->vPosition = vPosition;
	UpdateCamera();
}
Beispiel #4
0
void Pipeline::SetCameraAngleY(float fAngleY)
{
	this->fAngleY = fAngleY;
	UpdateCamera();
}
Beispiel #5
0
void cViewer::MessageProc( UINT message, WPARAM wParam, LPARAM lParam)
{
	if (m_scene)
		m_scene->MessageProc(message, wParam, lParam);

	switch (message)
	{
	case WM_DROPFILES:
		{
			HDROP hdrop = (HDROP)wParam;
			char filePath[ MAX_PATH];
			const UINT size = DragQueryFileA(hdrop, 0, filePath, MAX_PATH);
			if (size == 0) 
				return;// handle error...

			m_filePath = filePath;
			m_model->Create(filePath);
			m_model->SetAnimation("../media/ani4.ani");
		}
		break;

	case WM_MOUSEWHEEL:
		{
			int fwKeys = GET_KEYSTATE_WPARAM(wParam);
			int zDelta = GET_WHEEL_DELTA_WPARAM(wParam);
			dbg::Print( "%d %d", fwKeys, zDelta);

			Vector3 dir = m_lookAtPos - m_camPos;
			const float len = dir.Length();
			dir.Normalize();

			float zoomLen = (len > 100)? 50 : (len/3.f);
			if (fwKeys & 0x4)
				zoomLen = 1;

			m_camPos += (zDelta<0)? dir*-zoomLen : dir*zoomLen;
			UpdateCamera();
		}
		break;

	case WM_KEYDOWN:
		switch (wParam)
		{
		case VK_F5: // Refresh
			{
				if (m_filePath.empty())
					return;
				m_model->Create(m_filePath);
			}
			break;
		case VK_BACK:
			// 회전 행렬 초기화.
			m_rotateTm.SetIdentity();
			m_model->SetTM(m_rotateTm);
			break;
		case VK_TAB:
			{
				static bool flag = false;
				graphic::GetDevice()->SetRenderState(D3DRS_CULLMODE, flag);
				graphic::GetDevice()->SetRenderState(D3DRS_FILLMODE, flag? D3DFILL_SOLID : D3DFILL_WIREFRAME);
				flag = !flag;
			}
			break;
		}
		break;

	case WM_LBUTTONDOWN:
		{
			m_LButtonDown = true;
			m_curPos.x = LOWORD(lParam);
			m_curPos.y = HIWORD(lParam);
		}
		break;

	case WM_LBUTTONUP:
		m_LButtonDown = false;
		break;

	case WM_RBUTTONDOWN:
		{
			m_RButtonDown = true;
			m_curPos.x = LOWORD(lParam);
			m_curPos.y = HIWORD(lParam);
		}
		break;

	case WM_RBUTTONUP:
		m_RButtonDown = false;
		break;

	case WM_MOUSEMOVE:
		if (wParam & 0x10) // middle button down
		{
			POINT pos = {LOWORD(lParam), HIWORD(lParam)};
			m_scene->SetPos(Vector3(pos.x, pos.y,0));
		}

		if (m_LButtonDown)
		{
			POINT pos = {LOWORD(lParam), HIWORD(lParam)};
			const int x = pos.x - m_curPos.x;
			const int y = pos.y - m_curPos.y;
			m_curPos = pos;

			Matrix44 mat1;
			mat1.SetRotationY( -x * 0.01f );
			Matrix44 mat2;
			mat2.SetRotationX( -y * 0.01f );

			m_rotateTm *= (mat1 * mat2);
		}
		else if (m_RButtonDown)
		{
			POINT pos = {LOWORD(lParam), HIWORD(lParam)};
			const int x = pos.x - m_curPos.x;
			const int y = pos.y - m_curPos.y;
			m_curPos = pos;

			{ // rotate Y-Axis
				Quaternion q(Vector3(0,1,0), x * 0.005f); 
				Matrix44 m = q.GetMatrix();
				m_camPos *= m;
			}

			{ // rotate X-Axis
				Quaternion q(Vector3(1,0,0), y * 0.005f); 
				Matrix44 m = q.GetMatrix();
				m_camPos *= m;
			}

			UpdateCamera();
		}
		else
		{
			POINT pos = {LOWORD(lParam), HIWORD(lParam)};
			//m_scene->SetPos(Vector3(pos.x, pos.y,0));
			//if (m_image->IsContain(Vector2(pos.x, pos.y)))
			//{
			//	static int count = 0;
			//	++count;
			//	dbg::Print( "IsContain %d", count);
			//}
		}

		break;
	}
}
Beispiel #6
0
int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib example - obj viewer");

    // Define the camera to look into our 3d world
    Camera camera = { { 30.0f, 30.0f, 30.0f }, { 0.0f, 10.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 };

    Model model = LoadModel("resources/models/turret.obj");                     // Load default model obj
    Texture2D texture = LoadTexture("resources/models/turret_diffuse.png");     // Load default model texture
    model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Bind texture to model

    Vector3 position = { 0.0, 0.0, 0.0 };                   // Set model position
    BoundingBox bounds = MeshBoundingBox(model.meshes[0]);  // Set model bounds
    bool selected = false;                                  // Selected object flag

    SetCameraMode(camera, CAMERA_FREE);     // Set a free camera mode

    char objFilename[64] = "turret.obj";

    SetTargetFPS(60);               // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        if (IsFileDropped())
        {
            int count = 0;
            char **droppedFiles = GetDroppedFiles(&count);

            if (count == 1)
            {
                if (IsFileExtension(droppedFiles[0], ".obj"))
                {
                    for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]);
                    model.meshes = LoadMeshes(droppedFiles[0], &model.meshCount);
                    bounds = MeshBoundingBox(model.meshes[0]);
                }
                else if (IsFileExtension(droppedFiles[0], ".png"))
                {
                    UnloadTexture(texture);
                    texture = LoadTexture(droppedFiles[0]);
                    model.materials[0].maps[MAP_DIFFUSE].texture = texture;
                }

                strcpy(objFilename, GetFileName(droppedFiles[0]));
            }

            ClearDroppedFiles();    // Clear internal buffers
        }

        UpdateCamera(&camera);

        // Select model on mouse click
        if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
        {
            // Check collision between ray and box
            if (CheckCollisionRayBox(GetMouseRay(GetMousePosition(), camera), bounds)) selected = !selected;
            else selected = false;
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            BeginMode3D(camera);

                DrawModel(model, position, 1.0f, WHITE);   // Draw 3d model with texture

                DrawGrid(20.0, 10.0);        // Draw a grid

                if (selected) DrawBoundingBox(bounds, GREEN);

            EndMode3D();

            DrawText("Free camera default controls:", 10, 20, 10, DARKGRAY);
            DrawText("- Mouse Wheel to Zoom in-out", 20, 40, 10, GRAY);
            DrawText("- Mouse Wheel Pressed to Pan", 20, 60, 10, GRAY);
            DrawText("- Alt + Mouse Wheel Pressed to Rotate", 20, 80, 10, GRAY);
            DrawText("- Alt + Ctrl + Mouse Wheel Pressed for Smooth Zoom", 20, 100, 10, GRAY);

            DrawText("Drag & drop .obj/.png to load mesh/texture.", 10, GetScreenHeight() - 20, 10, DARKGRAY);
            DrawText(FormatText("Current file: %s", objFilename), 250, GetScreenHeight() - 20, 10, GRAY);
            if (selected) DrawText("MODEL SELECTED", GetScreenWidth() - 110, 10, 10, GREEN);

            DrawText("(c) Turret 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadModel(model);         // Unload model

    ClearDroppedFiles();        // Clear internal buffers

    CloseWindow();              // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #7
0
void Draw(void)
{
	// Use the program object, it's possible that you have multiple shader programs and switch it accordingly
	glUseProgram(GprogramID);

	// Set the sampler2D varying variable to the first texture unit (index 0)
	glUniform1i(glGetUniformLocation(GprogramID, "sampler2d"), 0);

	// Pass texture size to shader
	glUniform2fv(glGetUniformLocation(GprogramID, "resolution"), 1, new GLfloat[2]{ (GLfloat)WINDOW_WIDTH, (GLfloat)WINDOW_HEIGHT });

	// Time
	static float time = 0.0f;
	time += 0.01f;
	GLint timeLoc = glGetUniformLocation(GprogramID, "Time");
	if (timeLoc != -1)
	{
		glUniform1f(timeLoc, time);
	}

	// Update Camera
	UpdateCamera();

	// Set the viewport
	glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

	// Clear the buffers (Clear the screen basically)
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//==================================================
	// 1st pass - Render entire screen as a texture
	//==================================================
	PostProcessDraw(Gframebuffer, time, 0, GfullscreenTexture, PPS_RENDER_SCENE, -1);

	//==================================================
	// 2nd pass - Render entire screen without non-glowing objects
	//==================================================
	//PostProcessDraw(Gframebuffer, time, 0, GpTexture_2, PPS_RENDER_GLOWED, -1);
	
	//==================================================
	// 3rd Pass - Run High Pass Filter on the texture
	//==================================================
	//PostProcessDraw(Gframebuffer, time, GpTexture_2, GpTexture_0, PPS_HIGH_PASS, -1);
	PostProcessDraw(Gframebuffer, time, GfullscreenTexture, GpTexture_0, PPS_HIGH_PASS, -1);

	//==================================================
	// 4th Pass - Blur the texture horizontally
	//==================================================
	PostProcessDraw(Gframebuffer, time, GpTexture_0, GpTexture_1, PPS_GAUSSIAN_BLUR, 0);

	//==================================================
	// 5th Pass - Blur the texture vertically
	//==================================================
	PostProcessDraw(Gframebuffer, time, GpTexture_1, GpTexture_0, PPS_GAUSSIAN_BLUR, 1);

	//==================================================
	// Final Pass - Additively blend textures together
	//==================================================
	PostProcessDraw(0, time, GpTexture_0, 0, PPS_ADDITIVE_BLEND, -1, GfullscreenTexture);
	
	//Test with more iterations
	//HigherIntensityBloom(2, time, GpTexture_2, GpTexture_0, GpTexture_1);

	//DrawFmod();

	 //Triangle
	/*
	static GLfloat vVertices[] = 
	{
		 0.0f,  0.5f, 0.0f,
		-0.5f, -0.5f, 0.0f,
		 0.5f, -0.5f, 0.0f
	};

	static GLfloat vColors[] = // !! Color for each vertex
	{
		1.0f, 0.0f, 0.0f, 1.0f,
		0.0f, 1.0f, 0.0f, 1.0f,
		0.0f, 0.0f, 1.0f, 1.0f
	};
	*/

	//Double spinning Rects
	/*
	static float modelRotation = 0.0f;

	Matrix4 modelMatrix = Matrix4::translate(Vector3(0.0f, 0.0f, 0.0f)) *
						  Matrix4::rotate(-modelRotation, Vector3(0.0f, 1.0f, 0.0f));

	Matrix4 mvpMatrix = gPerspectiveMatrix * gViewMatrix * modelMatrix;
	GLint mvpMatrixLoc = glGetUniformLocation(GprogramID, "uMvpMatrix");
	
	//if (mvpMatrixLoc != -1)
	//{
	//	glUniformMatrix4fv(mvpMatrixLoc, 1, GL_FALSE, mvpMatrix.data); // Pass mvpMatirx to the vertex shader
	//}
	
	static float spacing = 1.0f;
	static float zAxis = -1.5f;
	static float rotSpeed = 100.0f;

	Matrix4 lTransMatrix = Matrix4::translate(Vector3(-spacing, 0.0f, zAxis)) *
						   Matrix4::rotate(-time * rotSpeed, Vector3(0.0f, 1.0f, 0.0f));
	Matrix4 rTransMatrix = Matrix4::translate(Vector3(spacing, 0.0f, zAxis)) *
						   Matrix4::rotate(time * rotSpeed, Vector3(0.0f, 1.0f, 0.0f));

	Matrix4 lSquareMatrix = gPerspectiveMatrix * gViewMatrix * lTransMatrix * modelMatrix;
	Matrix4 rSquareMatrix = gPerspectiveMatrix * gViewMatrix * rTransMatrix * modelMatrix;

	glUniformMatrix4fv(mvpMatrixLoc, 1, GL_FALSE, lSquareMatrix.data); // Pass lSquareMatrix to the vertex shader

	DrawSquare(GtextureID[5]);

	glUniformMatrix4fv(mvpMatrixLoc, 1, GL_FALSE, rSquareMatrix.data); // Pass rSquareMatrix to the vertex shader

	DrawSquare(GtextureID[5]);
	*/
}
Beispiel #8
0
	void PuppetEditor::Update()
	{
		Editor::Update();

		if (isEnabled)
		{
			UpdateCamera();

			timeline->currentAnimation = puppetEntity->puppet.GetCurrentAnimation();

			Animation *anim = puppetEntity->puppet.GetCurrentAnimation();

			if (Input::IsKeyPressed(keyTogglePause))
			{
				puppetEntity->puppet.TogglePause();
				Debug::render = Debug::showBounds = puppetEntity->puppet.IsPaused();
				if (!puppetEntity->puppet.IsPaused())
				{
					Debug::selectedEntity = NULL;
				}
				else
				{
					if (anim)
					{
						anim->SetCurrentTime(int(anim->GetCurrentTime()/TIME_STEP)*TIME_STEP);
					}
				}
			}

			if (puppetEntity->puppet.IsPaused())
			{
				if (Input::IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
					Debug::selectedEntity = scene->GetNearestEntityByControlPoint(Input::GetWorldMousePosition(), "", Debug::selectedEntity);

				if (Input::IsKeyHeld(KEY_LCTRL))
				{
					if (Input::IsKeyPressed(KEY_S))
					{
						puppetEntity->puppet.Save();
					}
				}

				if (Debug::selectedEntity)
				{
					Part *part = dynamic_cast<Part*>(Debug::selectedEntity);

					float moveSpeed = 10.0f;
					float rotateSpeed = 15.0f;

					if (Input::IsKeyHeld(KEY_LSHIFT))
					{
						float multiplier = 5.0f;
						moveSpeed *= multiplier;
						rotateSpeed *= multiplier;
					} 

					if (Input::IsKeyPressed(keyZero))
					{
						part->position = Vector2::zero;
						part->rotation = 0.0f;
						part->GetSprite()->position = Vector2::zero;
					}

					float moveAmount = Monocle::deltaTime * moveSpeed * 10.0f;
					float rotateAmount = Monocle::deltaTime * rotateSpeed;

					if (Input::IsKeyHeld(KEY_LCTRL))
					{
					}
					else
					{
						if (Input::IsKeyHeld(keyOffset))
						{
							if (part)
							{
								Sprite *sprite = part->GetSprite();

								if (Input::IsKeyHeld(keyMoveLeft))
									sprite->position += Vector2::left * moveAmount;
								if (Input::IsKeyHeld(keyMoveRight))
									sprite->position += Vector2::right * moveAmount;
								if (Input::IsKeyHeld(keyMoveUp))
									sprite->position += Vector2::up * moveAmount;
								if (Input::IsKeyHeld(keyMoveDown))
									sprite->position += Vector2::down * moveAmount;
							}
						}
						else
						{
							if (Input::IsKeyHeld(keyMoveLeft))
								Debug::selectedEntity->position += Vector2::left * moveAmount;
							if (Input::IsKeyHeld(keyMoveRight))
								Debug::selectedEntity->position += Vector2::right * moveAmount;
							if (Input::IsKeyHeld(keyMoveUp))
								Debug::selectedEntity->position += Vector2::up * moveAmount;
							if (Input::IsKeyHeld(keyMoveDown))
								Debug::selectedEntity->position += Vector2::down * moveAmount;
						}

						if (Input::IsKeyHeld(keyRotateLeft))
							Debug::selectedEntity->rotation -= rotateAmount;
						if (Input::IsKeyHeld(keyRotateRight))
							Debug::selectedEntity->rotation += rotateAmount;
					}


				}
				else 
				{

				}

				if (anim)
				{
					Part *part = dynamic_cast<Part*>(Debug::selectedEntity);

					if (Input::IsKeyPressed(keyBackwards))
						anim->AdjustCurrentTime(-TIME_STEP, false);
					if (Input::IsKeyPressed(keyForwards))
						anim->AdjustCurrentTime(TIME_STEP, false);

					if (Input::IsKeyPressed(keySetKeyFrame))
					{
						anim->SetPartKeyFrame(part, KeyFrame(anim->GetCurrentTime(), *part));
						//puppetEntity.puppet.GetCurrentAnimation()->AddNewPartKeyFrame();
					}
				}
			}
			else
			{
				//if (Input::IsMouseButtonHeld(MOUSE_BUTTON_LEFT))
				//puppetEntity->position = WEIGHTED_AVERAGE(puppetEntity->position, Input::GetWorldMousePosition(), 15);
			}
		}
	}
Beispiel #9
0
void CMapManager::Render()
{
	groundHandler.Render();
	UpdateCamera();
	RenderBrushBorder();
}
Beispiel #10
0
void Menu::Update() {
	WaitKeyButton::UpdateAll();
	UpdateCamera();
	SyncPlayerControls();

	if(mVisible) {
		AnimateCamera();
		mGame->GetEngine()->GetRenderer()->SetAmbientColor(Vector3(0.05, 0.05, 0.05));

		if(mGame->GetLevel()) {
			// back to menu by pressing [Esc]
			if(mGame->GetEngine()->GetInput()->IsKeyHit(IInput::Key::Esc)) {
				CameraStartFadeOut([this] {	Hide(); });
			}

			// switch on/off buttons if player dead or alive
			auto & player = mGame->GetLevel()->GetPlayer();
			if(player) {
				if(player->IsDead()) {
					mContinueGameButton->SetActive(false);
					mSaveGameButton->SetActive(false);
				} else {
					mContinueGameButton->SetActive(true);
					mSaveGameButton->SetActive(true);
				}
			} else {
				mSaveGameButton->SetActive(false);
			}
		}

		// check if quick save exists, let player to continue game
		ifstream f("quickSave.save");
		if(f.good()) {
			mContinueGameButton->SetActive(true);
			f.close();
		} else {
			mContinueGameButton->SetActive(mGame->GetLevel() == nullptr);
		}

		if(mPage == Page::Authors) {
			mModalWindow->CloseNoAction();
			SetAuthorsPageVisible(true);
		} else {
			SetAuthorsPageVisible(false);
		}

		mGUIOptionsCanvas->SetVisible(mPage == Page::Options);
		mOptionsCommonCanvas->SetVisible(mPage == Page::OptionsCommon);
		mOptionsKeysCanvas->SetVisible(mPage == Page::OptionsKeys);
		mOptionsGraphicsCanvas->SetVisible(mPage == Page::OptionsGraphics);
		mSaveGameButton->SetActive(mGame->GetLevel() != nullptr);

		if(mPage == Page::LoadGame) {
			mLoadGameCanvas->SetVisible(true);
			// inactivate all buttons
			for(int i = 0; i < mSaveLoadSlotCount; i++) {
				mLoadGameSlot[i]->SetActive(false);
			}
			for(int i = 0; i < mSaveFilesList.size(); i++) {
				// activate button associated with file
				mLoadGameSlot[i]->SetActive(true);
				mLoadGameSlot[i]->GetText()->SetText(mSaveFilesList[i].substr(0, mSaveFilesList[i].find_first_of('.')));
				mLoadGameFileTime[i]->SetText(GetFileCreationDate(mSaveFilesList[i]));
			}
		} else {
			mLoadGameCanvas->SetVisible(false);
		}

		if(mPage == Page::SaveGame) {
			mSaveGameCanvas->SetVisible(true);
			for(int i = mSaveFilesList.size(); i < mSaveLoadSlotCount; i++) {
				mSaveFilesList.push_back(StringBuilder("Slot") << i << ".save");
			}
			for(int i = 0; i < mSaveFilesList.size(); i++) {
				mSaveGameSlot[i]->GetText()->SetText(mSaveFilesList[i].substr(0, mSaveFilesList[i].find_first_of('.')));
				mSaveGameFileTime[i]->SetText(GetFileCreationDate(mSaveFilesList[i]));
			}
		} else {
			mSaveGameCanvas->SetVisible(false);
		}

		mMusic->Play();

		// apply graphics settings
		ApplySettings();

		// sync player controls
		SyncPlayerControls();
	} else {
		if(mGame->GetEngine()->GetInput()->IsKeyHit(IInput::Key::Esc)) {
			Show();
		}
	}
}
/*!
	Setup of the view port and projection initialization. In projection initialization the Ortho or Perspective is set
	as per requirement.

	\param[in] width of the screen.
	\param[in] height of the screen.

	\return void.
*/
void Renderer::setUpProjection()
{
	ProgramManager* ProgramManagerObj	= &RenderMemData.ProgramManagerObj;
	Transform*	TransformObj			= &RenderMemData.TransformObj;
	bool considerAspectRatio			= true;
	float span							= 10.0;

    //Transform Init() function is moved to the constructor no need to call every frame.
	//TransformObj->TransformInit();

	TransformObj->TransformSetMatrixMode( PROJECTION_MATRIX );

	TransformObj->TransformLoadIdentity();

	if ( considerAspectRatio ){
		GLfloat aspectRatio = (GLfloat)RenderMemData.screenWidth / (GLfloat)RenderMemData.screenHeight;
		if ( RenderMemData.isPerspective ){
			TransformObj->TransformSetPerspective(60.0f, aspectRatio, 0.01, 1000, 0);
		}else{
			if ( RenderMemData.screenWidth <= RenderMemData.screenHeight ){
				TransformObj->TransformOrtho( -span, span, -span / aspectRatio, span / aspectRatio, -span, span);
			}
			else{
				TransformObj->TransformOrtho( -span * aspectRatio, span * aspectRatio, -span, span, -span, span);
			}
		}
	}
	else{
		if ( RenderMemData.isPerspective ){
			TransformObj->TransformSetPerspective(60.0f, 1, 1.0, 100, 0);
		}
		else{
			TransformObj->TransformOrtho( -span, span, -span, span, -span, span );
		}
	}
	TransformObj->TransformSetMatrixMode( VIEW_MATRIX );
//	TransformObj->TransformLoadIdentity();
    //TransformObj->TransformTranslate(0,0,-3);
    static float frame = 0.0;
    UpdateCamera((clock()-globalClock)/100000000);
    glm::mat4* m_viewMatrix = TransformObj->TransformGetViewMatrix();
    
    LOGI("00: %f",(*m_viewMatrix)[0][0]);
    LOGI("10: %f",(*m_viewMatrix)[1][0]);
    LOGI("20: %f",(*m_viewMatrix)[2][0]);
    LOGI("30: %f",(*m_viewMatrix)[3][0]);
    
    LOGI("01: %f",(*m_viewMatrix)[0][1]);
    LOGI("11: %f",(*m_viewMatrix)[1][1]);
    LOGI("21: %f",(*m_viewMatrix)[2][1]);
    LOGI("31: %f",(*m_viewMatrix)[3][1]);
    
    LOGI("02: %f",(*m_viewMatrix)[0][2]);
    LOGI("12: %f",(*m_viewMatrix)[1][2]);
    LOGI("22: %f",(*m_viewMatrix)[2][2]);
    LOGI("32: %f",(*m_viewMatrix)[3][2]);
    
    LOGI("03: %f",(*m_viewMatrix)[0][3]);
    LOGI("13: %f",(*m_viewMatrix)[1][3]);
    LOGI("23: %f",(*m_viewMatrix)[2][3]);
    LOGI("33: %f",(*m_viewMatrix)[3][3]);

	TransformObj->TransformSetMatrixMode( MODEL_MATRIX );
	TransformObj->TransformLoadIdentity();
}
Beispiel #12
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 800;
    int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");

    // Define the camera to look into our 3d world
    Camera camera = {{ 0.0, 10.0, 10.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }};

    Vector3 cubePosition = { 0.0, 0.0, 0.0 };
    
    SetCameraMode(CAMERA_FREE);         // Set a free camera mode
    SetCameraPosition(camera.position); // Set internal camera position to match our camera position
    SetCameraTarget(camera.target);     // Set internal camera target to match our camera target

    SetTargetFPS(60);                   // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())        // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        UpdateCamera(&camera);          // Update internal camera and our camera
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(WHITE);

            Begin3dMode(camera);

                DrawCube(cubePosition, 2, 2, 2, RED);
                DrawCubeWires(cubePosition, 2, 2, 2, MAROON);

                DrawGrid(10.0, 1.0);

            End3dMode();

            DrawText("Free camera default controls:", 20, 20, 10, GRAY);
            DrawText("- Mouse Wheel to Zoom in-out", 40, 50, 10, DARKGRAY);
            DrawText("- Mouse Wheel Pressed to Pan", 40, 70, 10, DARKGRAY);
            DrawText("- Alt + Mouse Wheel Pressed to Rotate", 40, 90, 10, DARKGRAY);
            DrawText("- Alt + Ctrl + Mouse Wheel Pressed for Smooth Zoom", 40, 110, 10, DARKGRAY);
            DrawText("- Z to zoom to (0, 0, 0)", 40, 130, 10, DARKGRAY);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #13
0
/*******************************************************************************
関数名:	void UpdateGame(void)
引数:	なし
戻り値:	なし
説明:	ゲームの更新関数
*******************************************************************************/
void UpdateGame(void)
{
	//初期値
	g_fTimeSpeed = 0.01f;

	GAME_STEP stepNow = GetGameStep();
	switch(stepNow)
	{
		case STEP_PLAY:

			UpdatePlayer();
			UpdateCamera();
			UpdateGun();
			
			UpdatePlayerBullet(g_fTimeSpeed);
			UpdateEnemy( g_fTimeSpeed);
			UpdateEnemyBullet( g_fTimeSpeed);

			//UpdateBillBoard();
			UpdateParticle( g_fTimeSpeed);
			UpdateStageManager( g_fTimeSpeed);

			//UpdateModel();
			UpdateGunSight();
			UpdateItemBullet();
			UpdateClock( g_fTimeSpeed);
			UpdateTime( g_fTimeSpeed);

			if(GetKeyboardTrigger(DIK_P) )
			{
				SetGameStep(STEP_PAUSE);
				SetMessage(MSG_PAUSE);
			}
			break;
		case STEP_SHOOT:
			
			ChangeTimeSpeed( 1.0f);
			
			UpdateEnemy( g_fTimeSpeed);
			//UpdatePlayer();
			UpdatePlayerBullet( g_fTimeSpeed);
			//UpdateEnemyBullet( g_fTimeSpeed);
			UpdateClock( g_fTimeSpeed);
			UpdateTime( g_fTimeSpeed);

			g_nCounterShoot++;
			if( g_nCounterShoot > 15)
			{
				g_nCounterShoot = 0;
				SetGameStep(STEP_PLAY);
			}
			break;
		case STEP_PAUSE:
			StopSound();
			if(GetKeyboardTrigger(DIK_P) )
			{
				SetGameStep(STEP_PLAY);
				ClearMessage(MSG_PAUSE);
			}
			break;
		case STEP_DIE:
			ChangeTimeSpeed( 1.0f);

			UpdateEnemy( g_fTimeSpeed);
			UpdateEnemyBullet( g_fTimeSpeed);
			UpdatePlayerBullet( g_fTimeSpeed);
			UpdateParticle( g_fTimeSpeed);

			g_nCounterFrame++;
			if( g_nCounterFrame > 90)
			{
				g_nCounterFrame = 0;
				if( GetPlayer()->nLife <= 0)
				{
					FadeOutToNext(MODE_RESULT);
				}
				else
				{
					FadeOutToNext(STEP_RESET);
					SetGameStep(STEP_NOTHING);
				}
				
			}

			break;
		case STEP_RESET:
			InitStageManager( false, GetPlayer()->nLife);
			SetGameStep(STEP_PLAY);	
			break;
		case STEP_CLEAR:
			StopSound(SOUND_LABEL_SE_RUN);
			SetMessage(MSG_STAGECLEAR);

			g_nCounterFrame++;
			if( g_nCounterFrame > 90)
			{
				g_nCounterFrame = 0;

				switch(GetStageMode())
				{
				case STAGE0:
					FadeOutToNext(STAGE1);
					break;
				case STAGE1:
					FadeOutToNext(STAGE2);
					break;
				case STAGE2:
					FadeOutToNext(STAGE3);
					break;
				case STAGE3:
					FadeOutToNext(MODE_RESULT);
					g_bGameClear = true;
					break;
				}
				
				SetGameStep(STEP_NOTHING);
			}
			break;
		case STEP_NOTHING:
			//just let time go, and do nothing
			break;
	}	

	//UI update
	UpdateNumBullet();

	//Debug update
	UpdateMeshDome();

	if(GetKeyboardTrigger(DIK_RETURN) )
	{	
		FadeOutToNext(MODE_RESULT);
	}
	if(GetKeyboardTrigger(DIK_F3))
	{	
		PlaySound( SOUND_LABEL_SE_CLEAR);
		SetGameStep(STEP_CLEAR);
	}
	if(GetKeyboardTrigger(DIK_F2))
	{
		PlaySound(SOUND_LABEL_SE_SWITCH);
		SwitchDebug();
	}
}
Beispiel #14
0
void BoxBrowser::Draw()
{
	if( !visible )
		return;
	if( needToUpdateBoxes )
	{
		needToUpdateBoxes = false;
		viewMode = viewFlow;
		Shift( 0 );
	}
	if( viewMode == viewFlow )
	{
		//draw text and any other 2D elements ( and leave it in 2D for the rest of the gui )
		gameText->Draw();
		//change to 3D context to draw boxes
		tiny3d_Project3D();

		//draw the surface
		DrawSurface();

		//update camera motion
		UpdateCamera();

		for( int i = 0; i < NUM_BOXES; i++ )
		{
			int mtxIdx = ( ( i * ANIMATION_FRAMES ) + animFrame );
			if( mtxIdx >= (int)mtxBox.size() || mtxIdx < 0 )
			{
				continue;
			}
			tiny3d_SetMatrixModelView( &mtxBox[ mtxIdx ] );
			box[ i ]->DrawNoMtx();
		}
		UpdateAnimation();
	}
	else if( viewMode == viewZoom )
	{
		//draw text and any other 2D elements ( and leave it in 2D for the rest of the gui )
		if( bgImg2 )
		{
			bgImg2->Draw();
		}
		if( bgImg1 )
		{
			//make sure this image is positioned correctly
			if( !bgLoaded && bgImg1->IsLoaded() )
			{
				bgLoaded = true;
				//this image should either be 1000px wide or 1920
				if( bgImg1->GetWidth() <= 1000 )
					bgImg1->SetPosition( 124, 69, 0xfff0 );//these values seem to work for all my guitar hero & rockband games
				else
					bgImg1->SetPosition( 0, 0, 0xfff0 );//i dont have any games that fit this category, but i assume this is right
			}
			bgImg1->Draw();
		}

		//change to 3D
		tiny3d_Project3D();

		//update camera motion
		UpdateCamera();

		//set matrix for zoomed box
		SetZoomMatrix();

		//the center box hopefully is the selected one
		box[ NUM_BOXES / 2 ]->DrawNoMtx();
	}


	//done in 3D mode, switch to 2D
	tiny3d_SetMatrixModelView( NULL ); // set matrix identity
	tiny3d_Project2D();

	busy = false;
	inputIdx = 0;
}
Beispiel #15
0
void SpaceShip::SetPosition(Vector3D Position)
{
	m_Position = Position;

	UpdateCamera();
}
Beispiel #16
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 800;
    int screenHeight = 450;

    SetConfigFlags(FLAG_MSAA_4X_HINT);      // Enable Multi Sampling Anti Aliasing 4x (if available)

    InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader");

    // Define the camera to look into our 3d world
    Camera camera = {{ 3.0, 3.0, 3.0 }, { 0.0, 1.5, 0.0 }, { 0.0, 1.0, 0.0 }};

    Model dwarf = LoadModel("resources/model/dwarf.obj");                   // Load OBJ model
    Texture2D texture = LoadTexture("resources/model/dwarf_diffuse.png");   // Load model texture
    Shader shader = LoadShader("resources/shaders/base.vs",
                               "resources/shaders/grayscale.fs");           // Load model shader

    SetModelShader(&dwarf, shader);         // Set shader effect to 3d model
    SetModelTexture(&dwarf, texture);       // Bind texture to model

    Vector3 position = { 0.0, 0.0, 0.0 };   // Set model position

    // Setup orbital camera
    SetCameraMode(CAMERA_ORBITAL);          // Set an orbital camera mode
    SetCameraPosition(camera.position);     // Set internal camera position to match our camera position
    SetCameraTarget(camera.target);         // Set internal camera target to match our camera target

    SetTargetFPS(60);                       // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())            // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        UpdateCamera(&camera);              // Update internal camera and our camera
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

        ClearBackground(RAYWHITE);

        Begin3dMode(camera);

        DrawModel(dwarf, position, 2.0f, WHITE);   // Draw 3d model with texture

        DrawGrid(10.0, 1.0);     // Draw a grid

        End3dMode();

        DrawText("(c) Dwarf 3D model by David Moreno", screenWidth - 200, screenHeight - 20, 10, GRAY);

        DrawFPS(10, 10);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadShader(shader);       // Unload shader
    UnloadTexture(texture);     // Unload texture
    UnloadModel(dwarf);         // Unload model

    CloseWindow();              // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #17
0
void SpaceShip::Update(float RelativeTime)
{
	m_RelativeTime = RelativeTime;

	if (!m_Moving)
	{
		// Allow friction to slow the ship down
		float NewSpeed = m_Speed - m_Speed * m_Acceleration * m_RelativeTime * 0.2f;

		if (m_Speed > 0)
			m_Speed = (NewSpeed < 0 ? 0 : NewSpeed);
		else
			m_Speed = (NewSpeed > 0 ? 0 : NewSpeed);
	}

	if (!m_Turning)
	{
		// Rotate back to normal
		float NewRot = abs(m_RotZ) - 0.03f * m_RelativeTime;
		if (NewRot < 0)
			NewRot = 0;

		if (m_RotZ > 0)
			m_RotZ = NewRot;
		else
			m_RotZ = -NewRot;
	}

	// Set y-rotation
	m_RotY -= 0.01f * m_RotZ * m_Speed * m_RelativeTime;

	// Rotate ship
	D3DXMATRIX matrix;
	D3DXQuaternionRotationAxis(&m_QuatY, new D3DXVECTOR3(0, 1, 0), m_RotY);
	D3DXQuaternionRotationAxis(&m_QuatZ, new D3DXVECTOR3(0, 0, 1), m_RotZ);

	D3DXVECTOR4 vec = D3DXVECTOR4(0, 0, 1, 1);
	D3DXVec4Transform(&vec, &vec, D3DXMatrixRotationQuaternion(&matrix, &m_QuatY));
	D3DXVec4Normalize(&vec, &vec);

	// Move ship
	Vector3D OldPosition = m_Position;
	D3DXVECTOR4 newvec = vec * m_Speed * m_RelativeTime;
	m_Position += Vector3D(newvec.x, newvec.y, newvec.z);

	FollowTerrain();

	// Compare current position height and new position height
	float Scale = 1.0f;
	if (OldPosition.Y > m_Position.Y) // Ship is going down
		Scale += (OldPosition.Y - m_Position.Y);
	else if (OldPosition.Y < m_Position.Y) // Ship is going up
		Scale -= (m_Position.Y - OldPosition.Y) * 0.1f;

	// Move ship
	vec *= m_Speed * Scale * m_RelativeTime;
	m_Position = OldPosition + Vector3D(vec.x, vec.y, vec.z);

	// Set kilometres per hour
	m_NextKPH++;
	if (m_NextKPH == m_NumKPH)
		m_NextKPH = 0;

	m_KPH[m_NextKPH] = abs((int)(m_Speed * Scale * 100.0f));
	
	FollowTerrain();

	// See if the player is going off the edge
	Rect bounds = m_Terrain->GetBounds();

	if (m_Position.X < bounds.X)
		m_Position.X = bounds.X;
	else if (m_Position.X > bounds.X + bounds.W)
		m_Position.X = bounds.X + bounds.W;

	if (m_Position.Z < bounds.Y)
		m_Position.Z = bounds.Y;
	else if (m_Position.Z > bounds.Y + bounds.H)
		m_Position.Z = bounds.Y + bounds.H;

	// Update camera
	UpdateCamera();

	// Set mesh position
	Matrix pos, rot, out;
	Quaternion quat = m_QuatZ * m_QuatY;
	D3DXMatrixTranslation(&pos, m_Position.X, m_Position.Y, m_Position.Z);
	D3DXMatrixRotationQuaternion(&rot, &quat);
	out = rot * pos;

	m_Mesh->SetWorldMatrix(&out);
}
Beispiel #18
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 800;
    int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking");

    // Define the camera to look into our 3d world
    Camera camera = {{ 0.0, 10.0, 10.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }};

    Vector3 cubePosition = { 0.0, 1.0, 0.0 };
    
    Ray ray;        // Picking line ray
    
    SetCameraMode(CAMERA_FREE);         // Set a free camera mode
    SetCameraPosition(camera.position); // Set internal camera position to match our camera position

    SetTargetFPS(60);                   // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())        // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        UpdateCamera(&camera);          // Update internal camera and our camera
        
        if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
        {
            // NOTE: This function is NOT WORKING properly!
            ray = GetMouseRay(GetMousePosition(), camera);
            
            // TODO: Check collision between ray and box
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            Begin3dMode(camera);

                DrawCube(cubePosition, 2, 2, 2, GRAY);
                DrawCubeWires(cubePosition, 2, 2, 2, DARKGRAY);

                DrawGrid(10.0, 1.0);
                
                DrawRay(ray, MAROON);

            End3dMode();
            
            DrawText("Try selecting the box with mouse!", 240, 10, 20, GRAY);

            DrawFPS(10, 10);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #19
0
int main(int argc, char** argv)
{
    Settings settings;
    ConstructSettings(&settings);
    LoadSettingsFile(&settings, "settings.ini");
    if(Init(&settings) < 0) return -1;

    GLuint program;
    if(SetupProgram(&program) < 0) return -2;

    GLuint grid_vbuf = CreateGridVertexBuffer(settings.graphics.viewdistance);
    int grid_icount;
    GLuint grid_ibuf = CreateGridIndexBuffer(&grid_icount,
                                             settings.graphics.viewdistance);

    glUseProgram(program);
    GLint grid_pos_loc = glGetAttribLocation(program, "grid_pos");
    GLint grid_world_mat_loc = glGetUniformLocation(program, "world_mat");
    GLint grid_view_mat_loc = glGetUniformLocation(program, "view_mat");
    GLint grid_proj_mat_loc = glGetUniformLocation(program, "proj_mat");
    GLint grid_color_loc = glGetUniformLocation(program, "color");
    GLint grid_viewdistance_loc = glGetUniformLocation(program, "viewdistance");

    glUniform3f(grid_color_loc, 0.f, 0.6f, 0.f);
    glUniform1f(grid_viewdistance_loc, settings.graphics.viewdistance);

    GLuint grid_vao;
    glGenVertexArrays(1, &grid_vao);
    glBindVertexArray(grid_vao);
    glBindBuffer(GL_ARRAY_BUFFER, grid_vbuf);
    glEnableVertexAttribArray(grid_pos_loc);
    glVertexAttribPointer(grid_pos_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, grid_ibuf);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glClearColor(0.5f, 0.5f, 0.5f, 1.f);
    glViewport(0, 0, settings.video.width, settings.video.height);

    Node grid_node;
    ConstructNode(&grid_node);
    Camera camera;
    ConstructCamera(&camera);
    mat4x4 projection_matrix;
    mat4x4_perspective(projection_matrix,
                       settings.video.pfov,
                       settings.video.width/(float)settings.video.height,
                       settings.video.pnear,
                       settings.video.pfar);
    glUniformMatrix4fv(grid_proj_mat_loc, 1, GL_FALSE,
                       (const float*)projection_matrix);

    float speed = 10.f;
    Uint32 ticks = SDL_GetTicks();
    State state = STATE_RUNNING | (settings.video.fullscreen ? STATE_FULLSCREEN : 0);
    while(state & STATE_RUNNING)
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glUseProgram(program);
        glUniformMatrix4fv(grid_world_mat_loc, 1, GL_FALSE,
                           (const float*)grid_node.world_matrix);
        glUniformMatrix4fv(grid_view_mat_loc, 1, GL_FALSE,
                           (const float*)camera.view_matrix);
        glBindVertexArray(grid_vao);
        glDrawElements(GL_TRIANGLE_STRIP, grid_icount, GL_UNSIGNED_INT, NULL);
        SDL_GL_SwapWindow(window);

        SDL_Event event;
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
            case SDL_QUIT:
                state &= ~STATE_RUNNING;
                break;
            case SDL_KEYUP:
                switch(event.key.keysym.scancode)
                {
                case SDL_SCANCODE_F11:
                    state ^= STATE_FULLSCREEN;
                    SDL_SetWindowFullscreen
                    (
                        window,
                        state & STATE_FULLSCREEN ?
                        SDL_WINDOW_FULLSCREEN_DESKTOP : 0
                    );
                    break;
                case SDL_SCANCODE_ESCAPE:
                    state ^= STATE_MOUSE_GRABBED;
                    SDL_SetRelativeMouseMode(state & STATE_MOUSE_GRABBED);
                    break;
                case SDL_SCANCODE_LSHIFT:
                    speed = settings.controls.speed1;
                    break;
                default:
                    break;
                }
                break;
            case SDL_KEYDOWN:
                switch(event.key.keysym.scancode)
                {
                case SDL_SCANCODE_LSHIFT:
                    speed = settings.controls.speed2;
                    break;
                default:
                    break;
                }
                break;
            case SDL_WINDOWEVENT:
                if(event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
                {
                    int w = event.window.data1;
                    int h = event.window.data2;
                    glViewport(0, 0, w, h);
                    mat4x4_perspective(projection_matrix,
                                       settings.video.pfov,
                                       w/(float)h,
                                       settings.video.pnear,
                                       settings.video.pfar);
                    glUniformMatrix4fv(grid_proj_mat_loc, 1, GL_FALSE,
                                       (const float*)projection_matrix);
                }
                break;
            case SDL_MOUSEMOTION:
                if(state & STATE_MOUSE_GRABBED)
                {
                    camera.yaw -= settings.controls.xsensitivity *
                                  event.motion.xrel;
                    camera.pitch -= settings.controls.xsensitivity *
                                    event.motion.yrel;
                }
                break;
            default:
                break;
            }
        }
        Uint32 nticks = SDL_GetTicks();
        float delta = (nticks - ticks)/1000.f;
        ticks = nticks;

        const Uint8* keys = SDL_GetKeyboardState(NULL);
        vec3 movement;
        int i;
        for(i = 0; i < 3; i++) movement[i] = 0.f;
        SDL_bool moved = SDL_FALSE;
        if(keys[SDL_SCANCODE_W] && !keys[SDL_SCANCODE_S])
        {
            vec3_add(movement, movement, camera.direction);
            moved = SDL_TRUE;
        }
        else if(keys[SDL_SCANCODE_S] && !keys[SDL_SCANCODE_W])
        {
            vec3_sub(movement, movement, camera.direction);
            moved = SDL_TRUE;
        }
        if(keys[SDL_SCANCODE_A] && !keys[SDL_SCANCODE_D])
        {
            vec3_sub(movement, movement, camera.right);
            moved = SDL_TRUE;
        }
        else if(keys[SDL_SCANCODE_D] && !keys[SDL_SCANCODE_A])
        {
            vec3_add(movement, movement, camera.right);
            moved = SDL_TRUE;
        }
        if(keys[SDL_SCANCODE_Q] && !keys[SDL_SCANCODE_E])
        {
            vec3_sub(movement, movement, camera.up);
            moved = SDL_TRUE;
        }
        else if(keys[SDL_SCANCODE_E] && !keys[SDL_SCANCODE_Q])
        {
            vec3_add(movement, movement, camera.up);
            moved = SDL_TRUE;
        }

        if(moved)
        {
            vec3_norm(movement, movement);
            vec3_scale(movement, movement, delta * speed);
            vec3_add(camera.node.translation, camera.node.translation,
                     movement);
        }

        UpdateCamera(&camera);

        if(moved)
        {
            vec2 tmp1;
            tmp1[0] = camera.node.position[0];
            tmp1[1] = camera.node.position[2];
            vec2 tmp2;
            tmp2[0] = grid_node.position[0];
            tmp2[1] = grid_node.position[2];
            vec2_sub(tmp1, tmp1, tmp2);
            tmp1[0] = floor(tmp1[0]);
            tmp1[1] = floor(tmp1[1]);
            grid_node.translation[0] += tmp1[0];
            grid_node.translation[2] += tmp1[1];
            UpdateNode(&grid_node);
        }
    }

    glDeleteVertexArrays(1, &grid_vao);
    glDeleteBuffers(1, &grid_vbuf);
    glDeleteBuffers(1, &grid_ibuf);
    glDeleteProgram(program);

    return 0;
}
Beispiel #20
0
//-----------------------------------------------------------------------------------
void TheGame::Update(float deltaTime)
{
    DebugRenderer::instance->Update(deltaTime);
    if (InputSystem::instance->WasKeyJustPressed(InputSystem::ExtraKeys::TILDE))
    {
        Console::instance->ActivateConsole();
    }

    if (Console::instance->IsActive())
    {
        return; //Don't do anything involving input updates.
    }

    UpdateCamera(deltaTime);
    for (int i = 0; i < 16; i++)
    {
        m_lightPositions[i] = Vector3(sinf(static_cast<float>(GetCurrentTimeSeconds() + i)) * 5.0f, cosf(static_cast<float>(GetCurrentTimeSeconds() + i) / 2.0f) * 3.0f, 0.5f);
        m_lights[i].SetPosition(m_lightPositions[i]);
        m_currentMaterial->m_shaderProgram->SetVec3Uniform(Stringf("gLightPosition[%i]", i).c_str(), m_lightPositions[i], 16);
    }
    
    if (InputSystem::instance->WasKeyJustPressed('O'))
    {
        m_renderAxisLines = !m_renderAxisLines;
    }
    if (InputSystem::instance->WasKeyJustPressed('1'))
    {
        MeshBuilder builder;
        MeshBuilder::PlaneData* data = new MeshBuilder::PlaneData(Vector3::ZERO, Vector3::RIGHT, Vector3::UP);
        builder.BuildPatch(-5.0f, 5.0f, 50, -5.0f, 5.0f, 50,
            [](const void* userData, float x, float y)
        {
            MeshBuilder::PlaneData const *plane = (MeshBuilder::PlaneData const*)userData;
            Vector3 position = plane->initialPosition
                + (plane->right * x)
                + (plane->up * y);
            return position;
        }
        , data);
        builder.CopyToMesh(loadedMesh->m_mesh, &Vertex_SkinnedPCTN::Copy, sizeof(Vertex_SkinnedPCTN), &Vertex_SkinnedPCTN::BindMeshToVAO);
        spinFactor = 0.0f;
    }
    if (InputSystem::instance->WasKeyJustPressed('2'))
    {
        MeshBuilder builder;
        MeshBuilder::PlaneData* data = new MeshBuilder::PlaneData(Vector3::ZERO, Vector3::RIGHT, Vector3::UP);
        builder.BuildPatch(-5.0f, 5.0f, 50, -5.0f, 5.0f, 50,
            [](const void* userData, float x, float y)
            {
                MeshBuilder::PlaneData const *plane = (MeshBuilder::PlaneData const*)userData;
                Vector3 position = plane->initialPosition
                    + (plane->right * x)
                    + (plane->up * y);
                position.z = sin(x + y);
                return position;
            }
        , data);
        builder.CopyToMesh(loadedMesh->m_mesh, &Vertex_SkinnedPCTN::Copy, sizeof(Vertex_SkinnedPCTN), &Vertex_SkinnedPCTN::BindMeshToVAO);
        spinFactor = 0.0f;
    }
    if (InputSystem::instance->WasKeyJustPressed('3'))
    {
        MeshBuilder builder;
        MeshBuilder::PlaneData* data = new MeshBuilder::PlaneData(Vector3::ZERO, Vector3::RIGHT, Vector3::UP);
        builder.BuildPatch(-5.0f, 5.0f, 50, -5.0f, 5.0f, 50,
            [](const void* userData, float x, float y)
        {
            MeshBuilder::PlaneData const *plane = (MeshBuilder::PlaneData const*)userData;
            Vector3 position = plane->initialPosition
                + (plane->right * x)
                + (plane->up * y);
            position.z = .05f * -cos(((float)GetCurrentTimeSeconds() * 4.0f) + (Vector2(x, y).CalculateMagnitude() * 100.0f));
            return position;
        }
        , data);
        builder.CopyToMesh(loadedMesh->m_mesh, &Vertex_SkinnedPCTN::Copy, sizeof(Vertex_SkinnedPCTN), &Vertex_SkinnedPCTN::BindMeshToVAO);
        spinFactor = 0.0f;
    }
    if (InputSystem::instance->WasKeyJustPressed('4'))
    {
        FbxListScene("Data/FBX/SampleBox.fbx");
    }
    if (InputSystem::instance->WasKeyJustPressed('5'))
    {
        Console::instance->RunCommand("fbxLoad Data/FBX/unitychan.fbx");
    }
    if (InputSystem::instance->WasKeyJustPressed('6'))
    {
        Console::instance->RunCommand("fbxLoad Data/FBX/samplebox.fbx");
    }
    if (InputSystem::instance->WasKeyJustPressed('7'))
    {
        Console::instance->RunCommand("saveMesh saveFile.picomesh");
    }
    if (InputSystem::instance->WasKeyJustPressed('8'))
    {
        Console::instance->RunCommand("loadMesh saveFile.picomesh");
    }
    if (g_loadedMesh != nullptr)
    {
        loadedMesh->m_mesh = g_loadedMesh;
    }
    if (InputSystem::instance->WasKeyJustPressed('B'))
    {
        m_currentMaterial = m_testMaterial;
    }
    else if (InputSystem::instance->WasKeyJustPressed('N'))
    {
        m_currentMaterial = m_normalDebugMaterial;
    }
    else if (InputSystem::instance->WasKeyJustPressed('U'))
    {
        m_currentMaterial = m_uvDebugMaterial;
    }
    if(InputSystem::instance->WasKeyJustPressed('K'))
    {
        m_showSkeleton = !m_showSkeleton;
    }
    if (InputSystem::instance->WasKeyJustPressed('I') && g_loadedMotion != nullptr)
    {
        g_loadedMotion->m_playbackMode = AnimationMotion::CLAMP;
    }
    else if (InputSystem::instance->WasKeyJustPressed('L') && g_loadedMotion != nullptr)
    {
        g_loadedMotion->m_playbackMode = AnimationMotion::LOOP;
    }
    else if (InputSystem::instance->WasKeyJustPressed('P') && g_loadedMotion != nullptr)
    {
        g_loadedMotion->m_playbackMode = AnimationMotion::PING_PONG;
    }
    else if (InputSystem::instance->WasKeyJustPressed('O') && g_loadedMotion != nullptr)
    {
        g_loadedMotion->m_playbackMode = AnimationMotion::PAUSED;
    }

    quadForFBO->m_material->SetFloatUniform("gTime", (float)GetCurrentTimeSeconds());
}
Beispiel #21
0
//detecting input from devices
void Game::DetectInput(double time)
{
	//holds buttons an axis the mouse uses
	DIMOUSESTATE mouseCurrentState;

	BYTE keyboardState[256];

	DIKeyboard->Acquire();
	DIMouse->Acquire();

	//getting the state of each device, the mouse state holds buttons and axis our mouse may use
	DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrentState);
	DIKeyboard->GetDeviceState(sizeof(keyboardState), (LPVOID)&keyboardState);

	float cameraMoveSpeed = 20.0f*time;

	//specifying what types of input does
	if (keyboardState[DIK_ESCAPE] & 0x80)
		PostMessage(hwndRef, WM_DESTROY, 0, 0);

	#pragma region Camera movement
	//moving camera
	if (keyboardState[DIK_W] & 0x80 || (keyboardState[DIK_UPARROW] & 0x80))
	{
		moveBackForward += cameraMoveSpeed;
	}
	//moving left
	if (keyboardState[DIK_A] & 0x80 || (keyboardState[DIK_LEFTARROW] & 0x80))
	{
		moveLeftRight -= cameraMoveSpeed;
	}
	//moving backwards
	if (keyboardState[DIK_S] & 0x80 || (keyboardState[DIK_DOWNARROW] & 0x80))
	{
		moveBackForward -= cameraMoveSpeed;
	}
	//moving right
	if ((keyboardState[DIK_D] & 0x80) || (keyboardState[DIK_RIGHTARROW] & 0x80))
	{
		moveLeftRight += cameraMoveSpeed;
	}
#pragma endregion

	//moving the camera based on the mouses movement
	if ((mouseCurrentState.lX != mouseLastState.lX) || (mouseCurrentState.lY != mouseLastState.lY))
	{
		camYaw += mouseLastState.lX * 0.001f;

		camPitch += mouseCurrentState.lY * 0.001f;
	}

	if (mouseCurrentState.lZ != mouseLastState.lZ)
	{
		scaleX += (mouseCurrentState.lZ * 0.001f);
	}
	if (mouseCurrentState.lZ != mouseLastState.lZ)
	{
		scaleY += (mouseCurrentState.lZ * 0.001f);
	}

	mouseLastState = mouseCurrentState;

	UpdateCamera();

	return;
}
Beispiel #22
0
// Updating
void VoxGame::Update()
{
	// FPS
#ifdef _WIN32
	QueryPerformanceCounter(&m_fpsCurrentTicks);
	m_deltaTime = ((float)(m_fpsCurrentTicks.QuadPart - m_fpsPreviousTicks.QuadPart) / (float)m_fpsTicksPerSecond.QuadPart);
#else
	struct timeval tm;
	gettimeofday(&tm, NULL);
	m_fpsCurrentTicks = (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0;
	m_deltaTime = (m_fpsCurrentTicks - m_fpsPreviousTicks);
#endif //_WIN32
	m_fps = 1.0f / m_deltaTime;
	m_fpsPreviousTicks = m_fpsCurrentTicks;

	// Update interpolator singleton
	Interpolator::GetInstance()->Update(m_deltaTime);

	// Pause the interpolator if animations are paused.
	Interpolator::GetInstance()->SetPaused(m_animationUpdate == false);

	// Update the time manager (countdowntimers);
	TimeManager::GetInstance()->Update(m_deltaTime);

	// Animation update
	if (m_animationUpdate)
	{
		// Update the lighting manager
		m_pLightingManager->Update(m_deltaTime);

		// Block particle manager
		m_pBlockParticleManager->Update(m_deltaTime);

		// Player
		m_pPlayer->Update(m_deltaTime);

		if (m_cameraMode == CameraMode_MouseRotate || m_cameraMode == CameraMode_AutoCamera)
		{
			vec3 playerMovementChanged = m_pPlayer->GetPositionMovementAmount();
			m_pGameCamera->SetFakePosition(m_pGameCamera->GetFakePosition() + playerMovementChanged);
		}
	}

	// Update the chunk manager
	m_pChunkManager->Update(m_deltaTime);
	
	// Update controls
	UpdateControls(m_deltaTime);

	// Update the camera based on movements
	if (m_gameMode == GameMode_Game)
	{
		UpdateCamera(m_deltaTime);
	}

	// Update the dynamic camera zoom
	UpdateCameraZoom(m_deltaTime);

	// Update the camera clipping
	m_targetCameraPositionBeforeClipping = m_pGameCamera->GetFakePosition();
	UpdateCameraClipping(m_deltaTime);

	// Update the player's alpha and transparency based on camera distance to player
	if (m_gameMode == GameMode_Game && m_cameraMode != CameraMode_Debug)
	{
		UpdatePlayerAlpha(m_deltaTime);
	}

	// Update the GUI
	int x = m_pVoxWindow->GetCursorX();
	int y = m_pVoxWindow->GetCursorY();
	m_pGUI->Update(m_deltaTime);
	if (m_pVoxWindow->IsCursorOn())
	{
		m_pGUI->ImportMouseMotion(x, m_windowHeight - y);
	}
	UpdateGUI(m_deltaTime);

	// Update lights
	UpdateLights(m_deltaTime);

	// Update the application and window
	m_pVoxApplication->Update(m_deltaTime);
	m_pVoxWindow->Update(m_deltaTime);
}
Beispiel #23
0
void
TacRefDlg::SelectShip(const ShipDesign* design)
{
    if (beauty && camview) {
        scene.Graphics().clear();

        if (design) {
            radius = design->radius;

            UpdateCamera();

            int level = design->lod_levels-1;
            int n     = design->models[level].size();

            for (int i = 0; i < n; i++) {
                Model* model = design->models[level].at(i);

                Solid* s = new(__FILE__,__LINE__) Solid;
                s->UseModel(model);
                s->CreateShadows(1);
                s->MoveTo(*design->offsets[level].at(i));

                scene.Graphics().append(s);
            }
        }
    }

    if (txt_caption) {
        txt_caption->SetText("");

        if (design) {
            char txt[256];
            sprintf_s(txt, "%s %s", design->abrv, design->DisplayName());
            txt_caption->SetText(txt);
        }
    }

    if (txt_stats) {
        txt_stats->SetText("");

        if (design) {
            Text desc;
            char txt[256];

            sprintf_s(txt, "%s\t\t\t%s\n", Game::GetText("tacref.type").data(), Ship::ClassName(design->type));
            desc += txt;

            sprintf_s(txt, "%s\t\t\t%s\n", Game::GetText("tacref.class").data(), design->DisplayName());
            desc += txt;
            desc += Game::GetText("tacref.length");
            desc += "\t\t";

            if (design->type < Ship::STATION)
            FormatNumber(txt, design->radius/2);
            else
            FormatNumber(txt, design->radius*2);

            strcat_s(txt, " m\n");
            desc += txt;
            desc += Game::GetText("tacref.mass");
            desc += "\t\t\t";

            FormatNumber(txt, design->mass);
            strcat_s(txt, " T\n");
            desc += txt;
            desc += Game::GetText("tacref.hull");
            desc += "\t\t\t";

            FormatNumber(txt, design->integrity);
            strcat_s(txt, "\n");
            desc += txt;

            if (design->weapons.size()) {
                desc += Game::GetText("tacref.weapons");

                WepGroup groups[8];
                for (int w = 0; w < design->weapons.size(); w++) {
                    Weapon*     gun   = design->weapons[w];
                    WepGroup*   group = FindWepGroup(groups, gun->Group());

                    if (group)
                    group->count++;
                }

                for (int g = 0; g < 8; g++) {
                    WepGroup* group = &groups[g];
                    if (group && group->count) {
                        sprintf_s(txt, "\t\t%s (%d)\n\t\t", group->name.data(), group->count);
                        desc += txt;

                        for (int w = 0; w < design->weapons.size(); w++) {
                            Weapon* gun = design->weapons[w];

                            if (group->name == gun->Group()) {
                                sprintf_s(txt, "\t\t\t%s\n\t\t", (const char*) gun->Design()->name);
                                desc += txt;
                            }
                        }
                    }
                }

                desc += "\n";
            }

            txt_stats->SetText(desc);
        }
    }

    if (txt_description) {
        if (design && design->description.length()) {
            txt_description->SetText(design->description);
        }
        else {
            txt_description->SetText(Game::GetText("tacref.mass"));
        }
    }
}
Beispiel #24
0
void Pipeline::SetCameraAngleX(float fAngleX)
{
	this->fAngleX = fAngleX;
	UpdateCamera();
}
// Called every frame
void APlayerCharacter::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (isWalkingForward || isWalkingRight)
	{
		if (CanJump())
			UGameplayStatics::PlaySoundAtLocation(GetWorld(), WalkSound, GetActorLocation());
	}
	if (isJumpingGruntCheck)
	{
		UGameplayStatics::PlaySoundAtLocation(GetWorld(), GruntSound, GetActorLocation());
		isJumpingGruntCheck = false;
	}

	if (GetVelocity().Z == 0 && isJumpingGroundCheck)
	{
		UGameplayStatics::PlaySoundAtLocation(GetWorld(), JumpSound, GetActorLocation());
		isJumpingGroundCheck = false;

		UPeterAnimInstance* PeterAnimInstance = Cast<UPeterAnimInstance>(GetMesh()->GetAnimInstance());

		if (PeterAnimInstance)
		{
		}

	}
	if (CameraIsChanging == true)
	{
		UpdateCamera(FantasyCounter);
	}
	if (ShowTime == true)
	{
		FadeToWhite();
	}

	if (PhysicsHandleActive)
	{
		if (PhysicsHandler)
		{
			FVector HandleLocation;

			FVector ControllerForwardVector = UKismetMathLibrary::GetForwardVector(GetControlRotation());

			HandleLocation = ControllerForwardVector * 250 + GetActorLocation();

			HandleLocation.Z += 50;

			PhysicsHandler->SetTargetLocationAndRotation(HandleLocation, GetControlRotation());
		}
	}
	else if (PhysicsHandleActive == false)
	{
		PhysicsHandler->ReleaseComponent();
		if (PickedUpBox)
		{
			PickedUpBox->Drop(this);
		}
	}

	UPeterAnimInstance* PeterAnimInstance = Cast<UPeterAnimInstance>(GetMesh()->GetAnimInstance());
}
Beispiel #26
0
// Updating
void VoxGame::Update()
{
	// FPS
#ifdef _WIN32
	QueryPerformanceCounter(&m_fpsCurrentTicks);
	m_deltaTime = ((float)(m_fpsCurrentTicks.QuadPart - m_fpsPreviousTicks.QuadPart) / (float)m_fpsTicksPerSecond.QuadPart);
#else
	struct timeval tm;
	gettimeofday(&tm, NULL);
	m_fpsCurrentTicks = (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0;
	m_deltaTime = (m_fpsCurrentTicks - m_fpsPreviousTicks);
#endif //_WIN32
	m_fps = 1.0f / m_deltaTime;
	m_fpsPreviousTicks = m_fpsCurrentTicks;

	float maxDeltaTime = 0.25f;
	if (m_deltaTime > maxDeltaTime)
	{
		cout << "Warning: DeltaTime exceeded sensible value, switching dt from " << m_deltaTime << " to " << maxDeltaTime << ".\n";
		m_deltaTime = maxDeltaTime;
	}

	// Update interpolator singleton
	Interpolator::GetInstance()->Update(m_deltaTime);

	// Pause the interpolator we are are paused.
	Interpolator::GetInstance()->SetPaused(m_bPaused);

	// Update the time manager (countdowntimers);
	TimeManager::GetInstance()->Update(m_deltaTime);

	// Update the audio manager
	AudioManager::GetInstance()->Update(m_pGameCamera->GetPosition(), m_pGameCamera->GetFacing(), m_pGameCamera->GetUp());

	// Update the initial wait timer and variables, so we dont do gameplay updates straight away
	if (m_initialStartWait == true)
	{
		if (m_initialWaitTimer > m_initialWaitTime)
		{
			m_initialStartWait = false;
		}
		else
		{
			m_initialWaitTimer += m_deltaTime;
			m_initialStartWait = true;
		}
	}

	// Update the current biome
	Biome currentBiome = m_pBiomeManager->GetBiome(m_pPlayer->GetCenter());
	if (currentBiome != m_currentBiome)
	{
		m_pSkybox->SetCurrentBiome(currentBiome);
		m_currentBiome = currentBiome;
	}
	
	// Update game music
	if (m_gameMode == GameMode_Game)
	{
		UpdateGameMusic(m_deltaTime);
	}

	// Main components update
	if (m_bPaused == false && m_initialStartWait == false)
	{
		// Update the lighting manager
		m_pLightingManager->Update(m_deltaTime);

		// Block particle manager
		m_pBlockParticleManager->Update(m_deltaTime);

		// Instance manager
		m_pInstanceManager->Update(m_deltaTime);

		// Scenery manager
		m_pSceneryManager->Update(m_deltaTime);

		// Inventory manager
		m_pInventoryManager->Update(m_deltaTime);

		// Item manager
		m_pItemManager->Update(m_deltaTime);
		m_pItemManager->UpdateItemLights(m_deltaTime);
		m_pItemManager->UpdateItemParticleEffects(m_deltaTime);
		m_interactItemMutex.lock();
		m_pInteractItem = m_pItemManager->CheckItemPlayerInteraction();
		m_interactItemMutex.unlock();

		// Projectile manager
		m_pProjectileManager->Update(m_deltaTime);
		m_pProjectileManager->UpdateProjectileLights(m_deltaTime);
		m_pProjectileManager->UpdateProjectileParticleEffects(m_deltaTime);

		// Text effects manager
		m_pTextEffectsManager->Update(m_deltaTime);

		// Update the NPC manager
		m_pNPCManager->Update(m_deltaTime);

		// Update the enemy manager
		m_pEnemyManager->Update(m_deltaTime);

		// Update the biome manager
		m_pBiomeManager->Update(m_deltaTime);

		// Player
		if (m_animationUpdate)
		{
			m_pPlayer->Update(m_deltaTime);
		}

		// Camera faked position
		if (m_cameraMode == CameraMode_MouseRotate || m_cameraMode == CameraMode_AutoCamera || m_cameraMode == CameraMode_NPCDialog)
		{
			vec3 playerMovementChanged = m_pPlayer->GetPositionMovementAmount();
			m_pGameCamera->SetFakePosition(m_pGameCamera->GetFakePosition() + playerMovementChanged);
		}

		// Water
		m_elapsedWaterTime += m_deltaTime;
	}

	// Update the chunk manager
	m_pChunkManager->Update(m_deltaTime);

	// Update name picking
	if (m_pGUI->IsMouseInteractingWithGUIComponent(false) == false)
	{
		UpdateNamePicking();
	}

	// Update the NPC hover selection based on the mouse name picking
	if (m_gameMode == GameMode_FrontEnd)
	{
		if (m_bNamePickingSelected)
		{
			m_pNPCManager->UpdateHoverNamePickingSelection(m_pickedObject);
		}
		else
		{
			m_pNPCManager->UpdateHoverNamePickingSelection(-1);
		}
	}

	// Update controls
	UpdateControls(m_deltaTime);

	// Update the camera based on movements
	if (m_gameMode == GameMode_Game)
	{
		UpdateCamera(m_deltaTime);
		m_pPlayer->SetCameraPosition(m_pGameCamera->GetPosition());
		m_pPlayer->SetCameraForward(normalize(m_pGameCamera->GetFacing()));
		m_pPlayer->SetCameraUp(normalize(m_pGameCamera->GetUp()));
		m_pPlayer->SetCameraRight(normalize(m_pGameCamera->GetRight()));
	}

	// Update the dynamic camera zoom
	UpdateCameraZoom(m_deltaTime);

	// Update the camera clipping
	m_targetCameraPositionBeforeClipping = m_pGameCamera->GetFakePosition();
	UpdateCameraClipping(m_deltaTime);

	// Update the player's alpha and transparency based on camera distance to player
	if (m_gameMode == GameMode_Game && m_cameraMode != CameraMode_Debug)
	{
		UpdatePlayerAlpha(m_deltaTime);
	}

	// Update the frontend
	m_pFrontendManager->Update(m_deltaTime);

	// Update the GUI
	int x = m_pVoxWindow->GetCursorX();
	int y = m_pVoxWindow->GetCursorY();
	m_pGUI->Update(m_deltaTime);
	if (IsCursorOn())
	{
		m_pGUI->ImportMouseMotion(x, m_windowHeight - y);
	}
	UpdateGUI(m_deltaTime);

	if (m_bPaused == false && m_initialStartWait == false)
	{
		// Update game GUI
		UpdateGameGUI(m_deltaTime);

		// Update lights
		UpdateLights(m_deltaTime);
	}

	// Update the application and window
	m_pVoxWindow->Update(m_deltaTime);
}
Beispiel #27
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;
    
    SetConfigFlags(FLAG_MSAA_4X_HINT);
    InitWindow(screenWidth, screenHeight, "raylib [shaders] example - basic lighting");
    
    // Camera initialization
    Camera camera = {{ 8.0f, 8.0f, 8.0f }, { 0.0f, 3.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }};
    
    // Model initialization
    Vector3 position = { 0.0f, 0.0f, 0.0f };
    Model model = LoadModel("resources/model/dwarf.obj");
    Shader shader = LoadShader("resources/shaders/phong.vs", "resources/shaders/phong.fs");
    SetModelShader(&model, shader);
    
    // Shader locations initialization
    int lIntensityLoc = GetShaderLocation(shader, "light_intensity");
    int lAmbientLoc = GetShaderLocation(shader, "light_ambientColor");
    int lDiffuseLoc = GetShaderLocation(shader, "light_diffuseColor");
    int lSpecularLoc = GetShaderLocation(shader, "light_specularColor");
    int lSpecIntensityLoc = GetShaderLocation(shader, "light_specIntensity");
    
    int mAmbientLoc = GetShaderLocation(shader, "mat_ambientColor");
    int mSpecularLoc = GetShaderLocation(shader, "mat_specularColor");
    int mGlossLoc = GetShaderLocation(shader, "mat_glossiness");
    
    // Camera and light vectors shader locations
    int cameraLoc = GetShaderLocation(shader, "cameraPos");
    int lightLoc = GetShaderLocation(shader, "lightPos");
    
    // Model and View matrix locations (required for lighting)
    int modelLoc = GetShaderLocation(shader, "modelMatrix");
    //int viewLoc = GetShaderLocation(shader, "viewMatrix");        // Not used
    
    // Light and material definitions
    Light light;
    Material matBlinn;
    
    // Light initialization
    light.position = (Vector3){ 4.0f, 2.0f, 0.0f };
    light.direction = (Vector3){ 5.0f, 1.0f, 1.0f };
    light.intensity = 1.0f;
    light.diffuse = WHITE;
    light.ambient = (Color){ 150, 75, 0, 255 };
    light.specular = WHITE;
    light.specIntensity = 1.0f;
    
    // Material initialization
    matBlinn.colDiffuse = WHITE;
    matBlinn.colAmbient = (Color){ 50, 50, 50, 255 };
    matBlinn.colSpecular = WHITE;
    matBlinn.glossiness = 50.0f;
    
    // Setup camera
    SetCameraMode(CAMERA_FREE);             // Set camera mode
    SetCameraPosition(camera.position);     // Set internal camera position to match our camera position
    SetCameraTarget(camera.target);         // Set internal camera target to match our camera target
    
    SetTargetFPS(60);
    //--------------------------------------------------------------------------------------
    
    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        UpdateCamera(&camera);      // Update camera position
        
        // NOTE: Model transform can be set in model.transform or directly with params at draw... WATCH OUT!
        SetShaderValueMatrix(shader, modelLoc, model.transform);            // Send model matrix to shader
        //SetShaderValueMatrix(shader, viewLoc, GetCameraMatrix(camera));   // Not used
        
        // Glossiness input control
        if(IsKeyDown(KEY_UP)) matBlinn.glossiness += SHININESS_SPEED;
        else if(IsKeyDown(KEY_DOWN))
        {
            matBlinn.glossiness -= SHININESS_SPEED;
            if( matBlinn.glossiness < 0) matBlinn.glossiness = 0.0f;
        }
        
        // Light X movement
        if (IsKeyDown(KEY_D)) light.position.x += LIGHT_SPEED;
        else if(IsKeyDown(KEY_A)) light.position.x -= LIGHT_SPEED;
        
        // Light Y movement
        if (IsKeyDown(KEY_LEFT_SHIFT)) light.position.y += LIGHT_SPEED;
        else if (IsKeyDown(KEY_LEFT_CONTROL)) light.position.y -= LIGHT_SPEED;

        // Light Z movement
        if (IsKeyDown(KEY_S)) light.position.z += LIGHT_SPEED;
        else if (IsKeyDown(KEY_W)) light.position.z -= LIGHT_SPEED;
        
        // Send light values to shader
        SetShaderValue(shader, lIntensityLoc, &light.intensity, 1);
        SetShaderValue(shader, lAmbientLoc, ColorToFloat(light.ambient), 3);
        SetShaderValue(shader, lDiffuseLoc, ColorToFloat(light.diffuse), 3);
        SetShaderValue(shader, lSpecularLoc, ColorToFloat(light.specular), 3);
        SetShaderValue(shader, lSpecIntensityLoc, &light.specIntensity, 1);
        
        // Send material values to shader
        SetShaderValue(shader, mAmbientLoc, ColorToFloat(matBlinn.colAmbient), 3);
        SetShaderValue(shader, mSpecularLoc, ColorToFloat(matBlinn.colSpecular), 3);
        SetShaderValue(shader, mGlossLoc, &matBlinn.glossiness, 1);
        
        // Send camera and light transform values to shader
        SetShaderValue(shader, cameraLoc, VectorToFloat(camera.position), 3);
        SetShaderValue(shader, lightLoc, VectorToFloat(light.position), 3);
        //----------------------------------------------------------------------------------
        
        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();
        
            ClearBackground(RAYWHITE);
            
            Begin3dMode(camera);
                
                DrawModel(model, position, 4.0f, matBlinn.colDiffuse);
                DrawSphere(light.position, 0.5f, GOLD);
                
                DrawGrid(20, 1.0f);
                
            End3dMode();
            
            DrawFPS(10, 10);                // Draw FPS
            
        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadShader(shader);
    UnloadModel(model);

    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------
    
    return 0;
}
Beispiel #28
0
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 800;
    int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing");

    // Define the camera to look into our 3d world
    Camera camera = {{ 16.0f, 14.0f, 16.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f };

    Image image = LoadImage("resources/cubicmap.png");      // Load cubicmap image (RAM)
    Texture2D cubicmap = LoadTextureFromImage(image);       // Convert image to texture to display (VRAM)
    Model map = LoadCubicmap(image);                        // Load cubicmap model (generate model from image)
    
    // NOTE: By default each cube is mapped to one part of texture atlas
    Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");    // Load map texture
    map.material.texDiffuse = texture;                      // Set map diffuse texture
    
    Vector3 mapPosition = { -16.0f, 0.0f, -8.0f };          // Set model position

    UnloadImage(image);     // Unload cubesmap image from RAM, already uploaded to VRAM
    
    SetCameraMode(camera, CAMERA_ORBITAL);  // Set an orbital camera mode

    SetTargetFPS(60);                       // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())            // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        UpdateCamera(&camera);              // Update camera
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            Begin3dMode(camera);

                DrawModel(map, mapPosition, 1.0f, WHITE);

            End3dMode();
            
            DrawTextureEx(cubicmap, (Vector2){ screenWidth - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE);
            DrawRectangleLines(screenWidth - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN);
            
            DrawText("cubicmap image used to", 658, 90, 10, GRAY);
            DrawText("generate map 3d model", 658, 104, 10, GRAY);

            DrawFPS(10, 10);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadTexture(cubicmap);    // Unload cubicmap texture
    UnloadTexture(texture);     // Unload map texture
    UnloadModel(map);           // Unload map model

    CloseWindow();              // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze");

    // Define the camera to look into our 3d world
    Camera camera = { { 0.2f, 0.4f, 0.2f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 };

    Image imMap = LoadImage("resources/cubicmap.png");      // Load cubicmap image (RAM)
    Texture2D cubicmap = LoadTextureFromImage(imMap);       // Convert image to texture to display (VRAM)
    Mesh mesh = GenMeshCubicmap(imMap, (Vector3){ 1.0f, 1.0f, 1.0f });
    Model model = LoadModelFromMesh(mesh);

    // NOTE: By default each cube is mapped to one part of texture atlas
    Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");    // Load map texture
    model.materials[0].maps[MAP_DIFFUSE].texture = texture;             // Set map diffuse texture

    // Get map image data to be used for collision detection
    Color *mapPixels = GetImageData(imMap);
    UnloadImage(imMap);             // Unload image from RAM

    Vector3 mapPosition = { -16.0f, 0.0f, -8.0f };  // Set model position
    Vector3 playerPosition = camera.position;       // Set player position

    SetCameraMode(camera, CAMERA_FIRST_PERSON);     // Set camera mode

    SetTargetFPS(60);               // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        Vector3 oldCamPos = camera.position;    // Store old camera position

        UpdateCamera(&camera);      // Update camera

        // Check player collision (we simplify to 2D collision detection)
        Vector2 playerPos = { camera.position.x, camera.position.z };
        float playerRadius = 0.1f;  // Collision radius (player is modelled as a cilinder for collision)

        int playerCellX = (int)(playerPos.x - mapPosition.x + 0.5f);
        int playerCellY = (int)(playerPos.y - mapPosition.z + 0.5f);

        // Out-of-limits security check
        if (playerCellX < 0) playerCellX = 0;
        else if (playerCellX >= cubicmap.width) playerCellX = cubicmap.width - 1;

        if (playerCellY < 0) playerCellY = 0;
        else if (playerCellY >= cubicmap.height) playerCellY = cubicmap.height - 1;

        // Check map collisions using image data and player position
        // TODO: Improvement: Just check player surrounding cells for collision
        for (int y = 0; y < cubicmap.height; y++)
        {
            for (int x = 0; x < cubicmap.width; x++)
            {
                if ((mapPixels[y*cubicmap.width + x].r == 255) &&       // Collision: white pixel, only check R channel
                    (CheckCollisionCircleRec(playerPos, playerRadius,
                    (Rectangle){ mapPosition.x - 0.5f + x*1.0f, mapPosition.z - 0.5f + y*1.0f, 1.0f, 1.0f })))
                {
                    // Collision detected, reset camera position
                    camera.position = oldCamPos;
                }
            }
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            BeginMode3D(camera);

                DrawModel(model, mapPosition, 1.0f, WHITE);                     // Draw maze map
                //DrawCubeV(playerPosition, (Vector3){ 0.2f, 0.4f, 0.2f }, RED);  // Draw player

            EndMode3D();

            DrawTextureEx(cubicmap, (Vector2){ GetScreenWidth() - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE);
            DrawRectangleLines(GetScreenWidth() - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN);

            // Draw player position radar
            DrawRectangle(GetScreenWidth() - cubicmap.width*4 - 20 + playerCellX*4, 20 + playerCellY*4, 4, 4, RED);

            DrawFPS(10, 10);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    free(mapPixels);            // Unload color array

    UnloadTexture(cubicmap);    // Unload cubicmap texture
    UnloadTexture(texture);     // Unload map texture
    UnloadModel(model);         // Unload map model

    CloseWindow();              // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}