Example #1
0
Vector3d Quaternion::directionVector(const int col) const {
    Matrix4 dirMat = toMatrix();
    return Vector3d(dirMat.getValue(0, col), dirMat.getValue(1, col), dirMat.getValue(2, col));
}
Example #2
0
bool XMLElement::SetMatrix4(const ea::string& name, const Matrix4& value)
{
    return SetAttribute(name, value.ToString());
}
void Matrix4::load(const Matrix4& v) {
    memcpy(data, v.data, sizeof(data));
    mType = v.getType();
}
Example #4
0
Matrix4 operator*(Matrix4 left, const Matrix4& right) {
    return left.Multiply(right);
}
Example #5
0
void DisCOVERay::renderRect(const vistle::Matrix4 &P, const vistle::Matrix4 &MV, const IceTInt *viewport,
                           int width, int height, unsigned char *rgba, float *depth) {

   //StopWatch timer("DisCOVERay::render()");

#if 0
   CERR << "IceT draw CB: vp=" << viewport[0] << ", " << viewport[1] << ", " << viewport[2] << ", " <<  viewport[3]
             << ", img: " << width << "x" << height
             << std::endl;
#endif

   const int w = viewport[2];
   const int h = viewport[3];
   const int ts = m_tilesize;
   const int wt = ((w+ts-1)/ts)*ts;
   const int ht = ((h+ts-1)/ts)*ts;
   const int ntx = wt/ts;
   const int nty = ht/ts;

   //CERR << "PROJ:" << P << std::endl << std::endl;

   const vistle::Matrix4 MVP = P * MV;
   const auto inv = MVP.inverse();

   const Vector4 ro4 = MV.inverse().col(3);
   const Vector ro = ro4.block<3,1>(0,0)/ro4[3];

   const Vector4 lbn4 = inv * Vector4(-1, -1, -1, 1);
   Vector lbn(lbn4[0], lbn4[1], lbn4[2]);
   lbn /= lbn4[3];

   const Vector4 lbf4 = inv * Vector4(-1, -1, 1, 1);
   Vector lbf(lbf4[0], lbf4[1], lbf4[2]);
   lbf /= lbf4[3];

   const Vector4 rbn4 = inv * Vector4(1, -1, -1, 1);
   Vector rbn(rbn4[0], rbn4[1], rbn4[2]);
   rbn /= rbn4[3];

   const Vector4 ltn4 = inv * Vector4(-1, 1, -1, 1);
   Vector ltn(ltn4[0], ltn4[1], ltn4[2]);
   ltn /= ltn4[3];

   const Scalar tFar = (lbf-ro).norm()/(lbn-ro).norm();
   const Matrix4 depthTransform = MVP;

   TileTask renderTile(*this, m_renderManager.viewData(m_currentView));
   renderTile.rgba = rgba;
   renderTile.depth = depth;
   renderTile.depthTransform2 = depthTransform.row(2);
   renderTile.depthTransform3 = depthTransform.row(3);
   renderTile.ntx = ntx;
   renderTile.xoff = viewport[0];
   renderTile.yoff = viewport[1];
   renderTile.xlim = viewport[0] + viewport[2];
   renderTile.ylim = viewport[1] + viewport[3];
   renderTile.imgWidth = width;
   renderTile.imgHeight = height;
   renderTile.dx = (rbn-lbn)/renderTile.imgWidth;
   renderTile.dy = (ltn-lbn)/renderTile.imgHeight;
   renderTile.lowerBottom = lbn + 0.5*renderTile.dx + 0.5*renderTile.dy;
   renderTile.origin = ro;
   renderTile.tNear = 1.;
   renderTile.tFar = tFar;
   renderTile.modelView = MV;
#ifdef USE_TBB
   tbb::parallel_for(0, ntx*nty, 1, renderTile);
#else
#pragma omp parallel for schedule(dynamic)
   for (int t=0; t<ntx*nty; ++t) {
      renderTile(t);
   }
#endif

#if 0
   std::vector<std::future<void>> tiles;

   for (int t=0; t<ntx*nty; ++t) {
      TileTask renderTile(*this, t);
      renderTile.rgba = rgba;
      renderTile.depth = depth;
      renderTile.depthTransform = depthTransform;
      renderTile.ntx = ntx;
      renderTile.xoff = x0;
      renderTile.yoff = y0;
      renderTile.width = x1;
      renderTile.height = y1;
      renderTile.dx = (rbn-lbn)/w;
      renderTile.dy = (ltn-lbn)/h;
      renderTile.lowerBottom = lbn + 0.5*renderTile.dx + 0.5*renderTile.dy;
      renderTile.tNear = 1.;
      renderTile.tFar = zFar/zNear;
      tiles.emplace_back(std::async(std::launch::async, renderTile));
   }

   for (auto &task: tiles) {
      task.get();
   }
#endif

#ifdef ICET_CALLBACK
   m_renderManager.updateRect(m_currentView, viewport);
#endif

   int err = rtcGetDeviceError (m_device);
   if (err != 0) {
      CERR << "RTC error: " << err << std::endl;
   }
}
Example #6
0
scene::INodePtr BrushDef3Parser::parse(parser::DefTokeniser& tok) const
{
	// Create a new brush
	scene::INodePtr node = GlobalBrushCreator().createBrush();

	// Cast the node, this must succeed
	IBrushNodePtr brushNode = boost::dynamic_pointer_cast<IBrushNode>(node);
	assert(brushNode != NULL);

	IBrush& brush = brushNode->getIBrush();

	tok.assertNextToken("{");

	// Parse face tokens until a closing brace is encountered
	while (1)
	{
		std::string token = tok.nextToken();

		// Token should be either a "(" (start of face) or "}" (end of brush)
		if (token == "}")
		{
			break; // end of brush
		}
		else if (token == "(") // FACE
		{
			// Construct a plane and parse its values
			Plane3 plane;

			plane.normal().x() = string::to_float(tok.nextToken());
			plane.normal().y() = string::to_float(tok.nextToken());
			plane.normal().z() = string::to_float(tok.nextToken());
			plane.dist() = -string::to_float(tok.nextToken()); // negate d

			tok.assertNextToken(")");

			// Parse TexDef
			Matrix4 texdef;
			tok.assertNextToken("(");

			tok.assertNextToken("(");
			texdef.xx() = string::to_float(tok.nextToken());
			texdef.yx() = string::to_float(tok.nextToken());
			texdef.tx() = string::to_float(tok.nextToken());
			tok.assertNextToken(")");

			tok.assertNextToken("(");
			texdef.xy() = string::to_float(tok.nextToken());
			texdef.yy() = string::to_float(tok.nextToken());
			texdef.ty() = string::to_float(tok.nextToken());
			tok.assertNextToken(")");

			tok.assertNextToken(")");

			// Parse Shader
			std::string shader = tok.nextToken();

			// Parse Flags (usually each brush has all faces detail or all faces structural)
			IBrush::DetailFlag flag = static_cast<IBrush::DetailFlag>(
				string::convert<std::size_t>(tok.nextToken(), IBrush::Structural));
			brush.setDetailFlag(flag);

			// Ignore the other two flags
			tok.skipTokens(2);

			// Finally, add the new face to the brush
			/*IFace& face = */brush.addFace(plane, texdef, shader);
		}
		else {
			std::string text = (boost::format(_("BrushDef3Parser: invalid token '%s'")) % token).str();
			throw parser::ParseException(text);
		}
	}

	// Final outer "}"
	tok.assertNextToken("}");

	return node;
}
Example #7
0
void Matrix4::ApplyTranslation(Matrix4& matrix, const Vector3& translation) {
    matrix = matrix.Multiply(Matrix4::Translation(translation));
}
Example #8
0
//----------------------------------------------------------------------------
// Callback method called by GLUT when window readraw is necessary or when glutPostRedisplay() was called.
void Window::displayCallback()
{

	glEnable(GL_LIGHT0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // clear color and depth buffers
	glColor3f(0, 0, 1);
	//Setting moving camera
	Matrix4 glmatrix;
	if (cam) {
		if (t == 99) {
			back = true;
		}
		if (t == 0)
			back = false;
		Vector3 upd = belzCamera.upd;
		belzCamera.set(points[t], Vector3(0,0,0), upd);
		std::cout << t << std::endl;
	}
	if (altCam) {
		glmatrix = belzCamera.getInverse();
	}
	else {
		glmatrix = camera.getInverse();
	}
	//Drawing Light Source

	Matrix4 temp;
	temp.makeTranslate(position[0], position[1], position[2]);
	setMatrix(glmatrix, temp);
	glColor3f(1, 1, 0);
	glutSolidSphere(.5, 100, 100);
	setMatrix(glmatrix);
	glLightfv(GL_LIGHT0, GL_POSITION, position);
	//glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);

	/*
	//Seting main objects
	glColor3d(1, 0, 0);
	setMatrix(glmatrix, object.getMatrix());
	glutSolidCube(2);
	temp.makeTranslate(3, 1.5, 0);
	setMatrix(glmatrix, temp);
	glColor3d(1, 0, 1);
	glutSolidCube(3); 
	temp.makeTranslate(0, 1.5, 3);
	setMatrix(glmatrix, temp);
	glColor3d(0, 1, 1);
	glutSolidCube(3);
	temp.makeTranslate(0, 1.5, -3);
	setMatrix(glmatrix, temp);
	glColor3d(1, 1, 0);
	glutSolidCube(3);
	temp.makeTranslate(-3, 1.5, 0);
	setMatrix(glmatrix, temp);
	glColor3d(1, 1, 1);
	glutSolidCube(3);

	//Setting Floor
	setMatrix(glmatrix);
	glBegin(GL_QUADS);
	glNormal3d(0, 1, 0);
	glColor3d(0.5, 0.6, 0.7);
	glVertex3d(-10, 0, -10);
	glVertex3d(-10, 0, 10);
	glVertex3d(10, 0, 10);
	glVertex3d(10, 0, -10);
	glEnd();*/
	setMatrix(glmatrix);	
	if (light) {
		Globals::shader->bind();
	}
	else
		Globals::shader->unbind();
	glutSolidTeapot(5);
	plane.animate();
	plane.draw();
	Globals::shader->unbind();
	//Drawing Bezier Curve
	glBegin(GL_LINE_STRIP);
	for (int i = 0; i < 99; i++) {
		Vector3 current = points[i];
		Vector3 next = points[i + 1];
		glLineWidth(2.5);
		glColor3f(1.0, 1.0, 0.0);
		glVertex3d(current.getX(), current.getY(), current.getZ());
		glVertex3d(next.getX(), next.getY(), next.getZ());
	}
	glEnd();

	//Drawing Head
	glActiveTexture(GL_TEXTURE0);
	temp = glmatrix;
	control.set(person.getMatrix());
	character.draw(temp, light);
	
	//Drawing Camera
	setMatrix(glmatrix, cameraObject.getMatrix());
	glColor3f(0, 1, 1);
	glutSolidSphere(.5,100,100);
	if (cam) {
		Vector3 current;
		current = points[t];
		cameraObject.set(current.getX(), current.getY(), current.getZ());
		if (automatic) {
			if (!back) {
				t++;
			}
			else {
				t--;
			}
		}
	}
	glFlush();
	glutSwapBuffers();
}
Example #9
0
//----------------------------------------------------------------------------
// Callback method called by GLUT when users press specific keys on the keyboard
void Window::keyboardCallback(unsigned char key, int xn, int yn) {
	glMatrixMode(GL_PROJECTION);
	Matrix4 temp;
	switch (key) {
	case'q':
		person.rotateY(5);
		temp.makeRotateY(5);
		ahead = temp * ahead;
		side = temp * side;
		camera.rotateDirectionY(5);
		break;
	case'Q':
		person.rotateY(5);
		break;
	case'e':
		person.rotateY(-5);
		temp.makeRotateY(-5);
		ahead = temp * ahead;
		side = temp * side;
		camera.rotateDirectionY(-5);
		break;
	case'E':
		person.rotateY(-5);
		break;
	case 'z':
		camera.moveUp(1);
		break;
	case 'Z':
		camera.moveDown(1);
		break;
	case 'w':
		walk = true;
		person.move(ahead.get(0), ahead.get(1), ahead.get(2));
		camera.move(Vector3(ahead.get(0),ahead.get(1),ahead.get(2)),1);
		break;
	case's':
		walk = true;
		person.move(-ahead.get(0), -ahead.get(1), -ahead.get(2));
		camera.move(Vector3(-ahead.get(0), -ahead.get(1), -ahead.get(2)), 1);
		break;
	case 'a':
		person.move(side.get(0), side.get(1), side.get(2));
		camera.move(Vector3(side.get(0), side.get(1), side.get(2)), 1);
		break;
	case 'd':
		person.move(-side.get(0), -side.get(1), -side.get(2));
		camera.move(Vector3(-side.get(0), -side.get(1), -side.get(2)), 1);
		break;
	case 'i':
		camera.moveForward(1);
		break;
	case'k':
		camera.moveBackward(1);
		break;
	case 'j':
		camera.moveLeft(1);
		break;
	case 'l':
		camera.moveRight(1);
		break;
	case 'r':
		t = 0;
		cameraObject.set(initial.get(0), initial.get(1), initial.get(2));
		object.reset();
		object.move(0, 1, 0);
		belzCamera.set(points[0], belzD, belzUp);
		person.reset();
		camera.set(e, d, up);
		ahead = Vector4(0, 0, -1, 0);
		side = Vector4(-1, 0, 0, 0);
		break;
	case 'p':
		cam = !cam;
		break;
	case'o':
		altCam = !altCam;
		break;
	case'+':
		t++;
		if (t == 100)
			t = 99;
		break;
	case'-':
		t--;
		if (t == 0)
			t = 1;
		break;
	case'.':
		automatic = !automatic;
		break;
	case'/':
		light = !light;
		break;
	}
	glMatrixMode(GL_MODELVIEW);

}
Example #10
0
 /// test equaility of two matrices
 void ASSERT_MATRIX_EQ(const Matrix4& m1, const Matrix4& m2)
 {
     ASSERT_FLOAT_EQ(m1.get(0,0), m2.get(0,0));
     ASSERT_FLOAT_EQ(m1.get(0,1), m2.get(0,1));
     ASSERT_FLOAT_EQ(m1.get(0,2), m2.get(0,2));
     ASSERT_FLOAT_EQ(m1.get(0,3), m2.get(0,3));
     ASSERT_FLOAT_EQ(m1.get(1,0), m2.get(1,0));
     ASSERT_FLOAT_EQ(m1.get(1,1), m2.get(1,1));
     ASSERT_FLOAT_EQ(m1.get(1,2), m2.get(1,2));
     ASSERT_FLOAT_EQ(m1.get(1,3), m2.get(1,3));
     ASSERT_FLOAT_EQ(m1.get(2,0), m2.get(2,0));
     ASSERT_FLOAT_EQ(m1.get(2,1), m2.get(2,1));
     ASSERT_FLOAT_EQ(m1.get(2,2), m2.get(2,2));
     ASSERT_FLOAT_EQ(m1.get(2,3), m2.get(2,3));
     ASSERT_FLOAT_EQ(m1.get(3,0), m2.get(3,0));
     ASSERT_FLOAT_EQ(m1.get(3,1), m2.get(3,1));
     ASSERT_FLOAT_EQ(m1.get(3,2), m2.get(3,2));
     ASSERT_FLOAT_EQ(m1.get(3,3), m2.get(3,3));
 }
Example #11
0
//----------------------------------------------------------------------------
// Callback method called by GLUT when window readraw is necessary or when glutPostRedisplay() was called.
void Window::displayCallback()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // clear color and depth buffers
  glMatrixMode(GL_MODELVIEW);  // make sure we're in Modelview mode

  // Tell OpenGL what ModelView matrix to use:
  Matrix4 glmatrix;
  glmatrix = Globals::cube.getMatrix();
  glmatrix.transpose();
  glLoadMatrixd(glmatrix.getPointer());

  // Draw all six faces of the cube:
  glBegin(GL_QUADS);
    glColor3f(1.0, 0.0, 0.0);		// This makes the cube green; the parameters are for red, green and blue. 
                                // To change the color of the other faces you will need to repeat this call before each face is drawn.
    // Draw front face:
    glNormal3f(0.0, 0.0, 1.0);   
    glVertex3f(-5.0,  5.0,  5.0);
    glVertex3f( 5.0,  5.0,  5.0);
    glVertex3f( 5.0, -5.0,  5.0);
    glVertex3f(-5.0, -5.0,  5.0);
    
    // Draw left side:
    glNormal3f(-1.0, 0.0, 0.0);
    glVertex3f(-5.0,  5.0,  5.0);
    glVertex3f(-5.0,  5.0, -5.0);
    glVertex3f(-5.0, -5.0, -5.0);
    glVertex3f(-5.0, -5.0,  5.0);
    
    // Draw right side:
    glNormal3f(1.0, 0.0, 0.0);
    glVertex3f( 5.0,  5.0,  5.0);
    glVertex3f( 5.0,  5.0, -5.0);
    glVertex3f( 5.0, -5.0, -5.0);
    glVertex3f( 5.0, -5.0,  5.0);
  
    // Draw back face:
    glNormal3f(0.0, 0.0, -1.0);
    glVertex3f(-5.0,  5.0, -5.0);
    glVertex3f( 5.0,  5.0, -5.0);
    glVertex3f( 5.0, -5.0, -5.0);
    glVertex3f(-5.0, -5.0, -5.0);
  
    // Draw top side:
    glNormal3f(0.0, 1.0, 0.0);
    glVertex3f(-5.0,  5.0,  5.0);
    glVertex3f( 5.0,  5.0,  5.0);
    glVertex3f( 5.0,  5.0, -5.0);
    glVertex3f(-5.0,  5.0, -5.0);
  
    // Draw bottom side:
    glNormal3f(0.0, -1.0, 0.0);
    glVertex3f(-5.0, -5.0, -5.0);
    glVertex3f( 5.0, -5.0, -5.0);
    glVertex3f( 5.0, -5.0,  5.0);
    glVertex3f(-5.0, -5.0,  5.0);
  glEnd();
  
  glFlush();  
  glutSwapBuffers();
}
// takes a projection matrix and send to the the shaders
static void sendProjectionMatrix(const ShaderState& curSS, const Matrix4& projMatrix) {
  GLfloat glmatrix[16];
  projMatrix.writeToColumnMajorMatrix(glmatrix); // send projection matrix
  safe_glUniformMatrix4fv(curSS.h_uProjMatrix, glmatrix);
}
Example #13
0
Intersection Triangle::intersect(Ray r) {
    Intersection xsect;
    xsect.init();

    real_t min_dis = 999999.9;
    Vector3 e = invMat.transform_point(r.e);
    Vector3 d = normalize(invMat.transform_vector(r.d));

    Vector3 abc = vertices[0].position - vertices[1].position;
    Vector3 def = vertices[0].position - vertices[2].position;
    Vector3 fed = Vector3(def.z, def.y, def.x);
    Vector3 ghi = d;
    Vector3 ihg = Vector3(ghi.z, ghi.y, ghi.x);
    Vector3 jkl = vertices[0].position - e;

    Vector3 det_1 = Vector3(def.y * ghi.z - ghi.y * def.z, ghi.x * def.z - def.x * ghi.z, def.x * ghi.y - def.y * ghi.x);
    Vector3 det_2 = Vector3(abc.x * jkl.y - jkl.x * abc.y, jkl.x * abc.z - abc.x * jkl.z, abc.y * jkl.z - jkl.y * abc.z);

    // barycentric weighting factors
    real_t M = dot(abc, det_1);
    real_t beta = dot(jkl, det_1) / M;
    real_t gamma = dot(ihg, det_2) / M;
    real_t theta = -1 * dot(fed, det_2) / M;

    if (beta < 0 || beta > 1 - gamma || gamma < 0 || gamma > 1 || theta < epsilon)
        return xsect;

    Matrix4 inv;
    make_transformation_matrix(&inv, position, orientation, scale);

    Vector3 local_pos = e + theta * d;
    Vector3 world_pos = inv.transform_point(local_pos);
    real_t dist = squared_distance(r.e, world_pos);

    if (dist >= min_dis * min_dis) {
        return xsect;
    }

    xsect.squared_dist = dist;
    xsect.position = world_pos;

    Vector3 local_norm = normalize(vertices[0].normal + vertices[1].normal + vertices[2].normal);
    xsect.normal = normalize(normMat * local_norm);

    xsect.exists = true;

    real_t material_mult[3] = {1 - beta - gamma, beta, gamma};

    xsect.mat.black_out();

    Vector2 texel = Vector2::Zero();

    // Use the weighting factors to interpolate values at this point
    for (int i = 0; i < 3; ++i)
    {
        xsect.mat.ambient += vertices[i].material->ambient * material_mult[i];
        xsect.mat.diffuse += vertices[i].material->diffuse * material_mult[i];
        xsect.mat.specular += vertices[i].material->specular * material_mult[i];
        xsect.mat.refractive_index += vertices[i].material->refractive_index * material_mult[i];
        texel += vertices[i].tex_coord * material_mult[i];
    }

    texel.x -= floor(texel.x);
    texel.y -= floor(texel.y);

    int w, h;

    for (int i = 0; i < 3; ++i)
    {
        vertices[i].material->get_texture_size(&w, &h);
        xsect.texel += vertices[i].material->get_texture_pixel((int)(texel.x * w), (int)(texel.y * h)) * material_mult[i];
    }

    return xsect;
}
Example #14
0
Quaternion::Quaternion(const Matrix4 &m) {
    fromMatrix(m.getRotation());
}
Example #15
0
void Lighting::SetWorldMatrix(const Matrix4& WorldInverse)
{
	glUniformMatrix4fv(m_WorldMatrixLocation, 1, GL_FALSE, (const GLfloat*)WorldInverse.Begin());
}
Example #16
0
void Window::setMatrix(Matrix4 camera) {
	glMatrixMode(GL_MODELVIEW);
	Matrix4 temp = camera;
	temp.transpose();
	glLoadMatrixd(temp.getPointer());
}
Example #17
0
void Skeleton::loadSkeleton(const String& fileName) {
	OSFILE *inFile = OSBasics::open(fileName.c_str(), "rb");
	if(!inFile) {
		return;
	}
	
	bonesEntity	= new Entity();
	bonesEntity->visible = false;
	addChild(bonesEntity);
	
	unsigned int numBones;
	float t[3],rq[4],s[3];
	
	OSBasics::read(&numBones, sizeof(unsigned int), 1, inFile);
	unsigned int namelen;
	char buffer[1024];
	
	Matrix4 mat;
	unsigned int hasParent, boneID;
	for(int i=0; i < numBones; i++) {
		
		OSBasics::read(&namelen, sizeof(unsigned int), 1, inFile);
		memset(buffer, 0, 1024);
		OSBasics::read(buffer, 1, namelen, inFile);
		
		Bone *newBone = new Bone(String(buffer));
		
		OSBasics::read(&hasParent, sizeof(unsigned int), 1, inFile);
		if(hasParent == 1) {
			OSBasics::read(&boneID, sizeof(unsigned int), 1, inFile);
			newBone->parentBoneId = boneID;
		} else {
			newBone->parentBoneId = -1;
		}

		OSBasics::read(t, sizeof(float), 3, inFile);
		OSBasics::read(s, sizeof(float), 3, inFile);
		OSBasics::read(rq, sizeof(float), 4, inFile);
		
		bones.push_back(newBone);
		
		Quaternion bq;
		bq.set(rq[0], rq[1], rq[2], rq[3]);
        
        newBone->baseRotation = bq;
        newBone->baseScale = Vector3(s[0], s[1], s[2]);
        newBone->basePosition = Vector3(t[0], t[1], t[2]);
        
		newBone->setPosition(t[0], t[1], t[2]);
		newBone->setRotationQuat(rq[0], rq[1], rq[2], rq[3]);
		newBone->setScale(s[0], s[1], s[2]);
		newBone->rebuildTransformMatrix();
		
		newBone->setBaseMatrix(newBone->getTransformMatrix());
		newBone->setBoneMatrix(newBone->getTransformMatrix());

		OSBasics::read(t, sizeof(float), 3, inFile);
		OSBasics::read(s, sizeof(float), 3, inFile);
		OSBasics::read(rq, sizeof(float), 4, inFile);
		
		Quaternion q;
		q.set(rq[0], rq[1], rq[2], rq[3]);
		Matrix4 m = q.createMatrix();
		m.setPosition(t[0], t[1], t[2]);
		
		newBone->setRestMatrix(m);
		
	}

	Bone *parentBone;
	
	for(int i=0; i < bones.size(); i++) {
		if(bones[i]->parentBoneId != -1) {
			parentBone = bones[bones[i]->parentBoneId];
			parentBone->addChildBone(bones[i]);
			bones[i]->setParentBone(parentBone);
			parentBone->addChild(bones[i]);
		} else {
			bonesEntity->addChild(bones[i]);
		}
	}
	OSBasics::close(inFile);
}
Example #18
0
void Window::loadCharacter() {
	Matrix4 temp;
	Matrix4 id;
	id.identity();

	//Setting up Controller
	temp.makeTranslate(0, 0, 10);
	control = MatrixTransform(temp);

	//Setting up Head
	headCube = Cube(2);
	headCube.setTexture(head);
	headRotation = MatrixTransform(id);
	headScaling = MatrixTransform(id);
	temp.makeTranslate(0, 7, 0);
	headTranslation = MatrixTransform(temp);
	headRotation.addChild(&headCube);
	headScaling.addChild(&headRotation);
	headTranslation.addChild(&headScaling);
	control.addChild(&headTranslation);

	//Setting up body
	bodyCube = Cube(1);
	bodyCube.setTexture(body);
	bodyRotation = MatrixTransform(id);
	temp.makeScale(2, 3, 1);
	bodyScaling = MatrixTransform(temp);
	temp.makeTranslate(0, 4.5, 0);
	bodyTranslation = MatrixTransform(temp);
	bodyRotation.addChild(&bodyCube);
	bodyScaling.addChild(&bodyRotation);
	bodyTranslation.addChild(&bodyScaling);
	control.addChild(&bodyTranslation);

	//Setting up Arms
	armCube = Cube(1);
	armCube.setTexture(arm);
	leftArmRotation = MatrixTransform(id);
	rightArmRotation = MatrixTransform(id);
	temp.makeScale(1, 3, 1);
	leftArmScaling = MatrixTransform(temp);
	rightArmScaling = MatrixTransform(temp);
	temp.makeTranslate(1.5, 4.5, 0);
	leftArmTranslation = MatrixTransform(temp);
	temp.makeTranslate(-(1.5), 4.5, 0);
	rightArmTranslation = MatrixTransform(temp);
	leftArmScaling.addChild(&armCube);
	rightArmScaling.addChild(&armCube);
	leftArmRotation.addChild(&leftArmScaling);
	rightArmRotation.addChild(&rightArmScaling);
	leftArmTranslation.addChild(&leftArmRotation);
	rightArmTranslation.addChild(&rightArmRotation);
	control.addChild(&leftArmTranslation);
	control.addChild(&rightArmTranslation);

	//Setting up Legs
	legCube = Cube(1);
	legCube.setTexture(leg);
	leftLegRotation = MatrixTransform(id);
	rightLegRotation = MatrixTransform(id);
	temp.makeScale(1, 3, 1);
	leftLegScaling = MatrixTransform(temp);
	rightLegScaling = MatrixTransform(temp);
	temp.makeTranslate(.5, 1.5, 0);
	leftLegTranslation = MatrixTransform(temp);
	temp.makeTranslate(-.5, 1.5, 0);
	rightLegTranslation = MatrixTransform(temp);
	leftLegScaling.addChild(&legCube);
	rightLegScaling.addChild(&legCube);
	leftLegRotation.addChild(&leftLegScaling);
	rightLegRotation.addChild(&rightLegScaling);
	leftLegTranslation.addChild(&leftLegRotation);
	rightLegTranslation.addChild(&rightLegRotation);
	control.addChild(&leftLegTranslation);
	control.addChild(&rightLegTranslation);

	character.addChild(&control);

}
Example #19
0
GameObject* Terrain::CreateGameObject(const char* diffuseTxt_filename, const char* normalTxt_filename, const char* heightTxt_filemane)
{
	std::vector<float2> texture_coordinate = calculateTextureCoordiate();
	std::vector<float2> boundsY = CalcAllPatchBoundsY();

	const int iNumVertices = m_initInfo.HeightmapWidth / 8 * (m_initInfo.HeightmapHeight) / 8 * 4;
	const int iNumIndices = iNumVertices;
	VertexTerrain* vertices = new VertexTerrain[iNumVertices];
	unsigned int* indices = new unsigned int[iNumIndices];

	// Translate the terrain, so that the mid-point of terrain is at (0, 0, 0)
	Matrix4 translate;
	translate.CreateTranslation(Vector3(-GetWidth() / 2.0f, 0.0f, -GetDepth() / 2.0f));

	// Initialize the index to the vertex buffer.
	int indexCounter = 0;

	// Load the vertex and index array with the terrain data.
	for (int j = 0; j < m_initInfo.HeightmapHeight - 8; j += 8)
	{
		for (int i = 0; i < m_initInfo.HeightmapWidth - 8; i += 8)
		{
			const int index_bl = m_initInfo.HeightmapWidth * j + i;
			const int index_br = m_initInfo.HeightmapWidth * j + (i + 8);
			const int index_ul = m_initInfo.HeightmapWidth * (j + 8) + i;
			const int index_ur = m_initInfo.HeightmapWidth * (j + 8) + (i + 8);

			const float2 bl_uv(
				texture_coordinate[index_bl].x, texture_coordinate[index_bl].y
				);
			const float2 br_uv(
				(texture_coordinate[index_br].x == 0.0f ? 1.0f : texture_coordinate[index_br].x),
				texture_coordinate[index_br].y
				);
			const float2 ul_uv(
				texture_coordinate[index_ul].x,
				(texture_coordinate[index_ul].y == 1.0f ? 0.0f : texture_coordinate[index_ul].y)
				);
			const float2 ur_uv(
				(texture_coordinate[index_ur].x == 0.0f ? 1.0f : texture_coordinate[index_ur].x),
				(texture_coordinate[index_ur].y == 1.0f ? 0.0f : texture_coordinate[index_ur].y)
				);

			Vector3 bl(i * m_initInfo.CellSpacing, m_HeightMap[index_bl] * m_initInfo.CellSpacing, j* m_initInfo.CellSpacing);
			Vector3 br((i + 8)* m_initInfo.CellSpacing, m_HeightMap[index_br] * m_initInfo.CellSpacing, j* m_initInfo.CellSpacing);
			Vector3 ul(i* m_initInfo.CellSpacing, m_HeightMap[index_ul] * m_initInfo.CellSpacing, (j + 8)* m_initInfo.CellSpacing);
			Vector3 ur((i + 8)* m_initInfo.CellSpacing, m_HeightMap[index_ur] * m_initInfo.CellSpacing, (j + 8)* m_initInfo.CellSpacing);

			const int patch_id = j + (i / m_initInfo.CellsPerPatch);
			// bottom left
			{
				vertices[indexCounter].m_pos = bl;
				vertices[indexCounter].m_UV[0] = bl_uv.x;
				vertices[indexCounter].m_UV[1] = bl_uv.y;
				vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x;
				vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y;
				indices[indexCounter] = indexCounter;
				indexCounter++;
			}

			// bottom right
			{
				vertices[indexCounter].m_pos = br;
				vertices[indexCounter].m_UV[0] = br_uv.x;
				vertices[indexCounter].m_UV[1] = br_uv.y;
				vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x;
				vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y;
				indices[indexCounter] = indexCounter;
				indexCounter++;
			}

			// upper left
			{
				vertices[indexCounter].m_pos = ul;
				vertices[indexCounter].m_UV[0] = ul_uv.x;
				vertices[indexCounter].m_UV[1] = ul_uv.y;
				vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x;
				vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y;
				indices[indexCounter] = indexCounter;
				indexCounter++;
			}

			// upper right
			{
				vertices[indexCounter].m_pos = ur;
				vertices[indexCounter].m_UV[0] = ur_uv.x;
				vertices[indexCounter].m_UV[1] = ur_uv.y;
				vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x;
				vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y;
				indices[indexCounter] = indexCounter;
				indexCounter++;
			}
		}
	}

	std::string diffuseTxt_filepath = std::string("../Assets/") + diffuseTxt_filename;
	std::string normalTxt_filepath = std::string("../Assets/") + normalTxt_filename;
	std::string heightTxt_filepath = std::string("../Assets/") + heightTxt_filemane;

	MeshData* meshData = new MeshData(vertices, iNumVertices, indices, iNumIndices, sizeof(VertexTerrain));
	meshData->SetBoundingBox(AABB(Vector3(0, 0, 0), Vector3(m_initInfo.HeightmapHeight, 0, m_initInfo.HeightmapWidth)));
	Handle hMeshComp(sizeof(MeshComponent));
	new (hMeshComp) MeshComponent(meshData);
	SceneGraph::GetInstance()->AddComponent((MeshComponent*) hMeshComp.Raw());

	RenderPass* renderPass = new RenderPass;
	renderPass->SetVertexShader("../DEngine/Shaders/VS_terrain.hlsl");
	renderPass->SetHullShader("../DEngine/Shaders/HS_terrain.hlsl");
	renderPass->SetDomainShader("../DEngine/Shaders/DS_terrain.hlsl");
	renderPass->SetPixelShader("../DEngine/Shaders/PS_terrain.hlsl");
	Handle hTexture1(sizeof(Texture));
	new (hTexture1) Texture(Texture::SHADER_RESOURCES, 1, diffuseTxt_filepath.c_str());
	Handle hTexture2(sizeof(Texture));
	new (hTexture2) Texture(Texture::SHADER_RESOURCES, 1, normalTxt_filepath.c_str());
	Handle hTexture3(sizeof(Texture));
	new (hTexture3) Texture(Texture::SHADER_RESOURCES, 1, heightTxt_filepath.c_str());
	renderPass->AddTexture(hTexture1);
	renderPass->AddTexture(hTexture2);
	renderPass->AddTexture(hTexture3);
	renderPass->SetTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);
	renderPass->SetBlendState(State::NULL_STATE);
	renderPass->SetRenderTargets(D3D11Renderer::GetInstance()->m_pRTVArray, 2);
	renderPass->SetDepthStencilView(D3D11Renderer::GetInstance()->m_depth->GetDSV());
	renderPass->SetDepthStencilState(State::DEFAULT_DEPTH_STENCIL_DSS);
	renderPass->SetRasterizerState(State::CULL_BACK_RS);
	((MeshComponent*) hMeshComp.Raw())->m_pMeshData->m_Material.AddPassToTechnique(renderPass);

	GameObject* terrain = new GameObject;
	terrain->AddComponent((Component*) hMeshComp.Raw());

	delete[] vertices;
	delete[] indices;

	return terrain;
}
Example #20
0
//----------------------------------------------------------------------------
// Callback method called when system is idle.
void Window::idleCallback()
{
	Matrix4 transform;
	Matrix4 temp;
	Matrix4 reverseTemp;
	temp = leftArmRotation.get();
	reverseTemp = temp;
	if (walk) {
		if (forw) {
			temp.makeRotateX(degree);
			reverseTemp.makeRotateX(-degree);
			degree++;
			if (degree == 20)
				forw = !forw;
		}
		else {
			temp.makeRotateX(degree);
			reverseTemp.makeRotateX(-degree);
			std::cout << "ASD" << std::endl;
			degree--;
			if (degree == -20)
				forw = !forw;
		}
	}
	else {
		degree = 0;
		temp.identity();
		reverseTemp.identity();
	}
	transform.makeTranslate(0, -1.5, 0);
	temp = temp * transform;
	reverseTemp = reverseTemp * transform;
	transform.makeTranslate(0, 1.5, 0);
	temp = transform * temp;
	reverseTemp = transform * reverseTemp;
	leftArmRotation.set(temp);
	rightLegRotation.set(temp);
	rightArmRotation.set(reverseTemp);
	leftLegRotation.set(reverseTemp);
    displayCallback();         // call display routine to show the object
}
Example #21
0
void Matrix4::ApplyScaling(Matrix4& matrix, const Vector3& scaling) {
    matrix = matrix.Multiply(Matrix4::Scaling(scaling));
}
Example #22
0
bool Serializer::WriteMatrix4(const Matrix4& value)
{
    return Write(value.Data(), sizeof value) == sizeof value;
}
Example #23
0
void Matrix4::ApplyRotation(Matrix4& matrix, float angle, const Vector3& axis) {
    matrix = matrix.Multiply(Matrix4::Rotation(angle, axis));
}
Example #24
0
	void Camera::rotate(const int direction){
#define sqr(x) (x*x)
		//http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html#fig:axisrot
		//r46 meg tartalmaz egy kozvetlen kepletet, matrixok nelkul, de mivel nem mukodott, lecsereltem. Gyorsitasi lehetoseg.
		const float eps = 0.1f;
		Matrix4 T;
		Matrix4 Rxz;
		Matrix4 Rxz2z;
		Matrix4 Rz;
		float d1;
		float d;
		Vector3 rotv;
		if(direction==ROTATE_LEFT || direction==ROTATE_RIGHT){
			T = T.translate(-pos);
			d1 = (sqrt(sqr(up.getX()) + sqr(up.getY()) ));
			d = sqrt(sqr(up.getX())+sqr(up.getY())+sqr(up.getZ()));
			if(d1>=eps){
				Rxz.set(0,up.getX()/d1);
				Rxz.set(1,up.getY()/d1);
				Rxz.set(4,-up.getY()/d1);
				Rxz.set(5,up.getX()/d1);
			}
			Rxz2z.set(0,up.getZ()/d);
			Rxz2z.set(2,-d1/d);
			Rxz2z.set(8,d1/d);
			Rxz2z.set(10,up.getZ()/d);
			if(direction==ROTATE_LEFT){
				rotv.setZ(rotationIntensity);
			}else{//ROTATE_RIGHT
				rotv.setZ(-rotationIntensity);
			}
			Rz = Rz.rotate(rotv);
			lookAt = lookAt*T*Rxz*Rxz2z*Rz*Rxz2z.invert()*Rxz.invert()*T.invert();
		}else if(direction==LEAN_LEFT || direction==LEAN_RIGHT){
			T = T.translate(-pos);
			Vector3 dir(pos.getX()-lookAt.getX(), pos.getY()-lookAt.getY(), pos.getZ()-lookAt.getZ());
			dir.normalize();
			d1 = sqrt(sqr(dir.getX()) + sqr(dir.getY()) );
			d  = sqrt(sqr(dir.getX())+sqr(dir.getY())+sqr(dir.getZ()));
			if(d1>=eps){
				Rxz.set(0,dir.getX()/d1);
				Rxz.set(1,dir.getY()/d1);
				Rxz.set(4,-dir.getY()/d1);
				Rxz.set(5,dir.getX()/d1);
			}
			Rxz2z.set(0,dir.getZ()/d);
			Rxz2z.set(2,-d1/d);
			Rxz2z.set(8,d1/d);
			Rxz2z.set(10,dir.getZ()/d);
			if(direction==LEAN_LEFT){
				rotv.setZ(rotationIntensity);
			}else{//LEAN_RIGHT
				rotv.setZ(-rotationIntensity);
			}
			Rz = Rz.rotate(rotv);
			up = up*T*Rxz*Rxz2z*Rz*Rxz2z.invert()*Rxz.invert()*T.invert();
		}else if(ROTATE_UP || ROTATE_DOWN){
			Vector3 dir = lookAt-pos;
			dir.normalize();
			Vector3 right = dir.crossProduct(up);
			T = T.translate(-pos);
			d1 = (sqrt(sqr(right.getX()) + sqr(right.getY()) ));
			d = sqrt(sqr(right.getX())+sqr(right.getY())+sqr(right.getZ()));
			if(d1>=eps){
				Rxz.set(0,right.getX()/d1);
				Rxz.set(1,right.getY()/d1);
				Rxz.set(4,-right.getY()/d1);
				Rxz.set(5,right.getX()/d1);
			}
			Rxz2z.set(0,right.getZ()/d);
			Rxz2z.set(2,-d1/d);
			Rxz2z.set(8,d1/d);
			Rxz2z.set(10,right.getZ()/d);
			if(direction==ROTATE_UP){
				rotv.setZ(rotationIntensity);
			}else{//ROTATE_DOWN
				rotv.setZ(-rotationIntensity);
			}
			Rz = Rz.rotate(rotv);
			Vector3 newLookAt = lookAt*T*Rxz*Rxz2z*Rz*Rxz2z.invert()*Rxz.invert()*T.invert();
			dir = newLookAt-pos;
			dir.normalize();
			if(dir.crossProduct(up).length()>=0.2f){
				lookAt = newLookAt;
			}
			//up     =     up  *Rxz*Rxz2z*Rz*Rxz2z.invert()*Rxz.invert();
		}
#undef sqr
	}
	//---------------------------------------------------------------------
	void HlslFixedFuncEmuShaderGenerator::HlslFixedFuncPrograms::setFixedFuncProgramsParameters( const FixedFuncProgramsParameters & params )
	{
		_setProgramMatrix4Parameter(GPT_VERTEX_PROGRAM, "World", params.getWorldMat());
		_setProgramMatrix4Parameter(GPT_VERTEX_PROGRAM, "View", params.getViewMat());
		_setProgramMatrix4Parameter(GPT_VERTEX_PROGRAM, "Projection", params.getProjectionMat());

		_setProgramMatrix4Parameter(GPT_VERTEX_PROGRAM, "ViewIT", params.getViewMat().inverse().transpose());


		Matrix4 WorldViewIT = params.getViewMat() * params.getWorldMat();
		WorldViewIT = WorldViewIT.inverse().transpose();
		_setProgramMatrix4Parameter(GPT_VERTEX_PROGRAM, "WorldViewIT", WorldViewIT);


		_setProgramColorParameter(GPT_VERTEX_PROGRAM, "BaseLightAmbient", params.getLightAmbient());
		if (params.getLightingEnabled() && params.getLights().size() > 0)
		{
		
			uint pointLightCount = 0;
			uint directionalLightCount = 0;
			uint spotLightCount = 0;
			for(size_t i = 0 ; i < params.getLights().size() ; i++)
			{
				Light * curLight = params.getLights()[i];
				String prefix;

				switch (curLight->getType())
				{
				case Light::LT_POINT:
					prefix = "PointLight" + StringConverter::toString(pointLightCount) + "_";
					pointLightCount++;
					break;
				case Light::LT_DIRECTIONAL:
					prefix = "DirectionalLight" + StringConverter::toString(directionalLightCount) + "_";
					directionalLightCount++;
					break;
				case Light::LT_SPOTLIGHT:
					prefix = "SpotLight" + StringConverter::toString(spotLightCount) + "_";
					spotLightCount++;
					break;
				} 

				_setProgramColorParameter(GPT_VERTEX_PROGRAM, prefix + "Ambient", ColourValue::Black);
				_setProgramColorParameter(GPT_VERTEX_PROGRAM, prefix + "Diffuse", curLight->getDiffuseColour());
				_setProgramColorParameter(GPT_VERTEX_PROGRAM, prefix + "Specular", curLight->getSpecularColour());		

				switch (curLight->getType())
				{
				case Light::LT_POINT:
					{
						_setProgramVector3Parameter(GPT_VERTEX_PROGRAM, prefix + "Position", curLight->getPosition());
						_setProgramFloatParameter(GPT_VERTEX_PROGRAM, prefix + "Range", curLight->getAttenuationRange());

						Vector3 attenuation;
						attenuation[0] = curLight->getAttenuationConstant();
						attenuation[1] = curLight->getAttenuationLinear();
						attenuation[2] = curLight->getAttenuationQuadric();
						_setProgramVector3Parameter(GPT_VERTEX_PROGRAM, prefix + "Attenuation", attenuation);
					}
					break;
				case Light::LT_DIRECTIONAL:
					_setProgramVector3Parameter(GPT_VERTEX_PROGRAM, prefix + "Direction", curLight->getDirection());

					break;
				case Light::LT_SPOTLIGHT:
					{

						_setProgramVector3Parameter(GPT_VERTEX_PROGRAM, prefix + "Direction", curLight->getDirection());
						_setProgramVector3Parameter(GPT_VERTEX_PROGRAM, prefix + "Position", curLight->getPosition());

						Vector3 attenuation;
						attenuation[0] = curLight->getAttenuationConstant();
						attenuation[1] = curLight->getAttenuationLinear();
						attenuation[2] = curLight->getAttenuationQuadric();
						_setProgramVector3Parameter(GPT_VERTEX_PROGRAM, prefix + "Attenuation", attenuation);

						Vector3 spot;
						spot[0] = curLight->getSpotlightInnerAngle().valueRadians() ;
						spot[1] = curLight->getSpotlightOuterAngle().valueRadians();
						spot[2] = curLight->getSpotlightFalloff();
						_setProgramVector3Parameter(GPT_VERTEX_PROGRAM, prefix + "Spot", spot);					
					}
					break;
				} // end of - switch (curLight->getType())
			} // end of - for(size_t i = 0 ; i < params.getLights().size() ; i++) 
		} // end of -  if (params.getLightingEnabled())





		switch (params.getFogMode())
		{
		case FOG_NONE:
			break;
		case FOG_EXP:
		case FOG_EXP2:
			_setProgramFloatParameter(GPT_VERTEX_PROGRAM, "FogDensity", params.getFogDensitiy());
			break;
		case FOG_LINEAR:
			_setProgramFloatParameter(GPT_VERTEX_PROGRAM, "FogStart", params.getFogStart());
			_setProgramFloatParameter(GPT_VERTEX_PROGRAM, "FogEnd", params.getFogEnd());
			break;
		}

		if (params.getFogMode() != FOG_NONE)
		{
			_setProgramColorParameter(GPT_FRAGMENT_PROGRAM, "FogColor", params.getFogColour());
		}


		for(size_t i = 0 ; i < params.getTextureMatrices().size() && i < mFixedFuncState.getTextureLayerStateList().size(); i++)
		{
			if (params.isTextureStageEnabled(i))
			{
				if (params.isTextureStageEnabled(i))
				{
					_setProgramMatrix4Parameter(GPT_VERTEX_PROGRAM, "TextureMatrix" + StringConverter::toString(i), params.getTextureMatrices()[i]);
				}
			}
		}



	}
