Beispiel #1
0
void March(GLfloat **mTris, GLfloat **mNorms,Tetra *tetras)
{
	
	cell = realloc(cell, DIM*DIM*DIM*sizeof(Cell));
	mc.pos = SetVector(XMIN, YMIN, ZMIN);
	int i;
	free(*mTris);
	free(*mNorms);
	*mTris = malloc(0);
	*mNorms = malloc(0);
	free(verts);
	verts = malloc(0);
	vertListSize = 0;
	// loop through all cells and calculate number of particles
	for(i = 0; i < DIM*DIM*DIM; i++)
	{ 
		cell[i].nrParts = 0;
		cell[i].state = 0;
		int j;		
		for(j = 0; j < NO_OBJECTS; j++)
		{
			// Check if particle is inside this cell
			//OBS! Will NOT register both cells on cell border
			if(tetras[j].pos.x >= mc.pos.x 
			&& tetras[j].pos.x < (mc.pos.x + cellSize) 
			&& tetras[j].pos.y >= mc.pos.y 
			&& tetras[j].pos.y < (mc.pos.y + cellSize)
			&& tetras[j].pos.z >= mc.pos.z 
			&& tetras[j].pos.z < (mc.pos.z + cellSize))
			{
				// If particle is inside cell add to this cells particle count
				cell[i].nrParts++;
				tetras[j].whichCell = i;	
			}
				
		}
		
		if(cell[i].nrParts >= isolevel)
		{
			// If threshold is reached set state to 1!!!!!!!!!!!	
			cell[i].state = 1;
		}
		/*
		Step through cells using the position and check against the borders.
		When XMAX position is reached, step up in y direction and reset xpos.
		*/
		mc.pos.x += cellSize;
		if(mc.pos.x == XMAX)
                {
			mc.pos.x = XMIN;
			mc.pos.y += cellSize;

			if(mc.pos.y == YMAX)
                        {
				mc.pos.y = YMIN;
				mc.pos.z += cellSize;
			}
		}
	}
	int m, j, x, y, z, Case;
        y=z=0;
        x=-1;
        vec3 edge[12];
        int count = 0;
	float xCell, yCell, zCell;
	for(j=0; j< DIM * DIM * DIM; j++)
        {
                //detta gör vi för att inte alla hörnpunkter ska få värdet 1
                for(m=0; m<8; m++)
                        cubeCorners[m] = 0;
                x++;
                if(x == DIM)
                {
                        y++;
                        x=0;
                }
                if(y == DIM)
                {
                        z++;
                        x=y=0;
                }
                
		// nollställ density
		for(m = 0; m < 24; m++)
			density[m] = 0; 

                //Kolla mot kuber som ligger "vägg i vägg" med vår kub
                // Kolla även denstiy så den får rätt antal partiklar mot varje hörn
		if(x!=0 && cell[j-1].state == 1)
                {
			cubeCorners[0] = 1;
			density[0] += cell[j-1].nrParts;

                        cubeCorners[3] = 8;
			density[9] += cell[j-1].nrParts;

                        cubeCorners[4] = 16;
			density[12] += cell[j-1].nrParts;

                        cubeCorners[7] = 128;
			density[21] += cell[j-1].nrParts;
		}
                if(x!=DIM-1 && cell[j+1].state == 1)
                {
                        cubeCorners[1] = 2;
			density[3] += cell[j+1].nrParts;

                        cubeCorners[2] = 4;
			density[6] += cell[j+1].nrParts;		
	
                        cubeCorners[5] = 32;
			density[15] += cell[j+1].nrParts;

                        cubeCorners[6] = 64;
			density[18] += cell[j+1].nrParts;
                }
                if(y!=0 && cell[j-DIM].state == 1)
		{
                        cubeCorners[0] = 1;
			density[1] += cell[j-DIM].nrParts;

                        cubeCorners[1] = 2;
			density[4] += cell[j-DIM].nrParts;

                        cubeCorners[2] = 4;
			density[7] += cell[j-DIM].nrParts;     
                        
			cubeCorners[3] = 8;
			density[10] += cell[j-DIM].nrParts;
                }
                if(y!=DIM-1 && cell[j+DIM].state == 1)
                {
                        cubeCorners[4] = 16;
			density[13] += cell[j+DIM].nrParts;

                        cubeCorners[5] = 32;
			density[16] += cell[j+DIM].nrParts;

                        cubeCorners[6] = 64;
			density[19] += cell[j+DIM].nrParts;

                        cubeCorners[7] = 128;
			density[22] += cell[j+DIM].nrParts;
                }
                if(z!=0 && cell[j-DIM*DIM].state == 1)
		{
                        cubeCorners[0] = 1;
			density[2] += cell[j-DIM*DIM].nrParts;

                        cubeCorners[1] = 2;
			density[5] += cell[j-DIM*DIM].nrParts;

                        cubeCorners[4] = 16;
			density[14] += cell[j-DIM*DIM].nrParts;

                        cubeCorners[5] = 32;
			density[17] += cell[j-DIM*DIM].nrParts;
                }       
                if(z!=DIM-1 && cell[j+DIM*DIM].state == 1)
                {
                        cubeCorners[2] = 4;
			density[8] += cell[j+DIM*DIM].nrParts;
     
                        cubeCorners[3] = 8;
			density[11] += cell[j+DIM*DIM].nrParts;

                        cubeCorners[6] = 64;
			density[20] += cell[j+DIM*DIM].nrParts;

                        cubeCorners[7] = 128;
			density[23] += cell[j+DIM*DIM].nrParts;

                }
                
                //Kolla kuber som delar en edge med vår kub
                if(x!=0 && y!=0 && cell[j-DIM - 1].state == 1)
                {
                        cubeCorners[0] = 1;
			density[0] += cell[j-DIM-1].nrParts;
			density[1] += cell[j-DIM-1].nrParts;

                        cubeCorners[3] = 8;
			density[9] += cell[j-DIM-1].nrParts;
			density[10] += cell[j-DIM-1].nrParts;
                }
                if(x!=DIM-1 && y!=0 && cell[j-DIM + 1].state == 1)
                {
                        cubeCorners[1] = 2;
			density[3] += cell[j-DIM+1].nrParts;
			density[4] += cell[j-DIM+1].nrParts;

                        cubeCorners[2] = 4;
			density[6] += cell[j-DIM+1].nrParts;
			density[7] += cell[j-DIM+1].nrParts;
                }
                if(y!=0 && z!=0 && cell[j-DIM - DIM*DIM].state == 1)
                {
                        cubeCorners[0] = 1;
			density[1] += cell[j-DIM - DIM*DIM].nrParts;
			density[2] += cell[j-DIM - DIM*DIM].nrParts;

                        cubeCorners[1] = 2;
			density[4] += cell[j-DIM - DIM*DIM].nrParts;
			density[5] += cell[j-DIM - DIM*DIM].nrParts;

                }
                if(y!=0 && z!=DIM-1 && cell[j-DIM + DIM*DIM].state == 1)
                {
                        cubeCorners[2] = 4;
			density[7] += cell[j-DIM + DIM*DIM].nrParts;
			density[8] += cell[j-DIM + DIM*DIM].nrParts;

                        cubeCorners[3] = 8;
			density[10] += cell[j-DIM + DIM*DIM].nrParts;
			density[11] += cell[j-DIM + DIM*DIM].nrParts;

                }
                if(x!=0 && y!=DIM-1 && cell[j+DIM - 1].state == 1)
                {
                        cubeCorners[4] = 16;
			density[12] += cell[j+DIM - 1].nrParts;
			density[13] += cell[j+DIM - 1].nrParts;

                        cubeCorners[7] = 128;
			density[21] += cell[j+DIM - 1].nrParts;
			density[22] += cell[j+DIM - 1].nrParts;
                }
                if(x!=DIM-1 && y!=DIM-1 && cell[j+DIM + 1].state == 1)
                {
                        cubeCorners[5] = 32;
			density[15] += cell[j+DIM + 1].nrParts;
			density[16] += cell[j+DIM + 1].nrParts;

                        cubeCorners[6] = 64;
			density[18] += cell[j+DIM + 1].nrParts;
			density[19] += cell[j+DIM + 1].nrParts;
                }
                if(y!=DIM-1 && z!=0 && cell[j+DIM - DIM*DIM].state == 1)
                {
                        cubeCorners[4] = 16;
			density[13] += cell[j+DIM - DIM*DIM].nrParts;
			density[14] += cell[j+DIM - DIM*DIM].nrParts;

                        cubeCorners[5] = 32;
			density[16] += cell[j+DIM - DIM*DIM].nrParts;
			density[17] += cell[j+DIM - DIM*DIM].nrParts;
                }
                if(y!=DIM-1 && z!=DIM-1 && cell[j+DIM + DIM*DIM].state == 1)
                {
                        cubeCorners[6] = 64;
			density[19] += cell[j+DIM + DIM*DIM].nrParts;
			density[20] += cell[j+DIM + DIM*DIM].nrParts;

                        cubeCorners[7] = 128;
			density[22] += cell[j+DIM + DIM*DIM].nrParts;
			density[23] += cell[j+DIM + DIM*DIM].nrParts;
                }    
                if(x!=0 && z!=0 && cell[j-1 - DIM*DIM].state == 1)
                {
                        cubeCorners[0] = 1;
			density[0] += cell[j-1 - DIM*DIM].nrParts;
			density[2] += cell[j-1 - DIM*DIM].nrParts;

                        cubeCorners[4] = 16;
			density[12] += cell[j-1 - DIM*DIM].nrParts;
			density[14] += cell[j-1 - DIM*DIM].nrParts;
                }
                if(x!=DIM-1 && z!=0 && cell[j+1 - DIM*DIM].state == 1)
                {
                        cubeCorners[1] = 2;
			density[3] += cell[j+1 - DIM*DIM].nrParts;
			density[5] += cell[j+1 - DIM*DIM].nrParts;

                        cubeCorners[5] = 32;
			density[15] += cell[j+1 - DIM*DIM].nrParts;
			density[17] += cell[j+1 - DIM*DIM].nrParts;
                }
                if(x!=0 && z!=DIM-1 && cell[j-1 + DIM*DIM].state == 1)
                {
                        cubeCorners[7] = 128;
			density[21] += cell[j-1 + DIM*DIM].nrParts;
			density[23] += cell[j-1 + DIM*DIM].nrParts;

                        cubeCorners[3] = 8;
			density[9] += cell[j-1 + DIM*DIM].nrParts;
			density[11] += cell[j-1 + DIM*DIM].nrParts;
                }    
                if(x!=DIM-1 && z!=DIM-1 && cell[j+1 + DIM*DIM].state == 1)
                {
                        cubeCorners[6] = 64;
			density[18] += cell[j+1 + DIM*DIM].nrParts;
			density[20] += cell[j+1 + DIM*DIM].nrParts;

                        cubeCorners[2] = 4;
			density[6] += cell[j+1 + DIM*DIM].nrParts;
			density[8] += cell[j+1 + DIM*DIM].nrParts;
                }  
 
                //Kollar kuber som delar hörnpunkt med vår kub
                if(x!=0 && y!=0 && z!=0 && cell[j-1 - DIM - DIM*DIM].state == 1)
                {
                        cubeCorners[0] = 1;
			density[0] += cell[j-1 - DIM - DIM*DIM].nrParts;
			density[1] += cell[j-1 - DIM - DIM*DIM].nrParts;
			density[2] += cell[j-1 - DIM - DIM*DIM].nrParts;

                } 
                if(x!=DIM-1 && y!=0 && z!=0 && cell[j+1 - DIM - DIM*DIM].state == 1)
                {
                        cubeCorners[1] = 2;
			density[3] += cell[j+1 - DIM - DIM*DIM].nrParts;
			density[4] += cell[j+1 - DIM - DIM*DIM].nrParts;
			density[5] += cell[j+1 - DIM - DIM*DIM].nrParts;
                }  
                if(x!=0 && y!=0 && z!=DIM-1 && cell[j-1 - DIM + DIM*DIM].state == 1)
                {
                        cubeCorners[3] = 8;
			density[9] += cell[j-1 - DIM + DIM*DIM].nrParts;
			density[10] += cell[j-1 - DIM + DIM*DIM].nrParts;
			density[11] += cell[j-1 - DIM + DIM*DIM].nrParts;
                } 
                if(x!=DIM-1 && y!=0 && z!=DIM-1 && cell[j+1 - DIM + DIM*DIM].state == 1)
                {
                        cubeCorners[2] = 4;
			density[6] += cell[j+1 - DIM + DIM*DIM].nrParts;
			density[7] += cell[j+1 - DIM + DIM*DIM].nrParts;
			density[8] += cell[j+1 - DIM + DIM*DIM].nrParts;
                }
                if(x!=0 && y!=DIM-1 && z!=0 && cell[j-1 + DIM - DIM*DIM].state == 1)
                {
                        cubeCorners[4] = 16;
			density[12] += cell[j-1 + DIM - DIM*DIM].nrParts;
			density[13] += cell[j-1 + DIM - DIM*DIM].nrParts;
			density[14] += cell[j-1 + DIM - DIM*DIM].nrParts;
                } 
                if(x!=DIM-1 && y!=DIM-1 && z!=0 && cell[j+1 + DIM - DIM*DIM].state == 1)
                {
                        cubeCorners[5] = 32;
			density[15] += cell[j+1 + DIM - DIM*DIM].nrParts;
			density[16] += cell[j+1 + DIM - DIM*DIM].nrParts;
			density[17] += cell[j+1 + DIM - DIM*DIM].nrParts;
                }  
                if(x!=0 && y!=DIM-1 && z!=DIM-1 && cell[j-1 + DIM + DIM*DIM].state == 1)
                {
                        cubeCorners[7] = 128;
			density[21] += cell[j-1 + DIM + DIM*DIM].nrParts;
			density[22] += cell[j-1 + DIM + DIM*DIM].nrParts;
			density[23] += cell[j-1 + DIM + DIM*DIM].nrParts;
                } 
                if(x!=DIM-1 && y!=DIM-1 && z!=DIM-1 && cell[j+1 + DIM + DIM*DIM].state == 1)
                {
                        cubeCorners[6] = 64;
			density[18] += cell[j+1 + DIM + DIM*DIM].nrParts;
			density[19] += cell[j+1 + DIM + DIM*DIM].nrParts;
			density[20] += cell[j+1 + DIM + DIM*DIM].nrParts;
                }
                

                int k;
                Case = 0;
                for(k = 0; k<8; k++)
		{
                        Case += cubeCorners[k];
                }

		
                //vart ligger edgesen i världen

		// Ersätta detta med en loop ? 
		if(interOn){
			edge[0] = SetVector( interpolate(-1.0f+x*cellSize, -1.0f+x*cellSize+cellSize, density[0], density[3])
			 , -1.0f+y*cellSize, -1.0f+z*cellSize);

		        edge[1] = SetVector(-1.0f+(x+1)*cellSize, -1.0f+y*cellSize, 
			interpolate(-1.0f+z*cellSize, -1.0f+z*cellSize + cellSize, density[5], density[8]));

		        edge[2] = SetVector( interpolate(-1.0f+x*cellSize, -1.0f+x*cellSize + cellSize, density[9], density[6])
			, -1.0f+y*cellSize, -1.0f+(z+1)*cellSize);

		        edge[3] = SetVector(-1.0f+x*cellSize, -1.0f+y*cellSize, 
			interpolate(-1.0f+z*cellSize, -1.0f+z*cellSize + cellSize, density[2], density[11]));
		        
			//toppen av cuben
		        edge[4] = SetVector(interpolate(-1.0f+x*cellSize, -1.0f+x*cellSize + cellSize, density[12], density[15])
			, -1.0f+(y+1)*cellSize, -1.0f+z*cellSize);

		        edge[5] = SetVector(-1.0f+(x+1)*cellSize, -1.0f+(y+1)*cellSize, 
			interpolate(-1.0f+z*cellSize, -1.0f+z*cellSize + cellSize, density[17], density[20]));


		        edge[6] = SetVector(interpolate(-1.0f+x*cellSize, -1.0f+x*cellSize + cellSize, density[21], density[18])
			, -1.0f+(y+1)*cellSize, -1.0f+(z+1)*cellSize);

		        edge[7] = SetVector(-1.0f+x*cellSize, -1.0f+(y+1)*cellSize,
			interpolate(-1.0f+z*cellSize, -1.0f+z*cellSize+cellSize, density[14], density[23]));
		        
			//sidorna av cuben
		        edge[8] = SetVector(-1.0f+x*cellSize, 
			interpolate(-1.0f+y*cellSize, -1.0f+y*cellSize+cellSize, density[1], density[13])
			, -1.0f+z*cellSize);


		        edge[9] = SetVector(-1.0f+(x+1)*cellSize, 
			interpolate(-1.0f+y*cellSize, -1.0f+y*cellSize+cellSize, density[4], density[16])
			, -1.0f+z*cellSize);
	
		        edge[10] = SetVector(-1.0f+(x+1)*cellSize, 
			interpolate(-1.0f+y*cellSize, -1.0f+y*cellSize+cellSize, density[7], density[19])
			, -1.0f+(z+1)*cellSize);

		        edge[11] = SetVector(-1.0f+x*cellSize,
			interpolate(-1.0f+y*cellSize, -1.0f+y*cellSize+cellSize, density[10], density[22])
			, -1.0f+(z+1)*cellSize); 
		}else{   
			yCell = y*cellSize; 
			xCell = x*cellSize; 
			zCell = z*cellSize;   
			edge[0] = SetVector(-1.0f+xCell+halfSize, -1.0f+ yCell, -1.0f+zCell);
		        edge[1] = SetVector(-1.0f+xCell +cellSize, -1.0f+ yCell, -1.0f+zCell+halfSize);
		        edge[2] = SetVector(-1.0f+xCell+halfSize, -1.0f+ yCell, -1.0f+zCell + cellSize);
		        edge[3] = SetVector(-1.0f+xCell, -1.0f+ yCell, -1.0f+zCell+halfSize);
		        
			//toppen av cuben
		        edge[4] = SetVector(-1.0f+xCell+halfSize, -1.0f+yCell + cellSize, -1.0f+zCell);
		        edge[5] = SetVector(-1.0f+xCell + cellSize, -1.0f+yCell + cellSize, -1.0f+zCell+halfSize);
		        edge[6] = SetVector(-1.0f+xCell+halfSize, -1.0f+yCell + cellSize, -1.0f+zCell + cellSize);
		        edge[7] = SetVector(-1.0f+xCell, -1.0f+yCell + cellSize, -1.0f+zCell+halfSize);
		        
			//sidorna av cuben
		        edge[8] = SetVector(-1.0f+xCell, -1.0f+ yCell+halfSize, -1.0f+zCell);
		        edge[9] = SetVector(-1.0f+xCell + cellSize, -1.0f+ yCell+halfSize, -1.0f+zCell);
		        edge[10] = SetVector(-1.0f+xCell +cellSize, -1.0f+ yCell+halfSize, -1.0f+zCell + cellSize);
		        edge[11] = SetVector(-1.0f+xCell, -1.0f+ yCell+halfSize, -1.0f+zCell + cellSize);            
		}        

                //hämta vilket case
                int tmp;
                
                for(k = 0; k<16; k++)
                {
                        tmp = triTable[Case][k];
                        if(tmp != -1)
                        {	
				(*mTris) = realloc((*mTris),(count+3) * sizeof(GLfloat)); /* give the pointer some memory */
				
		
				/* 
					Here one could save the points via index. If the point
					already exists. Use the index. Otherwise add point to list and then 
					use the index.
				*/                                
				(*mTris)[count] = edge[tmp].x;
                                count++;
                                (*mTris)[count] = edge[tmp].y;
                                count++;                                
                                (*mTris)[count] = edge[tmp].z;
                                count++;
				////////////////////////////////////////////////////////////////////////
				int ind = vertIndex(edge[tmp]);
				if(ind == -1){
					verts = realloc(verts, (vertListSize+1) * sizeof(Vertlist));
					verts[vertListSize].position = SetVector(edge[tmp].x, edge[tmp].y, edge[tmp].z);
					verts[vertListSize].normal = SetVector(0.0f, 0.0f, 0.0f);				
					verts[vertListSize].nr = 1;
					vertListSize++;
				}else{
					verts[ind].nr++;
					//printf("%i  \n", ind);
				}
				////////////////////////////////////////////////////////////////////////
                        }
			else
                        	k=15;
                        
                }
		
	}
	//printf("found a total of  %i vertices \n\n", vertListSize);
	
	int normalCount = 0;
	vec3 normal, u, v, v1, v2;
	//Index of the normal	
	int normInd;
	(*mNorms) = realloc((*mNorms),count * sizeof(GLfloat));

	while(normalCount < count)
	{
		v1 = SetVector((*mTris)[normalCount], (*mTris)[normalCount+1], (*mTris)[normalCount+2]);
		v2 = SetVector((*mTris)[normalCount+3], (*mTris)[normalCount+4], (*mTris)[normalCount+5]);
		u = VectorSub(v2, v1);
		
		v2 = SetVector((*mTris)[normalCount+6], (*mTris)[normalCount+7], (*mTris)[normalCount+8]);
		v = Normalize(VectorSub(v2, v1));
		
		normal = Normalize(CrossProduct(u, v));
		
		
		
		(*mNorms)[normalCount] = normal.x;
		(*mNorms)[normalCount+1] = normal.y;
		(*mNorms)[normalCount+2] = normal.z;
		

		(*mNorms)[normalCount+3] = normal.x;
		(*mNorms)[normalCount+4] = normal.y;
		(*mNorms)[normalCount+5] = normal.z;

		(*mNorms)[normalCount+6] = normal.x;
		(*mNorms)[normalCount+7] = normal.y;
		(*mNorms)[normalCount+8] = normal.z;
		/*
		/*Find the index of this normal with help of vertex. Then add this normal 
		to a summed normal.*/
		if(vertNormOn && Norm(normal) > 0.0001){
		normInd = vertIndex(SetVector((*mTris)[normalCount], (*mTris)[normalCount+1], (*mTris)[normalCount+2]));
		verts[normInd].normal = VectorAdd(verts[normInd].normal, SetVector(normal.x, normal.y, normal.z));
		
		normInd = vertIndex(SetVector((*mTris)[normalCount+3], (*mTris)[normalCount+4], (*mTris)[normalCount+5]));
		verts[normInd].normal = VectorAdd(verts[normInd].normal, SetVector(normal.x, normal.y, normal.z));
		
		normInd = vertIndex(SetVector((*mTris)[normalCount+6], (*mTris)[normalCount+7], (*mTris)[normalCount+8]));
		verts[normInd].normal = VectorAdd(verts[normInd].normal, SetVector(normal.x, normal.y, normal.z));	
		//printf("normal is %f, %f, %f ", normal.x, normal.y, normal.z);  
		}		
		normalCount+=9;
	}
	//printf("%s", "\n\n");

	/*
		Normals for all indices have been calculated. Now one could add up all normals sharing a 
		vertex. Then divide with number of vertices or normalize. Then set normals for all with the 
		same index in the vertex list.
		1. Get all normals and divide by number of vertices sharing that normal and then normalize. Klar
		2. Take one point and find its index
		3. Use index to get new normal
	*/
	if(vertNormOn){
		int k;
		for(k=0; k<vertListSize; k++){
			verts[k].normal.x = verts[k].normal.x / verts[k].nr;
			verts[k].normal.y = verts[k].normal.y / verts[k].nr;
			verts[k].normal.z = verts[k].normal.z / verts[k].nr;
			verts[k].normal = Normalize(verts[k].normal);
			//printf("New normal is %f, %f, %f Number of normals was %i \n", verts[k].normal.x, verts[k].normal.y, verts[k].normal.z, verts[k].nr);  
		}
		int ind;
		for(k=0; k<count; k=k+3){
			ind = vertIndex(SetVector((*mTris)[k], (*mTris)[k+1], (*mTris)[k+2]));
			(*mNorms)[k] = verts[ind].normal.x;
			(*mNorms)[k+1] = verts[ind].normal.y;
			(*mNorms)[k+2] = verts[ind].normal.z;		
		}
	}
	//printf("%s", "\n\n");
	//Ge triSize storleken på det allokerade minnet
	triSize = (count) * sizeof(GLfloat); 

	
}	
Beispiel #2
0
void convert_mobile(MOB_INDEX_DATA * pMobIndex)
{
    int i;
    int type, number, bonus;
    int level;

    if (!pMobIndex || pMobIndex->new_format)
	return;

    level = pMobIndex->level;

    pMobIndex->act |= ACT_WARRIOR;

    /*
     * Calculate hit dice.  Gives close to the hitpoints
     * of old format mobs created with create_mobile()  (db.c)
     * A high number of dice makes for less variance in mobiles
     * hitpoints.
     * (might be a good idea to reduce the max number of dice)
     *
     * The conversion below gives:

     level:     dice         min         max        diff       mean
     1:       1d2+6       7(  7)     8(   8)     1(   1)     8(   8)
     2:       1d3+15     16( 15)    18(  18)     2(   3)    17(  17)
     3:       1d6+24     25( 24)    30(  30)     5(   6)    27(  27)
     5:      1d17+42     43( 42)    59(  59)    16(  17)    51(  51)
     10:      3d22+96     99( 95)   162( 162)    63(  67)   131(    )
     15:     5d30+161    166(159)   311( 311)   145( 150)   239(    )
     30:    10d61+416    426(419)  1026(1026)   600( 607)   726(    )
     50:    10d169+920   930(923)  2610(2610)  1680(1688)  1770(    )

     The values in parenthesis give the values generated in create_mobile.
     Diff = max - min.  Mean is the arithmetic mean.
     (hmm.. must be some roundoff error in my calculations.. smurfette got
     1d6+23 hp at level 3 ? -- anyway.. the values above should be
     approximately right..)
     */
    type = level * level * 27 / 40;
    number = UMIN(type / 40 + 1, 10);	/* how do they get 11 ??? */
    type = UMAX(2, type / number);
    bonus = UMAX(0, level * (8 + level) * .9 - number * type);

    pMobIndex->hit[DICE_NUMBER] = number;
    pMobIndex->hit[DICE_TYPE] = type;
    pMobIndex->hit[DICE_BONUS] = bonus;

    pMobIndex->mana[DICE_NUMBER] = level;
    pMobIndex->mana[DICE_TYPE] = 10;
    pMobIndex->mana[DICE_BONUS] = 100;

    /*
     * Calculate dam dice.  Gives close to the damage
     * of old format mobs in damage()  (fight.c)
     */
    type = level * 7 / 4;
    number = UMIN(type / 8 + 1, 5);
    type = UMAX(2, type / number);
    bonus = UMAX(0, level * 9 / 4 - number * type);

    pMobIndex->damage[DICE_NUMBER] = number;
    pMobIndex->damage[DICE_TYPE] = type;
    pMobIndex->damage[DICE_BONUS] = bonus;

    switch (number_range(1, 3)) {
    case (1):
	pMobIndex->dam_type = 3;
	break;			/* slash  */
    case (2):
	pMobIndex->dam_type = 7;
	break;			/* pound  */
    case (3):
	pMobIndex->dam_type = 11;
	break;			/* pierce */
    }

    for (i = 0; i < 3; i++)
	pMobIndex->ac[i] = interpolate(level, 100, -100);
    pMobIndex->ac[3] = interpolate(level, 100, 0);	/* exotic */

    pMobIndex->wealth /= 100;
    pMobIndex->size = SIZE_MEDIUM;
    pMobIndex->material = str_dup("none");

    pMobIndex->new_format = TRUE;
    ++newmobs;

    return;
}
Beispiel #3
0
int qFinderDMM::lineMinimizeFletcher(vector<double>& x, vector<double>& p, double f0, double df0, double alpha1, double& alphaNew, double& fAlpha, vector<double>& xalpha, vector<double>& gradient ){
    try {
        
        double rho = 0.01;
        double sigma = 0.10;
        double tau1 = 9.00;
        double tau2 = 0.05;
        double tau3 = 0.50;
        
        double alpha = alpha1;
        double alpha_prev = 0.0000;
        
        xalpha.resize(numOTUs, 0.0000);
        
        double falpha_prev = f0;
        double dfalpha_prev = df0;
        
        double a = 0.0000;          double b = alpha;
        double fa = f0;             double fb = 0.0000;
        double dfa = df0;           double dfb = 0.0/0.0;
        
        int iter = 0;
        int maxIters = 100;
        while(iter++ < maxIters){
            if (m->control_pressed) { break; }
            
            for(int i=0;i<numOTUs;i++){
                xalpha[i] = x[i] + alpha * p[i];
            }
            
            fAlpha = negativeLogEvidenceLambdaPi(xalpha);
            
            if(fAlpha > f0 + alpha * rho * df0 || fAlpha >= falpha_prev){
                a = alpha_prev;         b = alpha;
                fa = falpha_prev;       fb = fAlpha;
                dfa = dfalpha_prev;     dfb = 0.0/0.0;
                break;
            }
            
            negativeLogDerivEvidenceLambdaPi(xalpha, gradient);
            double dfalpha = 0.0000;
            for(int i=0;i<numOTUs;i++){ dfalpha += gradient[i] * p[i]; }
            
            if(abs(dfalpha) <= -sigma * df0){
                alphaNew = alpha;
                return 1;
            }
            
            if(dfalpha >= 0){
                a = alpha;                  b = alpha_prev;
                fa = fAlpha;                fb = falpha_prev;
                dfa = dfalpha;              dfb = dfalpha_prev;
                break;
            }
            
            double delta = alpha - alpha_prev;
            
            double lower = alpha + delta;
            double upper = alpha + tau1 * delta;
            
            double alphaNext = interpolate(alpha_prev, falpha_prev, dfalpha_prev, alpha, fAlpha, dfalpha, lower, upper);
            
            alpha_prev = alpha;
            falpha_prev = fAlpha;
            dfalpha_prev = dfalpha;
            alpha = alphaNext;
        }
        
        iter = 0;
        while(iter++ < maxIters){
            if (m->control_pressed) { break; }
            
            double delta = b - a;
            
            double lower = a + tau2 * delta;
            double upper = b - tau3 * delta;
            
            alpha = interpolate(a, fa, dfa, b, fb, dfb, lower, upper);
            
            for(int i=0;i<numOTUs;i++){
                xalpha[i] = x[i] + alpha * p[i];
            }
            
            fAlpha = negativeLogEvidenceLambdaPi(xalpha);
            
            if((a - alpha) * dfa <= EPSILON){
                return 0;
            }
            
            if(fAlpha > f0 + rho * alpha * df0 || fAlpha >= fa){
                b = alpha;
                fb = fAlpha;
                dfb = 0.0/0.0;
            }
            else{
                double dfalpha = 0.0000;
                
                negativeLogDerivEvidenceLambdaPi(xalpha, gradient);
                dfalpha = 0.0000;
                for(int i=0;i<numOTUs;i++){ dfalpha += gradient[i] * p[i]; }
                
                if(abs(dfalpha) <= -sigma * df0){
                    alphaNew = alpha;
                    return 1;
                }
                
                if(((b-a >= 0 && dfalpha >= 0) || ((b-a) <= 0.000 && dfalpha <= 0))){
                    b = a;      fb = fa;        dfb = dfa;
                    a = alpha;  fa = fAlpha;    dfa = dfalpha;
                }
                else{
                    a = alpha;
                    fa = fAlpha;
                    dfa = dfalpha;
                }
            }
            
            
        }
        
        return 1;
    }
	catch(exception& e) {
		m->errorOut(e, "qFinderDMM", "lineMinimizeFletcher");
		exit(1);
	}
}
Beispiel #4
0
static gint
pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
{
    gint ret = FALSE;

    SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
    if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
        SPDesktop *const dt = pc->desktop;

        pc->is_drawing = false;

        /* Find desktop coordinates */
        Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));

        /* Test whether we hit any anchor. */
        SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
                                                              revent.y));

        switch (pc->state) {
            case SP_PENCIL_CONTEXT_IDLE:
                /* Releasing button in idle mode means single click */
                /* We have already set up start point/anchor in button_press */
                if (!(revent.state & GDK_CONTROL_MASK)) {
                    // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
                    pc->state = SP_PENCIL_CONTEXT_ADDLINE;
                }
                ret = TRUE;
                break;
            case SP_PENCIL_CONTEXT_ADDLINE:
                /* Finish segment now */
                if (anchor) {
                    p = anchor->dp;
                } else {
                    spdc_endpoint_snap(pc, p, revent.state);
                }
                pc->ea = anchor;
                spdc_set_endpoint(pc, p);
                spdc_finish_endpoint(pc);
                pc->state = SP_PENCIL_CONTEXT_IDLE;
                ret = TRUE;
                break;
            case SP_PENCIL_CONTEXT_FREEHAND:
                if (revent.state & GDK_MOD1_MASK) {
                    /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */

                    sketch_interpolate(pc);

                    if (pc->green_anchor) {
                        pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
                    }

                    pc->state = SP_PENCIL_CONTEXT_SKETCH;
                } else {
                    /* Finish segment now */
                    /// \todo fixme: Clean up what follows (Lauris)
                    if (anchor) {
                        p = anchor->dp;
                    }
                    pc->ea = anchor;
                    /* Write curves to object */

                    dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));

                    interpolate(pc);
                    spdc_concat_colors_and_flush(pc, FALSE);
                    pc->sa = NULL;
                    pc->ea = NULL;
                    if (pc->green_anchor) {
                        pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
                    }
                    pc->state = SP_PENCIL_CONTEXT_IDLE;
                    // reset sketch mode too
                    pc->sketch_n = 0;
                }
                ret = TRUE;
                break;
            case SP_PENCIL_CONTEXT_SKETCH:
            default:
                break;
        }

        if (pc->grab) {
            /* Release grab now */
            sp_canvas_item_ungrab(pc->grab, revent.time);
            pc->grab = NULL;
        }

        ret = TRUE;
    }
    return ret;
}
Beispiel #5
0
int main() {

	double xx[100],yy[100];
	float ff[100];
	double x,y,z;
	float f;
	long index;
	long i,j;
	Vector v, normal, position, angle;

	printf("\n");
	printf("-------------------------------------\n");
	printf("    PhoSim Unit Testing Framework\n");
	printf("-------------------------------------\n\n");
	for (i=0;i<100;i++) xx[i]=((double)i)/100.0;
	for (i=0;i<100;i++) yy[i]=((double)i)/100.0;
	for (i=0;i<100;i++) ff[i]=((double)i)/100.0;


	find(xx,100,0.601,&index);
	unitTestOutput(index,60,"find","Index finding","none");

	index=find_linear(xx,100,0.601,&x);
	unitTestOutput(index,60,"findLinear","Index finding","none");

	find_linear_wrap(1.0,0.1,100,&i,&j,&x);
	unitTestOutput(j,60,"findLinearWrap","Index finding","none");

	x=1.0; y=1.0; z=0.0;
	normalize(&x,&y,&z);
	unitTestOutput(x,1.0/sqrt(2.0),"normalize","Normalize vector","none");

	x=interpolate(yy,xx,0.605,60);
	unitTestOutput(x,0.605,"interpolate","Interpolate array","none");

	x=interpolate_linear(yy,60,60.5);
	unitTestOutput(x,0.605,"interpolateLinear","Interpolate array","none");

	x=interpolate_bilinear(yy,0,0,0.0,60,60.5);
	unitTestOutput(x,0.605,"interpolateBilinear","Interpolate 2-D array","none");

	f=interpolate_bilinear_float_wrap(ff,0,0,1,0.0,60,61,0.5);
	unitTestOutput((double)f,0.605,"interpolateBilinearFloatWrap","Interpolate 2-D array","none");

	v.x=0.0; v.y=1.0/sqrt(2.0); v.z=-1.0/sqrt(2.0);
	normal.x=0.0; normal.y=0.0; normal.z=1.0;
	reflect(&v,normal);
	unitTestOutput(v.z,1/sqrt(2.0),"reflect","Ray component after reflection","none");

	v.x=0.0; v.y=1.0/sqrt(2.0); v.z=-1.0/sqrt(2.0);
	normal.x=0.0; normal.y=0.0; normal.z=1.0;
	refract(&v,normal,1.0,2.0);
	unitTestOutput(v.y,1/sqrt(2.0)/2.0,"refract","Ray component after snell's law","none");

	position.x=0.; position.y=0.; position.z=0.;
	angle.x=0; angle.y=1/sqrt(2.0); angle.z=1/sqrt(2.0);
	propagate(&position,angle,sqrt(2.0));
	unitTestOutput(position.y,1.0,"propagate","Ray position after propagation","none");

	return(0);
}
Beispiel #6
0
int kstfit_general_levenberg_marquardt(const double *const inArrays[], const int inArrayLens[],
              const double inScalars[], double *outArrays[], int outArrayLens[],
              double outScalars[], const char* inStrings[], char *outStrings[])
{
  KST_UNUSED(outStrings);

  int iReturn = -1;

  if (inArrayLens[X] >= 2 && inArrayLens[Y] >= 2) {
    mu::Parser parser;
    double* pResult[4];
    double* pDelete = 0L;
    double* pInputX;
    double* pInputY;
    double *parameters;
    double tolerance = inScalars[0];
    double xvar;
    char *token;
    char *toSplit;
    char *endPtr;
    int maxIterations = (int)inScalars[1];
    int n = inArrayLens[0];
    int paramsNumber = 2;
    int startsNumber = 0;
    int iLengthData;
    int i;
    int j;

    iLengthData = inArrayLens[X];
    if( inArrayLens[Y] > iLengthData ) {
      iLengthData = inArrayLens[Y];
    }

    if (inArrayLens[X] == iLengthData) {
      pInputX = (double*)inArrays[X];
    } else {
      pDelete = (double*)malloc(iLengthData * sizeof( double ));
      pInputX = pDelete;
      for( i=0; i<iLengthData; i++) {
        pInputX[i] = interpolate( i, iLengthData, inArrays[X], inArrayLens[X] );
      }
    }

    if (inArrayLens[Y] == iLengthData) {
      pInputY = (double*)inArrays[Y];
    } else {
      pDelete = (double*)malloc(iLengthData * sizeof( double ));
      pInputY = pDelete;
      for( i=0; i<iLengthData; i++) {
        pInputY[i] = interpolate( i, iLengthData, inArrays[Y], inArrayLens[Y] );
      }
    }

    //
    // count the number of parameter names
    //
    toSplit = strdup(inStrings[1]);
    token = strtok( toSplit, ",;:" );
    while( token != NULL ) {
      paramsNumber++;
      token = strtok( NULL, ",;:" );
    }
    free(toSplit);

    if( iLengthData > paramsNumber ) {
      if( outArrayLens[0] != iLengthData ) {
        pResult[0] = (double*)realloc( outArrays[0], iLengthData * sizeof( double ) );
      } else {
        pResult[0] = outArrays[0];
      }

      if( outArrayLens[1] != iLengthData ) {
        pResult[1] = (double*)realloc( outArrays[1], iLengthData * sizeof( double ) );
      } else {
        pResult[1] = outArrays[1];
      }

      if( outArrayLens[2] != paramsNumber ) {
        pResult[2] = (double*)realloc( outArrays[2], paramsNumber * sizeof( double ) );
      } else {
        pResult[2] = outArrays[2];
      }

      if( outArrayLens[3] != paramsNumber * paramsNumber ) {
        pResult[3] = (double*)realloc( outArrays[3], paramsNumber * paramsNumber * sizeof( double ) );
      } else {
        pResult[3] = outArrays[3];
      }

      if( pResult[0] != NULL &&
          pResult[1] != NULL &&
          pResult[2] != NULL &&
          pResult[3] != NULL ) {
        outArrays[0] = pResult[0];
        outArrayLens[0] = iLengthData;
        outArrays[1] = pResult[1];
        outArrayLens[1] = iLengthData;
        outArrays[2] = pResult[2];
        outArrayLens[2] = paramsNumber;
        outArrays[3] = pResult[3];
        outArrayLens[3] = paramsNumber * paramsNumber;

        parameters = new double[paramsNumber];
        for (i=0; i<paramsNumber; i++) {
          parameters[i] = 0.0;
        }
        paramsNumber = 0;

        //
        // set the parameter names
        //
        toSplit = strdup(inStrings[1]);
        token = strtok( toSplit, ",;:" );
        while( token != NULL ) {
          char *paramName = strdup(token);
          char *paramPointer = paramName;

          while (paramPointer[0] == ' ') {
            paramPointer++;
          }
          while (paramPointer[strlen(paramPointer)] == ' ') {
            paramPointer[strlen(paramPointer)] = '\0';
          }

          try {
            parser.DefineVar(paramPointer, &parameters[paramsNumber]);
          } catch (mu::Parser::exception_type &e) {
          }

          paramsNumber++;
          token = strtok( NULL, ",;:" );
          free( paramName );
        }
        free(toSplit);

        //
        // set parameter initial guesses
        //
        double pInit[paramsNumber];
        toSplit = strdup(inStrings[2]);
        token = strtok( toSplit, ",;:" );
        while( token != NULL ) {
          pInit[startsNumber] = strtod(token, &endPtr);
          startsNumber++;
          token = strtok( NULL, ",;:" );
        }
        free(toSplit);

        for (i=startsNumber; i<paramsNumber; i++) {
          pInit[i] = 0.0;
        }

        if (strstr(inStrings[0], "pi") != 0L) {
          parser.DefineConst("pi", M_PI);
        }
        if (strstr(inStrings[0], "Pi") != 0L) {
          parser.DefineConst("Pi", M_PI);
        }
        if (strstr(inStrings[0], "PI") != 0L) {
          parser.DefineConst("PI", M_PI);
        }
        parser.DefineVar("x", &xvar);
        parser.SetExpr(inStrings[0]);

        gsl_vector_view x = gsl_vector_view_array(pInit, paramsNumber);

        struct fit d = { n, inArrays[0], inArrays[1], outArrays[0], &xvar, parameters, paramsNumber, &parser };

        const gsl_multifit_fdfsolver_type *T = gsl_multifit_fdfsolver_lmsder;

        gsl_multifit_fdfsolver *s = gsl_multifit_fdfsolver_alloc(T, n, paramsNumber);
        if (s != 0L) {
          gsl_multifit_function_fdf f;
          gsl_matrix *covar = gsl_matrix_alloc(paramsNumber, paramsNumber);
          if (covar != 0L) {
            f.f = &function_f;
            f.df = &function_df;
            f.fdf = &function_fdf;
            f.n = n;
            f.p = paramsNumber;
            f.params = &d;

            gsl_multifit_fdfsolver_set(s, &f, &x.vector);

            int status;
            int iteration = 0;

            do {
              iteration++;
              status = gsl_multifit_fdfsolver_iterate(s);
              if (status) {
                break;
              }
              status = gsl_multifit_test_delta(s->dx, s->x, tolerance, tolerance);
            } while (status == GSL_CONTINUE && iteration < maxIterations);

            gsl_multifit_covar(s->J, 0.0, covar);

            for( i=0; i<n; i++ ) {
              xvar = inArrays[0][i];

              try {
                outArrays[0][i] = parser.Eval();
                outArrays[1][i] = inArrays[1][i] - outArrays[0][i];
              } catch (mu::Parser::exception_type &e) {
                outArrays[0][i] = 0.0;
                outArrays[1][i] = 0.0;
              }
            }

            for (i=0; i<paramsNumber; i++) {
              outArrays[2][i] = parameters[i];
              for (j=0; j<paramsNumber; j++) {
                outArrays[3][(i*paramsNumber)+j] = gsl_matrix_get( covar, i, j );
              }
            }

            //
            // determine the value of chi^2/nu
            //
            outScalars[0] = gsl_blas_dnrm2( s->f );

            iReturn = 0;

            gsl_matrix_free(covar);
          }

          gsl_multifit_fdfsolver_free(s);
        }
      }
    }

    if( pDelete )
    {
      free( pDelete );
    }
  }

  return iReturn;
}
Beispiel #7
0
 QRgb map(QRgb, QPoint point) const {
     return interpolate(orig, translate(point));
 }
