예제 #1
0
void Camera::backward(void)
{
	float tempForward[3], tempUp[3], tempRight[3];
	transformWithMouse(mouseLeftRight, mouseUpDown, tempForward, tempUp, tempRight);
	float vec[3];
	vectorCopy(vec, tempForward);
	vectorMul(vec, -cameraSpeed);
	vectorAdd(position, vec);
}
예제 #2
0
VECTOR3 hex_xyCoord2Space (signed int x, signed int y)
{
	VECTOR3
		p,
		q;
	p = hex_tileDistance (x, 0);
	q = hex_tileDistance (y, 1);
	q = vectorAdd (&p, &q);
	return q;
}
예제 #3
0
파일: object.cpp 프로젝트: onlyuser/Legacy
void object::goFwd(float dist)
{
	float *tempA;

	tempA = new float[3];
	vectorFromAngle(tempA, mAngle);
	vectorScale(tempA, tempA, dist);
	vectorAdd(mOrigin, mOrigin, tempA);
	delete []tempA;
}
예제 #4
0
void SetupCamera(void)
{
	vec3_t vLookat;
	
	vectorAdd(camera.position,camera.forward,vLookat);
	
	gluLookAt(camera.position, vLookat, camera.up, modelViewMatrix);
	
	gluPerspective(camera.fov, camera.aspect,camera.zNear, camera.zFar, projectionMatrix);
	
}
예제 #5
0
void addTypedName( pANTLR3_VECTOR       v,
                   ANTLR3_UINT32        type,
                   pANTLR3_UINT8        name )
{
    struct function_argument *  item = malloc( sizeof( struct function_argument ) );
    item->name = name;
    item->type = type;
    vectorAdd( v, item, free );

    return;
}
예제 #6
0
void SetupCameraF(void)
{
	vec3_t vLookat;
	
	vectorAdd(camera.position,camera.forward,vLookat);
	
	gluLookAt(camera.position, vLookat, camera.up, modelViewMatrix);
	
	//printf("t=%d, up=[%.2f,%.2f,%.2f]\n",simulationTime,camera.up[X],camera.up[Y],camera.up[Z]);
	
	glLoadMatrixf(modelViewMatrix);
}
예제 #7
0
파일: texture.c 프로젝트: xaphiriron/beyond
void textureDrawLine (TEXTURE t, VECTOR3 start, VECTOR3 end)
{
	VECTOR3
		diff = vectorSubtract (&end, &start),
		norm = vectorNormalize (&diff),
		current = start;
	/* i'm using i/max as a counter since due to floating point rounding error
	 * it's not feasible to use vector_cmp (&current, &end), which is the only
	 * other way i can think of to check for when the line is actually done
	 *  - xph 2011 08 27
	 */
	int
		i = 0,
		max = vectorMagnitude (&diff) + 1;
	/* if start is out of bounds skip ahead until it isn't (if it isn't), and
	 * if it goes out of bounds again then it's not coming back. this is
	 * important if start is out of bounds but end isn't (or if they're both
	 * oob but they cross the image edge at some point); the start of the line
	 * won't be drawn but stopping after the first oob coordiante would be
	 * wrong
	 * (there's a better way to do this: if either value is oob, calculate the
	 * intersection of the line w/ the screen edges and jump to that point
	 * without needing to loop)
	 *  - xph 2011 08 27
	 */
	while (textureOOB (t, current) && i < max)
	{
		current = vectorAdd (&current, &norm);
		i++;
	}
	while (i < max)
	{
		if (textureOOB (t, current))
			break;
		textureDrawPixel (t, current);
		current = vectorAdd (&current, &norm);
		i++;
	}
}
예제 #8
0
VECTOR3 position_renderCoords (Entity e)
{
	VECTOR3
		platter,
		total;
	POSITION
		position = component_getData (entity_getAs (e, "position"));
	if (!position->position)
		return vectorCreate (0.0, 0.0, 0.0);
	platter = renderOriginDistance (hexPos_platter (position->position, 1));
	total = vectorAdd (&platter, &position->pos);
	return total;
}
예제 #9
0
// Calculate the refraction when vector n1 goes from a material with refractive
// index mu1 into one with refractive index mu2, via a surface with normal s
// (s goes in the direction in to the new material, so may actually be the
// inverse of the collision-object surface normal depending on if the ray is
// entering or exiting the object)
struct Vector3 vectorRefract(struct Vector3 n1, 
                    struct Vector3 s, int mu1, int mu2)
{
    int n1DotS      = vectorUnitDotProduct(n1,s);
    struct Vector3 firstTerm   = vectorScalarMultiply(s,n1DotS);
    int sqrtTerm    = fp_sqrt(  (fp_mult(mu2,mu2)) - \
                                (fp_mult(mu1,mu1)) + \
                                (fp_mult(n1DotS,n1DotS)) );
    struct Vector3 result = \
        vectorAdd( vectorSubtract(n1, firstTerm),
            vectorScalarMultiply(s, sqrtTerm) );

