This commit is contained in:
listik committed 2026-11-29 15:49:17 +03:00
commit a85391509d
211 files changed
+28903

No files matched your search

Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
ok
+83
View File
@@ -0,0 +1,83 @@
import bpy, math
from mathutils import Vector
scene=bpy.context.scene
old=scene.collection.children.get("Atmosphere | colored halogen fixtures")
if old:
for ob in list(old.objects):bpy.data.objects.remove(ob,do_unlink=True)
bpy.data.collections.remove(old)
lights=bpy.data.collections.new("Atmosphere | colored halogen fixtures");scene.collection.children.link(lights)
def material(name,color,glow=0):
m=bpy.data.materials.new(name);m.diffuse_color=(*color,1);m.use_nodes=True
p=next(n for n in m.node_tree.nodes if n.type=="BSDF_PRINCIPLED")
p.inputs["Base Color"].default_value=(*color,1);p.inputs["Roughness"].default_value=.4
if glow:
p.inputs["Emission Color"].default_value=(*color,1);p.inputs["Emission Strength"].default_value=glow
return m
housing=material("Halogen | graphite housing",(.055,.075,.11))
colors={"cyan":(.04,.75,1),"amber":(1,.48,.09),"violet":(.48,.12,1),"mint":(.08,1,.52)}
lenses={k:material("Halogen | "+k,c,4) for k,c in colors.items()}
def solid(name,loc,size,mat):
assert min(size)>=2
bpy.ops.mesh.primitive_cube_add(size=1,location=loc)
ob=bpy.context.object;ob.name=name;ob.dimensions=size
bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
for c in list(ob.users_collection):c.objects.unlink(ob)
lights.objects.link(ob);ob.data.materials.append(mat)
b=ob.modifiers.new("Housing corner","BEVEL");b.width=.18;b.segments=2
return ob
def area(name,pos,target,color,energy=9000,size=7):
d=bpy.data.lights.new(name,"AREA");d.energy=energy;d.color=colors[color];d.shape="DISK";d.size=size
o=bpy.data.objects.new(name,d);lights.objects.link(o);o.location=pos
o.rotation_euler=(Vector(target)-o.location).to_track_quat("-Z","Y").to_euler()
return o
def ceiling(x,y,color,elevation=0):
solid("Recessed "+color+" ceiling housing",(x,y,24+elevation),(12,6,4),housing)
solid("Halogen "+color+" diffuser",(x,y,22+elevation),(8,4,2),lenses[color])
area("Underpass "+color+" wash",(x,y,20.8+elevation),(x,y,elevation),color,12000,8)
# Each district has a color identity; the central cross remains easy to read.
for x,y,c in [(0,0,"cyan"),(-32,0,"cyan"),(32,0,"cyan"),(0,-32,"amber"),(0,32,"amber"),
(-144,0,"violet"),(144,0,"mint"),
(0,320,"cyan"),(0,-320,"amber"),(-320,0,"violet"),(320,0,"mint"),
(-304,-304,"violet"),(-304,304,"cyan"),(304,-304,"amber"),(304,304,"mint")]:
ceiling(x,y,c)
for x in (-32,0,32):
ceiling(x,0,"violet",48)
def sconce(x,y,z,sign,color):
solid("Wall light "+color+" housing",(x,y+sign*2,z),(8,4,8),housing)
solid("Wall light "+color+" lens",(x,y+sign*4.8,z),(4,2,4),lenses[color])
area("Wall "+color+" pool",(x,y+sign*6,z),(x,y+sign*24,4),color,10000,5)
for x in (-32,32):
sconce(x,-48,18,-1,"amber")
sconce(x,48,18,1,"cyan")
for sx in (-1,1):
for sy in (-1,1):
sconce(304*sx+32,304*sy+48*sy,18,sy,"violet" if sx<0 else "mint")
# Substantial route markers stand outside the ramp footprint.
for x in (-144,144):
for y in (-160,160):
for side in (-1,1):
xx=x+side*24
solid("Ramp marker | plinth",(xx,y,4),(4,4,8),housing)
solid("Ramp marker | lamp",(xx,y,9),(4,4,2),lenses["violet" if x<0 else "mint"])
# Balanced dusk lighting keeps walking routes visible while colored pools read.
world=bpy.data.worlds.new("Arena | blue dusk");world.use_nodes=True
bg=next(n for n in world.node_tree.nodes if n.type=="BACKGROUND")
bg.inputs["Color"].default_value=(.24,.32,.46,1);bg.inputs["Strength"].default_value=.50
scene.world=world
d=bpy.data.lights.new("Dusk | soft key","SUN");d.energy=1.8;d.angle=math.radians(18);d.color=(.78,.85,1)
sun=bpy.data.objects.new("Dusk | soft key",d);lights.objects.link(sun)
sun.rotation_euler=(math.radians(28),math.radians(-22),math.radians(-25))
d=bpy.data.lights.new("Dusk | soft fill","SUN");d.energy=.65;d.angle=math.radians(30);d.color=(.74,.83,1)
fill=bpy.data.objects.new("Dusk | soft fill",d);lights.objects.link(fill)
fill.rotation_euler=(math.radians(55),math.radians(20),math.radians(155))
scene["lighting"]="Cyan north/center, amber south, violet west/middle gallery, mint east; 26 local area lights."
for a in bpy.context.window.screen.areas:
if a.type=="VIEW_3D":
a.spaces.active.shading.type="MATERIAL"
a.spaces.active.shading.use_scene_lights=True
a.spaces.active.shading.use_scene_world=True
a.spaces.active.overlay.show_overlays=False
bpy.ops.object.select_all(action="DESELECT")
bpy.ops.wm.save_as_mainfile(filepath=r"C:\roblox\hunter\3D models\game_zone\Hunter_Monolith_Arena.blend")
result={"fixtures":42,"colored_area_lights":26,"colors":list(colors),"rendered":False}
+58
View File
@@ -0,0 +1,58 @@
import bpy, math
from mathutils import Vector
s=bpy.context.scene
c=bpy.data.collections.new('Gloved Arms');s.collection.children.link(c)
def mat(name,col):
m=bpy.data.materials.new(name);m.diffuse_color=(*col,1);m.use_nodes=True
p=next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED');p.inputs['Base Color'].default_value=(*col,1);p.inputs['Roughness'].default_value=.8
return m
cloth=mat('Glove charcoal fabric',(.035,.045,.043));rubber=mat('Glove rubber armor',(.012,.017,.02));sleeve=mat('Tactical sleeve olive',(.075,.085,.055))
def link(o,name,material):
o.name=name
for col in list(o.users_collection):col.objects.unlink(o)
c.objects.link(o);o.data.materials.append(material)
for p in o.data.polygons:p.use_smooth=True
return o
def ell(name,loc,scale,material):
bpy.ops.mesh.primitive_uv_sphere_add(segments=20,ring_count=12,location=loc)
o=bpy.context.object;o.scale=scale;return link(o,name,material)
def segment(name,a,b,r1,r2,material):
a,b=Vector(a),Vector(b)
bpy.ops.mesh.primitive_cone_add(vertices=24,radius1=r1,radius2=r2,depth=(b-a).length,location=(a+b)/2)
o=bpy.context.object;o.rotation_euler=(b-a).to_track_quat('Z','Y').to_euler();link(o,name,material)
bevel=o.modifiers.new('Soft seam','BEVEL');bevel.width=.035;bevel.segments=3
return o
def finger(name,points,r=.06):
for i in range(len(points)-1):segment(name+' phalanx',points[i],points[i+1],r,r*.94,cloth)
for p in points:ell(name+' joint',p,(r,r,r),cloth)
# Weapon axis +X, right hand wraps the slanted rear grip.
ell('Right palm',(-2.88,.23,-.89),(.22,.15,.33),cloth)
for i in range(4):
z=-.65-i*.14;x=-2.72-i*.035
finger('Right finger '+str(i),[(x,.28,z),(x+.16,.13,z-.015),(x+.12,-.15,z-.035),(x-.02,-.25,z-.05)],.063)
finger('Right thumb',[(-3.03,.2,-.67),(-3.08,-.03,-.55),(-2.91,-.26,-.6)],.08)
for i in range(3):ell('Right knuckle armor',(-2.89,.365,-.7-i*.15),(.13,.035,.065),rubber)
segment('Right glove cuff',(-3,.28,-1.1),(-3.15,.4,-1.43),.19,.23,rubber)
segment('Right forearm sleeve',(-3.15,.4,-1.4),(-4.2,.85,-2.4),.23,.34,sleeve)
# Left palm under the front receiver; fingers curl around its far side.
ell('Left palm',(1.12,-.06,-.28),(.33,.27,.14),cloth)
for i in range(4):
x=.88+i*.16
finger('Left finger '+str(i),[(x,.12,-.28),(x,.33,-.18),(x,.39,.02),(x,.28,.12)],.066)
finger('Left thumb',[(.86,-.15,-.26),(.77,-.37,-.09),(.9,-.41,.1)],.084)
for i in range(3):ell('Left glove back armor',(.92+i*.16,-.13,-.405),(.07,.13,.035),rubber)
segment('Left glove wrist',(1,-.15,-.32),(.7,-.53,-.63),.19,.22,cloth)
segment('Left cuff',(.72,-.5,-.61),(.52,-.72,-.86),.22,.25,rubber)
segment('Left forearm sleeve',(.55,-.7,-.83),(-1.75,-1.7,-2.15),.25,.37,sleeve)
data=bpy.data.cameras.new('First Person Camera');cam=bpy.data.objects.new('First Person Camera',data);s.collection.objects.link(cam)
cam.location=(-5.7,-1.25,1.65)
cam.rotation_euler=(Vector((1.25,0,.25))-cam.location).to_track_quat('-Z','Y').to_euler();data.lens=25
s.camera=cam
s.render.resolution_x=1400;s.render.resolution_y=900;s.cycles.samples=24
s.render.filepath=r'C:\roblox\hunter\3D models\sniper_gloved_arms.png'
bpy.ops.wm.save_as_mainfile(filepath=r'C:\roblox\hunter\3D models\sniper_reference_v8_hands.blend')
bpy.ops.render.render(write_still=True)
print('Gloved hands saved',len(c.objects))
+416
View File
@@ -0,0 +1,416 @@
"""Fresh Blender build for the Hunter 520 x 520 city arena.
One Blender unit is one Roblox stud. Run this file in Blender's Python console.
"""
import bpy, math, os, random
from mathutils import Vector
ROOT = r"C:\roblox\hunter"
BLEND_OUT = os.path.join(ROOT, "3D models", "game_zone", "Hunter_CityArena.blend")
RENDER_OUT = os.path.join(ROOT, "renders", "hunter_city_arena.png")
os.makedirs(os.path.dirname(BLEND_OUT), exist_ok=True)
os.makedirs(os.path.dirname(RENDER_OUT), exist_ok=True)
SEED = random.randrange(1, 2**31)
RNG = random.Random(SEED)
SIZE, CELL, RADIUS = 520.0, 40.0, 6
for old_scene in list(bpy.data.scenes):
if old_scene.name.startswith("Hunter City Arena"):
bpy.data.scenes.remove(old_scene, do_unlink=True)
scene = bpy.data.scenes.new("Hunter City Arena | 520 studs")
if bpy.context.window:
bpy.context.window.scene = scene
def coll(name):
c = bpy.data.collections.new(name)
scene.collection.children.link(c)
return c
FOUNDATION = coll("01 Foundation")
ROADS = coll("02 Streets and route loops")
BUILDINGS = coll("03 Modular city buildings")
ROOFS = coll("04 Rooftop routes")
LANDMARKS = coll("05 Plaza and landmarks")
PROPS = coll("06 Trees, lanterns and cover")
WALLS = coll("07 Perimeter and gates")
SETUP = coll("08 Lighting and camera")
def mat(name, color, rough=0.85, metal=0.0, emission=0.0):
m = bpy.data.materials.new(name)
m.diffuse_color = (*color, 1)
m.use_nodes = True
bsdf = next((node for node in m.node_tree.nodes if node.type == "BSDF_PRINCIPLED"), None)
if bsdf:
bsdf.inputs["Base Color"].default_value = (*color, 1)
bsdf.inputs["Roughness"].default_value = rough
bsdf.inputs["Metallic"].default_value = metal
if emission:
bsdf.inputs["Emission Color"].default_value = (*color, 1)
bsdf.inputs["Emission Strength"].default_value = emission
return m
paper = mat("Warm paper stone", (.83,.75,.69))
walk = mat("Pale chalk paving", (.92,.86,.80))
plaza_pink = mat("Rose paper plaza", (.85,.70,.73))
road = mat("Graphite blue asphalt", (.19,.23,.31), .96)
lane = mat("Worn road pencil", (.51,.53,.58))
ink = mat("Indigo pencil line", (.16,.18,.29))
seam = mat("Soft violet pencil seam", (.30,.34,.48))
lav = mat("Lavender plaster", (.59,.64,.83))
blue = mat("Blue chalk plaster", (.48,.68,.83))
peach = mat("Peach plaster", (.87,.59,.46))
rose = mat("Rose plaster", (.80,.49,.60))
cream = mat("Cream plaster", (.92,.82,.69))
slate = mat("Violet slate roof", (.25,.28,.44), .72)
slate2 = mat("Blue slate roof", (.39,.44,.62), .74)
orange = mat("Painted orange tile", (.94,.37,.22), .78)
orange_light = mat("Warm orange pencil highlight", (1.0,.59,.34))
wood = mat("Cedar brown", (.32,.21,.18))
glass = mat("Turquoise glass", (.27,.72,.81), .22, .1)
water = mat("Fountain water", (.12,.66,.85), .2, .12, .12)
green = mat("Garden green", (.30,.56,.38))
leaf = mat("Sage foliage", (.31,.64,.48))
blossom = mat("Cherry blossom pink", (.92,.48,.72))
gold = mat("Lantern glow", (1.0,.68,.29), .4, 0, .2)
metal = mat("Blue charcoal metal", (.13,.18,.27), .55, .3)
walls_palette = [lav, blue, peach, rose, cream]
roofs_palette = [slate, slate2, orange]
class Mesh:
def __init__(self, name, material, collection, parent=None):
self.name, self.material, self.collection, self.parent = name, material, collection, parent
self.v, self.f = [], []
def box(self, center, size, angle=0.0):
x,y,z = center; sx,sy,sz = size
c,s = math.cos(angle), math.sin(angle); base = len(self.v)
for a,b,d in [(-sx/2,-sy/2,-sz/2),(sx/2,-sy/2,-sz/2),(sx/2,sy/2,-sz/2),(-sx/2,sy/2,-sz/2),(-sx/2,-sy/2,sz/2),(sx/2,-sy/2,sz/2),(sx/2,sy/2,sz/2),(-sx/2,sy/2,sz/2)]:
self.v.append((x+a*c-b*s,y+a*s+b*c,z+d))
self.f += [tuple(base+i for i in face) for face in ((0,3,2,1),(4,5,6,7),(0,1,5,4),(1,2,6,5),(2,3,7,6),(3,0,4,7))]
def mesh(self, verts, faces):
base=len(self.v); self.v.extend(verts); self.f.extend(tuple(base+i for i in face) for face in faces)
def gable(self,w,d,z,rise,cx=0,cy=0,over=.5):
w+=2*over; d+=2*over
v=[(cx-w/2,cy-d/2,z),(cx+w/2,cy-d/2,z),(cx+w/2,cy+d/2,z),(cx-w/2,cy+d/2,z),(cx,cy-d/2,z+rise),(cx,cy+d/2,z+rise)]
self.mesh(v,[(0,1,4),(3,5,2),(0,4,5,3),(1,2,5,4),(0,3,2,1)])
def finish(self, bevel=0):
if not self.f: return None
me=bpy.data.meshes.new(self.name+" mesh"); me.from_pydata(self.v,[],self.f); me.materials.append(self.material); me.update()
ob=bpy.data.objects.new(self.name,me); self.collection.objects.link(ob)
if self.parent: ob.parent=self.parent
if bevel:
b=ob.modifiers.new("Soft cut paper edges","BEVEL"); b.width=bevel; b.segments=1; b.limit_method="ANGLE"
ob.modifiers.new("Weighted corner normals","WEIGHTED_NORMAL")
return ob
def root_obj(name, x,y,angle, props=None):
o=bpy.data.objects.new(name,None); o.empty_display_type="PLAIN_AXES"; o.empty_display_size=2
o.location=(x,y,0); o.rotation_euler[2]=angle; BUILDINGS.objects.link(o)
if props:
for k,v in props.items(): o[k]=v
return o
def cylinder(batch, center, r, depth, sides=24, rt=None):
x,y,z=center; rt=r if rt is None else rt; v=[]
for zz,rr in ((z-depth/2,r),(z+depth/2,rt)):
for i in range(sides):
a=2*math.pi*i/sides; v.append((x+rr*math.cos(a),y+rr*math.sin(a),zz))
f=[tuple(reversed(range(sides))),tuple(range(sides,2*sides))]
for i in range(sides): j=(i+1)%sides; f.append((i,j,sides+j,sides+i))
batch.mesh(v,f)
def ico(batch, center, r, seed, stretch=(1,1,1)):
rng=random.Random(seed); p=(1+math.sqrt(5))/2
raw=[(-1,p,0),(1,p,0),(-1,-p,0),(1,-p,0),(0,-1,p),(0,1,p),(0,-1,-p),(0,1,-p),(p,0,-1),(p,0,1),(-p,0,-1),(-p,0,1)]
faces=[(0,11,5),(0,5,1),(0,1,7),(0,7,10),(0,10,11),(1,5,9),(5,11,4),(11,10,2),(10,7,6),(7,1,8),(3,9,4),(3,4,2),(3,2,6),(3,6,8),(3,8,9),(4,9,5),(2,4,11),(6,2,10),(8,6,7),(9,8,1)]
verts=[]
for x,y,z in raw:
n=math.sqrt(x*x+y*y+z*z); j=rng.uniform(.93,1.07)
verts.append((center[0]+r*x/n*j*stretch[0],center[1]+r*y/n*j*stretch[1],center[2]+r*z/n*j*stretch[2]))
batch.mesh(verts,faces)
# One foundation underlay; route tiles have raised, non-overlapping walkable surfaces.
ground=Mesh("520 x 520 paper foundation",paper,FOUNDATION); ground.box((0,0,-1.0),(SIZE,SIZE,1.8)); ground.finish(.15)
def is_route(i): return i in (-3,0,3)
def road_tile(x,y,horizontal=False,cross=False):
asphalt=Mesh("Crossroads" if cross else "Street module",road,ROADS); asphalt.box((x,y,.14),(39.85,39.85,.28)); asphalt.finish()
side=Mesh("Sidewalk module",walk,ROADS)
if cross:
for sx in (-1,1):
for sy in (-1,1): side.box((x+sx*14.5,y+sy*14.5,.34),(11,11,.16))
side.finish(.025)
stripes=Mesh("Painted crosswalk",lane,ROADS)
for sgn in (-1,1):
for i in range(-2,3):
stripes.box((x+sgn*13,y+i*2.3,.30),(1.25,.62,.04))
stripes.box((x+i*2.3,y+sgn*13,.30),(.62,1.25,.04))
stripes.finish(); return
marks=Mesh("Dashed centerline",lane,ROADS)
if horizontal:
side.box((x,y-15,.34),(39.9,10,.16)); side.box((x,y+15,.34),(39.9,10,.16))
for dx in (-15,-5,5,15): marks.box((x+dx,y,.30),(4.0,.28,.04))
else:
side.box((x-15,y,.34),(10,39.9,.16)); side.box((x+15,y,.34),(10,39.9,.16))
for dy in (-15,-5,5,15): marks.box((x,y+dy,.30),(.28,4.0,.04))
side.finish(.025); marks.finish()
for row in range(-RADIUS,RADIUS+1):
for col in range(-RADIUS,RADIUS+1):
if abs(row)<=1 and abs(col)<=1: continue
h,v=is_route(row),is_route(col)
if h or v: road_tile(col*CELL,row*CELL,horizontal=h and not v,cross=h and v)
# A generous central concourse replaces the cramped four-way tile intersection.
plinth=Mesh("Central rose-stone concourse",plaza_pink,LANDMARKS); plinth.box((0,0,.13),(120,120,.25)); plinth.finish(.08)
spokes=Mesh("Four broad plaza approaches",walk,LANDMARKS)
for yy in (-39,39): spokes.box((0,yy,.31),(16,42,.12))
for xx in (-39,39): spokes.box((xx,0,.31),(42,16,.12))
spokes.finish()
loop=Mesh("Square promenade loop",orange_light,LANDMARKS)
loop.box((0,42,.37),(78,9,.12)); loop.box((0,-42,.37),(78,9,.12))
loop.box((42,0,.37),(9,76,.12)); loop.box((-42,0,.37),(9,76,.12)); loop.finish()
insets=Mesh("Plaza pencil mosaics",seam,LANDMARKS)
for s in (-1,1):
for t in (-1,1):
insets.box((s*28,t*28,.43),(4,4,.06)); insets.box((t*28,s*28,.43),(4,4,.06))
insets.finish()
basin=Mesh("Fountain basin and column",lav,LANDMARKS)
cylinder(basin,(0,0,1.05),11,1.4,28); cylinder(basin,(0,0,1.92),8.5,.24,28)
basin.box((0,0,4.0),(2.3,2.3,4.0)); cylinder(basin,(0,0,6.35),4.0,.65,24,2.4); cylinder(basin,(0,0,6.85),2.0,.25,24); basin.finish(.08)
water_top=Mesh("Bright fountain water",water,LANDMARKS); cylinder(water_top,(0,0,1.8),8.15,.06,32); water_top.finish()
# Reusable house: open ground-floor arcade, two walkable roof levels, gabled crown and pencil grid.
tree_trunks=Mesh("Tree trunks",wood,PROPS); tree_leaves=Mesh("Sage crowns",leaf,PROPS); tree_blossoms=Mesh("Cherry crowns",blossom,PROPS)
lamp_metal=Mesh("Lantern posts",metal,PROPS); lamp_light=Mesh("Lantern warm glass",gold,PROPS)
orange_cover=Mesh("Orange cover blocks",orange,PROPS); cover_ink=Mesh("Orange block linework",orange_light,PROPS)
planters=Mesh("Tree planters",lav,PROPS)
def tree(x,y,pink=False,scale=1):
trunks=10*scale; tree_trunks.box((x,y,trunks/2+.22),(2*scale,2*scale,trunks))
b=tree_blossoms if pink else tree_leaves
ico(b,(x,y,12.4*scale),6.5*scale,int(x*19+y*27+1000))
ico(b,(x-3.2*scale,y+1.3*scale,11*scale),5*scale,int(x*11-y*17+2000))
ico(b,(x+3.3*scale,y-1.1*scale,11.5*scale),4.8*scale,int(x*23+y*9+3000))
planters.box((x,y,.42),(8*scale,8*scale,.5))
def lamp(x,y):
lamp_metal.box((x,y,4.8),(.5,.5,9.2)); lamp_metal.box((x+.8,y,8.9),(2,.45,.4))
lamp_light.box((x+1.5,y,8.2),(1.3,1.1,.9)); lamp_metal.box((x+1.5,y,9.0),(2.2,1.8,.24))
def crate(x,y,z=0.2,sx=7,sy=6,sz=7,a=0):
orange_cover.box((x,y,z+sz/2),(sx,sy,sz),a)
cover_ink.box((x,y-sy/2-.04,z+sz*.56),(sx*.75,.1,.16),a)
def build_house(col,row,index,landmark=None,forced=None):
x,y=col*CELL,row*CELL
rr=random.Random(SEED+(col+9)*1009+(row+9)*2027)
if abs(col)>abs(row): angle=math.pi/2 if col<0 else -math.pi/2
else: angle=0 if row>0 else math.pi
plaster=forced or rr.choice(walls_palette); roofmat=rr.choice(roofs_palette)
w=rr.uniform(25,29); d=rr.uniform(24,29); h=12.0; uh=rr.choice((7.5,8.5,9.5))
uw=w*rr.uniform(.59,.75); ud=d*rr.uniform(.59,.75); passage=7.2
name="Block %02d | %s"%(index,landmark or "paper-plaster walk-up")
root=root_obj(name,x,y,angle,{"GridX":col,"GridY":row,"Stories":2,"RoofAccess":True,"Landmark":landmark or ""})
wa=Mesh(name+" plaster",plaster,BUILDINGS,root); rf=Mesh(name+" roof",roofmat,BUILDINGS,root)
ln=Mesh(name+" ink seams",seam,BUILDINGS,root); dk=Mesh(name+" dark trim",ink,BUILDINGS,root)
gl=Mesh(name+" windows",glass,BUILDINGS,root); ac=Mesh(name+" orange accents",orange_light,BUILDINGS,root); wd=Mesh(name+" cedar",wood,BUILDINGS,root)
zc=h/2+.2
# Solid side walls, but facade panels leave a broad north-south route through the house.
wa.box((-w/2+.7,0,zc),(1.4,d-2,h-.4)); wa.box((w/2-.7,0,zc),(1.4,d-2,h-.4))
for fy in (-d/2,d/2):
panel=(w-passage)/2
wa.box((-(passage/2+panel/2),fy,zc),(panel,1.35,h-.4))
wa.box(((passage/2+panel/2),fy,zc),(panel,1.35,h-.4))
wa.box((0,fy,h-.8),(passage,1.35,1.6))
# Deep cedar arcade reveals make the through-route legible at street level.
dk.box((-passage/2-.22,fy*1.025,h/2),(0.32,.22,h))
dk.box((passage/2+.22,fy*1.025,h/2),(0.32,.22,h))
# Lower roof promenade and its raised orange rim.
rf.box((0,0,h+.22),(w+5,d+5,.55)); dk.box((0,0,h+.55),(w+5.7,d+5.7,.16))
upper_z=h+.7
wa.box((0,0,upper_z+uh/2),(uw,ud,uh))
rf.box((0,0,upper_z+uh+.25),(uw+3.8,ud+3.8,.55))
rf.gable(uw+3.8,ud+3.8,upper_z+uh+.52,rr.uniform(3.2,4.8),over=.65)
ac.box((0,0,upper_z+uh+4),(0.75,ud+5,.45))
# Big paired windows and sills face the road-facing side.
for s in (-1,1):
for level in range(2):
zz=h*(.34+.37*level); wx=s*w*.22
dk.box((wx,-d/2-.12,zz),(5.3,.16,4.6))
gl.box((wx,-d/2-.22,zz),(4.35,.13,3.65))
ac.box((wx,-d/2-.29,zz-2.1),(5.8,.34,.32))
wz=upper_z+uh*.53; wx=s*uw*.23
dk.box((wx,-ud/2-.11,wz),(4.7,.15,3.8)); gl.box((wx,-ud/2-.22,wz),(3.8,.13,2.95))
# Hand-drawn panel grid: offset pencil marks on facade and side elevations.
for gx in range(-int(w/2)+8,int(w/2),8):
if abs(gx)<passage/2+1.1: continue
ln.box((gx+rr.uniform(-.1,.1),-d/2-.30,zc),(0.11,.08,h-.7))
for gz in range(8,int(h),8):
ln.box((0,-d/2-.30,gz+.2),(w-passage-1,.08,.12))
for s in (-1,1):
fx=s*(w/2+.06)
for gy in range(-int(d/2)+8,int(d/2),8): ln.box((fx,gy,zc),(.08,.12,h-.7))
for gz in range(8,int(h),8): ln.box((fx,0,gz+.2),(.08,d-1,.12))
# Wide steps reach the first roof, then a narrower stair reaches the upper deck.
n=14; rise=h/n; run=d-6
for i in range(n):
yy=d/2-3-i*run/(n-1)
rf.box((w/2+3,yy,.2+(i+.5)*rise),(5.2,2.15,rise))
dk.box((w/2+3,yy,.2+(i+1)*rise),(5.35,.10,.12))
n2=11; rise2=uh/n2
for i in range(n2):
yy=ud/2-2-i*(ud-4)/(n2-1)
rf.box((uw/2+2.6,yy,upper_z+(i+.5)*rise2),(2.5,1.9,rise2))
for i in range(rr.randint(1,3)):
cx=rr.choice((-1,1))*rr.uniform(4,8); cy=rr.choice((-1,1))*rr.uniform(4,8)
ac.box((cx,cy,h+1.4),(rr.uniform(4,7),rr.uniform(3,5),2.8))
if landmark=="Clock tower":
rf.box((0,0,upper_z+uh+5),(11,11,9)); ac.box((0,0,upper_z+uh+9.8),(13,13,.65))
for a in range(4):
q=a*math.pi/2; gl.box((math.cos(q)*5.56,math.sin(q)*5.56,upper_z+uh+5),(2.3,.2,2.3),q)
elif landmark=="Pagoda lookout":
for k in range(3):
zz=upper_z+uh+k*4.6
rf.box((0,0,zz+1.7),(16-3*k,16-3*k,3.2)); ac.box((0,0,zz+3.5),(20-3*k,20-3*k,.55))
rf.box((0,0,upper_z+uh+14),(2.4,2.4,4.2))
elif landmark=="Market arcade":
for k in (-1,0,1):
ac.box((k*7,-d/2-1,h*.7),(5.6,1,3.8)); gl.box((k*7,-d/2-1.4,h*.31),(3.4,.16,3.0))
elif landmark=="Garden pavilion":
for xx in (-7,7):
for yy in (-7,7): wd.box((xx,yy,upper_z+uh+2.2),(1.2,1.2,4.5))
ac.box((0,0,upper_z+uh+4.8),(22,22,.7))
for b in (wa,rf,ln,dk,gl,ac,wd): b.finish(.045 if b in (wa,rf,ac) else 0)
return root
slots={(-4,4):("Clock tower",cream),(4,4):("Pagoda lookout",rose),(4,-4):("Market arcade",peach),(-4,-4):("Garden pavilion",blue)}
court_slots={(-5,-5),(-5,5),(5,-5),(5,5),(-2,-2),(-2,2),(2,-2),(2,2),
(-4,-2),(-4,2),(4,-2),(4,2),(-2,-4),(2,-4),(-2,4),(2,4),
(-6,-4),(-6,4),(6,-4),(6,4),(-4,-6),(4,-6),(-4,6),(4,6)}
def build_courtyard(col,row,index):
x,y=col*CELL,row*CELL
root=root_obj("Garden court %02d | open four-way passage"%index,x,y,0,
{"GridX":col,"GridY":row,"RouteAccess":True,"LotType":"Courtyard"})
stone=Mesh(root.name+" paving",walk,LANDMARKS,root)
grass=Mesh(root.name+" planted island",green,LANDMARKS,root)
border=Mesh(root.name+" chalk edging",lav,LANDMARKS,root)
woodwork=Mesh(root.name+" benches and gates",wood,LANDMARKS,root)
trim=Mesh(root.name+" orange wayfinding",orange_light,LANDMARKS,root)
stone.box((0,0,.2),(36,36,.25))
grass.box((-7,7,.37),(11,11,.12))
# Low walls protect the garden but leave all four sides open for a readable shortcut.
for sign in (-1,1):
for side in (-1,1):
border.box((sign*17,side*11,1.8),(2,12,3.2))
border.box((side*11,sign*17,1.8),(12,2,3.2))
border.box((sign*17,0,3.5),(2,9,.45))
border.box((0,sign*17,3.5),(9,2,.45))
woodwork.box((6,-7,.9),(8,1.1,1.4)); woodwork.box((6,-9,.52),(8,1.1,.24))
trim.box((0,0,.46),(2.4,2.4,.12))
for b in (stone,grass,border,woodwork,trim): b.finish(.035 if b in (stone,border) else 0)
tree(x-7,y+7,blossom=(index%3==0),scale=.62)
house_count=0; court_count=0
for row in range(-RADIUS,RADIUS+1):
for col in range(-RADIUS,RADIUS+1):
if abs(row)<=1 and abs(col)<=1: continue
if is_route(row) or is_route(col): continue
slot=slots.get((col,row))
if (col,row) in court_slots and not slot:
court_count+=1; build_courtyard(col,row,court_count)
else:
house_count+=1
build_house(col,row,house_count,slot[0] if slot else None,slot[1] if slot else None)
# Elevated links connect adjacent roof walks across the side boulevards.
bridge=Mesh("Four raised rooftop crossovers",slate2,ROOFS)
rails=Mesh("Bridge ink railings",ink,ROOFS)
bridge_marks=Mesh("Bridge orange route markers",orange_light,ROOFS)
for x in (-120,120):
for y in (-60,60):
bridge.box((x,y,12.95),(54,8.2,.7))
for s in (-1,1): rails.box((x,y+s*4.1,14.2),(54,.38,2.2))
for dx in (-18,18): bridge_marks.box((x+dx,y,13.34),(.65,6.3,.08))
bridge.finish(.07); rails.finish(.04); bridge_marks.finish()
# Outer ramparts stop at marked cardinal gates; the south arch frames portal entry.
rampart=Mesh("Low lavender arena ramparts",lav,WALLS)
rampart_caps=Mesh("Slate rampart caps",slate,WALLS)
rampart_lines=Mesh("Rampart pencil seams",seam,WALLS)
hwall=23.0
for edge in (-SIZE/2,SIZE/2):
for c in range(-RADIUS,RADIUS+1):
if c==0: continue
x=c*CELL; rampart.box((x,edge,hwall/2),(CELL-.4,2.8,hwall)); rampart_caps.box((x,edge,hwall+.24),(CELL-.2,4.4,.55))
rampart_lines.box((x-CELL/2+2,edge-1.5,hwall/2),(.14,.08,hwall-1))
# Gate pillars at each north/south opening.
for s in (-1,1):
xx=s*32; rampart.box((xx,edge,14),(10,8,28)); rampart_caps.box((xx,edge,28.4),(13,10,.8))
rampart.box((0,edge,29),(52,8,4)); rampart_caps.box((0,edge,31.5),(56,10,.9))
for edge in (-SIZE/2,SIZE/2):
for r in range(-RADIUS,RADIUS+1):
if r==0: continue
y=r*CELL; rampart.box((edge,y,hwall/2),(2.8,CELL-.4,hwall)); rampart_caps.box((edge,y,hwall+.24),(4.4,CELL-.2,.55))
rampart_lines.box((edge-1.5,y-CELL/2+2,hwall/2),(.08,.14,hwall-1))
rampart.finish(.10); rampart_caps.finish(.07); rampart_lines.finish()
gate=Mesh("South portal arch plaster",cream,WALLS); gate_roof=Mesh("South portal arch orange canopy",orange,WALLS); gate_ink=Mesh("South gate pencil trim",ink,WALLS)
for x in (-17,17):
gate.box((x,-238,13.5),(5.5,8,27)); gate_roof.box((x,-238,27.4),(7,10,1)); gate_ink.box((x,-233.8,13.5),(.15,.12,25))
gate.box((0,-238,29),(39,8,4.5)); gate_roof.box((0,-238,31.8),(43,10,1))
gate.finish(.1); gate_roof.finish(.08); gate_ink.finish()
# Avenues carry cover islands, garden corners and regular lamps; district corners get blossom trees.
cover=Mesh("Orange combat cover",orange,PROPS); cover_marks=Mesh("Cover pencil stripes",orange_light,PROPS)
for i,(x,y) in enumerate([(-205,-205),(-165,-195),(-65,-205),(70,-205),(205,-195),(200,-65),(205,55),(195,200),(70,205),(-65,205),(-205,190),(-205,60),(-195,-65),(-70,70),(70,-70),(185,170),(-170,165)]):
sx=RNG.uniform(5,9); sy=RNG.uniform(4,7); sz=RNG.uniform(5,10); a=RNG.choice((0,0,math.pi/4))
cover.box((x,y,.2+sz/2),(sx,sy,sz),a); cover_marks.box((x,y-sy/2-.05,.2+sz*.55),(sx*.72,.12,.16),a)
cover.finish(.06); cover_marks.finish()
for row in range(-RADIUS,RADIUS+1):
for col in range(-RADIUS,RADIUS+1):
if not (is_route(row) or is_route(col)) or (abs(row)<=1 and abs(col)<=1): continue
x,y=col*CELL,row*CELL
if row%2==0 and col in (-3,3): lamp_metal.box((x+12,y-11,4.8),(.5,.5,9.2)); lamp_metal.box((x+12.8,y-11,8.9),(2,.45,.4)); lamp_light.box((x+13.5,y-11,8.2),(1.3,1.1,.9)); lamp_metal.box((x+13.5,y-11,9),(2.2,1.8,.24))
if col%2==0 and row in (-3,3): lamp_metal.box((x-11,y+12,4.8),(.5,.5,9.2)); lamp_metal.box((x-10.2,y+12,8.9),(2,.45,.4)); lamp_light.box((x-9.5,y+12,8.2),(1.3,1.1,.9)); lamp_metal.box((x-9.5,y+12,9),(2.2,1.8,.24))
for cross_col in (-3,3):
for cross_row in (-3,3):
for sx in (-1,1):
for sy in (-1,1):
tree(cross_col*CELL+sx*14.5,cross_row*CELL+sy*14.5,
blossom=((cross_col+cross_row+sx+sy)%3==0),scale=.58)
for b in (tree_trunks,tree_leaves,tree_blossoms,lamp_metal,lamp_light,planters): b.finish(.045 if b in (tree_trunks,planters) else 0)
# The central hub connects to the nearby avenue modules with straight, readable approach paths.
approach=Mesh("Four plaza to boulevard connectors",walk,LANDMARKS)
for s in (-1,1):
approach.box((0,s*80,.31),(15,40,.13)); approach.box((s*80,0,.31),(40,15,.13))
approach.finish()
# Bright afternoon replaces the old night presentation; soft shadows reveal height changes.
world=bpy.data.worlds.new("Clear blue paper sky"); scene.world=world; world.use_nodes=True
world.node_tree.nodes.clear()
background=world.node_tree.nodes.new("ShaderNodeBackground")
output=world.node_tree.nodes.new("ShaderNodeOutputWorld")
world.node_tree.links.new(background.outputs["Background"],output.inputs["Surface"])
background.inputs["Color"].default_value=(.42,.72,.93,1)
background.inputs["Strength"].default_value=.65
sun_data=bpy.data.lights.new("Late morning sun","SUN"); sun_data.energy=2.1; sun_data.angle=math.radians(20)
sun=bpy.data.objects.new("Late morning sun",sun_data); SETUP.objects.link(sun); sun.rotation_euler=(math.radians(28),math.radians(-25),math.radians(-32))
area_data=bpy.data.lights.new("Broad sky fill","AREA"); area_data.energy=110000; area_data.shape="DISK"; area_data.size=420
area=bpy.data.objects.new("Broad sky fill",area_data); SETUP.objects.link(area); area.location=(-120,-230,470); area.rotation_euler=(Vector((0,0,0))-area.location).to_track_quat("-Z","Y").to_euler()
camdata=bpy.data.cameras.new("Three-quarter city overview"); cam=bpy.data.objects.new("Three-quarter city overview",camdata); SETUP.objects.link(cam)
cam.location=(610,-720,790); cam.rotation_euler=(Vector((0,0,2))-Vector(cam.location)).to_track_quat("-Z","Y").to_euler(); camdata.type="ORTHO"; camdata.ortho_scale=810; camdata.clip_end=4000; camdata.clip_start=.1; scene.camera=cam
scene.render.engine="CYCLES"; scene.cycles.samples=20; scene.cycles.use_denoising=True
scene.render.resolution_x=1800; scene.render.resolution_y=1400; scene.render.resolution_percentage=80
scene.render.image_settings.file_format="PNG"; scene.render.image_settings.color_mode="RGBA"; scene.render.film_transparent=False
scene.view_settings.view_transform="AgX"; scene.view_settings.look="AgX - Medium High Contrast"
scene.render.filepath=RENDER_OUT; scene.render.use_file_extension=True
scene["ArenaSize"]="520 x 520 studs"; scene["Seed"]=SEED
scene["RoutePlan"]="Six connected arterial lines; central square promenade loop; through-houses; four rooftop bridges; pocket-garden detours"
scene["HouseModules"]=house_count; scene["GardenCourts"]=court_count; scene["ArtDirection"]="Bright hand-drawn pastel city, ink-grid plaster, orange slate, graphite streets"
bpy.ops.wm.save_as_mainfile(filepath=BLEND_OUT)
bpy.ops.render.render(write_still=True)
result={"blend":BLEND_OUT,"render":RENDER_OUT,"seed":SEED,"arena_size":[520,520],"building_modules":house_count,"scene_objects":len(scene.objects)}
print(result)
+25
View File
@@ -0,0 +1,25 @@
import bpy, numpy as np, os
N=2048
rng=np.random.default_rng(183)
yy,xx=np.mgrid[0:N,0:N].astype(np.float32)
# Four 512px cells; one texture repeat = 32 studs, each cell = 8 studs.
x=xx+1.8*np.sin(yy*2*np.pi/512)+.55*np.sin(yy*2*np.pi/64)
y=yy+1.8*np.sin(xx*2*np.pi/512+1.2)+.55*np.sin(xx*2*np.pi/64)
qx=np.abs(x%512-256)-(256-11-2.4)
qy=np.abs(y%512-256)-(256-11-2.4)
dist=np.sqrt(np.maximum(qx,0)**2+np.maximum(qy,0)**2)+np.minimum(np.maximum(qx,qy),0)-11
fill=np.clip(.5-dist/1.4,0,1).astype(np.float32)
paper=rng.normal(0,.0015,(N,N)).astype(np.float32)
folder=r"C:\roblox\hunter\3D models\game_zone\textures"
os.makedirs(folder,exist_ok=True)
for filename,base,ink in [
("HD_navy.png",(.115,.17,.25),(.22,.25,.28)),
("HD_amber.png",(1,.57,.045),(.50,.25,.025)),
("HD_floor.png",(.25,.31,.40),(.13,.17,.23))]:
arr=np.ones((N,N,4),np.float32)
for i in range(3):
arr[:,:,i]=np.clip(ink[i]+fill*(base[i]-ink[i])+paper,0,1)
im=bpy.data.images.new(filename,width=N,height=N,alpha=True)
im.pixels.foreach_set(arr.ravel());im.filepath_raw=os.path.join(folder,filename);im.file_format="PNG";im.save();im.pack()
result={"textures":"2048x2048; 512 pixels per 8-stud tile"}
+376
View File
@@ -0,0 +1,376 @@
"""Detailed, connected two-storey house prototype; 1 Blender unit = 1 stud."""
import bpy, math, os
from mathutils import Vector
ROOT = r"C:\roblox\hunter"
BLEND_OUT = os.path.join(ROOT, "3D models", "game_zone", "Hunter_House_Prototype.blend")
RENDER_OUT = os.path.join(ROOT, "renders", "hunter_house_prototype.png")
os.makedirs(os.path.dirname(BLEND_OUT), exist_ok=True)
os.makedirs(os.path.dirname(RENDER_OUT), exist_ok=True)
for old in list(bpy.data.scenes):
if old.name.startswith("Hunter House Prototype"):
bpy.data.scenes.remove(old, do_unlink=True)
scene = bpy.data.scenes.new("Hunter House Prototype | connected rooms and stairs")
if bpy.context.window:
bpy.context.window.scene = scene
def collection(name):
c = bpy.data.collections.new(name)
scene.collection.children.link(c)
return c
ARCH = collection("01 Shell and plaster")
FLOORS = collection("02 Floors and roof decks")
DOORS = collection("03 Doors and hardware")
WINDOWS = collection("04 Windows and reveals")
INTERIOR = collection("05 Furnished interior")
STAIRS = collection("06 Connected roof stair")
TRIM = collection("07 Pencil trim")
SET = collection("08 Stage, lighting and camera")
def mat(name, color, rough=.82, metal=0, transmission=0, emission=0):
m = bpy.data.materials.new(name)
m.diffuse_color = (*color, 1)
m.use_nodes = True
p = next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
if p:
p.inputs["Base Color"].default_value = (*color, 1)
p.inputs["Roughness"].default_value = rough
p.inputs["Metallic"].default_value = metal
if "Transmission Weight" in p.inputs:
p.inputs["Transmission Weight"].default_value = transmission
if emission:
p.inputs["Emission Color"].default_value = (*color, 1)
p.inputs["Emission Strength"].default_value = emission
return m
plaster = mat("Pale lavender plaster", (.58,.63,.82))
chalk = mat("Chalk edge", (.81,.83,.93))
interior = mat("Warm ivory interior", (.88,.78,.66))
ink = mat("Deep indigo outline", (.12,.15,.25))
pencil = mat("Slate pencil lines", (.29,.33,.47))
slate = mat("Blue violet slate", (.22,.25,.40), .74)
slate_light = mat("Sunlit slate edge", (.39,.44,.61), .76)
terra = mat("Terracotta tile", (.92,.38,.24))
orange = mat("Orange highlight", (1,.60,.37))
walnut = mat("Walnut door", (.30,.17,.12), .72)
cedar = mat("Raised cedar panel", (.48,.29,.19), .78)
brass = mat("Brushed brass hardware", (.78,.49,.18), .32,.62)
glass = mat("Turquoise glazing", (.42,.80,.86), .15,.04,.68)
# Mix a clear dielectric with a small tint so room geometry remains visible through the pane.
glass.node_tree.nodes.clear()
glass_out=glass.node_tree.nodes.new("ShaderNodeOutputMaterial")
glass_clear=glass.node_tree.nodes.new("ShaderNodeBsdfTransparent")
glass_tint=glass.node_tree.nodes.new("ShaderNodeBsdfPrincipled")
glass_tint.inputs["Base Color"].default_value=(.24,.64,.72,1)
glass_tint.inputs["Roughness"].default_value=.12
glass_mix=glass.node_tree.nodes.new("ShaderNodeMixShader")
glass_mix.inputs[0].default_value=.72
glass.node_tree.links.new(glass_tint.outputs["BSDF"],glass_mix.inputs[1])
glass.node_tree.links.new(glass_clear.outputs["BSDF"],glass_mix.inputs[2])
glass.node_tree.links.new(glass_mix.outputs[0],glass_out.inputs["Surface"])
linen = mat("Warm linen curtains", (.94,.84,.73), .95)
teal = mat("Teal sofa", (.24,.54,.58))
rose = mat("Rose wool rug", (.68,.40,.48))
oak = mat("Oak floor", (.46,.31,.23))
stone = mat("Paper stone", (.76,.71,.70), .92)
green = mat("Planter green", (.32,.55,.40))
amber = mat("Amber lantern glass", (1,.68,.3), .4,0,0,1.5)
metal_dark = mat("Blue charcoal metal", (.13,.18,.27), .55,.3)
def cube(name, loc, dims, material, coll, angle=0, bevel=0):
x,y,z = dims
v = [(-x/2,-y/2,-z/2),(x/2,-y/2,-z/2),(x/2,y/2,-z/2),(-x/2,y/2,-z/2),
(-x/2,-y/2,z/2),(x/2,-y/2,z/2),(x/2,y/2,z/2),(-x/2,y/2,z/2)]
f = [(0,3,2,1),(4,5,6,7),(0,1,5,4),(1,2,6,5),(2,3,7,6),(3,0,4,7)]
me = bpy.data.meshes.new(name+" mesh")
me.from_pydata(v, [], f)
me.materials.append(material)
me.update()
ob = bpy.data.objects.new(name, me)
coll.objects.link(ob)
ob.location = loc
ob.rotation_euler[2] = angle
if bevel:
b = ob.modifiers.new("Soft hand-cut edge", "BEVEL")
b.width, b.segments, b.limit_method = bevel, 2, "ANGLE"
ob.modifiers.new("Weighted normals", "WEIGHTED_NORMAL")
return ob
def beam(name, a, b, width, depth, material, coll):
a,b = Vector(a),Vector(b)
d=b-a
ob=cube(name,(a+b)/2,(width,depth,d.length),material,coll)
ob.rotation_euler=d.to_track_quat("Z","Y").to_euler()
return ob
def gable(name,w,d,z,rise,material,coll):
x,y=w/2,d/2
v=[(-x,-y,z),(x,-y,z),(x,y,z),(-x,y,z),(0,-y,z+rise),(0,y,z+rise)]
me=bpy.data.meshes.new(name+" mesh")
me.from_pydata(v,[],[(0,1,4),(3,5,2),(0,4,5,3),(1,2,5,4),(0,3,2,1)])
me.materials.append(material); me.update()
ob=bpy.data.objects.new(name,me); coll.objects.link(ob)
return ob
def facade(name, axis, plane, width, height, base, thickness, openings):
"""Construct wall panels around true empty apertures."""
edges={-width/2,width/2}
for u,w,lo,hi in openings:
edges.update((u-w/2,u+w/2))
e=sorted(edges)
for a,b in zip(e[:-1],e[1:]):
u=(a+b)/2
op=next((q for q in openings if q[0]-q[1]/2-1e-5<=u<=q[0]+q[1]/2+1e-5),None)
def panel(z,h):
if h<=.04:return
pos=(u,plane,z+h/2) if axis=="front" else (plane,u,z+h/2)
size=(b-a,thickness,h) if axis=="front" else (thickness,b-a,h)
cube(name+" | wall panel",pos,size,plaster,ARCH,0,.025)
if op is None:
panel(base,height)
else:
low,high=op[2],op[3]
panel(base,low)
panel(high,height-high)
def window(name,axis,plane,u,z,width,height,thickness,side=-1):
if axis=="front":
outer_y=plane+side*(thickness/2+.08)
pane_y=plane+side*.12
inner_y=plane-side*.34
def box(n,du,dv,dz,x,y,zz,ma):
cube(name+" | "+n,(x,y,zz),(du,dv,dz),ma,WINDOWS,0,.025)
box("left reveal",.30,.22,height+.4,u-width/2-.12,outer_y,z,ink)
box("right reveal",.30,.22,height+.4,u+width/2+.12,outer_y,z,ink)
box("head reveal",width+.55,.22,.32,u,outer_y,z+height/2+.12,ink)
box("stone sill",width+.72,.52,.40,u,outer_y+side*.14,z-height/2-.12,chalk)
cube(name+" | fitted glass",(u,pane_y,z),(width-.48,.12,height-.46),glass,WINDOWS,0,.02)
cube(name+" | central mullion",(u,pane_y+side*.10,z),(.16,.15,height-.42),ink,WINDOWS,0,.02)
for s in (-1,1):
cube(name+" | linen curtain",(u+s*(width/2-.55),inner_y,z),(.62,.12,height-.32),linen,WINDOWS,0,.025)
cube(name+" | brass curtain rod",(u,inner_y,z+height/2-.12),(width+.18,.15,.14),brass,WINDOWS,0,.02)
else:
outer_x=plane+side*(thickness/2+.08)
pane_x=plane+side*.12
inner_x=plane-side*.34
def box(n,du,dv,dz,x,y,zz,ma):
cube(name+" | "+n,(x,y,zz),(dv,du,dz),ma,WINDOWS,0,.025)
box("left reveal",.30,.22,height+.4,u-width/2-.12,outer_x,z,ink)
box("right reveal",.30,.22,height+.4,u+width/2+.12,outer_x,z,ink)
box("head reveal",width+.55,.22,.32,u,outer_x,z+height/2+.12,ink)
box("stone sill",width+.72,.52,.40,u,outer_x+side*.14,z-height/2-.12,chalk)
cube(name+" | fitted glass",(pane_x,u,z),(.12,width-.48,height-.46),glass,WINDOWS,0,.02)
cube(name+" | central mullion",(pane_x+side*.10,u,z),(.15,.16,height-.42),ink,WINDOWS,0,.02)
for s in (-1,1):
cube(name+" | linen curtain",(inner_x,u+s*(width/2-.55),z),(.12,.62,height-.32),linen,WINDOWS,0,.025)
cube(name+" | brass curtain rod",(inner_x,u,z+height/2-.12),(.15,width+.18,.14),brass,WINDOWS,0,.02)
def hinged_door(name,hinge_x,plane,zbase,width,height):
angle=math.radians(64)
def pos(u,v,z):
return (hinge_x+u*math.cos(angle)-v*math.sin(angle),
plane+.18+u*math.sin(angle)+v*math.cos(angle),zbase+z)
center=pos(width*.48,0,height/2)
cube(name+" | leaf",center,(width-.22,.34,height-.18),walnut,DOORS,angle,.055)
def piece(label,u,v,z,du,dv,dz,material):
cube(name+" | "+label,pos(u,v,z),(du,dv,dz),material,DOORS,angle,.025)
for z in (height*.27,height*.70):
piece("raised cedar panel",width*.48,-.20,z,width*.62,.12,height*.29,cedar)
piece("brass handle",width*.84,-.34,height*.48,.18,.14,.20,brass)
piece("key plate",width*.84,-.33,height*.39,.14,.12,.27,brass)
for z in (height*.18,height*.50,height*.82):
piece("hinge",.12,-.34,z,.36,.16,.18,brass)
# House shell: 34 x 30 footprint, cut openings, two complete levels.
W,D=34.0,30.0
BASE,H,TH=1.0,11.7,1.25
FRONT=-D/2
TOP=BASE+H
cube("Paper stone stage",(0,0,-.55),(108,96,.5),stone,SET,0,.14)
cube("Dark foundation footing",(0,0,.13),(36,32,.72),ink,ARCH,0,.10)
cube("Lavender foundation course",(0,0,.55),(35.5,31.5,.32),chalk,ARCH,0,.05)
cube("Oak ground floor",(0,0,.82),(34.4,30.4,.20),oak,FLOORS,0,.035)
cube("West exterior wall",(-W/2+.55,0,BASE+H/2),(1.1,D-1,H),plaster,ARCH,0,.04)
facade("East side window wall","side",W/2-.55,D-1,H,BASE,1.1,[(1.0,5.2,4.0,8.0)])
cube("Rear exterior wall",(0,D/2-.55,BASE+H/2),(W,1.1,H),plaster,ARCH,0,.04)
facade("Front ground facade","front",FRONT,W,H,BASE,TH,
[(-8.5,5.4,3.1,7.7),(0,4.8,0,8.5),(8.5,5.4,3.1,7.7)])
facade("Rear patio door aperture","front",D/2-.55,W,H,BASE,1.1,[(0,4.3,0,8.4)])
# Glazing is recessed into the true holes; curtains, furniture and shelves sit behind each pane.
window("Living room window","front",FRONT,-8.5,BASE+5.4,5.4,4.6,TH,-1)
window("Kitchen window","front",FRONT,8.5,BASE+5.4,5.4,4.6,TH,-1)
window("East living-room window","side",W/2-.55,1,BASE+6,5.2,4,1.1,1)
cube("Interior rear lining",(0,D/2-1.25,BASE+H/2),(W-2,.18,H-.5),interior,INTERIOR,0,.02)
cube("Ceiling underside",(0,0,TOP-.16),(33.5,29.5,.20),interior,INTERIOR,0,.025)
for x in (-12,0,12): cube("Exposed ceiling beam",(x,0,TOP-.34),(.42,29,.35),walnut,INTERIOR,0,.04)
cube("Rose living-room rug",(-7,-2,1.0),(11,8,.1),rose,INTERIOR,0,.06)
cube("Sofa seat",(-8,3,2),(9,3.1,1.4),teal,INTERIOR,0,.13)
cube("Sofa back",(-8,4.15,3),(9,.95,2.3),teal,INTERIOR,0,.12)
for x in (-11.1,-4.9): cube("Sofa arm",(x,3,2.8),(1,3.2,1.8),teal,INTERIOR,0,.12)
for x in (-10.3,-8,-5.7): cube("Sofa cushion",(x,2.45,2.7),(2.1,1.6,.34),chalk,INTERIOR,0,.07)
cube("Coffee table top",(-7,-2.3,2.2),(6,3.2,.26),walnut,INTERIOR,0,.08)
for x in (-9.2,-4.8):
for y in (-3.3,-1.3): cube("Coffee table leg",(x,y,1.65),(.2,.2,1.05),walnut,INTERIOR,0,.02)
cube("Kitchen lower cabinets",(9,7,2.3),(10,3,2.7),chalk,INTERIOR,0,.06)
cube("Kitchen countertop",(9,6.7,3.78),(10.8,3.6,.32),ink,INTERIOR,0,.06)
cube("Kitchen backsplash",(9,8.1,5.1),(9.8,.18,2.2),interior,INTERIOR,0,.02)
cube("Kitchen wall cabinet",(9,7.9,6.8),(8,1.1,2.1),plaster,INTERIOR,0,.05)
cube("Sink",(9,6.1,3.98),(2.5,1.6,.12),metal_dark,INTERIOR,0,.03)
cube("Bookshelf",(-13,7,4.5),(3,1,7),walnut,INTERIOR,0,.05)
for z in (2.5,4.4,6.3): cube("Bookshelf shelf",(-13,6.4,z),(3.1,.18,.18),cedar,INTERIOR,0,.02)
for x,z,m in [(-13.8,3.3,terra),(-13,3.3,slate),(-12.3,3.3,orange),(-13.6,5.3,green),(-12.7,5.3,terra)]:
cube("Book spine",(x,6.25,z),(.48,.26,1.5),m,INTERIOR,0,.02)
cube("Dining table",(2,7,2.25),(6,4,.28),walnut,INTERIOR,0,.06)
for x in (-.4,4.4):
for y in (5.7,8.3): cube("Dining chair",(x,y,1.75),(1.2,1.2,1.3),cedar,INTERIOR,0,.04)
# Real entrance door with casing and brass handle; open leaf reveals the living room.
for x in (-2.55,2.55): cube("Main door jamb",(x,FRONT-.16,BASE+4.25),(.42,.36,8.5),ink,DOORS,0,.035)
cube("Main door header",(0,FRONT-.16,BASE+8.55),(5.5,.36,.4),ink,DOORS,0,.035)
cube("Main door threshold",(0,FRONT-.4,1.05),(5.25,1,.28),chalk,DOORS,0,.035)
hinged_door("Walnut main entrance",-2.35,FRONT,BASE,4.5,8.35)
# Rear service door is closed, framed, and panelled.
cube("Rear patio door leaf",(0,D/2-1.24,BASE+4.1),(4.05,.24,8.05),walnut,DOORS,0,.045)
for x in (-2.34,2.34): cube("Rear patio door jamb",(x,D/2-1.4,BASE+4.1),(.34,.34,8.45),ink,DOORS,0,.035)
cube("Rear patio door header",(0,D/2-1.4,BASE+8.3),(5,.34,.34),ink,DOORS,0,.035)
for z in (BASE+2.6,BASE+5.7): cube("Rear door raised panel",(0,D/2-1.39,z),(2.7,.10,2.25),cedar,DOORS,0,.03)
cube("Rear door brass latch",(1.2,D/2-1.34,BASE+4.1),(.16,.13,.22),brass,DOORS,0,.035)
# Walkable first roof terrace and second furnished floor.
cube("First roof terrace deck",(0,0,TOP+.34),(40,36,.68),slate,FLOORS,0,.09)
cube("Terrace front terracotta fascia",(0,-18.2,TOP+.34),(40.3,.34,.62),terra,TRIM,0,.035)
cube("Terrace east terracotta fascia",(20,0,TOP+.34),(.34,36.3,.62),terra,TRIM,0,.035)
UW,UD=22.5,20.5
UB, UH = TOP+.70, 9.0
UT=UB+UH
cube("Upper west wall",(-UW/2+.5,0,UB+UH/2),(1,UD,UH),plaster,ARCH,0,.035)
cube("Upper east wall",(UW/2-.5,0,UB+UH/2),(1,UD,UH),plaster,ARCH,0,.035)
cube("Upper rear wall",(0,UD/2-.5,UB+UH/2),(UW,1,UH),plaster,ARCH,0,.035)
facade("Upper front facade","front",-UD/2,UW,UH,UB,1,
[(-6.6,4.6,2.1,6.1),(0,4,0,7.4),(6.6,4.6,2.1,6.1)])
cube("Upper oak floor",(0,0,UB+.12),(UW-1,UD-1,.20),oak,INTERIOR,0,.03)
cube("Upper room rear lining",(0,UD/2-1,UB+UH/2),(UW-1,.16,UH-.4),interior,INTERIOR,0,.02)
cube("Study desk",(0,5,UB+1.65),(8,3.4,.28),walnut,INTERIOR,0,.06)
for x in (-3.2,3.2): cube("Study desk leg",(x,5,UB+.85),(.2,.2,1.4),walnut,INTERIOR,0,.02)
cube("Study chair",(0,1.3,UB+1.45),(2,1.8,.4),teal,INTERIOR,0,.05)
cube("Study bookcase",(-8.5,5.5,UB+4.1),(2.4,.9,6.6),walnut,INTERIOR,0,.045)
for z in (UB+2.6,UB+4.4,UB+6.2): cube("Study shelf",(-8.5,4.95,z),(2.5,.18,.18),cedar,INTERIOR,0,.02)
for x,z,m in [(-9,UB+3.4,terra),(-8.4,UB+3.4,slate),(-7.8,UB+3.4,orange),(-8.7,UB+5.4,green)]:
cube("Study books",(x,4.8,z),(.38,.24,1.3),m,INTERIOR,0,.02)
window("Upper study left window","front",-UD/2,-6.6,UB+4.1,4.6,4.6,1,-1)
window("Upper study right window","front",-UD/2,6.6,UB+4.1,4.6,4.6,1,-1)
for x in (-2.2,2.2): cube("Upper terrace door jamb",(x,-UD/2-.14,UB+3.7),(.35,.3,7.4),ink,DOORS,0,.035)
cube("Upper terrace door header",(0,-UD/2-.14,UB+7.55),(4.5,.3,.36),ink,DOORS,0,.035)
hinged_door("Upper terrace door",-1.9,-UD/2,UB,3.8,7.4)
# Pitched slate crown has no stair leading to an unusable roof.
cube("Upper roof eaves slab",(0,0,UT+.25),(UW+4.4,UD+4,.62),slate,FLOORS,0,.07)
gable("Upper pitched roof",UW+4.8,UD+4.4,UT+.5,5.9,slate,ARCH)
beam("Terracotta ridge cap",(0,-UD/2-2.6,UT+6.25),(0,UD/2+2.6,UT+6.25),.8,.65,terra,TRIM)
for s in (-1,1):
beam("Front gable ink rake",(0,-UD/2-2.35,UT+6.1),(s*(UW/2+2.35),-UD/2-2.35,UT+.35),.18,.18,ink,TRIM)
beam("Rear gable ink rake",(0,UD/2+2.35,UT+6.1),(s*(UW/2+2.35),UD/2+2.35,UT+.35),.18,.18,ink,TRIM)
# Connected stair: ground landing -> 17 touching treads -> roof landing, with rails and support piers.
sx,y0,y1=20.1,13.0,-12.4
level,bottom=TOP+.68,.82
count=17
rise=(level-bottom)/count
run=(y0-y1)/(count-1)
cube("Stair ground landing",(sx,14.8,.56),(7.4,6.5,.48),chalk,STAIRS,0,.055)
cube("Stair roof landing",(sx,-13,level-.24),(8.4,5,.48),slate_light,STAIRS,0,.055)
for i in range(count):
y=y0-i*run
top=bottom+(i+1)*rise
cube("Roof stair tread %02d"%i,(sx,y,top-rise/2),(5.9,run+.18,rise),terra if i%2==0 else orange,STAIRS,0,.02)
cube("Dark tread nosing %02d"%i,(sx,y-run/2,top-.04),(5.85,.10,.08),ink,STAIRS,0,.012)
for side in (-1,1):
x=sx+side*3.15
beam("Continuous stair stringer",(x,y0+run/2,.88),(x,y1-run/2,level-.18),.42,.52,ink,STAIRS)
beam("Wood stair handrail",(x,y0+run/2,2.3),(x,y1-run/2,level+1.42),.32,.30,walnut,STAIRS)
for i in (0,4,8,12,16):
y=y0-i*run
z=bottom+(i+1)*rise
cube("Handrail upright",(x,y,z+.68),(.28,.28,1.4),ink,STAIRS,0,.03)
# Vertical piers physically meet the underside of the flight.
for yy in (8.4,1,-6.2):
zunder=bottom+(y0-yy)/(y0-y1)*(level-bottom)-.62
for side in (-1,1):
cube("Stair support pier",(sx+side*2.15,yy,max(.85,zunder/2)),(.42,.5,max(.45,zunder-.18)),chalk,STAIRS,0,.03)
# Terrace rails preserve a wide stair entrance and an open apron at the upper door.
gz=level+1.25
cube("West terrace guardrail",(-18.7,0,gz),(.34,30,1.1),ink,STAIRS,0,.03)
for y,l in ((-1,11),(11,7)): cube("East terrace guardrail",(18.7,y,gz),(.34,l,1.1),ink,STAIRS,0,.03)
for y in (-17.1,17.1):
for x,l in ((-14,8),(14,8)): cube("Terrace end guardrail",(x,y,gz),(l,.34,1.1),ink,STAIRS,0,.03)
for x in (-18.7,18.7):
for y in (-13,13): cube("Terrace rail post",(x,y,gz),(.46,.46,1.4),chalk,STAIRS,0,.045)
# Pencil grid seams stop at windows and the front door opening.
fy=FRONT-.72
for z in (BASE+2.0,BASE+9.6):
spans=[(-W/2,W/2)]
for cx,ow,lo,hi in [(-8.5,5.4,3.1,7.7),(0,4.8,0,8.5),(8.5,5.4,3.1,7.7)]:
if lo-.1<=z-BASE<=hi+.1:
spans=[p for a,b in spans for p in ((a,min(b,cx-ow/2)),(max(a,cx+ow/2),b)) if p[1]-p[0]>.3]
for a,b in spans: cube("Broken pencil course",((a+b)/2,fy,z),(b-a,.07,.12),pencil,TRIM,0,.008)
for x in (-16,-11.4,-5.6,5.6,11.4,16):
cube("Front pencilled joint",(x,fy,BASE+H/2),(.11,.07,H-.4),pencil,TRIM,0,.008)
for side in (-1,1):
x=side*(W/2+.035)
for y in (-10,-2,6): cube("Side pencil course",(x,y,BASE+5.8),(.07,14,.12),pencil,TRIM,0,.008)
for z in (BASE+4,BASE+8): cube("Side pencil course",(x,0,z),(.07,D-1,.12),pencil,TRIM,0,.008)
# Entry path ties the threshold to the paving; planter and lantern add scale.
cube("Stone entry path",(0,-22,.05),(12,8,.15),chalk,SET,0,.04)
cube("Front step lower",(0,-18.7,.25),(7.2,2.6,.35),stone,SET,0,.04)
cube("Front step upper",(0,-17.1,.48),(6.4,1.6,.32),chalk,SET,0,.04)
cube("Terracotta planter",(-12,-19.4,.78),(5.6,4,1.1),terra,SET,0,.07)
cube("Planter soil",(-12,-19.4,1.38),(4.7,3.1,.14),green,SET,0,.025)
for x in (-13.1,-12,-10.9): cube("Planter shrub",(x,-19.4,2.1),(.65,.65,1.4),green,SET,0,.16)
cube("Wall lantern frame",(11.6,FRONT-.95,7),(1.2,.65,1.8),ink,TRIM,0,.05)
cube("Wall lantern glass",(11.6,FRONT-1.31,7),(.78,.15,1.1),amber,TRIM,0,.04)
for name,loc,power,size in [("Living pendant",(-7,1,TOP-1),650,2.2),("Kitchen pendant",(9,5,TOP-1),500,1.8),("Study pendant",(0,2,UT-1),360,1.5)]:
ld=bpy.data.lights.new(name,"POINT")
ld.energy=power; ld.color=(1,.62,.35); ld.shadow_soft_size=size
obj=bpy.data.objects.new(name,ld); SET.objects.link(obj); obj.location=loc
# Bright render camera frames the door, occupied windows, stair support and both roof levels.
world=bpy.data.worlds.new("Pale blue studio sky")
scene.world=world; world.use_nodes=True; world.node_tree.nodes.clear()
bg=world.node_tree.nodes.new("ShaderNodeBackground")
out=world.node_tree.nodes.new("ShaderNodeOutputWorld")
world.node_tree.links.new(bg.outputs["Background"],out.inputs["Surface"])
bg.inputs["Color"].default_value=(.34,.59,.76,1); bg.inputs["Strength"].default_value=.52
sd=bpy.data.lights.new("Soft afternoon sun","SUN")
sd.energy=1.8; sd.angle=math.radians(18)
sun=bpy.data.objects.new("Soft afternoon sun",sd); SET.objects.link(sun)
sun.rotation_euler=(math.radians(28),math.radians(-24),math.radians(-32))
ad=bpy.data.lights.new("Large facade fill","AREA")
ad.energy=12000; ad.shape="DISK"; ad.size=72
area=bpy.data.objects.new("Large facade fill",ad); SET.objects.link(area)
area.location=(36,-52,58)
area.rotation_euler=(Vector((0,0,10))-Vector(area.location)).to_track_quat("-Z","Y").to_euler()
cd=bpy.data.cameras.new("House detail camera")
cam=bpy.data.objects.new("House detail camera",cd); SET.objects.link(cam)
cam.location=(63,-86,46)
cam.rotation_euler=(Vector((0,-.5,11))-Vector(cam.location)).to_track_quat("-Z","Y").to_euler()
cd.type="ORTHO"; cd.ortho_scale=66; cd.clip_end=500; scene.camera=cam
scene.render.engine="CYCLES"; scene.cycles.samples=40; scene.cycles.use_denoising=True
scene.render.resolution_x=1650; scene.render.resolution_y=1300; scene.render.resolution_percentage=85
scene.render.image_settings.file_format="PNG"; scene.render.image_settings.color_mode="RGBA"; scene.render.film_transparent=False
scene.view_settings.view_transform="AgX"; scene.view_settings.look="AgX - Medium High Contrast"
scene.render.filepath=RENDER_OUT
scene["Footprint"]="34 x 30 studs"
scene["Stories"]=2
scene["RoofAccess"]=True
scene["ConnectionPlan"]="Front door opens into a furnished room. Supported exterior stair runs from ground landing to roof deck; upper door opens into furnished second floor. No stair leads to the pitched roof."
bpy.ops.wm.save_as_mainfile(filepath=BLEND_OUT)
bpy.ops.render.render(write_still=True)
result={"blend":BLEND_OUT,"render":RENDER_OUT,"objects":len(scene.objects),"footprint":[34,30],"stories":2,"treads":count}
print(result)
+91
View File
@@ -0,0 +1,91 @@
"""Iron sights for the assault-rifle version of the rifle (replaces the optical scope).
Run inside Blender with assault_reference_v13_iron_sights.blend open (scope objects already removed):
exec(open(r'C:\\roblox\\hunter\\blender\\build_iron_sights.py', encoding='utf-8').read())
Rifle space: +X toward the muzzle, +Z up, Y across. The top rail's teeth end at Z 0.689 and the
rail runs X -2.52 .. 2.13. Both sights sit on the rail; the rear aperture's centre and the tip of
the front post are on one sight line at Z = SIGHT_Z. Re-running replaces the previous sights.
"""
import bpy
import bmesh
from mathutils import Matrix, Vector
SIGHT_Z = 0.95
COLLECTION = bpy.data.collections['Rifle V4']
MAT = {k: bpy.data.materials[v] for k, v in {
'frame': 'Ceramic graphite', 'metal': 'Titanium panels', 'glow': 'Amber channel', 'dark': 'Rubber'}.items()}
for o in [o for o in COLLECTION.all_objects if o.name.startswith('Iron sight')]:
bpy.data.objects.remove(o, do_unlink=True)
def finish(name, bm, mat, bevel=0.012):
me = bpy.data.meshes.new(name)
bm.to_mesh(me)
bm.free()
me.materials.append(MAT[mat])
ob = bpy.data.objects.new(name, me)
COLLECTION.objects.link(ob)
if bevel:
m = ob.modifiers.new('Bevel', 'BEVEL')
m.width = bevel
m.segments = 2
m.limit_method = 'ANGLE'
ob.modifiers.new('WeightedNormal', 'WEIGHTED_NORMAL')
for p in me.polygons:
p.use_smooth = True
return ob
def box(name, x0, x1, y0, y1, z0, z1, mat, bevel=0.012):
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=1.0)
bmesh.ops.transform(bm, verts=bm.verts, matrix=Matrix.Diagonal((x1 - x0, y1 - y0, z1 - z0, 1)))
bmesh.ops.translate(bm, verts=bm.verts, vec=Vector(((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2)))
return finish(name, bm, mat, bevel)
def ring(name, center, outer, inner, length, mat):
"""Tube along X: an aperture."""
bm = bmesh.new()
seg = 24
rings = []
for x in (-length / 2, length / 2):
for r in (outer, inner):
rings.append([bm.verts.new((x, r * __import__('math').cos(a * 6.283185 / seg),
r * __import__('math').sin(a * 6.283185 / seg))) for a in range(seg)])
o0, i0, o1, i1 = rings
for k in range(seg):
n = (k + 1) % seg
bm.faces.new((o0[k], o0[n], o1[n], o1[k])) # outside
bm.faces.new((i0[n], i0[k], i1[k], i1[n])) # inside of the hole
bm.faces.new((o0[n], o0[k], i0[k], i0[n])) # rear face
bm.faces.new((o1[k], o1[n], i1[n], i1[k])) # front face
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
bmesh.ops.translate(bm, verts=bm.verts, vec=Vector(center))
return finish(name, bm, mat, bevel=0.006)
# ---------------------------------------------------------------- rear sight (aperture)
RX = -2.2
box('Iron sight rear base', RX - 0.25, RX + 0.25, -0.2, 0.2, 0.66, 0.80, 'frame')
box('Iron sight rear base groove', RX - 0.26, RX + 0.26, -0.21, 0.21, 0.70, 0.72, 'dark', bevel=0)
for side, y in (('L', 1), ('R', -1)):
box(f'Iron sight rear ear {side}', RX - 0.11, RX + 0.11, *sorted((0.13 * y, 0.2 * y)), 0.80, 1.08, 'metal')
box('Iron sight rear post', RX - 0.04, RX + 0.04, -0.035, 0.035, 0.80, SIGHT_Z - 0.06, 'metal', bevel=0.006)
ring('Iron sight rear aperture', (RX, 0, SIGHT_Z), 0.085, 0.04, 0.06, 'metal')
for side, y in (('L', 1), ('R', -1)): # tritium-style dots beside the aperture, facing the eye
box(f'Iron sight rear dot {side}', RX - 0.115, RX - 0.105, 0.155 * y - 0.018, 0.155 * y + 0.018,
SIGHT_Z - 0.018, SIGHT_Z + 0.018, 'glow', bevel=0)
# ---------------------------------------------------------------- front sight (hooded post)
FX = 1.9
box('Iron sight front base', FX - 0.18, FX + 0.18, -0.2, 0.2, 0.66, 0.80, 'frame')
for side, y in (('L', 1), ('R', -1)):
box(f'Iron sight front ear {side}', FX - 0.08, FX + 0.08, *sorted((0.115 * y, 0.175 * y)), 0.80, 1.12, 'metal')
box('Iron sight front post', FX - 0.03, FX + 0.03, -0.024, 0.024, 0.80, SIGHT_Z - 0.01, 'frame', bevel=0.005)
box('Iron sight front dot', FX - 0.032, FX + 0.032, -0.026, 0.026, SIGHT_Z - 0.01, SIGHT_Z + 0.025, 'glow', bevel=0)
IRON_SIGHTS = sorted(o.name for o in COLLECTION.all_objects if o.name.startswith('Iron sight'))
print(IRON_SIGHTS)
+192
View File
@@ -0,0 +1,192 @@
import bpy, math, os
from mathutils import Vector
ROOT=r"C:\roblox\hunter"
OUT=ROOT+r"\3D models\game_zone\Hunter_Monolith_Arena.blend"
scene=bpy.data.scenes.new("Hunter | Monolith arena")
bpy.context.window.scene=scene
coll=bpy.data.collections.new("Arena | solid modular architecture")
scene.collection.children.link(coll)
def mat(name,col,file=None):
m=bpy.data.materials.new(name);m.diffuse_color=(*col,1);m.use_nodes=True
n=m.node_tree.nodes;p=next(x for x in n if x.type=="BSDF_PRINCIPLED")
p.inputs["Base Color"].default_value=(*col,1);p.inputs["Roughness"].default_value=.88
if file:
im=bpy.data.images.load(ROOT+r"\3D models\game_zone\textures"+"/"+file,check_existing=False)
t=n.new("ShaderNodeTexImage");t.image=im;t.projection="FLAT";t.interpolation="Linear"
m.node_tree.links.new(t.outputs["Color"],p.inputs["Base Color"])
im.pack()
return m
navy=mat("HD navy | 8 stud cells",(.115,.17,.25),"HD_navy.png")
amber=mat("HD amber | 8 stud cells",(1,.57,.045),"HD_amber.png")
floor=mat("HD slate | 8 stud cells",(.25,.31,.40),"HD_floor.png")
def cube(name,x,y,z,sx,sy,sz,m):
assert min(sx,sy,sz)>=2
bpy.ops.mesh.primitive_cube_add(size=1,location=(x,y,z+sz/2))
o=bpy.context.object;o.name=name;o.dimensions=(sx,sy,sz)
bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
for c in list(o.users_collection):c.objects.unlink(o)
coll.objects.link(o);o.data.materials.append(m);o["grid_step"]=8
return o
def bevel(o):
mod=o.modifiers.new("Small edge chamfer","BEVEL");mod.width=.22;mod.segments=2
o.modifiers.new("Face normals","WEIGHTED_NORMAL")
return o
def block(name,x,y,sx,sy,h,m=navy,z=0):
return bevel(cube(name,x,y,z,sx,sy,h,m))
def cut(o,x,y,z,sx,sy,sz):
tool=cube("temporary opening",x,y,z,sx,sy,sz,navy)
bpy.context.view_layer.objects.active=o
mod=o.modifiers.new("Traversable passage","BOOLEAN");mod.operation="DIFFERENCE";mod.solver="EXACT";mod.object=tool
bpy.ops.object.modifier_apply(modifier=mod.name)
bpy.data.objects.remove(tool,do_unlink=True)
def gate(name,x,y,sx,sy,h,axis="Y",m=navy,z=0):
o=cube(name,x,y,z,sx,sy,h,m)
if axis in ("Y","CROSS"):cut(o,x,y,z-4,32,sy+8,28)
if axis in ("X","CROSS"):cut(o,x,y,z-4,sx+8,32,28)
return bevel(o)
def wedge(name,start,end,w,h,m=amber,z=0):
a=Vector(start);b=Vector(end);d=(b-a).normalized();p=Vector((-d.y,d.x))
v=[]
for pt,elev in ((a,z),(b,z),(b,z+h)):
for side in (-1,1):
xy=pt+p*(side*w/2);v.append((xy.x,xy.y,elev))
mesh=bpy.data.meshes.new(name);mesh.from_pydata(v,[],[(0,4,5,1),(0,1,3,2),(2,3,5,4),(0,2,4),(1,5,3)]);mesh.update()
o=bpy.data.objects.new(name,mesh);coll.objects.link(o);mesh.materials.append(m)
o["profile"]="right triangular prism";o["grid_step"]=8
return o
# A compact 448 x 448 field with a clear three-lane structure.
block("Foundation",0,0,896,896,8,floor,-8)
block("North enclosure",0,440,896,16,40)
block("South enclosure",0,-440,896,16,40)
block("West enclosure",-440,0,16,864,40)
block("East enclosure",440,0,16,864,40)
# Thick piers and deep lintels are one closed mesh. Both lower axes stay open.
gate("Central citadel | four ground entrances",0,0,96,96,48,"CROSS")
gate("West bastion | through passage",-144,0,64,128,48,"X")
gate("East bastion | through passage",144,0,64,128,48,"X")
# Broad 16-stud-deep links meet the bastion roofs at their ends.
block("West upper connection",-80,0,64,96,16,navy,32)
block("East upper connection",80,0,64,96,16,navy,32)
# Four large solid access wedges, 32 wide, 96 run, 48 rise.
for x,side in [(-144,"West"),(144,"East")]:
wedge(side+" south ramp",(x,-160),(x,-64),32,48)
wedge(side+" north ramp",(x,160),(x,64),32,48)
# Chunky edge cover. Openings line up with ramps and cross bridges.
for xx in (x-24,x+24):
for yy in (-48,48):
block(side+" roof shoulder",xx,yy,16,32,8,navy,48)
# Three playable central levels: ground cross, middle gallery, top roof.
# The middle gallery has only east/west openings, both with a receiving deck.
gate("Citadel | middle gallery and third floor",0,0,96,96,48,"X",navy,48)
wedge("Citadel | west ascent to third level",(-144,-32),(-48,-32),16,48,amber,48)
wedge("Citadel | east ascent to third level",(144,32),(48,32),16,48,amber,48)
block("Citadel | third level cover",0,0,16,32,16,amber,96)
for y in (-40,40):
block("Citadel | third level parapet",0,y,32,8,8,navy,96)
# Lower 24-stud terraces diversify elevation without unsupported plates.
block("North low terrace",0,176,64,64,24,amber)
wedge("North terrace access",(80,176),(32,176),24,24,navy)
block("North terrace cover",-16,184,16,32,16,navy,24)
block("South low terrace",0,-176,64,64,24,amber)
wedge("South terrace access",(-80,-176),(-32,-176),24,24,navy)
block("South terrace cover",16,-184,16,32,16,navy,24)
# Offset masses create corner-to-corner fights and stop full-map sight lines.
# Every dimension and position is in 8-stud increments.
for name,x,y,sx,sy,h,m in [
("NW inner block",-64,104,32,48,40,navy),
("NE inner block",64,112,32,32,24,amber),
("SW inner block",-64,-112,32,32,24,amber),
("SE inner block",64,-104,32,48,40,navy),
("West flank north",-184,112,16,32,24,navy),
("West flank south",-184,-112,16,32,24,amber),
("East flank north",184,112,16,32,24,amber),
("East flank south",184,-112,16,32,24,navy),
("South courtyard shield",-48,-64,32,16,16,amber),
("North courtyard shield",48,64,32,16,16,amber),
("West court shield",-80,48,16,32,16,amber),
("East court shield",80,-48,16,32,16,amber),
("South arrival cover",72,-184,16,24,16,navy),
("North arrival cover",-72,184,16,24,16,navy),
]:block(name,x,y,sx,sy,h,m)
# Four outer gates create cross connections between the old center and the
# perimeter loop. Ramps meet roof edges; the ground tunnels remain unobstructed.
for sy in (-1,1):
y=320*sy
gate("Outer north/south gallery",0,y,128,64,48,"Y")
wedge("Gallery west access",(-160,y),(-64,y),32,48)
wedge("Gallery east access",(160,y),(64,y),32,48)
block("Gallery roof cover",0,y+16*sy,32,16,16,amber,48)
for sx in (-1,1):
x=320*sx
gate("Outer east/west gallery",x,0,64,128,48,"X")
wedge("Gallery south access",(x,-160),(x,-64),32,48)
wedge("Gallery north access",(x,160),(x,64),32,48)
block("Gallery roof cover",x+16*sx,0,16,32,16,amber,48)
# Corner courts are offset around four compact forts, with cover at the
# approach corners and a walkable bypass outside each fort.
for sx in (-1,1):
for sy in (-1,1):
x,y=304*sx,304*sy
gate("Corner fort",x,y,96,96,40,"Y")
wedge("Corner fort inward access",(x-128*sx,y),(x-48*sx,y),32,40)
block("Corner fort top cover",x+24*sx,y,16,32,16,amber,40)
# Cover group: distinct sizes on the shared 8-stud module.
for ox,oy,wx,wy,h in [(80,0,16,32,24),(0,80,32,16,16),
(-32,80,16,16,32),(80,-64,24,24,16)]:
block("Outer courtyard cover",x+ox*sx,y+oy*sy,wx,wy,h,
amber if h!=32 else navy)
# Screens break the long diagonal sight line into the central area.
block("District corner screen",208*sx,224*sy,32,64,40)
block("District staggered cover",248*sx,176*sy,32,16,24,amber)
block("Inner ring cover",224*sx,80*sy,32,16,16,amber)
block("Inner ring tall cover",80*sx,224*sy,16,32,32)
# Physical face-space UVs: 8x8 studs per cell on walls, decks AND slopes.
# Using a tangent basis avoids stretching ramp textures by projecting downward.
for ob in coll.objects:
if ob.type!="MESH":continue
mesh=ob.data;mesh.update()
uv=mesh.uv_layers.active or mesh.uv_layers.new(name="StudGrid_8")
for face in mesh.polygons:
n=face.normal.normalized()
ref=Vector((1,0,0)) if abs(n.x)<.8 else Vector((0,1,0))
u=(ref-n*ref.dot(n)).normalized();v=n.cross(u).normalized()
for li in face.loop_indices:
pt=ob.matrix_world @ mesh.vertices[mesh.loops[li].vertex_index].co
uv.data[li].uv=(pt.dot(u)/32,pt.dot(v)/32)
ob["texture_cell_studs"]=8
ob["texture_pixels_per_stud"]=64
# Cameras are viewport bookmarks only. No render calls.
def camera(name,pos,target,lens=38):
data=bpy.data.cameras.new(name);o=bpy.data.objects.new(name,data);scene.collection.objects.link(o)
o.location=pos;o.rotation_euler=(Vector(target)-o.location).to_track_quat("-Z","Y").to_euler()
data.lens=lens;data.clip_end=3000
return o
cam=camera("Overview",(1080,-1240,1300),(0,0,8),43)
eye=camera("Ground route | central underpass",(36,-100,9),(0,14,14),28)
scene.camera=cam
world=bpy.data.worlds.new("Arena world");world.color=(.35,.4,.48);scene.world=world
scene["layout"]="896x896; central levels 0/48/96, outer gallery loop and four corner courts; 20 ramps"
scene["minimum_mesh_thickness"]=8
scene["preview_policy"]="Viewport screenshots only. Do not render."
# Predictable material preview; this writes no rendered image.
area=next((a for a in bpy.context.window.screen.areas if a.type=="VIEW_3D"),None)
if area:
sp=area.spaces.active
sp.shading.type="MATERIAL";sp.overlay.show_overlays=False;sp.show_gizmo=False
sp.region_3d.view_perspective="PERSP";sp.region_3d.view_rotation=cam.rotation_euler.to_quaternion()
sp.region_3d.view_location=Vector((0,0,8));sp.region_3d.view_distance=1360
bpy.ops.object.select_all(action="DESELECT")
lighting_path=ROOT+r"\blender\add_arena_lighting.py"
exec(compile(open(lighting_path,encoding="utf-8").read(),lighting_path,"exec"),{"__name__":"__main__"})
bpy.ops.wm.save_as_mainfile(filepath=OUT)
result={"blend":OUT,"objects":len(coll.objects),"size":[896,896],"central_levels":[0,48,96],"ramps":20}
+407
View File
@@ -0,0 +1,407 @@
import bpy
import math
import os
import random
import numpy as np
from mathutils import Vector
# Hunter pencil arena. 1 Blender unit = 1 Roblox stud.
SEED = 20261122
rng = random.Random(SEED)
np_rng = np.random.default_rng(SEED)
ROOT = r"C:\roblox\hunter"
BLEND = ROOT + r"\3D models\game_zone\Hunter_Pencil_Arena.blend"
TEXTURE_DIR = ROOT + r"\3D models\game_zone\textures"
os.makedirs(TEXTURE_DIR, exist_ok=True)
old = bpy.data.scenes.get("Hunter Pencil Arena | layered routes")
if old:
bpy.data.scenes.remove(old)
scene = bpy.data.scenes.new("Hunter Pencil Arena | layered routes")
bpy.context.window.scene = scene
for ob in list(scene.objects):
bpy.data.objects.remove(ob, do_unlink=True)
def collection(name):
c = bpy.data.collections.new(name)
scene.collection.children.link(c)
return c
ground_c = collection("01 | Ground and paths")
wall_c = collection("02 | Pencil tile walls")
deck_c = collection("03 | Connected upper routes")
cover_c = collection("04 | Cover and landmarks")
detail_c = collection("05 | Navigation details")
MODULE = 8 # Roblox studs; all cover footprints and heights use this increment.
# Paint a large seamless sheet: sixteen unique cells per direction, eight studs
# per cell. Fine paper grain and variable pencil pressure remain visible up close.
N = 2048
spacing = 128
line = np.zeros((N, N), dtype=np.float32)
ghost = np.zeros_like(line)
grain = np_rng.normal(0, 1, (N, N)).astype(np.float32)
along = np.arange(N, dtype=np.float32)
indices = np.arange(N)
for axis in range(2):
for index in range(16):
nominal = index * spacing
phase = rng.random() * math.tau
anchors = np_rng.normal(0, 1.9, 110)
wander = np.interp(along, np.linspace(0, N-1, len(anchors)), anchors)
edge_fade = np.clip(np.minimum(along, N-1-along)/45, 0, 1)
jitter = (wander + 1.5*np.sin(along*.022+phase)
+ .65*np.sin(along*.083+phase*1.3))*edge_fade
pressure = np.interp(along, np.linspace(0,N-1,70),
np_rng.uniform(.58, .98, 70))
pressure *= np.clip(np_rng.normal(.98,.12,N),.55,1.16)
width = np.interp(along, np.linspace(0,N-1,65),
np_rng.uniform(2.4,4.2,65))
for _ in range(4):
start = rng.randint(0,N-18)
pressure[start:start+rng.randint(3,12)] *= rng.uniform(.05,.27)
for offset in range(-10,11):
center = nominal + offset
target = center % N
distance = np.abs(offset-jitter)
soft = np.clip((width+.8-distance)/1.7,0,1)
pigment = soft*pressure*np.clip(.88+.15*grain[target,:] if axis==0
else .88+.15*grain[:,target],.45,1.08)
if axis == 0:
line[target,indices] = np.maximum(line[target,indices],pigment)
else:
line[indices,target] = np.maximum(line[indices,target],pigment)
# A lighter, slightly offset tracing gives the hand-drawn double edge.
echo_distance = np.abs(offset-jitter-(3.1 if index%2 else -3.1))
echo = np.clip((1.6-echo_distance)/1.5,0,1)*pressure*.32
if axis == 0:
ghost[target,indices] = np.maximum(ghost[target,indices],echo)
else:
ghost[indices,target] = np.maximum(ghost[indices,target],echo)
def pencil_image(name, base, ink, echo):
base = np.array(base, dtype=np.float32)
ink = np.array(ink, dtype=np.float32)
echo = np.array(echo, dtype=np.float32)
noise = np_rng.normal(0, .007, (N, N, 1)).astype(np.float32)
paper = np.clip(base[None,None,:] + noise + .004*grain[:,:,None], 0, 1)
rgb = paper * (1-line[:,:,None]) + ink[None,None,:] * line[:,:,None]
rgb = rgb * (1-ghost[:,:,None]) + echo[None,None,:] * ghost[:,:,None]
alpha = np.ones((N,N,1), dtype=np.float32)
rgba = np.concatenate((rgb, alpha), axis=2)
image = bpy.data.images.new(name, width=N, height=N, alpha=True)
image.pixels.foreach_set(rgba.ravel())
filename = name.split(" | ")[1].replace(" ", "_").replace("-", "_") + ".png"
image.filepath_raw = os.path.join(TEXTURE_DIR, filename)
image.file_format = "PNG"
image.save()
image.pack()
return image
def material(name, color, image=None):
m = bpy.data.materials.new(name)
m.diffuse_color = (*color, 1)
m.use_nodes = True
nodes = m.node_tree.nodes
bsdf = next(n for n in nodes if n.type == "BSDF_PRINCIPLED")
bsdf.inputs["Base Color"].default_value = (*color,1)
bsdf.inputs["Roughness"].default_value = .88
if image:
tex = nodes.new("ShaderNodeTexImage")
tex.image = image
tex.extension = "REPEAT"
tex.projection = "BOX"
tex.projection_blend = .04
pos = nodes.new("ShaderNodeNewGeometry")
scale = nodes.new("ShaderNodeVectorMath")
scale.operation = "SCALE"
scale.inputs[3].default_value = 1/128
m.node_tree.links.new(pos.outputs["Position"], scale.inputs[0])
m.node_tree.links.new(scale.outputs[0], tex.inputs["Vector"])
m.node_tree.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
return m
lav_img = pencil_image("Pencil tiles | uneven lavender 8-stud cells",
(.70,.72,.86), (.43,.47,.64), (.60,.62,.75))
paper_img = pencil_image("Pencil tiles | warm paper",
(.96,.84,.76), (.79,.68,.67), (.88,.77,.73))
orange_img = pencil_image("Pencil tiles | peach orange",
(.97,.59,.39), (.69,.37,.31), (.87,.48,.36))
navy_img = pencil_image("Pencil tiles | deep blue",
(.20,.29,.42), (.42,.45,.47), (.30,.38,.48))
lav = material("WALL | lavender pencil tiles", (.66,.69,.84), lav_img)
paper = material("FLOOR | peach paper tiles", (.95,.82,.73), paper_img)
orange = material("COVER | orange pencil tiles", (.97,.54,.33), orange_img)
navy = material("ROUTE | ink blue tiles", (.17,.25,.37), navy_img)
ink = material("INK | dark outline", (.08,.12,.20))
skyblue = material("MARK | cyan", (.12,.73,.88))
gold = material("MARK | amber", (1,.7,.25))
pale = material("LIGHT | pale cream", (.96,.9,.8))
def move_to(ob, coll):
for c in list(ob.users_collection):
c.objects.unlink(ob)
coll.objects.link(ob)
return ob
def box(name, center, size, mat, coll, bevel=.0, rot=0):
if min(size) < 2:
raise ValueError(f"{name}: mesh thickness must be at least 2 studs")
bpy.ops.mesh.primitive_cube_add(size=1, location=center)
ob = bpy.context.object
ob.name = name
ob.dimensions = size
ob.rotation_euler[2] = math.radians(rot)
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
ob.data.materials.append(mat)
move_to(ob, coll)
if bevel:
mod = ob.modifiers.new("Soft ink edges", "BEVEL")
mod.width = bevel
mod.segments = 2
ob.modifiers.new("Weighted face normals", "WEIGHTED_NORMAL")
return ob
def wall(name, cx, cy, sx, sy, height, mat=lav, rot=0):
ob=box(name, (cx,cy,height/2), (sx,sy,height), mat, wall_c, .16, rot)
# A narrow dark cap gives the sketch-like outer edge.
cap=box(name+" | ink cap", (cx,cy,height+1), (sx+2,sy+2,2), ink, detail_c, .12, rot)
return ob
def cover(name, cx, cy, sx, sy, height, mat=orange, base_z=0):
ob=box(name,(cx,cy,base_z+height/2),(sx,sy,height),mat,cover_c,.26)
ob["grid_step_studs"] = MODULE
ob["module_cells"] = (sx//MODULE, sy//MODULE, height//MODULE)
box(name+" | charcoal top",(cx,cy,base_z+height+1),(sx+2,sy+2,2),ink,detail_c,.12)
return ob
def cover_module(name, gx, gy, cells_x, cells_y, cells_z, mat=orange, level=0):
return cover(name, gx*MODULE, gy*MODULE,
cells_x*MODULE, cells_y*MODULE, cells_z*MODULE,
mat, level)
def oriented_deck(name, start, end, width, z, thickness=2, mat=navy):
a=Vector(start); b=Vector(end)
d=b-a
center=(a+b)/2
ob=box(name,(center.x,center.y,z-thickness/2),(d.length,width,thickness),mat,deck_c,.10,math.degrees(math.atan2(d.y,d.x)))
return ob
def ramp(name, start, end, width, top_z, mat=navy):
a=Vector(start); b=Vector(end)
d=(b-a).normalized()
perp=Vector((-d.y,d.x))
low=.03
high=top_z
# A closed triangular prism: horizontal bottom, vertical high end, sloped
# walkable face. Its length/height section is exactly a right triangle.
verts=[]
for p,z in ((a,low),(b,low),(b,high)):
for s in (-1,1):
xy=p+perp*(s*width/2)
verts.append((xy.x,xy.y,z))
faces=[(0,4,5,1),(0,1,3,2),(2,3,5,4),(0,2,4),(1,5,3)]
mesh=bpy.data.meshes.new(name)
mesh.from_pydata(verts,[],faces); mesh.update()
ob=bpy.data.objects.new(name,mesh); deck_c.objects.link(ob)
ob.data.materials.append(mat)
# Raised edge rails trace the slope without obstructing its full walking width.
for s in (-1,1):
for p0,p1 in ((a,b),):
u=p0+perp*(s*(width/2-1))
v=p1+perp*(s*(width/2-1))
rail=oriented_deck(name+" | side rail",u,v,2,0,2,ink)
# Replace the flat rail with a sloped beam by making its mesh vertices rise.
for vert in rail.data.vertices:
local = vert.co
along = local.x / max((v-u).length,.01) + .5
local.z += low + (high-low)*along + 1.8
return ob
def platform(name,cx,cy,sx,sy,z):
box(name,(cx,cy,z-1),(sx,sy,2),navy,deck_c,.12)
for x in (cx-sx/2+4,cx+sx/2-4):
for y in (cy-sy/2+4,cy+sy/2-4):
box(name+" | support",(x,y,(z-2)/2),(3.3,3.3,z-2),lav,deck_c,.08)
# low cover on the deck, deliberately leaving 18+ stud clear corridors
return
def railing(name,p0,p1,z):
a=Vector(p0);b=Vector(p1)
oriented_deck(name,a,b,2,z+3,2,ink)
for t in (0,.25,.5,.75,1):
p=a.lerp(b,t)
box(name+" | post",(p.x,p.y,z+1.5),(2,2,3),ink,detail_c,.12)
# Ground is one continuous slab: no overlapping, coplanar tiled plates.
box("520 x 520 | continuous paper arena floor",(0,0,-1.5),(520,520,3),paper,ground_c,.05)
# Four bounding walls; high enough to visually contain the fighting ground.
wall("North boundary",0,258,520,4,32,navy)
wall("South boundary",0,-258,520,4,32,navy)
wall("East boundary",258,0,4,520,32,navy)
wall("West boundary",-258,0,4,520,32,navy)
# Route hierarchy: three broad south-north lanes with offset links. Obstacles
# frame them instead of sealing them into disconnected rooms.
# Southern split and staggered entry walls.
wall("South | central divider",0,-185,29,86,30)
wall("South | west return",-86,-180,54,8,25)
wall("South | east return",90,-147,48,8,25)
wall("South | left flank",-191,-150,8,94,30)
wall("South | right flank",195,-183,8,104,30)
wall("South | cross screen",-113,-103,8,51,23)
wall("South | angled screen",117,-90,9,65,30,lav,-18)
# North approach: openings alternate side so no corridor is a blind straight tunnel.
wall("North | central divider",15,187,32,82,29)
wall("North | west return",-90,152,56,8,25)
wall("North | east return",100,176,58,8,26)
wall("North | left flank",-194,175,8,86,30)
wall("North | right flank",194,141,8,90,30)
wall("North | cross screen",-111,100,8,56,26)
wall("North | angled screen",123,96,8,74,31,lav,16)
# Middle: four separated corner structures preserve four entrances to the plaza.
wall("Center | NW west",-85,48,8,72,35)
wall("Center | NW north",-61,86,58,8,35)
wall("Center | NE north",72,87,65,8,34)
wall("Center | NE east",107,56,8,64,15)
wall("Center | SW west",-107,-58,8,66,15)
wall("Center | SW south",-76,-89,64,8,31)
wall("Center | SE south",64,-89,55,8,33)
wall("Center | SE east",89,-57,8,63,33)
# West and east bypass pockets. Several screens are diagonal to interrupt a grid.
wall("West | lower shield",-217,-36,9,80,28)
wall("West | mid shield",-166,8,66,8,15)
wall("West | upper shield",-215,75,9,94,31)
wall("West | diagonal",-155,201,8,57,29,lav,23)
wall("East | lower shield",215,-48,9,92,30)
wall("East | mid shield",170,9,69,8,15)
wall("East | upper shield",218,66,9,88,32)
wall("East | diagonal",153,-205,8,68,29,lav,-20)
# Each tuple is grid position, width cells, depth cells and height cells.
# The small, medium and tall variants can be rearranged on the same 8-stud grid.
for name,gx,gy,wx,wy,hz,mat in [
("Hub | orange obelisk",-3,2,2,2,2,orange),
("Hub | low orange shield",4,-3,3,1,1,orange),
("Hub | high slate shield",6,4,2,3,2,lav),
("Hub | slim barricade",-6,-4,1,3,1,lav),
("South | orange cover A",-8,-27,2,2,2,orange),
("South | orange cover B",8,-23,2,2,3,orange),
("South | low shield",18,-26,3,1,1,lav),
("South | long barricade",-6,-17,4,1,2,lav),
("South | slim tower",13,-28,1,1,3,orange),
("West | low crate",-26,-13,3,2,1,orange),
("West | tall crate",-18,8,2,2,3,orange),
("West | far corner block",-28,-28,2,2,2,lav),
("West | north bypass",-28,23,1,3,2,orange),
("East | orange tower",23,-11,2,2,4,orange),
("East | side barricade",28,16,1,3,2,lav),
("East | long low cover",28,26,3,1,1,orange),
("North | orange cover A",-7,26,2,2,2,orange),
("North | orange cover B",9,20,3,1,1,orange),
("North | tall slate",18,25,2,2,3,lav),
("North | tall marker",0,15,2,2,4,orange),
]:
cover_module(name,gx,gy,wx,wy,hz,mat)
# Four connected upper landings. Each has a real supporting structure,
# a walkable ramp at a free side, and attached bridge endpoints.
Z=24
platform("West lower terrace",-167,-78,82,70,Z)
platform("East upper terrace",166,78,82,70,Z)
platform("West north terrace",-167,161,82,70,Z)
platform("Central crossing",0,0,70,70,Z)
ramp("West terrace | south ramp",(-167,-191),(-167,-113),24,Z)
ramp("East terrace | south ramp",(166,-39),(166,43),24,Z)
ramp("North terrace | north ramp",(-167,250),(-167,196),24,Z)
# These wide spans overlap their receiving decks by several studs.
oriented_deck("West to center | diagonal upper crossing",(-129,-69),(-27,-22),19,Z+.12)
oriented_deck("Center to east | diagonal upper crossing",(25,21),(131,68),19,Z+.12)
oriented_deck("West terrace to north terrace | long overlook",(-167,-47),(-167,130),18,Z+.12)
# Secondary ground to upper route prevents one-sided camping.
platform("East south terrace",163,-158,74,57,Z)
ramp("East south terrace | east ramp",(247,-158),(200,-158),24,Z)
oriented_deck("East south to east north | flank crossing",(163,-134),(166,51),18,Z+.12)
# Low, differently shaped cover on landings keeps upper movement tactical.
cover_module("Upper west | short cover",-23,-10,1,1,1,orange,Z)
cover_module("Upper east | broad cover",23,12,2,1,1,orange,Z)
cover_module("Upper north | narrow cover",-23,22,1,2,1,lav,Z)
cover_module("Upper south east | low cover",18,-22,2,1,1,orange,Z)
# Sparse guard edges where the fall is highest, leaving bridge ends and ramps open.
for name,a,b in [
("West long edge",(-176,-37),(-176,125)),
("West diagonal north edge",(-128,-58),(-30,-11)),
("East diagonal south edge",(26,9),(131,56)),
("East flank edge",(172,-129),(174,50)),
]:
railing(name,a,b,Z)
# Upper-route edges and tall cover carry color cues, not player HUD.
for x,y,z in [(-167,-78,Z),(166,78,Z),(-167,161,Z),(163,-158,Z)]:
box("Landing beacon",(x,y,z+1.1),(5,5,2.2),gold,detail_c,.30)
for x,y in [(-245,-240),(245,-240),(-245,240),(245,240)]:
box("Perimeter light mast",(x,y,17),(2.2,2.2,34),ink,detail_c,.12)
box("Perimeter light",(x,y,35),(7,7,3),pale,detail_c,.5)
# Lighting: cool ambient sky plus warm side light emphasize the drawn texture.
world=bpy.data.worlds.new("Open cyan sky")
world.use_nodes=True
wn=world.node_tree.nodes
wn.clear()
bg=wn.new("ShaderNodeBackground")
bg.inputs["Color"].default_value=(.28,.67,.98,1)
bg.inputs["Strength"].default_value=.75
wo=wn.new("ShaderNodeOutputWorld")
world.node_tree.links.new(bg.outputs["Background"],wo.inputs["Surface"])
scene.world=world
def sun(name,rotation,power,color):
data=bpy.data.lights.new(name,"SUN")
ob=bpy.data.objects.new(name,data); scene.collection.objects.link(ob)
ob.rotation_euler=rotation
data.energy=power; data.color=color
data.angle=math.radians(6)
sun("Warm afternoon key",(math.radians(33),math.radians(-18),math.radians(-25)),2.4,(1,.82,.70))
sun("Cool sky fill",(math.radians(48),math.radians(18),math.radians(105)),.9,(.68,.81,1))
def camera(name,position,target,lens):
data=bpy.data.cameras.new(name)
ob=bpy.data.objects.new(name,data); scene.collection.objects.link(ob)
ob.location=position
direction=Vector(target)-ob.location
ob.rotation_euler=direction.to_track_quat("-Z","Y").to_euler()
data.lens=lens
data.clip_end=4000
return ob
overview_cam=camera("Overview | shows looped ground and upper routes",(610,-680,675),(0,0,0),43)
player_cam=camera("Player view | pencil tiles and ramps",(-142,-222,8),(-163,-76,14),31)
ramp_cam=camera("Ramp section | triangular side and module scale",(230,-211,14),(201,-157,12),38)
routes_cam=camera("Route plan | orthographic",(0,0,900),(0,0,0),32)
routes_cam.data.type="ORTHO"
routes_cam.data.ortho_scale=580
scene.render.engine="CYCLES"
scene.cycles.samples=72
scene.render.resolution_x=1440
scene.render.resolution_y=960
scene.render.resolution_percentage=100
scene.render.image_settings.file_format="PNG"
scene.view_settings.view_transform="Standard"
scene.view_settings.look="Medium High Contrast"
scene.render.film_transparent=False
scene.camera=overview_cam
bpy.ops.wm.save_as_mainfile(filepath=BLEND)
result={
"blend":BLEND,
"objects":len(scene.objects),
"size_studs":[520,520],
"upper_route_z":Z
}
+116
View File
@@ -0,0 +1,116 @@
"""Red dot (reflex) sight for the rifle's top rail, in the collection 'Sight Red Dot'.
Run inside Blender with assault_reference_v13_iron_sights.blend open:
exec(open(r'C:\\roblox\\hunter\\blender\\build_red_dot.py', encoding='utf-8').read())
Rifle space: +X toward the muzzle, +Z up. The rail's teeth end at Z 0.689 (rail X -2.52 .. 2.13).
The window is a rectangular frame around a glass pane; the dot floats just behind the glass at
DOT_Z. The glass has its own material ('Sight glass') so in Roblox it becomes its own MeshPart that
can be made see-through. Re-running replaces the previous sight.
"""
import math
import bpy
import bmesh
from mathutils import Matrix, Vector
COLLECTION = bpy.data.collections['Sight Red Dot']
CX = -1.0 # middle of the sight along the rail
DOT_Z = 1.0 # height of the window's centre (the aiming line)
def material(name, color, metal=0.0, rough=0.5, emit=0.0):
m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
m.use_nodes = True
p = next(n for n in m.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')
p.inputs['Base Color'].default_value = (*color, 1)
p.inputs['Metallic'].default_value = metal
p.inputs['Roughness'].default_value = rough
p.inputs['Emission Strength'].default_value = emit
if emit:
p.inputs['Emission Color'].default_value = (*color, 1)
return m
MAT = {
'frame': bpy.data.materials['Ceramic graphite'],
'metal': bpy.data.materials['Titanium panels'],
'cyan': bpy.data.materials['Cyan channel'],
'dark': bpy.data.materials['Rubber'],
'glass': material('Sight glass', (0.35, 0.75, 0.7), rough=0.05),
'dot': material('Red dot', (1.0, 0.02, 0.01), emit=6.0),
}
for o in list(COLLECTION.objects):
bpy.data.objects.remove(o, do_unlink=True)
def finish(name, bm, mat, bevel):
me = bpy.data.meshes.new(name)
bm.to_mesh(me)
bm.free()
me.materials.append(MAT[mat])
for p in me.polygons:
p.use_smooth = True
ob = bpy.data.objects.new(name, me)
COLLECTION.objects.link(ob)
if bevel:
m = ob.modifiers.new('Bevel', 'BEVEL')
m.width = bevel
m.segments = 2
m.limit_method = 'ANGLE'
ob.modifiers.new('WeightedNormal', 'WEIGHTED_NORMAL')
return ob
def box(name, x0, x1, y0, y1, z0, z1, mat, bevel=0.012):
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=1.0)
bmesh.ops.transform(bm, verts=bm.verts, matrix=Matrix.Diagonal((x1 - x0, y1 - y0, z1 - z0, 1)))
bmesh.ops.translate(bm, verts=bm.verts, vec=Vector(((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2)))
return finish(name, bm, mat, bevel)
def cylinder_y(name, center, radius, length, mat, bevel=0.008):
"""Knob: a cylinder whose axis runs across the rifle (Y)."""
bm = bmesh.new()
bmesh.ops.create_cone(bm, cap_ends=True, segments=20, radius1=radius, radius2=radius, depth=length)
bmesh.ops.rotate(bm, verts=bm.verts, matrix=Matrix.Rotation(math.pi / 2, 3, 'X'))
bmesh.ops.translate(bm, verts=bm.verts, vec=Vector(center))
return finish(name, bm, mat, bevel)
# mount: a clamp on the rail
box('Red dot mount', CX - 0.26, CX + 0.26, -0.2, 0.2, 0.66, 0.79, 'frame')
for side, y in (('L', 1), ('R', -1)):
box(f'Red dot clamp {side}', CX - 0.2, CX + 0.2, *sorted((0.2 * y, 0.24 * y)), 0.6, 0.74, 'frame', bevel=0.01)
box(f'Red dot clamp screw {side}', CX - 0.04, CX + 0.04, *sorted((0.24 * y, 0.26 * y)), 0.63, 0.71, 'metal', bevel=0.006)
# housing: a rectangular frame around the window, deeper at the bottom
W_Y, W_Z0, W_Z1 = 0.15, DOT_Z - 0.16, DOT_Z + 0.16 # window half-width and height
O_Y, O_Z0, O_Z1 = 0.21, 0.79, DOT_Z + 0.22 # outside of the frame
X0, X1 = CX - 0.2, CX + 0.2
box('Red dot frame bottom', X0 - 0.06, X1, -O_Y, O_Y, O_Z0, W_Z0, 'metal')
box('Red dot frame top', X0, X1 + 0.05, -O_Y, O_Y, W_Z1, O_Z1, 'metal') # top overhangs a bit: hood
for side, y in (('L', 1), ('R', -1)):
box(f'Red dot frame side {side}', X0, X1, *sorted((W_Y * y, O_Y * y)), W_Z0, W_Z1, 'metal')
box(f'Red dot side stripe {side}', X0 + 0.06, X1 - 0.06, *sorted((O_Y * y, (O_Y + 0.006) * y)),
DOT_Z - 0.03, DOT_Z + 0.03, 'cyan', bevel=0)
# glass pane near the front, the dot just behind it (on the eye side)
GX = X1 - 0.07
box('Red dot glass', GX - 0.012, GX + 0.012, -W_Y - 0.004, W_Y + 0.004, W_Z0 - 0.004, W_Z1 + 0.004, 'glass', bevel=0)
box('Red dot emitter', X0 + 0.02, X0 + 0.08, -0.025, 0.025, W_Z0, W_Z0 + 0.025, 'dark', bevel=0.004)
dot = bpy.data.meshes.new('Red dot dot')
bm = bmesh.new()
bmesh.ops.create_uvsphere(bm, u_segments=12, v_segments=8, radius=0.018)
bmesh.ops.translate(bm, verts=bm.verts, vec=Vector((GX - 0.03, 0, DOT_Z)))
finish('Red dot dot', bm, 'dot', 0)
# brightness knob on the right side, battery cap on the left
cylinder_y('Red dot knob', (CX - 0.05, -(O_Y + 0.035), O_Z0 + 0.09), 0.065, 0.07, 'frame')
box('Red dot knob mark', CX - 0.06, CX - 0.04, -(O_Y + 0.072), -(O_Y + 0.068), O_Z0 + 0.1, O_Z0 + 0.145, 'cyan', bevel=0)
cylinder_y('Red dot battery cap', (CX - 0.05, O_Y + 0.025, O_Z0 + 0.09), 0.06, 0.05, 'metal')
RED_DOT = sorted(o.name for o in COLLECTION.objects)
print(RED_DOT)
+92
View File
@@ -0,0 +1,92 @@
import bpy, math, os
from mathutils import Vector
OUT = r'C:\roblox\hunter\3D models'
os.makedirs(OUT, exist_ok=True)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
def mat(name, color, metallic=0.0, rough=0.35, emission=None):
m=bpy.data.materials.get(name) or bpy.data.materials.new(name)
m.diffuse_color=(*color,1); m.use_nodes=True
p=next((n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED'),None)
p.inputs['Base Color'].default_value=(*color,1)
p.inputs['Metallic'].default_value=metallic; p.inputs['Roughness'].default_value=rough
if emission:
p.inputs['Emission Color'].default_value=(*emission,1); p.inputs['Emission Strength'].default_value=4
return m
dark=mat('Graphite',(0.025,0.04,0.07),0.75,0.24)
metal=mat('Gunmetal',(0.16,0.2,0.27),0.8,0.25)
cyan=mat('CyanGlow',(0.01,0.18,0.28),0.25,0.2,(0.0,0.8,1.0))
orange=mat('OrangeAccent',(0.45,0.06,0.008),0.3,0.24,(1.0,0.16,0.01))
glass=mat('ScopeGlass',(0.02,0.16,0.22),0.3,0.08,(0.0,0.4,0.7))
def cube(n, loc, scale, material, bevel=0.12, rot=(0,0,0)):
bpy.ops.mesh.primitive_cube_add(location=loc, rotation=rot)
o=bpy.context.object; o.name=n; o.scale=scale
bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
if bevel:
b=o.modifiers.new('EdgeBevel','BEVEL'); b.width=bevel; b.segments=2
o.data.materials.append(material); return o
def cyl(n, loc, radius, depth, material, rot=(0,0,0), verts=32, bevel=0.08):
bpy.ops.mesh.primitive_cylinder_add(vertices=verts, radius=radius, depth=depth, location=loc, rotation=rot)
o=bpy.context.object; o.name=n
if bevel:
b=o.modifiers.new('EdgeBevel','BEVEL'); b.width=bevel; b.segments=2
o.data.materials.append(material); return o
def torus(n, loc, major, minor, material, rot=(0,0,0)):
bpy.ops.mesh.primitive_torus_add(major_radius=major, minor_radius=minor, major_segments=32, minor_segments=10, location=loc, rotation=rot)
o=bpy.context.object; o.name=n; o.data.materials.append(material); return o
# Main rifle axis is X; muzzle points +X.
cube('Receiver',(0,0,0),(2.15,0.52,0.48),dark,0.18)
cube('UpperArmor',(0.1,0,0.45),(1.45,0.58,0.18),metal,0.1)
cube('LowerModule',(-0.15,0,-0.58),(0.75,0.42,0.25),metal,0.1)
cube('FrontShroud',(2.1,0,0.02),(1.1,0.66,0.42),metal,0.16)
cube('RearStock',(-2.55,0,0.05),(0.85,0.48,0.7),dark,0.18)
cube('StockBrace',(-2.55,0,-0.85),(0.25,0.28,0.65),dark,0.12,rot=(0,math.radians(-14),0))
cube('Grip',(-0.65,0,-0.85),(0.28,0.3,0.72),dark,0.12,rot=(0,math.radians(-13),0))
cube('RearPad',(-3.35,0,0.05),(0.18,0.58,0.72),metal,0.12)
cyl('Barrel',(3.45,0,0.02),0.25,2.2,dark,rot=(0,math.radians(90),0),bevel=0.05)
cyl('Muzzle',(4.55,0,0.02),0.42,0.65,dark,rot=(0,math.radians(90),0),bevel=0.08)
for x in (4.22,4.72): torus('MuzzleRing',(x,0,0.02),0.42,0.07,cyan,rot=(0,math.radians(90),0))
for y in (-0.27,0.27):
cube('MuzzleProng',(4.9,y,0.02),(0.35,0.10,0.12),metal,0.04,rot=(0,0,math.radians(8 if y>0 else -8)))
for y in (-0.58,0.58): cube('SideFin',(2.15,y,0.03),(0.8,0.06,0.16),dark,0.04)
cyl('ScopeBody',(0.15,0,1.25),0.38,2.25,dark,rot=(0,math.radians(90),0),bevel=0.1)
cyl('ScopeFront',(1.28,0,1.25),0.52,0.46,dark,rot=(0,math.radians(90),0),bevel=0.1)
cyl('ScopeLens',(1.53,0,1.25),0.34,0.04,glass,rot=(0,math.radians(90),0),bevel=0.02)
for x in (-0.72,0.95): cyl('ScopeRing',(x,0,1.25),0.48,0.14,metal,rot=(0,math.radians(90),0),bevel=0.04)
cube('ScopeRail',(0,0,0.82),(1.55,0.22,0.08),dark,0.03)
for i in range(12): cube('RailTooth',(-1.45+i*0.25,0,0.96),(0.07,0.18,0.09),metal,0.025)
cube('ScopeHood',(1.12,0,1.25),(0.32,0.58,0.62),dark,0.10)
cube('CyanRail',(0.5,-0.56,0.0),(1.0,0.035,0.08),cyan,0.03)
cube('OrangePanel',(0.25,0,-0.48),(0.55,0.04,0.1),orange,0.02)
cube('OrangeStockAccent',(-2.6,-0.5,0.05),(0.35,0.03,0.12),orange,0.02)
cyl('TopDial',(-0.35,0,1.0),0.28,0.3,orange,rot=(math.radians(90),0,0),bevel=0.06)
for i in range(3): cube('Vent',(1.4+i*0.38,-0.69,0.18),(0.09,0.03,0.15),cyan,0.02,rot=(0,0,math.radians(18)))
cube('Display',(0,0,-1.75),(5.4,2.7,0.08),mat('DisplayMat',(0.008,0.02,0.045),0.1,0.35),0.04)
bpy.ops.object.camera_add(location=(9.5,-15.5,4.6))
cam=bpy.context.object; bpy.context.scene.camera=cam
def point(obj, target): obj.rotation_euler=(Vector(target)-obj.location).to_track_quat('-Z','Y').to_euler()
point(cam,(0,0,0)); cam.data.lens=55
bpy.ops.object.light_add(type='AREA', location=(1.5,-5,6))
key=bpy.context.object; key.data.energy=1200; key.data.size=5; point(key,(0,0,0))
bpy.ops.object.light_add(type='AREA', location=(-4,4,2))
fill=bpy.context.object; fill.data.energy=800; fill.data.color=(0.05,0.35,1); fill.data.size=4; point(fill,(0,0,0))
bpy.ops.object.light_add(type='AREA', location=(4,2,1))
rim=bpy.context.object; rim.data.energy=900; rim.data.color=(1,0.12,0.02); rim.data.size=3; point(rim,(1,0,0))
scene=bpy.context.scene; scene.render.engine='BLENDER_EEVEE'
scene.render.resolution_x=1400; scene.render.resolution_y=800; scene.render.resolution_percentage=100
scene.world.color=(0.004,0.008,0.02)
scene.render.filepath=os.path.join(OUT,'sniper_preview.png')
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT,'sniper_rifle.blend'))
bpy.ops.render.render(write_still=True)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.export_scene.gltf(filepath=os.path.join(OUT,'sniper_rifle.glb'),export_format='GLB',use_selection=True,export_apply=True,export_animations=False)
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT,'sniper_rifle.blend'))
print('SAVED',os.path.join(OUT,'sniper_rifle.blend'))
+62
View File
@@ -0,0 +1,62 @@
"""Report intersecting mesh objects in the current Blender scene.
Run inside Blender's Python environment. This is intentionally read-only.
Render meshes and collision proxies can be checked separately by adjusting
the name/collection filters below when a scene needs that distinction.
"""
import bpy
from mathutils import Vector
from mathutils.bvhtree import BVHTree
def world_vertices(obj):
matrix = obj.matrix_world
return [matrix @ vertex.co for vertex in obj.data.vertices]
def bvh_for(obj):
vertices = world_vertices(obj)
polygons = [tuple(poly.vertices) for poly in obj.data.polygons]
return BVHTree.FromPolygons(vertices, polygons, all_triangles=False)
def bounds_overlap(a, b):
amin, amax = a
bmin, bmax = b
return all(amin[i] <= bmax[i] and bmin[i] <= amax[i] for i in range(3))
def main():
meshes = [o for o in bpy.context.scene.objects if o.type == "MESH" and o.visible_get()]
bounds = {o: (o.bound_box[0], o.bound_box[0]) for o in []} # keeps type checkers quiet
bounds = {}
bvhs = {}
for obj in meshes:
corners = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
mins = tuple(min(v[i] for v in corners) for i in range(3))
maxs = tuple(max(v[i] for v in corners) for i in range(3))
bounds[obj] = (mins, maxs)
bvhs[obj] = bvh_for(obj)
hits = []
for index, left in enumerate(meshes):
for right in meshes[index + 1 :]:
if left.parent == right or right.parent == left:
continue
if not bounds_overlap(bounds[left], bounds[right]):
continue
if bvhs[left].overlap(bvhs[right]):
hits.append((left.name, right.name))
if hits:
print("COLLISION_CHECK: FAIL")
for left, right in hits:
print(f" INTERSECTION: {left} <-> {right}")
return 1
print(f"COLLISION_CHECK: PASS ({len(meshes)} mesh objects, no intersections)")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+39
View File
@@ -0,0 +1,39 @@
import bpy,bmesh,math
s=bpy.context.scene
c=next(c for c in s.collection.children if c.name.startswith('Rifle V4'))
def material_from(prefix):return next(o for o in c.objects if o.name.startswith(prefix)).data.materials[0]
dark=material_from('Lower receiver plate');metal=material_from('Breech armor');black=material_from('Unified receiver')
def panel(name,points,y,depth,mat,bevel=.015):
n=len(points);v=[((x-880)/180,d,(490-z)/180) for d in (y-depth/2,y+depth/2) for x,z in points]
f=[tuple(reversed(range(n))),tuple(range(n,2*n))]+[(i,(i+1)%n,(i+1)%n+n,i+n) for i in range(n)]
me=bpy.data.meshes.new(name);me.from_pydata(v,[],f);me.update()
bm=bmesh.new();bm.from_mesh(me);bmesh.ops.recalc_face_normals(bm,faces=bm.faces);bm.to_mesh(me);bm.free()
o=bpy.data.objects.new(name,me);c.objects.link(o);me.materials.append(mat)
b=o.modifiers.new('Panel edge','BEVEL');b.width=bevel;b.segments=2
o.modifiers.new('Face normals','WEIGHTED_NORMAL');return o
for side in (-1,1):
# A dark inset with a raised perimeter seats the existing luminous indicators.
panel('Indicator recessed bed',[(691,470),(817,470),(839,492),(814,527),(676,527),(663,512)],side*.405,.035,black)
panel('Indicator lower rim',[(676,530),(817,530),(839,505),(849,506),(823,541),(666,541)],side*.433,.04,dark)
panel('Receiver diagonal rib',[(625,468),(652,464),(672,481),(635,541),(607,541),(596,530)],side*.46,.12,metal)
panel('Rear connector armor',[(355,512),(406,518),(421,543),(403,560),(350,549),(333,530)],side*.365,.09,dark)
panel('Upper layered slide',[(361,426),(451,414),(475,420),(460,439),(355,446)],side*.395,.07,metal)
panel('Slide black separation',[(359,448),(463,441),(475,450),(362,458)],side*.407,.02,black,.006)
panel('Lower chassis reinforcement',[(534,535),(571,535),(587,550),(575,579),(535,579),(519,563)],side*.36,.1,dark)
panel('Magazine socket bevel',[(575,553),(615,548),(626,558),(727,558),(727,573),(572,573)],side*.35,.07,dark)
panel('Front angled reinforcement',[(850,484),(882,470),(912,485),(922,516),(897,530),(863,521)],side*.37,.1,dark)
panel('Service latch recess',[(611,480),(630,480),(622,500),(604,500)],side*.53,.015,black,.006)
panel('Service latch',[(611,484),(624,484),(619,491),(607,491)],side*.545,.02,metal,.004)
for x,z in [(550,554),(875,506),(380,535),(643,478)]:
bpy.ops.mesh.primitive_cylinder_add(vertices=8,radius=.028,depth=.02,location=((x-880)/180,side*.48,(490-z)/180),rotation=(math.pi/2,0,0))
o=bpy.context.object;o.name='Receiver fastener'
for col in list(o.users_collection):col.objects.unlink(o)
c.objects.link(o);o.data.materials.append(black)
# Keep indicators above their recessed bed, not buried by the new panel.
for o in c.objects:
if o.name.startswith('Diagonal amber indicator'):
for v in o.data.vertices:v.co.y += .012 if v.co.y>0 else -.012
bpy.context.view_layer.update()
path=r'C:\roblox\hunter\3D models\sniper_reference_v7.blend'
bpy.ops.wm.save_as_mainfile(filepath=path)
print('Receiver detailed and saved',path)
+40
View File
@@ -0,0 +1,40 @@
import bpy,os,json,struct
from mathutils import Vector,Matrix
D=r'C:\roblox\Ornament-Generator-RNG\3d model\furniture'
reports=[]
for label in ('bench','lamp'):
bpy.ops.wm.read_factory_settings(use_empty=True)
with bpy.data.libraries.load(os.path.join(D,label+'_source.blend')) as (a,b):b.objects=a.objects
for o in b.objects:
if o:bpy.context.collection.objects.link(o)
bpy.context.view_layer.update()
root=next(o for o in bpy.context.scene.objects if o.type=='EMPTY')
inv=root.matrix_world.inverted()
obs=[o for o in bpy.context.scene.objects if o.type in {'MESH','CURVE'}]
transforms={o:inv@o.matrix_world for o in obs}
for o in obs:o.parent=None;o.matrix_world=transforms[o]
bpy.data.objects.remove(root,do_unlink=True)
bpy.ops.object.select_all(action='SELECT');bpy.context.view_layer.objects.active=obs[0];bpy.ops.object.convert(target='MESH')
bpy.context.view_layer.update()
z=min((o.matrix_world@Vector(v)).z for o in obs for v in o.bound_box)
for o in obs:o.location.z-=z
for o in obs:
if not o.data.uv_layers:
bpy.ops.object.select_all(action='DESELECT');o.select_set(True);bpy.context.view_layer.objects.active=o;bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.uv.smart_project(island_margin=.02);bpy.ops.object.mode_set(mode='OBJECT')
mats={m for o in obs for m in o.data.materials if m}
for m in mats:
p=next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED');c=p.inputs['Base Color'].default_value[:]
def s(v):return v*12.92 if v<=.0031308 else 1.055*v**(1/2.4)-.055
im=bpy.data.images.new(label+'_'+m.name+'_BaseColor',width=16,height=16,alpha=True);im.pixels[:]=([s(v) for v in c[:3]]+[1])*256;im.pack()
n=m.node_tree.nodes.new('ShaderNodeTexImage');n.image=im;m.node_tree.links.new(n.outputs['Color'],p.inputs['Base Color'])
if p.inputs['Emission Strength'].default_value>0:m.node_tree.links.new(n.outputs['Color'],p.inputs['Emission Color'])
bpy.ops.object.select_all(action='SELECT')
path=os.path.join(D,label+'.glb')
bpy.ops.export_scene.gltf(filepath=path,export_format='GLB',use_selection=True,export_apply=True,export_animations=False)
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(D,label+'.blend'))
with open(path,'rb') as f:
f.read(12);length,_=struct.unpack('<II',f.read(8));doc=json.loads(f.read(length))
assert all('bufferView' in x for x in doc['images'])
bpy.ops.wm.read_factory_settings(use_empty=True);bpy.ops.import_scene.gltf(filepath=path)
reports.append({'asset':label,'meshes':sum(o.type=='MESH' for o in bpy.context.scene.objects),'embedded_textures':len(doc['images']),'bytes':os.path.getsize(path)})
print('VERIFIED',json.dumps(reports))
+75
View File
@@ -0,0 +1,75 @@
"""Export the posed gloved arms (no rifle) as a Roblox-ready GLB that lines up with sniper_rifle.glb.
Run in background Blender on sniper_reference_v12_hands_natural.blend (the .blend is not saved):
blender -b <v12.blend> --python export_hands_roblox.py
The pose comes from pose_hands_natural.py. Every mesh is split per material, moved so the
pistol grip (GRIP) is the origin, like the rifle export, and each part's bounding-box centre is
written to hands_layout.json: Roblox recentres each MeshPart on import, so the viewmodel
script places the parts from these centres.
"""
import json
import os
import bmesh
import bpy
from mathutils import Matrix, Vector
OUT_DIR = r'C:\roblox\hunter\3D models\sniper\export'
GLB = os.path.join(OUT_DIR, 'sniper_hands.glb')
GRIP = Vector((-2.75, 0.0, -0.85))
MAX_TEX = 1024
g = {'__name__': 'pose'}
exec(open(r'C:\roblox\hunter\blender\pose_hands_natural.py', encoding='utf-8').read(), g)
scene = bpy.data.scenes['Reference Sculpt V4']
dg = bpy.context.evaluated_depsgraph_get()
dg.update()
created, layout = [], {}
for src_name, label in (('hardknuckle', 'Glove'), ('sleeve', 'Sleeve')):
o = bpy.data.objects[src_name]
me = bpy.data.meshes.new_from_object(o.evaluated_get(dg), preserve_all_data_layers=True, depsgraph=dg)
me.transform(Matrix.Translation(-GRIP) @ o.matrix_world)
for i, mat in enumerate(me.materials):
bm = bmesh.new()
bm.from_mesh(me)
bmesh.ops.delete(bm, geom=[f for f in bm.faces if f.material_index != i], context='FACES')
if not bm.faces:
bm.free()
continue
bmesh.ops.triangulate(bm, faces=bm.faces)
name = f'Arms_{label}' + ('' if i == 0 else f'_{mat.name}')
part = bpy.data.meshes.new(name)
bm.to_mesh(part)
bm.free()
part.materials.clear()
part.materials.append(mat)
for p in part.polygons:
p.material_index = 0
ob = bpy.data.objects.new(name, part)
scene.collection.objects.link(ob)
created.append(ob)
xs = [v.co for v in part.vertices]
lo = Vector([min(v[k] for v in xs) for k in range(3)])
hi = Vector([max(v[k] for v in xs) for k in range(3)])
layout[name] = {'center': [round(c, 4) for c in (lo + hi) / 2], 'size': [round(c, 4) for c in hi - lo],
'triangles': len(part.polygons), 'material': mat.name if mat else None}
bpy.data.meshes.remove(me)
# Roblox textures top out at 1024 px; shrink in memory only (the .blend is never saved).
for im in bpy.data.images:
if im.size[0] > MAX_TEX:
im.scale(MAX_TEX, MAX_TEX)
for o in scene.objects:
o.select_set(o in created)
bpy.context.window_scene if hasattr(bpy.context, 'window_scene') else None
bpy.ops.export_scene.gltf(filepath=GLB, export_format='GLB', use_selection=True, use_active_scene=True,
export_apply=True, export_animations=False, export_skins=False, export_yup=True,
export_texcoords=True, export_normals=True, export_materials='EXPORT',
export_image_format='JPEG', export_jpeg_quality=90)
with open(os.path.join(OUT_DIR, 'hands_layout.json'), 'w', encoding='utf-8') as f:
json.dump(layout, f, indent=2)
print('HANDS_EXPORT', json.dumps({'file': GLB, 'bytes': os.path.getsize(GLB), 'layout': layout}))
+53
View File
@@ -0,0 +1,53 @@
import bpy, os, json
BASE=os.path.dirname(os.path.abspath(__file__))
reports=[]
for name in ('christmas_train','gingerbread_house'):
folder=os.path.join(BASE,name)
bpy.ops.wm.open_mainfile(filepath=os.path.join(folder,name+'.blend'))
bpy.context.scene.frame_set(1)
def presentation(o):
while o:
if o.name.startswith('PRESENTATION'): return True
o=o.parent
return False
for o in list(bpy.data.objects):
if presentation(o) or o.type in {'CAMERA','LIGHT'}: bpy.data.objects.remove(o,do_unlink=True)
bpy.ops.object.select_all(action='DESELECT')
meshes=[o for o in bpy.context.scene.objects if o.type in {'MESH','CURVE'}]
for o in meshes:o.select_set(True)
bpy.context.view_layer.objects.active=meshes[0]
bpy.ops.object.convert(target='MESH')
meshes=[o for o in bpy.context.scene.objects if o.type=='MESH']
for o in meshes:
if not o.data.uv_layers:
bpy.ops.object.select_all(action='DESELECT');o.select_set(True);bpy.context.view_layer.objects.active=o
bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.uv.smart_project(island_margin=.02);bpy.ops.object.mode_set(mode='OBJECT')
# Original assets use solid-color PBR materials. Embed their colors as real
# PNG textures while keeping metallic, roughness and emission settings.
mats={m for o in meshes for m in o.data.materials if m}
texdir=os.path.join(folder,'textures');os.makedirs(texdir,exist_ok=True)
for i,m in enumerate(sorted(mats,key=lambda m:m.name)):
p=next((n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED'),None)
if not p:continue
color=tuple(p.inputs['Base Color'].default_value)
im=bpy.data.images.new(name+'_'+m.name+'_BaseColor',width=16,height=16,alpha=True)
im.generated_color=color
im.pixels[:]=list(color)*256
im.filepath_raw=os.path.join(texdir,'%02d_basecolor.png'%i);im.file_format='PNG';im.save();im.pack()
tex=m.node_tree.nodes.new('ShaderNodeTexImage');tex.image=im
m.node_tree.links.new(tex.outputs['Color'],p.inputs['Base Color'])
for o in bpy.context.scene.objects:
if o.animation_data:o.animation_data_clear()
bpy.ops.object.select_all(action='SELECT')
target=os.path.join(folder,name+'_roblox.glb')
bpy.ops.export_scene.gltf(filepath=target,export_format='GLB',use_selection=True,export_apply=True,export_animations=False,export_yup=True,export_texcoords=True,export_normals=True,export_materials='EXPORT')
expected=len(meshes)
# Round-trip check ensures the file actually loads with meshes and textures.
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=target)
imported=[o for o in bpy.context.scene.objects if o.type=='MESH']
images=[im for im in bpy.data.images if im.type=='IMAGE']
assert imported and images, 'Missing meshes or embedded textures'
reports.append({'file':target,'bytes':os.path.getsize(target),'source_mesh_objects':expected,'imported_mesh_objects':len(imported),'embedded_images':len(images),'triangles':sum(len(p.vertices)-2 for o in imported for p in o.data.polygons)})
with open(os.path.join(BASE,'glb_export_report.json'),'w',encoding='utf8') as f:json.dump(reports,f,indent=2)
print('GLB_EXPORT_VERIFIED',json.dumps(reports))
+168
View File
@@ -0,0 +1,168 @@
"""Export the V4 sniper rifle (no hands) as a Roblox-ready GLB with embedded PBR textures.
Run inside Blender with sniper_reference_v12_hands_natural.blend open:
exec(open(r'C:\\roblox\\hunter\\blender\\export_sniper_roblox.py', encoding='utf-8').read())
The source scene is not modified: evaluated copies of the rifle parts (bevels applied) go
into a temporary scene, are joined into one mesh per material (Roblox MeshPart limit is
20k triangles each), get small baked base-colour and metal/roughness PNGs, and are exported.
The pivot is moved to the pistol grip so the mesh drops straight into a Tool Handle.
"""
import json
import os
import struct
import bpy
import bmesh
from mathutils import Matrix, Vector
OUT_DIR = r'C:\roblox\hunter\3D models\sniper\export'
GRIP = Vector((-2.75, 0.0, -0.85)) # middle of the pistol grip in rifle space
TEX = 32
# Optional settings, set before exec() to export another part (e.g. a sight) with the same
# pivot, so it lines up with the rifle when both get the same CFrame in Roblox:
# EXPORT_COLLECTION = 'Sight Scope'; EXPORT_GLB = 'sight_scope.glb'; EXPORT_PREFIX = 'Scope_'
_g = globals()
GLB = os.path.join(OUT_DIR, _g.get('EXPORT_GLB', 'sniper_rifle.glb'))
PREFIX = _g.get('EXPORT_PREFIX', 'Rifle_')
os.makedirs(os.path.join(OUT_DIR, 'textures'), exist_ok=True)
src = bpy.data.collections[_g.get('EXPORT_COLLECTION', 'Rifle V4')]
dg = bpy.context.evaluated_depsgraph_get()
# ------------------------------------------------ gather triangles per material
per_mat = {}
for o in list(src.all_objects): # snapshot: creating meshes invalidates the live iterator
if o.type != 'MESH' or o.hide_render:
continue
oe = o.evaluated_get(dg)
me = bpy.data.meshes.new_from_object(oe, preserve_all_data_layers=False, depsgraph=dg)
me.transform(Matrix.Translation(-GRIP) @ o.matrix_world)
for i, slot in enumerate(o.material_slots):
mat = slot.material
if mat is None:
continue
bm = bmesh.new()
bm.from_mesh(me)
bmesh.ops.delete(bm, geom=[f for f in bm.faces if f.material_index != i], context='FACES')
if bm.faces:
per_mat.setdefault(mat, []).append(bm)
else:
bm.free()
bpy.data.meshes.remove(me)
# ------------------------------------------------ build export objects (only they get selected)
scene = bpy.context.scene
created_images, created_mats, created_objs = [], [], []
def solid_image(name, rgba, path):
im = bpy.data.images.new(name, TEX, TEX, alpha=True)
im.pixels[:] = list(rgba) * (TEX * TEX)
im.filepath_raw = path
im.file_format = 'PNG'
im.save()
im.pack()
created_images.append(im)
return im
def export_material(src_mat):
"""Copy of the material driven by image textures, which glTF/Roblox read as SurfaceAppearance."""
p = next(n for n in src_mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')
color = list(p.inputs['Base Color'].default_value)
emit = p.inputs['Emission Strength'].default_value
if emit > 0: # glowing channels: bake the emission colour so it reads bright without lighting
color = list(p.inputs['Emission Color'].default_value)
metal = p.inputs['Metallic'].default_value
rough = p.inputs['Roughness'].default_value
slug = src_mat.name.lower().replace(' ', '_')
tex_dir = os.path.join(OUT_DIR, 'textures')
base = solid_image(f'{slug}_color', color[:3] + [1.0], os.path.join(tex_dir, f'{slug}_color.png'))
orm = solid_image(f'{slug}_mr', (1.0, rough, metal, 1.0), os.path.join(tex_dir, f'{slug}_metalrough.png'))
orm.colorspace_settings.name = 'Non-Color'
m = bpy.data.materials.new(src_mat.name)
created_mats.append(m)
nt = m.node_tree
nt.nodes.clear()
bsdf = nt.nodes.new('ShaderNodeBsdfPrincipled')
out = nt.nodes.new('ShaderNodeOutputMaterial')
nt.links.new(bsdf.outputs['BSDF'], out.inputs['Surface'])
t1 = nt.nodes.new('ShaderNodeTexImage'); t1.image = base
t2 = nt.nodes.new('ShaderNodeTexImage'); t2.image = orm
sep = nt.nodes.new('ShaderNodeSeparateColor')
nt.links.new(t1.outputs['Color'], bsdf.inputs['Base Color'])
nt.links.new(t2.outputs['Color'], sep.inputs['Color'])
nt.links.new(sep.outputs['Green'], bsdf.inputs['Roughness'])
nt.links.new(sep.outputs['Blue'], bsdf.inputs['Metallic'])
if emit > 0:
nt.links.new(t1.outputs['Color'], bsdf.inputs['Emission Color'])
bsdf.inputs['Emission Strength'].default_value = 1.0
return m, {'color': [round(c, 3) for c in color[:3]], 'metal': round(metal, 2),
'rough': round(rough, 2), 'emissive': emit > 0}
report = {'parts': []}
for src_mat, bms in sorted(per_mat.items(), key=lambda kv: kv[0].name):
joined = bmesh.new()
for bm in bms:
tmp = bpy.data.meshes.new('tmp')
bm.to_mesh(tmp)
bm.free()
joined.from_mesh(tmp)
bpy.data.meshes.remove(tmp)
bmesh.ops.triangulate(joined, faces=joined.faces)
name = PREFIX + src_mat.name.title().replace(' ', '')
me = bpy.data.meshes.new(name)
joined.to_mesh(me)
joined.free()
for uv in list(me.uv_layers):
me.uv_layers.remove(uv)
me.uv_layers.new(name='UVMap') # solid textures: any UV layout samples the same colour
mat, info = export_material(src_mat)
me.materials.clear()
me.materials.append(mat)
for poly in me.polygons:
poly.material_index = 0
ob = bpy.data.objects.new(name, me)
scene.collection.objects.link(ob)
created_objs.append(ob)
info.update(name=name, triangles=len(me.polygons))
report['parts'].append(info)
# ------------------------------------------------ export
prev_sel = [o for o in scene.objects if o.select_get()]
for o in scene.objects:
o.select_set(o in created_objs)
bpy.ops.export_scene.gltf(filepath=GLB, export_format='GLB', use_selection=True, use_active_scene=True,
export_apply=True, export_animations=False, export_yup=True,
export_texcoords=True, export_normals=True, export_materials='EXPORT',
export_image_format='AUTO')
for o in prev_sel:
o.select_set(True)
# ------------------------------------------------ clean up the temporary data
for o in created_objs:
me = o.data
bpy.data.objects.remove(o)
bpy.data.meshes.remove(me)
for m in created_mats:
bpy.data.materials.remove(m)
for im in created_images:
bpy.data.images.remove(im)
# ------------------------------------------------ verify the GLB contents
with open(GLB, 'rb') as f:
magic, _, total = struct.unpack('<4sII', f.read(12))
jlen, _ = struct.unpack('<II', f.read(8))
gltf = json.loads(f.read(jlen))
xs = [v for a in gltf['accessors'] if a.get('type') == 'VEC3' and 'min' in a for v in (a['min'], a['max'])]
lo = [min(v[i] for v in xs) for i in range(3)]
hi = [max(v[i] for v in xs) for i in range(3)]
report.update(file=GLB, bytes=total, magic=magic.decode(), meshes=len(gltf['meshes']),
materials=len(gltf['materials']), images=len(gltf.get('images', [])),
size_yup=[round(h - l, 2) for l, h in zip(lo, hi)],
triangles=sum(p['triangles'] for p in report['parts']))
EXPORT_REPORT = report
print(json.dumps(report))
+260
View File
@@ -0,0 +1,260 @@
"""Fit the gloved hands onto the rifle: no penetration, finger pads in contact, natural joints.
Run in Blender after pose_hands_natural.py has been exec'd into the same namespace `g`:
g = {'__name__': 'pose'}
exec(open(r'C:\\roblox\\hunter\\blender\\pose_hands_natural.py', encoding='utf-8').read(), g)
exec(open(r'C:\\roblox\\hunter\\blender\\fit_grip.py', encoding='utf-8').read(), g)
print(g['FIT_RESULT']) # paste the numbers back into pose_hands_natural.py
Each hand is fitted by coordinate descent over its placement (knuckle point, orientation)
and joint angles. The cost punishes penetration hard, rewards finger pads resting on the
surface, and keeps joints near a natural curl.
Inside/outside: every rifle part is a closed mesh, so a glove vertex is inside a part when a
ray from it crosses that part's surface an odd number of times (parts pre-filtered by bounding box).
"""
import math
import time
import bpy
from mathutils import Vector
from mathutils.bvhtree import BVHTree
FINGERS = ('index', 'middle', 'ring', 'pink')
DEPTH_WEIGHT = 40.0 # penetration is far worse than a small gap
CONTACT_GAP = 0.01 # a phalanx counts as touching below this gap
RAY_DIR = Vector((0.5774, 0.5774, 0.5774))
TRIGGER = Vector((-2.35, -0.06, -0.35))
HANDGUARD_TOP = 0.5
def build_rifle_bvh():
dg = bpy.context.evaluated_depsgraph_get()
verts, polys, parts = [], [], []
for o in bpy.data.collections['Rifle V4'].objects:
if o.type != 'MESH' or o.hide_render:
continue
oe = o.evaluated_get(dg)
me = oe.to_mesh()
wv = [oe.matrix_world @ v.co for v in me.vertices]
wp = [list(p.vertices) for p in me.polygons]
oe.to_mesh_clear()
lo = Vector([min(v[i] for v in wv) for i in range(3)])
hi = Vector([max(v[i] for v in wv) for i in range(3)])
parts.append((lo, hi, BVHTree.FromPolygons(wv, wp), o.name))
base = len(verts)
verts += wv
polys += [[base + i for i in p] for p in wp]
return BVHTree.FromPolygons(verts, polys), parts
def depth_inside(p):
"""Penetration depth of point p into the rifle (0 when outside)."""
deepest = 0.0
for lo, hi, tree, _ in PARTS:
if not (lo.x <= p.x <= hi.x and lo.y <= p.y <= hi.y and lo.z <= p.z <= hi.z):
continue
hits, origin = 0, p.copy()
while True:
loc, _, _, _ = tree.ray_cast(origin, RAY_DIR)
if loc is None:
break
hits += 1
origin = loc + RAY_DIR * 1e-4
if hits % 2:
deepest = max(deepest, tree.find_nearest(p)[3])
return deepest
GLOVE = bpy.data.objects['hardknuckle']
RIFLE, PARTS = build_rifle_bvh()
_groups = {vg.index: vg.name for vg in GLOVE.vertex_groups}
OWNER = []
for _v in GLOVE.data.vertices:
_best = max(_v.groups, key=lambda gw: gw.weight, default=None)
OWNER.append(_groups[_best.group] if _best else None)
def chain(finger, side):
if finger == 'thumb':
return [f'thumb_L.{side}', f'thumb_L.002.{side}', f'thumb_L.001.{side}']
return [f'{finger}_L.{side}', f'{finger}_L.003.{side}', f'{finger}_L.002.{side}', f'{finger}_L.001.{side}']
def hand_bones(side):
return [f'hand_L.{side}'] + [b for f in FINGERS + ('thumb',) for b in chain(f, side)]
def measure(bones):
"""{bone: [penetration depth sum, closest outside gap]} for glove vertices owned by `bones`."""
bpy.context.view_layer.update()
ge = GLOVE.evaluated_get(bpy.context.evaluated_depsgraph_get())
me = ge.to_mesh()
mw = ge.matrix_world
out = {b: [0.0, 9.0] for b in bones}
for i, v in enumerate(me.vertices):
b = OWNER[i]
if b not in out:
continue
p = mw @ v.co
d = depth_inside(p)
if d > 0:
out[b][0] += d
else:
loc, _, _, dist = RIFLE.find_nearest(p, 0.8)
if loc is not None:
out[b][1] = min(out[b][1], dist)
ge.to_mesh_clear()
return out
def world(bone, at='head'):
pb = rig.pose.bones[bone]
return rig.matrix_world @ (pb.head if at == 'head' else pb.tail)
# ------------------------------------------------------------------ parameterisation
def set_rot(bone, x=0.0, z=0.0):
pb = rig.pose.bones[bone]
pb.rotation_mode = 'XYZ'
pb.rotation_euler = (math.radians(x), 0.0, math.radians(z))
def aim_elbow(side, pole):
s_ = world(f'upperarm_L.{side}')
w_ = world(f'hand_IK_L.{side}')
set_world(f'elbow_IK_L.{side}', (s_ + w_) / 2 + pole)
def rotate_axes(axes, tilt):
from mathutils import Euler
r = Euler([math.radians(t) for t in tilt], 'XYZ').to_matrix()
return [r @ a for a in axes]
def apply_right(p):
zr = GRIP_AXIS.normalized()
xr = Vector((0, -1, 0))
axes = rotate_axes((xr, zr.cross(xr), zr), (p['tx'], p['ty'], p['tz']))
place_hand('R', RIGHT_KNUCKLE + Vector((p['kx'], p['ky'], p['kz'])), *axes)
aim_elbow('R', RIGHT_ELBOW_POLE)
for f in ('middle', 'ring', 'pink'):
spread = {'middle': 0, 'ring': 1, 'pink': 2}[f] * p['fan'] # lower fingers curl a bit more
for b, deg in zip(chain(f, 'R'), (p['b0'] + spread, p['b1'], p['b2'], p['b2'] * 0.5)):
set_rot(b, z=deg)
for b, deg in zip(chain('index', 'R'), (p['i0'], p['i1'], p['i2'], p['i2'] * 0.6)):
set_rot(b, z=deg)
rig.pose.bones['index_L.R'].rotation_euler.x = math.radians(p['ilift'])
t = chain('thumb', 'R')
set_rot(t[0], x=p['t0x'], z=p['t0'])
set_rot(t[1], z=p['t1'])
set_rot(t[2], z=p['t2'])
bpy.context.view_layer.update()
def apply_left(p):
xl = (LEFT_PALM_NORMAL + Vector((0, p['ny'], 0))).normalized()
a = math.radians(p['ang'])
yl = math.cos(a) * Vector((1, 0, 0)) + math.sin(a) * Vector((0, -1, 0))
yl = (yl - xl * yl.dot(xl)).normalized()
axes = rotate_axes((xl, yl, xl.cross(yl)), (p['tx'], 0.0, 0.0))
place_hand('L', LEFT_KNUCKLE + Vector((p['kx'], p['ky'], p['kz'])), *axes)
aim_elbow('L', LEFT_ELBOW_POLE)
for i, f in enumerate(FINGERS):
for b, deg in zip(chain(f, 'L'), (p['b0'] + i * p['fan'], p['b1'], p['b2'], p['b2'] * 0.6)):
set_rot(b, z=-deg)
t = chain('thumb', 'L')
set_rot(t[0], x=p['t0x'], z=-p['t0'])
set_rot(t[1], z=-p['t1'])
set_rot(t[2], z=-p['t2'])
bpy.context.view_layer.update()
# ------------------------------------------------------------------ costs
def contact_terms(m, side, fingers):
gap = 0.0
for f in fingers:
for b in chain(f, side)[-2:]: # the two outer phalanges carry the pads
if m[b][0] == 0:
gap += max(0.0, m[b][1] - CONTACT_GAP)
hb = f'hand_L.{side}'
if m[hb][0] == 0:
gap += 2 * max(0.0, m[hb][1] - CONTACT_GAP) # palm must rest on the rifle
return gap
def right_cost(p):
apply_right(p)
m = measure(hand_bones('R'))
depth = sum(v[0] for v in m.values())
c = DEPTH_WEIGHT * depth + contact_terms(m, 'R', ('middle', 'ring', 'pink', 'thumb'))
pad = (world('index_L.001.R') + world('index_L.001.R', 'tail')) / 2
c += 1.5 * (pad - TRIGGER).length # index pad on the trigger
c += 0.002 * (abs(p['tx']) + abs(p['ty']) + abs(p['tz']))
return c, depth
def left_cost(p):
apply_left(p)
m = measure(hand_bones('L'))
depth = sum(v[0] for v in m.values())
c = DEPTH_WEIGHT * depth + contact_terms(m, 'L', FINGERS + ('thumb',))
for f in FINGERS: # fingertips stay on the side, below the top edge
tip = world(chain(f, 'L')[-1], 'tail')
c += 3.0 * max(0.0, tip.z - (HANDGUARD_TOP - 0.15))
c += 0.002 * abs(p['tx'])
return c, depth
def descend(cost_fn, p, steps, limits, rounds=4, budget=60.0):
"""Coordinate descent: try +-step on each parameter, halve the steps each round."""
t0 = time.time()
best, depth = cost_fn(p)
evals = 1
for _ in range(rounds):
improved = True
while improved and time.time() - t0 < budget:
improved = False
for k in p:
for sgn in (1, -1):
q = dict(p)
lo, hi = limits.get(k, (-1e9, 1e9))
q[k] = min(hi, max(lo, p[k] + sgn * steps[k]))
if q[k] == p[k]:
continue
c, d = cost_fn(q)
evals += 1
if c < best - 1e-5:
best, depth, p, improved = c, d, q, True
break
steps = {k: v / 2 for k, v in steps.items()}
cost_fn(p)
return p, round(best, 4), round(depth, 4), evals
RIGHT_START = dict(kx=0.0, ky=0.0, kz=0.0, tx=0.0, ty=0.0, tz=0.0, fan=3.0,
b0=80.0, b1=60.0, b2=40.0, i0=35.0, i1=45.0, i2=25.0, ilift=10.0,
t0x=0.0, t0=60.0, t1=-20.0, t2=-10.0)
RIGHT_STEPS = dict(kx=0.04, ky=0.04, kz=0.04, tx=6, ty=6, tz=6, fan=3,
b0=8, b1=8, b2=8, i0=8, i1=8, i2=8, ilift=5, t0x=8, t0=8, t1=8, t2=8)
LEFT_START = dict(kx=0.0, ky=-0.05, kz=-0.03, ny=0.0, ang=65.0, tx=0.0, fan=3.0,
b0=55.0, b1=40.0, b2=20.0, t0x=0.0, t0=20.0, t1=10.0, t2=5.0)
LEFT_STEPS = dict(kx=0.04, ky=0.04, kz=0.04, ny=0.1, ang=8, tx=6, fan=3,
b0=8, b1=8, b2=8, t0x=8, t0=8, t1=8, t2=8)
JOINT_LIMITS = {k: (0, 100) for k in ('b0', 'b1', 'b2', 'i0', 'i1', 'i2')}
JOINT_LIMITS.update(fan=(0, 10), ilift=(-10, 30), t0x=(-40, 40), t0=(-30, 90), t1=(-60, 60), t2=(-60, 60),
ang=(20, 90), ny=(-0.6, 0.6), tx=(-30, 30), ty=(-30, 30), tz=(-30, 30))
RIGHT_FIT = descend(right_cost, dict(RIGHT_START), RIGHT_STEPS, JOINT_LIMITS)
LEFT_FIT = descend(left_cost, dict(LEFT_START), LEFT_STEPS, JOINT_LIMITS)
final = measure(hand_bones('R') + hand_bones('L'))
FIT_RESULT = {
'RIGHT': {k: round(v, 2) for k, v in RIGHT_FIT[0].items()},
'LEFT': {k: round(v, 2) for k, v in LEFT_FIT[0].items()},
'right_cost_depth_evals': RIGHT_FIT[1:],
'left_cost_depth_evals': LEFT_FIT[1:],
'bones_penetrating': sorted(b for b, v in final.items() if v[0] > 0),
'bones_touching': sorted(b for b, v in final.items() if v[0] == 0 and v[1] <= CONTACT_GAP),
}
print(FIT_RESULT)
+43
View File
@@ -0,0 +1,43 @@
import bpy
from mathutils import Vector
s=bpy.context.scene
c=next(c for c in s.collection.children if c.name.startswith('Rifle V4'))
mounts=[o for o in c.objects if o.name.startswith('Integrated mount')]
turret=next(o for o in c.objects if o.name.startswith('Elevation turret'))
core=next(o for o in c.objects if o.name.startswith('Scope core'))
rail=next(o for o in c.objects if o.name.startswith('Rail spine'))
def bounds(o):
pts=[o.matrix_world@Vector(p) for p in o.bound_box]
return Vector(tuple(min(p[i] for p in pts) for i in range(3))),Vector(tuple(max(p[i] for p in pts) for i in range(3)))
metal=mounts[0].data.materials[0]
def finish(o,name):
o.name=name
for col in list(o.users_collection):col.objects.unlink(o)
c.objects.link(o);o.data.materials.append(metal)
b=o.modifiers.new('Edge bevel','BEVEL');b.width=.018;b.segments=3
o.modifiers.new('Normals','WEIGHTED_NORMAL')
def box(name,loc,size):
bpy.ops.mesh.primitive_cube_add(location=loc);o=bpy.context.object;o.scale=Vector(size)/2
bpy.ops.object.transform_apply(location=False,rotation=False,scale=True);finish(o,name)
return o
rail_lo,rail_hi=bounds(rail)
for i,m in enumerate(mounts):
lo,hi=bounds(m);x=(lo.x+hi.x)/2
bottom=rail_hi.z-.065;top=lo.z+.07
box('Scope rail saddle '+str(i),(x,0,(bottom+top)/2),(.36,.56,top-bottom))
for side in (-1,1):
box('Rail gripping jaw',(x,side*.22,rail_hi.z-.025),(.34,.13,.19))
bpy.ops.mesh.primitive_cylinder_add(vertices=12,radius=.055,depth=.04,location=(x,side*.30,rail_hi.z+.015),rotation=(1.5707963,0,0))
finish(bpy.context.object,'Clamp screw')
# Tube radius at the turret is 40/180. Connect to its actual local surface.
top_core=(490-277)/180+40/180
lo,hi=bounds(turret)
bottom=top_core-.06;top=lo.z+.08
bpy.ops.mesh.primitive_cylinder_add(vertices=32,radius=.18,depth=top-bottom,location=(turret.location.x,turret.location.y,(top+bottom)/2))
finish(bpy.context.object,'Turret connecting stem')
box('Turret seating block',(turret.location.x,0,top_core-.025),(.42,.36,.18))
bpy.context.view_layer.update()
assert top>bottom
path=r'C:\roblox\hunter\3D models\sniper_reference_v6.blend'
bpy.ops.wm.save_as_mainfile(filepath=path)
print('Saved',path,'mounts',len(mounts),'turret connection',top-bottom)
+18
View File
@@ -0,0 +1,18 @@
import bpy,os,json
s=bpy.context.scene
old=next((c for c in s.collection.children if c.name.startswith('Gloved Arms')),None)
if old:
for o in list(old.objects):bpy.data.objects.remove(o,do_unlink=True)
bpy.data.collections.remove(old)
path=r'C:\roblox\hunter\3D models\hand\source\HandWithGloves.blend'
with bpy.data.libraries.load(path,link=False) as (src,dst):dst.objects=src.objects
c=bpy.data.collections.new('User Gloved Hands');s.collection.children.link(c)
for o in dst.objects:
if o:c.objects.link(o)
texdir=r'C:\roblox\hunter\3D models\hand\textures'
for im in bpy.data.images:
filename=os.path.basename(im.filepath.replace('\\','/'))
candidate=os.path.join(texdir,filename)
if filename and os.path.isfile(candidate):im.filepath=candidate;im.reload();im.pack()
bpy.context.view_layer.update()
print(json.dumps([{'name':o.name,'type':o.type,'location':list(o.location),'dimensions':list(o.dimensions),'parent':o.parent.name if o.parent else None,'bones':[(b.name,list(b.head_local),list(b.tail_local)) for b in o.data.bones] if o.type=='ARMATURE' else []} for o in c.objects]))
+4
View File
@@ -0,0 +1,4 @@
import bpy,json
r=next(o for o in bpy.context.scene.objects if o.type=='ARMATURE' and o.name.startswith('Armature'))
print('MATRIX',list(map(list,r.matrix_world)))
print(json.dumps([{'name':p.name,'head':list(r.matrix_world@p.head),'tail':list(r.matrix_world@p.tail),'constraints':[(c.name,c.type,getattr(c,'subtarget','')) for c in p.constraints]} for p in r.pose.bones if any(k in p.name for k in ('hand','lowerarm','upperarm','elbow'))]))
+42
View File
@@ -0,0 +1,42 @@
"""Per-material bounding boxes of the exported rifle, in the same space export_sniper_roblox.py
writes (rifle space with the pistol grip at the origin, bevels applied).
Each exported MeshPart is one material, and Roblox centres a MeshPart on its mesh's bounding box,
so comparing these before and after a model edit says how far each MeshPart's centre moves.
exec(open(r'C:\\roblox\\hunter\\blender\\material_bounds.py', encoding='utf-8').read())
MATERIAL_BOUNDS -> {'Rifle_Rubber': {'center': [...], 'size': [...]}, ...}
"""
import bpy
from mathutils import Matrix, Vector
GRIP = Vector((-2.75, 0.0, -0.85))
def material_bounds(collection_name='Rifle V4'):
dg = bpy.context.evaluated_depsgraph_get()
lo, hi = {}, {}
for o in list(bpy.data.collections[collection_name].all_objects):
if o.type != 'MESH' or o.hide_render:
continue
oe = o.evaluated_get(dg)
me = bpy.data.meshes.new_from_object(oe, preserve_all_data_layers=False, depsgraph=dg)
me.transform(Matrix.Translation(-GRIP) @ o.matrix_world)
for poly in me.polygons:
slot = o.material_slots[poly.material_index] if poly.material_index < len(o.material_slots) else None
if not slot or not slot.material:
continue
name = 'Rifle_' + slot.material.name.title().replace(' ', '')
for vi in poly.vertices:
v = me.vertices[vi].co
a = lo.setdefault(name, [1e9] * 3)
b = hi.setdefault(name, [-1e9] * 3)
for i in range(3):
a[i] = min(a[i], v[i])
b[i] = max(b[i], v[i])
bpy.data.meshes.remove(me)
return {n: {'center': [round((lo[n][i] + hi[n][i]) / 2, 5) for i in range(3)],
'size': [round(hi[n][i] - lo[n][i], 5) for i in range(3)]} for n in lo}
MATERIAL_BOUNDS = material_bounds()
+29
View File
@@ -0,0 +1,29 @@
import bpy,math,json
from mathutils import Vector,Matrix
s=bpy.context.scene;r=next(o for o in s.objects if o.type=='ARMATURE' and o.name.startswith('Armature'))
r.animation_data_clear()
if r.parent:r.parent.location=(-1.9,0,-4.9)
bpy.context.view_layer.update()
def control(name,target,direction):
p=r.pose.bones[name]
for con in p.constraints:con.mute=True
rot=Vector(direction).to_track_quat('Y','Z').to_matrix().to_4x4()
rot.translation=Vector(target)
p.matrix=r.matrix_world.inverted()@rot
def pole(name,point):
p=r.pose.bones[name];m=p.matrix.copy();m.translation=r.matrix_world.inverted()@Vector(point);p.matrix=m
control('hand_IK_L.L',(1.05,-.12,-.38),(0,1,.25))
control('hand_IK_L.R',(-2.95,.15,-1.05),(.25,-.1,1))
pole('elbow_IK_L.L',(-.6,-1.8,-1.7));pole('elbow_IK_L.R',(-3.8,1.3,-1.9))
for p in r.pose.bones:
if any(p.name.startswith(k) for k in ('index','middle','ring','pink','thumb')):
p.rotation_mode='XYZ';p.rotation_euler=(0,0,0)
if not p.name.startswith('thumb'):
p.rotation_euler.x=math.radians(38 if '.' in p.name.split('_')[1] else 20)
if p.name.startswith('index') and p.name.endswith('.R'):p.rotation_euler.x=math.radians(15)
else:p.rotation_euler.z=math.radians(15 if p.name.endswith('.L') else -15)
bpy.context.view_layer.update()
print(json.dumps({n:list(r.matrix_world@r.pose.bones[n].head) for n in ('hand_L.L','hand_L.R')}))
s.render.filepath=r'C:\roblox\hunter\3D models\hands_grip_preview.png';s.cycles.samples=16
bpy.ops.wm.save_as_mainfile(filepath=r'C:\roblox\hunter\3D models\sniper_reference_v10_grip.blend')
bpy.ops.render.render(write_still=True)
+172
View File
@@ -0,0 +1,172 @@
"""Pose the user's gloved FPS arms naturally on the V4 sniper rifle (right-handed shooter).
Run inside Blender (scene "Reference Sculpt V4"), e.g. via the Blender MCP:
exec(open(r'C:\\roblox\\hunter\\blender\\pose_hands_natural.py', encoding='utf-8').read())
Rifle space: barrel points +X, up is +Z, shooter's right is -Y.
Hand bone axes (both hands): Y = wrist -> fingers, +Z = index side.
Palm faces -X on the right hand and +X on the left hand, so fingers curl with
+Z rotation on the right hand and -Z rotation on the left.
"""
import math
import bpy
from mathutils import Euler, Matrix, Vector
# ---------------------------------------------------------------- parameters
ARM_SCALE = 1.4 # hand length ~19% of the rifle, close to real proportions
SHOULDERS = Vector((-4.22, 0.92, 0.3)) # centre between the shoulders: rifle height, right shoulder behind the stock
BLADE_DEG = 40 # bladed stance: left shoulder forward so the support arm reaches the handguard
EYE_PITCH_DEG = -9 # first-person camera looks slightly down
EYE_YAW_DEG = -5 # and slightly right, toward the rifle
EYE = Vector((-5.6, 1.4, 1.2)) # first-person camera: ~0.9 above the shoulders, left of the rifle
# Measured with ray casts: grip front edge at z=-0.7 is x=-2.66, sides at y=+-0.257,
# the grip leans along GRIP_AXIS. Handguard bottom z=-0.2, right face y=-0.41..-0.43.
GRIP_AXIS = Vector((0.33, 0.0, 0.94)) # grip leans back at the bottom
RIGHT_KNUCKLE = Vector((-2.58, -0.40, -0.72)) # middle-finger knuckle just off the grip's front-right edge
LEFT_KNUCKLE = Vector((0.60, -0.45, -0.33)) # middle-finger knuckle at the handguard's bottom-right edge
LEFT_PALM_NORMAL = Vector((0.0, 0.25, 0.97)) # left palm faces up (slightly left), under the handguard
RIGHT_HAND_TILT = (0.0, 0.0, 0.0) # extra hand rotation, degrees about world X/Y/Z (set by fit_grip.py)
LEFT_HAND_TILT = (0.0, 0.0, 0.0)
RIGHT_ELBOW_POLE = Vector((-0.3, -2.0, -0.6)) # right elbow out to the side, slightly down
LEFT_ELBOW_POLE = Vector((0.0, 0.9, -2.5)) # left elbow low and left, forearm rises to the handguard
LEFT_FINGER_ANGLE_DEG = 35 # 90 = fingers straight across to the right side, 0 = straight forward
# degrees per joint, base -> tip. Right fingers: knuckle bends ~90 to run across the
# grip's front face, then a second ~90 bend brings them back along its left side.
RIGHT_CURL = {
'index': (8, 0, 5, 5), # straight, along the right side of the trigger guard
'middle': (85, 5, 85, 20),
'ring': (85, 5, 85, 20),
'pink': (85, 10, 80, 20),
'thumb': (75, -40, -30), # base swings behind the grip (through the thumbhole), tip turns forward on the left side
}
RIGHT_INDEX_LIFT_DEG = 22 # raise the index from the grip angle to horizontal
# Left fingers: knuckle bends up so the fingers lie flat on the handguard's right face.
LEFT_CURL = {
'index': (40, 35, 25, 10), # relaxed wrap: fingers rise along the right face, tips curl in
'middle': (45, 35, 25, 10),
'ring': (50, 35, 25, 10),
'pink': (55, 35, 25, 10),
'thumb': (15, 0, 0), # along the handguard's left side, pointing forward
}
# ----------------------------------------------------------------------------
scene = bpy.data.scenes['Reference Sculpt V4']
rig = bpy.data.objects['Armature']
placement = rig.parent
def update():
bpy.context.view_layer.update()
def place_rig():
placement.scale = (0.16 * ARM_SCALE,) * 3
placement.rotation_euler = (0, 0, math.radians(90 - BLADE_DEG))
placement.location = (SHOULDERS.x, SHOULDERS.y, SHOULDERS.z - 4.665 * ARM_SCALE)
rig.animation_data_clear()
update()
def set_world(name, pos, x=None, y=None, z=None):
"""Put a pose bone at a world position (and world orientation if axes are given)."""
mw = rig.matrix_world
pb = rig.pose.bones[name]
for c in pb.constraints:
c.mute = True # Child Of to the old controller fights manual placement
if x is not None:
rot = mw.to_3x3().normalized().inverted() @ Matrix((x.normalized(), y.normalized(), z.normalized())).transposed()
m = rot.to_4x4()
else:
m = pb.matrix.to_3x3().normalized().to_4x4()
m.translation = mw.inverted() @ pos
pb.matrix = m
update()
def curl(side, sign, table):
for finger, angles in table.items():
if finger == 'thumb':
chain = [f'thumb_L.{side}', f'thumb_L.002.{side}', f'thumb_L.001.{side}']
else:
chain = [f'{finger}_L.{side}', f'{finger}_L.003.{side}', f'{finger}_L.002.{side}', f'{finger}_L.001.{side}']
for bone, deg in zip(chain, angles):
pb = rig.pose.bones.get(bone)
if pb:
pb.rotation_mode = 'XYZ'
pb.rotation_euler = (0, 0, sign * math.radians(deg))
def knuckle_offset(side):
"""Wrist -> middle-finger knuckle, in world units, measured from the rig."""
b = rig.data.bones
local = b[f'hand_L.{side}'].matrix_local.inverted() @ b[f'middle_L.{side}'].head_local
return local * rig.matrix_world.to_scale().x
def place_hand(side, knuckle, x, y, z):
"""Place the hand so its middle knuckle lands on `knuckle` with hand axes x/y/z."""
k = knuckle_offset(side)
wrist = knuckle - (k.x * x + k.y * y + k.z * z)
set_world(f'hand_IK_L.{side}', wrist, x, y, z)
return wrist
def pose_hands():
# Right hand: back of the hand on the grip's right side, knuckle line along the grip axis,
# knuckles at the front edge so the fingers wrap across the front strap to the left side.
zr = GRIP_AXIS.normalized()
xr = Vector((0, -1, 0)) # palm (-X) faces +Y, into the grip
yr = zr.cross(xr)
wrist_r = place_hand('R', RIGHT_KNUCKLE, xr, yr, zr)
# Left hand: palm up under the handguard, knuckles at its bottom-right edge,
# fingers bending up flat against the right face.
xl = LEFT_PALM_NORMAL.normalized()
a = math.radians(LEFT_FINGER_ANGLE_DEG)
yl = (math.cos(a) * Vector((1, 0, 0)) + math.sin(a) * Vector((0, -1, 0)))
yl = (yl - xl * yl.dot(xl)).normalized()
zl = xl.cross(yl) # index side points forward
wrist_l = place_hand('L', LEFT_KNUCKLE, xl, yl, zl)
mw = rig.matrix_world
sr = mw @ rig.pose.bones['upperarm_L.R'].head
sl = mw @ rig.pose.bones['upperarm_L.L'].head
set_world('elbow_IK_L.R', (sr + wrist_r) / 2 + RIGHT_ELBOW_POLE) # right elbow out and down
set_world('elbow_IK_L.L', (sl + wrist_l) / 2 + LEFT_ELBOW_POLE) # left elbow under the rifle
curl('R', +1, RIGHT_CURL)
curl('L', -1, LEFT_CURL)
rig.pose.bones['index_L.R'].rotation_euler.x = math.radians(RIGHT_INDEX_LIFT_DEG) # +X bends toward the index side (up)
update()
return wrist_r, wrist_l
def place_camera():
eye = EYE.copy()
cam = scene.camera
cam.location = eye
cam.rotation_mode = 'XYZ'
cam.rotation_euler = Euler((math.radians(90 + EYE_PITCH_DEG), 0, math.radians(-90 + EYE_YAW_DEG)), 'XYZ')
update()
return eye
def report(wrist_r, wrist_l):
mw = rig.matrix_world
hand_r = mw @ rig.pose.bones['hand_L.R'].head
hand_l = mw @ rig.pose.bones['hand_L.L'].head
return {
'right_hand_error': round((hand_r - wrist_r).length, 3), # > 0 means the arm can't reach
'left_hand_error': round((hand_l - wrist_l).length, 3),
}
place_rig()
_wr, _wl = pose_hands()
_eye = place_camera()
POSE_REPORT = report(_wr, _wl)
POSE_REPORT['eye'] = [round(v, 3) for v in _eye]
print(POSE_REPORT)
+130
View File
@@ -0,0 +1,130 @@
import bpy, bmesh, os, json, re, io, contextlib, math, struct, shutil
from mathutils import Vector, Matrix
from mathutils.bvhtree import BVHTree
ROOT=r"C:\roblox\hunter"
OUT=ROOT+r"\3D models\game_zone\Roblox_Import"
os.makedirs(OUT,exist_ok=True)
source=bpy.context.scene
assert source.name.startswith("Hunter | Monolith arena"),source.name
temp=bpy.data.scenes.new("TEMP | Roblox export")
deps=bpy.context.evaluated_depsgraph_get()
manifest={"size_studs":[896,120,896],"stud_to_meter":.28,"axis":"Blender (x,y,z) -> Roblox (x,z,-y)","meshes":[],"lights":[]}
def rvec(p):return [round(p[0],6),round(p[2],6),round(-p[1],6)]
def srgb(c):return 12.92*c if c<=.0031308 else 1.055*(max(c,0)**(1/2.4))-.055
def plain_color(mat):
p=next(n for n in mat.node_tree.nodes if n.type=="BSDF_PRINCIPLED")
return [round(srgb(c),6) for c in p.inputs["Base Color"].default_value[:3]]
all_points=[]
for i,ob in enumerate(sorted([o for o in source.objects if o.type=="MESH"],key=lambda o:o.name),1):
lighting=any(c.name.startswith("Atmosphere") for c in ob.users_collection)
code=("L" if lighting else "A")+str(i).zfill(4)
name=code+"_"+re.sub(r"[^a-zA-Z0-9]+","_",ob.name).strip("_")
mats=[m for m in ob.data.materials if m]
material=mats[0]
p=next(n for n in material.node_tree.nodes if n.type=="BSDF_PRINCIPLED")
emission=float(p.inputs["Emission Strength"].default_value)
shape="decor" if lighting else ("wedge" if len(ob.data.vertices)==6 else "box" if len(ob.data.vertices)==8 else "gate")
entry={"id":code,"name":name,"source":ob.name,"shape":shape,"neon":emission>0,
"color":plain_color(material),"material":material.name,"colliders":[]}
# Gate voids are preserved by explicit invisible box colliders, not a hull.
if shape=="gate":
verts=[ob.matrix_world@v.co for v in ob.data.vertices]
tree=BVHTree.FromPolygons(verts,[tuple(p.vertices) for p in ob.data.polygons])
axes=[sorted(set(round(v[a],5) for v in verts)) for a in range(3)]
direction=Vector((.731,.417,.541)).normalized()
for ix in range(len(axes[0])-1):
for iy in range(len(axes[1])-1):
for iz in range(len(axes[2])-1):
lows=Vector((axes[0][ix],axes[1][iy],axes[2][iz]))
highs=Vector((axes[0][ix+1],axes[1][iy+1],axes[2][iz+1]))
size=highs-lows
if min(size)<.001:continue
center=(lows+highs)/2
loc,normal,_,_=tree.ray_cast(center,direction,2000)
if loc is not None and normal.dot(direction)>0:
entry["colliders"].append({"position":rvec(center),"size":[size.x,size.z,size.y]})
assert entry["colliders"],"No gate colliders: "+ob.name
evaluated=ob.evaluated_get(deps)
mesh=bpy.data.meshes.new_from_object(evaluated,preserve_all_data_layers=True,depsgraph=deps)
mesh.transform(ob.matrix_world)
bm=bmesh.new();bm.from_mesh(mesh)
assert all(e.is_manifold for e in bm.edges),"Non-manifold: "+ob.name
bmesh.ops.triangulate(bm,faces=list(bm.faces));bm.to_mesh(mesh);bm.free()
mesh.update()
tri=len(mesh.polygons)
assert tri<=20000,(ob.name,tri)
entry["triangles"]=tri
mesh.name=name
copy=bpy.data.objects.new(name,mesh);temp.collection.objects.link(copy)
# Keep copied geometry in studs for the mandatory intersection review.
entry["bounds"]=[[min(v.co[a] for v in mesh.vertices) for a in range(3)],
[max(v.co[a] for v in mesh.vertices) for a in range(3)]]
for v in mesh.vertices:all_points.append(tuple(v.co))
manifest["meshes"].append(entry)
for ob in source.objects:
if ob.type=="LIGHT" and ob.data.type=="AREA":
pos=ob.matrix_world.translation
direction=ob.matrix_world.to_quaternion()@Vector((0,0,-1))
manifest["lights"].append({"name":ob.name,"position":rvec(pos),"direction":rvec(direction),
"color":list(ob.data.color),"brightness":2.5,"range":48})
manifest["size_studs"]=[max(v[a] for v in all_points)-min(v[a] for v in all_points) for a in [0,2,1]]
bpy.context.window.scene=temp
check={}
code=open(ROOT+r"\blender\check_collisions.py",encoding="utf8").read()
exec(compile(code,"check_collisions.py","exec"),check)
log=io.StringIO()
with contextlib.redirect_stdout(log):status=check["main"]()
textlog=log.getvalue()
open(os.path.join(OUT,"collision_check.txt"),"w",encoding="utf8").write(textlog)
# Full hit list is retained, with expected structural contacts classified below.
byname={e["name"]:e for e in manifest["meshes"]}
reviews=[]
unexpected=[]
for ln in textlog.splitlines():
if "INTERSECTION: " not in ln:continue
left,right=ln.split("INTERSECTION: ",1)[1].split(" <-> ")
a,b=byname[left],byname[right]
overlap=[min(a["bounds"][1][k],b["bounds"][1][k])-max(a["bounds"][0][k],b["bounds"][0][k]) for k in range(3)]
if a["shape"]=="decor" or b["shape"]=="decor":
reason="Fixture housing/lens mounting contact; visual fixtures are non-colliding."
elif min(overlap)<.001:
reason="Intentional structural face/edge contact."
elif ("Citadel" in a["source"] or "Citadel" in b["source"]) and ("ascent" in a["source"] or "ascent" in b["source"]):
reason="Solid ramp supported by roof/bridge; walkable top is unobstructed."
else:
reason="REVIEW";unexpected.append([left,right,overlap])
reviews.append({"left":left,"right":right,"classification":reason,"overlap":overlap})
manifest["contact_review"]=reviews
manifest["unreviewed_intersections"]=unexpected
json.dump(manifest,open(os.path.join(OUT,"manifest.json"),"w",encoding="utf8"),indent=2)
if unexpected:
bpy.context.window.scene=source
result={"blocked_by_contact_review":unexpected,"temp_scene":temp.name}
else:
for ob in temp.objects:
ob.data.transform(Matrix.Scale(.28,4))
bpy.ops.object.select_all(action="SELECT")
target=os.path.join(OUT,"Hunter_Monolith_Arena.glb")
bpy.ops.export_scene.gltf(filepath=target,export_format="GLB",use_selection=True,use_active_scene=True,
export_apply=False,export_animations=False,export_yup=True,
export_texcoords=True,export_normals=True,export_materials="EXPORT",export_cameras=False,export_lights=False)
with open(target,"rb") as f:
head=f.read(12);length,kind=struct.unpack("<II",f.read(8));glb=json.loads(f.read(length))
assert len(glb.get("meshes",[]))==len(manifest["meshes"])
assert not glb.get("cameras")
assert len(glb.get("images",[]))==3
assert all("bufferView" in im for im in glb["images"])
manifest["export"]={"bytes":os.path.getsize(target),"meshes":len(glb["meshes"]),
"embedded_images":len(glb["images"]),"triangles":sum(e["triangles"] for e in manifest["meshes"]),
"max_triangles":max(e["triangles"] for e in manifest["meshes"])}
json.dump(manifest,open(os.path.join(OUT,"manifest.json"),"w",encoding="utf8"),indent=2)
texdir=os.path.join(OUT,"textures");os.makedirs(texdir,exist_ok=True)
for fn in ("HD_navy.png","HD_amber.png","HD_floor.png"):
shutil.copy2(ROOT+r"\3D models\game_zone\textures"+"/"+fn,texdir)
bpy.context.window.scene=source
for ob in list(temp.objects):
mesh=ob.data;bpy.data.objects.remove(ob,do_unlink=True)
if mesh.users==0:bpy.data.meshes.remove(mesh)
bpy.data.scenes.remove(temp)
result={"export":manifest["export"],"contacts_reviewed":len(reviews),"output":OUT}
+87
View File
@@ -0,0 +1,87 @@
import bpy, math, os
from mathutils import Vector
ns={'__name__':'library'}
exec(compile(open(r'C:\roblox\hunter\blender\sniper_modular.py',encoding='utf8').read(),'library','exec'),ns)
s=bpy.data.scenes.new('Sniper Rebuilt'); bpy.context.window.scene=s
c=bpy.data.collections.new('Integrated Rifle'); s.collection.children.link(c)
ns.update(SCENE=s,WEAPON=c)
mat=ns['material']; M=mat('Titanium','2A2D34'); B=mat('Black','111111',.6); A=mat('Armor','606878',.32)
C=mat('Cyan','00FFFF',.3,0,5); O=mat('Amber','FF5500',.3,0,5)
box=ns['box']; cyl=ns['cylinder']; beam=ns['beam']
def profile(name,points,depth,material,y=0,bevel=.045):
n=len(points); verts=[(x,y+d,z) for d in (-depth/2,depth/2) for x,z in points]
faces=[tuple(reversed(range(n))),tuple(range(n,2*n))]+[(i,(i+1)%n,(i+1)%n+n,i+n) for i in range(n)]
mesh=bpy.data.meshes.new(name); mesh.from_pydata(verts,[],faces); mesh.update()
o=bpy.data.objects.new(name,mesh); c.objects.link(o); o.data.materials.append(material)
b=o.modifiers.new('Machined edges','BEVEL'); b.width=bevel;b.segments=3
o.modifiers.new('Panel normals','WEIGHTED_NORMAL'); return o
def shell(name,rings,material):
verts=[(x,math.cos(2*math.pi*i/12+math.pi/12)*r,1.32+math.sin(2*math.pi*i/12+math.pi/12)*r) for x,r in rings for i in range(12)]
faces=[tuple(reversed(range(12))),tuple(range((len(rings)-1)*12,len(rings)*12))]
for j in range(len(rings)-1):
for i in range(12): faces.append((j*12+i,j*12+(i+1)%12,(j+1)*12+(i+1)%12,(j+1)*12+i))
mesh=bpy.data.meshes.new(name);mesh.from_pydata(verts,[],faces);mesh.update()
o=bpy.data.objects.new(name,mesh);c.objects.link(o);o.data.materials.append(material)
b=o.modifiers.new('Soft edges','BEVEL');b.width=.025;b.segments=3;o.modifiers.new('Normals','WEIGHTED_NORMAL')
profile('Chassis',[(-2,.25),(-1.7,.46),(1.95,.46),(2.15,.22),(1.9,-.3),(.4,-.48),(-.7,-.55),(-1.9,-.22)],.62,B)
for side in (-1,1):
y=side*.35
profile('Continuous channel',[(-1.85,.22),(-.95,.22),(-.7,.04),(-.45,.04),(-.2,.32),(1.95,.32),(1.95,.23),(-.15,.23),(-.4,-.06),(-.75,-.06),(-1,.13),(-1.85,.13)],.035,C,y,.012)
profile('Rear armor',[(-1.95,.31),(-1.5,.48),(-.65,.48),(-.45,.3),(-.62,.18),(-1.95,.18)],.1,A,y,.035)
profile('Lower armor',[(-.5,-.12),(-.25,.13),(.95,.13),(1.1,-.08),(.85,-.4),(-.5,-.4)],.12,M,y,.04)
for i in range(3): profile('Status inset',[(.04+i*.2,-.23),(.15+i*.2,-.04),(.25+i*.2,-.04),(.14+i*.2,-.23)],.025,O,y+side*.07,.012)
profile('Fore armor',[(1,.38),(2.25,.38),(2.08,-.08),(1.2,-.08)],.12,A,y,.045)
for i in range(3): profile('Vent',[(1.35+i*.22,.02),(1.49+i*.22,.25),(1.58+i*.22,.25),(1.44+i*.22,.02)],.015,B,y+side*.07,.012)
box('Fore lower light',(1.55,y,-.24),(.85,.04,.065),O)
profile('Stock upper',[(-3.55,.25),(-3.35,.42),(-2,.32),(-1.85,.1),(-2.2,-.12),(-3.5,-.12)],.55,M)
beam('Stock rear',(-3.5,0,.22),(-3.5,0,-1.05),.24,.6,B)
beam('Stock diagonal',(-3.43,0,-1),(-2.65,0,-.12),.22,.42,M)
beam('Stock brace',(-3.35,0,-.9),(-2.3,0,-1.2),.17,.36,M)
box('Cheek rest',(-2.95,0,.48),(.8,.58,.18),B)
for side in (-1,1):
beam('Stock glow',(-3.3,side*.29,.03),(-2.55,side*.29,.03),.06,.02,O)
profile('Grip',[(-2,-.25),(-1.55,-.45),(-1.95,-1.55),(-2.5,-1.55),(-2.63,-1.35)],.43,M)
for side in (-1,1): profile('Grip rubber',[(-2.04,-.55),(-1.76,-.58),(-2.08,-1.4),(-2.42,-1.38)],.025,B,side*.23)
beam('Guard bottom',(-1.85,0,-.82),(-.9,0,-.82),.1,.24,M)
beam('Guard front',(-.9,0,-.82),(-.75,0,-.32),.1,.24,M)
beam('Trigger',(-1.43,0,-.35),(-1.5,0,-.61),.09,.1,O)
beam('Trigger tip',(-1.5,0,-.61),(-1.39,0,-.7),.09,.1,O)
profile('Magazine',[(-.65,-.4),(.35,-.4),(.35,-.9),(.15,-1.08),(-.55,-1.08),(-.7,-.9)],.55,M)
box('Magazine glow',(-.15,-.285,-.96),(.5,.035,.07),C)
cyl('Barrel',(2.8,0,.13),.17,1.5,B,vertices=48)
cyl('Collar',(3.4,0,.13),.22,.13,C,vertices=32)
for z in (-.1,.36):
profile('Brake jaw',[(3.55,z-.08),(4.4,z-.08),(4.55,z+.04),(4.4,z+.15),(3.65,z+.15)],.5,M)
box('Brake inner',(4,0,z+(.1 if z<0 else -.06)),(.65,.28,.035),C)
box('Brake bridge',(3.6,0,.13),(.16,.5,.5),B)
box('Rail',(0,0,.52),(4,.33,.12),B)
o=box('Teeth',(-1.9,0,.61),(.12,.4,.09),A,bevel=.015)
a=o.modifiers.new('Teeth array','ARRAY');a.count=25;a.relative_offset_displace=(1.3,0,0)
shell('Optical tube',[(-1.7,.23),(-1.5,.29),(-1.3,.24),(.2,.24),(.45,.35),(.8,.48),(1.15,.48)],B)
shell('Objective armor',[(.35,.32),(.65,.47),(1.05,.5),(1.17,.46)],M)
cyl('Lens recess',(1.18,0,1.32),.4,.025,B)
cyl('Lens',(1.2,0,1.32),.34,.025,C,vertices=48)
cyl('Eyepiece',(-1.65,0,1.32),.3,.25,M)
cyl('Eye neon',(-1.66,0,1.32),.31,.055,O)
for x in (-1,.0):
box('Mount foot',(x,0,.77),(.28,.48,.25),M)
cyl('Scope clamp',(x,0,1.32),.29,.17,A)
box('Clamp upright',(x,0,1),(.18,.42,.45),A)
for side in (-1,1):
o=cyl('Fastener',(x,side*.25,.84),.065,.035,B);o.rotation_euler=(math.pi/2,0,0)
cyl('Turret',(-.55,0,1.63),.21,.32,M,'Z')
cyl('Turret neon',(-.55,0,1.76),.22,.055,O,'Z')
for side in (-1,1):box('Scope channel',(.4,side*.3,1.27),(.5,.03,.045),C)
for o in c.objects:
if o.type=='MESH' and o.name.startswith(('Barrel','Collar')):
for p in o.data.polygons:p.use_smooth=True
stage=bpy.data.collections.new('Studio');s.collection.children.link(stage);ns['STAGE']=stage
ns['create_environment']();ns['create_camera_and_lights']()
s.camera.location=(4,-16,3.8);s.camera.rotation_euler=(Vector((.35,0,.1))-s.camera.location).to_track_quat('-Z','Y').to_euler();s.camera.data.ortho_scale=9.5
s.render.engine='CYCLES';s.cycles.samples=24
s.render.resolution_x=1400;s.render.resolution_y=800
out=r'C:\roblox\hunter\3D models'
s.render.filepath=os.path.join(out,'sniper_rebuilt.png')
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out,'sniper_rebuilt.blend'))
bpy.ops.render.render(write_still=True)
print('REBUILT SAVED')
+15
View File
@@ -0,0 +1,15 @@
import bpy,json
r=next(o for o in bpy.context.scene.objects if o.type=='ARMATURE' and o.name.startswith('Armature'))
print(json.dumps([{'name':p.name,'scale':list(p.scale),'basis_scale':list(p.matrix_basis.to_scale())} for p in r.pose.bones if 'hand' in p.name or 'lowerarm' in p.name]))
for p in r.pose.bones:
if 'hand_IK' in p.name:p.scale=(1,1,1)
bpy.context.view_layer.update()
print('AFTER',json.dumps([{'name':p.name,'scale':list(p.scale)} for p in r.pose.bones if 'hand_IK' in p.name]))
bpy.ops.wm.save_as_mainfile(filepath=r'C:\roblox\hunter\3D models\sniper_reference_v11_hands_fix.blend')
s=bpy.context.scene
# Inspection angle shows both arm chains rather than hiding them behind the rifle.
from mathutils import Vector
cam=s.camera;cam.location=(5,-11,4);cam.rotation_euler=(Vector((-.3,0,-.2))-cam.location).to_track_quat('-Z','Y').to_euler();cam.data.type='ORTHO';cam.data.ortho_scale=11
s.render.resolution_x=1200;s.render.resolution_y=800;s.cycles.samples=16
s.render.filepath=r'C:\roblox\hunter\3D models\hands_fix_check.png'
bpy.ops.render.render(write_still=True)
+36
View File
@@ -0,0 +1,36 @@
import bpy, math, os, bmesh
scene=bpy.context.scene
coll=next((c for c in scene.collection.children if c.name.startswith('Rifle V4')),None)
assert coll, 'Open Reference Sculpt V4 scene first'
old=[o for o in coll.objects if o.name.startswith(('Muzzle body','Muzzle inner emitter'))]
assert old, 'Original muzzle not found'
material=old[0].data.materials[0]
# Closed annular mesh: the front face bridges outer and inner walls, never the bore.
# Inner wall extends behind the muzzle into the barrel; the rear opening stays open.
cy=(490-441)/180
sections=[((1477-880)/180,.26),((1500-880)/180,.35),((1703-880)/180,.35),((1720-880)/180,.30),((1720-880)/180,.20),((1698-880)/180,.185),((1240-880)/180,.125),((1240-880)/180,.15),((1477-880)/180,.15)]
n=64
verts=[(x,math.cos(2*math.pi*i/n)*r,cy+math.sin(2*math.pi*i/n)*r) for x,r in sections for i in range(n)]
faces=[]
for j in range(len(sections)):
nxt=(j+1)%len(sections)
for i in range(n):faces.append((j*n+i,j*n+(i+1)%n,nxt*n+(i+1)%n,nxt*n+i))
mesh=bpy.data.meshes.new('Hollow muzzle mesh');mesh.from_pydata(verts,[],faces);mesh.update()
bm=bmesh.new();bm.from_mesh(mesh);bmesh.ops.recalc_face_normals(bm,faces=bm.faces);bm.to_mesh(mesh);bm.free()
obj=bpy.data.objects.new('Round muzzle with deep bore',mesh);coll.objects.link(obj);mesh.materials.append(material)
for p in mesh.polygons:p.use_smooth=True
bevel=obj.modifiers.new('Rim bevel','BEVEL');bevel.width=.012;bevel.segments=3
obj.modifiers.new('Weighted normals','WEIGHTED_NORMAL')
# Bore also passes through the existing barrel and collar rather than ending at a solid cap.
bpy.ops.mesh.primitive_cylinder_add(vertices=64,radius=.125,depth=3.2,location=((1480-880)/180,0,cy),rotation=(0,math.pi/2,0))
cutter=bpy.context.object;cutter.name='Bore cutter'
for ob in list(coll.objects):
if ob.name.startswith(('Barrel','Muzzle energy collar')):
mod=ob.modifiers.new('Continuous bore','BOOLEAN');mod.operation='DIFFERENCE';mod.solver='EXACT';mod.object=cutter
bpy.context.view_layer.objects.active=ob;bpy.ops.object.modifier_apply(modifier=mod.name)
bpy.data.objects.remove(cutter,do_unlink=True)
for ob in old:bpy.data.objects.remove(ob,do_unlink=True)
bpy.ops.object.select_all(action='DESELECT');obj.select_set(True);bpy.context.view_layer.objects.active=obj
path=r'C:\roblox\hunter\3D models\sniper_reference_v5.blend'
bpy.ops.wm.save_as_mainfile(filepath=path)
print('Saved',path,'Bore depth',sections[4][0]-sections[6][0],'Mesh faces',len(mesh.polygons))
+14
View File
@@ -0,0 +1,14 @@
import bpy, os, json
source = r'C:\roblox\hunter\blender\sniper_modular.py'
ns = {'__name__': 'sniper_mcp'}
with open(source, encoding='utf-8') as f:
exec(compile(f.read(), source, 'exec'), ns)
ns['main']()
scene = ns['SCENE']
assert len(ns['WEAPON'].objects) > 30
folder = r'C:\roblox\hunter\3D models'
target = os.path.join(folder, 'sniper_modular.blend')
if os.path.exists(target):
target = os.path.join(folder, 'sniper_modular_' + str(int(__import__('time').time())) + '.blend')
bpy.ops.wm.save_as_mainfile(filepath=target)
print(json.dumps({'saved': target, 'scene': scene.name, 'weapon_objects': len(ns['WEAPON'].objects), 'engine': scene.render.engine}))
+17
View File
@@ -0,0 +1,17 @@
import bpy,math
from mathutils import Vector
s=bpy.context.scene;c=next(c for c in s.collection.children if c.name.startswith('User Gloved Hands'))
rig=next(o for o in c.objects if o.type=='ARMATURE')
for o in c.objects:
if o not in [rig] and o.name not in ('sleeve','hardknuckle'):
o.hide_render=True;o.hide_set(True)
# Preserve the source rig, constraints and pose, normalize its large source units.
root=bpy.data.objects.new('Hands placement',None);c.objects.link(root)
rig.parent=root
root.scale=(.16,.16,.16);root.rotation_euler.z=math.pi/2
root.location=(-3,0,-3.5)
bpy.context.view_layer.update()
bpy.ops.object.select_all(action='DESELECT');rig.hide_set(False);rig.select_set(True);bpy.context.view_layer.objects.active=rig
path=r'C:\roblox\hunter\3D models\sniper_reference_v9_user_hands.blend'
bpy.ops.wm.save_as_mainfile(filepath=path)
print('SAVED',path,'meshes',[(o.name,len(o.data.vertices)) for o in c.objects if o.name in ('sleeve','hardknuckle')])
+20
View File
@@ -0,0 +1,20 @@
"""Send a Python file to the running Blender (Blender Lab MCP add-on on localhost:9876) and print the reply.
Usage: python send.py script.py
"""
import json
import socket
import sys
code = open(sys.argv[1], encoding="utf-8").read()
payload = (json.dumps({"type": "execute", "code": code, "strict_json": False}) + "\0").encode("utf-8")
with socket.create_connection(("localhost", 9876), timeout=600) as s:
s.sendall(payload)
buf = bytearray()
while b"\0" not in buf:
chunk = s.recv(65536)
if not chunk:
break
buf.extend(chunk)
end = buf.index(b"\0") if b"\0" in buf else len(buf)
print(json.dumps(json.loads(bytes(buf[:end])), ensure_ascii=False, indent=1))
+15
View File
@@ -0,0 +1,15 @@
import bpy
from mathutils import Vector
s=bpy.context.scene
c=next(c for c in s.collection.children if c.name.startswith('User Gloved Hands'))
for o in c.objects:
if o.name in ('sleeve','hardknuckle') or o.type=='ARMATURE':o.hide_render=False;o.hide_set(False);o.hide_viewport=False
r=next(o for o in c.objects if o.type=='ARMATURE')
# Move shoulder base forward to put the support target within the arm's reach.
r.parent.location.x+=.65
bpy.context.view_layer.update()
for name,target in [('hand_IK_L.L',(1.05,-.12,-.38)),('hand_IK_L.R',(-2.95,.15,-1.05))]:
p=r.pose.bones[name];m=p.matrix.copy();m.translation=r.matrix_world.inverted()@Vector(target);p.matrix=m
bpy.context.view_layer.update()
bpy.ops.wm.save_as_mainfile(filepath=r'C:\roblox\hunter\3D models\sniper_reference_v10_grip.blend')
print('Hands visible; grip pose saved')
+153
View File
@@ -0,0 +1,153 @@
"""Blender 4.0+: run in Text Editor. Creates a separate scene; F12 renders it."""
import bpy
import math
from mathutils import Vector
def rgba(h):
v=[int(h[i:i+2],16)/255 for i in (0,2,4)]
return tuple(x/12.92 if x<=.04045 else ((x+.055)/1.055)**2.4 for x in v)+(1,)
def material(name, color, rough=.4, metal=.8, emission=0, transmission=0):
m=bpy.data.materials.new(name); m.use_nodes=True
p=next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED')
for key,value in {'Base Color':rgba(color),'Metallic':metal,'Roughness':rough,'Emission Color':rgba(color),'Emission Strength':emission,'Transmission Weight':transmission}.items():
p.inputs[key].default_value=value
m.diffuse_color=rgba(color)
return m
def finish(o,name,mat,bevel=.04):
o.name=name
for c in list(o.users_collection): c.objects.unlink(o)
WEAPON.objects.link(o); o.data.materials.append(mat)
if bevel:
b=o.modifiers.new('Chamfer','BEVEL'); b.width=bevel; b.segments=2
return o
def box(name,pos,size,mat,angle=0,bevel=.04):
bpy.ops.mesh.primitive_cube_add(location=pos)
o=bpy.context.object; o.scale=Vector(size)/2
bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
o.rotation_euler.y=math.radians(angle)
return finish(o,name,mat,bevel)
def cylinder(name,pos,radius,length,mat,axis='X',vertices=12):
bpy.ops.mesh.primitive_cylinder_add(vertices=vertices,radius=radius,depth=length,location=pos)
o=bpy.context.object
o.rotation_euler.y=math.pi/2 if axis=='X' else 0
return finish(o,name,mat,.025)
def beam(name,a,b,width,depth,mat):
a,b=Vector(a),Vector(b)
o=box(name,(a+b)/2,(width,depth,(b-a).length),mat)
o.rotation_euler=(b-a).to_track_quat('Z','Y').to_euler()
return o
def create_receiver():
box('Receiver',(0,0,0),(3.8,.65,.65),M)
for side in (-1,1):
y=side*.35
box('Recess',(0,y,0),(2.9,.04,.42),BLACK)
box('Armor',(1.1,y*1.08,.1),(1.3,.1,.46),M,bevel=.09)
box('Lower cyan channel',(.1,y*1.09,-.25),(2.9,.04,.055),CYAN)
for i in range(3):
box('Orange diagonal',(-.85+i*.23,y*1.12,0),(.1,.035,.25),ORANGE,30,.015)
def create_stock():
box('Butt pad',(-3.3,0,-.3),(.24,.7,1.35),BLACK)
beam('Stock upper',(-3.2,0,.2),(-1.8,0,.2),.32,.55,M)
beam('Stock lower',(-3.15,0,-.85),(-1.85,0,.1),.25,.43,M)
beam('Stock rear',(-3.15,0,-.85),(-3.15,0,.2),.25,.48,M)
box('Cheek rest',(-2.65,0,.43),(.8,.58,.2),BLACK)
for s in (-1,1): box('Stock orange',(-2.7,s*.29,.23),(.75,.025,.07),ORANGE)
def create_grip():
beam('Grip',(-1.35,0,-.35),(-1.7,0,-1.45),.42,.43,BLACK)
beam('Grip inset',(-1.4,-.23,-.6),(-1.63,-.23,-1.3),.25,.035,M)
beam('Guard lower',(-1.25,0,-.95),(-.45,0,-.95),.1,.25,M)
beam('Guard front',(-.45,0,-.95),(-.45,0,-.35),.1,.25,M)
beam('Trigger',(-.95,0,-.35),(-1.02,0,-.65),.09,.12,ORANGE)
beam('Trigger tip',(-1.02,0,-.65),(-.9,0,-.78),.09,.12,ORANGE)
def create_magazine():
box('Magazine',(.1,0,-.65),(.85,.55,.65),M,bevel=.09)
box('Magazine base',(.1,0,-1),(.72,.6,.17),BLACK)
for s in (-1,1): box('Magazine glow',(.1,s*.305,-1),(.48,.02,.055),CYAN)
def create_barrel():
cylinder('Barrel',(2.55,0,.07),.16,1.6,BLACK,vertices=24)
cylinder('Energy collar',(3.18,0,.07),.21,.12,CYAN)
# Four beams form an open rectangular brake, with visible inner glow.
for z in (-.18,.32):
box('Brake jaw',(3.75,0,z),(1,.5,.17),M,bevel=.05)
box('Brake inner glow',(3.7,0,z+(.09 if z<0 else -.09)),(.65,.28,.025),CYAN)
box('Brake rear',(3.32,0,.07),(.15,.5,.5),BLACK)
def create_top_rail():
box('Rail base',(.1,0,.41),(3.7,.35,.12),BLACK)
o=box('Rail teeth',(-1.65,0,.51),(.11,.43,.1),M,bevel=.015)
a=o.modifiers.new('Repeated teeth','ARRAY'); a.count=22
a.use_relative_offset=False; a.use_constant_offset=True; a.constant_offset_displace=(.165,0,0)
def create_scope():
for x in (-.95,.25):
box('Scope foot',(x,0,.67),(.3,.5,.24),M)
cylinder('Mount ring',(x,0,1.03),.31,.16,M)
cylinder('Scope tube',(-.35,0,1.03),.24,2.1,BLACK)
cylinder('Objective hood',(.72,0,1.03),.44,.65,M,vertices=8)
cylinder('Objective recess',(1.055,0,1.03),.36,.025,BLACK)
cylinder('Crystal lens',(1.075,0,1.03),.3,.025,LENS,vertices=24)
cylinder('Eyepiece',(-1.5,0,1.03),.3,.3,M)
cylinder('Eyepiece orange',(-1.53,0,1.03),.31,.065,ORANGE)
cylinder('Turret',(-.4,0,1.38),.2,.3,M,'Z')
cylinder('Turret orange',(-.4,0,1.49),.21,.055,ORANGE,'Z')
for s in (-1,1): box('Scope stripe',(.1,s*.246,1.03),(.55,.025,.045),CYAN)
def create_environment():
floor=material('Navy floor','031126',.48,.3)
n=floor.node_tree.nodes; l=floor.node_tree.links
tex=n.new('ShaderNodeTexCoord'); sep=n.new('ShaderNodeSeparateXYZ'); l.new(tex.outputs['Object'],sep.inputs[0])
signals=[]
for axis in ('X','Y'):
mod=n.new('ShaderNodeMath'); mod.operation='PINGPONG'; mod.inputs[1].default_value=.7
l.new(sep.outputs[axis],mod.inputs[0])
test=n.new('ShaderNodeMath'); test.operation='LESS_THAN'; test.inputs[1].default_value=.012
l.new(mod.outputs[0],test.inputs[0]); signals.append(test)
maximum=n.new('ShaderNodeMath'); maximum.operation='MAXIMUM'
for i,t in enumerate(signals): l.new(t.outputs[0],maximum.inputs[i])
p=next(t for t in n if t.type=='BSDF_PRINCIPLED'); p.inputs['Emission Color'].default_value=rgba('0077CC')
l.new(maximum.outputs[0],p.inputs['Emission Strength'])
o=box('Grid floor',(0,0,-1.7),(200,200,.08),floor,bevel=0)
WEAPON.objects.unlink(o); STAGE.objects.link(o)
world=bpy.data.worlds.new('Blue gradient'); SCENE.world=world; world.use_nodes=True
n=world.node_tree.nodes; l=world.node_tree.links
tex=n.new('ShaderNodeTexCoord'); sep=n.new('ShaderNodeSeparateXYZ'); ramp=n.new('ShaderNodeValToRGB')
ramp.color_ramp.elements[0].color=rgba('020817'); ramp.color_ramp.elements[1].color=rgba('12345A')
background=next(node for node in n if node.type=='BACKGROUND')
l.new(tex.outputs['Normal'],sep.inputs[0]); l.new(sep.outputs['Z'],ramp.inputs[0]); l.new(ramp.outputs[0],background.inputs['Color'])
def create_camera_and_lights():
def aim(o): o.rotation_euler=(Vector((.3,0,0))-o.location).to_track_quat('-Z','Y').to_euler()
for name,kind,pos,power,color,size in [('Key','AREA',(-3,-5,7),1800,(.7,.85,1),5),('Rim','AREA',(2,4,5),2300,(.1,.6,1),4),('Warm glint','POINT',(3,-2,2),100,(1,.3,.08),.7),('Blue glint','POINT',(-3,1,1),80,(0,.5,1),.5)]:
d=bpy.data.lights.new(name,kind); d.energy=power; d.color=color
if kind=='AREA': d.shape='DISK'; d.size=size
else: d.shadow_soft_size=size
o=bpy.data.objects.new(name,d); STAGE.objects.link(o); o.location=pos; aim(o)
d=bpy.data.cameras.new('Camera'); o=bpy.data.objects.new('Camera',d); STAGE.objects.link(o)
o.location=(6,-15,5); aim(o); d.type='ORTHO'; d.ortho_scale=10; SCENE.camera=o
SCENE.render.engine='CYCLES'; SCENE.cycles.samples=64; SCENE.cycles.use_denoising=True
SCENE.render.resolution_x=1600; SCENE.render.resolution_y=900; SCENE.render.resolution_percentage=100
def main():
global SCENE,WEAPON,STAGE,M,BLACK,CYAN,ORANGE,LENS
SCENE=bpy.data.scenes.new('Futuristic Sniper')
bpy.context.window.scene=SCENE
WEAPON=bpy.data.collections.new('Sniper Geometry'); STAGE=bpy.data.collections.new('Presentation')
SCENE.collection.children.link(WEAPON); SCENE.collection.children.link(STAGE)
M=material('Body #2A2D34','2A2D34'); BLACK=material('Matte #111111','111111',.6)
CYAN=material('Cyan neon','00FFFF',.3,0,5); ORANGE=material('Orange neon','FF5500',.3,0,5)
LENS=material('Glowing crystal','00FFFF',.08,0,1.5,1)
for fn in (create_receiver,create_stock,create_grip,create_magazine,create_barrel,create_top_rail,create_scope,create_environment,create_camera_and_lights): fn()
bpy.ops.object.select_all(action='DESELECT')
print('Sniper created. Geometry: Sniper Geometry collection. F12 to render.')
if __name__=='__main__': main()
+97
View File
@@ -0,0 +1,97 @@
"""Reference-space silhouette construction. Image coordinates map directly to X/Z."""
import bpy, math, os, bmesh
from mathutils import Vector
lib={'__name__':'library'}
exec(open(r'C:\roblox\hunter\blender\sniper_modular.py',encoding='utf8').read(),lib)
s=bpy.data.scenes.new('Reference Sculpt V4');bpy.context.window.scene=s
c=bpy.data.collections.new('Rifle V4');s.collection.children.link(c)
lib.update(SCENE=s,WEAPON=c)
mat=lib['material']; dark=mat('Ceramic graphite','2A2D34');black=mat('Rubber','11151C',.5);silver=mat('Titanium panels','687385',.33)
cyan=mat('Cyan channel','00CCFF',.3,0,2);orange=mat('Amber channel','FF5500',.3,0,2)
def pos(x,y,d=0):return ((x-880)/180,d,(490-y)/180)
def poly(name,pts,depth,material,offset=0,bevel=.025):
n=len(pts);v=[pos(x,y,d) for d in (offset-depth/2,offset+depth/2) for x,y in pts]
f=[tuple(reversed(range(n))),tuple(range(n,2*n))]+[(i,(i+1)%n,(i+1)%n+n,i+n) for i in range(n)]
mesh=bpy.data.meshes.new(name);mesh.from_pydata(v,[],f);mesh.update()
bm=bmesh.new();bm.from_mesh(mesh);bmesh.ops.recalc_face_normals(bm,faces=bm.faces);bm.to_mesh(mesh);bm.free()
o=bpy.data.objects.new(name,mesh);c.objects.link(o);mesh.materials.append(material)
b=o.modifiers.new('Precision edge','BEVEL');b.width=bevel;b.segments=3
o.modifiers.new('Face normals','WEIGHTED_NORMAL');return o
def tube(name,x,y,r,length,material,verts=48):
return lib['cylinder'](name,pos(x,y),r/180,length/180,material,vertices=verts)
def ringbody(name,rings,y,material):
# Octagonal tapered surfaces, with flat broad facets and narrow edge bevels.
verts=[]
for x,r in rings:
for i in range(8):
a=2*math.pi*i/8+math.pi/8
verts.append(((x-880)/180,math.cos(a)*r/180,(490-y)/180+math.sin(a)*r/180))
f=[tuple(reversed(range(8))),tuple(range(len(verts)-8,len(verts)))]
for j in range(len(rings)-1):
for i in range(8):f.append((j*8+i,j*8+(i+1)%8,(j+1)*8+(i+1)%8,(j+1)*8+i))
me=bpy.data.meshes.new(name);me.from_pydata(verts,[],f);me.update()
bm=bmesh.new();bm.from_mesh(me);bmesh.ops.recalc_face_normals(bm,faces=bm.faces);bm.to_mesh(me);bm.free()
ob=bpy.data.objects.new(name,me);c.objects.link(ob);me.materials.append(material)
b=ob.modifiers.new('Edge glints','BEVEL');b.width=.018;b.segments=2
ob.modifiers.new('Normals','WEIGHTED_NORMAL')
# Pixel-traced major masses from the supplied 1774 x 887 reference.
poly('Unified receiver',[(330,440),(420,402),(1200,398),(1260,425),(1225,500),(920,533),(850,551),(575,567),(495,534),(355,515)],.62,black)
poly('Upper frame',[(350,429),(425,393),(1260,393),(1240,425),(600,436),(555,474),(351,474)],.68,dark)
poly('Stock shell',[(60,405),(108,388),(288,398),(350,427),(326,493),(173,507),(109,639),(64,632)],.48,dark)
poly('Stock heel',[(48,421),(72,403),(83,621),(115,651),(66,664),(42,635)],.56,black)
poly('Stock diagonal brace',[(120,600),(160,584),(278,654),(266,683)],.33,dark)
poly('Cheek rest',[(105,395),(126,380),(285,380),(308,399),(285,424),(117,425)],.58,black)
poly('Grip frame',[(353,509),(419,529),(393,586),(405,605),(366,716),(298,737),(255,698),(289,597)],.5,silver)
poly('Grip rubber',[(324,594),(377,613),(352,695),(303,710),(278,687)],.515,black)
poly('Trigger guard',[(413,520),(435,524),(427,582),(494,582),(514,550),(529,551),(515,603),(408,605),(392,588)],.28,dark)
poly('Trigger',[(449,522),(467,521),(460,548),(476,576),(455,576),(439,550)],.12,orange)
poly('Magazine body',[(561,532),(753,532),(758,604),(728,635),(564,631),(540,607)],.58,dark)
poly('Magazine base',[(566,613),(737,613),(717,653),(584,655),(558,639)],.53,black)
for side in (-1,1):
y=side*.37
poly('Bent cyan conduit',[(351,463),(548,463),(593,485),(620,437),(898,437),(899,450),(634,451),(604,501),(579,501),(545,479),(351,479)],.018,cyan,y,.009)
poly('Rear layered panel',[(348,481),(498,481),(532,508),(511,522),(352,504)],.055,silver,y+.035*side)
poly('Breech armor',[(486,412),(575,410),(598,434),(577,460),(473,460)],.07,silver,y+.03*side)
poly('Lower receiver plate',[(631,467),(672,463),(694,485),(860,474),(882,506),(844,549),(605,549),(589,530)],.1,dark,y)
for i in range(3):poly('Diagonal amber indicator',[(704+i*30,510),(725+i*30,477),(745+i*30,477),(725+i*30,510)],.018,orange,y+side*.06,.008)
poly('Forearm shield',[(890,412),(1240,412),(1216,479),(927,479)],.12,silver,y)
for i in range(3):
poly('Recessed cooling slot',[(1040+i*50,458),(1067+i*50,420),(1089+i*50,420),(1062+i*50,458)],.014,black,y+side*.07,.012)
poly('Lower forearm',[(923,483),(1199,483),(1177,515),(952,515)],.08,black,y)
poly('Amber forearm inset',[(953,493),(1154,493),(1142,505),(966,505)],.02,orange,y+side*.05,.009)
poly('Stock inset',[(94,492),(126,455),(234,455),(246,475),(137,475),(113,511)],.018,orange,side*.25,.012)
poly('Magazine face',[(578,555),(625,555),(646,544),(727,544),(727,606),(578,606)],.04,silver,side*.31)
poly('Magazine glow',[(588,626),(703,626),(694,641),(595,641)],.018,cyan,side*.29,.008)
tube('Barrel',1345,441,31,260,black)
tube('Muzzle energy collar',1450,441,37,25,cyan)
poly('Muzzle body',[(1501,386),(1704,372),(1730,397),(1705,420),(1590,420),(1573,441),(1590,463),(1707,463),(1730,486),(1705,507),(1504,497),(1477,472),(1477,412)],.58,dark)
poly('Muzzle inner emitter',[(1557,421),(1575,421),(1561,442),(1575,460),(1557,460),(1543,441)],.6,cyan)
poly('Rail spine',[(432,381),(1253,381),(1265,398),(425,398)],.35,black)
for i in range(33):
x=438+i*24
poly('Rail tooth',[(x,379),(x+7,366),(x+24,366),(x+18,379)],.4,silver,.0,.008)
ringbody('Scope core',[(374,43),(410,54),(474,40),(740,40),(800,62),(858,81),(1020,81)],277,black)
ringbody('Rear ocular armor',[(365,47),(380,60),(413,60),(430,48)],277,dark)
ringbody('Ocular orange ring',[(406,60),(418,60)],277,orange)
ringbody('Objective transition',[(758,45),(805,65),(874,87),(967,87)],277,dark)
ringbody('Objective outer hood',[(870,90),(982,90),(1010,82)],277,silver)
tube('Black lens recess',1014,277,72,8,black,8)
tube('Glowing lens',1020,277,61,6,cyan,32)
for x in (535,704):
ringbody('Scope collar',[(x-17,52),(x+17,52)],277,silver)
poly('Integrated mount',[(x-22,273),(x+22,273),(x+22,361),(x-22,361)],.5,dark)
for side in (-1,1):
ob=tube('Mount bolt',x,341,12,8,silver,8);ob.location.y=side*.27;ob.rotation_euler=(math.pi/2,0,0)
ob=lib['cylinder']('Elevation turret',pos(625,204),.25,.28,dark,axis='Z')
ob=lib['cylinder']('Turret amber',pos(625,183),.26,.055,orange,axis='Z')
for side in (-1,1):poly('Scope blue inset',[(799,285),(864,277),(864,289),(800,296)],.02,cyan,side*.36,.008)
stage=bpy.data.collections.new('Presentation V4');s.collection.children.link(stage);lib['STAGE']=stage
lib['create_environment']();lib['create_camera_and_lights']()
s.camera.location=(3,-18,3);target=Vector((-.05,0,.35));s.camera.rotation_euler=(target-s.camera.location).to_track_quat('-Z','Y').to_euler();s.camera.data.ortho_scale=10.6
s.cycles.samples=32;s.render.resolution_x=1600;s.render.resolution_y=900
out=r'C:\roblox\hunter\3D models'
s.render.filepath=os.path.join(out,'sniper_reference_v4.png')
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out,'sniper_reference_v4.blend'))
bpy.ops.render.render(write_still=True)
print('V4 complete',len(c.objects))