Beispiel #8
0
int main(int argc, char *argv[])
{
  double        fps, k;
  int           i, width, height, len;
  CvCapture     *in;
  CvVideoWriter *out;
  IplImage      *bufimg;

  if (argc != 3)
    {
      ERROR("Usage: interpolation source destination");
      return EXIT_FAILURE;
    }

  in = cvCaptureFromFile(argv[1]);
  if (!in)
    {
      ERROR("Failed to open for reading '%s'", argv[1]);
      return EXIT_FAILURE;
    }

  fps = cvGetCaptureProperty(in, CV_CAP_PROP_FPS);
  if (fps > TARGET)
    {
      ERROR("Video already has a framerate of %.2f (target was %.2f)",
            fps, TARGET);
      return EXIT_FAILURE;
    }

  width = cvGetCaptureProperty(in, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(in, CV_CAP_PROP_FRAME_HEIGHT);
  len = cvGetCaptureProperty(in, CV_CAP_PROP_FRAME_COUNT);

  out = cvCreateVideoWriter(TMPFILE, CODEC, TARGET, cvSize(width, height), 1);
  if (!out)
    {
      ERROR("Failed to open for writing '%s'", TMPFILE);
      return EXIT_FAILURE;
    }

  k = TARGET / fps;
  bufimg = cvQueryFrame(in);
  for (i = 1; i < len; ++i)
    {
      IplImage *img;

      img = cvCloneImage(bufimg);
      bufimg = cvQueryFrame(in);
      progressbar(100 * i / len);

      if (interpolate(k, out, img, bufimg))
        return EXIT_FAILURE;

      cvReleaseImage(&img);
    }
  cvWriteFrame(out, bufimg);
  progressbar(0);

  cvReleaseVideoWriter(&out);
  cvReleaseCapture(&in);

  if (add_audio(argv[1], argv[2]))
    return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
Beispiel #9
0
void GFourierWaveProcessor::doit(GWave& signal)
{
	for(unsigned short chan = 0; chan < signal.channels(); chan++)
	{
		// Denoise the signal. Here is an ascii-art representation of how the blocks align.
		// Suppose the signal is 4 blocks long (n=4). i will iterate from 0 to 4.
		//                 _________ _________ _________ _________
		//  0   A    B    C    D    E
		//  1             A    B    C    D    E
		//  2                       A    B    C    D    E
		//  3                                 A    B    C    D    E
		//  4                                           A    B    C    D    E
		GWaveIterator itSignalIn(signal);
		GWaveIterator itSignalOut(signal);
		size_t n = itSignalIn.remaining() / m_blockSize;
		if((m_blockSize * n) < itSignalIn.remaining())
			n++;
		for(size_t i = 0; i <= n; i++)
		{
			// Encode block D (which also covers the latter-half of C and the first-half of E)
			if(i != n)
			{
				encodeBlock(itSignalIn, m_pBufD, chan);
				struct ComplexNumber* pSrc = m_pBufD;
				struct ComplexNumber* pDest = m_pBufC + m_blockSize / 2;
				for(size_t j = 0; j < m_blockSize / 2; j++)
					*(pDest++) = *(pSrc++);
				pDest = m_pBufE;
				for(size_t j = 0; j < m_blockSize / 2; j++)
					*(pDest++) = *(pSrc++);

				// Blocks C and D are fully-encoded, so we can bring them to the Fourier domain now
				if(i != 0)
					GFourier::fft(m_blockSize, m_pBufC, true);
				GFourier::fft(m_blockSize, m_pBufD, true);
			}

			// Process the blocks that are ready-to-go
			if(i != 0)
			{
				// Denoise blocks B and C
				process(m_pBufB);
				GFourier::fft(m_blockSize, m_pBufB, false);
				if(i != n)
				{
					process(m_pBufC);
					GFourier::fft(m_blockSize, m_pBufC, false);
				}

				// Interpolate A, B, and C to produce the final B
				interpolate(i == 1 ? NULL : m_pBufA, m_pBufB, i == n ? NULL : m_pBufC, m_blockSize / 2);
				decodeBlock(itSignalOut, chan);
			}

			// Shift A<-C, B<-D, C<-E
			struct ComplexNumber* pTemp = m_pBufA;
			m_pBufA = m_pBufC;
			m_pBufC = m_pBufE;
			m_pBufE = pTemp;
			pTemp = m_pBufB;
			m_pBufB = m_pBufD;
			m_pBufD = pTemp;
		}
		GAssert(itSignalOut.remaining() == 0);
	}
}
    void IsoSurfaceMC::addMarchingCubesTriangles(const Vector3 *corners, const Vector4 *volumeValues, MeshBuilder *mb) const
    {
        unsigned char cubeIndex = 0;
        Vector4 values[8];

        // Find out the case.
        for (size_t i = 0; i < 8; ++i)
        {
            if (volumeValues)
            {
                values[i] = volumeValues[i];
            }
            else
            {
                values[i] = mSrc->getValueAndGradient(corners[i]);
            }
            if (values[i].w >= ISO_LEVEL)
            {
                cubeIndex |= 1 << i;
            }
        }

        int edge = mcEdges[cubeIndex];

        // Nothing intersects.
        if (!edge)
        {
            return;
        }

        // Find the intersection vertices.
        Vector3 intersectionPoints[12];
        Vector3 intersectionNormals[12];
        if (edge & 1)
        {
            intersectionPoints[0] = interpolate(corners[0], corners[1], values[0], values[1], intersectionNormals[0]);
        }
        if (edge & 2)
        {
            intersectionPoints[1] = interpolate(corners[1], corners[2], values[1], values[2], intersectionNormals[1]);
        }
        if (edge & 4)
        {
            intersectionPoints[2] = interpolate(corners[2], corners[3], values[2], values[3], intersectionNormals[2]);
        }
        if (edge & 8)
        {
            intersectionPoints[3] = interpolate(corners[3], corners[0], values[3], values[0], intersectionNormals[3]);
        }
        if (edge & 16)
        {
            intersectionPoints[4] = interpolate(corners[4], corners[5], values[4], values[5], intersectionNormals[4]);
        }
        if (edge & 32)
        {
            intersectionPoints[5] = interpolate(corners[5], corners[6], values[5], values[6], intersectionNormals[5]);
        }
        if (edge & 64)
        {
            intersectionPoints[6] = interpolate(corners[6], corners[7], values[6], values[7], intersectionNormals[6]);
        }
        if (edge & 128)
        {
            intersectionPoints[7] = interpolate(corners[7], corners[4], values[7], values[4], intersectionNormals[7]);
        }
        if (edge & 256)
        {
            intersectionPoints[8] = interpolate(corners[0], corners[4], values[0], values[4], intersectionNormals[8]);
        }
        if (edge & 512)
        {
            intersectionPoints[9] = interpolate(corners[1], corners[5], values[1], values[5], intersectionNormals[9]);
        }
        if (edge & 1024)
        {
            intersectionPoints[10] = interpolate(corners[2], corners[6], values[2], values[6], intersectionNormals[10]);
        }
        if (edge & 2048)
        {
            intersectionPoints[11] = interpolate(corners[3], corners[7], values[3], values[7], intersectionNormals[11]);
        }

        // Create the triangles according to the table.
        for (int i = 0; mcTriangles[cubeIndex][i] != -1; i += 3)
        {
            mb->addTriangle(intersectionPoints[mcTriangles[cubeIndex][i]], intersectionNormals[mcTriangles[cubeIndex][i]],
                intersectionPoints[mcTriangles[cubeIndex][i + 1]], intersectionNormals[mcTriangles[cubeIndex][i + 1]],
                intersectionPoints[mcTriangles[cubeIndex][i + 2]], intersectionNormals[mcTriangles[cubeIndex][i + 2]]);
        }
    }
Beispiel #11
0
static char *path_ok(struct interp *itable)
{
	static char rpath[PATH_MAX];
	static char interp_path[PATH_MAX];
	int retried_path = 0;
	char *path;
	char *dir;

	dir = itable[INTERP_SLOT_DIR].value;

	if (avoid_alias(dir)) {
		logerror("'%s': aliased", dir);
		return NULL;
	}

	if (*dir == '~') {
		if (!user_path) {
			logerror("'%s': User-path not allowed", dir);
			return NULL;
		}
		if (*user_path) {
			/* Got either "~alice" or "~alice/foo";
			 * rewrite them to "~alice/%s" or
			 * "~alice/%s/foo".
			 */
			int namlen, restlen = strlen(dir);
			char *slash = strchr(dir, '/');
			if (!slash)
				slash = dir + restlen;
			namlen = slash - dir;
			restlen -= namlen;
			loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
			snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
				 namlen, dir, user_path, restlen, slash);
			dir = rpath;
		}
	}
	else if (interpolated_path && saw_extended_args) {
		if (*dir != '/') {
			/* Allow only absolute */
			logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
			return NULL;
		}

		interpolate(interp_path, PATH_MAX, interpolated_path,
			    interp_table, ARRAY_SIZE(interp_table));
		loginfo("Interpolated dir '%s'", interp_path);

		dir = interp_path;
	}
	else if (base_path) {
		if (*dir != '/') {
			/* Allow only absolute */
			logerror("'%s': Non-absolute path denied (base-path active)", dir);
			return NULL;
		}
		snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
		dir = rpath;
	}

	do {
		path = enter_repo(dir, strict_paths);
		if (path)
			break;

		/*
		 * if we fail and base_path_relaxed is enabled, try without
		 * prefixing the base path
		 */
		if (base_path && base_path_relaxed && !retried_path) {
			dir = itable[INTERP_SLOT_DIR].value;
			retried_path = 1;
			continue;
		}
		break;
	} while (1);

	if (!path) {
		logerror("'%s': unable to chdir or not a git archive", dir);
		return NULL;
	}

	if ( ok_paths && *ok_paths ) {
		char **pp;
		int pathlen = strlen(path);

		/* The validation is done on the paths after enter_repo
		 * appends optional {.git,.git/.git} and friends, but
		 * it does not use getcwd().  So if your /pub is
		 * a symlink to /mnt/pub, you can whitelist /pub and
		 * do not have to say /mnt/pub.
		 * Do not say /pub/.
		 */
		for ( pp = ok_paths ; *pp ; pp++ ) {
			int len = strlen(*pp);
			if (len <= pathlen &&
			    !memcmp(*pp, path, len) &&
			    (path[len] == '\0' ||
			     (!strict_paths && path[len] == '/')))
				return path;
		}
	}
	else {
		/* be backwards compatible */
		if (!strict_paths)
			return path;
	}

	logerror("'%s': not in whitelist", path);
	return NULL;		/* Fallthrough. Deny by default */
}
    void IsoSurfaceMC::addMarchingSquaresTriangles(const Vector3 *corners, const Vector4 *volumeValues, const size_t *indices, const Real maxDistance, MeshBuilder *mb) const
    {
        unsigned char squareIndex = 0;
        Vector4 values[4];

        // Find out the case.
        for (size_t i = 0; i < 4; ++i)
        {
            if (volumeValues)
            {
                values[i] = volumeValues[indices[i]].w;
            }
            else
            {
                values[i] = mSrc->getValueAndGradient(corners[indices[i]]);
            }
            if (values[i].w >= ISO_LEVEL)
            {
                squareIndex |= 1 << i;
            }
        }
    
        // Don't generate triangles if we are completely inside and far enough away from the surface
        if (squareIndex == 15 && values[0].w >= maxDistance && values[1].w >= maxDistance && values[2].w >= maxDistance && values[3].w >= maxDistance)
        {
            return;
        }

        int edge = msEdges[squareIndex];

        // Find the intersection vertices.
        Vector3 intersectionPoints[8];
        Vector3 intersectionNormals[8];
        intersectionPoints[0] = corners[indices[0]];
        intersectionPoints[2] = corners[indices[1]];
        intersectionPoints[4] = corners[indices[2]];
        intersectionPoints[6] = corners[indices[3]];

        Vector4 innerVal = mSrc->getValueAndGradient(intersectionPoints[0]);
        intersectionNormals[0].x = innerVal.x;
        intersectionNormals[0].y = innerVal.y;
        intersectionNormals[0].z = innerVal.z;
        intersectionNormals[0].normalise();
        intersectionNormals[0] *= innerVal.w + (Real)1.0;
        innerVal = mSrc->getValueAndGradient(intersectionPoints[2]);
        intersectionNormals[2].x = innerVal.x;
        intersectionNormals[2].y = innerVal.y;
        intersectionNormals[2].z = innerVal.z;
        intersectionNormals[2].normalise();
        intersectionNormals[2] *= innerVal.w + (Real)1.0;
        innerVal = mSrc->getValueAndGradient(intersectionPoints[4]);
        intersectionNormals[4].x = innerVal.x;
        intersectionNormals[4].y = innerVal.y;
        intersectionNormals[4].z = innerVal.z;
        intersectionNormals[4].normalise();
        intersectionNormals[4] *= innerVal.w + (Real)1.0;
        innerVal = mSrc->getValueAndGradient(intersectionPoints[6]);
        intersectionNormals[6].x = innerVal.x;
        intersectionNormals[6].y = innerVal.y;
        intersectionNormals[6].z = innerVal.z;
        intersectionNormals[6].normalise();
        intersectionNormals[6] *= innerVal.w + (Real)1.0;

        if (edge & 1)
        {
            intersectionPoints[1] = interpolate(corners[indices[0]], corners[indices[1]], values[0], values[1], intersectionNormals[1]);
        }
        if (edge & 2)
        {
            intersectionPoints[3] = interpolate(corners[indices[1]], corners[indices[2]], values[1], values[2], intersectionNormals[3]);
        }
        if (edge & 4)
        {
            intersectionPoints[5] = interpolate(corners[indices[2]], corners[indices[3]], values[2], values[3], intersectionNormals[5]);
        }
        if (edge & 8)
        {
            intersectionPoints[7] = interpolate(corners[indices[3]], corners[indices[0]], values[3], values[0], intersectionNormals[7]);
        }
        
        // Ambigous case handling, 5 = 0 2 and 10 = 1 3
        /*if (squareIndex == 5 || squareIndex == 10)
        {
            Vector3 avg = (corners[indices[0]] + corners[indices[1]] + corners[indices[2]] + corners[indices[3]]) / (Real)4.0;
            // Lets take the alternative.
            if (mSrc->getValue(avg) >= ISO_LEVEL)
            {
                squareIndex = squareIndex == 5 ? 16 : 17;
            }
        }*/

        // Create the triangles according to the table.
        for (int i = 0; mcTriangles[squareIndex][i] != -1; i += 3)
        {
            mb->addTriangle(intersectionPoints[msTriangles[squareIndex][i]], intersectionNormals[msTriangles[squareIndex][i]],
                intersectionPoints[msTriangles[squareIndex][i + 1]], intersectionNormals[msTriangles[squareIndex][i + 1]],
                intersectionPoints[msTriangles[squareIndex][i + 2]], intersectionNormals[msTriangles[squareIndex][i + 2]]);
        }
    }
Beispiel #13
0
void HrtfFilter::ClockProcess (float* leftData, float* rightData, int bufferLength)
{
    float ltmp, rtmp;
    float lLowerDelay, lUpperDelay, rLowerDelay, rUpperDelay;
    float lDelayDifference, rDelayDifference;
    int lrp, lwp, rrp, rwp;
    lrp = leftReadPosition;
    lwp = leftWritePosition;
    rrp = rightReadPosition;
    rwp = rightWritePosition;
    
    // delay pointers
    float* lDelayPointer = delayBuffer.getWritePointer(0);
    float* rDelayPointer = delayBuffer.getWritePointer(1);
    
    // update delays
    if (currentAngle != previousAngle)
    {
        lPreviousDelay = lCurrentDelay;
        rPreviousDelay = rCurrentDelay;
        
        lLowerDelay = hrtfDelay.get(0, (int)currentAngle/10);
        lUpperDelay = hrtfDelay.get(0, (int)(currentAngle/10)+1);
        rLowerDelay = hrtfDelay.get(1, (int)currentAngle/10);
        rUpperDelay = hrtfDelay.get(1, (int)(currentAngle/10)+1);
        
        lCurrentDelay = interpolate(lUpperDelay, lLowerDelay);
        rCurrentDelay = interpolate(rUpperDelay, rLowerDelay);
        
        lDelayDifference = lCurrentDelay - lPreviousDelay;
        rDelayDifference = rCurrentDelay - rPreviousDelay;
    
        lrp -= ((int)lDelayDifference + delayBufferLength) % delayBufferLength;
        
        rrp -= ((int)rDelayDifference + delayBufferLength) % delayBufferLength;
    }
    
    // filter vectors
    float *lLowerHrtf = hrtfBuffer.getFilter(0, (int)currentAngle/10);
    float *rLowerHrtf = hrtfBuffer.getFilter(1, (int)currentAngle/10);
    float *lUpperHrtf = hrtfBuffer.getFilter(0, (int)(currentAngle/10)+1);
    float *rUpperHrtf = hrtfBuffer.getFilter(1, (int)(currentAngle/10)+1);
    int filterLength = hrtfBuffer.getLength();
    
    float *lFilterBuffer = getCoefs(0);
    float *rFilterBuffer = getCoefs(1);
    
    for (int n = 0; n < bufferLength; n++)
    {
        // write input to delay buffers
        lDelayPointer[lwp] = leftData[n];
        rDelayPointer[rwp] = leftData[n];
        
        // filter interpolation
        if (currentAngle != previousAngle)
        {
            if (n < filterLength)
            {
                lFilterBuffer[n] = interpolate(lUpperHrtf[n], lLowerHrtf[n]);
                rFilterBuffer[n] = interpolate(rUpperHrtf[n], rLowerHrtf[n]);
            }
        }
        
        // filtering
        ltmp = 0.0f;
        rtmp = 0.0f;
        for (int i = 0; i < filterLength; i++)
        {
            // left channel
            if (lrp - i < 0)
                ltmp += lDelayPointer[lrp - i + delayBufferLength] * lFilterBuffer[i];
            else
                ltmp += lDelayPointer[lrp - i] * lFilterBuffer[i];
            
            // right channel
            if (rrp - i < 0)
                rtmp += rDelayPointer[rrp - i + delayBufferLength] * rFilterBuffer[i];
            else
                rtmp += rDelayPointer[rrp - i] * rFilterBuffer[i];
        }
        // limiter
        if (ltmp > 1.0f)
            ltmp = 1.0f;
        if (ltmp < -1.0f)
            ltmp = -1.0f;
        if (rtmp > 1.0f)
            rtmp = 1.0f;
        if (rtmp < -1.0f)
            rtmp = -1.0f;
        
        // write output
        leftData[n] = ltmp;
        rightData[n] = rtmp;
        
        // advance pointers
        if (lrp == delayBufferLength)
            lrp = 0;
        else
            ++lrp;
        if (lwp == delayBufferLength)
            lwp = 0;
        else
            ++lwp;
        if (rrp == delayBufferLength)
            rrp = 0;
        else
            ++rrp;
        if (rwp == delayBufferLength)
            rwp = 0;
        else
            ++rwp;
    }
    
    // update delay buffer pointers
    leftReadPosition = lrp;
    leftWritePosition = lwp;
    rightReadPosition = rrp;
    rightWritePosition = rwp;
}
Beispiel #14
0
//---------------------------------------------------------
int main(int argc, char **argv)
{
   TPS<double>         rbf;
   Polinomio<double>   pol;
   Matrix<double>      A,B;
   Vector<double>      x,y,f;
   Vector<double>      lambda,b;
   Vector<double>      xnew,ynew,fnew; 
   double              c=0.01;
   int                 n,ni,m;
 
//make the data in the square [0,1] x [0,1]   
   make_data(0,1,0,1, 21, 21, x, y, ni, n);

//stablish the exponent in: r^beta log(r)
   rbf.set_beta(4);
   
//configure the associate polynomial
// pol.make( data_dimension, degree_pol)
   pol.make(2 , rbf.get_degree_pol());
   
//show the rbf and pol info
   cout<<rbf;
   cout<<pol;
   
//show the number of nodes   
   cout<<endl;
   cout<<"total nodes    N  = "<<n<<endl;
   cout<<"interior nodes ni = "<<ni<<endl;
   cout<<"boundary nodes nf = "<<n-ni<<endl;
   cout<<endl;
   

//get the number of elements in the polynomial base
   m = pol.get_M();
    
//resize the matrices to store the partial derivatives
   A.Resize(n+m,n+m);  A = 0.0;
   B.Resize(n+m,n+m);  B = 0.0;
   
//Recall that this problem has the general form
//   (Uxx+Uyy)   (Pxx+Pyy)   =  f     interior nodes  0..ni 
//     U           P_b       =  g     boundary nodes  ni..n 
//   P^transpose   0         =  0     momentun conditions in P  
//
// P is the polynomial wit size n x m
// P_b is the polynomial working in the boundary nodes, size   nf x m
// Pxx+Pyy  has size  ni x m   
   
//make the matriz derivatives   
   fill_matrix(   "dxx"     , rbf , pol , c , x , y, 0 ,  ni ,  A);
   fill_matrix(   "dyy"     , rbf , pol , c , x , y, 0 ,  ni ,  B);
      
   A = A + B;   //  A <-  Uxx + Uyy
    
//Add the submatriz for the boundary nodes:   U , P_b           boundary nodes  ni..n        
   fill_matrix(   "normal"  , rbf , pol , c , x , y, ni,   n ,  A);
   
//Add the submatriz P^transpose at the end:    P^transpose   
   fill_matrix( "pol_trans" , rbf , pol , c , x , y, n ,  n+m,  A);
     
//resize the vector to store the right_size of the PDE      
   b.Resize(n+m); b = 0.0;
    
//fill with   f  
   for(int i=0;i<ni;i++)
      b(i) = right_side(x(i), y(i));
      
//fill with the boundary condition      
   for(int i=ni;i<n;i++)
      b(i) = boundary_condition(x(i),y(i));
      
//solve the linear system of equations 
   lambda =  gauss(A,b);
    
//make the new data grid    
   int ni2,n2;
   make_data(0,1,0,1, 41, 41, xnew, ynew, ni2, n2);
    
//interpolate on this new data grid (xnew,ynew)     
   fnew = interpolate(rbf,pol,c,lambda,x,y,xnew,ynew);
     
//determine the maximum error
   double e=0.0;
   for(int i=0;i<ni2;i++)
   {
     e = max(e, fabs(fnew(i) - sin(2*M_PI*xnew(i))*cos(2*M_PI*ynew(i)))  );
   }
     
//show the error     
   cout<<endl;
   cout<<"The maximum error: e_max = "<<e<<endl<<endl;
   
//store the interpolated data   
   save_gnu_data("data",xnew,ynew,fnew);
     
  return 0;
}
T SimpleKeyableProperty<T>::get(long double pos) const{
	std::lock_guard<std::recursive_mutex> lock(mMutex);
	return interpolate(pos);
}
Beispiel #16
0
    bool OctreeNodeSplitPolicy::doSplit(OctreeNode *node, const Real geometricError) const
    {

        // We have a highest resolution.
        Vector3 from = node->getFrom();
        Vector3 to = node->getTo();
        if (to.x - from.x <= mMaxCellSize)
        {
            return false;
        }

        // Don't split if nothing is inside.
        Vector4 centerValue = mSrc->getValueAndGradient(node->getCenter());
        if (Math::Abs(centerValue.w) > (to - from).length() * mMinSplitDistanceDiagonalFactor)
        {
            node->setCenterValue(centerValue);
            return false;
        }

        // Error metric of http://www.andrew.cmu.edu/user/jessicaz/publication/meshing/
        Real f000 = mSrc->getValue(from);
        Real f001 = mSrc->getValue(node->getCorner3());
        Real f010 = mSrc->getValue(node->getCorner4());
        Real f011 = mSrc->getValue(node->getCorner7());
        Real f100 = mSrc->getValue(node->getCorner1());
        Real f101 = mSrc->getValue(node->getCorner2());
        Real f110 = mSrc->getValue(node->getCorner5());
        Real f111 = mSrc->getValue(to);
    
        Vector3 gradients[19];
        gradients[9] = Vector3(centerValue.x, centerValue.y, centerValue.z);

        Vector3 positions[19][2] = {
            {node->getCenterBackBottom(), Vector3((Real)0.5, (Real)0.0, (Real)0.0)},
            {node->getCenterLeftBottom(), Vector3((Real)0.0, (Real)0.0, (Real)0.5)},
            {node->getCenterBottom(), Vector3((Real)0.5, (Real)0.0, (Real)0.5)},
            {node->getCenterRightBottom(), Vector3((Real)1.0, (Real)0.0, (Real)0.5)},
            {node->getCenterFrontBottom(), Vector3((Real)0.5, (Real)0.0, (Real)1.0)},

            {node->getCenterBackLeft(), Vector3((Real)0.0, (Real)0.5, (Real)0.0)},
            {node->getCenterBack(), Vector3((Real)0.5, (Real)0.5, (Real)0.0)},
            {node->getCenterBackRight(), Vector3((Real)1.0, (Real)0.5, (Real)0.0)},
            {node->getCenterLeft(), Vector3((Real)0.0, (Real)0.5, (Real)0.5)},
            {node->getCenter(), Vector3((Real)0.5, (Real)0.5, (Real)0.5)},
            {node->getCenterRight(), Vector3((Real)1.0, (Real)0.5, (Real)0.5)},
            {node->getCenterFrontLeft(), Vector3((Real)0.0, (Real)0.5, (Real)1.0)},
            {node->getCenterFront(), Vector3((Real)0.5, (Real)0.5, (Real)1.0)},
            {node->getCenterFrontRight(), Vector3((Real)1.0, (Real)0.5, (Real)1.0)},
        
            {node->getCenterBackTop(), Vector3((Real)0.5, (Real)1.0, (Real)0.0)},
            {node->getCenterLeftTop(), Vector3((Real)0.0, (Real)1.0, (Real)0.5)},
            {node->getCenterTop(), Vector3((Real)0.5, (Real)1.0, (Real)0.5)},
            {node->getCenterRightTop(), Vector3((Real)1.0, (Real)1.0, (Real)0.5)},
            {node->getCenterFrontTop(), Vector3((Real)0.5, (Real)1.0, (Real)1.0)}
        };

    
        Real error = (Real)0.0;
        Real interpolated, gradientMagnitude;
        Vector4 value;
        Vector3 gradient;
        for (size_t i = 0; i < 19; ++i)
        {
            value = mSrc->getValueAndGradient(positions[i][0]);
            gradient.x = value.x;
            gradient.y = value.y;
            gradient.z = value.z;
            interpolated = interpolate(f000, f001, f010, f011, f100, f101, f110, f111, positions[i][1]);
            gradientMagnitude = gradient.length();
            if (gradientMagnitude < FLT_EPSILON)
            {
                gradientMagnitude = (Real)1.0;
            }
            error += Math::Abs(value.w - interpolated) / gradientMagnitude;
            if (error >= geometricError)
            {
                return true;
            }
        }
        node->setCenterValue(centerValue);
        return false;
    }
Beispiel #17
0
    bool  
    AxisRenderable::collideAxis(Ogre::Ray& ray)
    {   
        Ogre::Vector3 dir = getWorldPosition() - ray.getOrigin();
        Ogre::Real mAxisGizmoProjLen = mLength / mViewport->getActualWidth() * dir.length() * Ogre::Math::Tan(mCamera->getFOVy());

        dir.normalise();
        mAxisGizmoSelAxis = -1;

        // find axis to use...
        for(unsigned int  i = 0; i < 3; i++)
        {
            Ogre::Vector3 up, normal;

            up = dir.crossProduct(mAxisGizmoVector[i]);
            normal = up.crossProduct(mAxisGizmoVector[i]);

            if(normal.isZeroLength())
                break;

            Ogre::Plane plane(normal,getWorldPosition());


            // width of the axis poly is 1/10 the run   
            Ogre::Vector3 a = up * mAxisGizmoProjLen / 10;
            Ogre::Vector3 b = mAxisGizmoVector[i] * mAxisGizmoProjLen;

            Ogre::Vector3 poly [] = 
            {
                Ogre::Vector3(getWorldPosition() + a),
                    Ogre::Vector3(getWorldPosition() + a + b),
                    Ogre::Vector3(getWorldPosition() - a + b),
                    Ogre::Vector3(getWorldPosition() - a)
            };

            Ogre::Vector3 end = ray.getPoint(mProjectDistance);
            Ogre::Real t = intersect(&plane,ray.getOrigin(), end);

            if(t >= 0 && t <= 1)
            {
                Ogre::Vector3 pos = interpolate(ray.getOrigin(), end, t);

                // check if inside our 'poly' of this axis vector...
                bool inside = true;
                for(unsigned int  j = 0; inside && (j < 4); j++)
                {
                    unsigned int k = (j+1) % 4;
                    Ogre::Vector3 vec1 = poly[k] - poly[j];
                    Ogre::Vector3 vec2 = pos - poly[k];

                    if(vec1.dotProduct(vec2) >0.f)
                        inside = false;   
                }

                //
                if(inside)
                {
                    mAxisGizmoSelAxis = i;
                    return(true);
                }
            }
        }      

        return(false);
    }
Beispiel #18
0
BSplineCurveForm::BSplineCurveForm(GUIManager& guiManager, QWidget* parent)
	: Form(parent), m_guiManager(guiManager), m_currentPointIndex(-1) {

	QVBoxLayout* layout = new QVBoxLayout();
	this->setLayout(layout);

	m_controlPointInput = new VectorInput( "Next Point", false, true, false, this );
	m_controlPointInput->setValue( hpvec3(0.f, 0.f, 0.f) );
	layout->addWidget(m_controlPointInput);

	QPushButton* addPointButton  = new QPushButton("add control point");
	connect(addPointButton, SIGNAL(clicked()), this, SLOT(addPoint()));
	layout->addWidget(addPointButton);

	QPushButton* deletePointButton  = new QPushButton("delete current point");
	connect(deletePointButton, SIGNAL(clicked()), this, SLOT(deletePoint()));
	layout->addWidget(deletePointButton);

	QPushButton* interpolateButton  = new QPushButton("interpolate control points");
	connect(interpolateButton, SIGNAL(clicked()), this, SLOT(interpolate()));
	layout->addWidget(interpolateButton);

	m_periodicCheckBox = new QCheckBox("Periodic", this);
	m_periodicCheckBox->setCheckState(Qt::Unchecked);
	connect( m_periodicCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changePeriodic(int)) );
	layout->addWidget(m_periodicCheckBox);

	m_uniformCheckBox = new QCheckBox("Uniform", this);
	m_uniformCheckBox->setCheckState(Qt::Unchecked);
	connect( m_uniformCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changeUniform(int)) );
	layout->addWidget(m_uniformCheckBox);

	m_clampedCheckBox = new QCheckBox("Clamped", this);
	m_clampedCheckBox->setCheckState(Qt::Unchecked);
	connect( m_clampedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changeClamped(int)) );
	layout->addWidget(m_clampedCheckBox);

	QWidget* degreeWidget = new QWidget(this);
	m_degreeSpinBox = new QSpinBox(degreeWidget);
	m_degreeSpinBox->setMinimum(1);
	QGridLayout* degreeLayout = new QGridLayout();
	degreeLayout->addWidget( new QLabel("Degree: ", degreeWidget), 0,0 );
	degreeLayout->addWidget( m_degreeSpinBox, 0,1 );
	degreeWidget->setLayout(degreeLayout);
	connect( m_degreeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changeDegree(int)) );
	layout->addWidget(degreeWidget);

	QWidget* planeWidget = new QWidget(this);
	layout->addWidget(planeWidget);
	QGridLayout* planeLayout = new QGridLayout();
	planeWidget->setLayout( planeLayout );
	m_planeLabel = new QLabel("Using standard plane", planeWidget);
	planeLayout->addWidget( m_planeLabel, 0,0 );
	/*
	QPushButton* planeButton = new QPushButton("reset", planeWidget);
	planeLayout->addWidget( planeButton, 0,1 );
	connect( planeButton, SIGNAL(clicked()), this, SLOT(resetPlane()) );
	*/
	// TODO connect to resetPlane() instead of reset()

	QPushButton* createButton  = new QPushButton("create curve");
	connect(createButton, SIGNAL(clicked()), this, SLOT(createCurve()));
	layout->addWidget(createButton);

	QPushButton* resetButton = new QPushButton("reset", this);
	layout->addWidget(resetButton);
	connect( resetButton, SIGNAL(clicked()), this, SLOT(reset()) );

	QWidget* empty = new QWidget();
	empty->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Expanding);
	layout->addWidget(empty);
	
	reset();
}
Beispiel #19
0
  static bool colorize(const drc::map_image_t& iDepthMap,
                       const Eigen::Affine3d& iLocalToCamera,
                       const bot_core::image_t& iImage,
                       const BotCamTrans* iCamTrans,
                       bot_core::image_t& oImage) {
    oImage.utime = iDepthMap.utime;
    oImage.width = iDepthMap.width;
    oImage.height = iDepthMap.height;
    oImage.row_stride = 3*iDepthMap.width;
    oImage.pixelformat = PIXEL_FORMAT_RGB;
    oImage.size = oImage.row_stride * oImage.height;
    oImage.nmetadata = 0;
    oImage.data.resize(oImage.size);

    Eigen::Matrix4d xform;
    for (int i = 0; i < 4; ++i) {
      for (int j = 0; j < 4; ++j) {
        xform(i,j) = iDepthMap.transform[i][j];
      }
    }
    xform = iLocalToCamera.matrix()*xform.inverse();

    for (int i = 0; i < iDepthMap.height; ++i) {
      for (int j = 0; j < iDepthMap.width; ++j) {
        double z;
        if (iDepthMap.format == drc::map_image_t::FORMAT_GRAY_FLOAT32) {
          z = ((float*)(&iDepthMap.data[0] + i*iDepthMap.row_bytes))[j];
          if (z < -1e10) {
            continue;
          }
        }
        else if (iDepthMap.format == drc::map_image_t::FORMAT_GRAY_UINT8) {
          uint8_t val = iDepthMap.data[i*iDepthMap.row_bytes + j];
          if (val == 0) {
            continue;
          }
          z = val;
        }
        else {
          continue;
        }

        Eigen::Vector4d pt = xform*Eigen::Vector4d(j,i,z,1);
        double p[3] = {pt(0)/pt(3),pt(1)/pt(3),pt(2)/pt(3)};
        double pix[3];
        bot_camtrans_project_point(iCamTrans, p, pix);
        if (pix[2] < 0) {
          continue;
        }
        uint8_t r,g,b;
        if (!interpolate(pix[0], pix[1], iImage, r, g, b)) {
          continue;
        }
        int outImageIndex = i*oImage.row_stride + 3*j;
        oImage.data[outImageIndex+0] = r;
        oImage.data[outImageIndex+1] = g;
        oImage.data[outImageIndex+2] = b;
      }
    }

    return true;
  }
