int RemoveHighestPriority(Heap *interval_heap) { int value_removed; if(IntervalHeapIsEmpty(*interval_heap)) { printf("Fila vazia!\n"); return -1; } else if ((*interval_heap).node[0].min == -1) { value_removed = RemoveMaximum(&(*interval_heap), 0); } else if ((*interval_heap).node[0].max == -1) { value_removed = RemoveMinimum(&(*interval_heap), 0); } else { int final_node_position = (*interval_heap).size - 1; // Remove o valor mínimo da raiz. value_removed = RemoveMaximum(&(*interval_heap), 0); // Reinsere o valor do último nó na raiz. if((*interval_heap).node[final_node_position].max == -1) { SwapValues(&(*interval_heap).node[final_node_position].min, &(*interval_heap).node[0].max); } else { SwapValues(&(*interval_heap).node[final_node_position].max, &(*interval_heap).node[0].max); } DownwardsMax(&(*interval_heap), 0); } (*interval_heap).number_of_elements -= 1; if((*interval_heap).number_of_elements % 2 == 0) { (*interval_heap).size -= 1; } return value_removed; }
/* ======================== idJointBuffer::Swap ======================== */ void idJointBuffer::Swap( idJointBuffer & other ) { // Make sure the ownership of the buffer is not transferred to an unintended place. assert( other.OwnsBuffer() == OwnsBuffer() ); SwapValues( other.numJoints, numJoints ); SwapValues( other.offsetInOtherBuffer, offsetInOtherBuffer ); SwapValues( other.apiObject, apiObject ); }
char BoundingBox::intersect(const Ray &ray, float *hitt0, float *hitt1) const { float t0 = ray.m_tmin, t1 = ray.m_tmax; for (int i = 0; i < 3; ++i) { const float diri = ray.m_dir.comp(i); const Vector3F o = ray.m_origin; if(IsValueNearZero(diri)) { if(i == 0) { if(o.x < m_data[0] || o.x > m_data[3]) return 0; } else if(i == 1) { if(o.y < m_data[1] || o.y > m_data[4]) return 0; } else { if(o.z < m_data[2] || o.z > m_data[5]) return 0; } continue; } // Update interval for _i_th bounding box slab float invRayDir = 1.f / ray.m_dir.comp(i); float tNear = (getMin(i) - ray.m_origin.comp(i)) * invRayDir; float tFar = (getMax(i) - ray.m_origin.comp(i)) * invRayDir; // Update parametric interval from slab intersection $t$s if (tNear > tFar) SwapValues(tNear, tFar); t0 = tNear > t0 ? tNear : t0; t1 = tFar < t1 ? tFar : t1; if (t0 > t1) return 0; } if (hitt0) *hitt0 = t0; if (hitt1) *hitt1 = t1; return 1; }
// Tendo o pai como referência, o mesmo é comparado com seus filhos e trocado // caso a sua prioridade seja maior que a de um deles. void DownwardsMin(Heap *intervals, int position) { //Assume que o filho de menor valor é o da esquerda. int lowest_son_position = 2*position+1; bool stop = false; // Enquanto o vetor ainda estiver sendo percorrido e o pai // não ser menor que ambos seus filhos... while((!stop) && (lowest_son_position < (*intervals).size)) { // Caso os filhos da direita e esquerda existirem e o valor atual do // filho de menor valor for maior que o do irmão, significa que a // posição do filho de menor valor é a posição do irmão. int father_value = (*intervals).node[position].min; if(BrotherHasLowerValue((*intervals), lowest_son_position)){ lowest_son_position += 1; // Garante que o valor a ser utilizado é o correto. AssignValues(&(*intervals).node[lowest_son_position]); } // Caso o pai possua prioridade maior que a do filho de menor prioridade, // troca os valores de ambos entre si. A verificação é feita para ambos // os extremos do intervalo. if((father_value > (*intervals).node[lowest_son_position].min) && IsNotEmpty((*intervals).node[lowest_son_position].min)) { SwapValues(&(*intervals).node[position].min, &(*intervals).node[lowest_son_position].min); } else if ((father_value > (*intervals).node[lowest_son_position].max) && IsNotEmpty((*intervals).node[lowest_son_position].max)) { SwapValues(&(*intervals).node[position].min, &(*intervals).node[lowest_son_position].max); //Caso o pai esteja na posição correta, interrompe o loop. } else { stop = true; } position = lowest_son_position; lowest_son_position = (2 * lowest_son_position) + 1; //Ajusta os valores máximo e mínimo, caso necessário. AssignValues(&(*intervals).node[position]); } AssignValues(&(*intervals).node[position]); }
// Troca os valores máximo e mínimo caso não estejam no campo correto. bool AssignValues(Interval *node) { if((((*node).max > -1) && ((*node).max < (*node).min)) || (((*node).min > -1) && ((*node).min > (*node).max))) { SwapValues(&(*node).max, &(*node).min); return true; } return false; }
void main() { int a,b; int *a_ptr, *b_ptr; scanf("%d,%d",&a,&b); a_ptr = &a; b_ptr = &b; SwapValues(&a, &b);//等同於SwapValues(a_ptr, b_ptr); printf("a=%d,b=%d\n" , a,b);// 等同於printf("a=%d,b=%d",*a_ptr, *b_ptr); }
int InsertionSort(int the_array[], unsigned int size)//Apply the insertion sort algorithm to sort an array of integers. { int passes = 0; for (int i = 0; i <= (size - 1); i++) { passes++; int j = i; while (j > 0 && the_array[j] < the_array[j - 1]) { SwapValues(the_array[j], the_array[j - 1]); j = j - 1; } } return passes; }
int BubbleSort(int the_array[], unsigned int size)//Apply the bubble sort algorithm to sort an array of integers. { int passes = 0; for (int i = size - 1; i > 0; i--) { passes++; for (int j = 0; j < i; j++) { if (the_array[j] > the_array[j + 1]) { SwapValues(the_array[j], the_array[j + 1]); } } } return passes; }
// ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ // ¥ EvaluateInt // ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ TTBInteger CRandomFunction::EvaluateInt( CProgram &ioState) { SInt32 t; TTBInteger lower=mLower(ioState),higher=mHigher(ioState),temp; if (lower>higher) SwapValues(lower,higher,temp); // this implementation is assuming a 32 bit random number generator // if it's a 16 bit one, then passing a min max with a span > 16 bits will not yield a full spread COMPILE_TIME_ASSERT(RAND_MAX==0x7fffffff); UInt32 diff=higher-lower+1; TTBInteger rand; rand=std::rand()%diff+lower; return rand; }
int main() { //~ Function 1 int a = 1; int b = 2; printf("int a equals %d\n", a); printf("int b equals %d\n", b); SwapValues(&a, &b); printf("Values swapped\n"); printf("int a now equals %d\n", a); printf("int b now equals %d\n", b); int arr[5] = {1, 2, 3, 4, 5}; int len = 5; //~ Function 2 printf("New temp variable the sum is: %d\n", GetSumReturn(arr, len)); //~ Function 3 int sum = 0; printf("The sum value is now: %d\n", sum); GetSumParameter(arr, len, &sum); printf("Sum value changed\n"); printf("The sum value is now: %d\n", sum); //~ Function 4 int arr2[5] = {1, 2, 3, 4, 5}; int result[5]; int i = 0; for(; i != len; i++) { printf("%d\n", result[i]); } ArrayAdd(arr, arr2, len, result); i = 0; for(; i != len; i++) { printf("%d\n", result[i]); } return 0; }
int SelectionSort(int the_array[], unsigned int size)//Apply the selection sort algorithm to sort an array of integers. { int smallest = 0; int passes = 0; for (int i = 0; i < size; i++) { passes++; smallest = i; for (int j = (i + 1); j < size; j++) { if (the_array[j] < the_array[smallest]) { smallest = j; } } if (smallest != i) { SwapValues(the_array[i], the_array[smallest]); } } return passes; }
int OptimizedBubbleSort(int the_array[], unsigned int size)//Apply the optimized bubble sort algorithm to sort an array of integers. { int passes = 0; for (int i = size - 1; i > 0; i--) { bool swapped = false; passes++; for (int j = 0; j < i; j++) { if (the_array[j] > the_array[j + 1]) { SwapValues(the_array[j], the_array[j + 1]); swapped = true; } } if (swapped == false) { break; } } return passes; }
// Tendo o pai como referência, o mesmo é comparado com seus filhos e trocado // caso a sua prioridade seja menor que a de um deles. void DownwardsMax(Heap *intervals, int position) { //Assume que o filho de maior valor é o da esquerda. int highest_son_position = 2*position+1; bool stop = false; // Enquanto o vetor ainda estiver sendo percorrido e o pai // não ser maior que ambos seus filhos... while((!stop) && (highest_son_position < (*intervals).size)) { // Caso os filhos da direita e esquerda existirem e o valor do filho de // maior valor for menor que o do irmão, significa que a posição do filho de // maior valor é a posição do irmão. int father_value = (*intervals).node[position].max; if(BrotherHasHigherValue((*intervals), highest_son_position)) { highest_son_position += 1; // Garante que o valor a ser utilizado é o correto. AssignValues(&(*intervals).node[highest_son_position]); } // Caso o pai possua prioridade menor que a do filho de maior prioridade, // troca os valores de ambos entre si. if(father_value < (*intervals).node[highest_son_position].max) { SwapValues(&(*intervals).node[position].max, &(*intervals).node[highest_son_position].max); position = highest_son_position; highest_son_position = (2 * highest_son_position) + 1; //Ajusta os valores máximo e mínimo, caso necessário. AssignValues(&(*intervals).node[position]); //Caso o pai esteja na posição correta, interrompe o loop. } else { stop = true; } } AssignValues(&(*intervals).node[position]); }
/* ==================== idMD5Mesh::ParseMesh ==================== */ void idMD5Mesh::ParseMesh( idLexer& parser, int numJoints, const idJointMat* joints ) { idToken token; idToken name; parser.ExpectTokenString( "{" ); // // parse name // if( parser.CheckTokenString( "name" ) ) { parser.ReadToken( &name ); } // // parse shader // parser.ExpectTokenString( "shader" ); parser.ReadToken( &token ); idStr shaderName = token; shader = declManager->FindMaterial( shaderName ); // // parse texture coordinates // parser.ExpectTokenString( "numverts" ); int count = parser.ParseInt(); if( count < 0 ) { parser.Error( "Invalid size: %s", token.c_str() ); } this->numVerts = count; idList<idVec2> texCoords; idList<int> firstWeightForVertex; idList<int> numWeightsForVertex; texCoords.SetNum( count ); firstWeightForVertex.SetNum( count ); numWeightsForVertex.SetNum( count ); int numWeights = 0; int maxweight = 0; for( int i = 0; i < texCoords.Num(); i++ ) { parser.ExpectTokenString( "vert" ); parser.ParseInt(); parser.Parse1DMatrix( 2, texCoords[ i ].ToFloatPtr() ); firstWeightForVertex[ i ] = parser.ParseInt(); numWeightsForVertex[ i ] = parser.ParseInt(); if( !numWeightsForVertex[ i ] ) { parser.Error( "Vertex without any joint weights." ); } numWeights += numWeightsForVertex[ i ]; if( numWeightsForVertex[ i ] + firstWeightForVertex[ i ] > maxweight ) { maxweight = numWeightsForVertex[ i ] + firstWeightForVertex[ i ]; } } // // parse tris // parser.ExpectTokenString( "numtris" ); count = parser.ParseInt(); if( count < 0 ) { parser.Error( "Invalid size: %d", count ); } idList<int> tris; tris.SetNum( count * 3 ); numTris = count; for( int i = 0; i < count; i++ ) { parser.ExpectTokenString( "tri" ); parser.ParseInt(); tris[ i * 3 + 0 ] = parser.ParseInt(); tris[ i * 3 + 1 ] = parser.ParseInt(); tris[ i * 3 + 2 ] = parser.ParseInt(); } // // parse weights // parser.ExpectTokenString( "numweights" ); count = parser.ParseInt(); if( count < 0 ) { parser.Error( "Invalid size: %d", count ); } if( maxweight > count ) { parser.Warning( "Vertices reference out of range weights in model (%d of %d weights).", maxweight, count ); } idList<vertexWeight_t> tempWeights; tempWeights.SetNum( count ); assert( numJoints < 256 ); // so we can pack into bytes for( int i = 0; i < count; i++ ) { parser.ExpectTokenString( "weight" ); parser.ParseInt(); int jointnum = parser.ParseInt(); if( ( jointnum < 0 ) || ( jointnum >= numJoints ) ) { parser.Error( "Joint Index out of range(%d): %d", numJoints, jointnum ); } tempWeights[ i ].joint = jointnum; tempWeights[ i ].jointWeight = parser.ParseFloat(); parser.Parse1DMatrix( 3, tempWeights[ i ].offset.ToFloatPtr() ); } // create pre-scaled weights and an index for the vertex/joint lookup idVec4* scaledWeights = ( idVec4* ) Mem_Alloc16( numWeights * sizeof( scaledWeights[0] ), TAG_MD5_WEIGHT ); int* weightIndex = ( int* ) Mem_Alloc16( numWeights * 2 * sizeof( weightIndex[0] ), TAG_MD5_INDEX ); memset( weightIndex, 0, numWeights * 2 * sizeof( weightIndex[0] ) ); count = 0; for( int i = 0; i < texCoords.Num(); i++ ) { int num = firstWeightForVertex[i]; for( int j = 0; j < numWeightsForVertex[i]; j++, num++, count++ ) { scaledWeights[count].ToVec3() = tempWeights[num].offset * tempWeights[num].jointWeight; scaledWeights[count].w = tempWeights[num].jointWeight; weightIndex[count * 2 + 0] = tempWeights[num].joint * sizeof( idJointMat ); } weightIndex[count * 2 - 1] = 1; } parser.ExpectTokenString( "}" ); // update counters c_numVerts += texCoords.Num(); c_numWeights += numWeights; c_numWeightJoints++; for( int i = 0; i < numWeights; i++ ) { c_numWeightJoints += weightIndex[i * 2 + 1]; } // // build a base pose that can be used for skinning // idDrawVert* basePose = ( idDrawVert* )Mem_ClearedAlloc( texCoords.Num() * sizeof( *basePose ), TAG_MD5_BASE ); for( int j = 0, i = 0; i < texCoords.Num(); i++ ) { idVec3 v = ( *( idJointMat* )( ( byte* )joints + weightIndex[j * 2 + 0] ) ) * scaledWeights[j]; while( weightIndex[j * 2 + 1] == 0 ) { j++; v += ( *( idJointMat* )( ( byte* )joints + weightIndex[j * 2 + 0] ) ) * scaledWeights[j]; } j++; basePose[i].Clear(); basePose[i].xyz = v; basePose[i].SetTexCoord( texCoords[i] ); } // build the weights and bone indexes into the verts, so they will be duplicated // as necessary at mirror seems static int maxWeightsPerVert; static float maxResidualWeight; const int MAX_VERTEX_WEIGHTS = 4; idList< bool > jointIsUsed; jointIsUsed.SetNum( numJoints ); for( int i = 0; i < jointIsUsed.Num(); i++ ) { jointIsUsed[i] = false; } numMeshJoints = 0; maxJointVertDist = 0.0f; //----------------------------------------- // new-style setup for fixed four weights and normal / tangent deformation // // Several important models have >25% residual weight in joints after the // first four, which is worrisome for using a fixed four joint deformation. //----------------------------------------- for( int i = 0; i < texCoords.Num(); i++ ) { idDrawVert& dv = basePose[i]; // some models do have >4 joint weights, so it is necessary to sort and renormalize // sort the weights and take the four largest int weights[256]; const int numWeights = numWeightsForVertex[ i ]; for( int j = 0; j < numWeights; j++ ) { weights[j] = firstWeightForVertex[i] + j; } // bubble sort for( int j = 0; j < numWeights; j++ ) { for( int k = 0; k < numWeights - 1 - j; k++ ) { if( tempWeights[weights[k]].jointWeight < tempWeights[weights[k + 1]].jointWeight ) { SwapValues( weights[k], weights[k + 1] ); } } } if( numWeights > maxWeightsPerVert ) { maxWeightsPerVert = numWeights; } const int usedWeights = Min( MAX_VERTEX_WEIGHTS, numWeights ); float totalWeight = 0; for( int j = 0; j < numWeights; j++ ) { totalWeight += tempWeights[weights[j]].jointWeight; } assert( totalWeight > 0.999f && totalWeight < 1.001f ); float usedWeight = 0; for( int j = 0; j < usedWeights; j++ ) { usedWeight += tempWeights[weights[j]].jointWeight; } const float residualWeight = totalWeight - usedWeight; if( residualWeight > maxResidualWeight ) { maxResidualWeight = residualWeight; } byte finalWeights[MAX_VERTEX_WEIGHTS] = { 0 }; byte finalJointIndecies[MAX_VERTEX_WEIGHTS] = { 0 }; for( int j = 0; j < usedWeights; j++ ) { const vertexWeight_t& weight = tempWeights[weights[j]]; const int jointIndex = weight.joint; const float fw = weight.jointWeight; assert( fw >= 0.0f && fw <= 1.0f ); const float normalizedWeight = fw / usedWeight; finalWeights[j] = idMath::Ftob( normalizedWeight * 255.0f ); finalJointIndecies[j] = jointIndex; } // Sort the weights and indices for hardware skinning for( int k = 0; k < 3; ++k ) { for( int l = k + 1; l < 4; ++l ) { if( finalWeights[l] > finalWeights[k] ) { SwapValues( finalWeights[k], finalWeights[l] ); SwapValues( finalJointIndecies[k], finalJointIndecies[l] ); } } } // Give any left over to the biggest weight finalWeights[0] += Max( 255 - finalWeights[0] - finalWeights[1] - finalWeights[2] - finalWeights[3], 0 ); dv.color[0] = finalJointIndecies[0]; dv.color[1] = finalJointIndecies[1]; dv.color[2] = finalJointIndecies[2]; dv.color[3] = finalJointIndecies[3]; dv.color2[0] = finalWeights[0]; dv.color2[1] = finalWeights[1]; dv.color2[2] = finalWeights[2]; dv.color2[3] = finalWeights[3]; for( int j = usedWeights; j < 4; j++ ) { assert( dv.color2[j] == 0 ); } for( int j = 0; j < usedWeights; j++ ) { if( !jointIsUsed[finalJointIndecies[j]] ) { jointIsUsed[finalJointIndecies[j]] = true; numMeshJoints++; } const idJointMat& joint = joints[finalJointIndecies[j]]; float dist = ( dv.xyz - joint.GetTranslation() ).Length(); if( dist > maxJointVertDist ) { maxJointVertDist = dist; } } } meshJoints = ( byte* ) Mem_Alloc( numMeshJoints * sizeof( meshJoints[0] ), TAG_MODEL ); numMeshJoints = 0; for( int i = 0; i < numJoints; i++ ) { if( jointIsUsed[i] ) { meshJoints[numMeshJoints++] = i; } } // build the deformInfo and collect a final base pose with the mirror // seam verts properly including the bone weights deformInfo = R_BuildDeformInfo( texCoords.Num(), basePose, tris.Num(), tris.Ptr(), shader->UseUnsmoothedTangents() ); for( int i = 0; i < deformInfo->numOutputVerts; i++ ) { for( int j = 0; j < 4; j++ ) { if( deformInfo->verts[i].color[j] >= numJoints ) { idLib::FatalError( "Bad joint index" ); } } } Mem_Free( basePose ); }
/* ==================== idSurface_Polytope::SplitPolytope ==================== */ int idSurface_Polytope::SplitPolytope( const idPlane &plane, const float epsilon, idSurface_Polytope **front, idSurface_Polytope **back ) const { int side, i, j, s, v0, v1, v2, edgeNum; idSurface *surface[2]; idSurface_Polytope *polytopeSurfaces[2], *surf; int *onPlaneEdges[2]; onPlaneEdges[0] = (int *) _alloca( indexes.Num() / 3 * sizeof( int ) ); onPlaneEdges[1] = (int *) _alloca( indexes.Num() / 3 * sizeof( int ) ); side = Split( plane, epsilon, &surface[0], &surface[1], onPlaneEdges[0], onPlaneEdges[1] ); *front = polytopeSurfaces[0] = new (TAG_IDLIB_SURFACE) idSurface_Polytope; *back = polytopeSurfaces[1] = new (TAG_IDLIB_SURFACE) idSurface_Polytope; for ( s = 0; s < 2; s++ ) { if ( surface[s] ) { polytopeSurfaces[s] = new idSurface_Polytope( *surface[s] ); delete surface[s]; surface[s] = NULL; } } *front = polytopeSurfaces[0]; *back = polytopeSurfaces[1]; if ( side != SIDE_CROSS ) { return side; } // add triangles to close off the front and back polytope for ( s = 0; s < 2; s++ ) { surf = polytopeSurfaces[s]; edgeNum = surf->edgeIndexes[onPlaneEdges[s][0]]; v0 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITSET(edgeNum)]; v1 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITNOTSET(edgeNum)]; for ( i = 1; onPlaneEdges[s][i] >= 0; i++ ) { for ( j = i+1; onPlaneEdges[s][j] >= 0; j++ ) { edgeNum = surf->edgeIndexes[onPlaneEdges[s][j]]; if ( v1 == surf->edges[abs(edgeNum)].verts[INT32_SIGNBITSET(edgeNum)] ) { v1 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITNOTSET(edgeNum)]; SwapValues( onPlaneEdges[s][i], onPlaneEdges[s][j] ); break; } } } for ( i = 2; onPlaneEdges[s][i] >= 0; i++ ) { edgeNum = surf->edgeIndexes[onPlaneEdges[s][i]]; v1 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITNOTSET(edgeNum)]; v2 = surf->edges[abs(edgeNum)].verts[INT32_SIGNBITSET(edgeNum)]; surf->indexes.Append( v0 ); surf->indexes.Append( v1 ); surf->indexes.Append( v2 ); } surf->GenerateEdgeIndexes(); } return side; }
/* ==================== idRenderModelLiquid::Update ==================== */ void idRenderModelLiquid::Update() { int x, y; float* p2; float* p1; float value; time += update_tics; SwapValues( page1, page2 ); if( time > nextDropTime ) { WaterDrop( -1, -1, page2 ); nextDropTime = time + drop_delay; } else if( time < nextDropTime - drop_delay ) { nextDropTime = time + drop_delay; } p1 = page1; p2 = page2; switch( liquid_type ) { case 0 : for( y = 1; y < verts_y - 1; y++ ) { p2 += verts_x; p1 += verts_x; for( x = 1; x < verts_x - 1; x++ ) { value = ( p2[ x + verts_x ] + p2[ x - verts_x ] + p2[ x + 1 ] + p2[ x - 1 ] + p2[ x - verts_x - 1 ] + p2[ x - verts_x + 1 ] + p2[ x + verts_x - 1 ] + p2[ x + verts_x + 1 ] + p2[ x ] ) * ( 2.0f / 9.0f ) - p1[ x ]; p1[ x ] = value * density; } } break; case 1 : for( y = 1; y < verts_y - 1; y++ ) { p2 += verts_x; p1 += verts_x; for( x = 1; x < verts_x - 1; x++ ) { value = ( p2[ x + verts_x ] + p2[ x - verts_x ] + p2[ x + 1 ] + p2[ x - 1 ] + p2[ x - verts_x - 1 ] + p2[ x - verts_x + 1 ] + p2[ x + verts_x - 1 ] + p2[ x + verts_x + 1 ] ) * 0.25f - p1[ x ]; p1[ x ] = value * density; } } break; case 2 : for( y = 1; y < verts_y - 1; y++ ) { p2 += verts_x; p1 += verts_x; for( x = 1; x < verts_x - 1; x++ ) { value = ( p2[ x + verts_x ] + p2[ x - verts_x ] + p2[ x + 1 ] + p2[ x - 1 ] + p2[ x - verts_x - 1 ] + p2[ x - verts_x + 1 ] + p2[ x + verts_x - 1 ] + p2[ x + verts_x + 1 ] + p2[ x ] ) * ( 1.0f / 9.0f ); p1[ x ] = value * density; } } break; } }
/*! For 3D and 2D. @par Revision history: - 08.06.2006, c - 02.08.2006 */ int32 orient_elements( int32 *flag, int32 flag_n_row, int32 *conn, int32 conn_n_row, int32 conn_n_col, float64 *coors, int32 coors_n_row, int32 coors_n_col, int32 *v_roots, int32 v_roots_n_row, int32 *v_vecs, int32 v_vecs_n_row, int32 v_vecs_n_col, int32 *swap_from, int32 swap_from_n_row, int32 swap_from_n_col, int32 *swap_to, int32 swap_to_n_row, int32 swap_to_n_col ) { #define IR( iel, ir ) (conn[conn_n_col*(iel)+v_roots[ir]]) #define IV( iel, ir, iv ) (conn[conn_n_col*(iel)+v_vecs[v_vecs_n_col*ir+iv]]) #define CONN( iel, ip ) (conn[conn_n_col*(iel)+ip]) #define SWF( ir, is ) (swap_from[swap_from_n_col*ir+is]) #define SWT( ir, is ) (swap_to[swap_to_n_col*ir+is]) int32 ir, iel, ii, ip0, ip1, ip2, ip3, tmp, nc; float64 v0[3], v1[3], v2[3], v3[3], cross[3], dot[1]; nc = coors_n_col; if (nc == 4) { // 3D. for (iel = 0; iel < conn_n_row; iel++) { flag[iel] = 0; for (ir = 0; ir < v_roots_n_row; ir++) { ip0 = IR( iel, ir ); ip1 = IV( iel, ir, 0 ); ip2 = IV( iel, ir, 1 ); ip3 = IV( iel, ir, 2 ); for (ii = 0; ii < 3; ii++) { v0[ii] = coors[nc*ip0+ii]; v1[ii] = coors[nc*ip1+ii] - v0[ii]; v2[ii] = coors[nc*ip2+ii] - v0[ii]; v3[ii] = coors[nc*ip3+ii] - v0[ii]; } gtr_cross_product( cross, v1, v2 ); gtr_dot_v3( dot, v3, cross ); /* output( "%d %d -> %d %d %d %d %e\n", iel, ir, ip0, ip1, ip2, ip3, */ /* dot[0] ); */ if (dot[0] < CONST_MachEps) { flag[iel]++; for (ii = 0; ii < swap_from_n_col; ii++) { SwapValues( CONN( iel, SWF( ir, ii ) ), CONN( iel, SWT( ir, ii ) ), tmp ); /* output( "%d %d\n", SWF( ir, ii ), SWT( ir, ii ) ); */ } } } /* sys_pause(); */ } } else if (nc == 3) { // 2D. for (iel = 0; iel < conn_n_row; iel++) { flag[iel] = 0; for (ir = 0; ir < v_roots_n_row; ir++) { ip0 = IR( iel, ir ); ip1 = IV( iel, ir, 0 ); ip2 = IV( iel, ir, 1 ); for (ii = 0; ii < 2; ii++) { v0[ii] = coors[nc*ip0+ii]; v1[ii] = coors[nc*ip1+ii] - v0[ii]; v2[ii] = coors[nc*ip2+ii] - v0[ii]; } v1[2] = v2[2] = 0.0; gtr_cross_product( cross, v1, v2 ); if (cross[2] < CONST_MachEps) { flag[iel]++; for (ii = 0; ii < swap_from_n_col; ii++) { SwapValues( CONN( iel, SWF( ir, ii ) ), CONN( iel, SWT( ir, ii ) ), tmp ); } } } } } return( RET_OK ); #undef IR #undef IV #undef CONN #undef SWF #undef SWT }
/* ============ idWinding2D::RayIntersection ============ */ bool idWinding2D::RayIntersection( const idVec2 &start, const idVec2 &dir, float &scale1, float &scale2, int *edgeNums ) const { int i, numEdges, localEdgeNums[2]; int sides[MAX_POINTS_ON_WINDING_2D+1], counts[3]; float d1, d2, epsilon = 0.1f; idVec3 plane, edges[2]; scale1 = scale2 = 0.0f; counts[SIDE_FRONT] = counts[SIDE_BACK] = counts[SIDE_ON] = 0; plane = Plane2DFromVecs( start, dir ); for ( i = 0; i < numPoints; i++ ) { d1 = plane.x * p[i].x + plane.y * p[i].y + plane.z; if ( d1 > epsilon ) { sides[i] = SIDE_FRONT; } else if ( d1 < -epsilon ) { sides[i] = SIDE_BACK; } else { sides[i] = SIDE_ON; } counts[sides[i]]++; } sides[i] = sides[0]; if ( !counts[SIDE_FRONT] ) { return false; } if ( !counts[SIDE_BACK] ) { return false; } numEdges = 0; for ( i = 0; i < numPoints; i++ ) { if ( sides[i] != sides[i+1] && sides[i+1] != SIDE_ON ) { localEdgeNums[numEdges] = i; edges[numEdges++] = Plane2DFromPoints( p[i], p[(i+1)%numPoints] ); if ( numEdges >= 2 ) { break; } } } if ( numEdges < 2 ) { return false; } d1 = edges[0].x * start.x + edges[0].y * start.y + edges[0].z; d2 = - ( edges[0].x * dir.x + edges[0].y * dir.y ); if ( d2 == 0.0f ) { return false; } scale1 = d1 / d2; d1 = edges[1].x * start.x + edges[1].y * start.y + edges[1].z; d2 = - ( edges[1].x * dir.x + edges[1].y * dir.y ); if ( d2 == 0.0f ) { return false; } scale2 = d1 / d2; if ( idMath::Fabs( scale1 ) > idMath::Fabs( scale2 ) ) { SwapValues( scale1, scale2 ); SwapValues( localEdgeNums[0], localEdgeNums[1] ); } if ( edgeNums ) { edgeNums[0] = localEdgeNums[0]; edgeNums[1] = localEdgeNums[1]; } return true; }