Example #26
0
int StructureManager::getStructureFootprint(SharedObjectTemplate* objectTemplate, int angle, float& l0, float& w0, float& l1, float& w1) {
	SharedStructureObjectTemplate* serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(objectTemplate);

	if (serverTemplate == NULL)
		return 1;

	StructureFootprint* structureFootprint = serverTemplate->getStructureFootprint();
	//float l = 5; //Along the x axis.
	//float w = 5; //Along the y axis.

	if (structureFootprint != NULL) {
		//if (structureFootprint->getRowSize() > structureFootprint->getColSize())
		//	angle = angle + 180;

		float centerX = (structureFootprint->getCenterX() * 8) + 4;
		float centerY = (structureFootprint->getCenterY() * 8) + 4;

		//info ("centerX:" + String::valueOf(centerX) + " centerY:" + String::valueOf(centerY), true);

		float topLeftX = -centerX;
		float topLeftY = (structureFootprint->getRowSize() * 8 ) - centerY;

		float bottomRightX = (8 * structureFootprint->getColSize() - centerX);
		float bottomRightY = -centerY;

		w0 = MIN(topLeftX, bottomRightX);
		l0 = MIN(topLeftY, bottomRightY);

		w1 = MAX(topLeftX, bottomRightX);
		l1 = MAX(topLeftY, bottomRightY);

		Matrix4 translationMatrix;
		translationMatrix.setTranslation(0, 0, 0);

		float rad = (float)(angle) * Math::DEG2RAD;

		float cosRad = cos(rad);
		float sinRad = sin(rad);

		Matrix3 rot;
		rot[0][0] = cosRad;
		rot[0][2] = -sinRad;
		rot[1][1] = 1;
		rot[2][0] = sinRad;
		rot[2][2] = cosRad;

		Matrix4 rotateMatrix;
		rotateMatrix.setRotationMatrix(rot);

		Matrix4 moveAndRotate = (translationMatrix * rotateMatrix);

		Vector3 pointBottom(w0, 0, l0);
		Vector3 pointTop(w1, 0, l1);

		Vector3 resultBottom = pointBottom * moveAndRotate;
		Vector3 resultTop = pointTop * moveAndRotate;

		w0 = MIN(resultBottom.getX(), resultTop.getX());
		l0 = MIN(resultBottom.getZ(), resultTop.getZ());

		w1 = MAX(resultTop.getX(), resultBottom.getX());
		l1 = MAX(resultTop.getZ(), resultBottom.getZ());

		//info("objectTemplate:" + objectTemplate->getFullTemplateString() + " :" + structureFootprint->toString(), true);
		//info("angle:" + String::valueOf(angle) + " w0:" + String::valueOf(w0) + " l0:" + String::valueOf(l0) + " w1:" + String::valueOf(w1) + " l1:" + String::valueOf(l1), true);
	}

	return 0;
}
	void sgRenderEffect::setUniformObject( sg_render::CurrentRenderParam *param, sgSceneObject *object )
	{
		if(!param || !object)
			return ;
        
        // set model matrix
        Matrix4 modelMatrix = object->getFullTransform().transpose();
        Matrix4 mvMatrix = modelMatrix * param->view_matrix;
        Matrix4 mvpMatrix = modelMatrix * param->vp_matrix;
        param->current_gpu_program->setParameter(ModelMatrix, (1<<1)|0, modelMatrix.arr());
        param->current_gpu_program->setParameter(MVMatrix, (1<<1)|0, mvMatrix.arr());
        param->current_gpu_program->setParameter(MVPMatrix, (1<<1)|0, mvpMatrix.arr());
        
        // normal matrix
        Matrix3 normalMat3;
        object->getFullTransform().extract3x3Matrix(normalMat3);
        normalMat3 = normalMat3.inverse().transpose();
        Matrix4 normalMat(normalMat3);
        normalMat = normalMat.transpose();
        Matrix4 normalMVMatrix = normalMat * param->view_matrix;
        param->current_gpu_program->setParameter(NormalMatrix, (1<<1)|0, normalMat.arr());
        param->current_gpu_program->setParameter(NormalMVMatrix, (1<<1)|0, normalMVMatrix.arr());

		sgRenderStateComponent *renderState = (sgRenderStateComponent*)(object->getComponent(sgRenderStateComponent::GetClassTypeName()));
		sgMaterial *material = NULL;
		if(renderState != NULL)
		{
			material = renderState->getMaterial();
		}
		if(material != NULL)
		{
			param->current_gpu_program->setParameter(Material_Ambient, 1, material->ambientColor().toGLColor().data());
			param->current_gpu_program->setParameter(Material_Diffuse, 1, material->diffuseColor().toGLColor().data());
			param->current_gpu_program->setParameter(Material_Specular, 1, material->specularColor().toGLColor().data());
			param->current_gpu_program->setParameter(Material_Emission, 1, material->emissionColor().toGLColor().data());
			
			Real shininess = material->shininess();
			param->current_gpu_program->setParameter(Material_Shininess, 1, &shininess);

			Real specularAmount = material->specularAmount();
			param->current_gpu_program->setParameter(Material_SpecularAmount, 1, &specularAmount);

			Real reflectFraction = material->reflectFraction();
			param->current_gpu_program->setParameter(Material_ReflectFraction, 1, &reflectFraction);
		}
        // texture
        int textureEnabled = 0;
        param->textures.clear();
        param->current_gpu_program->setParameter(Texture0_Enabled, 1, &textureEnabled);
        param->current_gpu_program->setParameter(Texture1_Enabled, 1, &textureEnabled);
        param->current_gpu_program->setParameter(Texture2_Enabled, 1, &textureEnabled);
        param->current_gpu_program->setParameter(Texture3_Enabled, 1, &textureEnabled);
        
        if(renderState != NULL)
        {
            textureEnabled = 1;
            size_t texture_num = sgMin(renderState->getTextureNum(), (size_t)Texture_Max);
            for(size_t i=0; i<texture_num; ++i)
            {
                sgTexture *texture = renderState->getTexture(i);
                if(texture == NULL || !(texture->isActive()) )
                    continue;
                
                param->textures.push_back(texture->getTextureId());
                
                if(i == 0)
                {
                    param->current_gpu_program->setParameter(Texture0, 1, &i);
                    param->current_gpu_program->setParameter(Texture0_Enabled, 1, &textureEnabled);
                }
                else if(i == 1)
                {
                    param->current_gpu_program->setParameter(Texture1, 1, &i);
                    param->current_gpu_program->setParameter(Texture1_Enabled, 1, &textureEnabled);
                }
                else if(i == 2)
                {
                    param->current_gpu_program->setParameter(Texture2, 1, &i);
                    param->current_gpu_program->setParameter(Texture2_Enabled, 1, &textureEnabled);
                }
                else if(i == 3)
                {
                    param->current_gpu_program->setParameter(Texture3, 1, &i);
                    param->current_gpu_program->setParameter(Texture3_Enabled, 1, &textureEnabled);
                }
            }
        }
        

		// uniform user defined
		setUniformObjectExtra(param, object);
	}
