#!/usr/bin/env python
"""Find any vertices in a submesh with the same location but different 
bones, and give them all the average bones of that group of vertices.
This may fix glitches sometimes.
"""

import sys

import vb

if __name__ == '__main__':
	close = {}
	m = vb.Mesh(sys.argv[1])
	for i, v in enumerate(m.vertices):
		for j, w in enumerate(m.vertices[:i]):
			if v.distance(w) < 0.00001:
				if i not in close:
					close[i] = [j]
				else:
					close[i].append(j)
	groups = []
	for k, v in close.items():
		group = v + [k]
		for l in groups:
			if len(l) < len(group) and group[:len(l)] == l:
				l.extend(group[len(l):])
				break
		if group not in groups:
			groups.append(group)
	vs = set()
	for group in groups:
		if set(group).intersection(vs):
			raise Exception()
		vs.update(set(group))
	for g in groups:
		new_bones = dict()
		for i in g:
			for ind, wei in m.vertices[i].bones():
				if ind in new_bones:
					new_bones[ind] += wei
				else:
					new_bones[ind] = wei
		new_bones = sorted([(x, y/len(g)) for x, y in new_bones.items()], key=lambda z: -z[1])
		for i in g:
			m.vertices[i].set_bones(new_bones)
	m.write(sys.argv[1])


