+static void Mod_SplitSurfMeshIfTooBig(msurface_t *s)
+{
+ int j, base, tricount, newvertexcount, *index, *vertexremap;
+ surfmesh_t *newmesh, *oldmesh, *firstmesh;
+ if (s->mesh->numtriangles > 1000)
+ {
+ vertexremap = Mem_Alloc(tempmempool, s->mesh->numverts * sizeof(int));
+ memset(vertexremap, -1, s->mesh->numverts * sizeof(int));
+ base = 0;
+ oldmesh = NULL;
+ firstmesh = NULL;
+ newmesh = NULL;
+ while (base < s->mesh->numtriangles)
+ {
+ tricount = s->mesh->numtriangles - base;
+ if (tricount > 1000)
+ tricount = 1000;
+ index = s->mesh->index + base * 3;
+ base += tricount;
+
+ newvertexcount = 0;
+ for (j = 0;j < tricount * 3;j++)
+ if (vertexremap[index[j]] < 0)
+ vertexremap[index[j]] = newvertexcount++;
+
+ newmesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + newvertexcount * sizeof(surfvertex_t) + tricount * sizeof(int[3]));
+ newmesh->chain = NULL;
+ newmesh->numverts = newvertexcount;
+ newmesh->numtriangles = tricount;
+ newmesh->vertex = (surfvertex_t *)(newmesh + 1);
+ newmesh->index = (int *)(newmesh->vertex + newvertexcount);
+ for (j = 0;j < tricount * 3;j++)
+ {
+ newmesh->index[j] = vertexremap[index[j]];
+ // yes this copies the same vertex multiple times in many cases... but that's ok...
+ memcpy(&newmesh->vertex[newmesh->index[j]], &s->mesh->vertex[index[j]], sizeof(surfvertex_t));
+ }
+ if (oldmesh)
+ oldmesh->chain = newmesh;
+ else
+ firstmesh = newmesh;
+ oldmesh = newmesh;
+ }
+ Mem_Free(vertexremap);
+ Mem_Free(s->mesh);
+ s->mesh = firstmesh;
+ }
+}
+