Beispiel #20
0
void Interpolate_sV::newTwowayFlow(const QImage &left, const QImage &right,
                                   const FlowField_sV *flowLeftRight, const FlowField_sV *flowRightLeft,
                                   float pos, QImage &output)
{
    const int W = left.width();
    const int H = left.height();


    SourceField_sV leftSourcePixel(flowLeftRight, pos);
    leftSourcePixel.inpaint();
    SourceField_sV rightSourcePixel(flowRightLeft, 1-pos);
    rightSourcePixel.inpaint();

    float aspect = 1 - (.5 + std::cos(M_PI*pos)/2);

#if defined(FIX_FLOW)
    FlowField_sV diffField(flowLeftRight->width(), flowLeftRight->height());
    FlowTools_sV::difference(*flowLeftRight, *flowRightLeft, diffField);
    float diffSum;
    float tmpAspect;
#endif

#ifdef FIX_BORDERS
    bool leftOk;
    bool rightOk;
#endif


    float fx, fy;
    QColor colLeft, colRight;
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {

#ifdef FIX_BORDERS
            fx = leftSourcePixel.at(x,y).fromX;
            fy = leftSourcePixel.at(x,y).fromY;
            if (fx >= 0 && fx < W-1
                    && fy >= 0 && fy < H-1) {
                colLeft = interpolate(left, fx, fy);
                leftOk = true;
            } else {
                fx = leftSourcePixel.at(x,y).fromX;
                fy = leftSourcePixel.at(x,y).fromY;
                fx = CLAMP(fx, 0, W-1.01);
                fy = CLAMP(fy, 0, H-1.01);
                colLeft = interpolate(left, fx, fy);
                leftOk = false;
            }

            fx = rightSourcePixel.at(x,y).fromX;
            fy = rightSourcePixel.at(x,y).fromY;
            if (fx >= 0 && fx < W-1
                    && fy >= 0 && fy < H-1) {
                colRight = interpolate(right, fx, fy);
                rightOk = true;
            } else {
                colRight = qRgb(0,255,0);
                rightOk = false;
            }

            if (leftOk && rightOk) {
                output.setPixel(x,y, blend(colLeft, colRight, aspect).rgba());
            } else if (rightOk) {
                output.setPixel(x,y, colRight.rgba());
//                output.setPixel(x,y, qRgb(255, 0, 0));
            } else if (leftOk) {
                output.setPixel(x,y, colLeft.rgba());
//                output.setPixel(x,y, qRgb(0, 255, 0));
            } else {
                output.setPixel(x,y, colLeft.rgba());
            }
#else
            fx = leftSourcePixel.at(x,y).fromX;
            fy = leftSourcePixel.at(x,y).fromY;
            fx = CLAMP(fx, 0, W-1.01);
            fy = CLAMP(fy, 0, H-1.01);
            colLeft = interpolate(left, fx, fy);

#ifdef FIX_FLOW
            diffSum = diffField.x(fx, fy)+diffField.y(fx, fy);
            if (diffSum > 5) {
                tmpAspect = 0;
            } else if (diffSum < -5) {
                tmpAspect = 1;
            } else {
                tmpAspect = aspect;
            }
#endif

            fx = rightSourcePixel.at(x,y).fromX;
            fy = rightSourcePixel.at(x,y).fromY;
            fx = CLAMP(fx, 0, W-1.01);
            fy = CLAMP(fy, 0, H-1.01);
            colRight = interpolate(right, fx, fy);

#ifdef FIX_FLOW
            diffSum = diffField.x(fx, fy)+diffField.y(fx, fy);
            if (diffSum < 5) {
                tmpAspect = 0;
            } else if (diffSum > -5) {
                tmpAspect = 1;
            }
#endif

#ifdef FIX_FLOW
            output.setPixel(x,y, blend(colLeft, colRight, tmpAspect).rgba());
#else
            output.setPixel(x,y, blend(colLeft, colRight, aspect).rgba());
#endif

#endif
        }
    }
}
Beispiel #21
0
void Node::updateRecursive(const IUpdateThreadContext& updateContext, const glm::mat4& parentTransformMatrix, const VkBool32 parentTransformMatrixDirty, const glm::mat4& parentBindMatrix, const VkBool32 parentBindMatrixDirty, const INodeSP& armatureNode)
{
    transformMatrixDirty = transformMatrixDirty || parentTransformMatrixDirty;

    bindMatrixDirty = bindMatrixDirty || parentBindMatrixDirty;

    auto newArmatureNode = (joints != 0) ? INode::shared_from_this() : armatureNode;

    if (currentAnimation >= 0 && currentAnimation < (int32_t) allAnimations.size())
    {
        currentTime += (float) updateContext.getDeltaTime();

        if (currentTime < allAnimations[currentAnimation]->getStart() || currentTime > allAnimations[currentAnimation]->getStop())
        {
            currentTime = allAnimations[currentAnimation]->getStart();
        }

        const auto& currentChannels = allAnimations[currentAnimation]->getChannels();

        float value;

        //

        quat quaternion;

        VkBool32 quaternionDirty = VK_FALSE;

        //

        for (size_t i = 0; i < currentChannels.size(); i++)
        {
            value = interpolate(currentTime, currentChannels[i]);

            if (currentChannels[i]->getTargetTransform() == VKTS_TARGET_TRANSFORM_TRANSLATE)
            {
                translate[currentChannels[i]->getTargetTransformElement()] = value;
            }
            else if (currentChannels[i]->getTargetTransform() == VKTS_TARGET_TRANSFORM_ROTATE)
            {
                rotate[currentChannels[i]->getTargetTransformElement()] = value;
            }
            else if (currentChannels[i]->getTargetTransform() == VKTS_TARGET_TRANSFORM_QUATERNION_ROTATE)
            {
            	switch (currentChannels[i]->getTargetTransformElement())
            	{
            		case VKTS_TARGET_TRANSFORM_ELEMENT_X:
            			quaternion.x = value;
            			break;
            		case VKTS_TARGET_TRANSFORM_ELEMENT_Y:
            			quaternion.y = value;
            			break;
            		case VKTS_TARGET_TRANSFORM_ELEMENT_Z:
            			quaternion.z = value;
            			break;
            		case VKTS_TARGET_TRANSFORM_ELEMENT_W:
            			quaternion.w = value;
            			break;
            	}

                quaternionDirty = VK_TRUE;
            }
            else if (currentChannels[i]->getTargetTransform() == VKTS_TARGET_TRANSFORM_SCALE)
            {
                scale[currentChannels[i]->getTargetTransformElement()] = value;
            }
        }

        if (quaternionDirty)
        {
        	rotate = quaternion.rotation();
        }

        //

        transformMatrixDirty = VK_TRUE;
    }

    //

    if (bindMatrixDirty)
    {
    	// Only armature, having joints not zero and joints can enter here.

    	glm::mat4 localBindMatrix;

    	if (joints == 0)
    	{
    		localBindMatrix = translateMat4(bindTranslate.x, bindTranslate.y, bindTranslate.z) * rotateRzRyRxMat4(bindRotate.z, bindRotate.y, bindRotate.x) * scaleMat4(bindScale.x, bindScale.y, bindScale.z);
    	}
    	else
    	{
    		// Armature has no bind values, but transform is taken into account.

    		localBindMatrix = translateMat4(translate.x, translate.y, translate.z) * rotateRzRyRxMat4(rotate.z, rotate.y, rotate.x) * scaleMat4(scale.x, scale.y, scale.z);
    	}

		this->bindMatrix = parentBindMatrix * localBindMatrix;

        this->inverseBindMatrix = glm::inverse(this->bindMatrix);

        //

        transformMatrixDirty = VK_TRUE;
    }

    //

    if (transformMatrixDirty)
    {
        if (jointIndex == -1)
        {
        	this->transformMatrix = translateMat4(translate.x, translate.y, translate.z) * rotateRzRyRxMat4(rotate.z, rotate.y, rotate.x) * scaleMat4(scale.x, scale.y, scale.z);

        	// Only use parent transform, if this is not an armature.
        	if (joints == 0)
        	{
        		this->transformMatrix = parentTransformMatrix * this->transformMatrix;
        	}
        }
        else
        {
        	// Processing joints.

        	this->transformMatrix = bindMatrix * translateMat4(translate.x, translate.y, translate.z) * rotateRzRyRxMat4(rotate.z, rotate.y, rotate.x) * scaleMat4(scale.x, scale.y, scale.z) * this->inverseBindMatrix;

        	// Only use parent transform, if parent is not an armature.
        	if (parentNode.get() && parentNode->getNumberJoints() == 0)
        	{
        		this->transformMatrix = parentTransformMatrix * this->transformMatrix;
        	}
        }

        // Update buffer.
        if (allMeshes.size() > 0)
        {
            transformUniformBuffer->upload(0, 0, this->transformMatrix);

            auto transformNormalMatrix = glm::transpose(glm::inverse(glm::mat3(this->transformMatrix)));

            transformUniformBuffer->upload(sizeof(float) * 16, 0, transformNormalMatrix);
        }
        else if (joints != 0)
        {
        	// If this is an armature, store the parent matrix.
        	// This allows to modify the parent matrices without recalculating the bind matrices.

			jointsUniformBuffer->upload(0, 0, parentTransformMatrix);

            auto transformNormalMatrix = glm::transpose(glm::inverse(glm::mat3(parentTransformMatrix)));

            jointsUniformBuffer->upload(sizeof(float) * 16, 0, transformNormalMatrix);
        }
        else if (jointIndex >= 0 && jointIndex < VKTS_MAX_JOINTS)
        {
        	if (newArmatureNode.get())
        	{
        		auto currentJointsUniformBuffer = newArmatureNode->getJointsUniformBuffer();

        		if (currentJointsUniformBuffer.get())
        		{
        			// Upload the joint matrices to blend them on the GPU.

        			size_t offset = sizeof(float) * 16 + sizeof(float) * 12;

        			currentJointsUniformBuffer->upload(offset + jointIndex * sizeof(float) * 16, 0, this->transformMatrix);

                    auto transformNormalMatrix = glm::transpose(glm::inverse(glm::mat3(this->transformMatrix)));

        			currentJointsUniformBuffer->upload(offset + VKTS_MAX_JOINTS * sizeof(float) * 16 + jointIndex * sizeof(float) * 12, 0, transformNormalMatrix);
        		}
        	}
        }
    }

    for (size_t i = 0; i < allChildNodes.size(); i++)
    {
        allChildNodes[i]->updateRecursive(updateContext, this->transformMatrix, this->transformMatrixDirty, this->bindMatrix, this->bindMatrixDirty, newArmatureNode);
    }

    //

    transformMatrixDirty = VK_FALSE;

    bindMatrixDirty = VK_FALSE;
}
Beispiel #22
0
/**
  \todo fix bézier interpolation
  \code
      C prev
     /   /
    /   /
   /   /
  A curr
   \
    \
     B next (can be NULL)
  \endcode
  */
