# SPDX-FileCopyrightText: 2026 Thomas Gordon Lowrey IV # SPDX-License-Identifier: GPL-2.0-or-later """Publish engine-owned map scenes to the active native render context. Input, source selection, and annotation meaning belong to the shared model. """ from array import array import ctypes as C import math class Mark(C.Structure): _fields_=[('index',C.c_uint32),('ch',C.c_uint32),('ink',C.c_uint64)] def rgb565(color): r,g,b=color;return ((r>>3)<<11)|((g>>2)<<5)|(b>>3) def place_labels(labels,overlay,width,height): """Move a complete place-name run clear of station and path marks.""" runs=[];previous=-2;style=None for index,cell in sorted(labels.items()): if runs and index==previous+1 and index//width==previous//width and cell[1]==style:runs[-1].append((index,cell)) else:runs.append([(index,cell)]) previous=index;style=cell[1] occupied=set(labels)|set(overlay);placed={} for run in runs: original={index for index,_ in run};occupied.difference_update(original-set(overlay)) x=run[0][0]%width;y=run[0][0]//width for dx,dy in ((0,0),(0,-1),(0,1),(-1,0),(1,0),(0,-2),(0,2)): nx,ny=x+dx,y+dy if nx<0 or ny<0 or ny>=height or nx+len(run)>width:continue indices=[ny*width+nx+n for n in range(len(run))] if any(index in occupied for index in indices):continue placed.update((index,cell) for index,(_,cell) in zip(indices,run));occupied.update(indices);break return placed def terrain_detail(surface,view,features): """Sample terrain at semantic pixel density, within a fixed work budget.""" overview=getattr(surface,'pixel_overview',False) if overview and features.sample_width>=view.width*2 and features.sample_height>=view.height*4: return features.terrain,features.sample_width,features.sample_height if not getattr(surface,'terrain',False) or (not overview and getattr(surface.image,'source',None) not in ('semantic','semantic-prepared','pan-preview')): return features.terrain,features.sample_width,features.sample_height from desktop_elevation import enabled factor=min(8,math.isqrt((32768 if overview else 262144)//max(1,view.width*view.height*2))) if factor<2:return features.terrain,features.sample_width,features.sample_height dense=surface.renderer.module.Viewport(view.center,view.span,view.width*factor,view.height*factor,view.cell_aspect) renderer=surface.renderer path=renderer.prepared_path('terrain',dense,(overview,)) if hasattr(renderer,'prepared_path') else None if path: saved=renderer.read_prepared(path) if isinstance(saved,bytes) and len(saved)==dense.width*dense.height*8: return array('I',saved),dense.width,dense.height*2 from desktop_elevation import pixel_samples fast=pixel_samples(surface.renderer.engine,dense) if enabled() else None if fast is not None:return fast from offline_map import display_terrain_sampler frame,_=display_terrain_sampler(surface.renderer.engine)(dense,True) from offline_map import map_rgb samples=array('I') for row in range(dense.height): cells=frame[row*dense.width:(row+1)*dense.width] samples.extend(map_rgb(upper) for _,upper,_ in cells) samples.extend(map_rgb(lower) for _,_,lower in cells) if path:renderer.engine.prepared.save_base(path,samples.tobytes()) return samples,dense.width,dense.height*2 class View: input_role='map' def __init__(self,host,owner,*,name='Station Map'): self.host=host;self.owner=owner;self.name=name self.pending=None;self.ready=None;self.ready_layer=None;self.key=None;self.failed=None;self.pixel_frames=0;self.pixel_jobs=0;self.error='' self.ready_surface=None;self._presented_pan=None;self._loading_scene=None;self._presented_preview=None self._inset_key=None;self._inset_scene=None;self._inset_pending=None self._terrain_key=None;self._terrain_samples=None def plan(self): surface=self.owner.map_surface() if surface is None:return None layer=surface.layer;x,y,w,h,plane=layer projection=surface.image.projection key=surface.key return key,layer,surface def retained_preview(self): base=getattr(self.owner,'base',None) if (not getattr(getattr(self.host,'render_context',None),'native_pixels',False) or self.ready_surface is None or self.ready_surface.box_plane is not None or self.pending is not None or base is None or not base.preview or base.full_overview or base.side_overview or base._detail_request is not None or base._zoom_context_image is not None or getattr(self.owner,'terrain_active',False) or getattr(self.owner,'dialog',None)): return None target=base.target_box.view if target is None or self.ready_surface.image is not base._shown_image:return None layer=self.owner.layer() if layer is None or layer[:4]!=self.ready_layer[:4]:return None return target @property def pixel_dirty(self): if self._inset_pending is not None and self._inset_pending[1].done():return True pan=self.pan_offset() if pan is not None and pan!=self._presented_pan:return True preview=self.retained_preview() if preview is not None or self._presented_preview is not None:return preview!=self._presented_preview plan=self.plan() return bool(plan and ((self.pending and self.pending[1].done()) or (self.pending is None and plan[0]!=self.key and plan[0]!=self.failed))) @pixel_dirty.setter def pixel_dirty(self,value): if value:self.key=None def build(self,layer,surface): from scenes import MapScene x,y,w,h,plane=layer;overlay={} while hasattr(plane,'overlay') and hasattr(plane,'base'): if plane is not getattr(surface,'box_plane',None): for i,cell in plane.overlay.items():overlay.setdefault(i,cell) plane=plane.base view=surface.viewport() content_width=min(w,max(1,getattr(surface,'content_width',0) or w)) if surface.unavailable_reason: message=surface.unavailable_reason[:w] marks=(Mark*len(message))(*(Mark(i,ord(ch),(1<<48)|(0xffffff<<24)) for i,ch in enumerate(message))) return MapScene(w,h,array('I',[0]*(w*h*2)),w,h*2,(),marks) features=surface.features(view,plane) projected=[] for color,points in (*features.vectors,*surface.overlay_vectors): pixels=array('d') for i in range(0,len(points),2): px,py=view.project(points[i],points[i+1]);pixels.extend(((px+.5)*8,(py+.5)*16)) if len(pixels)//4>250000:raise ValueError('Map vector budget exceeded') projected.append((color,pixels)) if content_widthl and b>t:clipped.append((l,t,r-l,b-t)) wx,wy,_,_=self.host.bounds(self.host.window(self.name));ox,oy=self.host.origin return MapComposite(((self.ready,0,0),),w*8,h*16,tuple(clipped)),(wx+ox+1+x)*8,(wy+oy+1+y)*16,w*8,h*16 plan=self.plan() if plan is None:return None key,layer,surface=plan if self.pending and self.pending[1].done(): finished,future,retained_layer,retained_surface=self.pending;self.pending=None try:self.ready=future.result();self.key=finished;self.ready_layer=retained_layer;self.ready_surface=retained_surface;self.pixel_frames+=1;self.error='' except Exception as error:self.failed=finished;self.error=str(error) if self.pending and self.pending[2][:4]!=layer[:4]: self.pending[1].cancel();self.pending=None if not dragging and self.pending is None and key!=self.key and key!=self.failed: pool=surface.renderer.pool if pool is None: try: self.ready=self.build(layer,surface);self.key=key;self.ready_layer=layer;self.ready_surface=surface;self.pixel_frames+=1;self.error='' except Exception as error:self.failed=key;self.error=str(error) else: future=pool.submit(self.build,layer,surface);self.pending=key,future,layer,surface;future.add_done_callback(lambda f,callback=surface.renderer.completion_wakeup:self.wake(f,callback)) if self.ready is None or self.ready_layer[:4]!=layer[:4]: if self.pending is None:return None from scenes import MapScene x,y,w,h=layer[:4] if self._loading_scene is None or (self._loading_scene.width,self._loading_scene.height)!=(w,h): self._loading_scene=MapScene(w,h,array('I',[0x181822]),1,1,(),(Mark*0)()) wx,wy,_,_=self.host.bounds(self.host.window(self.name));ox,oy=self.host.origin return self._loading_scene,(wx+ox+1+x)*8,(wy+oy+1+y)*16,w*8,h*16 projection=getattr(getattr(surface,'image',None),'projection',None) view_matches=(base is None or projection is not None and tuple(projection.center)==tuple(base.center) and abs(projection.span-base.span)<1e-9) if not dragging and pan is not None and self.ready_surface is not None and self.ready_surface.image is surface.image and view_matches: base._gpu_pan_offset=None;pan=None return self.positioned(self.ready,layer,surface,pan) def presentation_marks(self): if self.pan_offset() is not None:return None plan=self.plan() if self.ready is None or plan is None or not hasattr(self.ready,'marks') or self.ready_layer[:4]!=plan[1][:4]:return None x,y,w,h=self.ready_layer[:4];wx,wy,_,_=self.host.bounds(self.host.window(self.name));ox,oy=self.host.origin return self.ready.marks,wx+ox+1+x,wy+oy+1+y,w,h