Skip to content

Commit

Permalink
increase max websocket buffer size
Browse files Browse the repository at this point in the history
  • Loading branch information
Krande committed Sep 26, 2024
1 parent 42b422d commit c205e36
Show file tree
Hide file tree
Showing 19 changed files with 55 additions and 65 deletions.
1 change: 1 addition & 0 deletions environment.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ channels:
dependencies:
- ada-py
- ada-cpp
- hdf5=1.14.4.3
- paradoc
- code-aster
- occt=*=*novtk*
Expand Down
4 changes: 2 additions & 2 deletions examples/scripts/animate_glb.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ def main():
]
keyframe_times = [0, 1, 3, 4, 6] # Example keyframe times

tri_anim = Animation("TestAnimation", box, translation_keyframes, keyframe_times, rotational_keyframes)
tri_anim = Animation("TestAnimation", keyframe_times, translation_keyframes, rotational_keyframes)
a.animation_store.add(tri_anim)

# Set your initial camera position
camera_position = p0 + np.array([0.35, 0.25, 0.15])

# Update the view
a.show(renderer="react", camera_position=camera_position.astype(float).tolist())
a.show()
# a.to_ifc("temp/moving_box.ifc")


Expand Down
11 changes: 0 additions & 11 deletions examples/scripts/check_server.py

This file was deleted.

22 changes: 6 additions & 16 deletions examples/scripts/param_model_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def gravity_step():


def eigen_step():
return ada.fem.StepEigen("gravity", 20)
return ada.fem.StepEigen("EIGEN", 20)


def main():
Expand All @@ -26,23 +26,13 @@ def main():
a = ada.Assembly("ParametricSite") / p
# a.fem.add_step(gravity_step())
a.fem.add_step(eigen_step())
res = a.to_fem(fem_res, "code_aster", overwrite=True, execute=True, scratch_dir=SCRATCH)
mesh = res.to_meshio_mesh(make_3xn_dofs=True)
mesh.write(res_file.with_suffix(".vtu"))
# res.to_vtu()
if not res_file.exists():
res = a.to_fem(fem_res, "code_aster", overwrite=True, execute=True, scratch_dir=SCRATCH)
else:
res = ada.from_fem_res(res_file, fem_format="code_aster")

# a.to_fem("ca_param_model_ses", "sesam", overwrite=True, execute=True)


def read_res():
fem_res = "ca_param_model_ca"
res_file = (SCRATCH / fem_res / fem_res).with_suffix(".rmed")
res = ada.from_fem_res(res_file, "code_aster")
mesh = res.to_meshio_mesh(make_3xn_dofs=True)
mesh.write(res_file.with_suffix(".vtu"))
# res.to_xdmf(res.name + ".xdmf")
res.show(ping_timeout=30)


if __name__ == "__main__":
main()
# read_res()
2 changes: 1 addition & 1 deletion examples/scripts/viewer_partial_updates.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ada
from ada.visit.websocket_server import SceneAction
from ada.visit.deprecated.websocket_server import SceneAction


def main():
Expand Down
6 changes: 3 additions & 3 deletions src/ada/comms/fb_model_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ class CameraParamsDC:
position: List[float] = None
look_at: List[float] = None
up: List[float] = None
fov: floatDC = 60.0
near: floatDC = 0.1
far: floatDC = 1000.0
fov: float = None
near: float = None
far: float = None
force_camera: bool = None