void Interpolate_sV::bezierFlow(const QImage &prev, const QImage &right, const FlowField_sV *flowPrevCurr, const FlowField_sV *flowCurrNext, float pos, QImage &output)
{
    const float Wmax = prev.width()-1.0001;
    const float Hmax = prev.height()-1.0001;

    Vector_sV a, b, c;
    Vector_sV Ta, Sa;
    float dist;

    QColor colOut;

    for (int y = 0; y < prev.height(); y++) {
        for (int x = 0; x < prev.width(); x++) {

            a = Vector_sV(x, y);
            // WHY minus?
            c = a + Vector_sV(flowPrevCurr->x(x, y), flowPrevCurr->y(x, y));
            if (flowCurrNext != NULL) {
                b = a + Vector_sV(flowCurrNext->x(x,y), flowCurrNext->y(x,y));
            } else {
                b = a;
            }

            dist = (b-a).length() + (c-a).length();
            if (dist > 0) {
                Ta = b + ( (b-a).length() / dist ) * (c-b);
                Sa = (Ta - a).rotate90();
                Sa = a + Sa;

            } else {
                Sa = a;
            }
#ifdef DEBUG_I
            Sa = a;
#endif

            QPointF position = BezierTools_sV::interpolate(pos, c.toQPointF(), c.toQPointF(), Sa.toQPointF(), a.toQPointF());
            position.rx() = x - pos*flowPrevCurr->x(x,y);
            position.ry() = y - pos*flowPrevCurr->y(x,y);
            position.rx() = CLAMP(position.x(), 0, Wmax);
            position.ry() = CLAMP(position.y(), 0, Hmax);

#ifdef DEBUG_I
//            if (x == 100 && y == 100 && false) {
//                qDebug() << "Interpolated from " << toString(c.toQPointF()) << ", " << toString(a.toQPointF()) << ", "
//                         << toString(b.toQPointF()) << " at " << pos << ": " << toString(position);
//            }
            if (y % 4 == 0) {
                position.rx() = x;
                position.ry() = y;
            }
#endif

            colOut = interpolate(prev, position.x(), position.y());

#ifdef DEBUG_I
            if (y % 4 == 1 && x % 2 == 0) {
                colOut = right.pixel(x, y);
            }
#endif
            output.setPixel(x,y, colOut.rgb());

        }
    }

    /*
    for (int y = 0; y < prev.height(); y++) {
        for (int x = 1; x < prev.width()-1; x++) {
            if (qAlpha(output.pixel(x,y)) == 0
                    && qAlpha(output.pixel(x-1,y)) > 0
                    && qAlpha(output.pixel(x+1,y)) > 0) {
                output.setPixel(x,y, qRgba(
                                    (qRed(output.pixel(x-1,y)) + qRed(output.pixel(x+1,y)))/2,
                                    (qGreen(output.pixel(x-1,y)) + qGreen(output.pixel(x+1,y)))/2,
                                    (qBlue(output.pixel(x-1,y)) + qBlue(output.pixel(x+1,y)))/2,
                                    (qAlpha(output.pixel(x-1,y)) + qAlpha(output.pixel(x+1,y)))/2
                                    ));
            }
        }
    }
    for (int x = 0; x < prev.width(); x++) {
        for (int y = 1; y < prev.height()-1; y++) {
            if (qAlpha(output.pixel(x,y)) == 0
                    && qAlpha(output.pixel(x,y-1)) > 0
                    && qAlpha(output.pixel(x,y+1)) > 0) {
                output.setPixel(x,y, qRgba(
                                    (qRed(output.pixel(x,y-1)) + qRed(output.pixel(x,y+1)))/2,
                                    (qGreen(output.pixel(x,y-1)) + qGreen(output.pixel(x,y+1)))/2,
                                    (qBlue(output.pixel(x,y-1)) + qBlue(output.pixel(x,y+1)))/2,
                                    (qAlpha(output.pixel(x,y-1)) + qAlpha(output.pixel(x,y+1)))/2
                                    ));
            }
        }
    }
    */
}
Beispiel #23
0
/** Updates the rubber ball.
 *  \param dt Time step size.
 *  \returns True if the rubber ball should be removed.
 */