    return result;  
}
예제 #10
0
void OBJ_GenerateLightingInfo(obj_t* obj)
{
	vec3_t v1,v2 ;
	int i;
	vec2_t st1,st2;
	float coef;
	vec3_t currentTangent;
	vec3_t currentNormal;
	vec3_t* tangents;
	vec3_t* normals;
	
	tangents = (vec3_t*)calloc(obj->num_vertices, sizeof(vec3_t));
	normals  = (vec3_t*)calloc(obj->num_vertices, sizeof(vec3_t));
	

	
	//Accumulate tangents & normals
	for(i=0;i<obj->num_indices/3;i++)
	{
		vectorSubtract(obj->vertices[obj->indices[i*3+2]].position , obj->vertices[obj->indices[i*3]].position, v1);
		vectorSubtract(obj->vertices[obj->indices[i*3+1]].position , obj->vertices[obj->indices[i*3]].position, v2);
		
		vector2Subtract(obj->vertices[obj->indices[i*3+2]].textCoo,obj->vertices[obj->indices[i*3]].textCoo,st1);
		vector2Subtract(obj->vertices[obj->indices[i*3+1]].textCoo,obj->vertices[obj->indices[i*3]].textCoo,st2);
	
		//Normal part
		vectorCrossProduct(v2, v1, currentNormal);
		vectorAdd(normals[obj->indices[i*3+0]],currentNormal,normals[obj->indices[i*3+0]]);
		vectorAdd(normals[obj->indices[i*3+1]],currentNormal,normals[obj->indices[i*3+1]]);
		vectorAdd(normals[obj->indices[i*3+2]],currentNormal,normals[obj->indices[i*3+2]]);
		
		//Tangent part
		coef = 1/ (st1[0] * st2[1] - st2[0] * st1[1]);
		
		currentTangent[0] = coef * (v1[0] * st2[1]  + v2[0] * -st1[1]);
		currentTangent[1] = coef * (v1[1] * st2[1]  + v2[1] * -st1[1]);
		currentTangent[2] = coef * (v1[2] * st2[1]  + v2[2] * -st1[1]);
		
		vectorAdd(tangents[obj->indices[i*3+0]],currentTangent,tangents[obj->indices[i*3+0]]);
		vectorAdd(tangents[obj->indices[i*3+1]],currentTangent,tangents[obj->indices[i*3+1]]);
		vectorAdd(tangents[obj->indices[i*3+2]],currentTangent,tangents[obj->indices[i*3+2]]);
	}
	
	//Vector Normalize + Normalize
	for(i=0;i<obj->num_vertices;i++)
	{
		normalize(tangents[i]);
		vectorScale(tangents[i],DE_SHRT_MAX,obj->vertices[i].tangent);
		
		normalize(normals[i]);
		vectorScale(normals[i],DE_SHRT_MAX,obj->vertices[i].normal);
	}
	
	free(tangents);
	free(normals);
}
예제 #11
0
void updateParticles(PARTICLE * ps, PARTICLE * tmp) {
  int i, j;
  VECTOR accel;
  VECTOR summAccel;
  memcpy(tmp, ps, sizeof(PARTICLE) * PARTICLE_NUMBER);
  for(i = 0; i != PARTICLE_NUMBER; i++) {
    vectorInit(&summAccel, 0, 0);
    for(j = 0; j != PARTICLE_NUMBER; j++) {
      if (i == j) continue;
	    calcInteraction(ps + i, ps + j, &accel);
      vectorAdd(&summAccel, &accel);
    }
    updateParticle(ps + i, tmp + i, &summAccel);
  }
  memcpy(ps, tmp, sizeof(PARTICLE) * PARTICLE_NUMBER);
}
예제 #12
0
long colorAdd(long colorA, long colorB)
{
	long result;
	float *vectA;
	float *vectB;
	float *vectC;

	vectA = vectorFromColor(colorA);
	vectB = vectorFromColor(colorB);
	vectC = vectorAdd(vectA, vectB, 3);
	result = rgb((long) vectC[0], (long) vectC[1], (long) vectC[2]);
	delete []vectA;
	delete []vectB;
	delete []vectC;
	return result;
}
예제 #13
0
void *MagFieldLineSegArray_BACKENDWORKER(void *arg)
{
  WorkerArg Arg;
  int fpFirst,fpLast;
  int fp,seg;
  
  Vector zerovect;
  Vector tmpvectA;
  Vector tmpvectB;

  double percent;
  int percent_denom;
  zerovect.coords[0]=0.0;
  zerovect.coords[1]=0.0;
  zerovect.coords[2]=0.0;
  
  Arg=*((WorkerArg*)(arg));
  fpFirst=Arg.start;
  fpLast=Arg.end;

  for(fp=fpFirst;fp<=fpLast;fp++)
    {
      percent_denom=(fpLast-fpFirst);
      if(percent_denom==0)
	{percent=100.0;}
      else
	{percent=100.0*(fp-fpFirst)/percent_denom;}
      printf("Fieldpoint %d in %d to %d. %g %% complete.\n",fp,fpFirst,fpLast,percent);

      
      tmpvectA=zerovect;
      for(seg=0;seg<Arg.numsegs;seg++)
	{
	  
	    tmpvectB=vectorAdd(tmpvectA,Biot_Savart_SingleLineSeg(Arg.segs[seg],Arg.fieldpoints[fp]));  
	    tmpvectA=tmpvectB;
	
	}
      Arg.Bfield[fp]=tmpvectB;
    }
  return NULL;
}
예제 #14
0
VECTOR3 hex_coord2space (unsigned int r, unsigned int k, unsigned int i)
{
	VECTOR3
		p = vectorCreate (0.0, 0.0, 0.0),
		q;
	if (r == 0)
	{
		return p;
	}
	assert (k < 6);
	assert (i < r);
	p = hex_tileDistance (r, k);
	if (i == 0)
	{
		return p;
	}
	q = hex_tileDistance (i, (k + 2) % 6);
	p = vectorAdd (&p, &q);
	return p;
}
예제 #15
0
파일: vector.c 프로젝트: snyderdan/PyVector
void main() {
	int i;
	int start;
	double c1[3] = {22.5, 12.8, 80.2};
	double c2[3] = {81.0, 5.0, 56.1};
	Vector *a = vectorNew(c1, 3);
	Vector *b = vectorNew(c2, 3);
	start = clock();
	for (i=0; i<100000; i++) {
		vectorAdd(a, b);
		vectorSub(a, b);
		vectorCompare(a, b);
		angle(a, b);
		vectorLength(a);
		vectorLength(b);
		dotProduct(a, b);
		crossProduct(a, b);
	}
	printf("%f ", (float)(clock()-start)/CLOCKS_PER_SEC);
	getchar();
}
예제 #16
0
void movePlayer(movableObject& objPlayer)
{

	if( IsKeyDown(KEY_UP))
	{
		//UP key is pressed
		objPlayer.v2Speed.fY = -1 * g_iPlayerSpeed;
	}
	else if( IsKeyDown(KEY_DOWN) )
	{
		//DOWN key is pressed
		objPlayer.v2Speed.fY =  g_iPlayerSpeed;
	}
	else
	{
		objPlayer.v2Speed.fY = 0;
	}

	objPlayer.v2Position = vectorAdd(objPlayer.v2Position,objPlayer.v2Speed);

}
예제 #17
0
void testVectors(){
    vector<double> test1(10,8.0);
    vector<double> abc(10,7.);
    vector<double> res(10);

    cout<<"vecadd test1+abc "<<endl;
    vectorAdd(&test1,&abc,&res);
    vectorPrint(&res);

    cout<<"vecsub res-abc "<<endl;
    vectorSub(&res,&abc,&res);
    vectorPrint(&res);

    cout<<"vecscalar 3 "<<endl;
    vectorScalar(&res,3.);
    vectorPrint(&res);

     cout<<"vecscalar 3 "<<endl;
    vectorScalar(&res,3.,&test1);
    vectorPrint(&test1);

    cout<<"vecvec test1 abc "<<endl;
    cout<<vectorVector(&test1,&abc)<<endl;
    vector<map< int,double> > testmat(2);//=new vector<map< int,double> >(n);
    for (int i=0;i<2;++i){
        testmat[i];//=new map< int,double> ();
    }

    testmat[0][0]= 1;
    testmat[0][1]= 1;
    testmat[1][0]= 1;
    //testmat[1][1]= 1;

    vector<double> vec(2,8.0);
    vector<double> ret(2);
    matrixVector(&testmat,&vec,&ret);
    vectorPrint(&ret);

}
예제 #18
0
파일: newsupport.c 프로젝트: OpenGelo/iarc
void updateMatrix(int * accel, int * gyro, int* matrix){
	int i;
	int normaccel[3];
	int wAccel[3];
	int orient[3];
	int output[9];

	normalize(accel, normaccel);

	cross(&matrix[6], normaccel, wAccel);
	
	for(i = 0; i < 3; i ++){
		orient[i] = ((gyro[i] * GYROSCALE) + (wAccel[i] * ACCELSCALE))/(DIVFACTOR);
	}

	for(i = 0; i < 3; i ++){
		cross(&matrix[3 * i], orient, &output[i * 3]);
		vectorAdd(&matrix[3 * i], &output[i * 3], &matrix[3 * i]);
	}

	orthoNormalize(matrix);
}
예제 #19
0
Scope *flattenScope(Scope *scope) {
    Scope *destinationScope = newScope(NULL);

    // Traverse every level of scope
    while(scope) {
        Vector *vars = scope->variables;

        for(int i = 0; i < vars->size; i++) {
            ScopeElement *elem = vectorGet(vars, i);
            char *identifier = elem->identifier;

            // If it hasn't already been declared in the flattened scope, "declare it"
            if(inLocalScope(destinationScope, identifier)) {
                error(REDECL_GLOBAL_VAR, identifier);
            } else {
                vectorAdd(destinationScope->variables, elem);
            }
        }

        scope = scope->enclosingScope;
    }

    return destinationScope;
}
// PageRank
float* pageRank(int nodes, float* A, int* IA, int* JA){
 
  // Initialize row_vector to 1/nodes
  float row_vector[nodes];
  for (int i = 0; i < nodes; ++i)
    row_vector[i] = 1/(float)(nodes);  

  // Initialize rank_vector to 0
  float* rank_vector = (float*)malloc(sizeof(float)*nodes);
  for (int j = 0; j < nodes; ++j)
    rank_vector[j] = 0;  


  float error = 10000;
  float threshold = 0.001;

  for ( int idx = 0; error > threshold ; ++idx ){
    float* vector1 = sparseMatrixMul(A, IA, JA, row_vector, nodes);
    float* vector2 = vectorMul(row_vector, P_VALUE, nodes);
    rank_vector = vectorAdd(vector1, vector2, nodes);

    // Error Calculation
    error = 0;
    for ( int i = 0; i < nodes; ++i )
      error += abs(rank_vector[i] - row_vector[i]); 

    memcpy((void*)row_vector, (void*)rank_vector, sizeof(float)*nodes);
  }

  for ( int i = 0; i < nodes; ++i )
    printf("%f ", rank_vector[i] ); 
  
  return rank_vector;


}
예제 #21
0
void vectorAddDouble(vector_t *vec, double value)
{
    value_t node;
    node.numberDouble = value;
    vectorAdd(vec, node, N_DOUBLE);
}
예제 #22
0
void lmHandlerReceiveLargeMessage(NodeManagerInterface nmi, JausMessage message)
{
	LargeMessageList msgList;
	JausMessage tempMessage;
	JausMessage outMessage;
	int i;
	unsigned long sequenceNumber;
	unsigned long index;
	JausUnsignedInteger newDataSize = 0;
	JausUnsignedInteger bufferIndex = 0;
	char address[128] = {0};
	
	switch(message->dataFlag)
	{
		case JAUS_FIRST_DATA_PACKET:
			// Check for valid SeqNumber(0), else Error
			if(message->sequenceNumber) 
			{
				cError("LargeMessageHandler: Received First Data Packet with invalid Sequence Number(%d)\n", message->sequenceNumber);
				jausMessageDestroy(message);
				return;
			}
			
			// Check if LargeMessageList exists (same CC & Source)
			msgList = lmHandlerGetMessageList(nmi->lmh, message);
			if(msgList)
			{
				// Destroy the list and all messages
				vectorRemove(nmi->lmh->messageLists, msgList, (void *)lmHandlerMessageListEqual);
				lmListDestroy(msgList);		
			}

			// create LargeMessageList
			msgList = lmListCreate();
			vectorAdd(nmi->lmh->messageLists, msgList);
				
			// add message to LargeMessageList at first position
			msgList->commandCode = message->commandCode;
			msgList->source->id = message->source->id;
			vectorAdd(msgList->messages, message);
			break;
		
		case JAUS_NORMAL_DATA_PACKET:
			// Check if LargeMessageList exists, error if not
			msgList = lmHandlerGetMessageList(nmi->lmh, message);
			if(msgList)
			{
				// Check if item exists in LargeMessageList with seqNumber
				if(vectorContains(msgList->messages, message, (void *)lmHandlerLargeMessageCheck) != -1)
				{
					cError("LargeMessageHandler: Received duplicate NORMAL_DATA_PACKET\n");
					jausMessageDestroy(message);
				}
				else
				{
					// insert to Vector
					vectorAdd(msgList->messages, message);
				}
			}
			else
			{
				// Destroy Message
				cError("LargeMessageHandler: Received NORMAL_DATA_PACKET (0x%4X) for unknown Large Message Set (never received JAUS_FIRST_DATA_PACKET)\n", message->commandCode);
				jausMessageDestroy(message);
			}
			break;
			
		case JAUS_RETRANSMITTED_DATA_PACKET:
			// Check if LargeMessageList exists, error if not
			msgList = lmHandlerGetMessageList(nmi->lmh, message);
			if(msgList)
			{
				// Check if item exists in LargeMessageList with seqNumber
				if(vectorContains(msgList->messages, message, (void *)lmHandlerLargeMessageCheck) != -1)
				{
					tempMessage = (JausMessage) vectorRemove(msgList->messages, message, (void *)lmHandlerLargeMessageCheck);
					jausMessageDestroy(tempMessage);
				}
				// insert to Vector
				vectorAdd(msgList->messages, message);
			}
			else
			{
				cError("LargeMessageHandler: Received RETRANSMITTED_DATA_PACKET for unknown Large Message Set (never received JAUS_FIRST_DATA_PACKET)\n");
				jausMessageDestroy(message);				
			}
			break;
		
		case JAUS_LAST_DATA_PACKET:
			// Check if LargeMessageList exists, error if not
			msgList = lmHandlerGetMessageList(nmi->lmh, message);
			if(msgList)
			{
				// insert message to end of list
				vectorAdd(msgList->messages, message);

				// Create JausMessage object
				outMessage = jausMessageCreate();

				// Calculate new message size
				newDataSize = 0;
				for(i = 0; i < msgList->messages->elementCount; i++)
				{
					tempMessage = (JausMessage)msgList->messages->elementData[i];
					newDataSize += tempMessage->dataSize;
				}

				// Setup Header and Data Buffer
				outMessage->properties = tempMessage->properties;
				outMessage->commandCode = tempMessage->commandCode;
				outMessage->destination->id = tempMessage->destination->id;
				outMessage->source->id = tempMessage->source->id;
				outMessage->dataControl = tempMessage->dataControl;
				outMessage->sequenceNumber = tempMessage->sequenceNumber;
				outMessage->data = (unsigned char *) malloc(newDataSize);
				
				// Populate new message
				sequenceNumber = 0;
				bufferIndex = 0;
				while(sequenceNumber <= message->sequenceNumber)
				{
					index = 0;
					do
					{
						tempMessage = (JausMessage)msgList->messages->elementData[index];
						index++;
						if(index > msgList->messages->elementCount)
						{
							// Invalid set of messages
							//TODO: Here is when you would request a retransmittal if ACK/NAK is set and ask the sending component to resend some packets
	
							// Received LAST_DATA_PACKET, but do not have proper sequence of messages
							// Destroy the list and all messages
							vectorRemove(nmi->lmh->messageLists, msgList, (void *)lmHandlerMessageListEqual);
							lmListDestroy(msgList);
						
							cError("LargeMessageHandler: Received LAST_DATA_PACKET, but do not have proper sequence of messages\n");						
							jausMessageDestroy(outMessage);
							return;
						}
					}
					while(tempMessage->sequenceNumber != sequenceNumber);
					
					// Move data from tempMessage to outMessage
					memcpy(outMessage->data + bufferIndex, tempMessage->data, tempMessage->dataSize);
					bufferIndex += tempMessage->dataSize;
					sequenceNumber++; // TOM: switched from i++
				}

				// Set DataSize
				// Set proper header flags (dataFlag JAUS_SINGLE_DATA_PACKET)
				outMessage->dataSize = newDataSize;
				outMessage->dataFlag = JAUS_SINGLE_DATA_PACKET;

				if(outMessage->scFlag)
				{
					scManagerReceiveMessage(nmi, outMessage);
				}
				else
				{
					queuePush(nmi->receiveQueue, (void *)outMessage);
				}
				
				// Destroy LargeMessageList
				vectorRemove(nmi->lmh->messageLists, msgList, (void *)lmHandlerMessageListEqual);
				lmListDestroy(msgList);
			}
			else
			{
				cError("LargeMessageHandler: Received LAST_DATA_PACKET for unknown Large Message Set (never received JAUS_FIRST_DATA_PACKET)\n");
				jausMessageDestroy(message);				
			}
			break;
		
		default:
			jausAddressToString(message->source, address);
			cError("lmHandler: Received (%s) with improper dataFlag (%d) from %s\n", jausMessageCommandCodeString(message), message->dataFlag, address);
			jausMessageDestroy(message);
			break;
	}
}
예제 #23
0
//update the ball's position on screen
void updateBallPosition(movableObject &obj)
{
	obj.v2Position = vectorAdd(obj.v2Position, obj.v2Speed);
}
예제 #24
0
bool declareFunction(Scope *scope, Type returnType, char *identifier, Vector *parameters,
        bool declaredExtern, bool isPrototype) {
    ScopeElement *foundVar = findScopeElement(scope, identifier);
    bool validDeclaration = true;

    // Determine if something with that name already exists
    if(foundVar) {
        // If that thing is a function, check some properties
        if(foundVar->elementType == SCOPE_FUNC) {
            ScopeFunction *func = foundVar->function;
            // Determine whether or not a function prototype has been duplicated
            if(isPrototype) {
                error(REDEF_PROTOTYPE, identifier);
                validDeclaration = false;
            }

            // Check if the function's return type has been changed
            if(returnType != func->returnType) {
                error(CHANGE_RET_TYPE, identifier, typeName(func->returnType), typeName(returnType));
                validDeclaration = false;
            }

            // Determine if the function has been implemented or declared as extern
            if(func->implemented) {
                // An already implemented function cannot be reimplemented
                error(REDEF_FUNCTION, identifier);
                validDeclaration = false;
            } else if(func->declaredExtern) {
                // An extern function cannot be declared in the same file
                error(REDEF_EXTERN, identifier);
                validDeclaration = false;
            } else {
                // Ensure that the prototype and declaration match
                Vector *expectedParams = func->parameters;
                int declared = parameters->size;
                int expected = expectedParams->size;
                int min = declared < expected ? declared : expected;

                // Check the types of each declared and expected parameter
                for(int i = 0; i < min; i++) {
                    FunctionParameter *declaredParam = vectorGet(parameters, i);
                    FunctionParameter *expectedParam = vectorGet(expectedParams, i);

                    Type declaredType = declaredParam->type;
                    Type expectedType = expectedParam->type;
                    if(! typesCompatible(declaredType, expectedType)) {
                        error(ARG_TYPE_CHANGE, i, identifier, typeName(declaredType),
                                typeName(expectedType));
                        validDeclaration = false;
                    }
                }

                if(declared == 0 && expected != 0) {
                    error(REDEF_WITHOUT_ARGS, identifier);
                    validDeclaration = false;
                } else if(declared != 0 && expected == 0) {
                    error(REDEF_WITH_ARGS, identifier);
                    validDeclaration = false;
                } else if(declared != expected) {
                    error(ARG_NUM_CHANGE, identifier, expected, declared);
                    validDeclaration = false;
                }

                func->implemented = true;
            }
        } else {
            // If it's a variable, then a variable can't be defined as a scope
            error(REDEF_VAR_AS_FUNC, identifier);
            validDeclaration = false;
        }
    } else {
        // Add the function to scope
        debug(E_DEBUG, "Declaring function %s of type %s on line %d.\n", identifier,
                typeName(returnType), mylineno);
        ScopeFunction *scopeFunction = malloc(sizeof(ScopeFunction));
        scopeFunction->returnType = returnType;
        scopeFunction->parameters = parameters;
        scopeFunction->implemented = false;
        scopeFunction->declaredExtern = declaredExtern;

        ScopeElement *elem = malloc(sizeof(ScopeElement));
        elem->identifier = identifier;

        // Don't override the function name "main" since it is necessary for execution entry
        if(strcmp(identifier, "main") == 0) {
            elem->protectedIdentifier = identifier;
        } else {
            int newIdentifierLength = strlen(identifier) + 2;
            char *protectedIdentifier = malloc(newIdentifierLength);
            snprintf(protectedIdentifier, newIdentifierLength, "_%s", identifier);
            elem->protectedIdentifier = protectedIdentifier;
        }

        elem->elementType = SCOPE_FUNC;
        elem->function = scopeFunction;
        vectorAdd(scope->variables, elem);

        return true;
    }

    return validDeclaration;
}
예제 #25
0
void MD5_GenerateLightingInfo (md5_mesh_t* mesh)
{
	int verticesCounter;
	int weightCounter;
	//User for tangent space generation
	vec3_t v1,v2,normal;
	
	vec3_t* normalAccumulator;
	vec3_t* normalWeightAccumulator;

	vec3_t tangent;
	float coef;
	vec3_t jointSpaceTangent;
	vec2_t st1,st2;
	vec3_t* tangentAccumulator;
	vec3_t* tangentWeightAccumulator;

	
	vertex_t* currentVertex = NULL;
	md5_vertex_t* md5Vertex;
	int facesCounter;
	
	md5_weight_t* weight;
	md5_bone_t* bone;
	md5_triangle_t* currentFace;
	
	vec3_t jointSpaceNormal;
	
	normalAccumulator		=	calloc(mesh->numVertices, sizeof(vec3_t));
	normalWeightAccumulator =	calloc(mesh->numWeights, sizeof(vec3_t));

	tangentAccumulator		=	calloc(mesh->numVertices, sizeof(vec3_t));
	tangentWeightAccumulator=	calloc(mesh->numWeights, sizeof(vec3_t));

	
	//printf("\nGenerating normal and tangents.\n");

	
	//Generate the normal and tangent per face
	currentFace = mesh->triangles;
	for(facesCounter = 0; facesCounter < mesh->numTriangles ; facesCounter++,currentFace++)
	{
		
		// Normal part
		vectorSubtract(mesh->vertexArray[currentFace->index[2]].pos , mesh->vertexArray[currentFace->index[0]].pos, v1);
		vectorSubtract(mesh->vertexArray[currentFace->index[1]].pos , mesh->vertexArray[currentFace->index[0]].pos, v2);
		vectorCrossProduct(v2,v1,normal);
		
		normalize(normal);
		
		vectorAdd(normalAccumulator[currentFace->index[0]],normal,normalAccumulator[currentFace->index[0]]);
		vectorAdd(normalAccumulator[currentFace->index[1]],normal,normalAccumulator[currentFace->index[1]]);
		vectorAdd(normalAccumulator[currentFace->index[2]],normal,normalAccumulator[currentFace->index[2]]);
		
		
		// The following part is from "Mathematic for 3D programming" by Eric Lengyel
		// Tangent part
		


		vector2Subtract(mesh->vertexArray[currentFace->index[2]].text,mesh->vertexArray[currentFace->index[0]].text,st1);
		vector2Subtract(mesh->vertexArray[currentFace->index[1]].text,mesh->vertexArray[currentFace->index[0]].text,st2);
		
		vector2Scale(st1,1/(float)32767,st1);
		vector2Scale(st2,1/(float)32767,st2);
		
		if (st1[0] == 0.0f && st2[0] == 0.0f)
		{
			st1[0] = 0.1f ; 
			st2[0] = 0.1f;
		}
		
		if (st1[1] == 0.0f && st2[1] == 0.0f)
		{
			st1[1] = 0.1f ;
			st2[1] = 0.1f;
		}
		
		
		coef = 1/ (st1[0] * st2[1] - st2[0] * st1[1]);
		
		
		
		tangent[0] = coef * (v1[0] * st2[1]  + v2[0] * -st1[1]);
		tangent[1] = coef * (v1[1] * st2[1]  + v2[1] * -st1[1]);
		tangent[2] = coef * (v1[2] * st2[1]  + v2[2] * -st1[1]);
		
		normalize(tangent);		
		
		
		vectorAdd(tangentAccumulator[currentFace->index[0]],tangent,tangentAccumulator[currentFace->index[0]]);
		vectorAdd(tangentAccumulator[currentFace->index[1]],tangent,tangentAccumulator[currentFace->index[1]]);
		vectorAdd(tangentAccumulator[currentFace->index[2]],tangent,tangentAccumulator[currentFace->index[2]]);
		
		
		
	}
	
	//Normalize accumulated normal and tangent
	for(verticesCounter=0 ; verticesCounter < mesh->numVertices ; verticesCounter++,currentVertex++)
	{
		
		
		normalize(normalAccumulator[verticesCounter]);
//		printf("normalized accumulated normal [%d][%.2f,%.2f,%.2f]\n",verticesCounter,normalAccumulator[verticesCounter][0],normalAccumulator[verticesCounter][1],normalAccumulator[verticesCounter][2]);
		normalize(tangentAccumulator[verticesCounter]);
//		printf("normalized accumulated tangent [%d][%.2f,%.2f,%.2f]\n",verticesCounter,tangentAccumulator[verticesCounter][0],tangentAccumulator[verticesCounter][1],tangentAccumulator[verticesCounter][2]);
	}
	
	//Now we have all the normal for this model, but need to transform them in bone space for re-usage
	// Translating the normal orientation from object to joint space and Store normals inside weights, 
	md5Vertex = mesh->vertices;
	currentVertex = mesh->vertexArray;
	for(verticesCounter=0 ; verticesCounter < mesh->numVertices ; verticesCounter++,md5Vertex++)
	{
		for (weightCounter = 0; weightCounter < md5Vertex->count; weightCounter++)
		{
			weight = &mesh->weights[md5Vertex->start + weightCounter];
			bone  = &mesh->bones[weight->boneId];
			
			multiplyByInvertQuaternion(normalAccumulator[verticesCounter],bone->orientation,jointSpaceNormal);
			vectorAdd(normalWeightAccumulator[md5Vertex->start + weightCounter],jointSpaceNormal,normalWeightAccumulator[md5Vertex->start + weightCounter]);
					
			multiplyByInvertQuaternion(tangentAccumulator[verticesCounter],bone->orientation,jointSpaceTangent);
			vectorAdd(tangentWeightAccumulator[md5Vertex->start + weightCounter],jointSpaceTangent,tangentWeightAccumulator[md5Vertex->start + weightCounter]);			
		}
		
	}
	
	weight = mesh->weights;
	for (weightCounter = 0; weightCounter < mesh->numWeights; weightCounter++,weight++)
	{
		normalize(normalWeightAccumulator[weightCounter]);
		vectorScale(normalWeightAccumulator[weightCounter],32767,weight->boneSpaceNormal);
		
		normalize(tangentWeightAccumulator[weightCounter]);
		vectorScale(tangentWeightAccumulator[weightCounter],32767,weight->boneSpaceTangent);
			
	}
	
	free(normalAccumulator);
	free(normalWeightAccumulator);

	free(tangentAccumulator);
	free(tangentWeightAccumulator);

}
예제 #26
0
void vectorAddAny(vector_t *vec, void *value)
{
    value_t node;
    node.ptrAny = value;
    vectorAdd(vec, node, P_ANY);
}
예제 #27
0
void vectorAddString(vector_t *vec, char *value)
{
    value_t node;
    node.string = value;
    vectorAdd(vec, node, P_STR);
}
예제 #28
0
void vectorAddLongLong(vector_t *vec, long long value)
{
    value_t node;
    node.numberLong = value;
    vectorAdd(vec, node, N_LONG);
}
예제 #29
0
void vectorAddUnsigned(vector_t *vec, unsigned value)
{
    value_t node;
    node.numberUnsigned = value;
    vectorAdd(vec, node, N_UNSIGNED);
}
예제 #30
0
void vectorAddInt(vector_t *vec, int value)
{
    value_t node;
    node.numberInteger = value;
    vectorAdd(vec, node, N_INT);
}