@dataclass
Expand Down
5 changes: 2 additions & 3 deletions src/ada/comms/wsock_client_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,10 @@ def update_scene(
target_id=None,
):
"""Updates the scene with the given GLTF data."""
self.websocket.send(
self._scene_update_prep(
buffer = self._scene_update_prep(
name, scene, purpose, scene_op, gltf_buffer_postprocessor, gltf_tree_postprocessor, target_id=target_id
)
)
self.websocket.send(buffer)

def update_file_server(self, file_object: FileObjectDC):
"""Updates the file server with a new file."""
Expand Down
4 changes: 2 additions & 2 deletions src/ada/comms/wsock_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,13 @@ async def forward_message(

async def start_async(self):
"""Run the server asynchronously. Blocks until the server is stopped."""
self.server = await websockets.serve(self.handle_client, self.host, self.port)
self.server = await websockets.serve(self.handle_client, self.host, self.port, max_size=10**9)
logger.debug(f"WebSocket server started on ws://{self.host}:{self.port}")
await self.server.wait_closed()

async def start_async_non_blocking(self):
"""Start the server asynchronously. Does not block the event loop."""
self.server = await websockets.serve(self.handle_client, self.host, self.port)
self.server = await websockets.serve(self.handle_client, self.host, self.port, max_size=10**9)
print(f"WebSocket server started on ws://{self.host}:{self.port}")
# Do not call await self.server.wait_closed() here

Expand Down
2 changes: 1 addition & 1 deletion src/ada/comms/wsockets_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from ada.comms.fb_model_gen import TargetTypeDC
from ada.config import logger
from ada.visit.websocket_server import start_external_ws_server
from ada.visit.deprecated.websocket_server import start_external_ws_server


def is_port_open(host: str, port: int) -> bool:
Expand Down
14 changes: 12 additions & 2 deletions src/ada/fem/results/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from ada.visit.renderer_manager import RenderParams

from ...comms.fb_model_gen import FilePurposeDC
from ...visit.websocket_server import send_to_viewer
from ada.visit.deprecated.websocket_server import send_to_viewer
from .field_data import ElementFieldData, NodalFieldData, NodalFieldType

if TYPE_CHECKING:
Expand Down Expand Up @@ -408,8 +408,9 @@ def show(
unique_id=None,
purpose: FilePurposeDC = FilePurposeDC.ANALYSIS,
params_override: RenderParams = None,
ping_timeout=1,
):
from ada.visit.renderer_manager import RendererManager, RenderParams
from ada.visit.renderer_manager import RendererManager, RenderParams, FEARenderParams

if renderer == "pygfx":
scene = self.to_trimesh(step, field, warp_field, warp_step, warp_scale, cfunc)
Expand All @@ -424,15 +425,24 @@ def show(
server_exe=server_exe,
server_args=server_args,
run_ws_in_thread=run_ws_in_thread,
ping_timeout=ping_timeout
)

fea_params = FEARenderParams(
step=step,
field=field,
warp_field=warp_field,
warp_step=warp_step,
warp_scale=warp_scale,
)
if params_override is None:
params_override = RenderParams(
unique_id=unique_id,
auto_sync_ifc_store=False,
stream_from_ifc_store=False,
add_ifc_backend=False,
purpose=purpose,
fea_params=fea_params
)

# Set up the renderer and WebSocket server
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import argparse

from ada.visit.websocket_server import WebSocketServer
from ada.visit.deprecated.websocket_server import WebSocketServer


def ws_cli_app():
Expand Down
File renamed without changes.
1 change: 1 addition & 0 deletions src/ada/visit/optimizing.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def optimize_positions(positions: np.ndarray, indices: np.ndarray) -> tuple[np.n
positions = positions.copy().reshape(len(positions) // 3, 3)
if len(indices.shape) == 1:
indices = indices.copy().reshape(len(indices) // 3, 3)

mesh = trimesh.Trimesh(vertices=positions, faces=indices)
mesh.merge_vertices()

Expand Down
24 changes: 9 additions & 15 deletions src/ada/visit/renderer_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import numpy as np
import trimesh

from ada.comms.fb_model_gen import FilePurposeDC
from ada.comms.fb_model_gen import FilePurposeDC, SceneOperationDC, SceneOperationsDC

if TYPE_CHECKING:
from IPython.display import HTML
Expand All @@ -27,37 +27,27 @@ class FEARenderParams:
warp_scale: float = 1.0


@dataclass
class CameraParams:
position: list[float] = (0.0, 0.0, 0.0)
look_at: list[float] = (0.0, 0.0, 0.0)
up: list[float] = (0.0, 0.0, 0.0)
fov: float = 60.0
near: float = 0.1
far: float = 1000.0
force_camera: bool = False


@dataclass
class RenderParams:
auto_sync_ifc_store: bool = False
stream_from_ifc_store: bool = False
merge_meshes: bool = True
scene_post_processor: Optional[Callable[[trimesh.Scene], trimesh.Scene]] = None
purpose: Optional[FilePurposeDC] = FilePurposeDC.DESIGN
scene_operation: SceneOperationDC = None
gltf_buffer_postprocessor: Optional[Callable[[OrderedDict, dict], None]] = None
gltf_tree_postprocessor: Optional[Callable[[OrderedDict], None]] = None
add_ifc_backend: bool = False
backend_file_dir: Optional[str] = None
unique_id: int = None
camera_params: Optional[CameraParams] = field(default_factory=CameraParams)
fea_params: Optional[FEARenderParams] = field(default_factory=FEARenderParams)

def __post_init__(self):
# ensure that if unique_id is set, it is a 32-bit integer
if self.unique_id is not None:
self.unique_id = self.unique_id & 0xFFFFFFFF

if self.scene_operation is None:
self.scene_operation = SceneOperationDC(operation=SceneOperationsDC.REPLACE)

def scene_from_fem_results(self: FEAResult, params: RenderParams):
from trimesh.path.entities import Line
Expand Down Expand Up @@ -161,6 +151,7 @@ def __init__(
server_exe: pathlib.Path = None,
server_args: list[str] = None,
run_ws_in_thread: bool = False,
ping_timeout=1,
):
self.renderer = renderer
self.host = host
Expand All @@ -169,6 +160,7 @@ def __init__(
self.server_args = server_args
self.run_ws_in_thread = run_ws_in_thread
self._is_in_notebook = None
self.ping_timeout=ping_timeout

def start_server(self):
"""Set up the WebSocket server and renderer."""
Expand Down Expand Up @@ -204,7 +196,7 @@ def ensure_liveness(self, wc, target_id=None) -> None | HTML:
if not self.is_in_notebook():
target_id = None # Currently does not support unique viewer IDs outside of notebooks

if wc.check_target_liveness(target_id=target_id):
if wc.check_target_liveness(target_id=target_id, timeout=self.ping_timeout):
# The target is alive meaning a viewer is running
return None

Expand Down Expand Up @@ -250,7 +242,9 @@ def render(self, obj: BackendGeom | Part | Assembly | FEAResult, params: RenderP
obj.name,
scene,
purpose=params.purpose,
scene_op=params.scene_operation.operation,
gltf_buffer_postprocessor=params.gltf_buffer_postprocessor,
gltf_tree_postprocessor=params.gltf_tree_postprocessor,
target_id=target_id,
)

Expand Down
2 changes: 1 addition & 1 deletion src/ada/visit/rendering/render_pygfx.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ def scale_tri_mesh(mesh: trimesh.Trimesh, sfac: float):


def standalone_viewer(host="localhost", port="8765"):
from ada.visit.websocket_server import WsRenderMessage, start_server
from ada.visit.deprecated.websocket_server import WsRenderMessage, start_server

with Manager() as manager:
# Create a shared queue
Expand Down
4 changes: 1 addition & 3 deletions src/ada/visit/rendering/renderer_react.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,7 @@ def get_notebook_renderer_widget(self, height=500, target_id=None):
from ada.visit.rendering.renderer_widget import WebSocketRenderer

as_html = self.local_html_path.read_text(encoding="utf-8")
renderer = WebSocketRenderer(as_html, height=height)
if target_id is not None:
renderer.unique_id = target_id
renderer = WebSocketRenderer(as_html, height=height, unique_id=target_id)
return renderer.display()


Expand Down
13 changes: 9 additions & 4 deletions src/ada/visit/rendering/renderer_widget.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import html
import random

import ipywidgets as widgets


class WebSocketRenderer(widgets.DOMWidget):
def __init__(self, html_content: str, height: int = 500):
def __init__(self, html_content: str, height: int = 500, unique_id: int = None, ws_port=None):
super().__init__()
self.unique_id: int = random.randint(0, 2**31 - 1)
html_inject_str = ''
if unique_id is not None:
self.unique_id = unique_id
html_inject_str += f'<script>window.WEBSOCKET_ID = "{self.unique_id}";</script>\n'
if ws_port is not None:
self.ws_port = ws_port
html_inject_str += f'<script>window.WEBSOCKET_PORT = {self.ws_port};</script>'

# Inject the unique ID into the HTML content
self.html_content = html_content.replace(
"<!--WEBSOCKET_ID_PLACEHOLDER-->", f'<script>window.WEBSOCKET_ID = "{self.unique_id}";</script>'
"<!--WEBSOCKET_ID_PLACEHOLDER-->", html_inject_str
)

# Escape and embed the HTML in the srcdoc of the iframe
Expand Down
3 changes: 3 additions & 0 deletions src/flatbuffers/dataclass_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ def generate_dataclasses_from_schema(schema: FlatBufferSchema, output_file: str
default_value = ' = ""'
elif python_type == "int":
default_value = " = None"
elif python_type == "float":
default_value = " = None"
elif python_type == "bool":
default_value = " = None"
elif python_type == "bytes":
Expand All @@ -70,6 +72,7 @@ def convert_flatbuffer_type_to_python(flat_type: str) -> tuple[str, bool]:
"int": "int",
"string": "str",
"bool": "bool",
"float": "float",
"[float]": "List[float]",
}

Expand Down

0 comments on commit c205e36

Please sign in to comment.