bool RubberBall::updateAndDelete(float dt)
{
    LinearWorld *world = dynamic_cast<LinearWorld*>(World::getWorld());
    // FIXME: what does the rubber ball do in case of battle mode??
    if(!world) return true;

    if(m_delete_timer>0)
    {
        m_delete_timer -= dt;
        if(m_delete_timer<=0)
        {
            hit(NULL);
#ifdef PRINT_BALL_REMOVE_INFO
            Log::debug("[RubberBall]", "ball %d deleted.", m_id);
#endif
            return true;
        }
    }

    // Update the target in case that the first kart was overtaken (or has
    // finished the race).
    computeTarget();
    updateDistanceToTarget();

    // Determine the new position. This new position is only temporary,
    // since it still needs to be adjusted for the height of the terrain.
    Vec3 next_xyz;
    if(m_aiming_at_target)
        moveTowardsTarget(&next_xyz, dt);
    else
        interpolate(&next_xyz, dt);

    // If the ball is close to the ground, we have to start the raycast
    // slightly higher (to avoid that the ball tunnels through the floor).
    // But if the ball is close to the ceiling of a tunnel and we would
    // start the raycast slightly higher, the ball might end up on top
    // of the ceiling.
    // The ball is considered close to the ground if the height above the
    // terrain is less than half the current maximum height.
    bool close_to_ground = 2.0*m_previous_height < m_current_max_height;

    float vertical_offset = close_to_ground ? 4.0f : 2.0f;
    // Note that at this stage getHoT still reports the height at
    // the previous location (since TerrainInfo wasn't updated). On
    // the other hand, we can't update TerrainInfo without having
    // at least a good estimation of the height.
    next_xyz.setY(getHoT() + vertical_offset);
    // Update height of terrain (which isn't done as part of
    // Flyable::update for rubber balls.
    TerrainInfo::update(next_xyz);

    m_height_timer += dt;
    float height    = updateHeight()+m_extend.getY()*0.5f;
    float new_y     = getHoT()+height;

    if(UserConfigParams::logFlyable())
        Log::debug("[RubberBall]", "ball %d: %f %f %f height %f new_y %f gethot %f ",
                m_id, next_xyz.getX(), next_xyz.getY(), next_xyz.getZ(), height, new_y, getHoT());

    // No need to check for terrain height if the ball is low to the ground
    if(height > 0.5f)
    {
        float terrain_height = getMaxTerrainHeight(vertical_offset)
                             - m_extend.getY();
        if(new_y>terrain_height)
            new_y = terrain_height;
    }

    if(UserConfigParams::logFlyable())
        Log::verbose("RubberBall", "newy2 %f gmth %f", new_y,
                     getMaxTerrainHeight(vertical_offset));

    next_xyz.setY(new_y);
    m_previous_xyz = getXYZ();
    m_previous_height = next_xyz.getY()-getHoT();
    setXYZ(next_xyz);

    if(checkTunneling())
        return true;

    // Determine new distance along track
    TrackSector::update(next_xyz);

    // Ball squashing:
    // ===============
    if(height<1.5f*m_extend.getY())
        m_node->setScale(core::vector3df(1.0f, height/m_extend.getY(),1.0f));
    else
        m_node->setScale(core::vector3df(1.0f, 1.0f, 1.0f));

    return Flyable::updateAndDelete(dt);
}   // updateAndDelete
Beispiel #24
0
// generate the interpolated vertices required for triangle construction
std::vector<Point> MarchingCubes::interpolated_vertices(const Octnode* node, unsigned int edges) {
    std::vector<Point> vertices(12);
    vertices[0] = *(node->vertex[0]); // intialize these to the node-vertex positions (?why?)
    vertices[1] = *(node->vertex[1]);
    vertices[2] = *(node->vertex[2]);
    vertices[3] = *(node->vertex[3]);
    vertices[4] = *(node->vertex[4]);
    vertices[5] = *(node->vertex[5]);
    vertices[6] = *(node->vertex[6]);
    vertices[7] = *(node->vertex[7]);
    if ( edges & 1 )
        vertices[0] = interpolate( node, 0 , 1 );
    if ( edges & 2 )
        vertices[1] = interpolate( node, 1 , 2 );
    if ( edges & 4 )
        vertices[2] = interpolate( node, 2 , 3 );
    if ( edges & 8 )
        vertices[3] = interpolate( node, 3 , 0 );
    if ( edges & 16 )
        vertices[4] = interpolate( node, 4 , 5 );
    if ( edges & 32 )
        vertices[5] = interpolate( node, 5 , 6 );
    if ( edges & 64 )
        vertices[6] = interpolate( node, 6 , 7 );
    if ( edges & 128 )
        vertices[7] = interpolate( node, 7 , 4 );
    if ( edges & 256 )
        vertices[8] = interpolate( node, 0 , 4 );
    if ( edges & 512 )
        vertices[9] = interpolate( node, 1 , 5 );
    if ( edges & 1024 )
        vertices[10] = interpolate( node, 2 , 6 );
    if ( edges & 2048 )
        vertices[11] = interpolate( node, 3 , 7 );
    return vertices;
}
Beispiel #25
0
bool SkApply::enable(SkAnimateMaker& maker) {
    fEnabled = true;
    bool initialized = fActive != nullptr;
    if (dynamicScope.size() > 0)
        enableDynamic(maker);
    if (maker.fError.hasError())
        return false;
    int animators = fAnimators.count();
    int index;
    for (index = 0; index < animators; index++) {
        SkAnimateBase* animator = fAnimators[index];
        animator->fStart = maker.fEnableTime;
        animator->fResetPending = animator->fReset;
    }
    if (scope && scope->isApply())
        ((SkApply*) scope)->setEmbedded();
/*  if (mode == kMode_once) {
        if (scope) {
            activate(maker);
            interpolate(maker, maker.fEnableTime);
            inactivate(maker);
        }
        return true;
    }*/
    if ((mode == kMode_immediate || mode == kMode_create) && scope == nullptr)
        return false;   // !!! error?
    bool enableMe = scope && (scope->hasEnable() || scope->isApply() || scope->isDrawable() == false);
    if ((mode == kMode_immediate && enableMe) || mode == kMode_create)
        activate(maker);    // for non-drawables like post, prime them here
    if (mode == kMode_immediate && enableMe)
        fActive->enable();
    if (mode == kMode_create && scope != nullptr) {
        enableCreate(maker);
        return true;
    }
    if (mode == kMode_immediate) {
        return scope->isApply() || scope->isDrawable() == false;
    }
    refresh(maker);
    SkDisplayList& displayList = maker.fDisplayList;
    SkADrawable* drawable;
#if defined SK_DEBUG && defined SK_DEBUG_ANIMATION_TIMING
    SkString debugOut;
    SkMSec time = maker.getAppTime();
    debugOut.appendS32(time - maker.fDebugTimeBase);
    debugOut.append(" apply enable id=");
    debugOut.append(_id);
    debugOut.append("; start=");
    debugOut.appendS32(maker.fEnableTime - maker.fDebugTimeBase);
    SkDebugf("%s\n", debugOut.c_str());
#endif
    if (scope == nullptr || scope->isApply() || scope->getType() == SkType_Movie || scope->isDrawable() == false) {
        activate(maker);    // for non-drawables like post, prime them here
        if (initialized) {
            append(this);
        }
        fEnabling = true;
        interpolate(maker, maker.fEnableTime);
        fEnabling = false;
        if (scope != nullptr && dontDraw == false)
            scope->enable(maker);
        return true;
    } else if (initialized && restore == false)
        append(this);
#if 0
    bool wasActive = inactivate(maker); // start fresh
    if (wasActive) {
        activate(maker);
        interpolate(maker, maker.fEnableTime);
        return true;
    }
#endif
//  start here;
    // now that one apply might embed another, only the parent apply should replace the scope
    // or get appended to the display list
    // similarly, an apply added by an add immediate has already been located in the display list
    // and should not get moved or added again here
    if (fEmbedded) {
        return false;   // already added to display list by embedder
    }
    drawable = (SkADrawable*) scope;
    SkTDDrawableArray* parentList;
    SkTDDrawableArray* grandList;
    SkGroup* parentGroup;
    SkGroup* thisGroup;
    int old = displayList.findGroup(drawable, &parentList, &parentGroup, &thisGroup, &grandList);
    if (old < 0)
        goto append;
    else if (fContainsScope) {
        if ((*parentList)[old] != this || restore) {
append:
            if (parentGroup)
                parentGroup->markCopySize(old);
            if (parentList->count() < 10000) {
                fAppended = true;
                *parentList->append() = this;
            } else
                maker.setErrorCode(SkDisplayXMLParserError::kDisplayTreeTooDeep);
            old = -1;
        } else
            reset();
    } else {
        SkASSERT(old < parentList->count());
        if ((*parentList)[old]->isApply()) {
            SkApply* apply = (SkApply*) (*parentList)[old];
            if (apply != this && apply->fActive == nullptr)
                apply->activate(maker);
            apply->append(this);
            parentGroup = nullptr;
        } else {
            if (parentGroup)
                parentGroup->markCopySize(old);
            SkADrawable** newApplyLocation = &(*parentList)[old];
            SkGroup* pGroup;
            int oldApply = displayList.findGroup(this, &parentList, &pGroup, &thisGroup, &grandList);
            if (oldApply >= 0) {
                (*parentList)[oldApply] = (SkADrawable*) SkDisplayType::CreateInstance(&maker, SkType_Apply);
                parentGroup = nullptr;
                fDeleteScope = true;
            }
            *newApplyLocation = this;
        }
    }
    if (parentGroup) {
        parentGroup->markCopySet(old);
        fDeleteScope = dynamicScope.size() == 0;
    }
    return true;
}
Beispiel #26
0
void ofxClouds::setup() {
    
    // we need GL_TEXTURE_2D for our models coords.
    ofDisableArbTex();
    
    ofPixels pixels,comp;
        
    comp.allocate(TEXTURE_SIZE, TEXTURE_SIZE, OF_IMAGE_GRAYSCALE);
    pixels.allocate(TEXTURE_SIZE, TEXTURE_SIZE, OF_IMAGE_COLOR_ALPHA);
    
    for(int i=0; i<TEXTURE_MEMORY_SIZE*4; i++ ) {
        pixels[i] = 0;
    }
    
    for (int j=0; j<4; j++) {
        for(int i=0; i<TEXTURE_MEMORY_SIZE; i++ ) {
           comp[i] = rand()&255;
        }
        
        interpolate(comp.getPixels(), 1 << (j*2+1));
        
        for(int i=0; i<TEXTURE_MEMORY_SIZE; i++ ) {
            pixels[i*4+j] = comp[i];
        }
        
    }
    
    
    
    fbm.allocate(pixels.getWidth(), pixels.getHeight(), ofGetGlInternalFormat(pixels));
    fbm.loadData(pixels);
    
    glBindTexture(GL_TEXTURE_2D, fbm.getTextureData().textureID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    
    ofEnableAlphaBlending();
    
	shader.load("shaders/clouds.vert", "shaders/clouds.frag");
	

    shader.begin();
    
    shader.setUniform2f("resolution", fbm.getWidth(),fbm.getHeight());
    shader.setUniformTexture("tex0", fbm, 0); 
    
    shader.setUniform2f("d0", 0.0f,2.5f);
    shader.setUniform2f("d1", 3.0f,0.0f);
    shader.setUniform2f("d2", -3.5f,0.0f);
    shader.setUniform2f("d3", 0.0f,4.0f);
    
    float a=0.2;
    float b=0.8;
    
    shader.setUniform1f("c", -a/(b-a));
    shader.setUniform1f("d", (1-a)/(b-a));
    
    shader.setUniform3f("color0", 0.7f,0.7f,0.7f);
    shader.setUniform3f("color1", 1.0f,1.0f,1.0f);
    
    shader.end();
    
    
	
    
}
Beispiel #27
0
void detail::evaluateTetra(K3DTree<size_t, float> &vertexTree, IndexBufferRAM *indexBuffer,
                           std::vector<vec3> &positions, std::vector<vec3> &normals,
                           const glm::vec3 &p0, const double &v0, const glm::vec3 &p1,
                           const double &v1, const glm::vec3 &p2, const double &v2,
                           const glm::vec3 &p3, const double &v3) {
    int index = 0;
    if (v0 >= 0) index += 1;
    if (v1 >= 0) index += 2;
    if (v2 >= 0) index += 4;
    if (v3 >= 0) index += 8;
    glm::vec3 a, b, c, d;
    if (index == 0 || index == 15) return;
    if (index == 1 || index == 14) {
        a = interpolate(p0, v0, p2, v2);
        b = interpolate(p0, v0, p1, v1);
        c = interpolate(p0, v0, p3, v3);
        if (index == 1) {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, c);
        } else {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, c, b);
        }
    } else if (index == 2 || index == 13) {
        a = interpolate(p1, v1, p0, v0);
        b = interpolate(p1, v1, p2, v2);
        c = interpolate(p1, v1, p3, v3);
        if (index == 2) {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, c);
        } else {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, c, b);
        }

    } else if (index == 4 || index == 11) {
        a = interpolate(p2, v2, p0, v0);
        b = interpolate(p2, v2, p1, v1);
        c = interpolate(p2, v2, p3, v3);
        if (index == 4) {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, c, b);
        } else {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, c);
        }
    } else if (index == 7 || index == 8) {
        a = interpolate(p3, v3, p0, v0);
        b = interpolate(p3, v3, p2, v2);
        c = interpolate(p3, v3, p1, v1);
        if (index == 7) {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, c);
        } else {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, c, b);
        }
    } else if (index == 3 || index == 12) {
        a = interpolate(p0, v0, p2, v2);
        b = interpolate(p1, v1, p3, v3);
        c = interpolate(p0, v0, p3, v3);
        d = interpolate(p1, v1, p2, v2);

        if (index == 3) {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, c);
            addTriangle(vertexTree, indexBuffer, positions, normals, a, d, b);
        } else {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, c, b);
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, d);
        }

    } else if (index == 5 || index == 10) {
        a = interpolate(p2, v2, p3, v3);
        b = interpolate(p0, v0, p1, v1);
        c = interpolate(p0, v0, p3, v3);
        d = interpolate(p1, v1, p2, v2);

        if (index == 5) {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, c);
            addTriangle(vertexTree, indexBuffer, positions, normals, a, d, b);
        } else {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, c, b);
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, d);
        }

    } else if (index == 6 || index == 9) {
        a = interpolate(p1, v1, p3, v3);
        b = interpolate(p0, v0, p2, v2);
        c = interpolate(p0, v0, p1, v1);
        d = interpolate(p2, v2, p3, v3);

        if (index == 6) {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, c, b);
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, d);
        } else {
            addTriangle(vertexTree, indexBuffer, positions, normals, a, b, c);
            addTriangle(vertexTree, indexBuffer, positions, normals, a, d, b);
        }
    }
}
const char *SimpleKeyableProperty<T>::getString(long double pos) const{
	std::lock_guard<std::recursive_mutex> lock(mMutex);
	return to_chararray(interpolate(pos));
}
Beispiel #29
0
void beat_points_update(int pulse)
{
	CHAR_DATA *i, *next_char;
	int restore;

	if (!UPDATE_PC_ON_BEAT)
		return;

	// only for PC's
	for (i = character_list; i; i = next_char)
	{
		next_char = i->next;
		if (IS_NPC(i))
			continue;

		if (IN_ROOM(i) == NOWHERE)
		{
			log("SYSERR: Pulse character in NOWHERE.");
			continue;
		}

		if (RENTABLE(i) <= time(NULL))
		{
			RENTABLE(i) = 0;
			AGRESSOR(i) = 0;
			AGRO(i) = 0;
			i->agrobd = false;
		}
		if (AGRO(i) < time(NULL))
			AGRO(i) = 0;
		beat_punish(i);

// This line is used only to control all situations when someone is
// dead (POS_DEAD). You can comment it to minimize heartbeat function
// working time, if you're sure, that you control these situations
// everywhere. To the time of this code revision I've fix some of them
// and haven't seen any other.
//             if (GET_POS(i) == POS_DEAD)
//                     die(i, NULL);

		if (GET_POS(i) < POS_STUNNED)
			continue;

		// Restore hitpoints
		restore = hit_gain(i);
		restore = interpolate(restore, pulse);

		if (AFF_FLAGGED(i, AFF_BANDAGE))
		{
			AFFECT_DATA* aff;
			for(aff = i->affected; aff; aff = aff->next)
			{
				if (aff->type == SPELL_BANDAGE)
				{
					restore += MIN(GET_REAL_MAX_HIT(i) / 10, aff->modifier);
					break;
				}
			}
		}

		if (GET_HIT(i) < GET_REAL_MAX_HIT(i))
			GET_HIT(i) = MIN(GET_HIT(i) + restore, GET_REAL_MAX_HIT(i));

		// Проверка аффекта !исступление!. Поместил именно здесь,
		// но если кто найдет более подходящее место переносите =)
		//Gorrah: перенес в handler::affect_total
		//check_berserk(i);

		// Restore PC caster mem
		if (!IS_MANA_CASTER(i) && !MEMQUEUE_EMPTY(i))
		{
			restore = mana_gain(i);
			restore = interpolate(restore, pulse);
			GET_MEM_COMPLETED(i) += restore;

	if (AFF_FLAGGED(i, AFF_RECALL_SPELLS))
		handle_recall_spells(i);

			while (GET_MEM_COMPLETED(i) > GET_MEM_CURRENT(i)
					&& !MEMQUEUE_EMPTY(i))
			{
				int spellnum;
				spellnum = MemQ_learn(i);
				GET_SPELL_MEM(i, spellnum)++;
				GET_CASTER(i) += spell_info[spellnum].danger;
			}

			if (MEMQUEUE_EMPTY(i))
			{
				if (GET_RELIGION(i) == RELIGION_MONO)
				{
					send_to_char
					("Наконец ваши занятия окончены. Вы с улыбкой захлопнули свой часослов.\r\n",
					 i);
					act("Окончив занятия, $n с улыбкой захлопнул$g часослов.",
						FALSE, i, 0, 0, TO_ROOM);
				}
				else
				{
					send_to_char
					("Наконец ваши занятия окончены. Вы с улыбкой убрали свои резы.\r\n", i);
					act("Окончив занятия, $n с улыбкой убрал$g резы.", FALSE, i, 0, 0, TO_ROOM);
				}
			}
		}

		if (!IS_MANA_CASTER(i) && MEMQUEUE_EMPTY(i))
		{
			GET_MEM_TOTAL(i) = 0;
			GET_MEM_COMPLETED(i) = 0;
		}

		// Гейн маны у волхвов
		if (IS_MANA_CASTER(i) && GET_MANA_STORED(i) < GET_MAX_MANA(i))
		{
			GET_MANA_STORED(i) += mana_gain(i);
			if (GET_MANA_STORED(i) >= GET_MAX_MANA(i))
			{
				GET_MANA_STORED(i) = GET_MAX_MANA(i);
				send_to_char("Ваша магическая энергия полностью восстановилась\r\n", i);
			}
		}
		if (IS_MANA_CASTER(i) && GET_MANA_STORED(i) > GET_MAX_MANA(i))
		{
			GET_MANA_STORED(i) = GET_MAX_MANA(i);
		}
		// Restore moves
		restore = move_gain(i);
		restore = interpolate(restore, pulse);
//		GET_MOVE(i) = MIN(GET_MOVE(i) + restore, GET_REAL_MAX_MOVE(i));
//MZ.overflow_fix
		if (GET_MOVE(i) < GET_REAL_MAX_MOVE(i))
			GET_MOVE(i) = MIN(GET_MOVE(i) + restore, GET_REAL_MAX_MOVE(i));
//-MZ.overflow_fix
	}
}
Beispiel #30
0
/**************************************************************
 * ar5416GetTargetPowersLeg
 *
 * Return the four rates of target power for the given target power table
 * channel, and number of channels
 */