Example #28
0
void Lighting::SetWVP(const Matrix4& WVP)
{
	glUniformMatrix4fv(m_WVPLocation, 1, GL_FALSE, (const GLfloat*)WVP.Begin());
}
Example #29
0
void OgreNewtonMesh::ParseEntity (MeshPtr mesh, const Matrix4& matrix)
{
	//find number of sub-meshes
	unsigned short sub = mesh->getNumSubMeshes();

	for (unsigned short cs = 0; cs < sub; cs++) {

		SubMesh* const sub_mesh = mesh->getSubMesh(cs);

		//vertex data!
		VertexData* v_data;

		if (sub_mesh->useSharedVertices) {
			v_data = mesh->sharedVertexData;
		} else {
			v_data = sub_mesh->vertexData;
		}

		//let's find more information about the Vertices...
		VertexDeclaration* const v_decl = v_data->vertexDeclaration;

		const VertexElement* const vertexElem = v_decl->findElementBySemantic(VES_POSITION);
		HardwareVertexBufferSharedPtr vertexPtr = v_data->vertexBufferBinding->getBuffer(vertexElem->getSource());
		dNewtonScopeBuffer<Vector3> points(vertexPtr->getNumVertices());
		{
			int size = vertexPtr->getVertexSize();
			int offset = vertexElem->getOffset() / sizeof (float);
			unsigned char* const ptr = static_cast<unsigned char*> (vertexPtr->lock(HardwareBuffer::HBL_READ_ONLY));
			for (int i = 0; i < points.GetElementsCount(); i ++) {
				float* data;
				vertexElem->baseVertexPointerToElement(ptr + i * size, &data);
				points[i] = matrix.transformAffine (Vector3 (data[offset + 0], data[offset + 1], data[offset + 2]));
			}
			vertexPtr->unlock();
		}

		dNewtonScopeBuffer<Vector3> normals;
		const VertexElement* const normalElem = v_decl->findElementBySemantic(VES_NORMAL);
		if (normalElem) {
			HardwareVertexBufferSharedPtr normalPtr = v_data->vertexBufferBinding->getBuffer(normalElem->getSource());
			normals.Init (normalPtr->getNumVertices());

			int size = normalPtr->getVertexSize();
			int offset = vertexElem->getOffset() / sizeof (float);
			unsigned char* const ptr = static_cast<unsigned char*> (normalPtr->lock(HardwareBuffer::HBL_READ_ONLY));
			for (int i = 0; i < normals.GetElementsCount(); i ++) {
				float* data;
				vertexElem->baseVertexPointerToElement(ptr + i * size, &data);
				normals[i] = matrix * Vector3 (data[offset + 0], data[offset + 1], data[offset + 2]);
				normals[i] = normals[i].normalise();
			}
			normalPtr->unlock();
		}


		dNewtonScopeBuffer<Vector3> uvs;
		const VertexElement* const uvElem = v_decl->findElementBySemantic(VES_TEXTURE_COORDINATES);
		if (uvElem) {
			HardwareVertexBufferSharedPtr uvPtr = v_data->vertexBufferBinding->getBuffer(uvElem->getSource());
			uvs.Init (uvPtr->getNumVertices());
		
			int size = uvPtr->getVertexSize();
			int offset = vertexElem->getOffset() / sizeof (float);
			unsigned char* const ptr = static_cast<unsigned char*> (uvPtr->lock(HardwareBuffer::HBL_READ_ONLY));
			for (int i = 0; i < uvs.GetElementsCount(); i ++) {
				float* data;
				uvElem->baseVertexPointerToElement(ptr + i * size, &data);
				uvs[i] = Vector3 (data[offset + 0], data[offset + 1], 0.0f);
			}
			uvPtr->unlock();
		}

		//now find more about the index!!
		IndexData* const i_data = sub_mesh->indexData;
		size_t index_count = i_data->indexCount;
		size_t poly_count = index_count / 3;

		// get pointer!
		HardwareIndexBufferSharedPtr i_sptr = i_data->indexBuffer;

		// 16 or 32 bit indices?
		bool uses32bit = (i_sptr->getType()	== HardwareIndexBuffer::IT_32BIT);
		unsigned long* i_Longptr = NULL;
		unsigned short* i_Shortptr = NULL;

		if (uses32bit) {
			i_Longptr = static_cast<unsigned long*> (i_sptr->lock(HardwareBuffer::HBL_READ_ONLY));
		} else {
			i_Shortptr = static_cast<unsigned short*> (i_sptr->lock(HardwareBuffer::HBL_READ_ONLY));
		}

		//now loop through the indices, getting polygon info!
		int i_offset = 0;

		Real poly_verts[3][12];
		memset (poly_verts, 0, sizeof (poly_verts));
		for (size_t i = 0; i < poly_count; i++)	{
			for (int j = 0; j < 3; j++) {
				// index to first vertex!
				int idx = uses32bit ? i_Longptr[i_offset + j] : i_Shortptr[i_offset + j]; 

				poly_verts[j][0] = points[idx].x;
				poly_verts[j][1] = points[idx].y;
				poly_verts[j][2] = points[idx].z;
				poly_verts[j][3] = 0.0f;

				if (normals.GetElementsCount()) {
					poly_verts[j][4] = normals[idx].x;
					poly_verts[j][5] = normals[idx].y;
					poly_verts[j][6] = normals[idx].z;
				}

				if (uvs.GetElementsCount()) {
					poly_verts[j][7] = uvs[idx].x;
					poly_verts[j][8] = uvs[idx].y;
				}
			}
			AddFace(3, &poly_verts[0][0], 12 * sizeof (Real), cs);
			i_offset += 3;
		}
		i_sptr->unlock();
	}
}
Example #30
0
void FluidTestScene::Tap3D(const grinliz::Vector2F& view, const grinliz::Ray& world)
{
	Vector3F at = { 0, 0, 0 };
	float t = 0;
	int result = IntersectRayAAPlane(world.origin, world.direction, 1, 0, &at, &t);
	if (result == INTERSECT) {
		Vector2I pos2i = ToWorld2I(at);
		Vector2I sector = { 0, 0 };
		CircuitSim* circuitSim = context.physicsSims->GetCircuitSim(sector);

		if (context.worldMap->Bounds().Contains(pos2i)) {

			bool trigger = false;
			if (!buildButton[BUTTON_DELETE].Down() && !buildButton[BUTTON_ROTATE].Down()) {
				Chit* building = context.chitBag->QueryPorch(pos2i);
				if (!building) {
					building = context.chitBag->QueryBuilding(IString(), pos2i, 0);
				}
				if (building) {
					if (building->GetItem()->IName() == ISC::detector) {
						circuitSim->TriggerDetector(pos2i);
						trigger = true;
					}
					else if (building->GetItem()->IName() == ISC::switchOn 
							 || building->GetItem()->IName() == ISC::switchOff) 
					{
						circuitSim->TriggerSwitch(pos2i);
						trigger = true;
					}
				}
			}

			int id = -1;
			if (!trigger) {
				for (int i = 0; i < NUM_BUTTONS; ++i) {
					if (buildButton[i].Down()) {
						id = i;
						break;
					}
				}
			}
			if (id >= 0) {
				Chit* chit = 0;
				switch (id) {
					case BUTTON_ROCK0:
					case BUTTON_ROCK1:
					case BUTTON_ROCK2:
					case BUTTON_ROCK3:
					context.worldMap->SetRock(pos2i.x, pos2i.y, id - BUTTON_ROCK0, false, WorldGrid::ROCK);
					break;

					case BUTTON_SWITCH_ON:
					chit = context.chitBag->NewBuilding(pos2i, "switchOn", TEAM_HOUSE);
					break;

					case BUTTON_SWITCH_OFF:
					chit = context.chitBag->NewBuilding(pos2i, "switchOff", TEAM_HOUSE);
					break;

					case BUTTON_TEMPLE:
					chit = context.chitBag->NewBuilding(pos2i, "temple", TEAM_HOUSE);
					break;

					case BUTTON_GATE:
					chit = context.chitBag->NewBuilding(pos2i, "gate", TEAM_HOUSE);
					break;

					case BUTTON_TIMED_GATE:
					chit = context.chitBag->NewBuilding(pos2i, "timedGate", TEAM_HOUSE);
					break;

					case BUTTON_DETECTOR:
					chit = context.chitBag->NewBuilding(pos2i, "detector", TEAM_HOUSE);
					break;

					case BUTTON_TURRET:
					chit = context.chitBag->NewBuilding(pos2i, "turret", TEAM_HOUSE);
					break;

					case BUTTON_DELETE:
					{
						Chit* building = context.chitBag->QueryBuilding(IString(), pos2i, 0);
						if (building) {
							building->QueueDelete();
						}
					}
					break;

					case BUTTON_ROTATE:
					{
						Chit* building = context.chitBag->QueryBuilding(IString(), pos2i, 0);
						if (building) {
							Matrix4 m;
							building->Rotation().ToMatrix(&m);
							float r = m.CalcRotationAroundAxis(1);
							r = NormalizeAngleDegrees(r + 90.0f);
							building->SetRotation(Quaternion::MakeYRotation(r));
						}

					}
					break;
				}
				if (chit) {
					MapSpatialComponent* msc = GET_SUB_COMPONENT(chit, SpatialComponent, MapSpatialComponent);
					if (msc) msc->SetNeedsCorePower(false);
				}
			}
		}
	}
}