42 lines
2.4 KiB
Python
42 lines
2.4 KiB
Python
|
|
"""Clip material boundaries through triangles instead of painting whole faces."""
|
||
|
|
import numpy as np
|
||
|
|
|
||
|
|
def split_material(primitive, selected, signed_distance, positive_material, negative_material, doc, read, accessor):
|
||
|
|
faces=read(primitive['indices']).reshape(-1,3).astype(np.int64)
|
||
|
|
arrays={key:read(value) for key,value in primitive['attributes'].items()}
|
||
|
|
output=[]
|
||
|
|
def clip(poly,values,sign):
|
||
|
|
result=[]
|
||
|
|
for i,a in enumerate(poly):
|
||
|
|
b=poly[(i+1)%len(poly)];va=float(a@values)*sign;vb=float(b@values)*sign
|
||
|
|
if va>=0:result.append(a)
|
||
|
|
if (va>=0)!=(vb>=0):result.append(a+(b-a)*(va/(va-vb)))
|
||
|
|
return result
|
||
|
|
for sign,material in [(1,positive_material),(-1,negative_material)]:
|
||
|
|
if material is None:continue
|
||
|
|
rows={key:[] for key in arrays}
|
||
|
|
for face in faces[selected]:
|
||
|
|
values=np.array([signed_distance(p) for p in arrays['POSITION'][face]])
|
||
|
|
poly=clip(list(np.eye(3)),values,sign)
|
||
|
|
for i in range(1,len(poly)-1):
|
||
|
|
for bary in [poly[0],poly[i],poly[i+1]]:
|
||
|
|
for key,array in arrays.items():
|
||
|
|
if key in ['JOINTS_0','WEIGHTS_0']:continue
|
||
|
|
value=bary@array[face]
|
||
|
|
if key=='NORMAL':value/=max(np.linalg.norm(value),1e-12)
|
||
|
|
rows[key].append(value)
|
||
|
|
weights={}
|
||
|
|
for corner in range(3):
|
||
|
|
for joint,weight in zip(arrays['JOINTS_0'][face[corner]],arrays['WEIGHTS_0'][face[corner]]):
|
||
|
|
weights[int(joint)]=weights.get(int(joint),0)+float(weight)*bary[corner]
|
||
|
|
pairs=sorted(weights.items(),key=lambda x:-x[1])[:4];pairs+=[(0,0)]*(4-len(pairs));total=max(sum(w for _,w in pairs),1e-12)
|
||
|
|
rows['JOINTS_0'].append([j for j,_ in pairs]);rows['WEIGHTS_0'].append([w/total for _,w in pairs])
|
||
|
|
if not rows['POSITION']:continue
|
||
|
|
attrs={}
|
||
|
|
for key,values in rows.items():
|
||
|
|
original=doc['accessors'][primitive['attributes'][key]]
|
||
|
|
attrs[key]=accessor(values,original['type'],original['componentType'])
|
||
|
|
output.append({'attributes':attrs,'material':material,'indices':accessor(np.arange(len(rows['POSITION'])).reshape(-1,1),'SCALAR',5125)})
|
||
|
|
primitive['indices']=accessor(faces[~selected].reshape(-1,1),'SCALAR',5125)
|
||
|
|
return output
|