void
ar5416GetTargetPowersLeg(struct ath_hal *ah,
    HAL_CHANNEL_INTERNAL *chan,
    CAL_TARGET_POWER_LEG *powInfo, u_int16_t numChannels,
    CAL_TARGET_POWER_LEG *pNewPower, u_int16_t numRates,
    HAL_BOOL isExtTarget)
{
    u_int16_t clo, chi;
    int i;
    int matchIndex = -1, lowIndex = -1;
    u_int16_t freq;
    CHAN_CENTERS centers;

    ar5416GetChannelCenters(ah, chan, &centers);
    freq = (isExtTarget) ? centers.ext_center : centers.ctl_center;

    /* Copy the target powers into the temp channel list */
    if (freq <= fbin2freq(powInfo[0].bChannel, IS_CHAN_2GHZ(chan)))
    {
        matchIndex = 0;
    }
    else
    {
        for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++)
        {
            if (freq == fbin2freq(powInfo[i].bChannel, IS_CHAN_2GHZ(chan)))
            {
                matchIndex = i;
                break;
            }
            else if ((freq < fbin2freq(powInfo[i].bChannel, IS_CHAN_2GHZ(chan))) &&
                (freq > fbin2freq(powInfo[i - 1].bChannel, IS_CHAN_2GHZ(chan))))
            {
                lowIndex = i - 1;
                break;
            }
        }
        if ((matchIndex == -1) && (lowIndex == -1))
        {
            HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IS_CHAN_2GHZ(chan)));
            matchIndex = i - 1;
        }
    }

    if (matchIndex != -1)
    {
        *pNewPower = powInfo[matchIndex];
    }
    else
    {
        HALASSERT(lowIndex != -1);
        /*
        * Get the lower and upper channels, target powers,
        * and interpolate between them.
        */
        clo = fbin2freq(powInfo[lowIndex].bChannel, IS_CHAN_2GHZ(chan));
        chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IS_CHAN_2GHZ(chan));

        for (i = 0; i < numRates; i++)
        {
            pNewPower->tPow2x[i] = (u_int8_t)interpolate(freq, clo, chi,
                powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
        }
    }
}